001/*
002 * Copyright 2002-2019 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.lang.Nullable;
029import org.springframework.util.Assert;
030
031/**
032 * A Jackson 2.6+ codec for encoding and decoding SockJS messages.
033 *
034 * <p>It customizes Jackson's default properties with the following ones:
035 * <ul>
036 * <li>{@link MapperFeature#DEFAULT_VIEW_INCLUSION} is disabled</li>
037 * <li>{@link DeserializationFeature#FAIL_ON_UNKNOWN_PROPERTIES} is disabled</li>
038 * </ul>
039 *
040 * <p>Note that Jackson's JSR-310 and Joda-Time support modules will be registered automatically
041 * when available (and when Java 8 and Joda-Time themselves are available, respectively).
042 *
043 * @author Rossen Stoyanchev
044 * @since 4.0
045 */
046public class Jackson2SockJsMessageCodec extends AbstractSockJsMessageCodec {
047
048        private final ObjectMapper objectMapper;
049
050
051        public Jackson2SockJsMessageCodec() {
052                this.objectMapper = Jackson2ObjectMapperBuilder.json().build();
053        }
054
055        public Jackson2SockJsMessageCodec(ObjectMapper objectMapper) {
056                Assert.notNull(objectMapper, "ObjectMapper must not be null");
057                this.objectMapper = objectMapper;
058        }
059
060
061        @Override
062        @Nullable
063        public String[] decode(String content) throws IOException {
064                return this.objectMapper.readValue(content, String[].class);
065        }
066
067        @Override
068        @Nullable
069        public String[] decodeInputStream(InputStream content) throws IOException {
070                return this.objectMapper.readValue(content, String[].class);
071        }
072
073        @Override
074        protected char[] applyJsonQuoting(String content) {
075                return JsonStringEncoder.getInstance().quoteAsString(content);
076        }
077
078}