repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
train-ticket
train-ticket-master/ts-auth-service/src/main/java/auth/repository/UserRepository.java
package auth.repository; import auth.entity.User; import org.springframework.data.repository.CrudRepository; import java.util.Optional; import java.util.UUID; /** * @author fdse */ public interface UserRepository extends CrudRepository<User, String> { /** * find by username * * @param username username * @return Optional<User> */ Optional<User> findByUsername(String username); /** * delete by user id * * @param userId user id * @return null */ void deleteByUserId(String userId); }
559
17.666667
70
java
train-ticket
train-ticket-master/ts-auth-service/src/main/java/auth/security/UserDetailsServiceImpl.java
package auth.security; import auth.constant.InfoConstant; import auth.repository.UserRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Component; import java.text.MessageFormat; /** * @author fdse */ @Component("userDetailServiceImpl") public class UserDetailsServiceImpl implements UserDetailsService { @Autowired private UserRepository userRepository; private static final Logger LOGGER = LoggerFactory.getLogger(UserDetailsServiceImpl.class); @Override public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException { LOGGER.info("[loadUserByUsername][load UsernamePasswordAuthenticationToken][username: {}]", s); return userRepository.findByUsername(s) .orElseThrow(() -> new UsernameNotFoundException( MessageFormat.format(InfoConstant.USER_NAME_NOT_FOUND_1, s) )); } }
1,236
34.342857
103
java
train-ticket
train-ticket-master/ts-auth-service/src/main/java/auth/security/jwt/JWTProvider.java
package auth.security.jwt; import auth.constant.InfoConstant; import auth.entity.User; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.util.Base64; import java.util.Date; /** * @author fdse */ @Component public class JWTProvider { private String secretKey = "secret"; private long validityInMilliseconds = 3600000; @PostConstruct protected void init() { secretKey = Base64.getEncoder().encodeToString(secretKey.getBytes()); } public String createToken(User user) { Claims claims = Jwts.claims().setSubject(user.getUsername()); claims.put(InfoConstant.ROLES, user.getRoles()); claims.put(InfoConstant.ID, user.getUserId()); Date now = new Date(); Date validate = new Date(now.getTime() + validityInMilliseconds); return Jwts.builder() .setClaims(claims) .setIssuedAt(now) .setExpiration(validate) .signWith(SignatureAlgorithm.HS256, secretKey) .compact(); } }
1,189
25.444444
77
java
train-ticket
train-ticket-master/ts-auth-service/src/main/java/auth/service/TokenService.java
package auth.service; import auth.dto.BasicAuthDto; import edu.fudan.common.util.Response; import org.springframework.http.HttpHeaders; /** * @author fdse */ public interface TokenService { /** * get token by dto * * @param dto dto * @param headers headers * @return Response */ Response getToken(BasicAuthDto dto, HttpHeaders headers); }
385
15.782609
61
java
train-ticket
train-ticket-master/ts-auth-service/src/main/java/auth/service/UserService.java
package auth.service; import auth.dto.AuthDto; import auth.entity.User; import edu.fudan.common.util.Response; import org.springframework.http.HttpHeaders; import java.util.List; import java.util.UUID; /** * @author fdse */ public interface UserService { /** * save user * * @param user user * @return user */ User saveUser(User user); /** * get all users * * @param headers headers * @return List<User> */ List<User> getAllUser(HttpHeaders headers); /** * create default auth user * * @param dto dto * @return user */ User createDefaultAuthUser(AuthDto dto); /** * delete by user id * * @param userId user id * @param headers headers * @return Response */ Response deleteByUserId(String userId, HttpHeaders headers); }
867
16.36
64
java
train-ticket
train-ticket-master/ts-auth-service/src/main/java/auth/service/impl/TokenServiceImpl.java
package auth.service.impl; import auth.constant.InfoConstant; import auth.dto.BasicAuthDto; import auth.dto.TokenDto; import auth.entity.User; import auth.exception.UserOperationException; import auth.repository.UserRepository; import auth.security.jwt.JWTProvider; import auth.service.TokenService; import edu.fudan.common.util.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.AuthenticationException; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import org.springframework.web.client.RestTemplate; import java.text.MessageFormat; import java.util.List; /** * @author fdse */ @Service public class TokenServiceImpl implements TokenService { private static final Logger LOGGER = LoggerFactory.getLogger(TokenServiceImpl.class); @Autowired private JWTProvider jwtProvider; @Autowired private UserRepository userRepository; @Autowired private AuthenticationManager authenticationManager; @Autowired private RestTemplate restTemplate; @Autowired private DiscoveryClient discoveryClient; private String getServiceUrl(String serviceName) { return "http://" + serviceName; } @Override public Response getToken(BasicAuthDto dto, HttpHeaders headers) throws UserOperationException { String username = dto.getUsername(); String password = dto.getPassword(); String verifyCode = dto.getVerificationCode(); // LOGGER.info("LOGIN USER :" + username + " __ " + password + " __ " + verifyCode); String verification_code_service_url = getServiceUrl("ts-verification-code-service"); if (!StringUtils.isEmpty(verifyCode)) { HttpEntity requestEntity = new HttpEntity(headers); ResponseEntity<Boolean> re = restTemplate.exchange( verification_code_service_url + "/api/v1/verifycode/verify/" + verifyCode, HttpMethod.GET, requestEntity, Boolean.class); boolean id = re.getBody(); // failed code if (!id) { LOGGER.info("[getToken][Verification failed][userName: {}]", username); return new Response<>(0, "Verification failed.", null); } } // verify username and password UsernamePasswordAuthenticationToken upat = new UsernamePasswordAuthenticationToken(username, password); try { authenticationManager.authenticate(upat); } catch (AuthenticationException e) { LOGGER.warn("[getToken][Incorrect username or password][username: {}, password: {}]", username, password); return new Response<>(0, "Incorrect username or password.", null); } User user = userRepository.findByUsername(username) .orElseThrow(() -> new UserOperationException(MessageFormat.format( InfoConstant.USER_NAME_NOT_FOUND_1, username ))); String token = jwtProvider.createToken(user); LOGGER.info("[getToken][success][USER TOKEN: {} USER ID: {}]", token, user.getUserId()); return new Response<>(1, "login success", new TokenDto(user.getUserId(), username, token)); } }
3,903
38.434343
118
java
train-ticket
train-ticket-master/ts-auth-service/src/main/java/auth/service/impl/UserServiceImpl.java
package auth.service.impl; import auth.constant.AuthConstant; import auth.constant.InfoConstant; import auth.dto.AuthDto; import auth.entity.User; import auth.exception.UserOperationException; import auth.repository.UserRepository; import auth.service.UserService; import edu.fudan.common.util.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.text.MessageFormat; import java.util.*; /** * @author fdse */ @Service public class UserServiceImpl implements UserService { private static final Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class); @Autowired private UserRepository userRepository; @Autowired protected PasswordEncoder passwordEncoder; @Override public User saveUser(User user) { return null; } @Override public List<User> getAllUser(HttpHeaders headers) { return (List<User>) userRepository.findAll(); } /** * create a user with default role of user * * @param dto * @return */ @Override public User createDefaultAuthUser(AuthDto dto) { LOGGER.info("[createDefaultAuthUser][Register User Info][AuthDto name: {}]", dto.getUserName()); User user = User.builder() .userId(dto.getUserId()) .username(dto.getUserName()) .password(passwordEncoder.encode(dto.getPassword())) .roles(new HashSet<>(Arrays.asList(AuthConstant.ROLE_USER))) .build(); try { checkUserCreateInfo(user); } catch (UserOperationException e) { LOGGER.error("[createDefaultAuthUser][Create default auth user][UserOperationException][message: {}]", e.getMessage()); } return userRepository.save(user); } @Override @Transactional public Response deleteByUserId(String userId, HttpHeaders headers) { LOGGER.info("[deleteByUserId][DELETE USER][user id: {}]", userId); userRepository.deleteByUserId(userId); return new Response(1, "DELETE USER SUCCESS", null); } /** * check Whether user info is empty * * @param user */ private void checkUserCreateInfo(User user) throws UserOperationException { LOGGER.info("[checkUserCreateInfo][Check user create info][userId: {}, userName: {}]", user.getUserId(), user.getUsername()); List<String> infos = new ArrayList<>(); if (null == user.getUsername() || "".equals(user.getUsername())) { infos.add(MessageFormat.format(InfoConstant.PROPERTIES_CANNOT_BE_EMPTY_1, InfoConstant.USERNAME)); } int passwordMaxLength = 6; if (null == user.getPassword()) { infos.add(MessageFormat.format(InfoConstant.PROPERTIES_CANNOT_BE_EMPTY_1, InfoConstant.PASSWORD)); } else if (user.getPassword().length() < passwordMaxLength) { infos.add(MessageFormat.format(InfoConstant.PASSWORD_LEAST_CHAR_1, 6)); } if (null == user.getRoles() || user.getRoles().isEmpty()) { infos.add(MessageFormat.format(InfoConstant.PROPERTIES_CANNOT_BE_EMPTY_1, InfoConstant.ROLES)); } if (!infos.isEmpty()) { LOGGER.warn(infos.toString()); throw new UserOperationException(infos.toString()); } } }
3,609
32.738318
133
java
train-ticket
train-ticket-master/ts-auth-service/src/test/java/auth/controller/AuthControllerTest.java
package auth.controller; import auth.dto.AuthDto; import auth.service.UserService; import com.alibaba.fastjson.JSONObject; import edu.fudan.common.util.Response; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; @RunWith(JUnit4.class) public class AuthControllerTest { @InjectMocks private AuthController authController; @Mock private UserService userService; private MockMvc mockMvc; @Before public void setUp() { MockitoAnnotations.initMocks(this); mockMvc = MockMvcBuilders.standaloneSetup(authController).build(); } @Test public void testGetHello() throws Exception { mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/auth/hello")) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.content().string("hello")); } @Test public void testCreateDefaultUser() throws Exception { AuthDto authDto = new AuthDto(); Mockito.when(userService.createDefaultAuthUser(Mockito.any(AuthDto.class))).thenReturn(null); String requestJson = JSONObject.toJSONString(authDto); String result = mockMvc.perform(MockMvcRequestBuilders.post("/api/v1/auth").contentType(MediaType.APPLICATION_JSON).content(requestJson)) .andExpect(MockMvcResultMatchers.status().isCreated()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals("SUCCESS", JSONObject.parseObject(result, Response.class).getMsg()); } }
2,048
34.327586
145
java
train-ticket
train-ticket-master/ts-auth-service/src/test/java/auth/controller/UserControllerTest.java
package auth.controller; import auth.dto.BasicAuthDto; import auth.entity.User; import auth.service.TokenService; import auth.service.UserService; import com.alibaba.fastjson.JSONObject; import edu.fudan.common.util.Response; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.springframework.http.*; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import java.util.ArrayList; import java.util.List; import java.util.UUID; @RunWith(JUnit4.class) public class UserControllerTest { @InjectMocks private UserController userController; @Mock private UserService userService; @Mock private TokenService tokenService; private MockMvc mockMvc; private Response response = new Response(); @Before public void setUp() { MockitoAnnotations.initMocks(this); mockMvc = MockMvcBuilders.standaloneSetup(userController).build(); } @Test public void testGetHello() throws Exception { mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/users/hello")) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.content().string("Hello")); } @Test public void testGetToken() throws Exception { BasicAuthDto dao = new BasicAuthDto(); Mockito.when(tokenService.getToken(Mockito.any(BasicAuthDto.class), Mockito.any(HttpHeaders.class))).thenReturn(response); String requestJson = JSONObject.toJSONString(dao); String result = mockMvc.perform(MockMvcRequestBuilders.post("/api/v1/users/login").contentType(MediaType.APPLICATION_JSON).content(requestJson)) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } @Test public void testGetAllUser() throws Exception { List<User> userList = new ArrayList<>(); Mockito.when(userService.getAllUser(Mockito.any(HttpHeaders.class))).thenReturn(userList); String result = mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/users")) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(userList, JSONObject.parseObject(result, List.class)); } @Test public void testDeleteUserById() throws Exception { UUID userId = UUID.randomUUID(); Mockito.when(userService.deleteByUserId(Mockito.any(UUID.class).toString(), Mockito.any(HttpHeaders.class))).thenReturn(response); String result = mockMvc.perform(MockMvcRequestBuilders.delete("/api/v1/users/" + userId.toString())) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } }
3,386
38.383721
152
java
train-ticket
train-ticket-master/ts-auth-service/src/test/java/auth/service/TokenServiceImplTest.java
package auth.service; import auth.dto.BasicAuthDto; import auth.entity.User; import auth.exception.UserOperationException; import auth.repository.UserRepository; import auth.security.jwt.JWTProvider; import auth.service.impl.TokenServiceImpl; import edu.fudan.common.util.Response; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.springframework.http.*; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.web.client.RestTemplate; import java.util.Optional; @RunWith(JUnit4.class) public class TokenServiceImplTest { @InjectMocks private TokenServiceImpl tokenServiceImpl; @Mock private RestTemplate restTemplate; @Mock private UserRepository userRepository; @Mock private JWTProvider jwtProvider; @Mock private AuthenticationManager authenticationManager; private HttpHeaders headers = new HttpHeaders(); HttpEntity requestEntity = new HttpEntity(headers); @Before public void setUp() { MockitoAnnotations.initMocks(this); } @Test public void testGetToken1() { BasicAuthDto dto = new BasicAuthDto(null, null, "verifyCode"); ResponseEntity<Boolean> re = new ResponseEntity<>(false, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-verification-code-service:15678/api/v1/verifycode/verify/" + "verifyCode", HttpMethod.GET, requestEntity, Boolean.class)).thenReturn(re); Response result = tokenServiceImpl.getToken(dto, headers); Assert.assertEquals(new Response<>(0, "Verification failed.", null), result); } @Test public void testGetToken2() throws UserOperationException { BasicAuthDto dto = new BasicAuthDto("username", null, ""); User user = new User(); Optional<User> optionalUser = Optional.of(user); Mockito.when(authenticationManager.authenticate(Mockito.any(UsernamePasswordAuthenticationToken.class))).thenReturn(null); Mockito.when(userRepository.findByUsername("username")).thenReturn(optionalUser); Mockito.when(jwtProvider.createToken(user)).thenReturn("token"); Response result = tokenServiceImpl.getToken(dto, headers); Assert.assertEquals("login success", result.getMsg()); } }
2,644
32.910256
130
java
train-ticket
train-ticket-master/ts-auth-service/src/test/java/auth/service/UserServiceImplTest.java
package auth.service; import auth.dto.AuthDto; import auth.entity.User; import auth.repository.UserRepository; import auth.service.impl.UserServiceImpl; import edu.fudan.common.util.Response; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.springframework.http.HttpHeaders; import org.springframework.security.crypto.password.PasswordEncoder; import java.util.*; @RunWith(JUnit4.class) public class UserServiceImplTest { @InjectMocks private UserServiceImpl userServiceImpl; @Mock private UserRepository userRepository; @Mock protected PasswordEncoder passwordEncoder; private HttpHeaders headers = new HttpHeaders(); @Before public void setUp() { MockitoAnnotations.initMocks(this); } @Test public void testSaveUser() { User user = new User(); Assert.assertEquals(null, userServiceImpl.saveUser(user)); } @Test public void testGetAllUser() { List<User> userList = new ArrayList<>(); userList.add(new User()); Mockito.when(userRepository.findAll()).thenReturn(userList); Assert.assertEquals(userList, userServiceImpl.getAllUser(headers)); } @Test public void testCreateDefaultAuthUser() { AuthDto dto = new AuthDto(UUID.randomUUID().toString(), "username", "password"); User user = new User(); Mockito.when(userRepository.save(user)).thenReturn(user); Mockito.when(passwordEncoder.encode(dto.getPassword())).thenReturn("password"); Assert.assertEquals(null, userServiceImpl.createDefaultAuthUser(dto)); } @Test public void testDeleteByUserId() { UUID userId = UUID.randomUUID(); Mockito.doNothing().doThrow(new RuntimeException()).when(userRepository).deleteByUserId(userId.toString()); Assert.assertEquals(new Response(1, "DELETE USER SUCCESS", null), userServiceImpl.deleteByUserId(userId.toString(), headers)); } }
2,164
29.492958
134
java
train-ticket
train-ticket-master/ts-basic-service/src/main/java/fdse/microservice/BasicApplication.java
package fdse.microservice; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.integration.annotation.IntegrationComponentScan; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.web.client.RestTemplate; import springfox.documentation.swagger2.annotations.EnableSwagger2; /** * @author fdse */ @SpringBootApplication @EnableAspectJAutoProxy(proxyTargetClass = true) @EnableAsync @IntegrationComponentScan @EnableSwagger2 @EnableDiscoveryClient public class BasicApplication { public static void main(String[] args) { SpringApplication.run(BasicApplication.class, args); } @LoadBalanced @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); } }
1,159
31.222222
75
java
train-ticket
train-ticket-master/ts-basic-service/src/main/java/fdse/microservice/config/SecurityConfig.java
package fdse.microservice.config; import edu.fudan.common.security.jwt.JWTFilter; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; 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.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import static org.springframework.web.cors.CorsConfiguration.ALL; /** * @author fdse */ @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) public class SecurityConfig extends WebSecurityConfigurerAdapter { /** * load password encoder * * @return PasswordEncoder */ @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } /** * allow cors domain * header By default, only six fields can be taken from the header, and the other fields can only be specified in the header. * credentials Cookies are not sent by default and can only be true if a Cookie is needed * Validity of this request * * @return WebMvcConfigurer */ @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurerAdapter() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins(ALL) .allowedMethods(ALL) .allowedHeaders(ALL) .allowCredentials(false) .maxAge(3600); } }; } @Override protected void configure(HttpSecurity httpSecurity) throws Exception { httpSecurity.httpBasic().disable() // close default csrf .csrf().disable() // close session .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .authorizeRequests() .antMatchers("/api/v1/basicservice/**").permitAll() .antMatchers("/swagger-ui.html", "/webjars/**", "/images/**", "/configuration/**", "/swagger-resources/**", "/v2/**").permitAll() .anyRequest().authenticated() .and() .addFilterBefore(new JWTFilter(), UsernamePasswordAuthenticationFilter.class); // close cache httpSecurity.headers().cacheControl(); } }
3,242
38.54878
130
java
train-ticket
train-ticket-master/ts-basic-service/src/main/java/fdse/microservice/controller/BasicController.java
package fdse.microservice.controller; import edu.fudan.common.entity.Travel; import fdse.microservice.service.BasicService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.web.bind.annotation.*; import java.util.List; import static org.springframework.http.ResponseEntity.ok; /** * @author Chenjie * @date 2017/6/6. */ @RestController @RequestMapping("/api/v1/basicservice") public class BasicController { @Autowired BasicService service; private static final Logger logger = LoggerFactory.getLogger(BasicController.class); @GetMapping(path = "/welcome") public String home(@RequestHeader HttpHeaders headers) { return "Welcome to [ Basic Service ] !"; } @PostMapping(value = "/basic/travel") public HttpEntity queryForTravel(@RequestBody Travel info, @RequestHeader HttpHeaders headers) { // TravelResult logger.info("[queryForTravel][Query for travel][Travel: {}]", info.toString()); return ok(service.queryForTravel(info, headers)); } @PostMapping(value = "/basic/travels") public HttpEntity queryForTravels(@RequestBody List<Travel> infos, @RequestHeader HttpHeaders headers) { // TravelResult logger.info("[queryForTravels][Query for travels][Travels: {}]", infos); return ok(service.queryForTravels(infos, headers)); } @GetMapping(value = "/basic/{stationName}") public HttpEntity queryForStationId(@PathVariable String stationName, @RequestHeader HttpHeaders headers) { // String id logger.info("[queryForStationId][Query for stationId by stationName][stationName: {}]", stationName); return ok(service.queryForStationId(stationName, headers)); } }
1,899
32.333333
111
java
train-ticket
train-ticket-master/ts-basic-service/src/main/java/fdse/microservice/service/BasicService.java
package fdse.microservice.service; import edu.fudan.common.entity.Travel; import edu.fudan.common.util.Response; import edu.fudan.common.entity.*; import org.springframework.http.HttpHeaders; import java.util.List; /** * @author Chenjie * @date 2017/6/6. */ public interface BasicService { /** * query for travel with travel information * * @param info information * @param headers headers * @return Response */ Response queryForTravel(Travel info, HttpHeaders headers); Response queryForTravels(List<Travel> infos, HttpHeaders headers); /** * query for station id with station name * * @param stationName station name * @param headers headers * @return Response */ Response queryForStationId(String stationName, HttpHeaders headers); }
828
22.027778
72
java
train-ticket
train-ticket-master/ts-basic-service/src/main/java/fdse/microservice/service/BasicServiceImpl.java
package fdse.microservice.service; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import edu.fudan.common.entity.*; import edu.fudan.common.util.JsonUtils; import edu.fudan.common.util.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import java.util.*; /** * @author fdse */ @Service public class BasicServiceImpl implements BasicService { @Autowired private RestTemplate restTemplate; @Autowired private DiscoveryClient discoveryClient; private static final Logger LOGGER = LoggerFactory.getLogger(BasicServiceImpl.class); private String getServiceUrl(String serviceName) { return "http://" + serviceName; } @Override public Response queryForTravel(Travel info, HttpHeaders headers) { Response response = new Response<>(); TravelResult result = new TravelResult(); result.setStatus(true); response.setStatus(1); response.setMsg("Success"); String start = info.getStartPlace(); String end = info.getEndPlace(); boolean startingPlaceExist = checkStationExists(start, headers); boolean endPlaceExist = checkStationExists(end, headers); if (!startingPlaceExist || !endPlaceExist) { result.setStatus(false); response.setStatus(0); response.setMsg("Start place or end place not exist!"); if (!startingPlaceExist) BasicServiceImpl.LOGGER.warn("[queryForTravel][Start place not exist][start place: {}]", info.getStartPlace()); if (!endPlaceExist) BasicServiceImpl.LOGGER.warn("[queryForTravel][End place not exist][end place: {}]", info.getEndPlace()); } TrainType trainType = queryTrainTypeByName(info.getTrip().getTrainTypeName(), headers); if (trainType == null) { BasicServiceImpl.LOGGER.warn("[queryForTravel][traintype doesn't exist][trainTypeName: {}]", info.getTrip().getTrainTypeName()); result.setStatus(false); response.setStatus(0); response.setMsg("Train type doesn't exist"); return response; } else { result.setTrainType(trainType); } String routeId = info.getTrip().getRouteId(); Route route = getRouteByRouteId(routeId, headers); if(route == null){ result.setStatus(false); response.setStatus(0); response.setMsg("Route doesn't exist"); return response; } //Check the route list for this train. Check that the required start and arrival stations are in the list of stops that are not on the route, and check that the location of the start station is before the stop //Trains that meet the above criteria are added to the return list int indexStart = 0; int indexEnd = 0; if (route.getStations().contains(start) && route.getStations().contains(end) && route.getStations().indexOf(start) < route.getStations().indexOf(end)){ indexStart = route.getStations().indexOf(start); indexEnd = route.getStations().indexOf(end); LOGGER.info("[queryForTravel][query start index and end index][indexStart: {} indexEnd: {}]", indexStart, indexEnd); LOGGER.info("[queryForTravel][query stations and distances][stations: {} distances: {}]", route.getStations(), route.getDistances()); }else { result.setStatus(false); response.setStatus(0); response.setMsg("Station not correct in Route"); return response; } PriceConfig priceConfig = queryPriceConfigByRouteIdAndTrainType(routeId, trainType.getName(), headers); HashMap<String, String> prices = new HashMap<>(); try { int distance = 0; distance = route.getDistances().get(indexEnd) - route.getDistances().get(indexStart); /** * We need the price Rate and distance (starting station). */ double priceForEconomyClass = distance * priceConfig.getBasicPriceRate(); double priceForConfortClass = distance * priceConfig.getFirstClassPriceRate(); prices.put("economyClass", "" + priceForEconomyClass); prices.put("confortClass", "" + priceForConfortClass); }catch (Exception e){ prices.put("economyClass", "95.0"); prices.put("confortClass", "120.0"); } result.setRoute(route); result.setPrices(prices); result.setPercent(1.0); response.setData(result); BasicServiceImpl.LOGGER.info("[queryForTravel][all done][result: {}]", result); return response; } @Override public Response queryForTravels(List<Travel> infos, HttpHeaders headers) { Response response = new Response<>(); response.setStatus(1); response.setMsg("Success"); HashMap<String, Travel> tripInfos = new HashMap<>(); HashMap<String, List<String>> startTrips = new HashMap<>(); HashMap<String, List<String>> endTrips = new HashMap<>(); HashMap<String, List<String>> routeTrips = new HashMap<>(); HashMap<String, List<String>> typeTrips = new HashMap<>(); Set<String> stationNames = new HashSet<>(); Set<String> trainTypeNames = new HashSet<>(); Set<String> routeIds = new HashSet<>(); Set<String> avaTrips = new HashSet<>(); for(Travel info: infos){ stationNames.add(info.getStartPlace()); stationNames.add(info.getEndPlace()); trainTypeNames.add(info.getTrip().getTrainTypeName()); routeIds.add(info.getTrip().getRouteId()); String tripNumber = info.getTrip().getTripId().toString(); avaTrips.add(tripNumber); tripInfos.put(tripNumber, info); String start = info.getStartPlace(); List<String> trips = startTrips.get(start); if(trips == null) { trips = new ArrayList<>(); } trips.add(tripNumber); startTrips.put(start, trips); String end = info.getEndPlace(); trips = endTrips.get(end); if(trips == null) { trips = new ArrayList<>(); } trips.add(tripNumber); endTrips.put(end, trips); String routeId = info.getTrip().getRouteId(); trips = routeTrips.get(routeId); if(trips == null) { trips = new ArrayList<>(); } trips.add(tripNumber); routeTrips.put(routeId, trips); String trainTypeName = info.getTrip().getTrainTypeName(); trips = typeTrips.get(trainTypeName); if(trips == null) { trips = new ArrayList<>(); } trips.add(tripNumber); typeTrips.put(trainTypeName, trips); } //List<String> invalidTrips = new ArrayList<>(); // check if station exist to exclude invalid travel info Map<String, String> stationMap = checkStationsExists(new ArrayList<>(stationNames), headers); if(stationMap == null) { response.setStatus(0); response.setMsg("all stations don't exist"); return response; } for(Map.Entry<String, String> s : stationMap.entrySet()){ if(s.getValue() == null ){ // station not exist if(startTrips.get(s.getKey()) != null){ avaTrips.removeAll(startTrips.get(s.getKey())); } if(endTrips.get(s.getKey()) != null){ avaTrips.removeAll(endTrips.get(s.getKey())); } } } if(avaTrips.size() == 0){ response.setStatus(0); response.setMsg("no travel info available"); return response; } // check if train_type exist List<TrainType> tts = queryTrainTypeByNames(new ArrayList<>(trainTypeNames), headers); if(tts == null){ response.setStatus(0); response.setMsg("all train_type don't exist"); return response; } Map<String, TrainType> trainTypeMap = new HashMap<>(); for(TrainType t: tts){ trainTypeMap.put(t.getName(), t); } for(Map.Entry<String, List<String>> typeTrip: typeTrips.entrySet()){ String ttype = typeTrip.getKey(); if(trainTypeMap.get(ttype) == null){ avaTrips.removeAll(typeTrip.getValue()); } } if(avaTrips.size() ==0){ response.setStatus(0); response.setMsg("no travel info available"); return response; } // check if route exist to exclude invalid travel info List<Route> routes = getRoutesByRouteIds(new ArrayList<>(routeIds), headers); if(routes == null) { response.setStatus(0); response.setMsg("all routes don't exist"); return response; } Map<String, Route> routeMap = new HashMap<>(); for(Route r: routes){ routeMap.put(r.getId(), r); } for(Map.Entry<String, List<String>> routeTrip: routeTrips.entrySet()){ String routeId = routeTrip.getKey(); if(routeMap.get(routeId) == null){ avaTrips.removeAll(routeTrip.getValue()); }else{ Route route = routeMap.get(routeId); List<String> trips = routeTrip.getValue(); for(String t: trips){ String start = tripInfos.get(t).getStartPlace(); String end = tripInfos.get(t).getEndPlace(); if (!route.getStations().contains(start) || !route.getStations().contains(end) || route.getStations().indexOf(start) >= route.getStations().indexOf(end)){ avaTrips.remove(t); } } } } if(avaTrips.size() == 0){ response.setStatus(0); response.setMsg("no travel info available"); return response; } List<String> routeIdAndTypes = new ArrayList<>(); for(String tripNumber: avaTrips){ String routeId = tripInfos.get(tripNumber).getTrip().getRouteId(); String trainType = tripInfos.get(tripNumber).getTrip().getTrainTypeName(); routeIdAndTypes.add(routeId+":"+trainType); } Map<String, PriceConfig> pcMap = queryPriceConfigByRouteIdsAndTrainTypes(routeIdAndTypes, headers); Map<String, TravelResult> trMap = new HashMap<>(); for(String tripNumber: avaTrips){ Travel info = tripInfos.get(tripNumber); String trainType = info.getTrip().getTrainTypeName(); String routeId = info.getTrip().getRouteId(); Route route = routeMap.get(routeId); int indexStart = route.getStations().indexOf(info.getStartPlace()); int indexEnd = route.getStations().indexOf(info.getEndPlace()); double basicPriceRate = 0.75; double firstPriceRate = 1; PriceConfig priceConfig = pcMap.get(routeId+":"+trainType); if(priceConfig != null){ basicPriceRate = priceConfig.getBasicPriceRate(); firstPriceRate = priceConfig.getFirstClassPriceRate(); } HashMap<String, String> prices = new HashMap<>(); try { int distance = 0; distance = route.getDistances().get(indexEnd) - route.getDistances().get(indexStart); /** * We need the price Rate and distance (starting station). */ double priceForEconomyClass = distance * basicPriceRate; double priceForConfortClass = distance * firstPriceRate; prices.put("economyClass", "" + priceForEconomyClass); prices.put("confortClass", "" + priceForConfortClass); }catch (Exception e){ prices.put("economyClass", "95.0"); prices.put("confortClass", "120.0"); } TravelResult result = new TravelResult(); result.setStatus(true); result.setTrainType(trainTypeMap.get(trainType)); result.setRoute(route); result.setPrices(prices); result.setPercent(1.0); trMap.put(tripNumber, result); } response.setData(trMap); BasicServiceImpl.LOGGER.info("[queryForTravels][all done][result map: {}]", trMap); return response; } @Override public Response queryForStationId(String stationName, HttpHeaders headers) { BasicServiceImpl.LOGGER.info("[queryForStationId][Query For Station Id][stationName: {}]", stationName); HttpEntity requestEntity = new HttpEntity(null); String station_service_url=getServiceUrl("ts-station-service"); ResponseEntity<Response> re = restTemplate.exchange( station_service_url + "/api/v1/stationservice/stations/id/" + stationName, HttpMethod.GET, requestEntity, Response.class); if (re.getBody().getStatus() != 1) { String msg = re.getBody().getMsg(); BasicServiceImpl.LOGGER.warn("[queryForStationId][Query for stationId error][stationName: {}, message: {}]", stationName, msg); return new Response<>(0, msg, null); } return re.getBody(); } public Map<String,String> checkStationsExists(List<String> stationNames, HttpHeaders headers) { BasicServiceImpl.LOGGER.info("[checkStationsExists][Check Stations Exists][stationNames: {}]", stationNames); HttpEntity requestEntity = new HttpEntity(stationNames, null); String station_service_url=getServiceUrl("ts-station-service"); ResponseEntity<Response> re = restTemplate.exchange( station_service_url + "/api/v1/stationservice/stations/idlist", HttpMethod.POST, requestEntity, Response.class); Response<Map<String, String>> r = re.getBody(); if(r.getStatus() == 0) { return null; } Map<String, String> stationMap = r.getData(); return stationMap; } public boolean checkStationExists(String stationName, HttpHeaders headers) { BasicServiceImpl.LOGGER.info("[checkStationExists][Check Station Exists][stationName: {}]", stationName); HttpEntity requestEntity = new HttpEntity(null); String station_service_url=getServiceUrl("ts-station-service"); ResponseEntity<Response> re = restTemplate.exchange( station_service_url + "/api/v1/stationservice/stations/id/" + stationName, HttpMethod.GET, requestEntity, Response.class); Response exist = re.getBody(); return exist.getStatus() == 1; } public List<TrainType> queryTrainTypeByNames(List<String> trainTypeNames, HttpHeaders headers) { BasicServiceImpl.LOGGER.info("[queryTrainTypeByNames][Query Train Type][Train Type names: {}]", trainTypeNames); HttpEntity requestEntity = new HttpEntity(trainTypeNames, null); String train_service_url=getServiceUrl("ts-train-service"); ResponseEntity<Response> re = restTemplate.exchange( train_service_url + "/api/v1/trainservice/trains/byNames", HttpMethod.POST, requestEntity, Response.class); Response<List<TrainType>> response = re.getBody(); if(response.getStatus() == 0){ return null; } List<TrainType> tts = Arrays.asList(JsonUtils.conveterObject(response.getData(), TrainType[].class)); return tts; } public TrainType queryTrainTypeByName(String trainTypeName, HttpHeaders headers) { BasicServiceImpl.LOGGER.info("[queryTrainTypeByName][Query Train Type][Train Type name: {}]", trainTypeName); HttpEntity requestEntity = new HttpEntity(null); String train_service_url=getServiceUrl("ts-train-service"); ResponseEntity<Response> re = restTemplate.exchange( train_service_url + "/api/v1/trainservice/trains/byName/" + trainTypeName, HttpMethod.GET, requestEntity, Response.class); Response response = re.getBody(); return JsonUtils.conveterObject(response.getData(), TrainType.class); } private List<Route> getRoutesByRouteIds(List<String> routeIds, HttpHeaders headers) { BasicServiceImpl.LOGGER.info("[getRoutesByRouteIds][Get Route By Ids][Route IDs:{}]", routeIds); HttpEntity requestEntity = new HttpEntity(routeIds, null); String route_service_url=getServiceUrl("ts-route-service"); ResponseEntity<Response> re = restTemplate.exchange( route_service_url + "/api/v1/routeservice/routes/byIds/", HttpMethod.POST, requestEntity, Response.class); Response<List<Route>> result = re.getBody(); if ( result.getStatus() == 0) { BasicServiceImpl.LOGGER.warn("[getRoutesByRouteIds][Get Route By Ids Failed][Fail msg: {}]", result.getMsg()); return null; } else { BasicServiceImpl.LOGGER.info("[getRoutesByRouteIds][Get Route By Ids][Success]"); List<Route> routes = Arrays.asList(JsonUtils.conveterObject(result.getData(), Route[].class));; return routes; } } private Route getRouteByRouteId(String routeId, HttpHeaders headers) { BasicServiceImpl.LOGGER.info("[getRouteByRouteId][Get Route By Id][Route ID:{}]", routeId); HttpEntity requestEntity = new HttpEntity(null); String route_service_url=getServiceUrl("ts-route-service"); ResponseEntity<Response> re = restTemplate.exchange( route_service_url + "/api/v1/routeservice/routes/" + routeId, HttpMethod.GET, requestEntity, Response.class); Response result = re.getBody(); if ( result.getStatus() == 0) { BasicServiceImpl.LOGGER.warn("[getRouteByRouteId][Get Route By Id Failed][Fail msg: {}]", result.getMsg()); return null; } else { BasicServiceImpl.LOGGER.info("[getRouteByRouteId][Get Route By Id][Success]"); return JsonUtils.conveterObject(result.getData(), Route.class); } } private PriceConfig queryPriceConfigByRouteIdAndTrainType(String routeId, String trainType, HttpHeaders headers) { BasicServiceImpl.LOGGER.info("[queryPriceConfigByRouteIdAndTrainType][Query For Price Config][RouteId: {} ,TrainType: {}]", routeId, trainType); HttpEntity requestEntity = new HttpEntity(null, null); String price_service_url=getServiceUrl("ts-price-service"); ResponseEntity<Response> re = restTemplate.exchange( price_service_url + "/api/v1/priceservice/prices/" + routeId + "/" + trainType, HttpMethod.GET, requestEntity, Response.class); Response result = re.getBody(); BasicServiceImpl.LOGGER.info("[queryPriceConfigByRouteIdAndTrainType][Response Resutl to String][result: {}]", result.toString()); return JsonUtils.conveterObject(result.getData(), PriceConfig.class); } private Map<String, PriceConfig> queryPriceConfigByRouteIdsAndTrainTypes(List<String> routeIdsTypes, HttpHeaders headers) { BasicServiceImpl.LOGGER.info("[queryPriceConfigByRouteIdsAndTrainTypes][Query For Price Config][RouteId and TrainType: {}]", routeIdsTypes); HttpEntity requestEntity = new HttpEntity(routeIdsTypes, null); String price_service_url=getServiceUrl("ts-price-service"); ResponseEntity<Response> re = restTemplate.exchange( price_service_url + "/api/v1/priceservice/prices/byRouteIdsAndTrainTypes", HttpMethod.POST, requestEntity, Response.class); Response<Map<String, PriceConfig>> result = re.getBody(); Map<String, PriceConfig> pcMap; if ( result.getStatus() == 0) { BasicServiceImpl.LOGGER.warn("[queryPriceConfigByRouteIdsAndTrainTypes][Get Price Config by routeId and trainType Failed][Fail msg: {}]", result.getMsg()); return null; } else { ObjectMapper mapper = new ObjectMapper(); try{ pcMap = mapper.readValue(JsonUtils.object2Json(result.getData()), new TypeReference<Map<String, PriceConfig>>(){}); }catch(Exception e) { BasicServiceImpl.LOGGER.warn("[queryPriceConfigByRouteIdsAndTrainTypes][Get Price Config by routeId and trainType Failed][Fail msg: {}]", e.getMessage()); return null; } BasicServiceImpl.LOGGER.info("[queryPriceConfigByRouteIdsAndTrainTypes][Get Price Config by routeId and trainType][Success][priceConfigs: {}]", result.getData()); return pcMap; } } }
21,924
44.113169
217
java
train-ticket
train-ticket-master/ts-basic-service/src/test/java/fdse/microservice/controller/BasicControllerTest.java
package fdse.microservice.controller; import com.alibaba.fastjson.JSONObject; import edu.fudan.common.entity.Travel; import edu.fudan.common.util.Response; import fdse.microservice.service.BasicService; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.springframework.http.*; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; @RunWith(JUnit4.class) public class BasicControllerTest { @InjectMocks private BasicController basicController; @Mock private BasicService basicService; private MockMvc mockMvc; private Response response = new Response(); @Before public void setUp() { MockitoAnnotations.initMocks(this); mockMvc = MockMvcBuilders.standaloneSetup(basicController).build(); } @Test public void testHome() throws Exception { mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/basicservice/welcome")) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.content().string("Welcome to [ Basic Service ] !")); } @Test public void testQueryForTravel() throws Exception { Travel info = new Travel(); Mockito.when(basicService.queryForTravel(Mockito.any(Travel.class), Mockito.any(HttpHeaders.class))).thenReturn(response); String requestJson = JSONObject.toJSONString(info); String result = mockMvc.perform(MockMvcRequestBuilders.post("/api/v1/basicservice/basic/travel").contentType(MediaType.APPLICATION_JSON).content(requestJson)) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } @Test public void testQueryForStationId() throws Exception { Mockito.when(basicService.queryForStationId(Mockito.anyString(), Mockito.any(HttpHeaders.class))).thenReturn(response); String result = mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/basicservice/basic/stationName")) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } }
2,721
39.626866
166
java
train-ticket
train-ticket-master/ts-basic-service/src/test/java/fdse/microservice/service/BasicServiceImplTest.java
package fdse.microservice.service; import edu.fudan.common.entity.*; import edu.fudan.common.util.Response; import edu.fudan.common.util.StringUtils; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.springframework.http.*; import org.springframework.web.client.RestTemplate; import java.util.Date; import java.util.UUID; @RunWith(JUnit4.class) public class BasicServiceImplTest { @InjectMocks private BasicServiceImpl basicServiceImpl; @Mock private RestTemplate restTemplate; private HttpHeaders headers = new HttpHeaders(); private HttpEntity requestEntity = new HttpEntity(headers); @Before public void setUp() { MockitoAnnotations.initMocks(this); } @Test public void testQueryForTravel() { Trip trip = new Trip(); trip.setTripId(new TripId()); trip.setRouteId("route_id"); trip.setStartTime(StringUtils.Date2String(new Date())); trip.setEndTime(StringUtils.Date2String(new Date())); Travel info = new Travel(); info.setTrip(trip); info.setStartPlace("starting_place"); info.setEndPlace("end_place"); info.setDepartureTime(StringUtils.Date2String(new Date())); Response response = new Response<>(1, null, null); ResponseEntity<Response> re = new ResponseEntity<>(response, HttpStatus.OK); //mock checkStationExists() and queryForStationId() Mockito.when(restTemplate.exchange( "http://ts-station-service:12345/api/v1/stationservice/stations/id/" + "starting_place", HttpMethod.GET, requestEntity, Response.class)).thenReturn(re); Mockito.when(restTemplate.exchange( "http://ts-station-service:12345/api/v1/stationservice/stations/id/" + "end_place", HttpMethod.GET, requestEntity, Response.class)).thenReturn(re); //mock queryTrainType() Mockito.when(restTemplate.exchange( "http://ts-train-service:14567/api/v1/trainservice/trains/" + "", HttpMethod.GET, requestEntity, Response.class)).thenReturn(re); //mock getRouteByRouteId() Mockito.when(restTemplate.exchange( "http://ts-route-service:11178/api/v1/routeservice/routes/" + "route_id", HttpMethod.GET, requestEntity, Response.class)).thenReturn(re); //mock queryPriceConfigByRouteIdAndTrainType() HttpEntity requestEntity2 = new HttpEntity(null, headers); Response response2 = new Response<>(1, null, new PriceConfig(UUID.randomUUID(), "", "", 1.0, 2.0)); ResponseEntity<Response> re2 = new ResponseEntity<>(response2, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-price-service:16579/api/v1/priceservice/prices/" + "route_id" + "/" + "", HttpMethod.GET, requestEntity2, Response.class)).thenReturn(re2); Response result = basicServiceImpl.queryForTravel(info, headers); Assert.assertEquals("Train type doesn't exist", result.getMsg()); } @Test public void testQueryForStationId() { Response response = new Response<>(1, null, null); ResponseEntity<Response> re = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-station-service:12345/api/v1/stationservice/stations/id/" + "stationName", HttpMethod.GET, requestEntity, Response.class)).thenReturn(re); Response result = basicServiceImpl.queryForStationId("stationName", headers); Assert.assertEquals(new Response<>(1, null, null), result); } @Test public void testCheckStationExists() { Response response = new Response<>(1, null, null); ResponseEntity<Response> re = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-station-service:12345/api/v1/stationservice/stations/id/" + "stationName", HttpMethod.GET, requestEntity, Response.class)).thenReturn(re); Boolean result = basicServiceImpl.checkStationExists("stationName", headers); Assert.assertTrue(result); } @Test public void testQueryTrainType() { Response response = new Response<>(1, null, null); ResponseEntity<Response> re = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-train-service:14567/api/v1/trainservice/trains/byName/" + "trainTypeName", HttpMethod.GET, requestEntity, Response.class)).thenReturn(re); TrainType result = basicServiceImpl.queryTrainTypeByName("trainTypeId", headers); Assert.assertNull(result); } }
5,217
39.449612
107
java
train-ticket
train-ticket-master/ts-cancel-service/src/main/java/cancel/CancelApplication.java
package cancel; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.integration.annotation.IntegrationComponentScan; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.web.client.RestTemplate; import springfox.documentation.swagger2.annotations.EnableSwagger2; /** * @author fdse */ @SpringBootApplication @EnableAspectJAutoProxy(proxyTargetClass = true) @EnableAsync @IntegrationComponentScan @EnableSwagger2 @EnableDiscoveryClient public class CancelApplication { public static void main(String[] args) { SpringApplication.run(CancelApplication.class, args); } @LoadBalanced @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); } }
1,180
31.805556
75
java
train-ticket
train-ticket-master/ts-cancel-service/src/main/java/cancel/config/SecurityConfig.java
package cancel.config; import edu.fudan.common.security.jwt.JWTFilter; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; 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.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import static org.springframework.web.cors.CorsConfiguration.ALL; /** * @author fdse */ @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) public class SecurityConfig extends WebSecurityConfigurerAdapter { /** * load password encoder * * @return PasswordEncoder */ @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } /** * allow cors domain * header By default, only six fields can be taken from the header, and the other fields can only be specified in the header. * credentials Cookies are not sent by default and can only be true if a Cookie is needed * Validity of this request * * @return WebMvcConfigurer */ @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurerAdapter() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins(ALL) .allowedMethods(ALL) .allowedHeaders(ALL) .allowCredentials(false) .maxAge(3600); } }; } @Override protected void configure(HttpSecurity httpSecurity) throws Exception { httpSecurity.httpBasic().disable() // close default csrf .csrf().disable() // close session .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .authorizeRequests() .antMatchers("/api/v1/cancelservice/**").hasAnyRole("ADMIN", "USER") .antMatchers("/swagger-ui.html", "/webjars/**", "/images/**", "/configuration/**", "/swagger-resources/**", "/v2/**").permitAll() .anyRequest().authenticated() .and() .addFilterBefore(new JWTFilter(), UsernamePasswordAuthenticationFilter.class); // close cache httpSecurity.headers().cacheControl(); } }
3,248
38.621951
130
java
train-ticket
train-ticket-master/ts-cancel-service/src/main/java/cancel/controller/CancelController.java
package cancel.controller; import cancel.service.CancelService; import edu.fudan.common.util.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import static org.springframework.http.ResponseEntity.ok; /** * @author fdse */ @RestController @RequestMapping("/api/v1/cancelservice") public class CancelController { @Autowired CancelService cancelService; private static final Logger LOGGER = LoggerFactory.getLogger(CancelController.class); @GetMapping(path = "/welcome") public String home(@RequestHeader HttpHeaders headers) { return "Welcome to [ Cancel Service ] !"; } @CrossOrigin(origins = "*") @GetMapping(path = "/cancel/refound/{orderId}") public HttpEntity calculate(@PathVariable String orderId, @RequestHeader HttpHeaders headers) { CancelController.LOGGER.info("[calculate][Calculate Cancel Refund][OrderId: {}]", orderId); return ok(cancelService.calculateRefund(orderId, headers)); } @CrossOrigin(origins = "*") @GetMapping(path = "/cancel/{orderId}/{loginId}") public HttpEntity cancelTicket(@PathVariable String orderId, @PathVariable String loginId, @RequestHeader HttpHeaders headers) { CancelController.LOGGER.info("[cancelTicket][Cancel Ticket][info: {}]", orderId); try { CancelController.LOGGER.info("[cancelTicket][Cancel Ticket, Verify Success]"); return ok(cancelService.cancelOrder(orderId, loginId, headers)); } catch (Exception e) { CancelController.LOGGER.error(e.getMessage()); return ok(new Response<>(1, "error", null)); } } }
1,931
34.127273
99
java
train-ticket
train-ticket-master/ts-cancel-service/src/main/java/cancel/entity/GetAccountByIdInfo.java
package cancel.entity; import lombok.Data; /** * @author fdse */ @Data public class GetAccountByIdInfo { private String accountId; public GetAccountByIdInfo() { //Default Constructor } }
214
10.944444
33
java
train-ticket
train-ticket-master/ts-cancel-service/src/main/java/cancel/entity/GetAccountByIdResult.java
package cancel.entity; import edu.fudan.common.entity.Account; import lombok.Data; import edu.fudan.common.entity.Account; /** * @author fdse */ @Data public class GetAccountByIdResult { private boolean status; private String message; private Account account; public GetAccountByIdResult() { //Default Constructor } }
355
13.833333
39
java
train-ticket
train-ticket-master/ts-cancel-service/src/main/java/cancel/entity/GetOrderByIdInfo.java
package cancel.entity; import lombok.Data; /** * @author fdse */ @Data public class GetOrderByIdInfo { private String orderId; public GetOrderByIdInfo() { //Default Constructor } }
208
10.611111
31
java
train-ticket
train-ticket-master/ts-cancel-service/src/main/java/cancel/service/CancelService.java
package cancel.service; import edu.fudan.common.util.Response; import org.springframework.http.HttpHeaders; /** * @author fdse */ public interface CancelService { /** * cancel order by order id, login id * * @param orderId order id * @param loginId login id * @param headers headers * @throws Exception * @return Response */ Response cancelOrder(String orderId, String loginId, HttpHeaders headers); /** * calculate refund by login id * * @param orderId order id * @param headers headers * @return Response */ Response calculateRefund(String orderId, HttpHeaders headers); }
669
19.9375
78
java
train-ticket
train-ticket-master/ts-cancel-service/src/main/java/cancel/service/CancelServiceImpl.java
package cancel.service; import edu.fudan.common.entity.NotifyInfo; import edu.fudan.common.entity.OrderStatus; import edu.fudan.common.entity.Order; import edu.fudan.common.entity.SeatClass; import edu.fudan.common.entity.User; import edu.fudan.common.util.Response; import edu.fudan.common.util.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import java.text.DecimalFormat; import java.util.Calendar; import java.util.Date; /** * @author fdse */ @Service public class CancelServiceImpl implements CancelService { @Autowired private RestTemplate restTemplate; @Autowired private DiscoveryClient discoveryClient; private static final Logger LOGGER = LoggerFactory.getLogger(CancelServiceImpl.class); String orderStatusCancelNotPermitted = "Order Status Cancel Not Permitted"; private String getServiceUrl(String serviceName) { return "http://" + serviceName; } @Override public Response cancelOrder(String orderId, String loginId, HttpHeaders headers) { Response<Order> orderResult = getOrderByIdFromOrder(orderId, headers); if (orderResult.getStatus() == 1) { CancelServiceImpl.LOGGER.info("[cancelOrder][Cancel Order, Order found G|H]"); Order order = orderResult.getData(); if (order.getStatus() == OrderStatus.NOTPAID.getCode() || order.getStatus() == OrderStatus.PAID.getCode() || order.getStatus() == OrderStatus.CHANGE.getCode()) { // order.setStatus(OrderStatus.CANCEL.getCode()); Response changeOrderResult = cancelFromOrder(order, headers); // 0 -- not find order 1 - cancel success if (changeOrderResult.getStatus() == 1) { CancelServiceImpl.LOGGER.info("[cancelOrder][Cancel Order Success]"); //Draw back money String money = calculateRefund(order); boolean status = drawbackMoney(money, loginId, headers); if (status) { CancelServiceImpl.LOGGER.info("[cancelOrder][Draw Back Money Success]"); Response<User> result = getAccount(order.getAccountId().toString(), headers); if (result.getStatus() == 0) { return new Response<>(0, "Cann't find userinfo by user id.", null); } NotifyInfo notifyInfo = new NotifyInfo(); notifyInfo.setDate(new Date().toString()); notifyInfo.setEmail(result.getData().getEmail()); notifyInfo.setStartPlace(order.getFrom()); notifyInfo.setEndPlace(order.getTo()); notifyInfo.setUsername(result.getData().getUserName()); notifyInfo.setSeatNumber(order.getSeatNumber()); notifyInfo.setOrderNumber(order.getId().toString()); notifyInfo.setPrice(order.getPrice()); notifyInfo.setSeatClass(SeatClass.getNameByCode(order.getSeatClass())); notifyInfo.setStartTime(order.getTravelTime().toString()); // TODO: change to async message serivce // sendEmail(notifyInfo, headers); } else { CancelServiceImpl.LOGGER.error("[cancelOrder][Draw Back Money Failed][loginId: {}, orderId: {}]", loginId, orderId); } return new Response<>(1, "Success.", "test not null"); } else { CancelServiceImpl.LOGGER.error("[cancelOrder][Cancel Order Failed][orderId: {}, Reason: {}]", orderId, changeOrderResult.getMsg()); return new Response<>(0, changeOrderResult.getMsg(), null); } } else { CancelServiceImpl.LOGGER.info("[cancelOrder][Cancel Order, Order Status Not Permitted][loginId: {}, orderId: {}]", loginId, orderId); return new Response<>(0, orderStatusCancelNotPermitted, null); } } else { Response<Order> orderOtherResult = getOrderByIdFromOrderOther(orderId, headers); if (orderOtherResult.getStatus() == 1) { CancelServiceImpl.LOGGER.info("[cancelOrder][Cancel Order, Order found Z|K|Other]"); Order order = orderOtherResult.getData(); if (order.getStatus() == OrderStatus.NOTPAID.getCode() || order.getStatus() == OrderStatus.PAID.getCode() || order.getStatus() == OrderStatus.CHANGE.getCode()) { CancelServiceImpl.LOGGER.info("[cancelOrder][Cancel Order, Order status ok]"); // order.setStatus(OrderStatus.CANCEL.getCode()); Response changeOrderResult = cancelFromOtherOrder(order, headers); if (changeOrderResult.getStatus() == 1) { CancelServiceImpl.LOGGER.info("[cancelOrder][Cancel Order Success]"); //Draw back money String money = calculateRefund(order); boolean status = drawbackMoney(money, loginId, headers); if (status) { CancelServiceImpl.LOGGER.info("[cancelOrder][Draw Back Money Success]"); } else { CancelServiceImpl.LOGGER.error("[cancelOrder][Draw Back Money Failed][loginId: {}, orderId: {}]", loginId, orderId); } return new Response<>(1, "Success.", null); } else { CancelServiceImpl.LOGGER.error("[cancelOrder][Cancel Order Failed][orderId: {}, Reason: {}]", orderId, changeOrderResult.getMsg()); return new Response<>(0, "Fail.Reason:" + changeOrderResult.getMsg(), null); } } else { CancelServiceImpl.LOGGER.warn("[cancelOrder][Cancel Order, Order Status Not Permitted][loginId: {}, orderId: {}]", loginId, orderId); return new Response<>(0, orderStatusCancelNotPermitted, null); } } else { CancelServiceImpl.LOGGER.warn("[cancelOrder][Cancel Order, Order Not Found][loginId: {}, orderId: {}]", loginId, orderId); return new Response<>(0, "Order Not Found.", null); } } } public boolean sendEmail(NotifyInfo notifyInfo, HttpHeaders headers) { CancelServiceImpl.LOGGER.info("[sendEmail][Send Email]"); HttpHeaders newHeaders = getAuthorizationHeadersFrom(headers); HttpEntity requestEntity = new HttpEntity(notifyInfo, newHeaders); String notification_service_url = getServiceUrl("ts-notification-service"); ResponseEntity<Boolean> re = restTemplate.exchange( notification_service_url + "/api/v1/notifyservice/notification/order_cancel_success", HttpMethod.POST, requestEntity, Boolean.class); return re.getBody(); } @Override public Response calculateRefund(String orderId, HttpHeaders headers) { Response<Order> orderResult = getOrderByIdFromOrder(orderId, headers); if (orderResult.getStatus() == 1) { Order order = orderResult.getData(); if (order.getStatus() == OrderStatus.NOTPAID.getCode() || order.getStatus() == OrderStatus.PAID.getCode()) { if (order.getStatus() == OrderStatus.NOTPAID.getCode()) { CancelServiceImpl.LOGGER.info("[calculateRefund][Cancel Order, Refund Price From Order Service.Not Paid][orderId: {}]", orderId); return new Response<>(1, "Success. Refoud 0", "0"); } else { CancelServiceImpl.LOGGER.info("[calculateRefund][Cancel Order, Refund Price From Order Service.Paid][orderId: {}]", orderId); return new Response<>(1, "Success. ", calculateRefund(order)); } } else { CancelServiceImpl.LOGGER.info("[calculateRefund][Cancel Order Refund Price Order.Cancel Not Permitted][orderId: {}]", orderId); return new Response<>(0, "Order Status Cancel Not Permitted, Refound error", null); } } else { Response<Order> orderOtherResult = getOrderByIdFromOrderOther(orderId, headers); if (orderOtherResult.getStatus() == 1) { Order order = orderOtherResult.getData(); if (order.getStatus() == OrderStatus.NOTPAID.getCode() || order.getStatus() == OrderStatus.PAID.getCode()) { if (order.getStatus() == OrderStatus.NOTPAID.getCode()) { CancelServiceImpl.LOGGER.info("[calculateRefund][Cancel Order, Refund Price From Order Other Service.Not Paid][orderId: {}]", orderId); return new Response<>(1, "Success, Refound 0", "0"); } else { CancelServiceImpl.LOGGER.info("[Cancel Order][Refund Price From Order Other Service.Paid][orderId: {}]", orderId); return new Response<>(1, "Success", calculateRefund(order)); } } else { CancelServiceImpl.LOGGER.warn("[Cancel Order][Refund Price, Order Other. Cancel Not Permitted][orderId: {}]", orderId); return new Response<>(0, orderStatusCancelNotPermitted, null); } } else { CancelServiceImpl.LOGGER.error("[Cancel Order][Refund Price][Order not found][orderId: {}]", orderId); return new Response<>(0, "Order Not Found", null); } } } private String calculateRefund(Order order) { if (order.getStatus() == OrderStatus.NOTPAID.getCode()) { return "0.00"; } CancelServiceImpl.LOGGER.info("[calculateRefund][Cancel Order][Order Travel Date: {}]", order.getTravelDate().toString()); Date nowDate = new Date(); Calendar cal = Calendar.getInstance(); cal.setTime(StringUtils.String2Date(order.getTravelDate())); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH); int day = cal.get(Calendar.DAY_OF_MONTH); Calendar cal2 = Calendar.getInstance(); cal2.setTime(StringUtils.String2Date(order.getTravelTime())); int hour = cal2.get(Calendar.HOUR); int minute = cal2.get(Calendar.MINUTE); int second = cal2.get(Calendar.SECOND); Date startTime = new Date(year, //NOSONAR month, day, hour, minute, second); CancelServiceImpl.LOGGER.info("[calculateRefund][Cancel Order][nowDate : {}]", nowDate); CancelServiceImpl.LOGGER.info("[calculateRefund][Cancel Order][startTime: {}]", startTime); if (nowDate.after(startTime)) { CancelServiceImpl.LOGGER.warn("[calculateRefund][Cancel Order, Ticket expire refund 0]"); return "0"; } else { double totalPrice = Double.parseDouble(order.getPrice()); double price = totalPrice * 0.8; DecimalFormat priceFormat = new java.text.DecimalFormat("0.00"); String str = priceFormat.format(price); CancelServiceImpl.LOGGER.info("[calculateRefund][calculate refund][refund: {}]", str); return str; } } private Response cancelFromOrder(Order order, HttpHeaders headers) { CancelServiceImpl.LOGGER.info("[cancelFromOrder][Change Order Status]"); order.setStatus(OrderStatus.CANCEL.getCode()); // add authorization header HttpHeaders newHeaders = getAuthorizationHeadersFrom(headers); HttpEntity requestEntity = new HttpEntity(order, newHeaders); String order_service_url = getServiceUrl("ts-order-service"); ResponseEntity<Response> re = restTemplate.exchange( order_service_url + "/api/v1/orderservice/order", HttpMethod.PUT, requestEntity, Response.class); return re.getBody(); } public static HttpHeaders getAuthorizationHeadersFrom(HttpHeaders oldHeaders) { HttpHeaders newHeaders = new HttpHeaders(); if (oldHeaders.containsKey(HttpHeaders.AUTHORIZATION)) { newHeaders.add(HttpHeaders.AUTHORIZATION, oldHeaders.getFirst(HttpHeaders.AUTHORIZATION)); } return newHeaders; } private Response cancelFromOtherOrder(Order order, HttpHeaders headers) { CancelServiceImpl.LOGGER.info("[cancelFromOtherOrder][Change Order Status]"); order.setStatus(OrderStatus.CANCEL.getCode()); HttpHeaders newHeaders = getAuthorizationHeadersFrom(headers); HttpEntity requestEntity = new HttpEntity(order, newHeaders); String order_other_service_url = getServiceUrl("ts-order-other-service"); ResponseEntity<Response> re = restTemplate.exchange( order_other_service_url + "/api/v1/orderOtherService/orderOther", HttpMethod.PUT, requestEntity, Response.class); return re.getBody(); } public boolean drawbackMoney(String money, String userId, HttpHeaders headers) { CancelServiceImpl.LOGGER.info("[drawbackMoney][Draw Back Money]"); HttpHeaders newHeaders = getAuthorizationHeadersFrom(headers); HttpEntity requestEntity = new HttpEntity(newHeaders); String inside_payment_service_url = getServiceUrl("ts-inside-payment-service"); ResponseEntity<Response> re = restTemplate.exchange( inside_payment_service_url + "/api/v1/inside_pay_service/inside_payment/drawback/" + userId + "/" + money, HttpMethod.GET, requestEntity, Response.class); Response result = re.getBody(); return result.getStatus() == 1; } public Response<User> getAccount(String orderId, HttpHeaders headers) { CancelServiceImpl.LOGGER.info("[getAccount][Get By Id][orderId: {}]", orderId); HttpHeaders newHeaders = getAuthorizationHeadersFrom(headers); HttpEntity requestEntity = new HttpEntity(newHeaders); String user_service_url = getServiceUrl("ts-user-service"); ResponseEntity<Response<User>> re = restTemplate.exchange( user_service_url + "/api/v1/userservice/users/id/" + orderId, HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<User>>() { }); return re.getBody(); } private Response<Order> getOrderByIdFromOrder(String orderId, HttpHeaders headers) { CancelServiceImpl.LOGGER.info("[getOrderByIdFromOrder][Get Order][orderId: {}]", orderId); HttpHeaders newHeaders = getAuthorizationHeadersFrom(headers); HttpEntity requestEntity = new HttpEntity(newHeaders); String order_service_url = getServiceUrl("ts-order-service"); ResponseEntity<Response<Order>> re = restTemplate.exchange( order_service_url + "/api/v1/orderservice/order/" + orderId, HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<Order>>() { }); return re.getBody(); } private Response<Order> getOrderByIdFromOrderOther(String orderId, HttpHeaders headers) { CancelServiceImpl.LOGGER.info("[getOrderByIdFromOrderOther][Get Order][orderId: {}]", orderId); HttpHeaders newHeaders = getAuthorizationHeadersFrom(headers); HttpEntity requestEntity = new HttpEntity(newHeaders); String order_other_service_url = getServiceUrl("ts-order-other-service"); ResponseEntity<Response<Order>> re = restTemplate.exchange( order_other_service_url + "/api/v1/orderOtherService/orderOther/" + orderId, HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<Order>>() { }); return re.getBody(); } }
16,899
49.148368
159
java
train-ticket
train-ticket-master/ts-cancel-service/src/test/java/cancel/controller/CancelControllerTest.java
package cancel.controller; import cancel.service.CancelService; import com.alibaba.fastjson.JSONObject; import edu.fudan.common.util.Response; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; @RunWith(JUnit4.class) public class CancelControllerTest { @InjectMocks private CancelController cancelController; @Mock private CancelService cancelService; private MockMvc mockMvc; private Response response = new Response(); @Before public void setUp() { MockitoAnnotations.initMocks(this); mockMvc = MockMvcBuilders.standaloneSetup(cancelController).build(); } @Test public void testHome() throws Exception { mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/cancelservice/welcome")) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.content().string("Welcome to [ Cancel Service ] !")); } @Test public void testCalculate() throws Exception { Mockito.when(cancelService.calculateRefund(Mockito.anyString(), Mockito.any(HttpHeaders.class))).thenReturn(response); String result = mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/cancelservice/cancel/refound/order_id")) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } @Test public void testCancelTicket() throws Exception { Mockito.when(cancelService.cancelOrder(Mockito.anyString(), Mockito.anyString(), Mockito.any(HttpHeaders.class))).thenReturn(response); String result = mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/cancelservice/cancel/order_id/login_id")) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } }
2,679
39
143
java
train-ticket
train-ticket-master/ts-cancel-service/src/test/java/cancel/service/CancelServiceImplTest.java
package cancel.service; import edu.fudan.common.entity.NotifyInfo; import edu.fudan.common.entity.Order; import edu.fudan.common.entity.User; import edu.fudan.common.util.Response; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.*; import org.springframework.web.client.RestTemplate; @RunWith(JUnit4.class) public class CancelServiceImplTest { @InjectMocks private CancelServiceImpl cancelServiceImpl; @Mock private RestTemplate restTemplate; private HttpHeaders headers = new HttpHeaders(); private HttpEntity requestEntity = new HttpEntity(headers); @Before public void setUp() { MockitoAnnotations.initMocks(this); } @Test public void testCancelOrder1() { //mock getOrderByIdFromOrder() Order order = new Order(); order.setStatus(6); Response<Order> response = new Response<>(1, null, order); ResponseEntity<Response<Order>> re = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-order-service:12031/api/v1/orderservice/order/" + "order_id", HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<Order>>() { })).thenReturn(re); Response result = cancelServiceImpl.cancelOrder("order_id", "login_id", headers); Assert.assertEquals(new Response<>(0, "Order Status Cancel Not Permitted", null), result); } @Test public void testCancelOrder2() { //mock getOrderByIdFromOrder() Response<Order> response = new Response<>(0, null, null); ResponseEntity<Response<Order>> re = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-order-service:12031/api/v1/orderservice/order/" + "order_id", HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<Order>>() { })).thenReturn(re); //mock getOrderByIdFromOrderOther() Order order = new Order(); order.setStatus(6); Response<Order> response2 = new Response<>(1, null, order); ResponseEntity<Response<Order>> re2 = new ResponseEntity<>(response2, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-order-other-service:12032/api/v1/orderOtherService/orderOther/" + "order_id", HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<Order>>() { })).thenReturn(re2); Response result = cancelServiceImpl.cancelOrder("order_id", "login_id", headers); Assert.assertEquals(new Response<>(0, "Order Status Cancel Not Permitted", null), result); } @Test public void testSendEmail() { NotifyInfo notifyInfo = new NotifyInfo(); HttpEntity requestEntity2 = new HttpEntity(notifyInfo, headers); ResponseEntity<Boolean> re = new ResponseEntity<>(true, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-notification-service:17853/api/v1/notifyservice/notification/order_cancel_success", HttpMethod.POST, requestEntity2, Boolean.class)).thenReturn(re); Boolean result = cancelServiceImpl.sendEmail(notifyInfo, headers); Assert.assertTrue(result); } @Test public void testCalculateRefund1() { //mock getOrderByIdFromOrder() Order order = new Order(); order.setStatus(6); Response<Order> response = new Response<>(1, null, order); ResponseEntity<Response<Order>> re = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-order-service:12031/api/v1/orderservice/order/" + "order_id", HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<Order>>() { })).thenReturn(re); Response result = cancelServiceImpl.calculateRefund("order_id", headers); Assert.assertEquals(new Response<>(0, "Order Status Cancel Not Permitted, Refound error", null), result); } @Test public void testCalculateRefund2() { //mock getOrderByIdFromOrder() Response<Order> response = new Response<>(0, null, null); ResponseEntity<Response<Order>> re = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-order-service:12031/api/v1/orderservice/order/" + "order_id", HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<Order>>() { })).thenReturn(re); //mock getOrderByIdFromOrderOther() Order order = new Order(); order.setStatus(6); Response<Order> response2 = new Response<>(1, null, order); ResponseEntity<Response<Order>> re2 = new ResponseEntity<>(response2, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-order-other-service:12032/api/v1/orderOtherService/orderOther/" + "order_id", HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<Order>>() { })).thenReturn(re2); Response result = cancelServiceImpl.calculateRefund("order_id", headers); Assert.assertEquals(new Response<>(0, "Order Status Cancel Not Permitted", null), result); } @Test public void testDrawbackMoney() { Response response = new Response<>(1, null, null); ResponseEntity<Response> re = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-inside-payment-service:18673/api/v1/inside_pay_service/inside_payment/drawback/" + "userId" + "/" + "money", HttpMethod.GET, requestEntity, Response.class)).thenReturn(re); Boolean result = cancelServiceImpl.drawbackMoney("money", "userId", headers); Assert.assertTrue(result); } @Test public void testGetAccount() { Response<User> response = new Response<>(); ResponseEntity<Response<User>> re = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-user-service:12342/api/v1/userservice/users/id/" + "orderId", HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<User>>() { })).thenReturn(re); Response<User> result = cancelServiceImpl.getAccount("orderId", headers); Assert.assertEquals(new Response<User>(null, null, null), result); } }
7,142
42.290909
135
java
train-ticket
train-ticket-master/ts-common/src/main/java/edu/fudan/common/config/SwaggerConfig.java
package edu.fudan.common.config; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; /** * @author fdse */ @Configuration public class SwaggerConfig { @Value("${swagger.controllerPackage}") private String controllerPackagePath; private static final Logger LOGGER = LoggerFactory.getLogger(SwaggerConfig.class); @Bean public Docket createRestApi() { SwaggerConfig.LOGGER.info("[createRestApi][create][controllerPackagePath: {}]", controllerPackagePath); return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select().apis(RequestHandlerSelectors.basePackage(controllerPackagePath)) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("Springboot builds the API documentation with swagger") .description("Simple and elegant restful style") .termsOfServiceUrl("https://github.com/FudanSELab/train-ticket") .version("1.0") .build(); } }
1,620
34.23913
111
java
train-ticket
train-ticket-master/ts-common/src/main/java/edu/fudan/common/entity/Account.java
package edu.fudan.common.entity; import lombok.Data; import lombok.NoArgsConstructor; import java.util.UUID; /** * @author fdse */ @Data public class Account { private UUID id; private String accountId; private String loginId; private String password; private int gender; private String name; private int documentType; private String documentNum; private String email; public Account(){ gender = Gender.OTHER.getCode(); password = "defaultPassword"; //NOSONAR name = "None"; documentType = DocumentType.NONE.getCode(); documentNum = "0123456789"; email = "0123456789"; } }
681
15.238095
51
java
train-ticket
train-ticket-master/ts-common/src/main/java/edu/fudan/common/entity/AdminTrip.java
package edu.fudan.common.entity; import lombok.Data; /** * @author fdse */ @Data public class AdminTrip { private Trip trip; private TrainType trainType; private Route route; public AdminTrip(){ //Default Constructor } }
255
12.473684
32
java
train-ticket
train-ticket-master/ts-common/src/main/java/edu/fudan/common/entity/Assurance.java
package edu.fudan.common.entity; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.Data; import javax.validation.constraints.NotNull; import java.util.UUID; /** * @author fdse */ @Data @JsonIgnoreProperties(ignoreUnknown = true) public class Assurance { private UUID id; /** * which order the assurance is related to */ @NotNull private UUID orderId; /** * the type of assurance */ private AssuranceType type; public Assurance(){ this.orderId = UUID.randomUUID(); } public Assurance(UUID id, UUID orderId, AssuranceType type){ this.id = id; this.orderId = orderId; this.type = type; } }
716
16.925
64
java
train-ticket
train-ticket-master/ts-common/src/main/java/edu/fudan/common/entity/AssuranceType.java
package edu.fudan.common.entity; import java.io.Serializable; /** * @author fdse */ public enum AssuranceType implements Serializable{ /** * traffic accident assurance */ TRAFFIC_ACCIDENT (1, "Traffic Accident Assurance", 3.0); /** * index of assurance type */ private int index; /** * the assurance type name */ private String name; /** * the price of this type of assurence */ private double price; AssuranceType(int index, String name, double price){ this.index = index; this.name = name; this.price = price; } public int getIndex() { return index; } void setIndex(int index) { this.index = index; } public String getName() { return name; } void setName(String name) { this.name = name; } public double getPrice() { return price; } void setPrice(double price) { this.price = price; } public static AssuranceType getTypeByIndex(int index){ AssuranceType[] ats = AssuranceType.values(); for(AssuranceType at : ats){ if(at.getIndex() == index){ return at; } } return null; } }
1,284
17.357143
60
java
train-ticket
train-ticket-master/ts-common/src/main/java/edu/fudan/common/entity/Config.java
package edu.fudan.common.entity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; /** * @author fdse */ @Data @NoArgsConstructor @AllArgsConstructor public class Config { private String name; private String value; private String description; }
302
12.772727
33
java
train-ticket
train-ticket-master/ts-common/src/main/java/edu/fudan/common/entity/Consign.java
package edu.fudan.common.entity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.util.UUID; @Data @AllArgsConstructor @NoArgsConstructor public class Consign { private String id; //id主键改成String类型的 自定义生成策略 private String orderId; //这次托运关联订单 private String accountId; //这次托运关联的账户 private String handleDate; private String targetDate; private String from; private String to; private String consignee; private String phone; private double weight; private boolean isWithin; }
580
21.346154
55
java
train-ticket
train-ticket-master/ts-common/src/main/java/edu/fudan/common/entity/Contacts.java
package edu.fudan.common.entity; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.util.UUID; /** * @author fdse */ @Data @JsonIgnoreProperties(ignoreUnknown = true) @NoArgsConstructor @AllArgsConstructor public class Contacts { private UUID id; private UUID accountId; private String name; private int documentType; private String documentNumber; private String phoneNumber; @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Contacts other = (Contacts) obj; return name.equals(other.getName()) && accountId .equals( other.getAccountId() ) && documentNumber.equals(other.getDocumentNumber()) && phoneNumber.equals(other.getPhoneNumber()) && documentType == other.getDocumentType(); } @Override public int hashCode() { int result = 17; result = 31 * result + (id == null ? 0 : id.hashCode()); return result; } }
1,288
21.614035
67
java
train-ticket
train-ticket-master/ts-common/src/main/java/edu/fudan/common/entity/DocumentType.java
package edu.fudan.common.entity; /** * @author fdse */ public enum DocumentType { /** * null */ NONE (0,"Null"), /** * id card */ ID_CARD (1,"ID Card"), /** * passport */ PASSPORT (2,"Passport"), /** * other */ OTHER (3,"Other"); private int code; private String name; DocumentType(int code, String name){ this.code = code; this.name = name; } public int getCode(){ return code; } public String getName() { return name; } public static String getNameByCode(int code){ DocumentType[] documentTypeSet = DocumentType.values(); for(DocumentType documentType : documentTypeSet){ if(documentType.getCode() == code){ return documentType.getName(); } } return documentTypeSet[0].getName(); } }
923
17.117647
63
java
train-ticket
train-ticket-master/ts-common/src/main/java/edu/fudan/common/entity/Food.java
package edu.fudan.common.entity; import lombok.Data; import javax.persistence.Embeddable; import java.io.Serializable; @Data @Embeddable public class Food implements Serializable{ private String foodName; private double price; public Food(){ //Default Constructor } }
298
13.95
42
java
train-ticket
train-ticket-master/ts-common/src/main/java/edu/fudan/common/entity/FoodOrder.java
package edu.fudan.common.entity; import lombok.Data; import java.util.UUID; /** * @author fdse */ @Data public class FoodOrder { private String id; private String orderId; /** * 1:train food;2:food store */ private int foodType; private String stationName; private String storeName; private String foodName; private double price; public FoodOrder(){ //Default Constructor } }
448
11.828571
32
java
train-ticket
train-ticket-master/ts-common/src/main/java/edu/fudan/common/entity/Gender.java
package edu.fudan.common.entity; /** * @author fdse */ public enum Gender { /** * null */ NONE (0, "Null"), /** * male */ MALE (1, "Male"), /** * female */ FEMALE (2, "Female"), /** * other */ OTHER (3, "Other"); private int code; private String name; Gender(int code, String name){ this.code = code; this.name = name; } public int getCode(){ return code; } public String getName() { return name; } public static String getNameByCode(int code){ Gender[] genderSet = Gender.values(); for(Gender gender : genderSet){ if(gender.getCode() == code){ return gender.getName(); } } return genderSet[0].getName(); } }
840
15.173077
49
java
train-ticket
train-ticket-master/ts-common/src/main/java/edu/fudan/common/entity/LeftTicketInfo.java
package edu.fudan.common.entity; import lombok.Data; import javax.validation.Valid; import javax.validation.constraints.NotNull; import java.util.Set; /** * @author fdse */ @Data public class LeftTicketInfo { @Valid @NotNull private Set<Ticket> soldTickets; public LeftTicketInfo(){ //Default Constructor } @Override public String toString() { return "LeftTicketInfo{" + "soldTickets=" + soldTickets + '}'; } }
498
16.206897
46
java
train-ticket
train-ticket-master/ts-common/src/main/java/edu/fudan/common/entity/NotifyInfo.java
package edu.fudan.common.entity; import lombok.Data; /** * @author fdse */ @Data public class NotifyInfo { public NotifyInfo(){ //Default Constructor } private String email; private String orderNumber; private String username; private String startPlace; private String endPlace; private String startTime; private String date; private String seatClass; private String seatNumber; private String price; }
466
16.296296
32
java
train-ticket
train-ticket-master/ts-common/src/main/java/edu/fudan/common/entity/Order.java
package edu.fudan.common.entity; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import edu.fudan.common.entity.SeatClass; import edu.fudan.common.util.StringUtils; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.util.Date; import java.util.UUID; /** * @author fdse */ @Data @JsonIgnoreProperties(ignoreUnknown = true) @AllArgsConstructor public class Order { private String id; private String boughtDate; private String travelDate; private String travelTime; /** * Which Account Bought it */ private String accountId; /** * Tickets bought for whom.... */ private String contactsName; private int documentType; private String contactsDocumentNumber; private String trainNumber; private int coachNumber; private int seatClass; private String seatNumber; private String from; private String to; private int status; private String price; private String differenceMoney; public Order(){ boughtDate = StringUtils.Date2String(new Date(System.currentTimeMillis())); travelDate = StringUtils.Date2String(new Date(123456789)); trainNumber = "G1235"; coachNumber = 5; seatClass = SeatClass.FIRSTCLASS.getCode(); seatNumber = "5A"; from = "shanghai"; to = "taiyuan"; status = OrderStatus.PAID.getCode(); price = "0.0"; differenceMoney ="0.0"; } public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Order other = (Order) obj; return getBoughtDate().equals(other.getBoughtDate()) && getBoughtDate().equals(other.getTravelDate()) && getTravelTime().equals(other.getTravelTime()) && accountId .equals( other.getAccountId() ) && contactsName.equals(other.getContactsName()) && contactsDocumentNumber.equals(other.getContactsDocumentNumber()) && documentType == other.getDocumentType() && trainNumber.equals(other.getTrainNumber()) && coachNumber == other.getCoachNumber() && seatClass == other.getSeatClass() && seatNumber .equals(other.getSeatNumber()) && from.equals(other.getFrom()) && to.equals(other.getTo()) && status == other.getStatus() && price.equals(other.price); } @Override public int hashCode() { int result = 17; result = 31 * result + (id == null ? 0 : id.hashCode()); return result; } }
2,843
24.621622
83
java
train-ticket
train-ticket-master/ts-common/src/main/java/edu/fudan/common/entity/OrderAlterInfo.java
package edu.fudan.common.entity; import lombok.AllArgsConstructor; import lombok.Data; /** * @author fdse */ @Data @AllArgsConstructor public class OrderAlterInfo { private String accountId; private String previousOrderId; private String loginToken; private Order newOrderInfo; public OrderAlterInfo(){ newOrderInfo = new Order(); } }
376
14.08
35
java
train-ticket
train-ticket-master/ts-common/src/main/java/edu/fudan/common/entity/OrderSecurity.java
package edu.fudan.common.entity; import lombok.AllArgsConstructor; import lombok.Data; /** * @author fdse */ @Data @AllArgsConstructor public class OrderSecurity { private int orderNumInLastOneHour; private int orderNumOfValidOrder; public OrderSecurity() { //Default Constructor } }
316
13.409091
38
java
train-ticket
train-ticket-master/ts-common/src/main/java/edu/fudan/common/entity/OrderStatus.java
package edu.fudan.common.entity; /** * @author fdse */ public enum OrderStatus { /** * not paid */ NOTPAID (0,"Not Paid"), /** * paid and not collected */ PAID (1,"Paid & Not Collected"), /** * collected */ COLLECTED (2,"Collected"), /** * cancel and rebook */ CHANGE (3,"Cancel & Rebook"), /** * cancel */ CANCEL (4,"Cancel"), /** * refunded */ REFUNDS (5,"Refunded"), /** * used */ USED (6,"Used"); private int code; private String name; OrderStatus(int code, String name){ this.code = code; this.name = name; } public int getCode(){ return code; } public String getName() { return name; } public static String getNameByCode(int code){ OrderStatus[] orderStatusSet = OrderStatus.values(); for(OrderStatus orderStatus : orderStatusSet){ if(orderStatus.getCode() == code){ return orderStatus.getName(); } } return orderStatusSet[0].getName(); } }
1,147
16.9375
60
java
train-ticket
train-ticket-master/ts-common/src/main/java/edu/fudan/common/entity/OrderTicketsInfo.java
package edu.fudan.common.entity; import edu.fudan.common.util.StringUtils; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.util.Date; /** * @author fdse */ @Data @Builder @NoArgsConstructor @AllArgsConstructor public class OrderTicketsInfo { private String accountId; private String contactsId; private String tripId; private int seatType; private String loginToken; private String date; private String from; private String to; private int assurance; private int foodType = 0; private String stationName; private String storeName; private String foodName; private double foodPrice; private String handleDate; private String consigneeName; private String consigneePhone; private double consigneeWeight; private boolean isWithin; public String getFrom() { return StringUtils.String2Lower(this.from); } public String getTo() { return StringUtils.String2Lower(this.to); } }
1,077
15.584615
51
java
train-ticket
train-ticket-master/ts-common/src/main/java/edu/fudan/common/entity/PaymentDifferenceInfo.java
package edu.fudan.common.entity; import lombok.Data; /** * @author fdse */ @Data public class PaymentDifferenceInfo { private String orderId; private String tripId; private String userId; private String price; public PaymentDifferenceInfo(){ //Default Constructor } }
310
11.958333
36
java
train-ticket
train-ticket-master/ts-common/src/main/java/edu/fudan/common/entity/PriceConfig.java
package edu.fudan.common.entity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.util.UUID; /** * @author fdse */ @Data @AllArgsConstructor public class PriceConfig { private UUID id; private String trainType; private String routeId; private double basicPriceRate; private double firstClassPriceRate; public PriceConfig() { //Empty Constructor } }
447
13.451613
39
java
train-ticket
train-ticket-master/ts-common/src/main/java/edu/fudan/common/entity/Route.java
package edu.fudan.common.entity; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.Data; import lombok.NoArgsConstructor; import java.util.List; import java.util.UUID; /** * @author fdse */ @Data @JsonIgnoreProperties(ignoreUnknown = true) public class Route { private String id; private List<String> stations; private List<Integer> distances; private String startStation; private String endStation; public Route(){ this.id = UUID.randomUUID().toString(); } public Route(String id, List<String> stations, List<Integer> distances, String startStationName, String terminalStationName) { this.id = id; this.stations = stations; this.distances = distances; this.startStation = startStationName; this.endStation = terminalStationName; } public Route(List<String> stations, List<Integer> distances, String startStationName, String terminalStationName) { this.id = UUID.randomUUID().toString(); this.stations = stations; this.distances = distances; this.startStation = startStationName; this.endStation = terminalStationName; } }
1,192
25.511111
130
java
train-ticket
train-ticket-master/ts-common/src/main/java/edu/fudan/common/entity/RouteInfo.java
package edu.fudan.common.entity; import edu.fudan.common.util.Response; import lombok.Data; import lombok.NoArgsConstructor; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * @author fdse */ @Data @NoArgsConstructor public class RouteInfo { private String loginId; private String startStation; private String endStation; private String stationList; private String distanceList; private String id; public List<String> getStations(){ String[] stations = stationList.split(","); return Arrays.asList(stations); } public List<String> getDistances(){ String[] distances = distanceList.split(","); return Arrays.asList(distances); } }
746
17.675
53
java
train-ticket
train-ticket-master/ts-common/src/main/java/edu/fudan/common/entity/RoutePlanInfo.java
package edu.fudan.common.entity; import edu.fudan.common.util.StringUtils; import lombok.AllArgsConstructor; import lombok.Data; import java.util.Date; /** * @author fdse */ @Data @AllArgsConstructor public class RoutePlanInfo { private String startStation; private String endStation; private String travelDate; private int num; public RoutePlanInfo() { //Empty Constructor } public String getStartStation() { return StringUtils.String2Lower(this.startStation); } public String getEndStation() { return StringUtils.String2Lower(this.endStation); } }
626
16.416667
59
java
train-ticket
train-ticket-master/ts-common/src/main/java/edu/fudan/common/entity/RoutePlanResultUnit.java
package edu.fudan.common.entity; import edu.fudan.common.util.StringUtils; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.util.List; import java.util.Date; /** * @author fdse */ @Data @NoArgsConstructor @AllArgsConstructor public class RoutePlanResultUnit { private String tripId; private String trainTypeName; private String startStation; private String endStation; private List<String> stopStations; private String priceForSecondClassSeat; private String priceForFirstClassSeat; private String startTime; private String endTime; }
637
15.358974
43
java
train-ticket
train-ticket-master/ts-common/src/main/java/edu/fudan/common/entity/Seat.java
package edu.fudan.common.entity; import edu.fudan.common.util.StringUtils; import lombok.AllArgsConstructor; import lombok.Data; import javax.validation.Valid; import javax.validation.constraints.NotNull; import java.util.Date; import java.util.List; /** * @author fdse */ @Data @AllArgsConstructor public class Seat { @Valid @NotNull private String travelDate; @Valid @NotNull private String trainNumber; @Valid @NotNull private String startStation; @Valid @NotNull private String destStation; @Valid @NotNull private int seatType; private int totalNum; private List<String> stations; public Seat(){ //Default Constructor this.travelDate = ""; this.trainNumber = ""; this.startStation = ""; this.destStation = ""; this.seatType = 0; this.totalNum = 0; this.stations = null; } }
934
15.696429
44
java
train-ticket
train-ticket-master/ts-common/src/main/java/edu/fudan/common/entity/SeatClass.java
package edu.fudan.common.entity; /** * @author fdse */ public enum SeatClass { /** * no seat */ NONE (0,"NoSeat"), /** * green seat */ BUSINESS (1,"GreenSeat"), /** * first class seat */ FIRSTCLASS (2,"FirstClassSeat"), /** * second class seat */ SECONDCLASS (3,"SecondClassSeat"), /** * hard seat */ HARDSEAT (4,"HardSeat"), /** * soft seat */ SOFTSEAT (5,"SoftSeat"), /** * hard bed */ HARDBED (6,"HardBed"), /** * soft bed */ SOFTBED (7,"SoftBed"), /** * high soft seat */ HIGHSOFTBED (8,"HighSoftSeat"); private int code; private String name; SeatClass(int code, String name){ this.code = code; this.name = name; } public int getCode(){ return code; } public String getName() { return name; } public static String getNameByCode(int code){ SeatClass[] seatClassSet = SeatClass.values(); for(SeatClass seatClass : seatClassSet){ if(seatClass.getCode() == code){ return seatClass.getName(); } } return seatClassSet[0].getName(); } }
1,274
16.957746
54
java
train-ticket
train-ticket-master/ts-common/src/main/java/edu/fudan/common/entity/SoldTicket.java
package edu.fudan.common.entity; import lombok.Data; import java.util.Date; /** * @author fdse */ @Data public class SoldTicket { private Date travelDate; private String trainNumber; private int noSeat; private int businessSeat; private int firstClassSeat; private int secondClassSeat; private int hardSeat; private int softSeat; private int hardBed; private int softBed; private int highSoftBed; public SoldTicket(){ noSeat = 0; businessSeat = 0; firstClassSeat = 0; secondClassSeat = 0; hardSeat = 0; softSeat = 0; hardBed = 0; softBed = 0; highSoftBed = 0; } }
706
13.729167
32
java
train-ticket
train-ticket-master/ts-common/src/main/java/edu/fudan/common/entity/Station.java
package edu.fudan.common.entity; import lombok.Data; import java.util.Locale; @Data public class Station { private String id; private String name; private int stayTime; public Station(){ this.name = ""; } public void setName(String name) { this.name = name.replace(" ", "").toLowerCase(Locale.ROOT); } public Station(String name) { this.name = name.replace(" ", "").toLowerCase(Locale.ROOT); } public Station(String name, int stayTime) { this.name = name.replace(" ", "").toLowerCase(Locale.ROOT);; this.stayTime = stayTime; } }
624
17.382353
68
java
train-ticket
train-ticket-master/ts-common/src/main/java/edu/fudan/common/entity/StationFoodStore.java
package edu.fudan.common.entity; import lombok.Data; import java.io.Serializable; import java.util.List; import java.util.UUID; @Data public class StationFoodStore implements Serializable{ private UUID id; private String stationName; private String storeName; private String telephone; private String businessTime; private double deliveryFee; private List<Food> foodList; public StationFoodStore(){ //Default Constructor } }
481
14.548387
54
java
train-ticket
train-ticket-master/ts-common/src/main/java/edu/fudan/common/entity/Ticket.java
package edu.fudan.common.entity; import lombok.Data; /** * @author fdse */ @Data public class Ticket { private int seatNo; private String startStation; private String destStation; public Ticket(){ //Default Constructor } public Ticket(int seatNo, String startStation, String destStation) { this.seatNo = seatNo; this.startStation = startStation; this.destStation = destStation; } }
451
15.740741
72
java
train-ticket
train-ticket-master/ts-common/src/main/java/edu/fudan/common/entity/TrainFood.java
package edu.fudan.common.entity; import lombok.Data; import java.io.Serializable; import java.util.List; import java.util.UUID; @Data public class TrainFood implements Serializable{ public TrainFood(){ //Default Constructor } private UUID id; private String tripId; private List<Food> foodList; }
333
13.521739
47
java
train-ticket
train-ticket-master/ts-common/src/main/java/edu/fudan/common/entity/TrainType.java
package edu.fudan.common.entity; import lombok.Data; import javax.validation.Valid; import javax.validation.constraints.NotNull; /** * @author fdse */ @Data public class TrainType { private String id; private String name; private int economyClass; private int confortClass; private int averageSpeed; public TrainType(){ //Default Constructor } public TrainType(String name, int economyClass, int confortClass) { this.name = name; this.economyClass = economyClass; this.confortClass = confortClass; } public TrainType(String name, int economyClass, int confortClass, int averageSpeed) { this.name = name; this.economyClass = economyClass; this.confortClass = confortClass; this.averageSpeed = averageSpeed; } }
828
20.815789
89
java
train-ticket
train-ticket-master/ts-common/src/main/java/edu/fudan/common/entity/Travel.java
package edu.fudan.common.entity; import edu.fudan.common.util.StringUtils; import lombok.Data; import java.util.Date; /** * @author fdse */ @Data public class Travel { private Trip trip; private String startPlace; private String endPlace; private String departureTime; public Travel(){ //Default Constructor } }
355
12.185185
41
java
train-ticket
train-ticket-master/ts-common/src/main/java/edu/fudan/common/entity/TravelInfo.java
package edu.fudan.common.entity; import edu.fudan.common.util.StringUtils; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.util.Date; /** * @author fdse */ @Data @NoArgsConstructor @AllArgsConstructor public class TravelInfo { private String loginId; private String tripId; private String trainTypeName; private String routeId; private String startStationName; private String stationsName; private String terminalStationName; private String startTime; private String endTime; // public Date getStartTime(){ // return StringUtils.String2Date(this.startTime); // } // // public Date getEndTime(){ // return StringUtils.String2Date(this.endTime); // } // // public String getStartStationName() { // return StringUtils.String2Lower(this.startStationName); // } // // public String getTerminalStationName() { // return StringUtils.String2Lower(this.terminalStationName); // } }
1,027
18.769231
68
java
train-ticket
train-ticket-master/ts-common/src/main/java/edu/fudan/common/entity/TravelResult.java
package edu.fudan.common.entity; import java.util.Map; import lombok.*; /** * @author fdse */ @Data public class TravelResult { private boolean status; private double percent; private TrainType trainType; private Route route; private Map<String,String> prices; public TravelResult(){ //Default Constructor } public boolean isStatus() { return status; } }
419
12.548387
38
java
train-ticket
train-ticket-master/ts-common/src/main/java/edu/fudan/common/entity/Trip.java
package edu.fudan.common.entity; import edu.fudan.common.util.StringUtils; import lombok.Data; import javax.validation.Valid; import javax.validation.constraints.NotNull; import java.util.Date; import java.util.UUID; /** * @author fdse */ @Data public class Trip { private String id; private TripId tripId; private String trainTypeName; private String routeId; private String startStationName; private String stationsName; private String terminalStationName; private String startTime; private String endTime; public Trip(edu.fudan.common.entity.TripId tripId, String trainTypeName, String startStationName, String stationsName, String terminalStationName, String startTime, String endTime) { this.tripId = tripId; this.trainTypeName = trainTypeName; this.startStationName = StringUtils.String2Lower(startStationName); this.stationsName = StringUtils.String2Lower(stationsName); this.terminalStationName = StringUtils.String2Lower(terminalStationName); this.startTime = startTime; this.endTime = endTime; } public Trip(TripId tripId, String trainTypeName, String routeId) { this.tripId = tripId; this.trainTypeName = trainTypeName; this.routeId = routeId; this.startStationName = ""; this.terminalStationName = ""; this.startTime = ""; this.endTime = ""; } public Trip(){ //Default Constructor this.trainTypeName = ""; this.startStationName = ""; this.terminalStationName = ""; this.startTime = ""; this.endTime = ""; } // public Date getStartTime(){ // return StringUtils.String2Date(this.startTime); // } // // public Date getEndTime(){ // return StringUtils.String2Date(this.endTime); // } // // public void setStartTime(Date startTime){ // this.startTime = StringUtils.Date2String(startTime); // } // // public void setEndTime(Date endTime){ // this.endTime = StringUtils.Date2String(endTime); // } }
2,093
25.506329
186
java
train-ticket
train-ticket-master/ts-common/src/main/java/edu/fudan/common/entity/TripAllDetail.java
package edu.fudan.common.entity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; /** * @author fdse */ @Data @NoArgsConstructor @AllArgsConstructor public class TripAllDetail { private boolean status; private String message; private TripResponse tripResponse; private Trip trip; }
345
13.416667
38
java
train-ticket
train-ticket-master/ts-common/src/main/java/edu/fudan/common/entity/TripAllDetailInfo.java
package edu.fudan.common.entity; import edu.fudan.common.util.StringUtils; import lombok.Data; import lombok.ToString; import java.util.Date; /** * @author fdse */ @Data @ToString public class TripAllDetailInfo { private String tripId; private String travelDate; private String from; private String to; public TripAllDetailInfo() { //Default Constructor } public String getFrom() { return StringUtils.String2Lower(this.from); } public String getTo() { return StringUtils.String2Lower(this.to); } // public Date getTravelDate() { // return StringUtils.String2Date(travelDate); // } // // public void setTravelDate(Date travelDate) { // this.travelDate = StringUtils.Date2String(travelDate); // } }
800
17.204545
64
java
train-ticket
train-ticket-master/ts-common/src/main/java/edu/fudan/common/entity/TripId.java
package edu.fudan.common.entity; import lombok.Data; import java.io.Serializable; /** * @author fdse */ @Data public class TripId implements Serializable{ private Type type; private String number; public TripId(){ //Default Constructor } public TripId(String trainNumber){ char type0 = trainNumber.charAt(0); switch(type0){ case 'Z': this.type = Type.Z; break; case 'T': this.type = Type.T; break; case 'K': this.type = Type.K; break; case 'G': this.type = Type.G; break; case 'D': this.type = Type.D; break; default:break; } this.number = trainNumber.substring(1); } @Override public String toString(){ return type.getName() + number; } }
918
18.978261
47
java
train-ticket
train-ticket-master/ts-common/src/main/java/edu/fudan/common/entity/TripInfo.java
package edu.fudan.common.entity; import edu.fudan.common.util.StringUtils; import lombok.AllArgsConstructor; import lombok.Data; import javax.validation.Valid; import javax.validation.constraints.NotNull; import java.util.Date; /** * @author fdse */ @Data @AllArgsConstructor public class TripInfo { @Valid @NotNull private String startPlace; @Valid @NotNull private String endPlace; @Valid @NotNull private String departureTime; public TripInfo(){ //Default Constructor this.startPlace = ""; this.endPlace = ""; this.departureTime = ""; } public String getStartPlace() { return StringUtils.String2Lower(this.startPlace); } public String getEndPlace() { return StringUtils.String2Lower(this.endPlace); } // public Date getDepartureTime(){ // return StringUtils.String2Date(this.departureTime); // } }
933
18.458333
61
java
train-ticket
train-ticket-master/ts-common/src/main/java/edu/fudan/common/entity/TripResponse.java
package edu.fudan.common.entity; import edu.fudan.common.util.StringUtils; import lombok.Data; import javax.validation.Valid; import javax.validation.constraints.NotNull; import java.util.Date; /** * @author fdse */ @Data public class TripResponse { @Valid private TripId tripId; @Valid @NotNull private String trainTypeName; @Valid @NotNull private String startStation; @Valid @NotNull private String terminalStation; @Valid @NotNull private String startTime; @Valid @NotNull private String endTime; /** * the number of economy seats */ @Valid @NotNull private int economyClass; /** * the number of confort seats */ @Valid @NotNull private int confortClass; @Valid @NotNull private String priceForEconomyClass; @Valid @NotNull private String priceForConfortClass; public TripResponse(){ //Default Constructor this.trainTypeName = ""; this.startStation = ""; this.terminalStation = ""; this.startTime = ""; this.endTime = ""; this.economyClass = 0; this.confortClass = 0; this.priceForEconomyClass = ""; this.priceForConfortClass = ""; } // public Date getStartTime(){ // return StringUtils.String2Date(startTime); // } // public Date getEndTime(){ // return StringUtils.String2Date(endTime); // } // // public void setStartTime(Date startTime){ // this.startTime = StringUtils.Date2String(startTime); // } // public void setEndTime(Date endTime){ // this.endTime = StringUtils.Date2String(endTime); // } }
1,708
18.420455
62
java
train-ticket
train-ticket-master/ts-common/src/main/java/edu/fudan/common/entity/Type.java
package edu.fudan.common.entity; import java.io.Serializable; /** * @author fdse */ public enum Type implements Serializable{ /** * G */ G("G", 1), /** * D */ D("D", 2), /** * Z */ Z("Z",3), /** * T */ T("T", 4), /** * K */ K("K", 5); private String name; private int index; Type(String name, int index) { this.name = name; this.index = index; } public static String getName(int index) { for (Type type : Type.values()) { if (type.getIndex() == index) { return type.name; } } return null; } public String getName() { return name; } void setName(String name) { this.name = name; } public int getIndex() { return index; } void setIndex(int index) { this.index = index; } }
940
13.936508
45
java
train-ticket
train-ticket-master/ts-common/src/main/java/edu/fudan/common/entity/User.java
package edu.fudan.common.entity; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.util.UUID; /** * @author fdse */ @Data @Builder @AllArgsConstructor @NoArgsConstructor public class User { private UUID userId; private String userName; private String password; private int gender; private int documentType; private String documentNum; private String email; }
470
13.71875
33
java
train-ticket
train-ticket-master/ts-common/src/main/java/edu/fudan/common/entity/VerifyResult.java
package rebook.entity; import lombok.Data; /** * @author fdse */ @Data public class VerifyResult { private boolean status; private String message; public VerifyResult() { //Default Constructor } }
229
10.5
29
java
train-ticket
train-ticket-master/ts-common/src/main/java/edu/fudan/common/exception/BaseException.java
package edu.fudan.common.exception; /** * @author fdse */ public class BaseException extends RuntimeException { public BaseException(String message) { super(message); } public BaseException(String message, Throwable cause) { super(message, cause); } }
288
18.266667
59
java
train-ticket
train-ticket-master/ts-common/src/main/java/edu/fudan/common/exception/TokenException.java
package edu.fudan.common.exception; /** * @author fdse */ public class TokenException extends BaseException{ public TokenException(String message) { super(message); } }
189
14.833333
50
java
train-ticket
train-ticket-master/ts-common/src/main/java/edu/fudan/common/security/jwt/JWTFilter.java
package edu.fudan.common.security.jwt; import io.jsonwebtoken.JwtException; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.filter.OncePerRequestFilter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * @author fdse */ public class JWTFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException { try { Authentication authentication = JWTUtil. getJWTAuthentication(httpServletRequest); SecurityContextHolder.getContext().setAuthentication(authentication); filterChain.doFilter(httpServletRequest, httpServletResponse); } catch (JwtException e) { httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); } } }
1,183
34.878788
179
java
train-ticket
train-ticket-master/ts-common/src/main/java/edu/fudan/common/security/jwt/JWTUtil.java
package edu.fudan.common.security.jwt; import edu.fudan.common.exception.TokenException; import io.jsonwebtoken.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import javax.servlet.ServletRequest; import javax.servlet.http.HttpServletRequest; import java.util.Base64; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.stream.Collectors; /** * @author fdse */ public class JWTUtil { private JWTUtil() { throw new IllegalStateException("Utility class"); } private static final Logger LOGGER = LoggerFactory.getLogger(JWTUtil.class); private static String secretKey = Base64.getEncoder().encodeToString("secret".getBytes()); public static Authentication getJWTAuthentication(ServletRequest request) { String token = getTokenFromHeader((HttpServletRequest) request); if (token != null && validateToken(token)) { UserDetails userDetails = new UserDetails() { @Override public Collection<? extends GrantedAuthority> getAuthorities() { return getRole(token).stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList()); } @Override public String getPassword() { return ""; } @Override public String getUsername() { return getUserName(token); } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return true; } }; // send to spring security return new UsernamePasswordAuthenticationToken(userDetails, "", userDetails.getAuthorities()); } return null; } private static String getUserName(String token) { return getClaims(token).getBody().getSubject(); } private static List<String> getRole(String token) { Jws<Claims> claimsJws = getClaims(token); return (List<String>) (claimsJws.getBody().get("roles", List.class)); } private static String getTokenFromHeader(HttpServletRequest request) { String bearerToken = request.getHeader("Authorization"); if (bearerToken != null && bearerToken.startsWith("Bearer ")) { return bearerToken.substring(7, bearerToken.length()); } return null; } private static boolean validateToken(String token) { try { Jws<Claims> claimsJws = getClaims(token); return !claimsJws.getBody().getExpiration().before(new Date()); } catch (ExpiredJwtException e) { LOGGER.error("[validateToken][getClaims][Token expired][ExpiredJwtException: {} ]" , e); throw new TokenException("Token expired"); } catch (UnsupportedJwtException e) { LOGGER.error("[validateToken][getClaims][Token format error][UnsupportedJwtException: {}]", e); throw new TokenException("Token format error"); } catch (MalformedJwtException e) { LOGGER.error("[validateToken][getClaims][Token is not properly constructed][MalformedJwtException: {}]", e); throw new TokenException("Token is not properly constructed"); } catch (SignatureException e) { LOGGER.error("[validateToken][getClaims][Signature failure][SignatureException: {}]", e); throw new TokenException("Signature failure"); } catch (IllegalArgumentException e) { LOGGER.error("[validateToken][getClaims][Illegal parameter exception][IllegalArgumentException: {}]", e); throw new TokenException("Illegal parameter exception"); } } private static Jws<Claims> getClaims(String token) { return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token); } }
4,616
36.233871
120
java
train-ticket
train-ticket-master/ts-common/src/main/java/edu/fudan/common/util/JsonUtils.java
package edu.fudan.common.util; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author fdse */ public class JsonUtils { private static final Logger LOGGER = LoggerFactory.getLogger(JsonUtils.class); private JsonUtils() { throw new IllegalStateException("Utility class"); } /** * <p> * Object to JSON string * </p> */ public static String object2Json(Object obj) { String result = null; try { ObjectMapper objectMapper = new ObjectMapper(); result = objectMapper.writeValueAsString(obj); } catch (IOException e) { JsonUtils.LOGGER.error("[object2Json][writeValueAsString][IOException: {}]", e.getMessage()); } return result; } public static Map object2Map(Object obj) { String object2Json = object2Json(obj); Map<?, ?> result = jsonToMap(object2Json); return result; } /** * <p> * JSON string to Map object * </p> */ public static Map<?, ?> jsonToMap(String json) { return json2Object(json, Map.class); } /** * <p> * JSON to Object * </p> */ public static <T> T json2Object(String json, Class<T> cls) { T result = null; try { ObjectMapper objectMapper = new ObjectMapper(); result = objectMapper.readValue(json, cls); } catch (NullPointerException e) { JsonUtils.LOGGER.error("[json2Object][objectMapper.readValue][NullPointerException: {}]",e.getMessage()); } catch (IOException e) { JsonUtils.LOGGER.error("[json2Object][objectMapper.readValue][IOException: {}]",e.getMessage()); } return result; } public static <T> T conveterObject(Object srcObject, Class<T> destObjectType) { String jsonContent = object2Json(srcObject); return json2Object(jsonContent, destObjectType); } }
2,062
25.448718
117
java
train-ticket
train-ticket-master/ts-common/src/main/java/edu/fudan/common/util/Response.java
package edu.fudan.common.util; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.ToString; /** * @author fdse */ @Data @AllArgsConstructor @NoArgsConstructor @ToString public class Response<T> { /** * 1 true, 0 false */ Integer status; String msg; T data; }
341
12.68
33
java
train-ticket
train-ticket-master/ts-common/src/main/java/edu/fudan/common/util/StringUtils.java
package edu.fudan.common.util; import java.text.SimpleDateFormat; import java.util.Locale; import java.util.Date; public class StringUtils { public static String String2Lower(String str){ if(str == null || str.isEmpty()) { return str; } return str.replace(" ", "").toLowerCase(Locale.ROOT); } public static Date String2Date(String str){ SimpleDateFormat formatter; if(str.length() > 10){ formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); }else{ formatter = new SimpleDateFormat("yyyy-MM-dd"); } try{ Date d = formatter.parse(str); return d; }catch(Exception e){ return new Date(0); } } public static String Date2String(Date date){ SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); return formatter.format(date); } }
943
25.222222
80
java
train-ticket
train-ticket-master/ts-config-service/src/main/java/config/ConfigApplication.java
package config; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.integration.annotation.IntegrationComponentScan; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.web.client.RestTemplate; import springfox.documentation.swagger2.annotations.EnableSwagger2; /** * @author fdse */ @SpringBootApplication @EnableAspectJAutoProxy(proxyTargetClass = true) @EnableAsync @IntegrationComponentScan @EnableSwagger2 @EnableDiscoveryClient public class ConfigApplication { public static void main(String[] args) { SpringApplication.run(ConfigApplication.class, args); } @LoadBalanced @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); } }
1,180
31.805556
75
java
train-ticket
train-ticket-master/ts-config-service/src/main/java/config/SecurityConfig.java
package config; import edu.fudan.common.security.jwt.JWTFilter; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; 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.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import static org.springframework.web.cors.CorsConfiguration.ALL; /** * @author fdse */ @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) public class SecurityConfig extends WebSecurityConfigurerAdapter { String admin = "ADMIN"; /** * load password encoder * * @return PasswordEncoder */ @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } /** * allow cors domain * header By default, only six fields can be taken from the header, and the other fields can only be specified in the header. * credentials Cookies are not sent by default and can only be true if a Cookie is needed * Validity of this request * * @return WebMvcConfigurer */ @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurerAdapter() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins(ALL) .allowedMethods(ALL) .allowedHeaders(ALL) .allowCredentials(false) .maxAge(3600); } }; } @Override protected void configure(HttpSecurity httpSecurity) throws Exception { httpSecurity.httpBasic().disable() // close default csrf .csrf().disable() // close session .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .authorizeRequests() .antMatchers("/api/v1/configservice/**").permitAll() .antMatchers(HttpMethod.POST, "/api/v1/configservice/configs").hasAnyRole(admin) .antMatchers(HttpMethod.PUT, "/api/v1/configservice/configs").hasAnyRole(admin) .antMatchers(HttpMethod.DELETE, "/api/v1/configservice/configs/*").hasAnyRole(admin) .antMatchers("/swagger-ui.html", "/webjars/**", "/images/**", "/configuration/**", "/swagger-resources/**", "/v2/**").permitAll() .anyRequest().authenticated() .and() .addFilterBefore(new JWTFilter(), UsernamePasswordAuthenticationFilter.class); // close cache httpSecurity.headers().cacheControl(); } }
3,592
39.829545
130
java
train-ticket
train-ticket-master/ts-config-service/src/main/java/config/controller/ConfigController.java
package config.controller; import config.entity.Config; import config.service.ConfigService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import static org.springframework.http.ResponseEntity.ok; /** * @author Chenjie Xu * @date 2017/5/11. */ @RestController @RequestMapping("api/v1/configservice") public class ConfigController { @Autowired private ConfigService configService; private static final Logger logger = LoggerFactory.getLogger(ConfigController.class); @GetMapping(path = "/welcome") public String home(@RequestHeader HttpHeaders headers) { return "Welcome to [ Config Service ] !"; } @CrossOrigin(origins = "*") @GetMapping(value = "/configs") public HttpEntity queryAll(@RequestHeader HttpHeaders headers) { logger.info("[queryAll][Query all configs]"); return ok(configService.queryAll(headers)); } @CrossOrigin(origins = "*") @PostMapping(value = "/configs") public HttpEntity<?> createConfig(@RequestBody Config info, @RequestHeader HttpHeaders headers) { logger.info("[createConfig][Create config][Config name: {}]", info.getName()); return new ResponseEntity<>(configService.create(info, headers), HttpStatus.CREATED); } @CrossOrigin(origins = "*") @PutMapping(value = "/configs") public HttpEntity updateConfig(@RequestBody Config info, @RequestHeader HttpHeaders headers) { logger.info("[updateConfig][Update config][Config name: {}]", info.getName()); return ok(configService.update(info, headers)); } @CrossOrigin(origins = "*") @DeleteMapping(value = "/configs/{configName}") public HttpEntity deleteConfig(@PathVariable String configName, @RequestHeader HttpHeaders headers) { logger.info("[deleteConfig][Delete config][configName: {}]", configName); return ok(configService.delete(configName, headers)); } @CrossOrigin(origins = "*") @GetMapping(value = "/configs/{configName}") public HttpEntity retrieve(@PathVariable String configName, @RequestHeader HttpHeaders headers) { logger.info("[retrieve][Retrieve config][configName: {}]", configName); return ok(configService.query(configName, headers)); } }
2,550
33.472973
105
java
train-ticket
train-ticket-master/ts-config-service/src/main/java/config/entity/Config.java
package config.entity; import lombok.Data; import javax.persistence.Id; import javax.persistence.Entity; import javax.validation.Valid; import javax.validation.constraints.NotNull; /** * @author fdse */ @Data @Entity public class Config { @Valid @Id @NotNull private String name; @Valid @NotNull private String value; @Valid private String description; public Config() { this.name = ""; this.value = ""; } public Config(String name, String value, String description) { this.name = name; this.value = value; this.description = description; } }
645
15.15
66
java
train-ticket
train-ticket-master/ts-config-service/src/main/java/config/init/InitData.java
package config.init; import config.entity.Config; import config.service.ConfigService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; /** * @author fdse */ @Component public class InitData implements CommandLineRunner{ @Autowired ConfigService service; @Override public void run(String... args) throws Exception { Config config = new Config(); config.setName("DirectTicketAllocationProportion"); config.setValue("0.5"); config.setDescription("Allocation Proportion Of The Direct Ticket - From Start To End"); service.create(config,null); } }
726
24.068966
96
java
train-ticket
train-ticket-master/ts-config-service/src/main/java/config/repository/ConfigRepository.java
package config.repository; import config.entity.Config; import org.springframework.data.repository.CrudRepository; import java.util.List; /** * @author fdse */ public interface ConfigRepository extends CrudRepository<Config, String> { /** * find by name * * @param name name * @return Config */ Config findByName(String name); /** * find all * * @return List<Config> */ @Override List<Config> findAll(); /** * delete by name * * @param name name * @return null */ void deleteByName(String name); }
604
15.351351
74
java
train-ticket
train-ticket-master/ts-config-service/src/main/java/config/service/ConfigService.java
package config.service; import config.entity.Config; import edu.fudan.common.util.Response; import org.springframework.http.HttpHeaders; /** * @author fdse */ public interface ConfigService { /** * create by config information and headers * * @param info info * @param headers headers * @return Response */ Response create(Config info, HttpHeaders headers); /** * update by config information and headers * * @param info info * @param headers headers * @return Response */ Response update(Config info, HttpHeaders headers); /** * Config retrieve * * @param name name * @param headers headers * @return Response */ Response query(String name, HttpHeaders headers); /** * delete by name and headers * * @param name name * @param headers headers * @return Response */ Response delete(String name, HttpHeaders headers); /** * query all by headers * * @param headers headers * @return Response */ Response queryAll(HttpHeaders headers); }
1,129
18.824561
54
java
train-ticket
train-ticket-master/ts-config-service/src/main/java/config/service/ConfigServiceImpl.java
package config.service; import config.entity.Config; import config.repository.ConfigRepository; import edu.fudan.common.util.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; /** * @author fdse */ @Service public class ConfigServiceImpl implements ConfigService { @Autowired ConfigRepository repository; private static final Logger logger = LoggerFactory.getLogger(ConfigServiceImpl.class); String config0 = "Config "; @Override public Response create(Config info, HttpHeaders headers) { if (repository.findByName(info.getName()) != null) { String result = config0 + info.getName() + " already exists."; logger.warn("[create][{} already exists][config info: {}]", config0, info.getName()); return new Response<>(0, result, null); } else { Config config = new Config(info.getName(), info.getValue(), info.getDescription()); repository.save(config); logger.info("[create][create success][Config: {}]", info); return new Response<>(1, "Create success", config); } } @Override public Response update(Config info, HttpHeaders headers) { if (repository.findByName(info.getName()) == null) { String result = config0 + info.getName() + " doesn't exist."; logger.warn(result); return new Response<>(0, result, null); } else { Config config = new Config(info.getName(), info.getValue(), info.getDescription()); repository.save(config); logger.info("[update][update success][Config: {}]", config); return new Response<>(1, "Update success", config); } } @Override public Response query(String name, HttpHeaders headers) { Config config = repository.findByName(name); if (config == null) { logger.warn("[query][Config does not exist][name: {}, message: {}]", name, "No content"); return new Response<>(0, "No content", null); } else { logger.info("[query][Query config success][config name: {}]", name); return new Response<>(1, "Success", config); } } @Override @Transactional public Response delete(String name, HttpHeaders headers) { Config config = repository.findByName(name); if (config == null) { String result = config0 + name + " doesn't exist."; logger.warn("[delete][config doesn't exist][config name: {}]", name); return new Response<>(0, result, null); } else { repository.deleteByName(name); logger.info("[delete][Config delete success][config name: {}]", name); return new Response<>(1, "Delete success", config); } } @Override public Response queryAll(HttpHeaders headers) { List<Config> configList = repository.findAll(); if (configList != null && !configList.isEmpty()) { logger.info("[queryAll][Query all config success]"); return new Response<>(1, "Find all config success", configList); } else { logger.warn("[queryAll][Query config, No content]"); return new Response<>(0, "No content", null); } } }
3,547
35.204082
101
java
train-ticket
train-ticket-master/ts-config-service/src/test/java/config/controller/ConfigControllerTest.java
package config.controller; import com.alibaba.fastjson.JSONObject; import config.entity.Config; import config.service.ConfigService; import edu.fudan.common.util.Response; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.springframework.http.*; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; @RunWith(JUnit4.class) public class ConfigControllerTest { @InjectMocks private ConfigController configController; @Mock private ConfigService configService; private MockMvc mockMvc; private Response response = new Response(); @Before public void setUp() { MockitoAnnotations.initMocks(this); mockMvc = MockMvcBuilders.standaloneSetup(configController).build(); } @Test public void testHome() throws Exception { mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/configservice/welcome")) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.content().string("Welcome to [ Config Service ] !")); } @Test public void testQueryAll() throws Exception { Mockito.when(configService.queryAll(Mockito.any(HttpHeaders.class))).thenReturn(response); String result = mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/configservice/configs")) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } @Test public void testCreateConfig() throws Exception { Config info = new Config(); Mockito.when(configService.create(Mockito.any(Config.class), Mockito.any(HttpHeaders.class))).thenReturn(response); String requestJson = JSONObject.toJSONString(info); String result = mockMvc.perform(MockMvcRequestBuilders.post("/api/v1/configservice/configs").contentType(MediaType.APPLICATION_JSON).content(requestJson)) .andExpect(MockMvcResultMatchers.status().isCreated()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } @Test public void testUpdateConfig() throws Exception { Config info = new Config(); Mockito.when(configService.update(Mockito.any(Config.class), Mockito.any(HttpHeaders.class))).thenReturn(response); String requestJson = JSONObject.toJSONString(info); String result = mockMvc.perform(MockMvcRequestBuilders.put("/api/v1/configservice/configs").contentType(MediaType.APPLICATION_JSON).content(requestJson)) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } @Test public void testDeleteConfig() throws Exception { Mockito.when(configService.delete(Mockito.anyString(), Mockito.any(HttpHeaders.class))).thenReturn(response); String result = mockMvc.perform(MockMvcRequestBuilders.delete("/api/v1/configservice/configs/config_name")) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } @Test public void testRetrieve() throws Exception { Mockito.when(configService.query(Mockito.anyString(), Mockito.any(HttpHeaders.class))).thenReturn(response); String result = mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/configservice/configs/config_name")) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } }
4,352
44.34375
162
java
train-ticket
train-ticket-master/ts-config-service/src/test/java/config/service/ConfigServiceImplTest.java
package config.service; import config.entity.Config; import config.repository.ConfigRepository; import edu.fudan.common.util.Response; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.springframework.http.HttpHeaders; import java.util.ArrayList; import java.util.List; @RunWith(JUnit4.class) public class ConfigServiceImplTest { @InjectMocks private ConfigServiceImpl configServiceImpl; @Mock private ConfigRepository repository; private HttpHeaders headers = new HttpHeaders(); @Before public void setUp() { MockitoAnnotations.initMocks(this); } @Test public void testCreate1() { Config info = new Config(); Mockito.when(repository.findByName(info.getName())).thenReturn(info); Response result = configServiceImpl.create(info, headers); Assert.assertEquals(new Response<>(0, "Config already exists.", null), result); } @Test public void testCreate2() { Config info = new Config("", "", ""); Mockito.when(repository.findByName(info.getName())).thenReturn(null); Mockito.when(repository.save(Mockito.any(Config.class))).thenReturn(null); Response result = configServiceImpl.create(info, headers); Assert.assertEquals(new Response<>(1, "Create success", new Config("", "", "")), result); } @Test public void testUpdate1() { Config info = new Config(); Mockito.when(repository.findByName(info.getName())).thenReturn(null); Response result = configServiceImpl.update(info, headers); Assert.assertEquals(new Response<>(0, "Config doesn't exist.", null), result); } @Test public void testUpdate2() { Config info = new Config("", "", ""); Mockito.when(repository.findByName(info.getName())).thenReturn(info); Mockito.when(repository.save(Mockito.any(Config.class))).thenReturn(null); Response result = configServiceImpl.update(info, headers); Assert.assertEquals(new Response<>(1, "Update success", new Config("", "", "")), result); } @Test public void testQuery1() { Mockito.when(repository.findByName("name")).thenReturn(null); Response result = configServiceImpl.query("name", headers); Assert.assertEquals(new Response<>(0, "No content", null), result); } @Test public void testQuery2() { Config info = new Config(); Mockito.when(repository.findByName("name")).thenReturn(info); Response result = configServiceImpl.query("name", headers); Assert.assertEquals(new Response<>(1, "Success", new Config()), result); } @Test public void testDelete1() { Mockito.when(repository.findByName("name")).thenReturn(null); Response result = configServiceImpl.delete("name", headers); Assert.assertEquals(new Response<>(0, "Config name doesn't exist.", null), result); } @Test public void testDelete2() { Config info = new Config(); Mockito.when(repository.findByName("name")).thenReturn(info); Mockito.doNothing().doThrow(new RuntimeException()).when(repository).deleteByName("name"); Response result = configServiceImpl.delete("name", headers); Assert.assertEquals(new Response<>(1, "Delete success", info), result); } @Test public void testQueryAll1() { List<Config> configList = new ArrayList<>(); configList.add(new Config()); Mockito.when(repository.findAll()).thenReturn(configList); Response result = configServiceImpl.queryAll(headers); Assert.assertEquals(new Response<>(1, "Find all config success", configList), result); } @Test public void testQueryAll2() { Mockito.when(repository.findAll()).thenReturn(null); Response result = configServiceImpl.queryAll(headers); Assert.assertEquals(new Response<>(0, "No content", null), result); } }
4,168
34.330508
98
java
train-ticket
train-ticket-master/ts-consign-price-service/src/main/java/consignprice/ConsignPriceApplication.java
package consignprice; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.integration.annotation.IntegrationComponentScan; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.web.client.RestTemplate; import springfox.documentation.swagger2.annotations.EnableSwagger2; import java.util.Date; /** * @author fdse */ @SpringBootApplication @EnableAspectJAutoProxy(proxyTargetClass = true) @EnableAsync @IntegrationComponentScan @EnableSwagger2 @EnableDiscoveryClient public class ConsignPriceApplication { private static final Logger LOGGER = LoggerFactory.getLogger(ConsignPriceApplication.class); public static void main(String[] args) { ConsignPriceApplication.LOGGER.info("[ConsignPriceApplication.main][launch date: {}]", new Date()); SpringApplication.run(ConsignPriceApplication.class, args); } @LoadBalanced @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); } }
1,485
33.55814
107
java
train-ticket
train-ticket-master/ts-consign-price-service/src/main/java/consignprice/config/SecurityConfig.java
package consignprice.config; import edu.fudan.common.security.jwt.JWTFilter; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; 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.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import static org.springframework.web.cors.CorsConfiguration.ALL; /** * @author fdse */ @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) public class SecurityConfig extends WebSecurityConfigurerAdapter { /** * load password encoder * * @return PasswordEncoder */ @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } /** * allow cors domain * header By default, only six fields can be taken from the header, and the other fields can only be specified in the header. * credentials Cookies are not sent by default and can only be true if a Cookie is needed * Validity of this request * * @return WebMvcConfigurer */ @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurerAdapter() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins(ALL) .allowedMethods(ALL) .allowedHeaders(ALL) .allowCredentials(false) .maxAge(3600); } }; } @Override protected void configure(HttpSecurity httpSecurity) throws Exception { httpSecurity.httpBasic().disable() // close default csrf .csrf().disable() // close session .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .authorizeRequests() .antMatchers("/api/v1/consignpriceservice/**").hasAnyRole("ADMIN", "USER") .antMatchers("/swagger-ui.html", "/webjars/**", "/images/**", "/configuration/**", "/swagger-resources/**", "/v2/**").permitAll() .anyRequest().authenticated() .and() .addFilterBefore(new JWTFilter(), UsernamePasswordAuthenticationFilter.class); // close cache httpSecurity.headers().cacheControl(); } }
3,260
38.768293
130
java
train-ticket
train-ticket-master/ts-consign-price-service/src/main/java/consignprice/controller/ConsignPriceController.java
package consignprice.controller; import consignprice.entity.ConsignPrice; import consignprice.service.ConsignPriceService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.web.bind.annotation.*; import static org.springframework.http.ResponseEntity.ok; /** * @author fdse */ @RestController @RequestMapping("/api/v1/consignpriceservice") public class ConsignPriceController { @Autowired ConsignPriceService service; private static final Logger logger = LoggerFactory.getLogger(ConsignPriceController.class); @GetMapping(path = "/welcome") public String home(@RequestHeader HttpHeaders headers) { return "Welcome to [ ConsignPrice Service ] !"; } @GetMapping(value = "/consignprice/{weight}/{isWithinRegion}") public HttpEntity getPriceByWeightAndRegion(@PathVariable String weight, @PathVariable String isWithinRegion, @RequestHeader HttpHeaders headers) { logger.info("[getPriceByWeightAndRegion][Get price by weight and region][weight: {}, region: {}]", weight, isWithinRegion); return ok(service.getPriceByWeightAndRegion(Double.parseDouble(weight), Boolean.parseBoolean(isWithinRegion), headers)); } @GetMapping(value = "/consignprice/price") public HttpEntity getPriceInfo(@RequestHeader HttpHeaders headers) { logger.info("[getPriceInfo][Get price info]"); return ok(service.queryPriceInformation(headers)); } @GetMapping(value = "/consignprice/config") public HttpEntity getPriceConfig(@RequestHeader HttpHeaders headers) { logger.info("[getPriceConfig][Get price config]"); return ok(service.getPriceConfig(headers)); } @PostMapping(value = "/consignprice") public HttpEntity modifyPriceConfig(@RequestBody ConsignPrice priceConfig, @RequestHeader HttpHeaders headers) { logger.info("[modifyPriceConfig][Create and modify price][config: {}]", priceConfig); return ok(service.createAndModifyPrice(priceConfig, headers)); } }
2,279
38.310345
131
java
train-ticket
train-ticket-master/ts-consign-price-service/src/main/java/consignprice/entity/ConsignPrice.java
package consignprice.entity; import lombok.AllArgsConstructor; import lombok.Data; import org.hibernate.annotations.GenericGenerator; import javax.persistence.*; import java.util.UUID; /** * @author fdse */ @Data @AllArgsConstructor @Entity @GenericGenerator(name = "jpa-uuid", strategy = "org.hibernate.id.UUIDGenerator") @Table(name="consign_price") public class ConsignPrice { @Id @GeneratedValue(generator = "jpa-uuid") @Column(length = 36) private String id; @Column(name = "idx",unique = true) private int index; @Column(name = "initial_weight") private double initialWeight; @Column(name = "initial_price") private double initialPrice; @Column(name = "within_price") private double withinPrice; @Column(name = "beyond_price") private double beyondPrice; public ConsignPrice(){ //Default Constructor } }
890
21.275
81
java
train-ticket
train-ticket-master/ts-consign-price-service/src/main/java/consignprice/init/InitData.java
package consignprice.init; import consignprice.entity.ConsignPrice; import consignprice.service.ConsignPriceService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; import java.util.UUID; /** * @author fdse */ @Component public class InitData implements CommandLineRunner { @Autowired ConsignPriceService service; private static final Logger LOGGER = LoggerFactory.getLogger(InitData.class); @Override public void run(String... strings) throws Exception { InitData.LOGGER.info("[InitData.run][Consign price service][Init data operation]"); ConsignPrice config = new ConsignPrice(); config.setId(UUID.randomUUID().toString()); config.setIndex(0); config.setInitialPrice(8); config.setInitialWeight(1); config.setWithinPrice(2); config.setBeyondPrice(4); service.createAndModifyPrice(config, null); } }
1,077
28.135135
91
java
train-ticket
train-ticket-master/ts-consign-price-service/src/main/java/consignprice/repository/ConsignPriceConfigRepository.java
package consignprice.repository; import consignprice.entity.ConsignPrice; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; /** * @author fdse */ @Repository public interface ConsignPriceConfigRepository extends CrudRepository<ConsignPrice, String> { /** * find by index * * @param index index * @return ConsignPrice */ // @Query("{ 'index': ?0 }") ConsignPrice findByIndex(int index); }
489
20.304348
92
java
train-ticket
train-ticket-master/ts-consign-price-service/src/main/java/consignprice/service/ConsignPriceService.java
package consignprice.service; import consignprice.entity.ConsignPrice; import edu.fudan.common.util.Response; import org.springframework.http.HttpHeaders; /** * @author fdse */ public interface ConsignPriceService { /** * get price by weight and region * * @param weight weight * @param isWithinRegion whether is within region * @param headers headers * @return Response */ Response getPriceByWeightAndRegion(double weight, boolean isWithinRegion, HttpHeaders headers); /** * query price information * * @param headers headers * @return Response */ Response queryPriceInformation(HttpHeaders headers); /** * create and modify price * * @param config config * @param headers headers * @return Response */ Response createAndModifyPrice(ConsignPrice config, HttpHeaders headers); /** * get price config * * @param headers headers * @return Response */ Response getPriceConfig(HttpHeaders headers); }
1,052
21.404255
99
java
train-ticket
train-ticket-master/ts-consign-price-service/src/main/java/consignprice/service/ConsignPriceServiceImpl.java
package consignprice.service; import consignprice.entity.ConsignPrice; import consignprice.repository.ConsignPriceConfigRepository; import edu.fudan.common.util.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.stereotype.Service; /** * @author fdse */ @Service public class ConsignPriceServiceImpl implements ConsignPriceService { @Autowired private ConsignPriceConfigRepository repository; String success = "Success"; private static final Logger LOGGER = LoggerFactory.getLogger(ConsignPriceServiceImpl.class); @Override public Response getPriceByWeightAndRegion(double weight, boolean isWithinRegion, HttpHeaders headers) { ConsignPrice priceConfig = repository.findByIndex(0); double price = 0; double initialPrice = priceConfig.getInitialPrice(); if (weight <= priceConfig.getInitialWeight()) { price = initialPrice; } else { double extraWeight = weight - priceConfig.getInitialWeight(); if (isWithinRegion) { price = initialPrice + extraWeight * priceConfig.getWithinPrice(); }else { price = initialPrice + extraWeight * priceConfig.getBeyondPrice(); } } return new Response<>(1, success, price); } @Override public Response queryPriceInformation(HttpHeaders headers) { StringBuilder sb = new StringBuilder(); ConsignPrice price = repository.findByIndex(0); sb.append("The price of weight within "); sb.append(price.getInitialWeight()); sb.append(" is "); sb.append(price.getInitialPrice()); sb.append(". The price of extra weight within the region is "); sb.append(price.getWithinPrice()); sb.append(" and beyond the region is "); sb.append(price.getBeyondPrice()); sb.append("\n"); return new Response<>(1, success, sb.toString()); } @Override public Response createAndModifyPrice(ConsignPrice config, HttpHeaders headers) { ConsignPriceServiceImpl.LOGGER.info("[createAndModifyPrice][Create New Price Config]"); //update price ConsignPrice originalConfig; if (repository.findByIndex(0) != null) { originalConfig = repository.findByIndex(0); } else { originalConfig = new ConsignPrice(); } originalConfig.setId(config.getId()); originalConfig.setIndex(0); originalConfig.setInitialPrice(config.getInitialPrice()); originalConfig.setInitialWeight(config.getInitialWeight()); originalConfig.setWithinPrice(config.getWithinPrice()); originalConfig.setBeyondPrice(config.getBeyondPrice()); repository.save(originalConfig); return new Response<>(1, success, originalConfig); } @Override public Response getPriceConfig(HttpHeaders headers) { return new Response<>(1, success, repository.findByIndex(0)); } }
3,125
36.214286
107
java
train-ticket
train-ticket-master/ts-consign-price-service/src/test/java/consignprice/controller/ConsignPriceControllerTest.java
package consignprice.controller; import com.alibaba.fastjson.JSONObject; import consignprice.entity.ConsignPrice; import consignprice.service.ConsignPriceService; import edu.fudan.common.util.Response; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.springframework.http.*; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; @RunWith(JUnit4.class) public class ConsignPriceControllerTest { @InjectMocks private ConsignPriceController consignPriceController; @Mock private ConsignPriceService service; private MockMvc mockMvc; private Response response = new Response(); @Before public void setUp() { MockitoAnnotations.initMocks(this); mockMvc = MockMvcBuilders.standaloneSetup(consignPriceController).build(); } @Test public void testHome() throws Exception { mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/consignpriceservice/welcome")) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.content().string("Welcome to [ ConsignPrice Service ] !")); } @Test public void testGetPriceByWeightAndRegion() throws Exception { Mockito.when(service.getPriceByWeightAndRegion(Mockito.anyDouble(), Mockito.anyBoolean(), Mockito.any(HttpHeaders.class))).thenReturn(response); String result = mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/consignpriceservice/consignprice/1.0/true")) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } @Test public void testGetPriceInfo() throws Exception { Mockito.when(service.queryPriceInformation(Mockito.any(HttpHeaders.class))).thenReturn(response); String result = mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/consignpriceservice/consignprice/price")) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } @Test public void testGetPriceConfig() throws Exception { Mockito.when(service.getPriceConfig(Mockito.any(HttpHeaders.class))).thenReturn(response); String result = mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/consignpriceservice/consignprice/config")) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } @Test public void testModifyPriceConfig() throws Exception { ConsignPrice priceConfig = new ConsignPrice(); Mockito.when(service.createAndModifyPrice(Mockito.any(ConsignPrice.class), Mockito.any(HttpHeaders.class))).thenReturn(response); String requestJson = JSONObject.toJSONString(priceConfig); String result = mockMvc.perform(MockMvcRequestBuilders.post("/api/v1/consignpriceservice/consignprice").contentType(MediaType.APPLICATION_JSON).content(requestJson)) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } }
3,873
44.576471
173
java
train-ticket
train-ticket-master/ts-consign-price-service/src/test/java/consignprice/service/ConsignPriceServiceImplTest.java
package consignprice.service; import consignprice.entity.ConsignPrice; import consignprice.repository.ConsignPriceConfigRepository; import edu.fudan.common.util.Response; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.springframework.http.HttpHeaders; import java.util.UUID; @RunWith(JUnit4.class) public class ConsignPriceServiceImplTest { @InjectMocks private ConsignPriceServiceImpl consignPriceServiceImpl; @Mock private ConsignPriceConfigRepository repository; private HttpHeaders headers = new HttpHeaders(); @Before public void setUp() { MockitoAnnotations.initMocks(this); } @Test public void testGetPriceByWeightAndRegion1() { ConsignPrice priceConfig = new ConsignPrice(UUID.randomUUID().toString(), 1, 2.0, 3.0, 3.5, 4.0); Mockito.when(repository.findByIndex(0)).thenReturn(priceConfig); Response result = consignPriceServiceImpl.getPriceByWeightAndRegion(1.0, true, headers); Assert.assertEquals(new Response<>(1, "Success", 3.0), result); } @Test public void testGetPriceByWeightAndRegion2() { ConsignPrice priceConfig = new ConsignPrice(UUID.randomUUID().toString(), 1, 2.0, 3.0, 3.5, 4.0); Mockito.when(repository.findByIndex(0)).thenReturn(priceConfig); Response result = consignPriceServiceImpl.getPriceByWeightAndRegion(3.0, true, headers); Assert.assertEquals(new Response<>(1, "Success", 6.5), result); } @Test public void testGetPriceByWeightAndRegion3() { ConsignPrice priceConfig = new ConsignPrice(UUID.randomUUID().toString(), 1, 2.0, 3.0, 3.5, 4.0); Mockito.when(repository.findByIndex(0)).thenReturn(priceConfig); Response result = consignPriceServiceImpl.getPriceByWeightAndRegion(3.0, false, headers); Assert.assertEquals(new Response<>(1, "Success", 7.0), result); } @Test public void testQueryPriceInformation() { ConsignPrice priceConfig = new ConsignPrice(UUID.randomUUID().toString(), 1, 2.0, 3.0, 3.5, 4.0); Mockito.when(repository.findByIndex(0)).thenReturn(priceConfig); Response result = consignPriceServiceImpl.queryPriceInformation(headers); String str = "The price of weight within 2.0 is 3.0. The price of extra weight within the region is 3.5 and beyond the region is 4.0\n"; Assert.assertEquals(new Response<>(1, "Success", str), result); } @Test public void testCreateAndModifyPrice1() { ConsignPrice config = new ConsignPrice(UUID.randomUUID().toString(), 1, 2.0, 3.0, 3.5, 4.0); Mockito.when(repository.findByIndex(0)).thenReturn(config); Mockito.when(repository.save(Mockito.any(ConsignPrice.class))).thenReturn(null); Response result = consignPriceServiceImpl.createAndModifyPrice(config, headers); Assert.assertEquals(new Response<>(1, "Success", config), result); } @Test public void testCreateAndModifyPrice2() { ConsignPrice config = new ConsignPrice(UUID.randomUUID().toString(), 0, 2.0, 3.0, 3.5, 4.0); Mockito.when(repository.findByIndex(0)).thenReturn(null); Mockito.when(repository.save(Mockito.any(ConsignPrice.class))).thenReturn(null); Response result = consignPriceServiceImpl.createAndModifyPrice(config, headers); Assert.assertEquals(new Response<>(1, "Success", config), result); } @Test public void testGetPriceConfig() { ConsignPrice config = new ConsignPrice(); Mockito.when(repository.findByIndex(0)).thenReturn(config); Response result = consignPriceServiceImpl.getPriceConfig(headers); Assert.assertEquals(new Response<>(1, "Success", config), result); } }
3,942
40.505263
144
java