001/*
002 * Copyright 2002-2015 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      https://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.springframework.web.socket.sockjs.frame;
018
019import java.io.IOException;
020import java.io.InputStream;
021
022import com.fasterxml.jackson.core.io.JsonStringEncoder;
023import com.fasterxml.jackson.databind.DeserializationFeature;
024import com.fasterxml.jackson.databind.MapperFeature;
025import com.fasterxml.jackson.databind.ObjectMapper;
026
027import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
028import org.springframework.util.Assert;
029
030/**
031 * A Jackson 2.6+ codec for encoding and decoding SockJS messages.
032 *
033 * <p>It customizes Jackson's default properties with the following ones:
034 * <ul>
035 * <li>{@link MapperFeature#DEFAULT_VIEW_INCLUSION} is disabled</li>
036 * <li>{@link DeserializationFeature#FAIL_ON_UNKNOWN_PROPERTIES} is disabled</li>
037 * </ul>
038 *
039 * <p>Note that Jackson's JSR-310 and Joda-Time support modules will be registered automatically
040 * when available (and when Java 8 and Joda-Time themselves are available, respectively).
041 *
042 * @author Rossen Stoyanchev
043 * @since 4.0
044 */
045public class Jackson2SockJsMessageCodec extends AbstractSockJsMessageCodec {
046
047        private final ObjectMapper objectMapper;
048
049
050        public Jackson2SockJsMessageCodec() {
051                this.objectMapper = Jackson2ObjectMapperBuilder.json().build();
052        }
053
054        public Jackson2SockJsMessageCodec(ObjectMapper objectMapper) {
055                Assert.notNull(objectMapper, "ObjectMapper must not be null");
056                this.objectMapper = objectMapper;
057        }
058
059
060        @Override
061        public String[] decode(String content) throws IOException {
062                return this.objectMapper.readValue(content, String[].class);
063        }
064
065        @Override
066        public String[] decodeInputStream(InputStream content) throws IOException {
067                return this.objectMapper.readValue(content, String[].class);
068        }
069
070        @Override
071        protected char[] applyJsonQuoting(String content) {
072                return JsonStringEncoder.getInstance().quoteAsString(content);
073        }
074
075}