美文网首页
1.middleware

1.middleware

作者: 盗生一 | 来源:发表于2020-12-19 13:51 被阅读0次
    package com.gxhj.safecommunity.middleware.utils;
    
    import com.fasterxml.jackson.core.JsonGenerator;
    import com.fasterxml.jackson.core.JsonParser;
    import com.fasterxml.jackson.core.JsonProcessingException;
    import com.fasterxml.jackson.databind.*;
    import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
    import com.gxhj.commontools.utils.StringUtils;
    import com.gxhj.core.exception.BusinessException;
    import com.gxhj.safecommunity.device.entity.DeviceInfo;
    import com.hjkj.commandentity.base.CommandArgument;
    import com.hjkj.commandentity.base.CommandNames;
    import com.hjkj.commandentity.base.CommandResult;
    import com.hjkj.commandentity.request.RequestCommand;
    import com.hjkj.commandentity.response.ResponseCommand;
    
    import java.io.*;
    import java.text.SimpleDateFormat;
    import java.time.LocalDate;
    import java.time.LocalDateTime;
    import java.time.LocalTime;
    import java.time.format.DateTimeFormatter;
    import java.util.Date;
    import java.util.Locale;
    import java.util.TimeZone;
    
    public class MiddlewareUtil {
    
        /**
         * 得到HTTP请求body中的JSON字符串
         * @param inputStream
         * @return
         * @throws IOException
         */
        public static String getRequestBodyJson(InputStream inputStream) throws IOException {
            Reader input = new InputStreamReader(inputStream);
            Writer output = new StringWriter();
            char[] buffer = new char[1024];
            int n = 0;
            while(-1 != (n = input.read(buffer))) {
                output.write(buffer, 0, n);
            }
            return output.toString();
        }
    
        /**
         * json字符串转换成类
         */
        public static <T extends CommandResult> ResponseCommand<T> jsonFormatResponseCommand(String json, Class<T> clazz) {
            if (StringUtils.isEmpty(json)) {
                throw new BusinessException("json字符串转换成类失败--json字符串为空");
            }
            ObjectMapper objMapper = getSerialObjMapper();
            try {
                JavaType javaTypeOfVehicle = objMapper.getTypeFactory().constructParametricType(ResponseCommand.class, clazz);
                return objMapper.readValue(json, javaTypeOfVehicle);
            } catch (JsonProcessingException e) {
                throw new BusinessException("json转换类失败");
            }
        }
    
        /**
         * 类转换json字符串
         *
         * @param t
         * @return {}
         * @auther zhangJunPeng
         * @date 2020/7/11 0011 14:40
         */
        public static <T> String objectFormatJson(T t) {
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                return objectMapper.writeValueAsString(t);
            } catch (JsonProcessingException e) {
                throw new BusinessException("类转换json失败");
            }
        }
    
        /**
         * 获得序列化后的objectMapper
         *
         * @auther zhangJunPeng
         * @date 2020/7/16 0016 16:29
         */
        public static ObjectMapper getSerialObjMapper() {
            // 设置ObjectMapper的反序列化
            ObjectMapper objMapper = new ObjectMapper();
            objMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
            objMapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);
    
            objMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            objMapper.setLocale(Locale.forLanguageTag("zh"));
            objMapper.setTimeZone(TimeZone.getTimeZone("GMT+8"));
            objMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
    
            JavaTimeModule javaTimeModule = new JavaTimeModule();
            // LocalDateTime序列化
            javaTimeModule.addSerializer(LocalDateTime.class, new JsonSerializer<LocalDateTime>() {
                @Override
                public void serialize(LocalDateTime dateTime, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
                    jsonGenerator.writeString(dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                }
            });
            // LocalDate序列化
            javaTimeModule.addSerializer(LocalDate.class, new JsonSerializer<LocalDate>() {
                @Override
                public void serialize(LocalDate date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
                    jsonGenerator.writeString(date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                }
            });
            // LocalTime序列化
            javaTimeModule.addSerializer(LocalTime.class, new JsonSerializer<LocalTime>() {
                @Override
                public void serialize(LocalTime dateTime, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
                    jsonGenerator.writeString(dateTime.format(DateTimeFormatter.ofPattern("HH:mm:ss")));
                }
            });
    
            // LocalDateTime反序列化
            javaTimeModule.addDeserializer(LocalDateTime.class, new JsonDeserializer<LocalDateTime>() {
                @Override
                public LocalDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
                    return LocalDateTime.parse(jsonParser.getText(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                }
            });
            // LocalDate反序列化
            javaTimeModule.addDeserializer(LocalDate.class, new JsonDeserializer<LocalDate>() {
                @Override
                public LocalDate deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
                    return LocalDate.parse(jsonParser.getText(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                }
            });
            // LocalTime反序列化
            javaTimeModule.addDeserializer(LocalTime.class, new JsonDeserializer<LocalTime>() {
                @Override
                public LocalTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
                    return LocalTime.parse(jsonParser.getText(), DateTimeFormatter.ofPattern("HH:mm:ss"));
                }
            });
    
            objMapper.registerModule(javaTimeModule);
            return objMapper;
        }
    
        /***
         * 将参数放入RequestCommand中
         */
        public static <T extends CommandArgument> RequestCommand<T> putParamInRequestCommand(DeviceInfo deviceInfo, CommandNames commandName, T commandArgument) {
    
            //指令信息
            RequestCommand<T> requestCommand = new RequestCommand<>();
            requestCommand.setCommandName(commandName);
            requestCommand.setCreatetime(new Date());
    
            //设备信息
            CommandArgument cmdArg = commandArgument;
            cmdArg.setIp(deviceInfo.getIpAddress());
            cmdArg.setSdkport(deviceInfo.getServicePort());
            cmdArg.setUsername(deviceInfo.getAccount());
            cmdArg.setPassword(deviceInfo.getPassword());
            cmdArg.setDeviceFactoryType(deviceInfo.getManufacturerCode().getValue());
    //        cmdArg.setDeviceTypes(deviceInfo.getDeviceType());
    
            requestCommand.setCommandArg(commandArgument);
    
            return requestCommand;
        }
    }
    
    

    相关文章

      网友评论

          本文标题:1.middleware

          本文链接:https://www.haomeiwen.com/subject/jcfcnktx.html