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-consign-service/src/main/java/consign/ConsignApplication.java
package consign; 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 ConsignApplication { public static void main(String[] args) { SpringApplication.run(ConsignApplication.class, args); } @LoadBalanced @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); } }
1,182
32.8
75
java
train-ticket
train-ticket-master/ts-consign-service/src/main/java/consign/config/SecurityConfig.java
package consign.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/consignservice/**").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,250
38.646341
130
java
train-ticket
train-ticket-master/ts-consign-service/src/main/java/consign/controller/ConsignController.java
package consign.controller; import consign.entity.Consign; import consign.service.ConsignService; 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.UUID; import static org.springframework.http.ResponseEntity.ok; /** * @author fdse */ @RestController @RequestMapping("/api/v1/consignservice") public class ConsignController { @Autowired ConsignService service; private static final Logger logger = LoggerFactory.getLogger(ConsignController.class); @GetMapping(path = "/welcome") public String home(@RequestHeader HttpHeaders headers) { return "Welcome to [ Consign Service ] !"; } @PostMapping(value = "/consigns") public HttpEntity insertConsign(@RequestBody Consign request, @RequestHeader HttpHeaders headers) { logger.info("[insertConsign][Insert consign record][id:{}]", request.getId()); return ok(service.insertConsignRecord(request, headers)); } @PutMapping(value = "/consigns") public HttpEntity updateConsign(@RequestBody Consign request, @RequestHeader HttpHeaders headers) { logger.info("[updateConsign][Update consign record][id: {}]", request.getId()); return ok(service.updateConsignRecord(request, headers)); } @GetMapping(value = "/consigns/account/{id}") public HttpEntity findByAccountId(@PathVariable String id, @RequestHeader HttpHeaders headers) { logger.info("[findByAccountId][Find consign by account id][id: {}]", id); UUID newid = UUID.fromString(id); return ok(service.queryByAccountId(newid, headers)); } @GetMapping(value = "/consigns/order/{id}") public HttpEntity findByOrderId(@PathVariable String id, @RequestHeader HttpHeaders headers) { logger.info("[findByOrderId][Find consign by order id][id: {}]", id); UUID newid = UUID.fromString(id); return ok(service.queryByOrderId(newid, headers)); } @GetMapping(value = "/consigns/{consignee}") public HttpEntity findByConsignee(@PathVariable String consignee, @RequestHeader HttpHeaders headers) { logger.info("[findByConsignee][Find consign by consignee][consignee: {}]", consignee); return ok(service.queryByConsignee(consignee, headers)); } }
2,490
36.179104
107
java
train-ticket
train-ticket-master/ts-consign-service/src/main/java/consign/entity/Consign.java
package consign.entity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.hibernate.annotations.GenericGenerator; import javax.persistence.*; /** * @author fdse */ @Data @AllArgsConstructor @NoArgsConstructor @GenericGenerator(name="jpa-uuid",strategy ="uuid") public class Consign { @Id @GeneratedValue(generator = "jpa-uuid") @Column(length = 36) 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; }
783
20.189189
55
java
train-ticket
train-ticket-master/ts-consign-service/src/main/java/consign/entity/ConsignRecord.java
package consign.entity; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.*; /** * @author fdse */ @Data @AllArgsConstructor @NoArgsConstructor @Entity @JsonIgnoreProperties(ignoreUnknown = true) @Table(schema = "ts-consign-mysql") public class ConsignRecord { @Id @Column(name = "consign_record_id") private String id; private String orderId; @Column(name = "user_id") private String accountId; private String handleDate; private String targetDate; @Column(name = "from_place") private String from; @Column(name = "to_place") private String to; private String consignee; @Column(name = "consign_record_phone") private String phone; private double weight; @Column(name = "consign_record_price") private double price; }
922
21.512195
61
java
train-ticket
train-ticket-master/ts-consign-service/src/main/java/consign/entity/GetPriceDomain.java
package consign.entity; import lombok.Data; /** * @author fdse */ @Data public class GetPriceDomain { private double weight; private boolean isWithinRegion; public GetPriceDomain(){ //Default Constructor } }
238
12.277778
35
java
train-ticket
train-ticket-master/ts-consign-service/src/main/java/consign/entity/InsertConsignRecordResult.java
package consign.entity; import lombok.Data; /** * @author fdse */ @Data public class InsertConsignRecordResult { private boolean status; private String message; public InsertConsignRecordResult(){ //Default Constructor } }
254
12.421053
40
java
train-ticket
train-ticket-master/ts-consign-service/src/main/java/consign/init/InitData.java
package consign.init; import consign.entity.Consign; import consign.entity.ConsignRecord; import consign.repository.ConsignRepository; import consign.service.ConsignService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; import java.util.ArrayList; @Component public class InitData implements CommandLineRunner { @Autowired ConsignService service; @Autowired ConsignRepository repository; @Override public void run(String... args) throws Exception { //do nothing /* ConsignRecord c_1 = new ConsignRecord(); String id_1 = "ff8080817b3e4c27017b3e4c3bee0000"; String orderID_1 = "ff8080817b3e4c27017b3e4order0000"; String accountID_1 = "ff8080817b3e4c27017b3e4c3acc0000"; String consignee_1 = "xxx1"; c_1.setId(id_1); c_1.setAccountId(accountID_1); c_1.setOrderId(orderID_1); c_1.setConsignee(consignee_1); c_1.setFrom("from"); c_1.setTo("to"); c_1.setHandleDate("handle_date"); c_1.setTargetDate("target_date"); c_1.setPhone("12345"); c_1.setWeight(10); repository.save(c_1); ConsignRecord c_2 = new ConsignRecord(); String id_2 = "ff8080817b3e4c27017b3e4c3bee1111"; String orderID_2 = "ff8080817b3e4c27017b3e4order1111"; String accountID_2 = "ff8080817b3e4c27017b3e4c3acc0000"; //同一个account String consignee_2 = "xxx2"; c_2.setId(id_2); c_2.setAccountId(accountID_2); c_2.setOrderId(orderID_2); c_2.setConsignee(consignee_2); c_2.setFrom("from2"); c_2.setTo("to2"); c_2.setHandleDate("handle_date2"); c_2.setTargetDate("target_date2"); c_2.setPhone("12345"); c_2.setWeight(12); repository.save(c_2); ConsignRecord res1 = repository.findById(id_1).get(); System.out.println("id查找成功 : " + res1.getId()); ConsignRecord res2 = repository.findByOrderId(orderID_1); System.out.println("orderID查找成功 : "+ res2.getId()); ArrayList<ConsignRecord> res3 = repository.findByAccountId(accountID_1); System.out.println("accountID查找成功 : " + res3.size()); ArrayList<ConsignRecord> res4 = repository.findByConsignee(consignee_1); System.out.println("consignee查找成功 : " + res4.size()); */ } }
2,458
31.355263
80
java
train-ticket
train-ticket-master/ts-consign-service/src/main/java/consign/repository/ConsignRepository.java
package consign.repository; import consign.entity.ConsignRecord; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import java.util.ArrayList; import java.util.Optional; /** * @author fdse */ @Repository public interface ConsignRepository extends CrudRepository<ConsignRecord, String> { /** * find by account id * * @param accountId account id * @return ArrayList<ConsignRecord> */ ArrayList<ConsignRecord> findByAccountId(String accountId); /** * find by order id * * @param accountId account id * @return ConsignRecord */ ConsignRecord findByOrderId(String accountId); /** * find by consignee * * @param consignee consignee * @return ArrayList<ConsignRecord> */ ArrayList<ConsignRecord> findByConsignee(String consignee); /** * find by id * * @param id id * @return ConsignRecord */ Optional<ConsignRecord> findById(String id); }
1,032
20.520833
82
java
train-ticket
train-ticket-master/ts-consign-service/src/main/java/consign/service/ConsignService.java
package consign.service; import consign.entity.Consign; import org.springframework.http.HttpHeaders; import edu.fudan.common.util.Response; import java.util.UUID; /** * @author fdse */ public interface ConsignService { /** * insert consign record * * @param consignRequest consign request * @param headers headers * @return Response */ Response insertConsignRecord(Consign consignRequest, HttpHeaders headers); /** * update consign record * * @param consignRequest consign request * @param headers headers * @return Response */ Response updateConsignRecord(Consign consignRequest, HttpHeaders headers); /** * query by account id * * @param accountId account id * @param headers headers * @return Response */ Response queryByAccountId(UUID accountId, HttpHeaders headers); /** * query by order id * * @param orderId order id * @param headers headers * @return Response */ Response queryByOrderId(UUID orderId, HttpHeaders headers); /** * query by consignee * * @param consignee consignee * @param headers headers * @return Response */ Response queryByConsignee(String consignee, HttpHeaders headers); }
1,303
20.733333
78
java
train-ticket
train-ticket-master/ts-consign-service/src/main/java/consign/service/ConsignServiceImpl.java
package consign.service; import consign.entity.ConsignRecord; import consign.entity.Consign; import consign.repository.ConsignRepository; 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.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.util.List; import java.util.Optional; import java.util.UUID; /** * @author fdse */ @Service public class ConsignServiceImpl implements ConsignService { @Autowired ConsignRepository repository; @Autowired RestTemplate restTemplate; @Autowired private DiscoveryClient discoveryClient; private static final Logger LOGGER = LoggerFactory.getLogger(ConsignServiceImpl.class); private String getServiceUrl(String serviceName) { return "http://" + serviceName; } @Override public Response insertConsignRecord(Consign consignRequest, HttpHeaders headers) { ConsignServiceImpl.LOGGER.info("[insertConsignRecord][Insert Start][consignRequest.getOrderId: {}]", consignRequest.getOrderId()); ConsignRecord consignRecord = new ConsignRecord(); //Set the record attribute consignRecord.setId(UUID.randomUUID().toString()); consignRecord.setOrderId(consignRequest.getOrderId().toString()); consignRecord.setAccountId(consignRequest.getAccountId().toString()); ConsignServiceImpl.LOGGER.info("[insertConsignRecord][Insert Info][handle date: {}, target date: {}]", consignRequest.getHandleDate(), consignRequest.getTargetDate()); consignRecord.setHandleDate(consignRequest.getHandleDate()); consignRecord.setTargetDate(consignRequest.getTargetDate()); consignRecord.setFrom(consignRequest.getFrom()); consignRecord.setTo(consignRequest.getTo()); consignRecord.setConsignee(consignRequest.getConsignee()); consignRecord.setPhone(consignRequest.getPhone()); consignRecord.setWeight(consignRequest.getWeight()); //get the price HttpEntity requestEntity = new HttpEntity(null, headers); String consign_price_service_url = getServiceUrl("ts-consign-price-service"); ResponseEntity<Response<Double>> re = restTemplate.exchange( consign_price_service_url + "/api/v1/consignpriceservice/consignprice/" + consignRequest.getWeight() + "/" + consignRequest.isWithin(), HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<Double>>() { }); consignRecord.setPrice(re.getBody().getData()); LOGGER.info("[insertConsignRecord][SAVE consign info][consignRecord : {}]", consignRecord.toString()); ConsignRecord result = repository.save(consignRecord); LOGGER.info("[insertConsignRecord][SAVE consign result][result: {}]", result.toString()); return new Response<>(1, "You have consigned successfully! The price is " + result.getPrice(), result); } @Override public Response updateConsignRecord(Consign consignRequest, HttpHeaders headers) { ConsignServiceImpl.LOGGER.info("[updateConsignRecord][Update Start]"); if (!repository.findById(consignRequest.getId()).isPresent()) { return insertConsignRecord(consignRequest, headers); } ConsignRecord originalRecord = repository.findById(consignRequest.getId()).get(); originalRecord.setAccountId(consignRequest.getAccountId().toString()); originalRecord.setHandleDate(consignRequest.getHandleDate()); originalRecord.setTargetDate(consignRequest.getTargetDate()); originalRecord.setFrom(consignRequest.getFrom()); originalRecord.setTo(consignRequest.getTo()); originalRecord.setConsignee(consignRequest.getConsignee()); originalRecord.setPhone(consignRequest.getPhone()); //Recalculate price if (originalRecord.getWeight() != consignRequest.getWeight()) { HttpEntity requestEntity = new HttpEntity<>(null, headers); String consign_price_service_url = getServiceUrl("ts-consign-price-service"); ResponseEntity<Response<Double>> re = restTemplate.exchange( consign_price_service_url + "/api/v1/consignpriceservice/consignprice/" + consignRequest.getWeight() + "/" + consignRequest.isWithin(), HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<Double>>() { }); originalRecord.setPrice(re.getBody().getData()); } else { originalRecord.setPrice(originalRecord.getPrice()); } originalRecord.setConsignee(consignRequest.getConsignee()); originalRecord.setPhone(consignRequest.getPhone()); originalRecord.setWeight(consignRequest.getWeight()); repository.save(originalRecord); return new Response<>(1, "Update consign success", originalRecord); } @Override public Response queryByAccountId(UUID accountId, HttpHeaders headers) { List<ConsignRecord> consignRecords = repository.findByAccountId(accountId.toString()); if (consignRecords != null && !consignRecords.isEmpty()) { return new Response<>(1, "Find consign by account id success", consignRecords); }else { LOGGER.warn("[queryByAccountId][No Content according to accountId][accountId: {}]", accountId); return new Response<>(0, "No Content according to accountId", null); } } @Override public Response queryByOrderId(UUID orderId, HttpHeaders headers) { ConsignRecord consignRecords = repository.findByOrderId(orderId.toString()); if (consignRecords != null ) { return new Response<>(1, "Find consign by order id success", consignRecords); }else { LOGGER.warn("[queryByOrderId][No Content according to orderId][orderId: {}]", orderId); return new Response<>(0, "No Content according to order id", null); } } @Override public Response queryByConsignee(String consignee, HttpHeaders headers) { List<ConsignRecord> consignRecords = repository.findByConsignee(consignee); if (consignRecords != null && !consignRecords.isEmpty()) { return new Response<>(1, "Find consign by consignee success", consignRecords); }else { LOGGER.warn("[queryByConsignee][No Content according to consignee][consignee: {}]", consignee); return new Response<>(0, "No Content according to consignee", null); } } }
7,137
46.271523
175
java
train-ticket
train-ticket-master/ts-consign-service/src/test/java/consign/controller/ConsignControllerTest.java
package consign.controller; import com.alibaba.fastjson.JSONObject; import consign.entity.Consign; import consign.service.ConsignService; 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.UUID; @RunWith(JUnit4.class) public class ConsignControllerTest { @InjectMocks private ConsignController consignController; @Mock private ConsignService service; private MockMvc mockMvc; private Response response = new Response(); @Before public void setUp() { MockitoAnnotations.initMocks(this); mockMvc = MockMvcBuilders.standaloneSetup(consignController).build(); } @Test public void testHome() throws Exception { mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/consignservice/welcome")) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.content().string("Welcome to [ Consign Service ] !")); } @Test public void testInsertConsign() throws Exception { Consign request = new Consign(); Mockito.when(service.insertConsignRecord(Mockito.any(Consign.class), Mockito.any(HttpHeaders.class))).thenReturn(response); String requestJson = JSONObject.toJSONString(request); String result = mockMvc.perform(MockMvcRequestBuilders.post("/api/v1/consignservice/consigns").contentType(MediaType.APPLICATION_JSON).content(requestJson)) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } @Test public void testUpdateConsign() throws Exception { Consign request = new Consign(); Mockito.when(service.updateConsignRecord(Mockito.any(Consign.class), Mockito.any(HttpHeaders.class))).thenReturn(response); String requestJson = JSONObject.toJSONString(request); String result = mockMvc.perform(MockMvcRequestBuilders.put("/api/v1/consignservice/consigns").contentType(MediaType.APPLICATION_JSON).content(requestJson)) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } @Test public void testFindByAccountId() throws Exception { UUID id = UUID.randomUUID(); Mockito.when(service.queryByAccountId(Mockito.any(UUID.class), Mockito.any(HttpHeaders.class))).thenReturn(response); String result = mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/consignservice/consigns/account/" + id.toString())) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } @Test public void testFindByOrderId() throws Exception { UUID id = UUID.randomUUID(); Mockito.when(service.queryByOrderId(Mockito.any(UUID.class), Mockito.any(HttpHeaders.class))).thenReturn(response); String result = mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/consignservice/consigns/order/" + id.toString())) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } @Test public void testFindByConsignee() throws Exception { Mockito.when(service.queryByConsignee(Mockito.anyString(), Mockito.any(HttpHeaders.class))).thenReturn(response); String result = mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/consignservice/consigns/consignee")) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } }
4,579
44.8
164
java
train-ticket
train-ticket-master/ts-consign-service/src/test/java/consign/service/ConsignServiceImplTest.java
package consign.service; import consign.entity.Consign; import consign.entity.ConsignRecord; import consign.repository.ConsignRepository; 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; import java.util.ArrayList; import java.util.List; import java.util.UUID; @RunWith(JUnit4.class) public class ConsignServiceImplTest { @InjectMocks private ConsignServiceImpl consignServiceImpl; @Mock private ConsignRepository repository; @Mock private RestTemplate restTemplate; private HttpHeaders headers = new HttpHeaders(); @Before public void setUp() { MockitoAnnotations.initMocks(this); } @Test public void testInsertConsignRecord() { HttpEntity requestEntity = new HttpEntity(null, headers); Response<Double> response = new Response<>(1, null, 3.0); ResponseEntity<Response<Double>> re = new ResponseEntity<>(response, HttpStatus.OK); Consign consignRequest = new Consign(UUID.randomUUID().toString(), UUID.randomUUID().toString(), UUID.randomUUID().toString(), "handle_date", "target_date", "place_from", "place_to", "consignee", "10001", 1.0, true); ConsignRecord consignRecord = new ConsignRecord(UUID.randomUUID().toString(), UUID.randomUUID().toString(), UUID.randomUUID().toString(), "handle_date", "target_date", "place_from", "place_to", "consignee", "10001", 1.0, 3.0); Mockito.when(restTemplate.exchange( "http://ts-consign-price-service:16110/api/v1/consignpriceservice/consignprice/" + consignRequest.getWeight() + "/" + consignRequest.isWithin(), HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<Double>>() { })).thenReturn(re); Mockito.when(repository.save(Mockito.any(ConsignRecord.class))).thenReturn(consignRecord); Response result = consignServiceImpl.insertConsignRecord(consignRequest, headers); Assert.assertEquals(new Response<>(1, "You have consigned successfully! The price is 3.0", consignRecord), result); } @Test public void testUpdateConsignRecord1() { HttpEntity requestEntity = new HttpEntity(null, headers); Response<Double> response = new Response<>(1, null, 3.0); ResponseEntity<Response<Double>> re = new ResponseEntity<>(response, HttpStatus.OK); Consign consignRequest = new Consign(UUID.randomUUID().toString(), UUID.randomUUID().toString(), UUID.randomUUID().toString(), "handle_date", "target_date", "place_from", "place_to", "consignee", "10001", 1.0, true); ConsignRecord consignRecord = new ConsignRecord(UUID.randomUUID().toString(), UUID.randomUUID().toString(), UUID.randomUUID().toString(), "handle_date", "target_date", "place_from", "place_to", "consignee", "10001", 2.0, 3.0); Mockito.when(repository.findById(Mockito.anyString())).thenReturn(java.util.Optional.of(consignRecord)); Mockito.when(restTemplate.exchange( "http://ts-consign-price-service:16110/api/v1/consignpriceservice/consignprice/" + consignRequest.getWeight() + "/" + consignRequest.isWithin(), HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<Double>>() { })).thenReturn(re); Mockito.when(repository.save(Mockito.any(ConsignRecord.class))).thenReturn(null); Response result = consignServiceImpl.updateConsignRecord(consignRequest, headers); consignRecord.setWeight(1.0); Assert.assertEquals(new Response<>(1, "Update consign success", consignRecord), result); } @Test public void testUpdateConsignRecord2() { Consign consignRequest = new Consign(UUID.randomUUID().toString(), UUID.randomUUID().toString(), UUID.randomUUID().toString(), "handle_date", "target_date", "place_from", "place_to", "consignee", "10001", 1.0, true); ConsignRecord consignRecord = new ConsignRecord(UUID.randomUUID().toString(), UUID.randomUUID().toString(), UUID.randomUUID().toString(), "handle_date", "target_date", "place_from", "place_to", "consignee", "10001", 1.0, 3.0); Mockito.when(repository.findById(Mockito.anyString())).thenReturn(java.util.Optional.of(consignRecord)); Mockito.when(repository.save(Mockito.any(ConsignRecord.class))).thenReturn(null); Response result = consignServiceImpl.updateConsignRecord(consignRequest, headers); Assert.assertEquals(new Response<>(1, "Update consign success", consignRecord), result); } @Test public void testQueryByAccountId1() { UUID accountId = UUID.randomUUID(); ArrayList<ConsignRecord> consignRecords = new ArrayList<>(); consignRecords.add(new ConsignRecord()); Mockito.when(repository.findByAccountId(Mockito.anyString())).thenReturn(consignRecords); Response result = consignServiceImpl.queryByAccountId(accountId, headers); Assert.assertEquals(new Response<>(1, "Find consign by account id success", consignRecords), result); } @Test public void testQueryByAccountId2() { UUID accountId = UUID.randomUUID(); Mockito.when(repository.findByAccountId(Mockito.anyString())).thenReturn(null); Response result = consignServiceImpl.queryByAccountId(accountId, headers); Assert.assertEquals(new Response<>(0, "No Content according to accountId", null), result); } @Test public void testQueryByOrderId1() { UUID orderId = UUID.randomUUID(); ConsignRecord consignRecords = new ConsignRecord(); Mockito.when(repository.findByOrderId(Mockito.anyString())).thenReturn(consignRecords); Response result = consignServiceImpl.queryByOrderId(orderId, headers); Assert.assertEquals(new Response<>(1, "Find consign by order id success", consignRecords), result); } @Test public void testQueryByOrderId2() { UUID orderId = UUID.randomUUID(); Mockito.when(repository.findByOrderId(Mockito.anyString())).thenReturn(null); Response result = consignServiceImpl.queryByOrderId(orderId, headers); Assert.assertEquals(new Response<>(0, "No Content according to order id", null), result); } @Test public void testQueryByConsignee1() { ArrayList<ConsignRecord> consignRecords = new ArrayList<>(); consignRecords.add(new ConsignRecord()); Mockito.when(repository.findByConsignee(Mockito.anyString())).thenReturn(consignRecords); Response result = consignServiceImpl.queryByConsignee("consignee", headers); Assert.assertEquals(new Response<>(1, "Find consign by consignee success", consignRecords), result); } @Test public void testQueryByConsignee2() { Mockito.when(repository.findByConsignee(Mockito.anyString())).thenReturn(null); Response result = consignServiceImpl.queryByConsignee("consignee", headers); Assert.assertEquals(new Response<>(0, "No Content according to consignee", null), result); } }
7,427
50.944056
234
java
train-ticket
train-ticket-master/ts-contacts-service/src/main/java/contacts/ContactsApplication.java
package contacts; 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 ContactsApplication { public static void main(String[] args) { SpringApplication.run(ContactsApplication.class, args); } @LoadBalanced @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); } }
1,186
31.972222
75
java
train-ticket
train-ticket-master/ts-contacts-service/src/main/java/contacts/config/SecurityConfig.java
package contacts.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/contactservice/**").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,251
38.658537
130
java
train-ticket
train-ticket-master/ts-contacts-service/src/main/java/contacts/controller/ContactsController.java
package contacts.controller; import contacts.entity.*; 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.*; import org.springframework.web.bind.annotation.*; import contacts.service.ContactsService; import java.util.UUID; import static org.springframework.http.ResponseEntity.ok; /** * @author fdse */ @RestController @RequestMapping("api/v1/contactservice") public class ContactsController { @Autowired private ContactsService contactsService; private static final Logger LOGGER = LoggerFactory.getLogger(ContactsController.class); @GetMapping(path = "/contacts/welcome") public String home() { return "Welcome to [ Contacts Service ] !"; } @CrossOrigin(origins = "*") @GetMapping(path = "/contacts") public HttpEntity getAllContacts(@RequestHeader HttpHeaders headers) { ContactsController.LOGGER.info("[getAllContacts][Get All Contacts]"); return ok(contactsService.getAllContacts(headers)); } @CrossOrigin(origins = "*") @PostMapping(path = "/contacts") public ResponseEntity<Response> createNewContacts(@RequestBody Contacts aci, @RequestHeader HttpHeaders headers) { ContactsController.LOGGER.info("[createNewContacts][VerifyLogin Success]"); return new ResponseEntity<>(contactsService.create(aci, headers), HttpStatus.CREATED); } @CrossOrigin(origins = "*") @PostMapping(path = "/contacts/admin") public HttpEntity<?> createNewContactsAdmin(@RequestBody Contacts aci, @RequestHeader HttpHeaders headers) { aci.setId(UUID.randomUUID().toString()); ContactsController.LOGGER.info("[createNewContactsAdmin][Create Contacts In Admin]"); return new ResponseEntity<>(contactsService.createContacts(aci, headers), HttpStatus.CREATED); } @CrossOrigin(origins = "*") @DeleteMapping(path = "/contacts/{contactsId}") public HttpEntity deleteContacts(@PathVariable String contactsId, @RequestHeader HttpHeaders headers) { return ok(contactsService.delete(contactsId, headers)); } @CrossOrigin(origins = "*") @PutMapping(path = "/contacts") public HttpEntity modifyContacts(@RequestBody Contacts info, @RequestHeader HttpHeaders headers) { ContactsController.LOGGER.info("[Contacts modifyContacts][Modify Contacts] ContactsId: {}", info.getId()); return ok(contactsService.modify(info, headers)); } @CrossOrigin(origins = "*") @GetMapping(path = "/contacts/account/{accountId}") public HttpEntity findContactsByAccountId(@PathVariable String accountId, @RequestHeader HttpHeaders headers) { ContactsController.LOGGER.info("[findContactsByAccountId][Find Contacts By Account Id][accountId: {}]", accountId); ContactsController.LOGGER.info("[ContactsService][VerifyLogin Success]"); return ok(contactsService.findContactsByAccountId(accountId, headers)); } @CrossOrigin(origins = "*") @GetMapping(path = "/contacts/{id}") public HttpEntity getContactsByContactsId(@PathVariable String id, @RequestHeader HttpHeaders headers) { ContactsController.LOGGER.info("[ContactsService][Contacts Id Print][id: {}]", id); ContactsController.LOGGER.info("[ContactsService][VerifyLogin Success]"); return ok(contactsService.findContactsById(id, headers)); } }
3,529
37.791209
123
java
train-ticket
train-ticket-master/ts-contacts-service/src/main/java/contacts/entity/Contacts.java
package contacts.entity; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.AllArgsConstructor; import lombok.Data; import javax.persistence.*; import org.hibernate.annotations.GenericGenerator; import java.util.UUID; /** * @author fdse */ @Data @AllArgsConstructor @Entity @GenericGenerator(name = "jpa-uuid", strategy = "org.hibernate.id.UUIDGenerator") @JsonIgnoreProperties(ignoreUnknown = true) @Table(indexes = {@Index(name = "account_document_idx", columnList = "account_id, document_number, document_type", unique = true)}) public class Contacts { @Id // private UUID id; @GeneratedValue(generator = "jpa-uuid") @Column(length = 36) private String id; @Column(name = "account_id") private String accountId; private String name; @Column(name = "document_type") private int documentType; @Column(name = "document_number") private String documentNumber; @Column(name = "phone_number") private String phoneNumber; public Contacts() { //Default Constructor } @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,834
25.214286
131
java
train-ticket
train-ticket-master/ts-contacts-service/src/main/java/contacts/entity/DocumentType.java
package contacts.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(); } }
915
16.960784
63
java
train-ticket
train-ticket-master/ts-contacts-service/src/main/java/contacts/init/InitData.java
package contacts.init; import contacts.entity.Contacts; import contacts.entity.DocumentType; import contacts.service.ContactsService; 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 ContactsService service; @Override public void run(String... args)throws Exception{ Contacts contactsOne = new Contacts(); contactsOne.setAccountId(UUID.fromString("4d2a46c7-71cb-4cf1-b5bb-b68406d9da6f").toString()); contactsOne.setDocumentType(DocumentType.ID_CARD.getCode()); contactsOne.setName("Contacts_One"); contactsOne.setDocumentNumber("DocumentNumber_One"); contactsOne.setPhoneNumber("ContactsPhoneNum_One"); contactsOne.setId(UUID.fromString("4d2a46c7-71cb-4cf1-a5bb-b68406d9da6f").toString()); service.create(contactsOne ,null); Contacts contactsTwo = new Contacts(); contactsTwo.setAccountId(UUID.fromString("4d2a46c7-71cb-4cf1-b5bb-b68406d9da6f").toString()); contactsTwo.setDocumentType(DocumentType.ID_CARD.getCode()); contactsTwo.setName("Contacts_Two"); contactsTwo.setDocumentNumber("DocumentNumber_Two"); contactsTwo.setPhoneNumber("ContactsPhoneNum_Two"); contactsTwo.setId(UUID.fromString("4d2546c7-71cb-4cf1-a5bb-b68406d9da6f").toString()); service.create(contactsTwo,null); } }
1,574
37.414634
101
java
train-ticket
train-ticket-master/ts-contacts-service/src/main/java/contacts/repository/ContactsRepository.java
package contacts.repository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import contacts.entity.Contacts; import java.util.*; /** * @author fdse */ @Repository public interface ContactsRepository extends CrudRepository<Contacts, String> { /** * find by id * * @param id id * @return Contacts */ Optional<Contacts> findById(String id); /** * find by account id * * @param accountId account id * @return ArrayList<Contacts> */ // @Query("{ 'accountId' : ?0 }") ArrayList<Contacts> findByAccountId(String accountId); /** * delete by id * * @param id id * @return null */ void deleteById(String id); /** * find all * * @return ArrayList<Contacts> */ @Override ArrayList<Contacts> findAll(); @Query(value="SELECT * FROM contacts WHERE account_id = ?1 AND document_number = ?2 AND document_type = ?3", nativeQuery = true) Contacts findByAccountIdAndDocumentTypeAndDocumentType(String account_id, String document_number, int document_type); }
1,208
21.811321
132
java
train-ticket
train-ticket-master/ts-contacts-service/src/main/java/contacts/service/ContactsService.java
package contacts.service; import contacts.entity.*; import edu.fudan.common.util.Response; import org.springframework.http.HttpHeaders; import java.util.UUID; /** * @author fdse */ public interface ContactsService { /** * create contacts * * @param contacts contacts * @param headers headers * @return Reaponse */ Response createContacts(Contacts contacts, HttpHeaders headers); /** * create * * @param addContacts add contacts * @param headers headers * @return Reaponse */ Response create(Contacts addContacts, HttpHeaders headers); /** * delete * * @param contactsId contacts id * @param headers headers * @return Reaponse */ Response delete(String contactsId, HttpHeaders headers); /** * modify * * @param contacts contacts * @param headers headers * @return Reaponse */ Response modify(Contacts contacts, HttpHeaders headers); /** * get all contacts * * @param headers headers * @return Reaponse */ Response getAllContacts(HttpHeaders headers); /** * find contacts by id * * @param id id * @param headers headers * @return Reaponse */ Response findContactsById(String id, HttpHeaders headers); /** * find contacts by account id * * @param accountId account id * @param headers headers * @return Reaponse */ Response findContactsByAccountId(String accountId, HttpHeaders headers); }
1,561
19.285714
76
java
train-ticket
train-ticket-master/ts-contacts-service/src/main/java/contacts/service/ContactsServiceImpl.java
package contacts.service; import contacts.entity.*; 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 contacts.repository.ContactsRepository; import java.util.ArrayList; import java.util.UUID; /** * @author fdse */ @Service public class ContactsServiceImpl implements ContactsService { @Autowired private ContactsRepository contactsRepository; String success = "Success"; private static final Logger LOGGER = LoggerFactory.getLogger(ContactsServiceImpl.class); @Override public Response findContactsById(String id, HttpHeaders headers) { LOGGER.info("FIND CONTACTS BY ID: " + id); Contacts contacts = contactsRepository.findById(id).orElse(null); if (contacts != null) { return new Response<>(1, success, contacts); } else { LOGGER.error("[findContactsById][contactsRepository.findById][No contacts according to contactsId][contactsId: {}]", id); return new Response<>(0, "No contacts according to contacts id", null); } } @Override public Response findContactsByAccountId(String accountId, HttpHeaders headers) { ArrayList<Contacts> arr = contactsRepository.findByAccountId(accountId); ContactsServiceImpl.LOGGER.info("[findContactsByAccountId][Query Contacts][Result Size: {}]", arr.size()); return new Response<>(1, success, arr); } @Override public Response createContacts(Contacts contacts, HttpHeaders headers) { Contacts contactsTemp = contactsRepository.findByAccountIdAndDocumentTypeAndDocumentType(contacts.getAccountId(), contacts.getDocumentNumber(), contacts.getDocumentType()); if (contactsTemp != null) { ContactsServiceImpl.LOGGER.warn("[createContacts][Init Contacts, Already Exists][Id: {}]", contacts.getId()); return new Response<>(0, "Already Exists", contactsTemp); } else { contactsRepository.save(contacts); return new Response<>(1, "Create Success", null); } } @Override public Response create(Contacts addContacts, HttpHeaders headers) { Contacts c = contactsRepository.findByAccountIdAndDocumentTypeAndDocumentType(addContacts.getAccountId(), addContacts.getDocumentNumber(), addContacts.getDocumentType()); if (c != null) { ContactsServiceImpl.LOGGER.warn("[Contacts-Add&Delete-Service.create][AddContacts][Fail.Contacts already exists][contactId: {}]", addContacts.getId()); return new Response<>(0, "Contacts already exists", null); } else { Contacts contacts = contactsRepository.save(addContacts); ContactsServiceImpl.LOGGER.info("[Contacts-Add&Delete-Service.create][AddContacts Success]"); return new Response<>(1, "Create contacts success", contacts); } } @Override public Response delete(String contactsId, HttpHeaders headers) { contactsRepository.deleteById(contactsId); Contacts contacts = contactsRepository.findById(contactsId).orElse(null); if (contacts == null) { ContactsServiceImpl.LOGGER.info("[Contacts-Add&Delete-Service][DeleteContacts Success]"); return new Response<>(1, "Delete success", contactsId); } else { ContactsServiceImpl.LOGGER.error("[Contacts-Add&Delete-Service][DeleteContacts][Fail.Reason not clear][contactsId: {}]", contactsId); return new Response<>(0, "Delete failed", contactsId); } } @Override public Response modify(Contacts contacts, HttpHeaders headers) { headers = null; Response oldContactResponse = findContactsById(contacts.getId(), headers); LOGGER.info(oldContactResponse.toString()); Contacts oldContacts = (Contacts) oldContactResponse.getData(); if (oldContacts == null) { ContactsServiceImpl.LOGGER.error("[Contacts-Modify-Service.modify][ModifyContacts][Fail.Contacts not found][contactId: {}]", contacts.getId()); return new Response<>(0, "Contacts not found", null); } else { oldContacts.setName(contacts.getName()); oldContacts.setDocumentType(contacts.getDocumentType()); oldContacts.setDocumentNumber(contacts.getDocumentNumber()); oldContacts.setPhoneNumber(contacts.getPhoneNumber()); contactsRepository.save(oldContacts); ContactsServiceImpl.LOGGER.info("[Contacts-Modify-Service.modify][ModifyContacts Success]"); return new Response<>(1, "Modify success", oldContacts); } } @Override public Response getAllContacts(HttpHeaders headers) { ArrayList<Contacts> contacts = contactsRepository.findAll(); if (contacts != null && !contacts.isEmpty()) { return new Response<>(1, success, contacts); } else { LOGGER.error("[getAllContacts][contactsRepository.findAll][Get all contacts error][message: {}]", "No content"); return new Response<>(0, "No content", null); } } }
5,281
42.295082
180
java
train-ticket
train-ticket-master/ts-contacts-service/src/test/java/contacts/controller/ContactsControllerTest.java
package contacts.controller; import com.alibaba.fastjson.JSONObject; import contacts.entity.Contacts; import contacts.service.ContactsService; 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.UUID; @RunWith(JUnit4.class) public class ContactsControllerTest { @InjectMocks private ContactsController contactsController; @Mock private ContactsService contactsService; private MockMvc mockMvc; private Response response = new Response(); @Before public void setUp() { MockitoAnnotations.initMocks(this); mockMvc = MockMvcBuilders.standaloneSetup(contactsController).build(); } @Test public void testHome() throws Exception { mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/contactservice/contacts/welcome")) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.content().string("Welcome to [ Contacts Service ] !")); } @Test public void testGetAllContacts() throws Exception { Mockito.when(contactsService.getAllContacts(Mockito.any(HttpHeaders.class))).thenReturn(response); String result = mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/contactservice/contacts")) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } @Test public void testCreateNewContacts() throws Exception { Contacts aci = new Contacts(); Mockito.when(contactsService.create(Mockito.any(Contacts.class), Mockito.any(HttpHeaders.class))).thenReturn(response); String requestJson = JSONObject.toJSONString(aci); String result = mockMvc.perform(MockMvcRequestBuilders.post("/api/v1/contactservice/contacts").contentType(MediaType.APPLICATION_JSON).content(requestJson)) .andExpect(MockMvcResultMatchers.status().isCreated()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } @Test public void testCreateNewContactsAdmin() throws Exception { Contacts aci = new Contacts(); Mockito.when(contactsService.createContacts(Mockito.any(Contacts.class), Mockito.any(HttpHeaders.class))).thenReturn(response); String requestJson = JSONObject.toJSONString(aci); String result = mockMvc.perform(MockMvcRequestBuilders.post("/api/v1/contactservice/contacts/admin").contentType(MediaType.APPLICATION_JSON).content(requestJson)) .andExpect(MockMvcResultMatchers.status().isCreated()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } @Test public void testDeleteContacts() throws Exception { UUID contactsId = UUID.randomUUID(); Mockito.when(contactsService.delete(Mockito.any(UUID.class).toString(), Mockito.any(HttpHeaders.class))).thenReturn(response); String result = mockMvc.perform(MockMvcRequestBuilders.delete("/api/v1/contactservice/contacts/" + contactsId.toString())) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } @Test public void testModifyContacts() throws Exception { Contacts info = new Contacts(); Mockito.when(contactsService.modify(Mockito.any(Contacts.class), Mockito.any(HttpHeaders.class))).thenReturn(response); String requestJson = JSONObject.toJSONString(info); String result = mockMvc.perform(MockMvcRequestBuilders.put("/api/v1/contactservice/contacts").contentType(MediaType.APPLICATION_JSON).content(requestJson)) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } @Test public void testFindContactsByAccountId() throws Exception { UUID accountId = UUID.randomUUID(); Mockito.when(contactsService.findContactsByAccountId(Mockito.any(UUID.class).toString(), Mockito.any(HttpHeaders.class))).thenReturn(response); String result = mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/contactservice/contacts/account/" + accountId.toString())) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } @Test public void testGetContactsByContactsId() throws Exception { UUID id = UUID.randomUUID(); Mockito.when(contactsService.findContactsById(Mockito.any(UUID.class).toString(), Mockito.any(HttpHeaders.class))).thenReturn(response); String result = mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/contactservice/contacts/" + id.toString())) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } }
5,957
48.239669
170
java
train-ticket
train-ticket-master/ts-contacts-service/src/test/java/contacts/service/ContactsServiceImplTest.java
package contacts.service; import contacts.entity.Contacts; import contacts.repository.ContactsRepository; 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.Optional; import java.util.UUID; @RunWith(JUnit4.class) public class ContactsServiceImplTest { @InjectMocks private ContactsServiceImpl contactsServiceImpl; @Mock private ContactsRepository contactsRepository; private HttpHeaders headers = new HttpHeaders(); @Before public void setUp() { MockitoAnnotations.initMocks(this); } @Test public void testFindContactsById1() { UUID id = UUID.randomUUID(); Contacts contacts = new Contacts(); Mockito.when(contactsRepository.findById(Mockito.any(UUID.class).toString())).thenReturn(Optional.of(contacts)); Response result = contactsServiceImpl.findContactsById(id.toString(), headers); Assert.assertEquals(new Response<>(1, "Success", contacts), result); } @Test public void testFindContactsById2() { UUID id = UUID.randomUUID(); Mockito.when(contactsRepository.findById(Mockito.any(UUID.class).toString())).thenReturn(Optional.empty()); Response result = contactsServiceImpl.findContactsById(id.toString(), headers); Assert.assertEquals(new Response<>(0, "No contacts according to contacts id", null), result); } @Test public void testFindContactsByAccountId() { UUID accountId = UUID.randomUUID(); ArrayList<Contacts> arr = new ArrayList<>(); Mockito.when(contactsRepository.findByAccountId(Mockito.any(UUID.class).toString())).thenReturn(arr); Response result = contactsServiceImpl.findContactsByAccountId(accountId.toString(), headers); Assert.assertEquals(new Response<>(1, "Success", arr), result); } @Test public void testCreateContacts1() { Contacts contacts = new Contacts(); Mockito.when(contactsRepository.findById(Mockito.any(UUID.class).toString())).thenReturn(Optional.of(contacts)); Response result = contactsServiceImpl.createContacts(contacts, headers); Assert.assertEquals(new Response<>(0, "Already Exists", contacts), result); } @Test public void testCreateContacts2() { Contacts contacts = new Contacts(); Mockito.when(contactsRepository.findById(Mockito.any(UUID.class).toString())).thenReturn(Optional.empty()); Mockito.when(contactsRepository.save(Mockito.any(Contacts.class))).thenReturn(null); Response result = contactsServiceImpl.createContacts(contacts, headers); Assert.assertEquals(new Response<>(1, "Create Success", null), result); } @Test public void testCreate1() { Contacts addContacts = new Contacts(UUID.randomUUID().toString(), UUID.randomUUID().toString(), "name", 1, "12", "10001"); ArrayList<Contacts> accountContacts = new ArrayList<>(); accountContacts.add(addContacts); Mockito.when(contactsRepository.findByAccountId(Mockito.any(UUID.class).toString())).thenReturn(accountContacts); Response result = contactsServiceImpl.create(addContacts, headers); Assert.assertEquals(new Response<>(0, "Contacts already exists", null), result); } @Test public void testCreate2() { Contacts addContacts = new Contacts(UUID.randomUUID().toString(), UUID.randomUUID().toString(), "name", 1, "12", "10001"); ArrayList<Contacts> accountContacts = new ArrayList<>(); Mockito.when(contactsRepository.findByAccountId(Mockito.any(UUID.class).toString())).thenReturn(accountContacts); Mockito.when(contactsRepository.save(Mockito.any(Contacts.class))).thenReturn(null); Response result = contactsServiceImpl.create(addContacts, headers); Assert.assertEquals(new Response<>(1, "Create contacts success", addContacts), result); } @Test public void testDelete1() { UUID contactsId = UUID.randomUUID(); Mockito.doNothing().doThrow(new RuntimeException()).when(contactsRepository).deleteById(Mockito.any(UUID.class).toString()); Mockito.when(contactsRepository.findById(Mockito.any(UUID.class).toString())).thenReturn(Optional.empty()); Response result = contactsServiceImpl.delete(contactsId.toString(), headers); Assert.assertEquals(new Response<>(1, "Delete success", contactsId), result); } @Test public void testDelete2() { UUID contactsId = UUID.randomUUID(); Contacts contacts = new Contacts(); Mockito.doNothing().doThrow(new RuntimeException()).when(contactsRepository).deleteById(Mockito.any(UUID.class).toString()); Mockito.when(contactsRepository.findById(Mockito.any(UUID.class).toString())).thenReturn(Optional.of(contacts)); Response result = contactsServiceImpl.delete(contactsId.toString(), headers); Assert.assertEquals(new Response<>(0, "Delete failed", contactsId), result); } @Test public void testModify1() { Contacts contacts = new Contacts(UUID.randomUUID().toString(), UUID.randomUUID().toString(), "name", 1, "12", "10001"); Mockito.when(contactsRepository.findById(Mockito.any(UUID.class).toString())).thenReturn(Optional.empty()); Response result = contactsServiceImpl.modify(contacts, headers); Assert.assertEquals(new Response<>(0, "Contacts not found", null), result); } @Test public void testModify2() { Contacts contacts = new Contacts(UUID.randomUUID().toString(), UUID.randomUUID().toString(), "name", 1, "12", "10001"); Mockito.when(contactsRepository.findById(Mockito.any(UUID.class).toString())).thenReturn(Optional.of(contacts)); Mockito.when(contactsRepository.save(Mockito.any(Contacts.class))).thenReturn(null); Response result = contactsServiceImpl.modify(contacts, headers); Assert.assertEquals(new Response<>(1, "Modify success", contacts), result); } @Test public void testGetAllContacts1() { ArrayList<Contacts> contacts = new ArrayList<>(); contacts.add(new Contacts()); Mockito.when(contactsRepository.findAll()).thenReturn(contacts); Response result = contactsServiceImpl.getAllContacts(headers); Assert.assertEquals(new Response<>(1, "Success", contacts), result); } @Test public void testGetAllContacts2() { Mockito.when(contactsRepository.findAll()).thenReturn(null); Response result = contactsServiceImpl.getAllContacts(headers); Assert.assertEquals(new Response<>(0, "No content", null), result); } }
6,936
44.339869
132
java
train-ticket
train-ticket-master/ts-delivery-service/src/main/java/delivery/DeliveryApplication.java
package delivery; 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.web.client.RestTemplate; import springfox.documentation.swagger2.annotations.EnableSwagger2; /** * @author humbertzhang */ @SpringBootApplication @EnableSwagger2 @EnableDiscoveryClient public class DeliveryApplication { public static void main(String[] args) { SpringApplication.run(DeliveryApplication.class, args); } @LoadBalanced @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); } }
899
28.032258
72
java
train-ticket
train-ticket-master/ts-delivery-service/src/main/java/delivery/config/Queues.java
package delivery.config; import org.springframework.amqp.core.Queue; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class Queues { public final static String queueName = "food_delivery"; @Bean public Queue emailQueue() { return new Queue(queueName); } }
370
20.823529
60
java
train-ticket
train-ticket-master/ts-delivery-service/src/main/java/delivery/entity/Delivery.java
package delivery.entity; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.AllArgsConstructor; import lombok.Data; import org.hibernate.annotations.GeneratorType; import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.GenericGenerators; import javax.persistence.Column; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Entity; import java.util.UUID; @Data @AllArgsConstructor @Entity @GenericGenerator(name = "jpa-uuid", strategy = "org.hibernate.id.UUIDGenerator") @JsonIgnoreProperties(ignoreUnknown = true) public class Delivery { public Delivery() { //Default Constructor } @Id @GeneratedValue(generator = "jpa-uuid") @Column(length = 36) private String id; private UUID orderId; private String foodName; private String storeName; private String stationName; }
919
24.555556
81
java
train-ticket
train-ticket-master/ts-delivery-service/src/main/java/delivery/mq/RabbitReceive.java
package delivery.mq; import delivery.config.Queues; import delivery.entity.Delivery; import delivery.repository.DeliveryRepository; import edu.fudan.common.util.JsonUtils; import edu.fudan.common.util.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; import java.util.UUID; @Component public class RabbitReceive { private static final Logger logger = LoggerFactory.getLogger(RabbitReceive.class); @Autowired private RestTemplate restTemplate; @Autowired private DeliveryRepository deliveryRepository; @RabbitListener(queues = Queues.queueName) public void process(String payload) { Delivery delivery = JsonUtils.json2Object(payload, Delivery.class); if (delivery == null) { logger.error("[process][json2Object][Receive delivery object is null error]"); return; } logger.info("[process][Receive delivery object][delivery object: {}]" + delivery); if (delivery.getId() == null) { delivery.setId(UUID.randomUUID().toString()); } try { deliveryRepository.save(delivery); logger.info("[process][Save delivery object into database success]"); } catch (Exception e) { logger.error("[process][deliveryRepository.save][Save delivery object into database failed][exception: {}]", e.toString()); } } }
1,823
31
135
java
train-ticket
train-ticket-master/ts-delivery-service/src/main/java/delivery/repository/DeliveryRepository.java
package delivery.repository; import delivery.entity.Delivery; import org.springframework.data.repository.CrudRepository; import org.springframework.scheduling.Trigger; import org.springframework.stereotype.Repository; import java.util.List; import java.util.Optional; import java.util.UUID; @Repository public interface DeliveryRepository extends CrudRepository<Delivery, String> { Optional<Delivery> findById(String id); Delivery findByOrderId(UUID orderId); @Override List<Delivery> findAll(); void deleteById(String id); void deleteFoodOrderByOrderId(String id); }
603
19.827586
78
java
train-ticket
train-ticket-master/ts-execute-service/src/main/java/execute/ExecuteApplication.java
package execute; 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 ExecuteApplication { public static void main(String[] args) { SpringApplication.run(ExecuteApplication.class, args); } @LoadBalanced @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); } }
1,183
31.888889
75
java
train-ticket
train-ticket-master/ts-execute-service/src/main/java/execute/config/SecurityConfig.java
package execute.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/executeservice/**").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,250
38.646341
130
java
train-ticket
train-ticket-master/ts-execute-service/src/main/java/execute/controller/ExecuteControlller.java
package execute.controller; import execute.serivce.ExecuteService; 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/executeservice") public class ExecuteControlller { @Autowired private ExecuteService executeService; private static final Logger LOGGER = LoggerFactory.getLogger(ExecuteControlller.class); @GetMapping(path = "/welcome") public String home(@RequestHeader HttpHeaders headers) { return "Welcome to [ Execute Service ] !"; } @CrossOrigin(origins = "*") @GetMapping(path = "/execute/execute/{orderId}") public HttpEntity executeTicket(@PathVariable String orderId, @RequestHeader HttpHeaders headers) { ExecuteControlller.LOGGER.info("[executeTicket][Execute][Id: {}]", orderId); // null return ok(executeService.ticketExecute(orderId, headers)); } @CrossOrigin(origins = "*") @GetMapping(path = "/execute/collected/{orderId}") public HttpEntity collectTicket(@PathVariable String orderId, @RequestHeader HttpHeaders headers) { ExecuteControlller.LOGGER.info("[collectTicket][Collect][Id: {}]", orderId); // null return ok(executeService.ticketCollect(orderId, headers)); } }
1,542
31.829787
103
java
train-ticket
train-ticket-master/ts-execute-service/src/main/java/execute/serivce/ExecuteService.java
package execute.serivce; import edu.fudan.common.util.Response; import org.springframework.http.HttpHeaders; /** * @author fdse */ public interface ExecuteService { /** * ticket execute by order id * * @param orderId order id * @param headers headers * @return Response */ Response ticketExecute(String orderId, HttpHeaders headers); /** * ticker collect * * @param orderId order id * @param headers headers * @return Response */ Response ticketCollect(String orderId, HttpHeaders headers); }
576
18.233333
64
java
train-ticket
train-ticket-master/ts-execute-service/src/main/java/execute/serivce/ExecuteServiceImpl.java
package execute.serivce; import edu.fudan.common.util.Response; import edu.fudan.common.entity.*; 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.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.util.List; /** * @author fdse */ @Service public class ExecuteServiceImpl implements ExecuteService { @Autowired private RestTemplate restTemplate; @Autowired private DiscoveryClient discoveryClient; String orderStatusWrong = "Order Status Wrong"; private static final Logger LOGGER = LoggerFactory.getLogger(ExecuteServiceImpl.class); private String getServiceUrl(String serviceName) { return "http://" + serviceName; } @Override public Response ticketExecute(String orderId, HttpHeaders headers) { //1.Get order information headers = null; Response<Order> resultFromOrder = getOrderByIdFromOrder(orderId, headers); Order order; if (resultFromOrder.getStatus() == 1) { order = resultFromOrder.getData(); //2.Check if the order can come in if (order.getStatus() != OrderStatus.COLLECTED.getCode()) { LOGGER.error("[ticketExecute][getOrderByIdFromOrder][ticket execute error: {}][orderId: {}]", orderStatusWrong, orderId); return new Response<>(0, orderStatusWrong, null); } //3.Confirm inbound, request change order information Response resultExecute = executeOrder(orderId, OrderStatus.USED.getCode(), headers); if (resultExecute.getStatus() == 1) { return new Response<>(1, "Success.", null); } else { LOGGER.error("[ticketExecute][executeOrder][executeOrder error: {}][orderId: {}]", resultExecute.getMsg(), orderId); return new Response<>(0, resultExecute.getMsg(), null); } } else { resultFromOrder = getOrderByIdFromOrderOther(orderId, headers); if (resultFromOrder.getStatus() == 1) { order = resultFromOrder.getData(); //2.Check if the order can come in if (order.getStatus() != OrderStatus.COLLECTED.getCode()) { LOGGER.error("[ticketExecute][getOrderByIdFromOrderOther][ticket execute error: {}][orderId: {}]", orderStatusWrong, orderId); return new Response<>(0, orderStatusWrong, null); } //3.Confirm inbound, request change order information Response resultExecute = executeOrderOther(orderId, OrderStatus.USED.getCode(), headers); if (resultExecute.getStatus() == 1) { return new Response<>(1, "Success", null); } else { LOGGER.error("[ticketExecute][executeOrderOther][executeOrderOther error: {}][orderId: {}]", resultExecute.getMsg(), orderId); return new Response<>(0, resultExecute.getMsg(), null); } } else { LOGGER.error("[ticketExecute][getOrderByIdFromOrderOther][ticker execute error: {}][orderId: {}]", "Order Not Found", orderId); return new Response<>(0, "Order Not Found", null); } } } @Override public Response ticketCollect(String orderId, HttpHeaders headers) { //1.Get order information headers = null; Response<Order> resultFromOrder = getOrderByIdFromOrder(orderId, headers); Order order; if (resultFromOrder.getStatus() == 1) { order = resultFromOrder.getData(); //2.Check if the order can come in if (order.getStatus() != OrderStatus.PAID.getCode() && order.getStatus() != OrderStatus.CHANGE.getCode()) { LOGGER.error("[ticketCollect][getOrderByIdFromOrder][ticket collect error: {}][orderId: {}]", orderStatusWrong, orderId); return new Response<>(0, orderStatusWrong, null); } //3.Confirm inbound, request change order information Response resultExecute = executeOrder(orderId, OrderStatus.COLLECTED.getCode(), headers); if (resultExecute.getStatus() == 1) { return new Response<>(1, "Success", null); } else { LOGGER.error("[ticketCollect][executeOrder][ticket collect error: {}][orderId: {}]", resultExecute.getMsg(), orderId); return new Response<>(0, resultExecute.getMsg(), null); } } else { resultFromOrder = getOrderByIdFromOrderOther(orderId, headers); if (resultFromOrder.getStatus() == 1) { order = (Order) resultFromOrder.getData(); //2.Check if the order can come in if (order.getStatus() != OrderStatus.PAID.getCode() && order.getStatus() != OrderStatus.CHANGE.getCode()) { LOGGER.error("[ticketCollect][getOrderByIdFromOrderOther][ticket collect error: {}][orderId: {}]", orderStatusWrong, orderId); return new Response<>(0, orderStatusWrong, null); } //3.Confirm inbound, request change order information Response resultExecute = executeOrderOther(orderId, OrderStatus.COLLECTED.getCode(), headers); if (resultExecute.getStatus() == 1) { return new Response<>(1, "Success.", null); } else { LOGGER.error("[ticketCollect][executeOrderOther][ticket collect error: {}][orderId: {}]", resultExecute.getMsg(), orderId); return new Response<>(0, resultExecute.getMsg(), null); } } else { LOGGER.error("[ticketCollect][getOrderByIdFromOrderOther][ticket collect error: {}][orderId: {}]", "Order Not Found", orderId); return new Response<>(0, "Order Not Found", null); } } } private Response executeOrder(String orderId, int status, HttpHeaders headers) { ExecuteServiceImpl.LOGGER.info("[Execute Service][Execute Order] Executing...."); headers = null; HttpEntity requestEntity = new HttpEntity(headers); String order_service_url=getServiceUrl("ts-order-service"); ResponseEntity<Response> re = restTemplate.exchange( order_service_url + "/api/v1/orderservice/order/status/" + orderId + "/" + status, HttpMethod.GET, requestEntity, Response.class); return re.getBody(); } private Response executeOrderOther(String orderId, int status, HttpHeaders headers) { ExecuteServiceImpl.LOGGER.info("[Execute Service][Execute Order] Executing...."); headers = null; HttpEntity requestEntity = new HttpEntity(headers); String order_other_service_url=getServiceUrl("ts-order-other-service"); ResponseEntity<Response> re = restTemplate.exchange( order_other_service_url + "/api/v1/orderOtherService/orderOther/status/" + orderId + "/" + status, HttpMethod.GET, requestEntity, Response.class); return re.getBody(); } private Response<Order> getOrderByIdFromOrder(String orderId, HttpHeaders headers) { ExecuteServiceImpl.LOGGER.info("[Execute Service][Get Order] Getting...."); headers = null; HttpEntity requestEntity = new HttpEntity(headers); 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) { ExecuteServiceImpl.LOGGER.info("[getOrderByIdFromOrderOther][Execute Service, Get Order]"); headers = null; HttpEntity requestEntity = new HttpEntity(headers); 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(); } }
9,132
46.567708
146
java
train-ticket
train-ticket-master/ts-execute-service/src/test/java/execute/controller/ExecuteControlllerTest.java
package execute.controller; import com.alibaba.fastjson.JSONObject; import edu.fudan.common.util.Response; import execute.serivce.ExecuteService; 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 ExecuteControlllerTest { @InjectMocks private ExecuteControlller executeController; @Mock private ExecuteService executeService; private MockMvc mockMvc; private Response response = new Response(); @Before public void setUp() { MockitoAnnotations.initMocks(this); mockMvc = MockMvcBuilders.standaloneSetup(executeController).build(); } @Test public void testHome() throws Exception { mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/executeservice/welcome")) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.content().string("Welcome to [ Execute Service ] !")); } @Test public void testExecuteTicket() throws Exception { Mockito.when(executeService.ticketExecute(Mockito.anyString(), Mockito.any(HttpHeaders.class))).thenReturn(response); String result = mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/executeservice/execute/execute/order_id")) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } @Test public void testCollectTicket() throws Exception { Mockito.when(executeService.ticketCollect(Mockito.anyString(), Mockito.any(HttpHeaders.class))).thenReturn(response); String result = mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/executeservice/execute/collected/order_id")) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } }
2,683
39.059701
125
java
train-ticket
train-ticket-master/ts-execute-service/src/test/java/execute/service/ExecuteServiceImplTest.java
package execute.service; import edu.fudan.common.util.Response; import edu.fudan.common.entity.Order; import execute.serivce.ExecuteServiceImpl; import org.junit.Assert; import org.junit.Before; import org.junit.Test; 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; public class ExecuteServiceImplTest { @InjectMocks private ExecuteServiceImpl executeServiceImpl; @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 testTicketExecute1() { //mock getOrderByIdFromOrder() Order order = new Order(); order.setStatus(2); 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); //mock executeOrder() Response response2 = new Response(1, null, null); ResponseEntity<Response> re2 = new ResponseEntity<>(response2, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-order-service:12031/api/v1/orderservice/order/status/" + "order_id" + "/" + 6, HttpMethod.GET, requestEntity, Response.class)).thenReturn(re2); Response result = executeServiceImpl.ticketExecute("order_id", headers); Assert.assertEquals(new Response<>(1, "Success.", null), result); } @Test public void testTicketExecute2() { //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(2); 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); //mock executeOrderOther() Response response3 = new Response(1, null, null); ResponseEntity<Response> re3 = new ResponseEntity<>(response3, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-order-other-service:12032/api/v1/orderOtherService/orderOther/status/" + "order_id" + "/" + 6, HttpMethod.GET, requestEntity, Response.class)).thenReturn(re3); Response result = executeServiceImpl.ticketExecute("order_id", headers); Assert.assertEquals(new Response<>(1, "Success", null), result); } @Test public void testTicketCollect1() { //mock getOrderByIdFromOrder() Order order = new Order(); order.setStatus(1); 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); //mock executeOrder() Response response2 = new Response(1, null, null); ResponseEntity<Response> re2 = new ResponseEntity<>(response2, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-order-service:12031/api/v1/orderservice/order/status/" + "order_id" + "/" + 2, HttpMethod.GET, requestEntity, Response.class)).thenReturn(re2); Response result = executeServiceImpl.ticketCollect("order_id", headers); Assert.assertEquals(new Response<>(1, "Success", null), result); } @Test public void testTicketCollect2() { //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(1); 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); //mock executeOrderOther() Response response3 = new Response(1, null, null); ResponseEntity<Response> re3 = new ResponseEntity<>(response3, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-order-other-service:12032/api/v1/orderOtherService/orderOther/status/" + "order_id" + "/" + 2, HttpMethod.GET, requestEntity, Response.class)).thenReturn(re3); Response result = executeServiceImpl.ticketCollect("order_id", headers); Assert.assertEquals(new Response<>(1, "Success.", null), result); } }
6,780
43.611842
121
java
train-ticket
train-ticket-master/ts-food-delivery-service/src/main/java/food_delivery/FoodDeliveryApplication.java
package food_delivery; 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; @SpringBootApplication @EnableAspectJAutoProxy(proxyTargetClass = true) @EnableAsync @IntegrationComponentScan @EnableSwagger2 @EnableDiscoveryClient public class FoodDeliveryApplication { public static void main(String[] args) { SpringApplication.run(FoodDeliveryApplication.class, args); } @LoadBalanced @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); } }
1,175
34.636364
75
java
train-ticket
train-ticket-master/ts-food-delivery-service/src/main/java/food_delivery/config/SecurityConfig.java
package food_delivery.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; @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) public class SecurityConfig extends WebSecurityConfigurerAdapter { // load password encoder @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } /** * allow cors domain * header 在默认的情况下只能从头部取出6个字段,想要其他字段只能自己在头里指定 * credentials 默认不发送Cookie, 如果需要Cookie,这个值只能为true * 本次请求检查的有效期 * * @return */ @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/fooddeliveryservice/**").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,013
39.186667
102
java
train-ticket
train-ticket-master/ts-food-delivery-service/src/main/java/food_delivery/controller/FoodDeliveryController.java
package food_delivery.controller; import edu.fudan.common.util.Response; import food_delivery.entity.DeliveryInfo; import food_delivery.entity.FoodDeliveryOrder; import food_delivery.entity.SeatInfo; import food_delivery.entity.TripOrderInfo; import food_delivery.service.FoodDeliveryService; 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; @RestController @RequestMapping("/api/v1/fooddeliveryservice") public class FoodDeliveryController { @Autowired private FoodDeliveryService foodDeliveryService; private static final Logger LOGGER = LoggerFactory.getLogger(FoodDeliveryController.class); @GetMapping(path = "/welcome") public String home() { return "Welcome to [ food delivery service ] !"; } @PostMapping("/orders") public HttpEntity createFoodDeliveryOrder(@RequestBody FoodDeliveryOrder fd, @RequestHeader HttpHeaders headers) { LOGGER.info("[Food Delivery Service][Create Food Delivery Order]"); return ok(foodDeliveryService.createFoodDeliveryOrder(fd, headers)); } @DeleteMapping("/orders/d/{orderId}") public HttpEntity deleteFoodDeliveryOrder(@PathVariable String orderId, @RequestHeader HttpHeaders headers) { LOGGER.info("[Food Delivery Service][Delete Food Delivery Order]"); return ok(foodDeliveryService.deleteFoodDeliveryOrder(orderId, headers)); } @GetMapping("/orders/{orderId}") public HttpEntity getFoodDeliveryOrderById(@PathVariable String orderId, @RequestHeader HttpHeaders headers) { LOGGER.info("[Food Delivery Service][Get Food Delivery Order By Id]"); return ok(foodDeliveryService.getFoodDeliveryOrderById(orderId, headers)); } @GetMapping("/orders/all") public HttpEntity getAllFoodDeliveryOrders(@RequestHeader HttpHeaders headers) { LOGGER.info("[Food Delivery Service][Get All Food Delivery Orders]"); return ok(foodDeliveryService.getAllFoodDeliveryOrders(headers)); } @GetMapping("/orders/store/{storeId}") public HttpEntity getFoodDeliveryOrderByStoreId(@PathVariable String storeId, @RequestHeader HttpHeaders headers) { LOGGER.info("[Food Delivery Service][Get Food Delivery Order By StoreId]"); return ok(foodDeliveryService.getFoodDeliveryOrderByStoreId(storeId, headers)); } @PutMapping("/orders/tripid") public HttpEntity updateTripId(@RequestBody TripOrderInfo tripOrderInfo, @RequestHeader HttpHeaders headers) { LOGGER.info("[Food Delivery Service][Update Trip Id]"); return ok(foodDeliveryService.updateTripId(tripOrderInfo, headers)); } @PutMapping("/orders/seatno") public HttpEntity updateSeatNo(@RequestBody SeatInfo seatInfo, @RequestHeader HttpHeaders headers) { LOGGER.info("[Food Delivery Service][Update Seat No]"); return ok(foodDeliveryService.updateSeatNo(seatInfo, headers)); } @PutMapping("/orders/dtime") public HttpEntity updateDeliveryTime(@RequestBody DeliveryInfo deliveryInfo, @RequestHeader HttpHeaders headers) { LOGGER.info("[Food Delivery Service][Update Delivery Time]"); return ok(foodDeliveryService.updateDeliveryTime(deliveryInfo, headers)); } }
3,466
41.280488
119
java
train-ticket
train-ticket-master/ts-food-delivery-service/src/main/java/food_delivery/entity/DeliveryInfo.java
package food_delivery.entity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor public class DeliveryInfo { private String orderId; private String deliveryTime; }
255
17.285714
33
java
train-ticket
train-ticket-master/ts-food-delivery-service/src/main/java/food_delivery/entity/FoodDeliveryOrder.java
package food_delivery.entity; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.hibernate.annotations.GenericGenerator; import javax.persistence.*; import java.util.List; import edu.fudan.common.entity.Food; @Data @Entity @GenericGenerator(name = "jpa-uuid", strategy = "uuid") @JsonIgnoreProperties(ignoreUnknown = true) @AllArgsConstructor @NoArgsConstructor public class FoodDeliveryOrder { @Id @GeneratedValue(generator = "jpa-uuid") @Column(length = 36) private String id; private String stationFoodStoreId; @ElementCollection(targetClass = Food.class) private List<Food> foodList; private String tripId; private int seatNo; private String createdTime; private String deliveryTime; private double deliveryFee; }
886
20.634146
61
java
train-ticket
train-ticket-master/ts-food-delivery-service/src/main/java/food_delivery/entity/SeatInfo.java
package food_delivery.entity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor public class SeatInfo { private String orderId; private int seatNo; }
241
17.615385
33
java
train-ticket
train-ticket-master/ts-food-delivery-service/src/main/java/food_delivery/entity/StationFoodStoreInfo.java
package food_delivery.entity; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.util.List; import edu.fudan.common.entity.Food; @Data @NoArgsConstructor @AllArgsConstructor @JsonIgnoreProperties(ignoreUnknown = true) public class StationFoodStoreInfo { private String id; private String stationId; private String storeName; private String telephone; private String businessTime; private double deliveryFee; private List<Food> foodList; }
588
17.40625
61
java
train-ticket
train-ticket-master/ts-food-delivery-service/src/main/java/food_delivery/entity/TripOrderInfo.java
package food_delivery.entity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor public class TripOrderInfo { private String orderId; private String tripId; }
250
16.928571
33
java
train-ticket
train-ticket-master/ts-food-delivery-service/src/main/java/food_delivery/init/InitData.java
package food_delivery.init; import food_delivery.service.FoodDeliveryService; 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.io.BufferedReader; import java.io.InputStreamReader; import edu.fudan.common.entity.Food; @Component public class InitData implements CommandLineRunner { @Autowired FoodDeliveryService foodDeliveryService; private static final Logger LOGGER = LoggerFactory.getLogger(InitData.class); @Override public void run(String... args) { BufferedReader br = new BufferedReader(new InputStreamReader(this.getClass().getResourceAsStream("/food_delivery_orders.txt"))); try { // 有限制,不能随意init初始化数据,因此先注释掉。 // String line; // while ((line = br.readLine()) != null) { // String[] strs = line.trim().split("\\|"); // String[] foods = strs[1].trim().split(","); // List<Food> foodList = new ArrayList<>(); // for (String food : foods) { // String[] food_info = food.trim().split("_"); // foodList.add(new Food(food_info[0], Double.parseDouble(food_info[1]))); // } // FoodDeliveryOrder foodDeliveryOrder = new FoodDeliveryOrder( // UUID.randomUUID().toString(), // id // strs[0], // stationFoodStoreId // foodList, // foodList // strs[2], // tripId // Integer.parseInt(strs[3]), // seatNo // strs[4], // createdTime // strs[5], // deliveryTime // Double.parseDouble(strs[6]) // deliveryFee // ); // foodDeliveryService.createFoodDeliveryOrder(foodDeliveryOrder, null); // } } catch(Exception e) { InitData.LOGGER.info("food_delivery_orders.txt has format error!"); InitData.LOGGER.error(e.getMessage()); System.exit(1); } } }
2,350
41.745455
136
java
train-ticket
train-ticket-master/ts-food-delivery-service/src/main/java/food_delivery/repository/FoodDeliveryOrderRepository.java
package food_delivery.repository; import food_delivery.entity.FoodDeliveryOrder; import org.springframework.data.repository.CrudRepository; import java.util.List; public interface FoodDeliveryOrderRepository extends CrudRepository<FoodDeliveryOrder, String> { List<FoodDeliveryOrder> findByStationFoodStoreId(String stationFoodStoreId); @Override List<FoodDeliveryOrder> findAll(); }
402
24.1875
96
java
train-ticket
train-ticket-master/ts-food-delivery-service/src/main/java/food_delivery/service/FoodDeliveryService.java
package food_delivery.service; import edu.fudan.common.util.Response; import food_delivery.entity.DeliveryInfo; import food_delivery.entity.FoodDeliveryOrder; import food_delivery.entity.SeatInfo; import food_delivery.entity.TripOrderInfo; import org.springframework.http.HttpHeaders; public interface FoodDeliveryService { Response createFoodDeliveryOrder(FoodDeliveryOrder fd, HttpHeaders headers); Response deleteFoodDeliveryOrder(String id, HttpHeaders headers); Response getFoodDeliveryOrderById(String id, HttpHeaders headers); Response getAllFoodDeliveryOrders(HttpHeaders headers); Response getFoodDeliveryOrderByStoreId(String storeId, HttpHeaders headers); Response updateTripId(TripOrderInfo tripOrderInfo, HttpHeaders headers); Response updateSeatNo(SeatInfo seatInfo, HttpHeaders headers); Response updateDeliveryTime(DeliveryInfo deliveryInfo, HttpHeaders headers); }
924
32.035714
80
java
train-ticket
train-ticket-master/ts-food-delivery-service/src/main/java/food_delivery/service/FoodDeliveryServiceImpl.java
package food_delivery.service; import edu.fudan.common.util.Response; import food_delivery.entity.*; import edu.fudan.common.entity.*; import food_delivery.repository.FoodDeliveryOrderRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.client.ServiceInstance; 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.util.List; import java.util.Map; import java.util.stream.Collectors; @Service public class FoodDeliveryServiceImpl implements FoodDeliveryService { @Autowired FoodDeliveryOrderRepository foodDeliveryOrderRepository; private static final Logger LOGGER = LoggerFactory.getLogger(FoodDeliveryServiceImpl.class); @Autowired private RestTemplate restTemplate; @Autowired private DiscoveryClient discoveryClient; private String getServiceUrl(String serviceName) { return "http://" + serviceName; } @Override public Response createFoodDeliveryOrder(FoodDeliveryOrder fd, HttpHeaders headers) { String stationFoodStoreId = fd.getStationFoodStoreId(); String staion_food_service_url = getServiceUrl("ts-station-food-service"); // staion_food_service_url = "http://ts-station-food-service"; // 测试 ResponseEntity<Response<StationFoodStoreInfo>> getStationFoodStore = restTemplate.exchange( staion_food_service_url + "/api/v1/stationfoodservice/stationfoodstores/bystoreid/" + stationFoodStoreId, HttpMethod.GET, new HttpEntity(headers), new ParameterizedTypeReference<Response<StationFoodStoreInfo>>() { }); Response<StationFoodStoreInfo> result = getStationFoodStore.getBody(); StationFoodStoreInfo stationFoodStoreInfo = result.getData(); List<Food> storeFoodList = stationFoodStoreInfo.getFoodList(); Map<String, Double> foodPrice = storeFoodList.stream() .collect(Collectors.toMap(Food::getFoodName, Food::getPrice)); List<Food> orderFoodList = fd.getFoodList(); double deliveryFee = 0; for (Food food : orderFoodList) { Double fee = foodPrice.get(food.getFoodName()); if (fee == null) { LOGGER.error("{}:{} have no such food: {}", stationFoodStoreId, stationFoodStoreInfo.getStoreName(), food.getFoodName()); return new Response<>(0, "Food not in store", null); } deliveryFee += fee; } deliveryFee += stationFoodStoreInfo.getDeliveryFee(); fd.setDeliveryFee(deliveryFee); FoodDeliveryOrder res = foodDeliveryOrderRepository.save(fd); return new Response<>(1, "Save success", res); } @Override public Response deleteFoodDeliveryOrder(String id, HttpHeaders headers) { FoodDeliveryOrder t = foodDeliveryOrderRepository.findById(id).orElse(null); if (t == null) { LOGGER.error("[deleteFoodDeliveryOrder] No such food delivery order id: {}", id); return new Response<>(0, "No such food delivery order id", id); } else { foodDeliveryOrderRepository.deleteById(id); LOGGER.info("[deleteFoodDeliveryOrder] Delete success, food delivery order id: {}", id); return new Response<>(1, "Delete success", null); } } @Override public Response getFoodDeliveryOrderById(String id, HttpHeaders headers) { FoodDeliveryOrder t = foodDeliveryOrderRepository.findById(id).orElse(null); if (t == null) { LOGGER.error("[deleteFoodDeliveryOrder] No such food delivery order id: {}", id); return new Response<>(0, "No such food delivery order id", id); } else { LOGGER.info("[getFoodDeliveryOrderById] Get success, food delivery order id: {}", id); return new Response<>(1, "Get success", t); } } @Override public Response getAllFoodDeliveryOrders(HttpHeaders headers) { List<FoodDeliveryOrder> foodDeliveryOrders = foodDeliveryOrderRepository.findAll(); if (foodDeliveryOrders == null) { LOGGER.error("[getAllFoodDeliveryOrders] Food delivery orders query error"); return new Response<>(0, "food delivery orders query error", null); } else { LOGGER.info("[getAllFoodDeliveryOrders] Get all food delivery orders success"); return new Response<>(1, "Get success", foodDeliveryOrders); } } @Override public Response getFoodDeliveryOrderByStoreId(String storeId, HttpHeaders headers) { List<FoodDeliveryOrder> foodDeliveryOrders = foodDeliveryOrderRepository.findByStationFoodStoreId(storeId); if (foodDeliveryOrders == null) { LOGGER.error("[getAllFoodDeliveryOrders] Food delivery orders query error"); return new Response<>(0, "food delivery orders query error", storeId); } else { LOGGER.info("[getAllFoodDeliveryOrders] Get food delivery orders by storeId {} success", storeId); return new Response<>(1, "Get success", foodDeliveryOrders); } } @Override public Response updateTripId(TripOrderInfo tripInfo, HttpHeaders headers) { String id = tripInfo.getOrderId(); String tripId = tripInfo.getTripId(); FoodDeliveryOrder t = foodDeliveryOrderRepository.findById(id).orElse(null); if (t == null) { LOGGER.error("[updateTripId] No such delivery order id: {}", id); return new Response<>(0, "No such delivery order id", id); } else { t.setTripId(tripId); foodDeliveryOrderRepository.save(t); LOGGER.info("[updateTripId] update tripId success. id:{}, tripId:{}", id, tripId); return new Response<>(1, "update tripId success", t); } } @Override public Response updateSeatNo(SeatInfo seatInfo, HttpHeaders headers) { String id = seatInfo.getOrderId(); int seatNo = seatInfo.getSeatNo(); FoodDeliveryOrder t = foodDeliveryOrderRepository.findById(id).orElse(null); if (t == null) { LOGGER.error("[updateSeatNo] No such delivery order id: {}", id); return new Response<>(0, "No such delivery order id", id); } else { t.setSeatNo(seatNo); foodDeliveryOrderRepository.save(t); LOGGER.info("[updateSeatNo] update seatNo success. id:{}, seatNo:{}", id, seatNo); return new Response<>(1, "update seatNo success", t); } } @Override public Response updateDeliveryTime(DeliveryInfo deliveryInfo, HttpHeaders headers) { String id = deliveryInfo.getOrderId(); String deliveryTime = deliveryInfo.getDeliveryTime(); FoodDeliveryOrder t = foodDeliveryOrderRepository.findById(id).orElse(null); if (t == null) { LOGGER.error("[updateDeliveryTime] No such delivery order id: {}", id); return new Response<>(0, "No such delivery order id", id); } else { t.setDeliveryTime(deliveryTime); foodDeliveryOrderRepository.save(t); LOGGER.info("[updateDeliveryTime] update deliveryTime success. id:{}, deliveryTime:{}", id, deliveryTime); return new Response<>(1, "update deliveryTime success", t); } } }
7,826
44.242775
137
java
train-ticket
train-ticket-master/ts-food-delivery-service/src/test/java/food_delivery/controller/FoodDeliveryControllerTest.java
package food_delivery.controller; import com.alibaba.fastjson.JSONObject; import edu.fudan.common.util.Response; import food_delivery.entity.DeliveryInfo; import food_delivery.entity.FoodDeliveryOrder; import food_delivery.entity.SeatInfo; import food_delivery.entity.TripOrderInfo; import food_delivery.service.FoodDeliveryService; 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.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 FoodDeliveryControllerTest { @InjectMocks private FoodDeliveryController foodDeliveryController; @Mock private FoodDeliveryService foodDeliveryService; private MockMvc mockMvc; private Response response = new Response(); @Before public void setUp() { MockitoAnnotations.initMocks(this); mockMvc = MockMvcBuilders.standaloneSetup(foodDeliveryController).build(); } @Test public void testHome() throws Exception { mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/fooddeliveryservice/welcome")) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.content().string("Welcome to [ food delivery service ] !")); } @Test public void testCreateFoodDeliveryOrder() throws Exception { FoodDeliveryOrder foodDeliveryOrder = new FoodDeliveryOrder(); Mockito.when(foodDeliveryService.createFoodDeliveryOrder(Mockito.any(FoodDeliveryOrder.class), Mockito.any(HttpHeaders.class))).thenReturn(response); String requestJson = JSONObject.toJSONString(foodDeliveryOrder); String result = mockMvc.perform(MockMvcRequestBuilders.post("/api/v1/fooddeliveryservice/orders").contentType(MediaType.APPLICATION_JSON).content(requestJson)) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } @Test public void testDeleteFoodDeliveryOrder() throws Exception { Mockito.when(foodDeliveryService.deleteFoodDeliveryOrder(Mockito.anyString(), Mockito.any(HttpHeaders.class))).thenReturn(response); String result = mockMvc.perform(MockMvcRequestBuilders.delete("/api/v1/fooddeliveryservice/orders/d/123")) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } @Test public void testGetFoodDeliveryOrderById() throws Exception { Mockito.when(foodDeliveryService.getFoodDeliveryOrderById(Mockito.anyString(), Mockito.any(HttpHeaders.class))).thenReturn(response); String result = mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/fooddeliveryservice/orders/123")) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } @Test public void testGetFoodDeliveryOrderByStoreId() throws Exception { Mockito.when(foodDeliveryService.getFoodDeliveryOrderByStoreId(Mockito.anyString(), Mockito.any(HttpHeaders.class))).thenReturn(response); String result = mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/fooddeliveryservice/orders/store/1234")) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } @Test public void testGetAllFoodDeliveryOrders() throws Exception { Mockito.when(foodDeliveryService.getAllFoodDeliveryOrders(Mockito.any(HttpHeaders.class))).thenReturn(response); String result = mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/fooddeliveryservice/orders/all")) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } @Test public void testUpdateTripId() throws Exception { TripOrderInfo tripOrderInfo = new TripOrderInfo(); Mockito.when(foodDeliveryService.updateTripId(Mockito.any(TripOrderInfo.class), Mockito.any(HttpHeaders.class))).thenReturn(response); String requestJson = JSONObject.toJSONString(tripOrderInfo); String result = mockMvc.perform(MockMvcRequestBuilders.put("/api/v1/fooddeliveryservice/orders/tripid").contentType(MediaType.APPLICATION_JSON).content(requestJson)) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } @Test public void testUpdateSeatNo() throws Exception { SeatInfo seatInfo = new SeatInfo(); Mockito.when(foodDeliveryService.updateSeatNo(Mockito.any(SeatInfo.class), Mockito.any(HttpHeaders.class))).thenReturn(response); String requestJson = JSONObject.toJSONString(seatInfo); String result = mockMvc.perform(MockMvcRequestBuilders.put("/api/v1/fooddeliveryservice/orders/seatno").contentType(MediaType.APPLICATION_JSON).content(requestJson)) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } @Test public void testUpdateDeliveryTime() throws Exception { DeliveryInfo deliveryInfo = new DeliveryInfo(); Mockito.when(foodDeliveryService.updateDeliveryTime(Mockito.any(DeliveryInfo.class), Mockito.any(HttpHeaders.class))).thenReturn(response); String requestJson = JSONObject.toJSONString(deliveryInfo); String result = mockMvc.perform(MockMvcRequestBuilders.put("/api/v1/fooddeliveryservice/orders/dtime").contentType(MediaType.APPLICATION_JSON).content(requestJson)) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } }
6,908
51.740458
173
java
train-ticket
train-ticket-master/ts-food-delivery-service/src/test/java/food_delivery/service/FoodDeliveryServiceImplTest.java
package food_delivery.service; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.http.*; import org.springframework.web.client.RestTemplate; public class FoodDeliveryServiceImplTest { @InjectMocks private FoodDeliveryServiceImpl foodDeliveryServiceImpl; @Mock private RestTemplate restTemplate; private HttpHeaders headers = new HttpHeaders(); private HttpEntity requestEntity = new HttpEntity(headers); @Before public void setUp() { MockitoAnnotations.initMocks(this); } }
645
22.925926
63
java
train-ticket
train-ticket-master/ts-food-service/src/main/java/foodsearch/FoodApplication.java
package foodsearch; 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; @SpringBootApplication @EnableAspectJAutoProxy(proxyTargetClass = true) @EnableAsync @IntegrationComponentScan @EnableSwagger2 @EnableDiscoveryClient public class FoodApplication { public static void main(String[] args) { SpringApplication.run(FoodApplication.class, args); } @LoadBalanced @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); } }
1,157
33.058824
75
java
train-ticket
train-ticket-master/ts-food-service/src/main/java/foodsearch/config/Queues.java
package foodsearch.config; import org.springframework.amqp.core.Queue; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class Queues { public final static String queueName = "food_delivery"; @Bean public Queue emailQueue() { return new Queue(queueName); } }
372
20.941176
60
java
train-ticket
train-ticket-master/ts-food-service/src/main/java/foodsearch/config/SecurityConfig.java
package foodsearch.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; @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/foodservice/**").permitAll() .antMatchers(HttpMethod.DELETE, "/api/v1/foodservice/orders/*").hasAnyRole(admin) .antMatchers(HttpMethod.PUT, "/api/v1/foodservice/orders").hasAnyRole(admin) .antMatchers(HttpMethod.POST, "/api/v1/foodservice/orders").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,568
40.988235
130
java
train-ticket
train-ticket-master/ts-food-service/src/main/java/foodsearch/controller/FoodController.java
package foodsearch.controller; import edu.fudan.common.util.JsonUtils; import foodsearch.entity.*; import foodsearch.mq.RabbitSend; import foodsearch.service.FoodService; 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.web.bind.annotation.*; import java.util.List; import java.util.UUID; import static org.springframework.http.ResponseEntity.ok; @RestController @RequestMapping("/api/v1/foodservice") public class FoodController { @Autowired FoodService foodService; @Autowired RabbitSend sender; private static final Logger LOGGER = LoggerFactory.getLogger(FoodController.class); @GetMapping(path = "/welcome") public String home() { return "Welcome to [ Food Service ] !"; } @GetMapping(path = "/test_send_delivery") public boolean test_send_delivery() { Delivery delivery = new Delivery(); delivery.setFoodName("HotPot"); delivery.setOrderId(UUID.randomUUID()); delivery.setStationName("Shang Hai"); delivery.setStoreName("MiaoTing Instant-Boiled Mutton"); String deliveryJson = JsonUtils.object2Json(delivery); sender.send(deliveryJson); return true; } @GetMapping(path = "/orders") public HttpEntity findAllFoodOrder(@RequestHeader HttpHeaders headers) { FoodController.LOGGER.info("[Food Service]Try to Find all FoodOrder!"); return ok(foodService.findAllFoodOrder(headers)); } @PostMapping(path = "/orders") public HttpEntity createFoodOrder(@RequestBody FoodOrder addFoodOrder, @RequestHeader HttpHeaders headers) { FoodController.LOGGER.info("[createFoodOrder][Try to Create a FoodOrder!]"); return ok(foodService.createFoodOrder(addFoodOrder, headers)); } @PostMapping(path = "/createOrderBatch") public HttpEntity createFoodBatches(@RequestBody List<FoodOrder> foodOrderList, @RequestHeader HttpHeaders headers) { FoodController.LOGGER.info("[createFoodBatches][Try to Create Food Batches!]"); return ok(foodService.createFoodOrdersInBatch(foodOrderList, headers)); } @PutMapping(path = "/orders") public HttpEntity updateFoodOrder(@RequestBody FoodOrder updateFoodOrder, @RequestHeader HttpHeaders headers) { FoodController.LOGGER.info("[updateFoodOrder][Try to Update a FoodOrder!]"); return ok(foodService.updateFoodOrder(updateFoodOrder, headers)); } @ResponseStatus(HttpStatus.ACCEPTED) @DeleteMapping(path = "/orders/{orderId}") public HttpEntity deleteFoodOrder(@PathVariable String orderId, @RequestHeader HttpHeaders headers) { FoodController.LOGGER.info("[deleteFoodOrder][Try to Cancel a FoodOrder!]"); return ok(foodService.deleteFoodOrder(orderId, headers)); } @GetMapping(path = "/orders/{orderId}") public HttpEntity findFoodOrderByOrderId(@PathVariable String orderId, @RequestHeader HttpHeaders headers) { FoodController.LOGGER.info("[findFoodOrderByOrderId][Try to Find FoodOrder By orderId!][orderId: {}]", orderId); return ok(foodService.findByOrderId(orderId, headers)); } // This relies on a lot of other services, not completely modified @GetMapping(path = "/foods/{date}/{startStation}/{endStation}/{tripId}") public HttpEntity getAllFood(@PathVariable String date, @PathVariable String startStation, @PathVariable String endStation, @PathVariable String tripId, @RequestHeader HttpHeaders headers) { FoodController.LOGGER.info("[getAllFood][Get Food Request!]"); return ok(foodService.getAllFood(date, startStation, endStation, tripId, headers)); } }
3,924
39.05102
121
java
train-ticket
train-ticket-master/ts-food-service/src/main/java/foodsearch/entity/AllTripFood.java
package foodsearch.entity; import edu.fudan.common.entity.Food; import edu.fudan.common.entity.StationFoodStore; import edu.fudan.common.entity.TrainFood; import lombok.Data; import java.util.List; import java.util.Map; @Data public class AllTripFood { private List<Food> trainFoodList; private Map<String, List<StationFoodStore>> foodStoreListMap; public AllTripFood(){ //Default Constructor } }
429
17.695652
66
java
train-ticket
train-ticket-master/ts-food-service/src/main/java/foodsearch/entity/Delivery.java
package foodsearch.entity; import lombok.Data; import java.io.Serializable; import java.util.UUID; @Data public class Delivery { public Delivery() { //Default Constructor } private UUID orderId; private String foodName; private String storeName; private String stationName; }
312
15.473684
31
java
train-ticket
train-ticket-master/ts-food-service/src/main/java/foodsearch/entity/FoodOrder.java
package foodsearch.entity; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.AllArgsConstructor; import lombok.Data; import org.hibernate.annotations.GenericGenerator; import javax.persistence.Column; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Entity; import java.util.UUID; @Data @AllArgsConstructor @Entity @JsonIgnoreProperties(ignoreUnknown = true) @GenericGenerator(name = "jpa-uuid", strategy = "org.hibernate.id.UUIDGenerator") public class FoodOrder { @Id @GeneratedValue(generator = "jpa-uuid") @Column(length = 36) 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 } }
915
19.818182
81
java
train-ticket
train-ticket-master/ts-food-service/src/main/java/foodsearch/mq/RabbitSend.java
package foodsearch.mq; import foodsearch.config.Queues; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.amqp.core.AmqpTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class RabbitSend { @Autowired private AmqpTemplate rabbitTemplate; private static final Logger logger = LoggerFactory.getLogger(RabbitSend.class); public void send(String val) { logger.info("Send info to mq:" + val); this.rabbitTemplate.convertAndSend(Queues.queueName, val); } }
617
23.72
83
java
train-ticket
train-ticket-master/ts-food-service/src/main/java/foodsearch/repository/FoodOrderRepository.java
package foodsearch.repository; import foodsearch.entity.FoodOrder; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import java.util.List; import java.util.Optional; import java.util.UUID; @Repository public interface FoodOrderRepository extends CrudRepository<FoodOrder, String> { Optional<FoodOrder> findById(String id); FoodOrder findByOrderId(String orderId); @Override List<FoodOrder> findAll(); void deleteById(UUID id); void deleteFoodOrderByOrderId(String id); }
565
19.962963
80
java
train-ticket
train-ticket-master/ts-food-service/src/main/java/foodsearch/service/FoodService.java
package foodsearch.service; import edu.fudan.common.util.Response; import foodsearch.entity.*; import org.springframework.http.HttpHeaders; import java.util.List; public interface FoodService { Response createFoodOrder(FoodOrder afoi, HttpHeaders headers); Response createFoodOrdersInBatch(List<FoodOrder> orders, HttpHeaders headers); Response deleteFoodOrder(String orderId, HttpHeaders headers); Response findByOrderId(String orderId, HttpHeaders headers); Response updateFoodOrder(FoodOrder updateFoodOrder, HttpHeaders headers); Response findAllFoodOrder(HttpHeaders headers); Response getAllFood(String date, String startStation, String endStation, String tripId, HttpHeaders headers); }
738
26.37037
113
java
train-ticket
train-ticket-master/ts-food-service/src/main/java/foodsearch/service/FoodServiceImpl.java
package foodsearch.service; import edu.fudan.common.entity.Food; import edu.fudan.common.entity.StationFoodStore; import edu.fudan.common.entity.TrainFood; import edu.fudan.common.util.JsonUtils; import edu.fudan.common.util.Response; import edu.fudan.common.entity.Route; import foodsearch.entity.*; import foodsearch.mq.RabbitSend; import foodsearch.repository.FoodOrderRepository; 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.transaction.annotation.Transactional; import org.springframework.web.client.RestTemplate; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.stream.Collectors; @Service public class FoodServiceImpl implements FoodService { @Autowired private RestTemplate restTemplate; @Autowired private FoodOrderRepository foodOrderRepository; @Autowired private RabbitSend sender; @Autowired private DiscoveryClient discoveryClient; private static final Logger LOGGER = LoggerFactory.getLogger(FoodServiceImpl.class); private String getServiceUrl(String serviceName) { return "http://" + serviceName; } String success = "Success."; String orderIdNotExist = "Order Id Is Non-Existent."; @Override public Response createFoodOrdersInBatch(List<FoodOrder> orders, HttpHeaders headers) { boolean error = false; String errorOrderId = ""; // Check if foodOrder exists for (FoodOrder addFoodOrder : orders) { FoodOrder fo = foodOrderRepository.findByOrderId(addFoodOrder.getOrderId()); if (fo != null) { LOGGER.error("[createFoodOrdersInBatch][AddFoodOrder][Order Id Has Existed][OrderId: {}]", addFoodOrder.getOrderId()); error = true; errorOrderId = addFoodOrder.getOrderId().toString(); break; } } if (error) { return new Response<>(0, "Order Id " + errorOrderId + "Existed", null); } List<String> deliveryJsons = new ArrayList<>(); for (FoodOrder addFoodOrder : orders) { FoodOrder fo = new FoodOrder(); fo.setId(UUID.randomUUID().toString()); fo.setOrderId(addFoodOrder.getOrderId()); fo.setFoodType(addFoodOrder.getFoodType()); if (addFoodOrder.getFoodType() == 2) { fo.setStationName(addFoodOrder.getStationName()); fo.setStoreName(addFoodOrder.getStoreName()); } fo.setFoodName(addFoodOrder.getFoodName()); fo.setPrice(addFoodOrder.getPrice()); foodOrderRepository.save(fo); LOGGER.info("[createFoodOrdersInBatch][AddFoodOrderBatch][Success Save One Order][FoodOrderId: {}]", fo.getOrderId()); Delivery delivery = new Delivery(); delivery.setFoodName(addFoodOrder.getFoodName()); delivery.setOrderId(UUID.fromString(addFoodOrder.getOrderId())); delivery.setStationName(addFoodOrder.getStationName()); delivery.setStoreName(addFoodOrder.getStoreName()); String deliveryJson = JsonUtils.object2Json(delivery); deliveryJsons.add(deliveryJson); } // 批量发送消息 for(String deliveryJson: deliveryJsons) { LOGGER.info("[createFoodOrdersInBatch][AddFoodOrder][delivery info send to mq][delivery info: {}]", deliveryJson); try { sender.send(deliveryJson); } catch (Exception e) { LOGGER.error("[createFoodOrdersInBatch][AddFoodOrder][send delivery info to mq error][exception: {}]", e.toString()); } } return new Response<>(1, success, null); } @Override public Response createFoodOrder(FoodOrder addFoodOrder, HttpHeaders headers) { FoodOrder fo = foodOrderRepository.findByOrderId(addFoodOrder.getOrderId()); if (fo != null) { FoodServiceImpl.LOGGER.error("[createFoodOrder][AddFoodOrder][Order Id Has Existed][OrderId: {}]", addFoodOrder.getOrderId()); return new Response<>(0, "Order Id Has Existed.", null); } else { fo = new FoodOrder(); fo.setId(UUID.randomUUID().toString()); fo.setOrderId(addFoodOrder.getOrderId()); fo.setFoodType(addFoodOrder.getFoodType()); if (addFoodOrder.getFoodType() == 2) { fo.setStationName(addFoodOrder.getStationName()); fo.setStoreName(addFoodOrder.getStoreName()); } fo.setFoodName(addFoodOrder.getFoodName()); fo.setPrice(addFoodOrder.getPrice()); foodOrderRepository.save(fo); FoodServiceImpl.LOGGER.info("[createFoodOrder][AddFoodOrder Success]"); Delivery delivery = new Delivery(); delivery.setFoodName(addFoodOrder.getFoodName()); delivery.setOrderId(UUID.fromString(addFoodOrder.getOrderId())); delivery.setStationName(addFoodOrder.getStationName()); delivery.setStoreName(addFoodOrder.getStoreName()); String deliveryJson = JsonUtils.object2Json(delivery); LOGGER.info("[createFoodOrder][AddFoodOrder, delivery info send to mq][delivery info: {}]", deliveryJson); try { sender.send(deliveryJson); } catch (Exception e) { LOGGER.error("[createFoodOrder][AddFoodOrder][send delivery info to mq error][exception: {}]", e.toString()); } return new Response<>(1, success, fo); } } @Transactional @Override public Response deleteFoodOrder(String orderId, HttpHeaders headers) { FoodOrder foodOrder = foodOrderRepository.findByOrderId(UUID.fromString(orderId).toString()); if (foodOrder == null) { FoodServiceImpl.LOGGER.error("[deleteFoodOrder][Cancel FoodOrder][Order Id Is Non-Existent][orderId: {}]", orderId); return new Response<>(0, orderIdNotExist, null); } else { // foodOrderRepository.deleteFoodOrderByOrderId(UUID.fromString(orderId)); foodOrderRepository.deleteFoodOrderByOrderId(orderId); FoodServiceImpl.LOGGER.info("[deleteFoodOrder][Cancel FoodOrder Success]"); return new Response<>(1, success, null); } } @Override public Response findAllFoodOrder(HttpHeaders headers) { List<FoodOrder> foodOrders = foodOrderRepository.findAll(); if (foodOrders != null && !foodOrders.isEmpty()) { return new Response<>(1, success, foodOrders); } else { FoodServiceImpl.LOGGER.error("[findAllFoodOrder][Find all food order error: {}]", "No Content"); return new Response<>(0, "No Content", null); } } @Override public Response updateFoodOrder(FoodOrder updateFoodOrder, HttpHeaders headers) { FoodOrder fo = foodOrderRepository.findById(updateFoodOrder.getId()).orElse(null); if (fo == null) { FoodServiceImpl.LOGGER.info("[updateFoodOrder][Update FoodOrder][Order Id Is Non-Existent][orderId: {}]", updateFoodOrder.getOrderId()); return new Response<>(0, orderIdNotExist, null); } else { fo.setFoodType(updateFoodOrder.getFoodType()); if (updateFoodOrder.getFoodType() == 1) { fo.setStationName(updateFoodOrder.getStationName()); fo.setStoreName(updateFoodOrder.getStoreName()); } fo.setFoodName(updateFoodOrder.getFoodName()); fo.setPrice(updateFoodOrder.getPrice()); foodOrderRepository.save(fo); FoodServiceImpl.LOGGER.info("[updateFoodOrder][Update FoodOrder Success]"); return new Response<>(1, "Success", fo); } } @Override public Response findByOrderId(String orderId, HttpHeaders headers) { FoodOrder fo = foodOrderRepository.findByOrderId(UUID.fromString(orderId).toString()); if (fo != null) { FoodServiceImpl.LOGGER.info("[findByOrderId][Find Order by id Success][orderId: {}]", orderId); return new Response<>(1, success, fo); } else { FoodServiceImpl.LOGGER.warn("[findByOrderId][Find Order by id][Order Id Is Non-Existent][orderId: {}]", orderId); return new Response<>(0, orderIdNotExist, null); } } @Override public Response getAllFood(String date, String startStation, String endStation, String tripId, HttpHeaders headers) { FoodServiceImpl.LOGGER.info("[getAllFood][get All Food with info][data:{} start:{} end:{} tripid:{}]", date, startStation, endStation, tripId); AllTripFood allTripFood = new AllTripFood(); if (null == tripId || tripId.length() <= 2) { FoodServiceImpl.LOGGER.error("[getAllFood][Get the Get Food Request Failed][Trip id is not suitable][date: {}, tripId: {}]", date, tripId); return new Response<>(0, "Trip id is not suitable", null); } // need return this tow element List<Food> trainFoodList = null; Map<String, List<StationFoodStore>> foodStoreListMap = new HashMap<>(); /**--------------------------------------------------------------------------------------*/ HttpEntity requestEntityGetTrainFoodListResult = new HttpEntity(null); String train_food_service_url = getServiceUrl("ts-train-food-service"); ResponseEntity<Response<List<Food>>> reGetTrainFoodListResult = restTemplate.exchange( train_food_service_url + "/api/v1/trainfoodservice/trainfoods/" + tripId, HttpMethod.GET, requestEntityGetTrainFoodListResult, new ParameterizedTypeReference<Response<List<Food>>>() { }); List<Food> trainFoodListResult = reGetTrainFoodListResult.getBody().getData(); if (trainFoodListResult != null) { trainFoodList = trainFoodListResult; FoodServiceImpl.LOGGER.info("[getAllFood][Get Train Food List!]"); } else { FoodServiceImpl.LOGGER.error("[getAllFood][reGetTrainFoodListResult][Get the Get Food Request Failed!][date: {}, tripId: {}]", date, tripId); return new Response<>(0, "Get the Get Food Request Failed!", null); } //车次途经的车站 /**--------------------------------------------------------------------------------------*/ HttpEntity requestEntityGetRouteResult = new HttpEntity(null, null); String travel_service_url = getServiceUrl("ts-travel-service"); ResponseEntity<Response<Route>> reGetRouteResult = restTemplate.exchange( travel_service_url + "/api/v1/travelservice/routes/" + tripId, HttpMethod.GET, requestEntityGetRouteResult, new ParameterizedTypeReference<Response<Route>>() { }); Response<Route> stationResult = reGetRouteResult.getBody(); if (stationResult.getStatus() == 1) { Route route = stationResult.getData(); List<String> stations = route.getStations(); //去除不经过的站,如果起点终点有的话 if (null != startStation && !"".equals(startStation)) { /**--------------------------------------------------------------------------------------*/ for (int i = 0; i < stations.size(); i++) { if (stations.get(i).equals(startStation)) { break; } else { stations.remove(i); } } } if (null != endStation && !"".equals(endStation)) { /**--------------------------------------------------------------------------------------*/ for (int i = stations.size() - 1; i >= 0; i--) { if (stations.get(i).equals(endStation)) { break; } else { stations.remove(i); } } } HttpEntity requestEntityFoodStoresListResult = new HttpEntity(stations, null); String station_food_service_url = getServiceUrl("ts-station-food-service"); ResponseEntity<Response<List<StationFoodStore>>> reFoodStoresListResult = restTemplate.exchange( station_food_service_url + "/api/v1/stationfoodservice/stationfoodstores", HttpMethod.POST, requestEntityFoodStoresListResult, new ParameterizedTypeReference<Response<List<StationFoodStore>>>() { }); List<StationFoodStore> stationFoodStoresListResult = reFoodStoresListResult.getBody().getData(); if (stationFoodStoresListResult != null && !stationFoodStoresListResult.isEmpty()) { for (String station : stations) { List<StationFoodStore> res = stationFoodStoresListResult.stream() .filter(stationFoodStore -> (stationFoodStore.getStationName().equals(station))) .collect(Collectors.toList()); foodStoreListMap.put(station, res); } } else { FoodServiceImpl.LOGGER.error("[getAllFood][Get the Get Food Request Failed!][foodStoresListResult is null][date: {}, tripId: {}]", date, tripId); return new Response<>(0, "Get All Food Failed", allTripFood); } } else { FoodServiceImpl.LOGGER.error("[getAllFood][Get the Get Food Request Failed!][station status error][date: {}, tripId: {}]", date, tripId); return new Response<>(0, "Get All Food Failed", allTripFood); } allTripFood.setTrainFoodList(trainFoodList); allTripFood.setFoodStoreListMap(foodStoreListMap); return new Response<>(1, "Get All Food Success", allTripFood); } }
14,510
45.361022
161
java
train-ticket
train-ticket-master/ts-food-service/src/test/java/adminorder/controller/FoodControllerTest.java
package adminorder.controller; import com.alibaba.fastjson.JSONObject; import edu.fudan.common.util.Response; import foodsearch.controller.FoodController; import foodsearch.entity.FoodOrder; import foodsearch.service.FoodService; 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 FoodControllerTest { @InjectMocks private FoodController foodController; @Mock private FoodService foodService; private MockMvc mockMvc; private Response response = new Response(); @Before public void setUp() { MockitoAnnotations.initMocks(this); mockMvc = MockMvcBuilders.standaloneSetup(foodController).build(); } @Test public void testHome() throws Exception { mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/foodservice/welcome")) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.content().string("Welcome to [ Food Service ] !")); } @Test public void testFindAllFoodOrder() throws Exception { Mockito.when(foodService.findAllFoodOrder(Mockito.any(HttpHeaders.class))).thenReturn(response); String result = mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/foodservice/orders")) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } @Test public void testCreateFoodOrder() throws Exception { FoodOrder addFoodOrder = new FoodOrder(); Mockito.when(foodService.createFoodOrder(Mockito.any(FoodOrder.class), Mockito.any(HttpHeaders.class))).thenReturn(response); String requestJson = JSONObject.toJSONString(addFoodOrder); String result = mockMvc.perform(MockMvcRequestBuilders.post("/api/v1/foodservice/orders").contentType(MediaType.APPLICATION_JSON).content(requestJson)) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } @Test public void testUpdateFoodOrder() throws Exception { FoodOrder updateFoodOrder = new FoodOrder(); Mockito.when(foodService.updateFoodOrder(Mockito.any(FoodOrder.class), Mockito.any(HttpHeaders.class))).thenReturn(response); String requestJson = JSONObject.toJSONString(updateFoodOrder); String result = mockMvc.perform(MockMvcRequestBuilders.put("/api/v1/foodservice/orders").contentType(MediaType.APPLICATION_JSON).content(requestJson)) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } @Test public void testDeleteFoodOrder() throws Exception { Mockito.when(foodService.deleteFoodOrder(Mockito.anyString(), Mockito.any(HttpHeaders.class))).thenReturn(response); String result = mockMvc.perform(MockMvcRequestBuilders.delete("/api/v1/foodservice/orders/order_id")) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } @Test public void testFindFoodOrderByOrderId() throws Exception { Mockito.when(foodService.findByOrderId(Mockito.anyString(), Mockito.any(HttpHeaders.class))).thenReturn(response); String result = mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/foodservice/orders/order_id")) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } @Test public void testGetAllFood() throws Exception { Mockito.when(foodService.getAllFood(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.any(HttpHeaders.class))).thenReturn(response); String result = mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/foodservice/foods/date/start_station/end_station/trip_id")) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } }
5,094
47.066038
182
java
train-ticket
train-ticket-master/ts-food-service/src/test/java/adminorder/service/FoodServiceImplTest.java
package adminorder.service; import edu.fudan.common.util.Response; import foodsearch.entity.FoodOrder; import foodsearch.repository.FoodOrderRepository; import foodsearch.service.FoodServiceImpl; 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; import java.util.Optional; import java.util.UUID; @RunWith(JUnit4.class) public class FoodServiceImplTest { @InjectMocks private FoodServiceImpl foodServiceImpl; @Mock private FoodOrderRepository foodOrderRepository; private HttpHeaders headers = new HttpHeaders(); @Before public void setUp() { MockitoAnnotations.initMocks(this); } @Test public void testCreateFoodOrder1() { FoodOrder fo = new FoodOrder(); Mockito.when(foodOrderRepository.findByOrderId(Mockito.any(UUID.class).toString())).thenReturn(fo); Response result = foodServiceImpl.createFoodOrder(fo, headers); Assert.assertEquals(new Response<>(0, "Order Id Has Existed.", null), result); } @Test public void testCreateFoodOrder2() { FoodOrder fo = new FoodOrder(UUID.randomUUID().toString(), UUID.randomUUID().toString(), 2, "station_name", "store_name", "food_name", 3.0); Mockito.when(foodOrderRepository.findByOrderId(Mockito.any(UUID.class).toString())).thenReturn(null); Mockito.when(foodOrderRepository.save(Mockito.any(FoodOrder.class))).thenReturn(null); Response result = foodServiceImpl.createFoodOrder(fo, headers); Assert.assertEquals("Success.", result.getMsg()); } @Test public void testDeleteFoodOrder1() { UUID orderId = UUID.randomUUID(); Mockito.when(foodOrderRepository.findByOrderId(Mockito.any(UUID.class).toString())).thenReturn(null); Response result = foodServiceImpl.deleteFoodOrder(orderId.toString(), headers); Assert.assertEquals(new Response<>(0, "Order Id Is Non-Existent.", null), result); } @Test public void testDeleteFoodOrder2() { UUID orderId = UUID.randomUUID(); FoodOrder foodOrder = new FoodOrder(); Mockito.when(foodOrderRepository.findByOrderId(Mockito.any(UUID.class).toString())).thenReturn(foodOrder); Mockito.doNothing().doThrow(new RuntimeException()).when(foodOrderRepository).deleteFoodOrderByOrderId(Mockito.any(UUID.class).toString()); Response result = foodServiceImpl.deleteFoodOrder(orderId.toString(), headers); Assert.assertEquals(new Response<>(1, "Success.", null), result); } @Test public void testFindAllFoodOrder1() { List<FoodOrder> foodOrders = new ArrayList<>(); foodOrders.add(new FoodOrder()); Mockito.when(foodOrderRepository.findAll()).thenReturn(foodOrders); Response result = foodServiceImpl.findAllFoodOrder(headers); Assert.assertEquals(new Response<>(1, "Success.", foodOrders), result); } @Test public void testFindAllFoodOrder2() { Mockito.when(foodOrderRepository.findAll()).thenReturn(null); Response result = foodServiceImpl.findAllFoodOrder(headers); Assert.assertEquals(new Response<>(0, "No Content", null), result); } @Test public void testUpdateFoodOrder1() { FoodOrder updateFoodOrder = new FoodOrder(); Mockito.when(foodOrderRepository.findById(Mockito.any(UUID.class).toString())).thenReturn(null); Response result = foodServiceImpl.updateFoodOrder(updateFoodOrder, headers); Assert.assertEquals(new Response<>(0, "Order Id Is Non-Existent.", null), result); } @Test public void testUpdateFoodOrder2() { FoodOrder updateFoodOrder = new FoodOrder(UUID.randomUUID().toString(), UUID.randomUUID().toString(), 1, "station_name", "store_name", "food_name", 3.0); Mockito.when(foodOrderRepository.findById(Mockito.any(UUID.class).toString())).thenReturn(Optional.of(updateFoodOrder)); Mockito.when(foodOrderRepository.save(Mockito.any(FoodOrder.class))).thenReturn(null); Response result = foodServiceImpl.updateFoodOrder(updateFoodOrder, headers); Assert.assertEquals(new Response<>(1, "Success", updateFoodOrder), result); } @Test public void testFindByOrderId1() { UUID orderId = UUID.randomUUID(); FoodOrder fo = new FoodOrder(); Mockito.when(foodOrderRepository.findByOrderId(Mockito.any(UUID.class).toString())).thenReturn(fo); Response result = foodServiceImpl.findByOrderId(orderId.toString(), headers); Assert.assertEquals(new Response<>(1, "Success.", fo), result); } @Test public void testFindByOrderId2() { UUID orderId = UUID.randomUUID(); Mockito.when(foodOrderRepository.findByOrderId(Mockito.any(UUID.class).toString())).thenReturn(null); Response result = foodServiceImpl.findByOrderId(orderId.toString(), headers); Assert.assertEquals(new Response<>(0, "Order Id Is Non-Existent.", null), result); } @Test public void testGetAllFood() { } }
5,309
39.846154
161
java
train-ticket
train-ticket-master/ts-gateway-service/src/main/java/gateway/GatewayApplication.java
package gateway; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.integration.annotation.IntegrationComponentScan; import org.springframework.scheduling.annotation.EnableAsync; @SpringBootApplication @EnableAspectJAutoProxy(proxyTargetClass = true) @EnableAsync @IntegrationComponentScan @EnableDiscoveryClient public class GatewayApplication { public static void main(String[] args) { SpringApplication.run(GatewayApplication.class, args); } }
705
32.619048
75
java
train-ticket
train-ticket-master/ts-gateway-service/src/main/java/gateway/GatewayConfiguration.java
package gateway; import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayFlowRule; import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayRuleManager; import com.alibaba.csp.sentinel.adapter.gateway.sc.SentinelGatewayFilter; import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler; import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager; import com.alibaba.csp.sentinel.adapter.gateway.sc.exception.SentinelGatewayBlockExceptionHandler; import com.alibaba.csp.sentinel.slots.block.RuleConstant; import org.springframework.beans.factory.ObjectProvider; import org.springframework.cloud.gateway.filter.GlobalFilter; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.codec.ServerCodecConfigurer; import org.springframework.web.reactive.function.BodyInserters; import org.springframework.web.reactive.function.server.ServerResponse; import org.springframework.web.reactive.result.view.ViewResolver; import javax.annotation.PostConstruct; import java.util.*; /** * 网关配置类 * * <p>主要是<a href="https://sentinelguard.io/zh-cn/docs/api-gateway-flow-control.html">基于sentinel的网关限流策略配置</a></p> * * @author Akasaka Isami * @since 2022-06-30 15:13:58 */ @Configuration public class GatewayConfiguration { private final List<ViewResolver> viewResolvers; private final ServerCodecConfigurer serverCodecConfigurer; public GatewayConfiguration(ObjectProvider<List<ViewResolver>> viewResolversProvider, ServerCodecConfigurer serverCodecConfigurer) { this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList); this.serverCodecConfigurer = serverCodecConfigurer; } /** * 配置限流的异常处理器 * * @return 限流的异常处理器 */ @Bean @Order(Ordered.HIGHEST_PRECEDENCE) public SentinelGatewayBlockExceptionHandler sentinelGatewayBlockExceptionHandler() { // Register the block exception handler for Spring Cloud Gateway. return new SentinelGatewayBlockExceptionHandler(viewResolvers, serverCodecConfigurer); } /** * 初始化一个限流的过滤器 * * @return 限流过滤器 */ @Bean @Order(-1) public GlobalFilter sentinelGatewayFilter() { return new SentinelGatewayFilter(); } /** * 配置初始化的限流参数 */ @PostConstruct public void doInit() { initGatewayRules(); // initBlockHandlers(); System.out.println("===== begin to do flow control"); System.out.println("only 20 requests per second can pass"); } /** * 注册函数用于实现自定义的逻辑处理被限流的请求 * * <p>默认是返回错误信息: “Blocked by Sentinel: FlowException”。 这里自定义了异常处理,封装了自然语句。</p> */ private void initBlockHandlers() { BlockRequestHandler blockRequestHandler = (serverWebExchange, throwable) -> { Map<Object, Object> map = new HashMap<>(); map.put("code", 0); map.put("message", "接口被限流了"); return ServerResponse.status(HttpStatus.OK). contentType(MediaType.APPLICATION_JSON_UTF8). body(BodyInserters.fromObject(map)); }; GatewayCallbackManager.setBlockHandler(blockRequestHandler); } /** * 初始化流量控制规则 * * <p>Sentinal 的流量控制只能基于 route 或自定义 api 分组,这里的限流还是基于 application.yml 中定义的路由(即每个服务)采用 QPS 流量控制策略。 * 当前是简单的对转发到 admin-basic-info-service 服务的流量做了QPS限制,每秒不超过20个请求。</p> */ private void initGatewayRules() { Set<GatewayFlowRule> rules = new HashSet<>(); // 对于转发到 admin-basic-info 的请求 set limit qps to 20 // qps 超过 20 直接拒绝 rules.add(new GatewayFlowRule("admin-basic-info") //资源名称,对应路由 id .setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT) .setCount(20) // 限流qps阈值 .setIntervalSec(1) // 统计时间窗口,单位是秒,默认是 1 秒 ); GatewayRuleManager.loadRules(rules); } }
4,198
33.702479
112
java
train-ticket
train-ticket-master/ts-inside-payment-service/src/main/java/inside_payment/InsidePaymentApplication.java
package inside_payment; 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 InsidePaymentApplication { public static void main(String[] args) { SpringApplication.run(InsidePaymentApplication.class, args); } @LoadBalanced @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); } }
1,201
33.342857
75
java
train-ticket
train-ticket-master/ts-inside-payment-service/src/main/java/inside_payment/async/AsyncTask.java
package inside_payment.async; import java.util.concurrent.Future; import inside_payment.entity.OutsidePaymentInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.AsyncResult; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; /** * @author fdse */ @Component public class AsyncTask { @Autowired private RestTemplate restTemplate; private static final Logger LOGGER = LoggerFactory.getLogger(AsyncTask.class); @Async("mySimpleAsync") public Future<Boolean> sendAsyncCallToPaymentService(OutsidePaymentInfo outsidePaymentInfo) { AsyncTask.LOGGER.info("[sendAsyncCallToPaymentService][Inside Payment Service, Async Task,Begin]"); Boolean value = restTemplate.getForObject("http://rest-service-external:16100/greet", Boolean.class); AsyncTask.LOGGER.info("[sendAsyncCallToPaymentService][Inside Payment Service, Async Task][Receive call Value directly back: {}]", value); return new AsyncResult<>(value); } }
1,206
35.575758
146
java
train-ticket
train-ticket-master/ts-inside-payment-service/src/main/java/inside_payment/async/ExecutorConfig.java
package inside_payment.async; import java.util.concurrent.Executor; import java.util.concurrent.ThreadPoolExecutor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; /** * @author fdse */ @Configuration @EnableAsync public class ExecutorConfig { private int corePoolSize = 10; private int maxPoolSize = 200; private int queueCapacity = 10; @Bean public Executor mySimpleAsync() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(corePoolSize); executor.setMaxPoolSize(maxPoolSize); executor.setQueueCapacity(queueCapacity); executor.setThreadNamePrefix("MySimpleExecutor-"); executor.initialize(); return executor; } @Bean public Executor myAsync() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(corePoolSize); executor.setMaxPoolSize(maxPoolSize); executor.setQueueCapacity(queueCapacity); executor.setThreadNamePrefix("MyExecutor-"); // rejection-policy:当pool已经达到max size的时候,如何处理新任务 // CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行 executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); executor.initialize(); return executor; } }
1,584
30.7
90
java
train-ticket
train-ticket-master/ts-inside-payment-service/src/main/java/inside_payment/config/SecurityConfig.java
package inside_payment.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/inside_pay_service/**").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,261
38.780488
130
java
train-ticket
train-ticket-master/ts-inside-payment-service/src/main/java/inside_payment/controller/InsidePaymentController.java
package inside_payment.controller; import inside_payment.entity.*; import inside_payment.service.InsidePaymentService; 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/inside_pay_service") public class InsidePaymentController { @Autowired public InsidePaymentService service; private static final Logger LOGGER = LoggerFactory.getLogger(InsidePaymentController.class); @GetMapping(path = "/welcome") public String home() { return "Welcome to [ InsidePayment Service ] !"; } @PostMapping(value = "/inside_payment") public HttpEntity pay(@RequestBody PaymentInfo info, @RequestHeader HttpHeaders headers) { InsidePaymentController.LOGGER.info("[pay][Inside Payment Service.Pay][Pay for: {}]", info.getOrderId()); return ok(service.pay(info, headers)); } @PostMapping(value = "/inside_payment/account") public HttpEntity createAccount(@RequestBody AccountInfo info, @RequestHeader HttpHeaders headers) { LOGGER.info("[createAccount][Create account][accountInfo: {}]", info); return ok(service.createAccount(info, headers)); } @GetMapping(value = "/inside_payment/{userId}/{money}") public HttpEntity addMoney(@PathVariable String userId, @PathVariable String money, @RequestHeader HttpHeaders headers) { LOGGER.info("[addMoney][add money][userId: {}, money: {}]", userId, money); return ok(service.addMoney(userId, money, headers)); } @GetMapping(value = "/inside_payment/payment") public HttpEntity queryPayment(@RequestHeader HttpHeaders headers) { LOGGER.info("[queryPayment][query payment]"); return ok(service.queryPayment(headers)); } @GetMapping(value = "/inside_payment/account") public HttpEntity queryAccount(@RequestHeader HttpHeaders headers) { LOGGER.info("[queryAccount][query account]"); return ok(service.queryAccount(headers)); } @GetMapping(value = "/inside_payment/drawback/{userId}/{money}") public HttpEntity drawBack(@PathVariable String userId, @PathVariable String money, @RequestHeader HttpHeaders headers) { LOGGER.info("[drawBack][draw back payment][userId: {}, money: {}]", userId, money); return ok(service.drawBack(userId, money, headers)); } @PostMapping(value = "/inside_payment/difference") public HttpEntity payDifference(@RequestBody PaymentInfo info, @RequestHeader HttpHeaders headers) { LOGGER.info("[payDifference][pay difference]"); return ok(service.payDifference(info, headers)); } @GetMapping(value = "/inside_payment/money") public HttpEntity queryAddMoney(@RequestHeader HttpHeaders headers) { LOGGER.info("[queryAddMoney][query add money]"); return ok(service.queryAddMoney(headers)); } }
3,148
37.876543
125
java
train-ticket
train-ticket-master/ts-inside-payment-service/src/main/java/inside_payment/entity/AccountInfo.java
package inside_payment.entity; import lombok.Data; /** * @author fdse */ @Data public class AccountInfo { private String userId; private String money; public AccountInfo(){ //Default Constructor } }
231
10.6
30
java
train-ticket
train-ticket-master/ts-inside-payment-service/src/main/java/inside_payment/entity/Balance.java
package inside_payment.entity; import lombok.Data; import javax.validation.Valid; import javax.validation.constraints.NotNull; /** * @author fdse */ @Data public class Balance { @Valid @NotNull private String userId; @Valid @NotNull private String balance; //NOSONAR public Balance(){ //Default Constructor this.userId = ""; this.balance = ""; } }
412
13.75
44
java
train-ticket
train-ticket-master/ts-inside-payment-service/src/main/java/inside_payment/entity/Money.java
package inside_payment.entity; import lombok.Data; import org.hibernate.annotations.GenericGenerator; import javax.persistence.*; //import org.springframework.data.mongodb.core.mapping.Document; import javax.validation.Valid; import javax.validation.constraints.NotNull; import java.util.UUID; /** * @author fdse */ @Data @Entity @GenericGenerator(name = "jpa-uuid", strategy = "org.hibernate.id.UUIDGenerator") @Table(name = "inside_money") public class Money { @Valid @NotNull @Id @Column(length = 36) @GeneratedValue(generator = "jpa-uuid") private String id; @Valid @NotNull @Column(length = 36) private String userId; @Valid @NotNull private String money; //NOSONAR @Valid @NotNull @Enumerated(EnumType.STRING) private MoneyType type; public Money(){ this.userId = ""; this.money = ""; } }
900
17.02
81
java
train-ticket
train-ticket-master/ts-inside-payment-service/src/main/java/inside_payment/entity/MoneyType.java
package inside_payment.entity; import java.io.Serializable; /** * @author fdse */ public enum MoneyType implements Serializable { /** * add money */ A("Add Money",1), /** * draw back money */ D("Draw Back Money",2); private String name; private int index; MoneyType(String name, int index) { this.name = name; this.index = index; } public static String getName(int index) { for (MoneyType type : MoneyType.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; } }
883
16
51
java
train-ticket
train-ticket-master/ts-inside-payment-service/src/main/java/inside_payment/entity/OutsidePaymentInfo.java
package inside_payment.entity; import lombok.Data; /** * @author fdse */ @Data public class OutsidePaymentInfo { public OutsidePaymentInfo(){ //Default Constructor } private String orderId; private String price; private String userId; }
271
13.315789
33
java
train-ticket
train-ticket-master/ts-inside-payment-service/src/main/java/inside_payment/entity/Payment.java
package inside_payment.entity; import lombok.Data; import org.hibernate.annotations.GenericGenerator; import javax.persistence.*; //import org.springframework.data.mongodb.core.mapping.Document; import javax.validation.Valid; import javax.validation.constraints.NotNull; import java.util.UUID; /** * @author fdse */ @Data @Entity @GenericGenerator(name = "jpa-uuid", strategy = "org.hibernate.id.UUIDGenerator") @Table(name="inside_payment") public class Payment { @Id @NotNull @Column(length = 36) @GeneratedValue(generator = "jpa-uuid") private String id; @NotNull @Valid @Column(length = 36) private String orderId; @NotNull @Valid @Column(length = 36) private String userId; @NotNull @Valid private String price; @NotNull @Valid @Enumerated(EnumType.STRING) private PaymentType type; public Payment(){ this.orderId = ""; this.userId = ""; this.price = ""; } }
988
17.660377
81
java
train-ticket
train-ticket-master/ts-inside-payment-service/src/main/java/inside_payment/entity/PaymentInfo.java
package inside_payment.entity; import lombok.AllArgsConstructor; import lombok.Data; /** * @author fdse */ @Data @AllArgsConstructor public class PaymentInfo { public PaymentInfo(){ //Default Constructor } private String userId; private String orderId; private String tripId; private String price; // public String getOrderId(){ // return this.orderId; // } }
411
15.48
33
java
train-ticket
train-ticket-master/ts-inside-payment-service/src/main/java/inside_payment/entity/PaymentType.java
package inside_payment.entity; import java.io.Serializable; /** * @author fdse */ public enum PaymentType implements Serializable { /** * payment */ P("Payment",1), /** * difference */ D("Difference",2), /** * outside payment */ O("Outside Payment",3), /** * difference and outside payment */ E("Difference & Outside Payment",4); private String name; private int index; PaymentType(String name, int index) { this.name = name; this.index = index; } public static String getName(int index) { for (PaymentType type : PaymentType.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; } }
1,040
16.35
55
java
train-ticket
train-ticket-master/ts-inside-payment-service/src/main/java/inside_payment/init/InitData.java
package inside_payment.init; import inside_payment.entity.*; import inside_payment.repository.AddMoneyRepository; import inside_payment.repository.PaymentRepository; import inside_payment.service.InsidePaymentService; 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 InsidePaymentService service; @Autowired PaymentRepository paymentRepository; @Autowired AddMoneyRepository addMoneyRepository; @Override public void run(String... args) throws Exception{ AccountInfo info1 = new AccountInfo(); info1.setUserId("4d2a46c7-71cb-4cf1-b5bb-b68406d9da6f"); info1.setMoney("10000"); service.createAccount(info1,null); Payment payment = new Payment(); payment.setId("5ad7750ba68b49c0a8c035276b321701"); payment.setOrderId("5ad7750b-a68b-49c0-a8c0-32776b067702"); payment.setPrice("100.0"); payment.setUserId("4d2a46c7-71cb-4cf1-b5bb-b68406d9da6f"); payment.setType(PaymentType.P); service.initPayment(payment,null); } }
1,256
28.928571
67
java
train-ticket
train-ticket-master/ts-inside-payment-service/src/main/java/inside_payment/repository/AddMoneyRepository.java
package inside_payment.repository; import inside_payment.entity.Money; //import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.data.repository.CrudRepository; import java.util.List; /** * @author fdse */ public interface AddMoneyRepository extends CrudRepository<Money,String> { /** * find by user id * * @param userId user id * @return List<Money> */ List<Money> findByUserId(String userId); /** * find all * * @return List<Money> */ @Override List<Money> findAll(); }
583
18.466667
74
java
train-ticket
train-ticket-master/ts-inside-payment-service/src/main/java/inside_payment/repository/PaymentRepository.java
package inside_payment.repository; import inside_payment.entity.Payment; //import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.data.repository.CrudRepository; import java.util.List; import java.util.Optional; /** * @author fdse */ public interface PaymentRepository extends CrudRepository<Payment,String> { /** * find by id * * @param id id * @return Payment */ Optional<Payment> findById(String id); /** * find by order id * * @param orderId order id * @return List<Payment> */ List<Payment> findByOrderId(String orderId); /** * find all * * @return List<Payment> */ @Override List<Payment> findAll(); /** * find by user id * * @param userId user id * @return List<Payment> */ List<Payment> findByUserId(String userId); }
906
18.297872
75
java
train-ticket
train-ticket-master/ts-inside-payment-service/src/main/java/inside_payment/service/InsidePaymentService.java
package inside_payment.service; import edu.fudan.common.util.Response; import inside_payment.entity.*; import org.springframework.http.HttpHeaders; /** * @author Administrator * @date 2017/6/20. */ public interface InsidePaymentService { /** * pay by payment info * * @param info payment info * @param headers headers * @return Response */ Response pay(PaymentInfo info , HttpHeaders headers); /** * create account by payment info * * @param info payment info * @param headers headers * @return Response */ Response createAccount(AccountInfo info, HttpHeaders headers); /** * add money with user id, money * * @param userId user id * @param money money * @param headers headers * @return Response */ Response addMoney(String userId,String money, HttpHeaders headers); /** * query payment info * * @param headers headers * @return Response */ Response queryPayment(HttpHeaders headers); /** * query account info * * @param headers headers * @return Response */ Response queryAccount(HttpHeaders headers); /** * drawback with user id, money * * @param userId user id * @param money money * @param headers headers * @return Response */ Response drawBack(String userId, String money, HttpHeaders headers); /** * pay difference by payment info * * @param info payment info * @param headers headers * @return Response */ Response payDifference(PaymentInfo info, HttpHeaders headers); /** * query add money * * @param headers headers * @return Response */ Response queryAddMoney(HttpHeaders headers); /** * init payment * * @param payment payment * @param headers headers * @return Response */ void initPayment(Payment payment, HttpHeaders headers); }
2,000
20.063158
72
java
train-ticket
train-ticket-master/ts-inside-payment-service/src/main/java/inside_payment/service/InsidePaymentServiceImpl.java
package inside_payment.service; import edu.fudan.common.entity.OrderStatus; import edu.fudan.common.entity.Order; import edu.fudan.common.util.Response; import inside_payment.entity.*; import inside_payment.repository.AddMoneyRepository; import inside_payment.repository.PaymentRepository; 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.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.math.BigDecimal; import java.util.*; /** * @author fdse */ @Service public class InsidePaymentServiceImpl implements InsidePaymentService { @Autowired public AddMoneyRepository addMoneyRepository; @Autowired public PaymentRepository paymentRepository; @Autowired public RestTemplate restTemplate; private static final Logger LOGGER = LoggerFactory.getLogger(InsidePaymentServiceImpl.class); private String getServiceUrl(String serviceName) { return "http://" + serviceName; } @Override public Response pay(PaymentInfo info, HttpHeaders headers) { String userId = info.getUserId(); String requestOrderURL = ""; String order_service_url = getServiceUrl("ts-order-service"); String order_other_service_url = getServiceUrl("ts-order-other-service"); if (info.getTripId().startsWith("G") || info.getTripId().startsWith("D")) { requestOrderURL = order_service_url + "/api/v1/orderservice/order/" + info.getOrderId(); } else { requestOrderURL = order_other_service_url + "/api/v1/orderOtherService/orderOther/" + info.getOrderId(); } HttpEntity requestGetOrderResults = new HttpEntity(headers); ResponseEntity<Response<Order>> reGetOrderResults = restTemplate.exchange( requestOrderURL, HttpMethod.GET, requestGetOrderResults, new ParameterizedTypeReference<Response<Order>>() { }); Response<Order> result = reGetOrderResults.getBody(); if (result.getStatus() == 1) { Order order = result.getData(); if (order.getStatus() != OrderStatus.NOTPAID.getCode()) { InsidePaymentServiceImpl.LOGGER.warn("[Inside Payment Service.pay][Order status Not allowed to Pay]"); return new Response<>(0, "Error. Order status Not allowed to Pay.", null); } Payment payment = new Payment(); payment.setOrderId(info.getOrderId()); payment.setPrice(order.getPrice()); payment.setUserId(userId); //判断一下账户余额够不够,不够要去站外支付 List<Payment> payments = paymentRepository.findByUserId(userId); List<Money> addMonies = addMoneyRepository.findByUserId(userId); Iterator<Payment> paymentsIterator = payments.iterator(); Iterator<Money> addMoniesIterator = addMonies.iterator(); BigDecimal totalExpand = new BigDecimal("0"); while (paymentsIterator.hasNext()) { Payment p = paymentsIterator.next(); totalExpand = totalExpand.add(new BigDecimal(p.getPrice())); } totalExpand = totalExpand.add(new BigDecimal(order.getPrice())); BigDecimal money = new BigDecimal("0"); while (addMoniesIterator.hasNext()) { Money addMoney = addMoniesIterator.next(); money = money.add(new BigDecimal(addMoney.getMoney())); } if (totalExpand.compareTo(money) > 0) { //站外支付 Payment outsidePaymentInfo = new Payment(); outsidePaymentInfo.setOrderId(info.getOrderId()); outsidePaymentInfo.setUserId(userId); outsidePaymentInfo.setPrice(order.getPrice()); /****这里调用第三方支付***/ HttpEntity requestEntityOutsidePaySuccess = new HttpEntity(outsidePaymentInfo, headers); String payment_service_url = getServiceUrl("ts-payment-service"); ResponseEntity<Response> reOutsidePaySuccess = restTemplate.exchange( payment_service_url + "/api/v1/paymentservice/payment", HttpMethod.POST, requestEntityOutsidePaySuccess, Response.class); Response outsidePaySuccess = reOutsidePaySuccess.getBody(); InsidePaymentServiceImpl.LOGGER.info("[Inside Payment Service.pay][outside Pay][Out pay result: {}]", outsidePaySuccess.toString()); if (outsidePaySuccess.getStatus() == 1) { payment.setType(PaymentType.O); paymentRepository.save(payment); setOrderStatus(info.getTripId(), info.getOrderId(), headers); return new Response<>(1, "Payment Success " + outsidePaySuccess.getMsg(), null); } else { LOGGER.error("Payment failed: {}", outsidePaySuccess.getMsg()); return new Response<>(0, "Payment Failed: " + outsidePaySuccess.getMsg(), null); } } else { setOrderStatus(info.getTripId(), info.getOrderId(), headers); payment.setType(PaymentType.P); paymentRepository.save(payment); } LOGGER.info("[Inside Payment Service.pay][Payment success][orderId: {}]", info.getOrderId()); return new Response<>(1, "Payment Success", null); } else { LOGGER.error("[Inside Payment Service.pay][Payment failed][Order not exists][orderId: {}]", info.getOrderId()); return new Response<>(0, "Payment Failed, Order Not Exists", null); } } @Override public Response createAccount(AccountInfo info, HttpHeaders headers) { List<Money> list = addMoneyRepository.findByUserId(info.getUserId()); if (list.isEmpty()) { Money addMoney = new Money(); addMoney.setMoney(info.getMoney()); addMoney.setUserId(info.getUserId()); addMoney.setType(MoneyType.A); addMoneyRepository.save(addMoney); return new Response<>(1, "Create Account Success", null); } else { LOGGER.error("[createAccount][Create Account Failed][Account already Exists][userId: {}]", info.getUserId()); return new Response<>(0, "Create Account Failed, Account already Exists", null); } } @Override public Response addMoney(String userId, String money, HttpHeaders headers) { if (addMoneyRepository.findByUserId(userId) != null) { Money addMoney = new Money(); addMoney.setUserId(userId); addMoney.setMoney(money); addMoney.setType(MoneyType.A); addMoneyRepository.save(addMoney); return new Response<>(1, "Add Money Success", null); } else { LOGGER.error("Add Money Failed, userId: {}", userId); return new Response<>(0, "Add Money Failed", null); } } @Override public Response queryAccount(HttpHeaders headers) { List<Balance> result = new ArrayList<>(); List<Money> list = addMoneyRepository.findAll(); Iterator<Money> ite = list.iterator(); HashMap<String, String> map = new HashMap<>(); while (ite.hasNext()) { Money addMoney = ite.next(); if (map.containsKey(addMoney.getUserId())) { BigDecimal money = new BigDecimal(map.get(addMoney.getUserId())); map.put(addMoney.getUserId(), money.add(new BigDecimal(addMoney.getMoney())).toString()); } else { map.put(addMoney.getUserId(), addMoney.getMoney()); } } Iterator ite1 = map.entrySet().iterator(); while (ite1.hasNext()) { Map.Entry entry = (Map.Entry) ite1.next(); String userId = (String) entry.getKey(); String money = (String) entry.getValue(); List<Payment> payments = paymentRepository.findByUserId(userId); Iterator<Payment> iterator = payments.iterator(); String totalExpand = "0"; while (iterator.hasNext()) { Payment p = iterator.next(); BigDecimal expand = new BigDecimal(totalExpand); totalExpand = expand.add(new BigDecimal(p.getPrice())).toString(); } String balanceMoney = new BigDecimal(money).subtract(new BigDecimal(totalExpand)).toString(); Balance balance = new Balance(); balance.setUserId(userId); balance.setBalance(balanceMoney); result.add(balance); } return new Response<>(1, "Success", result); } public String queryAccount(String userId, HttpHeaders headers) { List<Payment> payments = paymentRepository.findByUserId(userId); List<Money> addMonies = addMoneyRepository.findByUserId(userId); Iterator<Payment> paymentsIterator = payments.iterator(); Iterator<Money> addMoniesIterator = addMonies.iterator(); BigDecimal totalExpand = new BigDecimal("0"); while (paymentsIterator.hasNext()) { Payment p = paymentsIterator.next(); totalExpand.add(new BigDecimal(p.getPrice())); } BigDecimal money = new BigDecimal("0"); while (addMoniesIterator.hasNext()) { Money addMoney = addMoniesIterator.next(); money.add(new BigDecimal(addMoney.getMoney())); } return money.subtract(totalExpand).toString(); } @Override public Response queryPayment(HttpHeaders headers) { List<Payment> payments = paymentRepository.findAll(); if (payments != null && !payments.isEmpty()) { return new Response<>(1, "Query Payment Success", payments); }else { LOGGER.error("[queryPayment][Query payment failed][payment is null]"); return new Response<>(0, "Query Payment Failed", null); } } @Override public Response drawBack(String userId, String money, HttpHeaders headers) { if (addMoneyRepository.findByUserId(userId) != null) { Money addMoney = new Money(); addMoney.setUserId(userId); addMoney.setMoney(money); addMoney.setType(MoneyType.D); addMoneyRepository.save(addMoney); return new Response<>(1, "Draw Back Money Success", null); } else { LOGGER.error("[drawBack][Draw Back Money Failed][addMoneyRepository.findByUserId null][userId: {}]", userId); return new Response<>(0, "Draw Back Money Failed", null); } } @Override public Response payDifference(PaymentInfo info, HttpHeaders headers) { String userId = info.getUserId(); Payment payment = new Payment(); payment.setOrderId(info.getOrderId()); payment.setPrice(info.getPrice()); payment.setUserId(info.getUserId()); List<Payment> payments = paymentRepository.findByUserId(userId); List<Money> addMonies = addMoneyRepository.findByUserId(userId); Iterator<Payment> paymentsIterator = payments.iterator(); Iterator<Money> addMoniesIterator = addMonies.iterator(); BigDecimal totalExpand = new BigDecimal("0"); while (paymentsIterator.hasNext()) { Payment p = paymentsIterator.next(); totalExpand.add(new BigDecimal(p.getPrice())); } totalExpand.add(new BigDecimal(info.getPrice())); BigDecimal money = new BigDecimal("0"); while (addMoniesIterator.hasNext()) { Money addMoney = addMoniesIterator.next(); money.add(new BigDecimal(addMoney.getMoney())); } if (totalExpand.compareTo(money) > 0) { //站外支付 Payment outsidePaymentInfo = new Payment(); outsidePaymentInfo.setOrderId(info.getOrderId()); outsidePaymentInfo.setUserId(userId); outsidePaymentInfo.setPrice(info.getPrice()); HttpEntity requestEntityOutsidePaySuccess = new HttpEntity(outsidePaymentInfo, headers); String payment_service_url = getServiceUrl("ts-payment-service"); ResponseEntity<Response> reOutsidePaySuccess = restTemplate.exchange( payment_service_url + "/api/v1/paymentservice/payment", HttpMethod.POST, requestEntityOutsidePaySuccess, Response.class); Response outsidePaySuccess = reOutsidePaySuccess.getBody(); if (outsidePaySuccess.getStatus() == 1) { payment.setType(PaymentType.E); paymentRepository.save(payment); return new Response<>(1, "Pay Difference Success", null); } else { LOGGER.error("[payDifference][Pay Difference Failed][outsidePaySuccess status not 1][orderId: {}]", info.getOrderId()); return new Response<>(0, "Pay Difference Failed", null); } } else { payment.setType(PaymentType.E); paymentRepository.save(payment); } return new Response<>(1, "Pay Difference Success", null); } @Override public Response queryAddMoney(HttpHeaders headers) { List<Money> monies = addMoneyRepository.findAll(); if (monies != null && !monies.isEmpty()) { return new Response<>(1, "Query Money Success", null); } else { LOGGER.error("[queryAddMoney][Query money failed][addMoneyRepository.findAll null]"); return new Response<>(0, "Query money failed", null); } } private Response setOrderStatus(String tripId, String orderId, HttpHeaders headers) { //order paid and not collected int orderStatus = 1; Response result; if (tripId.startsWith("G") || tripId.startsWith("D")) { HttpEntity requestEntityModifyOrderStatusResult = new HttpEntity(headers); String order_service_url = getServiceUrl("ts-order-service"); ResponseEntity<Response> reModifyOrderStatusResult = restTemplate.exchange( order_service_url + "/api/v1/orderservice/order/status/" + orderId + "/" + orderStatus, HttpMethod.GET, requestEntityModifyOrderStatusResult, Response.class); result = reModifyOrderStatusResult.getBody(); } else { HttpEntity requestEntityModifyOrderStatusResult = new HttpEntity(headers); String order_other_service_url = getServiceUrl("ts-order-other-service"); ResponseEntity<Response> reModifyOrderStatusResult = restTemplate.exchange( order_other_service_url + "/api/v1/orderOtherService/orderOther/status/" + orderId + "/" + orderStatus, HttpMethod.GET, requestEntityModifyOrderStatusResult, Response.class); result = reModifyOrderStatusResult.getBody(); } return result; } @Override public void initPayment(Payment payment, HttpHeaders headers) { Optional<Payment> paymentTemp = paymentRepository.findById(payment.getId()); if (paymentTemp == null) { paymentRepository.save(payment); } else { InsidePaymentServiceImpl.LOGGER.error("[initPayment][paymentTemp Already Exists][paymentId: {}, orderId: {}]", payment.getId(), payment.getOrderId()); } } }
16,058
42.285714
162
java
train-ticket
train-ticket-master/ts-inside-payment-service/src/main/java/inside_payment/util/CookieUtil.java
package inside_payment.util; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.HashMap; import java.util.Map; /** * @author fdse */ public class CookieUtil { private CookieUtil() { throw new IllegalStateException("Utility class"); } public static void addCookie(HttpServletResponse response, String name, String value, int maxAge){ Cookie cookie = new Cookie(name,value); // against Cross-Site Scripting (XSS) attacks cookie.setHttpOnly(true); cookie.setPath("/"); if(maxAge>0) { cookie.setMaxAge(maxAge); } response.addCookie(cookie); } public static Cookie getCookieByName(HttpServletRequest request, String name){ Map<String,Cookie> cookieMap = readCookieMap(request); if(cookieMap.containsKey(name)){ return cookieMap.get(name); }else{ return null; } } private static Map<String,Cookie> readCookieMap(HttpServletRequest request){ Map<String,Cookie> cookieMap = new HashMap<>(); Cookie[] cookies = request.getCookies(); if(null!=cookies){ for(Cookie cookie : cookies){ cookieMap.put(cookie.getName(), cookie); } } return cookieMap; } }
1,385
27.285714
102
java
train-ticket
train-ticket-master/ts-inside-payment-service/src/test/java/inside_payment/controller/InsidePaymentControllerTest.java
package inside_payment.controller; import com.alibaba.fastjson.JSONObject; import edu.fudan.common.util.Response; import inside_payment.entity.AccountInfo; import inside_payment.entity.PaymentInfo; import inside_payment.service.InsidePaymentService; 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 InsidePaymentControllerTest { @InjectMocks private InsidePaymentController insidePaymentController; @Mock private InsidePaymentService service; private MockMvc mockMvc; private Response response = new Response(); @Before public void setUp() { MockitoAnnotations.initMocks(this); mockMvc = MockMvcBuilders.standaloneSetup(insidePaymentController).build(); } @Test public void testHome() throws Exception { mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/inside_pay_service/welcome")) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.content().string("Welcome to [ InsidePayment Service ] !")); } @Test public void testPay() throws Exception { PaymentInfo info = new PaymentInfo(); Mockito.when(service.pay(Mockito.any(PaymentInfo.class), Mockito.any(HttpHeaders.class))).thenReturn(response); String requestJson = JSONObject.toJSONString(info); String result = mockMvc.perform(MockMvcRequestBuilders.post("/api/v1/inside_pay_service/inside_payment").contentType(MediaType.APPLICATION_JSON).content(requestJson)) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } @Test public void testCreateAccount() throws Exception { AccountInfo info = new AccountInfo(); Mockito.when(service.createAccount(Mockito.any(AccountInfo.class), Mockito.any(HttpHeaders.class))).thenReturn(response); String requestJson = JSONObject.toJSONString(info); String result = mockMvc.perform(MockMvcRequestBuilders.post("/api/v1/inside_pay_service/inside_payment/account").contentType(MediaType.APPLICATION_JSON).content(requestJson)) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } @Test public void testAddMoney() throws Exception { Mockito.when(service.addMoney(Mockito.anyString(), Mockito.anyString(), Mockito.any(HttpHeaders.class))).thenReturn(response); String result = mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/inside_pay_service/inside_payment/user_id/money")) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } @Test public void testQueryPayment() throws Exception { Mockito.when(service.queryPayment(Mockito.any(HttpHeaders.class))).thenReturn(response); String result = mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/inside_pay_service/inside_payment/payment")) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } @Test public void testQueryAccount() throws Exception { Mockito.when(service.queryAccount(Mockito.any(HttpHeaders.class))).thenReturn(response); String result = mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/inside_pay_service/inside_payment/account")) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } @Test public void testDrawBack() throws Exception { Mockito.when(service.drawBack(Mockito.anyString(), Mockito.anyString(), Mockito.any(HttpHeaders.class))).thenReturn(response); String result = mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/inside_pay_service/inside_payment/drawback/user_id/money")) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } @Test public void testPayDifference() throws Exception { PaymentInfo info = new PaymentInfo(); Mockito.when(service.payDifference(Mockito.any(PaymentInfo.class), Mockito.any(HttpHeaders.class))).thenReturn(response); String requestJson = JSONObject.toJSONString(info); String result = mockMvc.perform(MockMvcRequestBuilders.post("/api/v1/inside_pay_service/inside_payment/difference").contentType(MediaType.APPLICATION_JSON).content(requestJson)) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } @Test public void testQueryAddMoney() throws Exception { Mockito.when(service.queryAddMoney(Mockito.any(HttpHeaders.class))).thenReturn(response); String result = mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/inside_pay_service/inside_payment/money")) .andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Assert.assertEquals(response, JSONObject.parseObject(result, Response.class)); } }
6,326
49.214286
185
java
train-ticket
train-ticket-master/ts-inside-payment-service/src/test/java/inside_payment/service/InsidePaymentServiceImplTest.java
package inside_payment.service; import edu.fudan.common.entity.Order; import edu.fudan.common.util.Response; import inside_payment.entity.*; import inside_payment.repository.AddMoneyRepository; import inside_payment.repository.PaymentRepository; 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; import java.util.ArrayList; import java.util.List; import static org.mockito.internal.verification.VerificationModeFactory.times; @RunWith(JUnit4.class) public class InsidePaymentServiceImplTest { @InjectMocks private InsidePaymentServiceImpl insidePaymentServiceImpl; @Mock private AddMoneyRepository addMoneyRepository; @Mock private PaymentRepository paymentRepository; @Mock private RestTemplate restTemplate; private HttpHeaders headers = new HttpHeaders(); HttpEntity httpEntity = new HttpEntity(headers); @Before public void setUp() { MockitoAnnotations.initMocks(this); } @Test public void testPay() { PaymentInfo info = new PaymentInfo("user_id", "order_id", "G", "1.0"); Order order = new Order(); order.setStatus(0); order.setPrice("1.0"); 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, httpEntity, new ParameterizedTypeReference<Response<Order>>() { })).thenReturn(re); List<Payment> payments = new ArrayList<>(); List<Money> monies = new ArrayList<>(); Money money = new Money(); money.setMoney("2.0"); monies.add(money); Mockito.when(paymentRepository.findByUserId(Mockito.anyString())).thenReturn(payments); Mockito.when(addMoneyRepository.findByUserId(Mockito.anyString())).thenReturn(monies); //mock setOrderStatus() Response response2 = new Response(1, "", null); ResponseEntity<Response> re2 = new ResponseEntity<>(response2, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-order-service:12031/api/v1/orderservice/order/status/" + "order_id" + "/" + 1, HttpMethod.GET, httpEntity, Response.class)).thenReturn(re2); Mockito.when(paymentRepository.save(Mockito.any(Payment.class))).thenReturn(null); Response result = insidePaymentServiceImpl.pay(info, headers); Assert.assertEquals(new Response<>(1, "Payment Success", null), result); } @Test public void testCreateAccount1() { AccountInfo info = new AccountInfo(); List<Money> list = new ArrayList<>(); Mockito.when(addMoneyRepository.findByUserId(Mockito.anyString())).thenReturn(list); Mockito.when(addMoneyRepository.save(Mockito.any(Money.class))).thenReturn(null); Response result = insidePaymentServiceImpl.createAccount(info, headers); Assert.assertEquals(new Response<>(1, "Create Account Success", null), result); } @Test public void testCreateAccount2() { AccountInfo info = new AccountInfo(); List<Money> list = new ArrayList<>(); list.add(new Money()); Mockito.when(addMoneyRepository.findByUserId(Mockito.anyString())).thenReturn(list); Response result = insidePaymentServiceImpl.createAccount(info, headers); Assert.assertEquals(new Response<>(0, "Create Account Failed, Account already Exists", null), result); } @Test public void testAddMoney1() { List<Money> list = new ArrayList<>(); Mockito.when(addMoneyRepository.findByUserId(Mockito.anyString())).thenReturn(list); Mockito.when(addMoneyRepository.save(Mockito.any(Money.class))).thenReturn(null); Response result = insidePaymentServiceImpl.addMoney("user_id", "money", headers); Assert.assertEquals(new Response<>(1, "Add Money Success", null), result); } @Test public void testAddMoney2() { Mockito.when(addMoneyRepository.findByUserId(Mockito.anyString())).thenReturn(null); Response result = insidePaymentServiceImpl.addMoney("user_id", "money", headers); Assert.assertEquals(new Response<>(0, "Add Money Failed", null), result); } @Test public void testQueryAccount() { List<Money> list = new ArrayList<>(); Mockito.when(addMoneyRepository.findAll()).thenReturn(list); Response result = insidePaymentServiceImpl.queryAccount(headers); Assert.assertEquals("Success", result.getMsg()); } @Test public void testQueryPayment1() { List<Payment> payments = new ArrayList<>(); payments.add(new Payment()); Mockito.when(paymentRepository.findAll()).thenReturn(payments); Response result = insidePaymentServiceImpl.queryPayment(headers); Assert.assertEquals(new Response<>(1, "Query Payment Success", payments), result); } @Test public void testQueryPayment2() { Mockito.when(paymentRepository.findAll()).thenReturn(null); Response result = insidePaymentServiceImpl.queryPayment(headers); Assert.assertEquals(new Response<>(0, "Query Payment Failed", null), result); } @Test public void testDrawBack1() { List<Money> list = new ArrayList<>(); Mockito.when(addMoneyRepository.findByUserId(Mockito.anyString())).thenReturn(list); Mockito.when(addMoneyRepository.save(Mockito.any(Money.class))).thenReturn(null); Response result = insidePaymentServiceImpl.drawBack("user_id", "money", headers); Assert.assertEquals(new Response<>(1, "Draw Back Money Success", null), result); } @Test public void testDrawBack2() { Mockito.when(addMoneyRepository.findByUserId(Mockito.anyString())).thenReturn(null); Response result = insidePaymentServiceImpl.drawBack("user_id", "money", headers); Assert.assertEquals(new Response<>(0, "Draw Back Money Failed", null), result); } @Test public void testPayDifference() { PaymentInfo info = new PaymentInfo("user_id", "order_id", "G", "1.0"); List<Payment> payments = new ArrayList<>(); List<Money> monies = new ArrayList<>(); Money money = new Money(); money.setMoney("2.0"); monies.add(money); Mockito.when(paymentRepository.findByUserId(Mockito.anyString())).thenReturn(payments); Mockito.when(addMoneyRepository.findByUserId(Mockito.anyString())).thenReturn(monies); Mockito.when(paymentRepository.save(Mockito.any(Payment.class))).thenReturn(null); Response result = insidePaymentServiceImpl.payDifference(info, headers); Assert.assertEquals(new Response<>(1, "Pay Difference Success", null), result); } @Test public void testQueryAddMoney1() { List<Money> monies = new ArrayList<>(); monies.add(new Money()); Mockito.when(addMoneyRepository.findAll()).thenReturn(monies); Response result = insidePaymentServiceImpl.queryAddMoney(headers); Assert.assertEquals(new Response<>(1, "Query Money Success", null), result); } @Test public void testQueryAddMoney2() { Mockito.when(addMoneyRepository.findAll()).thenReturn(null); Response result = insidePaymentServiceImpl.queryAddMoney(headers); Assert.assertEquals(new Response<>(0, "Query money failed", null), result); } @Test public void testInitPayment1() { Payment payment = new Payment(); Mockito.when(paymentRepository.findById(Mockito.anyString())).thenReturn(null); Mockito.when(paymentRepository.save(Mockito.any(Payment.class))).thenReturn(null); insidePaymentServiceImpl.initPayment(payment, headers); Mockito.verify(paymentRepository, times(1)).save(Mockito.any(Payment.class)); } @Test public void testInitPayment2() { Payment payment = new Payment(); Mockito.when(paymentRepository.findById(Mockito.anyString()).get()).thenReturn(payment); Mockito.when(paymentRepository.save(Mockito.any(Payment.class))).thenReturn(null); insidePaymentServiceImpl.initPayment(payment, headers); Mockito.verify(paymentRepository, times(0)).save(Mockito.any(Payment.class)); } }
8,806
40.938095
110
java
train-ticket
train-ticket-master/ts-notification-service/src/main/java/notification/NotificationApplication.java
package notification; 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.web.client.RestTemplate; import springfox.documentation.swagger2.annotations.EnableSwagger2; /** * @author fdse */ @SpringBootApplication @EnableSwagger2 @EnableDiscoveryClient public class NotificationApplication{ public static void main(String[] args) { SpringApplication.run(NotificationApplication.class, args); } @LoadBalanced @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); } }
899
31.142857
72
java
train-ticket
train-ticket-master/ts-notification-service/src/main/java/notification/config/EmailConfig.java
package notification.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.stereotype.Component; /** * @author fdse */ @Component @Configuration public class EmailConfig { @Autowired EmailProperties emailProperties; }
340
15.238095
62
java
train-ticket
train-ticket-master/ts-notification-service/src/main/java/notification/config/EmailProperties.java
package notification.config; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; /** * @author fdse */ @Component @ConfigurationProperties("email") public class EmailProperties { private String host; private String port; private String username; private String password; public void setHost(String host) { this.host = host; } public String getHost() { return host; } public void setPort(String port) { this.port = port; } public String getPort() { return port; } public void setUsername(String username) { this.username = username; } public String getUsername() { return username; } public void setPassword(String password) { this.password = password; } public String getPassword() { return password; } }
936
17.372549
75
java
train-ticket
train-ticket-master/ts-notification-service/src/main/java/notification/config/Queues.java
package notification.config; import org.springframework.amqp.core.Queue; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class Queues { public final static String queueName = "email"; @Bean public Queue emailQueue() { return new Queue(queueName); } }
366
20.588235
60
java
train-ticket
train-ticket-master/ts-notification-service/src/main/java/notification/config/SecurityConfig.java
package notification.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/notifyservice/**").permitAll() //.antMatchers("/api/v1/notifyservice/**").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,325
39.072289
130
java
train-ticket
train-ticket-master/ts-notification-service/src/main/java/notification/controller/NotificationController.java
package notification.controller; import notification.entity.NotifyInfo; import notification.mq.RabbitSend; import notification.service.NotificationService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpHeaders; import org.springframework.web.bind.annotation.*; /** * @author Wenvi * @date 2017/6/15 */ @RestController @RequestMapping("/api/v1/notifyservice") public class NotificationController { @Autowired NotificationService service; @Autowired RabbitSend sender; @Value("${test_send_mail_user}") String test_mail_user; @GetMapping(path = "/welcome") public String home() { return "Welcome to [ Notification Service ] !"; } @GetMapping("/test_send_mq") public boolean test_send() { sender.send("test"); return true; } @GetMapping("/test_send_mail") public boolean test_send_mail() { NotifyInfo notifyInfo = new NotifyInfo(); notifyInfo.setDate("Wed Jul 21 09:49:44 CST 2021"); notifyInfo.setEmail(test_mail_user); notifyInfo.setEndPlace("Test"); notifyInfo.setStartPlace("Test"); notifyInfo.setOrderNumber("111-111-111"); notifyInfo.setPrice("100"); notifyInfo.setSeatClass("1"); notifyInfo.setSeatNumber("1102"); notifyInfo.setStartTime("Sat May 04 07:00:00 CST 2013"); notifyInfo.setUsername("h10g"); service.preserveSuccess(notifyInfo, null); return true; } @PostMapping(value = "/notification/preserve_success") public boolean preserve_success(@RequestBody NotifyInfo info, @RequestHeader HttpHeaders headers) { return service.preserveSuccess(info, headers); } @PostMapping(value = "/notification/order_create_success") public boolean order_create_success(@RequestBody NotifyInfo info, @RequestHeader HttpHeaders headers) { return service.orderCreateSuccess(info, headers); } @PostMapping(value = "/notification/order_changed_success") public boolean order_changed_success(@RequestBody NotifyInfo info, @RequestHeader HttpHeaders headers) { return service.orderChangedSuccess(info, headers); } @PostMapping(value = "/notification/order_cancel_success") public boolean order_cancel_success(@RequestBody NotifyInfo info, @RequestHeader HttpHeaders headers) { return service.orderCancelSuccess(info, headers); } }
2,514
31.662338
108
java
train-ticket
train-ticket-master/ts-notification-service/src/main/java/notification/entity/Mail.java
package notification.entity; import lombok.Data; import java.util.Date; import java.util.List; import java.util.Map; /** * @author fdse */ @Data public class Mail { private String mailFrom; private String mailTo; private String mailCc; private String mailBcc; private String mailSubject; private String mailContent; private String contentType; private List < Object > attachments; private Map < String, Object > model; public Mail() { contentType = "text/plain"; } }
534
13.459459
41
java
train-ticket
train-ticket-master/ts-notification-service/src/main/java/notification/entity/NotifyInfo.java
package notification.entity; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.AllArgsConstructor; import lombok.Data; import javax.persistence.Column; import javax.persistence.Id; import javax.persistence.Entity; import org.hibernate.annotations.GenericGenerator; import java.util.UUID; import lombok.Data; import javax.persistence.Entity; /** * @author fdse */ @Data @AllArgsConstructor @Entity @GenericGenerator(name = "jpa-uuid", strategy = "org.hibernate.id.UUIDGenerator") @JsonIgnoreProperties(ignoreUnknown = true) public class NotifyInfo { public NotifyInfo(){ //Default Constructor } @Id @JsonIgnoreProperties(ignoreUnknown = true) @Column(length = 36) private String id; private Boolean sendStatus; 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; }
1,077
19.730769
81
java
train-ticket
train-ticket-master/ts-notification-service/src/main/java/notification/mq/RabbitReceive.java
package notification.mq; import edu.fudan.common.util.JsonUtils; import edu.fudan.common.util.Response; import notification.config.Queues; import notification.entity.Mail; import notification.entity.NotifyInfo; import notification.repository.NotifyRepository; import notification.service.MailService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.amqp.rabbit.annotation.RabbitHandler; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; import java.util.HashMap; import java.util.Map; import java.util.UUID; @Component public class RabbitReceive { private static final Logger logger = LoggerFactory.getLogger(RabbitReceive.class); @Autowired MailService mailService; @Autowired private RestTemplate restTemplate; @Autowired private NotifyRepository notifyRepository; @Value("${email_address:[email protected]}") String email; String username = "username"; String startPlace = "startPlace"; String endPlace = "endPlace"; String startTime = "startTime"; String seatClass = "seatClass"; String seatNumber = "seatNumber"; String date = "date"; String price = "price"; @RabbitListener(queues = Queues.queueName) public void process(String payload) { NotifyInfo info = JsonUtils.json2Object(payload, NotifyInfo.class); if (info == null) { logger.error("[process][json2Object][Receive email object is null, error]"); return; } logger.info("[process][Receive email object][info: {}]", info); Mail mail = new Mail(); mail.setMailFrom(email); mail.setMailTo(info.getEmail()); mail.setMailSubject("Preserve Success"); Map<String, Object> model = new HashMap<>(); model.put(username, info.getUsername()); model.put(startPlace,info.getStartPlace()); model.put(endPlace,info.getEndPlace()); model.put(startTime,info.getStartTime()); model.put(date,info.getDate()); model.put(seatClass,info.getSeatClass()); model.put(seatNumber,info.getSeatNumber()); model.put(price,info.getPrice()); mail.setModel(model); try { mailService.sendEmail(mail, "preserve_success.ftl"); logger.info("[process][Send email to user {} success]", username); info.setSendStatus(true); } catch (Exception e) { logger.error("[process][mailService.sendEmail][Send email error][Exception: {}]", e.getMessage()); info.setSendStatus(false); } info.setId(UUID.randomUUID().toString()); logger.info("[process][Save notify info object [{}] into database]", info.getId()); notifyRepository.save(info); } }
3,164
33.032258
110
java
train-ticket
train-ticket-master/ts-notification-service/src/main/java/notification/mq/RabbitSend.java
package notification.mq; import notification.config.Queues; import org.springframework.amqp.core.AmqpTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Component public class RabbitSend { @Autowired private AmqpTemplate rabbitTemplate; private static final Logger logger = LoggerFactory.getLogger(RabbitSend.class); public void send(String val) { logger.info("send val:" + val); this.rabbitTemplate.convertAndSend(Queues.queueName, val); } }
613
24.583333
83
java
train-ticket
train-ticket-master/ts-notification-service/src/main/java/notification/repository/NotifyRepository.java
package notification.repository; import notification.entity.NotifyInfo; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import java.util.List; import java.util.Optional; @Repository public interface NotifyRepository extends CrudRepository<NotifyInfo, String> { Optional<NotifyInfo> findById(String id); @Override List<NotifyInfo> findAll(); void deleteById(String id); }
455
20.714286
78
java
train-ticket
train-ticket-master/ts-notification-service/src/main/java/notification/service/MailService.java
package notification.service; import javax.mail.internet.MimeMessage; import notification.entity.Mail; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Service; import org.springframework.ui.freemarker.FreeMarkerTemplateUtils; import freemarker.template.Configuration; import freemarker.template.Template; /** * @author fdse */ @Service public class MailService { @Autowired private JavaMailSender sender; @Autowired @Qualifier("freeMarkerConfiguration") private Configuration freemarkerConfig; public void sendEmail(Mail mail,String template) throws Exception { MimeMessage message = sender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message); // Using a subfolder such as /templates here freemarkerConfig.setClassForTemplateLoading(this.getClass(), "/templates"); Template t = freemarkerConfig.getTemplate(template); String text = FreeMarkerTemplateUtils.processTemplateIntoString(t, mail.getModel()); helper.setTo(mail.getMailTo()); helper.setText(text, true); helper.setFrom(mail.getMailFrom()); helper.setSubject(mail.getMailSubject()); sender.send(message); } }
1,458
28.77551
92
java
train-ticket
train-ticket-master/ts-notification-service/src/main/java/notification/service/NotificationService.java
package notification.service; import notification.entity.NotifyInfo; import org.springframework.http.HttpHeaders; /** * @author Wenvi * @date 2017/6/15 */ public interface NotificationService { /** * preserve success with notify info * * @param info notify info * @param headers headers * @return boolean */ boolean preserveSuccess(NotifyInfo info, HttpHeaders headers); /**S * order create success with notify info * * @param info notify info * @param headers headers * @return boolean */ boolean orderCreateSuccess(NotifyInfo info, HttpHeaders headers); /** * order changed success with notify info * * @param info notify info * @param headers headers * @return boolean */ boolean orderChangedSuccess(NotifyInfo info, HttpHeaders headers); /** * order cancel success with notify info * * @param info notify info * @param headers headers * @return boolean */ boolean orderCancelSuccess(NotifyInfo info, HttpHeaders headers); }
1,089
21.708333
70
java
train-ticket
train-ticket-master/ts-notification-service/src/main/java/notification/service/NotificationServiceImpl.java
package notification.service; import notification.entity.Mail; import notification.entity.NotifyInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.stereotype.Service; import java.util.HashMap; import java.util.Map; /** * @author fdse */ @Service public class NotificationServiceImpl implements NotificationService{ @Autowired private JavaMailSender mailSender; @Autowired MailService mailService; private static final Logger LOGGER = LoggerFactory.getLogger(NotificationServiceImpl.class); String email = "[email protected]"; String username = "username"; String startPlace = "startPlace"; String endPlace = "endPlace"; String startTime = "startTime"; String seatClass = "seatClass"; String seatNumber = "seatNumber"; @Override public boolean preserveSuccess(NotifyInfo info, HttpHeaders headers){ Mail mail = new Mail(); mail.setMailFrom(email); mail.setMailTo(info.getEmail()); mail.setMailSubject("Preserve Success"); Map<String, Object> model = new HashMap<>(); model.put(username, info.getUsername()); model.put(startPlace,info.getStartPlace()); model.put(endPlace,info.getEndPlace()); model.put(startTime,info.getStartTime()); model.put("date",info.getDate()); model.put(seatClass,info.getSeatClass()); model.put(seatNumber,info.getSeatNumber()); model.put("price",info.getPrice()); mail.setModel(model); try { mailService.sendEmail(mail,"preserve_success.ftl"); return true; } catch (Exception e) { LOGGER.error("[preserveSuccess][mailService.sendEmai][Exception: {}]", e.getMessage()); return false; } } @Override public boolean orderCreateSuccess(NotifyInfo info, HttpHeaders headers){ Mail mail = new Mail(); mail.setMailFrom(email); mail.setMailTo(info.getEmail()); mail.setMailSubject("Order Create Success"); Map<String, Object> model = new HashMap<>(); model.put(username, info.getUsername()); model.put(startPlace,info.getStartPlace()); model.put(endPlace,info.getEndPlace()); model.put(startTime,info.getStartTime()); model.put("date",info.getDate()); model.put(seatClass,info.getSeatClass()); model.put(seatNumber,info.getSeatNumber()); model.put("orderNumber", info.getOrderNumber()); mail.setModel(model); try { mailService.sendEmail(mail,"order_create_success.ftl"); return true; } catch (Exception e) { LOGGER.error("[orderCreateSuccess][mailService.sendEmai][Exception: {}]", e.getMessage()); return false; } } @Override public boolean orderChangedSuccess(NotifyInfo info, HttpHeaders headers){ Mail mail = new Mail(); mail.setMailFrom(email); mail.setMailTo(info.getEmail()); mail.setMailSubject("Order Changed Success"); Map<String, Object> model = new HashMap<>(); model.put(username, info.getUsername()); model.put(startPlace,info.getStartPlace()); model.put(endPlace,info.getEndPlace()); model.put(startTime,info.getStartTime()); model.put("date",info.getDate()); model.put(seatClass,info.getSeatClass()); model.put(seatNumber,info.getSeatNumber()); model.put("orderNumber", info.getOrderNumber()); mail.setModel(model); try { mailService.sendEmail(mail,"order_changed_success.ftl"); return true; } catch (Exception e) { LOGGER.error("[orderChangedSuccess][mailService.sendEmai][Exception: {}]", e.getMessage()); return false; } } @Override public boolean orderCancelSuccess(NotifyInfo info, HttpHeaders headers){ Mail mail = new Mail(); mail.setMailFrom(email); mail.setMailTo(info.getEmail()); mail.setMailSubject("Order Cancel Success"); Map<String, Object> model = new HashMap<>(); model.put(username, info.getUsername()); model.put("price",info.getPrice()); mail.setModel(model); try { mailService.sendEmail(mail,"order_cancel_success.ftl"); return true; } catch (Exception e) { LOGGER.error("[orderCancelSuccess][mailService.sendEmai][Exception: {}]", e.getMessage()); return false; } } }
4,739
33.347826
103
java