WIP:三方对接逻辑

This commit is contained in:
ZZ 2021-11-09 16:29:53 +08:00
parent 93e2f109bb
commit 2280e9af5e
16 changed files with 565 additions and 212 deletions

View File

@ -15,7 +15,7 @@ public class StartChargeRequest {
@JsonProperty("StartChargeSeq") @JsonProperty("StartChargeSeq")
String startChargeSeq; String startChargeSeq;
@JsonProperty("ConnectorId") @JsonProperty("ConnectorID")
String connectorId; String connectorId;
@JsonProperty("QRCode") @JsonProperty("QRCode")
@ -24,10 +24,16 @@ public class StartChargeRequest {
@JsonProperty("PlateNum") @JsonProperty("PlateNum")
String plateNum; String plateNum;
@JsonProperty("CarPlateNo")
String plateNum2;
@JsonProperty("ChargingAmt") @JsonProperty("ChargingAmt")
Integer chargingAmt; Integer chargingAmt;
@JsonProperty("driverId") @JsonProperty("driverId")
String driverId; String driverId;
@JsonProperty("UserId")
String userId3rdpty;
} }

View File

@ -63,7 +63,12 @@ public class Aes128Cbc {
NoSuchAlgorithmException, IllegalBlockSizeException, UnsupportedEncodingException, NoSuchPaddingException, NoSuchAlgorithmException, IllegalBlockSizeException, UnsupportedEncodingException, NoSuchPaddingException,
InvalidKeyException { InvalidKeyException {
System.out.println(encrypt("{\"PageNo\": \"1\", \"PageSize\": 49}", "8LpncubmWiPCzY3V", "av6A8QdnRaVRMXu6")); System.out.println(decryptString("6vjf229/jP0V/lvorkuYeRSKiv" +
"+A2CMWqPaFVhjebxCxkYmRObUp9I8EoXkHLoeHYRVZwlG47PQ1N4YIn6B5bvtpP4hmFkgHvNzg7UW5+GnCSKxV9RBXxGW" +
"/uWDiPQbgh6gflk4Ia/zvgD9ZLTyAXAm4in/dYovaWcHm08fZ" +
"+xfGoHENu1taQO7BcWidJJtmPkVAWECKTHEbcoFcZagKjHIJV5f7V8OrmawYGQqNmA8=", "8LpncubmWiPCzY3V", "av6A8QdnRaVRMXu6"
));
//ujNoGsWRo5MyPKYOxeofKwgPEng3xF+yhM8DDjwtwHo=
System.out.println(encrypt("{\"StationIDs\":[\"1\"]}", "8LpncubmWiPCzY3V", "av6A8QdnRaVRMXu6")); System.out.println(encrypt("{\"StationIDs\":[\"1\"]}", "8LpncubmWiPCzY3V", "av6A8QdnRaVRMXu6"));
System.out.println(encrypt("{\"OperatorID\":\"MA5FNJXW9\", \"OperatorSecret\":\"Ut5UFdqDthiJyncU\"}", System.out.println(encrypt("{\"OperatorID\":\"MA5FNJXW9\", \"OperatorSecret\":\"Ut5UFdqDthiJyncU\"}",
"8LpncubmWiPCzY3V", "av6A8QdnRaVRMXu6")); "8LpncubmWiPCzY3V", "av6A8QdnRaVRMXu6"));

View File

@ -14,6 +14,7 @@
<groupId>com.xhpc</groupId> <groupId>com.xhpc</groupId>
<artifactId>evcs-common</artifactId> <artifactId>evcs-common</artifactId>
<version>1.0</version> <version>1.0</version>
<scope>compile</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>mysql</groupId> <groupId>mysql</groupId>

View File

@ -53,6 +53,8 @@ public class QueryEquipAuthController {
String terminalStatus = (String) realTimeTerminalData.get("vehicleGunStatus"); String terminalStatus = (String) realTimeTerminalData.get("vehicleGunStatus");
if ("".equals(terminalStatus)) { if ("".equals(terminalStatus)) {
resp.setMsg("gun is not plugging"); resp.setMsg("gun is not plugging");
resp.setRet("1");
equipAuthResponse.setSuccStat(1);
equipAuthResponse.setFailReason(1); equipAuthResponse.setFailReason(1);
} else { } else {
resp.setMsg("success"); resp.setMsg("success");

View File

@ -39,14 +39,15 @@ public class QueryEquipBusinessPolicyController {
commonResponse.setRet("1"); commonResponse.setRet("1");
return commonResponse; return commonResponse;
} }
Long rateModelId = (Long) cachePile.get("rateModelId");
CacheRateModel rateModel = REDIS.getCacheObject("rateModel:" + rateModelId);
String[] tfPricesSeq = rateModel.getTfPricesSeq();
//存储时段
ArrayList<String> modelTypes = new ArrayList<>(); ArrayList<String> modelTypes = new ArrayList<>();
//存储时段个数 //存储时段个数
ArrayList<Integer> modelCount = new ArrayList<>(); ArrayList<Integer> modelCount = new ArrayList<>();
Long rateModelId = (Long) cachePile.get("rateModelId");
CacheRateModel rateModel = REDIS.getCacheObject("rateModel:" + rateModelId);
PolicyInfos[] policyInfosArr = new PolicyInfos[0];
if (rateModel != null) {
String[] tfPricesSeq = rateModel.getTfPricesSeq();
//存储时段
//建立对应时段的映射Map集合存放其对应的价格和服务费 //建立对应时段的映射Map集合存放其对应的价格和服务费
Map<String, Object> timeMap = new HashMap<>(); Map<String, Object> timeMap = new HashMap<>();
//个数计数器 //个数计数器
@ -102,8 +103,7 @@ public class QueryEquipBusinessPolicyController {
timeList.add(finalTime); timeList.add(finalTime);
} }
} }
policyInfosArr = new PolicyInfos[timeList.size()];
PolicyInfos[] policyInfosArr = new PolicyInfos[timeList.size()];
for (int i = 0; i <= timeList.size() - 1; i++) { for (int i = 0; i <= timeList.size() - 1; i++) {
PolicyInfos policyInfos = new PolicyInfos(); PolicyInfos policyInfos = new PolicyInfos();
policyInfos.setStartTime(timeList.get(i)); policyInfos.setStartTime(timeList.get(i));
@ -130,6 +130,7 @@ public class QueryEquipBusinessPolicyController {
} }
policyInfosArr[i] = policyInfos; policyInfosArr[i] = policyInfos;
} }
}
//封装数据 //封装数据
EquipBizResponse equipBizResponse = new EquipBizResponse(); EquipBizResponse equipBizResponse = new EquipBizResponse();

View File

@ -51,13 +51,16 @@ public class QueryStartChargeController {
resp.setMsg("This 3rd has no token"); resp.setMsg("This 3rd has no token");
} else { } else {
// invoke a order making interface(finished); // invoke a order making interface(finished);
R res = pileOrderService.pileStartUpBy3rd(startChargeSeq, startChargeRequest.getDriverId(), startChargeRequest.getChargingAmt(), startChargeRequest.getPlateNum(), 0, connectorID); String plateNum = startChargeRequest.getPlateNum();
plateNum = plateNum == null ? startChargeRequest.getPlateNum2() : plateNum;
R res = pileOrderService.pileStartUpBy3rd(startChargeSeq, startChargeRequest.getDriverId(),
startChargeRequest.getChargingAmt(), plateNum, 0, connectorID);
startChargeResponse.setStartChargeSeq(startChargeSeq); startChargeResponse.setStartChargeSeq(startChargeSeq);
startChargeResponse.setConnectorID(connectorID); startChargeResponse.setConnectorID(connectorID);
if (res.getCode() != 200) { if (res.getCode() != 200) {
startChargeResponse.setSuccStat(1); startChargeResponse.setSuccStat(1);
startChargeResponse.setFailReason(0); startChargeResponse.setFailReason(0);
startChargeResponse.setStartChargeSeqStat(5); startChargeResponse.setStartChargeSeqStat(4);
} else { } else {
Map<String, Object> etOrderData = (Map<String, Object>) res.getData(); Map<String, Object> etOrderData = (Map<String, Object>) res.getData();
EtOrderMapping etOrderMapping = new EtOrderMapping(); EtOrderMapping etOrderMapping = new EtOrderMapping();
@ -81,6 +84,7 @@ public class QueryStartChargeController {
pushOrder.put("chargeOrderInfoNotificationStat", 0); pushOrder.put("chargeOrderInfoNotificationStat", 0);
REDIS.setCacheMap("pushOrder:".concat(orderNo), pushOrder); REDIS.setCacheMap("pushOrder:".concat(orderNo), pushOrder);
} }
resp.setMsg(res.getMsg());
resp.setRet(String.valueOf(res.getCode())); resp.setRet(String.valueOf(res.getCode()));
} }
resp.setData(JSONUtil.toJSONString(startChargeResponse)); resp.setData(JSONUtil.toJSONString(startChargeResponse));

View File

@ -46,9 +46,9 @@ public class QueryStationStatusController {
if (null != chargingStationDto) { if (null != chargingStationDto) {
pileIds = chargingStationDto.getPiles(); pileIds = chargingStationDto.getPiles();
} }
for (String pileId : pileIds) {
boolean existsGun = false; boolean existsGun = false;
List<ConnectorStatusInfo> connectorStatusInfos = new ArrayList<>(); List<ConnectorStatusInfo> connectorStatusInfos = new ArrayList<>();
for (String pileId : pileIds) {
for (String value : gunsIds) { for (String value : gunsIds) {
if (pileId.equals(value.substring(0, 14))) { if (pileId.equals(value.substring(0, 14))) {
existsGun = true; existsGun = true;
@ -63,6 +63,7 @@ public class QueryStationStatusController {
connectorStatusInfos.add(connectorStatusInfo); connectorStatusInfos.add(connectorStatusInfo);
} }
} }
}
if (existsGun) { if (existsGun) {
StationStatusInfo stationStatusInfo = new StationStatusInfo(); StationStatusInfo stationStatusInfo = new StationStatusInfo();
stationStatusInfo.setStationID(stationID); stationStatusInfo.setStationID(stationID);
@ -70,7 +71,6 @@ public class QueryStationStatusController {
stationStatusInfos.add(stationStatusInfo); stationStatusInfos.add(stationStatusInfo);
} }
} }
}
StationStatusInfoWrapper stationStatusInfoWrappers = new StationStatusInfoWrapper(); StationStatusInfoWrapper stationStatusInfoWrappers = new StationStatusInfoWrapper();
stationStatusInfoWrappers.setTotal(stationStatusInfos.size()); stationStatusInfoWrappers.setTotal(stationStatusInfos.size());
@ -79,7 +79,7 @@ public class QueryStationStatusController {
} }
CommonResponse resp = new CommonResponse(); CommonResponse resp = new CommonResponse();
resp.setRet("0"); resp.setRet("0");
resp.setMsg(""); resp.setMsg("Query station status success");
resp.setData(JSONUtil.toJSONString(stationStatusInfoWrappers)); resp.setData(JSONUtil.toJSONString(stationStatusInfoWrappers));
return resp; return resp;
} }

View File

@ -1,15 +1,14 @@
package com.xhpc.evcs.api; package com.xhpc.evcs.api;
import com.fasterxml.jackson.databind.JsonNode;
import com.xhpc.evcs.config.EvcsFilter;
import com.xhpc.evcs.domain.AuthSecretToken; import com.xhpc.evcs.domain.AuthSecretToken;
import com.xhpc.evcs.domain.XhpcInternetUser;
import com.xhpc.evcs.dto.CommonResponse; import com.xhpc.evcs.dto.CommonResponse;
import com.xhpc.evcs.dto.TokenRequest; import com.xhpc.evcs.dto.TokenRequest;
import com.xhpc.evcs.dto.TokenResponse; import com.xhpc.evcs.dto.TokenResponse;
import com.xhpc.evcs.jpa.AuthSecretTokenRepository; import com.xhpc.evcs.jpa.AuthSecretTokenRepository;
import com.xhpc.evcs.jpa.XhpcInternetUserRepository;
import com.xhpc.evcs.utils.JSONUtil; import com.xhpc.evcs.utils.JSONUtil;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestBody;
@ -17,7 +16,10 @@ import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.StandardCharsets; import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Calendar; import java.util.Calendar;
import java.util.Date; import java.util.Date;
import java.util.UUID; import java.util.UUID;
@ -28,6 +30,8 @@ public class QueryTokenController {
@Autowired @Autowired
private AuthSecretTokenRepository authSecretTokenRepository; private AuthSecretTokenRepository authSecretTokenRepository;
@Autowired
private XhpcInternetUserRepository xhpcInternetUserRepository;
@PostMapping("/v1/query_token") @PostMapping("/v1/query_token")
public CommonResponse queryToken(@RequestHeader(value = "enc.out", defaultValue = "true") String encout, public CommonResponse queryToken(@RequestHeader(value = "enc.out", defaultValue = "true") String encout,
@ -37,15 +41,28 @@ public class QueryTokenController {
CommonResponse resp = new CommonResponse(); CommonResponse resp = new CommonResponse();
resp.setRet("0"); resp.setRet("0");
resp.setMsg(""); resp.setMsg("");
String decodedData = (String) tokenRequest.getAdditionalProperties().get("Data");
try {
tokenRequest = JSONUtil.readParams(decodedData, TokenRequest.class);
} catch (Exception e) {
log.error("invalid Data string: {}", decodedData);
}
String operatorID = tokenRequest.getOperatorId(); String operatorID = tokenRequest.getOperatorId();
TokenResponse tokenResponse = new TokenResponse(); TokenResponse tokenResponse = new TokenResponse();
tokenResponse.setOperatorId("MA6DFCTD5"); tokenResponse.setOperatorId("MA6DFCTD5");
tokenResponse.setSuccStat(0); tokenResponse.setSuccStat(0);
tokenResponse.setFailReason(0); tokenResponse.setFailReason(0);
String data = null; String data = null;
XhpcInternetUser xhpcInternetUser =
xhpcInternetUserRepository.findByOperatorIdEvcsAndCooperationStartTimeBeforeAndCooperationEndTimeAfter(tokenRequest.getOperatorId(), Instant.now(), Instant.now());
if (xhpcInternetUser != null) {
String operatorSecret = tokenRequest.getOperatorSecret();
if (operatorSecret == null) {
operatorSecret = tokenRequest.getOperatorSecret();
}
AuthSecretToken authSecretTokenIn = AuthSecretToken authSecretTokenIn =
authSecretTokenRepository.findByOperatorId3irdptyAndSecretTokenTypeAndOperatorSecret( authSecretTokenRepository.findByOperatorId3irdptyAndSecretTokenTypeAndOperatorSecret(
operatorID, AuthSecretToken.SECRET_TOKEN_TYPE_IN, tokenRequest.getOperatorSecret()).orElse(null); operatorID, AuthSecretToken.SECRET_TOKEN_TYPE_IN, operatorSecret).orElse(null);
if (authSecretTokenIn == null) { if (authSecretTokenIn == null) {
resp.setRet("4003"); resp.setRet("4003");
resp.setMsg("Invalid OperatorID/Secret"); resp.setMsg("Invalid OperatorID/Secret");
@ -59,33 +76,31 @@ public class QueryTokenController {
} else { } else {
token = UUID.randomUUID().toString().replaceAll("-", ""); token = UUID.randomUUID().toString().replaceAll("-", "");
authSecretTokenIn.setToken(token); authSecretTokenIn.setToken(token);
authSecretTokenIn.setTokenExpiry(getTokenExpiry()); authSecretTokenIn.setTokenExpiry(getTokenExpiry(xhpcInternetUser));
authSecretTokenRepository.save(authSecretTokenIn); authSecretTokenRepository.save(authSecretTokenIn);
} }
tokenResponse.setAccessToken(token); tokenResponse.setAccessToken(token);
tokenResponse.setTokenAvailableTime(7200); Instant te = authSecretTokenIn.getTokenExpiry().toInstant();
tokenResponse.setTokenAvailableTime(Long.valueOf(ChronoUnit.SECONDS.between(Instant.now(), te)).intValue());
tokenResponse.setSuccStat(0); tokenResponse.setSuccStat(0);
tokenResponse.setFailReason(0); tokenResponse.setFailReason(0);
resp.setMsg("Query token success"); resp.setMsg("Query token success");
resp.setData(JSONUtil.toJSONString(tokenResponse)); resp.setData(JSONUtil.toJSONString(tokenResponse));
byte[] buf = JSONUtil.toJSONString(resp).getBytes(StandardCharsets.UTF_8);
log.debug("out.plain: {}", new String(buf, StandardCharsets.UTF_8));
if (!encout.equalsIgnoreCase("false") || !authSecretTokenIn.isEncrypt()) {
final JsonNode encrypt = EvcsFilter.encryptRespOut(authSecretTokenIn.getDataSecret(),
authSecretTokenIn.getDataSecretIV(), authSecretTokenIn.getSigSecret(), buf);
resp.setData(encrypt.get("Data"));
resp.setSig(encrypt.get("Sig").asText());
log.debug("out.enc: {}", resp);
} }
} }
return resp; return resp;
} }
private Date getTokenExpiry() { private Date getTokenExpiry(XhpcInternetUser xhpcInternetUser) {
DateTime dt = new DateTime(); Instant cooperationEndTime = xhpcInternetUser.getCooperationEndTime();
dt = dt.plusSeconds(7200); LocalDateTime now = LocalDateTime.now();
return dt.toDate(); Instant tokenEndtime = now.plusSeconds(7200).toInstant(ZoneId.systemDefault().getRules().getOffset(now));
if (tokenEndtime.isAfter(cooperationEndTime)) {
return Date.from(cooperationEndTime);
} else {
return Date.from(tokenEndtime);
}
} }
} }

View File

@ -79,7 +79,10 @@ public class EvcsFilter extends OncePerRequestFilter {
AuthSecretToken authSecretTokenIn; AuthSecretToken authSecretTokenIn;
Date now = Calendar.getInstance().getTime(); Date now = Calendar.getInstance().getTime();
ContentCachingResponseWrapper responseWrapper = new ContentCachingResponseWrapper(response); ContentCachingResponseWrapper responseWrapper = new ContentCachingResponseWrapper(response);
if (authorization != null && authorization.startsWith("Bearer ")) { if (servletPath.endsWith("query_token")) {
handleQueryToken(request, response, chain, requestWrapper, bodyString, commonRequest, operatorId,
responseWrapper);
} else if (authorization != null && authorization.startsWith("Bearer ")) {
String token = authorization.substring(7); String token = authorization.substring(7);
authSecretTokenIn = authSecretTokenIn =
authSecretTokenRepository.findByOperatorId3irdptyAndSecretTokenTypeAndTokenExpiryGreaterThan( authSecretTokenRepository.findByOperatorId3irdptyAndSecretTokenTypeAndTokenExpiryGreaterThan(
@ -94,41 +97,6 @@ public class EvcsFilter extends OncePerRequestFilter {
chain.doFilter(requestWrapper, responseWrapper); chain.doFilter(requestWrapper, responseWrapper);
return; return;
} }
} else if (authorization == null) { //todo giv't better arrangement
if (servletPath.endsWith("/query_token")) {
authSecretTokenIn = authSecretTokenRepository.findByOperatorId3irdptyAndSecretTokenType(operatorId,
AuthSecretToken.SECRET_TOKEN_TYPE_IN).orElse(null);
if (authSecretTokenIn == null) {
CommonResponse resp = new CommonResponse();
resp.setRet("4003");
resp.setMsg("Invalid OperatorID");
String data = JSONUtil.toJSONString(resp);
response.getOutputStream().write(data.getBytes(StandardCharsets.UTF_8));
// response.setStatus(403);
responseWrapper = new ContentCachingResponseWrapper(response);
chain.doFilter(requestWrapper, responseWrapper);
return;
} else {
final byte[] decrypt;
try {
decrypt = decrypt(request, authSecretTokenIn, commonRequest, bodyString);
} catch (BadPaddingException | InvalidAlgorithmParameterException | NoSuchAlgorithmException | IllegalBlockSizeException | NoSuchPaddingException | InvalidKeyException e) {
e.printStackTrace();
CommonResponse resp = new CommonResponse();
resp.setRet("4003");
resp.setMsg("Invalid Encryption");
String data = JSONUtil.toJSONString(resp);
response.getOutputStream().write(data.getBytes(StandardCharsets.UTF_8));
chain.doFilter(requestWrapper, responseWrapper);
return;
}
((HttpServletRequestRepeatReadWrapper) requestWrapper).setBody(decrypt);
chain.doFilter(requestWrapper, response);
return;
}
}
} }
//decrypt request //decrypt request
byte[] decryptedReq = null; byte[] decryptedReq = null;
@ -136,14 +104,17 @@ public class EvcsFilter extends OncePerRequestFilter {
CommonResponse resp = new CommonResponse(); CommonResponse resp = new CommonResponse();
authSecretTokenIn = authSecretTokenRepository.findByOperatorId3irdptyAndSecretTokenType(operatorId, authSecretTokenIn = authSecretTokenRepository.findByOperatorId3irdptyAndSecretTokenType(operatorId,
AuthSecretToken.SECRET_TOKEN_TYPE_IN).orElse(null); AuthSecretToken.SECRET_TOKEN_TYPE_IN).orElse(null);
if (authSecretTokenIn != null if (authSecretTokenIn != null) {
&& now.before(authSecretTokenIn.getTokenExpiry()) if (servletPath.endsWith("query_token") ||
&& authorization != null && authorization.substring(7).equals(authSecretTokenIn.getToken())) { (now.before(authSecretTokenIn.getTokenExpiry())
&& authorization != null && authorization.substring(7).equals(authSecretTokenIn.getToken()))) {
try { try {
if (authSecretTokenIn.isEncrypt() && !"false".equals(encin)) { if (authSecretTokenIn.isEncrypt() && !"false".equals(encin)) {
decryptedReq = decrypt(request, authSecretTokenIn, commonRequest, bodyString); decryptedReq = decrypt(request, authSecretTokenIn, commonRequest, bodyString);
} else { } else {
decryptedReq = commonRequest.getData().getBytes(StandardCharsets.UTF_8); String data = commonRequest.getData();
if (data == null) data = bodyString;
decryptedReq = data.getBytes(StandardCharsets.UTF_8);
} }
commonRequest.setData(new String(decryptedReq)); commonRequest.setData(new String(decryptedReq));
log.debug("in.dec: {}", commonRequest); log.debug("in.dec: {}", commonRequest);
@ -153,6 +124,7 @@ public class EvcsFilter extends OncePerRequestFilter {
} else { } else {
erroMsg = "Authorization error, check OperatorID or token expiry"; erroMsg = "Authorization error, check OperatorID or token expiry";
} }
}
if (decryptedReq != null && decryptedReq.length > 0) { if (decryptedReq != null && decryptedReq.length > 0) {
requestWrapper = new HttpServletRequestWritableWrapper(request, requestWrapper = new HttpServletRequestWritableWrapper(request,
JSONUtil.toJSONString(commonRequest).getBytes(StandardCharsets.UTF_8)); JSONUtil.toJSONString(commonRequest).getBytes(StandardCharsets.UTF_8));
@ -193,11 +165,47 @@ public class EvcsFilter extends OncePerRequestFilter {
resp.setMsg("Encryption error"); resp.setMsg("Encryption error");
String data = JSONUtil.toJSONString(resp); String data = JSONUtil.toJSONString(resp);
response.getOutputStream().write(data.getBytes(StandardCharsets.UTF_8)); response.getOutputStream().write(data.getBytes(StandardCharsets.UTF_8));
chain.doFilter(requestWrapper, responseWrapper); // chain.doFilter(requestWrapper, responseWrapper);
} }
} }
} }
private void handleQueryToken(HttpServletRequest request,
HttpServletResponse response, FilterChain chain,
ServletRequest requestWrapper, String bodyString, CommonRequest commonRequest,
String operatorId,
ContentCachingResponseWrapper responseWrapper) throws IOException, ServletException {
AuthSecretToken authSecretTokenIn = authSecretTokenRepository.findByOperatorId3irdptyAndSecretTokenType(operatorId,
AuthSecretToken.SECRET_TOKEN_TYPE_IN).orElse(null);
if (authSecretTokenIn == null) {
CommonResponse resp = new CommonResponse();
resp.setRet("4003");
resp.setMsg("Invalid OperatorID");
String data = JSONUtil.toJSONString(resp);
response.getOutputStream().write(data.getBytes(StandardCharsets.UTF_8));
// response.setStatus(403);
responseWrapper = new ContentCachingResponseWrapper(response);
// chain.doFilter(requestWrapper, responseWrapper);
} else {
final byte[] decrypt;
try {
decrypt = decrypt(request, authSecretTokenIn, commonRequest, bodyString);
} catch (BadPaddingException | InvalidAlgorithmParameterException | NoSuchAlgorithmException | IllegalBlockSizeException | NoSuchPaddingException | InvalidKeyException e) {
e.printStackTrace();
CommonResponse resp = new CommonResponse();
resp.setRet("4003");
resp.setMsg("Invalid Encryption");
String data = JSONUtil.toJSONString(resp);
response.getOutputStream().write(data.getBytes(StandardCharsets.UTF_8));
// chain.doFilter(requestWrapper, responseWrapper);
return;
}
((HttpServletRequestRepeatReadWrapper) requestWrapper).setBody(decrypt);
// chain.doFilter(requestWrapper, response);
}
}
private byte[] internalError() { private byte[] internalError() {
CommonResponse resp = new CommonResponse(); CommonResponse resp = new CommonResponse();
@ -295,12 +303,14 @@ public class EvcsFilter extends OncePerRequestFilter {
JsonNode timestampNode = rootNode.path("TimeStamp"); JsonNode timestampNode = rootNode.path("TimeStamp");
JsonNode seqNode = rootNode.path("Seq"); JsonNode seqNode = rootNode.path("Seq");
if (!dataNode.isNull()) { if (!dataNode.isNull()) {
if (!dataNode.asText().startsWith("{")) {
String computedSig = HMAC.hmacDigest( String computedSig = HMAC.hmacDigest(
operatorIDNode.asText().concat(dataNode.asText()).concat(timestampNode.asText()).concat(seqNode.asText()), operatorIDNode.asText().concat(dataNode.asText()).concat(timestampNode.asText()).concat(seqNode.asText()),
authSecretToken.getSigSecret()); authSecretToken.getSigSecret());
if ((encin == null || !"false".equals(encin)) && !computedSig.equals(sigNode.asText())) { if ((encin == null || !"false".equals(encin)) && !computedSig.equals(sigNode.asText())) {
throw new InvalidAlgorithmParameterException("Illegal Sig, computed: ".concat(computedSig)); throw new InvalidAlgorithmParameterException("Illegal Sig, computed: ".concat(computedSig));
} }
}
String rawData = dataNode.asText(); String rawData = dataNode.asText();
String decryptedData = rawData; String decryptedData = rawData;
if ((encin == null || encin.equals("true")) || authSecretToken.isEncrypt()) { if ((encin == null || encin.equals("true")) || authSecretToken.isEncrypt()) {

View File

@ -0,0 +1,19 @@
package com.xhpc.evcs.jpa;
import com.xhpc.evcs.domain.XhpcInternetUser;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.query.QueryByExampleExecutor;
import org.springframework.stereotype.Repository;
import java.time.Instant;
@Repository
public interface XhpcInternetUserRepository extends JpaRepository<XhpcInternetUser, Long>,
QueryByExampleExecutor<XhpcInternetUser>, JpaSpecificationExecutor<XhpcInternetUser> {
XhpcInternetUser findByOperatorIdEvcsAndCooperationStartTimeBeforeAndCooperationEndTimeAfter(String operatorId3rdpty,
Instant now, Instant now2);
}

View File

@ -14,8 +14,8 @@
<version>1.0</version> <version>1.0</version>
<modules> <modules>
<module>evcs-core</module>
<module>evcs-common</module> <module>evcs-common</module>
<module>evcs-core</module>
</modules> </modules>
<description> <description>

View File

@ -67,5 +67,10 @@ public interface PileOrderService {
@GetMapping(value = "/chargeOrder/pileStartUpBy3rd") @GetMapping(value = "/chargeOrder/pileStartUpBy3rd")
R pileStartUpBy3rd(@RequestParam(value = "internetSerialNumber") String internetSerialNumber, @RequestParam(value = "driverId") String driverId, @RequestParam(value = "chargingAmt") Integer chargingAmt, @RequestParam(value = "plateNum", required = false) String plateNum, @RequestParam(value = "status") Integer status, @RequestParam(value = "connectorId") String connectorId); R pileStartUpBy3rd(@RequestParam(value = "internetSerialNumber") String internetSerialNumber,
@RequestParam(value = "driverId", required = false) String driverId,
@RequestParam(value = "chargingAmt", required = false, defaultValue = "500") Integer chargingAmt,
@RequestParam(value = "plateNum", required = false) String plateNum,
@RequestParam(value = "status") Integer status,
@RequestParam(value = "connectorId") String connectorId);
} }

View File

@ -54,7 +54,7 @@ public class PileOrderFallbackFactory implements FallbackFactory<PileOrderServic
@Override @Override
public R pileStartUpBy3rd(String internetSerialNumber, String driverId, Integer chargingAmt, String plateNum, Integer status, String connectorId) { public R pileStartUpBy3rd(String internetSerialNumber, String driverId, Integer chargingAmt, String plateNum, Integer status, String connectorId) {
return R.fail("通过第三方创建充电订单失败:" + cause.getMessage()); return R.fail("互联网订单启动失败:" + cause.getMessage());
} }
}; };
} }

View File

@ -0,0 +1,274 @@
package com.xhpc.evcs.domain;
import com.xhpc.common.core.web.domain.BaseEntity;
import javax.persistence.*;
import java.time.Instant;
@Table(name = "xhpc_internet_user")
@Entity
public class XhpcInternetUser extends BaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "internet_user_id", nullable = false)
private Long id;
@Column(name = "name", length = 30)
private String name;
@Column(name = "phone", length = 11)
private String phone;
@Column(name = "contact_name", length = 30)
private String contactName;
@Column(name = "contact_phone", length = 20)
private String contactPhone;
@Column(name = "open_bank", length = 20)
private String openBank;
@Column(name = "card_number", length = 100)
private String cardNumber;
@Column(name = "cooperation_start_time")
private Instant cooperationStartTime;
@Column(name = "cooperation_end_time")
private Instant cooperationEndTime;
@Column(name = "balance")
private Double balance;
@Column(name = "area_code")
private Integer areaCode;
@Column(name = "address", length = 50)
private String address;
@Column(name = "detailed_address", length = 50)
private String detailedAddress;
@Column(name = "commission_type")
private Integer commissionType;
@Column(name = "commission_rate")
private Double commissionRate;
@Column(name = "longitude", length = 30)
private String longitude;
@Column(name = "latitude", length = 30)
private String latitude;
@Column(name = "status")
private Integer status;
@Column(name = "del_flag")
private Character delFlag;
@Column(name = "operator_id_evcs", length = 20)
private String operatorIdEvcs;
public String getOperatorIdEvcs() {
return operatorIdEvcs;
}
public void setOperatorIdEvcs(String operatorIdEvcs) {
this.operatorIdEvcs = operatorIdEvcs;
}
public Character getDelFlag() {
return delFlag;
}
public void setDelFlag(Character delFlag) {
this.delFlag = delFlag;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getLatitude() {
return latitude;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public Double getCommissionRate() {
return commissionRate;
}
public void setCommissionRate(Double commissionRate) {
this.commissionRate = commissionRate;
}
public Integer getCommissionType() {
return commissionType;
}
public void setCommissionType(Integer commissionType) {
this.commissionType = commissionType;
}
public String getDetailedAddress() {
return detailedAddress;
}
public void setDetailedAddress(String detailedAddress) {
this.detailedAddress = detailedAddress;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Integer getAreaCode() {
return areaCode;
}
public void setAreaCode(Integer areaCode) {
this.areaCode = areaCode;
}
public Double getBalance() {
return balance;
}
public void setBalance(Double balance) {
this.balance = balance;
}
public Instant getCooperationEndTime() {
return cooperationEndTime;
}
public void setCooperationEndTime(Instant cooperationEndTime) {
this.cooperationEndTime = cooperationEndTime;
}
public Instant getCooperationStartTime() {
return cooperationStartTime;
}
public void setCooperationStartTime(Instant cooperationStartTime) {
this.cooperationStartTime = cooperationStartTime;
}
public String getCardNumber() {
return cardNumber;
}
public void setCardNumber(String cardNumber) {
this.cardNumber = cardNumber;
}
public String getOpenBank() {
return openBank;
}
public void setOpenBank(String openBank) {
this.openBank = openBank;
}
public String getContactPhone() {
return contactPhone;
}
public void setContactPhone(String contactPhone) {
this.contactPhone = contactPhone;
}
public String getContactName() {
return contactName;
}
public void setContactName(String contactName) {
this.contactName = contactName;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}

View File

@ -438,7 +438,13 @@ public class XhpcPileOrderController extends BaseController {
// } // }
// } // }
@GetMapping(value = "/chargeOrder/pileStartUpBy3rd") @GetMapping(value = "/chargeOrder/pileStartUpBy3rd")
public R pileStartUpBy3rd(@RequestParam(value = "internetSerialNumber") String internetSerialNumber, @RequestParam(value = "driverId") String driverId, @RequestParam(value = "chargingAmt") Integer chargingAmt, @RequestParam(value = "plateNum", required = false) String plateNum, @RequestParam(value = "status") Integer status, @RequestParam(value = "connectorId") String connectorId) { public R pileStartUpBy3rd(@RequestParam(value = "internetSerialNumber") String internetSerialNumber,
@RequestParam(value = "driverId", required = false) String driverId,
@RequestParam(value = "chargingAmt", required = false, defaultValue = "500") Integer chargingAmt,
@RequestParam(value = "plateNum", required = false) String plateNum,
@RequestParam(value = "status") Integer status,
@RequestParam(value = "connectorId") String connectorId) {
return xhpcChargeOrderService.startUpBy3rd(internetSerialNumber, driverId, chargingAmt, plateNum, status, connectorId); return xhpcChargeOrderService.startUpBy3rd(internetSerialNumber, driverId, chargingAmt, plateNum, status, connectorId);
} }

View File

@ -20,10 +20,7 @@ import org.springframework.stereotype.Component;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList; import java.util.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static cn.hutool.core.util.NumberUtil.isInteger; import static cn.hutool.core.util.NumberUtil.isInteger;
import static com.xhpc.common.data.redis.StaticBeanUtil.REDIS; import static com.xhpc.common.data.redis.StaticBeanUtil.REDIS;
@ -105,8 +102,8 @@ public class RealtimeDataLogic implements ServiceLogic {
cacheTerminalStatusMap.put(terminalId, statusOrSOC); cacheTerminalStatusMap.put(terminalId, statusOrSOC);
REDIS.setCacheMap(stationTermStatusKey, cacheTerminalStatusMap); REDIS.setCacheMap(stationTermStatusKey, cacheTerminalStatusMap);
Map<String, Object> cacheOrder = REDIS.getCacheMap(orderkey); Map<String, Object> cacheOrder = REDIS.getCacheMap(orderkey);
List<CacheRealtimeData> realtimeDataList = (List<CacheRealtimeData>) cacheOrder.get("realtimeDataList");
if (!orderNo.equals("00000000000000000000000000000000") && statusInt == 3) { if (!orderNo.equals("00000000000000000000000000000000") && statusInt == 3) {
List<CacheRealtimeData> realtimeDataList = (List<CacheRealtimeData>) cacheOrder.get("realtimeDataList");
cacheGun.put("idleCnt", 0); cacheGun.put("idleCnt", 0);
if (realtimeDataList == null) { if (realtimeDataList == null) {
realtimeDataList = new ArrayList<>(); realtimeDataList = new ArrayList<>();
@ -177,15 +174,23 @@ public class RealtimeDataLogic implements ServiceLogic {
Integer idleCnt = (Integer) cacheGun.get("idleCnt"); Integer idleCnt = (Integer) cacheGun.get("idleCnt");
idleCnt = idleCnt == null ? 0 : idleCnt; idleCnt = idleCnt == null ? 0 : idleCnt;
idleCnt++; idleCnt++;
if (idleCnt > 3 && orderkey != null) { if (idleCnt > 3) {
if (orderkey != null) {
Map<String, Object> problematicOrder = REDIS.getCacheMap(orderkey); Map<String, Object> problematicOrder = REDIS.getCacheMap(orderkey);
Object orderData = problematicOrder.get("orderData"); Object orderData = problematicOrder.get("orderData");
String status = (String) problematicOrder.get("status"); String status = (String) problematicOrder.get("status");
if (!isInteger(status) && !status.equals("充电中") && orderData == null) { if (!isInteger(status) && !status.equals("充电中") && orderData == null) {
pileOrderService.abnormalOrder(orderNo); pileOrderService.abnormalOrder(orderNo);
log.error("abnormal order[{}]", orderNo);
cacheGun.put("orderkey", null); cacheGun.put("orderkey", null);
idleCnt = 0; idleCnt = 0;
} }
} else {
Collection<String> cacheOrderKyes = REDIS.keys("order:".concat(terminalId).concat("*"));
for (String cacheOrderKye : cacheOrderKyes) {
}
}
} }
cacheGun.put("idleCnt", idleCnt); cacheGun.put("idleCnt", idleCnt);
} }