Java Examples for org.springframework.http.converter.HttpMessageNotReadableException

The following java examples will help you to understand the usage of org.springframework.http.converter.HttpMessageNotReadableException. These source code samples are taken from different open source projects.

Example 1
Project: jdip-web-master  File: SimpleConnectionSignUp.java View source code
@Override
public String execute(Connection<?> conn) {
    UserProfile profile = conn.fetchUserProfile();
    UserEntity newguy = new UserEntity();
    String newname = "";
    newname = profile.getUsername();
    //newguy.setEmail(profile.getEmail());
    System.out.println(conn.getApi().getClass());
    if (conn.getApi() instanceof Google) {
        //System.out.println("in Google");
        Google google = (Google) conn.getApi();
        try {
            Person guser = google.plusOperations().getGoogleProfile();
            newname = guser.getDisplayName();
        } catch (HttpMessageNotReadableException e) {
            e.printStackTrace();
        }
    //System.out.println("fn: "+guser.getDisplayName());
    }
    newguy.setUsername(newname);
    for (int i = 1; i < 100; i++) {
        if (userRepo.getUserByName(newguy.getUsername()) != null) {
            newguy.setUsername(newname + "" + i);
        } else {
            break;
        }
    }
    userRepo.saveUser(newguy);
    return newguy.getId() + "";
}
Example 2
Project: rest-shell-master  File: JsonFormatter.java View source code
@Override
public String format(String nonFormattedString) {
    Object obj;
    try {
        if (nonFormattedString.startsWith("[")) {
            obj = mapper.readValue(nonFormattedString.getBytes(), List.class);
        } else {
            obj = mapper.readValue(nonFormattedString.getBytes(), Map.class);
        }
        return mapper.writeValueAsString(obj);
    } catch (IOException e) {
        throw new HttpMessageNotReadableException(e.getMessage(), e);
    }
}
Example 3
Project: login-server-master  File: AutologinRequestConverter.java View source code
@Override
protected AutologinRequest readInternal(Class<? extends AutologinRequest> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
    MultiValueMap<String, String> map = converter.read(null, inputMessage);
    String username = map.getFirst("username");
    String password = map.getFirst("password");
    AutologinRequest result = new AutologinRequest();
    result.setUsername(username);
    result.setPassword(password);
    return result;
}
Example 4
Project: mbit-cloud-platform-master  File: AutologinRequestConverter.java View source code
@Override
protected AutologinRequest readInternal(Class<? extends AutologinRequest> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
    MultiValueMap<String, String> map = converter.read(null, inputMessage);
    String username = map.getFirst("username");
    String password = map.getFirst("password");
    AutologinRequest result = new AutologinRequest();
    result.setUsername(username);
    result.setPassword(password);
    return result;
}
Example 5
Project: online-whatif-master  File: FeatureHttpMessageConverter.java View source code
@Override
protected Object readInternal(final Class<? extends Object> arg0, final HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
    LOGGER.debug("Entering FeatureHttpMessageConverter.readInternal().");
    final MediaType contentType = inputMessage.getHeaders().getContentType();
    LOGGER.debug("content type of the message received: " + contentType);
    return featureJSON.readFeatureCollection(inputMessage.getBody());
}
Example 6
Project: spring-security-javaconfig-master  File: SparklrController.java View source code
@RequestMapping("/sparklr/photos/{id}")
public ResponseEntity<BufferedImage> photo(@PathVariable String id) throws Exception {
    InputStream photo = sparklrService.loadSparklrPhoto(id);
    if (photo == null) {
        throw new UnavailableException("The requested photo does not exist");
    }
    BufferedImage body;
    MediaType contentType = MediaType.IMAGE_JPEG;
    Iterator<ImageReader> imageReaders = ImageIO.getImageReadersByMIMEType(contentType.toString());
    if (imageReaders.hasNext()) {
        ImageReader imageReader = imageReaders.next();
        ImageReadParam irp = imageReader.getDefaultReadParam();
        imageReader.setInput(new MemoryCacheImageInputStream(photo), true);
        body = imageReader.read(0, irp);
    } else {
        throw new HttpMessageNotReadableException("Could not find javax.imageio.ImageReader for Content-Type [" + contentType + "]");
    }
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.IMAGE_JPEG);
    return new ResponseEntity<BufferedImage>(body, headers, HttpStatus.OK);
}
Example 7
Project: spring-security-oauth-javaconfig-master  File: SparklrController.java View source code
@RequestMapping("/sparklr/photos/{id}")
public ResponseEntity<BufferedImage> photo(@PathVariable String id) throws Exception {
    InputStream photo = sparklrService.loadSparklrPhoto(id);
    if (photo == null) {
        throw new UnavailableException("The requested photo does not exist");
    }
    BufferedImage body;
    MediaType contentType = MediaType.IMAGE_JPEG;
    Iterator<ImageReader> imageReaders = ImageIO.getImageReadersByMIMEType(contentType.toString());
    if (imageReaders.hasNext()) {
        ImageReader imageReader = imageReaders.next();
        ImageReadParam irp = imageReader.getDefaultReadParam();
        imageReader.setInput(new MemoryCacheImageInputStream(photo), true);
        body = imageReader.read(0, irp);
    } else {
        throw new HttpMessageNotReadableException("Could not find javax.imageio.ImageReader for Content-Type [" + contentType + "]");
    }
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.IMAGE_JPEG);
    return new ResponseEntity<BufferedImage>(body, headers, HttpStatus.OK);
}
Example 8
Project: spring-security-oauth-master  File: OAuth2ErrorHandlerTests.java View source code
@Test
public void testHandleMessageConversionExceptions() throws Exception {
    HttpMessageConverter<?> extractor = new HttpMessageConverter() {

        @Override
        public boolean canRead(Class clazz, MediaType mediaType) {
            return true;
        }

        @Override
        public boolean canWrite(Class clazz, MediaType mediaType) {
            return false;
        }

        @Override
        public List<MediaType> getSupportedMediaTypes() {
            return null;
        }

        @Override
        public Object read(Class clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
            throw new HttpMessageConversionException("error");
        }

        @Override
        public void write(Object o, MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        }
    };
    ArrayList<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
    messageConverters.add(extractor);
    handler.setMessageConverters(messageConverters);
    HttpHeaders headers = new HttpHeaders();
    final String appSpecificBodyContent = "This user is not authorized";
    InputStream appSpecificErrorBody = new ByteArrayInputStream(appSpecificBodyContent.getBytes("UTF-8"));
    ClientHttpResponse response = new TestClientHttpResponse(headers, 401, appSpecificErrorBody);
    expected.expect(HttpClientErrorException.class);
    handler.handleError(response);
}
Example 9
Project: com.revolsys.open-master  File: RecordReaderHttpMessageConverter.java View source code
@Override
public RecordReader read(final Class<? extends RecordReader> clazz, final HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
    try {
        final HttpHeaders headers = inputMessage.getHeaders();
        final MediaType mediaType = headers.getContentType();
        Charset charset = mediaType.getCharSet();
        if (charset == null) {
            charset = StandardCharsets.UTF_8;
        }
        final InputStream body = inputMessage.getBody();
        final String mediaTypeString = mediaType.getType() + "/" + mediaType.getSubtype();
        final RecordReaderFactory readerFactory = IoFactory.factoryByMediaType(RecordReaderFactory.class, mediaTypeString);
        if (readerFactory == null) {
            throw new HttpMessageNotReadableException("Cannot read data in format" + mediaType);
        } else {
            final Reader<Record> reader = readerFactory.newRecordReader(new InputStreamResource("recordInput", body));
            GeometryFactory factory = this.geometryFactory;
            final ServletWebRequest requestAttributes = (ServletWebRequest) RequestContextHolder.getRequestAttributes();
            final String srid = requestAttributes.getParameter("srid");
            if (srid != null && srid.trim().length() > 0) {
                factory = GeometryFactory.floating3(Integer.parseInt(srid));
            }
            reader.setProperty(IoConstants.GEOMETRY_FACTORY, factory);
            return (RecordReader) reader;
        }
    } catch (final IOException e) {
        throw new HttpMessageNotReadableException("Error reading data", e);
    }
}
Example 10
Project: elmis-master  File: BaseController.java View source code
@ExceptionHandler(Exception.class)
public ResponseEntity<OpenLmisResponse> handleException(Exception ex) {
    logger.error("something broke with following exception... ", ex);
    if (ex instanceof AccessDeniedException) {
        return error(messageService.message(FORBIDDEN_EXCEPTION), HttpStatus.FORBIDDEN);
    }
    if (ex instanceof MissingServletRequestParameterException || ex instanceof HttpMessageNotReadableException || ex instanceof DataException) {
        return error(ex.getMessage(), BAD_REQUEST);
    }
    return error(messageService.message(UNEXPECTED_EXCEPTION), HttpStatus.INTERNAL_SERVER_ERROR);
}
Example 11
Project: genson-master  File: GensonMessageConverter.java View source code
@Override
protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
    MethodParameter mp = ThreadLocalHolder.get("__GENSON$method_param", MethodParameter.class);
    WithBeanView ann = null;
    Type type = clazz;
    if (mp != null) {
        ann = mp.getMethodAnnotation(WithBeanView.class);
        type = mp.getGenericParameterType();
    }
    GenericType<?> genericType = GenericType.of(type);
    if (ann != null)
        return genson.deserialize(genericType, genson.createReader(inputMessage.getBody()), new Context(genson, Arrays.asList(ann.views())));
    else
        return genson.deserialize(genericType, genson.createReader(inputMessage.getBody()), new Context(genson));
}
Example 12
Project: spring-social-tumblr-master  File: TumblrHttpMessageConverter.java View source code
@Override
public Object read(Type type, Class<?> contextClass, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
    try {
        TumblrResponse tumblrResponse = objectMapper.readValue(inputMessage.getBody(), TumblrResponse.class);
        checkResponse(tumblrResponse);
        Object result;
        if (TumblrResponse.class.equals(type)) {
            // don't parse the response json, callee is going to process is manually
            result = tumblrResponse;
        } else {
            // parse the response json into an instance of the given class
            JavaType javaType = getJavaType(type, contextClass);
            result = objectMapper.readValue(tumblrResponse.getResponseJson(), javaType);
        }
        return result;
    } catch (JsonParseException ex) {
        throw new HttpMessageNotReadableException("Could not read JSON: " + ex.getMessage(), ex);
    } catch (EOFException ex) {
        throw new HttpMessageNotReadableException("Could not read JSON: " + ex.getMessage(), ex);
    }
}
Example 13
Project: akvo-flow-master  File: SurveyAssignmentRestService.java View source code
@RequestMapping(method = RequestMethod.GET, value = "/{id}")
@ResponseBody
public Map<String, SurveyAssignmentDto> getById(@PathVariable("id") Long id) {
    final HashMap<String, SurveyAssignmentDto> response = new HashMap<String, SurveyAssignmentDto>();
    final SurveyAssignment sa = surveyAssignmentDao.getByKey(id);
    if (sa == null) {
        throw new HttpMessageNotReadableException("Survey Assignment with id: " + id + " not found");
    }
    response.put("survey_assignment", marshallToDto(sa));
    return response;
}
Example 14
Project: geode-master  File: SerializableObjectHttpMessageConverter.java View source code
@Override
protected Serializable readInternal(final Class<? extends Serializable> type, final HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
    try {
        return type.cast(IOUtils.deserializeObject(IOUtils.toByteArray(inputMessage.getBody()), ObjectUtils.defaultIfNull(type.getClassLoader(), getClass().getClassLoader())));
    } catch (ClassNotFoundException e) {
        throw new HttpMessageNotReadableException(String.format("Unable to convert the HTTP message body into an Object of type (%1$s)", type.getName()), e);
    }
}
Example 15
Project: geoserver-master  File: MapXMLConverter.java View source code
//
// reading
//
@Override
public Map<?, ?> readInternal(Class<? extends Map<?, ?>> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
    Object result;
    SAXBuilder builder = new SAXBuilder();
    Document doc;
    try {
        doc = builder.build(inputMessage.getBody());
    } catch (JDOMException e) {
        throw new IOException("Error building document", e);
    }
    Element elem = doc.getRootElement();
    result = convert(elem);
    return (Map<?, ?>) result;
}
Example 16
Project: hsweb-framework-master  File: FastJsonHttpMessageConverter.java View source code
@Override
protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    InputStream in = inputMessage.getBody();
    byte[] buf = new byte[1024];
    for (; ; ) {
        int len = in.read(buf);
        if (len == -1) {
            break;
        }
        if (len > 0) {
            baos.write(buf, 0, len);
        }
    }
    byte[] bytes = baos.toByteArray();
    if (clazz == String.class)
        return new String(bytes, charset);
    return JSON.parseObject(bytes, 0, bytes.length, charset.newDecoder(), clazz);
}
Example 17
Project: ical-combinator-master  File: UriListHttpMessageConverter.java View source code
@Override
protected List<URI> readInternal(Class<? extends List<URI>> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
    InputStream in = inputMessage.getBody();
    try {
        String text = IOUtils.toString(in, "UTF-8");
        List<URI> result = parseURIs(text);
        logger.info("Produced a list of " + result.size() + " items: " + result);
        return result;
    } catch (URISyntaxException e) {
        throw new HttpMessageNotReadableException("Illegal URI in list of URIs: " + e.getInput());
    } finally {
        IOUtils.closeQuietly(in);
    }
}
Example 18
Project: moVirt-master  File: VvFileHttpMessageConverter.java View source code
@Override
protected Object readInternal(Class<? extends Object> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
    Object result = null;
    InputStream inputStream = inputMessage.getBody();
    try {
        result = convertStreamToConsoleConnectionDetails(inputStream);
    } catch (Exception x) {
        throw new IllegalStateException("Couldn't parse .vv file response", x);
    } finally {
        ObjectUtils.closeSilently(inputStream);
    }
    return result;
}
Example 19
Project: nio-sandbox-master  File: StringHttpMessageConverter.java View source code
@Override
protected void readInternal(Class<? extends String> clazz, final HttpInputMessage outputMessage, final Promise<String> promise) throws IOException, HttpMessageNotReadableException {
    outputMessage.getHeaders().addCompletionHandler(new AbstractCompletionHandler<HttpHeaders>() {

        @Override
        public void completed(HttpHeaders headers) {
            final Charset charset = getContentTypeCharset(headers.getContentType());
            outputMessage.setCompletionHandler(new AbstractCompletionHandler<Object>() {

                private StringBuffer sb = new StringBuffer();

                @Override
                public boolean chunk(ByteBuffer buffer) {
                    sb.append(charset.decode(buffer).array());
                    return true;
                }

                @Override
                public void completed(Object obj) {
                    promise.result(sb.toString());
                }

                @Override
                public void failed(Throwable throwable) {
                    promise.failure(throwable);
                }
            });
        }
    });
}
Example 20
Project: osm-tools-master  File: ReadOnlyGzipJaxb2HttpMessageConverter.java View source code
protected Object readFromSource(Class<?> clazz, HttpHeaders headers, Source source) throws IOException {
    try {
        Unmarshaller unmarshaller = createUnmarshaller(clazz);
        if (clazz.isAnnotationPresent(XmlRootElement.class)) {
            return unmarshaller.unmarshal(source);
        } else {
            JAXBElement jaxbElement = unmarshaller.unmarshal(source, clazz);
            return jaxbElement.getValue();
        }
    } catch (UnmarshalException ex) {
        throw new HttpMessageNotReadableException("Could not unmarshal to [" + clazz + "]: " + ex.getMessage(), ex);
    } catch (JAXBException ex) {
        throw new HttpMessageConversionException("Could not instantiate JAXBContext: " + ex.getMessage(), ex);
    }
}
Example 21
Project: spring-batch-admin-master  File: BindingHttpMessageConverter.java View source code
public T read(Class<? extends T> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
    MultiValueMap<String, ?> map = delegate.read(null, inputMessage);
    BeanWrapperImpl beanWrapper = new BeanWrapperImpl(targetType);
    initBeanWrapper(beanWrapper);
    Map<String, Object> props = new HashMap<String, Object>();
    for (String key : map.keySet()) {
        if (beanWrapper.isWritableProperty(key)) {
            List<?> list = map.get(key);
            props.put(key, map.get(key).size() > 1 ? list : map.getFirst(key));
        }
    }
    beanWrapper.setPropertyValues(props);
    @SuppressWarnings("unchecked") T result = (T) beanWrapper.getWrappedInstance();
    return result;
}
Example 22
Project: spring-cloud-aws-master  File: NotificationMessageHandlerMethodArgumentResolver.java View source code
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
protected Object doResolveArgumentFromNotificationMessage(JsonNode content, HttpInputMessage request, Class<?> parameterType) {
    if (!"Notification".equals(content.get("Type").asText())) {
        throw new IllegalArgumentException("@NotificationMessage annotated parameters are only allowed for method that receive a notification message.");
    }
    MediaType mediaType = getMediaType(content);
    String messageContent = content.findPath("Message").asText();
    for (HttpMessageConverter<?> converter : this.messageConverter) {
        if (converter.canRead(parameterType, mediaType)) {
            try {
                return converter.read((Class) parameterType, new ByteArrayHttpInputMessage(messageContent, mediaType, request));
            } catch (Exception e) {
                throw new HttpMessageNotReadableException("Error converting notification message with payload:" + messageContent, e);
            }
        }
    }
    throw new HttpMessageNotReadableException("Error converting notification message with payload:" + messageContent);
}
Example 23
Project: spring-data-rest-master  File: DomainObjectReader.java View source code
/**
	 * Reads the given input stream into an {@link ObjectNode} and applies that to the given existing instance.
	 * 
	 * @param source must not be {@literal null}.
	 * @param target must not be {@literal null}.
	 * @param mapper must not be {@literal null}.
	 * @return
	 */
public <T> T read(InputStream source, T target, ObjectMapper mapper) {
    Assert.notNull(target, "Target object must not be null!");
    Assert.notNull(source, "InputStream must not be null!");
    Assert.notNull(mapper, "ObjectMapper must not be null!");
    try {
        return doMerge((ObjectNode) mapper.readTree(source), target, mapper);
    } catch (Exception o_O) {
        throw new HttpMessageNotReadableException("Could not read payload!", o_O);
    }
}
Example 24
Project: spring-framework-master  File: RequestResponseBodyMethodProcessorTests.java View source code
// SPR-9942
@Test(expected = HttpMessageNotReadableException.class)
public void resolveArgumentRequiredNoContent() throws Exception {
    this.servletRequest.setContent(new byte[0]);
    this.servletRequest.setContentType("text/plain");
    List<HttpMessageConverter<?>> converters = new ArrayList<>();
    converters.add(new StringHttpMessageConverter());
    RequestResponseBodyMethodProcessor processor = new RequestResponseBodyMethodProcessor(converters);
    processor.resolveArgument(paramString, container, request, factory);
}
Example 25
Project: spring-integration-samples-master  File: TrafficHttpConverter.java View source code
public Traffic read(Class<? extends Traffic> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
    Traffic traffic = new Traffic();
    try {
        Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(inputMessage.getBody());
        XPathExpression titlesXp = XPathExpressionFactory.createXPathExpression("/ResultSet/Result[@type='incident']/Title");
        List<Node> titles = titlesXp.evaluateAsNodeList(document);
        XPathExpression descXp = XPathExpressionFactory.createXPathExpression("/ResultSet/Result[@type='incident']/Description");
        List<Node> description = descXp.evaluateAsNodeList(document);
        int counter = 0;
        for (Node node : titles) {
            traffic.addIncident(((Element) node).getTextContent(), ((Element) description.get(counter++)).getTextContent());
        }
    } catch (Exception e) {
        throw new HttpMessageConversionException("Failed to convert response to: " + clazz, e);
    }
    return traffic;
}
Example 26
Project: spring-social-master  File: FormMapHttpMessageConverter.java View source code
public Map<String, String> read(Class<? extends Map<String, String>> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
    LinkedMultiValueMap<String, String> lmvm = new LinkedMultiValueMap<String, String>();
    @SuppressWarnings("unchecked") Class<LinkedMultiValueMap<String, String>> mvmClazz = (Class<LinkedMultiValueMap<String, String>>) lmvm.getClass();
    MultiValueMap<String, String> mvm = delegate.read(mvmClazz, inputMessage);
    return mvm.toSingleValueMap();
}
Example 27
Project: spring-social-weibo-master  File: WeiboOAuth2Template.java View source code
@Override
public MultiValueMap<String, String> read(Class<? extends MultiValueMap<String, ?>> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
    TypeReference<Map<String, ?>> mapType = new TypeReference<Map<String, ?>>() {
    };
    LinkedHashMap<String, ?> readValue = objectMapper.readValue(inputMessage.getBody(), mapType);
    LinkedMultiValueMap<String, String> result = new LinkedMultiValueMap<String, String>();
    for (Entry<String, ?> currentEntry : readValue.entrySet()) {
        result.add(currentEntry.getKey(), currentEntry.getValue().toString());
    }
    return result;
}
Example 28
Project: uaa-master  File: ExceptionReportHttpMessageConverter.java View source code
@Override
protected ExceptionReport readInternal(Class<? extends ExceptionReport> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
    for (HttpMessageConverter<?> converter : messageConverters) {
        for (MediaType mediaType : converter.getSupportedMediaTypes()) {
            if (converter.canRead(Map.class, mediaType)) {
                @SuppressWarnings({ "rawtypes", "unchecked" }) HttpMessageConverter<Map> messageConverter = (HttpMessageConverter<Map>) converter;
                @SuppressWarnings("unchecked") Map<String, String> map = messageConverter.read(Map.class, inputMessage);
                return new ExceptionReport(getException(map));
            }
        }
    }
    return null;
}
Example 29
Project: c24-spring-master  File: C24HttpMessageConverter.java View source code
/* (non-Javadoc)
	 * @see org.springframework.http.converter.HttpMessageConverter#read(java.lang.Class, org.springframework.http.HttpInputMessage)
	 */
public ComplexDataObject read(Class<? extends ComplexDataObject> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
    HttpHeaders headers = inputMessage.getHeaders();
    MediaType contentType = headers.getContentType();
    Source source = getSourceFor(inputMessage.getBody(), contentType);
    ComplexDataObject result = source.readObject(model.getElementFor(clazz));
    return C24Utils.potentiallyUnwrapDocumentRoot(result);
}
Example 30
Project: cats-master  File: JaxbSerializedHttpMessageConverterTest.java View source code
@Test(expected = HttpMessageNotReadableException.class)
public void testReadInternalException() throws IOException {
    List<Object> list = new ArrayList<Object>();
    list.add(new SettopDesc());
    InputStream inputStream = EasyMock.createMock(InputStream.class);
    HttpInputMessage inputMessage = EasyMock.createMock(HttpInputMessage.class);
    expect(inputMessage.getBody()).andThrow(new HttpMessageNotReadableException(""));
    EasyMock.replay(inputStream, inputMessage);
    Object obj = jaxbSerializedHttpMessageConverter.readInternal(SettopDesc.class, inputMessage);
    Assert.assertNull(obj);
    EasyMock.verify(inputMessage);
}
Example 31
Project: cherimodata-master  File: EntityConverter.java View source code
@Override
public Object read(Type type, Class<?> contextClass, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
    // what we have (plain entity/list of entities)
    if (type instanceof Class) {
        // simple class
        return factory.readEntity((Class<? extends Entity>) type, IOUtils.toString(inputMessage.getBody()));
    } else {
        // collection
        return factory.readList((Class<? extends Entity>) ((ParameterizedType) type).getActualTypeArguments()[0], IOUtils.toString(inputMessage.getBody()));
    }
}
Example 32
Project: cicada-master  File: AppResponseEntityExceptionHandler.java View source code
@Override
protected //
ResponseEntity<Object> handleHttpMessageNotReadable(//
final HttpMessageNotReadableException ex, //
final HttpHeaders headers, //
final HttpStatus status, final WebRequest request) {
    log.error("HttpMessageNotReadableException:{}", ex);
    final AppError appError = AppError.OTHER_HTTP_MESSAGE_NOT_READABLE;
    final ErrorMessage errorMessage = new ErrorMessage(appError.getErrorCode(), appError.getMessageKey());
    return new ResponseEntity<Object>(errorMessage, headers, status);
}
Example 33
Project: easylocate-master  File: AbstractJaxbMessageConverter.java View source code
@Override
protected final E readFromSource(Class<? extends E> clazz, HttpHeaders headers, Source source) throws IOException {
    try {
        JAXBElement<? extends I> jaxbElement = createUnmarshaller().unmarshal(source, internalClass);
        return convertToExternal(jaxbElement.getValue());
    } catch (UnmarshalException ex) {
        throw new HttpMessageNotReadableException("Could not unmarshal to [" + clazz + "]: " + ex.getMessage(), ex);
    } catch (JAXBException ex) {
        throw new HttpMessageConversionException("Could not instantiate JAXBContext: " + ex.getMessage(), ex);
    }
}
Example 34
Project: parkandrideAPI-master  File: UtilizationITest.java View source code
@Test
public void timestamp_must_have_timezone() {
    submitUtilization(BAD_REQUEST, facility.id, minValidPayload().put(Key.TIMESTAMP, "2015-01-01T11:00:00.000")).spec(assertResponse(HttpMessageNotReadableException.class)).body("violations[0].path", is("[0]." + Key.TIMESTAMP)).body("violations[0].type", is("TypeMismatch")).body("violations[0].message", containsString("expected ISO 8601 date time with timezone"));
}
Example 35
Project: restjplat-master  File: DefaultRestErrorResolver.java View source code
/**
	 * 将spring中的http状�和异常互相对应 �考 spring的defaultExceptionHandler实现类似
	 * 
	 * @return
	 */
private final Map<String, String> createDefaultExceptionMappingDefinitions() {
    Map<String, String> m = new LinkedHashMap<String, String>();
    // 400
    applyDef(m, HttpMessageNotReadableException.class, HttpStatus.BAD_REQUEST);
    applyDef(m, MissingServletRequestParameterException.class, HttpStatus.BAD_REQUEST);
    applyDef(m, TypeMismatchException.class, HttpStatus.BAD_REQUEST);
    applyDef(m, "javax.validation.ValidationException", HttpStatus.BAD_REQUEST);
    // 404
    applyDef(m, NoSuchRequestHandlingMethodException.class, HttpStatus.NOT_FOUND);
    applyDef(m, "org.hibernate.ObjectNotFoundException", HttpStatus.NOT_FOUND);
    // 405
    applyDef(m, HttpRequestMethodNotSupportedException.class, HttpStatus.METHOD_NOT_ALLOWED);
    // 406
    applyDef(m, HttpMediaTypeNotAcceptableException.class, HttpStatus.NOT_ACCEPTABLE);
    // 409
    applyDef(m, "org.springframework.dao.DataIntegrityViolationException", HttpStatus.CONFLICT);
    // 415
    applyDef(m, HttpMediaTypeNotSupportedException.class, HttpStatus.UNSUPPORTED_MEDIA_TYPE);
    return m;
}
Example 36
Project: restler-master  File: SpringDataRestMessageConverter.java View source code
@Override
public Object read(Type type, Class<?> aClass, HttpInputMessage httpInputMessage) throws IOException, HttpMessageNotReadableException {
    JsonNode rootNode = objectMapper.readTree(httpInputMessage.getBody());
    Class<?> resultClass = TypeToken.of(((ParameterizedType) type).getRawType()).getRawType();
    Class<?> elementClass;
    try {
        elementClass = Class.forName(((ParameterizedType) type).getActualTypeArguments()[0].getTypeName());
    } catch (ClassNotFoundException e) {
        throw new RestlerException(e);
    }
    if (isList(resultClass)) {
        JsonNode embedded = rootNode.get("_embedded");
        if (embedded == null) {
            return new ArrayList<>();
        }
        Optional<ArrayNode> first = StreamSupport.stream(embedded.spliterator(), false).filter( e -> e instanceof ArrayNode).map( e -> (ArrayNode) e).findFirst();
        return first.map( objects -> mapToProxies(objects, elementClass)).orElse(new ArrayList());
    }
    throw new HttpMessageNotReadableException("Unexpected response format");
}
Example 37
Project: riptide-master  File: StreamConverterTest.java View source code
@Test
public void shouldFailOnReadForIOException() throws Exception {
    exception.expect(HttpMessageNotReadableException.class);
    exception.expectCause(instanceOf(IOException.class));
    final StreamConverter<?> unit = new StreamConverter<>();
    final HttpInputMessage input = mockWithContentType(APPLICATION_X_JSON_STREAM);
    doThrow(new IOException()).when(input).getBody();
    unit.read(Streams.streamOf(Object.class).getType(), null, input);
}
Example 38
Project: spring-android-master  File: GsonHttpMessageConverterTests.java View source code
@SmallTest
public void testReadInvalidJson() throws IOException {
    boolean success = false;
    try {
        String body = "FooBar";
        MockHttpInputMessage inputMessage = new MockHttpInputMessage(body.getBytes("UTF-8"));
        inputMessage.getHeaders().setContentType(new MediaType("application", "json"));
        this.converter.read(MyBean.class, inputMessage);
    } catch (HttpMessageNotReadableException e) {
        success = true;
    }
    assertTrue(success);
}
Example 39
Project: spring-flex-master  File: FlexAuthenticationEntryPoint.java View source code
/**
	 * If the incoming message is an {@link ActionMessage}, indicating a standard Flex Remoting or Messaging 
	 * request, invokes Spring BlazeDS's {@link ExceptionTranslator}s with the {@link AuthenticationException} and 
	 * sends the resulting {@link MessageException} as an AMF response to the client.
	 * 
	 * <p>If the request is unabled to be deserialized to AMF, if the resulting deserialized object is not an 
	 * <code>ActionMessage</code>, or if no appropriate <code>ExceptionTranslator</code> is found, will simply 
	 * delegate to the parent class to return a 403 response.
	 */
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
    if (CollectionUtils.isEmpty(this.exceptionTranslators)) {
        exceptionTranslators = Collections.singleton(DEFAULT_TRANSLATOR);
    }
    HttpInputMessage inputMessage = new ServletServerHttpRequest(request);
    HttpOutputMessage outputMessage = new ServletServerHttpResponse(response);
    if (!converter.canRead(Object.class, inputMessage.getHeaders().getContentType())) {
        super.commence(request, response, authException);
        return;
    }
    ActionMessage deserializedInput = null;
    try {
        deserializedInput = (ActionMessage) this.converter.read(ActionMessage.class, inputMessage);
    } catch (HttpMessageNotReadableException ex) {
        log.info("Authentication failure detected, but request could not be read as AMF.", ex);
        super.commence(request, response, authException);
        return;
    }
    if (deserializedInput instanceof ActionMessage) {
        for (ExceptionTranslator translator : this.exceptionTranslators) {
            if (translator.handles(authException.getClass())) {
                MessageException result = translator.translate(authException);
                ErrorMessage err = result.createErrorMessage();
                MessageBody body = (MessageBody) ((ActionMessage) deserializedInput).getBody(0);
                Message amfInputMessage = body.getDataAsMessage();
                err.setCorrelationId(amfInputMessage.getMessageId());
                err.setDestination(amfInputMessage.getDestination());
                err.setClientId(amfInputMessage.getClientId());
                ActionMessage responseMessage = new ActionMessage();
                responseMessage.setVersion(((ActionMessage) deserializedInput).getVersion());
                MessageBody responseBody = new MessageBody();
                responseMessage.addBody(responseBody);
                responseBody.setData(err);
                responseBody.setTargetURI(body.getResponseURI());
                responseBody.setReplyMethod(MessageIOConstants.STATUS_METHOD);
                converter.write(responseMessage, amfMediaType, outputMessage);
                response.flushBuffer();
                return;
            }
        }
    }
    super.commence(request, response, authException);
}
Example 40
Project: spring-integration-master  File: MultipartAwareFormHttpMessageConverter.java View source code
@Override
public MultiValueMap<String, ?> read(Class<? extends MultiValueMap<String, ?>> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
    MediaType contentType = inputMessage.getHeaders().getContentType();
    if (!MediaType.MULTIPART_FORM_DATA.includes(contentType)) {
        return this.wrappedConverter.read(clazz, inputMessage);
    }
    Assert.state(inputMessage instanceof MultipartHttpInputMessage, "A request with 'multipart/form-data' Content-Type must be a MultipartHttpInputMessage. " + "Be sure to provide a 'multipartResolver' bean in the ApplicationContext.");
    MultipartHttpInputMessage multipartInputMessage = (MultipartHttpInputMessage) inputMessage;
    return this.readMultipart(multipartInputMessage);
}
Example 41
Project: 51daifan-android-master  File: PostService.java View source code
/**
     *
     * @param url
     * @param responseType
     * @param <T>
     * @return null if exception
     */
private <T> ResponseEntity<T> http(String url, Class<T> responseType, MultiValueMap posts) {
    Log.d(Singleton.DAIFAN_TAG, url);
    //TODO: url encoding for names
    HttpHeaders reqHead = new HttpHeaders();
    List<MediaType> acceptableMediaTypes = new ArrayList<MediaType>();
    acceptableMediaTypes.add(MediaType.APPLICATION_JSON);
    reqHead.setAccept(acceptableMediaTypes);
    RestTemplate restTemplate = new RestTemplate();
    restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());
    restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter2());
    try {
        ResponseEntity<T> rtn;
        if (posts != null) {
            reqHead.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            restTemplate.getMessageConverters().add(new FormHttpMessageConverter());
            rtn = restTemplate.postForEntity(url, new HttpEntity<Object>(posts, reqHead), responseType);
        } else {
            HttpEntity<?> requestEntity = new HttpEntity<Object>(reqHead);
            rtn = restTemplate.exchange(url, HttpMethod.GET, requestEntity, responseType);
        }
        Log.d(Singleton.DAIFAN_TAG, "response:" + rtn);
        return rtn;
    } catch (HttpMessageNotReadableException e) {
        Log.e(Singleton.DAIFAN_TAG, "Post service reading message exception", e);
        return null;
    }
}
Example 42
Project: appverse-web-master  File: CustomMappingJacksonHttpMessageConverter.java View source code
@Override
protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputMessage.getBody(), DEFAULT_CHARSET));
    StringBuilder stringBuilder = new StringBuilder();
    String line = null;
    while ((line = bufferedReader.readLine()) != null) {
        stringBuilder.append(line + " ");
    }
    logger.debug("Middleware recieves " + clazz.getName() + " " + stringBuilder.toString());
    JavaType javaType = getJavaType(clazz);
    return this.objectMapper.readValue(stringBuilder.toString(), javaType);
}
Example 43
Project: fiware-cepheus-master  File: AdminController.java View source code
@ExceptionHandler({ HttpMessageNotReadableException.class })
public ResponseEntity<Object> messageNotReadableExceptionHandler(HttpServletRequest req, HttpMessageNotReadableException exception) {
    logger.error("Request not readable: {}", exception.toString());
    StatusCode statusCode = new StatusCode();
    statusCode.setCode("400");
    statusCode.setReasonPhrase(exception.getMessage());
    if (exception.getCause() != null) {
        statusCode.setDetail(exception.getCause().getMessage());
    }
    return new ResponseEntity<>(statusCode, HttpStatus.BAD_REQUEST);
}
Example 44
Project: gvnix-master  File: DataBinderMappingJackson2HttpMessageConverter.java View source code
/**
     * Before call to {@link ObjectMapper#readValue(java.io.InputStream, Class)}
     * creates a {@link ServletRequestDataBinder} and put it to current Thread
     * in order to be used by the {@link DataBinderDeserializer}.
     * <p/>
     * Ref: <a href=
     * "http://java.dzone.com/articles/java-thread-local-%E2%80%93-how-use">When
     * to use Thread Local?</a>
     * 
     * @param javaType
     * @param inputMessage
     * @return
     */
private Object readJavaType(JavaType javaType, HttpInputMessage inputMessage) {
    try {
        Object target = null;
        String objectName = null;
        // CRear el DataBinder con un target object en funcion del javaType,
        // ponerlo en el thread local
        Class<?> clazz = javaType.getRawClass();
        if (Collection.class.isAssignableFrom(clazz)) {
            Class<?> contentClazz = javaType.getContentType().getRawClass();
            target = new DataBinderList<Object>(contentClazz);
            objectName = "list";
        } else if (Map.class.isAssignableFrom(clazz)) {
            // TODO Class<?> contentClazz =
            // javaType.getContentType().getRawClass();
            target = CollectionFactory.createMap(clazz, 0);
            objectName = "map";
        } else {
            target = BeanUtils.instantiateClass(clazz);
            objectName = "bean";
        }
        WebDataBinder binder = new ServletRequestDataBinder(target, objectName);
        binder.setConversionService(this.conversionService);
        binder.setAutoGrowNestedPaths(true);
        binder.setValidator(validator);
        ThreadLocalUtil.setThreadVariable(BindingResult.MODEL_KEY_PREFIX.concat("JSON_DataBinder"), binder);
        Object value = getObjectMapper().readValue(inputMessage.getBody(), javaType);
        return value;
    } catch (IOException ex) {
        throw new HttpMessageNotReadableException("Could not read JSON: ".concat(ex.getMessage()), ex);
    }
}
Example 45
Project: molgenis-master  File: RestController.java View source code
/**
	 * Login to the api.
	 * <p>
	 * Returns a json object with a token on correct login else throws an AuthenticationException. Clients can use this
	 * token when calling the api.
	 * <p>
	 * Example:
	 * <p>
	 * Request: {username:admin,password:xxx}
	 * <p>
	 * Response: {token: b4fd94dc-eae6-4d9a-a1b7-dd4525f2f75d}
	 *
	 * @param login
	 * @param request
	 * @return
	 */
@RequestMapping(value = "/login", method = POST, produces = APPLICATION_JSON_VALUE)
@ResponseBody
@RunAsSystem
public LoginResponse login(@Valid @RequestBody LoginRequest login, HttpServletRequest request) {
    if (login == null) {
        throw new HttpMessageNotReadableException("Missing login");
    }
    UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(login.getUsername(), login.getPassword());
    authToken.setDetails(new WebAuthenticationDetails(request));
    // Authenticate the login
    Authentication authentication = authenticationManager.authenticate(authToken);
    if (!authentication.isAuthenticated()) {
        throw new BadCredentialsException("Unknown username or password");
    }
    User user = dataService.findOne(USER, new QueryImpl<User>().eq(UserMetaData.USERNAME, authentication.getName()), User.class);
    // User authenticated, log the user in
    SecurityContextHolder.getContext().setAuthentication(authentication);
    // Generate a new token for the user
    String token = tokenService.generateAndStoreToken(authentication.getName(), "Rest api login");
    return new LoginResponse(token, user.getUsername(), user.getFirstName(), user.getLastName());
}
Example 46
Project: snomed-content-service-master  File: RefsetExceptionResolver.java View source code
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(HttpMessageNotReadableException.class)
@ResponseBody
Result<Map<String, Object>> handleValidationException(HttpMessageNotReadableException e) {
    LOGGER.error("Exception details \n", e);
    String message = StringUtils.isEmpty(e.getMessage()) ? "Request does not conform to expected input. Please see error details and try again" : e.getMessage();
    ErrorInfo errorInfo = new ErrorInfo(message, Integer.toString(org.apache.commons.httpclient.HttpStatus.SC_BAD_REQUEST));
    Meta m = new Meta();
    m.setStatus(HttpStatus.BAD_REQUEST);
    m.setErrorInfo(errorInfo);
    response.setMeta(m);
    return response;
}
Example 47
Project: spring4-1-showcase-master  File: ProtobufHttpMessageConverter.java View source code
@Override
protected Message readInternal(Class<? extends Message> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
    MediaType contentType = inputMessage.getHeaders().getContentType();
    contentType = (contentType != null ? contentType : PROTOBUF);
    Charset charset = getCharset(inputMessage.getHeaders());
    InputStreamReader reader = new InputStreamReader(inputMessage.getBody(), charset);
    try {
        Message.Builder builder = getMessageBuilder(clazz);
        if (MediaType.APPLICATION_JSON.isCompatibleWith(contentType)) {
            JsonFormat.merge(reader, this.extensionRegistry, builder);
        } else if (MediaType.TEXT_PLAIN.isCompatibleWith(contentType)) {
            TextFormat.merge(reader, this.extensionRegistry, builder);
        } else if (MediaType.APPLICATION_XML.isCompatibleWith(contentType)) {
            XmlFormat.merge(reader, this.extensionRegistry, builder);
        } else {
            builder.mergeFrom(inputMessage.getBody(), this.extensionRegistry);
        }
        return builder.build();
    } catch (Exception e) {
        throw new HttpMessageNotReadableException("Could not read Protobuf message: " + e.getMessage(), e);
    }
}
Example 48
Project: storm-integration-master  File: ControllerUtils.java View source code
public static SpaceDocument[] createSpaceDocuments(String type, BufferedReader reader, GigaSpace gigaSpace) throws TypeNotFoundException {
    HashMap<String, Object>[] propertyMapArr;
    try {
        //get payload
        StringBuilder sb = new StringBuilder();
        String line = reader.readLine();
        while (line != null) {
            sb.append(line + "\n");
            line = reader.readLine();
        }
        reader.close();
        //if single json object convert it to array
        String data = sb.toString();
        if (!data.startsWith("[")) {
            sb.insert(0, "[");
            sb.append("]");
        }
        //convert to json
        propertyMapArr = mapper.readValue(sb.toString(), typeRef);
    } catch (Exception e) {
        throw new HttpMessageNotReadableException(e.getMessage(), e.getCause());
    }
    SpaceDocument[] documents = new SpaceDocument[propertyMapArr.length];
    for (int i = 0; i < propertyMapArr.length; i++) {
        try {
            Map<String, Object> typeBasedProperties = getTypeBasedProperties(type, propertyMapArr[i], gigaSpace);
            documents[i] = new SpaceDocument(type, typeBasedProperties);
        } catch (UnknownTypeException e) {
            logger.log(Level.SEVERE, "could not convert properties based on type", e);
            return null;
        }
    }
    return documents;
}
Example 49
Project: telekom-workflow-engine-master  File: GsonHttpMessageConverterForSpring3.java View source code
@Override
protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
    Reader json = new InputStreamReader(inputMessage.getBody(), getCharset(inputMessage.getHeaders()));
    try {
        Type typeOfT = getType();
        if (typeOfT != null) {
            return this.gson.fromJson(json, typeOfT);
        } else {
            return this.gson.fromJson(json, clazz);
        }
    } catch (JsonSyntaxException ex) {
        throw new HttpMessageNotReadableException("Could not read JSON: " + ex.getMessage(), ex);
    } catch (JsonIOException ex) {
        throw new HttpMessageNotReadableException("Could not read JSON: " + ex.getMessage(), ex);
    } catch (JsonParseException ex) {
        throw new HttpMessageNotReadableException("Could not read JSON: " + ex.getMessage(), ex);
    }
}
Example 50
Project: udaLib-master  File: UdaMappingJackson2HttpMessageConverter.java View source code
@Override
protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
    try {
        if (!ThreadSafeCache.getMap().isEmpty() && ThreadSafeCache.getMap().keySet().contains("RUP_MULTI_ENTITY")) {
            logger.info("UDA's MultiBean deserialization Mechanism is being triggered.");
            return this.udaObjectMapper.readValue(inputMessage.getBody(), clazz);
        } else {
            logger.info("Spring's Default Object Mapper deserialization is being triggered.");
            return super.readInternal(clazz, inputMessage);
        }
    } catch (Exception ex) {
        logger.error(StackTraceManager.getStackTrace(ex));
        throw new HttpMessageNotReadableException("Could not deserialize JSON: " + ex.getMessage(), ex);
    }
}
Example 51
Project: JavaNosApi-master  File: DataProviderImpl.java View source code
@Override
public SearchResults searchForDocuments(String queryString, SearchSort sort) {
    Assert.notNull(queryString);
    String searchSort;
    if (sort == null) {
        searchSort = SearchSort.SCORE.toString().toLowerCase();
    } else {
        searchSort = sort.toString().toLowerCase();
    }
    String url = serverBaseUrl + "search/query/key/{apikey}/output/json/q/{search}/sort/{sort}";
    SearchWrapper searchResults;
    try {
        searchResults = restTemplate.getForObject(url, SearchWrapper.class, apiKey, queryString, searchSort);
    } catch (HttpMessageNotReadableException e) {
        logger.error("There might be a problem on the server while searching for documents. Usually this exception " + "is thrown if the json returned has a wrong format. The used query is {}", queryString, e.getMostSpecificCause());
        throw new UnknownClientException("Most probably an incorrect response was received from the nos data api", e.getMostSpecificCause());
    }
    ArrayList<nl.gridshore.nosapi.mapping.Document> documents = searchResults.getSearch().get(0).getDocuments();
    List<nl.gridshore.nosapi.Document> foundDocuments = new ArrayList<nl.gridshore.nosapi.Document>();
    for (nl.gridshore.nosapi.mapping.Document document : documents) {
        foundDocuments.add(new nl.gridshore.nosapi.Document(document.getId(), document.getType(), document.getTitle(), document.getDescription(), document.getCategory(), document.getSubCategory(), document.getPublished(), document.getLastUpdate(), document.getLink(), document.getThumbnail(), document.getScore(), document.getKeywords()));
    }
    ArrayList<nl.gridshore.nosapi.mapping.Keyword> keywords = searchResults.getSearch().get(0).getKeywords();
    List<nl.gridshore.nosapi.Keyword> foundKeywords = new ArrayList<nl.gridshore.nosapi.Keyword>();
    for (nl.gridshore.nosapi.mapping.Keyword keyword : keywords) {
        foundKeywords.add(new nl.gridshore.nosapi.Keyword(keyword.getTag(), keyword.getCount()));
    }
    return new SearchResults(foundDocuments, foundKeywords);
}
Example 52
Project: quadriga-master  File: ConceptcollectionController.java View source code
/**
     * This method is used to search the conceptpower for items and will also
     * give options to add it.
     * 
     * @param collection_id
     * @param req
     *            HttpRequest must have pos and search name as parameters to hit
     *            the conceptpower rest service
     * @param model
     * @return
     * @throws QuadrigaStorageException
     */
@AccessPolicies({ @ElementAccessPolicy(type = CheckedElementType.CONCEPTCOLLECTION, paramIndex = 1, userRole = { RoleNames.ROLE_CC_COLLABORATOR_ADMIN, RoleNames.ROLE_CC_COLLABORATOR_READ_WRITE }) })
@RequestMapping(value = "auth/conceptcollections/{collection_id}/searchitems", method = RequestMethod.GET)
public String conceptSearchHandler(@PathVariable("collection_id") String collection_id, HttpServletRequest req, ModelMap model) throws QuadrigaStorageException, QuadrigaAccessException, QuadrigaException {
    try {
        ConceptpowerReply conReply = conceptControllerManager.search(req.getParameter("name"), req.getParameter("pos"));
        if (conReply != null) {
            List<ConceptEntry> lists = conReply.getConceptEntry();
            lists.sort(new Comparator<ConceptEntry>() {

                @Override
                public int compare(ConceptEntry o1, ConceptEntry o2) {
                    return o1.getLemma().toLowerCase().compareTo(o2.getLemma().toLowerCase());
                }
            });
            model.addAttribute("result", conReply.getConceptEntry());
        }
    } catch (HttpMessageNotReadableException hex) {
        throw new QuadrigaException(hex);
    }
    model.addAttribute("collectionid", collection_id);
    return "auth/searchitems";
}
Example 53
Project: spring-data-couchdb-master  File: CouchDbMappingJacksonHttpMessageConverter.java View source code
@Override
protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
    JavaType javaType = getJavaType(clazz);
    try {
        return success(clazz, inputMessage);
    // return this.objectMapper.readValue(inputMessage.getBody(),
    // javaType);
    } catch (Exception ex) {
        throw new HttpMessageNotReadableException("Could not read JSON: " + ex.getMessage(), ex);
    }
}
Example 54
Project: spring-data-document-examples-master  File: CouchDbMappingJacksonHttpMessageConverter.java View source code
@Override
protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
    JavaType javaType = getJavaType(clazz);
    try {
        return success(clazz, inputMessage);
    // return this.objectMapper.readValue(inputMessage.getBody(),
    // javaType);
    } catch (Exception ex) {
        throw new HttpMessageNotReadableException("Could not read JSON: " + ex.getMessage(), ex);
    }
}
Example 55
Project: spring-rest-exception-handler-master  File: RestHandlerExceptionResolverBuilder.java View source code
private Map<Class, RestExceptionHandler> getDefaultHandlers() {
    Map<Class, RestExceptionHandler> map = new HashMap<>();
    map.put(NoSuchRequestHandlingMethodException.class, new NoSuchRequestHandlingMethodExceptionHandler());
    map.put(HttpRequestMethodNotSupportedException.class, new HttpRequestMethodNotSupportedExceptionHandler());
    map.put(HttpMediaTypeNotSupportedException.class, new HttpMediaTypeNotSupportedExceptionHandler());
    map.put(MethodArgumentNotValidException.class, new MethodArgumentNotValidExceptionHandler());
    if (ClassUtils.isPresent("javax.validation.ConstraintViolationException", getClass().getClassLoader())) {
        map.put(ConstraintViolationException.class, new ConstraintViolationExceptionHandler());
    }
    addHandlerTo(map, HttpMediaTypeNotAcceptableException.class, NOT_ACCEPTABLE);
    addHandlerTo(map, MissingServletRequestParameterException.class, BAD_REQUEST);
    addHandlerTo(map, ServletRequestBindingException.class, BAD_REQUEST);
    addHandlerTo(map, ConversionNotSupportedException.class, INTERNAL_SERVER_ERROR);
    addHandlerTo(map, TypeMismatchException.class, BAD_REQUEST);
    addHandlerTo(map, HttpMessageNotReadableException.class, UNPROCESSABLE_ENTITY);
    addHandlerTo(map, HttpMessageNotWritableException.class, INTERNAL_SERVER_ERROR);
    addHandlerTo(map, MissingServletRequestPartException.class, BAD_REQUEST);
    addHandlerTo(map, Exception.class, INTERNAL_SERVER_ERROR);
    // this class didn't exist before Spring 4.0
    try {
        Class clazz = Class.forName("org.springframework.web.servlet.NoHandlerFoundException");
        addHandlerTo(map, clazz, NOT_FOUND);
    } catch (ClassNotFoundException ex) {
    }
    return map;
}
Example 56
Project: spring4-showcase-master  File: ServerControllerTest.java View source code
@Test
public void test7() throws Exception {
    //JSON请求/�应
    String requestBody = "{\"id\":1, \"name\":\"zhang\"}";
    mockMvc.perform(post("/user").contentType(MediaType.APPLICATION_JSON).content(requestBody).accept(//执行请求
    MediaType.APPLICATION_JSON)).andExpect(//验��应contentType
    content().contentType(MediaType.APPLICATION_JSON)).andExpect(//使用Json path验�JSON 请�考http://goessner.net/articles/JsonPath/
    jsonPath("$.id").value(1));
    String errorBody = "{id:1, name:zhang}";
    MvcResult result = mockMvc.perform(post("/user").contentType(MediaType.APPLICATION_JSON).content(errorBody).accept(//执行请求
    MediaType.APPLICATION_JSON)).andExpect(//400错误请求
    status().isBadRequest()).andReturn();
    //错误的请求内容体
    Assert.assertTrue(HttpMessageNotReadableException.class.isAssignableFrom(result.getResolvedException().getClass()));
}
Example 57
Project: hydra-java-master  File: XhtmlResourceMessageConverter.java View source code
public Object read(java.lang.reflect.Type type, Class<?> contextClass, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
    final Class clazz;
    if (type instanceof Class) {
        clazz = (Class) type;
    } else if (type instanceof ParameterizedType) {
        ParameterizedType parameterizedType = (ParameterizedType) type;
        Type rawType = parameterizedType.getRawType();
        if (rawType instanceof Class) {
            clazz = (Class) rawType;
        } else {
            throw new IllegalArgumentException("unexpected raw type " + rawType);
        }
    } else {
        throw new IllegalArgumentException("unexpected type " + type);
    }
    return readInternal(clazz, inputMessage);
}
Example 58
Project: MLDS-master  File: BadRequestControllerAdvice.java View source code
@ExceptionHandler(HttpMessageNotReadableException.class)
public ResponseEntity<String> handleBadJSONException(HttpMessageNotReadableException ex) {
    return new ResponseEntity<String>(ex.getMessage(), HttpStatus.BAD_REQUEST);
}
Example 59
Project: problem-spring-web-master  File: MessageNotReadableAdviceTrait.java View source code
@ExceptionHandler
default ResponseEntity<Problem> handleMessageNotReadableException(final HttpMessageNotReadableException exception, final NativeWebRequest request) {
    return create(Status.BAD_REQUEST, exception, request);
}
Example 60
Project: antares-master  File: ExceptionCatcher.java View source code
@ExceptionHandler(HttpMessageNotReadableException.class)
@ResponseBody
public JsonResponse paramFormatError() {
    String errMsg = messages.get(JsonResponse.PARAM_FORMAT_ERROR.getErr().toString());
    return JsonResponse.notOk(errMsg);
}
Example 61
Project: cloudbreak-master  File: HttpMessageNotReadableExceptionMapper.java View source code
@Override
public Response toResponse(HttpMessageNotReadableException exception) {
    LOGGER.error(exception.getMessage(), exception);
    return Response.status(Response.Status.BAD_REQUEST).entity(new ExceptionResult(exception.getMessage())).build();
}
Example 62
Project: restlist-master  File: BookmarkHttpMessageConverter.java View source code
@Override
protected Bookmark readInternal(Class<Bookmark> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
    ObjectMapper mapper = new ObjectMapper();
    return mapper.readValue(inputMessage.getBody(), Bookmark.class);
}
Example 63
Project: sagan-master  File: DownloadConverter.java View source code
@Override
public byte[] read(Class<? extends byte[]> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
    return StreamUtils.copyToByteArray(inputMessage.getBody());
}
Example 64
Project: suite-master  File: JSONMessageConverter.java View source code
@Override
protected JSONWrapper readInternal(Class<? extends JSONWrapper> clazz, HttpInputMessage message) throws IOException, HttpMessageNotReadableException {
    return JSONWrapper.read(message.getBody());
}
Example 65
Project: transgalactica-master  File: DelegateHttpMessageConverter.java View source code
@Override
public T read(Class<? extends T> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
    return delegate.read(clazz, inputMessage);
}
Example 66
Project: androidannotations-master  File: WrongConstructorConverter.java View source code
@Override
protected String readInternal(Class<? extends String> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
    throw new UnsupportedOperationException();
}
Example 67
Project: convergent-ui-master  File: BufferedImageHttpMessageConverter.java View source code
@Override
protected BufferedImage readInternal(Class<? extends BufferedImage> type, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
    return ImageIO.read(inputMessage.getBody());
}
Example 68
Project: cross-preferences-master  File: HtmlMessageConverter.java View source code
@Override
protected ResourceSupport readInternal(Class<? extends ResourceSupport> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
    throw new UnsupportedOperationException();
}
Example 69
Project: fastjson-master  File: FastJsonHttpMessageConverter4.java View source code
public //
Object read(//
Type type, //
Class<?> contextClass, //
HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
    InputStream in = inputMessage.getBody();
    return JSON.parseObject(in, fastJsonConfig.getCharset(), type, fastJsonConfig.getFeatures());
}
Example 70
Project: find-master  File: GlobalExceptionHandler.java View source code
@ExceptionHandler(HttpMessageNotReadableException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public ErrorResponse messageNotReadableHandler(final HttpMessageNotReadableException exception) throws HttpMessageNotReadableException {
    return handler(exception);
}
Example 71
Project: google-apps-service-master  File: PropertiesHttpMessageConverter.java View source code
@Override
protected Properties readInternal(Class<? extends Properties> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
    InputStream in = null;
    Properties result = new Properties();
    try {
        in = inputMessage.getBody();
        result.load(in);
    } finally {
        IOUtils.closeQuietly(in);
    }
    return result;
}
Example 72
Project: spring-boot-cf-service-broker-master  File: BaseController.java View source code
@ExceptionHandler(HttpMessageNotReadableException.class)
@ResponseBody
public ResponseEntity<ErrorMessage> handleException(HttpMessageNotReadableException ex, HttpServletResponse response) {
    return getErrorResponse(ex.getMessage(), HttpStatus.UNPROCESSABLE_ENTITY);
}
Example 73
Project: dungproxy-master  File: BadRequestExceptionHandler.java View source code
/** 
    * 导致400的异常,默认处��会显示字段�匹�的原因
    */
public void GlobalExceptionHandler() {
    filterExceptions.add(TypeMismatchException.class);
    filterExceptions.add(HttpMessageNotReadableException.class);
    filterExceptions.add(MissingServletRequestParameterException.class);
}
Example 74
Project: lavagna-master  File: GsonHttpMessageConverter.java View source code
@Override
protected Object readInternal(Class<? extends Object> clazz, HttpInputMessage inputMessage) throws IOException {
    try (Reader reader = new InputStreamReader(inputMessage.getBody(), StandardCharsets.UTF_8)) {
        return gson.fromJson(reader, clazz);
    } catch (JsonSyntaxException e) {
        throw new HttpMessageNotReadableException("Could not read JSON: " + e.getMessage(), e);
    }
}
Example 75
Project: qcadoo-master  File: JsonHttpMessageConverter.java View source code
@Override
protected JSONObject readInternal(final Class<? extends JSONObject> clazz, final HttpInputMessage inputMessage) throws IOException {
    String body = IOUtils.toString(inputMessage.getBody(), CHARSET.name());
    try {
        return new JSONObject(body);
    } catch (JSONException e) {
        throw new HttpMessageNotReadableException(e.getMessage(), e);
    }
}
Example 76
Project: spearal-spring-master  File: SpearalMessageConverter.java View source code
public Object read(Class<? extends Object> type, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
    SpearalDecoder decoder = factory.newDecoder(inputMessage.getBody());
    return decoder.readAny(type);
}
Example 77
Project: spring-sync-master  File: JsonPatchHttpMessageConverter.java View source code
@Override
protected Patch readInternal(Class<? extends Patch> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
    return jsonPatchMaker.convert(MAPPER.readTree(inputMessage.getBody()));
}
Example 78
Project: webofneeds-master  File: RdfDatasetConverter.java View source code
@Override
protected Dataset readInternal(Class<? extends Dataset> aClass, HttpInputMessage httpInputMessage) throws IOException, HttpMessageNotReadableException {
    Lang rdfLanguage = mimeTypeToJenaLanguage(httpInputMessage.getHeaders().getContentType(), Lang.TRIG);
    return RdfUtils.toDataset(httpInputMessage.getBody(), new RDFFormat(rdfLanguage));
}
Example 79
Project: cloudpier-adapters-master  File: UploadApplicationPayloadHttpMessageConverter.java View source code
public UploadApplicationPayload read(Class<? extends UploadApplicationPayload> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
    throw new UnsupportedOperationException();
}
Example 80
Project: cloudpier-core-master  File: UploadApplicationPayloadHttpMessageConverter.java View source code
public UploadApplicationPayload read(Class<? extends UploadApplicationPayload> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
    throw new UnsupportedOperationException();
}
Example 81
Project: cts2-framework-master  File: Cts2v10XmlHttpMessageConverter.java View source code
/* (non-Javadoc)
	 * @see org.springframework.http.converter.AbstractHttpMessageConverter#readInternal(java.lang.Class, org.springframework.http.HttpInputMessage)
	 */
@Override
protected Object readInternal(Class<? extends Object> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
    throw new UnsupportedOperationException("Cannot accept CTS2 1.0 XML.");
}
Example 82
Project: demo-application-master  File: ApiGlobalExceptionHandler.java View source code
@Override
protected ResponseEntity<Object> handleHttpMessageNotReadable(final HttpMessageNotReadableException ex, final HttpHeaders headers, final HttpStatus status, final WebRequest request) {
    if (ex.getCause() instanceof Exception) {
        return handleExceptionInternal((Exception) ex.getCause(), null, headers, status, request);
    } else {
        return handleExceptionInternal(ex, null, headers, status, request);
    }
}
Example 83
Project: spring-advanced-marhshallers-and-service-exporters-master  File: MarshallingHttpMessageConverter.java View source code
@Override
protected Object readInternal(Class clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
    InputStream in = inputMessage.getBody();
    try {
        return unmarshaller.unmarshal(clazz, in);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Example 84
Project: spring-data-commons-master  File: XmlBeamHttpMessageConverter.java View source code
/* 
	 * (non-Javadoc)
	 * @see org.springframework.http.converter.AbstractHttpMessageConverter#readInternal(java.lang.Class, org.springframework.http.HttpInputMessage)
	 */
@Override
protected Object readInternal(Class<? extends Object> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
    return projectionFactory.io().stream(inputMessage.getBody()).read(clazz);
}
Example 85
Project: niths-master  File: RESTExceptionHandler.java View source code
@ExceptionHandler(org.springframework.http.converter.HttpMessageNotReadableException.class)
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public void notReadable(org.springframework.http.converter.HttpMessageNotReadableException cve, HttpServletResponse res) {
    res.setHeader("Error", cve.getMessage());
}
Example 86
Project: ABRAID-MP-master  File: CSVMessageConverter.java View source code
/**
     * Implements the abstract template method that reads the actual object. Invoked from {@link #read}.
     * @param clazz the type of object to return
     * @param inputMessage the HTTP input message to read from
     * @return the converted object
     * @throws IOException in case of I/O errors
     * @throws HttpMessageNotReadableException in case of conversion errors
     */
@Override
protected WrappedList<?> readInternal(Class<? extends WrappedList<?>> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
    // Should not be called, since we return false for all canRead
    throw new UnsupportedOperationException();
}
Example 87
Project: android-viewer-for-khan-academy-master  File: MappingJacksonHttpMessageConverter.java View source code
@Override
protected Object readInternal(Class<? extends Object> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
    return objectMapper.readValue(inputMessage.getBody(), clazz);
}
Example 88
Project: arsnova-backend-master  File: ControllerExceptionHandler.java View source code
@ExceptionHandler(HttpMessageNotReadableException.class)
@ResponseBody
@ResponseStatus(HttpStatus.BAD_REQUEST)
public Map<String, Object> handleHttpMessageNotReadableException(final Exception e, final HttpServletRequest request) {
    return handleException(e, Level.DEBUG);
}
Example 89
Project: categolj2-backend-master  File: ApiGlobalExceptionHandler.java View source code
@Override
protected ResponseEntity<Object> handleHttpMessageNotReadable(HttpMessageNotReadableException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
    if (ex.getCause() instanceof Exception) {
        return handleExceptionInternal((Exception) ex.getCause(), null, headers, status, request);
    } else {
        return handleExceptionInternal(ex, null, headers, status, request);
    }
}
Example 90
Project: eGov-master  File: ApiController.java View source code
@ExceptionHandler({ HttpMessageNotReadableException.class })
public ResponseEntity<String> apiExceptionHandler(HttpMessageNotReadableException ex) {
    return getResponseHandler().error(ex.getMessage(), HttpStatus.BAD_REQUEST);
}
Example 91
Project: Juice-master  File: BaseAppController.java View source code
/**
     * 用于处�HttpMessageNotReadableException
     *
     * @param e
     * @return
     */
@ResponseBody
@ExceptionHandler({ HttpMessageNotReadableException.class })
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public Result exception(HttpMessageNotReadableException e) throws IOException {
    //log.warn("got a Exception",e);
    Integer status = REQUEST_PARAMS_INVALID_ERROR.getStatus();
    String message = REQUEST_PARAMS_INVALID_ERROR.getMessage();
    return handleValue(status, message);
}
Example 92
Project: Leabharlann-master  File: FileContentMessageConverter.java View source code
/**
     * Always throws {@link HttpMessageNotReadableException} to indicate that reading {@link FileContent} descriptors is
     * not supported.
     *
     * @param clazz        A class description.
     * @param inputMessage Used to access the servlet request headers and input stream.
     * @return Always throws an exception.
     * @throws HttpMessageNotReadableException Indicates that a {@link FileContent} cannot be read.
     */
@Override
protected FileContent readInternal(final Class<? extends FileContent> clazz, final HttpInputMessage inputMessage) throws HttpMessageNotReadableException {
    throw new HttpMessageNotReadableException("Cannot read messages of this type");
}
Example 93
Project: openclouddb-master  File: MappingJacksonHttpMessageConverter.java View source code
protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
    JavaType javaType = getJavaType(clazz);
    try {
        return this.objectMapper.readValue(inputMessage.getBody(), javaType);
    } catch (IOException ex) {
        throw new HttpMessageNotReadableException("Could not read JSON: " + ex.getMessage(), ex);
    }
}
Example 94
Project: REST-With-Spring-master  File: RestResponseEntityExceptionHandler.java View source code
// API
// 400
@Override
protected final ResponseEntity<Object> handleHttpMessageNotReadable(final HttpMessageNotReadableException ex, final HttpHeaders headers, final HttpStatus status, final WebRequest request) {
    log.info("Bad Request: {}", ex.getMessage());
    log.debug("Bad Request: ", ex);
    final ApiError apiError = message(HttpStatus.BAD_REQUEST, ex);
    return handleExceptionInternal(ex, apiError, headers, HttpStatus.BAD_REQUEST, request);
}
Example 95
Project: spring-cloud-netflix-master  File: SpringEncoderTests.java View source code
@Override
protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
    return null;
}
Example 96
Project: ankush-master  File: BaseController.java View source code
/**
	 * Exception handler.
	 *
	 * @param e the e
	 * @return the response entity
	 */
@ExceptionHandler(HttpMessageNotReadableException.class)
@ResponseBody
public ResponseEntity<String> exceptionHandler(HttpMessageNotReadableException e) {
    log.error("Invalid request body", e);
    return new ResponseEntity<String>(e.getMessage(), HttpStatus.BAD_REQUEST);
}
Example 97
Project: JSON-RPC-master  File: MappingJacksonRPC2HttpMessageConverter.java View source code
@Override
protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
    JavaType javaType = getJavaType(clazz);
    try {
        return this.objectMapper.readValue(inputMessage.getBody(), javaType);
    } catch (IOException ex) {
        throw new HttpMessageNotReadableException("Could not read JSON: " + ex.getMessage(), ex);
    }
}
Example 98
Project: jsonrpc4j-master  File: MappingJacksonRPC2HttpMessageConverter.java View source code
@Override
protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
    JavaType javaType = getJavaType(clazz);
    try {
        return this.objectMapper.readValue(inputMessage.getBody(), javaType);
    } catch (IOException ex) {
        throw new HttpMessageNotReadableException("Could not read JSON: " + ex.getMessage(), ex);
    }
}
Example 99
Project: solarnetwork-common-master  File: SimpleCsvHttpMessageConverter.java View source code
@Override
protected Object readInternal(Class<? extends Object> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
    throw new UnsupportedOperationException("Reading CSV is not supported.");
}
Example 100
Project: spring-ide-master  File: Spring3MappingJacksonHttpMessageConverter.java View source code
@Override
protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException, HttpMessageNotReadableException {
    return objectMapper.readValue(inputMessage.getBody(), clazz);
}
Example 101
Project: openmrs-core-master  File: MappingJacksonHttpMessageConverter.java View source code
@Override
protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
    JavaType javaType = getJavaType(clazz, null);
    return readJavaType(javaType, inputMessage);
}