JAVA常用工具类整理

JsonUtils 工具类

package com.esdata.sync.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.annotation.JsonInclude;

import java.util.List;
import java.util.Map;

public class JsonUtils {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    static {
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        objectMapper.findAndRegisterModules();
    }

    private JsonUtils() {
        throw new UnsupportedOperationException("Utility class");
    }

    public static String toJson(Object object) {
        try {
            return objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Error converting object to JSON string", e);
        }
    }

    public static <T> T fromJson(String json, Class<T> clazz) {
        try {
            return objectMapper.readValue(json, clazz);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Error converting JSON string to object", e);
        }
    }

    public static <T> List<T> fromJsonToList(String json, Class<T> clazz) {
        try {
            return objectMapper.readValue(json, objectMapper.getTypeFactory().constructCollectionType(List.class, clazz));
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Error converting JSON string to List", e);
        }
    }

    public static <K, V> Map<K, V> fromJsonToMap(String json, Class<K> keyClass, Class<V> valueClass) {
        try {
            return objectMapper.readValue(json, objectMapper.getTypeFactory().constructMapType(Map.class, keyClass, valueClass));
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Error converting JSON string to Map", e);
        }
    }

    public static <T> T fromJson(String json, TypeReference<T> typeReference) {
        try {
            return objectMapper.readValue(json, typeReference);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Error converting JSON string to type", e);
        }
    }

    public static String toJsonPretty(Object object) {
        try {
            return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(object);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Error converting object to formatted JSON string", e);
        }
    }

    public static void ignoreNullValues() {
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    }
}

ESUtils

package com.esdata.sync.utils;

import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j2;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
@Log4j2
@Component
public class ESUtils {

    @Autowired
    private  RestHighLevelClient client;



    /**
     *  判断提定的索引名是否存在
     * @param indexName 索引名
     * @return true 存在  false 不存在
     * @throws IOException
     */
    public boolean indexExists(String indexName) {
        GetIndexRequest request = new GetIndexRequest(indexName);
        try {
            RequestOptions aDefault = RequestOptions.DEFAULT;
            return client.indices().exists(request,aDefault);
        }catch (Exception ex){
            log.error("indexExists ex:{}",ex);
        }
        return false;
    }

    /**
     * 创建索引
     * @param indexName
     * @return
     * @throws IOException
     */
    public boolean createIndex(String indexName)  {
        try {
            CreateIndexRequest indexRequest = new CreateIndexRequest(indexName);

            CreateIndexResponse createIndexResponse =client.indices().create(indexRequest, RequestOptions.DEFAULT);
            return true;
        }catch (Exception ex){
            log.error("createIndex ex:{}",ex);
        }
        return false;
    }


    public void insert(String indexName,String id,String strJson) {
        //新增数据时执行此方法
        if (yesOrNO(indexName)){
            try {
                IndexRequest request = new IndexRequest(indexName).id(id);
                log.info("新增数据时执行此方法{}:{}:{}",indexName,id,strJson);
                request.source(strJson, XContentType.JSON);
                IndexResponse response = client.index(request, RequestOptions.DEFAULT);
                log.info("json:{}--status:{}--result:{}",strJson,response.status().getStatus(),response.getResult());
            }catch (Exception ex){
                log.error("insert ex:{}",ex);
            }
        }

    }

    @SneakyThrows
    public void update(String indexName,String id,String strJson) {
        log.info("更新数据时执行此方法{}:{}",indexName,id);
        UpdateRequest request=new UpdateRequest(indexName,id);
        request.doc(strJson, XContentType.JSON);
        UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
        log.info("status:{}--result:{}",response.status().getStatus(),response.getResult());
        //更新数据时执行此方法
    }

    @SneakyThrows
    public void delete(String indexName, String id) {
        log.info("删除数据时执行此方法{}:{}",indexName,id);

        //删除数据
        DeleteRequest deleteRequest = new DeleteRequest().index(indexName).id(id);
        DeleteResponse deleteResponse = client.delete(deleteRequest, RequestOptions.DEFAULT);
        log.info("status:{}--result:{}",deleteResponse.status().getStatus(),deleteResponse.getResult());

    }

    private boolean yesOrNO(String indexName) {

        boolean exists =indexExists(indexName) ;
        if (!exists){
           return createIndex(indexName);
        }
        return true;
    }
}

 Bean 工具类

/**
 * 对象拷贝
 */
public class BeanToVoUtils {


    public static void copyProperties(Object source, Object target) {
        BeanUtils.copyProperties(source, target);
    }


    public static <T> T copyPropertiesVo(Object source, Class<T> clazz) {
        try {
            //将实体类转换为 Map
            Map map = JsonUtils.fromJson(JsonUtils.toJson(source), Map.class);
            // 将Map转换为 实体类类型不一样
            return (T) JsonUtils.fromJson(JsonUtils.toJson(map), clazz);
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值