src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
IsoTypeReader { public static float readFixedPoint88(ByteBuffer bb) { byte[] bytes = new byte[2]; bb.get(bytes); short result = 0; result |= ((bytes[0] << 8) & 0xFF00); result |= ((bytes[1]) & 0xFF); return ((float) result) / 256; } static long readUInt32BE(ByteBuffer bb); static long readUInt32(ByteBuffer bb); static int readUInt24(ByteBuffer bb); static int readUInt16(ByteBuffer bb); static int readUInt16BE(ByteBuffer bb); static int readUInt8(ByteBuffer bb); static int byte2int(byte b); static String readString(ByteBuffer byteBuffer); static String readString(ByteBuffer byteBuffer, int length); static long readUInt64(ByteBuffer byteBuffer); static double readFixedPoint1616(ByteBuffer bb); static double readFixedPoint0230(ByteBuffer bb); static float readFixedPoint88(ByteBuffer bb); static String readIso639(ByteBuffer bb); static String read4cc(ByteBuffer bb); }
@Test public void testFixedPoint88() throws IOException { final double fixedPointTest1 = 10.13; final double fixedPointTest2 = -10.13; ByteBuffer bb = ByteBuffer.allocate(4); IsoTypeWriter.writeFixedPoint88(bb, fixedPointTest1); IsoTypeWriter.writeFixedPoint88(bb, fixedPointTest2); bb.rewind(); Assert.assertEquals("fixedPointTest1", fixedPointTest1, IsoTypeReader.readFixedPoint88(bb), 1d / 256); Assert.assertEquals("fixedPointTest2", fixedPointTest2, IsoTypeReader.readFixedPoint88(bb), 1d / 256); }
IsoTypeReader { public static String read4cc(ByteBuffer bb) { bb.get(codeBytes); int result = ((codeBytes[0] << 24) & 0xFF000000); result |= ((codeBytes[1] << 16) & 0xFF0000); result |= ((codeBytes[2] << 8) & 0xFF00); result |= ((codeBytes[3]) & 0xFF); String code; if ((code = (String) codeCache.get(result)) != null) { return code; } else { try { code = new String(codeBytes, "ISO-8859-1"); codeCache.put(result, code); return code; } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } } static long readUInt32BE(ByteBuffer bb); static long readUInt32(ByteBuffer bb); static int readUInt24(ByteBuffer bb); static int readUInt16(ByteBuffer bb); static int readUInt16BE(ByteBuffer bb); static int readUInt8(ByteBuffer bb); static int byte2int(byte b); static String readString(ByteBuffer byteBuffer); static String readString(ByteBuffer byteBuffer, int length); static long readUInt64(ByteBuffer byteBuffer); static double readFixedPoint1616(ByteBuffer bb); static double readFixedPoint0230(ByteBuffer bb); static float readFixedPoint88(ByteBuffer bb); static String readIso639(ByteBuffer bb); static String read4cc(ByteBuffer bb); }
@Test public void testRead4cc() throws IOException { ByteBuffer bb = ByteBuffer.wrap("abcd".getBytes()); String code = IsoTypeReader.read4cc(bb); Assert.assertEquals(4, bb.position()); Assert.assertEquals("abcd", code); }
BitWriterBuffer { public void writeBits(int i, int numBits) { assert i <= ((1 << numBits)-1): String.format("Trying to write a value bigger (%s) than the number bits (%s) allows. " + "Please mask the value before writing it and make your code is really working as intended.", i, (1<<numBits)-1); int left = 8 - position % 8; if (numBits <= left) { int current = (buffer.get(initialPos + position / 8)); current = current < 0 ? current + 256 : current; current += i << (left - numBits); buffer.put(initialPos + position / 8, (byte) (current > 127 ? current - 256 : current)); position += numBits; } else { int bitsSecondWrite = numBits - left; writeBits(i >> bitsSecondWrite, left); writeBits(i & (1 << bitsSecondWrite) - 1, bitsSecondWrite); } buffer.position(initialPos + position / 8 + ((position % 8 > 0) ? 1 : 0)); } BitWriterBuffer(ByteBuffer buffer); void writeBits(int i, int numBits); }
@Test public void testWriteWithinBuffer() { ByteBuffer b = ByteBuffer.allocate(2); b.put((byte) 0); BitWriterBuffer bwb = new BitWriterBuffer(b); bwb.writeBits(15, 4); Assert.assertEquals("0000000011110000", toString(b)); } @Test public void testSimple() { ByteBuffer bb = ByteBuffer.allocate(4); BitWriterBuffer bitWriterBuffer = new BitWriterBuffer(bb); bitWriterBuffer.writeBits(15, 4); bb.rewind(); int test = IsoTypeReader.readUInt8(bb); Assert.assertEquals(15 << 4, test); } @Test public void testSimpleOnByteBorder() { ByteBuffer bb = ByteBuffer.allocate(4); BitWriterBuffer bitWriterBuffer = new BitWriterBuffer(bb); bitWriterBuffer.writeBits(15, 4); bitWriterBuffer.writeBits(15, 4); bitWriterBuffer.writeBits(15, 4); bb.rewind(); int test = IsoTypeReader.readUInt8(bb); Assert.assertEquals(255, test); test = IsoTypeReader.readUInt8(bb); Assert.assertEquals(15 << 4, test); } @Test public void testSimpleCrossByteBorder() { ByteBuffer bb = ByteBuffer.allocate(2); BitWriterBuffer bitWriterBuffer = new BitWriterBuffer(bb); bitWriterBuffer.writeBits(1, 4); bitWriterBuffer.writeBits(1, 5); bitWriterBuffer.writeBits(1, 3); Assert.assertEquals("0001000010010000", toString(bb)); } @Test public void testMultiByte() { ByteBuffer bb = ByteBuffer.allocate(4); BitWriterBuffer bitWriterBuffer = new BitWriterBuffer(bb); bitWriterBuffer.writeBits(0, 1); bitWriterBuffer.writeBits(65535, 16); bb.rewind(); int test = IsoTypeReader.readUInt8(bb); Assert.assertEquals(127, test); test = IsoTypeReader.readUInt8(bb); Assert.assertEquals(255, test); test = IsoTypeReader.readUInt8(bb); Assert.assertEquals(1 << 7, test); } @Test public void testPattern() { ByteBuffer bb = ByteBuffer.allocate(1); BitWriterBuffer bwb = new BitWriterBuffer(bb); bwb.writeBits(1, 1); bwb.writeBits(1, 2); bwb.writeBits(1, 3); bwb.writeBits(1, 2); Assert.assertEquals("10100101", toString(bb)); } @Test public void testWriterReaderRoundTrip() { ByteBuffer b = ByteBuffer.allocate(3); BitWriterBuffer bwb = new BitWriterBuffer(b); bwb.writeBits(1, 1); bwb.writeBits(1, 2); bwb.writeBits(1, 3); bwb.writeBits(1, 4); bwb.writeBits(1, 5); bwb.writeBits(7, 6); b.rewind(); Assert.assertEquals("101001000100001000111000", toString(b)); }
BindController { @RequestMapping(value = "/baseType") public String baseType(@RequestParam("age") int age) { return "age:" + age; } @RequestMapping(value = "/baseType") String baseType(@RequestParam("age") int age); @RequestMapping(value = "/baseType2") String baseType2(Integer age); @RequestMapping(value = "/array") String array(String[] name); @RequestMapping(value = "/object") String object(User user, Admin admin); @InitBinder("user") void initUser(WebDataBinder binder); @InitBinder("admin") void initAdmin(WebDataBinder binder); @RequestMapping(value = "list") String list(UserListForm userListForm); @RequestMapping(value = "set") String set(UserSetForm userSetForm); @RequestMapping(value = "map") String map(UserMapForm userMapForm); @RequestMapping(value = "json") String json(@RequestBody User user); @RequestMapping(value = "xml", consumes = MediaType.APPLICATION_XML_VALUE, produces = MediaType.APPLICATION_XML_VALUE) String xml(@RequestBody Admin admin); @RequestMapping(value = "date1") String date1(Date date1); @InitBinder("date1") void initDate1(WebDataBinder binder); @RequestMapping(value = "date2") String date2(Date date2); @GetMapping(value = "/book") String book(HttpServletRequest request); @GetMapping(value = "/subject/{subjectId}") String getSubject(@PathVariable("subjectId") String subjectId); @PostMapping(value = "/subject/{subjectId}") String postSubject(@PathVariable("subjectId") String subjectId); @DeleteMapping(value = "/subject/{subjectId}") String deleteSubject(@PathVariable("subjectId") String subjectId); @PutMapping(value = "/subject/{subjectId}") String putSubject(@PathVariable("subjectId") String subjectId); }
@Test public void baseType() throws Exception { MultiValueMap<String, String> params = new LinkedMultiValueMap<>(16); params.add("age", "20"); String response = mockMvc.perform(get("/baseType") .contentType(APPLICATION_JSON_UTF8) .params(params)) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsString(); System.out.println(response); }
BindController { @RequestMapping(value = "date2") public String date2(Date date2) { return Objects.nonNull(date2) ? date2.toString() : "绑定date2参数失败,date2为null"; } @RequestMapping(value = "/baseType") String baseType(@RequestParam("age") int age); @RequestMapping(value = "/baseType2") String baseType2(Integer age); @RequestMapping(value = "/array") String array(String[] name); @RequestMapping(value = "/object") String object(User user, Admin admin); @InitBinder("user") void initUser(WebDataBinder binder); @InitBinder("admin") void initAdmin(WebDataBinder binder); @RequestMapping(value = "list") String list(UserListForm userListForm); @RequestMapping(value = "set") String set(UserSetForm userSetForm); @RequestMapping(value = "map") String map(UserMapForm userMapForm); @RequestMapping(value = "json") String json(@RequestBody User user); @RequestMapping(value = "xml", consumes = MediaType.APPLICATION_XML_VALUE, produces = MediaType.APPLICATION_XML_VALUE) String xml(@RequestBody Admin admin); @RequestMapping(value = "date1") String date1(Date date1); @InitBinder("date1") void initDate1(WebDataBinder binder); @RequestMapping(value = "date2") String date2(Date date2); @GetMapping(value = "/book") String book(HttpServletRequest request); @GetMapping(value = "/subject/{subjectId}") String getSubject(@PathVariable("subjectId") String subjectId); @PostMapping(value = "/subject/{subjectId}") String postSubject(@PathVariable("subjectId") String subjectId); @DeleteMapping(value = "/subject/{subjectId}") String deleteSubject(@PathVariable("subjectId") String subjectId); @PutMapping(value = "/subject/{subjectId}") String putSubject(@PathVariable("subjectId") String subjectId); }
@Test public void date2() throws Exception { MultiValueMap<String, String> params = new LinkedMultiValueMap<>(16); params.add("date2", "2020-03-14"); String response = mockMvc.perform(get("/date2") .contentType(APPLICATION_JSON_UTF8) .params(params)) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsString(); System.out.println(response); }
BindController { @GetMapping(value = "/book") public String book(HttpServletRequest request) { String contentType = request.getContentType(); if (contentType == null) { return "book.default"; } String typeTxt = "zccoder/txt"; if (typeTxt.equalsIgnoreCase(contentType)) { return "book.txt"; } String typeHtml = "zccoder/html"; if (typeHtml.equalsIgnoreCase(contentType)) { return "book.html"; } return "book.default"; } @RequestMapping(value = "/baseType") String baseType(@RequestParam("age") int age); @RequestMapping(value = "/baseType2") String baseType2(Integer age); @RequestMapping(value = "/array") String array(String[] name); @RequestMapping(value = "/object") String object(User user, Admin admin); @InitBinder("user") void initUser(WebDataBinder binder); @InitBinder("admin") void initAdmin(WebDataBinder binder); @RequestMapping(value = "list") String list(UserListForm userListForm); @RequestMapping(value = "set") String set(UserSetForm userSetForm); @RequestMapping(value = "map") String map(UserMapForm userMapForm); @RequestMapping(value = "json") String json(@RequestBody User user); @RequestMapping(value = "xml", consumes = MediaType.APPLICATION_XML_VALUE, produces = MediaType.APPLICATION_XML_VALUE) String xml(@RequestBody Admin admin); @RequestMapping(value = "date1") String date1(Date date1); @InitBinder("date1") void initDate1(WebDataBinder binder); @RequestMapping(value = "date2") String date2(Date date2); @GetMapping(value = "/book") String book(HttpServletRequest request); @GetMapping(value = "/subject/{subjectId}") String getSubject(@PathVariable("subjectId") String subjectId); @PostMapping(value = "/subject/{subjectId}") String postSubject(@PathVariable("subjectId") String subjectId); @DeleteMapping(value = "/subject/{subjectId}") String deleteSubject(@PathVariable("subjectId") String subjectId); @PutMapping(value = "/subject/{subjectId}") String putSubject(@PathVariable("subjectId") String subjectId); }
@Test public void book() throws Exception { String contentType = "zccoder/txt"; String response = mockMvc.perform(get("/book") .contentType(contentType)) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsString(); System.out.println(response); }
BindController { @GetMapping(value = "/subject/{subjectId}") public String getSubject(@PathVariable("subjectId") String subjectId) { return "this is get method,subject:" + subjectId; } @RequestMapping(value = "/baseType") String baseType(@RequestParam("age") int age); @RequestMapping(value = "/baseType2") String baseType2(Integer age); @RequestMapping(value = "/array") String array(String[] name); @RequestMapping(value = "/object") String object(User user, Admin admin); @InitBinder("user") void initUser(WebDataBinder binder); @InitBinder("admin") void initAdmin(WebDataBinder binder); @RequestMapping(value = "list") String list(UserListForm userListForm); @RequestMapping(value = "set") String set(UserSetForm userSetForm); @RequestMapping(value = "map") String map(UserMapForm userMapForm); @RequestMapping(value = "json") String json(@RequestBody User user); @RequestMapping(value = "xml", consumes = MediaType.APPLICATION_XML_VALUE, produces = MediaType.APPLICATION_XML_VALUE) String xml(@RequestBody Admin admin); @RequestMapping(value = "date1") String date1(Date date1); @InitBinder("date1") void initDate1(WebDataBinder binder); @RequestMapping(value = "date2") String date2(Date date2); @GetMapping(value = "/book") String book(HttpServletRequest request); @GetMapping(value = "/subject/{subjectId}") String getSubject(@PathVariable("subjectId") String subjectId); @PostMapping(value = "/subject/{subjectId}") String postSubject(@PathVariable("subjectId") String subjectId); @DeleteMapping(value = "/subject/{subjectId}") String deleteSubject(@PathVariable("subjectId") String subjectId); @PutMapping(value = "/subject/{subjectId}") String putSubject(@PathVariable("subjectId") String subjectId); }
@Test public void getSubject() throws Exception { String subjectId = "111"; String response = mockMvc.perform(get("/subject/" + subjectId) .contentType(APPLICATION_JSON_UTF8)) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsString(); System.out.println(response); }
BindController { @PostMapping(value = "/subject/{subjectId}") public String postSubject(@PathVariable("subjectId") String subjectId) { return "this is post method,subject:" + subjectId; } @RequestMapping(value = "/baseType") String baseType(@RequestParam("age") int age); @RequestMapping(value = "/baseType2") String baseType2(Integer age); @RequestMapping(value = "/array") String array(String[] name); @RequestMapping(value = "/object") String object(User user, Admin admin); @InitBinder("user") void initUser(WebDataBinder binder); @InitBinder("admin") void initAdmin(WebDataBinder binder); @RequestMapping(value = "list") String list(UserListForm userListForm); @RequestMapping(value = "set") String set(UserSetForm userSetForm); @RequestMapping(value = "map") String map(UserMapForm userMapForm); @RequestMapping(value = "json") String json(@RequestBody User user); @RequestMapping(value = "xml", consumes = MediaType.APPLICATION_XML_VALUE, produces = MediaType.APPLICATION_XML_VALUE) String xml(@RequestBody Admin admin); @RequestMapping(value = "date1") String date1(Date date1); @InitBinder("date1") void initDate1(WebDataBinder binder); @RequestMapping(value = "date2") String date2(Date date2); @GetMapping(value = "/book") String book(HttpServletRequest request); @GetMapping(value = "/subject/{subjectId}") String getSubject(@PathVariable("subjectId") String subjectId); @PostMapping(value = "/subject/{subjectId}") String postSubject(@PathVariable("subjectId") String subjectId); @DeleteMapping(value = "/subject/{subjectId}") String deleteSubject(@PathVariable("subjectId") String subjectId); @PutMapping(value = "/subject/{subjectId}") String putSubject(@PathVariable("subjectId") String subjectId); }
@Test public void postSubject() throws Exception { String subjectId = "111"; String response = mockMvc.perform(post("/subject/" + subjectId) .contentType(APPLICATION_JSON_UTF8)) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsString(); System.out.println(response); }
BindController { @DeleteMapping(value = "/subject/{subjectId}") public String deleteSubject(@PathVariable("subjectId") String subjectId) { return "this is delete method,subject:" + subjectId; } @RequestMapping(value = "/baseType") String baseType(@RequestParam("age") int age); @RequestMapping(value = "/baseType2") String baseType2(Integer age); @RequestMapping(value = "/array") String array(String[] name); @RequestMapping(value = "/object") String object(User user, Admin admin); @InitBinder("user") void initUser(WebDataBinder binder); @InitBinder("admin") void initAdmin(WebDataBinder binder); @RequestMapping(value = "list") String list(UserListForm userListForm); @RequestMapping(value = "set") String set(UserSetForm userSetForm); @RequestMapping(value = "map") String map(UserMapForm userMapForm); @RequestMapping(value = "json") String json(@RequestBody User user); @RequestMapping(value = "xml", consumes = MediaType.APPLICATION_XML_VALUE, produces = MediaType.APPLICATION_XML_VALUE) String xml(@RequestBody Admin admin); @RequestMapping(value = "date1") String date1(Date date1); @InitBinder("date1") void initDate1(WebDataBinder binder); @RequestMapping(value = "date2") String date2(Date date2); @GetMapping(value = "/book") String book(HttpServletRequest request); @GetMapping(value = "/subject/{subjectId}") String getSubject(@PathVariable("subjectId") String subjectId); @PostMapping(value = "/subject/{subjectId}") String postSubject(@PathVariable("subjectId") String subjectId); @DeleteMapping(value = "/subject/{subjectId}") String deleteSubject(@PathVariable("subjectId") String subjectId); @PutMapping(value = "/subject/{subjectId}") String putSubject(@PathVariable("subjectId") String subjectId); }
@Test public void deleteSubject() throws Exception { String subjectId = "111"; String response = mockMvc.perform(delete("/subject/" + subjectId) .contentType(APPLICATION_JSON_UTF8)) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsString(); System.out.println(response); }
BindController { @PutMapping(value = "/subject/{subjectId}") public String putSubject(@PathVariable("subjectId") String subjectId) { return "this is put method,subject:" + subjectId; } @RequestMapping(value = "/baseType") String baseType(@RequestParam("age") int age); @RequestMapping(value = "/baseType2") String baseType2(Integer age); @RequestMapping(value = "/array") String array(String[] name); @RequestMapping(value = "/object") String object(User user, Admin admin); @InitBinder("user") void initUser(WebDataBinder binder); @InitBinder("admin") void initAdmin(WebDataBinder binder); @RequestMapping(value = "list") String list(UserListForm userListForm); @RequestMapping(value = "set") String set(UserSetForm userSetForm); @RequestMapping(value = "map") String map(UserMapForm userMapForm); @RequestMapping(value = "json") String json(@RequestBody User user); @RequestMapping(value = "xml", consumes = MediaType.APPLICATION_XML_VALUE, produces = MediaType.APPLICATION_XML_VALUE) String xml(@RequestBody Admin admin); @RequestMapping(value = "date1") String date1(Date date1); @InitBinder("date1") void initDate1(WebDataBinder binder); @RequestMapping(value = "date2") String date2(Date date2); @GetMapping(value = "/book") String book(HttpServletRequest request); @GetMapping(value = "/subject/{subjectId}") String getSubject(@PathVariable("subjectId") String subjectId); @PostMapping(value = "/subject/{subjectId}") String postSubject(@PathVariable("subjectId") String subjectId); @DeleteMapping(value = "/subject/{subjectId}") String deleteSubject(@PathVariable("subjectId") String subjectId); @PutMapping(value = "/subject/{subjectId}") String putSubject(@PathVariable("subjectId") String subjectId); }
@Test public void putSubject() throws Exception { String subjectId = "111"; String response = mockMvc.perform(put("/subject/" + subjectId) .contentType(APPLICATION_JSON_UTF8)) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsString(); System.out.println(response); }
EmployeeService { @Transactional(rollbackFor = Exception.class) public void updateAgeById(Integer id, Integer age) { this.employeeRepository.updateAgeById(id, age); } @Transactional(rollbackFor = Exception.class) void updateAgeById(Integer id, Integer age); @Transactional(rollbackFor = Exception.class) void save(List<Employee> employees); }
@Test public void updateAgeByIdTest() { EmployeeService employeeService = ctx.getBean(EmployeeService.class); employeeService.updateAgeById(1, 55); }
HelloController { @RequestMapping(value = "say", method = RequestMethod.GET) @ResponseBody public String say() { return girlProperties.getCupSize(); } @RequestMapping(method = RequestMethod.GET) String index(); @RequestMapping(value = "say", method = RequestMethod.GET) @ResponseBody String say(); @GetMapping(value = "/say/one") @ResponseBody String sayOne(@RequestParam(value = "id", required = false, defaultValue = "0") Integer myId); }
@Test public void say() throws Exception { String response = mockMvc.perform(get("/hello/say") .contentType(APPLICATION_JSON_UTF8)) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsString(); System.out.println(response); }
HelloController { @GetMapping(value = "/say/one") @ResponseBody public String sayOne(@RequestParam(value = "id", required = false, defaultValue = "0") Integer myId) { return "id:" + myId; } @RequestMapping(method = RequestMethod.GET) String index(); @RequestMapping(value = "say", method = RequestMethod.GET) @ResponseBody String say(); @GetMapping(value = "/say/one") @ResponseBody String sayOne(@RequestParam(value = "id", required = false, defaultValue = "0") Integer myId); }
@Test public void sayOne() throws Exception { MultiValueMap<String, String> params = new LinkedMultiValueMap<>(16); params.add("id", "5"); String response = mockMvc.perform(get("/hello/say/one") .contentType(APPLICATION_JSON_UTF8) .params(params)) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsString(); System.out.println(response); }
GirlController { @GetMapping public List<Girl> listGirl() { return girlRepository.findAll(); } @GetMapping List<Girl> listGirl(); @PostMapping Result<Girl> girlAdd(@Valid Girl girl, BindingResult bindingResult); @GetMapping("/{id}") Girl getGirlById(@PathVariable("id") Integer id); @PutMapping("/{id}") Girl updateGirlById(@PathVariable("id") Integer id, @RequestParam("cupSize") String cupSize, @RequestParam("age") Integer age); @DeleteMapping("/{id}") void removeGirl(@PathVariable("id") Integer id); @GetMapping("/age/{age}") List<Girl> listGirlByAge(@PathVariable("age") Integer age); @PostMapping("/two") void saveGirlTwo(); @GetMapping(value = "/getAge/{id}") void getAge(@PathVariable("id") Integer id); }
@Test public void listGirl() throws Exception { String response = mockMvc.perform(get("/girls") .contentType(APPLICATION_JSON_UTF8)) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsString(); System.out.println(response); }
BindController { @RequestMapping(value = "/baseType2") public String baseType2(Integer age) { return "age:" + age; } @RequestMapping(value = "/baseType") String baseType(@RequestParam("age") int age); @RequestMapping(value = "/baseType2") String baseType2(Integer age); @RequestMapping(value = "/array") String array(String[] name); @RequestMapping(value = "/object") String object(User user, Admin admin); @InitBinder("user") void initUser(WebDataBinder binder); @InitBinder("admin") void initAdmin(WebDataBinder binder); @RequestMapping(value = "list") String list(UserListForm userListForm); @RequestMapping(value = "set") String set(UserSetForm userSetForm); @RequestMapping(value = "map") String map(UserMapForm userMapForm); @RequestMapping(value = "json") String json(@RequestBody User user); @RequestMapping(value = "xml", consumes = MediaType.APPLICATION_XML_VALUE, produces = MediaType.APPLICATION_XML_VALUE) String xml(@RequestBody Admin admin); @RequestMapping(value = "date1") String date1(Date date1); @InitBinder("date1") void initDate1(WebDataBinder binder); @RequestMapping(value = "date2") String date2(Date date2); @GetMapping(value = "/book") String book(HttpServletRequest request); @GetMapping(value = "/subject/{subjectId}") String getSubject(@PathVariable("subjectId") String subjectId); @PostMapping(value = "/subject/{subjectId}") String postSubject(@PathVariable("subjectId") String subjectId); @DeleteMapping(value = "/subject/{subjectId}") String deleteSubject(@PathVariable("subjectId") String subjectId); @PutMapping(value = "/subject/{subjectId}") String putSubject(@PathVariable("subjectId") String subjectId); }
@Test public void baseType2() throws Exception { MultiValueMap<String, String> params = new LinkedMultiValueMap<>(16); params.add("age", "20"); String response = mockMvc.perform(get("/baseType") .contentType(APPLICATION_JSON_UTF8) .params(params)) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsString(); System.out.println(response); }
GirlController { @PostMapping public Result<Girl> girlAdd(@Valid Girl girl, BindingResult bindingResult) { if (bindingResult.hasErrors()) { FieldError fieldError = bindingResult.getFieldError(); if (Objects.nonNull(fieldError)) { return ResultUtil.error(ResultUtil.RESPONSE_CODE_ERROR_PARAM, fieldError.getDefaultMessage()); } return ResultUtil.error(ResultUtil.RESPONSE_CODE_ERROR_PARAM, "未知参数错误"); } girl.setCupSize(girl.getCupSize()); girl.setAge(girl.getAge()); return ResultUtil.success(girlRepository.save(girl)); } @GetMapping List<Girl> listGirl(); @PostMapping Result<Girl> girlAdd(@Valid Girl girl, BindingResult bindingResult); @GetMapping("/{id}") Girl getGirlById(@PathVariable("id") Integer id); @PutMapping("/{id}") Girl updateGirlById(@PathVariable("id") Integer id, @RequestParam("cupSize") String cupSize, @RequestParam("age") Integer age); @DeleteMapping("/{id}") void removeGirl(@PathVariable("id") Integer id); @GetMapping("/age/{age}") List<Girl> listGirlByAge(@PathVariable("age") Integer age); @PostMapping("/two") void saveGirlTwo(); @GetMapping(value = "/getAge/{id}") void getAge(@PathVariable("id") Integer id); }
@Test public void girlAdd() throws Exception { MultiValueMap<String, String> params = new LinkedMultiValueMap<>(16); params.add("cupSize", "B"); params.add("age", "20"); String response = mockMvc.perform(post("/girls") .contentType(APPLICATION_JSON_UTF8) .params(params)) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsString(); System.out.println(response); }
GirlController { @GetMapping("/{id}") public Girl getGirlById(@PathVariable("id") Integer id) { return girlRepository.findById(id).orElse(null); } @GetMapping List<Girl> listGirl(); @PostMapping Result<Girl> girlAdd(@Valid Girl girl, BindingResult bindingResult); @GetMapping("/{id}") Girl getGirlById(@PathVariable("id") Integer id); @PutMapping("/{id}") Girl updateGirlById(@PathVariable("id") Integer id, @RequestParam("cupSize") String cupSize, @RequestParam("age") Integer age); @DeleteMapping("/{id}") void removeGirl(@PathVariable("id") Integer id); @GetMapping("/age/{age}") List<Girl> listGirlByAge(@PathVariable("age") Integer age); @PostMapping("/two") void saveGirlTwo(); @GetMapping(value = "/getAge/{id}") void getAge(@PathVariable("id") Integer id); }
@Test public void getGirlById() throws Exception { int id = 3; String response = mockMvc.perform(get("/girls/" + id) .contentType(APPLICATION_JSON_UTF8)) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsString(); TypeReference<Girl> typeReference = new TypeReference<Girl>() { }; Girl girl = objectMapper.readValue(response, typeReference); System.out.println(girl); }
GirlController { @PutMapping("/{id}") public Girl updateGirlById(@PathVariable("id") Integer id, @RequestParam("cupSize") String cupSize, @RequestParam("age") Integer age) { Girl girl = new Girl(); girl.setId(id); girl.setCupSize(cupSize); girl.setAge(age); return girlRepository.save(girl); } @GetMapping List<Girl> listGirl(); @PostMapping Result<Girl> girlAdd(@Valid Girl girl, BindingResult bindingResult); @GetMapping("/{id}") Girl getGirlById(@PathVariable("id") Integer id); @PutMapping("/{id}") Girl updateGirlById(@PathVariable("id") Integer id, @RequestParam("cupSize") String cupSize, @RequestParam("age") Integer age); @DeleteMapping("/{id}") void removeGirl(@PathVariable("id") Integer id); @GetMapping("/age/{age}") List<Girl> listGirlByAge(@PathVariable("age") Integer age); @PostMapping("/two") void saveGirlTwo(); @GetMapping(value = "/getAge/{id}") void getAge(@PathVariable("id") Integer id); }
@Test public void updateGirlById() throws Exception { int id = 3; MultiValueMap<String, String> params = new LinkedMultiValueMap<>(16); params.add("cupSize", "C"); params.add("age", "22"); String response = mockMvc.perform(put("/girls/" + id) .contentType(APPLICATION_JSON_UTF8) .params(params)) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsString(); TypeReference<Girl> typeReference = new TypeReference<Girl>() { }; Girl girl = objectMapper.readValue(response, typeReference); System.out.println(girl); }
GirlController { @DeleteMapping("/{id}") public void removeGirl(@PathVariable("id") Integer id) { girlRepository.deleteById(id); } @GetMapping List<Girl> listGirl(); @PostMapping Result<Girl> girlAdd(@Valid Girl girl, BindingResult bindingResult); @GetMapping("/{id}") Girl getGirlById(@PathVariable("id") Integer id); @PutMapping("/{id}") Girl updateGirlById(@PathVariable("id") Integer id, @RequestParam("cupSize") String cupSize, @RequestParam("age") Integer age); @DeleteMapping("/{id}") void removeGirl(@PathVariable("id") Integer id); @GetMapping("/age/{age}") List<Girl> listGirlByAge(@PathVariable("age") Integer age); @PostMapping("/two") void saveGirlTwo(); @GetMapping(value = "/getAge/{id}") void getAge(@PathVariable("id") Integer id); }
@Test public void removeGirl() throws Exception { int id = 2; String response = mockMvc.perform(delete("/girls/" + id) .contentType(APPLICATION_JSON_UTF8)) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsString(); System.out.println(response); }
GirlController { @GetMapping("/age/{age}") public List<Girl> listGirlByAge(@PathVariable("age") Integer age) { return girlRepository.findByAge(age); } @GetMapping List<Girl> listGirl(); @PostMapping Result<Girl> girlAdd(@Valid Girl girl, BindingResult bindingResult); @GetMapping("/{id}") Girl getGirlById(@PathVariable("id") Integer id); @PutMapping("/{id}") Girl updateGirlById(@PathVariable("id") Integer id, @RequestParam("cupSize") String cupSize, @RequestParam("age") Integer age); @DeleteMapping("/{id}") void removeGirl(@PathVariable("id") Integer id); @GetMapping("/age/{age}") List<Girl> listGirlByAge(@PathVariable("age") Integer age); @PostMapping("/two") void saveGirlTwo(); @GetMapping(value = "/getAge/{id}") void getAge(@PathVariable("id") Integer id); }
@Test public void listGirlByAge() throws Exception { int age = 8; String response = mockMvc.perform(get("/girls/age/" + age) .contentType(APPLICATION_JSON_UTF8)) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsString(); TypeReference<List<Girl>> typeReference = new TypeReference<List<Girl>>() { }; List<Girl> list = objectMapper.readValue(response, typeReference); System.out.println(list); }
GirlController { @PostMapping("/two") public void saveGirlTwo() { girlService.saveTwo(); } @GetMapping List<Girl> listGirl(); @PostMapping Result<Girl> girlAdd(@Valid Girl girl, BindingResult bindingResult); @GetMapping("/{id}") Girl getGirlById(@PathVariable("id") Integer id); @PutMapping("/{id}") Girl updateGirlById(@PathVariable("id") Integer id, @RequestParam("cupSize") String cupSize, @RequestParam("age") Integer age); @DeleteMapping("/{id}") void removeGirl(@PathVariable("id") Integer id); @GetMapping("/age/{age}") List<Girl> listGirlByAge(@PathVariable("age") Integer age); @PostMapping("/two") void saveGirlTwo(); @GetMapping(value = "/getAge/{id}") void getAge(@PathVariable("id") Integer id); }
@Test public void saveGirlTwo() throws Exception { String response = mockMvc.perform(post("/girls/two") .contentType(APPLICATION_JSON_UTF8)) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsString(); System.out.println(response); }
TodoRepository { public void save(TodoItem item){ items.put(item.getName(),item); } void save(TodoItem item); TodoItem query(String name); }
@Test public void saveTest(){ TodoItem todoItem = new TodoItem("imooc"); repository.save(todoItem); Assert.assertNull(repository.query(todoItem.getName())); }
MailService { public void sendSimpleMail(String to, String subject, String content) { SimpleMailMessage message = new SimpleMailMessage(); message.setTo(to); message.setSubject(subject); message.setText(content); message.setFrom(from); this.mailSender.send(message); } void sendSimpleMail(String to, String subject, String content); void sendHtmlMail(String to, String subject, String content); void sendAttachmentsMail(String to, String subject, String content, String[] filePaths); void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId); }
@Test public void sendSimpleMail() { this.mailService.sendSimpleMail(TO, "这是第一封邮件", "大家好,这是我的第一封邮件"); }
MailService { public void sendHtmlMail(String to, String subject, String content) throws Exception { MimeMessage message = this.mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setTo(to); helper.setSubject(subject); helper.setText(content, true); helper.setFrom(from); this.mailSender.send(message); } void sendSimpleMail(String to, String subject, String content); void sendHtmlMail(String to, String subject, String content); void sendAttachmentsMail(String to, String subject, String content, String[] filePaths); void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId); }
@Test public void sendHtmlMail() throws Exception { StringBuilder content = new StringBuilder(128); content.append("<html\n>"); content.append("<body>\n"); content.append("<h3> Hello World!这是一封Html邮件</h3>\n"); content.append("</body>\n"); content.append("</html>"); this.mailService.sendHtmlMail(TO, "这是一封html邮件", content.toString()); } @Test public void sendTemplateMail() throws Exception { Context context = new Context(); context.setVariable("id", "006"); String emailContent = this.templateEngine.process("emailTemplate", context); this.mailService.sendHtmlMail(TO, "这是一封模版邮件", emailContent); }
MailService { public void sendAttachmentsMail(String to, String subject, String content, String[] filePaths) throws Exception { MimeMessage message = this.mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setTo(to); helper.setSubject(subject); helper.setText(content, true); FileSystemResource file; for (String filePath : filePaths) { file = new FileSystemResource(new File(filePath)); String fileName = file.getFilename(); helper.addAttachment(fileName, file); } helper.setFrom(from); this.mailSender.send(message); } void sendSimpleMail(String to, String subject, String content); void sendHtmlMail(String to, String subject, String content); void sendAttachmentsMail(String to, String subject, String content, String[] filePaths); void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId); }
@Test public void sendAttachmentsMail() throws Exception { String filePath = "d:\\48-boot-mail-hello.zip"; this.mailService.sendAttachmentsMail(TO, "这是一封带附件的邮件", "这是一封带附件的邮件内容", new String[]{filePath}); }
BindController { @RequestMapping(value = "/array") public String array(String[] name) { StringBuilder stringBuilder = new StringBuilder(); for (String item : name) { stringBuilder.append(item).append(" "); } return stringBuilder.toString(); } @RequestMapping(value = "/baseType") String baseType(@RequestParam("age") int age); @RequestMapping(value = "/baseType2") String baseType2(Integer age); @RequestMapping(value = "/array") String array(String[] name); @RequestMapping(value = "/object") String object(User user, Admin admin); @InitBinder("user") void initUser(WebDataBinder binder); @InitBinder("admin") void initAdmin(WebDataBinder binder); @RequestMapping(value = "list") String list(UserListForm userListForm); @RequestMapping(value = "set") String set(UserSetForm userSetForm); @RequestMapping(value = "map") String map(UserMapForm userMapForm); @RequestMapping(value = "json") String json(@RequestBody User user); @RequestMapping(value = "xml", consumes = MediaType.APPLICATION_XML_VALUE, produces = MediaType.APPLICATION_XML_VALUE) String xml(@RequestBody Admin admin); @RequestMapping(value = "date1") String date1(Date date1); @InitBinder("date1") void initDate1(WebDataBinder binder); @RequestMapping(value = "date2") String date2(Date date2); @GetMapping(value = "/book") String book(HttpServletRequest request); @GetMapping(value = "/subject/{subjectId}") String getSubject(@PathVariable("subjectId") String subjectId); @PostMapping(value = "/subject/{subjectId}") String postSubject(@PathVariable("subjectId") String subjectId); @DeleteMapping(value = "/subject/{subjectId}") String deleteSubject(@PathVariable("subjectId") String subjectId); @PutMapping(value = "/subject/{subjectId}") String putSubject(@PathVariable("subjectId") String subjectId); }
@Test public void array() throws Exception { MultiValueMap<String, String> params = new LinkedMultiValueMap<>(16); params.add("name", "Tom,Lucy"); String response = mockMvc.perform(get("/array") .contentType(APPLICATION_JSON_UTF8) .params(params)) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsString(); System.out.println(response); }
MailService { public void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId) { logger.info("发送图片邮件开始:{},{},{},{},{}", to, subject, content, rscPath, rscId); MimeMessage message = this.mailSender.createMimeMessage(); MimeMessageHelper helper; try { helper = new MimeMessageHelper(message, true); helper.setTo(to); helper.setSubject(subject); helper.setText(content, true); FileSystemResource file = new FileSystemResource(new File(rscPath)); helper.addInline(rscId, file); helper.setFrom(from); this.mailSender.send(message); logger.info("发送图片邮件成功!"); } catch (MessagingException ex) { logger.error("发送图片邮件异常:", ex); } } void sendSimpleMail(String to, String subject, String content); void sendHtmlMail(String to, String subject, String content); void sendAttachmentsMail(String to, String subject, String content, String[] filePaths); void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId); }
@Test public void sendInlineResourceMail() { String rscPath = "d:\\thumb.jpg"; String rscId = "img001"; StringBuilder content = new StringBuilder(128); content.append("<html\n>"); content.append("<body>\n"); content.append("<h3> 这是有图片的邮件</h3>\n"); content.append("<img src=\'cid:").append(rscId).append("\'></img>\n"); content.append("<img src=\'cid:").append(rscId).append("\'></img>\n"); content.append("</body>\n"); content.append("</html>"); this.mailService.sendInlineResourceMail(TO, "这是一封带图片的邮件", content.toString(), rscPath, rscId); }
HelloService { public void sayHello() { System.out.println("Hello World"); } void sayHello(); }
@Test public void sayHelloTest() { this.helloService.sayHello(); }
Students { public void setTeachers(Set<Teachers> teachers) { this.teachers = teachers; } Students(); Students(String sname, String gender, Date birthday, String major); @Override String toString(); Set<Teachers> getTeachers(); void setTeachers(Set<Teachers> teachers); String getSname(); void setSname(String sname); Integer getSid(); void setSid(Integer sid); String getGender(); void setGender(String gender); Date getBirthday(); void setBirthday(Date birthday); String getMajor(); void setMajor(String major); }
@Test public void addStudents() { Session session = sessionFactory.getCurrentSession(); Transaction tx = session.beginTransaction(); Teachers t1 = new Teachers("T001", "张老师"); Teachers t2 = new Teachers("T002", "李老师"); Teachers t3 = new Teachers("T003", "陈老师"); Teachers t4 = new Teachers("T004", "刘老师"); Students s1 = new Students("张三", "男", new Date(), "计算机"); Students s2 = new Students("李四", "男", new Date(), "计算机"); Students s3 = new Students("王五", "女", new Date(), "计算机"); Students s4 = new Students("赵六", "女", new Date(), "计算机"); Set<Teachers> set1 = new HashSet<>(); set1.add(t1); set1.add(t2); Set<Teachers> set2 = new HashSet<>(); set2.add(t3); set2.add(t4); Set<Teachers> set3 = new HashSet<>(); set3.add(t1); set3.add(t3); set3.add(t4); Set<Teachers> set4 = new HashSet<>(); set4.add(t2); set4.add(t3); set4.add(t4); s1.setTeachers(set1); s2.setTeachers(set2); s3.setTeachers(set3); s4.setTeachers(set4); session.save(t1); session.save(t2); session.save(t3); session.save(t4); session.save(s1); session.save(s2); session.save(s3); session.save(s4); tx.commit(); }
Students { public void setTeachers(Set<Teachers> teachers) { this.teachers = teachers; } Students(); Students(String sname, String gender, Date birthday, String major); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); Set<Teachers> getTeachers(); void setTeachers(Set<Teachers> teachers); String getSname(); void setSname(String sname); Integer getSid(); void setSid(Integer sid); String getGender(); void setGender(String gender); Date getBirthday(); void setBirthday(Date birthday); String getMajor(); void setMajor(String major); }
@Test public void addStudents() { Session session = sessionFactory.getCurrentSession(); Transaction tx = session.beginTransaction(); Teachers t1 = new Teachers("T001", "张老师"); Teachers t2 = new Teachers("T002", "李老师"); Teachers t3 = new Teachers("T003", "陈老师"); Teachers t4 = new Teachers("T004", "刘老师"); Students s1 = new Students("张三", "男", new Date(), "计算机"); Students s2 = new Students("李四", "男", new Date(), "计算机"); Students s3 = new Students("王五", "女", new Date(), "计算机"); Students s4 = new Students("赵六", "女", new Date(), "计算机"); Set<Teachers> set1 = new HashSet<>(); set1.add(t1); set1.add(t2); Set<Teachers> set2 = new HashSet<>(); set2.add(t3); set2.add(t4); Set<Teachers> set3 = new HashSet<>(); set3.add(t1); set3.add(t3); set3.add(t4); Set<Teachers> set4 = new HashSet<>(); set4.add(t2); set4.add(t3); set4.add(t4); s1.setTeachers(set1); s2.setTeachers(set2); s3.setTeachers(set3); s4.setTeachers(set4); session.save(t1); session.save(t2); session.save(t3); session.save(t4); session.save(s1); session.save(s2); session.save(s3); session.save(s4); tx.commit(); }
Students { public void setClassRoom(ClassRoom classRoom) { this.classRoom = classRoom; } Students(); Students(String sname, String gender, Date birthday, String major); @Override String toString(); String getSname(); void setSname(String sname); ClassRoom getClassRoom(); void setClassRoom(ClassRoom classRoom); Integer getSid(); void setSid(Integer sid); String getGender(); void setGender(String gender); Date getBirthday(); void setBirthday(Date birthday); String getMajor(); void setMajor(String major); }
@Test public void addStudents() { Session session = sessionFactory.getCurrentSession(); Transaction tx = session.beginTransaction(); ClassRoom c1 = new ClassRoom("C001", "软件工程"); ClassRoom c2 = new ClassRoom("C002", "网络工程"); Students s1 = new Students("张三", "男", new Date(), "计算机"); Students s2 = new Students("李四", "男", new Date(), "计算机"); Students s3 = new Students("王五", "女", new Date(), "计算机"); Students s4 = new Students("赵六", "女", new Date(), "计算机"); s1.setClassRoom(c1); s2.setClassRoom(c1); s3.setClassRoom(c2); s4.setClassRoom(c2); session.save(c1); session.save(c2); session.save(s1); session.save(s2); session.save(s3); session.save(s4); tx.commit(); }
GirlController { @GetMapping(value = "/girls") public List<Girl> girlList() { logger.info("girlList"); return girlRepository.findAll(); } @GetMapping(value = "/girls") List<Girl> girlList(); @PostMapping(value = "/girls") Result<Girl> girlAdd(@Valid Girl girl, BindingResult bindingResult); @GetMapping(value = "/girls/{id}") Girl girlFindOne(@PathVariable("id") Integer id); @PutMapping(value = "/girls/{id}") Girl girlUpdate(@PathVariable("id") Integer id, @RequestParam("cupSize") String cupSize, @RequestParam("age") Integer age); @DeleteMapping(value = "/girls/{id}") void girlDelete(@PathVariable("id") Integer id); @GetMapping(value = "/girls/age/{age}") List<Girl> girlListByAge(@PathVariable("age") Integer age); @PostMapping(value = "/girls/two") void girlTwo(); @GetMapping(value = "girls/getAge/{id}") void getAge(@PathVariable("id") Integer id); }
@Test public void girlList() throws Exception { mvc.perform(MockMvcRequestBuilders.get("/girls")) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.content().string("abc")); }
JDBCUtil { public static Connection getConnection() throws Exception { InputStream inputStream = JDBCUtil.class.getClassLoader().getResourceAsStream("db.properties"); Properties properties = new Properties(); properties.load(inputStream); String url = properties.getProperty("jdbc.url"); String user = properties.getProperty("jdbc.user"); String password = properties.getProperty("jdbc.password"); String driverClass = properties.getProperty("jdbc.driverClass"); Class.forName(driverClass); Connection connection = DriverManager.getConnection(url, user, password); return connection; } static Connection getConnection(); static void release(ResultSet resultSet, Statement statement, Connection connection); }
@Test public void testGetConnection() throws Exception { Connection connection = JDBCUtil.getConnection(); Assert.assertNotNull(connection); }
EmployeeService { @Transactional public void update(Integer id, Integer age) { employeeRepository.update(id, age); } @Transactional void update(Integer id, Integer age); }
@Test public void testUpdate() { employeeService.update(1, 55); }
BindController { @RequestMapping(value = "/object") public String object(User user, Admin admin) { return user.toString() + " ### " + admin.toString(); } @RequestMapping(value = "/baseType") String baseType(@RequestParam("age") int age); @RequestMapping(value = "/baseType2") String baseType2(Integer age); @RequestMapping(value = "/array") String array(String[] name); @RequestMapping(value = "/object") String object(User user, Admin admin); @InitBinder("user") void initUser(WebDataBinder binder); @InitBinder("admin") void initAdmin(WebDataBinder binder); @RequestMapping(value = "list") String list(UserListForm userListForm); @RequestMapping(value = "set") String set(UserSetForm userSetForm); @RequestMapping(value = "map") String map(UserMapForm userMapForm); @RequestMapping(value = "json") String json(@RequestBody User user); @RequestMapping(value = "xml", consumes = MediaType.APPLICATION_XML_VALUE, produces = MediaType.APPLICATION_XML_VALUE) String xml(@RequestBody Admin admin); @RequestMapping(value = "date1") String date1(Date date1); @InitBinder("date1") void initDate1(WebDataBinder binder); @RequestMapping(value = "date2") String date2(Date date2); @GetMapping(value = "/book") String book(HttpServletRequest request); @GetMapping(value = "/subject/{subjectId}") String getSubject(@PathVariable("subjectId") String subjectId); @PostMapping(value = "/subject/{subjectId}") String postSubject(@PathVariable("subjectId") String subjectId); @DeleteMapping(value = "/subject/{subjectId}") String deleteSubject(@PathVariable("subjectId") String subjectId); @PutMapping(value = "/subject/{subjectId}") String putSubject(@PathVariable("subjectId") String subjectId); }
@Test public void object() throws Exception { MultiValueMap<String, String> params = new LinkedMultiValueMap<>(16); params.add("name", "Tom"); params.add("age", "20"); params.add("contactInfo.phone", "10086"); params.add("contactInfo.address", "11号"); params.add("admin.name", "Lucy"); params.add("admin.age", "18"); String response = mockMvc.perform(get("/object") .contentType(APPLICATION_JSON_UTF8) .params(params)) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsString(); System.out.println(response); }
StudentDAOImpl implements StudentDAO { @Override public List<Student> query() { List<Student> students = new ArrayList<Student>(); Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; String sql = "select id, name , age from student"; try { connection = JDBCUtil.getConnection(); preparedStatement = connection.prepareStatement(sql); resultSet = preparedStatement.executeQuery(); Student student = null; while (resultSet.next()) { int id = resultSet.getInt("id"); String name = resultSet.getString("name"); int age = resultSet.getInt("age"); student = new Student(); student.setId(id); student.setName(name); student.setAge(age); students.add(student); } } catch (Exception e) { e.printStackTrace(); } finally { JDBCUtil.release(resultSet,preparedStatement,connection); } return students; } @Override List<Student> query(); @Override void save(Student student); }
@Test public void testQuery() { StudentDAO studentDAO = new StudentDAOImpl(); List<Student> students = studentDAO.query(); for (Student student : students) { System.out.println("id:" + student.getId() + " , name:" + student.getName() + ", age:" + student.getAge()); } }
StudentDAOImpl implements StudentDAO { @Override public void save(Student student) { Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; String sql = "insert into student(name, age) values(?,?)"; try { connection = JDBCUtil.getConnection(); preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1, student.getName()); preparedStatement.setInt(2, student.getAge()); preparedStatement.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } finally { JDBCUtil.release(resultSet,preparedStatement,connection); } } @Override List<Student> query(); @Override void save(Student student); }
@Test public void testSave() { StudentDAO studentDAO = new StudentDAOImpl(); Student student = new Student(); student.setName("test"); student.setAge(30); studentDAO.save(student); }
StudentDAOSpringJdbcImpl implements StudentDAO { @Override public List<Student> query() { final List<Student> students = new ArrayList<Student>(); String sql = "select id, name , age from student"; jdbcTemplate.query(sql, new RowCallbackHandler(){ @Override public void processRow(ResultSet rs) throws SQLException { int id = rs.getInt("id"); String name = rs.getString("name"); int age = rs.getInt("age"); Student student = new Student(); student.setId(id); student.setName(name); student.setAge(age); students.add(student); } }); return students; } @Override List<Student> query(); @Override void save(Student student); JdbcTemplate getJdbcTemplate(); void setJdbcTemplate(JdbcTemplate jdbcTemplate); }
@Test public void testQuery() { List<Student> students = studentDAO.query(); for (Student student : students) { System.out.println("id:" + student.getId() + " , name:" + student.getName() + ", age:" + student.getAge()); } }
StudentDAOSpringJdbcImpl implements StudentDAO { @Override public void save(Student student) { String sql = "insert into student(name, age) values(?,?)"; jdbcTemplate.update(sql, new Object[]{student.getName(), student.getAge()}); } @Override List<Student> query(); @Override void save(Student student); JdbcTemplate getJdbcTemplate(); void setJdbcTemplate(JdbcTemplate jdbcTemplate); }
@Test public void testSave() { Student student = new Student(); student.setName("test-spring-jdbc"); student.setAge(40); studentDAO.save(student); }
SessionManager { public Long getSessionId() { return sessionIdProvider.get(); } @Inject SessionManager( @SessionId Provider<Long> sessionIdProvider); Long getSessionId(); }
@Test public void testGetSessionId() throws InterruptedException { Long sessionId1 = sessionManager.getSessionId(); Thread.sleep(1000); Long sessionId2 = sessionManager.getSessionId(); assertNotEquals( sessionId2.longValue(), sessionId1.longValue()); }
DemoService { @Transactional(rollbackFor = Exception.class) public void addUser(String name) { OperationLog log = new OperationLog(); log.setContent("create user:" + name); operationLogDao.save(log); User user = new User(); user.setName(name); userDao.save(user); } @Transactional(rollbackFor = Exception.class) void addUser(String name); }
@Test public void testWithoutTransaction(){ demoService.addUser("tom"); }
GirlController { @GetMapping public List<Girl> listGirl() { return girlRepository.findAll(); } @GetMapping List<Girl> listGirl(); @PostMapping Girl girlAdd(@RequestParam("cupSize") String cupSize, @RequestParam("age") Integer age); @GetMapping("/{id}") Girl getGirlById(@PathVariable("id") Integer id); @PutMapping("/{id}") Girl updateGirlById(@PathVariable("id") Integer id, @RequestParam("cupSize") String cupSize, @RequestParam("age") Integer age); @DeleteMapping("/{id}") void removeGirl(@PathVariable("id") Integer id); @GetMapping("/age/{age}") List<Girl> listGirlByAge(@PathVariable("age") Integer age); @PostMapping("/two") void saveGirlTwo(); }
@Test public void listGirl() throws Exception { String response = mockMvc.perform(get("/girls") .contentType(APPLICATION_JSON_UTF8)) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsString(); System.out.println(response); }
GirlController { @PostMapping public Girl girlAdd(@RequestParam("cupSize") String cupSize, @RequestParam("age") Integer age) { Girl girl = new Girl(); girl.setCupSize(cupSize); girl.setAge(age); return girlRepository.save(girl); } @GetMapping List<Girl> listGirl(); @PostMapping Girl girlAdd(@RequestParam("cupSize") String cupSize, @RequestParam("age") Integer age); @GetMapping("/{id}") Girl getGirlById(@PathVariable("id") Integer id); @PutMapping("/{id}") Girl updateGirlById(@PathVariable("id") Integer id, @RequestParam("cupSize") String cupSize, @RequestParam("age") Integer age); @DeleteMapping("/{id}") void removeGirl(@PathVariable("id") Integer id); @GetMapping("/age/{age}") List<Girl> listGirlByAge(@PathVariable("age") Integer age); @PostMapping("/two") void saveGirlTwo(); }
@Test public void girlAdd() throws Exception { MultiValueMap<String, String> params = new LinkedMultiValueMap<>(16); params.add("cupSize", "B"); params.add("age", "20"); String response = mockMvc.perform(post("/girls") .contentType(APPLICATION_JSON_UTF8) .params(params)) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsString(); System.out.println(response); }
BindController { @RequestMapping(value = "list") public String list(UserListForm userListForm) { return "listSize:" + userListForm.getUsers().size() + userListForm.toString(); } @RequestMapping(value = "/baseType") String baseType(@RequestParam("age") int age); @RequestMapping(value = "/baseType2") String baseType2(Integer age); @RequestMapping(value = "/array") String array(String[] name); @RequestMapping(value = "/object") String object(User user, Admin admin); @InitBinder("user") void initUser(WebDataBinder binder); @InitBinder("admin") void initAdmin(WebDataBinder binder); @RequestMapping(value = "list") String list(UserListForm userListForm); @RequestMapping(value = "set") String set(UserSetForm userSetForm); @RequestMapping(value = "map") String map(UserMapForm userMapForm); @RequestMapping(value = "json") String json(@RequestBody User user); @RequestMapping(value = "xml", consumes = MediaType.APPLICATION_XML_VALUE, produces = MediaType.APPLICATION_XML_VALUE) String xml(@RequestBody Admin admin); @RequestMapping(value = "date1") String date1(Date date1); @InitBinder("date1") void initDate1(WebDataBinder binder); @RequestMapping(value = "date2") String date2(Date date2); @GetMapping(value = "/book") String book(HttpServletRequest request); @GetMapping(value = "/subject/{subjectId}") String getSubject(@PathVariable("subjectId") String subjectId); @PostMapping(value = "/subject/{subjectId}") String postSubject(@PathVariable("subjectId") String subjectId); @DeleteMapping(value = "/subject/{subjectId}") String deleteSubject(@PathVariable("subjectId") String subjectId); @PutMapping(value = "/subject/{subjectId}") String putSubject(@PathVariable("subjectId") String subjectId); }
@Test public void list() throws Exception { MultiValueMap<String, String> params = new LinkedMultiValueMap<>(16); params.add("users[0].name", "Tome"); params.add("users[20].name", "Lucy"); String response = mockMvc.perform(get("/list") .contentType(APPLICATION_JSON_UTF8) .params(params)) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsString(); System.out.println(response); }
GirlController { @GetMapping("/{id}") public Girl getGirlById(@PathVariable("id") Integer id) { return girlRepository.findById(id).orElse(null); } @GetMapping List<Girl> listGirl(); @PostMapping Girl girlAdd(@RequestParam("cupSize") String cupSize, @RequestParam("age") Integer age); @GetMapping("/{id}") Girl getGirlById(@PathVariable("id") Integer id); @PutMapping("/{id}") Girl updateGirlById(@PathVariable("id") Integer id, @RequestParam("cupSize") String cupSize, @RequestParam("age") Integer age); @DeleteMapping("/{id}") void removeGirl(@PathVariable("id") Integer id); @GetMapping("/age/{age}") List<Girl> listGirlByAge(@PathVariable("age") Integer age); @PostMapping("/two") void saveGirlTwo(); }
@Test public void getGirlById() throws Exception { int id = 3; String response = mockMvc.perform(get("/girls/" + id) .contentType(APPLICATION_JSON_UTF8)) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsString(); TypeReference<Girl> typeReference = new TypeReference<Girl>() { }; Girl girl = objectMapper.readValue(response, typeReference); System.out.println(girl); }
GirlController { @PutMapping("/{id}") public Girl updateGirlById(@PathVariable("id") Integer id, @RequestParam("cupSize") String cupSize, @RequestParam("age") Integer age) { Girl girl = new Girl(); girl.setId(id); girl.setCupSize(cupSize); girl.setAge(age); return girlRepository.save(girl); } @GetMapping List<Girl> listGirl(); @PostMapping Girl girlAdd(@RequestParam("cupSize") String cupSize, @RequestParam("age") Integer age); @GetMapping("/{id}") Girl getGirlById(@PathVariable("id") Integer id); @PutMapping("/{id}") Girl updateGirlById(@PathVariable("id") Integer id, @RequestParam("cupSize") String cupSize, @RequestParam("age") Integer age); @DeleteMapping("/{id}") void removeGirl(@PathVariable("id") Integer id); @GetMapping("/age/{age}") List<Girl> listGirlByAge(@PathVariable("age") Integer age); @PostMapping("/two") void saveGirlTwo(); }
@Test public void updateGirlById() throws Exception { int id = 3; MultiValueMap<String, String> params = new LinkedMultiValueMap<>(16); params.add("cupSize", "C"); params.add("age", "22"); String response = mockMvc.perform(put("/girls/" + id) .contentType(APPLICATION_JSON_UTF8) .params(params)) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsString(); TypeReference<Girl> typeReference = new TypeReference<Girl>() { }; Girl girl = objectMapper.readValue(response, typeReference); System.out.println(girl); }
GirlController { @DeleteMapping("/{id}") public void removeGirl(@PathVariable("id") Integer id) { girlRepository.deleteById(id); } @GetMapping List<Girl> listGirl(); @PostMapping Girl girlAdd(@RequestParam("cupSize") String cupSize, @RequestParam("age") Integer age); @GetMapping("/{id}") Girl getGirlById(@PathVariable("id") Integer id); @PutMapping("/{id}") Girl updateGirlById(@PathVariable("id") Integer id, @RequestParam("cupSize") String cupSize, @RequestParam("age") Integer age); @DeleteMapping("/{id}") void removeGirl(@PathVariable("id") Integer id); @GetMapping("/age/{age}") List<Girl> listGirlByAge(@PathVariable("age") Integer age); @PostMapping("/two") void saveGirlTwo(); }
@Test public void removeGirl() throws Exception { int id = 2; String response = mockMvc.perform(delete("/girls/" + id) .contentType(APPLICATION_JSON_UTF8)) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsString(); System.out.println(response); }
GirlController { @GetMapping("/age/{age}") public List<Girl> listGirlByAge(@PathVariable("age") Integer age) { return girlRepository.findByAge(age); } @GetMapping List<Girl> listGirl(); @PostMapping Girl girlAdd(@RequestParam("cupSize") String cupSize, @RequestParam("age") Integer age); @GetMapping("/{id}") Girl getGirlById(@PathVariable("id") Integer id); @PutMapping("/{id}") Girl updateGirlById(@PathVariable("id") Integer id, @RequestParam("cupSize") String cupSize, @RequestParam("age") Integer age); @DeleteMapping("/{id}") void removeGirl(@PathVariable("id") Integer id); @GetMapping("/age/{age}") List<Girl> listGirlByAge(@PathVariable("age") Integer age); @PostMapping("/two") void saveGirlTwo(); }
@Test public void listGirlByAge() throws Exception { int age = 18; String response = mockMvc.perform(get("/girls/age/" + age) .contentType(APPLICATION_JSON_UTF8)) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsString(); TypeReference<List<Girl>> typeReference = new TypeReference<List<Girl>>() { }; List<Girl> list = objectMapper.readValue(response, typeReference); System.out.println(list); }
GirlController { @PostMapping("/two") public void saveGirlTwo() { girlService.saveTwo(); } @GetMapping List<Girl> listGirl(); @PostMapping Girl girlAdd(@RequestParam("cupSize") String cupSize, @RequestParam("age") Integer age); @GetMapping("/{id}") Girl getGirlById(@PathVariable("id") Integer id); @PutMapping("/{id}") Girl updateGirlById(@PathVariable("id") Integer id, @RequestParam("cupSize") String cupSize, @RequestParam("age") Integer age); @DeleteMapping("/{id}") void removeGirl(@PathVariable("id") Integer id); @GetMapping("/age/{age}") List<Girl> listGirlByAge(@PathVariable("age") Integer age); @PostMapping("/two") void saveGirlTwo(); }
@Test public void saveGirlTwo() throws Exception { String response = mockMvc.perform(post("/girls/two") .contentType(APPLICATION_JSON_UTF8)) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsString(); System.out.println(response); }
SeckillServiceImpl implements SeckillService { @Override public List<Seckill> getSeckillList() { return seckillDao.queryAll(0, 4); } @Override List<Seckill> getSeckillList(); @Override Seckill getById(long seckillId); @Override Exposer exportSeckillUrl(long seckillId); @Transactional(rollbackFor = Exception.class) @Override SeckillExecution executeSeckill(long seckillId, long userPhone, String md5); @Override SeckillExecution executeSeckillProcedure(long seckillId, long userPhone, String md5); }
@Test public void getSeckillList() throws Exception { List<Seckill> list = seckillService.getSeckillList(); logger.info("list={}",list); }
SeckillServiceImpl implements SeckillService { @Override public Seckill getById(long seckillId) { return seckillDao.queryById(seckillId); } @Override List<Seckill> getSeckillList(); @Override Seckill getById(long seckillId); @Override Exposer exportSeckillUrl(long seckillId); @Transactional(rollbackFor = Exception.class) @Override SeckillExecution executeSeckill(long seckillId, long userPhone, String md5); @Override SeckillExecution executeSeckillProcedure(long seckillId, long userPhone, String md5); }
@Test public void getById() throws Exception { long id = 1000L; Seckill seckill = seckillService.getById(id); logger.info("seckill={}", seckill); }
SeckillServiceImpl implements SeckillService { @Override public SeckillExecution executeSeckillProcedure(long seckillId, long userPhone, String md5) { if (md5 == null || !md5.equals(getMd5(seckillId))) { return new SeckillExecution(seckillId, SeckillStatEnum.DATA_REWRITE); } Date killTime = new Date(); Map<String, Object> map = new HashMap<>(16); map.put("seckillId", seckillId); map.put("phone", userPhone); map.put("killTime", killTime); map.put("result", null); try { seckillDao.killByProcedure(map); int result = MapUtils.getInteger(map, "result", -2); if (result == 1) { SuccessSeckilled sk = successKilledDao.queryByIdWithSeckill(seckillId, userPhone); return new SeckillExecution(seckillId, SeckillStatEnum.SUCCESS, sk); } else { return new SeckillExecution(seckillId, SeckillStatEnum.stateOf(result)); } } catch (Exception e) { logger.error(e.getMessage(), e); return new SeckillExecution(seckillId, SeckillStatEnum.INNER_ERROR); } } @Override List<Seckill> getSeckillList(); @Override Seckill getById(long seckillId); @Override Exposer exportSeckillUrl(long seckillId); @Transactional(rollbackFor = Exception.class) @Override SeckillExecution executeSeckill(long seckillId, long userPhone, String md5); @Override SeckillExecution executeSeckillProcedure(long seckillId, long userPhone, String md5); }
@Test public void executeSeckillProcedure(){ long seckillId = 1001L; long phone = 13621254121L; Exposer exposer = seckillService.exportSeckillUrl(seckillId); if(exposer.isExposed()){ String md5 = exposer.getMd5(); SeckillExecution execution = seckillService.executeSeckillProcedure(seckillId,phone,md5); logger.info(execution.getStateInfo()); } }
BeanAnnotation { public void say(String arg) { System.out.println("BeanAnnotation : " + arg); } void say(String arg); }
@Test public void testSay() { BeanAnnotation bean = super.getBean("beanAnnotation", BeanAnnotation.class); bean.say("This is test."); bean = super.getBean("beanAnnotation", BeanAnnotation.class); bean.say("This is test."); }
BindController { @RequestMapping(value = "set") public String set(UserSetForm userSetForm) { return userSetForm.toString(); } @RequestMapping(value = "/baseType") String baseType(@RequestParam("age") int age); @RequestMapping(value = "/baseType2") String baseType2(Integer age); @RequestMapping(value = "/array") String array(String[] name); @RequestMapping(value = "/object") String object(User user, Admin admin); @InitBinder("user") void initUser(WebDataBinder binder); @InitBinder("admin") void initAdmin(WebDataBinder binder); @RequestMapping(value = "list") String list(UserListForm userListForm); @RequestMapping(value = "set") String set(UserSetForm userSetForm); @RequestMapping(value = "map") String map(UserMapForm userMapForm); @RequestMapping(value = "json") String json(@RequestBody User user); @RequestMapping(value = "xml", consumes = MediaType.APPLICATION_XML_VALUE, produces = MediaType.APPLICATION_XML_VALUE) String xml(@RequestBody Admin admin); @RequestMapping(value = "date1") String date1(Date date1); @InitBinder("date1") void initDate1(WebDataBinder binder); @RequestMapping(value = "date2") String date2(Date date2); @GetMapping(value = "/book") String book(HttpServletRequest request); @GetMapping(value = "/subject/{subjectId}") String getSubject(@PathVariable("subjectId") String subjectId); @PostMapping(value = "/subject/{subjectId}") String postSubject(@PathVariable("subjectId") String subjectId); @DeleteMapping(value = "/subject/{subjectId}") String deleteSubject(@PathVariable("subjectId") String subjectId); @PutMapping(value = "/subject/{subjectId}") String putSubject(@PathVariable("subjectId") String subjectId); }
@Test public void set() throws Exception { MultiValueMap<String, String> params = new LinkedMultiValueMap<>(16); params.add("users[0].name", "Tome"); String response = mockMvc.perform(get("/set") .contentType(APPLICATION_JSON_UTF8) .params(params)) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsString(); System.out.println(response); }
BeanAnnotation { void myHashCode() { System.out.println("BeanAnnotation : " + this.hashCode()); } void say(String arg); }
@Test public void testScpoe() { BeanAnnotation bean = super.getBean("beanAnnotation", BeanAnnotation.class); bean.myHashCode(); bean = super.getBean("beanAnnotation", BeanAnnotation.class); bean.myHashCode(); }
BeanScope { public void say() { System.out.println("BeanScope say : " + this.hashCode()); } void say(); }
@Test public void testSay() { BeanScope beanScope = super.getBean("beanScope", BeanScope.class); beanScope.say(); BeanScope beanScope2 = super.getBean("beanScope", BeanScope.class); beanScope2.say(); } @Test public void testSay2() { BeanScope beanScope = super.getBean("beanScopeSingleton", BeanScope.class); beanScope.say(); BeanScope beanScope2 = super.getBean("beanScopeSingleton", BeanScope.class); beanScope2.say(); }
SessionManager { public Long getSessionId() { return sessionIdProvider.get(); } @Inject SessionManager(@SessionId Provider<Long> sessionIdProvider); Long getSessionId(); }
@Test public void testGetSessionId() throws InterruptedException { Long sessionId1 = sessionManager.getSessionId(); Thread.sleep(1000); Long sessionId2 = sessionManager.getSessionId(); assertNotEquals(sessionId1.longValue(), sessionId2.longValue()); }
OrderSender { public void send(Order order) { CorrelationData correlationData = new CorrelationData(); correlationData.setId(order.getMessageId()); this.rabbitTemplate.convertAndSend("order-exchange", "order.a", order, correlationData); } @Autowired OrderSender( RabbitTemplate rabbitTemplate); void send(Order order); }
@Test public void testSend1() { Order order = new Order(); order.setId("201809062009010001"); order.setName("测试订单1"); order.setMessageId(System.currentTimeMillis() + "$" + UUID.randomUUID().toString().replaceAll("-", "")); this.orderSender.send(order); }
BindController { @RequestMapping(value = "map") public String map(UserMapForm userMapForm) { return userMapForm.toString(); } @RequestMapping(value = "/baseType") String baseType(@RequestParam("age") int age); @RequestMapping(value = "/baseType2") String baseType2(Integer age); @RequestMapping(value = "/array") String array(String[] name); @RequestMapping(value = "/object") String object(User user, Admin admin); @InitBinder("user") void initUser(WebDataBinder binder); @InitBinder("admin") void initAdmin(WebDataBinder binder); @RequestMapping(value = "list") String list(UserListForm userListForm); @RequestMapping(value = "set") String set(UserSetForm userSetForm); @RequestMapping(value = "map") String map(UserMapForm userMapForm); @RequestMapping(value = "json") String json(@RequestBody User user); @RequestMapping(value = "xml", consumes = MediaType.APPLICATION_XML_VALUE, produces = MediaType.APPLICATION_XML_VALUE) String xml(@RequestBody Admin admin); @RequestMapping(value = "date1") String date1(Date date1); @InitBinder("date1") void initDate1(WebDataBinder binder); @RequestMapping(value = "date2") String date2(Date date2); @GetMapping(value = "/book") String book(HttpServletRequest request); @GetMapping(value = "/subject/{subjectId}") String getSubject(@PathVariable("subjectId") String subjectId); @PostMapping(value = "/subject/{subjectId}") String postSubject(@PathVariable("subjectId") String subjectId); @DeleteMapping(value = "/subject/{subjectId}") String deleteSubject(@PathVariable("subjectId") String subjectId); @PutMapping(value = "/subject/{subjectId}") String putSubject(@PathVariable("subjectId") String subjectId); }
@Test public void map() throws Exception { MultiValueMap<String, String> params = new LinkedMultiValueMap<>(16); params.add("users['x'].name", "Tom"); params.add("users['y'].age", "1"); params.add("users['y'].name", "Lucy"); String response = mockMvc.perform(get("/map") .contentType(APPLICATION_JSON_UTF8) .params(params)) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsString(); System.out.println(response); }
BindController { @RequestMapping(value = "json") public String json(@RequestBody User user) { return user.toString(); } @RequestMapping(value = "/baseType") String baseType(@RequestParam("age") int age); @RequestMapping(value = "/baseType2") String baseType2(Integer age); @RequestMapping(value = "/array") String array(String[] name); @RequestMapping(value = "/object") String object(User user, Admin admin); @InitBinder("user") void initUser(WebDataBinder binder); @InitBinder("admin") void initAdmin(WebDataBinder binder); @RequestMapping(value = "list") String list(UserListForm userListForm); @RequestMapping(value = "set") String set(UserSetForm userSetForm); @RequestMapping(value = "map") String map(UserMapForm userMapForm); @RequestMapping(value = "json") String json(@RequestBody User user); @RequestMapping(value = "xml", consumes = MediaType.APPLICATION_XML_VALUE, produces = MediaType.APPLICATION_XML_VALUE) String xml(@RequestBody Admin admin); @RequestMapping(value = "date1") String date1(Date date1); @InitBinder("date1") void initDate1(WebDataBinder binder); @RequestMapping(value = "date2") String date2(Date date2); @GetMapping(value = "/book") String book(HttpServletRequest request); @GetMapping(value = "/subject/{subjectId}") String getSubject(@PathVariable("subjectId") String subjectId); @PostMapping(value = "/subject/{subjectId}") String postSubject(@PathVariable("subjectId") String subjectId); @DeleteMapping(value = "/subject/{subjectId}") String deleteSubject(@PathVariable("subjectId") String subjectId); @PutMapping(value = "/subject/{subjectId}") String putSubject(@PathVariable("subjectId") String subjectId); }
@Test public void json() throws Exception { User user = new User(); user.setName("Jim"); user.setAge(16); ContactInfo contactInfo = new ContactInfo(); contactInfo.setAddress("beijing"); contactInfo.setPhone("10010"); user.setContactInfo(contactInfo); String request = super.objectMapper.writeValueAsString(user); System.out.println(request); String response = mockMvc.perform(post("/json") .contentType(APPLICATION_JSON_UTF8) .content(request)) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsString(); System.out.println(response); }
BindController { @RequestMapping(value = "xml", consumes = MediaType.APPLICATION_XML_VALUE, produces = MediaType.APPLICATION_XML_VALUE) public String xml(@RequestBody Admin admin) { return admin.toString(); } @RequestMapping(value = "/baseType") String baseType(@RequestParam("age") int age); @RequestMapping(value = "/baseType2") String baseType2(Integer age); @RequestMapping(value = "/array") String array(String[] name); @RequestMapping(value = "/object") String object(User user, Admin admin); @InitBinder("user") void initUser(WebDataBinder binder); @InitBinder("admin") void initAdmin(WebDataBinder binder); @RequestMapping(value = "list") String list(UserListForm userListForm); @RequestMapping(value = "set") String set(UserSetForm userSetForm); @RequestMapping(value = "map") String map(UserMapForm userMapForm); @RequestMapping(value = "json") String json(@RequestBody User user); @RequestMapping(value = "xml", consumes = MediaType.APPLICATION_XML_VALUE, produces = MediaType.APPLICATION_XML_VALUE) String xml(@RequestBody Admin admin); @RequestMapping(value = "date1") String date1(Date date1); @InitBinder("date1") void initDate1(WebDataBinder binder); @RequestMapping(value = "date2") String date2(Date date2); @GetMapping(value = "/book") String book(HttpServletRequest request); @GetMapping(value = "/subject/{subjectId}") String getSubject(@PathVariable("subjectId") String subjectId); @PostMapping(value = "/subject/{subjectId}") String postSubject(@PathVariable("subjectId") String subjectId); @DeleteMapping(value = "/subject/{subjectId}") String deleteSubject(@PathVariable("subjectId") String subjectId); @PutMapping(value = "/subject/{subjectId}") String putSubject(@PathVariable("subjectId") String subjectId); }
@Test public void xml() throws Exception { String request = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><admin><name>Jim</name><age>18</age></admin>"; String response = mockMvc.perform(post("/xml") .contentType(APPLICATION_XML_VALUE) .content(request)) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsString(); System.out.println(response); }
BindController { @RequestMapping(value = "date1") public String date1(Date date1) { return date1.toString(); } @RequestMapping(value = "/baseType") String baseType(@RequestParam("age") int age); @RequestMapping(value = "/baseType2") String baseType2(Integer age); @RequestMapping(value = "/array") String array(String[] name); @RequestMapping(value = "/object") String object(User user, Admin admin); @InitBinder("user") void initUser(WebDataBinder binder); @InitBinder("admin") void initAdmin(WebDataBinder binder); @RequestMapping(value = "list") String list(UserListForm userListForm); @RequestMapping(value = "set") String set(UserSetForm userSetForm); @RequestMapping(value = "map") String map(UserMapForm userMapForm); @RequestMapping(value = "json") String json(@RequestBody User user); @RequestMapping(value = "xml", consumes = MediaType.APPLICATION_XML_VALUE, produces = MediaType.APPLICATION_XML_VALUE) String xml(@RequestBody Admin admin); @RequestMapping(value = "date1") String date1(Date date1); @InitBinder("date1") void initDate1(WebDataBinder binder); @RequestMapping(value = "date2") String date2(Date date2); @GetMapping(value = "/book") String book(HttpServletRequest request); @GetMapping(value = "/subject/{subjectId}") String getSubject(@PathVariable("subjectId") String subjectId); @PostMapping(value = "/subject/{subjectId}") String postSubject(@PathVariable("subjectId") String subjectId); @DeleteMapping(value = "/subject/{subjectId}") String deleteSubject(@PathVariable("subjectId") String subjectId); @PutMapping(value = "/subject/{subjectId}") String putSubject(@PathVariable("subjectId") String subjectId); }
@Test public void date1() throws Exception { MultiValueMap<String, String> params = new LinkedMultiValueMap<>(16); params.add("date1", "2020-03-14"); String response = mockMvc.perform(get("/date1") .contentType(APPLICATION_JSON_UTF8) .params(params)) .andExpect(status().isOk()) .andReturn() .getResponse() .getContentAsString(); System.out.println(response); }
ViewPagerAnimator implements ViewPager.OnPageChangeListener { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { if (position == 0 && positionOffsetPixels == 0 && !isAnimating()) { onPageSelected(0); } if (isAnimating() && lastPosition != position || positionOffsetPixels == 0) { endAnimation(position); } if (positionOffsetPixels > 0) { beginAnimation(position); } if (isAnimating()) { float fraction = interpolator.getInterpolation(positionOffset); V value = evaluator.evaluate(fraction, startValue, endValue); property.set(value); } lastPosition = position; } ViewPagerAnimator(@NonNull ViewPager viewPager, @NonNull Provider<V> provider, @NonNull Property<V> property, @NonNull TypeEvaluator<V> evaluator); ViewPagerAnimator(@NonNull ViewPager viewPager, @NonNull Provider<V> provider, @NonNull Property<V> property, @NonNull TypeEvaluator<V> evaluator, @NonNull Interpolator interpolator); static ViewPagerAnimator<Integer> ofInt(ViewPager viewPager, Provider<Integer> provider, Property<Integer> property); static ViewPagerAnimator<Integer> ofArgb(ViewPager viewPager, Provider<Integer> provider, Property<Integer> property); static ViewPagerAnimator<Number> ofFloat(ViewPager viewPager, Provider<Number> provider, Property<Number> property); @Override void onPageScrolled(int position, float positionOffset, int positionOffsetPixels); @Override void onPageSelected(int position); @Override void onPageScrollStateChanged(int state); void destroy(); void setViewPager(ViewPager viewPager); void setInterpolator(Interpolator newInterpolator); }
@Test public void givenAStartedIntegerAnimation_whenWeReverseDirectionPastAPageBoundary_thenTheFractionValueIsCorrect() { integerAnimator.onPageScrolled(1, 0f, 0); integerAnimator.onPageScrolled(1, 0.1f, 10); integerAnimator.onPageScrolled(0, 0.9f, 90); assertThat(integerProperty.get()).isEqualTo(90); } @Test public void givenAnIdleIntegerAnimation_whenWeDragTheViewPager_thenTheAnimationStarts() { integerAnimator.onPageScrolled(1, 0f, 0); integerAnimator.onPageScrolled(0, 0.9f, 90); assertThat(integerProperty.get()).isEqualTo(90); } @Test public void givenANewlyCreatedIntegerAnimation_whenItIsInitialised_thenThePageIsSet() { integerAnimator.onPageScrolled(0, 0f, 0); verify(integerProperty, times(1)).set(eq(0)); } @Test public void givenAStartedFloatAnimation_whenWeReverseDirectionPastAPageBoundary_thenTheFractionValueIsCorrect() { numberAnimator.onPageScrolled(1, 0f, 0); numberAnimator.onPageScrolled(1, 0.1f, 10); numberAnimator.onPageScrolled(0, 0.9f, 90); assertThat(numberProperty.get()).isEqualTo(0.9f); } @Test public void givenAStartedArgbAnimation_whenWeReverseDirectionPastAPageBoundary_thenTheFractionValueIsCorrect() { argbAnimator.onPageScrolled(1, 0f, 0); argbAnimator.onPageScrolled(1, 0.1f, 10); argbAnimator.onPageScrolled(0, 0.9f, 90); assertThat(argbProperty.get()).isEqualTo(0xFF1AE500); }
ViewPagerAnimator implements ViewPager.OnPageChangeListener { public void destroy() { viewPager.removeOnPageChangeListener(this); } ViewPagerAnimator(@NonNull ViewPager viewPager, @NonNull Provider<V> provider, @NonNull Property<V> property, @NonNull TypeEvaluator<V> evaluator); ViewPagerAnimator(@NonNull ViewPager viewPager, @NonNull Provider<V> provider, @NonNull Property<V> property, @NonNull TypeEvaluator<V> evaluator, @NonNull Interpolator interpolator); static ViewPagerAnimator<Integer> ofInt(ViewPager viewPager, Provider<Integer> provider, Property<Integer> property); static ViewPagerAnimator<Integer> ofArgb(ViewPager viewPager, Provider<Integer> provider, Property<Integer> property); static ViewPagerAnimator<Number> ofFloat(ViewPager viewPager, Provider<Number> provider, Property<Number> property); @Override void onPageScrolled(int position, float positionOffset, int positionOffsetPixels); @Override void onPageSelected(int position); @Override void onPageScrollStateChanged(int state); void destroy(); void setViewPager(ViewPager viewPager); void setInterpolator(Interpolator newInterpolator); }
@Test public void givenAnInitialisedIntegerAnimation_whenDestroyIt_thenItIsDetachedFromTheViewPager() { integerAnimator.destroy(); verify(integerViewPager, times(1)).removeOnPageChangeListener(eq(integerAnimator)); }
RestCurseProvider implements BitcoinCurseProvider { @Override public BitcoinCurse getCurrentCurse() { if(lastCurse == null || ttlIsOver()) { try { lastCurse = requestBitcoinCurse(); } catch (IOException e) { log.error("Error while request bitcoin!", e); lastCurse = new BitcoinCurse(DateTime.now().minusDays(1), null, null); } lastCall = DateTime.now(); } return lastCurse; } @Override BitcoinCurse getCurrentCurse(); static final String ENDPOINT; }
@Test public void request(){ BitcoinCurse currentCurse = provider.getCurrentCurse(); assertNotNull(currentCurse.getDate()); assertNotNull(currentCurse.getCoin()); assertNotNull(currentCurse.getEuro()); BitcoinCurse currentCurse2 = provider.getCurrentCurse(); assertSame(currentCurse, currentCurse2); }
SpeechService { public OutputSpeech speechError(Throwable t) { final String speechText; if (t instanceof AlexaExcpetion) { speechText = messageService.de(((AlexaExcpetion)t).getMessageKey()); } else { speechText = messageService.de("event.error"); } return speechMessage(speechText); } OutputSpeech speechWelcomeMessage(Locale locale); OutputSpeech speechBye(Locale locale); OutputSpeech speechHelpMessage(Locale locale); OutputSpeech speechGeneralConfirmation(Locale locale); OutputSpeech readEvents(Locale locale, List<Event> events); OutputSpeech readEvents(Locale locale, String moment, List<Event> events); OutputSpeech speechCancelNewEvent(Locale locale); OutputSpeech speechError(Throwable t); OutputSpeech confirmNewEvent(String title, DateTime from, DateTime to, Locale locale); OutputSpeech speechNewEventSaved(Locale locale); OutputSpeech speechConnectWithCalendar(String calendarName, Locale locale); }
@Test public void speechError(){ CalendarReadException e = new CalendarReadException("error"); final PlainTextOutputSpeech result = (PlainTextOutputSpeech)toTest.speechError(e); assertEquals("Es tut mir leid. Ich konnte die Termine nicht auslesen.", result.getText()); }
SpeechService { public OutputSpeech readEvents(Locale locale, List<Event> events) { return readEvents(locale, "", events); } OutputSpeech speechWelcomeMessage(Locale locale); OutputSpeech speechBye(Locale locale); OutputSpeech speechHelpMessage(Locale locale); OutputSpeech speechGeneralConfirmation(Locale locale); OutputSpeech readEvents(Locale locale, List<Event> events); OutputSpeech readEvents(Locale locale, String moment, List<Event> events); OutputSpeech speechCancelNewEvent(Locale locale); OutputSpeech speechError(Throwable t); OutputSpeech confirmNewEvent(String title, DateTime from, DateTime to, Locale locale); OutputSpeech speechNewEventSaved(Locale locale); OutputSpeech speechConnectWithCalendar(String calendarName, Locale locale); }
@Test public void readEvents_empty(){ List<Event> events = Collections.emptyList(); final String moment = "heute"; final PlainTextOutputSpeech result = (PlainTextOutputSpeech)toTest.readEvents(aLocale, moment, events); assertEquals("Es stehen " + moment + " keine Termine an.", result.getText()); } @Test public void readEvents_singleEventTodayNoTime() { Event event = new Event(); event.setStart(DateTime.now(), false); event.setSummary("<summary>"); List<Event> events = Arrays.asList(event); final String moment = "heute"; final SsmlOutputSpeech result = (SsmlOutputSpeech)toTest.readEvents(aLocale, moment, events); assertEquals("<speak>Folgende Termine stehen " + moment + " an:<break time=\"500ms\"/>" + "Heute: " + event.getSummary() + "</speak>", result.getSsml()); } @Test public void readEvents_singleEventTodayIncludesTime() { final DateTime start = DateTime.now(); final Event event = new Event(); event.setStart(start, true); event.setSummary("<summary>"); final List<Event> events = Arrays.asList(event); final String moment = "heute"; final SsmlOutputSpeech result = (SsmlOutputSpeech)toTest.readEvents(aLocale, moment, events); assertEquals("<speak>Folgende Termine stehen " + moment + " an:<break time=\"500ms\"/>" + "Heute um " + start.toString("HH:mm") + " Uhr: " + event.getSummary() + "</speak>", result.getSsml()); } @Test public void readEvents_singleEventTodayDuration() { final DateTime start = DateTime.now(); final DateTime end = start.plusHours(1).plusMinutes(1); final Event event = new Event(); event.setStart(start, true); event.setEnd(end, true); event.setSummary("<summary>"); final List<Event> events = Arrays.asList(event); final String moment = "heute"; final SsmlOutputSpeech result = (SsmlOutputSpeech)toTest.readEvents(aLocale, moment, events); assertEquals("<speak>Folgende Termine stehen " + moment + " an:<break time=\"500ms\"/>" + "Heute von " + start.toString("HH:mm") + " Uhr bis " + end.toString("HH:mm") + " Uhr: " + event.getSummary() + "</speak>", result.getSsml()); } @Test public void readEvents_singleEventTomorrowNoTime() { Event event = new Event(); event.setStart(DateTime.now().plusDays(1), false); event.setSummary("<summary>"); List<Event> events = Arrays.asList(event); final String moment = "morgen"; final SsmlOutputSpeech result = (SsmlOutputSpeech)toTest.readEvents(aLocale, moment, events); assertEquals("<speak>Folgende Termine stehen " + moment + " an:<break time=\"500ms\"/>" + "Morgen: " + event.getSummary() + "</speak>", result.getSsml()); } @Test public void readEvents_singleEventTomorrowIncludesTime() { final DateTime start = DateTime.now().plusDays(1); final Event event = new Event(); event.setStart(start, true); event.setSummary("<summary>"); final List<Event> events = Arrays.asList(event); final String moment = "morgen"; final SsmlOutputSpeech result = (SsmlOutputSpeech)toTest.readEvents(aLocale, moment, events); assertEquals("<speak>Folgende Termine stehen " + moment + " an:<break time=\"500ms\"/>" + "Morgen um " + start.toString("HH:mm") + " Uhr: " + event.getSummary() + "</speak>", result.getSsml()); } @Test public void readEvents_singleEventTomorrowDuration() { final DateTime start = DateTime.now().plusDays(1); final DateTime end = start.plusHours(1).plusMinutes(1); final Event event = new Event(); event.setStart(start, true); event.setEnd(end, true); event.setSummary("<summary>"); final List<Event> events = Arrays.asList(event); final String moment = "morgen"; final SsmlOutputSpeech result = (SsmlOutputSpeech)toTest.readEvents(aLocale, moment, events); assertEquals("<speak>Folgende Termine stehen " + moment + " an:<break time=\"500ms\"/>" + "Morgen von " + start.toString("HH:mm") + " Uhr bis " + end.toString("HH:mm") + " Uhr: " + event.getSummary() + "</speak>", result.getSsml()); } @Test public void readEvents_singleEventNextWeekNoTime() { final DateTime start = DateTime.now().plusWeeks(1); final Event event = new Event(); event.setStart(start, false); event.setSummary("<summary>"); List<Event> events = Arrays.asList(event); final String moment = "morgen"; final SsmlOutputSpeech result = (SsmlOutputSpeech)toTest.readEvents(aLocale, moment, events); assertEquals(String.format("<speak>Folgende Termine stehen %s an:<break time=\"500ms\"/>Am %s, den <say-as interpret-as=\"date\" format=\"dm\">%s</say-as>: %s</speak>", moment, start.toString("EEEE", aLocale), start.toString("dd.MM."), event.getSummary() ), result.getSsml()); } @Test public void readEvents_singleEventNextWeekIncludesTime() { final DateTime start = DateTime.now().plusWeeks(1); final Event event = new Event(); event.setStart(start, true); event.setSummary("<summary>"); final List<Event> events = Arrays.asList(event); final String moment = "morgen"; final SsmlOutputSpeech result = (SsmlOutputSpeech)toTest.readEvents(aLocale, moment, events); assertEquals(String.format("<speak>Folgende Termine stehen %s an:<break time=\"500ms\"/>Am %s, den <say-as interpret-as=\"date\" format=\"dm\">%s</say-as> um %s Uhr: %s</speak>", moment, start.toString("EEEE", aLocale), start.toString("dd.MM."), start.toString("HH:mm"), event.getSummary() ), result.getSsml()); } @Test public void readEvents_singleEventNextWeekDuration() { final DateTime start = DateTime.now().plusWeeks(1); final DateTime end = start.plusHours(1).plusMinutes(1); final Event event = new Event(); event.setStart(start, true); event.setEnd(end, true); event.setSummary("<summary>"); final List<Event> events = Arrays.asList(event); final String moment = "morgen"; final SsmlOutputSpeech result = (SsmlOutputSpeech)toTest.readEvents(aLocale, moment, events); assertEquals(String.format("<speak>Folgende Termine stehen %s an:<break time=\"500ms\"/>Am %s, den <say-as interpret-as=\"date\" format=\"dm\">%s</say-as> von %s Uhr bis %s Uhr: %s</speak>", moment, start.toString("EEEE", aLocale), start.toString("dd.MM."), start.toString("HH:mm"), end.toString("HH:mm"), event.getSummary() ), result.getSsml()); }
ReflectionUtils { public static Object call(Method method, Object target, Argument...arguments) { checkArguments(method, arguments); Object[] methodArguments = collectArguments(method, arguments); return org.springframework.util.ReflectionUtils.invokeMethod(method, target, methodArguments); } static Object call(Method method, Object target, Argument...arguments); }
@Test(expected = IllegalArgumentException.class) public void argumentsNotEnough() throws NoSuchMethodException { TestClass toTest = new TestClass(); Method method = TestClass.class.getMethod("integer", Integer.class); ReflectionUtils.call(method, toTest); } @Test(expected = IllegalArgumentException.class) public void argumentsNotRight() throws NoSuchMethodException { TestClass toTest = new TestClass(); Method method = TestClass.class.getMethod("integer", Integer.class); ReflectionUtils.call(method, toTest, new Argument(Long.class, 13L)); } @Test public void exactMatch() throws NoSuchMethodException { TestClass toTest = new TestClass(); Method method = TestClass.class.getMethod("integer", Integer.class); final Object result = ReflectionUtils.call(method, toTest, new Argument(Integer.class, 13)); assertEquals("integer13", result); } @Test public void oneOfArgumentsMatches() throws NoSuchMethodException { TestClass toTest = new TestClass(); Method method = TestClass.class.getMethod("integer", Integer.class); final Object result = ReflectionUtils.call(method, toTest, new Argument(Integer.class, 13), new Argument(Long.class, 14L)); assertEquals("integer13", result); } @Test public void multipleArgumentsMatches() throws NoSuchMethodException { TestClass toTest = new TestClass(); Method method = TestClass.class.getMethod("integer", Integer.class); final Object result = ReflectionUtils.call(method, toTest, new Argument(Integer.class, 13), new Argument(Integer.class, 14)); assertEquals("integer13", result); } @Test public void subClassMatch() throws NoSuchMethodException { TestClass toTest = new TestClass(); Method method = TestClass.class.getMethod("interfaceMethod", List.class); final Object result = ReflectionUtils.call(method, toTest, new Argument(Integer.class, 13), new Argument(ArrayList.class, new ArrayList())); assertEquals("interfaceArrayList", result); }
SpeechService { public OutputSpeech confirmNewEvent(String title, DateTime from, DateTime to, Locale locale) { final String speechText; if(from.getYear() == to.getYear() && from.getDayOfYear() == to.getDayOfYear()) { speechText = messageService.de("event.new.confirm.sameday", from.toString(DAY_FORMAT, locale), from.toString(DATE_YEAR_FORMAT), from.toString(TIME_FORMAT), to.toString(TIME_FORMAT), title); } else { speechText = messageService.de("event.new.confirm", from.toString(DAY_FORMAT, locale), from.toString(DATE_YEAR_FORMAT), from.toString(TIME_FORMAT), to.toString(DAY_FORMAT, locale), to.toString(DATE_YEAR_FORMAT), to.toString(TIME_FORMAT), title); } return speechMessage(speechText); } OutputSpeech speechWelcomeMessage(Locale locale); OutputSpeech speechBye(Locale locale); OutputSpeech speechHelpMessage(Locale locale); OutputSpeech speechGeneralConfirmation(Locale locale); OutputSpeech readEvents(Locale locale, List<Event> events); OutputSpeech readEvents(Locale locale, String moment, List<Event> events); OutputSpeech speechCancelNewEvent(Locale locale); OutputSpeech speechError(Throwable t); OutputSpeech confirmNewEvent(String title, DateTime from, DateTime to, Locale locale); OutputSpeech speechNewEventSaved(Locale locale); OutputSpeech speechConnectWithCalendar(String calendarName, Locale locale); }
@Test public void confirmNewEvent_sameDay() { final String title = "hello world"; final DateTime from = DateTime.parse("2010-08-13T20:15"); final DateTime to = from.plusHours(1); final SsmlOutputSpeech result = (SsmlOutputSpeech)toTest.confirmNewEvent(title, from, to, aLocale); assertEquals(String.format("<speak>Kann ich den Termin am %s, den <say-as interpret-as=\"date\" format=\"dmy\">%s</say-as> von %s Uhr bis %s Uhr mit dem Titel \"%s\" speichern?</speak>", "Freitag", "13.08.2010", "20:15", "21:15", title ), result.getSsml()); } @Test public void confirmNewEvent_differentDay() { final String title = "hello world"; final DateTime from = DateTime.parse("2010-08-13T20:15"); final DateTime to = from.plusHours(1).plusDays(1); final SsmlOutputSpeech result = (SsmlOutputSpeech)toTest.confirmNewEvent(title, from, to, aLocale); assertEquals(String.format("<speak>Kann ich den Termin von %s, den <say-as interpret-as=\"date\" format=\"dmy\">%s</say-as> um %s Uhr bis %s, den <say-as interpret-as=\"date\" format=\"dm\">%s</say-as> um %s Uhr mit dem Titel \"%s\" speichern?</speak>", "Freitag", "13.08.2010", "20:15", "Samstag", "14.08.2010", "21:15", title ), result.getSsml()); }
SpeechService { public OutputSpeech speechNewEventSaved(Locale locale) { final String speechText = messageService.de("event.new.saved"); return speechMessage(speechText); } OutputSpeech speechWelcomeMessage(Locale locale); OutputSpeech speechBye(Locale locale); OutputSpeech speechHelpMessage(Locale locale); OutputSpeech speechGeneralConfirmation(Locale locale); OutputSpeech readEvents(Locale locale, List<Event> events); OutputSpeech readEvents(Locale locale, String moment, List<Event> events); OutputSpeech speechCancelNewEvent(Locale locale); OutputSpeech speechError(Throwable t); OutputSpeech confirmNewEvent(String title, DateTime from, DateTime to, Locale locale); OutputSpeech speechNewEventSaved(Locale locale); OutputSpeech speechConnectWithCalendar(String calendarName, Locale locale); }
@Test public void speechNewEventSaved(){ final PlainTextOutputSpeech result = (PlainTextOutputSpeech)toTest.speechNewEventSaved(aLocale); assertEquals("OK. Ich habe den Termin gespeichert.", result.getText()); }
SpeechService { public OutputSpeech speechGeneralConfirmation(Locale locale) { final String speechText = messageService.de("confirm"); return speechMessage(speechText); } OutputSpeech speechWelcomeMessage(Locale locale); OutputSpeech speechBye(Locale locale); OutputSpeech speechHelpMessage(Locale locale); OutputSpeech speechGeneralConfirmation(Locale locale); OutputSpeech readEvents(Locale locale, List<Event> events); OutputSpeech readEvents(Locale locale, String moment, List<Event> events); OutputSpeech speechCancelNewEvent(Locale locale); OutputSpeech speechError(Throwable t); OutputSpeech confirmNewEvent(String title, DateTime from, DateTime to, Locale locale); OutputSpeech speechNewEventSaved(Locale locale); OutputSpeech speechConnectWithCalendar(String calendarName, Locale locale); }
@Test public void speechGeneralConfirmation(){ final PlainTextOutputSpeech result = (PlainTextOutputSpeech)toTest.speechGeneralConfirmation(aLocale); assertEquals("OK.", result.getText()); }
CalendarService { public List<Event> getNextEvents() throws CalendarReadException { final DateTime from = DateTime.now(); final DateTime to = from.plusWeeks(1).plusDays(1).withTimeAtStartOfDay(); return getEvents(from, to); } List<Event> getEvents(DateTime from, DateTime to); List<Event> getNextEvents(); String createEvent( final String calendarName, final String summary, final DateTime from, final DateTime to); }
@Test public void getNextEvents() throws CalendarReadException { final List<Event> events = new ArrayList<>(); doReturn(events).when(toTest).getEvents(any(), any()); final DateTime now = DateTime.now(); final List<Event> result = toTest.getNextEvents(); ArgumentCaptor<DateTime> timeCap = ArgumentCaptor.forClass(DateTime.class); assertSame(events, result); verify(toTest, times(1)).getEvents(timeCap.capture(), timeCap.capture()); assertTrue(timeCap.getAllValues().get(0).getMillis() - now.getMillis() <= 1000); assertEquals( now.plusDays(1).plusWeeks(1).withTimeAtStartOfDay().toString(), timeCap.getAllValues().get(1).toString()); }
CalendarService { public List<Event> getEvents(DateTime from, DateTime to) throws CalendarReadException { if(getCalendars() == null) return Collections.emptyList(); try { List<Event> allEvents = new ArrayList<>(); List<Future<List<Event>>> futures = new ArrayList<>(getCalendars().size()); for(CalendarCLIAdapter calendar : getCalendars().values()) { Future<List<Event>> future = executor.submit(() -> { return calendar.readAgenda(from, to).stream() .flatMap(rawEvent -> parser.parseEvent(rawEvent).stream()) .map(vEvent -> mapper.map(vEvent, calendar.getDefaultTimeZone())) .collect(Collectors.toList()); }); futures.add(future); } for(Future<List<Event>> future : futures) { allEvents.addAll(future.get()); } allEvents.sort(Comparator.comparing(Event::getStart)); return allEvents; } catch (Exception e) { throw new CalendarReadException("Could not read calendar.", e); } } List<Event> getEvents(DateTime from, DateTime to); List<Event> getNextEvents(); String createEvent( final String calendarName, final String summary, final DateTime from, final DateTime to); }
@Test public void getEvents() throws IOException, CalendarReadException { final CalendarCLIAdapter calendarOne = mock(CalendarCLIAdapter.class); final CalendarCLIAdapter calendarTwo = mock(CalendarCLIAdapter.class); final Map<String, CalendarCLIAdapter> calendars = new HashMap<>(); calendars.put("one", calendarOne); calendars.put("two", calendarTwo); doReturn(TimeZone.getTimeZone("UTC")).when(calendarOne).getDefaultTimeZone(); doReturn(TimeZone.getTimeZone("Europe/Berlin")).when(calendarTwo).getDefaultTimeZone(); when(calendarOne.readAgenda(any(), any())) .thenReturn(Arrays.asList("<cal1-event1>", "<cal1-event2>")); when(calendarTwo.readAgenda(any(), any())) .thenReturn(Arrays.asList("<cal2-event1>")); doReturn(calendars).when(toTest).getCalendars(); List<VEvent> cal1Event1 = Arrays.asList(e("cal1e1", DateTime.parse("2000-01-01"))); List<VEvent> cal1Event2 = Arrays.asList(e("cal1e2", DateTime.parse("2010-01-01")), e("cal1e3", DateTime.parse("2000-01-02"))); List<VEvent> cal2Event1 = Arrays.asList(e("cal2e1", DateTime.parse("2000-01-01"))); doReturn(cal1Event1).when(parser).parseEvent(eq("<cal1-event1>")); doReturn(cal1Event2).when(parser).parseEvent(eq("<cal1-event2>")); doReturn(cal2Event1).when(parser).parseEvent(eq("<cal2-event1>")); final DateTime from = DateTime.now(); final DateTime to = DateTime.now().plusDays(1); final List<Event> results = toTest.getEvents(from, to); verify(calendarOne, times(1)).readAgenda(from, to); verify(calendarTwo, times(1)).readAgenda(from, to); assertEquals("cal1e1", results.get(0).getSummary()); assertEquals("cal2e1", results.get(1).getSummary()); assertEquals("cal1e3", results.get(2).getSummary()); assertEquals("cal1e2", results.get(3).getSummary()); }
CalendarCLIAdapter { public List<String> readAgenda(DateTime from, DateTime to) throws IOException { List<String> subCommands = new ArrayList<>(); subCommands.add("--icalendar"); subCommands.add("calendar"); subCommands.add("agenda"); if(from != null) { subCommands.add("--from-time"); subCommands.add(from.toString()); } if(to != null) { subCommands.add("--to-time"); subCommands.add(to.toString()); } final String rawOutput = execute(subCommands); List<String> rawEvents = new ArrayList<>(); StringBuilder sb = new StringBuilder(); for(String line : rawOutput.split("\n")){ if(line.isEmpty() && sb.length() > 0) { rawEvents.add(sb.toString().trim()); sb = new StringBuilder(); } sb.append(line); sb.append("\n"); } if(sb.length() > 0) { rawEvents.add(sb.toString().trim()); } Iterator<String> iter = rawEvents.iterator(); while (iter.hasNext()) { if(iter.next().isEmpty()) { iter.remove(); } } return rawEvents; } CalendarCLIAdapter(String caldavURL, String caldavUser, String caldavPassword, String calendarURL); CalendarCLIAdapter(String caldavURL, String caldavUser, String caldavPassword, String calendarURL, TimeZone tz); TimeZone getDefaultTimeZone(); List<String> readAgenda(DateTime from, DateTime to); String createEvent(final String summary, final DateTime from, final DateTime to); }
@Test public void readAgenda() throws IOException { final DateTime from = DateTime.now().minusDays(1); final DateTime to = from.plusDays(2); List<String> result = toTest.readAgenda(from, to); assertTrue(result.isEmpty()); ArgumentCaptor<CommandLine> cmdCap = ArgumentCaptor.forClass(CommandLine.class); verify(toTest, times(1)).doExecute(cmdCap.capture(), any()); assertEquals("calendar-cli.py", cmdCap.getValue().getExecutable()); assertEquals(15, cmdCap.getValue().getArguments().length); assertEquals("--caldav-url", cmdCap.getValue().getArguments()[0]); assertEquals(CALDAV_URL, cmdCap.getValue().getArguments()[1]); assertEquals("--caldav-user", cmdCap.getValue().getArguments()[2]); assertEquals(CALDAV_USER, cmdCap.getValue().getArguments()[3]); assertEquals("--caldav-pass", cmdCap.getValue().getArguments()[4]); assertEquals(CALDAV_PASSWORD, cmdCap.getValue().getArguments()[5]); assertEquals("--calendar-url", cmdCap.getValue().getArguments()[6]); assertEquals(CALENDAR_URL, cmdCap.getValue().getArguments()[7]); assertEquals("--icalendar", cmdCap.getValue().getArguments()[8]); assertEquals("calendar", cmdCap.getValue().getArguments()[9]); assertEquals("agenda", cmdCap.getValue().getArguments()[10]); assertEquals("--from-time", cmdCap.getValue().getArguments()[11]); assertEquals(from.toString(), cmdCap.getValue().getArguments()[12]); assertEquals("--to-time", cmdCap.getValue().getArguments()[13]); assertEquals(to.toString(), cmdCap.getValue().getArguments()[14]); }
CalendarCLIAdapter { public String createEvent(final String summary, final DateTime from, final DateTime to) throws IOException { List<String> subCommands = new ArrayList<>(); subCommands.add("calendar"); subCommands.add("add"); final Duration duration = new Interval(from, to).toDuration(); final StringBuilder eventTime = new StringBuilder(); eventTime.append(from.toString("yyyy-MM-dd'T'HH:mm")); eventTime.append("+"); eventTime.append(duration.getStandardMinutes()); eventTime.append("m"); subCommands.add(eventTime.toString()); subCommands.add(summary); final String rawOutput = execute(subCommands); final String uid; final Matcher matcher = eventUUID.matcher(rawOutput); if(matcher.find()) { uid = matcher.group(1); }else{ uid = "<unknown>"; } return uid; } CalendarCLIAdapter(String caldavURL, String caldavUser, String caldavPassword, String calendarURL); CalendarCLIAdapter(String caldavURL, String caldavUser, String caldavPassword, String calendarURL, TimeZone tz); TimeZone getDefaultTimeZone(); List<String> readAgenda(DateTime from, DateTime to); String createEvent(final String summary, final DateTime from, final DateTime to); }
@Test public void createEvent() throws IOException { final String summary = "<summary>"; final DateTime from = DateTime.parse("2010-08-13T20:15:00"); final DateTime to = from.plusDays(1).plusHours(1).plusMinutes(1); doAnswer((inv) -> { OutputStream os = (OutputStream)ReflectionTestUtils.getField( ((DefaultExecutor)inv.getArguments()[1]).getStreamHandler(), "out"); os.write("Added event with uid=578ee4a3-3330-11e7-a7d0-0242ac130006\n".getBytes()); return null; }).when(toTest).doExecute(any(), any()); final String result = toTest.createEvent(summary, from, to); assertEquals("578ee4a3-3330-11e7-a7d0-0242ac130006", result); ArgumentCaptor<CommandLine> cmdCap = ArgumentCaptor.forClass(CommandLine.class); verify(toTest, times(1)).doExecute(cmdCap.capture(), any()); assertEquals("--caldav-url", cmdCap.getValue().getArguments()[0]); assertEquals(CALDAV_URL, cmdCap.getValue().getArguments()[1]); assertEquals("--caldav-user", cmdCap.getValue().getArguments()[2]); assertEquals(CALDAV_USER, cmdCap.getValue().getArguments()[3]); assertEquals("--caldav-pass", cmdCap.getValue().getArguments()[4]); assertEquals(CALDAV_PASSWORD, cmdCap.getValue().getArguments()[5]); assertEquals("--calendar-url", cmdCap.getValue().getArguments()[6]); assertEquals(CALENDAR_URL, cmdCap.getValue().getArguments()[7]); assertEquals("calendar", cmdCap.getValue().getArguments()[8]); assertEquals("add", cmdCap.getValue().getArguments()[9]); assertEquals("2010-08-13T20:15+1501m", cmdCap.getValue().getArguments()[10]); assertEquals(summary, cmdCap.getValue().getArguments()[11]); }
ICalendarParser { public List<VEvent> parseEvents(List<String> rawEvents) { List<VEvent> events = rawEvents.stream() .flatMap(raw -> parseEvent(raw).stream()) .collect(Collectors.toList()); return events; } List<VEvent> parseEvents(List<String> rawEvents); List<VEvent> parseEvent(String rawEvent); }
@Test public void testParser(){ List<String> rawEvents = Arrays.asList( "BEGIN:VCALENDAR\n" + "VERSION:2.0\n" + "PRODID:- + "CALSCALE:GREGORIAN\n" + "BEGIN:VEVENT\n" + "DTSTAMP:20170411T200614Z\n" + "UID:20170411T200614Z-2ce178178dd977ce\n" + "DTSTART;VALUE=DATE:20170527\n" + "DTEND;VALUE=DATE:20170528\n" + "SUMMARY:Great Event!\n" + "STATUS:TENTATIVE\n" + "BEGIN:VALARM\n" + "TRIGGER:-PT420M\n" + "ACTION:DISPLAY\n" + "DESCRIPTION:Great Event!\n" + "END:VALARM\n" + "END:VEVENT\n" + "END:VCALENDAR", "BEGIN:VCALENDAR\n" + "VERSION:2.0\n" + "PRODID:- + "CALSCALE:GREGORIAN\n" + "BEGIN:VEVENT\n" + "DTSTAMP:20170427T162550Z\n" + "UID:20170427T162550Z-2ce178178dd977ce\n" + "DTSTART:20170524T120000Z\n" + "DTEND:20170524T140000Z\n" + "SUMMARY:Birthdayparteeeeeeeeyyyy\n" + "LOCATION:@Home\n" + "STATUS:TENTATIVE\n" + "BEGIN:VALARM\n" + "TRIGGER:-PT10M\n" + "ACTION:DISPLAY\n" + "DESCRIPTION:Birthdayparteeeeeeeeyyyy\n" + "END:VALARM\n" + "END:VEVENT\n" + "END:VCALENDAR", "BEGIN:VCALENDAR\n" + "VERSION:2.0\n" + "PRODID:- + "CALSCALE:GREGORIAN\n" + "BEGIN:VEVENT\n" + "DTSTAMP:20170430T163825Z\n" + "UID:20170412T100903Z-2ce178178dd977ce\n" + "SEQUENCE:2\n" + "SUMMARY:Doctor\n" + "DESCRIPTION:Goto doctor right now!\n" + "STATUS:TENTATIVE\n" + "CLASS:PUBLIC\n" + "DTSTART:20170503T080000Z\n" + "DTEND:20170503T090000Z\n" + "BEGIN:VALARM\n" + "TRIGGER:-P1D\n" + "ACTION;X-NC-GROUP-ID=0:DISPLAY\n" + "DESCRIPTION:Doctor\n" + "END:VALARM\n" + "END:VEVENT\n" + "END:VCALENDAR"); List<VEvent> result = toTest.parseEvents(rawEvents); assertEquals(rawEvents.size(), result.size()); }
EventMapper { public Event map(VEvent event, TimeZone defaultTimeZone) { Event result = new Event(); nullSave(() -> { final DateTime start = new DateTime(event.getDateStart().getValue().getTime(), DateTimeZone.forTimeZone(defaultTimeZone)); result.setStart(start, event.getDateStart().getValue().hasTime()); }); nullSave(() -> { final DateTime end = new DateTime(event.getDateEnd().getValue().getTime(), DateTimeZone.forTimeZone(defaultTimeZone)); result.setEnd(end, event.getDateStart().getValue().hasTime()); }); nullSave(() -> result.setSummary(event.getSummary().getValue())); nullSave(() -> result.setDescription(event.getDescription().getValue())); return result; } Event map(VEvent event, TimeZone defaultTimeZone); }
@Test public void map() { final VEvent event = new VEvent(); event.setDateStart(DateTime.parse("2009-12-15T22:15:00").withZone(DateTimeZone.UTC).toDate(), true); event.setDateEnd(DateTime.parse("2010-08-13T20:15:00").withZone(DateTimeZone.UTC).toDate(), true); event.setSummary("<summary>"); event.setDescription("<description>"); final TimeZone tz = TimeZone.getTimeZone("Europe/Berlin"); final Event result = toTest.map(event, tz); assertEquals(DateTime.parse("2009-12-15T22:15:00").withZone(DateTimeZone.forID("Europe/Berlin")).toString(), result.getStart().toString()); assertEquals(DateTime.parse("2010-08-13T20:15:00").withZone(DateTimeZone.forID("Europe/Berlin")).toString(), result.getEnd().toString()); assertEquals("<summary>", result.getSummary()); assertEquals("<description>", result.getDescription()); } @Test public void map_noTime() { final VEvent event = new VEvent(); event.setDateStart(DateTime.parse("2009-12-15T22:15:00").withZone(DateTimeZone.UTC).toDate(), false); event.setDateEnd(DateTime.parse("2010-08-13T21:15:00").withZone(DateTimeZone.UTC).toDate(), false); event.setSummary("<summary>"); event.setDescription("<description>"); final TimeZone tz = TimeZone.getTimeZone("Europe/Berlin"); final Event result = toTest.map(event, tz); assertEquals(DateTime.parse("2009-12-15T00:00:00").withZone(DateTimeZone.forID("Europe/Berlin")).toString(), result.getStart().toString()); assertEquals(DateTime.parse("2010-08-13T00:00:00").withZone(DateTimeZone.forID("Europe/Berlin")).toString(), result.getEnd().toString()); assertEquals("<summary>", result.getSummary()); assertEquals("<description>", result.getDescription()); } @Test public void map_nullSave() { final VEvent event = new VEvent(); final TimeZone tz = TimeZone.getTimeZone("Europe/Berlin"); final Event result = toTest.map(event, tz); assertNull(result.getStart()); assertNull(result.getEnd()); assertNull(result.getSummary()); assertNull(result.getDescription()); }
NewEventSpeechlet { @OnIntent("NewEvent") public SpeechletResponse handleDialogAction(final IntentRequest request, final Session session) throws CalendarWriteException { session.setAttribute(BasicSpeechlet.KEY_DIALOG_TYPE, BasicSpeechlet.DIALOG_TYPE_NEW_EVENT); final SpeechletResponse response; try { switch (request.getIntent().getConfirmationStatus()) { default: case NONE: response = handleProgress(request, session); break; case CONFIRMED: response = handleConfirmed(request, session); break; case DENIED: response = handleDenied(request, session); break; } } catch (CalendarWriteException e) { return SpeechletResponse.newTellResponse(speechService.speechError(e)); } response.setShouldEndSession(false); return response; } @OnIntent("NewEvent") SpeechletResponse handleDialogAction(final IntentRequest request, final Session session); @OnIntent("SetCalendarInSession") SpeechletResponse handleSetCalendarInSession(IntentRequest request, Session session); static final String SLOT_PREFIX_SUMMARY; static final String SLOT_DATE_FROM; static final String SLOT_TIME_FROM; static final String SLOT_DATE_TO; static final String SLOT_TIME_TO; static final String SLOT_DURATION; static final String SLOT_CALENDAR; static final String SESSION_FROM; static final String SESSION_TO; static final String SESSION_DATE_FORMAT; static final String SESSION_CALENDAR; }
@Test public void inProgress_NotAllSlotsAreFilled() throws CalendarWriteException { final Session session = Session.builder() .withSessionId("<session-id>") .build(); final Intent intent = Intent.builder() .withName("<intent>") .withSlots(slots( slot("day", null) )) .build(); final IntentRequest request = IntentRequest.builder() .withRequestId("<requestId>") .withIntent(intent) .withDialogState(DialogState.IN_PROGRESS) .build(); final SpeechletResponse response = toTest.handleDialogAction(request, session); assertEquals( json(SpeechletResponse.newDialogDelegateResponse(intent)), json(response)); } @Test public void inProgress_AllSlotsAreFilled() throws CalendarWriteException { final Intent intent = Intent.builder() .withName("<intent>") .withSlots(slots( slot(SLOT_DATE_FROM, "2010-08-13"), slot(SLOT_TIME_FROM, "20:15"), slot(SLOT_DURATION, "PT2H"), slot(SLOT_PREFIX_SUMMARY, "Title") )) .build(); final IntentRequest request = IntentRequest.builder() .withRequestId("<requestId>") .withLocale(Locale.GERMANY) .withIntent(intent) .withDialogState(DialogState.IN_PROGRESS) .build(); final Session session = Session.builder() .withSessionId("<sessionId>") .build(); final PlainTextOutputSpeech speech = new PlainTextOutputSpeech(); speech.setText("<confirm>"); doReturn(speech).when(speechService).confirmNewEvent(any(), any(), any(), any()); final SpeechletResponse response = toTest.handleDialogAction(request, session); ArgumentCaptor<DateTime> dateCap = ArgumentCaptor.forClass(DateTime.class); assertEquals( json(SpeechletResponse.newDialogConfirmIntentResponse(speech)), json(response)); verify(speechService, times(1)).confirmNewEvent( eq("Title"), dateCap.capture(), dateCap.capture(), same(request.getLocale())); assertEquals("dd.MM.yyyy HH:mm", session.getAttribute(SESSION_DATE_FORMAT)); assertEquals("13.08.2010 20:15", session.getAttribute(SESSION_FROM)); assertEquals("13.08.2010 22:15", session.getAttribute(SESSION_TO)); assertEquals(DateTime.parse("2010-08-13T20:15"), dateCap.getAllValues().get(0)); assertEquals(DateTime.parse("2010-08-13T22:15"), dateCap.getAllValues().get(1)); } @Test public void denied() throws CalendarWriteException { final Session session = Session.builder() .withSessionId("<session-id>") .build(); final Intent intent = Intent.builder() .withName("<intent>") .withConfirmationStatus(ConfirmationStatus.DENIED) .build(); final IntentRequest request = IntentRequest.builder() .withRequestId("<requestId>") .withLocale(Locale.GERMANY) .withIntent(intent) .withDialogState(DialogState.IN_PROGRESS) .build(); final PlainTextOutputSpeech speech = new PlainTextOutputSpeech(); speech.setText("<cancel>"); doReturn(speech).when(speechService).speechCancelNewEvent(any()); final SpeechletResponse response = toTest.handleDialogAction(request, session); verify(speechService, times(1)).speechCancelNewEvent(eq(request.getLocale())); final SpeechletResponse expected = SpeechletResponse .newTellResponse(speechService.speechCancelNewEvent(request.getLocale())); expected.setShouldEndSession(false); assertEquals(json(expected), json(response)); } @Test public void confirmed() throws CalendarWriteException { final Intent intent = Intent.builder() .withName("<intent>") .withSlots(slots( slot(SLOT_DATE_FROM, "2010-08-13"), slot(SLOT_TIME_FROM, "20:15"), slot(SLOT_DURATION, "PT2H"), slot(SLOT_PREFIX_SUMMARY, "Title") )) .withConfirmationStatus(ConfirmationStatus.CONFIRMED) .build(); final IntentRequest request = IntentRequest.builder() .withRequestId("<requestId>") .withLocale(Locale.GERMANY) .withIntent(intent) .withDialogState(DialogState.IN_PROGRESS) .build(); final Session session = Session.builder() .withSessionId("<sessionId>") .withAttributes(attributes( attribute(SESSION_FROM, "13.08.2010 20:15"), attribute(SESSION_TO, "13.08.2010 22:15"), attribute(SESSION_DATE_FORMAT, "dd.MM.yyyy HH:mm") )) .build(); final PlainTextOutputSpeech speech = new PlainTextOutputSpeech(); speech.setText("<event-saved>"); doReturn(speech).when(speechService).speechNewEventSaved(any()); final SimpleCard card = new SimpleCard(); card.setTitle("Neuer Termin erstellt"); card.setContent("Titel: Title\nBeginn: 13.08.2010 20:15\nEnde:13.08.2010 22:15"); final SpeechletResponse response = toTest.handleDialogAction(request, session); verify(speechService, times(1)).speechNewEventSaved(eq(request.getLocale())); verify(calendarService, times(1)).createEvent( null, "Title", DateTime.parse("2010-08-13T20:15"), DateTime.parse("2010-08-13T22:15")); final SpeechletResponse expected = SpeechletResponse .newTellResponse(speechService.speechNewEventSaved(request.getLocale()), card); expected.setShouldEndSession(false); assertEquals(json(expected), json(response)); }
NewEventSpeechlet { private String checkCalendarName(IntentRequest request, Session session) { if(sv(request, SLOT_CALENDAR) == null) { return null; } final String givenName = sv(request, SLOT_CALENDAR); if(givenName == null) { return null; } final String foundName = findCalendarName(givenName); session.setAttribute(SESSION_CALENDAR, foundName); return foundName; } @OnIntent("NewEvent") SpeechletResponse handleDialogAction(final IntentRequest request, final Session session); @OnIntent("SetCalendarInSession") SpeechletResponse handleSetCalendarInSession(IntentRequest request, Session session); static final String SLOT_PREFIX_SUMMARY; static final String SLOT_DATE_FROM; static final String SLOT_TIME_FROM; static final String SLOT_DATE_TO; static final String SLOT_TIME_TO; static final String SLOT_DURATION; static final String SLOT_CALENDAR; static final String SESSION_FROM; static final String SESSION_TO; static final String SESSION_DATE_FORMAT; static final String SESSION_CALENDAR; }
@Test public void inProgress_CalendarName() throws CalendarWriteException { checkCalendarName("geburtstag", "Geburtstage"); checkCalendarName("geburt", "Geburtstage"); checkCalendarName("termin", "Termine"); checkCalendarName("termine", "Termine"); checkCalendarName("haus", "Haushalt"); checkCalendarName("haushalt", "Haushalt"); checkCalendarName("Progammierung", null); }
MessageService { public String de(String key, Object...args) { return String.format(messages.getOrDefault(key, key), args); } String de(String key, Object...args); }
@Test public void de(){ final String messageKey = "help"; final String result = toTest.de(messageKey); assertEquals("Frage mich: was ansteht, um die aktuellen Termine zu erfahren. Oder trage einen neuen Termin ein.", result); }
SpeechService { public OutputSpeech speechWelcomeMessage(Locale locale) { final String speechText = messageService.de("welcome"); return speechMessage(speechText); } OutputSpeech speechWelcomeMessage(Locale locale); OutputSpeech speechBye(Locale locale); OutputSpeech speechHelpMessage(Locale locale); OutputSpeech speechGeneralConfirmation(Locale locale); OutputSpeech readEvents(Locale locale, List<Event> events); OutputSpeech readEvents(Locale locale, String moment, List<Event> events); OutputSpeech speechCancelNewEvent(Locale locale); OutputSpeech speechError(Throwable t); OutputSpeech confirmNewEvent(String title, DateTime from, DateTime to, Locale locale); OutputSpeech speechNewEventSaved(Locale locale); OutputSpeech speechConnectWithCalendar(String calendarName, Locale locale); }
@Test public void speechWelcomeMessage(){ final PlainTextOutputSpeech result = (PlainTextOutputSpeech)toTest.speechWelcomeMessage(aLocale); assertEquals("Willkommen in deinem Kalender.", result.getText()); }
SpeechService { public OutputSpeech speechHelpMessage(Locale locale) { final String speechText = messageService.de("help"); return speechMessage(speechText); } OutputSpeech speechWelcomeMessage(Locale locale); OutputSpeech speechBye(Locale locale); OutputSpeech speechHelpMessage(Locale locale); OutputSpeech speechGeneralConfirmation(Locale locale); OutputSpeech readEvents(Locale locale, List<Event> events); OutputSpeech readEvents(Locale locale, String moment, List<Event> events); OutputSpeech speechCancelNewEvent(Locale locale); OutputSpeech speechError(Throwable t); OutputSpeech confirmNewEvent(String title, DateTime from, DateTime to, Locale locale); OutputSpeech speechNewEventSaved(Locale locale); OutputSpeech speechConnectWithCalendar(String calendarName, Locale locale); }
@Test public void speechHelpMessage(){ final PlainTextOutputSpeech result = (PlainTextOutputSpeech)toTest.speechHelpMessage(aLocale); assertEquals("Frage mich: was ansteht, um die aktuellen Termine zu erfahren. Oder trage einen neuen Termin ein.", result.getText()); }
ElementProviderExtension implements IOCExtensionConfigurator { static Collection<String> elemental2ElementTags(final MetaClass type) { final Collection<String> customElementTags = customElementTags(type); if (!customElementTags.isEmpty()) { return customElementTags; } return Elemental2TagMapping.getTags(type.asClass()); } @Override void configure(final IOCProcessingContext context, final InjectionContext injectionContext); @Override void afterInitialization(final IOCProcessingContext context, final InjectionContext injectionContext); }
@Test public void elemental2ElementTag_customElement() { final Collection<String> tags = elemental2ElementTags(metaClass(CustomElement.class)); assertEquals(singletonList("div"), tags); } @Test public void elemental2ElementTag_customElementChild() { final Collection<String> tags = elemental2ElementTags(metaClass(CustomElement.Child.class)); assertEquals(singletonList("div"), tags); } @Test public void elemental2ElementTag_customElementWithCustomTag() { final Collection<String> tags = elemental2ElementTags(metaClass(CustomElement.WithCustomTag.class)); assertEquals(singletonList("foo"), tags); } @Test public void elemental2ElementTag_customElementWithCustomTagChild() { final Collection<String> tags = elemental2ElementTags( metaClass(CustomElement.WithCustomTag.ChildWithoutElementAnnotation.class)); assertEquals(emptyList(), tags); } @Test public void elemental2ElementTag_customElementWithCustomTagChildWithElementAnnotation() { final Collection<String> tags = elemental2ElementTags( metaClass(CustomElement.WithCustomTag.ChildWithoutElementAnnotation.class)); assertEquals(emptyList(), tags); } @Test public void elemental2ElementTag_customElementWithCustomTagChildWithCustomTag() { final Collection<String> tags = elemental2ElementTags( metaClass(CustomElement.WithCustomTag.ChildWithCustomTag.class)); assertEquals(singletonList("sub-foo"), tags); }
ErraiAppPropertiesFiles { public static List<URL> getUrls(final ClassLoader... classLoaders) { return Stream.of(classLoaders).flatMap(ErraiAppPropertiesFiles::getUrls).collect(Collectors.toList()); } static List<URL> getUrls(final ClassLoader... classLoaders); static List<URL> getModulesUrls(); }
@Test public void testGetUrls() { final ClassLoader classLoader = ErraiAppPropertiesFilesTest.class.getClassLoader(); final List<URL> urls = ErraiAppPropertiesFiles.getUrls(classLoader); assertEquals(3, urls.size()); }
ErraiAppPropertiesFiles { public static List<URL> getModulesUrls() { return getModulesUrls(ErraiAppPropertiesFiles.class.getClassLoader()); } static List<URL> getUrls(final ClassLoader... classLoaders); static List<URL> getModulesUrls(); }
@Test public void testGetModuleUrls() { final List<URL> moduleUrls = ErraiAppPropertiesFiles.getModulesUrls(); assertEquals(2, moduleUrls.size()); }
ErraiAppPropertiesFiles { static String getModuleDir(final URL url) { final String urlString = url.toExternalForm(); final int metaInfEndIndex = urlString.indexOf(META_INF_FILE_NAME); if (metaInfEndIndex > -1) { return urlString.substring(0, metaInfEndIndex); } final int rootDirEndIndex = urlString.indexOf(FILE_NAME); if (rootDirEndIndex > -1) { return urlString.substring(0, rootDirEndIndex); } throw new RuntimeException("URL " + url.toExternalForm() + " is not of a " + FILE_NAME); } static List<URL> getUrls(final ClassLoader... classLoaders); static List<URL> getModulesUrls(); }
@Test public void testGetModuleDirRootFile() throws MalformedURLException { final URL url = new URL("file:/foo/bar/ErraiApp.properties/"); final String moduleDir = ErraiAppPropertiesFiles.getModuleDir(url); assertEquals("file:/foo/bar/", moduleDir); } @Test public void testGetModuleDirMetaInfFile() throws MalformedURLException { final URL url = new URL("file:/foo/bar/META-INF/ErraiApp.properties/"); final String moduleDir = ErraiAppPropertiesFiles.getModuleDir(url); assertEquals("file:/foo/bar/", moduleDir); } @Test(expected = RuntimeException.class) public void testGetModuleDirWithInvalidFileName() throws MalformedURLException { final URL url = new URL("file:/foo/bar/META-INF/InvalidName.properties/"); ErraiAppPropertiesFiles.getModuleDir(url); }
Properties { public static Map<String, String> load(final String data) { final ParseState parseState = new ParseState(data); while (parseState.next()); return parseState.properties; } private Properties(); static Map<String, String> load(final String data); }
@Test public void parsePropertiesWithEquals() { final String data = "key1=value1\nkey2=value2"; final Map<String, String> props = Properties.load(data); assertEquals("value1", props.get("key1")); assertEquals("value2", props.get("key2")); assertEquals(2, props.size()); } @Test public void parsePropertiesWithColon() throws Exception { final String data = "key1:value1\nkey2:value2"; final Map<String, String> props = Properties.load(data); assertEquals("value1", props.get("key1")); assertEquals("value2", props.get("key2")); assertEquals(2, props.size()); } @Test public void parsePropertiesWithEqualsAndColon() throws Exception { final String data = "key1:value1\nkey2=value2"; final Map<String, String> props = Properties.load(data); assertEquals("value1", props.get("key1")); assertEquals("value2", props.get("key2")); assertEquals(2, props.size()); } @Test public void ignoreSpaceBetweenKeyAndValue() throws Exception { final String data = "key1 = value1\nkey2= value2\nkey3 =value3"; final Map<String, String> props = Properties.load(data); assertEquals("value1", props.get("key1")); assertEquals("value2", props.get("key2")); assertEquals("value3", props.get("key3")); assertEquals(3, props.size()); } @Test public void ignoreCommentLines() throws Exception { final String data = "key1=value1\n#key2=value2\n!key3=value3"; final Map<String, String> props = Properties.load(data); assertEquals("value1", props.get("key1")); assertEquals(1, props.size()); } @Test public void parseEmpty() throws Exception { final String data = ""; final Map<String, String> props = Properties.load(data); assertEquals(0, props.size()); } @Test public void parseWhitespaceOnly() throws Exception { final String data = " \n "; final Map<String, String> props = Properties.load(data); assertEquals(0, props.size()); } @Test public void includeWhitespaceAfterPropertyValueExceptTerminalNewline() throws Exception { final String data = "key1=value1 \t\n"; final Map<String, String> props = Properties.load(data); assertEquals("value1 \t", props.get("key1")); assertEquals(1, props.size()); } @Test public void ignoreWhitespaceAfterBackslash() throws Exception { final String data = "key1=value1\\ \t\n, and value2"; final Map<String, String> props = Properties.load(data); assertEquals("value1, and value2", props.get("key1")); assertEquals(1, props.size()); } @Test public void valueWithReturnNewlineAndTab() throws Exception { final String data = "key1=value1\\t\\r\\n"; final Map<String, String> props = Properties.load(data); assertEquals("value1\t\r\n", props.get("key1")); assertEquals(1, props.size()); } @Test public void escapeBackslashesBecomeSingleBackslashes() throws Exception { final String data = "key1=\\\\value1"; final Map<String, String> props = Properties.load(data); assertEquals("\\value1", props.get("key1")); assertEquals(1, props.size()); } @Test public void unicodeValues() throws Exception { final String data = "key1=value\\u2202"; final Map<String, String> props = Properties.load(data); assertEquals("value\u2202", props.get("key1")); assertEquals(1, props.size()); } @Test public void lineEndingWithReturn() throws Exception { final String data = "key1=value1\rkey2=value2"; final Map<String, String> props = Properties.load(data); assertEquals("value1", props.get("key1")); assertEquals("value2", props.get("key2")); assertEquals(2, props.size()); } @Test public void lineEndingWithReturnAndNewline() throws Exception { final String data = "key1=value1\r\nkey2=value2"; final Map<String, String> props = Properties.load(data); assertEquals("value1", props.get("key1")); assertEquals("value2", props.get("key2")); assertEquals(2, props.size()); } @Test public void parseValueEndingWithEscapedEquals() { final String data = "key1=value1\\=\nkey2=value2"; final Map<String, String> props = Properties.load(data); assertEquals("value1=", props.get("key1")); assertEquals("value2", props.get("key2")); assertEquals(2, props.size()); } @Test public void parseValueEndingWithEscapedTwoPoints() { final String data = "key1=value1\\:\nkey2=value2"; final Map<String, String> props = Properties.load(data); assertEquals("value1:", props.get("key1")); assertEquals("value2", props.get("key2")); assertEquals(2, props.size()); }
Elemental2DomUtil { public boolean removeAllElementChildren(final Node node) { final boolean hadChildren = node.lastChild != null; while (node.lastChild != null) { node.removeChild(node.lastChild); } return hadChildren; } boolean removeAllElementChildren(final Node node); void appendWidgetToElement(final HTMLElement parent, final Widget child); HTMLElement asHTMLElement(final com.google.gwt.dom.client.Element gwtElement); HTMLElement asHTMLElement(final org.jboss.errai.common.client.dom.HTMLElement htmlElement); org.jboss.errai.common.client.dom.HTMLElement asHTMLElement(final HTMLElement htmlElement); }
@Test public void testRemoveAllElementChildrenWhenNodeDoesNotHaveAnyChildren() { final Node node = Mockito.spy(makeNode()); final boolean hadChildren = elemental2DomUtil.removeAllElementChildren(node); Mockito.verify(node, Mockito.never()).removeChild(any()); assertFalse(hadChildren); } @Test public void testRemoveAllElementChildrenWhenNodeHasChildren() { final Node child1 = mock(Node.class); final Node child2 = mock(Node.class); final Node node = Mockito.spy(makeNode(child1, child2)); final boolean hadChildren = elemental2DomUtil.removeAllElementChildren(node); Mockito.verify(node).removeChild(child1); Mockito.verify(node).removeChild(child2); assertTrue(hadChildren); }
Elemental2DomUtil { public HTMLElement asHTMLElement(final com.google.gwt.dom.client.Element gwtElement) { return Js.cast(gwtElement); } boolean removeAllElementChildren(final Node node); void appendWidgetToElement(final HTMLElement parent, final Widget child); HTMLElement asHTMLElement(final com.google.gwt.dom.client.Element gwtElement); HTMLElement asHTMLElement(final org.jboss.errai.common.client.dom.HTMLElement htmlElement); org.jboss.errai.common.client.dom.HTMLElement asHTMLElement(final HTMLElement htmlElement); }
@Test public void testAsHTMLElementForGWTElement() throws Exception { final com.google.gwt.dom.client.Element gwtElement = mock(com.google.gwt.dom.client.Element.class); final HTMLElement expectedElement = mock(HTMLElement.class); mockJsCast(expectedElement, gwtElement); final HTMLElement actualElement = elemental2DomUtil.asHTMLElement(gwtElement); assertSame(expectedElement, actualElement); } @Test public void testAsHTMLElementForErraiHTMLElement() throws Exception { final org.jboss.errai.common.client.dom.HTMLElement htmlElement = mock( org.jboss.errai.common.client.dom.HTMLElement.class); final HTMLElement expectedElement = mock(HTMLElement.class); mockJsCast(expectedElement, htmlElement); final HTMLElement actualElement = elemental2DomUtil.asHTMLElement(htmlElement); assertSame(expectedElement, actualElement); } @Test public void testAsHTMLElementForHTMLElement() throws Exception { final org.jboss.errai.common.client.dom.HTMLElement deprecatedElement = mock( org.jboss.errai.common.client.dom.HTMLElement.class); final HTMLElement htmlElement = mock(HTMLElement.class); mockJsCast(deprecatedElement, htmlElement); org.jboss.errai.common.client.dom.HTMLElement actualElement = elemental2DomUtil.asHTMLElement(htmlElement); assertSame(deprecatedElement, actualElement); }
Reflections extends ReflectionUtils { public <T> Set<Class<? extends T>> getSubTypesOf(final Class<T> type) { Set<String> subTypes = store.getSubTypesOf(type.getName()); return ImmutableSet.copyOf(ReflectionUtils.<T>forNames(subTypes)); } Reflections(final Configuration configuration); Reflections(final String prefix, final Scanner... scanners); Reflections(final Object[] urlHints, final Scanner... scanners); protected Reflections(); static Reflections collect(); Reflections collect(final String packagePrefix, final Predicate<String> resourceNameFilter); Reflections collect(final String packagePrefix, final Predicate<String> resourceNameFilter, final Serializer serializer); Reflections collect(final InputStream inputStream); Reflections collect(final File file); Reflections merge(final Reflections reflections); Set<Class<? extends T>> getSubTypesOf(final Class<T> type); Set<Class<?>> getTypesAnnotatedWith(final Class<? extends Annotation> annotation); Set<Class<?>> getTypesAnnotatedWith(final Class<? extends Annotation> annotation, boolean honorInherited); Set<Class<?>> getTypesAnnotatedWith(final Annotation annotation); Set<Class<?>> getTypesAnnotatedWith(final Annotation annotation, boolean honorInherited); Set<Method> getMethodsAnnotatedWith(final Class<? extends Annotation> annotation); Set<Method> getMethodsAnnotatedWith(final Annotation annotation); Set<Field> getFieldsAnnotatedWith(final Class<? extends Annotation> annotation); Set<Field> getFieldsAnnotatedWith(final Annotation annotation); Set<Method> getConverters(final Class<?> from, final Class<?> to); Set<Method> getMethodsWithAnyParamAnnotated(Class<? extends Annotation> annotation); Set<String> getResources(final Predicate<String> namePredicate); Set<String> getResources(final Pattern pattern); Store getStore(); File save(final String filename); File save(final String filename, final Serializer serializer); }
@Test public void testSubTypesOf() { assertThat(reflections.getSubTypesOf(I1.class), are(I2.class, C1.class, C2.class, C3.class, C5.class)); assertThat(reflections.getSubTypesOf(I2.class), are(C1.class, C2.class, C3.class, C5.class)); }
Reflections extends ReflectionUtils { public Set<Class<?>> getTypesAnnotatedWith(final Class<? extends Annotation> annotation) { Set<String> typesAnnotatedWith = store.getTypesAnnotatedWith(annotation.getName()); return ImmutableSet.copyOf(forNames(typesAnnotatedWith)); } Reflections(final Configuration configuration); Reflections(final String prefix, final Scanner... scanners); Reflections(final Object[] urlHints, final Scanner... scanners); protected Reflections(); static Reflections collect(); Reflections collect(final String packagePrefix, final Predicate<String> resourceNameFilter); Reflections collect(final String packagePrefix, final Predicate<String> resourceNameFilter, final Serializer serializer); Reflections collect(final InputStream inputStream); Reflections collect(final File file); Reflections merge(final Reflections reflections); Set<Class<? extends T>> getSubTypesOf(final Class<T> type); Set<Class<?>> getTypesAnnotatedWith(final Class<? extends Annotation> annotation); Set<Class<?>> getTypesAnnotatedWith(final Class<? extends Annotation> annotation, boolean honorInherited); Set<Class<?>> getTypesAnnotatedWith(final Annotation annotation); Set<Class<?>> getTypesAnnotatedWith(final Annotation annotation, boolean honorInherited); Set<Method> getMethodsAnnotatedWith(final Class<? extends Annotation> annotation); Set<Method> getMethodsAnnotatedWith(final Annotation annotation); Set<Field> getFieldsAnnotatedWith(final Class<? extends Annotation> annotation); Set<Field> getFieldsAnnotatedWith(final Annotation annotation); Set<Method> getConverters(final Class<?> from, final Class<?> to); Set<Method> getMethodsWithAnyParamAnnotated(Class<? extends Annotation> annotation); Set<String> getResources(final Predicate<String> namePredicate); Set<String> getResources(final Pattern pattern); Store getStore(); File save(final String filename); File save(final String filename, final Serializer serializer); }
@Test public void testTypesAnnotatedWith() { assertThat("when honoring @Inherited, meta-annotation should only effect annotated super classes and it's sub types", reflections.getTypesAnnotatedWith(MAI1.class), are(AI1.class)); assertThat("when honoring @Inherited, meta-annotation should only effect annotated super classes and it's sub types", reflections.getTypesAnnotatedWith(AI2.class), are(I2.class)); assertThat("when honoring @Inherited, meta-annotation should only effect annotated super classes and it's sub types", reflections.getTypesAnnotatedWith(AC1.class), are(C1.class, C2.class, C3.class, C5.class)); assertThat("when not honoring @Inherited, meta annotation effects all subtypes, including annotations interfaces and classes", reflections.getTypesAnnotatedWith(AI1.class, false), are(I1.class, I2.class, C1.class, C2.class, C3.class, C5.class)); assertThat("when not honoring @Inherited, meta annotation effects all subtypes, including annotations interfaces and classes", reflections.getTypesAnnotatedWith(AI2.class, false), are(I2.class, C1.class, C2.class, C3.class, C5.class)); assertThat(reflections.getTypesAnnotatedWith(AM1.class), isEmpty); AC2 ac2 = new AC2() { public String value() { return "ugh?!"; } public Class<? extends Annotation> annotationType() { return AC2.class; } }; assertThat("when honoring @Inherited, meta-annotation should only effect annotated super classes and it's sub types", reflections.getTypesAnnotatedWith(ac2), are(C3.class, I3.class)); assertThat("when not honoring @Inherited, meta annotation effects all subtypes, including annotations interfaces and classes", reflections.getTypesAnnotatedWith(ac2, false), are(C3.class, C5.class, I3.class, C6.class)); }
Reflections extends ReflectionUtils { public Set<Method> getMethodsAnnotatedWith(final Class<? extends Annotation> annotation) { Set<String> annotatedWith = store.getMethodsAnnotatedWith(annotation.getName()); Set<Method> result = Sets.newHashSet(); for (String annotated : annotatedWith) { result.add(Utils.getMethodFromDescriptor(annotated)); } return result; } Reflections(final Configuration configuration); Reflections(final String prefix, final Scanner... scanners); Reflections(final Object[] urlHints, final Scanner... scanners); protected Reflections(); static Reflections collect(); Reflections collect(final String packagePrefix, final Predicate<String> resourceNameFilter); Reflections collect(final String packagePrefix, final Predicate<String> resourceNameFilter, final Serializer serializer); Reflections collect(final InputStream inputStream); Reflections collect(final File file); Reflections merge(final Reflections reflections); Set<Class<? extends T>> getSubTypesOf(final Class<T> type); Set<Class<?>> getTypesAnnotatedWith(final Class<? extends Annotation> annotation); Set<Class<?>> getTypesAnnotatedWith(final Class<? extends Annotation> annotation, boolean honorInherited); Set<Class<?>> getTypesAnnotatedWith(final Annotation annotation); Set<Class<?>> getTypesAnnotatedWith(final Annotation annotation, boolean honorInherited); Set<Method> getMethodsAnnotatedWith(final Class<? extends Annotation> annotation); Set<Method> getMethodsAnnotatedWith(final Annotation annotation); Set<Field> getFieldsAnnotatedWith(final Class<? extends Annotation> annotation); Set<Field> getFieldsAnnotatedWith(final Annotation annotation); Set<Method> getConverters(final Class<?> from, final Class<?> to); Set<Method> getMethodsWithAnyParamAnnotated(Class<? extends Annotation> annotation); Set<String> getResources(final Predicate<String> namePredicate); Set<String> getResources(final Pattern pattern); Store getStore(); File save(final String filename); File save(final String filename, final Serializer serializer); }
@Test public void testMethodsAnnotatedWith() { try { assertThat(reflections.getMethodsAnnotatedWith(AM1.class), are(C4.class.getDeclaredMethod("m1"), C4.class.getDeclaredMethod("m1", int.class, String[].class), C4.class.getDeclaredMethod("m1", int[][].class, String[][].class), C4.class.getDeclaredMethod("m3"))); AM1 am1 = new AM1() { public String value() { return "1"; } public Class<? extends Annotation> annotationType() { return AM1.class; } }; assertThat(reflections.getMethodsAnnotatedWith(am1), are(C4.class.getDeclaredMethod("m1"), C4.class.getDeclaredMethod("m1", int.class, String[].class), C4.class.getDeclaredMethod("m1", int[][].class, String[][].class))); } catch (NoSuchMethodException e) { fail(); } }
Reflections extends ReflectionUtils { public Set<Field> getFieldsAnnotatedWith(final Class<? extends Annotation> annotation) { final Set<Field> result = Sets.newHashSet(); Collection<String> annotatedWith = store.getFieldsAnnotatedWith(annotation.getName()); for (String annotated : annotatedWith) { result.add(Utils.getFieldFromString(annotated)); } return result; } Reflections(final Configuration configuration); Reflections(final String prefix, final Scanner... scanners); Reflections(final Object[] urlHints, final Scanner... scanners); protected Reflections(); static Reflections collect(); Reflections collect(final String packagePrefix, final Predicate<String> resourceNameFilter); Reflections collect(final String packagePrefix, final Predicate<String> resourceNameFilter, final Serializer serializer); Reflections collect(final InputStream inputStream); Reflections collect(final File file); Reflections merge(final Reflections reflections); Set<Class<? extends T>> getSubTypesOf(final Class<T> type); Set<Class<?>> getTypesAnnotatedWith(final Class<? extends Annotation> annotation); Set<Class<?>> getTypesAnnotatedWith(final Class<? extends Annotation> annotation, boolean honorInherited); Set<Class<?>> getTypesAnnotatedWith(final Annotation annotation); Set<Class<?>> getTypesAnnotatedWith(final Annotation annotation, boolean honorInherited); Set<Method> getMethodsAnnotatedWith(final Class<? extends Annotation> annotation); Set<Method> getMethodsAnnotatedWith(final Annotation annotation); Set<Field> getFieldsAnnotatedWith(final Class<? extends Annotation> annotation); Set<Field> getFieldsAnnotatedWith(final Annotation annotation); Set<Method> getConverters(final Class<?> from, final Class<?> to); Set<Method> getMethodsWithAnyParamAnnotated(Class<? extends Annotation> annotation); Set<String> getResources(final Predicate<String> namePredicate); Set<String> getResources(final Pattern pattern); Store getStore(); File save(final String filename); File save(final String filename, final Serializer serializer); }
@Test public void testFieldsAnnotatedWith() { try { assertThat(reflections.getFieldsAnnotatedWith(AF1.class), are(C4.class.getDeclaredField("f1"), C4.class.getDeclaredField("f2") )); assertThat(reflections.getFieldsAnnotatedWith(new AF1() { public String value() { return "2"; } public Class<? extends Annotation> annotationType() { return AF1.class; } }), are(C4.class.getDeclaredField("f2"))); } catch (NoSuchFieldException e) { fail(); } }
Reflections extends ReflectionUtils { public Set<Method> getConverters(final Class<?> from, final Class<?> to) { Set<Method> result = Sets.newHashSet(); Set<String> converters = store.getConverters(from.getName(), to.getName()); for (String converter : converters) { result.add(Utils.getMethodFromDescriptor(converter)); } return result; } Reflections(final Configuration configuration); Reflections(final String prefix, final Scanner... scanners); Reflections(final Object[] urlHints, final Scanner... scanners); protected Reflections(); static Reflections collect(); Reflections collect(final String packagePrefix, final Predicate<String> resourceNameFilter); Reflections collect(final String packagePrefix, final Predicate<String> resourceNameFilter, final Serializer serializer); Reflections collect(final InputStream inputStream); Reflections collect(final File file); Reflections merge(final Reflections reflections); Set<Class<? extends T>> getSubTypesOf(final Class<T> type); Set<Class<?>> getTypesAnnotatedWith(final Class<? extends Annotation> annotation); Set<Class<?>> getTypesAnnotatedWith(final Class<? extends Annotation> annotation, boolean honorInherited); Set<Class<?>> getTypesAnnotatedWith(final Annotation annotation); Set<Class<?>> getTypesAnnotatedWith(final Annotation annotation, boolean honorInherited); Set<Method> getMethodsAnnotatedWith(final Class<? extends Annotation> annotation); Set<Method> getMethodsAnnotatedWith(final Annotation annotation); Set<Field> getFieldsAnnotatedWith(final Class<? extends Annotation> annotation); Set<Field> getFieldsAnnotatedWith(final Annotation annotation); Set<Method> getConverters(final Class<?> from, final Class<?> to); Set<Method> getMethodsWithAnyParamAnnotated(Class<? extends Annotation> annotation); Set<String> getResources(final Predicate<String> namePredicate); Set<String> getResources(final Pattern pattern); Store getStore(); File save(final String filename); File save(final String filename, final Serializer serializer); }
@Test public void testConverters() { try { assertThat(reflections.getConverters(C2.class, C3.class), are(C4.class.getDeclaredMethod("c2toC3", C2.class))); } catch (NoSuchMethodException e) { fail(); } }
Reflections extends ReflectionUtils { public static Reflections collect() { return new Reflections(new ConfigurationBuilder()). collect("META-INF/reflections", new FilterBuilder().include(".*-reflections.xml")); } Reflections(final Configuration configuration); Reflections(final String prefix, final Scanner... scanners); Reflections(final Object[] urlHints, final Scanner... scanners); protected Reflections(); static Reflections collect(); Reflections collect(final String packagePrefix, final Predicate<String> resourceNameFilter); Reflections collect(final String packagePrefix, final Predicate<String> resourceNameFilter, final Serializer serializer); Reflections collect(final InputStream inputStream); Reflections collect(final File file); Reflections merge(final Reflections reflections); Set<Class<? extends T>> getSubTypesOf(final Class<T> type); Set<Class<?>> getTypesAnnotatedWith(final Class<? extends Annotation> annotation); Set<Class<?>> getTypesAnnotatedWith(final Class<? extends Annotation> annotation, boolean honorInherited); Set<Class<?>> getTypesAnnotatedWith(final Annotation annotation); Set<Class<?>> getTypesAnnotatedWith(final Annotation annotation, boolean honorInherited); Set<Method> getMethodsAnnotatedWith(final Class<? extends Annotation> annotation); Set<Method> getMethodsAnnotatedWith(final Annotation annotation); Set<Field> getFieldsAnnotatedWith(final Class<? extends Annotation> annotation); Set<Field> getFieldsAnnotatedWith(final Annotation annotation); Set<Method> getConverters(final Class<?> from, final Class<?> to); Set<Method> getMethodsWithAnyParamAnnotated(Class<? extends Annotation> annotation); Set<String> getResources(final Predicate<String> namePredicate); Set<String> getResources(final Pattern pattern); Store getStore(); File save(final String filename); File save(final String filename, final Serializer serializer); }
@Test public void collect() { String path = getUserDir() + "/target/test-classes" + "/META-INF/reflections/testModel-reflections.xml"; try { Predicate<String> filter = new FilterBuilder().include("org.jboss.errai.reflections.TestModel\\$.*"); Reflections testModelReflections = new Reflections(new ConfigurationBuilder() .filterInputsBy(filter) .setScanners( new SubTypesScanner().filterResultsBy(filter), new TypeAnnotationsScanner().filterResultsBy(filter)) .setUrls(asList(ClasspathHelper.forClass(TestModel.class)))); testModelReflections.scan(); testModelReflections.save(path); reflections = Reflections.collect(); reflections.scan(); testAll(); } finally { new File(path).delete(); } }
KeycloakAuthenticationService implements AuthenticationService, Serializable { @Override public boolean isLoggedIn() { return keycloakIsLoggedIn() || wrappedAuthService.isLoggedIn(); } @Override User login(final String username, final String password); @Override boolean isLoggedIn(); @Override void logout(); @Override User getUser(); }
@Test public void isLoggedInReturnsFalseWhenNoUserLoggedIn() throws Exception { assertFalse(authService.isLoggedIn()); }
KeycloakAuthenticationService implements AuthenticationService, Serializable { @Override public User getUser() { if (keycloakIsLoggedIn()) { return getKeycloakUser(); } else if (wrappedAuthService.isLoggedIn()) { return wrappedAuthService.getUser(); } else { return User.ANONYMOUS; } } @Override User login(final String username, final String password); @Override boolean isLoggedIn(); @Override void logout(); @Override User getUser(); }
@Test public void getUserReturnsAnonymousWhenNoUserLoggedIn() throws Exception { assertEquals(User.ANONYMOUS, authService.getUser()); }
KeycloakAuthenticationService implements AuthenticationService, Serializable { @Override public void logout() { if (keycloakIsLoggedIn()) { keycloakLogout(); try { if (RpcContext.getMessage() != null) ((HttpServletRequest) RpcContext.getServletRequest()).logout(); } catch (ServletException e) { throw new AuthenticationException("An error occurred while attempting to log out of Keycloak."); } } else if (wrappedAuthService.isLoggedIn()) { wrappedAuthService.logout(); } } @Override User login(final String username, final String password); @Override boolean isLoggedIn(); @Override void logout(); @Override User getUser(); }
@Test public void logoutIsIdempotent() throws Exception { authService.logout(); authService.logout(); isLoggedInReturnsFalseWhenNoUserLoggedIn(); }
KeycloakAuthenticationService implements AuthenticationService, Serializable { @Override public User login(final String username, final String password) { if (!keycloakIsLoggedIn()) { return wrappedAuthService.login(username, password); } else { throw new AlreadyLoggedInException("Already logged in through Keycloak."); } } @Override User login(final String username, final String password); @Override boolean isLoggedIn(); @Override void logout(); @Override User getUser(); }
@Test(expected = AlreadyLoggedInException.class) public void loginFailsIfKeycloakUserLoggedIn() throws Exception { getUserReturnsUserWhenKeycloakUserLoggedIn(); authService.login(PREFERRED_USERNAME, ""); }
KeycloakAuthenticationService implements AuthenticationService, Serializable { void setSecurityContext(final KeycloakSecurityContext keycloakSecurityContext) { if (wrappedAuthService.isLoggedIn() && keycloakSecurityContext != null) { throw new AlreadyLoggedInException("Logged in as " + wrappedAuthService.getUser()); } this.keycloakSecurityContext = keycloakSecurityContext; keycloakUser = null; } @Override User login(final String username, final String password); @Override boolean isLoggedIn(); @Override void logout(); @Override User getUser(); }
@Test(expected = AlreadyLoggedInException.class) public void settingKeycloakUserFailsIfWrappedUserLoggedIn() throws Exception { getUserReturnsUserWhenWrappedUserLoggedIn(); authService.setSecurityContext(securityContext); }