Unified data export based on java services

1. We often need to export data. However, different business scenarios only have different data, but the export actions have many commonalities. Therefore, we can adopt the idea of dynamic and static separation to extract actions as a service. The data depends on actions, so we can use a set of code to deal with some public things.

2. Idea: if you only use actions as util s, each service needs to rely on the actions. Services and actions have a high degree of coupling. My idea is to extract actions into basic (public) services, which only do specific actions. The data comes from other services and is processed into a specific flow for other services to call

3. Code implementation:

 

Action in base service: fileimportexportcontroller java

import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;

import cn.togeek.service.FileImportExportService;

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

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/ftp")
@Api(tags = "Unified file import and export")
@AllArgsConstructor
public class FileImportExportController {

   private final FileImportExportService fileImportExportService;

   @PostMapping("/export/xls")
   public byte[] exportFile(@RequestBody List<Map> data) throws Exception {
      return fileImportExportService.doExport(data);
   }

   @PostMapping("/import/xls")
   public List<Map> importFile(@RequestBody MultipartFile[] files) throws Exception {
      return fileImportExportService.doImport(files);
   }

}

 

service implementation: fileimportexportservice java

import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.IntStream;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

@Service
public class FileImportExportService {

   public byte[] doExport(List<Map> data) throws IOException
   {
      ExcelWriter writer = ExcelUtil.getWriter();
      writer.write(data);
      IntStream.range(0, data.size()+1).forEach(x -> {
         writer.setRowHeight(x, 30);
      });
      IntStream.range(0, data.get(0).size()).forEach(j -> {
         writer.setColumnWidth(j, 40);
      });
      ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
      writer.getWorkbook().write(outputStream);
      return outputStream.toByteArray();
   }

   public List<Map> doImport(MultipartFile[] files) {
      return Collections.emptyList();
   }
}

 

Dependent service: spotbasedatafeign Java (called in fengin mode)

import cn.togeek.common.domain.ElectricityRetailer;
import cn.togeek.common.domain.TradingUnit;
import cn.togeek.common.domain.Unit;
import cn.togeek.common.domain.UnitCost;
import cn.togeek.domain.base.InstalledGenerationCapacityInfo;
import cn.togeek.domain.base.UnitMarginalCost;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.core.io.Resource;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@FeignClient(name = "spot-base-data", url = "${service.spot-base-data.url}", fallbackFactory = SpotBaseDataFeign.ApiBaseDataServiceFallbackFactory.class)
@RequestMapping("/spot-base-data")
public interface SpotBaseDataFeign {
  
   @PostMapping("/ftp/export/xls")
   byte[] exportFile(@RequestBody List<Map<Object,Object>> data);

   @Component
   static class ApiBaseDataServiceFallbackFactory extends FeignFallbackFactory<SpotBaseDataFeign> {
      @Override
      public SpotBaseDataFeign newHandler() {
         return new SpotBaseDataFeign() {

            @Override
            public byte[] exportFile(List<Map<Object,Object>> data) {
               return new byte[0];
            }
         };
      }
   }
}

 

use:

public void exportMonthlyTargetSummary(YearMonth month) {
      List<Map<Object, Object>> data = this.getMonthlyTargetSummary(month);
      ExportUtil.doExport(spotBaseDataFeign.exportFile(transTargetSummaryToExportFormat(data)),"Medium scalar summary" + month.toString() + ".xls");
   }

 

util encapsulation:

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;

import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

public class ExportUtil {

   private static OutputStream getResponseOutputStreamWithFileName(String fileName) throws IOException {
      ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
      HttpServletResponse response = attr.getResponse();
      response.setCharacterEncoding("utf-8");
      // Set encoding format
      response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));
      OutputStream outputStream = response.getOutputStream();
      return outputStream;
   }

   public static <T> void doExport(byte[] bytes, String fileName) {
      OutputStream outputStream = null;
      try {
         outputStream = ExportUtil.getResponseOutputStreamWithFileName(fileName);
         outputStream.write(bytes);
         outputStream.flush();
         outputStream.close();
      }
      catch(IOException e) {
         e.printStackTrace();
      }
   }
}

 

 

 

TRANSLATE with
COPY THE URL BELOW
EMBED THE SNIPPET BELOW IN YOUR SITE
Enable collaborative features and customize widget: Bing Webmaster Portal
 
 
The language of this page is English
 
Translated into Chinese (Simplified)
 
 
 
 
  • Chinese (Simplified)
  • Chinese (traditional)
  • Danish
  • Ukrainian
  • Urdu
  • Armenian
  • Russian
  • Bulgarian
  • Croatian
  • Icelandic
  • Catalan
  • Hungarian
  • Kanada
  • Hindi
  • Indonesian
  • Gujarati
  • kazakh
  • Turkish
  • Welsh
  • Bengali
  • Nepali
  • Boolean (Afrikaans)
  • Hebrew
  • Greek
  • Kurdish language
  • German
  • Italian
  • Latvian
  • norwegian
  • Czech
  • Slovak
  • Slovenian
  • Punjabi
  • Japanese
  • Pashto
  • Maori
  • French
  • Polish
  • farsi
  • Telugu
  • Tamil
  • Thai
  • Haitian Creole
  • Estonian
  • Swedish
  • Lithuanian
  • Burmese
  • romanian
  • Lao
  • Finnish
  • English
  • Dutch
  • Samoan
  • Portuguese
  • Spanish
  • Vietnamese
  • Azerbaijani
  • Amharic
  • albanian
  • Arabic
  • Korean
  • Margash
  • Marathi
  • Malayalam
  • Malay
  • Maltese
  • Khmer
 
Translate English into Chinese (Simplified) PRO at any time
No translation of English
No translation of i.cnblogs com

Posted by L on Fri, 06 May 2022 06:55:37 +0300