使用spring boot和mongodb以csv格式生成报告数据的最佳方法是什么?

时间:2017-10-15 20:31:08

标签: java spring rest spring-boot spring-data-mongodb

一旦用户点击给定的uri,我就必须以text-csv格式显示各种案例的报告数据。

给定的案例是

1)End_Customer数据

2)不完整的档案。

3)总连接数

以下是我拥有的用户和登录用户模型。

LoginUser

public class LoginUser {
private String contact;
private String email;
private String address;
private Gender gender;
@Indexed
private String name;
private Date dob;
@Indexed(unique = true)
private String username;

用户

public class User extends LoginUser {
public static final String OBJECT_KEY = "APPUSER";

@Id
private String id;
private String[] imageIds;
private String concerns;
private String summary;
private String likings;
private String occupation;
private String religion;
private String education;
private String height;
@GeoSpatialIndexed(type = GeoSpatialIndexType.GEO_2DSPHERE)
private double[] location;
private INTERESTS[] interests;
private String fcmId;
private List connections;
private List declined;
private List pending;

以下是我编写的代码。

1)对于所有的Uri,我使用了CSV Writer类来编写Header数据。提供给标题数据的输入是通过我为各自的Uri创建的Bean.For For End Customer的示例和不完整的配置文件我使用了用户报告bean,对于Total Connections,我使用了Connections Report bean,因为我们必须显示具有不同标题的不同字段的数据。

2)然后,我使用findAll方法从记录中检索了所有用户。 然后,对于每个用户,我们根据案例

完成了以下任务

a)对于End_Customer

1)对于每个用户,我们检索了特定的用户数据并将其设置在User Report bean中,最后将User Report bean设置为Csv Writer。

b)对于不完整的配置文件

1)对于每个用户,我们检查了是否有任何字段为NULL。如果这是真的,我已将用户数据设置为User Report Bean,然后最终将用户报告Bean设置为Csv Writer。

c)中TotalConnections

对于每个用户,我检查了连接ID(连接ID是包含用户ID的列表的外键)。 对于每个连接ID,我检索了Connected特定于用户的详细信息,并将它们存储在Connections Report Bean中。

下面是

UserReport

public class UserReport {
@Indexed
private String name;
@Indexed(unique = true)
private String username;
private String contact;
private String address;
private String email;
private List connections;
private List pending;
private INTERESTS[] interests;
private String occupation;
private Gender gender;
private String region;

ConnectionsReport

public class ConnectionsReport {
@Indexed
private String name;
@Indexed(unique = true)
private String username;
private List connectionName;
private Set mutualInterest;
private List locations;
private String customerAge;
private List connectionAge;
private Gender customerGender;
private List connectionGender;
private String customerAddress;
private List connectionAddress;

案例1 EndCustomer

@RestController
@RequestMapping("/report")
public class ReportController {
@Autowired
private UserService userService;
@RequestMapping(value = "/endcustomer", method = RequestMethod.GET, produces = "text/csv")
public void endCustomerReport(HttpServletResponse response) {
    ICsvBeanWriter csvWriter=null;
    int pageSize=2000;
    Page<User> users=null;
    int page=0;
    String csvFileName = "End-customer.csv";
    List<String> headerList=null;
    Field[] declaredFields=null;
    UserReport userReport=new UserReport();
    try {
        response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", csvFileName));
         headerList = new ArrayList<>();
         declaredFields = UserReport.class.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            headerList.add(declaredField.getName());
        }

        String[] header = headerList.toArray(new String[]{});
        csvWriter.writeHeader(header);
/*   CsvPreference.STANDARD_PREFERENCE
    Ready to use configuration that should cover 99% of all usages.*/

         csvWriter = new CsvBeanWriter(response.getWriter(),
                CsvPreference.STANDARD_PREFERENCE);

        do {
            users = userService.getAllUsers(new PageRequest(page,pageSize));
            for (User user : users) {
                userReport.setName(user.getName());
                userReport.setUsername(user.getUsername());
                userReport.setContact(user.getContact());
                userReport.setAddress(user.getAddress());
                userReport.setEmail(user.getEmail());
                userReport.setConnections(user.getConnections());
                userReport.setPending(user.getPending());
                userReport.setInterests(user.getInterests());
                userReport.setOccupation(user.getOccupation());
                userReport.setGender(user.getGender());
                csvWriter.write(userReport, header);
            }
            page++;
        }while (users.hasNext());
        }
    catch (IOException e){
        e.printStackTrace();
    }
   finally{
       if(csvWriter!=null){
           try {
               csvWriter.close();
           } catch (IOException e) {
               e.printStackTrace();
           }
       }
    }

}

案例2不完整的个人资料

@RequestMapping(value = "/incompleteProfiles", method = RequestMethod.GET, produces = "text/csv")
public void incompleteProfiles(HttpServletResponse response) {
    ICsvBeanWriter csvWriter=null;
    int pageSize=2000;
    Page<User> users=null;
    int page=0;
    String csvFileName = "IncompleteProfiles.csv";
    List<String> headerList=null;
    Field[] declaredFields=null;
    UserReport userReport=new UserReport();
    try {
        response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", csvFileName));
        headerList = new ArrayList<>();
        declaredFields = UserReport.class.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            headerList.add(declaredField.getName());
        }

        String[] header = headerList.toArray(new String[]{});
        csvWriter.writeHeader(header);
/*   CsvPreference.STANDARD_PREFERENCE
    Ready to use configuration that should cover 99% of all usages.*/

        csvWriter = new CsvBeanWriter(response.getWriter(),
                CsvPreference.STANDARD_PREFERENCE);

        do {
            users = userService.getAllUsers(new PageRequest(page,pageSize));
            for (User user : users) {
                if(user.getName()==null || user.getGender()==null || user.getInterests()==null || user.getImageIds()==null){
                    userReport.setName(user.getName());
                    userReport.setUsername(user.getUsername());
                    userReport.setContact(user.getContact());
                    userReport.setAddress(user.getAddress());
                    userReport.setEmail(user.getEmail());
                    userReport.setConnections(user.getConnections());
                    userReport.setPending(user.getPending());
                    userReport.setInterests(user.getInterests());
                    userReport.setOccupation(user.getOccupation());
                    userReport.setGender(user.getGender());
                }
                csvWriter.write(userReport, header);
            }
            page++;
        }while (users.hasNext());
    }
    catch (IOException e){
        e.printStackTrace();
    }
    finally{
        if(csvWriter!=null){
            try {
                csvWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

案例3 TotalConnections

 @RequestMapping(value = "/totalConnections", method = RequestMethod.GET, produces = "text/csv")
public  void totalConnections(HttpServletResponse response) {
    ICsvBeanWriter csvWriter=null;
    int pageSize=2000;
    Page<User> users=null;
    int page=0;
    String csvFileName = "totalConnections.csv";
    List<String> headerList=null;
    Field[] declaredFields=null;
    ConnectionsReport consreport=new ConnectionsReport();

    try {
        response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", csvFileName));
        headerList = new ArrayList<>();
        declaredFields = ConnectionsReport.class.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            headerList.add(declaredField.getName());
        }

        String[] header = headerList.toArray(new String[]{});
        csvWriter.writeHeader(header);
/*   CsvPreference.STANDARD_PREFERENCE
    Ready to use configuration that should cover 99% of all usages.*/

        csvWriter = new CsvBeanWriter(response.getWriter(),
                CsvPreference.STANDARD_PREFERENCE);

        do {
            users = userService.getAllUsers(new PageRequest(page,pageSize));
            for (User user : users) {
                ArrayList connList=new ArrayList();
                Set mutualInterestList=new HashSet();
                ArrayList locationList=new ArrayList();
                ArrayList ageList=new ArrayList();
                ArrayList genderList=new ArrayList();
                ArrayList addressList=new ArrayList();
                if(user.getConnections()!=null){
                    consreport.setName(user.getName());
                    consreport.setUsername(user.getUsername());
                    List connections=user.getConnections();
                    Iterator it=connections.iterator();
                    LocalDate birthdate = new LocalDate(user.getDob());          //Birth date
                    LocalDate now = new LocalDate();                    //Today's date
                    Period period = new Period(birthdate, now, PeriodType.yearMonthDay());
                    consreport.setCustomerAge(period.getYears()+"");
                    while(it.hasNext()) {
                        String connectionId = (String) it.next();
                        User connectedUser=userService.get(connectionId);

                        connList.add(connectedUser.getName());
                        mutualInterestList.add(connectedUser.getInterests());
                        genderList.add(connectedUser.getGender());
                        addressList.add(connectedUser.getAddress());
                        locationList.add(connectedUser.getLocation());
                        addressList.add(connectedUser.getAddress());
                        LocalDate birthdateconnectedUser = new LocalDate(connectedUser.getDob());          //Birth date
                        Period period1 = new Period(birthdateconnectedUser, now, PeriodType.yearMonthDay());
                        ageList.add(period1.getYears());
                    }
                    consreport.setConnectionName(connList);
                    consreport.setMutualInterest(mutualInterestList);
                    consreport.setLocations(locationList);

                    consreport.setConnectionAge(ageList);
                    consreport.setCustomerGender(user.getGender());
                    consreport.setConnectionGender(genderList);
                    consreport.setCustomerAddress(user.getAddress());
                    consreport.setConnectionAddress(addressList);
                }
                csvWriter.write(consreport, header);
            }
            page++;
        }while (users.hasNext());
    }
    catch (IOException e){
        e.printStackTrace();
    }
    finally{
        if(csvWriter!=null){
            try {
                csvWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

任何人都可以指导我如何优化我的代码。因此,我可以在内存和性能方面提高效率和效率。

0 个答案:

没有答案