language stringclasses 1
value | owner stringlengths 2 15 | repo stringlengths 2 21 | sha stringlengths 45 45 | message stringlengths 7 36.3k | path stringlengths 1 199 | patch stringlengths 15 102k | is_multipart bool 2
classes |
|---|---|---|---|---|---|---|---|
Other | spring-projects | spring-framework | 05765d752062f37b202e7dfd20593c995dc47df0.json | Replace EasyMock with Mockito
Issue: SPR-10126 | spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/util/PortletUtilsTests.java | @@ -21,23 +21,23 @@
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
+
import javax.portlet.PortletContext;
import javax.portlet.PortletRequest;
import javax.portlet.PortletSession;
import org.junit.Test;
-
-import org.springframework.tests.sample.beans.ITestBean;
-import org.springframework.tests.sample.beans.TestBean;
import org.springframework.mock.web.portlet.MockActionRequest;
import org.springframework.mock.web.portlet.MockActionResponse;
import org.springframework.mock.web.portlet.MockPortletContext;
import org.springframework.mock.web.portlet.MockPortletRequest;
import org.springframework.mock.web.portlet.MockPortletSession;
+import org.springframework.tests.sample.beans.ITestBean;
+import org.springframework.tests.sample.beans.TestBean;
import org.springframework.web.util.WebUtils;
-import static org.easymock.EasyMock.*;
import static org.junit.Assert.*;
+import static org.mockito.BDDMockito.*;
/**
* @author Rick Evans
@@ -60,9 +60,8 @@ public void testGetTempDirSunnyDay() throws Exception {
public void testGetRealPathInterpretsLocationAsRelativeToWebAppRootIfPathDoesNotBeginWithALeadingSlash() throws Exception {
final String originalPath = "web/foo";
final String expectedRealPath = "/" + originalPath;
- PortletContext ctx = createMock(PortletContext.class);
- expect(ctx.getRealPath(expectedRealPath)).andReturn(expectedRealPath);
- replay(ctx);
+ PortletContext ctx = mock(PortletContext.class);
+ given(ctx.getRealPath(expectedRealPath)).willReturn(expectedRealPath);
String actualRealPath = PortletUtils.getRealPath(ctx, originalPath);
assertEquals(expectedRealPath, actualRealPath);
@@ -402,132 +401,97 @@ public void testSetSessionAttributeWithNullPortletRequest() throws Exception {
@Test
public void testGetSessionAttributeDoes_Not_CreateANewSession() throws Exception {
- PortletRequest request = createMock(PortletRequest.class);
- expect(request.getPortletSession(false)).andReturn(null);
- replay(request);
+ PortletRequest request = mock(PortletRequest.class);
Object sessionAttribute = PortletUtils.getSessionAttribute(request, "foo");
assertNull("Must return null if session attribute does not exist (or if Session does not exist)", sessionAttribute);
- verify(request);
+ verify(request).getPortletSession(false);
}
@Test
public void testGetSessionAttributeWithExistingSession() throws Exception {
MockPortletSession session = new MockPortletSession();
session.setAttribute("foo", "foo");
- PortletRequest request = createMock(PortletRequest.class);
- expect(request.getPortletSession(false)).andReturn(session);
- replay(request);
+ PortletRequest request = mock(PortletRequest.class);
+ given(request.getPortletSession(false)).willReturn(session);
Object sessionAttribute = PortletUtils.getSessionAttribute(request, "foo");
assertNotNull("Must not return null if session attribute exists (and Session exists)", sessionAttribute);
assertEquals("foo", sessionAttribute);
-
- verify(request);
}
@Test
public void testGetRequiredSessionAttributeWithExistingSession() throws Exception {
MockPortletSession session = new MockPortletSession();
session.setAttribute("foo", "foo");
- PortletRequest request = createMock(PortletRequest.class);
- expect(request.getPortletSession(false)).andReturn(session);
- replay(request);
+ PortletRequest request = mock(PortletRequest.class);
+ given(request.getPortletSession(false)).willReturn(session);
Object sessionAttribute = PortletUtils.getRequiredSessionAttribute(request, "foo");
assertNotNull("Must not return null if session attribute exists (and Session exists)", sessionAttribute);
assertEquals("foo", sessionAttribute);
-
- verify(request);
}
@Test
public void testGetRequiredSessionAttributeWithExistingSessionAndNoAttribute() throws Exception {
MockPortletSession session = new MockPortletSession();
- final PortletRequest request = createMock(PortletRequest.class);
- expect(request.getPortletSession(false)).andReturn(session);
- replay(request);
+ final PortletRequest request = mock(PortletRequest.class);
+ given(request.getPortletSession(false)).willReturn(session);
try {
PortletUtils.getRequiredSessionAttribute(request, "foo");
fail("expected IllegalStateException");
} catch (IllegalStateException ex) { /* expected */ }
- verify(request);
+
}
@Test
public void testSetSessionAttributeWithExistingSessionAndNullValue() throws Exception {
- PortletSession session = createMock(PortletSession.class);
- PortletRequest request = createMock(PortletRequest.class);
-
- expect(request.getPortletSession(false)).andReturn(session); // must not create Session for null value...
- session.removeAttribute("foo", PortletSession.APPLICATION_SCOPE);
- replay(request, session);
-
+ PortletSession session = mock(PortletSession.class);
+ PortletRequest request = mock(PortletRequest.class);
+ given(request.getPortletSession(false)).willReturn(session); // must not create Session for null value...
PortletUtils.setSessionAttribute(request, "foo", null, PortletSession.APPLICATION_SCOPE);
-
- verify(request, session);
+ verify(session).removeAttribute("foo", PortletSession.APPLICATION_SCOPE);
}
@Test
public void testSetSessionAttributeWithNoExistingSessionAndNullValue() throws Exception {
- PortletRequest request = createMock(PortletRequest.class);
-
- expect(request.getPortletSession(false)).andReturn(null); // must not create Session for null value...
- replay(request);
-
+ PortletRequest request = mock(PortletRequest.class);
PortletUtils.setSessionAttribute(request, "foo", null, PortletSession.APPLICATION_SCOPE);
-
- verify(request);
+ verify(request).getPortletSession(false); // must not create Session for null value...
}
@Test
public void testSetSessionAttributeWithExistingSessionAndSpecificScope() throws Exception {
- PortletSession session = createMock(PortletSession.class);
- PortletRequest request = createMock(PortletRequest.class);
-
- expect(request.getPortletSession()).andReturn(session); // must not create Session ...
- session.setAttribute("foo", "foo", PortletSession.APPLICATION_SCOPE);
- replay(request, session);
-
+ PortletSession session = mock(PortletSession.class);
+ PortletRequest request = mock(PortletRequest.class);
+ given(request.getPortletSession()).willReturn(session); // must not create Session ...
PortletUtils.setSessionAttribute(request, "foo", "foo", PortletSession.APPLICATION_SCOPE);
-
- verify(request, session);
+ verify(session).setAttribute("foo", "foo", PortletSession.APPLICATION_SCOPE);
}
@Test
public void testGetSessionAttributeWithExistingSessionAndSpecificScope() throws Exception {
- PortletSession session = createMock(PortletSession.class);
- PortletRequest request = createMock(PortletRequest.class);
-
- expect(request.getPortletSession(false)).andReturn(session);
- expect(session.getAttribute("foo", PortletSession.APPLICATION_SCOPE)).andReturn("foo");
- replay(request, session);
-
+ PortletSession session = mock(PortletSession.class);
+ PortletRequest request = mock(PortletRequest.class);
+ given(request.getPortletSession(false)).willReturn(session);
+ given(session.getAttribute("foo", PortletSession.APPLICATION_SCOPE)).willReturn("foo");
Object sessionAttribute = PortletUtils.getSessionAttribute(request, "foo", PortletSession.APPLICATION_SCOPE);
assertNotNull("Must not return null if session attribute exists (and Session exists)", sessionAttribute);
assertEquals("foo", sessionAttribute);
-
- verify(request, session);
}
@Test
public void testGetSessionAttributeWithExistingSessionDefaultsToPortletScope() throws Exception {
- PortletSession session = createMock(PortletSession.class);
- PortletRequest request = createMock(PortletRequest.class);
-
- expect(request.getPortletSession(false)).andReturn(session);
- expect(session.getAttribute("foo", PortletSession.PORTLET_SCOPE)).andReturn("foo");
-
- replay(request, session);
-
+ PortletSession session = mock(PortletSession.class);
+ PortletRequest request = mock(PortletRequest.class);
+ given(request.getPortletSession(false)).willReturn(session);
+ given(session.getAttribute("foo", PortletSession.PORTLET_SCOPE)).willReturn("foo");
Object sessionAttribute = PortletUtils.getSessionAttribute(request, "foo");
assertNotNull("Must not return null if session attribute exists (and Session exists)", sessionAttribute);
assertEquals("foo", sessionAttribute);
-
- verify(request, session);
}
| true |
Other | spring-projects | spring-framework | 05765d752062f37b202e7dfd20593c995dc47df0.json | Replace EasyMock with Mockito
Issue: SPR-10126 | spring-webmvc-tiles3/src/test/java/org/springframework/web/servlet/view/tiles3/TilesViewResolverTests.java | @@ -1,5 +1,5 @@
/*
- * Copyright 2002-2012 the original author or authors.
+ * Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,24 +15,18 @@
*/
package org.springframework.web.servlet.view.tiles3;
-import static org.easymock.EasyMock.eq;
-import static org.easymock.EasyMock.expect;
-import static org.easymock.EasyMock.isA;
-import static org.easymock.EasyMock.replay;
-import static org.easymock.EasyMock.verify;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-
import java.util.Locale;
import org.apache.tiles.request.Request;
import org.apache.tiles.request.render.Renderer;
-import org.easymock.EasyMock;
import org.junit.Before;
import org.junit.Test;
import org.springframework.mock.web.test.MockServletContext;
import org.springframework.web.context.support.StaticWebApplicationContext;
+import static org.junit.Assert.*;
+import static org.mockito.BDDMockito.*;
+
/**
* Test fixture for {@link TilesViewResolver}.
*
@@ -51,7 +45,7 @@ public void setUp() {
wac.setServletContext(new MockServletContext());
wac.refresh();
- this.renderer = EasyMock.createMock(Renderer.class);
+ this.renderer = mock(Renderer.class);
this.viewResolver = new TilesViewResolver();
this.viewResolver.setRenderer(this.renderer);
@@ -60,13 +54,13 @@ public void setUp() {
@Test
public void testResolve() throws Exception {
- expect(this.renderer.isRenderable(eq("/template.test"), isA(Request.class))).andReturn(true);
- expect(this.renderer.isRenderable(eq("/nonexistent.test"), isA(Request.class))).andReturn(false);
- replay(this.renderer);
+ given(this.renderer.isRenderable(eq("/template.test"), isA(Request.class))).willReturn(true);
+ given(this.renderer.isRenderable(eq("/nonexistent.test"), isA(Request.class))).willReturn(false);
assertTrue(this.viewResolver.resolveViewName("/template.test", Locale.ITALY) instanceof TilesView);
assertNull(this.viewResolver.resolveViewName("/nonexistent.test", Locale.ITALY));
- verify(this.renderer);
+ verify(this.renderer).isRenderable(eq("/template.test"), isA(Request.class));
+ verify(this.renderer).isRenderable(eq("/nonexistent.test"), isA(Request.class));
}
} | true |
Other | spring-projects | spring-framework | 05765d752062f37b202e7dfd20593c995dc47df0.json | Replace EasyMock with Mockito
Issue: SPR-10126 | spring-webmvc-tiles3/src/test/java/org/springframework/web/servlet/view/tiles3/TilesViewTests.java | @@ -1,5 +1,5 @@
/*
- * Copyright 2002-2012 the original author or authors.
+ * Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,18 +15,9 @@
*/
package org.springframework.web.servlet.view.tiles3;
-import static org.easymock.EasyMock.and;
-import static org.easymock.EasyMock.createMock;
-import static org.easymock.EasyMock.eq;
-import static org.easymock.EasyMock.isA;
-import static org.easymock.EasyMock.replay;
-import static org.easymock.EasyMock.verify;
-import static org.junit.Assert.assertEquals;
-
import java.util.HashMap;
import java.util.Map;
-import org.apache.tiles.request.ApplicationContext;
import org.apache.tiles.request.Request;
import org.apache.tiles.request.render.Renderer;
import org.junit.Before;
@@ -37,6 +28,10 @@
import org.springframework.web.context.support.StaticWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
+import static org.junit.Assert.*;
+import static org.mockito.Matchers.*;
+import static org.mockito.BDDMockito.*;
+
/**
* Test fixture for {@link TilesView}.
*
@@ -67,7 +62,7 @@ public void setUp() throws Exception {
response = new MockHttpServletResponse();
- renderer = createMock(Renderer.class);
+ renderer = mock(Renderer.class);
view = new TilesView();
view.setServletContext(servletContext);
@@ -80,16 +75,9 @@ public void setUp() throws Exception {
public void testRender() throws Exception {
Map<String, Object> model = new HashMap<String, Object>();
model.put("modelAttribute", "modelValue");
-
- ApplicationContext tilesContext = createMock(ApplicationContext.class);
-
- renderer.render(eq(VIEW_PATH), and(isA(Request.class), isA(Request.class)));
- replay(tilesContext, renderer);
-
view.render(model, request, response);
-
assertEquals("modelValue", request.getAttribute("modelAttribute"));
- verify(tilesContext, renderer);
+ verify(renderer).render(eq(VIEW_PATH), isA(Request.class));
}
} | true |
Other | spring-projects | spring-framework | 05765d752062f37b202e7dfd20593c995dc47df0.json | Replace EasyMock with Mockito
Issue: SPR-10126 | spring-webmvc/src/test/java/org/springframework/web/servlet/DispatcherServletTests.java | @@ -61,8 +61,7 @@
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
-import static org.mockito.Matchers.*;
-import static org.mockito.Mockito.*;
+import static org.mockito.BDDMockito.*;
/**
* @author Rod Johnson | true |
Other | spring-projects | spring-framework | 05765d752062f37b202e7dfd20593c995dc47df0.json | Replace EasyMock with Mockito
Issue: SPR-10126 | spring-webmvc/src/test/java/org/springframework/web/servlet/HandlerExecutionChainTests.java | @@ -1,5 +1,5 @@
/*
- * Copyright 2002-2012 the original author or authors.
+ * Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,17 +16,14 @@
package org.springframework.web.servlet;
-import static org.easymock.EasyMock.createStrictMock;
-import static org.easymock.EasyMock.expect;
-import static org.easymock.EasyMock.replay;
-import static org.easymock.EasyMock.verify;
-import static org.junit.Assert.assertSame;
-
import org.junit.Before;
import org.junit.Test;
import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.mock.web.test.MockHttpServletResponse;
+import static org.junit.Assert.*;
+import static org.mockito.BDDMockito.*;
+
/**
* A test fixture with HandlerExecutionChain and mock handler interceptors.
*
@@ -56,9 +53,9 @@ public void setup() {
this.handler = new Object();
this.chain = new HandlerExecutionChain(this.handler);
- this.interceptor1 = createStrictMock(AsyncHandlerInterceptor.class);
- this.interceptor2 = createStrictMock(AsyncHandlerInterceptor.class);
- this.interceptor3 = createStrictMock(AsyncHandlerInterceptor.class);
+ this.interceptor1 = mock(AsyncHandlerInterceptor.class);
+ this.interceptor2 = mock(AsyncHandlerInterceptor.class);
+ this.interceptor3 = mock(AsyncHandlerInterceptor.class);
this.chain.addInterceptor(this.interceptor1);
this.chain.addInterceptor(this.interceptor2);
@@ -69,79 +66,60 @@ public void setup() {
public void successScenario() throws Exception {
ModelAndView mav = new ModelAndView();
- expect(this.interceptor1.preHandle(this.request, this.response, this.handler)).andReturn(true);
- expect(this.interceptor2.preHandle(this.request, this.response, this.handler)).andReturn(true);
- expect(this.interceptor3.preHandle(this.request, this.response, this.handler)).andReturn(true);
-
- this.interceptor1.postHandle(this.request, this.response, this.handler, mav);
- this.interceptor2.postHandle(this.request, this.response, this.handler, mav);
- this.interceptor3.postHandle(this.request, this.response, this.handler, mav);
-
- this.interceptor3.afterCompletion(this.request, this.response, this.handler, null);
- this.interceptor2.afterCompletion(this.request, this.response, this.handler, null);
- this.interceptor1.afterCompletion(this.request, this.response, this.handler, null);
-
- replay(this.interceptor1, this.interceptor2, this.interceptor3);
+ given(this.interceptor1.preHandle(this.request, this.response, this.handler)).willReturn(true);
+ given(this.interceptor2.preHandle(this.request, this.response, this.handler)).willReturn(true);
+ given(this.interceptor3.preHandle(this.request, this.response, this.handler)).willReturn(true);
this.chain.applyPreHandle(request, response);
this.chain.applyPostHandle(request, response, mav);
this.chain.triggerAfterCompletion(this.request, this.response, null);
- verify(this.interceptor1, this.interceptor2, this.interceptor3);
+ verify(this.interceptor1).postHandle(this.request, this.response, this.handler, mav);
+ verify(this.interceptor2).postHandle(this.request, this.response, this.handler, mav);
+ verify(this.interceptor3).postHandle(this.request, this.response, this.handler, mav);
+
+ verify(this.interceptor3).afterCompletion(this.request, this.response, this.handler, null);
+ verify(this.interceptor2).afterCompletion(this.request, this.response, this.handler, null);
+ verify(this.interceptor1).afterCompletion(this.request, this.response, this.handler, null);
}
@Test
public void successAsyncScenario() throws Exception {
- expect(this.interceptor1.preHandle(this.request, this.response, this.handler)).andReturn(true);
- expect(this.interceptor2.preHandle(this.request, this.response, this.handler)).andReturn(true);
- expect(this.interceptor3.preHandle(this.request, this.response, this.handler)).andReturn(true);
-
- this.interceptor1.afterConcurrentHandlingStarted(request, response, this.handler);
- this.interceptor2.afterConcurrentHandlingStarted(request, response, this.handler);
- this.interceptor3.afterConcurrentHandlingStarted(request, response, this.handler);
-
- replay(this.interceptor1, this.interceptor2, this.interceptor3);
+ given(this.interceptor1.preHandle(this.request, this.response, this.handler)).willReturn(true);
+ given(this.interceptor2.preHandle(this.request, this.response, this.handler)).willReturn(true);
+ given(this.interceptor3.preHandle(this.request, this.response, this.handler)).willReturn(true);
this.chain.applyPreHandle(request, response);
this.chain.applyAfterConcurrentHandlingStarted(request, response);
this.chain.triggerAfterCompletion(this.request, this.response, null);
- verify(this.interceptor1, this.interceptor2, this.interceptor3);
+ verify(this.interceptor1).afterConcurrentHandlingStarted(request, response, this.handler);
+ verify(this.interceptor2).afterConcurrentHandlingStarted(request, response, this.handler);
+ verify(this.interceptor3).afterConcurrentHandlingStarted(request, response, this.handler);
}
@Test
public void earlyExitInPreHandle() throws Exception {
- expect(this.interceptor1.preHandle(this.request, this.response, this.handler)).andReturn(true);
- expect(this.interceptor2.preHandle(this.request, this.response, this.handler)).andReturn(false);
-
- this.interceptor1.afterCompletion(this.request, this.response, this.handler, null);
-
- replay(this.interceptor1, this.interceptor2, this.interceptor3);
+ given(this.interceptor1.preHandle(this.request, this.response, this.handler)).willReturn(true);
+ given(this.interceptor2.preHandle(this.request, this.response, this.handler)).willReturn(false);
this.chain.applyPreHandle(request, response);
- verify(this.interceptor1, this.interceptor2, this.interceptor3);
+ verify(this.interceptor1).afterCompletion(this.request, this.response, this.handler, null);
}
@Test
public void exceptionBeforePreHandle() throws Exception {
- replay(this.interceptor1, this.interceptor2, this.interceptor3);
-
this.chain.triggerAfterCompletion(this.request, this.response, null);
-
- verify(this.interceptor1, this.interceptor2, this.interceptor3);
+ verifyZeroInteractions(this.interceptor1, this.interceptor2, this.interceptor3);
}
@Test
public void exceptionDuringPreHandle() throws Exception {
Exception ex = new Exception("");
- expect(this.interceptor1.preHandle(this.request, this.response, this.handler)).andReturn(true);
- expect(this.interceptor2.preHandle(this.request, this.response, this.handler)).andThrow(ex);
-
- this.interceptor1.afterCompletion(this.request, this.response, this.handler, ex);
-
- replay(this.interceptor1, this.interceptor2, this.interceptor3);
+ given(this.interceptor1.preHandle(this.request, this.response, this.handler)).willReturn(true);
+ given(this.interceptor2.preHandle(this.request, this.response, this.handler)).willThrow(ex);
try {
this.chain.applyPreHandle(request, response);
@@ -151,27 +129,24 @@ public void exceptionDuringPreHandle() throws Exception {
}
this.chain.triggerAfterCompletion(this.request, this.response, ex);
- verify(this.interceptor1, this.interceptor2, this.interceptor3);
+ verify(this.interceptor1).afterCompletion(this.request, this.response, this.handler, ex);
+ verify(this.interceptor3, never()).preHandle(this.request, this.response, this.handler);
}
@Test
public void exceptionAfterPreHandle() throws Exception {
Exception ex = new Exception("");
- expect(this.interceptor1.preHandle(this.request, this.response, this.handler)).andReturn(true);
- expect(this.interceptor2.preHandle(this.request, this.response, this.handler)).andReturn(true);
- expect(this.interceptor3.preHandle(this.request, this.response, this.handler)).andReturn(true);
-
- this.interceptor3.afterCompletion(this.request, this.response, this.handler, ex);
- this.interceptor2.afterCompletion(this.request, this.response, this.handler, ex);
- this.interceptor1.afterCompletion(this.request, this.response, this.handler, ex);
-
- replay(this.interceptor1, this.interceptor2, this.interceptor3);
+ given(this.interceptor1.preHandle(this.request, this.response, this.handler)).willReturn(true);
+ given(this.interceptor2.preHandle(this.request, this.response, this.handler)).willReturn(true);
+ given(this.interceptor3.preHandle(this.request, this.response, this.handler)).willReturn(true);
this.chain.applyPreHandle(request, response);
this.chain.triggerAfterCompletion(this.request, this.response, ex);
- verify(this.interceptor1, this.interceptor2, this.interceptor3);
+ verify(this.interceptor3).afterCompletion(this.request, this.response, this.handler, ex);
+ verify(this.interceptor2).afterCompletion(this.request, this.response, this.handler, ex);
+ verify(this.interceptor1).afterCompletion(this.request, this.response, this.handler, ex);
}
} | true |
Other | spring-projects | spring-framework | 05765d752062f37b202e7dfd20593c995dc47df0.json | Replace EasyMock with Mockito
Issue: SPR-10126 | spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/DelegatingWebMvcConfigurationTests.java | @@ -1,5 +1,5 @@
/*
- * Copyright 2002-2012 the original author or authors.
+ * Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,23 +16,17 @@
package org.springframework.web.servlet.config.annotation;
-import static org.easymock.EasyMock.capture;
-import static org.easymock.EasyMock.expect;
-import static org.easymock.EasyMock.replay;
-import static org.easymock.EasyMock.verify;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
-
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
-import org.easymock.Capture;
-import org.easymock.EasyMock;
import org.junit.Before;
import org.junit.Test;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Captor;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.springframework.core.convert.ConversionService;
import org.springframework.format.support.FormattingConversionService;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
@@ -48,6 +42,9 @@
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver;
+import static org.junit.Assert.*;
+import static org.mockito.BDDMockito.*;
+
/**
* A test fixture for {@link DelegatingWebMvcConfiguration} tests.
*
@@ -57,46 +54,59 @@ public class DelegatingWebMvcConfigurationTests {
private DelegatingWebMvcConfiguration delegatingConfig;
+ @Mock
private WebMvcConfigurer webMvcConfigurer;
+ @Captor
+ private ArgumentCaptor<List<HttpMessageConverter<?>>> converters;
+
+ @Captor
+ private ArgumentCaptor<ContentNegotiationConfigurer> contentNegotiationConfigurer;
+
+ @Captor
+ private ArgumentCaptor<FormattingConversionService> conversionService;
+
+ @Captor
+ private ArgumentCaptor<List<HandlerMethodArgumentResolver>> resolvers;
+
+ @Captor
+ private ArgumentCaptor<List<HandlerMethodReturnValueHandler>> handlers;
+
+ @Captor
+ private ArgumentCaptor<AsyncSupportConfigurer> asyncConfigurer;
+
+ @Captor
+ private ArgumentCaptor<List<HandlerExceptionResolver>> exceptionResolvers;
+
+
@Before
public void setUp() {
- webMvcConfigurer = EasyMock.createMock(WebMvcConfigurer.class);
+ MockitoAnnotations.initMocks(this);
delegatingConfig = new DelegatingWebMvcConfiguration();
}
@Test
public void requestMappingHandlerAdapter() throws Exception {
- Capture<List<HttpMessageConverter<?>>> converters = new Capture<List<HttpMessageConverter<?>>>();
- Capture<ContentNegotiationConfigurer> contentNegotiationConfigurer = new Capture<ContentNegotiationConfigurer>();
- Capture<FormattingConversionService> conversionService = new Capture<FormattingConversionService>();
- Capture<List<HandlerMethodArgumentResolver>> resolvers = new Capture<List<HandlerMethodArgumentResolver>>();
- Capture<List<HandlerMethodReturnValueHandler>> handlers = new Capture<List<HandlerMethodReturnValueHandler>>();
- Capture<AsyncSupportConfigurer> asyncConfigurer = new Capture<AsyncSupportConfigurer>();
-
- webMvcConfigurer.configureMessageConverters(capture(converters));
- webMvcConfigurer.configureContentNegotiation(capture(contentNegotiationConfigurer));
- expect(webMvcConfigurer.getValidator()).andReturn(null);
- expect(webMvcConfigurer.getMessageCodesResolver()).andReturn(null);
- webMvcConfigurer.addFormatters(capture(conversionService));
- webMvcConfigurer.addArgumentResolvers(capture(resolvers));
- webMvcConfigurer.addReturnValueHandlers(capture(handlers));
- webMvcConfigurer.configureAsyncSupport(capture(asyncConfigurer));
- replay(webMvcConfigurer);
delegatingConfig.setConfigurers(Arrays.asList(webMvcConfigurer));
RequestMappingHandlerAdapter adapter = delegatingConfig.requestMappingHandlerAdapter();
ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) adapter.getWebBindingInitializer();
- assertSame(conversionService.getValue(), initializer.getConversionService());
+ ConversionService initializerConversionService = initializer.getConversionService();
assertTrue(initializer.getValidator() instanceof LocalValidatorFactoryBean);
+ verify(webMvcConfigurer).configureMessageConverters(converters.capture());
+ verify(webMvcConfigurer).configureContentNegotiation(contentNegotiationConfigurer.capture());
+ verify(webMvcConfigurer).addFormatters(conversionService.capture());
+ verify(webMvcConfigurer).addArgumentResolvers(resolvers.capture());
+ verify(webMvcConfigurer).addReturnValueHandlers(handlers.capture());
+ verify(webMvcConfigurer).configureAsyncSupport(asyncConfigurer.capture());
+
+ assertSame(conversionService.getValue(), initializerConversionService);
assertEquals(0, resolvers.getValue().size());
assertEquals(0, handlers.getValue().size());
assertEquals(converters.getValue(), adapter.getMessageConverters());
assertNotNull(asyncConfigurer);
-
- verify(webMvcConfigurer);
}
@Test
@@ -117,47 +127,39 @@ public void configureMessageConverters(List<HttpMessageConverter<?>> converters)
@Test
public void getCustomValidator() {
- expect(webMvcConfigurer.getValidator()).andReturn(new LocalValidatorFactoryBean());
- replay(webMvcConfigurer);
+ given(webMvcConfigurer.getValidator()).willReturn(new LocalValidatorFactoryBean());
delegatingConfig.setConfigurers(Arrays.asList(webMvcConfigurer));
delegatingConfig.mvcValidator();
- verify(webMvcConfigurer);
+ verify(webMvcConfigurer).getValidator();
}
@Test
public void getCustomMessageCodesResolver() {
- expect(webMvcConfigurer.getMessageCodesResolver()).andReturn(new DefaultMessageCodesResolver());
- replay(webMvcConfigurer);
+ given(webMvcConfigurer.getMessageCodesResolver()).willReturn(new DefaultMessageCodesResolver());
delegatingConfig.setConfigurers(Arrays.asList(webMvcConfigurer));
delegatingConfig.getMessageCodesResolver();
- verify(webMvcConfigurer);
+ verify(webMvcConfigurer).getMessageCodesResolver();
}
@Test
public void handlerExceptionResolver() throws Exception {
- Capture<List<HttpMessageConverter<?>>> converters = new Capture<List<HttpMessageConverter<?>>>();
- Capture<List<HandlerExceptionResolver>> exceptionResolvers = new Capture<List<HandlerExceptionResolver>>();
- Capture<ContentNegotiationConfigurer> contentNegotiationConfigurer = new Capture<ContentNegotiationConfigurer>();
-
- webMvcConfigurer.configureMessageConverters(capture(converters));
- webMvcConfigurer.configureContentNegotiation(capture(contentNegotiationConfigurer));
- webMvcConfigurer.configureHandlerExceptionResolvers(capture(exceptionResolvers));
- replay(webMvcConfigurer);
delegatingConfig.setConfigurers(Arrays.asList(webMvcConfigurer));
delegatingConfig.handlerExceptionResolver();
+ verify(webMvcConfigurer).configureMessageConverters(converters.capture());
+ verify(webMvcConfigurer).configureContentNegotiation(contentNegotiationConfigurer.capture());
+ verify(webMvcConfigurer).configureHandlerExceptionResolvers(exceptionResolvers.capture());
+
assertEquals(3, exceptionResolvers.getValue().size());
assertTrue(exceptionResolvers.getValue().get(0) instanceof ExceptionHandlerExceptionResolver);
assertTrue(exceptionResolvers.getValue().get(1) instanceof ResponseStatusExceptionResolver);
assertTrue(exceptionResolvers.getValue().get(2) instanceof DefaultHandlerExceptionResolver);
assertTrue(converters.getValue().size() > 0);
-
- verify(webMvcConfigurer);
}
@Test | true |
Other | spring-projects | spring-framework | 05765d752062f37b202e7dfd20593c995dc47df0.json | Replace EasyMock with Mockito
Issue: SPR-10126 | spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/ControllerTests.java | @@ -1,5 +1,5 @@
/*
- * Copyright 2002-2012 the original author or authors.
+ * Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -28,14 +28,15 @@
import javax.servlet.http.HttpServletResponse;
import junit.framework.TestCase;
-import org.easymock.MockControl;
import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.mock.web.test.MockHttpServletResponse;
import org.springframework.web.context.support.StaticWebApplicationContext;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;
+import static org.mockito.BDDMockito.*;
+
/**
* @author Rod Johnson
* @author Juergen Hoeller
@@ -74,43 +75,31 @@ public void testServletForwardingControllerWithBeanName() throws Exception {
private void doTestServletForwardingController(ServletForwardingController sfc, boolean include)
throws Exception {
- MockControl requestControl = MockControl.createControl(HttpServletRequest.class);
- HttpServletRequest request = (HttpServletRequest) requestControl.getMock();
- MockControl responseControl = MockControl.createControl(HttpServletResponse.class);
- HttpServletResponse response = (HttpServletResponse) responseControl.getMock();
- MockControl contextControl = MockControl.createControl(ServletContext.class);
- ServletContext context = (ServletContext) contextControl.getMock();
- MockControl dispatcherControl = MockControl.createControl(RequestDispatcher.class);
- RequestDispatcher dispatcher = (RequestDispatcher) dispatcherControl.getMock();
-
- request.getMethod();
- requestControl.setReturnValue("GET", 1);
- context.getNamedDispatcher("action");
- contextControl.setReturnValue(dispatcher, 1);
+ HttpServletRequest request = mock(HttpServletRequest.class);
+ HttpServletResponse response = mock(HttpServletResponse.class);
+ ServletContext context = mock(ServletContext.class);
+ RequestDispatcher dispatcher = mock(RequestDispatcher.class);
+
+ given(request.getMethod()).willReturn("GET");
+ given(context.getNamedDispatcher("action")).willReturn(dispatcher);
if (include) {
- request.getAttribute(WebUtils.INCLUDE_REQUEST_URI_ATTRIBUTE);
- requestControl.setReturnValue("somePath", 1);
- dispatcher.include(request, response);
- dispatcherControl.setVoidCallable(1);
+ given(request.getAttribute(WebUtils.INCLUDE_REQUEST_URI_ATTRIBUTE)).willReturn("somePath");
}
else {
- request.getAttribute(WebUtils.INCLUDE_REQUEST_URI_ATTRIBUTE);
- requestControl.setReturnValue(null, 1);
- dispatcher.forward(request, response);
- dispatcherControl.setVoidCallable(1);
+ given(request.getAttribute(WebUtils.INCLUDE_REQUEST_URI_ATTRIBUTE)).willReturn(null);
}
- requestControl.replay();
- contextControl.replay();
- dispatcherControl.replay();
StaticWebApplicationContext sac = new StaticWebApplicationContext();
sac.setServletContext(context);
sfc.setApplicationContext(sac);
assertNull(sfc.handleRequest(request, response));
- requestControl.verify();
- contextControl.verify();
- dispatcherControl.verify();
+ if (include) {
+ verify(dispatcher).include(request, response);
+ }
+ else {
+ verify(dispatcher).forward(request, response);
+ }
}
public void testServletWrappingController() throws Exception { | true |
Other | spring-projects | spring-framework | 05765d752062f37b202e7dfd20593c995dc47df0.json | Replace EasyMock with Mockito
Issue: SPR-10126 | spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/HttpEntityMethodProcessorMockTests.java | @@ -1,5 +1,5 @@
/*
- * Copyright 2002-2012 the original author or authors.
+ * Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,27 +15,14 @@
*/
package org.springframework.web.servlet.mvc.method.annotation;
-import static org.easymock.EasyMock.capture;
-import static org.easymock.EasyMock.createMock;
-import static org.easymock.EasyMock.eq;
-import static org.easymock.EasyMock.expect;
-import static org.easymock.EasyMock.isA;
-import static org.easymock.EasyMock.replay;
-import static org.easymock.EasyMock.reset;
-import static org.easymock.EasyMock.verify;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-import static org.springframework.web.servlet.HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collections;
-import org.easymock.Capture;
import org.junit.Before;
import org.junit.Test;
+import org.mockito.ArgumentCaptor;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
@@ -52,7 +39,12 @@
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.method.support.ModelAndViewContainer;
-import org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor;
+
+import static org.mockito.Mockito.*;
+
+import static org.junit.Assert.*;
+import static org.mockito.BDDMockito.*;
+import static org.springframework.web.servlet.HandlerMapping.*;
/**
* Test fixture for {@link HttpEntityMethodProcessor} delegating to a mock
@@ -88,9 +80,8 @@ public class HttpEntityMethodProcessorMockTests {
@SuppressWarnings("unchecked")
@Before
public void setUp() throws Exception {
- messageConverter = createMock(HttpMessageConverter.class);
- expect(messageConverter.getSupportedMediaTypes()).andReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
- replay(messageConverter);
+ messageConverter = mock(HttpMessageConverter.class);
+ given(messageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
processor = new HttpEntityMethodProcessor(Collections.<HttpMessageConverter<?>>singletonList(messageConverter));
reset(messageConverter);
@@ -135,26 +126,23 @@ public void resolveArgument() throws Exception {
servletRequest.addHeader("Content-Type", contentType.toString());
String body = "Foo";
- expect(messageConverter.canRead(String.class, contentType)).andReturn(true);
- expect(messageConverter.read(eq(String.class), isA(HttpInputMessage.class))).andReturn(body);
- replay(messageConverter);
+ given(messageConverter.canRead(String.class, contentType)).willReturn(true);
+ given(messageConverter.read(eq(String.class), isA(HttpInputMessage.class))).willReturn(body);
Object result = processor.resolveArgument(paramHttpEntity, mavContainer, webRequest, null);
assertTrue(result instanceof HttpEntity);
assertFalse("The requestHandled flag shouldn't change", mavContainer.isRequestHandled());
assertEquals("Invalid argument", body, ((HttpEntity<?>) result).getBody());
- verify(messageConverter);
}
@Test(expected = HttpMediaTypeNotSupportedException.class)
public void resolveArgumentNotReadable() throws Exception {
MediaType contentType = MediaType.TEXT_PLAIN;
servletRequest.addHeader("Content-Type", contentType.toString());
- expect(messageConverter.getSupportedMediaTypes()).andReturn(Arrays.asList(contentType));
- expect(messageConverter.canRead(String.class, contentType)).andReturn(false);
- replay(messageConverter);
+ given(messageConverter.getSupportedMediaTypes()).willReturn(Arrays.asList(contentType));
+ given(messageConverter.canRead(String.class, contentType)).willReturn(false);
processor.resolveArgument(paramHttpEntity, mavContainer, webRequest, null);
@@ -175,16 +163,14 @@ public void handleReturnValue() throws Exception {
MediaType accepted = MediaType.TEXT_PLAIN;
servletRequest.addHeader("Accept", accepted.toString());
- expect(messageConverter.canWrite(String.class, null)).andReturn(true);
- expect(messageConverter.getSupportedMediaTypes()).andReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
- expect(messageConverter.canWrite(String.class, accepted)).andReturn(true);
- messageConverter.write(eq(body), eq(accepted), isA(HttpOutputMessage.class));
- replay(messageConverter);
+ given(messageConverter.canWrite(String.class, null)).willReturn(true);
+ given(messageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
+ given(messageConverter.canWrite(String.class, accepted)).willReturn(true);
processor.handleReturnValue(returnValue, returnTypeResponseEntity, mavContainer, webRequest);
assertTrue(mavContainer.isRequestHandled());
- verify(messageConverter);
+ verify(messageConverter).write(eq(body), eq(accepted), isA(HttpOutputMessage.class));
}
@Test
@@ -195,14 +181,12 @@ public void handleReturnValueProduces() throws Exception {
servletRequest.addHeader("Accept", "text/*");
servletRequest.setAttribute(PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE, Collections.singleton(MediaType.TEXT_HTML));
- expect(messageConverter.canWrite(String.class, MediaType.TEXT_HTML)).andReturn(true);
- messageConverter.write(eq(body), eq(MediaType.TEXT_HTML), isA(HttpOutputMessage.class));
- replay(messageConverter);
+ given(messageConverter.canWrite(String.class, MediaType.TEXT_HTML)).willReturn(true);
processor.handleReturnValue(returnValue, returnTypeResponseEntityProduces, mavContainer, webRequest);
assertTrue(mavContainer.isRequestHandled());
- verify(messageConverter);
+ verify(messageConverter).write(eq(body), eq(MediaType.TEXT_HTML), isA(HttpOutputMessage.class));
}
@Test(expected = HttpMediaTypeNotAcceptableException.class)
@@ -213,10 +197,9 @@ public void handleReturnValueNotAcceptable() throws Exception {
MediaType accepted = MediaType.APPLICATION_ATOM_XML;
servletRequest.addHeader("Accept", accepted.toString());
- expect(messageConverter.canWrite(String.class, null)).andReturn(true);
- expect(messageConverter.getSupportedMediaTypes()).andReturn(Arrays.asList(MediaType.TEXT_PLAIN));
- expect(messageConverter.canWrite(String.class, accepted)).andReturn(false);
- replay(messageConverter);
+ given(messageConverter.canWrite(String.class, null)).willReturn(true);
+ given(messageConverter.getSupportedMediaTypes()).willReturn(Arrays.asList(MediaType.TEXT_PLAIN));
+ given(messageConverter.canWrite(String.class, accepted)).willReturn(false);
processor.handleReturnValue(returnValue, returnTypeResponseEntity, mavContainer, webRequest);
@@ -231,10 +214,9 @@ public void handleReturnValueNotAcceptableProduces() throws Exception {
MediaType accepted = MediaType.TEXT_PLAIN;
servletRequest.addHeader("Accept", accepted.toString());
- expect(messageConverter.canWrite(String.class, null)).andReturn(true);
- expect(messageConverter.getSupportedMediaTypes()).andReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
- expect(messageConverter.canWrite(String.class, accepted)).andReturn(false);
- replay(messageConverter);
+ given(messageConverter.canWrite(String.class, null)).willReturn(true);
+ given(messageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
+ given(messageConverter.canWrite(String.class, accepted)).willReturn(false);
processor.handleReturnValue(returnValue, returnTypeResponseEntityProduces, mavContainer, webRequest);
@@ -270,18 +252,16 @@ public void responseHeaderAndBody() throws Exception {
responseHeaders.set("header", "headerValue");
ResponseEntity<String> returnValue = new ResponseEntity<String>("body", responseHeaders, HttpStatus.ACCEPTED);
- Capture<HttpOutputMessage> outputMessage = new Capture<HttpOutputMessage>();
- expect(messageConverter.canWrite(String.class, null)).andReturn(true);
- expect(messageConverter.getSupportedMediaTypes()).andReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
- expect(messageConverter.canWrite(String.class, MediaType.TEXT_PLAIN)).andReturn(true);
- messageConverter.write(eq("body"), eq(MediaType.TEXT_PLAIN), capture(outputMessage));
- replay(messageConverter);
+ given(messageConverter.canWrite(String.class, null)).willReturn(true);
+ given(messageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
+ given(messageConverter.canWrite(String.class, MediaType.TEXT_PLAIN)).willReturn(true);
processor.handleReturnValue(returnValue, returnTypeResponseEntity, mavContainer, webRequest);
+ ArgumentCaptor<HttpOutputMessage> outputMessage = ArgumentCaptor.forClass(HttpOutputMessage.class);
+ verify(messageConverter).write(eq("body"), eq(MediaType.TEXT_PLAIN), outputMessage.capture());
assertTrue(mavContainer.isRequestHandled());
assertEquals("headerValue", outputMessage.getValue().getHeaders().get("header").get(0));
- verify(messageConverter);
}
public ResponseEntity<String> handle1(HttpEntity<String> httpEntity, ResponseEntity<String> responseEntity, int i) {
@@ -302,4 +282,4 @@ public ResponseEntity<String> handle4() {
}
-}
\ No newline at end of file
+} | true |
Other | spring-projects | spring-framework | 05765d752062f37b202e7dfd20593c995dc47df0.json | Replace EasyMock with Mockito
Issue: SPR-10126 | spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestPartMethodArgumentResolverTests.java | @@ -1,5 +1,5 @@
/*
- * Copyright 2002-2012 the original author or authors.
+ * Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,20 +16,6 @@
package org.springframework.web.servlet.mvc.method.annotation;
-import static org.easymock.EasyMock.createMock;
-import static org.easymock.EasyMock.eq;
-import static org.easymock.EasyMock.expect;
-import static org.easymock.EasyMock.isA;
-import static org.easymock.EasyMock.replay;
-import static org.easymock.EasyMock.reset;
-import static org.easymock.EasyMock.verify;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Arrays;
@@ -52,19 +38,21 @@
import org.springframework.mock.web.test.MockMultipartHttpServletRequest;
import org.springframework.mock.web.test.MockPart;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
+import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.ServletWebRequest;
-import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.MissingServletRequestPartException;
import org.springframework.web.multipart.support.RequestPartServletServerHttpRequest;
-import org.springframework.web.servlet.mvc.method.annotation.RequestPartMethodArgumentResolver;
+
+import static org.junit.Assert.*;
+import static org.mockito.BDDMockito.*;
/**
* Test fixture with {@link RequestPartMethodArgumentResolver} and mock {@link HttpMessageConverter}.
@@ -116,9 +104,8 @@ public void setUp() throws Exception {
paramServlet30Part.initParameterNameDiscovery(new LocalVariableTableParameterNameDiscoverer());
paramRequestParamAnnot = new MethodParameter(method, 8);
- messageConverter = createMock(HttpMessageConverter.class);
- expect(messageConverter.getSupportedMediaTypes()).andReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
- replay(messageConverter);
+ messageConverter = mock(HttpMessageConverter.class);
+ given(messageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
resolver = new RequestPartMethodArgumentResolver(Collections.<HttpMessageConverter<?>>singletonList(messageConverter));
reset(messageConverter);
@@ -246,17 +233,14 @@ public void isMultipartRequestPut() throws Exception {
private void testResolveArgument(SimpleBean argValue, MethodParameter parameter) throws IOException, Exception {
MediaType contentType = MediaType.TEXT_PLAIN;
- expect(messageConverter.canRead(SimpleBean.class, contentType)).andReturn(true);
- expect(messageConverter.read(eq(SimpleBean.class), isA(RequestPartServletServerHttpRequest.class))).andReturn(argValue);
- replay(messageConverter);
+ given(messageConverter.canRead(SimpleBean.class, contentType)).willReturn(true);
+ given(messageConverter.read(eq(SimpleBean.class), isA(RequestPartServletServerHttpRequest.class))).willReturn(argValue);
ModelAndViewContainer mavContainer = new ModelAndViewContainer();
Object actualValue = resolver.resolveArgument(parameter, mavContainer, webRequest, new ValidatingBinderFactory());
assertEquals("Invalid argument value", argValue, actualValue);
assertFalse("The requestHandled flag shouldn't change", mavContainer.isRequestHandled());
-
- verify(messageConverter);
}
private static class SimpleBean { | true |
Other | spring-projects | spring-framework | 05765d752062f37b202e7dfd20593c995dc47df0.json | Replace EasyMock with Mockito
Issue: SPR-10126 | spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestResponseBodyMethodProcessorMockTests.java | @@ -1,5 +1,5 @@
/*
- * Copyright 2002-2012 the original author or authors.
+ * Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,20 +16,6 @@
package org.springframework.web.servlet.mvc.method.annotation;
-import static org.easymock.EasyMock.createMock;
-import static org.easymock.EasyMock.eq;
-import static org.easymock.EasyMock.expect;
-import static org.easymock.EasyMock.isA;
-import static org.easymock.EasyMock.replay;
-import static org.easymock.EasyMock.reset;
-import static org.easymock.EasyMock.verify;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Arrays;
@@ -61,6 +47,9 @@
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.servlet.HandlerMapping;
+import static org.junit.Assert.*;
+import static org.mockito.BDDMockito.*;
+
/**
* Test fixture for {@link RequestResponseBodyMethodProcessor} delegating to a
* mock HttpMessageConverter.
@@ -95,12 +84,10 @@ public class RequestResponseBodyMethodProcessorMockTests {
@SuppressWarnings("unchecked")
@Before
public void setUp() throws Exception {
- messageConverter = createMock(HttpMessageConverter.class);
- expect(messageConverter.getSupportedMediaTypes()).andReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
- replay(messageConverter);
+ messageConverter = mock(HttpMessageConverter.class);
+ given(messageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
processor = new RequestResponseBodyMethodProcessor(Collections.<HttpMessageConverter<?>>singletonList(messageConverter));
- reset(messageConverter);
Method methodHandle1 = getClass().getMethod("handle1", String.class, Integer.TYPE);
paramRequestBodyString = new MethodParameter(methodHandle1, 0);
@@ -138,15 +125,13 @@ public void resolveArgument() throws Exception {
String body = "Foo";
servletRequest.setContent(body.getBytes());
- expect(messageConverter.canRead(String.class, contentType)).andReturn(true);
- expect(messageConverter.read(eq(String.class), isA(HttpInputMessage.class))).andReturn(body);
- replay(messageConverter);
+ given(messageConverter.canRead(String.class, contentType)).willReturn(true);
+ given(messageConverter.read(eq(String.class), isA(HttpInputMessage.class))).willReturn(body);
Object result = processor.resolveArgument(paramRequestBodyString, mavContainer, webRequest, new ValidatingBinderFactory());
assertEquals("Invalid argument", body, result);
assertFalse("The requestHandled flag shouldn't change", mavContainer.isRequestHandled());
- verify(messageConverter);
}
@Test
@@ -172,40 +157,34 @@ private void testResolveArgumentWithValidation(SimpleBean simpleBean) throws IOE
servletRequest.setContent(new byte[] {});
@SuppressWarnings("unchecked")
- HttpMessageConverter<SimpleBean> beanConverter = createMock(HttpMessageConverter.class);
- expect(beanConverter.getSupportedMediaTypes()).andReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
- expect(beanConverter.canRead(SimpleBean.class, contentType)).andReturn(true);
- expect(beanConverter.read(eq(SimpleBean.class), isA(HttpInputMessage.class))).andReturn(simpleBean);
- replay(beanConverter);
+ HttpMessageConverter<SimpleBean> beanConverter = mock(HttpMessageConverter.class);
+ given(beanConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
+ given(beanConverter.canRead(SimpleBean.class, contentType)).willReturn(true);
+ given(beanConverter.read(eq(SimpleBean.class), isA(HttpInputMessage.class))).willReturn(simpleBean);
processor = new RequestResponseBodyMethodProcessor(Collections.<HttpMessageConverter<?>>singletonList(beanConverter));
processor.resolveArgument(paramValidBean, mavContainer, webRequest, new ValidatingBinderFactory());
-
- verify(beanConverter);
}
@Test(expected = HttpMediaTypeNotSupportedException.class)
public void resolveArgumentCannotRead() throws Exception {
MediaType contentType = MediaType.TEXT_PLAIN;
servletRequest.addHeader("Content-Type", contentType.toString());
- expect(messageConverter.canRead(String.class, contentType)).andReturn(false);
- replay(messageConverter);
+ given(messageConverter.canRead(String.class, contentType)).willReturn(false);
processor.resolveArgument(paramRequestBodyString, mavContainer, webRequest, null);
}
@Test
public void resolveArgumentNoContentType() throws Exception {
- expect(messageConverter.canRead(String.class, MediaType.APPLICATION_OCTET_STREAM)).andReturn(false);
- replay(messageConverter);
+ given(messageConverter.canRead(String.class, MediaType.APPLICATION_OCTET_STREAM)).willReturn(false);
try {
processor.resolveArgument(paramRequestBodyString, mavContainer, webRequest, null);
fail("Expected exception");
}
catch (HttpMediaTypeNotSupportedException ex) {
}
- verify(messageConverter);
}
@Test
@@ -223,16 +202,14 @@ public void handleReturnValue() throws Exception {
servletRequest.addHeader("Accept", accepted.toString());
String body = "Foo";
- expect(messageConverter.canWrite(String.class, null)).andReturn(true);
- expect(messageConverter.getSupportedMediaTypes()).andReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
- expect(messageConverter.canWrite(String.class, accepted)).andReturn(true);
- messageConverter.write(eq(body), eq(accepted), isA(HttpOutputMessage.class));
- replay(messageConverter);
+ given(messageConverter.canWrite(String.class, null)).willReturn(true);
+ given(messageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
+ given(messageConverter.canWrite(String.class, accepted)).willReturn(true);
processor.handleReturnValue(body, returnTypeString, mavContainer, webRequest);
assertTrue("The requestHandled flag wasn't set", mavContainer.isRequestHandled());
- verify(messageConverter);
+ verify(messageConverter).write(eq(body), eq(accepted), isA(HttpOutputMessage.class));
}
@Test
@@ -242,14 +219,12 @@ public void handleReturnValueProduces() throws Exception {
servletRequest.addHeader("Accept", "text/*");
servletRequest.setAttribute(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE, Collections.singleton(MediaType.TEXT_HTML));
- expect(messageConverter.canWrite(String.class, MediaType.TEXT_HTML)).andReturn(true);
- messageConverter.write(eq(body), eq(MediaType.TEXT_HTML), isA(HttpOutputMessage.class));
- replay(messageConverter);
+ given(messageConverter.canWrite(String.class, MediaType.TEXT_HTML)).willReturn(true);
processor.handleReturnValue(body, returnTypeStringProduces, mavContainer, webRequest);
assertTrue(mavContainer.isRequestHandled());
- verify(messageConverter);
+ verify(messageConverter).write(eq(body), eq(MediaType.TEXT_HTML), isA(HttpOutputMessage.class));
}
@@ -258,10 +233,9 @@ public void handleReturnValueNotAcceptable() throws Exception {
MediaType accepted = MediaType.APPLICATION_ATOM_XML;
servletRequest.addHeader("Accept", accepted.toString());
- expect(messageConverter.canWrite(String.class, null)).andReturn(true);
- expect(messageConverter.getSupportedMediaTypes()).andReturn(Arrays.asList(MediaType.TEXT_PLAIN));
- expect(messageConverter.canWrite(String.class, accepted)).andReturn(false);
- replay(messageConverter);
+ given(messageConverter.canWrite(String.class, null)).willReturn(true);
+ given(messageConverter.getSupportedMediaTypes()).willReturn(Arrays.asList(MediaType.TEXT_PLAIN));
+ given(messageConverter.canWrite(String.class, accepted)).willReturn(false);
processor.handleReturnValue("Foo", returnTypeString, mavContainer, webRequest);
}
@@ -271,10 +245,9 @@ public void handleReturnValueNotAcceptableProduces() throws Exception {
MediaType accepted = MediaType.TEXT_PLAIN;
servletRequest.addHeader("Accept", accepted.toString());
- expect(messageConverter.canWrite(String.class, null)).andReturn(true);
- expect(messageConverter.getSupportedMediaTypes()).andReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
- expect(messageConverter.canWrite(String.class, accepted)).andReturn(false);
- replay(messageConverter);
+ given(messageConverter.canWrite(String.class, null)).willReturn(true);
+ given(messageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
+ given(messageConverter.canWrite(String.class, accepted)).willReturn(false);
processor.handleReturnValue("Foo", returnTypeStringProduces, mavContainer, webRequest);
}
@@ -289,16 +262,14 @@ public void handleReturnValueMediaTypeSuffix() throws Exception {
servletRequest.addHeader("Accept", accepted);
- expect(messageConverter.canWrite(String.class, null)).andReturn(true);
- expect(messageConverter.getSupportedMediaTypes()).andReturn(supported);
- expect(messageConverter.canWrite(String.class, accepted)).andReturn(true);
- messageConverter.write(eq(body), eq(accepted), isA(HttpOutputMessage.class));
- replay(messageConverter);
+ given(messageConverter.canWrite(String.class, null)).willReturn(true);
+ given(messageConverter.getSupportedMediaTypes()).willReturn(supported);
+ given(messageConverter.canWrite(String.class, accepted)).willReturn(true);
processor.handleReturnValue(body, returnTypeStringProduces, mavContainer, webRequest);
assertTrue(mavContainer.isRequestHandled());
- verify(messageConverter);
+ verify(messageConverter).write(eq(body), eq(accepted), isA(HttpOutputMessage.class));
}
@@ -348,4 +319,4 @@ public String getName() {
}
}
-}
\ No newline at end of file
+} | true |
Other | spring-projects | spring-framework | 05765d752062f37b202e7dfd20593c995dc47df0.json | Replace EasyMock with Mockito
Issue: SPR-10126 | spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/AbstractHtmlElementTagTests.java | @@ -1,5 +1,5 @@
/*
- * Copyright 2002-2012 the original author or authors.
+ * Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,8 +16,6 @@
package org.springframework.web.servlet.tags.form;
-import static org.easymock.EasyMock.createMock;
-
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
@@ -32,14 +30,16 @@
import org.springframework.validation.BindingResult;
import org.springframework.validation.Errors;
import org.springframework.web.context.support.StaticWebApplicationContext;
-import org.springframework.web.servlet.support.RequestDataValueProcessorWrapper;
import org.springframework.web.servlet.support.JspAwareRequestContext;
import org.springframework.web.servlet.support.RequestContext;
import org.springframework.web.servlet.support.RequestContextUtils;
import org.springframework.web.servlet.support.RequestDataValueProcessor;
+import org.springframework.web.servlet.support.RequestDataValueProcessorWrapper;
import org.springframework.web.servlet.tags.AbstractTagTests;
import org.springframework.web.servlet.tags.RequestContextAwareTag;
+import static org.mockito.BDDMockito.*;
+
/**
* @author Rob Harrop
* @author Juergen Hoeller
@@ -102,7 +102,7 @@ protected final RequestContext getRequestContext() {
}
protected RequestDataValueProcessor getMockRequestDataValueProcessor() {
- RequestDataValueProcessor mockProcessor = createMock(RequestDataValueProcessor.class);
+ RequestDataValueProcessor mockProcessor = mock(RequestDataValueProcessor.class);
ServletRequest request = getPageContext().getRequest();
StaticWebApplicationContext wac = (StaticWebApplicationContext) RequestContextUtils.getWebApplicationContext(request);
wac.getBean(RequestDataValueProcessorWrapper.class).setRequestDataValueProcessor(mockProcessor); | true |
Other | spring-projects | spring-framework | 05765d752062f37b202e7dfd20593c995dc47df0.json | Replace EasyMock with Mockito
Issue: SPR-10126 | spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/FormTagTests.java | @@ -16,10 +16,6 @@
package org.springframework.web.servlet.tags.form;
-import static org.easymock.EasyMock.expect;
-import static org.easymock.EasyMock.replay;
-import static org.easymock.EasyMock.verify;
-
import java.util.Collections;
import javax.servlet.jsp.PageContext;
@@ -28,6 +24,8 @@
import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.web.servlet.support.RequestDataValueProcessor;
+import static org.mockito.BDDMockito.*;
+
/**
* @author Rob Harrop
* @author Rick Evans
@@ -328,9 +326,8 @@ public void testClearAttributesOnFinally() throws Exception {
public void testRequestDataValueProcessorHooks() throws Exception {
String action = "/my/form?foo=bar";
RequestDataValueProcessor processor = getMockRequestDataValueProcessor();
- expect(processor.processAction(this.request, action)).andReturn(action);
- expect(processor.getExtraHiddenFields(this.request)).andReturn(Collections.singletonMap("key", "value"));
- replay(processor);
+ given(processor.processAction(this.request, action)).willReturn(action);
+ given(processor.getExtraHiddenFields(this.request)).willReturn(Collections.singletonMap("key", "value"));
this.tag.doStartTag();
this.tag.doEndTag();
@@ -341,8 +338,6 @@ public void testRequestDataValueProcessorHooks() throws Exception {
assertEquals("<input type=\"hidden\" name=\"key\" value=\"value\" />", getInputTag(output));
assertFormTagOpened(output);
assertFormTagClosed(output);
-
- verify(processor);
}
private String getFormTag(String output) { | true |
Other | spring-projects | spring-framework | 05765d752062f37b202e7dfd20593c995dc47df0.json | Replace EasyMock with Mockito
Issue: SPR-10126 | spring-webmvc/src/test/java/org/springframework/web/servlet/view/BaseViewTests.java | @@ -1,5 +1,5 @@
/*
- * Copyright 2002-2012 the original author or authors.
+ * Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,11 +15,6 @@
*/
package org.springframework.web.servlet.view;
-import static org.easymock.EasyMock.createMock;
-import static org.easymock.EasyMock.expectLastCall;
-import static org.easymock.EasyMock.replay;
-import static org.easymock.EasyMock.verify;
-
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
@@ -40,6 +35,8 @@
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.View;
+import static org.mockito.BDDMockito.*;
+
/**
* Tests for AbstractView. Not called AbstractViewTests as
* would otherwise be excluded by Ant build script wildcard.
@@ -49,11 +46,8 @@
public class BaseViewTests extends TestCase {
public void testRenderWithoutStaticAttributes() throws Exception {
-
- WebApplicationContext wac = createMock(WebApplicationContext.class);
- wac.getServletContext();
- expectLastCall().andReturn(new MockServletContext());
- replay(wac);
+ WebApplicationContext wac = mock(WebApplicationContext.class);
+ given(wac.getServletContext()).willReturn(new MockServletContext());
HttpServletRequest request = new MockHttpServletRequest();
HttpServletResponse response = new MockHttpServletResponse();
@@ -72,17 +66,14 @@ public void testRenderWithoutStaticAttributes() throws Exception {
checkContainsAll(model, tv.model);
assertTrue(tv.inited);
- verify(wac);
}
/**
* Test attribute passing, NOT CSV parsing.
*/
public void testRenderWithStaticAttributesNoCollision() throws Exception {
- WebApplicationContext wac = createMock(WebApplicationContext.class);
- wac.getServletContext();
- expectLastCall().andReturn(new MockServletContext());
- replay(wac);
+ WebApplicationContext wac = mock(WebApplicationContext.class);
+ given(wac.getServletContext()).willReturn(new MockServletContext());
HttpServletRequest request = new MockHttpServletRequest();
HttpServletResponse response = new MockHttpServletResponse();
@@ -104,14 +95,11 @@ public void testRenderWithStaticAttributesNoCollision() throws Exception {
checkContainsAll(p, tv.model);
assertTrue(tv.inited);
- verify(wac);
}
public void testPathVarsOverrideStaticAttributes() throws Exception {
- WebApplicationContext wac = createMock(WebApplicationContext.class);
- wac.getServletContext();
- expectLastCall().andReturn(new MockServletContext());
- replay(wac);
+ WebApplicationContext wac = mock(WebApplicationContext.class);
+ given(wac.getServletContext()).willReturn(new MockServletContext());
HttpServletRequest request = new MockHttpServletRequest();
HttpServletResponse response = new MockHttpServletResponse();
@@ -138,14 +126,11 @@ public void testPathVarsOverrideStaticAttributes() throws Exception {
assertTrue(tv.model.get("something").equals("else"));
assertTrue(tv.inited);
- verify(wac);
}
public void testDynamicModelOverridesStaticAttributesIfCollision() throws Exception {
- WebApplicationContext wac = createMock(WebApplicationContext.class);
- wac.getServletContext();
- expectLastCall().andReturn(new MockServletContext());
- replay(wac);
+ WebApplicationContext wac = mock(WebApplicationContext.class);
+ given(wac.getServletContext()).willReturn(new MockServletContext());
HttpServletRequest request = new MockHttpServletRequest();
HttpServletResponse response = new MockHttpServletResponse();
@@ -169,14 +154,11 @@ public void testDynamicModelOverridesStaticAttributesIfCollision() throws Except
assertTrue(tv.model.get("something").equals("else"));
assertTrue(tv.inited);
- verify(wac);
}
public void testDynamicModelOverridesPathVariables() throws Exception {
- WebApplicationContext wac = createMock(WebApplicationContext.class);
- wac.getServletContext();
- expectLastCall().andReturn(new MockServletContext());
- replay(wac);
+ WebApplicationContext wac = mock(WebApplicationContext.class);
+ given(wac.getServletContext()).willReturn(new MockServletContext());
TestView tv = new TestView(wac);
tv.setApplicationContext(wac);
@@ -202,7 +184,6 @@ public void testDynamicModelOverridesPathVariables() throws Exception {
assertTrue(tv.model.get("something").equals("else"));
assertTrue(tv.inited);
- verify(wac);
}
public void testIgnoresNullAttributes() { | true |
Other | spring-projects | spring-framework | 05765d752062f37b202e7dfd20593c995dc47df0.json | Replace EasyMock with Mockito
Issue: SPR-10126 | spring-webmvc/src/test/java/org/springframework/web/servlet/view/ContentNegotiatingViewResolverTests.java | @@ -1,5 +1,5 @@
/*
- * Copyright 2002-2012 the original author or authors.
+ * Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,15 +16,6 @@
package org.springframework.web.servlet.view;
-import static org.easymock.EasyMock.createMock;
-import static org.easymock.EasyMock.expect;
-import static org.easymock.EasyMock.replay;
-import static org.easymock.EasyMock.verify;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
-
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
@@ -53,6 +44,9 @@
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;
+import static org.junit.Assert.*;
+import static org.mockito.BDDMockito.*;
+
/**
* @author Arjen Poutsma
*/
@@ -92,25 +86,21 @@ public void getMediaTypeAcceptHeaderWithProduces() throws Exception {
public void resolveViewNameWithPathExtension() throws Exception {
request.setRequestURI("/test.xls");
- ViewResolver viewResolverMock = createMock(ViewResolver.class);
+ ViewResolver viewResolverMock = mock(ViewResolver.class);
viewResolver.setViewResolvers(Collections.singletonList(viewResolverMock));
viewResolver.afterPropertiesSet();
- View viewMock = createMock("application_xls", View.class);
+ View viewMock = mock(View.class, "application_xls");
String viewName = "view";
Locale locale = Locale.ENGLISH;
- expect(viewResolverMock.resolveViewName(viewName, locale)).andReturn(null);
- expect(viewResolverMock.resolveViewName(viewName + ".xls", locale)).andReturn(viewMock);
- expect(viewMock.getContentType()).andReturn("application/vnd.ms-excel").anyTimes();
-
- replay(viewResolverMock, viewMock);
+ given(viewResolverMock.resolveViewName(viewName, locale)).willReturn(null);
+ given(viewResolverMock.resolveViewName(viewName + ".xls", locale)).willReturn(viewMock);
+ given(viewMock.getContentType()).willReturn("application/vnd.ms-excel");
View result = viewResolver.resolveViewName(viewName, locale);
assertSame("Invalid view", viewMock, result);
-
- verify(viewResolverMock, viewMock);
}
@Test
@@ -123,23 +113,20 @@ public void resolveViewNameWithAcceptHeader() throws Exception {
manager.addFileExtensionResolvers(extensionsResolver);
viewResolver.setContentNegotiationManager(manager);
- ViewResolver viewResolverMock = createMock(ViewResolver.class);
+ ViewResolver viewResolverMock = mock(ViewResolver.class);
viewResolver.setViewResolvers(Collections.singletonList(viewResolverMock));
- View viewMock = createMock("application_xls", View.class);
+ View viewMock = mock(View.class, "application_xls");
String viewName = "view";
Locale locale = Locale.ENGLISH;
- expect(viewResolverMock.resolveViewName(viewName, locale)).andReturn(null);
- expect(viewResolverMock.resolveViewName(viewName + ".xls", locale)).andReturn(viewMock);
- expect(viewMock.getContentType()).andReturn("application/vnd.ms-excel").anyTimes();
-
- replay(viewResolverMock, viewMock);
+ given(viewResolverMock.resolveViewName(viewName, locale)).willReturn(null);
+ given(viewResolverMock.resolveViewName(viewName + ".xls", locale)).willReturn(viewMock);
+ given(viewMock.getContentType()).willReturn("application/vnd.ms-excel");
View result = viewResolver.resolveViewName(viewName, locale);
assertSame("Invalid view", viewMock, result);
- verify(viewResolverMock, viewMock);
}
@Test
@@ -159,26 +146,21 @@ public void resolveViewNameWithRequestParameter() throws Exception {
ParameterContentNegotiationStrategy paramStrategy = new ParameterContentNegotiationStrategy(mapping);
viewResolver.setContentNegotiationManager(new ContentNegotiationManager(paramStrategy));
- ViewResolver viewResolverMock = createMock(ViewResolver.class);
+ ViewResolver viewResolverMock = mock(ViewResolver.class);
viewResolver.setViewResolvers(Collections.singletonList(viewResolverMock));
-
viewResolver.afterPropertiesSet();
- View viewMock = createMock("application_xls", View.class);
+ View viewMock = mock(View.class, "application_xls");
String viewName = "view";
Locale locale = Locale.ENGLISH;
- expect(viewResolverMock.resolveViewName(viewName, locale)).andReturn(null);
- expect(viewResolverMock.resolveViewName(viewName + ".xls", locale)).andReturn(viewMock);
- expect(viewMock.getContentType()).andReturn("application/vnd.ms-excel").anyTimes();
-
- replay(viewResolverMock, viewMock);
+ given(viewResolverMock.resolveViewName(viewName, locale)).willReturn(null);
+ given(viewResolverMock.resolveViewName(viewName + ".xls", locale)).willReturn(viewMock);
+ given(viewMock.getContentType()).willReturn("application/vnd.ms-excel");
View result = viewResolver.resolveViewName(viewName, locale);
assertSame("Invalid view", viewMock, result);
-
- verify(viewResolverMock, viewMock);
}
@Test
@@ -189,58 +171,49 @@ public void resolveViewNameWithDefaultContentType() throws Exception {
FixedContentNegotiationStrategy fixedStrategy = new FixedContentNegotiationStrategy(mediaType);
viewResolver.setContentNegotiationManager(new ContentNegotiationManager(fixedStrategy));
- ViewResolver viewResolverMock1 = createMock("viewResolver1", ViewResolver.class);
- ViewResolver viewResolverMock2 = createMock("viewResolver2", ViewResolver.class);
+ ViewResolver viewResolverMock1 = mock(ViewResolver.class, "viewResolver1");
+ ViewResolver viewResolverMock2 = mock(ViewResolver.class, "viewResolver2");
viewResolver.setViewResolvers(Arrays.asList(viewResolverMock1, viewResolverMock2));
-
viewResolver.afterPropertiesSet();
- View viewMock1 = createMock("application_xml", View.class);
- View viewMock2 = createMock("text_html", View.class);
+ View viewMock1 = mock(View.class, "application_xml");
+ View viewMock2 = mock(View.class, "text_html");
String viewName = "view";
Locale locale = Locale.ENGLISH;
- expect(viewResolverMock1.resolveViewName(viewName, locale)).andReturn(viewMock1);
- expect(viewResolverMock2.resolveViewName(viewName, locale)).andReturn(viewMock2);
- expect(viewMock1.getContentType()).andReturn("application/xml").anyTimes();
- expect(viewMock2.getContentType()).andReturn("text/html;charset=ISO-8859-1").anyTimes();
-
- replay(viewResolverMock1, viewResolverMock2, viewMock1, viewMock2);
+ given(viewResolverMock1.resolveViewName(viewName, locale)).willReturn(viewMock1);
+ given(viewResolverMock2.resolveViewName(viewName, locale)).willReturn(viewMock2);
+ given(viewMock1.getContentType()).willReturn("application/xml");
+ given(viewMock2.getContentType()).willReturn("text/html;charset=ISO-8859-1");
View result = viewResolver.resolveViewName(viewName, locale);
assertSame("Invalid view", viewMock1, result);
-
- verify(viewResolverMock1, viewResolverMock2, viewMock1, viewMock2);
}
@Test
public void resolveViewNameAcceptHeader() throws Exception {
request.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
- ViewResolver viewResolverMock1 = createMock(ViewResolver.class);
- ViewResolver viewResolverMock2 = createMock(ViewResolver.class);
+ ViewResolver viewResolverMock1 = mock(ViewResolver.class);
+ ViewResolver viewResolverMock2 = mock(ViewResolver.class);
viewResolver.setViewResolvers(Arrays.asList(viewResolverMock1, viewResolverMock2));
viewResolver.afterPropertiesSet();
- View viewMock1 = createMock("application_xml", View.class);
- View viewMock2 = createMock("text_html", View.class);
+ View viewMock1 = mock(View.class, "application_xml");
+ View viewMock2 = mock(View.class, "text_html");
String viewName = "view";
Locale locale = Locale.ENGLISH;
- expect(viewResolverMock1.resolveViewName(viewName, locale)).andReturn(viewMock1);
- expect(viewResolverMock2.resolveViewName(viewName, locale)).andReturn(viewMock2);
- expect(viewMock1.getContentType()).andReturn("application/xml").anyTimes();
- expect(viewMock2.getContentType()).andReturn("text/html;charset=ISO-8859-1").anyTimes();
-
- replay(viewResolverMock1, viewResolverMock2, viewMock1, viewMock2);
+ given(viewResolverMock1.resolveViewName(viewName, locale)).willReturn(viewMock1);
+ given(viewResolverMock2.resolveViewName(viewName, locale)).willReturn(viewMock2);
+ given(viewMock1.getContentType()).willReturn("application/xml");
+ given(viewMock2.getContentType()).willReturn("text/html;charset=ISO-8859-1");
View result = viewResolver.resolveViewName(viewName, locale);
assertSame("Invalid view", viewMock2, result);
-
- verify(viewResolverMock1, viewResolverMock2, viewMock1, viewMock2);
}
// SPR-9160
@@ -251,26 +224,23 @@ public void resolveViewNameAcceptHeaderSortByQuality() throws Exception {
viewResolver.setContentNegotiationManager(new ContentNegotiationManager(new HeaderContentNegotiationStrategy()));
- ViewResolver htmlViewResolver = createMock(ViewResolver.class);
- ViewResolver jsonViewResolver = createMock(ViewResolver.class);
+ ViewResolver htmlViewResolver = mock(ViewResolver.class);
+ ViewResolver jsonViewResolver = mock(ViewResolver.class);
viewResolver.setViewResolvers(Arrays.asList(htmlViewResolver, jsonViewResolver));
- View htmlView = createMock("text_html", View.class);
- View jsonViewMock = createMock("application_json", View.class);
+ View htmlView = mock(View.class, "text_html");
+ View jsonViewMock = mock(View.class, "application_json");
String viewName = "view";
Locale locale = Locale.ENGLISH;
- expect(htmlViewResolver.resolveViewName(viewName, locale)).andReturn(htmlView);
- expect(jsonViewResolver.resolveViewName(viewName, locale)).andReturn(jsonViewMock);
- expect(htmlView.getContentType()).andReturn("text/html").anyTimes();
- expect(jsonViewMock.getContentType()).andReturn("application/json").anyTimes();
- replay(htmlViewResolver, jsonViewResolver, htmlView, jsonViewMock);
+ given(htmlViewResolver.resolveViewName(viewName, locale)).willReturn(htmlView);
+ given(jsonViewResolver.resolveViewName(viewName, locale)).willReturn(jsonViewMock);
+ given(htmlView.getContentType()).willReturn("text/html");
+ given(jsonViewMock.getContentType()).willReturn("application/json");
View result = viewResolver.resolveViewName(viewName, locale);
assertSame("Invalid view", jsonViewMock, result);
-
- verify(htmlViewResolver, jsonViewResolver, htmlView, jsonViewMock);
}
// SPR-9807
@@ -279,40 +249,36 @@ public void resolveViewNameAcceptHeaderSortByQuality() throws Exception {
public void resolveViewNameAcceptHeaderWithSuffix() throws Exception {
request.addHeader("Accept", "application/vnd.example-v2+xml");
- ViewResolver viewResolverMock = createMock(ViewResolver.class);
+ ViewResolver viewResolverMock = mock(ViewResolver.class);
viewResolver.setViewResolvers(Arrays.asList(viewResolverMock));
viewResolver.afterPropertiesSet();
- View viewMock = createMock("application_xml", View.class);
+ View viewMock = mock(View.class, "application_xml");
String viewName = "view";
Locale locale = Locale.ENGLISH;
- expect(viewResolverMock.resolveViewName(viewName, locale)).andReturn(viewMock);
- expect(viewMock.getContentType()).andReturn("application/*+xml").anyTimes();
-
- replay(viewResolverMock, viewMock);
+ given(viewResolverMock.resolveViewName(viewName, locale)).willReturn(viewMock);
+ given(viewMock.getContentType()).willReturn("application/*+xml");
View result = viewResolver.resolveViewName(viewName, locale);
assertSame("Invalid view", viewMock, result);
assertEquals(new MediaType("application", "vnd.example-v2+xml"), request.getAttribute(View.SELECTED_CONTENT_TYPE));
-
- verify(viewResolverMock, viewMock);
}
@Test
public void resolveViewNameAcceptHeaderDefaultView() throws Exception {
request.addHeader("Accept", "application/json");
- ViewResolver viewResolverMock1 = createMock(ViewResolver.class);
- ViewResolver viewResolverMock2 = createMock(ViewResolver.class);
+ ViewResolver viewResolverMock1 = mock(ViewResolver.class);
+ ViewResolver viewResolverMock2 = mock(ViewResolver.class);
viewResolver.setViewResolvers(Arrays.asList(viewResolverMock1, viewResolverMock2));
- View viewMock1 = createMock("application_xml", View.class);
- View viewMock2 = createMock("text_html", View.class);
- View viewMock3 = createMock("application_json", View.class);
+ View viewMock1 = mock(View.class, "application_xml");
+ View viewMock2 = mock(View.class, "text_html");
+ View viewMock3 = mock(View.class, "application_json");
List<View> defaultViews = new ArrayList<View>();
defaultViews.add(viewMock3);
@@ -323,49 +289,41 @@ public void resolveViewNameAcceptHeaderDefaultView() throws Exception {
String viewName = "view";
Locale locale = Locale.ENGLISH;
- expect(viewResolverMock1.resolveViewName(viewName, locale)).andReturn(viewMock1);
- expect(viewResolverMock2.resolveViewName(viewName, locale)).andReturn(viewMock2);
- expect(viewMock1.getContentType()).andReturn("application/xml").anyTimes();
- expect(viewMock2.getContentType()).andReturn("text/html;charset=ISO-8859-1").anyTimes();
- expect(viewMock3.getContentType()).andReturn("application/json").anyTimes();
-
- replay(viewResolverMock1, viewResolverMock2, viewMock1, viewMock2, viewMock3);
+ given(viewResolverMock1.resolveViewName(viewName, locale)).willReturn(viewMock1);
+ given(viewResolverMock2.resolveViewName(viewName, locale)).willReturn(viewMock2);
+ given(viewMock1.getContentType()).willReturn("application/xml");
+ given(viewMock2.getContentType()).willReturn("text/html;charset=ISO-8859-1");
+ given(viewMock3.getContentType()).willReturn("application/json");
View result = viewResolver.resolveViewName(viewName, locale);
assertSame("Invalid view", viewMock3, result);
-
- verify(viewResolverMock1, viewResolverMock2, viewMock1, viewMock2, viewMock3);
}
@Test
public void resolveViewNameFilename() throws Exception {
request.setRequestURI("/test.html");
- ViewResolver viewResolverMock1 = createMock("viewResolver1", ViewResolver.class);
- ViewResolver viewResolverMock2 = createMock("viewResolver2", ViewResolver.class);
+ ViewResolver viewResolverMock1 = mock(ViewResolver.class, "viewResolver1");
+ ViewResolver viewResolverMock2 = mock(ViewResolver.class, "viewResolver2");
viewResolver.setViewResolvers(Arrays.asList(viewResolverMock1, viewResolverMock2));
viewResolver.afterPropertiesSet();
- View viewMock1 = createMock("application_xml", View.class);
- View viewMock2 = createMock("text_html", View.class);
+ View viewMock1 = mock(View.class, "application_xml");
+ View viewMock2 = mock(View.class, "text_html");
String viewName = "view";
Locale locale = Locale.ENGLISH;
- expect(viewResolverMock1.resolveViewName(viewName, locale)).andReturn(viewMock1);
- expect(viewResolverMock1.resolveViewName(viewName + ".html", locale)).andReturn(null);
- expect(viewResolverMock2.resolveViewName(viewName, locale)).andReturn(null);
- expect(viewResolverMock2.resolveViewName(viewName + ".html", locale)).andReturn(viewMock2);
- expect(viewMock1.getContentType()).andReturn("application/xml").anyTimes();
- expect(viewMock2.getContentType()).andReturn("text/html;charset=ISO-8859-1").anyTimes();
-
- replay(viewResolverMock1, viewResolverMock2, viewMock1, viewMock2);
+ given(viewResolverMock1.resolveViewName(viewName, locale)).willReturn(viewMock1);
+ given(viewResolverMock1.resolveViewName(viewName + ".html", locale)).willReturn(null);
+ given(viewResolverMock2.resolveViewName(viewName, locale)).willReturn(null);
+ given(viewResolverMock2.resolveViewName(viewName + ".html", locale)).willReturn(viewMock2);
+ given(viewMock1.getContentType()).willReturn("application/xml");
+ given(viewMock2.getContentType()).willReturn("text/html;charset=ISO-8859-1");
View result = viewResolver.resolveViewName(viewName, locale);
assertSame("Invalid view", viewMock2, result);
-
- verify(viewResolverMock1, viewResolverMock2, viewMock1, viewMock2);
}
@Test
@@ -376,13 +334,13 @@ public void resolveViewNameFilenameDefaultView() throws Exception {
PathExtensionContentNegotiationStrategy pathStrategy = new PathExtensionContentNegotiationStrategy(mapping);
viewResolver.setContentNegotiationManager(new ContentNegotiationManager(pathStrategy));
- ViewResolver viewResolverMock1 = createMock(ViewResolver.class);
- ViewResolver viewResolverMock2 = createMock(ViewResolver.class);
+ ViewResolver viewResolverMock1 = mock(ViewResolver.class);
+ ViewResolver viewResolverMock2 = mock(ViewResolver.class);
viewResolver.setViewResolvers(Arrays.asList(viewResolverMock1, viewResolverMock2));
- View viewMock1 = createMock("application_xml", View.class);
- View viewMock2 = createMock("text_html", View.class);
- View viewMock3 = createMock("application_json", View.class);
+ View viewMock1 = mock(View.class, "application_xml");
+ View viewMock2 = mock(View.class, "text_html");
+ View viewMock3 = mock(View.class, "application_json");
List<View> defaultViews = new ArrayList<View>();
defaultViews.add(viewMock3);
@@ -393,45 +351,37 @@ public void resolveViewNameFilenameDefaultView() throws Exception {
String viewName = "view";
Locale locale = Locale.ENGLISH;
- expect(viewResolverMock1.resolveViewName(viewName, locale)).andReturn(viewMock1);
- expect(viewResolverMock1.resolveViewName(viewName + ".json", locale)).andReturn(null);
- expect(viewResolverMock2.resolveViewName(viewName, locale)).andReturn(viewMock2);
- expect(viewResolverMock2.resolveViewName(viewName + ".json", locale)).andReturn(null);
- expect(viewMock1.getContentType()).andReturn("application/xml").anyTimes();
- expect(viewMock2.getContentType()).andReturn("text/html;charset=ISO-8859-1").anyTimes();
- expect(viewMock3.getContentType()).andReturn("application/json").anyTimes();
-
- replay(viewResolverMock1, viewResolverMock2, viewMock1, viewMock2, viewMock3);
+ given(viewResolverMock1.resolveViewName(viewName, locale)).willReturn(viewMock1);
+ given(viewResolverMock1.resolveViewName(viewName + ".json", locale)).willReturn(null);
+ given(viewResolverMock2.resolveViewName(viewName, locale)).willReturn(viewMock2);
+ given(viewResolverMock2.resolveViewName(viewName + ".json", locale)).willReturn(null);
+ given(viewMock1.getContentType()).willReturn("application/xml");
+ given(viewMock2.getContentType()).willReturn("text/html;charset=ISO-8859-1");
+ given(viewMock3.getContentType()).willReturn("application/json");
View result = viewResolver.resolveViewName(viewName, locale);
assertSame("Invalid view", viewMock3, result);
-
- verify(viewResolverMock1, viewResolverMock2, viewMock1, viewMock2, viewMock3);
}
@Test
public void resolveViewContentTypeNull() throws Exception {
request.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
- ViewResolver viewResolverMock = createMock(ViewResolver.class);
+ ViewResolver viewResolverMock = mock(ViewResolver.class);
viewResolver.setViewResolvers(Collections.singletonList(viewResolverMock));
viewResolver.afterPropertiesSet();
- View viewMock = createMock("application_xml", View.class);
+ View viewMock = mock(View.class, "application_xml");
String viewName = "view";
Locale locale = Locale.ENGLISH;
- expect(viewResolverMock.resolveViewName(viewName, locale)).andReturn(viewMock);
- expect(viewMock.getContentType()).andReturn(null).anyTimes();
-
- replay(viewResolverMock, viewMock);
+ given(viewResolverMock.resolveViewName(viewName, locale)).willReturn(viewMock);
+ given(viewMock.getContentType()).willReturn(null);
View result = viewResolver.resolveViewName(viewName, locale);
assertNull("Invalid view", result);
-
- verify(viewResolverMock, viewMock);
}
@Test
@@ -445,81 +395,69 @@ public void resolveViewNameRedirectView() throws Exception {
UrlBasedViewResolver urlViewResolver = new InternalResourceViewResolver();
urlViewResolver.setApplicationContext(webAppContext);
- ViewResolver xmlViewResolver = createMock(ViewResolver.class);
+ ViewResolver xmlViewResolver = mock(ViewResolver.class);
viewResolver.setViewResolvers(Arrays.<ViewResolver>asList(xmlViewResolver, urlViewResolver));
- View xmlView = createMock("application_xml", View.class);
- View jsonView = createMock("application_json", View.class);
+ View xmlView = mock(View.class, "application_xml");
+ View jsonView = mock(View.class, "application_json");
viewResolver.setDefaultViews(Arrays.asList(jsonView));
viewResolver.afterPropertiesSet();
String viewName = "redirect:anotherTest";
Locale locale = Locale.ENGLISH;
- expect(xmlViewResolver.resolveViewName(viewName, locale)).andReturn(xmlView);
- expect(jsonView.getContentType()).andReturn("application/json").anyTimes();
-
- replay(xmlViewResolver, xmlView, jsonView);
+ given(xmlViewResolver.resolveViewName(viewName, locale)).willReturn(xmlView);
+ given(jsonView.getContentType()).willReturn("application/json");
View actualView = viewResolver.resolveViewName(viewName, locale);
assertEquals("Invalid view", RedirectView.class, actualView.getClass());
-
- verify(xmlViewResolver, xmlView, jsonView);
}
@Test
public void resolveViewNoMatch() throws Exception {
request.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9");
- ViewResolver viewResolverMock = createMock(ViewResolver.class);
+ ViewResolver viewResolverMock = mock(ViewResolver.class);
viewResolver.setViewResolvers(Collections.singletonList(viewResolverMock));
viewResolver.afterPropertiesSet();
- View viewMock = createMock("application_xml", View.class);
+ View viewMock = mock(View.class, "application_xml");
String viewName = "view";
Locale locale = Locale.ENGLISH;
- expect(viewResolverMock.resolveViewName(viewName, locale)).andReturn(viewMock);
- expect(viewMock.getContentType()).andReturn("application/pdf").anyTimes();
-
- replay(viewResolverMock, viewMock);
+ given(viewResolverMock.resolveViewName(viewName, locale)).willReturn(viewMock);
+ given(viewMock.getContentType()).willReturn("application/pdf");
View result = viewResolver.resolveViewName(viewName, locale);
assertNull("Invalid view", result);
-
- verify(viewResolverMock, viewMock);
}
@Test
public void resolveViewNoMatchUseUnacceptableStatus() throws Exception {
viewResolver.setUseNotAcceptableStatusCode(true);
request.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9");
- ViewResolver viewResolverMock = createMock(ViewResolver.class);
+ ViewResolver viewResolverMock = mock(ViewResolver.class);
viewResolver.setViewResolvers(Collections.singletonList(viewResolverMock));
viewResolver.afterPropertiesSet();
- View viewMock = createMock("application_xml", View.class);
+ View viewMock = mock(View.class, "application_xml");
String viewName = "view";
Locale locale = Locale.ENGLISH;
- expect(viewResolverMock.resolveViewName(viewName, locale)).andReturn(viewMock);
- expect(viewMock.getContentType()).andReturn("application/pdf").anyTimes();
-
- replay(viewResolverMock, viewMock);
+ given(viewResolverMock.resolveViewName(viewName, locale)).willReturn(viewMock);
+ given(viewMock.getContentType()).willReturn("application/pdf");
View result = viewResolver.resolveViewName(viewName, locale);
assertNotNull("Invalid view", result);
MockHttpServletResponse response = new MockHttpServletResponse();
result.render(null, request, response);
assertEquals("Invalid status code set", 406, response.getStatus());
-
- verify(viewResolverMock, viewMock);
}
@Test | true |
Other | spring-projects | spring-framework | 05765d752062f37b202e7dfd20593c995dc47df0.json | Replace EasyMock with Mockito
Issue: SPR-10126 | spring-webmvc/src/test/java/org/springframework/web/servlet/view/InternalResourceViewTests.java | @@ -1,5 +1,5 @@
/*
- * Copyright 2002-2012 the original author or authors.
+ * Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,11 +16,6 @@
package org.springframework.web.servlet.view;
-import static org.easymock.EasyMock.createMock;
-import static org.easymock.EasyMock.expectLastCall;
-import static org.easymock.EasyMock.replay;
-import static org.easymock.EasyMock.verify;
-
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
@@ -36,6 +31,8 @@
import org.springframework.web.servlet.View;
import org.springframework.web.util.WebUtils;
+import static org.mockito.BDDMockito.*;
+
/**
* @author Rod Johnson
* @author Juergen Hoeller
@@ -150,19 +147,9 @@ public void testAlwaysInclude() throws Exception {
String url = "forward-to";
- HttpServletRequest request = createMock(HttpServletRequest.class);
- request.getAttribute(View.PATH_VARIABLES);
- expectLastCall().andReturn(null);
- Set<String> keys = model.keySet();
- for (Iterator<String> iter = keys.iterator(); iter.hasNext();) {
- String key = iter.next();
- request.setAttribute(key, model.get(key));
- expectLastCall().times(1);
- }
-
- request.getRequestDispatcher(url);
- expectLastCall().andReturn(new MockRequestDispatcher(url));
- replay(request);
+ HttpServletRequest request = mock(HttpServletRequest.class);
+ given(request.getAttribute(View.PATH_VARIABLES)).willReturn(null);
+ given(request.getRequestDispatcher(url)).willReturn(new MockRequestDispatcher(url));
MockHttpServletResponse response = new MockHttpServletResponse();
InternalResourceView v = new InternalResourceView();
@@ -172,7 +159,12 @@ public void testAlwaysInclude() throws Exception {
// Can now try multiple tests
v.render(model, request, response);
assertEquals(url, response.getIncludedUrl());
- verify(request);
+
+ Set<String> keys = model.keySet();
+ for (Iterator<String> iter = keys.iterator(); iter.hasNext();) {
+ String key = iter.next();
+ verify(request).setAttribute(key, model.get(key));
+ }
}
public void testIncludeOnAttribute() throws Exception {
@@ -183,21 +175,11 @@ public void testIncludeOnAttribute() throws Exception {
String url = "forward-to";
- HttpServletRequest request = createMock(HttpServletRequest.class);
- request.getAttribute(View.PATH_VARIABLES);
- expectLastCall().andReturn(null);
- Set<String> keys = model.keySet();
- for (Iterator<String> iter = keys.iterator(); iter.hasNext();) {
- String key = iter.next();
- request.setAttribute(key, model.get(key));
- expectLastCall().times(1);
- }
+ HttpServletRequest request = mock(HttpServletRequest.class);
+ given(request.getAttribute(View.PATH_VARIABLES)).willReturn(null);
- request.getAttribute(WebUtils.INCLUDE_REQUEST_URI_ATTRIBUTE);
- expectLastCall().andReturn("somepath");
- request.getRequestDispatcher(url);
- expectLastCall().andReturn(new MockRequestDispatcher(url));
- replay(request);
+ given(request.getAttribute(WebUtils.INCLUDE_REQUEST_URI_ATTRIBUTE)).willReturn("somepath");
+ given(request.getRequestDispatcher(url)).willReturn(new MockRequestDispatcher(url));
MockHttpServletResponse response = new MockHttpServletResponse();
InternalResourceView v = new InternalResourceView();
@@ -206,7 +188,12 @@ public void testIncludeOnAttribute() throws Exception {
// Can now try multiple tests
v.render(model, request, response);
assertEquals(url, response.getIncludedUrl());
- verify(request);
+
+ Set<String> keys = model.keySet();
+ for (Iterator<String> iter = keys.iterator(); iter.hasNext();) {
+ String key = iter.next();
+ verify(request).setAttribute(key, model.get(key));
+ }
}
public void testIncludeOnCommitted() throws Exception {
@@ -217,21 +204,11 @@ public void testIncludeOnCommitted() throws Exception {
String url = "forward-to";
- HttpServletRequest request = createMock(HttpServletRequest.class);
- request.getAttribute(View.PATH_VARIABLES);
- expectLastCall().andReturn(null);
- Set<String> keys = model.keySet();
- for (Iterator<String> iter = keys.iterator(); iter.hasNext();) {
- String key = iter.next();
- request.setAttribute(key, model.get(key));
- expectLastCall().times(1);
- }
+ HttpServletRequest request = mock(HttpServletRequest.class);
+ given(request.getAttribute(View.PATH_VARIABLES)).willReturn(null);
- request.getAttribute(WebUtils.INCLUDE_REQUEST_URI_ATTRIBUTE);
- expectLastCall().andReturn(null);
- request.getRequestDispatcher(url);
- expectLastCall().andReturn(new MockRequestDispatcher(url));
- replay(request);
+ given(request.getAttribute(WebUtils.INCLUDE_REQUEST_URI_ATTRIBUTE)).willReturn(null);
+ given(request.getRequestDispatcher(url)).willReturn(new MockRequestDispatcher(url));
MockHttpServletResponse response = new MockHttpServletResponse();
response.setCommitted(true);
@@ -241,7 +218,12 @@ public void testIncludeOnCommitted() throws Exception {
// Can now try multiple tests
v.render(model, request, response);
assertEquals(url, response.getIncludedUrl());
- verify(request);
+
+ Set<String> keys = model.keySet();
+ for (Iterator<String> iter = keys.iterator(); iter.hasNext();) {
+ String key = iter.next();
+ verify(request).setAttribute(key, model.get(key));
+ }
}
} | true |
Other | spring-projects | spring-framework | 05765d752062f37b202e7dfd20593c995dc47df0.json | Replace EasyMock with Mockito
Issue: SPR-10126 | spring-webmvc/src/test/java/org/springframework/web/servlet/view/RedirectViewTests.java | @@ -16,14 +16,6 @@
package org.springframework.web.servlet.view;
-import static org.easymock.EasyMock.createMock;
-import static org.easymock.EasyMock.createNiceMock;
-import static org.easymock.EasyMock.expect;
-import static org.easymock.EasyMock.replay;
-import static org.easymock.EasyMock.verify;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@@ -34,13 +26,12 @@
import junit.framework.AssertionFailedError;
-import org.easymock.EasyMock;
import org.junit.Test;
-import org.springframework.tests.sample.beans.TestBean;
import org.springframework.http.HttpStatus;
import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.mock.web.test.MockHttpServletResponse;
import org.springframework.mock.web.test.MockServletContext;
+import org.springframework.tests.sample.beans.TestBean;
import org.springframework.ui.ModelMap;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.support.StaticWebApplicationContext;
@@ -53,6 +44,9 @@
import org.springframework.web.servlet.support.SessionFlashMapManager;
import org.springframework.web.util.WebUtils;
+import static org.junit.Assert.*;
+import static org.mockito.BDDMockito.*;
+
/**
* Tests for redirect view, and query string construction.
* Doesn't test URL encoding, although it does check that it's called.
@@ -156,7 +150,7 @@ public void updateTargetUrl() throws Exception {
wac.setServletContext(new MockServletContext());
wac.refresh();
- RequestDataValueProcessor mockProcessor = createMock(RequestDataValueProcessor.class);
+ RequestDataValueProcessor mockProcessor = mock(RequestDataValueProcessor.class);
wac.getBean(RequestDataValueProcessorWrapper.class).setRequestDataValueProcessor(mockProcessor);
RedirectView rv = new RedirectView();
@@ -167,12 +161,11 @@ public void updateTargetUrl() throws Exception {
request.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
HttpServletResponse response = new MockHttpServletResponse();
- EasyMock.expect(mockProcessor.processUrl(request, "/path")).andReturn("/path?key=123");
- EasyMock.replay(mockProcessor);
+ given(mockProcessor.processUrl(request, "/path")).willReturn("/path?key=123");
rv.render(new ModelMap(), request, response);
- EasyMock.verify(mockProcessor);
+ verify(mockProcessor).processUrl(request, "/path");
}
@@ -186,7 +179,7 @@ public void updateTargetUrlWithContextLoader() throws Exception {
contextLoader.initWebApplicationContext(servletContext);
try {
- RequestDataValueProcessor mockProcessor = createMock(RequestDataValueProcessor.class);
+ RequestDataValueProcessor mockProcessor = mock(RequestDataValueProcessor.class);
wac.getBean(RequestDataValueProcessorWrapper.class).setRequestDataValueProcessor(mockProcessor);
RedirectView rv = new RedirectView();
@@ -195,12 +188,11 @@ public void updateTargetUrlWithContextLoader() throws Exception {
MockHttpServletRequest request = createRequest();
HttpServletResponse response = new MockHttpServletResponse();
- EasyMock.expect(mockProcessor.processUrl(request, "/path")).andReturn("/path?key=123");
- EasyMock.replay(mockProcessor);
+ given(mockProcessor.processUrl(request, "/path")).willReturn("/path?key=123");
rv.render(new ModelMap(), request, response);
- EasyMock.verify(mockProcessor);
+ verify(mockProcessor).processUrl(request, "/path");
}
finally {
contextLoader.closeWebApplicationContext(servletContext);
@@ -363,32 +355,28 @@ protected Map<String, Object> queryProperties(Map<String, Object> model) {
rv.setContextRelative(contextRelative);
rv.setExposeModelAttributes(exposeModelAttributes);
- HttpServletRequest request = createNiceMock("request", HttpServletRequest.class);
+ HttpServletRequest request = mock(HttpServletRequest.class, "request");
if (exposeModelAttributes) {
- expect(request.getCharacterEncoding()).andReturn(WebUtils.DEFAULT_CHARACTER_ENCODING);
+ given(request.getCharacterEncoding()).willReturn(WebUtils.DEFAULT_CHARACTER_ENCODING);
}
if (contextRelative) {
expectedUrlForEncoding = "/context" + expectedUrlForEncoding;
- expect(request.getContextPath()).andReturn("/context");
+ given(request.getContextPath()).willReturn("/context");
}
- expect(request.getAttribute(DispatcherServlet.OUTPUT_FLASH_MAP_ATTRIBUTE)).andReturn(new FlashMap());
+ given(request.getAttribute(DispatcherServlet.OUTPUT_FLASH_MAP_ATTRIBUTE)).willReturn(new FlashMap());
FlashMapManager flashMapManager = new SessionFlashMapManager();
- expect(request.getAttribute(DispatcherServlet.FLASH_MAP_MANAGER_ATTRIBUTE)).andReturn(flashMapManager);
+ given(request.getAttribute(DispatcherServlet.FLASH_MAP_MANAGER_ATTRIBUTE)).willReturn(flashMapManager);
- HttpServletResponse response = createMock("response", HttpServletResponse.class);
- expect(response.encodeRedirectURL(expectedUrlForEncoding)).andReturn(expectedUrlForEncoding);
+ HttpServletResponse response = mock(HttpServletResponse.class, "response");
+ given(response.encodeRedirectURL(expectedUrlForEncoding)).willReturn(expectedUrlForEncoding);
response.sendRedirect(expectedUrlForEncoding);
- replay(request, response);
-
rv.render(map, request, response);
if (exposeModelAttributes) {
assertTrue("queryProperties() should have been called.", rv.queryPropertiesCalled);
}
-
- verify(request, response);
}
} | true |
Other | spring-projects | spring-framework | 05765d752062f37b202e7dfd20593c995dc47df0.json | Replace EasyMock with Mockito
Issue: SPR-10126 | spring-webmvc/src/test/java/org/springframework/web/servlet/view/freemarker/FreeMarkerViewTests.java | @@ -1,5 +1,5 @@
/*
- * Copyright 2002-2012 the original author or authors.
+ * Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -23,16 +23,10 @@
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
+
import javax.servlet.http.HttpServletResponse;
-import freemarker.ext.servlet.AllHttpScopesHashModel;
-import freemarker.template.Configuration;
-import freemarker.template.Template;
-import freemarker.template.TemplateException;
-import org.easymock.MockControl;
-import static org.junit.Assert.*;
import org.junit.Test;
-
import org.springframework.context.ApplicationContextException;
import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.mock.web.test.MockHttpServletResponse;
@@ -46,6 +40,14 @@
import org.springframework.web.servlet.view.InternalResourceView;
import org.springframework.web.servlet.view.RedirectView;
+import freemarker.ext.servlet.AllHttpScopesHashModel;
+import freemarker.template.Configuration;
+import freemarker.template.Template;
+import freemarker.template.TemplateException;
+
+import static org.junit.Assert.*;
+import static org.mockito.BDDMockito.*;
+
/**
* @author Juergen Hoeller
* @since 14.03.2004
@@ -56,15 +58,9 @@ public class FreeMarkerViewTests {
public void testNoFreeMarkerConfig() throws Exception {
FreeMarkerView fv = new FreeMarkerView();
- MockControl wmc = MockControl.createControl(WebApplicationContext.class);
- WebApplicationContext wac = (WebApplicationContext) wmc.getMock();
- wac.getBeansOfType(FreeMarkerConfig.class, true, false);
- wmc.setReturnValue(new HashMap());
- wac.getParentBeanFactory();
- wmc.setReturnValue(null);
- wac.getServletContext();
- wmc.setReturnValue(new MockServletContext());
- wmc.replay();
+ WebApplicationContext wac = mock(WebApplicationContext.class);
+ given(wac.getBeansOfType(FreeMarkerConfig.class, true, false)).willReturn(new HashMap<String, FreeMarkerConfig>());
+ given(wac.getServletContext()).willReturn(new MockServletContext());
fv.setUrl("anythingButNull");
try {
@@ -76,8 +72,6 @@ public void testNoFreeMarkerConfig() throws Exception {
// Check there's a helpful error message
assertTrue(ex.getMessage().indexOf("FreeMarkerConfig") != -1);
}
-
- wmc.verify();
}
@Test
@@ -97,21 +91,15 @@ public void testNoTemplateName() throws Exception {
public void testValidTemplateName() throws Exception {
FreeMarkerView fv = new FreeMarkerView();
- MockControl wmc = MockControl.createNiceControl(WebApplicationContext.class);
- WebApplicationContext wac = (WebApplicationContext) wmc.getMock();
+ WebApplicationContext wac = mock(WebApplicationContext.class);
MockServletContext sc = new MockServletContext();
- wac.getBeansOfType(FreeMarkerConfig.class, true, false);
Map configs = new HashMap();
FreeMarkerConfigurer configurer = new FreeMarkerConfigurer();
configurer.setConfiguration(new TestConfiguration());
configs.put("configurer", configurer);
- wmc.setReturnValue(configs);
- wac.getParentBeanFactory();
- wmc.setReturnValue(null);
- wac.getServletContext();
- wmc.setReturnValue(sc, 2);
- wmc.replay();
+ given(wac.getBeansOfType(FreeMarkerConfig.class, true, false)).willReturn(configs);
+ given(wac.getServletContext()).willReturn(sc);
fv.setUrl("templateName");
fv.setApplicationContext(wac);
@@ -126,29 +114,22 @@ public void testValidTemplateName() throws Exception {
model.put("myattr", "myvalue");
fv.render(model, request, response);
- wmc.verify();
assertEquals(AbstractView.DEFAULT_CONTENT_TYPE, response.getContentType());
}
@Test
public void testKeepExistingContentType() throws Exception {
FreeMarkerView fv = new FreeMarkerView();
- MockControl wmc = MockControl.createNiceControl(WebApplicationContext.class);
- WebApplicationContext wac = (WebApplicationContext) wmc.getMock();
+ WebApplicationContext wac = mock(WebApplicationContext.class);
MockServletContext sc = new MockServletContext();
- wac.getBeansOfType(FreeMarkerConfig.class, true, false);
Map configs = new HashMap();
FreeMarkerConfigurer configurer = new FreeMarkerConfigurer();
configurer.setConfiguration(new TestConfiguration());
configs.put("configurer", configurer);
- wmc.setReturnValue(configs);
- wac.getParentBeanFactory();
- wmc.setReturnValue(null);
- wac.getServletContext();
- wmc.setReturnValue(sc, 2);
- wmc.replay();
+ given(wac.getBeansOfType(FreeMarkerConfig.class, true, false)).willReturn(configs);
+ given(wac.getServletContext()).willReturn(sc);
fv.setUrl("templateName");
fv.setApplicationContext(wac);
@@ -164,7 +145,6 @@ public void testKeepExistingContentType() throws Exception {
model.put("myattr", "myvalue");
fv.render(model, request, response);
- wmc.verify();
assertEquals("myContentType", response.getContentType());
}
| true |
Other | spring-projects | spring-framework | 05765d752062f37b202e7dfd20593c995dc47df0.json | Replace EasyMock with Mockito
Issue: SPR-10126 | spring-webmvc/src/test/java/org/springframework/web/servlet/view/jasperreports/AbstractJasperReportsViewTests.java | @@ -1,5 +1,5 @@
/*
- * Copyright 2002-2012 the original author or authors.
+ * Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -32,15 +32,16 @@
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRAbstractBeanDataSourceProvider;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
-import org.easymock.MockControl;
-import org.junit.Ignore;
+import org.junit.Ignore;
import org.springframework.context.ApplicationContextException;
import org.springframework.mock.web.test.MockServletContext;
import org.springframework.ui.jasperreports.PersonBean;
import org.springframework.web.context.support.StaticWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
+import static org.mockito.BDDMockito.*;
+
/**
* @author Rob Harrop
* @author Juergen Hoeller
@@ -372,11 +373,8 @@ public void testJRDataSourceOverridesJdbcDataSource() throws Exception {
}
private DataSource getMockJdbcDataSource() throws SQLException {
- MockControl ctl = MockControl.createControl(DataSource.class);
- DataSource ds = (DataSource) ctl.getMock();
- ds.getConnection();
- ctl.setThrowable(new SQLException());
- ctl.replay();
+ DataSource ds = mock(DataSource.class);
+ given(ds.getConnection()).willThrow(new SQLException());
return ds;
}
| true |
Other | spring-projects | spring-framework | 05765d752062f37b202e7dfd20593c995dc47df0.json | Replace EasyMock with Mockito
Issue: SPR-10126 | spring-webmvc/src/test/java/org/springframework/web/servlet/view/json/MappingJackson2JsonViewTests.java | @@ -1,5 +1,5 @@
/*
- * Copyright 2002-2012 the original author or authors.
+ * Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,13 +16,6 @@
package org.springframework.web.servlet.view.json;
-import static org.easymock.EasyMock.createMock;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
-
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
@@ -56,6 +49,9 @@
import com.fasterxml.jackson.databind.ser.SerializerFactory;
import com.fasterxml.jackson.databind.ser.Serializers;
+import static org.junit.Assert.*;
+import static org.mockito.BDDMockito.*;
+
/**
* @author Jeremy Grelle
* @author Arjen Poutsma
@@ -93,7 +89,7 @@ public void isExposePathVars() {
public void renderSimpleMap() throws Exception {
Map<String, Object> model = new HashMap<String, Object>();
- model.put("bindingResult", createMock("binding_result", BindingResult.class));
+ model.put("bindingResult", mock(BindingResult.class, "binding_result"));
model.put("foo", "bar");
view.setUpdateContentLength(true);
@@ -133,7 +129,7 @@ public void renderCaching() throws Exception {
view.setDisableCaching(false);
Map<String, Object> model = new HashMap<String, Object>();
- model.put("bindingResult", createMock("binding_result", BindingResult.class));
+ model.put("bindingResult", mock(BindingResult.class, "binding_result"));
model.put("foo", "bar");
view.render(model, request, response);
@@ -154,7 +150,7 @@ public void renderSimpleBean() throws Exception {
Object bean = new TestBeanSimple();
Map<String, Object> model = new HashMap<String, Object>();
- model.put("bindingResult", createMock("binding_result", BindingResult.class));
+ model.put("bindingResult", mock(BindingResult.class, "binding_result"));
model.put("foo", bean);
view.setUpdateContentLength(true); | true |
Other | spring-projects | spring-framework | 05765d752062f37b202e7dfd20593c995dc47df0.json | Replace EasyMock with Mockito
Issue: SPR-10126 | spring-webmvc/src/test/java/org/springframework/web/servlet/view/json/MappingJacksonJsonViewTests.java | @@ -1,5 +1,5 @@
/*
- * Copyright 2002-2012 the original author or authors.
+ * Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,13 +16,6 @@
package org.springframework.web.servlet.view.json;
-import static org.easymock.EasyMock.createMock;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
-
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
@@ -48,6 +41,9 @@
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
+import static org.junit.Assert.*;
+import static org.mockito.BDDMockito.*;
+
/**
* @author Jeremy Grelle
* @author Arjen Poutsma
@@ -84,7 +80,7 @@ public void isExposePathVars() {
public void renderSimpleMap() throws Exception {
Map<String, Object> model = new HashMap<String, Object>();
- model.put("bindingResult", createMock("binding_result", BindingResult.class));
+ model.put("bindingResult", mock(BindingResult.class, "binding_result"));
model.put("foo", "bar");
view.setUpdateContentLength(true);
@@ -108,7 +104,7 @@ public void renderCaching() throws Exception {
view.setDisableCaching(false);
Map<String, Object> model = new HashMap<String, Object>();
- model.put("bindingResult", createMock("binding_result", BindingResult.class));
+ model.put("bindingResult", mock(BindingResult.class, "binding_result"));
model.put("foo", "bar");
view.render(model, request, response);
@@ -129,7 +125,7 @@ public void renderSimpleBean() throws Exception {
Object bean = new TestBeanSimple();
Map<String, Object> model = new HashMap<String, Object>();
- model.put("bindingResult", createMock("binding_result", BindingResult.class));
+ model.put("bindingResult", mock(BindingResult.class, "binding_result"));
model.put("foo", bean);
view.setUpdateContentLength(true); | true |
Other | spring-projects | spring-framework | 05765d752062f37b202e7dfd20593c995dc47df0.json | Replace EasyMock with Mockito
Issue: SPR-10126 | spring-webmvc/src/test/java/org/springframework/web/servlet/view/velocity/VelocityViewTests.java | @@ -1,5 +1,5 @@
/*
- * Copyright 2002-2012 the original author or authors.
+ * Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,15 +16,6 @@
package org.springframework.web.servlet.view.velocity;
-import static org.easymock.EasyMock.createMock;
-import static org.easymock.EasyMock.expectLastCall;
-import static org.easymock.EasyMock.replay;
-import static org.easymock.EasyMock.verify;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
import java.io.IOException;
import java.util.HashMap;
import java.util.Locale;
@@ -53,6 +44,9 @@
import org.springframework.web.servlet.support.RequestDataValueProcessor;
import org.springframework.web.servlet.view.AbstractView;
+import static org.junit.Assert.*;
+import static org.mockito.BDDMockito.*;
+
/**
* @author Rod Johnson
* @author Juergen Hoeller
@@ -63,12 +57,8 @@ public class VelocityViewTests {
@Test
public void testNoVelocityConfig() throws Exception {
VelocityView vv = new VelocityView();
- WebApplicationContext wac = createMock(WebApplicationContext.class);
- wac.getBeansOfType(VelocityConfig.class, true, false);
- expectLastCall().andReturn(new HashMap<String, Object>());
- wac.getParentBeanFactory();
- expectLastCall().andReturn(null);
- replay(wac);
+ WebApplicationContext wac = mock(WebApplicationContext.class);
+ given(wac.getBeansOfType(VelocityConfig.class, true, false)).willReturn(new HashMap<String, VelocityConfig>());
vv.setUrl("anythingButNull");
try {
@@ -79,8 +69,6 @@ public void testNoVelocityConfig() throws Exception {
// Check there's a helpful error message
assertTrue(ex.getMessage().contains("VelocityConfig"));
}
-
- verify(wac);
}
@Test
@@ -131,7 +119,7 @@ private void testValidTemplateName(final Exception mergeTemplateFailureException
final String templateName = "test.vm";
- WebApplicationContext wac = createMock(WebApplicationContext.class);
+ WebApplicationContext wac = mock(WebApplicationContext.class);
MockServletContext sc = new MockServletContext();
sc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
@@ -142,17 +130,12 @@ public VelocityEngine getVelocityEngine() {
return new TestVelocityEngine(templateName, expectedTemplate);
}
};
- wac.getBeansOfType(VelocityConfig.class, true, false);
- Map<String, Object> configurers = new HashMap<String, Object>();
+ Map<String, VelocityConfig> configurers = new HashMap<String, VelocityConfig>();
configurers.put("velocityConfigurer", vc);
- expectLastCall().andReturn(configurers);
- wac.getParentBeanFactory();
- expectLastCall().andReturn(null);
- wac.getServletContext();
- expectLastCall().andReturn(sc).times(3);
- wac.getBean("requestDataValueProcessor", RequestDataValueProcessor.class);
- expectLastCall().andReturn(null);
- replay(wac);
+ given(wac.getBeansOfType(VelocityConfig.class, true, false)).willReturn(configurers);
+ given(wac.getServletContext()).willReturn(sc);
+ given(wac.getBean("requestDataValueProcessor",
+ RequestDataValueProcessor.class)).willReturn(null);
HttpServletRequest request = new MockHttpServletRequest();
final HttpServletResponse expectedResponse = new MockHttpServletResponse();
@@ -182,15 +165,13 @@ protected void mergeTemplate(Template template, Context context, HttpServletResp
assertNotNull(mergeTemplateFailureException);
assertEquals(ex, mergeTemplateFailureException);
}
-
- verify(wac);
}
@Test
public void testKeepExistingContentType() throws Exception {
final String templateName = "test.vm";
- WebApplicationContext wac = createMock(WebApplicationContext.class);
+ WebApplicationContext wac = mock(WebApplicationContext.class);
MockServletContext sc = new MockServletContext();
sc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
@@ -201,17 +182,12 @@ public VelocityEngine getVelocityEngine() {
return new TestVelocityEngine(templateName, expectedTemplate);
}
};
- wac.getBeansOfType(VelocityConfig.class, true, false);
- Map<String, Object> configurers = new HashMap<String, Object>();
+ Map<String, VelocityConfig> configurers = new HashMap<String, VelocityConfig>();
configurers.put("velocityConfigurer", vc);
- expectLastCall().andReturn(configurers);
- wac.getParentBeanFactory();
- expectLastCall().andReturn(null);
- wac.getServletContext();
- expectLastCall().andReturn(sc).times(3);
- wac.getBean("requestDataValueProcessor", RequestDataValueProcessor.class);
- expectLastCall().andReturn(null);
- replay(wac);
+ given(wac.getBeansOfType(VelocityConfig.class, true, false)).willReturn(configurers);
+ given(wac.getServletContext()).willReturn(sc);
+ given(wac.getBean("requestDataValueProcessor",
+ RequestDataValueProcessor.class)).willReturn(null);
HttpServletRequest request = new MockHttpServletRequest();
final HttpServletResponse expectedResponse = new MockHttpServletResponse();
@@ -233,19 +209,15 @@ protected void exposeHelpers(Map<String, Object> model, HttpServletRequest reque
vv.setApplicationContext(wac);
vv.render(new HashMap<String, Object>(), request, expectedResponse);
- verify(wac);
assertEquals("myContentType", expectedResponse.getContentType());
}
@Test
public void testExposeHelpers() throws Exception {
final String templateName = "test.vm";
- WebApplicationContext wac = createMock(WebApplicationContext.class);
- wac.getParentBeanFactory();
- expectLastCall().andReturn(null);
- wac.getServletContext();
- expectLastCall().andReturn(new MockServletContext());
+ WebApplicationContext wac = mock(WebApplicationContext.class);
+ given(wac.getServletContext()).willReturn(new MockServletContext());
final Template expectedTemplate = new Template();
VelocityConfig vc = new VelocityConfig() {
@@ -254,22 +226,16 @@ public VelocityEngine getVelocityEngine() {
return new TestVelocityEngine(templateName, expectedTemplate);
}
};
- wac.getBeansOfType(VelocityConfig.class, true, false);
- Map<String, Object> configurers = new HashMap<String, Object>();
+ Map<String, VelocityConfig> configurers = new HashMap<String, VelocityConfig>();
configurers.put("velocityConfigurer", vc);
- expectLastCall().andReturn(configurers);
- replay(wac);
+ given(wac.getBeansOfType(VelocityConfig.class, true, false)).willReturn(configurers);
// let it ask for locale
- HttpServletRequest req = createMock(HttpServletRequest.class);
- req.getAttribute(View.PATH_VARIABLES);
- expectLastCall().andReturn(null);
- req.getAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE);
- expectLastCall().andReturn(new AcceptHeaderLocaleResolver());
- req.getLocale();
- expectLastCall().andReturn(Locale.CANADA);
- replay(req);
+ HttpServletRequest req = mock(HttpServletRequest.class);
+ given(req.getAttribute(View.PATH_VARIABLES)).willReturn(null);
+ given(req.getAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE)).willReturn(new AcceptHeaderLocaleResolver());
+ given(req.getLocale()).willReturn(Locale.CANADA);
final HttpServletResponse expectedResponse = new MockHttpServletResponse();
@@ -308,8 +274,6 @@ protected void exposeHelpers(Map<String, Object> model, HttpServletRequest reque
vv.render(new HashMap<String, Object>(), req, expectedResponse);
- verify(wac);
- verify(req);
assertEquals(AbstractView.DEFAULT_CONTENT_TYPE, expectedResponse.getContentType());
}
| true |
Other | spring-projects | spring-framework | 05765d752062f37b202e7dfd20593c995dc47df0.json | Replace EasyMock with Mockito
Issue: SPR-10126 | spring-webmvc/src/test/java/org/springframework/web/servlet/view/xml/MarshallingViewTests.java | @@ -1,5 +1,5 @@
/*
- * Copyright 2002-2012 the original author or authors.
+ * Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,18 +18,19 @@
import java.util.HashMap;
import java.util.Map;
+
import javax.servlet.ServletException;
import javax.xml.transform.stream.StreamResult;
-import static org.easymock.EasyMock.*;
-import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
-
import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.mock.web.test.MockHttpServletResponse;
import org.springframework.oxm.Marshaller;
+import static org.junit.Assert.*;
+import static org.mockito.BDDMockito.*;
+
/**
* @author Arjen Poutsma
*/
@@ -41,7 +42,7 @@ public class MarshallingViewTests {
@Before
public void createView() throws Exception {
- marshallerMock = createMock(Marshaller.class);
+ marshallerMock = mock(Marshaller.class);
view = new MarshallingView(marshallerMock);
}
@@ -71,14 +72,12 @@ public void renderModelKey() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
- expect(marshallerMock.supports(Object.class)).andReturn(true);
+ given(marshallerMock.supports(Object.class)).willReturn(true);
marshallerMock.marshal(eq(toBeMarshalled), isA(StreamResult.class));
- replay(marshallerMock);
view.render(model, request, response);
assertEquals("Invalid content type", "application/xml", response.getContentType());
assertEquals("Invalid content length", 0, response.getContentLength());
- verify(marshallerMock);
}
@Test
@@ -92,7 +91,6 @@ public void renderInvalidModelKey() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
- replay(marshallerMock);
try {
view.render(model, request, response);
fail("ServletException expected");
@@ -101,7 +99,6 @@ public void renderInvalidModelKey() throws Exception {
// expected
}
assertEquals("Invalid content length", 0, response.getContentLength());
- verify(marshallerMock);
}
@Test
@@ -113,7 +110,6 @@ public void renderNullModelValue() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
- replay(marshallerMock);
try {
view.render(model, request, response);
fail("ServletException expected");
@@ -122,7 +118,6 @@ public void renderNullModelValue() throws Exception {
// expected
}
assertEquals("Invalid content length", 0, response.getContentLength());
- verify(marshallerMock);
}
@Test
@@ -136,17 +131,15 @@ public void renderModelKeyUnsupported() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
- expect(marshallerMock.supports(Object.class)).andReturn(false);
+ given(marshallerMock.supports(Object.class)).willReturn(false);
- replay(marshallerMock);
try {
view.render(model, request, response);
fail("ServletException expected");
}
catch (ServletException ex) {
// expected
}
- verify(marshallerMock);
}
@Test
@@ -159,14 +152,12 @@ public void renderNoModelKey() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
- expect(marshallerMock.supports(Object.class)).andReturn(true);
- marshallerMock.marshal(eq(toBeMarshalled), isA(StreamResult.class));
+ given(marshallerMock.supports(Object.class)).willReturn(true);
- replay(marshallerMock);
view.render(model, request, response);
assertEquals("Invalid content type", "application/xml", response.getContentType());
assertEquals("Invalid content length", 0, response.getContentLength());
- verify(marshallerMock);
+ verify(marshallerMock).marshal(eq(toBeMarshalled), isA(StreamResult.class));
}
@Test
@@ -179,17 +170,15 @@ public void testRenderUnsupportedModel() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
- expect(marshallerMock.supports(Object.class)).andReturn(false);
+ given(marshallerMock.supports(Object.class)).willReturn(false);
- replay(marshallerMock);
try {
view.render(model, request, response);
fail("ServletException expected");
}
catch (ServletException ex) {
// expected
}
- verify(marshallerMock);
}
} | true |
Other | spring-projects | spring-framework | 05765d752062f37b202e7dfd20593c995dc47df0.json | Replace EasyMock with Mockito
Issue: SPR-10126 | src/test/java/org/springframework/scheduling/annotation/ScheduledAndTransactionalAnnotationIntegrationTests.java | @@ -16,14 +16,6 @@
package org.springframework.scheduling.annotation;
-import static org.easymock.EasyMock.createMock;
-import static org.easymock.EasyMock.replay;
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.Matchers.greaterThan;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Before;
@@ -43,6 +35,10 @@
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;
+import static org.hamcrest.Matchers.*;
+import static org.junit.Assert.*;
+import static org.mockito.BDDMockito.*;
+
/**
* Integration tests cornering bug SPR-8651, which revealed that @Scheduled methods may
* not work well with beans that have already been proxied for other reasons such
@@ -81,7 +77,7 @@ public void succeedsWhenSubclassProxyAndScheduledMethodNotPresentOnInterface() t
MyRepository repository = ctx.getBean(MyRepository.class);
CallCountingTransactionManager txManager = ctx.getBean(CallCountingTransactionManager.class);
- assertThat("repository is not a proxy", AopUtils.isAopProxy(repository), is(true));
+ assertThat("repository is not a proxy", AopUtils.isAopProxy(repository), equalTo(true));
assertThat("@Scheduled method never called", repository.getInvocationCount(), greaterThan(0));
assertThat("no transactions were committed", txManager.commits, greaterThan(0));
}
@@ -142,8 +138,7 @@ public PlatformTransactionManager txManager() {
@Bean
public PersistenceExceptionTranslator peTranslator() {
- PersistenceExceptionTranslator txlator = createMock(PersistenceExceptionTranslator.class);
- replay(txlator);
+ PersistenceExceptionTranslator txlator = mock(PersistenceExceptionTranslator.class);
return txlator;
}
} | true |
Other | spring-projects | spring-framework | c611083415845bcb9758c0f92c4749a712b049f0.json | Catch IAE when parsing content type
Issue: SPR-10308 | spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMapping.java | @@ -205,7 +205,12 @@ else if (patternAndMethodMatches.isEmpty() && !allowedMethods.isEmpty()) {
if (!consumableMediaTypes.isEmpty()) {
MediaType contentType = null;
if (StringUtils.hasLength(request.getContentType())) {
- contentType = MediaType.parseMediaType(request.getContentType());
+ try {
+ contentType = MediaType.parseMediaType(request.getContentType());
+ }
+ catch (IllegalArgumentException ex) {
+ throw new HttpMediaTypeNotSupportedException(ex.getMessage());
+ }
}
throw new HttpMediaTypeNotSupportedException(contentType, new ArrayList<MediaType>(consumableMediaTypes));
} | true |
Other | spring-projects | spring-framework | c611083415845bcb9758c0f92c4749a712b049f0.json | Catch IAE when parsing content type
Issue: SPR-10308 | spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMappingTests.java | @@ -180,6 +180,19 @@ private void testMediaTypeNotSupported(String url) throws Exception {
}
}
+ @Test
+ public void testMediaTypeNotValue() throws Exception {
+ try {
+ MockHttpServletRequest request = new MockHttpServletRequest("PUT", "/person/1");
+ request.setContentType("bogus");
+ this.handlerMapping.getHandler(request);
+ fail("HttpMediaTypeNotSupportedException expected");
+ }
+ catch (HttpMediaTypeNotSupportedException ex) {
+ assertEquals("Invalid media type \"bogus\": does not contain '/'", ex.getMessage());
+ }
+ }
+
@Test
public void mediaTypeNotAccepted() throws Exception {
testMediaTypeNotAccepted("/persons"); | true |
Other | spring-projects | spring-framework | 3abe05c65e40755e209971888e3d5e6ea38b2487.json | Update @RequestParam javadoc
Issue: SPR-10180 | spring-web/src/main/java/org/springframework/web/bind/annotation/RequestParam.java | @@ -68,8 +68,9 @@
boolean required() default true;
/**
- * The default value to use as a fallback. Supplying a default value implicitly
- * sets {@link #required()} to false.
+ * The default value to use as a fallback when the request parameter value
+ * is not provided or empty. Supplying a default value implicitly sets
+ * {@link #required()} to false.
*/
String defaultValue() default ValueConstants.DEFAULT_NONE;
| false |
Other | spring-projects | spring-framework | 5d727b2d8e6896392a5b55c83ec9ad8e985e97ce.json | Add Castor XSD information to reference docs
Update the Spring OXM reference documentation to include changes
introduced in CastorMarshaller, specifically around CastorMarshaller
XSD configuration.
Issue: SPR-8509 | src/reference/docbook/oxm.xml | @@ -332,6 +332,9 @@ public class Application {
<listitem>
<para><link linkend="oxm-xmlbeans-xsd"><literal>xmlbeans-marshaller</literal></link></para>
</listitem>
+ <listitem>
+ <para><link linkend="oxm-castor-xsd"><literal>castor-marshaller</literal></link></para>
+ </listitem>
<listitem>
<para><link linkend="oxm-jibx-xsd"><literal>jibx-marshaller</literal></link></para>
</listitem>
@@ -475,6 +478,86 @@ public class Application {
</bean>
</beans>
]]></programlisting>
+ <section xml:id="oxm-castor-xsd">
+ <title>XML Schema-based Configuration</title>
+ <para>
+ The <literal>castor-marshaller</literal> tag configures a
+ <classname>org.springframework.oxm.castor.CastorMarshaller</classname>.
+ Here is an example:
+ </para>
+
+ <programlisting language="xml">
+ <![CDATA[<oxm:castor-marshaller id="marshaller" mapping-location="classpath:org/springframework/oxm/castor/mapping.xml"/>]]></programlisting>
+
+ <para>
+ The marshaller instance can be configured in two ways, by specifying either the location of
+ a mapping file (through the <property>mapping-location</property> property), or by
+ identifying Java POJOs (through the <property>target-class</property> or
+ <property>target-package</property> properties) for which there exist corresponding
+ XML descriptor classes. The latter way is usually used in conjunction with XML code generation
+ from XML schemas.
+ </para>
+
+ <para>
+ Available attributes are:
+ <informaltable>
+ <tgroup cols="3">
+ <colspec colwidth="1.5*"/>
+ <colspec colwidth="4*"/>
+ <colspec colwidth="1*"/>
+ <thead>
+ <row>
+ <entry>Attribute</entry>
+ <entry>Description</entry>
+ <entry>Required</entry>
+ </row>
+ </thead>
+ <tbody>
+ <row>
+ <entry>
+ <literal>id</literal>
+ </entry>
+ <entry>the id of the marshaller</entry>
+ <entry>no</entry>
+ </row>
+ <row>
+ <entry>
+ <literal>encoding</literal>
+ </entry>
+ <entry>the encoding to use for unmarshalling from XML</entry>
+ <entry>no</entry>
+ </row>
+ <row>
+ <entry>
+ <literal>target-class</literal>
+ </entry>
+ <entry>a Java class name for a POJO for which an XML class descriptor is available (as
+ generated through code generation)
+ </entry>
+ <entry>no</entry>
+ </row>
+ <row>
+ <entry>
+ <literal>target-package</literal>
+ </entry>
+ <entry>a Java package name that identifies a package that contains POJOs and their
+ corresponding Castor
+ XML descriptor classes (as generated through code generation from XML schemas)
+ </entry>
+ <entry>no</entry>
+ </row>
+ <row>
+ <entry>
+ <literal>mapping-location</literal>
+ </entry>
+ <entry>location of a Castor XML mapping file</entry>
+ <entry>no</entry>
+ </row>
+ </tbody>
+ </tgroup>
+ </informaltable>
+ </para>
+ </section>
</section>
</section>
| false |
Other | spring-projects | spring-framework | 39c236baa8c3f189cc422f2814443fd9652876fb.json | Fix minor javadoc typos | spring-jms/src/main/java/org/springframework/jms/listener/endpoint/JmsMessageEndpointFactory.java | @@ -1,5 +1,5 @@
/*
- * Copyright 2002-2012 the original author or authors.
+ * Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -109,11 +109,11 @@ protected ClassLoader getEndpointClassLoader() {
/**
- * Internal exception thrown when a ResourceExeption has been encountered
+ * Internal exception thrown when a ResourceException has been encountered
* during the endpoint invocation.
* <p>Will only be used if the ResourceAdapter does not invoke the
* endpoint's {@code beforeDelivery} and {@code afterDelivery}
- * directly, leavng it up to the concrete endpoint to apply those -
+ * directly, leaving it up to the concrete endpoint to apply those -
* and to handle any ResourceExceptions thrown from them.
*/
@SuppressWarnings("serial") | true |
Other | spring-projects | spring-framework | 39c236baa8c3f189cc422f2814443fd9652876fb.json | Fix minor javadoc typos | spring-tx/src/main/java/org/springframework/jca/endpoint/GenericMessageEndpointFactory.java | @@ -1,5 +1,5 @@
/*
- * Copyright 2002-2012 the original author or authors.
+ * Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -141,11 +141,11 @@ protected ClassLoader getEndpointClassLoader() {
/**
- * Internal exception thrown when a ResourceExeption has been encountered
+ * Internal exception thrown when a ResourceException has been encountered
* during the endpoint invocation.
* <p>Will only be used if the ResourceAdapter does not invoke the
* endpoint's {@code beforeDelivery} and {@code afterDelivery}
- * directly, leavng it up to the concrete endpoint to apply those -
+ * directly, leaving it up to the concrete endpoint to apply those -
* and to handle any ResourceExceptions thrown from them.
*/
@SuppressWarnings("serial") | true |
Other | spring-projects | spring-framework | c4ba8ce1243012ea1f5e6946614787de1a20dd54.json | Fix incorrect closing <web-app> tag in MVC docs | src/reference/docbook/mvc.xml | @@ -2602,7 +2602,7 @@ deferredResult.setResult(data);
...
- <web-app>
+ </web-app>
</programlisting>
<para>The <classname>DispatcherServlet</classname> and any | false |
Other | spring-projects | spring-framework | c0e4387cbcb9ef0b62372ae8a7a0fbca567b955a.json | Fix JIRA issue number in @Ignore comments
Issue: SPR-10333 | spring-orm/src/test/java/org/springframework/orm/jpa/openjpa/OpenJpaEntityManagerFactoryWithAspectJWeavingIntegrationTests.java | @@ -25,7 +25,7 @@
* @author Ramnivas Laddad
* @author Chris Beams
*/
-@Ignore("This test causes gradle to hang. See SPR-103333.")
+@Ignore("This test causes gradle to hang. See SPR-10333.")
public class OpenJpaEntityManagerFactoryWithAspectJWeavingIntegrationTests extends OpenJpaEntityManagerFactoryIntegrationTests {
@Override | true |
Other | spring-projects | spring-framework | c0e4387cbcb9ef0b62372ae8a7a0fbca567b955a.json | Fix JIRA issue number in @Ignore comments
Issue: SPR-10333 | spring-orm/src/test/java/org/springframework/orm/jpa/toplink/TopLinkMultiEntityManagerFactoryIntegrationTests.java | @@ -28,7 +28,7 @@
* @author Costin Leau
* @author Chris Beams
*/
-@Ignore("This test causes gradle to hang. See SPR-103333.")
+@Ignore("This test causes gradle to hang. See SPR-10333.")
public class TopLinkMultiEntityManagerFactoryIntegrationTests extends
AbstractContainerEntityManagerFactoryIntegrationTests {
| true |
Other | spring-projects | spring-framework | 9b72bf4691c443af062205e001858e984ae9c791.json | Update @since tag for StreamUtils | spring-core/src/main/java/org/springframework/util/StreamUtils.java | @@ -37,7 +37,7 @@
*
* @author Juergen Hoeller
* @author Phillip Webb
- * @since 3.2
+ * @since 3.2.2
* @see FileCopyUtils
*/
public abstract class StreamUtils { | false |
Other | spring-projects | spring-framework | 55caf7bdb0b418d64967f057832eba40de7ff825.json | Improve diagnostics for invalid testGroup values | spring-core/src/test/java/org/springframework/tests/TestGroup.java | @@ -21,6 +21,10 @@
import java.util.HashSet;
import java.util.Set;
+import org.springframework.util.StringUtils;
+
+import static java.lang.String.*;
+
/**
* A test group used to limit when certain tests are run.
*
@@ -64,8 +68,10 @@ public static Set<TestGroup> parse(String value) {
try {
groups.add(valueOf(group.trim().toUpperCase()));
} catch (IllegalArgumentException e) {
- throw new IllegalArgumentException("Unable to find test group '" + group.trim()
- + "' when parsing '" + value + "'");
+ throw new IllegalArgumentException(format(
+ "Unable to find test group '%s' when parsing testGroups value: '%s'. " +
+ "Available groups include: [%s]", group.trim(), value,
+ StringUtils.arrayToCommaDelimitedString(TestGroup.values())));
}
}
return groups; | true |
Other | spring-projects | spring-framework | 55caf7bdb0b418d64967f057832eba40de7ff825.json | Improve diagnostics for invalid testGroup values | spring-core/src/test/java/org/springframework/tests/TestGroupTests.java | @@ -62,7 +62,9 @@ public void parseInMixedCase() throws Exception {
@Test
public void parseMissing() throws Exception {
thrown.expect(IllegalArgumentException.class);
- thrown.expectMessage("Unable to find test group 'missing' when parsing 'performance, missing'");
+ thrown.expectMessage("Unable to find test group 'missing' when parsing " +
+ "testGroups value: 'performance, missing'. Available groups include: " +
+ "[LONG_RUNNING,PERFORMANCE,JMXMP]");
TestGroup.parse("performance, missing");
}
| true |
Other | spring-projects | spring-framework | 7dff02b2c145a94ff47da3e8931d34d05f05f331.json | Fix import issue introduced in prior commit
Issue: SPR-9289 | spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/PathVariableMapMethodArgumentResolver.java | @@ -16,6 +16,7 @@
package org.springframework.web.servlet.mvc.method.annotation;
+import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
@@ -30,8 +31,6 @@
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.servlet.HandlerMapping;
-import edu.emory.mathcs.backport.java.util.Collections;
-
/**
* Resolves {@link Map} method arguments annotated with an @{@link PathVariable}
* where the annotation does not specify a path variable name. The created | false |
Other | spring-projects | spring-framework | c85b6116009ba41202ce6100aa23efc336be1120.json | Update copyright header for XStreamMarshaller
Issue: SPR-9536 | spring-oxm/src/main/java/org/springframework/oxm/xstream/XStreamMarshaller.java | @@ -1,5 +1,5 @@
/*
- * Copyright 2002-2011 the original author or authors.
+ * Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. | false |
Other | spring-projects | spring-framework | a0747458e7e23bf53620caf26f5bb3e2b17bf963.json | Add support for HTTP PATCH method
The HTTP PATCH method is now supported whereever HTTP methods are used.
Annotated controllers can be mapped to RequestMethod.PATCH.
On the client side the RestTemplate execute(..) and exchange(..)
methods can be used with HttpMethod.PATCH. In terms of HTTP client
libraries, Apache HttpComponents HttpClient version 4.2 or later is
required (see HTTPCLIENT-1191). The JDK HttpURLConnection does not
support the HTTP PATCH method.
Issue: SPR-7985 | build.gradle | @@ -360,7 +360,7 @@ project('spring-web') {
compile("commons-fileupload:commons-fileupload:1.2", optional)
runtime("commons-io:commons-io:1.3", optional)
compile("commons-httpclient:commons-httpclient:3.1", optional)
- compile("org.apache.httpcomponents:httpclient:4.1.1", optional)
+ compile("org.apache.httpcomponents:httpclient:4.2", optional)
compile("org.codehaus.jackson:jackson-mapper-asl:1.4.2", optional)
compile("com.fasterxml.jackson.core:jackson-databind:2.0.1", optional)
compile("taglibs:standard:1.1.2", optional) | true |
Other | spring-projects | spring-framework | a0747458e7e23bf53620caf26f5bb3e2b17bf963.json | Add support for HTTP PATCH method
The HTTP PATCH method is now supported whereever HTTP methods are used.
Annotated controllers can be mapped to RequestMethod.PATCH.
On the client side the RestTemplate execute(..) and exchange(..)
methods can be used with HttpMethod.PATCH. In terms of HTTP client
libraries, Apache HttpComponents HttpClient version 4.2 or later is
required (see HTTPCLIENT-1191). The JDK HttpURLConnection does not
support the HTTP PATCH method.
Issue: SPR-7985 | spring-web/src/main/java/org/springframework/http/HttpMethod.java | @@ -1,5 +1,5 @@
/*
- * Copyright 2002-2009 the original author or authors.
+ * Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -26,6 +26,6 @@
*/
public enum HttpMethod {
- GET, POST, HEAD, OPTIONS, PUT, DELETE, TRACE
+ GET, POST, HEAD, OPTIONS, PUT, PATCH, DELETE, TRACE
} | true |
Other | spring-projects | spring-framework | a0747458e7e23bf53620caf26f5bb3e2b17bf963.json | Add support for HTTP PATCH method
The HTTP PATCH method is now supported whereever HTTP methods are used.
Annotated controllers can be mapped to RequestMethod.PATCH.
On the client side the RestTemplate execute(..) and exchange(..)
methods can be used with HttpMethod.PATCH. In terms of HTTP client
libraries, Apache HttpComponents HttpClient version 4.2 or later is
required (see HTTPCLIENT-1191). The JDK HttpURLConnection does not
support the HTTP PATCH method.
Issue: SPR-7985 | spring-web/src/main/java/org/springframework/http/client/CommonsClientHttpRequestFactory.java | @@ -1,5 +1,5 @@
/*
- * Copyright 2002-2011 the original author or authors.
+ * Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -141,6 +141,9 @@ protected HttpMethodBase createCommonsHttpMethod(HttpMethod httpMethod, String u
return new PutMethod(uri);
case TRACE:
return new TraceMethod(uri);
+ case PATCH:
+ throw new IllegalArgumentException(
+ "HTTP method PATCH not available before Apache HttpComponents HttpClient 4.2");
default:
throw new IllegalArgumentException("Invalid HTTP method: " + httpMethod);
} | true |
Other | spring-projects | spring-framework | a0747458e7e23bf53620caf26f5bb3e2b17bf963.json | Add support for HTTP PATCH method
The HTTP PATCH method is now supported whereever HTTP methods are used.
Annotated controllers can be mapped to RequestMethod.PATCH.
On the client side the RestTemplate execute(..) and exchange(..)
methods can be used with HttpMethod.PATCH. In terms of HTTP client
libraries, Apache HttpComponents HttpClient version 4.2 or later is
required (see HTTPCLIENT-1191). The JDK HttpURLConnection does not
support the HTTP PATCH method.
Issue: SPR-7985 | spring-web/src/main/java/org/springframework/http/client/HttpComponentsClientHttpRequestFactory.java | @@ -1,5 +1,5 @@
/*
- * Copyright 2002-2011 the original author or authors.
+ * Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,12 +17,9 @@
package org.springframework.http.client;
import java.io.IOException;
+import java.lang.reflect.Constructor;
import java.net.URI;
-import org.springframework.beans.factory.DisposableBean;
-import org.springframework.http.HttpMethod;
-import org.springframework.util.Assert;
-
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
@@ -40,6 +37,10 @@
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.HttpContext;
+import org.springframework.beans.factory.DisposableBean;
+import org.springframework.http.HttpMethod;
+import org.springframework.util.Assert;
+import org.springframework.util.ClassUtils;
/**
* {@link org.springframework.http.client.ClientHttpRequestFactory} implementation that uses
@@ -155,11 +156,30 @@ protected HttpUriRequest createHttpUriRequest(HttpMethod httpMethod, URI uri) {
return new HttpPut(uri);
case TRACE:
return new HttpTrace(uri);
+ case PATCH:
+ return createHttpPatch(uri);
default:
throw new IllegalArgumentException("Invalid HTTP method: " + httpMethod);
}
}
+ private HttpUriRequest createHttpPatch(URI uri) {
+ String className = "org.apache.http.client.methods.HttpPatch";
+ ClassLoader classloader = this.getClass().getClassLoader();
+ if (!ClassUtils.isPresent(className, classloader)) {
+ throw new IllegalArgumentException(
+ "HTTP method PATCH not available before Apache HttpComponents HttpClient 4.2");
+ }
+ try {
+ Class<?> clazz = classloader.loadClass(className);
+ Constructor<?> constructor = clazz.getConstructor(URI.class);
+ return (HttpUriRequest) constructor.newInstance(uri);
+ }
+ catch (Throwable ex) {
+ throw new IllegalStateException("Unable to instantiate " + className, ex);
+ }
+ }
+
/**
* Template method that allows for manipulating the {@link HttpUriRequest} before it is
* returned as part of a {@link HttpComponentsClientHttpRequest}. | true |
Other | spring-projects | spring-framework | a0747458e7e23bf53620caf26f5bb3e2b17bf963.json | Add support for HTTP PATCH method
The HTTP PATCH method is now supported whereever HTTP methods are used.
Annotated controllers can be mapped to RequestMethod.PATCH.
On the client side the RestTemplate execute(..) and exchange(..)
methods can be used with HttpMethod.PATCH. In terms of HTTP client
libraries, Apache HttpComponents HttpClient version 4.2 or later is
required (see HTTPCLIENT-1191). The JDK HttpURLConnection does not
support the HTTP PATCH method.
Issue: SPR-7985 | spring-web/src/main/java/org/springframework/http/client/SimpleClientHttpRequestFactory.java | @@ -1,5 +1,5 @@
/*
- * Copyright 2002-2011 the original author or authors.
+ * Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -152,7 +152,7 @@ protected void prepareConnection(HttpURLConnection connection, String httpMethod
else {
connection.setInstanceFollowRedirects(false);
}
- if ("PUT".equals(httpMethod) || "POST".equals(httpMethod)) {
+ if ("PUT".equals(httpMethod) || "POST".equals(httpMethod) || "PATCH".equals(httpMethod)) {
connection.setDoOutput(true);
}
else { | true |
Other | spring-projects | spring-framework | a0747458e7e23bf53620caf26f5bb3e2b17bf963.json | Add support for HTTP PATCH method
The HTTP PATCH method is now supported whereever HTTP methods are used.
Annotated controllers can be mapped to RequestMethod.PATCH.
On the client side the RestTemplate execute(..) and exchange(..)
methods can be used with HttpMethod.PATCH. In terms of HTTP client
libraries, Apache HttpComponents HttpClient version 4.2 or later is
required (see HTTPCLIENT-1191). The JDK HttpURLConnection does not
support the HTTP PATCH method.
Issue: SPR-7985 | spring-web/src/main/java/org/springframework/web/HttpMediaTypeNotSupportedException.java | @@ -1,5 +1,5 @@
/*
- * Copyright 2002-2009 the original author or authors.
+ * Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,7 +21,7 @@
import org.springframework.http.MediaType;
/**
- * Exception thrown when a client POSTs or PUTs content
+ * Exception thrown when a client POSTs, PUTs, or PATCHes content of a type
* not supported by request handler.
*
* @author Arjen Poutsma | true |
Other | spring-projects | spring-framework | a0747458e7e23bf53620caf26f5bb3e2b17bf963.json | Add support for HTTP PATCH method
The HTTP PATCH method is now supported whereever HTTP methods are used.
Annotated controllers can be mapped to RequestMethod.PATCH.
On the client side the RestTemplate execute(..) and exchange(..)
methods can be used with HttpMethod.PATCH. In terms of HTTP client
libraries, Apache HttpComponents HttpClient version 4.2 or later is
required (see HTTPCLIENT-1191). The JDK HttpURLConnection does not
support the HTTP PATCH method.
Issue: SPR-7985 | spring-web/src/main/java/org/springframework/web/bind/annotation/RequestMapping.java | @@ -271,7 +271,7 @@
/**
* The HTTP request methods to map to, narrowing the primary mapping:
- * GET, POST, HEAD, OPTIONS, PUT, DELETE, TRACE.
+ * GET, POST, HEAD, OPTIONS, PUT, PATCH, DELETE, TRACE.
* <p><b>Supported at the type level as well as at the method level!</b>
* When used at the type level, all method-level mappings inherit
* this HTTP method restriction (i.e. the type-level restriction | true |
Other | spring-projects | spring-framework | a0747458e7e23bf53620caf26f5bb3e2b17bf963.json | Add support for HTTP PATCH method
The HTTP PATCH method is now supported whereever HTTP methods are used.
Annotated controllers can be mapped to RequestMethod.PATCH.
On the client side the RestTemplate execute(..) and exchange(..)
methods can be used with HttpMethod.PATCH. In terms of HTTP client
libraries, Apache HttpComponents HttpClient version 4.2 or later is
required (see HTTPCLIENT-1191). The JDK HttpURLConnection does not
support the HTTP PATCH method.
Issue: SPR-7985 | spring-web/src/main/java/org/springframework/web/bind/annotation/RequestMethod.java | @@ -1,5 +1,5 @@
/*
- * Copyright 2002-2009 the original author or authors.
+ * Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -22,7 +22,7 @@
* {@link RequestMapping} annotation.
*
* <p>Note that, by default, {@link org.springframework.web.servlet.DispatcherServlet}
- * supports GET, HEAD, POST, PUT and DELETE only. DispatcherServlet will
+ * supports GET, HEAD, POST, PUT, PATCH and DELETE only. DispatcherServlet will
* process TRACE and OPTIONS with the default HttpServlet behavior unless
* explicitly told to dispatch those request types as well: Check out
* the "dispatchOptionsRequest" and "dispatchTraceRequest" properties,
@@ -36,6 +36,6 @@
*/
public enum RequestMethod {
- GET, HEAD, POST, PUT, DELETE, OPTIONS, TRACE
+ GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE
} | true |
Other | spring-projects | spring-framework | a0747458e7e23bf53620caf26f5bb3e2b17bf963.json | Add support for HTTP PATCH method
The HTTP PATCH method is now supported whereever HTTP methods are used.
Annotated controllers can be mapped to RequestMethod.PATCH.
On the client side the RestTemplate execute(..) and exchange(..)
methods can be used with HttpMethod.PATCH. In terms of HTTP client
libraries, Apache HttpComponents HttpClient version 4.2 or later is
required (see HTTPCLIENT-1191). The JDK HttpURLConnection does not
support the HTTP PATCH method.
Issue: SPR-7985 | spring-web/src/main/java/org/springframework/web/filter/HttpPutFormContentFilter.java | @@ -1,5 +1,5 @@
/*
- * Copyright 2002-2011 the original author or authors.
+ * Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -44,24 +44,24 @@
import org.springframework.util.MultiValueMap;
/**
- * {@link javax.servlet.Filter} that makes form encoded data available through
- * the {@code ServletRequest.getParameter*()} family of methods during HTTP PUT
- * requests.
- *
- * <p>The Servlet spec requires form data to be available for HTTP POST but
- * not for HTTP PUT requests. This filter intercepts HTTP PUT requests where
- * content type is {@code 'application/x-www-form-urlencoded'}, reads form
- * encoded content from the body of the request, and wraps the ServletRequest
+ * {@link javax.servlet.Filter} that makes form encoded data available through
+ * the {@code ServletRequest.getParameter*()} family of methods during HTTP PUT
+ * or PATCH requests.
+ *
+ * <p>The Servlet spec requires form data to be available for HTTP POST but
+ * not for HTTP PUT or PATCH requests. This filter intercepts HTTP PUT and PATCH
+ * requests where content type is {@code 'application/x-www-form-urlencoded'},
+ * reads form encoded content from the body of the request, and wraps the ServletRequest
* in order to make the form data available as request parameters just like
* it is for HTTP POST requests.
- *
+ *
* @author Rossen Stoyanchev
* @since 3.1
*/
public class HttpPutFormContentFilter extends OncePerRequestFilter {
private final FormHttpMessageConverter formConverter = new XmlAwareFormHttpMessageConverter();
-
+
/**
* The default character set to use for reading form data.
*/
@@ -73,7 +73,7 @@ public void setCharset(Charset charset) {
protected void doFilterInternal(final HttpServletRequest request, HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
- if ("PUT".equals(request.getMethod()) && isFormContentType(request)) {
+ if (("PUT".equals(request.getMethod()) || "PATCH".equals(request.getMethod())) && isFormContentType(request)) {
HttpInputMessage inputMessage = new ServletServerHttpRequest(request) {
@Override
public InputStream getBody() throws IOException {
@@ -102,7 +102,7 @@ private boolean isFormContentType(HttpServletRequest request) {
}
private static class HttpPutFormContentRequestWrapper extends HttpServletRequestWrapper {
-
+
private MultiValueMap<String, String> formParameters;
public HttpPutFormContentRequestWrapper(HttpServletRequest request, MultiValueMap<String, String> parameters) { | true |
Other | spring-projects | spring-framework | a0747458e7e23bf53620caf26f5bb3e2b17bf963.json | Add support for HTTP PATCH method
The HTTP PATCH method is now supported whereever HTTP methods are used.
Annotated controllers can be mapped to RequestMethod.PATCH.
On the client side the RestTemplate execute(..) and exchange(..)
methods can be used with HttpMethod.PATCH. In terms of HTTP client
libraries, Apache HttpComponents HttpClient version 4.2 or later is
required (see HTTPCLIENT-1191). The JDK HttpURLConnection does not
support the HTTP PATCH method.
Issue: SPR-7985 | spring-web/src/test/java/org/springframework/http/client/AbstractHttpRequestFactoryTestCase.java | @@ -1,5 +1,5 @@
/*
- * Copyright 2002-2011 the original author or authors.
+ * Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -68,6 +68,7 @@ public static void startJettyServer() throws Exception {
jettyContext.addServlet(new ServletHolder(new MethodServlet("OPTIONS")), "/methods/options");
jettyContext.addServlet(new ServletHolder(new PostServlet()), "/methods/post");
jettyContext.addServlet(new ServletHolder(new MethodServlet("PUT")), "/methods/put");
+ jettyContext.addServlet(new ServletHolder(new MethodServlet("PATCH")), "/methods/patch");
jettyServer.start();
}
@@ -160,7 +161,7 @@ public void httpMethods() throws Exception {
assertHttpMethod("delete", HttpMethod.DELETE);
}
- private void assertHttpMethod(String path, HttpMethod method) throws Exception {
+ protected void assertHttpMethod(String path, HttpMethod method) throws Exception {
ClientHttpResponse response = null;
try {
ClientHttpRequest request = factory.createRequest(new URI(baseUrl + "/methods/" + path), method); | true |
Other | spring-projects | spring-framework | a0747458e7e23bf53620caf26f5bb3e2b17bf963.json | Add support for HTTP PATCH method
The HTTP PATCH method is now supported whereever HTTP methods are used.
Annotated controllers can be mapped to RequestMethod.PATCH.
On the client side the RestTemplate execute(..) and exchange(..)
methods can be used with HttpMethod.PATCH. In terms of HTTP client
libraries, Apache HttpComponents HttpClient version 4.2 or later is
required (see HTTPCLIENT-1191). The JDK HttpURLConnection does not
support the HTTP PATCH method.
Issue: SPR-7985 | spring-web/src/test/java/org/springframework/http/client/BufferedSimpleHttpRequestFactoryTests.java | @@ -1,5 +1,5 @@
/*
- * Copyright 2002-2011 the original author or authors.
+ * Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,10 +16,26 @@
package org.springframework.http.client;
+import java.net.ProtocolException;
+
+import org.junit.Test;
+import org.springframework.http.HttpMethod;
+
public class BufferedSimpleHttpRequestFactoryTests extends AbstractHttpRequestFactoryTestCase {
@Override
protected ClientHttpRequestFactory createRequestFactory() {
return new SimpleClientHttpRequestFactory();
}
+
+ @Test
+ public void httpMethods() throws Exception {
+ try {
+ assertHttpMethod("patch", HttpMethod.PATCH);
+ }
+ catch (ProtocolException ex) {
+ // Currently HttpURLConnection does not support HTTP PATCH
+ }
+ }
+
} | true |
Other | spring-projects | spring-framework | a0747458e7e23bf53620caf26f5bb3e2b17bf963.json | Add support for HTTP PATCH method
The HTTP PATCH method is now supported whereever HTTP methods are used.
Annotated controllers can be mapped to RequestMethod.PATCH.
On the client side the RestTemplate execute(..) and exchange(..)
methods can be used with HttpMethod.PATCH. In terms of HTTP client
libraries, Apache HttpComponents HttpClient version 4.2 or later is
required (see HTTPCLIENT-1191). The JDK HttpURLConnection does not
support the HTTP PATCH method.
Issue: SPR-7985 | spring-web/src/test/java/org/springframework/http/client/CommonsHttpRequestFactoryTests.java | @@ -1,5 +1,5 @@
/*
- * Copyright 2002-2009 the original author or authors.
+ * Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,14 +16,21 @@
package org.springframework.http.client;
-import org.springframework.http.client.AbstractHttpRequestFactoryTestCase;
-import org.springframework.http.client.ClientHttpRequestFactory;
-import org.springframework.http.client.CommonsClientHttpRequestFactory;
+import java.net.URI;
+
+import org.junit.Test;
+import org.springframework.http.HttpMethod;
public class CommonsHttpRequestFactoryTests extends AbstractHttpRequestFactoryTestCase {
@Override
protected ClientHttpRequestFactory createRequestFactory() {
return new CommonsClientHttpRequestFactory();
}
+
+ @Test(expected=IllegalArgumentException.class)
+ public void httpPatch() throws Exception {
+ factory.createRequest(new URI(baseUrl + "/methods/PATCH"), HttpMethod.PATCH);
+ }
+
} | true |
Other | spring-projects | spring-framework | a0747458e7e23bf53620caf26f5bb3e2b17bf963.json | Add support for HTTP PATCH method
The HTTP PATCH method is now supported whereever HTTP methods are used.
Annotated controllers can be mapped to RequestMethod.PATCH.
On the client side the RestTemplate execute(..) and exchange(..)
methods can be used with HttpMethod.PATCH. In terms of HTTP client
libraries, Apache HttpComponents HttpClient version 4.2 or later is
required (see HTTPCLIENT-1191). The JDK HttpURLConnection does not
support the HTTP PATCH method.
Issue: SPR-7985 | spring-web/src/test/java/org/springframework/http/client/HttpComponentsClientHttpRequestFactoryTests.java | @@ -1,5 +1,5 @@
/*
- * Copyright 2002-2011 the original author or authors.
+ * Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,10 +16,19 @@
package org.springframework.http.client;
+import org.junit.Test;
+import org.springframework.http.HttpMethod;
+
public class HttpComponentsClientHttpRequestFactoryTests extends AbstractHttpRequestFactoryTestCase {
@Override
protected ClientHttpRequestFactory createRequestFactory() {
return new HttpComponentsClientHttpRequestFactory();
}
+
+ @Test
+ public void httpMethods() throws Exception {
+ assertHttpMethod("patch", HttpMethod.PATCH);
+ }
+
} | true |
Other | spring-projects | spring-framework | a0747458e7e23bf53620caf26f5bb3e2b17bf963.json | Add support for HTTP PATCH method
The HTTP PATCH method is now supported whereever HTTP methods are used.
Annotated controllers can be mapped to RequestMethod.PATCH.
On the client side the RestTemplate execute(..) and exchange(..)
methods can be used with HttpMethod.PATCH. In terms of HTTP client
libraries, Apache HttpComponents HttpClient version 4.2 or later is
required (see HTTPCLIENT-1191). The JDK HttpURLConnection does not
support the HTTP PATCH method.
Issue: SPR-7985 | spring-web/src/test/java/org/springframework/web/filter/HttpPutFormContentFilterTests.java | @@ -1,5 +1,5 @@
/*
- * Copyright 2002-2011 the original author or authors.
+ * Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -29,25 +29,26 @@
import org.junit.Before;
import org.junit.Test;
+import org.springframework.http.HttpMethod;
import org.springframework.mock.web.MockFilterChain;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
/**
* Test fixture for {@link HttpPutFormContentFilter}.
- *
+ *
* @author Rossen Stoyanchev
*/
public class HttpPutFormContentFilterTests {
private HttpPutFormContentFilter filter;
-
+
private MockHttpServletRequest request;
-
+
private MockHttpServletResponse response;
-
+
private MockFilterChain filterChain;
-
+
@Before
public void setup() {
filter = new HttpPutFormContentFilter();
@@ -59,14 +60,18 @@ public void setup() {
}
@Test
- public void wrapPutOnly() throws Exception {
+ public void wrapPutAndPatchOnly() throws Exception {
request.setContent("".getBytes("ISO-8859-1"));
- String[] methods = new String[] {"GET", "POST", "DELETE", "HEAD", "OPTIONS", "TRACE"};
- for (String method : methods) {
- request.setMethod(method);
+ for (HttpMethod method : HttpMethod.values()) {
+ request.setMethod(method.name());
filterChain = new MockFilterChain();
filter.doFilter(request, response, filterChain);
- assertSame("Should not wrap for HTTP method " + method, request, filterChain.getRequest());
+ if (method.equals(HttpMethod.PUT) || method.equals(HttpMethod.PATCH)) {
+ assertNotSame("Should wrap HTTP method " + method, request, filterChain.getRequest());
+ }
+ else {
+ assertSame("Should not wrap for HTTP method " + method, request, filterChain.getRequest());
+ }
}
}
@@ -81,31 +86,31 @@ public void wrapFormEncodedOnly() throws Exception {
assertSame("Should not wrap for content type " + contentType, request, filterChain.getRequest());
}
}
-
+
@Test
public void getParameter() throws Exception {
request.setContent("name=value".getBytes("ISO-8859-1"));
filter.doFilter(request, response, filterChain);
-
+
assertEquals("value", filterChain.getRequest().getParameter("name"));
}
-
+
@Test
public void getParameterFromQueryString() throws Exception {
request.addParameter("name", "value1");
request.setContent("name=value2".getBytes("ISO-8859-1"));
filter.doFilter(request, response, filterChain);
-
+
assertNotSame("Request not wrapped", request, filterChain.getRequest());
- assertEquals("Query string parameters should be listed ahead of form parameters",
+ assertEquals("Query string parameters should be listed ahead of form parameters",
"value1", filterChain.getRequest().getParameter("name"));
}
-
+
@Test
public void getParameterNullValue() throws Exception {
request.setContent("name=value".getBytes("ISO-8859-1"));
filter.doFilter(request, response, filterChain);
-
+
assertNotSame("Request not wrapped", request, filterChain.getRequest());
assertNull(filterChain.getRequest().getParameter("noSuchParam"));
}
@@ -115,27 +120,27 @@ public void getParameterNames() throws Exception {
request.addParameter("name1", "value1");
request.addParameter("name2", "value2");
request.setContent("name1=value1&name3=value3&name4=value4".getBytes("ISO-8859-1"));
-
+
filter.doFilter(request, response, filterChain);
List<String> names = Collections.list(filterChain.getRequest().getParameterNames());
assertNotSame("Request not wrapped", request, filterChain.getRequest());
assertEquals(Arrays.asList("name1", "name2", "name3", "name4"), names);
}
-
+
@Test
public void getParameterValues() throws Exception {
request.addParameter("name", "value1");
request.addParameter("name", "value2");
request.setContent("name=value3&name=value4".getBytes("ISO-8859-1"));
-
+
filter.doFilter(request, response, filterChain);
String[] values = filterChain.getRequest().getParameterValues("name");
assertNotSame("Request not wrapped", request, filterChain.getRequest());
assertArrayEquals(new String[]{"value1", "value2", "value3", "value4"}, values);
}
-
+
@Test
public void getParameterValuesFromQueryString() throws Exception {
request.addParameter("name", "value1");
@@ -148,33 +153,33 @@ public void getParameterValuesFromQueryString() throws Exception {
assertNotSame("Request not wrapped", request, filterChain.getRequest());
assertArrayEquals(new String[]{"value1", "value2"}, values);
}
-
+
@Test
public void getParameterValuesFromFormContent() throws Exception {
request.addParameter("name", "value1");
request.addParameter("name", "value2");
request.setContent("anotherName=anotherValue".getBytes("ISO-8859-1"));
-
+
filter.doFilter(request, response, filterChain);
String[] values = filterChain.getRequest().getParameterValues("anotherName");
assertNotSame("Request not wrapped", request, filterChain.getRequest());
assertArrayEquals(new String[]{"anotherValue"}, values);
}
-
+
@Test
public void getParameterValuesInvalidName() throws Exception {
request.addParameter("name", "value1");
request.addParameter("name", "value2");
request.setContent("anotherName=anotherValue".getBytes("ISO-8859-1"));
-
+
filter.doFilter(request, response, filterChain);
String[] values = filterChain.getRequest().getParameterValues("noSuchParameter");
assertNotSame("Request not wrapped", request, filterChain.getRequest());
assertNull(values);
}
-
+
@Test
public void getParameterMap() throws Exception {
request.addParameter("name", "value1");
@@ -189,5 +194,5 @@ public void getParameterMap() throws Exception {
assertArrayEquals(new String[] {"value1", "value2", "value3"}, parameters.get("name"));
assertArrayEquals(new String[] {"value4"}, parameters.get("name4"));
}
-
+
} | true |
Other | spring-projects | spring-framework | a0747458e7e23bf53620caf26f5bb3e2b17bf963.json | Add support for HTTP PATCH method
The HTTP PATCH method is now supported whereever HTTP methods are used.
Annotated controllers can be mapped to RequestMethod.PATCH.
On the client side the RestTemplate execute(..) and exchange(..)
methods can be used with HttpMethod.PATCH. In terms of HTTP client
libraries, Apache HttpComponents HttpClient version 4.2 or later is
required (see HTTPCLIENT-1191). The JDK HttpURLConnection does not
support the HTTP PATCH method.
Issue: SPR-7985 | spring-webmvc/src/main/java/org/springframework/web/servlet/FrameworkServlet.java | @@ -41,6 +41,7 @@
import org.springframework.util.ClassUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
+import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.ConfigurableWebApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.request.RequestAttributes;
@@ -767,6 +768,25 @@ protected void onRefresh(ApplicationContext context) {
}
+ /**
+ * Override the parent class implementation in order to intercept PATCH
+ * requests.
+ *
+ * @see #doPatch(HttpServletRequest, HttpServletResponse)
+ */
+ @Override
+ protected void service(HttpServletRequest request, HttpServletResponse response)
+ throws ServletException, IOException {
+
+ String method = request.getMethod();
+ if (method.equalsIgnoreCase(RequestMethod.PATCH.name())) {
+ doPatch(request, response);
+ }
+ else {
+ super.service(request, response);
+ }
+ }
+
/**
* Delegate GET requests to processRequest/doService.
* <p>Will also be invoked by HttpServlet's default implementation of <code>doHead</code>,
@@ -803,6 +823,16 @@ protected final void doPut(HttpServletRequest request, HttpServletResponse respo
processRequest(request, response);
}
+ /**
+ * Delegate PATCH requests to {@link #processRequest}.
+ * @see #doService
+ */
+ protected final void doPatch(HttpServletRequest request, HttpServletResponse response)
+ throws ServletException, IOException {
+
+ processRequest(request, response);
+ }
+
/**
* Delegate DELETE requests to {@link #processRequest}.
* @see #doService | true |
Other | spring-projects | spring-framework | a0747458e7e23bf53620caf26f5bb3e2b17bf963.json | Add support for HTTP PATCH method
The HTTP PATCH method is now supported whereever HTTP methods are used.
Annotated controllers can be mapped to RequestMethod.PATCH.
On the client side the RestTemplate execute(..) and exchange(..)
methods can be used with HttpMethod.PATCH. In terms of HTTP client
libraries, Apache HttpComponents HttpClient version 4.2 or later is
required (see HTTPCLIENT-1191). The JDK HttpURLConnection does not
support the HTTP PATCH method.
Issue: SPR-7985 | spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ServletAnnotationControllerHandlerMethodTests.java | @@ -1,5 +1,5 @@
/*
- * Copyright 2002-2011 the original author or authors.
+ * Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -144,20 +144,20 @@
/**
* The origin of this test class is {@link ServletAnnotationControllerHandlerMethodTests}.
- *
+ *
* Tests in this class run against the {@link HandlerMethod} infrastructure:
* <ul>
- * <li>RequestMappingHandlerMapping
- * <li>RequestMappingHandlerAdapter
+ * <li>RequestMappingHandlerMapping
+ * <li>RequestMappingHandlerAdapter
* <li>ExceptionHandlerExceptionResolver
* </ul>
- *
+ *
* <p>Rather than against the existing infrastructure:
* <ul>
* <li>DefaultAnnotationHandlerMapping
* <li>AnnotationMethodHandlerAdapter
* <li>AnnotationMethodHandlerExceptionResolver
- * </ul>
+ * </ul>
*
* @author Rossen Stoyanchev
*/
@@ -249,7 +249,7 @@ public void initialize(GenericWebApplicationContext context) {
context.registerBeanDefinition("ppc", ppc);
}
}, DefaultExpressionValueParamController.class);
-
+
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myApp/myPath.do");
request.setContextPath("/myApp");
MockHttpServletResponse response = new MockHttpServletResponse();
@@ -656,7 +656,7 @@ public void parameterDispatchingController() throws Exception {
final MockServletContext servletContext = new MockServletContext();
final MockServletConfig servletConfig = new MockServletConfig(servletContext);
- WebApplicationContext webAppContext =
+ WebApplicationContext webAppContext =
initServlet(new ApplicationContextInitializer<GenericWebApplicationContext>() {
public void initialize(GenericWebApplicationContext wac) {
wac.setServletContext(servletContext);
@@ -705,7 +705,7 @@ public void initialize(GenericWebApplicationContext wac) {
getServlet().service(request, response);
assertEquals("mySurpriseView", response.getContentAsString());
- MyParameterDispatchingController deserialized =
+ MyParameterDispatchingController deserialized =
(MyParameterDispatchingController) SerializationTestUtils.serializeAndDeserialize(
webAppContext.getBean(MyParameterDispatchingController.class.getSimpleName()));
assertNotNull(deserialized.request);
@@ -813,6 +813,21 @@ public void requestBodyResponseBody() throws ServletException, IOException {
assertEquals(requestBody, response.getContentAsString());
}
+ @Test
+ public void httpPatch() throws ServletException, IOException {
+ initServletWithControllers(RequestResponseBodyController.class);
+
+ MockHttpServletRequest request = new MockHttpServletRequest("PATCH", "/something");
+ String requestBody = "Hello world!";
+ request.setContent(requestBody.getBytes("UTF-8"));
+ request.addHeader("Content-Type", "text/plain; charset=utf-8");
+ request.addHeader("Accept", "text/*, */*");
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ getServlet().service(request, response);
+ assertEquals(200, response.getStatus());
+ assertEquals(requestBody, response.getContentAsString());
+ }
+
@Test
public void responseBodyNoAcceptableMediaType() throws ServletException, IOException {
initServlet(new ApplicationContextInitializer<GenericWebApplicationContext>() {
@@ -1248,7 +1263,7 @@ public void requestHeaderMap() throws Exception {
assertEquals("Content-Type=[text/html],Custom-Header=[value21,value22]", response.getContentAsString());
}
-
+
@Test
public void requestMappingInterface() throws Exception {
initServletWithControllers(IMyControllerImpl.class);
@@ -1298,7 +1313,7 @@ public void requestMappingBaseClass() throws Exception {
assertEquals("handle", response.getContentAsString());
}
-
+
@Test
public void trailingSlash() throws Exception {
initServletWithControllers(TrailingSlashController.class);
@@ -1444,7 +1459,7 @@ public void testHeadersCondition() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
MockHttpServletResponse response = new MockHttpServletResponse();
getServlet().service(request, response);
-
+
assertEquals(200, response.getStatus());
assertEquals("home", response.getForwardedUrl());
@@ -1462,11 +1477,11 @@ public void testHeadersCondition() throws Exception {
request.addHeader("Accept", "application/json");
response = new MockHttpServletResponse();
getServlet().service(request, response);
-
+
assertEquals(200, response.getStatus());
assertEquals("application/json", response.getHeader("Content-Type"));
assertEquals("homeJson", response.getContentAsString());
- }
+ }
@Test
public void redirectAttribute() throws Exception {
@@ -1479,7 +1494,7 @@ public void redirectAttribute() throws Exception {
// POST -> bind error
getServlet().service(request, response);
-
+
assertEquals(200, response.getStatus());
assertEquals("messages/new", response.getForwardedUrl());
assertTrue(RequestContextUtils.getOutputFlashMap(request).isEmpty());
@@ -1516,20 +1531,20 @@ public void initialize(GenericWebApplicationContext context) {
context.registerBeanDefinition("controller", beanDef);
}
});
-
+
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
request.addParameter("param", "1");
MockHttpServletResponse response = new MockHttpServletResponse();
getServlet().service(request, response);
-
+
assertEquals("count:3", response.getContentAsString());
response = new MockHttpServletResponse();
getServlet().service(request, response);
-
+
assertEquals("count:3", response.getContentAsString());
}
-
+
/*
* Controllers
*/
@@ -2335,6 +2350,12 @@ public static class RequestResponseBodyController {
public String handle(@RequestBody String body) throws IOException {
return body;
}
+
+ @RequestMapping(value = "/something", method = RequestMethod.PATCH)
+ @ResponseBody
+ public String handlePartialUpdate(@RequestBody String content) throws IOException {
+ return content;
+ }
}
@Controller
@@ -2366,7 +2387,7 @@ public void handle(@RequestBody A a) throws IOException {
@XmlRootElement
public static class A {
-
+
}
@XmlRootElement
@@ -2729,7 +2750,7 @@ public static class TrailingSlashController {
public void root(Writer writer) throws IOException {
writer.write("root");
}
-
+
@RequestMapping(value = "/{templatePath}/", method = RequestMethod.GET)
public void templatePath(Writer writer) throws IOException {
writer.write("templatePath");
@@ -2839,7 +2860,7 @@ public void handle2(Writer writer) throws IOException {
@Controller
static class HeadersConditionController {
-
+
@RequestMapping(value = "/", method = RequestMethod.GET)
public String home() {
return "home";
@@ -2887,7 +2908,7 @@ static class PrototypeController {
public void initBinder(WebDataBinder dataBinder) {
this.count++;
}
-
+
@ModelAttribute
public void populate(Model model) {
this.count++;
@@ -2899,16 +2920,16 @@ public void message(int param, Writer writer) throws IOException {
writer.write("count:" + this.count);
}
}
-
+
// Test cases deleted from the original SevletAnnotationControllerTests:
-
-// @Ignore("Controller interface => no method-level @RequestMapping annotation")
+
+// @Ignore("Controller interface => no method-level @RequestMapping annotation")
// public void standardHandleMethod() throws Exception {
-
+
// @Ignore("ControllerClassNameHandlerMapping")
// public void emptyRequestMapping() throws Exception {
-// @Ignore("Controller interface => no method-level @RequestMapping annotation")
+// @Ignore("Controller interface => no method-level @RequestMapping annotation")
// public void proxiedStandardHandleMethod() throws Exception {
// @Ignore("ServletException no longer thrown for unmatched parameter constraints")
@@ -2919,10 +2940,10 @@ public void message(int param, Writer writer) throws IOException {
// @Ignore("Method name dispatching")
// public void methodNameDispatchingControllerWithSuffix() throws Exception {
-
+
// @Ignore("ControllerClassNameHandlerMapping")
// public void controllerClassNamePlusMethodNameDispatchingController() throws Exception {
-
+
// @Ignore("Method name dispatching")
// public void postMethodNameDispatchingController() throws Exception {
| true |
Other | spring-projects | spring-framework | a0747458e7e23bf53620caf26f5bb3e2b17bf963.json | Add support for HTTP PATCH method
The HTTP PATCH method is now supported whereever HTTP methods are used.
Annotated controllers can be mapped to RequestMethod.PATCH.
On the client side the RestTemplate execute(..) and exchange(..)
methods can be used with HttpMethod.PATCH. In terms of HTTP client
libraries, Apache HttpComponents HttpClient version 4.2 or later is
required (see HTTPCLIENT-1191). The JDK HttpURLConnection does not
support the HTTP PATCH method.
Issue: SPR-7985 | src/dist/changelog.txt | @@ -11,6 +11,7 @@ Changes in version 3.2 M2
* add JacksonObjectMapperFactoryBean for configuring a Jackson ObjectMapper in XML
* infer return type of parameterized factory methods (SPR-9493)
* add ContentNegotiationManager/ContentNegotiationStrategy to resolve requested media types
+* add support for the HTTP PATCH method
Changes in version 3.2 M1 (2012-05-28)
-------------------------------------- | true |
Other | spring-projects | spring-framework | a0747458e7e23bf53620caf26f5bb3e2b17bf963.json | Add support for HTTP PATCH method
The HTTP PATCH method is now supported whereever HTTP methods are used.
Annotated controllers can be mapped to RequestMethod.PATCH.
On the client side the RestTemplate execute(..) and exchange(..)
methods can be used with HttpMethod.PATCH. In terms of HTTP client
libraries, Apache HttpComponents HttpClient version 4.2 or later is
required (see HTTPCLIENT-1191). The JDK HttpURLConnection does not
support the HTTP PATCH method.
Issue: SPR-7985 | src/reference/docbook/mvc.xml | @@ -1975,7 +1975,7 @@ public class EditPetForm {
<literal>ServletRequest.getParameter*()</literal> family of methods to
support form field access only for HTTP POST, not for HTTP PUT.</para>
- <para>To support HTTP PUT requests, the <literal>spring-web</literal>
+ <para>To support HTTP PUT and PATCH requests, the <literal>spring-web</literal>
module provides the filter
<classname>HttpPutFormContentFilter</classname>, which can be
configured in <filename>web.xml</filename>:</para>
@@ -1995,7 +1995,7 @@ public class EditPetForm {
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet></programlisting>
- <para>The above filter intercepts HTTP PUT requests with content type
+ <para>The above filter intercepts HTTP PUT and PATCH requests with content type
<literal>application/x-www-form-urlencoded</literal>, reads the form
data from the body of the request, and wraps the
<classname>ServletRequest</classname> in order to make the form data | true |
Other | spring-projects | spring-framework | f05e2bc56f8e03466977d73a5e99c37651248803.json | Add abstractions for content negotiation
Introduced ContentNeogtiationStrategy for resolving the requested
media types from an incoming request. The available implementations
are based on path extension, request parameter, 'Accept' header,
and a fixed default content type. The logic for these implementations
is based on equivalent options, previously available only in the
ContentNegotiatingViewResolver.
Also in this commit is ContentNegotiationManager, the central class to
use when configuring content negotiation options. It accepts one or
more ContentNeogtiationStrategy instances and delegates to them.
The ContentNeogiationManager can now be used to configure the
following classes:
- RequestMappingHandlerMappingm
- RequestMappingHandlerAdapter
- ExceptionHandlerExceptionResolver
- ContentNegotiatingViewResolver
Issue: SPR-8410, SPR-8417, SPR-8418,SPR-8416, SPR-8419,SPR-7722 | build.gradle | @@ -368,6 +368,7 @@ project('spring-web') {
optional dep
exclude group: 'org.mortbay.jetty', module: 'servlet-api-2.5'
}
+ testCompile project(":spring-context-support") // for JafMediaTypeFactory
testCompile "xmlunit:xmlunit:1.2"
}
| true |
Other | spring-projects | spring-framework | f05e2bc56f8e03466977d73a5e99c37651248803.json | Add abstractions for content negotiation
Introduced ContentNeogtiationStrategy for resolving the requested
media types from an incoming request. The available implementations
are based on path extension, request parameter, 'Accept' header,
and a fixed default content type. The logic for these implementations
is based on equivalent options, previously available only in the
ContentNegotiatingViewResolver.
Also in this commit is ContentNegotiationManager, the central class to
use when configuring content negotiation options. It accepts one or
more ContentNeogtiationStrategy instances and delegates to them.
The ContentNeogiationManager can now be used to configure the
following classes:
- RequestMappingHandlerMappingm
- RequestMappingHandlerAdapter
- ExceptionHandlerExceptionResolver
- ContentNegotiatingViewResolver
Issue: SPR-8410, SPR-8417, SPR-8418,SPR-8416, SPR-8419,SPR-7722 | spring-web/src/main/java/org/springframework/web/accept/AbstractMappingContentNegotiationStrategy.java | @@ -0,0 +1,82 @@
+/*
+ * Copyright 2002-2012 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.springframework.web.accept;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+
+import org.springframework.http.MediaType;
+import org.springframework.util.StringUtils;
+import org.springframework.web.context.request.NativeWebRequest;
+
+/**
+ * A base class for ContentNegotiationStrategy types that maintain a map with keys
+ * such as "json" and media types such as "application/json".
+ *
+ * @author Rossen Stoyanchev
+ * @since 3.2
+ */
+public abstract class AbstractMappingContentNegotiationStrategy extends MappingMediaTypeExtensionsResolver
+ implements ContentNegotiationStrategy, MediaTypeExtensionsResolver {
+
+ /**
+ * Create an instance with the given extension-to-MediaType lookup.
+ * @throws IllegalArgumentException if a media type string cannot be parsed
+ */
+ public AbstractMappingContentNegotiationStrategy(Map<String, String> mediaTypes) {
+ super(mediaTypes);
+ }
+
+ public List<MediaType> resolveMediaTypes(NativeWebRequest webRequest) {
+ String key = getMediaTypeKey(webRequest);
+ if (StringUtils.hasText(key)) {
+ MediaType mediaType = lookupMediaType(key);
+ if (mediaType != null) {
+ handleMatch(key, mediaType);
+ return Collections.singletonList(mediaType);
+ }
+ mediaType = handleNoMatch(webRequest, key);
+ if (mediaType != null) {
+ addMapping(key, mediaType);
+ return Collections.singletonList(mediaType);
+ }
+ }
+ return Collections.emptyList();
+ }
+
+ /**
+ * Sub-classes must extract the key to use to look up a media type.
+ * @return the lookup key or {@code null} if the key cannot be derived
+ */
+ protected abstract String getMediaTypeKey(NativeWebRequest request);
+
+ /**
+ * Invoked when a matching media type is found in the lookup map.
+ */
+ protected void handleMatch(String mappingKey, MediaType mediaType) {
+ }
+
+ /**
+ * Invoked when no matching media type is found in the lookup map.
+ * Sub-classes can take further steps to determine the media type.
+ */
+ protected MediaType handleNoMatch(NativeWebRequest request, String mappingKey) {
+ return null;
+ }
+
+}
\ No newline at end of file | true |
Other | spring-projects | spring-framework | f05e2bc56f8e03466977d73a5e99c37651248803.json | Add abstractions for content negotiation
Introduced ContentNeogtiationStrategy for resolving the requested
media types from an incoming request. The available implementations
are based on path extension, request parameter, 'Accept' header,
and a fixed default content type. The logic for these implementations
is based on equivalent options, previously available only in the
ContentNegotiatingViewResolver.
Also in this commit is ContentNegotiationManager, the central class to
use when configuring content negotiation options. It accepts one or
more ContentNeogtiationStrategy instances and delegates to them.
The ContentNeogiationManager can now be used to configure the
following classes:
- RequestMappingHandlerMappingm
- RequestMappingHandlerAdapter
- ExceptionHandlerExceptionResolver
- ContentNegotiatingViewResolver
Issue: SPR-8410, SPR-8417, SPR-8418,SPR-8416, SPR-8419,SPR-7722 | spring-web/src/main/java/org/springframework/web/accept/ContentNegotiationManager.java | @@ -0,0 +1,105 @@
+/*
+ * Copyright 2002-2012 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.springframework.web.accept;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Set;
+
+import org.springframework.http.MediaType;
+import org.springframework.util.Assert;
+import org.springframework.web.HttpMediaTypeNotAcceptableException;
+import org.springframework.web.context.request.NativeWebRequest;
+
+/**
+ * This class is used to determine the requested {@linkplain MediaType media types}
+ * in a request by delegating to a list of {@link ContentNegotiationStrategy} instances.
+ *
+ * <p>It may also be used to determine the extensions associated with a MediaType by
+ * delegating to a list of {@link MediaTypeExtensionsResolver} instances.
+ *
+ * @author Rossen Stoyanchev
+ * @since 3.2
+ */
+public class ContentNegotiationManager implements ContentNegotiationStrategy, MediaTypeExtensionsResolver {
+
+ private final List<ContentNegotiationStrategy> contentNegotiationStrategies = new ArrayList<ContentNegotiationStrategy>();
+
+ private final Set<MediaTypeExtensionsResolver> extensionResolvers = new LinkedHashSet<MediaTypeExtensionsResolver>();
+
+ /**
+ * Create an instance with the given ContentNegotiationStrategy instances.
+ * <p>Each instance is checked to see if it is also an implementation of
+ * MediaTypeExtensionsResolver, and if so it is registered as such.
+ */
+ public ContentNegotiationManager(ContentNegotiationStrategy... strategies) {
+ Assert.notEmpty(strategies, "At least one ContentNegotiationStrategy is expected");
+ this.contentNegotiationStrategies.addAll(Arrays.asList(strategies));
+ for (ContentNegotiationStrategy strategy : this.contentNegotiationStrategies) {
+ if (strategy instanceof MediaTypeExtensionsResolver) {
+ this.extensionResolvers.add((MediaTypeExtensionsResolver) strategy);
+ }
+ }
+ }
+
+ /**
+ * Create an instance with a {@link HeaderContentNegotiationStrategy}.
+ */
+ public ContentNegotiationManager() {
+ this(new HeaderContentNegotiationStrategy());
+ }
+
+ /**
+ * Add MediaTypeExtensionsResolver instances.
+ */
+ public void addExtensionsResolver(MediaTypeExtensionsResolver... resolvers) {
+ this.extensionResolvers.addAll(Arrays.asList(resolvers));
+ }
+
+ /**
+ * Delegate to all configured ContentNegotiationStrategy instances until one
+ * returns a non-empty list.
+ * @param request the current request
+ * @return the requested media types or an empty list, never {@code null}
+ * @throws HttpMediaTypeNotAcceptableException if the requested media types cannot be parsed
+ */
+ public List<MediaType> resolveMediaTypes(NativeWebRequest webRequest) throws HttpMediaTypeNotAcceptableException {
+ for (ContentNegotiationStrategy strategy : this.contentNegotiationStrategies) {
+ List<MediaType> mediaTypes = strategy.resolveMediaTypes(webRequest);
+ if (!mediaTypes.isEmpty()) {
+ return mediaTypes;
+ }
+ }
+ return Collections.emptyList();
+ }
+
+ /**
+ * Delegate to all configured MediaTypeExtensionsResolver instances and aggregate
+ * the list of all extensions found.
+ */
+ public List<String> resolveExtensions(MediaType mediaType) {
+ Set<String> extensions = new LinkedHashSet<String>();
+ for (MediaTypeExtensionsResolver resolver : this.extensionResolvers) {
+ extensions.addAll(resolver.resolveExtensions(mediaType));
+ }
+ return new ArrayList<String>(extensions);
+ }
+
+} | true |
Other | spring-projects | spring-framework | f05e2bc56f8e03466977d73a5e99c37651248803.json | Add abstractions for content negotiation
Introduced ContentNeogtiationStrategy for resolving the requested
media types from an incoming request. The available implementations
are based on path extension, request parameter, 'Accept' header,
and a fixed default content type. The logic for these implementations
is based on equivalent options, previously available only in the
ContentNegotiatingViewResolver.
Also in this commit is ContentNegotiationManager, the central class to
use when configuring content negotiation options. It accepts one or
more ContentNeogtiationStrategy instances and delegates to them.
The ContentNeogiationManager can now be used to configure the
following classes:
- RequestMappingHandlerMappingm
- RequestMappingHandlerAdapter
- ExceptionHandlerExceptionResolver
- ContentNegotiatingViewResolver
Issue: SPR-8410, SPR-8417, SPR-8418,SPR-8416, SPR-8419,SPR-7722 | spring-web/src/main/java/org/springframework/web/accept/ContentNegotiationStrategy.java | @@ -0,0 +1,44 @@
+/*
+ * Copyright 2002-2012 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.springframework.web.accept;
+
+import java.util.List;
+
+import org.springframework.http.MediaType;
+import org.springframework.web.HttpMediaTypeNotAcceptableException;
+import org.springframework.web.context.request.NativeWebRequest;
+
+/**
+ * A strategy for resolving the requested media types in a request.
+ *
+ * @author Rossen Stoyanchev
+ * @since 3.2
+ */
+public interface ContentNegotiationStrategy {
+
+ /**
+ * Resolve the given request to a list of media types. The returned list is
+ * ordered by specificity first and by quality parameter second.
+ *
+ * @param request the current request
+ * @return the requested media types or an empty list, never {@code null}
+ *
+ * @throws HttpMediaTypeNotAcceptableException if the requested media types cannot be parsed
+ */
+ List<MediaType> resolveMediaTypes(NativeWebRequest webRequest) throws HttpMediaTypeNotAcceptableException;
+
+} | true |
Other | spring-projects | spring-framework | f05e2bc56f8e03466977d73a5e99c37651248803.json | Add abstractions for content negotiation
Introduced ContentNeogtiationStrategy for resolving the requested
media types from an incoming request. The available implementations
are based on path extension, request parameter, 'Accept' header,
and a fixed default content type. The logic for these implementations
is based on equivalent options, previously available only in the
ContentNegotiatingViewResolver.
Also in this commit is ContentNegotiationManager, the central class to
use when configuring content negotiation options. It accepts one or
more ContentNeogtiationStrategy instances and delegates to them.
The ContentNeogiationManager can now be used to configure the
following classes:
- RequestMappingHandlerMappingm
- RequestMappingHandlerAdapter
- ExceptionHandlerExceptionResolver
- ContentNegotiatingViewResolver
Issue: SPR-8410, SPR-8417, SPR-8418,SPR-8416, SPR-8419,SPR-7722 | spring-web/src/main/java/org/springframework/web/accept/FixedContentNegotiationStrategy.java | @@ -0,0 +1,53 @@
+/*
+ * Copyright 2002-2012 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.springframework.web.accept;
+
+import java.util.Collections;
+import java.util.List;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.springframework.http.MediaType;
+import org.springframework.web.context.request.NativeWebRequest;
+
+/**
+ * A ContentNegotiationStrategy that returns a fixed content type.
+ *
+ * @author Rossen Stoyanchev
+ * @since 3.2
+ */
+public class FixedContentNegotiationStrategy implements ContentNegotiationStrategy {
+
+ private static final Log logger = LogFactory.getLog(FixedContentNegotiationStrategy.class);
+
+ private final MediaType defaultContentType;
+
+ /**
+ * Create an instance that always returns the given content type.
+ */
+ public FixedContentNegotiationStrategy(MediaType defaultContentType) {
+ this.defaultContentType = defaultContentType;
+ }
+
+ public List<MediaType> resolveMediaTypes(NativeWebRequest webRequest) {
+ if (logger.isDebugEnabled()) {
+ logger.debug("Requested media types is " + this.defaultContentType + " (based on default MediaType)");
+ }
+ return Collections.singletonList(this.defaultContentType);
+ }
+
+} | true |
Other | spring-projects | spring-framework | f05e2bc56f8e03466977d73a5e99c37651248803.json | Add abstractions for content negotiation
Introduced ContentNeogtiationStrategy for resolving the requested
media types from an incoming request. The available implementations
are based on path extension, request parameter, 'Accept' header,
and a fixed default content type. The logic for these implementations
is based on equivalent options, previously available only in the
ContentNegotiatingViewResolver.
Also in this commit is ContentNegotiationManager, the central class to
use when configuring content negotiation options. It accepts one or
more ContentNeogtiationStrategy instances and delegates to them.
The ContentNeogiationManager can now be used to configure the
following classes:
- RequestMappingHandlerMappingm
- RequestMappingHandlerAdapter
- ExceptionHandlerExceptionResolver
- ContentNegotiatingViewResolver
Issue: SPR-8410, SPR-8417, SPR-8418,SPR-8416, SPR-8419,SPR-7722 | spring-web/src/main/java/org/springframework/web/accept/HeaderContentNegotiationStrategy.java | @@ -0,0 +1,57 @@
+/*
+ * Copyright 2002-2012 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.springframework.web.accept;
+
+import java.util.Collections;
+import java.util.List;
+
+import org.springframework.http.MediaType;
+import org.springframework.util.StringUtils;
+import org.springframework.web.HttpMediaTypeNotAcceptableException;
+import org.springframework.web.context.request.NativeWebRequest;
+
+/**
+ * A ContentNegotiationStrategy that parses the 'Accept' header of the request.
+ *
+ * @author Rossen Stoyanchev
+ * @since 3.2
+ */
+public class HeaderContentNegotiationStrategy implements ContentNegotiationStrategy {
+
+ private static final String ACCEPT_HEADER = "Accept";
+
+ /**
+ * {@inheritDoc}
+ * @throws HttpMediaTypeNotAcceptableException if the 'Accept' header cannot be parsed.
+ */
+ public List<MediaType> resolveMediaTypes(NativeWebRequest webRequest) throws HttpMediaTypeNotAcceptableException {
+ String acceptHeader = webRequest.getHeader(ACCEPT_HEADER);
+ try {
+ if (StringUtils.hasText(acceptHeader)) {
+ List<MediaType> mediaTypes = MediaType.parseMediaTypes(acceptHeader);
+ MediaType.sortBySpecificityAndQuality(mediaTypes);
+ return mediaTypes;
+ }
+ }
+ catch (IllegalArgumentException ex) {
+ throw new HttpMediaTypeNotAcceptableException(
+ "Could not parse accept header [" + acceptHeader + "]: " + ex.getMessage());
+ }
+ return Collections.emptyList();
+ }
+
+} | true |
Other | spring-projects | spring-framework | f05e2bc56f8e03466977d73a5e99c37651248803.json | Add abstractions for content negotiation
Introduced ContentNeogtiationStrategy for resolving the requested
media types from an incoming request. The available implementations
are based on path extension, request parameter, 'Accept' header,
and a fixed default content type. The logic for these implementations
is based on equivalent options, previously available only in the
ContentNegotiatingViewResolver.
Also in this commit is ContentNegotiationManager, the central class to
use when configuring content negotiation options. It accepts one or
more ContentNeogtiationStrategy instances and delegates to them.
The ContentNeogiationManager can now be used to configure the
following classes:
- RequestMappingHandlerMappingm
- RequestMappingHandlerAdapter
- ExceptionHandlerExceptionResolver
- ContentNegotiatingViewResolver
Issue: SPR-8410, SPR-8417, SPR-8418,SPR-8416, SPR-8419,SPR-7722 | spring-web/src/main/java/org/springframework/web/accept/MappingMediaTypeExtensionsResolver.java | @@ -0,0 +1,82 @@
+/*
+ * Copyright 2002-2012 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.springframework.web.accept;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+
+import org.springframework.http.MediaType;
+
+/**
+ * An implementation of {@link MediaTypeExtensionsResolver} that maintains a lookup
+ * from extension to MediaType.
+ *
+ * @author Rossen Stoyanchev
+ * @since 3.2
+ */
+public class MappingMediaTypeExtensionsResolver implements MediaTypeExtensionsResolver {
+
+ private ConcurrentMap<String, MediaType> mediaTypes = new ConcurrentHashMap<String, MediaType>();
+
+ /**
+ * Create an instance with the given mappings between extensions and media types.
+ * @throws IllegalArgumentException if a media type string cannot be parsed
+ */
+ public MappingMediaTypeExtensionsResolver(Map<String, String> mediaTypes) {
+ if (mediaTypes != null) {
+ for (Map.Entry<String, String> entry : mediaTypes.entrySet()) {
+ String extension = entry.getKey().toLowerCase(Locale.ENGLISH);
+ MediaType mediaType = MediaType.parseMediaType(entry.getValue());
+ this.mediaTypes.put(extension, mediaType);
+ }
+ }
+ }
+
+ /**
+ * Find the extensions applicable to the given MediaType.
+ * @return 0 or more extensions, never {@code null}
+ */
+ public List<String> resolveExtensions(MediaType mediaType) {
+ List<String> result = new ArrayList<String>();
+ for (Entry<String, MediaType> entry : this.mediaTypes.entrySet()) {
+ if (mediaType.includes(entry.getValue())) {
+ result.add(entry.getKey());
+ }
+ }
+ return result;
+ }
+
+ /**
+ * Return the MediaType mapped to the given extension.
+ * @return a MediaType for the key or {@code null}
+ */
+ public MediaType lookupMediaType(String extension) {
+ return this.mediaTypes.get(extension);
+ }
+
+ /**
+ * Map a MediaType to an extension or ignore if the extensions is already mapped.
+ */
+ protected void addMapping(String extension, MediaType mediaType) {
+ this.mediaTypes.putIfAbsent(extension, mediaType);
+ }
+
+}
\ No newline at end of file | true |
Other | spring-projects | spring-framework | f05e2bc56f8e03466977d73a5e99c37651248803.json | Add abstractions for content negotiation
Introduced ContentNeogtiationStrategy for resolving the requested
media types from an incoming request. The available implementations
are based on path extension, request parameter, 'Accept' header,
and a fixed default content type. The logic for these implementations
is based on equivalent options, previously available only in the
ContentNegotiatingViewResolver.
Also in this commit is ContentNegotiationManager, the central class to
use when configuring content negotiation options. It accepts one or
more ContentNeogtiationStrategy instances and delegates to them.
The ContentNeogiationManager can now be used to configure the
following classes:
- RequestMappingHandlerMappingm
- RequestMappingHandlerAdapter
- ExceptionHandlerExceptionResolver
- ContentNegotiatingViewResolver
Issue: SPR-8410, SPR-8417, SPR-8418,SPR-8416, SPR-8419,SPR-7722 | spring-web/src/main/java/org/springframework/web/accept/MediaTypeExtensionsResolver.java | @@ -0,0 +1,40 @@
+/*
+ * Copyright 2002-2012 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.springframework.web.accept;
+
+import java.util.List;
+
+import org.springframework.http.MediaType;
+
+/**
+ * A strategy for resolving a {@link MediaType} to one or more path extensions.
+ * For example "application/json" to "json".
+ *
+ * @author Rossen Stoyanchev
+ * @since 3.2
+ */
+public interface MediaTypeExtensionsResolver {
+
+ /**
+ * Resolve the given media type to a list of path extensions.
+ *
+ * @param mediaType the media type to resolve
+ * @return a list of extensions or an empty list, never {@code null}
+ */
+ List<String> resolveExtensions(MediaType mediaType);
+
+} | true |
Other | spring-projects | spring-framework | f05e2bc56f8e03466977d73a5e99c37651248803.json | Add abstractions for content negotiation
Introduced ContentNeogtiationStrategy for resolving the requested
media types from an incoming request. The available implementations
are based on path extension, request parameter, 'Accept' header,
and a fixed default content type. The logic for these implementations
is based on equivalent options, previously available only in the
ContentNegotiatingViewResolver.
Also in this commit is ContentNegotiationManager, the central class to
use when configuring content negotiation options. It accepts one or
more ContentNeogtiationStrategy instances and delegates to them.
The ContentNeogiationManager can now be used to configure the
following classes:
- RequestMappingHandlerMappingm
- RequestMappingHandlerAdapter
- ExceptionHandlerExceptionResolver
- ContentNegotiatingViewResolver
Issue: SPR-8410, SPR-8417, SPR-8418,SPR-8416, SPR-8419,SPR-7722 | spring-web/src/main/java/org/springframework/web/accept/ParameterContentNegotiationStrategy.java | @@ -0,0 +1,71 @@
+/*
+ * Copyright 2002-2012 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.springframework.web.accept;
+
+import java.util.Map;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.springframework.http.MediaType;
+import org.springframework.util.Assert;
+import org.springframework.web.context.request.NativeWebRequest;
+
+/**
+ * A ContentNegotiationStrategy that uses a request parameter to determine what
+ * media types are requested. The default parameter name is {@code format}.
+ * Its value is used to look up the media type in the map given to the constructor.
+ *
+ * @author Rossen Stoyanchev
+ * @since 3.2
+ */
+public class ParameterContentNegotiationStrategy extends AbstractMappingContentNegotiationStrategy {
+
+ private static final Log logger = LogFactory.getLog(ParameterContentNegotiationStrategy.class);
+
+ private String parameterName = "format";
+
+ /**
+ * Create an instance with the given extension-to-MediaType lookup.
+ * @throws IllegalArgumentException if a media type string cannot be parsed
+ */
+ public ParameterContentNegotiationStrategy(Map<String, String> mediaTypes) {
+ super(mediaTypes);
+ Assert.notEmpty(mediaTypes, "Cannot look up media types without any mappings");
+ }
+
+ /**
+ * Set the parameter name that can be used to determine the requested media type.
+ * <p>The default parameter name is {@code format}.
+ */
+ public void setParameterName(String parameterName) {
+ this.parameterName = parameterName;
+ }
+
+ @Override
+ protected String getMediaTypeKey(NativeWebRequest webRequest) {
+ return webRequest.getParameter(this.parameterName);
+ }
+
+ @Override
+ protected void handleMatch(String mediaTypeKey, MediaType mediaType) {
+ if (logger.isDebugEnabled()) {
+ logger.debug("Requested media type is '" + mediaType + "' (based on parameter '" +
+ this.parameterName + "'='" + mediaTypeKey + "')");
+ }
+ }
+
+} | true |
Other | spring-projects | spring-framework | f05e2bc56f8e03466977d73a5e99c37651248803.json | Add abstractions for content negotiation
Introduced ContentNeogtiationStrategy for resolving the requested
media types from an incoming request. The available implementations
are based on path extension, request parameter, 'Accept' header,
and a fixed default content type. The logic for these implementations
is based on equivalent options, previously available only in the
ContentNegotiatingViewResolver.
Also in this commit is ContentNegotiationManager, the central class to
use when configuring content negotiation options. It accepts one or
more ContentNeogtiationStrategy instances and delegates to them.
The ContentNeogiationManager can now be used to configure the
following classes:
- RequestMappingHandlerMappingm
- RequestMappingHandlerAdapter
- ExceptionHandlerExceptionResolver
- ContentNegotiatingViewResolver
Issue: SPR-8410, SPR-8417, SPR-8418,SPR-8416, SPR-8419,SPR-7722 | spring-web/src/main/java/org/springframework/web/accept/PathExtensionContentNegotiationStrategy.java | @@ -0,0 +1,187 @@
+/*
+ * Copyright 2002-2012 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.springframework.web.accept;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Locale;
+import java.util.Map;
+
+import javax.activation.FileTypeMap;
+import javax.activation.MimetypesFileTypeMap;
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.springframework.core.io.ClassPathResource;
+import org.springframework.core.io.Resource;
+import org.springframework.http.MediaType;
+import org.springframework.util.ClassUtils;
+import org.springframework.util.StringUtils;
+import org.springframework.web.context.request.NativeWebRequest;
+import org.springframework.web.util.UrlPathHelper;
+import org.springframework.web.util.WebUtils;
+
+/**
+ * A ContentNegotiationStrategy that uses the path extension of the URL to determine
+ * what media types are requested. The path extension is used as follows:
+ *
+ * <ol>
+ * <li>Look upin the map of media types provided to the constructor
+ * <li>Call to {@link ServletContext#getMimeType(String)}
+ * <li>Use the Java Activation framework
+ * </ol>
+ *
+ * <p>The presence of the Java Activation framework is detected and enabled automatically
+ * but the {@link #setUseJaf(boolean)} property may be used to override that setting.
+ *
+ * @author Rossen Stoyanchev
+ * @since 3.2
+ */
+public class PathExtensionContentNegotiationStrategy extends AbstractMappingContentNegotiationStrategy {
+
+ private static final boolean JAF_PRESENT =
+ ClassUtils.isPresent("javax.activation.FileTypeMap", PathExtensionContentNegotiationStrategy.class.getClassLoader());
+
+ private static final Log logger = LogFactory.getLog(PathExtensionContentNegotiationStrategy.class);
+
+ private static final UrlPathHelper urlPathHelper = new UrlPathHelper();
+
+ static {
+ urlPathHelper.setUrlDecode(false);
+ }
+
+ private boolean useJaf = JAF_PRESENT;
+
+ /**
+ * Create an instance with the given extension-to-MediaType lookup.
+ * @throws IllegalArgumentException if a media type string cannot be parsed
+ */
+ public PathExtensionContentNegotiationStrategy(Map<String, String> mediaTypes) {
+ super(mediaTypes);
+ }
+
+ /**
+ * Create an instance without any mappings to start with. Mappings may be added
+ * later on if any extensions are resolved through {@link ServletContext#getMimeType(String)}
+ * or through the Java Activation framework.
+ */
+ public PathExtensionContentNegotiationStrategy() {
+ super(null);
+ }
+
+ /**
+ * Indicate whether to use the Java Activation Framework to map from file extensions to media types.
+ * <p>Default is {@code true}, i.e. the Java Activation Framework is used (if available).
+ */
+ public void setUseJaf(boolean useJaf) {
+ this.useJaf = useJaf;
+ }
+
+ @Override
+ protected String getMediaTypeKey(NativeWebRequest webRequest) {
+ HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.class);
+ if (servletRequest == null) {
+ logger.warn("An HttpServletRequest is required to determine the media type key");
+ return null;
+ }
+ String path = urlPathHelper.getLookupPathForRequest(servletRequest);
+ String filename = WebUtils.extractFullFilenameFromUrlPath(path);
+ String extension = StringUtils.getFilenameExtension(filename);
+ return (StringUtils.hasText(extension)) ? extension.toLowerCase(Locale.ENGLISH) : null;
+ }
+
+ @Override
+ protected void handleMatch(String extension, MediaType mediaType) {
+ if (logger.isDebugEnabled()) {
+ logger.debug("Requested media type is '" + mediaType + "' (based on file extension '" + extension + "')");
+ }
+ }
+
+ @Override
+ protected MediaType handleNoMatch(NativeWebRequest webRequest, String extension) {
+ MediaType mediaType = null;
+ HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.class);
+ if (servletRequest != null) {
+ String mimeType = servletRequest.getServletContext().getMimeType("file." + extension);
+ if (StringUtils.hasText(mimeType)) {
+ mediaType = MediaType.parseMediaType(mimeType);
+ }
+ }
+ if ((mediaType == null || MediaType.APPLICATION_OCTET_STREAM.equals(mediaType)) && this.useJaf) {
+ MediaType jafMediaType = JafMediaTypeFactory.getMediaType("file." + extension);
+ if (jafMediaType != null && !MediaType.APPLICATION_OCTET_STREAM.equals(jafMediaType)) {
+ mediaType = jafMediaType;
+ }
+ }
+ return mediaType;
+ }
+
+
+ /**
+ * Inner class to avoid hard-coded dependency on JAF.
+ */
+ private static class JafMediaTypeFactory {
+
+ private static final FileTypeMap fileTypeMap;
+
+ static {
+ fileTypeMap = initFileTypeMap();
+ }
+
+ /**
+ * Find extended mime.types from the spring-context-support module.
+ */
+ private static FileTypeMap initFileTypeMap() {
+ Resource resource = new ClassPathResource("org/springframework/mail/javamail/mime.types");
+ if (resource.exists()) {
+ if (logger.isTraceEnabled()) {
+ logger.trace("Loading Java Activation Framework FileTypeMap from " + resource);
+ }
+ InputStream inputStream = null;
+ try {
+ inputStream = resource.getInputStream();
+ return new MimetypesFileTypeMap(inputStream);
+ }
+ catch (IOException ex) {
+ // ignore
+ }
+ finally {
+ if (inputStream != null) {
+ try {
+ inputStream.close();
+ }
+ catch (IOException ex) {
+ // ignore
+ }
+ }
+ }
+ }
+ if (logger.isTraceEnabled()) {
+ logger.trace("Loading default Java Activation Framework FileTypeMap");
+ }
+ return FileTypeMap.getDefaultFileTypeMap();
+ }
+
+ public static MediaType getMediaType(String filename) {
+ String mediaType = fileTypeMap.getContentType(filename);
+ return (StringUtils.hasText(mediaType) ? MediaType.parseMediaType(mediaType) : null);
+ }
+ }
+
+} | true |
Other | spring-projects | spring-framework | f05e2bc56f8e03466977d73a5e99c37651248803.json | Add abstractions for content negotiation
Introduced ContentNeogtiationStrategy for resolving the requested
media types from an incoming request. The available implementations
are based on path extension, request parameter, 'Accept' header,
and a fixed default content type. The logic for these implementations
is based on equivalent options, previously available only in the
ContentNegotiatingViewResolver.
Also in this commit is ContentNegotiationManager, the central class to
use when configuring content negotiation options. It accepts one or
more ContentNeogtiationStrategy instances and delegates to them.
The ContentNeogiationManager can now be used to configure the
following classes:
- RequestMappingHandlerMappingm
- RequestMappingHandlerAdapter
- ExceptionHandlerExceptionResolver
- ContentNegotiatingViewResolver
Issue: SPR-8410, SPR-8417, SPR-8418,SPR-8416, SPR-8419,SPR-7722 | spring-web/src/main/java/org/springframework/web/accept/package-info.java | @@ -0,0 +1,17 @@
+
+/**
+ * This package contains classes used to determine the requested the media types in a request.
+ *
+ * <p>{@link org.springframework.web.accept.ContentNegotiationStrategy} is the main
+ * abstraction for determining requested {@linkplain org.springframework.http.MediaType media types}
+ * with implementations based on
+ * {@linkplain org.springframework.web.accept.PathExtensionContentNegotiationStrategy path extensions}, a
+ * {@linkplain org.springframework.web.accept.ParameterContentNegotiationStrategy a request parameter}, the
+ * {@linkplain org.springframework.web.accept.HeaderContentNegotiationStrategy 'Accept' header}, or a
+ * {@linkplain org.springframework.web.accept.FixedContentNegotiationStrategy default content type}.
+ *
+ * <p>{@link org.springframework.web.accept.ContentNegotiationManager} is used to delegate to one
+ * ore more of the above strategies in a specific order.
+ */
+package org.springframework.web.accept;
+ | true |
Other | spring-projects | spring-framework | f05e2bc56f8e03466977d73a5e99c37651248803.json | Add abstractions for content negotiation
Introduced ContentNeogtiationStrategy for resolving the requested
media types from an incoming request. The available implementations
are based on path extension, request parameter, 'Accept' header,
and a fixed default content type. The logic for these implementations
is based on equivalent options, previously available only in the
ContentNegotiatingViewResolver.
Also in this commit is ContentNegotiationManager, the central class to
use when configuring content negotiation options. It accepts one or
more ContentNeogtiationStrategy instances and delegates to them.
The ContentNeogiationManager can now be used to configure the
following classes:
- RequestMappingHandlerMappingm
- RequestMappingHandlerAdapter
- ExceptionHandlerExceptionResolver
- ContentNegotiatingViewResolver
Issue: SPR-8410, SPR-8417, SPR-8418,SPR-8416, SPR-8419,SPR-7722 | spring-web/src/test/java/org/springframework/web/accept/AbstractMappingContentNegotiationStrategyTests.java | @@ -0,0 +1,99 @@
+/*
+ * Copyright 2002-2012 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.springframework.web.accept;
+
+import static org.junit.Assert.assertEquals;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+
+import org.junit.Test;
+import org.springframework.http.MediaType;
+import org.springframework.web.context.request.NativeWebRequest;
+
+/**
+ * A test fixture with a test sub-class of AbstractMappingContentNegotiationStrategy.
+ *
+ * @author Rossen Stoyanchev
+ * @since 3.2
+ */
+public class AbstractMappingContentNegotiationStrategyTests {
+
+ @Test
+ public void resolveMediaTypes() {
+ Map<String, String> mapping = Collections.singletonMap("json", "application/json");
+ TestMappingContentNegotiationStrategy strategy = new TestMappingContentNegotiationStrategy("json", mapping);
+
+ List<MediaType> mediaTypes = strategy.resolveMediaTypes(null);
+
+ assertEquals(1, mediaTypes.size());
+ assertEquals("application/json", mediaTypes.get(0).toString());
+ }
+
+ @Test
+ public void resolveMediaTypesNoMatch() {
+ Map<String, String> mapping = null;
+ TestMappingContentNegotiationStrategy strategy = new TestMappingContentNegotiationStrategy("blah", mapping);
+
+ List<MediaType> mediaTypes = strategy.resolveMediaTypes(null);
+
+ assertEquals(0, mediaTypes.size());
+ }
+
+ @Test
+ public void resolveMediaTypesNoKey() {
+ Map<String, String> mapping = Collections.singletonMap("json", "application/json");
+ TestMappingContentNegotiationStrategy strategy = new TestMappingContentNegotiationStrategy(null, mapping);
+
+ List<MediaType> mediaTypes = strategy.resolveMediaTypes(null);
+
+ assertEquals(0, mediaTypes.size());
+ }
+
+ @Test
+ public void resolveMediaTypesHandleNoMatch() {
+ Map<String, String> mapping = null;
+ TestMappingContentNegotiationStrategy strategy = new TestMappingContentNegotiationStrategy("xml", mapping);
+
+ List<MediaType> mediaTypes = strategy.resolveMediaTypes(null);
+
+ assertEquals(1, mediaTypes.size());
+ assertEquals("application/xml", mediaTypes.get(0).toString());
+ }
+
+
+ private static class TestMappingContentNegotiationStrategy extends AbstractMappingContentNegotiationStrategy {
+
+ private final String extension;
+
+ public TestMappingContentNegotiationStrategy(String extension, Map<String, String> mapping) {
+ super(mapping);
+ this.extension = extension;
+ }
+
+ @Override
+ protected String getMediaTypeKey(NativeWebRequest request) {
+ return this.extension;
+ }
+
+ @Override
+ protected MediaType handleNoMatch(NativeWebRequest request, String mappingKey) {
+ return "xml".equals(mappingKey) ? MediaType.APPLICATION_XML : null;
+ }
+ }
+
+} | true |
Other | spring-projects | spring-framework | f05e2bc56f8e03466977d73a5e99c37651248803.json | Add abstractions for content negotiation
Introduced ContentNeogtiationStrategy for resolving the requested
media types from an incoming request. The available implementations
are based on path extension, request parameter, 'Accept' header,
and a fixed default content type. The logic for these implementations
is based on equivalent options, previously available only in the
ContentNegotiatingViewResolver.
Also in this commit is ContentNegotiationManager, the central class to
use when configuring content negotiation options. It accepts one or
more ContentNeogtiationStrategy instances and delegates to them.
The ContentNeogiationManager can now be used to configure the
following classes:
- RequestMappingHandlerMappingm
- RequestMappingHandlerAdapter
- ExceptionHandlerExceptionResolver
- ContentNegotiatingViewResolver
Issue: SPR-8410, SPR-8417, SPR-8418,SPR-8416, SPR-8419,SPR-7722 | spring-web/src/test/java/org/springframework/web/accept/HeaderContentNegotiationStrategyTests.java | @@ -0,0 +1,68 @@
+/*
+ * Copyright 2002-2012 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.springframework.web.accept;
+
+import static org.junit.Assert.assertEquals;
+
+import java.util.List;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.springframework.http.MediaType;
+import org.springframework.mock.web.MockHttpServletRequest;
+import org.springframework.web.HttpMediaTypeNotAcceptableException;
+import org.springframework.web.context.request.NativeWebRequest;
+import org.springframework.web.context.request.ServletWebRequest;
+
+/**
+ * Test fixture for HeaderContentNegotiationStrategy tests.
+ *
+ * @author Rossen Stoyanchev
+ */
+public class HeaderContentNegotiationStrategyTests {
+
+ private HeaderContentNegotiationStrategy strategy;
+
+ private NativeWebRequest webRequest;
+
+ private MockHttpServletRequest servletRequest;
+
+ @Before
+ public void setup() {
+ this.strategy = new HeaderContentNegotiationStrategy();
+ this.servletRequest = new MockHttpServletRequest();
+ this.webRequest = new ServletWebRequest(servletRequest );
+ }
+
+ @Test
+ public void resolveMediaTypes() throws Exception {
+ this.servletRequest.addHeader("Accept", "text/plain; q=0.5, text/html, text/x-dvi; q=0.8, text/x-c");
+ List<MediaType> mediaTypes = this.strategy.resolveMediaTypes(this.webRequest);
+
+ assertEquals(4, mediaTypes.size());
+ assertEquals("text/html", mediaTypes.get(0).toString());
+ assertEquals("text/x-c", mediaTypes.get(1).toString());
+ assertEquals("text/x-dvi;q=0.8", mediaTypes.get(2).toString());
+ assertEquals("text/plain;q=0.5", mediaTypes.get(3).toString());
+ }
+
+ @Test(expected=HttpMediaTypeNotAcceptableException.class)
+ public void resolveMediaTypesParseError() throws Exception {
+ this.servletRequest.addHeader("Accept", "textplain; q=0.5");
+ this.strategy.resolveMediaTypes(this.webRequest);
+ }
+
+} | true |
Other | spring-projects | spring-framework | f05e2bc56f8e03466977d73a5e99c37651248803.json | Add abstractions for content negotiation
Introduced ContentNeogtiationStrategy for resolving the requested
media types from an incoming request. The available implementations
are based on path extension, request parameter, 'Accept' header,
and a fixed default content type. The logic for these implementations
is based on equivalent options, previously available only in the
ContentNegotiatingViewResolver.
Also in this commit is ContentNegotiationManager, the central class to
use when configuring content negotiation options. It accepts one or
more ContentNeogtiationStrategy instances and delegates to them.
The ContentNeogiationManager can now be used to configure the
following classes:
- RequestMappingHandlerMappingm
- RequestMappingHandlerAdapter
- ExceptionHandlerExceptionResolver
- ContentNegotiatingViewResolver
Issue: SPR-8410, SPR-8417, SPR-8418,SPR-8416, SPR-8419,SPR-7722 | spring-web/src/test/java/org/springframework/web/accept/MappingMediaTypeExtensionsResolverTests.java | @@ -0,0 +1,44 @@
+/*
+ * Copyright 2002-2012 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.springframework.web.accept;
+
+import static org.junit.Assert.assertEquals;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+
+import org.junit.Test;
+import org.springframework.http.MediaType;
+
+/**
+ * Test fixture for MappingMediaTypeExtensionsResolver.
+ *
+ * @author Rossen Stoyanchev
+ */
+public class MappingMediaTypeExtensionsResolverTests {
+
+ @Test
+ public void resolveExtensions() {
+ Map<String, String> mapping = Collections.singletonMap("json", "application/json");
+ MappingMediaTypeExtensionsResolver resolver = new MappingMediaTypeExtensionsResolver(mapping);
+ List<String> extensions = resolver.resolveExtensions(MediaType.APPLICATION_JSON);
+
+ assertEquals(1, extensions.size());
+ assertEquals("json", extensions.get(0));
+ }
+
+} | true |
Other | spring-projects | spring-framework | f05e2bc56f8e03466977d73a5e99c37651248803.json | Add abstractions for content negotiation
Introduced ContentNeogtiationStrategy for resolving the requested
media types from an incoming request. The available implementations
are based on path extension, request parameter, 'Accept' header,
and a fixed default content type. The logic for these implementations
is based on equivalent options, previously available only in the
ContentNegotiatingViewResolver.
Also in this commit is ContentNegotiationManager, the central class to
use when configuring content negotiation options. It accepts one or
more ContentNeogtiationStrategy instances and delegates to them.
The ContentNeogiationManager can now be used to configure the
following classes:
- RequestMappingHandlerMappingm
- RequestMappingHandlerAdapter
- ExceptionHandlerExceptionResolver
- ContentNegotiatingViewResolver
Issue: SPR-8410, SPR-8417, SPR-8418,SPR-8416, SPR-8419,SPR-7722 | spring-web/src/test/java/org/springframework/web/accept/PathExtensionContentNegotiationStrategyTests.java | @@ -0,0 +1,113 @@
+/*
+ * Copyright 2002-2012 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.springframework.web.accept;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.springframework.http.MediaType;
+import org.springframework.mock.web.MockHttpServletRequest;
+import org.springframework.web.context.request.NativeWebRequest;
+import org.springframework.web.context.request.ServletWebRequest;
+
+/**
+ * A test fixture for PathExtensionContentNegotiationStrategy.
+ *
+ * @author Rossen Stoyanchev
+ * @since 3.2
+ */
+public class PathExtensionContentNegotiationStrategyTests {
+
+ private NativeWebRequest webRequest;
+
+ private MockHttpServletRequest servletRequest;
+
+ @Before
+ public void setup() {
+ this.servletRequest = new MockHttpServletRequest();
+ this.webRequest = new ServletWebRequest(servletRequest );
+ }
+
+ @Test
+ public void resolveMediaTypesFromMapping() {
+ this.servletRequest.setRequestURI("test.html");
+ PathExtensionContentNegotiationStrategy strategy = new PathExtensionContentNegotiationStrategy();
+
+ List<MediaType> mediaTypes = strategy.resolveMediaTypes(this.webRequest);
+
+ assertEquals(Arrays.asList(new MediaType("text", "html")), mediaTypes);
+
+ strategy = new PathExtensionContentNegotiationStrategy(Collections.singletonMap("HTML", "application/xhtml+xml"));
+ mediaTypes = strategy.resolveMediaTypes(this.webRequest);
+
+ assertEquals(Arrays.asList(new MediaType("application", "xhtml+xml")), mediaTypes);
+ }
+
+ @Test
+ public void resolveMediaTypesFromJaf() {
+ this.servletRequest.setRequestURI("test.xls");
+ PathExtensionContentNegotiationStrategy strategy = new PathExtensionContentNegotiationStrategy();
+
+ List<MediaType> mediaTypes = strategy.resolveMediaTypes(this.webRequest);
+
+ assertEquals(Arrays.asList(new MediaType("application", "vnd.ms-excel")), mediaTypes);
+ }
+
+ @Test
+ public void getMediaTypeFromFilenameNoJaf() {
+ this.servletRequest.setRequestURI("test.xls");
+ PathExtensionContentNegotiationStrategy strategy = new PathExtensionContentNegotiationStrategy();
+ strategy.setUseJaf(false);
+
+ List<MediaType> mediaTypes = strategy.resolveMediaTypes(this.webRequest);
+
+ assertEquals(Arrays.asList(MediaType.APPLICATION_OCTET_STREAM), mediaTypes);
+ }
+
+ // SPR-8678
+
+ @Test
+ public void getMediaTypeFilenameWithContextPath() {
+ this.servletRequest.setContextPath("/project-1.0.0.M3");
+ this.servletRequest.setRequestURI("/project-1.0.0.M3/");
+ PathExtensionContentNegotiationStrategy strategy = new PathExtensionContentNegotiationStrategy();
+
+ assertTrue("Context path should be excluded", strategy.resolveMediaTypes(webRequest).isEmpty());
+
+ this.servletRequest.setRequestURI("/project-1.0.0.M3");
+
+ assertTrue("Context path should be excluded", strategy.resolveMediaTypes(webRequest).isEmpty());
+ }
+
+ // SPR-9390
+
+ @Test
+ public void getMediaTypeFilenameWithEncodedURI() {
+ this.servletRequest.setRequestURI("/quo%20vadis%3f.html");
+ PathExtensionContentNegotiationStrategy strategy = new PathExtensionContentNegotiationStrategy();
+
+ List<MediaType> result = strategy.resolveMediaTypes(webRequest);
+
+ assertEquals("Invalid content type", Collections.singletonList(new MediaType("text", "html")), result);
+ }
+
+} | true |
Other | spring-projects | spring-framework | f05e2bc56f8e03466977d73a5e99c37651248803.json | Add abstractions for content negotiation
Introduced ContentNeogtiationStrategy for resolving the requested
media types from an incoming request. The available implementations
are based on path extension, request parameter, 'Accept' header,
and a fixed default content type. The logic for these implementations
is based on equivalent options, previously available only in the
ContentNegotiatingViewResolver.
Also in this commit is ContentNegotiationManager, the central class to
use when configuring content negotiation options. It accepts one or
more ContentNeogtiationStrategy instances and delegates to them.
The ContentNeogiationManager can now be used to configure the
following classes:
- RequestMappingHandlerMappingm
- RequestMappingHandlerAdapter
- ExceptionHandlerExceptionResolver
- ContentNegotiatingViewResolver
Issue: SPR-8410, SPR-8417, SPR-8418,SPR-8416, SPR-8419,SPR-7722 | spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/condition/AbstractMediaTypeExpression.java | @@ -21,6 +21,7 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.http.MediaType;
+import org.springframework.web.HttpMediaTypeException;
import org.springframework.web.bind.annotation.RequestMapping;
/**
@@ -68,15 +69,12 @@ public final boolean match(HttpServletRequest request) {
boolean match = matchMediaType(request);
return !isNegated ? match : !match;
}
- catch (IllegalArgumentException ex) {
- if (logger.isDebugEnabled()) {
- logger.debug("Could not parse media type header: " + ex.getMessage());
- }
+ catch (HttpMediaTypeException ex) {
return false;
}
}
- protected abstract boolean matchMediaType(HttpServletRequest request);
+ protected abstract boolean matchMediaType(HttpServletRequest request) throws HttpMediaTypeException;
public int compareTo(AbstractMediaTypeExpression other) {
return MediaType.SPECIFICITY_COMPARATOR.compare(this.getMediaType(), other.getMediaType()); | true |
Other | spring-projects | spring-framework | f05e2bc56f8e03466977d73a5e99c37651248803.json | Add abstractions for content negotiation
Introduced ContentNeogtiationStrategy for resolving the requested
media types from an incoming request. The available implementations
are based on path extension, request parameter, 'Accept' header,
and a fixed default content type. The logic for these implementations
is based on equivalent options, previously available only in the
ContentNegotiatingViewResolver.
Also in this commit is ContentNegotiationManager, the central class to
use when configuring content negotiation options. It accepts one or
more ContentNeogtiationStrategy instances and delegates to them.
The ContentNeogiationManager can now be used to configure the
following classes:
- RequestMappingHandlerMappingm
- RequestMappingHandlerAdapter
- ExceptionHandlerExceptionResolver
- ContentNegotiatingViewResolver
Issue: SPR-8410, SPR-8417, SPR-8418,SPR-8416, SPR-8419,SPR-7722 | spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/condition/ConsumesRequestCondition.java | @@ -28,17 +28,18 @@
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
+import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.condition.HeadersRequestCondition.HeaderExpression;
/**
- * A logical disjunction (' || ') request condition to match a request's
- * 'Content-Type' header to a list of media type expressions. Two kinds of
- * media type expressions are supported, which are described in
- * {@link RequestMapping#consumes()} and {@link RequestMapping#headers()}
- * where the header name is 'Content-Type'. Regardless of which syntax is
+ * A logical disjunction (' || ') request condition to match a request's
+ * 'Content-Type' header to a list of media type expressions. Two kinds of
+ * media type expressions are supported, which are described in
+ * {@link RequestMapping#consumes()} and {@link RequestMapping#headers()}
+ * where the header name is 'Content-Type'. Regardless of which syntax is
* used, the semantics are the same.
- *
+ *
* @author Arjen Poutsma
* @author Rossen Stoyanchev
* @since 3.1
@@ -49,18 +50,18 @@ public final class ConsumesRequestCondition extends AbstractRequestCondition<Con
/**
* Creates a new instance from 0 or more "consumes" expressions.
- * @param consumes expressions with the syntax described in
- * {@link RequestMapping#consumes()}; if 0 expressions are provided,
+ * @param consumes expressions with the syntax described in
+ * {@link RequestMapping#consumes()}; if 0 expressions are provided,
* the condition will match to every request.
*/
public ConsumesRequestCondition(String... consumes) {
this(consumes, null);
}
/**
- * Creates a new instance with "consumes" and "header" expressions.
+ * Creates a new instance with "consumes" and "header" expressions.
* "Header" expressions where the header name is not 'Content-Type' or have
- * no header value defined are ignored. If 0 expressions are provided in
+ * no header value defined are ignored. If 0 expressions are provided in
* total, the condition will match to every request
* @param consumes as described in {@link RequestMapping#consumes()}
* @param headers as described in {@link RequestMapping#headers()}
@@ -116,7 +117,7 @@ public Set<MediaType> getConsumableMediaTypes() {
}
return result;
}
-
+
/**
* Whether the condition has any media type expressions.
*/
@@ -135,24 +136,24 @@ protected String getToStringInfix() {
}
/**
- * Returns the "other" instance if it has any expressions; returns "this"
- * instance otherwise. Practically that means a method-level "consumes"
+ * Returns the "other" instance if it has any expressions; returns "this"
+ * instance otherwise. Practically that means a method-level "consumes"
* overrides a type-level "consumes" condition.
*/
public ConsumesRequestCondition combine(ConsumesRequestCondition other) {
return !other.expressions.isEmpty() ? other : this;
}
/**
- * Checks if any of the contained media type expressions match the given
- * request 'Content-Type' header and returns an instance that is guaranteed
+ * Checks if any of the contained media type expressions match the given
+ * request 'Content-Type' header and returns an instance that is guaranteed
* to contain matching expressions only. The match is performed via
* {@link MediaType#includes(MediaType)}.
- *
+ *
* @param request the current request
- *
- * @return the same instance if the condition contains no expressions;
- * or a new condition with matching expressions only;
+ *
+ * @return the same instance if the condition contains no expressions;
+ * or a new condition with matching expressions only;
* or {@code null} if no expressions match.
*/
public ConsumesRequestCondition getMatchingCondition(HttpServletRequest request) {
@@ -175,10 +176,10 @@ public ConsumesRequestCondition getMatchingCondition(HttpServletRequest request)
* <li>0 if the two conditions have the same number of expressions
* <li>Less than 0 if "this" has more or more specific media type expressions
* <li>Greater than 0 if "other" has more or more specific media type expressions
- * </ul>
- *
- * <p>It is assumed that both instances have been obtained via
- * {@link #getMatchingCondition(HttpServletRequest)} and each instance contains
+ * </ul>
+ *
+ * <p>It is assumed that both instances have been obtained via
+ * {@link #getMatchingCondition(HttpServletRequest)} and each instance contains
* the matching consumable media type expression only or is otherwise empty.
*/
public int compareTo(ConsumesRequestCondition other, HttpServletRequest request) {
@@ -197,7 +198,7 @@ else if (other.expressions.isEmpty()) {
}
/**
- * Parses and matches a single media type expression to a request's 'Content-Type' header.
+ * Parses and matches a single media type expression to a request's 'Content-Type' header.
*/
static class ConsumeMediaTypeExpression extends AbstractMediaTypeExpression {
@@ -210,11 +211,17 @@ static class ConsumeMediaTypeExpression extends AbstractMediaTypeExpression {
}
@Override
- protected boolean matchMediaType(HttpServletRequest request) {
- MediaType contentType = StringUtils.hasLength(request.getContentType()) ?
- MediaType.parseMediaType(request.getContentType()) :
- MediaType.APPLICATION_OCTET_STREAM ;
- return getMediaType().includes(contentType);
+ protected boolean matchMediaType(HttpServletRequest request) throws HttpMediaTypeNotSupportedException {
+ try {
+ MediaType contentType = StringUtils.hasLength(request.getContentType()) ?
+ MediaType.parseMediaType(request.getContentType()) :
+ MediaType.APPLICATION_OCTET_STREAM;
+ return getMediaType().includes(contentType);
+ }
+ catch (IllegalArgumentException ex) {
+ throw new HttpMediaTypeNotSupportedException(
+ "Can't parse Content-Type [" + request.getContentType() + "]: " + ex.getMessage());
+ }
}
}
| true |
Other | spring-projects | spring-framework | f05e2bc56f8e03466977d73a5e99c37651248803.json | Add abstractions for content negotiation
Introduced ContentNeogtiationStrategy for resolving the requested
media types from an incoming request. The available implementations
are based on path extension, request parameter, 'Accept' header,
and a fixed default content type. The logic for these implementations
is based on equivalent options, previously available only in the
ContentNegotiatingViewResolver.
Also in this commit is ContentNegotiationManager, the central class to
use when configuring content negotiation options. It accepts one or
more ContentNeogtiationStrategy instances and delegates to them.
The ContentNeogiationManager can now be used to configure the
following classes:
- RequestMappingHandlerMappingm
- RequestMappingHandlerAdapter
- ExceptionHandlerExceptionResolver
- ContentNegotiatingViewResolver
Issue: SPR-8410, SPR-8417, SPR-8418,SPR-8416, SPR-8419,SPR-7722 | spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/condition/ProducesRequestCondition.java | @@ -1,5 +1,5 @@
/*
- * Copyright 2002-2011 the original author or authors.
+ * Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,7 +17,6 @@
package org.springframework.web.servlet.mvc.condition;
import java.util.ArrayList;
-import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
@@ -28,17 +27,19 @@
import javax.servlet.http.HttpServletRequest;
import org.springframework.http.MediaType;
-import org.springframework.util.StringUtils;
+import org.springframework.web.HttpMediaTypeNotAcceptableException;
+import org.springframework.web.accept.ContentNegotiationManager;
import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.servlet.mvc.condition.HeadersRequestCondition.HeaderExpression;
/**
* A logical disjunction (' || ') request condition to match a request's 'Accept' header
- * to a list of media type expressions. Two kinds of media type expressions are
+ * to a list of media type expressions. Two kinds of media type expressions are
* supported, which are described in {@link RequestMapping#produces()} and
- * {@link RequestMapping#headers()} where the header name is 'Accept'.
+ * {@link RequestMapping#headers()} where the header name is 'Accept'.
* Regardless of which syntax is used, the semantics are the same.
- *
+ *
* @author Arjen Poutsma
* @author Rossen Stoyanchev
* @since 3.1
@@ -47,35 +48,45 @@ public final class ProducesRequestCondition extends AbstractRequestCondition<Pro
private final List<ProduceMediaTypeExpression> expressions;
+ private final ContentNegotiationManager contentNegotiationManager;
+
/**
- * Creates a new instance from 0 or more "produces" expressions.
- * @param produces expressions with the syntax described in {@link RequestMapping#produces()}
- * if 0 expressions are provided, the condition matches to every request
+ * Creates a new instance from "produces" expressions. If 0 expressions
+ * are provided in total, this condition will match to any request.
+ * @param produces expressions with syntax defined by {@link RequestMapping#produces()}
*/
public ProducesRequestCondition(String... produces) {
- this(parseExpressions(produces, null));
+ this(produces, (String[]) null);
}
-
+
/**
- * Creates a new instance with "produces" and "header" expressions. "Header" expressions
- * where the header name is not 'Accept' or have no header value defined are ignored.
- * If 0 expressions are provided in total, the condition matches to every request
- * @param produces expressions with the syntax described in {@link RequestMapping#produces()}
- * @param headers expressions with the syntax described in {@link RequestMapping#headers()}
+ * Creates a new instance with "produces" and "header" expressions. "Header"
+ * expressions where the header name is not 'Accept' or have no header value
+ * defined are ignored. If 0 expressions are provided in total, this condition
+ * will match to any request.
+ * @param produces expressions with syntax defined by {@link RequestMapping#produces()}
+ * @param headers expressions with syntax defined by {@link RequestMapping#headers()}
*/
public ProducesRequestCondition(String[] produces, String[] headers) {
- this(parseExpressions(produces, headers));
+ this(produces, headers, null);
}
/**
- * Private constructor accepting parsed media type expressions.
+ * Same as {@link #ProducesRequestCondition(String[], String[])} but also
+ * accepting a {@link ContentNegotiationManager}.
+ * @param produces expressions with syntax defined by {@link RequestMapping#produces()}
+ * @param headers expressions with syntax defined by {@link RequestMapping#headers()}
+ * @param contentNegotiationManager used to determine requested media types
*/
- private ProducesRequestCondition(Collection<ProduceMediaTypeExpression> expressions) {
- this.expressions = new ArrayList<ProduceMediaTypeExpression>(expressions);
+ public ProducesRequestCondition(String[] produces, String[] headers,
+ ContentNegotiationManager manager) {
+
+ this.expressions = new ArrayList<ProduceMediaTypeExpression>(parseExpressions(produces, headers));
Collections.sort(this.expressions);
+ this.contentNegotiationManager = (manager != null) ? manager : new ContentNegotiationManager();
}
- private static Set<ProduceMediaTypeExpression> parseExpressions(String[] produces, String[] headers) {
+ private Set<ProduceMediaTypeExpression> parseExpressions(String[] produces, String[] headers) {
Set<ProduceMediaTypeExpression> result = new LinkedHashSet<ProduceMediaTypeExpression>();
if (headers != null) {
for (String header : headers) {
@@ -95,6 +106,17 @@ private static Set<ProduceMediaTypeExpression> parseExpressions(String[] produce
return result;
}
+ /**
+ * Private constructor with already parsed media type expressions.
+ */
+ private ProducesRequestCondition(Collection<ProduceMediaTypeExpression> expressions,
+ ContentNegotiationManager manager) {
+
+ this.expressions = new ArrayList<ProduceMediaTypeExpression>(expressions);
+ Collections.sort(this.expressions);
+ this.contentNegotiationManager = (manager != null) ? manager : new ContentNegotiationManager();
+ }
+
/**
* Return the contained "produces" expressions.
*/
@@ -133,24 +155,24 @@ protected String getToStringInfix() {
}
/**
- * Returns the "other" instance if it has any expressions; returns "this"
- * instance otherwise. Practically that means a method-level "produces"
+ * Returns the "other" instance if it has any expressions; returns "this"
+ * instance otherwise. Practically that means a method-level "produces"
* overrides a type-level "produces" condition.
*/
public ProducesRequestCondition combine(ProducesRequestCondition other) {
return !other.expressions.isEmpty() ? other : this;
}
/**
- * Checks if any of the contained media type expressions match the given
- * request 'Content-Type' header and returns an instance that is guaranteed
+ * Checks if any of the contained media type expressions match the given
+ * request 'Content-Type' header and returns an instance that is guaranteed
* to contain matching expressions only. The match is performed via
* {@link MediaType#isCompatibleWith(MediaType)}.
- *
+ *
* @param request the current request
- *
- * @return the same instance if there are no expressions;
- * or a new condition with matching expressions;
+ *
+ * @return the same instance if there are no expressions;
+ * or a new condition with matching expressions;
* or {@code null} if no expressions match.
*/
public ProducesRequestCondition getMatchingCondition(HttpServletRequest request) {
@@ -164,58 +186,57 @@ public ProducesRequestCondition getMatchingCondition(HttpServletRequest request)
iterator.remove();
}
}
- return (result.isEmpty()) ? null : new ProducesRequestCondition(result);
+ return (result.isEmpty()) ? null : new ProducesRequestCondition(result, this.contentNegotiationManager);
}
/**
* Compares this and another "produces" condition as follows:
- *
+ *
* <ol>
* <li>Sort 'Accept' header media types by quality value via
* {@link MediaType#sortByQualityValue(List)} and iterate the list.
* <li>Get the first index of matching media types in each "produces"
- * condition first matching with {@link MediaType#equals(Object)} and
+ * condition first matching with {@link MediaType#equals(Object)} and
* then with {@link MediaType#includes(MediaType)}.
* <li>If a lower index is found, the condition at that index wins.
- * <li>If both indexes are equal, the media types at the index are
+ * <li>If both indexes are equal, the media types at the index are
* compared further with {@link MediaType#SPECIFICITY_COMPARATOR}.
* </ol>
- *
- * <p>It is assumed that both instances have been obtained via
- * {@link #getMatchingCondition(HttpServletRequest)} and each instance
- * contains the matching producible media type expression only or
+ *
+ * <p>It is assumed that both instances have been obtained via
+ * {@link #getMatchingCondition(HttpServletRequest)} and each instance
+ * contains the matching producible media type expression only or
* is otherwise empty.
*/
public int compareTo(ProducesRequestCondition other, HttpServletRequest request) {
- List<MediaType> acceptedMediaTypes = getAcceptedMediaTypes(request);
- MediaType.sortByQualityValue(acceptedMediaTypes);
-
- for (MediaType acceptedMediaType : acceptedMediaTypes) {
- int thisIndex = this.indexOfEqualMediaType(acceptedMediaType);
- int otherIndex = other.indexOfEqualMediaType(acceptedMediaType);
- int result = compareMatchingMediaTypes(this, thisIndex, other, otherIndex);
- if (result != 0) {
- return result;
- }
- thisIndex = this.indexOfIncludedMediaType(acceptedMediaType);
- otherIndex = other.indexOfIncludedMediaType(acceptedMediaType);
- result = compareMatchingMediaTypes(this, thisIndex, other, otherIndex);
- if (result != 0) {
- return result;
+ try {
+ List<MediaType> acceptedMediaTypes = getAcceptedMediaTypes(request);
+
+ for (MediaType acceptedMediaType : acceptedMediaTypes) {
+ int thisIndex = this.indexOfEqualMediaType(acceptedMediaType);
+ int otherIndex = other.indexOfEqualMediaType(acceptedMediaType);
+ int result = compareMatchingMediaTypes(this, thisIndex, other, otherIndex);
+ if (result != 0) {
+ return result;
+ }
+ thisIndex = this.indexOfIncludedMediaType(acceptedMediaType);
+ otherIndex = other.indexOfIncludedMediaType(acceptedMediaType);
+ result = compareMatchingMediaTypes(this, thisIndex, other, otherIndex);
+ if (result != 0) {
+ return result;
+ }
}
+ return 0;
+ }
+ catch (HttpMediaTypeNotAcceptableException e) {
+ // should never happen
+ throw new IllegalStateException("Cannot compare without having any requested media types");
}
-
- return 0;
}
- private static List<MediaType> getAcceptedMediaTypes(HttpServletRequest request) {
- String acceptHeader = request.getHeader("Accept");
- if (StringUtils.hasLength(acceptHeader)) {
- return MediaType.parseMediaTypes(acceptHeader);
- }
- else {
- return Collections.singletonList(MediaType.ALL);
- }
+ private List<MediaType> getAcceptedMediaTypes(HttpServletRequest request) throws HttpMediaTypeNotAcceptableException {
+ List<MediaType> mediaTypes = this.contentNegotiationManager.resolveMediaTypes(new ServletWebRequest(request));
+ return mediaTypes.isEmpty() ? Collections.singletonList(MediaType.ALL) : mediaTypes;
}
private int indexOfEqualMediaType(MediaType mediaType) {
@@ -238,8 +259,9 @@ private int indexOfIncludedMediaType(MediaType mediaType) {
return -1;
}
- private static int compareMatchingMediaTypes(ProducesRequestCondition condition1, int index1,
- ProducesRequestCondition condition2, int index2) {
+ private int compareMatchingMediaTypes(ProducesRequestCondition condition1,
+ int index1, ProducesRequestCondition condition2, int index2) {
+
int result = 0;
if (index1 != index2) {
result = index2 - index1;
@@ -254,22 +276,22 @@ else if (index1 != -1 && index2 != -1) {
}
/**
- * Return the contained "produces" expressions or if that's empty, a list
- * with a {@code MediaType_ALL} expression.
- */
+ * Return the contained "produces" expressions or if that's empty, a list
+ * with a {@code MediaType_ALL} expression.
+ */
private List<ProduceMediaTypeExpression> getExpressionsToCompare() {
- return this.expressions.isEmpty() ? DEFAULT_EXPRESSION_LIST : this.expressions;
+ return this.expressions.isEmpty() ? MEDIA_TYPE_ALL_LIST : this.expressions;
}
- private static final List<ProduceMediaTypeExpression> DEFAULT_EXPRESSION_LIST =
- Arrays.asList(new ProduceMediaTypeExpression("*/*"));
+ private final List<ProduceMediaTypeExpression> MEDIA_TYPE_ALL_LIST =
+ Collections.singletonList(new ProduceMediaTypeExpression("*/*"));
+
-
/**
- * Parses and matches a single media type expression to a request's 'Accept' header.
+ * Parses and matches a single media type expression to a request's 'Accept' header.
*/
- static class ProduceMediaTypeExpression extends AbstractMediaTypeExpression {
-
+ class ProduceMediaTypeExpression extends AbstractMediaTypeExpression {
+
ProduceMediaTypeExpression(MediaType mediaType, boolean negated) {
super(mediaType, negated);
}
@@ -279,7 +301,7 @@ static class ProduceMediaTypeExpression extends AbstractMediaTypeExpression {
}
@Override
- protected boolean matchMediaType(HttpServletRequest request) {
+ protected boolean matchMediaType(HttpServletRequest request) throws HttpMediaTypeNotAcceptableException {
List<MediaType> acceptedMediaTypes = getAcceptedMediaTypes(request);
for (MediaType acceptedMediaType : acceptedMediaTypes) {
if (getMediaType().isCompatibleWith(acceptedMediaType)) { | true |
Other | spring-projects | spring-framework | f05e2bc56f8e03466977d73a5e99c37651248803.json | Add abstractions for content negotiation
Introduced ContentNeogtiationStrategy for resolving the requested
media types from an incoming request. The available implementations
are based on path extension, request parameter, 'Accept' header,
and a fixed default content type. The logic for these implementations
is based on equivalent options, previously available only in the
ContentNegotiatingViewResolver.
Also in this commit is ContentNegotiationManager, the central class to
use when configuring content negotiation options. It accepts one or
more ContentNeogtiationStrategy instances and delegates to them.
The ContentNeogiationManager can now be used to configure the
following classes:
- RequestMappingHandlerMappingm
- RequestMappingHandlerAdapter
- ExceptionHandlerExceptionResolver
- ContentNegotiatingViewResolver
Issue: SPR-8410, SPR-8417, SPR-8418,SPR-8416, SPR-8419,SPR-7722 | spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/AbstractMessageConverterMethodProcessor.java | @@ -27,15 +27,16 @@
import javax.servlet.http.HttpServletResponse;
import org.springframework.core.MethodParameter;
-import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.util.CollectionUtils;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
+import org.springframework.web.accept.ContentNegotiationManager;
import org.springframework.web.context.request.NativeWebRequest;
+import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.servlet.HandlerMapping;
@@ -52,8 +53,17 @@ public abstract class AbstractMessageConverterMethodProcessor extends AbstractMe
private static final MediaType MEDIA_TYPE_APPLICATION = new MediaType("application");
+ private final ContentNegotiationManager contentNegotiationManager;
+
protected AbstractMessageConverterMethodProcessor(List<HttpMessageConverter<?>> messageConverters) {
+ this(messageConverters, null);
+ }
+
+ protected AbstractMessageConverterMethodProcessor(List<HttpMessageConverter<?>> messageConverters,
+ ContentNegotiationManager manager) {
+
super(messageConverters);
+ this.contentNegotiationManager = (manager != null) ? manager : new ContentNegotiationManager();
}
/**
@@ -100,14 +110,15 @@ protected <T> void writeWithMessageConverters(T returnValue,
Class<?> returnValueClass = returnValue.getClass();
- List<MediaType> acceptableMediaTypes = getAcceptableMediaTypes(inputMessage);
- List<MediaType> producibleMediaTypes = getProducibleMediaTypes(inputMessage.getServletRequest(), returnValueClass);
+ HttpServletRequest servletRequest = inputMessage.getServletRequest();
+ List<MediaType> requestedMediaTypes = getAcceptableMediaTypes(servletRequest);
+ List<MediaType> producibleMediaTypes = getProducibleMediaTypes(servletRequest, returnValueClass);
Set<MediaType> compatibleMediaTypes = new LinkedHashSet<MediaType>();
- for (MediaType a : acceptableMediaTypes) {
+ for (MediaType r : requestedMediaTypes) {
for (MediaType p : producibleMediaTypes) {
- if (a.isCompatibleWith(p)) {
- compatibleMediaTypes.add(getMostSpecificMediaType(a, p));
+ if (r.isCompatibleWith(p)) {
+ compatibleMediaTypes.add(getMostSpecificMediaType(r, p));
}
}
}
@@ -175,17 +186,9 @@ else if (!allSupportedMediaTypes.isEmpty()) {
}
}
- private List<MediaType> getAcceptableMediaTypes(HttpInputMessage inputMessage) {
- try {
- List<MediaType> result = inputMessage.getHeaders().getAccept();
- return result.isEmpty() ? Collections.singletonList(MediaType.ALL) : result;
- }
- catch (IllegalArgumentException ex) {
- if (logger.isDebugEnabled()) {
- logger.debug("Could not parse Accept header: " + ex.getMessage());
- }
- return Collections.emptyList();
- }
+ private List<MediaType> getAcceptableMediaTypes(HttpServletRequest request) throws HttpMediaTypeNotAcceptableException {
+ List<MediaType> mediaTypes = this.contentNegotiationManager.resolveMediaTypes(new ServletWebRequest(request));
+ return mediaTypes.isEmpty() ? Collections.singletonList(MediaType.ALL) : mediaTypes;
}
/** | true |
Other | spring-projects | spring-framework | f05e2bc56f8e03466977d73a5e99c37651248803.json | Add abstractions for content negotiation
Introduced ContentNeogtiationStrategy for resolving the requested
media types from an incoming request. The available implementations
are based on path extension, request parameter, 'Accept' header,
and a fixed default content type. The logic for these implementations
is based on equivalent options, previously available only in the
ContentNegotiatingViewResolver.
Also in this commit is ContentNegotiationManager, the central class to
use when configuring content negotiation options. It accepts one or
more ContentNeogtiationStrategy instances and delegates to them.
The ContentNeogiationManager can now be used to configure the
following classes:
- RequestMappingHandlerMappingm
- RequestMappingHandlerAdapter
- ExceptionHandlerExceptionResolver
- ContentNegotiatingViewResolver
Issue: SPR-8410, SPR-8417, SPR-8418,SPR-8416, SPR-8419,SPR-7722 | spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ExceptionHandlerExceptionResolver.java | @@ -32,6 +32,7 @@
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.xml.SourceHttpMessageConverter;
import org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter;
+import org.springframework.web.accept.ContentNegotiationManager;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.method.HandlerMethod;
@@ -69,6 +70,8 @@ public class ExceptionHandlerExceptionResolver extends AbstractHandlerMethodExce
private List<HttpMessageConverter<?>> messageConverters;
+ private ContentNegotiationManager contentNegotiationManager = new ContentNegotiationManager();
+
private final Map<Class<?>, ExceptionHandlerMethodResolver> exceptionHandlerMethodResolvers =
new ConcurrentHashMap<Class<?>, ExceptionHandlerMethodResolver>();
@@ -182,6 +185,14 @@ public List<HttpMessageConverter<?>> getMessageConverters() {
return messageConverters;
}
+ /**
+ * Set the {@link ContentNegotiationManager} to use to determine requested media types.
+ * If not set, the default constructor is used.
+ */
+ public void setContentNegotiationManager(ContentNegotiationManager contentNegotiationManager) {
+ this.contentNegotiationManager = contentNegotiationManager;
+ }
+
public void afterPropertiesSet() {
if (this.argumentResolvers == null) {
List<HandlerMethodArgumentResolver> resolvers = getDefaultArgumentResolvers();
@@ -223,11 +234,11 @@ protected List<HandlerMethodReturnValueHandler> getDefaultReturnValueHandlers()
handlers.add(new ModelAndViewMethodReturnValueHandler());
handlers.add(new ModelMethodProcessor());
handlers.add(new ViewMethodReturnValueHandler());
- handlers.add(new HttpEntityMethodProcessor(getMessageConverters()));
+ handlers.add(new HttpEntityMethodProcessor(getMessageConverters(), this.contentNegotiationManager));
// Annotation-based return value types
handlers.add(new ModelAttributeMethodProcessor(false));
- handlers.add(new RequestResponseBodyMethodProcessor(getMessageConverters()));
+ handlers.add(new RequestResponseBodyMethodProcessor(getMessageConverters(), this.contentNegotiationManager));
// Multi-purpose return value types
handlers.add(new ViewNameMethodReturnValueHandler()); | true |
Other | spring-projects | spring-framework | f05e2bc56f8e03466977d73a5e99c37651248803.json | Add abstractions for content negotiation
Introduced ContentNeogtiationStrategy for resolving the requested
media types from an incoming request. The available implementations
are based on path extension, request parameter, 'Accept' header,
and a fixed default content type. The logic for these implementations
is based on equivalent options, previously available only in the
ContentNegotiatingViewResolver.
Also in this commit is ContentNegotiationManager, the central class to
use when configuring content negotiation options. It accepts one or
more ContentNeogtiationStrategy instances and delegates to them.
The ContentNeogiationManager can now be used to configure the
following classes:
- RequestMappingHandlerMappingm
- RequestMappingHandlerAdapter
- ExceptionHandlerExceptionResolver
- ContentNegotiatingViewResolver
Issue: SPR-8410, SPR-8417, SPR-8418,SPR-8416, SPR-8419,SPR-7722 | spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/HttpEntityMethodProcessor.java | @@ -33,6 +33,7 @@
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.util.Assert;
import org.springframework.web.HttpMediaTypeNotSupportedException;
+import org.springframework.web.accept.ContentNegotiationManager;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.ModelAndViewContainer;
@@ -56,6 +57,12 @@ public HttpEntityMethodProcessor(List<HttpMessageConverter<?>> messageConverters
super(messageConverters);
}
+ public HttpEntityMethodProcessor(List<HttpMessageConverter<?>> messageConverters,
+ ContentNegotiationManager contentNegotiationManager) {
+
+ super(messageConverters, contentNegotiationManager);
+ }
+
public boolean supportsParameter(MethodParameter parameter) {
Class<?> parameterType = parameter.getParameterType();
return HttpEntity.class.equals(parameterType);
@@ -123,7 +130,7 @@ public void handleReturnValue(
if (!entityHeaders.isEmpty()) {
outputMessage.getHeaders().putAll(entityHeaders);
}
-
+
Object body = responseEntity.getBody();
if (body != null) {
writeWithMessageConverters(body, returnType, inputMessage, outputMessage); | true |
Other | spring-projects | spring-framework | f05e2bc56f8e03466977d73a5e99c37651248803.json | Add abstractions for content negotiation
Introduced ContentNeogtiationStrategy for resolving the requested
media types from an incoming request. The available implementations
are based on path extension, request parameter, 'Accept' header,
and a fixed default content type. The logic for these implementations
is based on equivalent options, previously available only in the
ContentNegotiatingViewResolver.
Also in this commit is ContentNegotiationManager, the central class to
use when configuring content negotiation options. It accepts one or
more ContentNeogtiationStrategy instances and delegates to them.
The ContentNeogiationManager can now be used to configure the
following classes:
- RequestMappingHandlerMappingm
- RequestMappingHandlerAdapter
- ExceptionHandlerExceptionResolver
- ContentNegotiatingViewResolver
Issue: SPR-8410, SPR-8417, SPR-8418,SPR-8416, SPR-8419,SPR-7722 | spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerAdapter.java | @@ -47,6 +47,7 @@
import org.springframework.util.ClassUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ReflectionUtils.MethodFilter;
+import org.springframework.web.accept.ContentNegotiationManager;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
@@ -147,6 +148,8 @@ public class RequestMappingHandlerAdapter extends AbstractHandlerMethodAdapter i
private Long asyncRequestTimeout;
+ private ContentNegotiationManager contentNegotiationManager = new ContentNegotiationManager();
+
/**
* Default constructor.
*/
@@ -410,6 +413,14 @@ public void setAsyncRequestTimeout(long asyncRequestTimeout) {
this.asyncRequestTimeout = asyncRequestTimeout;
}
+ /**
+ * Set the {@link ContentNegotiationManager} to use to determine requested media types.
+ * If not set, the default constructor is used.
+ */
+ public void setContentNegotiationManager(ContentNegotiationManager contentNegotiationManager) {
+ this.contentNegotiationManager = contentNegotiationManager;
+ }
+
/**
* {@inheritDoc}
* <p>A {@link ConfigurableBeanFactory} is expected for resolving
@@ -525,12 +536,12 @@ private List<HandlerMethodReturnValueHandler> getDefaultReturnValueHandlers() {
handlers.add(new ModelAndViewMethodReturnValueHandler());
handlers.add(new ModelMethodProcessor());
handlers.add(new ViewMethodReturnValueHandler());
- handlers.add(new HttpEntityMethodProcessor(getMessageConverters()));
+ handlers.add(new HttpEntityMethodProcessor(getMessageConverters(), this.contentNegotiationManager));
handlers.add(new AsyncMethodReturnValueHandler());
// Annotation-based return value types
handlers.add(new ModelAttributeMethodProcessor(false));
- handlers.add(new RequestResponseBodyMethodProcessor(getMessageConverters()));
+ handlers.add(new RequestResponseBodyMethodProcessor(getMessageConverters(), this.contentNegotiationManager));
// Multi-purpose return value types
handlers.add(new ViewNameMethodReturnValueHandler()); | true |
Other | spring-projects | spring-framework | f05e2bc56f8e03466977d73a5e99c37651248803.json | Add abstractions for content negotiation
Introduced ContentNeogtiationStrategy for resolving the requested
media types from an incoming request. The available implementations
are based on path extension, request parameter, 'Accept' header,
and a fixed default content type. The logic for these implementations
is based on equivalent options, previously available only in the
ContentNegotiatingViewResolver.
Also in this commit is ContentNegotiationManager, the central class to
use when configuring content negotiation options. It accepts one or
more ContentNeogtiationStrategy instances and delegates to them.
The ContentNeogiationManager can now be used to configure the
following classes:
- RequestMappingHandlerMappingm
- RequestMappingHandlerAdapter
- ExceptionHandlerExceptionResolver
- ContentNegotiatingViewResolver
Issue: SPR-8410, SPR-8417, SPR-8418,SPR-8416, SPR-8419,SPR-7722 | spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerMapping.java | @@ -20,6 +20,8 @@
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Controller;
+import org.springframework.web.accept.ContentNegotiationManager;
+import org.springframework.web.accept.HeaderContentNegotiationStrategy;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.condition.AbstractRequestCondition;
import org.springframework.web.servlet.mvc.condition.CompositeRequestCondition;
@@ -48,6 +50,8 @@ public class RequestMappingHandlerMapping extends RequestMappingInfoHandlerMappi
private boolean useTrailingSlashMatch = true;
+ private ContentNegotiationManager contentNegotiationManager = new ContentNegotiationManager();
+
/**
* Whether to use suffix pattern match (".*") when matching patterns to
* requests. If enabled a method mapped to "/users" also matches to "/users.*".
@@ -66,6 +70,14 @@ public void setUseTrailingSlashMatch(boolean useTrailingSlashMatch) {
this.useTrailingSlashMatch = useTrailingSlashMatch;
}
+ /**
+ * Set the {@link ContentNegotiationManager} to use to determine requested media types.
+ * If not set, the default constructor is used.
+ */
+ public void setContentNegotiationManager(ContentNegotiationManager contentNegotiationManager) {
+ this.contentNegotiationManager = contentNegotiationManager;
+ }
+
/**
* Whether to use suffix pattern matching.
*/
@@ -79,6 +91,13 @@ public boolean useTrailingSlashMatch() {
return this.useTrailingSlashMatch;
}
+ /**
+ * Return the configured {@link ContentNegotiationManager}.
+ */
+ public ContentNegotiationManager getContentNegotiationManager() {
+ return contentNegotiationManager;
+ }
+
/**
* {@inheritDoc}
* Expects a handler to have a type-level @{@link Controller} annotation.
@@ -160,7 +179,7 @@ private RequestMappingInfo createRequestMappingInfo(RequestMapping annotation, R
new ParamsRequestCondition(annotation.params()),
new HeadersRequestCondition(annotation.headers()),
new ConsumesRequestCondition(annotation.consumes(), annotation.headers()),
- new ProducesRequestCondition(annotation.produces(), annotation.headers()),
+ new ProducesRequestCondition(annotation.produces(), annotation.headers(), getContentNegotiationManager()),
customCondition);
}
| true |
Other | spring-projects | spring-framework | f05e2bc56f8e03466977d73a5e99c37651248803.json | Add abstractions for content negotiation
Introduced ContentNeogtiationStrategy for resolving the requested
media types from an incoming request. The available implementations
are based on path extension, request parameter, 'Accept' header,
and a fixed default content type. The logic for these implementations
is based on equivalent options, previously available only in the
ContentNegotiatingViewResolver.
Also in this commit is ContentNegotiationManager, the central class to
use when configuring content negotiation options. It accepts one or
more ContentNeogtiationStrategy instances and delegates to them.
The ContentNeogiationManager can now be used to configure the
following classes:
- RequestMappingHandlerMappingm
- RequestMappingHandlerAdapter
- ExceptionHandlerExceptionResolver
- ContentNegotiatingViewResolver
Issue: SPR-8410, SPR-8417, SPR-8418,SPR-8416, SPR-8419,SPR-7722 | spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestResponseBodyMethodProcessor.java | @@ -29,6 +29,7 @@
import org.springframework.validation.BindingResult;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
+import org.springframework.web.accept.ContentNegotiationManager;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.RequestBody;
@@ -60,6 +61,12 @@ public RequestResponseBodyMethodProcessor(List<HttpMessageConverter<?>> messageC
super(messageConverters);
}
+ public RequestResponseBodyMethodProcessor(List<HttpMessageConverter<?>> messageConverters,
+ ContentNegotiationManager contentNegotiationManager) {
+
+ super(messageConverters, contentNegotiationManager);
+ }
+
public boolean supportsParameter(MethodParameter parameter) {
return parameter.hasParameterAnnotation(RequestBody.class);
} | true |
Other | spring-projects | spring-framework | f05e2bc56f8e03466977d73a5e99c37651248803.json | Add abstractions for content negotiation
Introduced ContentNeogtiationStrategy for resolving the requested
media types from an incoming request. The available implementations
are based on path extension, request parameter, 'Accept' header,
and a fixed default content type. The logic for these implementations
is based on equivalent options, previously available only in the
ContentNegotiatingViewResolver.
Also in this commit is ContentNegotiationManager, the central class to
use when configuring content negotiation options. It accepts one or
more ContentNeogtiationStrategy instances and delegates to them.
The ContentNeogiationManager can now be used to configure the
following classes:
- RequestMappingHandlerMappingm
- RequestMappingHandlerAdapter
- ExceptionHandlerExceptionResolver
- ContentNegotiatingViewResolver
Issue: SPR-8410, SPR-8417, SPR-8418,SPR-8416, SPR-8419,SPR-7722 | spring-webmvc/src/main/java/org/springframework/web/servlet/view/ContentNegotiatingViewResolver.java | @@ -16,48 +16,47 @@
package org.springframework.web.servlet.view;
-import java.io.IOException;
-import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
+import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
-import java.util.Map.Entry;
import java.util.Set;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
+
import javax.activation.FileTypeMap;
-import javax.activation.MimetypesFileTypeMap;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-
import org.springframework.beans.factory.BeanFactoryUtils;
+import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.OrderComparator;
import org.springframework.core.Ordered;
-import org.springframework.core.io.ClassPathResource;
-import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
-import org.springframework.util.ClassUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
+import org.springframework.web.HttpMediaTypeNotAcceptableException;
+import org.springframework.web.accept.ContentNegotiationManager;
+import org.springframework.web.accept.FixedContentNegotiationStrategy;
+import org.springframework.web.accept.PathExtensionContentNegotiationStrategy;
+import org.springframework.web.accept.HeaderContentNegotiationStrategy;
+import org.springframework.web.accept.ParameterContentNegotiationStrategy;
+import org.springframework.web.accept.ContentNegotiationStrategy;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
+import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.context.support.WebApplicationObjectSupport;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.SmartView;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;
-import org.springframework.web.util.UrlPathHelper;
-import org.springframework.web.util.WebUtils;
/**
* Implementation of {@link ViewResolver} that resolves a view based on the request file name or {@code Accept} header.
@@ -69,23 +68,8 @@
* property needs to be set to a higher precedence than the others (the default is {@link Ordered#HIGHEST_PRECEDENCE}.)
*
* <p>This view resolver uses the requested {@linkplain MediaType media type} to select a suitable {@link View} for a
- * request. This media type is determined by using the following criteria:
- * <ol>
- * <li>If the requested path has a file extension and if the {@link #setFavorPathExtension} property is
- * {@code true}, the {@link #setMediaTypes(Map) mediaTypes} property is inspected for a matching media type.</li>
- * <li>If the request contains a parameter defining the extension and if the {@link #setFavorParameter}
- * property is <code>true</code>, the {@link #setMediaTypes(Map) mediaTypes} property is inspected for a matching
- * media type. The default name of the parameter is <code>format</code> and it can be configured using the
- * {@link #setParameterName(String) parameterName} property.</li>
- * <li>If there is no match in the {@link #setMediaTypes(Map) mediaTypes} property and if the Java Activation
- * Framework (JAF) is both {@linkplain #setUseJaf enabled} and present on the classpath,
- * {@link FileTypeMap#getContentType(String)} is used instead.</li>
- * <li>If the previous steps did not result in a media type, and
- * {@link #setIgnoreAcceptHeader ignoreAcceptHeader} is {@code false}, the request {@code Accept} header is
- * used.</li>
- * </ol>
- *
- * <p>Once the requested media type has been determined, this resolver queries each delegate view resolver for a
+ * request. The requested media type is determined through the configured {@link ContentNegotiationManager}.
+ * Once the requested media type has been determined, this resolver queries each delegate view resolver for a
* {@link View} and determines if the requested media type is {@linkplain MediaType#includes(MediaType) compatible}
* with the view's {@linkplain View#getContentType() content type}). The most compatible view is returned.
*
@@ -107,44 +91,33 @@
* @see InternalResourceViewResolver
* @see BeanNameViewResolver
*/
-public class ContentNegotiatingViewResolver extends WebApplicationObjectSupport implements ViewResolver, Ordered {
+public class ContentNegotiatingViewResolver extends WebApplicationObjectSupport implements ViewResolver, Ordered, InitializingBean {
private static final Log logger = LogFactory.getLog(ContentNegotiatingViewResolver.class);
- private static final String ACCEPT_HEADER = "Accept";
-
- private static final boolean jafPresent =
- ClassUtils.isPresent("javax.activation.FileTypeMap", ContentNegotiatingViewResolver.class.getClassLoader());
-
- private static final UrlPathHelper urlPathHelper = new UrlPathHelper();
-
- static {
- urlPathHelper.setUrlDecode(false);
- }
-
private int order = Ordered.HIGHEST_PRECEDENCE;
- private boolean favorPathExtension = true;
+ private ContentNegotiationManager contentNegotiationManager;
+ private boolean favorPathExtension = true;
private boolean favorParameter = false;
-
- private String parameterName = "format";
-
- private boolean useNotAcceptableStatusCode = false;
-
private boolean ignoreAcceptHeader = false;
+ private Map<String, String> mediaTypes = new HashMap<String, String>();
+ private Boolean useJaf;
+ private String parameterName;
+ private MediaType defaultContentType;
- private boolean useJaf = jafPresent;
-
- private ConcurrentMap<String, MediaType> mediaTypes = new ConcurrentHashMap<String, MediaType>();
+ private boolean useNotAcceptableStatusCode = false;
private List<View> defaultViews;
- private MediaType defaultContentType;
-
private List<ViewResolver> viewResolvers;
+ public ContentNegotiatingViewResolver() {
+ super();
+ }
+
public void setOrder(int order) {
this.order = order;
}
@@ -153,23 +126,45 @@ public int getOrder() {
return this.order;
}
+ /**
+ * Set the {@link ContentNegotiationManager} to use to determine requested media types.
+ * If not set, the default constructor is used.
+ */
+ public void setContentNegotiationManager(ContentNegotiationManager contentNegotiationManager) {
+ this.contentNegotiationManager = contentNegotiationManager;
+ }
+
/**
* Indicate whether the extension of the request path should be used to determine the requested media type,
* in favor of looking at the {@code Accept} header. The default value is {@code true}.
* <p>For instance, when this flag is <code>true</code> (the default), a request for {@code /hotels.pdf}
* will result in an {@code AbstractPdfView} being resolved, while the {@code Accept} header can be the
* browser-defined {@code text/html,application/xhtml+xml}.
+ *
+ * @deprecated use {@link #setContentNegotiationManager(ContentNegotiationManager)}
*/
public void setFavorPathExtension(boolean favorPathExtension) {
this.favorPathExtension = favorPathExtension;
}
+ /**
+ * Indicate whether to use the Java Activation Framework to map from file extensions to media types.
+ * <p>Default is {@code true}, i.e. the Java Activation Framework is used (if available).
+ *
+ * @deprecated use {@link #setContentNegotiationManager(ContentNegotiationManager)}
+ */
+ public void setUseJaf(boolean useJaf) {
+ this.useJaf = useJaf;
+ }
+
/**
* Indicate whether a request parameter should be used to determine the requested media type,
* in favor of looking at the {@code Accept} header. The default value is {@code false}.
* <p>For instance, when this flag is <code>true</code>, a request for {@code /hotels?format=pdf} will result
* in an {@code AbstractPdfView} being resolved, while the {@code Accept} header can be the browser-defined
* {@code text/html,application/xhtml+xml}.
+ *
+ * @deprecated use {@link #setContentNegotiationManager(ContentNegotiationManager)}
*/
public void setFavorParameter(boolean favorParameter) {
this.favorParameter = favorParameter;
@@ -178,6 +173,8 @@ public void setFavorParameter(boolean favorParameter) {
/**
* Set the parameter name that can be used to determine the requested media type if the {@link
* #setFavorParameter} property is {@code true}. The default parameter name is {@code format}.
+ *
+ * @deprecated use {@link #setContentNegotiationManager(ContentNegotiationManager)}
*/
public void setParameterName(String parameterName) {
this.parameterName = parameterName;
@@ -188,61 +185,54 @@ public void setParameterName(String parameterName) {
* <p>If set to {@code true}, this view resolver will only refer to the file extension and/or
* parameter, as indicated by the {@link #setFavorPathExtension favorPathExtension} and
* {@link #setFavorParameter favorParameter} properties.
+ *
+ * @deprecated use {@link #setContentNegotiationManager(ContentNegotiationManager)}
*/
public void setIgnoreAcceptHeader(boolean ignoreAcceptHeader) {
this.ignoreAcceptHeader = ignoreAcceptHeader;
}
- /**
- * Indicate whether a {@link HttpServletResponse#SC_NOT_ACCEPTABLE 406 Not Acceptable}
- * status code should be returned if no suitable view can be found.
- * <p>Default is {@code false}, meaning that this view resolver returns {@code null} for
- * {@link #resolveViewName(String, Locale)} when an acceptable view cannot be found.
- * This will allow for view resolvers chaining. When this property is set to {@code true},
- * {@link #resolveViewName(String, Locale)} will respond with a view that sets the
- * response status to {@code 406 Not Acceptable} instead.
- */
- public void setUseNotAcceptableStatusCode(boolean useNotAcceptableStatusCode) {
- this.useNotAcceptableStatusCode = useNotAcceptableStatusCode;
- }
-
/**
* Set the mapping from file extensions to media types.
* <p>When this mapping is not set or when an extension is not present, this view resolver
* will fall back to using a {@link FileTypeMap} when the Java Action Framework is available.
+ *
+ * @deprecated use {@link #setContentNegotiationManager(ContentNegotiationManager)}
*/
public void setMediaTypes(Map<String, String> mediaTypes) {
- Assert.notNull(mediaTypes, "'mediaTypes' must not be null");
- for (Map.Entry<String, String> entry : mediaTypes.entrySet()) {
- String extension = entry.getKey().toLowerCase(Locale.ENGLISH);
- MediaType mediaType = MediaType.parseMediaType(entry.getValue());
- this.mediaTypes.put(extension, mediaType);
- }
- }
-
- /**
- * Set the default views to use when a more specific view can not be obtained
- * from the {@link ViewResolver} chain.
- */
- public void setDefaultViews(List<View> defaultViews) {
- this.defaultViews = defaultViews;
+ this.mediaTypes = mediaTypes;
}
/**
* Set the default content type.
* <p>This content type will be used when file extension, parameter, nor {@code Accept}
* header define a content-type, either through being disabled or empty.
+ *
+ * @deprecated use {@link #setContentNegotiationManager(ContentNegotiationManager)}
*/
public void setDefaultContentType(MediaType defaultContentType) {
this.defaultContentType = defaultContentType;
}
/**
- * Indicate whether to use the Java Activation Framework to map from file extensions to media types.
- * <p>Default is {@code true}, i.e. the Java Activation Framework is used (if available).
+ * Indicate whether a {@link HttpServletResponse#SC_NOT_ACCEPTABLE 406 Not Acceptable}
+ * status code should be returned if no suitable view can be found.
+ * <p>Default is {@code false}, meaning that this view resolver returns {@code null} for
+ * {@link #resolveViewName(String, Locale)} when an acceptable view cannot be found.
+ * This will allow for view resolvers chaining. When this property is set to {@code true},
+ * {@link #resolveViewName(String, Locale)} will respond with a view that sets the
+ * response status to {@code 406 Not Acceptable} instead.
*/
- public void setUseJaf(boolean useJaf) {
- this.useJaf = useJaf;
+ public void setUseNotAcceptableStatusCode(boolean useNotAcceptableStatusCode) {
+ this.useNotAcceptableStatusCode = useNotAcceptableStatusCode;
+ }
+
+ /**
+ * Set the default views to use when a more specific view can not be obtained
+ * from the {@link ViewResolver} chain.
+ */
+ public void setDefaultViews(List<View> defaultViews) {
+ this.defaultViews = defaultViews;
}
/**
@@ -283,6 +273,32 @@ protected void initServletContext(ServletContext servletContext) {
OrderComparator.sort(this.viewResolvers);
}
+ public void afterPropertiesSet() throws Exception {
+ if (this.contentNegotiationManager == null) {
+ List<ContentNegotiationStrategy> strategies = new ArrayList<ContentNegotiationStrategy>();
+ if (this.favorPathExtension) {
+ PathExtensionContentNegotiationStrategy strategy = new PathExtensionContentNegotiationStrategy(this.mediaTypes);
+ if (this.useJaf != null) {
+ strategy.setUseJaf(this.useJaf);
+ }
+ strategies.add(strategy);
+ }
+ if (this.favorParameter) {
+ ParameterContentNegotiationStrategy strategy = new ParameterContentNegotiationStrategy(this.mediaTypes);
+ strategy.setParameterName(this.parameterName);
+ strategies.add(strategy);
+ }
+ if (!this.ignoreAcceptHeader) {
+ strategies.add(new HeaderContentNegotiationStrategy());
+ }
+ if (this.defaultContentType != null) {
+ strategies.add(new FixedContentNegotiationStrategy(this.defaultContentType));
+ }
+ ContentNegotiationStrategy[] array = strategies.toArray(new ContentNegotiationStrategy[strategies.size()]);
+ this.contentNegotiationManager = new ContentNegotiationManager(array);
+ }
+ }
+
public View resolveViewName(String viewName, Locale locale) throws Exception {
RequestAttributes attrs = RequestContextHolder.getRequestAttributes();
Assert.isInstanceOf(ServletRequestAttributes.class, attrs);
@@ -317,69 +333,28 @@ public View resolveViewName(String viewName, Locale locale) throws Exception {
* @return the list of media types requested, if any
*/
protected List<MediaType> getMediaTypes(HttpServletRequest request) {
- if (this.favorPathExtension) {
- String requestUri = urlPathHelper.getLookupPathForRequest(request);
- String filename = WebUtils.extractFullFilenameFromUrlPath(requestUri);
- MediaType mediaType = getMediaTypeFromFilename(filename);
- if (mediaType != null) {
- if (logger.isDebugEnabled()) {
- logger.debug("Requested media type is '" + mediaType + "' (based on filename '" + filename + "')");
- }
- return Collections.singletonList(mediaType);
- }
- }
- if (this.favorParameter) {
- if (request.getParameter(this.parameterName) != null) {
- String parameterValue = request.getParameter(this.parameterName);
- MediaType mediaType = getMediaTypeFromParameter(parameterValue);
- if (mediaType != null) {
- if (logger.isDebugEnabled()) {
- logger.debug("Requested media type is '" + mediaType + "' (based on parameter '" +
- this.parameterName + "'='" + parameterValue + "')");
- }
- return Collections.singletonList(mediaType);
- }
- }
- }
- if (!this.ignoreAcceptHeader) {
- String acceptHeader = request.getHeader(ACCEPT_HEADER);
- if (StringUtils.hasText(acceptHeader)) {
- try {
- List<MediaType> acceptableMediaTypes = MediaType.parseMediaTypes(acceptHeader);
- List<MediaType> producibleMediaTypes = getProducibleMediaTypes(request);
- Set<MediaType> compatibleMediaTypes = new LinkedHashSet<MediaType>();
- for (MediaType acceptable : acceptableMediaTypes) {
- for (MediaType producible : producibleMediaTypes) {
- if (acceptable.isCompatibleWith(producible)) {
- compatibleMediaTypes.add(getMostSpecificMediaType(acceptable, producible));
- }
- }
- }
- List<MediaType> selectedMediaTypes = new ArrayList<MediaType>(compatibleMediaTypes);
- MediaType.sortBySpecificityAndQuality(selectedMediaTypes);
- if (logger.isDebugEnabled()) {
- logger.debug("Requested media types are " + selectedMediaTypes + " based on Accept header types " +
- "and producible media types " + producibleMediaTypes + ")");
+ try {
+ ServletWebRequest webRequest = new ServletWebRequest(request);
+ List<MediaType> acceptableMediaTypes = this.contentNegotiationManager.resolveMediaTypes(webRequest);
+ List<MediaType> producibleMediaTypes = getProducibleMediaTypes(request);
+ Set<MediaType> compatibleMediaTypes = new LinkedHashSet<MediaType>();
+ for (MediaType acceptable : acceptableMediaTypes) {
+ for (MediaType producible : producibleMediaTypes) {
+ if (acceptable.isCompatibleWith(producible)) {
+ compatibleMediaTypes.add(getMostSpecificMediaType(acceptable, producible));
}
- return selectedMediaTypes;
- }
- catch (IllegalArgumentException ex) {
- if (logger.isDebugEnabled()) {
- logger.debug("Could not parse accept header [" + acceptHeader + "]: " + ex.getMessage());
- }
- return null;
}
}
- }
- if (this.defaultContentType != null) {
+ List<MediaType> selectedMediaTypes = new ArrayList<MediaType>(compatibleMediaTypes);
+ MediaType.sortBySpecificityAndQuality(selectedMediaTypes);
if (logger.isDebugEnabled()) {
- logger.debug("Requested media types is " + this.defaultContentType +
- " (based on defaultContentType property)");
+ logger.debug("Requested media types are " + selectedMediaTypes + " based on Accept header types " +
+ "and producible media types " + producibleMediaTypes + ")");
}
- return Collections.singletonList(this.defaultContentType);
+ return selectedMediaTypes;
}
- else {
- return Collections.emptyList();
+ catch (HttpMediaTypeNotAcceptableException ex) {
+ return null;
}
}
@@ -404,52 +379,6 @@ private MediaType getMostSpecificMediaType(MediaType acceptType, MediaType produ
return MediaType.SPECIFICITY_COMPARATOR.compare(acceptType, produceType) < 0 ? acceptType : produceType;
}
- /**
- * Determines the {@link MediaType} for the given filename.
- * <p>The default implementation will check the {@linkplain #setMediaTypes(Map) media types}
- * property first for a defined mapping. If not present, and if the Java Activation Framework
- * can be found on the classpath, it will call {@link FileTypeMap#getContentType(String)}
- * <p>This method can be overridden to provide a different algorithm.
- * @param filename the current request file name (i.e. {@code hotels.html})
- * @return the media type, if any
- */
- protected MediaType getMediaTypeFromFilename(String filename) {
- String extension = StringUtils.getFilenameExtension(filename);
- if (!StringUtils.hasText(extension)) {
- return null;
- }
- extension = extension.toLowerCase(Locale.ENGLISH);
- MediaType mediaType = this.mediaTypes.get(extension);
- if (mediaType == null) {
- String mimeType = getServletContext().getMimeType(filename);
- if (StringUtils.hasText(mimeType)) {
- mediaType = MediaType.parseMediaType(mimeType);
- }
- if (this.useJaf && (mediaType == null || MediaType.APPLICATION_OCTET_STREAM.equals(mediaType))) {
- MediaType jafMediaType = ActivationMediaTypeFactory.getMediaType(filename);
- if (jafMediaType != null && !MediaType.APPLICATION_OCTET_STREAM.equals(jafMediaType)) {
- mediaType = jafMediaType;
- }
- }
- if (mediaType != null) {
- this.mediaTypes.putIfAbsent(extension, mediaType);
- }
- }
- return mediaType;
- }
-
- /**
- * Determines the {@link MediaType} for the given parameter value.
- * <p>The default implementation will check the {@linkplain #setMediaTypes(Map) media types}
- * property for a defined mapping.
- * <p>This method can be overriden to provide a different algorithm.
- * @param parameterValue the parameter value (i.e. {@code pdf}).
- * @return the media type, if any
- */
- protected MediaType getMediaTypeFromParameter(String parameterValue) {
- return this.mediaTypes.get(parameterValue.toLowerCase(Locale.ENGLISH));
- }
-
private List<View> getCandidateViews(String viewName, Locale locale, List<MediaType> requestedMediaTypes)
throws Exception {
@@ -460,15 +389,14 @@ private List<View> getCandidateViews(String viewName, Locale locale, List<MediaT
candidateViews.add(view);
}
for (MediaType requestedMediaType : requestedMediaTypes) {
- List<String> extensions = getExtensionsForMediaType(requestedMediaType);
+ List<String> extensions = this.contentNegotiationManager.resolveExtensions(requestedMediaType);
for (String extension : extensions) {
String viewNameWithExtension = viewName + "." + extension;
view = viewResolver.resolveViewName(viewNameWithExtension, locale);
if (view != null) {
candidateViews.add(view);
}
}
-
}
}
if (!CollectionUtils.isEmpty(this.defaultViews)) {
@@ -477,16 +405,6 @@ private List<View> getCandidateViews(String viewName, Locale locale, List<MediaT
return candidateViews;
}
- private List<String> getExtensionsForMediaType(MediaType requestedMediaType) {
- List<String> result = new ArrayList<String>();
- for (Entry<String, MediaType> entry : this.mediaTypes.entrySet()) {
- if (requestedMediaType.includes(entry.getValue())) {
- result.add(entry.getKey());
- }
- }
- return result;
- }
-
private View getBestView(List<View> candidateViews, List<MediaType> requestedMediaTypes) {
for (View candidateView : candidateViews) {
if (candidateView instanceof SmartView) {
@@ -528,54 +446,4 @@ public void render(Map<String, ?> model, HttpServletRequest request, HttpServlet
}
};
-
- /**
- * Inner class to avoid hard-coded JAF dependency.
- */
- private static class ActivationMediaTypeFactory {
-
- private static final FileTypeMap fileTypeMap;
-
- static {
- fileTypeMap = loadFileTypeMapFromContextSupportModule();
- }
-
- private static FileTypeMap loadFileTypeMapFromContextSupportModule() {
- // see if we can find the extended mime.types from the context-support module
- Resource mappingLocation = new ClassPathResource("org/springframework/mail/javamail/mime.types");
- if (mappingLocation.exists()) {
- if (logger.isTraceEnabled()) {
- logger.trace("Loading Java Activation Framework FileTypeMap from " + mappingLocation);
- }
- InputStream inputStream = null;
- try {
- inputStream = mappingLocation.getInputStream();
- return new MimetypesFileTypeMap(inputStream);
- }
- catch (IOException ex) {
- // ignore
- }
- finally {
- if (inputStream != null) {
- try {
- inputStream.close();
- }
- catch (IOException ex) {
- // ignore
- }
- }
- }
- }
- if (logger.isTraceEnabled()) {
- logger.trace("Loading default Java Activation Framework FileTypeMap");
- }
- return FileTypeMap.getDefaultFileTypeMap();
- }
-
- public static MediaType getMediaType(String filename) {
- String mediaType = fileTypeMap.getContentType(filename);
- return (StringUtils.hasText(mediaType) ? MediaType.parseMediaType(mediaType) : null);
- }
- }
-
} | true |
Other | spring-projects | spring-framework | f05e2bc56f8e03466977d73a5e99c37651248803.json | Add abstractions for content negotiation
Introduced ContentNeogtiationStrategy for resolving the requested
media types from an incoming request. The available implementations
are based on path extension, request parameter, 'Accept' header,
and a fixed default content type. The logic for these implementations
is based on equivalent options, previously available only in the
ContentNegotiatingViewResolver.
Also in this commit is ContentNegotiationManager, the central class to
use when configuring content negotiation options. It accepts one or
more ContentNeogtiationStrategy instances and delegates to them.
The ContentNeogiationManager can now be used to configure the
following classes:
- RequestMappingHandlerMappingm
- RequestMappingHandlerAdapter
- ExceptionHandlerExceptionResolver
- ContentNegotiatingViewResolver
Issue: SPR-8410, SPR-8417, SPR-8418,SPR-8416, SPR-8419,SPR-7722 | spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/condition/ParamsRequestConditionTests.java | @@ -44,7 +44,7 @@ public void paramEquals() {
new ParamsRequestCondition("foo=bar").equals(new ParamsRequestCondition("FOO=bar")));
}
- @Test
+ @Test
public void paramPresent() {
ParamsRequestCondition condition = new ParamsRequestCondition("foo");
@@ -96,7 +96,7 @@ public void paramValueNoMatch() {
@Test
public void compareTo() {
MockHttpServletRequest request = new MockHttpServletRequest();
-
+
ParamsRequestCondition condition1 = new ParamsRequestCondition("foo", "bar", "baz");
ParamsRequestCondition condition2 = new ParamsRequestCondition("foo", "bar");
| true |
Other | spring-projects | spring-framework | f05e2bc56f8e03466977d73a5e99c37651248803.json | Add abstractions for content negotiation
Introduced ContentNeogtiationStrategy for resolving the requested
media types from an incoming request. The available implementations
are based on path extension, request parameter, 'Accept' header,
and a fixed default content type. The logic for these implementations
is based on equivalent options, previously available only in the
ContentNegotiatingViewResolver.
Also in this commit is ContentNegotiationManager, the central class to
use when configuring content negotiation options. It accepts one or
more ContentNeogtiationStrategy instances and delegates to them.
The ContentNeogiationManager can now be used to configure the
following classes:
- RequestMappingHandlerMappingm
- RequestMappingHandlerAdapter
- ExceptionHandlerExceptionResolver
- ContentNegotiatingViewResolver
Issue: SPR-8410, SPR-8417, SPR-8418,SPR-8416, SPR-8419,SPR-7722 | spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/condition/ProducesRequestConditionTests.java | @@ -36,7 +36,7 @@
public class ProducesRequestConditionTests {
@Test
- public void producesMatch() {
+ public void match() {
ProducesRequestCondition condition = new ProducesRequestCondition("text/plain");
MockHttpServletRequest request = new MockHttpServletRequest();
@@ -46,7 +46,7 @@ public void producesMatch() {
}
@Test
- public void negatedProducesMatch() {
+ public void matchNegated() {
ProducesRequestCondition condition = new ProducesRequestCondition("!text/plain");
MockHttpServletRequest request = new MockHttpServletRequest();
@@ -56,13 +56,13 @@ public void negatedProducesMatch() {
}
@Test
- public void getProducibleMediaTypesNegatedExpression() {
+ public void getProducibleMediaTypes() {
ProducesRequestCondition condition = new ProducesRequestCondition("!application/xml");
assertEquals(Collections.emptySet(), condition.getProducibleMediaTypes());
}
@Test
- public void producesWildcardMatch() {
+ public void matchWildcard() {
ProducesRequestCondition condition = new ProducesRequestCondition("text/*");
MockHttpServletRequest request = new MockHttpServletRequest();
@@ -72,7 +72,7 @@ public void producesWildcardMatch() {
}
@Test
- public void producesMultipleMatch() {
+ public void matchMultiple() {
ProducesRequestCondition condition = new ProducesRequestCondition("text/plain", "application/xml");
MockHttpServletRequest request = new MockHttpServletRequest();
@@ -82,7 +82,7 @@ public void producesMultipleMatch() {
}
@Test
- public void producesSingleNoMatch() {
+ public void matchSingle() {
ProducesRequestCondition condition = new ProducesRequestCondition("text/plain");
MockHttpServletRequest request = new MockHttpServletRequest();
@@ -92,7 +92,7 @@ public void producesSingleNoMatch() {
}
@Test
- public void producesParseError() {
+ public void matchParseError() {
ProducesRequestCondition condition = new ProducesRequestCondition("text/plain");
MockHttpServletRequest request = new MockHttpServletRequest();
@@ -102,7 +102,7 @@ public void producesParseError() {
}
@Test
- public void producesParseErrorWithNegation() {
+ public void matchParseErrorWithNegation() {
ProducesRequestCondition condition = new ProducesRequestCondition("!text/plain");
MockHttpServletRequest request = new MockHttpServletRequest();
@@ -111,6 +111,15 @@ public void producesParseErrorWithNegation() {
assertNull(condition.getMatchingCondition(request));
}
+ @Test
+ public void matchByRequestParameter() {
+ ProducesRequestCondition condition = new ProducesRequestCondition(new String[] {"text/plain"}, new String[] {});
+
+ MockHttpServletRequest request = new MockHttpServletRequest("GET", "/foo.txt");
+
+ assertNotNull(condition.getMatchingCondition(request));
+ }
+
@Test
public void compareTo() {
ProducesRequestCondition html = new ProducesRequestCondition("text/html");
@@ -286,7 +295,7 @@ public void combineWithDefault() {
}
@Test
- public void parseProducesAndHeaders() {
+ public void instantiateWithProducesAndHeaderConditions() {
String[] produces = new String[] {"text/plain"};
String[] headers = new String[]{"foo=bar", "accept=application/xml,application/pdf"};
ProducesRequestCondition condition = new ProducesRequestCondition(produces, headers);
@@ -312,7 +321,7 @@ public void getMatchingCondition() {
private void assertConditions(ProducesRequestCondition condition, String... expected) {
Collection<ProduceMediaTypeExpression> expressions = condition.getContent();
- assertEquals("Invalid amount of conditions", expressions.size(), expected.length);
+ assertEquals("Invalid number of conditions", expressions.size(), expected.length);
for (String s : expected) {
boolean found = false;
for (ProduceMediaTypeExpression expr : expressions) { | true |
Other | spring-projects | spring-framework | f05e2bc56f8e03466977d73a5e99c37651248803.json | Add abstractions for content negotiation
Introduced ContentNeogtiationStrategy for resolving the requested
media types from an incoming request. The available implementations
are based on path extension, request parameter, 'Accept' header,
and a fixed default content type. The logic for these implementations
is based on equivalent options, previously available only in the
ContentNegotiatingViewResolver.
Also in this commit is ContentNegotiationManager, the central class to
use when configuring content negotiation options. It accepts one or
more ContentNeogtiationStrategy instances and delegates to them.
The ContentNeogiationManager can now be used to configure the
following classes:
- RequestMappingHandlerMappingm
- RequestMappingHandlerAdapter
- ExceptionHandlerExceptionResolver
- ContentNegotiatingViewResolver
Issue: SPR-8410, SPR-8417, SPR-8418,SPR-8416, SPR-8419,SPR-7722 | spring-webmvc/src/test/java/org/springframework/web/servlet/view/ContentNegotiatingViewResolverTests.java | @@ -24,12 +24,10 @@
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
-import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
@@ -42,6 +40,12 @@
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockServletContext;
+import org.springframework.web.accept.ContentNegotiationManager;
+import org.springframework.web.accept.FixedContentNegotiationStrategy;
+import org.springframework.web.accept.HeaderContentNegotiationStrategy;
+import org.springframework.web.accept.MappingMediaTypeExtensionsResolver;
+import org.springframework.web.accept.ParameterContentNegotiationStrategy;
+import org.springframework.web.accept.PathExtensionContentNegotiationStrategy;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.support.StaticWebApplicationContext;
@@ -75,104 +79,22 @@ public void resetRequestContextHolder() {
}
@Test
- public void getMediaTypeFromFilenameMediaTypes() {
- viewResolver.setMediaTypes(Collections.singletonMap("HTML", "application/xhtml+xml"));
- assertEquals("Invalid content type", new MediaType("application", "xhtml+xml"),
- viewResolver.getMediaTypeFromFilename("test.html"));
- }
-
- @Test
- public void getMediaTypeFromFilenameJaf() {
- assertEquals("Invalid content type", new MediaType("application", "vnd.ms-excel"),
- viewResolver.getMediaTypeFromFilename("test.xls"));
- }
-
- @Test
- public void getMediaTypeFromFilenameNoJaf() {
- viewResolver.setUseJaf(false);
- assertEquals("Invalid content type", MediaType.APPLICATION_OCTET_STREAM,
- viewResolver.getMediaTypeFromFilename("test.xls"));
- }
-
- @Test
- public void getMediaTypeFilename() {
- request.setRequestURI("/test.html?foo=bar");
- List<MediaType> result = viewResolver.getMediaTypes(request);
- assertEquals("Invalid content type", Collections.singletonList(new MediaType("text", "html")), result);
- viewResolver.setMediaTypes(Collections.singletonMap("html", "application/xhtml+xml"));
- result = viewResolver.getMediaTypes(request);
- assertEquals("Invalid content type", Collections.singletonList(new MediaType("application", "xhtml+xml")),
- result);
- }
-
- // SPR-8678
-
- @Test
- public void getMediaTypeFilenameWithContextPath() {
- request.setContextPath("/project-1.0.0.M3");
- request.setRequestURI("/project-1.0.0.M3/");
- assertTrue("Context path should be excluded", viewResolver.getMediaTypes(request).isEmpty());
- request.setRequestURI("/project-1.0.0.M3");
- assertTrue("Context path should be excluded", viewResolver.getMediaTypes(request).isEmpty());
- }
-
- // SPR-9390
-
- @Test
- public void getMediaTypeFilenameWithEncodedURI() {
- request.setRequestURI("/quo%20vadis%3f.html");
- List<MediaType> result = viewResolver.getMediaTypes(request);
- assertEquals("Invalid content type", Collections.singletonList(new MediaType("text", "html")), result);
- }
-
- @Test
- public void getMediaTypeParameter() {
- viewResolver.setFavorParameter(true);
- viewResolver.setMediaTypes(Collections.singletonMap("html", "application/xhtml+xml"));
- request.addParameter("format", "html");
- List<MediaType> result = viewResolver.getMediaTypes(request);
- assertEquals("Invalid content type", Collections.singletonList(new MediaType("application", "xhtml+xml")),
- result);
- }
-
- @Test
- public void getMediaTypeAcceptHeader() {
- request.addHeader("Accept", "text/html,application/xml;q=0.9,application/xhtml+xml,*/*;q=0.8");
- List<MediaType> result = viewResolver.getMediaTypes(request);
- assertEquals("Invalid amount of media types", 4, result.size());
- assertEquals("Invalid content type", new MediaType("text", "html"), result.get(0));
- assertEquals("Invalid content type", new MediaType("application", "xhtml+xml"), result.get(1));
- assertEquals("Invalid content type", new MediaType("application", "xml", Collections.singletonMap("q", "0.9")),
- result.get(2));
- assertEquals("Invalid content type", new MediaType("*", "*", Collections.singletonMap("q", "0.8")),
- result.get(3));
- }
-
- @Test
- public void getMediaTypeAcceptHeaderWithProduces() {
+ public void getMediaTypeAcceptHeaderWithProduces() throws Exception {
Set<MediaType> producibleTypes = Collections.singleton(MediaType.APPLICATION_XHTML_XML);
request.setAttribute(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE, producibleTypes);
request.addHeader("Accept", "text/html,application/xml;q=0.9,application/xhtml+xml,*/*;q=0.8");
+ viewResolver.afterPropertiesSet();
List<MediaType> result = viewResolver.getMediaTypes(request);
assertEquals("Invalid content type", new MediaType("application", "xhtml+xml"), result.get(0));
}
- @Test
- public void getDefaultContentType() {
- request.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
- viewResolver.setIgnoreAcceptHeader(true);
- viewResolver.setDefaultContentType(new MediaType("application", "pdf"));
- List<MediaType> result = viewResolver.getMediaTypes(request);
- assertEquals("Invalid amount of media types", 1, result.size());
- assertEquals("Invalid content type", new MediaType("application", "pdf"), result.get(0));
- }
-
@Test
public void resolveViewNameWithPathExtension() throws Exception {
request.setRequestURI("/test.xls");
ViewResolver viewResolverMock = createMock(ViewResolver.class);
viewResolver.setViewResolvers(Collections.singletonList(viewResolverMock));
+ viewResolver.afterPropertiesSet();
View viewMock = createMock("application_xls", View.class);
@@ -195,7 +117,11 @@ public void resolveViewNameWithPathExtension() throws Exception {
public void resolveViewNameWithAcceptHeader() throws Exception {
request.addHeader("Accept", "application/vnd.ms-excel");
- viewResolver.setMediaTypes(Collections.singletonMap("xls", "application/vnd.ms-excel"));
+ Map<String, String> mapping = Collections.singletonMap("xls", "application/vnd.ms-excel");
+ MappingMediaTypeExtensionsResolver extensionsResolver = new MappingMediaTypeExtensionsResolver(mapping);
+ ContentNegotiationManager manager = new ContentNegotiationManager(new HeaderContentNegotiationStrategy());
+ manager.addExtensionsResolver(extensionsResolver);
+ viewResolver.setContentNegotiationManager(manager);
ViewResolver viewResolverMock = createMock(ViewResolver.class);
viewResolver.setViewResolvers(Collections.singletonList(viewResolverMock));
@@ -220,6 +146,7 @@ public void resolveViewNameWithAcceptHeader() throws Exception {
public void resolveViewNameWithInvalidAcceptHeader() throws Exception {
request.addHeader("Accept", "application");
+ viewResolver.afterPropertiesSet();
View result = viewResolver.resolveViewName("test", Locale.ENGLISH);
assertNull(result);
}
@@ -228,12 +155,15 @@ public void resolveViewNameWithInvalidAcceptHeader() throws Exception {
public void resolveViewNameWithRequestParameter() throws Exception {
request.addParameter("format", "xls");
- viewResolver.setFavorParameter(true);
- viewResolver.setMediaTypes(Collections.singletonMap("xls", "application/vnd.ms-excel"));
+ Map<String, String> mapping = Collections.singletonMap("xls", "application/vnd.ms-excel");
+ ParameterContentNegotiationStrategy paramStrategy = new ParameterContentNegotiationStrategy(mapping);
+ viewResolver.setContentNegotiationManager(new ContentNegotiationManager(paramStrategy));
ViewResolver viewResolverMock = createMock(ViewResolver.class);
viewResolver.setViewResolvers(Collections.singletonList(viewResolverMock));
+ viewResolver.afterPropertiesSet();
+
View viewMock = createMock("application_xls", View.class);
String viewName = "view";
@@ -255,13 +185,16 @@ public void resolveViewNameWithRequestParameter() throws Exception {
public void resolveViewNameWithDefaultContentType() throws Exception {
request.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
- viewResolver.setIgnoreAcceptHeader(true);
- viewResolver.setDefaultContentType(new MediaType("application", "xml"));
+ MediaType mediaType = new MediaType("application", "xml");
+ FixedContentNegotiationStrategy fixedStrategy = new FixedContentNegotiationStrategy(mediaType);
+ viewResolver.setContentNegotiationManager(new ContentNegotiationManager(fixedStrategy));
ViewResolver viewResolverMock1 = createMock("viewResolver1", ViewResolver.class);
ViewResolver viewResolverMock2 = createMock("viewResolver2", ViewResolver.class);
viewResolver.setViewResolvers(Arrays.asList(viewResolverMock1, viewResolverMock2));
+ viewResolver.afterPropertiesSet();
+
View viewMock1 = createMock("application_xml", View.class);
View viewMock2 = createMock("text_html", View.class);
@@ -289,6 +222,8 @@ public void resolveViewNameAcceptHeader() throws Exception {
ViewResolver viewResolverMock2 = createMock(ViewResolver.class);
viewResolver.setViewResolvers(Arrays.asList(viewResolverMock1, viewResolverMock2));
+ viewResolver.afterPropertiesSet();
+
View viewMock1 = createMock("application_xml", View.class);
View viewMock2 = createMock("text_html", View.class);
@@ -314,6 +249,8 @@ public void resolveViewNameAcceptHeader() throws Exception {
public void resolveViewNameAcceptHeaderSortByQuality() throws Exception {
request.addHeader("Accept", "text/plain;q=0.5, application/json");
+ viewResolver.setContentNegotiationManager(new ContentNegotiationManager(new HeaderContentNegotiationStrategy()));
+
ViewResolver htmlViewResolver = createMock(ViewResolver.class);
ViewResolver jsonViewResolver = createMock(ViewResolver.class);
viewResolver.setViewResolvers(Arrays.asList(htmlViewResolver, jsonViewResolver));
@@ -330,7 +267,6 @@ public void resolveViewNameAcceptHeaderSortByQuality() throws Exception {
expect(jsonViewMock.getContentType()).andReturn("application/json").anyTimes();
replay(htmlViewResolver, jsonViewResolver, htmlView, jsonViewMock);
- viewResolver.setFavorPathExtension(false);
View result = viewResolver.resolveViewName(viewName, locale);
assertSame("Invalid view", jsonViewMock, result);
@@ -353,6 +289,8 @@ public void resolveViewNameAcceptHeaderDefaultView() throws Exception {
defaultViews.add(viewMock3);
viewResolver.setDefaultViews(defaultViews);
+ viewResolver.afterPropertiesSet();
+
String viewName = "view";
Locale locale = Locale.ENGLISH;
@@ -378,6 +316,8 @@ public void resolveViewNameFilename() throws Exception {
ViewResolver viewResolverMock2 = createMock("viewResolver2", ViewResolver.class);
viewResolver.setViewResolvers(Arrays.asList(viewResolverMock1, viewResolverMock2));
+ viewResolver.afterPropertiesSet();
+
View viewMock1 = createMock("application_xml", View.class);
View viewMock2 = createMock("text_html", View.class);
@@ -403,9 +343,10 @@ public void resolveViewNameFilename() throws Exception {
public void resolveViewNameFilenameDefaultView() throws Exception {
request.setRequestURI("/test.json");
- Map<String, String> mediaTypes = new HashMap<String, String>();
- mediaTypes.put("json", "application/json");
- viewResolver.setMediaTypes(mediaTypes);
+
+ Map<String, String> mapping = Collections.singletonMap("json", "application/json");
+ PathExtensionContentNegotiationStrategy pathStrategy = new PathExtensionContentNegotiationStrategy(mapping);
+ viewResolver.setContentNegotiationManager(new ContentNegotiationManager(pathStrategy));
ViewResolver viewResolverMock1 = createMock(ViewResolver.class);
ViewResolver viewResolverMock2 = createMock(ViewResolver.class);
@@ -419,6 +360,8 @@ public void resolveViewNameFilenameDefaultView() throws Exception {
defaultViews.add(viewMock3);
viewResolver.setDefaultViews(defaultViews);
+ viewResolver.afterPropertiesSet();
+
String viewName = "view";
Locale locale = Locale.ENGLISH;
@@ -445,6 +388,8 @@ public void resolveViewContentTypeNull() throws Exception {
ViewResolver viewResolverMock = createMock(ViewResolver.class);
viewResolver.setViewResolvers(Collections.singletonList(viewResolverMock));
+ viewResolver.afterPropertiesSet();
+
View viewMock = createMock("application_xml", View.class);
String viewName = "view";
@@ -479,6 +424,8 @@ public void resolveViewNameRedirectView() throws Exception {
View jsonView = createMock("application_json", View.class);
viewResolver.setDefaultViews(Arrays.asList(jsonView));
+ viewResolver.afterPropertiesSet();
+
String viewName = "redirect:anotherTest";
Locale locale = Locale.ENGLISH;
@@ -500,6 +447,8 @@ public void resolveViewNoMatch() throws Exception {
ViewResolver viewResolverMock = createMock(ViewResolver.class);
viewResolver.setViewResolvers(Collections.singletonList(viewResolverMock));
+ viewResolver.afterPropertiesSet();
+
View viewMock = createMock("application_xml", View.class);
String viewName = "view";
@@ -524,6 +473,8 @@ public void resolveViewNoMatchUseUnacceptableStatus() throws Exception {
ViewResolver viewResolverMock = createMock(ViewResolver.class);
viewResolver.setViewResolvers(Collections.singletonList(viewResolverMock));
+ viewResolver.afterPropertiesSet();
+
View viewMock = createMock("application_xml", View.class);
String viewName = "view";
@@ -553,7 +504,11 @@ public void nestedViewResolverIsNotSpringBean() throws Exception {
nestedResolver.setApplicationContext(webAppContext);
nestedResolver.setViewClass(InternalResourceView.class);
viewResolver.setViewResolvers(new ArrayList<ViewResolver>(Arrays.asList(nestedResolver)));
- viewResolver.setDefaultContentType(MediaType.TEXT_HTML);
+
+ FixedContentNegotiationStrategy fixedStrategy = new FixedContentNegotiationStrategy(MediaType.TEXT_HTML);
+ viewResolver.setContentNegotiationManager(new ContentNegotiationManager(fixedStrategy));
+
+ viewResolver.afterPropertiesSet();
String viewName = "view";
Locale locale = Locale.ENGLISH; | true |
Other | spring-projects | spring-framework | f05e2bc56f8e03466977d73a5e99c37651248803.json | Add abstractions for content negotiation
Introduced ContentNeogtiationStrategy for resolving the requested
media types from an incoming request. The available implementations
are based on path extension, request parameter, 'Accept' header,
and a fixed default content type. The logic for these implementations
is based on equivalent options, previously available only in the
ContentNegotiatingViewResolver.
Also in this commit is ContentNegotiationManager, the central class to
use when configuring content negotiation options. It accepts one or
more ContentNeogtiationStrategy instances and delegates to them.
The ContentNeogiationManager can now be used to configure the
following classes:
- RequestMappingHandlerMappingm
- RequestMappingHandlerAdapter
- ExceptionHandlerExceptionResolver
- ContentNegotiatingViewResolver
Issue: SPR-8410, SPR-8417, SPR-8418,SPR-8416, SPR-8419,SPR-7722 | src/dist/changelog.txt | @@ -10,7 +10,7 @@ Changes in version 3.2 M2
* raise RestClientException instead of IllegalArgumentException for unknown status codes
* add JacksonObjectMapperFactoryBean for configuring a Jackson ObjectMapper in XML
* infer return type of parameterized factory methods (SPR-9493)
-
+* add ContentNegotiationManager/ContentNegotiationStrategy to resolve requested media types
Changes in version 3.2 M1 (2012-05-28)
-------------------------------------- | true |
Other | spring-projects | spring-framework | e3d8ab20883f127c0b73ab95c8794ce503a4ee42.json | Fix Javadoc typo in ConfigurableWebEnvironment | spring-web/src/main/java/org/springframework/web/context/ConfigurableWebEnvironment.java | @@ -24,7 +24,7 @@
/**
* Specialization of {@link ConfigurableEnvironment} allowing initialization of
* servlet-related {@link org.springframework.core.env.PropertySource} objects at the
- * earliest moment the {@link ServletContext} and (optionally) {@link ServletConfig}
+ * earliest moment that the {@link ServletContext} and (optionally) {@link ServletConfig}
* become available.
*
* @author Chris Beams
@@ -39,7 +39,7 @@ public interface ConfigurableWebEnvironment extends ConfigurableEnvironment {
* instances acting as placeholders with real servlet context/config property sources
* using the given parameters.
* @param servletContext the {@link ServletContext} (may not be {@code null})
- * @param servletConfig the {@link ServletContext} ({@code null} if not available)
+ * @param servletConfig the {@link ServletConfig} ({@code null} if not available)
*/
void initPropertySources(ServletContext servletContext, ServletConfig servletConfig);
| false |
Other | spring-projects | spring-framework | e5bbec7e2b322f280cffc540d3419baefd29d187.json | Add Gradle task for building zip with dependencies
Some Spring Framework users and teams cannot use transitive dependency
management tools like Maven, Gradle and Ivy. For them, a `distZip` task
has been added to allow for creating a Spring Framework distribution
from source that includes all optional and required runtime
dependencies for all modules of the framework.
This 'dist-with-deps' zip is not published to the SpringSource
repository nor to the SpringSource community download page. It is
strictly an optional task introduced as a convenience to the users
mentioned above.
Detailed instructions for building this zip locally have been added to
the wiki and the README has been updated with a link to that new doc.
Issue: SPR-6575 | README.md | @@ -15,9 +15,9 @@ The framework also serves as the foundation for
[Python](https://github.com/SpringSource/spring-python) variants are available as well.
## Downloading artifacts
-Instructions on
-[downloading Spring artifacts](https://github.com/SpringSource/spring-framework/wiki/Downloading-Spring-artifacts)
-via Maven and other build systems are available via the project wiki.
+See [downloading Spring artifacts](https://github.com/SpringSource/spring-framework/wiki/Downloading-Spring-artifacts)
+for Maven repository information. Unable to use Maven or other transitive dependency management tools?
+See [building a distribution with dependencies](https://github.com/SpringSource/spring-framework/wiki/Building-a-distribution-with-dependencies).
## Documentation
See the current [Javadoc](http://static.springsource.org/spring-framework/docs/current/api) | true |
Other | spring-projects | spring-framework | e5bbec7e2b322f280cffc540d3419baefd29d187.json | Add Gradle task for building zip with dependencies
Some Spring Framework users and teams cannot use transitive dependency
management tools like Maven, Gradle and Ivy. For them, a `distZip` task
has been added to allow for creating a Spring Framework distribution
from source that includes all optional and required runtime
dependencies for all modules of the framework.
This 'dist-with-deps' zip is not published to the SpringSource
repository nor to the SpringSource community download page. It is
strictly an optional task introduced as a convenience to the users
mentioned above.
Detailed instructions for building this zip locally have been added to
the wiki and the README has been updated with a link to that new doc.
Issue: SPR-6575 | build.gradle | @@ -640,7 +640,7 @@ configure(rootProject) {
description = "Builds -${classifier} archive, containing all jars and docs, " +
"suitable for community download page."
- def baseDir = "${project.name}-${project.version}";
+ ext.baseDir = "${project.name}-${project.version}";
from('src/dist') {
include 'readme.txt'
@@ -671,6 +671,36 @@ configure(rootProject) {
}
}
+ // Create an distribution that contains all dependencies (required and optional).
+ // Not published by default; only for use when building from source.
+ task depsZip(type: Zip, dependsOn: distZip) { zipTask ->
+ group = 'Distribution'
+ classifier = 'dist-with-deps'
+ description = "Builds -${classifier} archive, containing everything " +
+ "in the -${distZip.classifier} archive plus all runtime dependencies."
+
+ from zipTree(distZip.archivePath)
+
+ gradle.taskGraph.whenReady { taskGraph ->
+ if (taskGraph.hasTask(":${zipTask.name}")) {
+ def projectNames = rootProject.subprojects*.name
+ def artifacts = new HashSet()
+ subprojects.each { subproject ->
+ subproject.configurations.runtime.resolvedConfiguration.resolvedArtifacts.each { artifact ->
+ def dependency = artifact.moduleVersion.id
+ if (!projectNames.contains(dependency.name)) {
+ artifacts << artifact.file
+ }
+ }
+ }
+
+ zipTask.from(artifacts) {
+ into "${distZip.baseDir}/deps"
+ }
+ }
+ }
+ }
+
artifacts {
archives docsZip
archives schemaZip | true |
Other | spring-projects | spring-framework | 726655af50b6747b8c87ed023aa7911c2b4fe2ed.json | Fix outdated Javadoc in the TestContext framework
Fixed outdated Javadoc regarding support for 'annotated classes' in
the TestContext Framework. | spring-test/src/main/java/org/springframework/test/context/junit4/AbstractJUnit4SpringContextTests.java | @@ -18,7 +18,9 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+
import org.junit.runner.RunWith;
+
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.test.context.ContextConfiguration;
@@ -29,30 +31,26 @@
import org.springframework.test.context.support.DirtiesContextTestExecutionListener;
/**
- * <p>
* Abstract base test class which integrates the <em>Spring TestContext
* Framework</em> with explicit {@link ApplicationContext} testing support in a
* <strong>JUnit 4.5+</strong> environment.
- * </p>
- * <p>
- * Concrete subclasses should typically declare a class-level
+ *
+ * <p>Concrete subclasses should typically declare a class-level
* {@link ContextConfiguration @ContextConfiguration} annotation to
- * configure the {@link ApplicationContext application context}
- * {@link ContextConfiguration#locations() resource locations}.
- * <em>If your test does not need to load an application context, you may choose
- * to omit the {@link ContextConfiguration @ContextConfiguration} declaration
- * and to configure the appropriate
- * {@link org.springframework.test.context.TestExecutionListener TestExecutionListeners}
- * manually.</em>
- * </p>
- * <p>
- * Note: this class serves only as a convenience for extension. If you do not
+ * configure the {@link ApplicationContext application context} {@link
+ * ContextConfiguration#locations() resource locations} or {@link
+ * ContextConfiguration#classes() annotated classes}. <em>If your test does not
+ * need to load an application context, you may choose to omit the {@link
+ * ContextConfiguration @ContextConfiguration} declaration and to configure
+ * the appropriate {@link org.springframework.test.context.TestExecutionListener
+ * TestExecutionListeners} manually.</em>
+ *
+ * <p>Note: this class serves only as a convenience for extension. If you do not
* wish for your test classes to be tied to a Spring-specific class hierarchy,
* you may configure your own custom test classes by using
* {@link SpringJUnit4ClassRunner}, {@link ContextConfiguration
* @ContextConfiguration}, {@link TestExecutionListeners
* @TestExecutionListeners}, etc.
- * </p>
*
* @author Sam Brannen
* @since 2.5 | true |
Other | spring-projects | spring-framework | 726655af50b6747b8c87ed023aa7911c2b4fe2ed.json | Fix outdated Javadoc in the TestContext framework
Fixed outdated Javadoc regarding support for 'annotated classes' in
the TestContext Framework. | spring-test/src/main/java/org/springframework/test/context/junit4/AbstractTransactionalJUnit4SpringContextTests.java | @@ -32,33 +32,28 @@
import org.springframework.transaction.annotation.Transactional;
/**
- * <p>
* Abstract {@link Transactional transactional} extension of
* {@link AbstractJUnit4SpringContextTests} which adds convenience functionality
* for JDBC access. Expects a {@link DataSource} bean and a
* {@link PlatformTransactionManager} bean to be defined in the Spring
* {@link ApplicationContext application context}.
- * </p>
- * <p>
- * This class exposes a {@link SimpleJdbcTemplate} and provides an easy way to
- * {@link #countRowsInTable(String) count the number of rows in a table} ,
- * {@link #deleteFromTables(String...) delete from the database} , and
+ *
+ * <p>This class exposes a {@link SimpleJdbcTemplate} and provides an easy way
+ * to {@link #countRowsInTable(String) count the number of rows in a table},
+ * {@link #deleteFromTables(String...) delete from tables}, and
* {@link #executeSqlScript(String, boolean) execute SQL scripts} within a
* transaction.
- * </p>
- * <p>
- * Concrete subclasses must fulfill the same requirements outlined in
+ *
+ * <p>Concrete subclasses must fulfill the same requirements outlined in
* {@link AbstractJUnit4SpringContextTests}.
- * </p>
- * <p>
- * Note: this class serves only as a convenience for extension. If you do not
+ *
+ * <p>Note: this class serves only as a convenience for extension. If you do not
* wish for your test classes to be tied to a Spring-specific class hierarchy,
* you may configure your own custom test classes by using
* {@link SpringJUnit4ClassRunner}, {@link ContextConfiguration
* @ContextConfiguration}, {@link TestExecutionListeners
* @TestExecutionListeners}, {@link Transactional @Transactional},
* etc.
- * </p>
*
* @author Sam Brannen
* @author Juergen Hoeller
@@ -76,9 +71,9 @@
* @see org.springframework.test.jdbc.SimpleJdbcTestUtils
* @see org.springframework.test.context.testng.AbstractTransactionalTestNGSpringContextTests
*/
-@SuppressWarnings("deprecation")
@TestExecutionListeners(TransactionalTestExecutionListener.class)
@Transactional
+@SuppressWarnings("deprecation")
public abstract class AbstractTransactionalJUnit4SpringContextTests extends AbstractJUnit4SpringContextTests {
/** | true |
Other | spring-projects | spring-framework | 726655af50b6747b8c87ed023aa7911c2b4fe2ed.json | Fix outdated Javadoc in the TestContext framework
Fixed outdated Javadoc regarding support for 'annotated classes' in
the TestContext Framework. | spring-test/src/main/java/org/springframework/test/context/testng/AbstractTestNGSpringContextTests.java | @@ -21,6 +21,7 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.test.context.ContextConfiguration;
@@ -29,6 +30,7 @@
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import org.springframework.test.context.support.DirtiesContextTestExecutionListener;
+
import org.testng.IHookCallBack;
import org.testng.IHookable;
import org.testng.ITestResult;
@@ -38,27 +40,23 @@
import org.testng.annotations.BeforeMethod;
/**
- * <p>
- * Abstract base test class which integrates the
- * <em>Spring TestContext Framework</em> with explicit
- * {@link ApplicationContext} testing support in a <strong>TestNG</strong>
+ * Abstract base test class which integrates the <em>Spring TestContext Framework</em>
+ * with explicit {@link ApplicationContext} testing support in a <strong>TestNG</strong>
* environment.
- * </p>
- * <p>
- * Concrete subclasses:
- * </p>
+ *
+ * <p>Concrete subclasses:
* <ul>
* <li>Typically declare a class-level {@link ContextConfiguration
- * @ContextConfiguration} annotation to configure the
- * {@link ApplicationContext application context}
- * {@link ContextConfiguration#locations() resource locations}.
- * <em>If your test does not need to load an application context, you may choose
- * to omit the {@link ContextConfiguration @ContextConfiguration} declaration
- * and to configure the appropriate
+ * @ContextConfiguration} annotation to configure the {@link ApplicationContext
+ * application context} {@link ContextConfiguration#locations() resource locations}
+ * or {@link ContextConfiguration#classes() annotated classes}. <em>If your test
+ * does not need to load an application context, you may choose to omit the
+ * {@link ContextConfiguration @ContextConfiguration} declaration and to
+ * configure the appropriate
* {@link org.springframework.test.context.TestExecutionListener TestExecutionListeners}
* manually.</em></li>
* <li>Must have constructors which either implicitly or explicitly delegate to
- * <code>super();</code>.</li>
+ * {@code super();}.</li>
* </ul>
*
* @author Sam Brannen | true |
Other | spring-projects | spring-framework | 726655af50b6747b8c87ed023aa7911c2b4fe2ed.json | Fix outdated Javadoc in the TestContext framework
Fixed outdated Javadoc regarding support for 'annotated classes' in
the TestContext Framework. | spring-test/src/main/java/org/springframework/test/context/testng/AbstractTransactionalTestNGSpringContextTests.java | @@ -31,24 +31,20 @@
import org.springframework.transaction.annotation.Transactional;
/**
- * <p>
* Abstract {@link Transactional transactional} extension of
* {@link AbstractTestNGSpringContextTests} which adds convenience functionality
* for JDBC access. Expects a {@link DataSource} bean and a
* {@link PlatformTransactionManager} bean to be defined in the Spring
* {@link ApplicationContext application context}.
- * </p>
- * <p>
- * This class exposes a {@link SimpleJdbcTemplate} and provides an easy way to
- * {@link #countRowsInTable(String) count the number of rows in a table} ,
- * {@link #deleteFromTables(String...) delete from the database} , and
+ *
+ * <p>This class exposes a {@link SimpleJdbcTemplate} and provides an easy way
+ * to {@link #countRowsInTable(String) count the number of rows in a table},
+ * {@link #deleteFromTables(String...) delete from tables}, and
* {@link #executeSqlScript(String, boolean) execute SQL scripts} within a
* transaction.
- * </p>
- * <p>
- * Concrete subclasses must fulfill the same requirements outlined in
+ *
+ * <p>Concrete subclasses must fulfill the same requirements outlined in
* {@link AbstractTestNGSpringContextTests}.
- * </p>
*
* @author Sam Brannen
* @author Juergen Hoeller
@@ -64,9 +60,9 @@
* @see org.springframework.test.jdbc.SimpleJdbcTestUtils
* @see org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests
*/
-@SuppressWarnings("deprecation")
@TestExecutionListeners(TransactionalTestExecutionListener.class)
@Transactional
+@SuppressWarnings("deprecation")
public abstract class AbstractTransactionalTestNGSpringContextTests extends AbstractTestNGSpringContextTests {
/**
@@ -125,7 +121,6 @@ protected int deleteFromTables(String... names) {
* and continueOnError was <code>false</code>
*/
protected void executeSqlScript(String sqlResourcePath, boolean continueOnError) throws DataAccessException {
-
Resource resource = this.applicationContext.getResource(sqlResourcePath);
SimpleJdbcTestUtils.executeSqlScript(this.simpleJdbcTemplate, new EncodedResource(resource,
this.sqlScriptEncoding), continueOnError); | true |
Other | spring-projects | spring-framework | 726655af50b6747b8c87ed023aa7911c2b4fe2ed.json | Fix outdated Javadoc in the TestContext framework
Fixed outdated Javadoc regarding support for 'annotated classes' in
the TestContext Framework. | spring-test/src/test/java/org/springframework/test/context/testng/AnnotationConfigTransactionalTestNGSpringContextTests.java | @@ -1,5 +1,5 @@
/*
- * Copyright 2002-2011 the original author or authors.
+ * Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -32,7 +32,6 @@
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.test.annotation.NotTransactional;
import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.support.AnnotationConfigContextLoader;
import org.springframework.test.context.transaction.AfterTransaction;
import org.springframework.test.context.transaction.BeforeTransaction;
import org.springframework.transaction.PlatformTransactionManager;
@@ -48,13 +47,13 @@
* classes with TestNG-based tests.
*
* <p>Configuration will be loaded from
- * {@link AnnotationConfigTransactionalTestNGSpringContextTestsConfig}.
+ * {@link AnnotationConfigTransactionalTestNGSpringContextTests.ContextConfiguration}.
*
* @author Sam Brannen
* @since 3.1
*/
@SuppressWarnings("deprecation")
-@ContextConfiguration(loader = AnnotationConfigContextLoader.class)
+@ContextConfiguration
public class AnnotationConfigTransactionalTestNGSpringContextTests extends
AbstractTransactionalTestNGSpringContextTests {
| true |
Other | spring-projects | spring-framework | de04d9c654c4c44649cc238019d461a60d75fad9.json | Fix typo in MessageSource reference docs
Issue: SPR-5022 | src/reference/docbook/beans-context-additional.xml | @@ -183,7 +183,7 @@ argument.required=The '{0}' argument is required.</programlisting>
<lineannotation><!-- this <interfacename>MessageSource</interfacename> is being used in a web application --></lineannotation>
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
- <property name="basename" value="test-messages"/>
+ <property name="basename" value="exceptions"/>
</bean>
<lineannotation><!-- lets inject the above <interfacename>MessageSource</interfacename> into this POJO --></lineannotation> | false |
Other | spring-projects | spring-framework | b0f80d6358b6e45cffee6fd74dffca7b15024a34.json | Add splitIndex Javadoc option to the root project
Splits the very large index page with all classes into individual pages
organized by first letter.
Issue: SPR-4984 | build.gradle | @@ -574,6 +574,7 @@ configure(rootProject) {
options.author = true
options.header = rootProject.description
options.overview = 'src/api/overview.html'
+ options.splitIndex = true
options.links(
'http://docs.jboss.org/jbossas/javadoc/4.0.5/connector'
) | false |
Other | spring-projects | spring-framework | 7cdc53487d729c5ddbd23cde0b2d448db9faafae.json | Allow parsing of media types with single-quotes
Previously MediaType could only parse double-quoted parameters without
raising an IllegalArgumentException. Now parameters can also be
single-quoted.
Issue: SPR-8917 | spring-web/src/main/java/org/springframework/http/MediaType.java | @@ -376,7 +376,12 @@ else if (!isQuotedString(value)) {
}
private boolean isQuotedString(String s) {
- return s.length() > 1 && s.startsWith("\"") && s.endsWith("\"") ;
+ if (s.length() < 2) {
+ return false;
+ }
+ else {
+ return ((s.startsWith("\"") && s.endsWith("\"")) || (s.startsWith("'") && s.endsWith("'")));
+ }
}
private String unquote(String s) { | true |
Other | spring-projects | spring-framework | 7cdc53487d729c5ddbd23cde0b2d448db9faafae.json | Allow parsing of media types with single-quotes
Previously MediaType could only parse double-quoted parameters without
raising an IllegalArgumentException. Now parameters can also be
single-quoted.
Issue: SPR-8917 | spring-web/src/test/java/org/springframework/http/MediaTypeTests.java | @@ -181,6 +181,14 @@ public void parseMediaTypeQuotedParameterValue() {
assertEquals("\"v>alue\"", mediaType.getParameter("attr"));
}
+ // SPR-8917
+
+ @Test
+ public void parseMediaTypeSingleQuotedParameterValue() {
+ MediaType mediaType = MediaType.parseMediaType("audio/*;attr='v>alue'");
+ assertEquals("'v>alue'", mediaType.getParameter("attr"));
+ }
+
@Test(expected = IllegalArgumentException.class)
public void parseMediaTypeIllegalQuotedParameterValue() {
MediaType.parseMediaType("audio/*;attr=\""); | true |
Other | spring-projects | spring-framework | cd6f7de4082258f9dcf78657633035da5abfcd65.json | SPR-9498: Add support for MultiValueMap to CollectionFactory
This turns out not to be the main problem exposed in SPR-9498
but it seems like a sensible addition anyway. | spring-core/src/main/java/org/springframework/core/CollectionFactory.java | @@ -35,6 +35,8 @@
import java.util.concurrent.CopyOnWriteArraySet;
import org.springframework.util.LinkedCaseInsensitiveMap;
+import org.springframework.util.LinkedMultiValueMap;
+import org.springframework.util.MultiValueMap;
/**
* Factory for collections, being aware of Java 5 and Java 6 collections.
@@ -305,6 +307,9 @@ public static Map createMap(Class<?> mapType, int initialCapacity) {
else if (SortedMap.class.equals(mapType) || mapType.equals(navigableMapClass)) {
return new TreeMap();
}
+ else if (MultiValueMap.class.equals(mapType)) {
+ return new LinkedMultiValueMap();
+ }
else {
throw new IllegalArgumentException("Unsupported Map interface: " + mapType.getName());
} | true |
Other | spring-projects | spring-framework | cd6f7de4082258f9dcf78657633035da5abfcd65.json | SPR-9498: Add support for MultiValueMap to CollectionFactory
This turns out not to be the main problem exposed in SPR-9498
but it seems like a sensible addition anyway. | spring-core/src/test/java/org/springframework/core/CollectionFactoryTests.java | @@ -24,9 +24,12 @@
import junit.framework.TestCase;
+import org.springframework.util.MultiValueMap;
+
/**
* @author Darren Davison
* @author Juergen Hoeller
+ * @author Dave Syer
*/
public class CollectionFactoryTests extends TestCase {
@@ -50,6 +53,11 @@ public void testConcurrentMap() {
assertTrue(map.getClass().getName().endsWith("ConcurrentHashMap"));
}
+ public void testMultiValueMap() {
+ Map map = CollectionFactory.createMap(MultiValueMap.class, 16);
+ assertTrue(map.getClass().getName().endsWith("MultiValueMap"));
+ }
+
public void testConcurrentMapWithExplicitInterface() {
ConcurrentMap map = CollectionFactory.createConcurrentMap(16);
assertTrue(map.getClass().getSuperclass().getName().endsWith("ConcurrentHashMap")); | true |
Other | spring-projects | spring-framework | 3ba4bb31facfe3d0d309b944ab162f34d47b592c.json | Add Maven artifacts to .gitignore | .gitignore | @@ -4,6 +4,7 @@
.DS_Store
.settings
.springBeans
+target
bin
build.sh
integration-repo
@@ -17,6 +18,7 @@ build
.classpath
.project
argfile*
+pom.xml
# IDEA metadata and output dirs
*.iml | false |
Other | spring-projects | spring-framework | ab4952a959174c496a194967eb873cf119dfeab9.json | Raise RestClientException for unknown status codes
HttpStatus cannot be created with an unknown status code. If a server
returns a status code that's not in the HttpStatus enum values, an
IllegalArgumentException is raised. Rather than allowing it to
propagate as such, this change ensures the actual exception raised is
a RestClientException.
Issue: SPR-9406 | spring-web/src/main/java/org/springframework/web/client/DefaultResponseErrorHandler.java | @@ -45,7 +45,18 @@ public class DefaultResponseErrorHandler implements ResponseErrorHandler {
* Delegates to {@link #hasError(HttpStatus)} with the response status code.
*/
public boolean hasError(ClientHttpResponse response) throws IOException {
- return hasError(response.getStatusCode());
+ return hasError(getStatusCode(response));
+ }
+
+ private HttpStatus getStatusCode(ClientHttpResponse response) throws IOException {
+ HttpStatus statusCode;
+ try {
+ statusCode = response.getStatusCode();
+ }
+ catch (IllegalArgumentException ex) {
+ throw new RestClientException("Unknown status code [" + response.getRawStatusCode() + "]");
+ }
+ return statusCode;
}
/**
@@ -69,7 +80,7 @@ protected boolean hasError(HttpStatus statusCode) {
* and a {@link RestClientException} in other cases.
*/
public void handleError(ClientHttpResponse response) throws IOException {
- HttpStatus statusCode = response.getStatusCode();
+ HttpStatus statusCode = getStatusCode(response);
HttpHeaders headers = response.getHeaders();
MediaType contentType = headers.getContentType();
Charset charset = contentType != null ? contentType.getCharSet() : null; | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.