下面列出了怎么用org.springframework.http.converter.HttpMessageConversionException的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void merge(InputStream input, Charset charset, MediaType contentType,
ExtensionRegistry extensionRegistry, Message.Builder builder)
throws IOException, HttpMessageConversionException {
if (contentType.isCompatibleWith(APPLICATION_JSON)) {
this.jsonFormatter.merge(input, charset, extensionRegistry, builder);
}
else if (contentType.isCompatibleWith(APPLICATION_XML)) {
this.xmlFormatter.merge(input, charset, extensionRegistry, builder);
}
else {
throw new HttpMessageConversionException(
"protobuf-java-format does not support parsing " + contentType);
}
}
@Override
public void print(Message message, OutputStream output, MediaType contentType, Charset charset)
throws IOException, HttpMessageConversionException {
if (contentType.isCompatibleWith(APPLICATION_JSON)) {
this.jsonFormatter.print(message, output, charset);
}
else if (contentType.isCompatibleWith(APPLICATION_XML)) {
this.xmlFormatter.print(message, output, charset);
}
else if (contentType.isCompatibleWith(TEXT_HTML)) {
this.htmlFormatter.print(message, output, charset);
}
else {
throw new HttpMessageConversionException(
"protobuf-java-format does not support printing " + contentType);
}
}
/**
* Return a {@link JAXBContext} for the given class.
* @param clazz the class to return the context for
* @return the {@code JAXBContext}
* @throws HttpMessageConversionException in case of JAXB errors
*/
protected final JAXBContext getJaxbContext(Class<?> clazz) {
Assert.notNull(clazz, "Class must not be null");
JAXBContext jaxbContext = this.jaxbContexts.get(clazz);
if (jaxbContext == null) {
try {
jaxbContext = JAXBContext.newInstance(clazz);
this.jaxbContexts.putIfAbsent(clazz, jaxbContext);
}
catch (JAXBException ex) {
throw new HttpMessageConversionException(
"Could not instantiate JAXBContext for class [" + clazz + "]: " + ex.getMessage(), ex);
}
}
return jaxbContext;
}
@Override
public void merge(InputStream input, Charset charset, MediaType contentType,
ExtensionRegistry extensionRegistry, Message.Builder builder)
throws IOException, HttpMessageConversionException {
if (contentType.isCompatibleWith(APPLICATION_JSON)) {
this.jsonFormatter.merge(input, charset, extensionRegistry, builder);
}
else if (contentType.isCompatibleWith(APPLICATION_XML)) {
this.xmlFormatter.merge(input, charset, extensionRegistry, builder);
}
else {
throw new HttpMessageConversionException(
"protobuf-java-format does not support parsing " + contentType);
}
}
@Override
public void print(Message message, OutputStream output, MediaType contentType, Charset charset)
throws IOException, HttpMessageConversionException {
if (contentType.isCompatibleWith(APPLICATION_JSON)) {
this.jsonFormatter.print(message, output, charset);
}
else if (contentType.isCompatibleWith(APPLICATION_XML)) {
this.xmlFormatter.print(message, output, charset);
}
else if (contentType.isCompatibleWith(TEXT_HTML)) {
this.htmlFormatter.print(message, output, charset);
}
else {
throw new HttpMessageConversionException(
"protobuf-java-format does not support printing " + contentType);
}
}
/**
* Return a {@link JAXBContext} for the given class.
* @param clazz the class to return the context for
* @return the {@code JAXBContext}
* @throws HttpMessageConversionException in case of JAXB errors
*/
protected final JAXBContext getJaxbContext(Class<?> clazz) {
Assert.notNull(clazz, "Class must not be null");
JAXBContext jaxbContext = this.jaxbContexts.get(clazz);
if (jaxbContext == null) {
try {
jaxbContext = JAXBContext.newInstance(clazz);
this.jaxbContexts.putIfAbsent(clazz, jaxbContext);
}
catch (JAXBException ex) {
throw new HttpMessageConversionException(
"Could not instantiate JAXBContext for class [" + clazz + "]: " + ex.getMessage(), ex);
}
}
return jaxbContext;
}
@ExceptionHandler(RuntimeException.class)
public Object handleRuntionException(RuntimeException e) {
if (e instanceof HttpMessageConversionException) {
log.error("bad request:{},{}", e.getMessage(), e);
return new Reply(ErrorCode.BAD_REQUEST.getCode(), "参数无法理解");
}
if (e instanceof ServiceError) {
log.error("业务错误:{},{}", e.getMessage(), e);
return new Reply(((ServiceError) e).getErrorCode(), e.getMessage());
}
if (e instanceof RuntimeException) {
return new Reply(ErrorCode.SERVICE_ERROR.getCode(),e.getMessage() );
}
log.error("其他错误:{},{}", e.getMessage(), e);
return new Reply(ErrorCode.UNKONWN_ERROR.getCode(), "未知错误");
}
/**
* Return a {@link JAXBContext} for the given class.
* @param clazz the class to return the context for
* @return the {@code JAXBContext}
* @throws HttpMessageConversionException in case of JAXB errors
*/
protected final JAXBContext getJaxbContext(Class<?> clazz) {
Assert.notNull(clazz, "'clazz' must not be null");
JAXBContext jaxbContext = this.jaxbContexts.get(clazz);
if (jaxbContext == null) {
try {
jaxbContext = JAXBContext.newInstance(clazz);
this.jaxbContexts.putIfAbsent(clazz, jaxbContext);
}
catch (JAXBException ex) {
throw new HttpMessageConversionException(
"Could not instantiate JAXBContext for class [" + clazz + "]: " + ex.getMessage(), ex);
}
}
return jaxbContext;
}
@Override
@SuppressWarnings("unchecked")
protected T readInternal(Class<? extends T> clazz, HttpInputMessage inputMessage)
throws IOException, HttpMessageNotReadableException {
InputStream body = inputMessage.getBody();
if (DOMSource.class == clazz) {
return (T) readDOMSource(body);
}
else if (SAXSource.class == clazz) {
return (T) readSAXSource(body);
}
else if (StAXSource.class == clazz) {
return (T) readStAXSource(body);
}
else if (StreamSource.class == clazz || Source.class == clazz) {
return (T) readStreamSource(body);
}
else {
throw new HttpMessageConversionException("Could not read class [" + clazz +
"]. Only DOMSource, SAXSource, StAXSource, and StreamSource are supported.");
}
}
/**
* Return a {@link JAXBContext} for the given class.
* @param clazz the class to return the context for
* @return the {@code JAXBContext}
* @throws HttpMessageConversionException in case of JAXB errors
*/
protected final JAXBContext getJaxbContext(Class<?> clazz) {
Assert.notNull(clazz, "'clazz' must not be null");
JAXBContext jaxbContext = this.jaxbContexts.get(clazz);
if (jaxbContext == null) {
try {
jaxbContext = JAXBContext.newInstance(clazz);
this.jaxbContexts.putIfAbsent(clazz, jaxbContext);
}
catch (JAXBException ex) {
throw new HttpMessageConversionException(
"Could not instantiate JAXBContext for class [" + clazz + "]: " + ex.getMessage(), ex);
}
}
return jaxbContext;
}
@Override
@SuppressWarnings("unchecked")
protected T readInternal(Class<? extends T> clazz, HttpInputMessage inputMessage)
throws IOException, HttpMessageNotReadableException {
InputStream body = inputMessage.getBody();
if (DOMSource.class == clazz) {
return (T) readDOMSource(body);
}
else if (SAXSource.class == clazz) {
return (T) readSAXSource(body);
}
else if (StAXSource.class == clazz) {
return (T) readStAXSource(body);
}
else if (StreamSource.class == clazz || Source.class == clazz) {
return (T) readStreamSource(body);
}
else {
throw new HttpMessageConversionException("Could not read class [" + clazz +
"]. Only DOMSource, SAXSource, StAXSource, and StreamSource are supported.");
}
}
protected boolean isMissingExpectedContentCase(HttpMessageConversionException ex) {
if (ex instanceof HttpMessageNotReadableException) {
// Different versions of Spring Web MVC can have different ways of expressing missing content.
// More common case
if (ex.getMessage().startsWith("Required request body is missing")) {
return true;
}
// An older/more unusual case. Unfortunately there's a lot of manual digging that we have to do to determine
// that we've reached this case.
Throwable cause = ex.getCause();
//noinspection RedundantIfStatement
if (cause != null
&& "com.fasterxml.jackson.databind.JsonMappingException".equals(cause.getClass().getName())
&& nullSafeStringContains(cause.getMessage(), "No content to map due to end-of-input")
) {
return true;
}
}
return false;
}
@Override
public void execute(PostDownloadExecution execution) {
PushbulletRequest body = new PushbulletRequest();
body.body = execution.fileName;
body.title = "A new file has been downloaded";
body.type = "note";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("Authorization", "Bearer " + apiKey);
try {
LOGGER.info("Sending notification to Pushbullet for {}", execution.fileName);
LOGGER.debug("API Key: {}", apiKey);
HttpEntity<PushbulletRequest> httpEntity = new HttpEntity<PushbulletRequest>(body, headers);
LOGGER.debug("Sending message to Pushbullet: {}", httpEntity);
restTemplate.exchange("https://api.pushbullet.com/v2/pushes", HttpMethod.POST, httpEntity, Object.class);
} catch (RestClientException | HttpMessageConversionException e ) {
LOGGER.debug("Full stacktrace", e);
LOGGER.error("Unable to complete notification to Pushbullet. Given error: {}", e.getMessage());
}
}
@Override
public void execute(PostDownloadExecution execution) {
try {
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", contentType);
LOGGER.info("Sending message to generic API for {}", execution.fileName);
HttpEntity<String> httpEntity = new HttpEntity<String>(resolveFilename(body, execution.fileName), headers);
LOGGER.debug("Sending {} message {} to generic API: {}", method, httpEntity, url);
restTemplate.exchange(resolveFilename(url, execution.fileName), method, httpEntity, Object.class);
} catch (RestClientException | HttpMessageConversionException e) {
LOGGER.debug("Full stacktrace", e);
LOGGER.error("Unable to complete message to generic API. Given error: {}", e.getMessage());
}
}
@Override
public Version retrieveRemoteVersion() {
try {
String gitHubURL = "https://raw.githubusercontent.com/linuxserver/davos/LatestRelease/version.txt";
LOGGER.debug("Calling out to GitHub to check for new version ({})", gitHubURL);
ResponseEntity<String> response = restTemplate.exchange(gitHubURL, HttpMethod.GET,
new HttpEntity<String>(new HttpHeaders()), String.class);
String body = response.getBody();
LOGGER.debug("GitHub responded with a {}, and body of {}", response.getStatusCode(), body);
return new Version(body);
} catch (RestClientException | HttpMessageConversionException e) {
LOGGER.error("Unable to get version from GitHub: {}", e.getMessage(), e);
LOGGER.debug("Defaulting remote version to zero");
return new Version(0, 0, 0);
}
}
/**
* Create a new {@code Message.Builder} instance for the given class.
* <p>This method uses a ConcurrentReferenceHashMap for caching method lookups.
*/
private Message.Builder getMessageBuilder(Class<? extends Message> clazz) {
try {
Method method = methodCache.get(clazz);
if (method == null) {
method = clazz.getMethod("newBuilder");
methodCache.put(clazz, method);
}
return (Message.Builder) method.invoke(clazz);
}
catch (Exception ex) {
throw new HttpMessageConversionException(
"Invalid Protobuf Message type: no invocable newBuilder() method on " + clazz, ex);
}
}
@Override
public void merge(InputStream input, Charset charset, MediaType contentType,
ExtensionRegistry extensionRegistry, Message.Builder builder)
throws IOException, HttpMessageConversionException {
if (contentType.isCompatibleWith(APPLICATION_JSON)) {
InputStreamReader reader = new InputStreamReader(input, charset);
this.parser.merge(reader, builder);
}
else {
throw new HttpMessageConversionException(
"protobuf-java-util does not support parsing " + contentType);
}
}
@Override
public void print(Message message, OutputStream output, MediaType contentType, Charset charset)
throws IOException, HttpMessageConversionException {
if (contentType.isCompatibleWith(APPLICATION_JSON)) {
OutputStreamWriter writer = new OutputStreamWriter(output, charset);
this.printer.appendTo(message, writer);
writer.flush();
}
else {
throw new HttpMessageConversionException(
"protobuf-java-util does not support printing " + contentType);
}
}
/**
* Create a new {@link Marshaller} for the given class.
* @param clazz the class to create the marshaller for
* @return the {@code Marshaller}
* @throws HttpMessageConversionException in case of JAXB errors
*/
protected final Marshaller createMarshaller(Class<?> clazz) {
try {
JAXBContext jaxbContext = getJaxbContext(clazz);
Marshaller marshaller = jaxbContext.createMarshaller();
customizeMarshaller(marshaller);
return marshaller;
}
catch (JAXBException ex) {
throw new HttpMessageConversionException(
"Could not create Marshaller for class [" + clazz + "]: " + ex.getMessage(), ex);
}
}
/**
* Create a new {@link Unmarshaller} for the given class.
* @param clazz the class to create the unmarshaller for
* @return the {@code Unmarshaller}
* @throws HttpMessageConversionException in case of JAXB errors
*/
protected final Unmarshaller createUnmarshaller(Class<?> clazz) {
try {
JAXBContext jaxbContext = getJaxbContext(clazz);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
customizeUnmarshaller(unmarshaller);
return unmarshaller;
}
catch (JAXBException ex) {
throw new HttpMessageConversionException(
"Could not create Unmarshaller for class [" + clazz + "]: " + ex.getMessage(), ex);
}
}
@Test
public void readWithNoDefaultConstructor() throws Exception {
String body = "{\"property1\":\"foo\",\"property2\":\"bar\"}";
MockHttpInputMessage inputMessage = new MockHttpInputMessage(body.getBytes("UTF-8"));
inputMessage.getHeaders().setContentType(new MediaType("application", "json"));
try {
converter.read(BeanWithNoDefaultConstructor.class, inputMessage);
}
catch (HttpMessageConversionException ex) {
assertTrue(ex.getMessage(), ex.getMessage().startsWith("Type definition error:"));
return;
}
fail();
}
/**
* Create a new {@code Message.Builder} instance for the given class.
* <p>This method uses a ConcurrentReferenceHashMap for caching method lookups.
*/
private Message.Builder getMessageBuilder(Class<? extends Message> clazz) {
try {
Method method = methodCache.get(clazz);
if (method == null) {
method = clazz.getMethod("newBuilder");
methodCache.put(clazz, method);
}
return (Message.Builder) method.invoke(clazz);
}
catch (Exception ex) {
throw new HttpMessageConversionException(
"Invalid Protobuf Message type: no invocable newBuilder() method on " + clazz, ex);
}
}
@Override
public void merge(InputStream input, Charset charset, MediaType contentType,
ExtensionRegistry extensionRegistry, Message.Builder builder)
throws IOException, HttpMessageConversionException {
if (contentType.isCompatibleWith(APPLICATION_JSON)) {
InputStreamReader reader = new InputStreamReader(input, charset);
this.parser.merge(reader, builder);
}
else {
throw new HttpMessageConversionException(
"protobuf-java-util does not support parsing " + contentType);
}
}
@Override
public void print(Message message, OutputStream output, MediaType contentType, Charset charset)
throws IOException, HttpMessageConversionException {
if (contentType.isCompatibleWith(APPLICATION_JSON)) {
OutputStreamWriter writer = new OutputStreamWriter(output, charset);
this.printer.appendTo(message, writer);
writer.flush();
}
else {
throw new HttpMessageConversionException(
"protobuf-java-util does not support printing " + contentType);
}
}
/**
* Create a new {@link Marshaller} for the given class.
* @param clazz the class to create the marshaller for
* @return the {@code Marshaller}
* @throws HttpMessageConversionException in case of JAXB errors
*/
protected final Marshaller createMarshaller(Class<?> clazz) {
try {
JAXBContext jaxbContext = getJaxbContext(clazz);
Marshaller marshaller = jaxbContext.createMarshaller();
customizeMarshaller(marshaller);
return marshaller;
}
catch (JAXBException ex) {
throw new HttpMessageConversionException(
"Could not create Marshaller for class [" + clazz + "]: " + ex.getMessage(), ex);
}
}
/**
* Create a new {@link Unmarshaller} for the given class.
* @param clazz the class to create the unmarshaller for
* @return the {@code Unmarshaller}
* @throws HttpMessageConversionException in case of JAXB errors
*/
protected final Unmarshaller createUnmarshaller(Class<?> clazz) {
try {
JAXBContext jaxbContext = getJaxbContext(clazz);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
customizeUnmarshaller(unmarshaller);
return unmarshaller;
}
catch (JAXBException ex) {
throw new HttpMessageConversionException(
"Could not create Unmarshaller for class [" + clazz + "]: " + ex.getMessage(), ex);
}
}
@Test
public void readWithNoDefaultConstructor() throws Exception {
String body = "{\"property1\":\"foo\",\"property2\":\"bar\"}";
MockHttpInputMessage inputMessage = new MockHttpInputMessage(body.getBytes("UTF-8"));
inputMessage.getHeaders().setContentType(new MediaType("application", "json"));
try {
converter.read(BeanWithNoDefaultConstructor.class, inputMessage);
}
catch (HttpMessageConversionException ex) {
assertTrue(ex.getMessage(), ex.getMessage().startsWith("Type definition error:"));
return;
}
fail();
}
/**
* Create a new {@link Marshaller} for the given class.
* @param clazz the class to create the marshaller for
* @return the {@code Marshaller}
* @throws HttpMessageConversionException in case of JAXB errors
*/
protected final Marshaller createMarshaller(Class<?> clazz) {
try {
JAXBContext jaxbContext = getJaxbContext(clazz);
Marshaller marshaller = jaxbContext.createMarshaller();
customizeMarshaller(marshaller);
return marshaller;
}
catch (JAXBException ex) {
throw new HttpMessageConversionException(
"Could not create Marshaller for class [" + clazz + "]: " + ex.getMessage(), ex);
}
}
/**
* Create a new {@link Unmarshaller} for the given class.
* @param clazz the class to create the unmarshaller for
* @return the {@code Unmarshaller}
* @throws HttpMessageConversionException in case of JAXB errors
*/
protected final Unmarshaller createUnmarshaller(Class<?> clazz) throws JAXBException {
try {
JAXBContext jaxbContext = getJaxbContext(clazz);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
customizeUnmarshaller(unmarshaller);
return unmarshaller;
}
catch (JAXBException ex) {
throw new HttpMessageConversionException(
"Could not create Unmarshaller for class [" + clazz + "]: " + ex.getMessage(), ex);
}
}
/**
* Create a new {@link Marshaller} for the given class.
* @param clazz the class to create the marshaller for
* @return the {@code Marshaller}
* @throws HttpMessageConversionException in case of JAXB errors
*/
protected final Marshaller createMarshaller(Class<?> clazz) {
try {
JAXBContext jaxbContext = getJaxbContext(clazz);
Marshaller marshaller = jaxbContext.createMarshaller();
customizeMarshaller(marshaller);
return marshaller;
}
catch (JAXBException ex) {
throw new HttpMessageConversionException(
"Could not create Marshaller for class [" + clazz + "]: " + ex.getMessage(), ex);
}
}