工具类Utils——CreateCsvFileUtil.java (生成csv文件)

工具类Utils——CreateCsvFileUtil.java (生成csv文件),第1张

工具类Utils——CreateCsvFileUtil.java (生成csv文件) CreateCsvFileUtil
import com.google.common.base.Joiner;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Set;


public class CreateCsvFileUtil {
    public static boolean createCsvFile(HttpServletResponse response, Set> rows, String fileName) throws Exception {
        OutputStream o = null;
        boolean flag = true;

        StringBuffer sb= new StringBuffer();
        sb.append(""RoleId","RoleName","PolicyId","PolicyName","ResourceId"");
        sb.append("n");
        try{
            for (List rowData : rows) {
                sb.append(parseListToStr(rowData));
                sb.append("n");
            }
            response.reset();
            response.setContentType("application/csv");
            response.setHeader("Content-disposition",
                    "attachment;filename="" + fileName+".csv"");

            o = response.getOutputStream();
            o.write(sb.toString().getBytes("GBK"));

        }catch (Exception e){
            flag = false;
            e.printStackTrace();
        }finally {
            try{
                o.close();
            }catch (IOException e)
            {
                e.printStackTrace();
            }
        }
        return flag;
    }

    public static  String parseListToStr(List list){
        return Joiner.on(",")
                .join(list)
                .replaceAll("([^,]+)", ""$1""); // [^,]+ = Matches all characters except [,]. "$1" = Replaces the matched group by appending ["] at both sides.
    }
}
使用 ——searchEEMSDataList
import com.alibaba.fastjson.JSON;
import com.citihawk.model.PolicyDto;
import com.citihawk.model.ResourceDto;
import com.citihawk.model.SJResponseDto;
import com.citihawk.service.endpoint.EEMSServiceEndpoint;
import com.citihawk.utils.CitihawkConstants;
import com.citihawk.utils.CreateCsvFileUtil;
import com.citihawk.utils.PropertyUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.json.JSONException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.util.*;



@RestController
@Api("generate csv file")
public class EEMSEmanativeController
{
    private static final Logger logger = LoggerFactory.getLogger(EEMSEmanativeController.class);

    @Autowired
    EEMSServiceEndpoint eems;

    @ApiOperation(value = "Fetch EEMS List from DataMod by soeids ")
    @RequestMapping(value = "/reportbuilder/dataMod/searchEEMSDataList", method=RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @CrossOrigin
    @ResponseBody
    public ResponseEntity searchEEMSDataListBySoeids(HttpServletResponse response,
                                                        @RequestBody List aliasArr) throws JSonException {
        Set> res = new HashSet<>();
        try {
            for (String alias: aliasArr) {
                String resStr=eems.getDynamicRolesForGeneratingCsvFile(alias);
                Set> resp = JSON2ArrayList(resStr, SJResponseDto.class);
                for (List row:resp) {
                    res.add(row);
                }
            }
            String fileName = PropertyUtils.getProperty(CitihawkConstants.EEMS_DYNAMIC_ROLES_CSV_FILE_NAME,System.getProperty(CitihawkConstants.CITIHAWKS_SERVER_ENV));
            boolean Flag= CreateCsvFileUtil.createCsvFile(response,res,fileName);
            if (Flag == true)
            {
                logger.info("CSV file was created successfully!");
            }else {
                logger.info("CSV file creation failed!");
            }
            return new ResponseEntity<>("CSV file was created successfully!", HttpStatus.OK);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return new ResponseEntity<>("CSV file creation failed!", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    public static Set> JSON2ArrayList(String jsonStr, Class beanClass) {
        List sJResponse = new ArrayList<>();
        sJResponse= JSON.parseArray(jsonStr,beanClass);
        Set> rows = new HashSet<>();

        for (SJResponseDto sd:sJResponse){
            String id = sd.getId();
            String name = sd.getName();
            List policies = sd.getPolicies();
            String pid="", pname="",  rid="";
            ResourceDto rd =null;

            if (policies == null) {
                rows.add(Arrays.asList(id, name));
                continue;
            }

            if(policies.size()==0){
                rows.add(Arrays.asList(id, name));
                continue;
            }

            for (int i=0;i 
ResourceDto 
package com.citihawk.model;
import com.fasterxml.jackson.annotation.JsonProperty;

public class ResourceDto {
    @JsonProperty("resourceid")
    private String resourceid;

    @JsonProperty("resourcename")
    private String resourcename;

    public String getResourceid() {
        return resourceid;
    }

    public void setResourceid(String resourceid) {
        this.resourceid = resourceid;
    }

    public String getResourcename() {
        return resourcename;
    }

    public void setResourcename(String resourcename) {
        this.resourcename = resourcename;
    }

    @Override
    public String toString() {
        return "ResourceDto{" +
                "resourceid='" + resourceid + ''' +
                ", resourcename='" + resourcename + ''' +
                '}';
    }
}
PolicyDto
package com.citihawk.model;

import com.fasterxml.jackson.annotation.JsonProperty;

import java.util.List;

public class PolicyDto {
    @JsonProperty("policyid")
    private String policyid;

    @JsonProperty("policyname")
    private String policyname;

    @JsonProperty("policydesc")
    private String policydesc;

    @JsonProperty("resources")
    private List resources;

    public String getPolicyid() {
        return policyid;
    }

    public void setPolicyid(String policyid) {
        this.policyid = policyid;
    }

    public String getPolicyname() {
        return policyname;
    }

    public void setPolicyname(String policyname) {
        this.policyname = policyname;
    }

    public String getPolicydesc() {
        return policydesc;
    }

    public void setPolicydesc(String policydesc) {
        this.policydesc = policydesc;
    }

    public List getResources() {
        return resources;
    }

    public void setResources(List resources) {
        this.resources = resources;
    }

    @Override
    public String toString() {
        return "PolicyDto{" +
                "policyid='" + policyid + ''' +
                ", policyname='" + policyname + ''' +
                ", policydesc='" + policydesc + ''' +
                ", resources=" + resources +
                '}';
    }
}
SJResponseDto
import com.fasterxml.jackson.annotation.JsonProperty;

import java.util.List;

public class SJResponseDto {
    @JsonProperty("id")
    private String id;

    @JsonProperty("name")
    private String name;

    //@JsonProperty("description")
    //private String description;

    @JsonProperty("policies")
    private List policies;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

//    public String getDescription() {
//        return description;
//    }
//
//    public void setDescription(String description) {
//        this.description = description;
//    }

    public List getPolicies() {
        return policies;
    }

    public void setPolicies(List policies) {
        this.policies = policies;
    }

    @Override
    public String toString() {
        return "SJResponseDto{" +
                "id='" + id + ''' +
                ", name='" + name + ''' +
               // ", description='" + description + ''' +
                ", policies=" + policies +
                '}';
    }

}
getDynamicRolesForGeneratingCsvFile()
public String getDynamicRolesForGeneratingCsvFile(String user) throws EndpointFailedException {
	logger.info("Calling EEMS API for Approved dynamic roles...");
	return fetchFromEems(getEEMSUrlForGeneratingCsvFile(user));
}
fetchFromEems(String url)
private String fetchFromEems(String url) throws EndpointFailedException {
	Client client = HttpConnectionUtil.getDefaultHttpClient();
	ClientResponse clientResponse;
	String response = null;
	try {
		WebResource webResource = client.resource(url);
		logger.info("Calling EEMS API " + webResource.getURI());

		clientResponse = webResource.header("accept", "application/json").get(ClientResponse.class);
		if (clientResponse.getStatus() != 200) {
			logger.error("Error response for API . Error code: {} ,  {}", clientResponse.getStatus(),
					clientResponse.getEntity(String.class));
			throw new EndpointFailedException(" Response was not successful from  " + url, null);
		}
		response = clientResponse.getEntity(String.class);
		logger.info("Response from EEMS API..." + response);
	}
	catch(Exception e){
		logger.info("Error  while  fetching the response from EEMS ..." + e.getMessage());
	}
	return response;
}
getEEMSUrlForGeneratingCsvFile()
private String getEEMSUrlForGeneratingCsvFile(String user) {
	return getEEMSUrlwithMethodIdAndDomainId(user, CitihawkConstants.EEMS_DYNAMIC_ROLES_CSV_DOMAIN_ID,
			CitihawkConstants.EEMS_DYNAMIC_ROLES_CSV_METHOD_ID);

}
getEEMSUrlwithMethodIdAndDomainId()
String getEEMSUrlwithMethodIdAndDomainId(String user, String domainIdKey, String methodIdKey) {
	user = user.toLowerCase();
	logger.debug("user from header " + user);
	String key = "EEMS_RESOURCE_ACTIONS";
	String urlbase = getEEMsHOST();
	String domain = PropertyUtils.getProperty(domainIdKey,
			System.getProperty(CitihawkConstants.CITIHAWKS_SERVER_ENV));
	String method = PropertyUtils.getProperty(methodIdKey,
			System.getProperty(CitihawkConstants.CITIHAWKS_SERVER_ENV));

	String url = "";
	if (null != urlbase && null != user && null != domain && null != method) {
		url = urlbase + "?domainId=" + domain + "&methodId=" + method + "&alias=" + user;

	}
	logger.debug("Complete URL" + url);
	return url;
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5677734.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存