Restore serializability of HttpStatusCodeException

SPR-7591 introduced a java.nio.charset.Charset field within
HttpStatusCodeException. The former is non-serializable, thus by
extension the latter also became non-serializable.

Because the Charset field is only used for outputting the charset name
in HttpStatusCodeException#getResponseBodyAsString, it is reasonable to
store the value returned by Charset#name() instead of the actual Charset
object itself.

This commit refactors HttpStatusCodeException's responseCharset field to
be of type String instead of Charset and adds tests to prove that
HttpStatusCodeException objects are once again serializable as expected.

Issue: SPR-9273, SPR-7591
This commit is contained in:
Chris Beams
2012-05-14 14:47:11 +03:00
parent 9a856c09f3
commit 2ff43726be
4 changed files with 71 additions and 7 deletions

View File

@@ -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.client;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.charset.Charset;
import org.junit.Test;
import org.springframework.http.HttpStatus;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
/**
* Unit tests for {@link HttpStatusCodeException} and subclasses.
*
* @author Chris Beams
*/
public class HttpStatusCodeExceptionTests {
/**
* Corners bug SPR-9273, which reported the fact that following the changes made in
* SPR-7591, {@link HttpStatusCodeException} and subtypes became no longer
* serializable due to the addition of a non-serializable {@link Charset} field.
*/
@Test
public void testSerializability() throws IOException, ClassNotFoundException {
HttpStatusCodeException ex1 = new HttpClientErrorException(
HttpStatus.BAD_REQUEST, null, null, Charset.forName("US-ASCII"));
ByteArrayOutputStream out = new ByteArrayOutputStream();
new ObjectOutputStream(out).writeObject(ex1);
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
HttpStatusCodeException ex2 =
(HttpStatusCodeException) new ObjectInputStream(in).readObject();
assertThat(ex2.getResponseBodyAsString(), equalTo(ex1.getResponseBodyAsString()));
}
}