新增部分异常处理(源数据有误或为空时)

更改响应类的数据结构
main
lensfrex 3 years ago
parent 3756c9f91a
commit 51e4a56177
Signed by: lensfrex
GPG Key ID: 947ADABD8533C476
  1. 17
      .idea/compiler.xml
  2. 20
      .idea/jarRepositories.xml
  3. 13
      .idea/libraries/Maven__org_projectlombok_lombok_1_18_22.xml
  4. 7
      .idea/misc.xml
  5. 25
      vegetables/pom.xml
  6. 0
      vegetables/resources/empty.txt
  7. 4
      vegetables/resources/worn.txt
  8. 17
      vegetables/src/main/java/me/lensfrex/vegetables/VegetablesMain.java
  9. 19
      vegetables/src/main/java/me/lensfrex/vegetables/data/Vegetable.java
  10. 0
      vegetables/src/main/java/me/lensfrex/vegetables/exceptions/IllegalPageParamException.java
  11. 0
      vegetables/src/main/java/me/lensfrex/vegetables/exceptions/RequestPageTooLargeException.java
  12. 7
      vegetables/src/main/java/me/lensfrex/vegetables/exceptions/SourceDataWornException.java
  13. 22
      vegetables/src/main/java/me/lensfrex/vegetables/resopnse/ResponseGenerator.java
  14. 26
      vegetables/src/main/java/me/lensfrex/vegetables/resopnse/ResponseProcessor.java
  15. 48
      vegetables/src/main/java/me/lensfrex/vegetables/resopnse/ResponseTool.java
  16. 32
      vegetables/src/main/java/me/lensfrex/vegetables/resopnse/ResultStatus.java
  17. 41
      vegetables/src/main/java/me/lensfrex/vegetables/resopnse/UnityResponse.java
  18. 0
      vegetables/src/main/java/me/lensfrex/vegetables/utils/IOUtils.java
  19. 24
      vegetables/src/me/lensfrex/vegetables/resopnse/ResponseTool.java
  20. 94
      vegetables/src/me/lensfrex/vegetables/resopnse/UnityResponse.java
  21. 13
      vegetables/vegetables.iml

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<annotationProcessing>
<profile default="true" name="Default" enabled="true" />
<profile name="Maven default annotation processors profile" enabled="true">
<sourceOutputDir name="target/generated-sources/annotations" />
<sourceTestOutputDir name="target/generated-test-sources/test-annotations" />
<outputRelativeToContentRoot value="true" />
<module name="vegetables" />
</profile>
</annotationProcessing>
<bytecodeTargetLevel>
<module name="vegetables" target="8" />
</bytecodeTargetLevel>
</component>
</project>

@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="RemoteRepositoriesConfiguration">
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Central Repository" />
<option name="url" value="https://repo.maven.apache.org/maven2" />
</remote-repository>
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Maven Central repository" />
<option name="url" value="https://repo1.maven.org/maven2" />
</remote-repository>
<remote-repository>
<option name="id" value="jboss.community" />
<option name="name" value="JBoss Community repository" />
<option name="url" value="https://repository.jboss.org/nexus/content/repositories/public/" />
</remote-repository>
</component>
</project>

@ -0,0 +1,13 @@
<component name="libraryTable">
<library name="Maven: org.projectlombok:lombok:1.18.22">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/projectlombok/lombok/1.18.22/lombok-1.18.22.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/org/projectlombok/lombok/1.18.22/lombok-1.18.22-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/org/projectlombok/lombok/1.18.22/lombok-1.18.22-sources.jar!/" />
</SOURCES>
</library>
</component>

@ -1,5 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="MavenProjectsManager">
<option name="originalFiles">
<list>
<option value="$PROJECT_DIR$/vegetables/pom.xml" />
</list>
</option>
</component>
<component name="ProjectRootManager" version="2" project-jdk-name="1.8" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>

@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>vegetables</groupId>
<artifactId>vegetables</artifactId>
<version>0.0.0</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.22</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>

@ -0,0 +1,4 @@
大白菜 1.4 1.7 2.0 2022-03-24 00:00:00
大白菜 2.5 2.6 2.7 2022-03-24 00:00:00
娃娃菜 1.5 1.6s5 1.8 2022-03-24 00:00:00
小白菜 1.2 1.35 1.5 2022-03-24 00:00:00

@ -1,6 +1,7 @@
package me.lensfrex.vegetables;
import me.lensfrex.vegetables.data.Vegetable;
import me.lensfrex.vegetables.resopnse.ResponseProcessor;
import me.lensfrex.vegetables.resopnse.UnityResponse;
import java.util.ArrayList;
@ -18,6 +19,22 @@ public class VegetablesMain {
UnityResponse<ArrayList<Vegetable>> response = null;
ResponseProcessor responseProcessor = null;
// 测试数据部分不正确时
responseProcessor = new ResponseProcessor(System.getProperty("user.dir") + "/resources/worn.txt");
response = responseProcessor.getListPage(1, 10);
System.out.println("------------------------------------");
System.out.println("测试:数据部分不正确时");
System.out.println(response);
System.out.println("------------------------------------");
// 测试数据为空时
responseProcessor = new ResponseProcessor(System.getProperty("user.dir") + "/resources/empty.txt");
response = responseProcessor.getListPage(1, 10);
System.out.println("------------------------------------");
System.out.println("测试:数据空时");
System.out.println(response);
System.out.println("------------------------------------");
if (args.length != 0) {
System.out.println("Read source data from: " + args[0]);
responseProcessor = new ResponseProcessor(args[0]);

@ -1,10 +1,13 @@
package me.lensfrex.vegetables.data;
import lombok.Data;
import java.util.Arrays;
/**
* Vegetable的信息数据类仅用于存储相关的数据结构
*/
@Data
public class Vegetable {
public static final int PRICE_MIN = 0;
public static final int PRICE_AVG = 1;
@ -15,14 +18,6 @@ public class Vegetable {
private String priceDate;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice(int priceType) {
return price[priceType];
}
@ -31,14 +26,6 @@ public class Vegetable {
this.price[priceType] = price;
}
public String getPriceDate() {
return priceDate;
}
public void setPriceDate(String priceDate) {
this.priceDate = priceDate;
}
@Override
public String toString() {
return "{" +

@ -0,0 +1,7 @@
package me.lensfrex.vegetables.exceptions;
public class SourceDataWornException extends Exception {
public SourceDataWornException(String message) {
super(message);
}
}

@ -0,0 +1,22 @@
package me.lensfrex.vegetables.resopnse;
public class ResponseGenerator {
/**
* 构建请求成功的响应返回类
* @param data 请求到的数据
* @param <T> 请求的数据类型
* @return 构建出的请求响应类
*/
public static <T> UnityResponse<T> success(T data) {
return new UnityResponse<>(ResultStatus.SUCCESS, data);
}
/**
* 构建请求失败的响应返回类
* @param resultStatus 指定状态信息
* @return 构建出的请求响应类
*/
public static <T> UnityResponse<T> error(ResultStatus resultStatus) {
return new UnityResponse<>(resultStatus, null);
}
}

@ -1,10 +1,9 @@
package me.lensfrex.vegetables;
package me.lensfrex.vegetables.resopnse;
import me.lensfrex.vegetables.data.Vegetable;
import me.lensfrex.vegetables.exceptions.IllegalPageParamException;
import me.lensfrex.vegetables.exceptions.RequestPageTooLargeException;
import me.lensfrex.vegetables.resopnse.ResponseTool;
import me.lensfrex.vegetables.resopnse.UnityResponse;
import me.lensfrex.vegetables.exceptions.SourceDataWornException;
import me.lensfrex.vegetables.utils.IOUtils;
import java.util.ArrayList;
@ -16,10 +15,11 @@ import java.util.LinkedList;
*/
public class ResponseProcessor {
public final String sourceFilePath;
private final String sourceFilePath;
/**
* 初始化ResponseProcessor实例并指定源数据文件的路径
*
* @param sourceFilePath 数据源文件路径
*/
public ResponseProcessor(String sourceFilePath) {
@ -28,12 +28,13 @@ public class ResponseProcessor {
/**
* 从文件中读取并根据参数进行分页
* @param pageNum 页码从1开始
*
* @param pageNum 页码从1开始
* @param pageSize 每页结果的数量
* @return UnityResponse<ArrayList<Vegetable>> 统一的响应类
* @return UnityResponse<ArrayList < Vegetable>> 统一的响应类
*/
public UnityResponse<ArrayList<Vegetable>> getListPage(int pageNum, int pageSize) {
Tools tools = new Tools();
ResponseTool tools = new ResponseTool();
try {
LinkedList<String> sourceData = IOUtils.getListFromFile(sourceFilePath);
@ -41,16 +42,19 @@ public class ResponseProcessor {
ArrayList<Vegetable> result = new ArrayList<>(tools.getListPage(pageNum, pageSize, allVegetables));
return ResponseTool.success(result, "成功");
return ResponseGenerator.success(result);
} catch (RequestPageTooLargeException e) {
e.printStackTrace();
return ResponseTool.error("请求的页码超过最大值", UnityResponse.ResultCode.PAGE_OUT_OF_MAX);
return ResponseGenerator.error(ResultStatus.PAGE_OUT_OF_RANGE);
} catch (IllegalPageParamException e) {
e.printStackTrace();
return ResponseTool.error("请求的分页参数有误", UnityResponse.ResultCode.PAGE_PARAM_WORN);
return ResponseGenerator.error(ResultStatus.PAGE_PARAM_WORN);
} catch (SourceDataWornException e) {
e.printStackTrace();
return ResponseGenerator.error(ResultStatus.SOURCE_DATA_WORN);
} catch (Exception e) {
e.printStackTrace();
return ResponseTool.error("未知错误", UnityResponse.ResultCode.UNKNOWN_ERROR);
return ResponseGenerator.error(ResultStatus.UNKNOWN_ERROR);
}
}
}

@ -1,8 +1,9 @@
package me.lensfrex.vegetables;
package me.lensfrex.vegetables.resopnse;
import me.lensfrex.vegetables.data.Vegetable;
import me.lensfrex.vegetables.exceptions.IllegalPageParamException;
import me.lensfrex.vegetables.exceptions.RequestPageTooLargeException;
import me.lensfrex.vegetables.exceptions.SourceDataWornException;
import java.util.LinkedList;
import java.util.List;
@ -11,10 +12,7 @@ import java.util.List;
* 请求处理工具
* 由于功能较为简单目前仅有获取分页数据的功能
*/
public class Tools {
// 测试用路径,使用前记得改 :P
// public static final String SOURCE_FILE_PATH = "C:\\Users\\lenfrex\\projects\\AmberGround\\vegetables\\resources\\vegetables.txt";
public class ResponseTool {
/**
* 根据给定的页索引以及页大小对全部蔬菜数据进行分页并返回分页后的List
*
@ -26,7 +24,7 @@ public class Tools {
* @throws IllegalPageParamException 如果分页请求的参数不对
*/
public List<Vegetable> getListPage(int pageNum, int pageSize, List<Vegetable> allVegetableList)
throws RequestPageTooLargeException, IllegalPageParamException {
throws RequestPageTooLargeException, IllegalPageParamException, SourceDataWornException {
// 请求的分页大小或页码非法
if (pageNum <= 0 || pageSize <= 0) {
@ -37,12 +35,15 @@ public class Tools {
int resultSize = allVegetableList.size();
// 判断上一页的记录是不是已经超过最后一条记录,防止页码超过最大值
if ((pageNum - 1)*pageSize >= resultSize) {
if ((pageNum - 1) * pageSize >= resultSize) {
if (allVegetableList.isEmpty()) {
throw new SourceDataWornException("源数据为空");
}
throw new RequestPageTooLargeException("请求页码:" + pageNum);
}
LinkedList<Vegetable> pagedVegetableList = new LinkedList<>();
for (int i = (pageNum - 1)*pageSize; (i < pageNum*pageSize && i < resultSize); i++) {
for (int i = (pageNum - 1) * pageSize; (i < pageNum * pageSize && i < resultSize); i++) {
pagedVegetableList.add(allVegetableList.get(i));
}
@ -60,9 +61,16 @@ public class Tools {
public LinkedList<Vegetable> getAllVegetables(LinkedList<String> vegetableStrings) {
LinkedList<Vegetable> vegetables = new LinkedList<>();
for (String vegetableString : vegetableStrings) {
vegetables.add(parseVegetableInfo(vegetableString));
try {
vegetables.add(parseVegetableInfo(vegetableString));
} catch (SourceDataWornException e) {
e.printStackTrace();
// 能成功读到多少就返回多少
return vegetables;
}
}
return vegetables;
}
@ -74,15 +82,23 @@ public class Tools {
* 其中信息日期格式应为 "yyyy-mm-dd hh:mm:ss"
* @return 蔬菜信息数据类
*/
private Vegetable parseVegetableInfo(String vegetableString) {
String[] spilt = vegetableString.split(" ");
private Vegetable parseVegetableInfo(String vegetableString) throws SourceDataWornException {
Vegetable vegetable = new Vegetable();
try {
String[] spilt = vegetableString.split(" ");
vegetable.setName(spilt[0]);
vegetable.setPrice(Double.parseDouble(spilt[1]), Vegetable.PRICE_MIN);
vegetable.setPrice(Double.parseDouble(spilt[2]), Vegetable.PRICE_AVG);
vegetable.setPrice(Double.parseDouble(spilt[3]), Vegetable.PRICE_MAX);
vegetable.setPriceDate(spilt[4] + ' ' + spilt[5]);
vegetable.setName(spilt[0]);
vegetable.setPrice(Double.parseDouble(spilt[1]), Vegetable.PRICE_MIN);
vegetable.setPrice(Double.parseDouble(spilt[2]), Vegetable.PRICE_AVG);
vegetable.setPrice(Double.parseDouble(spilt[3]), Vegetable.PRICE_MAX);
vegetable.setPriceDate(spilt[4] + ' ' + spilt[5]);
} catch (Exception e) {
throw new SourceDataWornException("解析源数据时发生错误:" + e.getMessage()
+ "\n请检查源数据格式是否符合“蔬菜名 最低价(double) 平均价(double) 最高价(double) 信息日期”"
+ "其中信息日期格式应为 \"yyyy-mm-dd hh:mm:ss\""
+ "当前输入为:" + vegetableString);
}
return vegetable;
}

@ -0,0 +1,32 @@
package me.lensfrex.vegetables.resopnse;
public enum ResultStatus {
SUCCESS(200, "成功!"),
EMPTY_DATA(0, "数据是空的"),
PAGE_OUT_OF_RANGE(100, "请求的页码超过最大值"),
PAGE_PARAM_WORN(101, "分页参数有误"),
SOURCE_DATA_WORN(404, "源数据有错误,分页读取失败"),
UNKNOWN_ERROR(503, "未知错误");
/**
* 返回码其值为ResultCode中定义的常量
*/
private final int code;
/**
* 返回的结果信息
*/
private final String message;
ResultStatus(int code, String message) {
this.code = code;
this.message = message;
}
@Override
public String toString() {
return "code: " + code + ", " +
"msg: '" + message + '\'';
}
}

@ -0,0 +1,41 @@
package me.lensfrex.vegetables.resopnse;
import lombok.Data;
/**
* 统一的返回数据结构含有字段code, message, data
*
* @param <T> data的类型
*/
@Data
public class UnityResponse<T> {
/**
* 请求处理的状态信息
*/
private final ResultStatus resultStatus;
/**
* 请求的数据其类型为声明返回类时指定的类型
*/
private T data;
public UnityResponse(ResultStatus resultCodes, T data) {
this.resultStatus = resultCodes;
this.data = data;
}
public UnityResponse() {
resultStatus = ResultStatus.EMPTY_DATA;
this.data = null;
}
// 手动拼成类似json的格式...
// 当然真正生成json还是看gson之类专门的库吧...
@Override
public String toString() {
return "{" + resultStatus +
", data: " + data +
'}';
}
}

@ -1,24 +0,0 @@
package me.lensfrex.vegetables.resopnse;
public class ResponseTool {
/**
* 构建请求成功的响应返回类
* @param data 请求到的数据
* @param message 请求信息
* @param <T> 请求的数据类型
* @return 构建出的请求响应类
*/
public static <T> UnityResponse<T> success(T data, String message) {
return new UnityResponse<>(UnityResponse.ResultCode.SUCCESS, message, data);
}
/**
* 构建请求失败的响应返回类
* @param message 失败信息
* @param code 失败状态码应从UnityResponse.ResultCode中定义的常量中选择
* @return 构建出的请求响应类
*/
public static <T> UnityResponse<T> error(String message, int code) {
return new UnityResponse<>(code, message, null);
}
}

@ -1,94 +0,0 @@
package me.lensfrex.vegetables.resopnse;
/**
* 统一的返回数据结构含有字段code, message, data
*
* @param <T> data的类型
*/
public class UnityResponse<T> {
/**
* 返回码其值为ResultCode中定义的常量
*/
private int code;
/**
* 返回的结果信息
*/
private String message;
/**
* 请求的数据其类型为声明返回类时指定的类型
*/
private T data;
public UnityResponse(int code, String message, T data) {
this.code = code;
this.message = message;
this.data = data;
}
public UnityResponse() {
this.code = ResultCode.EMPTY_DATA;
this.message = "数据未初始化";
this.data = null;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
// 手动拼成json格式...
// 当然真正生成json还是看gson之类的吧...
@Override
public String toString() {
return "{" +
"code=" + code +
", message='" + message + '\'' +
", data=" + data +
'}';
}
/**
* 状态码的常量
*/
public static class ResultCode {
/**
* 请求成功
*/
public static final int SUCCESS = 200;
/**
* 数据是空的
*/
public static final int EMPTY_DATA = 0;
/**
* 请求的分页页码超过最大值
*/
public static final int PAGE_OUT_OF_MAX = 100;
/**
* 请求的分页参数有误
*/
public static final int PAGE_PARAM_WORN = 101;
/**
* 未知错误
*/
public static final int UNKNOWN_ERROR = 503;
}
}

@ -1,11 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_8">
<output url="file://$MODULE_DIR$/target/classes" />
<output-test url="file://$MODULE_DIR$/target/test-classes" />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/test/java" isTestSource="true" />
<excludeFolder url="file://$MODULE_DIR$/target" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.projectlombok:lombok:1.18.22" level="project" />
</component>
</module>
Loading…
Cancel
Save