org.springframework.http.converter.HttpMessageConversionException Java Examples

The following examples show how to use org.springframework.http.converter.HttpMessageConversionException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ProtobufHttpMessageConverter.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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);
	}
}
 
Example #2
Source File: AbstractJaxb2HttpMessageConverter.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #3
Source File: SourceHttpMessageConverter.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@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.");
	}
}
 
Example #4
Source File: ExceptionHandle.java    From demo-project with MIT License 6 votes vote down vote up
@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(), "未知错误");
}
 
Example #5
Source File: AbstractJaxb2HttpMessageConverter.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #6
Source File: SourceHttpMessageConverter.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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.");
	}
}
 
Example #7
Source File: AbstractJaxb2HttpMessageConverter.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * 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;
}
 
Example #8
Source File: OneOffSpringCommonFrameworkExceptionHandlerListener.java    From backstopper with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #9
Source File: ProtobufHttpMessageConverter.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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);
	}
}
 
Example #10
Source File: PushbulletNotifyAction.java    From davos with MIT License 6 votes vote down vote up
@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());
    }
}
 
Example #11
Source File: HttpAPICallAction.java    From davos with MIT License 6 votes vote down vote up
@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());
    }
}
 
Example #12
Source File: SettingsServiceImpl.java    From davos with MIT License 6 votes vote down vote up
@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);
    }
}
 
Example #13
Source File: AbstractJaxb2HttpMessageConverter.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * 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;
}
 
Example #14
Source File: ProtobufHttpMessageConverter.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@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);
	}
}
 
Example #15
Source File: ProtobufHttpMessageConverter.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@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);
	}
}
 
Example #16
Source File: SyncHttpMessageConverter.java    From ecs-sync with Apache License 2.0 5 votes vote down vote up
@Override
protected void writeToResult(Object o, HttpHeaders headers, Result result) throws IOException {
    try {
        getJaxbContext().createMarshaller().marshal(o, result);
    } catch (JAXBException e) {
        throw new HttpMessageConversionException("Could not create JAXB context", e);
    }
}
 
Example #17
Source File: ProtobufHttpMessageConverter.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * 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);
	}
}
 
Example #18
Source File: ControllerInputValidatorAspect.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
/**
 * Validate param using param specific validator and validate all strings using a blacklist validator
 * @param arg
 * @param argName
 */
private void validateArg(Object arg, String argName) {
    BindingResult result = new BeanPropertyBindingResult(arg, argName);
    ValidationUtils.invokeValidator(getValidator(), arg, result);
    // force string validation for bad chars
    if (arg instanceof String) {
        ValidationUtils.invokeValidator(getValidator(), new DefaultStringValidatable((String) arg), result);
    }
    if (result.hasErrors()) {
        throw new HttpMessageConversionException("Invalid input parameter " + argName, new BindException(result));
    }
}
 
Example #19
Source File: AbstractJaxb2HttpMessageConverter.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
	}
}
 
Example #20
Source File: AbstractJaxb2HttpMessageConverter.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
	}
}
 
Example #21
Source File: ApiControllerExceptionHandler.java    From alf.io with GNU General Public License v3.0 5 votes vote down vote up
@ExceptionHandler(HttpMessageConversionException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public String badRequest(HttpMessageConversionException e) {
    log.error("message conversion exception", e);
    return "bad request";
}
 
Example #22
Source File: SpringManyMultipartFilesReader.java    From feign-form with Apache License 2.0 5 votes vote down vote up
private byte[] getMultiPartBoundary (MediaType contentType) {
  val boundaryString = unquote(contentType.getParameter("boundary"));
  if (StringUtils.isEmpty(boundaryString)) {
    throw new HttpMessageConversionException("Content-Type missing boundary information.");
  }
  return boundaryString.getBytes(UTF_8);
}
 
Example #23
Source File: HttpAPICallActionTest.java    From davos with MIT License 5 votes vote down vote up
@Test
public void ifRestTemplateFailsBecauseMessageIsUnreadbleThenDoNothing() {

    PostDownloadExecution execution = new PostDownloadExecution();
    execution.fileName = "filename";
    
    when(mockRestTemplate.exchange(eq("http://url"), eq(HttpMethod.POST), any(HttpEntity.class), eq(Object.class)))
            .thenThrow(new HttpMessageConversionException(""));

    httpAPICallAction.execute(execution);
}
 
Example #24
Source File: OneOffSpringCommonFrameworkExceptionHandlerListener.java    From backstopper with Apache License 2.0 5 votes vote down vote up
protected ApiExceptionHandlerListenerResult handleHttpMessageConversionException(
    HttpMessageConversionException ex,
    List<Pair<String, String>> extraDetailsForLogging
) {
    // Malformed requests can be difficult to track down - add the exception's message to our logging details
    utils.addBaseExceptionMessageToExtraDetailsForLogging(ex, extraDetailsForLogging);

    // HttpMessageNotWritableException is a special case of HttpMessageConversionException that should be
    //      treated as a 500 internal service error. See Spring's DefaultHandlerExceptionResolver and/or
    //      ResponseEntityExceptionHandler for verification.
    if (ex instanceof HttpMessageNotWritableException) {
        return handleError(projectApiErrors.getGenericServiceError(), extraDetailsForLogging);
    }
    else {
        // All other HttpMessageConversionException should be treated as a 400.
        if (isMissingExpectedContentCase(ex)) {
            return handleError(projectApiErrors.getMissingExpectedContentApiError(), extraDetailsForLogging);
        }
        else {
            // NOTE: If this was a HttpMessageNotReadableException with a cause of
            //          com.fasterxml.jackson.databind.exc.InvalidFormatException then we *could* theoretically map
            //          to projectApiErrors.getTypeConversionApiError(). If we ever decide to implement this, then
            //          InvalidFormatException does contain reference to the field that failed to convert - we can
            //          get to it via getPath(), iterating over each path object, and building the full path by
            //          concatenating them with '.'. For now we'll just turn all errors in this category into
            //          projectApiErrors.getMalformedRequestApiError().
            return handleError(projectApiErrors.getMalformedRequestApiError(), extraDetailsForLogging);
        }
    }
}
 
Example #25
Source File: SyncHttpMessageConverter.java    From ecs-sync with Apache License 2.0 5 votes vote down vote up
@Override
protected Object readFromSource(Class<?> clazz, HttpHeaders headers, Source source) throws IOException {
    try {
        return getJaxbContext().createUnmarshaller().unmarshal(source);
    } catch (JAXBException e) {
        throw new HttpMessageConversionException("Could not create JAXB context", e);
    }
}
 
Example #26
Source File: OneOffSpringCommonFrameworkExceptionHandlerListenerTest.java    From backstopper with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldHandleException_returns_MALFORMED_REQUEST_for_generic_HttpMessageConversionException() {
    // given
    HttpMessageConversionException ex = new HttpMessageConversionException("foobar");

    // when
    ApiExceptionHandlerListenerResult result = listener.shouldHandleException(ex);

    // then
    validateResponse(result, true, singletonList(testProjectApiErrors.getMalformedRequestApiError()));
    assertThat(result.extraDetailsForLogging).containsExactly(Pair.of("exception_message", ex.getMessage()));
}
 
Example #27
Source File: JaxbMapper.java    From Shop-for-JavaWeb with MIT License 5 votes vote down vote up
protected static JAXBContext getJaxbContext(Class clazz) {
	Assert.notNull(clazz, "'clazz' must not be null");
	JAXBContext jaxbContext = jaxbContexts.get(clazz);
	if (jaxbContext == null) {
		try {
			jaxbContext = JAXBContext.newInstance(clazz, CollectionWrapper.class);
			jaxbContexts.putIfAbsent(clazz, jaxbContext);
		} catch (JAXBException ex) {
			throw new HttpMessageConversionException("Could not instantiate JAXBContext for class [" + clazz
					+ "]: " + ex.getMessage(), ex);
		}
	}
	return jaxbContext;
}
 
Example #28
Source File: RestErrorHandler.java    From logsniffer with GNU Lesser General Public License v3.0 5 votes vote down vote up
@ExceptionHandler(HttpMessageConversionException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public ErrorResponse processHttpMessageConversionError(final HttpMessageConversionException ex,
		final HttpServletResponse response) throws IOException {
	return processExceptionResponse(ex, response, org.apache.http.HttpStatus.SC_BAD_REQUEST);
}
 
Example #29
Source File: ConfigControllerTest.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Test
public void testBadSave() throws Exception {
    Map<String, Config> mapOfConfigs = new HashMap<String, Config>();
    Config bad = new Config("+++", null, null, Type.FIELD, null, null, null, null, null);
    mapOfConfigs.put("something", bad);
    ConfigMap map = new ConfigMap();
    map.setConfig(mapOfConfigs);
    try {
        configController.saveConfig(map);
        Assert.fail("Should not be able to save");
    } catch (HttpMessageConversionException e) {
        Assert.assertEquals("Invalid input parameter configMap", e.getMessage().substring(0, 33));
    }
}
 
Example #30
Source File: PushbulletNotifyActionTest.java    From davos with MIT License 5 votes vote down vote up
@Test
public void ifRestTemplateFailsBecauseMessageIsUnreadbleThenDoNothing() {
    
    when(mockRestTemplate.exchange(eq("https://api.pushbullet.com/v2/pushes"), eq(HttpMethod.POST), any(HttpEntity.class),
            eq(Object.class))).thenThrow(new HttpMessageConversionException(""));
    
    pushbulletNotifyAction.execute(new PostDownloadExecution());
}