cn.cuizuoli.appranking.http.converter.JsoupHttpMessageConverter.java Source code

Java tutorial

Introduction

Here is the source code for cn.cuizuoli.appranking.http.converter.JsoupHttpMessageConverter.java

Source

/*
 * Copyright 2014 NHN China. All rights Reserved.
 * NHN China PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package cn.cuizuoli.appranking.http.converter;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotWritableException;

/**
 * JsoupHttpMessageConverter
 * @author CN40101
 * @date 20141010
 */
public class JsoupHttpMessageConverter extends AbstractHttpMessageConverter<Document> {

    public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");

    private final Charset defaultCharset;

    private final List<Charset> availableCharsets;

    public JsoupHttpMessageConverter() {
        this(DEFAULT_CHARSET);
    }

    public JsoupHttpMessageConverter(Charset defaultCharset) {
        super(new MediaType("text", "html", defaultCharset), MediaType.ALL);
        this.defaultCharset = defaultCharset;
        this.availableCharsets = new ArrayList<Charset>(Charset.availableCharsets().values());
    }

    @Override
    protected boolean supports(Class<?> clazz) {
        return Document.class.equals(clazz);
    }

    @Override
    protected Document readInternal(Class<? extends Document> clazz, HttpInputMessage inputMessage)
            throws IOException {
        Charset charset = getContentTypeCharset(inputMessage.getHeaders().getContentType());
        return Jsoup.parse(inputMessage.getBody(), charset.name(), StringUtils.EMPTY);
    }

    @Override
    protected void writeInternal(Document doc, HttpOutputMessage outputMessage)
            throws IOException, HttpMessageNotWritableException {
        throw new UnsupportedOperationException();
    }

    /**
     * Return the list of supported {@link Charset}.
     * <p>By default, returns {@link Charset#availableCharsets()}. Can be overridden in subclasses.
     * @return the list of accepted charsets
     */
    protected List<Charset> getAcceptedCharsets() {
        return this.availableCharsets;
    }

    private Charset getContentTypeCharset(MediaType contentType) {
        if (contentType != null && contentType.getCharSet() != null) {
            return contentType.getCharSet();
        } else {
            return this.defaultCharset;
        }
    }

}