Commit 9f8e1dd6 authored by zhouleilei's avatar zhouleilei

新增海信-获取当前方案接口

引用dom4j
parent 9c528862
...@@ -40,25 +40,25 @@ ...@@ -40,25 +40,25 @@
<groupId>org.springframework.cloud</groupId> <groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId> <artifactId>spring-cloud-starter-oauth2</artifactId>
</dependency> </dependency>
<dependency> <!-- <dependency>-->
<groupId>com.wanji</groupId> <!-- <groupId>com.wanji</groupId>-->
<artifactId>identity-client-starter</artifactId> <!-- <artifactId>identity-client-starter</artifactId>-->
<version>1.2</version> <!-- <version>1.2</version>-->
<exclusions> <!-- <exclusions>-->
<exclusion> <!-- <exclusion>-->
<artifactId>springfox-spring-web</artifactId> <!-- <artifactId>springfox-spring-web</artifactId>-->
<groupId>io.springfox</groupId> <!-- <groupId>io.springfox</groupId>-->
</exclusion> <!-- </exclusion>-->
<exclusion> <!-- <exclusion>-->
<artifactId>swagger-annotations</artifactId> <!-- <artifactId>swagger-annotations</artifactId>-->
<groupId>io.swagger</groupId> <!-- <groupId>io.swagger</groupId>-->
</exclusion> <!-- </exclusion>-->
<exclusion> <!-- <exclusion>-->
<artifactId>springfox-core</artifactId> <!-- <artifactId>springfox-core</artifactId>-->
<groupId>io.springfox</groupId> <!-- <groupId>io.springfox</groupId>-->
</exclusion> <!-- </exclusion>-->
</exclusions> <!-- </exclusions>-->
</dependency> <!-- </dependency>-->
<!-- 鉴权包 end --> <!-- 鉴权包 end -->
<dependency> <dependency>
<groupId>io.swagger</groupId> <groupId>io.swagger</groupId>
......
package net.wanji.web.config; //package net.wanji.web.config;
//
import com.wanji.identity.auth.IdentityResourceServerConfig; //import lombok.extern.slf4j.Slf4j;
import lombok.extern.slf4j.Slf4j; //import net.wanji.common.framework.rest.HeaderMapRequestWrapper;
import net.wanji.common.framework.rest.HeaderMapRequestWrapper; //import net.wanji.common.utils.cache.IgniteClientCacheUtil;
import net.wanji.common.utils.cache.IgniteClientCacheUtil; //import net.wanji.common.utils.cookie.CookieUtil;
import net.wanji.common.utils.cookie.CookieUtil; //import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.StringUtils; //import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Configuration; //import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpHeaders; //import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; //import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity; //import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken; //import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; //import org.springframework.security.web.context.SecurityContextPersistenceFilter;
import org.springframework.security.web.context.SecurityContextPersistenceFilter; //import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.filter.OncePerRequestFilter; //
//import javax.servlet.FilterChain;
import javax.servlet.FilterChain; //import javax.servlet.ServletException;
import javax.servlet.ServletException; //import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequest; //import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponse; //import java.io.IOException;
import java.io.IOException; //import java.util.ArrayList;
import java.util.ArrayList; //import java.util.List;
import java.util.List; //
//import static net.wanji.common.framework.Constants.Cache.LOGIN_CACHE;
import static net.wanji.common.framework.Constants.Cache.LOGIN_CACHE; //
///**
/** // * @Description: 资源服务器配置
* @Description: 资源服务器配置 // * @Author
* @Author // * @Date 2020/4/12 21:01
* @Date 2020/4/12 21:01 // */
*/ //@Configuration
@Configuration //@EnableResourceServer
@EnableResourceServer //@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableGlobalMethodSecurity(prePostEnabled = true) //@Slf4j
@Slf4j //public class ResourceServerConfig extends IdentityResourceServerConfig {
public class ResourceServerConfig extends IdentityResourceServerConfig { //
// @Override
@Override // public void configure(HttpSecurity http) throws Exception {
public void configure(HttpSecurity http) throws Exception { //
//// 放开全部
// 放开全部 // http.authorizeRequests()
http.authorizeRequests() // .antMatchers(whiteList.toArray(new String[whiteList.size()])).permitAll()
.antMatchers(whiteList.toArray(new String[whiteList.size()])).permitAll() // .anyRequest().authenticated()
.anyRequest().authenticated() // .and().cors()
.and().cors() // .and().csrf().disable()
.and().csrf().disable() // .addFilterBefore(new OncePerRequestFilter() {
.addFilterBefore(new OncePerRequestFilter() { // @Override
@Override // protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { // String breakerToken = " ";
String breakerToken = " "; // // 判断header里有没有authorization,有则赋值给breakertoken,没有则根据tokenid
// 判断header里有没有authorization,有则赋值给breakertoken,没有则根据tokenid // if (!StringUtils.isEmpty(request.getHeader(HttpHeaders.AUTHORIZATION))) {
if (!StringUtils.isEmpty(request.getHeader(HttpHeaders.AUTHORIZATION))) { // breakerToken = request.getHeader(HttpHeaders.AUTHORIZATION);
breakerToken = request.getHeader(HttpHeaders.AUTHORIZATION); // } else {
} else { // String tokenId = "";
String tokenId = ""; // // 移动端的tokenid在请求头里,pc端的在cookie里
// 移动端的tokenid在请求头里,pc端的在cookie里 // String mobileTokenId = request.getHeader("tokenId");
String mobileTokenId = request.getHeader("tokenId"); // if (!StringUtils.isEmpty(mobileTokenId)) {
if (!StringUtils.isEmpty(mobileTokenId)) { // tokenId = mobileTokenId;
tokenId = mobileTokenId; // } else {
} else { // tokenId = CookieUtil.getUid(request, "tokenId");
tokenId = CookieUtil.getUid(request, "tokenId"); // }
} // if (!StringUtils.isEmpty(tokenId)) {
if (!StringUtils.isEmpty(tokenId)) { // try {
try { //
// OAuth2AccessToken oAuth2AccessToken = (OAuth2AccessToken) IgniteClientCacheUtil.getValue(LOGIN_CACHE, tokenId);
OAuth2AccessToken oAuth2AccessToken = (OAuth2AccessToken) IgniteClientCacheUtil.getValue(LOGIN_CACHE, tokenId); // breakerToken = oAuth2AccessToken.getTokenType() + " " + oAuth2AccessToken.getValue();
breakerToken = oAuth2AccessToken.getTokenType() + " " + oAuth2AccessToken.getValue(); // } catch (Exception e) {
} catch (Exception e) { // e.printStackTrace();
e.printStackTrace(); // }
} // }
} // }
} // HeaderMapRequestWrapper requestWrapper = new HeaderMapRequestWrapper(request);
HeaderMapRequestWrapper requestWrapper = new HeaderMapRequestWrapper(request); // if (!StringUtils.isEmpty(breakerToken)) {
if (!StringUtils.isEmpty(breakerToken)) { // //将cookie中的token放到header,供oauth鉴权使用
//将cookie中的token放到header,供oauth鉴权使用 // requestWrapper.addHeader(HttpHeaders.AUTHORIZATION, breakerToken);
requestWrapper.addHeader(HttpHeaders.AUTHORIZATION, breakerToken); // }
} // try {
try { // filterChain.doFilter(requestWrapper, response);
filterChain.doFilter(requestWrapper, response); // } catch (Exception e) {
} catch (Exception e) { // log.error("配置信息错误:", e);
log.error("配置信息错误:", e); // }
} // }
} // }, SecurityContextPersistenceFilter.class);
}, SecurityContextPersistenceFilter.class); // }
} //
// //访问白名单
//访问白名单 // private static final List<String> whiteList = new ArrayList<String>() {{
private static final List<String> whiteList = new ArrayList<String>() {{ // //swagger
//swagger // add("/webjars/**");
add("/webjars/**"); // add("/resources/**");
add("/resources/**"); // add("/swagger-ui.html");
add("/swagger-ui.html"); // add("/swagger-resources/**");
add("/swagger-resources/**"); // add("/v2/api-docs");
add("/v2/api-docs"); // add("/getSwaggerToken");
add("/getSwaggerToken"); // add("/");
add("/"); // add("/**/*.html");
add("/**/*.html"); // add("/**/*.htm");
add("/**/*.htm"); // add("/**/*.woff");
add("/**/*.woff"); // add("/**/*.woff2");
add("/**/*.woff2"); // add("/**/*.ttf");
add("/**/*.ttf"); // add("/**/*.svg");
add("/**/*.svg"); // add("/**/*.css");
add("/**/*.css"); // add("/**/*.png");
add("/**/*.png"); // add("/**/*.jpg");
add("/**/*.jpg"); // add("/**/*.gif");
add("/**/*.gif"); // add("/**/*.ico");
add("/**/*.ico"); // add("/**/*.json");
add("/**/*.json"); // add("/**/*.js");
add("/**/*.js"); // add("/**/*.txt");
add("/**/*.txt"); // add("/**");
add("/**"); // }};
}}; //}
}
package net.wanji.feign.service; package net.wanji.feign.service;
import net.wanji.common.framework.rest.JsonViewObject;
import net.wanji.feign.config.FeignHisenseClientsConfig; import net.wanji.feign.config.FeignHisenseClientsConfig;
import net.wanji.feign.service.common.FeignCommon; import net.wanji.feign.service.common.FeignCommon;
import org.springframework.cloud.openfeign.FeignClient; import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
/** /**
* @author duanruiming * @author duanruiming
...@@ -11,4 +14,11 @@ import org.springframework.cloud.openfeign.FeignClient; ...@@ -11,4 +14,11 @@ import org.springframework.cloud.openfeign.FeignClient;
@FeignClient(name = "UtcHisenseFeignClients", url = "${utc.hisense.service.url}", @FeignClient(name = "UtcHisenseFeignClients", url = "${utc.hisense.service.url}",
configuration = FeignHisenseClientsConfig.class) configuration = FeignHisenseClientsConfig.class)
public interface UtcHisenseFeignClients extends FeignCommon { public interface UtcHisenseFeignClients extends FeignCommon {
/**
* 海信-获取方案号
*
* @return
*/
@PostMapping("/staticInfo/crossSchemeNo")
JsonViewObject getSchemeNo(@RequestParam String crossId);
} }
...@@ -115,4 +115,6 @@ public interface FeignCommon { ...@@ -115,4 +115,6 @@ public interface FeignCommon {
@PostMapping("/control/findPlanId") @PostMapping("/control/findPlanId")
Integer findPlanId(@RequestParam Date datetime, @RequestParam String dateStr, @RequestParam String crossId); Integer findPlanId(@RequestParam Date datetime, @RequestParam String dateStr, @RequestParam String crossId);
} }
...@@ -13,9 +13,33 @@ ...@@ -13,9 +13,33 @@
<java.version>1.8</java.version> <java.version>1.8</java.version>
<mybatis.generator.version>1.3.2</mybatis.generator.version> <mybatis.generator.version>1.3.2</mybatis.generator.version>
<mysql.connector.version>5.1.41</mysql.connector.version> <mysql.connector.version>5.1.41</mysql.connector.version>
<dom4j.version>1.6.1</dom4j.version>
<xstream.version>1.4.11.1</xstream.version>
<jaxen.version>1.1.6</jaxen.version>
</properties> </properties>
<dependencies> <dependencies>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.9.3</version>
</dependency>
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>${dom4j.version}</version>
</dependency>
<dependency>
<groupId>jaxen</groupId>
<artifactId>jaxen</artifactId>
<version>${jaxen.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.thoughtworks.xstream/xstream 支持xml转bean -->
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<version>${xstream.version}</version>
</dependency>
<dependency> <dependency>
<groupId>net.wanji</groupId> <groupId>net.wanji</groupId>
<artifactId>signal-feign-service</artifactId> <artifactId>signal-feign-service</artifactId>
......
...@@ -34,6 +34,6 @@ public class HisenseApplication implements CommandLineRunner { ...@@ -34,6 +34,6 @@ public class HisenseApplication implements CommandLineRunner {
public void run(String... args) throws Exception { public void run(String... args) throws Exception {
//UdpClient.connection(localPort, remoteProt); //UdpClient.connection(localPort, remoteProt);
//TcpClient.connection(remoteIp, remoteProt); //TcpClient.connection(remoteIp, remoteProt);
TcpClient.connection("127.0.0.1", remoteProt); // TcpClient.connection("127.0.0.1", remoteProt);
} }
} }
package net.wanji.utc.hisense.common;
import net.wanji.common.utils.tool.LocalDateTimeUtil;
import net.wanji.common.utils.tool.RandomUtil;
import net.wanji.utc.hisense.common.constants.HttpConstants;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
/**
* @author zhouleilei
* @version 1.0
* @date 2024/11/3 12:46
*/
public class OperationBaseDom {
private OperationBaseDom() {
}
/**
* 产生一个基本操作dom
*
* @return
*/
public static Document generateBaseDoc() {
Document document = DocumentHelper.createDocument();
Element message = document.addElement("systemScription")
.addAttribute("System", "TCIP")
.addAttribute("Version", "1.0");
message.addElement("subSystem").setText("Hisense");
message.addElement("isRequest").setText("1");
message.addElement("seq").setText(LocalDateTimeUtil.formatNow(LocalDateTimeUtil.SIMPLE) + RandomUtil.generateFromSource(6, RandomUtil.NUMBER_SOURCE));
message.addElement("needResponse").setText("1");
message.addElement("result").setText("0");
message.addElement("flag").setText("0");
message.addElement("messageContent");
return document;
}
public static void main(String[] args) throws DocumentException {
Document document = OperationBaseDom.generateBaseDoc();
Element element = (Element) document.selectSingleNode("/systemScription");
element.addElement("messageType").setText("12");
Element messageContent = (Element) document.selectSingleNode("/systemScription/messageContent");
messageContent.addElement("Spot").setText("101");
System.out.println(document.asXML());
String post = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<systemScription System=\"TCIP\" Version=\"1.0\">\n" +
" <subSystem>Hisense</subSystem>\n" +
" <messageType>12</messageType>\n" +
" <isRequest>0</isRequest>\n" +
" <seq>20241103155205549244</seq>\n" +
" <needResponse>1</needResponse>\n" +
" <result>1</result>\n" +
" <flag>0</flag>\n" +
" <tStamp>1730623180670</tStamp>\n" +
" <messageContent>\n" +
" <Spot>882530</Spot>\n" +
" <CoordPatternStatus>58</CoordPatternStatus>\n" +
" <CoordCycleStatus>200</CoordCycleStatus>\n" +
" <CoordSyncStatus>41</CoordSyncStatus>\n" +
" </messageContent>\n" +
"</systemScription>";
Document postResult = DocumentHelper.parseText(post);
String result = postResult.selectSingleNode(HttpConstants.SYSTEMSCRIPTION_RESULT).getText();
if (HttpConstants.RESULT_1.equals(result)){
//成功
String spot = postResult.selectSingleNode(HttpConstants.SYSTEMSCRIPTION_MESSAGECONTENT).valueOf("Spot");
System.out.println(spot);
}else {
//失败
}
}
}
package net.wanji.utc.hisense.common.constants;
/**
* @ClassName HttpConstants
* @Description 海信Http请求需要的常量
* @Author zhouleilei
* @Date 2024/11/3 16:47
*/
public class HttpConstants {
//MESSAGETYPE
public static final String MESSAGETYPE = "messageType";
// /systemScription
public static final String SYSTEMSCRIPTION = "/systemScription";
// systemScription/messageContent
public static final String SYSTEMSCRIPTION_MESSAGECONTENT = "/systemScription/messageContent";
// /systemScription/result
public static final String SYSTEMSCRIPTION_RESULT = "/systemScription/result";
//Spot
public static final String SPOT = "Spot";
//5.7协调状态 获取方案号
public static final String MESSAGETYPE_12 = "12";
// result = 0 失败
public static final String RESULT_0 = "0";
// result = 1 成功
public static final String RESULT_1 = "1";
}
...@@ -21,7 +21,7 @@ public class Swagger2 { ...@@ -21,7 +21,7 @@ public class Swagger2 {
.apiInfo(apiInfo()) .apiInfo(apiInfo())
.select() .select()
//为当前包路径 //为当前包路径
.apis(RequestHandlerSelectors.basePackage("net.wanji.utc.hisense.controller")) .apis(RequestHandlerSelectors.basePackage("net.wanji.utc.hisense.controller.*"))
.paths(PathSelectors.any()) .paths(PathSelectors.any())
.build(); .build();
} }
......
...@@ -5,7 +5,6 @@ import io.swagger.annotations.ApiOperation; ...@@ -5,7 +5,6 @@ import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses; import io.swagger.annotations.ApiResponses;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import net.wanji.utc.hisense.service.StaticInfoService;
import net.wanji.common.annotation.aspect.AspectLog; import net.wanji.common.annotation.aspect.AspectLog;
import net.wanji.common.enums.BaseEnum; import net.wanji.common.enums.BaseEnum;
import net.wanji.common.framework.rest.JsonViewObject; import net.wanji.common.framework.rest.JsonViewObject;
...@@ -15,12 +14,13 @@ import net.wanji.databus.dto.PlanSectionDTO; ...@@ -15,12 +14,13 @@ import net.wanji.databus.dto.PlanSectionDTO;
import net.wanji.databus.dto.SchemePhaseLightsDTO; import net.wanji.databus.dto.SchemePhaseLightsDTO;
import net.wanji.databus.vo.PlanSectionVO; import net.wanji.databus.vo.PlanSectionVO;
import net.wanji.databus.vo.SchemePhaseLightsVO; import net.wanji.databus.vo.SchemePhaseLightsVO;
import net.wanji.utc.hisense.pojo.result.CoordinationStatus;
import net.wanji.utc.hisense.service.StaticInfoService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.validation.annotation.Validated; import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.constraints.NotNull;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import java.util.List; import java.util.List;
...@@ -76,4 +76,21 @@ public class StaticInfoController { ...@@ -76,4 +76,21 @@ public class StaticInfoController {
List<CrossSchedulesPO> crossSchedulesPOS = staticInfoService.crossSchedules(crossSchedulesDTO); List<CrossSchedulesPO> crossSchedulesPOS = staticInfoService.crossSchedules(crossSchedulesDTO);
return JsonViewObject.newInstance().success(crossSchedulesPOS); return JsonViewObject.newInstance().success(crossSchedulesPOS);
} }
@AspectLog(description = "5.7协调状态-获取当前方案号", operationType = BaseEnum.OperationTypeEnum.QUERY)
@GetMapping(value = "/crossSchemeNo")
@ApiOperation(value = "5.7协调状态-获取当前方案号", notes = "协调状态-获取当前方案号", response = CrossSchedulesPO.class,
produces = MediaType.APPLICATION_JSON, consumes = MediaType.APPLICATION_JSON)
@ApiResponses({
@ApiResponse(code = 200, message = "OK", response = CrossSchedulesPO.class)
})
public JsonViewObject crossPlanId(@NotNull String crossId) throws Exception {
CoordinationStatus coordinationStatus = staticInfoService.crossPlan(crossId);
if (ObjectUtils.isNotEmpty(coordinationStatus)) {
return JsonViewObject.newInstance().success(coordinationStatus);
} else {
return JsonViewObject.newInstance().fail("获取当前方案号 失败");
}
}
} }
package net.wanji.utc.hisense.pojo.result;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @ClassName CoordinationStatus
* @Description 5.7. 协调状态
* @Author zhouleilei
* @Date 2024/11/3 12:31
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class CoordinationStatus {
/**
* 控制点编号
*/
private String spot;
/**
* 当前信号机的运行方案号
*/
private String coordPatternStatus;
/**
* 当前信号机运行方案的周期长
*/
private String coordCycleStatus;
/**
* 当前信号机运行方案的周期倒计时
*/
private String coordSyncStatus;
}
...@@ -88,4 +88,10 @@ public interface ControlCommandService { ...@@ -88,4 +88,10 @@ public interface ControlCommandService {
* @return * @return
*/ */
// JsonViewObject delBaseConfig(DelBaseConfigPOfigPO delBaseConfigPO) throws Exception; // JsonViewObject delBaseConfig(DelBaseConfigPOfigPO delBaseConfigPO) throws Exception;
/**
* 临时方案下发
*/
JsonViewObject tempSchemeSend(SchemeSendVO schemeSendVO) throws Exception;
} }
...@@ -8,6 +8,7 @@ import net.wanji.databus.dto.SchemePhaseLightsDTO; ...@@ -8,6 +8,7 @@ import net.wanji.databus.dto.SchemePhaseLightsDTO;
import net.wanji.databus.po.CrossInfoPO; import net.wanji.databus.po.CrossInfoPO;
import net.wanji.databus.vo.PlanSectionVO; import net.wanji.databus.vo.PlanSectionVO;
import net.wanji.databus.vo.SchemePhaseLightsVO; import net.wanji.databus.vo.SchemePhaseLightsVO;
import net.wanji.utc.hisense.pojo.result.CoordinationStatus;
import java.util.List; import java.util.List;
...@@ -20,5 +21,10 @@ public interface StaticInfoService { ...@@ -20,5 +21,10 @@ public interface StaticInfoService {
List<PlanSectionVO> planSection(PlanSectionDTO planSectionDTO) throws Exception; List<PlanSectionVO> planSection(PlanSectionDTO planSectionDTO) throws Exception;
List<CrossSchedulesPO> crossSchedules(CrossSchedulesDTO crossSchedulesDTO) throws Exception; List<CrossSchedulesPO> crossSchedules(CrossSchedulesDTO crossSchedulesDTO) throws Exception;
/**
* @Description : 5.7. 协调状态 - 获取当前方案
* @Param crossId 路口编号
**/
CoordinationStatus crossPlan(String crossId) throws Exception;
} }
...@@ -18,6 +18,8 @@ public class ControlCommandServiceImpl implements ControlCommandService { ...@@ -18,6 +18,8 @@ public class ControlCommandServiceImpl implements ControlCommandService {
@Override @Override
public JsonViewObject schemeSend(SchemeSendVO schemeSendVO) throws Exception { public JsonViewObject schemeSend(SchemeSendVO schemeSendVO) throws Exception {
// 海信方案下发
// 下发xml
return null; return null;
} }
......
...@@ -2,6 +2,7 @@ package net.wanji.utc.hisense.service.impl; ...@@ -2,6 +2,7 @@ package net.wanji.utc.hisense.service.impl;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import net.wanji.common.utils.tool.StringUtils;
import net.wanji.databus.dao.entity.CrossSchedulesPO; import net.wanji.databus.dao.entity.CrossSchedulesPO;
import net.wanji.databus.dto.CrossInfoDTO; import net.wanji.databus.dto.CrossInfoDTO;
import net.wanji.databus.dto.CrossSchedulesDTO; import net.wanji.databus.dto.CrossSchedulesDTO;
...@@ -10,7 +11,15 @@ import net.wanji.databus.dto.SchemePhaseLightsDTO; ...@@ -10,7 +11,15 @@ import net.wanji.databus.dto.SchemePhaseLightsDTO;
import net.wanji.databus.po.CrossInfoPO; import net.wanji.databus.po.CrossInfoPO;
import net.wanji.databus.vo.PlanSectionVO; import net.wanji.databus.vo.PlanSectionVO;
import net.wanji.databus.vo.SchemePhaseLightsVO; import net.wanji.databus.vo.SchemePhaseLightsVO;
import net.wanji.utc.hisense.common.OperationBaseDom;
import net.wanji.utc.hisense.common.constants.HttpConstants;
import net.wanji.utc.hisense.pojo.result.CoordinationStatus;
import net.wanji.utc.hisense.service.StaticInfoService; import net.wanji.utc.hisense.service.StaticInfoService;
import net.wanji.utc.hisense.util.OkHttpClientUtil;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.util.List; import java.util.List;
...@@ -24,6 +33,8 @@ import java.util.List; ...@@ -24,6 +33,8 @@ import java.util.List;
@Slf4j @Slf4j
public class StaticInfoServiceImpl implements StaticInfoService { public class StaticInfoServiceImpl implements StaticInfoService {
@Value("${hisense.url}")
private String hisenseUrl;
@Override @Override
public List<CrossInfoPO> crossBasicInfo(CrossInfoDTO crossInfoDTO) throws Exception { public List<CrossInfoPO> crossBasicInfo(CrossInfoDTO crossInfoDTO) throws Exception {
return null; return null;
...@@ -43,4 +54,43 @@ public class StaticInfoServiceImpl implements StaticInfoService { ...@@ -43,4 +54,43 @@ public class StaticInfoServiceImpl implements StaticInfoService {
public List<CrossSchedulesPO> crossSchedules(CrossSchedulesDTO crossSchedulesDTO) throws Exception { public List<CrossSchedulesPO> crossSchedules(CrossSchedulesDTO crossSchedulesDTO) throws Exception {
return null; return null;
} }
@Override
public CoordinationStatus crossPlan(String crossId) throws Exception {
//组装document
Document document = OperationBaseDom.generateBaseDoc();
Element element = (Element) document.selectSingleNode(HttpConstants.SYSTEMSCRIPTION);
element.addElement(HttpConstants.MESSAGETYPE).setText(HttpConstants.MESSAGETYPE_12);
Element messageContent = (Element) document.selectSingleNode(HttpConstants.SYSTEMSCRIPTION_MESSAGECONTENT);
messageContent.addElement(HttpConstants.SPOT).setText(crossId);
//给海信发送http请求
String post = OkHttpClientUtil.xmlPost(hisenseUrl, document.asXML());
if (StringUtils.isBlank(post)){
log.error("请求 5.7. 协调状态 失败");
return null;
}
Document postResult = DocumentHelper.parseText(post);
String result = postResult.selectSingleNode(HttpConstants.SYSTEMSCRIPTION_RESULT).getText();
if (HttpConstants.RESULT_1.equals(result)){
//成功
String spot = postResult.selectSingleNode(HttpConstants.SYSTEMSCRIPTION_MESSAGECONTENT).valueOf("Spot");
String CoordPatternStatus = postResult.selectSingleNode(HttpConstants.SYSTEMSCRIPTION_MESSAGECONTENT).valueOf("CoordPatternStatus");
String CoordCycleStatus = postResult.selectSingleNode(HttpConstants.SYSTEMSCRIPTION_MESSAGECONTENT).valueOf("CoordCycleStatus");
String CoordSyncStatus = postResult.selectSingleNode(HttpConstants.SYSTEMSCRIPTION_MESSAGECONTENT).valueOf("CoordSyncStatus");
CoordinationStatus coordinationStatus = CoordinationStatus.builder()
.spot(spot)
.coordPatternStatus(CoordPatternStatus)
.coordCycleStatus(CoordCycleStatus)
.coordSyncStatus(CoordSyncStatus)
.build();
return coordinationStatus;
}else {
//失败
log.error("请求 5.7. 协调状态 失败");
}
return null;
}
} }
package net.wanji.utc.hisense.util;
import net.wanji.common.utils.tool.StringUtils;
import okhttp3.*;
import java.io.IOException;
/**
* @ClassName OkHttpClient
* @Description OkHttpClient
* @Author zhouleilei
* @Date 2024/11/3 18:11
*/
public class OkHttpClientUtil {
public static String xmlPost(String url,String xmlContent){
if (StringUtils.isBlank(url) || StringUtils.isBlank(xmlContent)){
return null;
}
// 创建 OkHttpClient 实例
OkHttpClient client = new OkHttpClient();
// 创建请求体
RequestBody body = RequestBody.create(xmlContent, MediaType.get("application/xml; charset=utf-8"));
// 创建请求
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
// 执行请求
try (Response response = client.newCall(request).execute()) {
// 获取响应体
if (response.code() == 200 && response.body() != null) {
String responseString = response.body().string();
return responseString;
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
/*String post = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<systemScription System=\"TCIP\" Version=\"1.0\">\n" +
" <subSystem>Hisense</subSystem>\n" +
" <messageType>12</messageType>\n" +
" <isRequest>0</isRequest>\n" +
" <seq>20241103155205549244</seq>\n" +
" <needResponse>1</needResponse>\n" +
" <result>1</result>\n" +
" <flag>0</flag>\n" +
" <tStamp>1730623180670</tStamp>\n" +
" <messageContent>\n" +
" <Spot>882530</Spot>\n" +
" <CoordPatternStatus>58</CoordPatternStatus>\n" +
" <CoordCycleStatus>200</CoordCycleStatus>\n" +
" <CoordSyncStatus>41</CoordSyncStatus>\n" +
" </messageContent>\n" +
"</systemScription>";*/
String post = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<systemScription System=\"TCIP\" Version=\"1.0\"><subSystem>Hisense</subSystem><isRequest>1</isRequest><seq>20241103190736692398</seq><needResponse>1</needResponse><result>0</result><flag>0</flag><messageContent><Spot>882530</Spot></messageContent><messageContent>12</messageContent></systemScription>";
String s = xmlPost("http://172.24.71.94:10013", post);
System.out.println(s);
}
}
...@@ -7,7 +7,7 @@ spring: ...@@ -7,7 +7,7 @@ spring:
cloud: cloud:
nacos: nacos:
config: config:
server-addr: 173.17.0.1:8848 server-addr: 37.12.182.29:8848
file-extension: yaml file-extension: yaml
group: signal group: signal
namespace: signal namespace: signal
......
spring: spring:
profiles: profiles:
active: dev active: docker
\ No newline at end of file \ No newline at end of file
...@@ -124,4 +124,13 @@ public class StaticInfoController { ...@@ -124,4 +124,13 @@ public class StaticInfoController {
public JsonViewObject signalTime(@RequestParam String crossId) throws Exception { public JsonViewObject signalTime(@RequestParam String crossId) throws Exception {
return staticInfoService.signalTime(crossId); return staticInfoService.signalTime(crossId);
} }
@AspectLog(description = "获取当前运行方案号", operationType = BaseEnum.OperationTypeEnum.QUERY)
@PostMapping(value = "/crossSchemeNo", produces = MediaType.APPLICATION_JSON)
@ApiResponses({
@ApiResponse(code = 200, message = "OK", response = CrossSchedulesPO.class)
})
public JsonViewObject crossSchemeNo(@RequestParam String crossId) throws Exception {
return staticInfoService.crossSchemeNo(crossId);
}
} }
...@@ -31,4 +31,5 @@ public interface StaticInfoService { ...@@ -31,4 +31,5 @@ public interface StaticInfoService {
List<CrossSchedulesPO> buildCrossSchedulesResponse(List<String> crossIdList); List<CrossSchedulesPO> buildCrossSchedulesResponse(List<String> crossIdList);
JsonViewObject signalTime(String crossId) throws Exception; JsonViewObject signalTime(String crossId) throws Exception;
JsonViewObject crossSchemeNo(String crossId) throws Exception;
} }
...@@ -39,4 +39,11 @@ public interface WanJiCommonStaticInfoService { ...@@ -39,4 +39,11 @@ public interface WanJiCommonStaticInfoService {
Result<List<CrossSchedulesPO>> schedules(String crossId, String signalId) throws Exception; Result<List<CrossSchedulesPO>> schedules(String crossId, String signalId) throws Exception;
JsonViewObject signalTime(String crossId) throws Exception; JsonViewObject signalTime(String crossId) throws Exception;
/**
* @Description 获取当前运行的方案号
* @Param [crossId] 路口编号
* @return net.wanji.common.framework.rest.JsonViewObject
**/
JsonViewObject crossSchemeNo(String crossId) throws Exception;
} }
...@@ -208,4 +208,11 @@ public class StaticInfoServiceImpl implements StaticInfoService { ...@@ -208,4 +208,11 @@ public class StaticInfoServiceImpl implements StaticInfoService {
} }
return jsonViewObject; return jsonViewObject;
} }
@Override
public JsonViewObject crossSchemeNo(String crossId) throws Exception {
JsonViewObject jsonViewObject = JsonViewObject.newInstance();
jsonViewObject = wanjiCommonStaticInfoService.crossSchemeNo(crossId);
return jsonViewObject;
}
} }
...@@ -13,6 +13,8 @@ import net.wanji.databus.dto.PlanSectionDTO; ...@@ -13,6 +13,8 @@ import net.wanji.databus.dto.PlanSectionDTO;
import net.wanji.databus.vo.CrossIdVO; import net.wanji.databus.vo.CrossIdVO;
import net.wanji.databus.vo.PlanSectionVO; import net.wanji.databus.vo.PlanSectionVO;
import net.wanji.databus.vo.SchemePhaseLightsVO; import net.wanji.databus.vo.SchemePhaseLightsVO;
import net.wanji.feign.service.UtcHisenseFeignClients;
import net.wanji.feign.service.common.FeignCommon;
import net.wanji.utc.cache.CrossInfoCache; import net.wanji.utc.cache.CrossInfoCache;
import net.wanji.utc.cache.UtcFeignClientCache; import net.wanji.utc.cache.UtcFeignClientCache;
import net.wanji.utc.common.Result; import net.wanji.utc.common.Result;
...@@ -175,4 +177,15 @@ public class WanJiCommonStaticInfoServiceImpl implements WanJiCommonStaticInfoSe ...@@ -175,4 +177,15 @@ public class WanJiCommonStaticInfoServiceImpl implements WanJiCommonStaticInfoSe
return jsonViewObject; return jsonViewObject;
} }
@Override
public JsonViewObject crossSchemeNo(String crossId) throws Exception {
String manufacturerIdCode = crossInfoCache.getManufacturerCodeByCrossId(crossId);
UtcHisenseFeignClients utcFeignClientService = (UtcHisenseFeignClients)utcFeignClientCache.getUtcFeignClientService(manufacturerIdCode);
JsonViewObject jsonViewObject = utcFeignClientService.getSchemeNo(crossId);
if (Objects.isNull(jsonViewObject) || jsonViewObject.getCode() != 200) {
throw new Exception("获取信号机时间远程服务调用异常,异常信息" + jsonViewObject.getMessage());
}
return jsonViewObject;
}
} }
...@@ -7,7 +7,7 @@ spring: ...@@ -7,7 +7,7 @@ spring:
cloud: cloud:
nacos: nacos:
config: config:
server-addr: 173.17.0.1:8848 server-addr: 37.12.182.29:8848
file-extension: yaml file-extension: yaml
group: signal group: signal
namespace: signal namespace: signal
......
spring:
application:
# dubbo启动需要程序名称
name: utc
main:
allow-circular-references: true
cloud:
nacos:
config:
server-addr: 172.17.0.1:8848
file-extension: yaml
group: signal
namespace: signal
username: nacos
password: nacos
\ No newline at end of file
spring:
application:
# dubbo启动需要程序名称
name: utc
main:
allow-circular-references: true
cloud:
nacos:
config:
server-addr: 10.102.1.182:8848
file-extension: yaml
group: signal
namespace: signal
username: nacos
password: nacos
\ No newline at end of file
spring:
application:
# dubbo启动需要程序名称
name: utc
main:
allow-circular-references: true
cloud:
nacos:
config:
server-addr: 10.102.1.182:8848
file-extension: yaml
group: signal
namespace: signal
username: nacos
password: nacos
\ No newline at end of file
spring: spring:
profiles: profiles:
active: dev active: docker
\ No newline at end of file \ No newline at end of file
package net.wanji.common.utils.tool;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.time.temporal.TemporalUnit;
import java.util.Date;
import java.util.TimeZone;
/**
* 时间工具类
*
* @author zhouleilei
* @version 1.0
* @date 2024/11/3 13:16
*/
public class LocalDateTimeUtil {
public static final String TIMEFORMATTER = "yyyy-MM-dd HH:mm:ss";
public static final String HOURFORMATTER = "HH";
public static final String DAYFORMATTER = "yyyy-MM-dd";
public static final String MONTHFORMATTER = "yyyy-MM";
public static final String YEARFORMATTER = "yyyy";
public static final String SIMPLE = "yyyyMMddHHmmss";
public static final String TIMEFORMATTERTILT = "yyyy/MM/dd HH:mm:ss";
private LocalDateTimeUtil() {
}
//Date转换为LocalDateTime
public static LocalDateTime convertDateToLDT(Date date) {
return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
}
//LocalDateTime转换为Date
public static Date convertLDTToDate(LocalDateTime time) {
return Date.from(time.atZone(ZoneId.systemDefault()).toInstant());
}
public static java.sql.Date localTimeToDate(LocalDateTime localDateTime) {
return new java.sql.Date(localDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
}
//获取指定日期的毫秒
public static Long getMilliByTime(LocalDateTime time) {
return time.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
}
//获取指定日期的秒
public static Long getSecondsByTime(LocalDateTime time) {
return time.atZone(ZoneId.systemDefault()).toInstant().getEpochSecond();
}
//获取指定时间的指定格式
public static String formatTime(LocalDateTime time, String pattern) {
return time.format(DateTimeFormatter.ofPattern(pattern));
}
//获取指定时间的指定格式
public static String formatTimeStamp(Long timestamp, String pattern) {
return formatTime(parseLongToDateTime(timestamp), pattern);
}
//获取当前时间的指定格式
public static String formatNow(String pattern) {
return formatTime(LocalDateTime.now(), pattern);
}
//日期加上一个数,根据field不同加不同值,field为ChronoUnit.*
public static LocalDateTime plus(LocalDateTime time, long number, TemporalUnit field) {
return time.plus(number, field);
}
//日期减去一个数,根据field不同减不同值,field参数为ChronoUnit.*
public static LocalDateTime minu(LocalDateTime time, long number, TemporalUnit field) {
return time.minus(number, field);
}
//获取当前时间前N个月份
public static String getLastNMonth(int n) {
LocalDateTime lastNMonth = LocalDateTime.now().minusMonths(n);
DateTimeFormatter formatters = DateTimeFormatter.ofPattern(MONTHFORMATTER);
return formatters.format(lastNMonth);
}
/**
* 获取两个日期的差 field参数为ChronoUnit.*
*
* @param startTime
* @param endTime
* @param field 单位(年月日时分秒)
* @return
*/
public static long betweenTwoTime(LocalDateTime startTime, LocalDateTime endTime, ChronoUnit field) {
Period period = Period.between(LocalDate.from(startTime), LocalDate.from(endTime));
if (field == ChronoUnit.YEARS) {
return period.getYears();
}
if (field == ChronoUnit.MONTHS) {
return (long) (period.getYears() * 12 + period.getMonths());
}
return field.between(startTime, endTime);
}
//获取一天的开始时间,2017,7,22 00:00
public static LocalDateTime getDayStart(LocalDateTime time) {
return time.withHour(0)
.withMinute(0)
.withSecond(0);
//.withNano(0);
}
//获取一天的结束时间,2017,7,22 23:59:59.999999999
public static LocalDateTime getDayEnd(LocalDateTime time) {
return time.withHour(23)
.withMinute(59)
.withSecond(59);
//.withNano(999999999);
}
/**
* 把长整数转化为LocalDateTime
*
* @param timestamp 时间长整数
* @return
*/
public static LocalDateTime parseLongToDateTime(Long timestamp) {
return LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), TimeZone.getDefault().toZoneId());
}
/**
* 把时间戳转化为LocalDateTime
*
* @param timestamp 时间戳
* @return
*/
public static LocalDateTime getDateTimeOfTimestamp(long timestamp) {
Instant instant = Instant.ofEpochMilli(timestamp);
ZoneId zone = ZoneId.systemDefault();
return LocalDateTime.ofInstant(instant, zone);
}
/**
* 将日期字符串转化为LocalDateTime
*
* @param time 时间字符串
* @param format 格式
* @return
*/
public static LocalDateTime parseStringToDateTime(String time, String format) {
DateTimeFormatter df = DateTimeFormatter.ofPattern(format);
return LocalDateTime.parse(time, df);
}
/**
* 将日期字符串转化为LocalDateTime
*
* @param time 时间字符串
* @param format 格式
* @return
*/
public static LocalDateTime parseStringToDateTimeTwo(String time, String format) {
DateTimeFormatter df = DateTimeFormatter.ofPattern(format);
return LocalDateTime.parse(checkFormat(time), df);
}
public static void main(String[] args) {
System.out.println("--"+new Date());
String date = "2021/10/22 17:45:20";
String nowStageStartTime = date == null ? "" : date.toString().replaceAll("\"", "");
LocalDateTime localDateTime = parseStringToDateTimeTwo(nowStageStartTime, LocalDateTimeUtil.TIMEFORMATTERTILT);
String time = nowStageStartTime.isEmpty() ? "0" : Long.toString(LocalDateTimeUtil.betweenTwoTime(localDateTime, LocalDateTime.now(), ChronoUnit.SECONDS));
System.out.println(time);
}
/**
* 将日期字符串转化为指定格式的日期字符串
*
* @param time 时间字符串
* @return
*/
public static String parseStringToFormatString(String time, String oldFormat, String newFormat) {
if (time == null || time.isEmpty()) return time;
DateTimeFormatter df = DateTimeFormatter.ofPattern(oldFormat);
return LocalDateTime.parse(checkFormat(time), df).format(DateTimeFormatter.ofPattern(newFormat));
}
/**
* 时间格式规范,仅标准格式
*/
public static String checkFormat(String time) {
String timeNew = time.substring(0, time.indexOf(" "));
String spit = timeNew.substring(4, 5);
String year = timeNew.substring(0, timeNew.indexOf(spit));
String month = timeNew.substring(timeNew.indexOf(spit) + 1, timeNew.lastIndexOf(spit));
String day = timeNew.substring(timeNew.lastIndexOf(spit) + 1);
//弄时分秒
String shifenmiao = time.substring(time.indexOf(" ") + 1);
String hour = shifenmiao.substring(0, shifenmiao.indexOf(":"));
String min = shifenmiao.substring(shifenmiao.indexOf(":") + 1, shifenmiao.lastIndexOf(":"));
String sec = shifenmiao.substring(shifenmiao.lastIndexOf(":") + 1);
return MessageFormat.format("{0}{1}{2}{3}{4}{5}{6}{7}{8}{9}{10}",
year, spit, String.format("%02d", Integer.valueOf(month)), spit, String.format("%02d", Integer.valueOf(day)),
" ",
String.format("%02d", Integer.valueOf(hour)), ":", String.format("%02d", Integer.valueOf(min)), ":", String.format("%02d", Integer.valueOf(sec)));
}
/**
* 获取当前时间的前一天时间值 如:2019-10-12 12:10:08 --> 2019-10-11 12:10:08
*
* @param time 时间
*/
public static String getYesterdayString(String time) {
return LocalDateTimeUtil.parseStringToDateTime(time, TIMEFORMATTER).plusDays(-1).format(DateTimeFormatter.ofPattern(TIMEFORMATTER));
}
/**
* 获取指定时间所在月的第一天
*
* @param dateTime
* @return
*/
public static LocalDateTime getMonthFirstDay(LocalDateTime dateTime) {
LocalDateTime firstday = dateTime.with(TemporalAdjusters.firstDayOfMonth());
firstday = firstday.withHour(0).withMinute(0).withSecond(0);
return firstday;
}
/**
* 获取指定时间所在月的最后一天
*
* @param dateTime
* @return
*/
public static LocalDateTime getMonthLastDay(LocalDateTime dateTime) {
LocalDateTime lastDay = dateTime.with(TemporalAdjusters.lastDayOfMonth());
lastDay = lastDay.withHour(23).withMinute(59).withSecond(59);
return lastDay;
}
/**
* 得到现在分钟(Integer)
*
* @author lzs
*/
public static Integer getNowMinuteInt() {
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = formatter.format(currentTime);
String min;
min = dateString.substring(14, 16);
return Integer.valueOf(min);
}
/**
* 得到现在小时(Integer)
*
* @author lzs
*/
public static Integer getNowHourInt() {
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = formatter.format(currentTime);
String hour;
hour = dateString.substring(11, 13);
return Integer.valueOf(hour);
}
/**
* 获得日期是周几
*
* @param localDateTime
* @return
*/
public static int getDayOfWeekNum(LocalDateTime localDateTime) {
return localDateTime.getDayOfWeek().getValue();
}
}
package net.wanji.common.utils.tool;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
/**
* @author zhouleilei
* @version 1.0
* @date 2024/11/3 13:24
*/
public class RandomUtil {
/**
* 字符源,可以剔除O、L、0和1,避免0和1与O和L混淆,这里没有剔除<br/>
* 可以根据需要加入小写英文字母和特殊字符等
*/
public static final String[] GENERATE_SOURCE = new String[]{"0", "1", "2", "3", "4", "5", "6", "7",
"8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J",
"K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
"W", "X", "Y", "Z"};
private static final int STR_LEN = GENERATE_SOURCE.length;
public static final String[] NUMBER_SOURCE = new String[]{"0", "1", "2", "3", "4", "5", "6", "7","8", "9"};
/**
* 使用 Collections.shuffle 生成六位随机字符串
*
* @return
*/
private static String generateByShuffle() {
List<String> list = Arrays.asList(GENERATE_SOURCE);
//打乱元素排序,增加反推难度
Collections.shuffle(list);
StringBuilder randomStr = new StringBuilder();
for (int i = 0; i < STR_LEN; i++) {
randomStr.append(list.get(i));
}
//更改下面两个数字可以取到不同位数的随机数哦
return randomStr.substring(4, 10);
}
/**
* 生成数字和字母组合,字母区分大小写
*
* @param length 随机字符串的长度
* @return
*/
public static String generateByRandom(final int length) {
StringBuilder randomSb = new StringBuilder(length);
Random random = new Random();
for (int i = 0; i < length; i++) {
// 输出字母还是数字
String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
// 字符串
if ("char".equals(charOrNum)) {
// 判断字母大小写
int choice = random.nextInt(2) % 2 == 0 ? 65 : 97;
randomSb = randomSb.append((char) (choice + random.nextInt(26)));
} else {
randomSb = randomSb.append(random.nextInt(10));
}
}
return randomSb.toString();
}
/**
* 生成随机字符串,generateByRandom的简化版
* @param count 随机字符串的长度
* @param source 源字符集
* @return
*/
public static String generateFromSource(int count, String[] source) {
StringBuilder sb = new StringBuilder(count);
int sourceLen = source.length;
for (int i = 0; i < count; i++) {
final int index = new Random().nextInt(sourceLen);
sb.append(source[index]);
}
return sb.toString();
}
/**
* @param begin 自增长序列
* @return
*/
public static String generateByOrder(final int begin) {
List<String> src = Arrays.asList(GENERATE_SOURCE);
Collections.shuffle(src);
StringBuilder randomSb = new StringBuilder(6);
int i4 = (begin) % 36;
int i3 = (begin / (36)) % 36;
int i2 = (begin / (36 * 36)) % 36;
int i1 = (begin / (36 * 36 * 36)) % 36;
int i0 = (begin / (36 * 36 * 36 * 36)) % 36;
int i = (begin / (36 * 36 * 36 * 36 * 36)) % 36;
randomSb = randomSb.append(src.get(i0)).append(src.get(i1))
.append(src.get(i2)).append(src.get(i3))
.append(src.get(i4)).append(src.get(i));
return randomSb.toString();
}
public static void main(String[] args) {
String s = generateByRandom(10);
System.out.println(s);
String ss = generateByOrder(1);
System.out.println(ss);
String sss = generateFromSource(6,RandomUtil.NUMBER_SOURCE);
System.out.println(sss);
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment