001/**
002 * Copyright (c) 2015-2022, Michael Yang 杨福海 (fuhai999@gmail.com).
003 * <p>
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 * <p>
008 * http://www.apache.org/licenses/LICENSE-2.0
009 * <p>
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 */
016package io.jboot.web.render;
017
018import com.jfinal.kit.JsonKit;
019import com.jfinal.render.Render;
020import com.jfinal.render.RenderException;
021import io.jboot.utils.DateUtil;
022import io.jboot.web.ResponseEntity;
023
024import java.io.IOException;
025import java.io.PrintWriter;
026import java.util.Date;
027import java.util.Map;
028
029/**
030 * @author michael yang (fuhai999@gmail.com)
031 * @Date: 2020/4/7
032 */
033public class JbootResponseEntityRender extends Render {
034
035    private ResponseEntity responseEntity;
036
037    public JbootResponseEntityRender(ResponseEntity responseEntity) {
038        this.responseEntity = responseEntity;
039    }
040
041    @Override
042    public void render() {
043
044        PrintWriter writer = null;
045        try {
046            //默认输出 json,但是 responseEntity 可以配置 Header 覆盖这个输出
047            response.setHeader("Cache-Control", "no-cache");
048            response.setHeader("Content-Type", "application/json; charset=utf-8");
049            response.setStatus(responseEntity.getHttpStatus().value());
050
051            Map<String, String> headers = responseEntity.getHeaders();
052            if (headers != null && !headers.isEmpty()) {
053                for (Map.Entry<String, String> entry : headers.entrySet()) {
054                    response.setHeader(entry.getKey(), entry.getValue());
055                }
056            }
057
058            Object body = responseEntity.getBody();
059            String bodyString = null;
060            if (body == null) {
061                bodyString = "";
062            } else if (body instanceof String) {
063                bodyString = (String) body;
064            } else if (body instanceof Date) {
065                bodyString = DateUtil.toDateTimeString((Date) body);
066            } else {
067                JsonKit.toJson(body);
068            }
069            writer = response.getWriter();
070            writer.write(bodyString);
071            // writer.flush();
072        } catch (IOException e) {
073            throw new RenderException(e);
074        }
075
076    }
077}