src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
---|---|
ManageTagController { @PutMapping("/manage/tagList/enable") @ResponseStatus(HttpStatus.NO_CONTENT) @Transactional public void enable(@RequestParam String name) { tagRepository.getOne(name).setDisabled(false); } @GetMapping("/manageTag") String index(); @GetMapping("/manageTagAdd") String toAdd(); @GetMapping("/manage/tagDetail") String detail(@RequestParam String name, Model model); @GetMapping("/manage/tagEdit") String edit(@RequestParam String name, Model model); @GetMapping("/manage/tagList") @RowCustom(distinct = true, dramatizer = JQueryDataTableDramatizer.class) RowDefinition data(); @PostMapping("/manage/tagList") @Transactional String add(@RequestParam String name, Integer type
, @RequestParam(required = false, defaultValue = "0") Integer weight, String icon); @PostMapping("/manage/addTag") @ResponseBody String add(String name); @DeleteMapping("/manage/tagList") @ResponseStatus(HttpStatus.NO_CONTENT) void delete(@RequestParam String name); @GetMapping("/manage/tagList/check") @ResponseBody String checkName(@RequestParam String name); @PutMapping("/manage/tagList/disable") @ResponseStatus(HttpStatus.NO_CONTENT) @Transactional void disable(@RequestParam String name); @PutMapping("/manage/tagList/enable") @ResponseStatus(HttpStatus.NO_CONTENT) @Transactional void enable(@RequestParam String name); } | @Test public void enable() throws Exception { changeDisable("/enable", false); } |
ManageTagController { @GetMapping("/manageTagAdd") public String toAdd() { return "_tagOperator.html"; } @GetMapping("/manageTag") String index(); @GetMapping("/manageTagAdd") String toAdd(); @GetMapping("/manage/tagDetail") String detail(@RequestParam String name, Model model); @GetMapping("/manage/tagEdit") String edit(@RequestParam String name, Model model); @GetMapping("/manage/tagList") @RowCustom(distinct = true, dramatizer = JQueryDataTableDramatizer.class) RowDefinition data(); @PostMapping("/manage/tagList") @Transactional String add(@RequestParam String name, Integer type
, @RequestParam(required = false, defaultValue = "0") Integer weight, String icon); @PostMapping("/manage/addTag") @ResponseBody String add(String name); @DeleteMapping("/manage/tagList") @ResponseStatus(HttpStatus.NO_CONTENT) void delete(@RequestParam String name); @GetMapping("/manage/tagList/check") @ResponseBody String checkName(@RequestParam String name); @PutMapping("/manage/tagList/disable") @ResponseStatus(HttpStatus.NO_CONTENT) @Transactional void disable(@RequestParam String name); @PutMapping("/manage/tagList/enable") @ResponseStatus(HttpStatus.NO_CONTENT) @Transactional void enable(@RequestParam String name); } | @Test public void check() throws Exception{ toAdd(); Tag tag = tagRepository.findAll().stream().max(new RandomComparator()).orElse(null); if (tag == null) { return; } MvcResult result = mockMvc.perform(get(TAG_LIST_URL + "/check") .param("name",tag.getName())) .andExpect(status().is2xxSuccessful()) .andReturn(); assertThat(result.getResponse().getContentAsString()).isEqualToIgnoringCase("false"); result = mockMvc.perform(get(TAG_LIST_URL+ "/check") .param("name", RandomStringUtils.randomAlphabetic(10))) .andExpect(status().is2xxSuccessful()) .andReturn(); assertThat(result.getResponse().getContentAsString()).isEqualToIgnoringCase("true"); }
@Test public void toAdd() throws Exception { addNewTag(); } |
ManageCommonProblemController { @PreAuthorize("hasAnyRole('ROOT','" + Login.ROLE_PRODUCT_CENTER + "','" + Login.ROLE_LOOK + "')") @GetMapping("/manage/commonProblem") public String index() { return "operation-management/_helpCenter.html"; } @PreAuthorize("hasAnyRole('ROOT','" + Login.ROLE_PRODUCT_CENTER + "','" + Login.ROLE_LOOK + "')") @GetMapping("/manage/commonProblem") String index(); @GetMapping("/manage/commonProblemList") @RowCustom(dramatizer = JQueryDataTableDramatizer.class, distinct = true) RowDefinition<CommonProblem> data(); @GetMapping("/manage/commonProblemAdd") String indexForCreate(); @GetMapping("/manage/commonProblemEdit") String indexForEdit(long id, Model model); @PostMapping("/manage/commonProblemSubmit") String add(Long id, String title, Integer weight,String content); @PutMapping("/help/{id}/enable") @ResponseStatus(HttpStatus.NO_CONTENT) @Transactional void enable(@PathVariable("id") long id); @PutMapping("/help/{id}/disable") @ResponseStatus(HttpStatus.NO_CONTENT) @Transactional void disable(@PathVariable("id") long id); @PutMapping("/help/{id}/isHotLabel") @ResponseStatus(HttpStatus.NO_CONTENT) @Transactional void isHotLabel(@PathVariable("id") long id); @PutMapping("/help/{id}/notHotLabel") @ResponseStatus(HttpStatus.NO_CONTENT) @Transactional void notHotLabel(@PathVariable("id") long id); } | @Test public void index(){ Manager manager = newRandomManager(ManageLevel.root); updateAllRunWith(manager); String title = RandomStringUtils.randomAscii(10); commonProblemService.addAndEditCommonProblem(null, title,50 , RandomStringUtils.randomAscii(20)); driver.get("http: ManageHelpCenterPage manageHelpCenterPage = initPage(ManageHelpCenterPage.class); manageHelpCenterPage.assertHasTopic(title); } |
ManageManagerController { @PreAuthorize("hasAnyRole('ROOT','" + Login.ROLE_GRANT + "')") @PostMapping("/manage/managers") @Transactional public String addUser(String name, String department, String realName, boolean enable, String comment , String[] role, @AuthenticationPrincipal Login login, RedirectAttributes redirectAttributes) { Login current = loginService.get(login.getId()); final String rawPassword = RandomStringUtils.randomAlphabetic(6); Supplier<Manager> managerSupplier = () -> { if (loginService.byLoginName(name) != null) throw new IllegalArgumentException(name + "已存在"); return loginService.newLogin(Manager.class, name, current, rawPassword); }; updateManagerInfo(department, realName, enable, comment, role, current, managerSupplier); redirectAttributes.addAttribute("rawPassword", rawPassword); return "redirect:/manageManager"; } @GetMapping("/manage/bindManager{id}") BufferedImage toScanImage(@PathVariable("id") long id); @GetMapping("/manageManager") String index(); @GetMapping("/manageManagerAdd") String addIndex(@AuthenticationPrincipal Login login, Model model); @GetMapping("/manageManagerEdit") String editIndex(long id, @AuthenticationPrincipal Login login, Model model); @GetMapping("/manage/managers") @RowCustom(distinct = true, dramatizer = JQueryDataTableDramatizer.class) RowDefinition list(String name, String department, String realName); @PreAuthorize("hasAnyRole('ROOT','" + Login.ROLE_GRANT + "')") @PostMapping("/manage/manager") @Transactional String updateUser(String name, String department, String realName, boolean enable, String comment
, String[] role, @AuthenticationPrincipal Login login, long id); @PreAuthorize("hasAnyRole('ROOT','" + Login.ROLE_GRANT + "')") @PostMapping("/manage/managers") @Transactional String addUser(String name, String department, String realName, boolean enable, String comment
, String[] role, @AuthenticationPrincipal Login login, RedirectAttributes redirectAttributes); @PutMapping("/login/{id}/disable") @ResponseStatus(HttpStatus.NO_CONTENT) @Transactional void disable(@PathVariable("id") long id, @AuthenticationPrincipal Login current); @PutMapping("/login/{id}/enable") @ResponseStatus(HttpStatus.NO_CONTENT) @Transactional void enable(@PathVariable("id") long id, @AuthenticationPrincipal Login current); @DeleteMapping("/login/{id}") @ResponseStatus(HttpStatus.NO_CONTENT) @Transactional void delete(@PathVariable("id") long id, @AuthenticationPrincipal Login current); @PutMapping("/login/{id}/password") @ResponseBody @Transactional String password(@PathVariable("id") long id, @AuthenticationPrincipal Login current); } | @Test public void pages() throws Exception { driver.get("http: System.out.println(driver.getPageSource()); addUser(); Login lastOne = loginRepository.findAll(new Sort(Sort.Direction.DESC, "id")).get(0); driver.get("http: System.out.println(driver.getPageSource()); assertThat(true) .isTrue(); }
@Test public void addUser() throws Exception { final String loginName = randomMobile(); Collection<ManageLevel> levelSet = randomLevel(); mockMvc.perform( paramLevel(post("/manage/managers") .param("name", loginName) .param("department", RandomStringUtils.randomAlphabetic(10)) .param("realName", RandomStringUtils.randomAlphabetic(10)) .param("enable", "1") .param("comment", RandomStringUtils.randomAlphabetic(10)), levelSet) ) .andExpect(status().is3xxRedirection()); Manager manager = (Manager) loginService.byLoginName(loginName); assertThat(manager) .isNotNull(); assertThat(manager.getLevelSet()) .containsOnlyElementsOf(levelSet); assertThat(manager.isEnabled()) .isTrue(); } |
ManageManagerController { @GetMapping("/manage/managers") @RowCustom(distinct = true, dramatizer = JQueryDataTableDramatizer.class) public RowDefinition list(String name, String department, String realName) { return new RowDefinition<Manager>() { @Override public Class<Manager> entityClass() { return Manager.class; } @Override public List<FieldDefinition<Manager>> fields() { return Arrays.asList( FieldBuilder.asName(Manager.class, "id") .addSelect(managerRoot -> managerRoot) .addFormat(toBi(Login::getId)) .addOrder(managerRoot -> managerRoot.get("id")) .build() , FieldBuilder.asName(Manager.class, "name") .addSelect(managerRoot -> null) .addFormat(toBi(Login::getLoginName)) .addOrder(managerRoot -> managerRoot.get("loginName")) .build() , FieldBuilder.asName(Manager.class, "department") .addSelect(managerRoot -> null) .addFormat(toBi(Manager::getDepartment)) .addOrder(managerRoot -> managerRoot.get("department")) .build() , FieldBuilder.asName(Manager.class, "realName") .addSelect(managerRoot -> null) .addFormat(toBi(Manager::getRealName)) .addOrder(managerRoot -> managerRoot.get("realName")) .build() , FieldBuilder.asName(Manager.class, "wechatID") .addSelect(managerRoot -> null) .addFormat(toBi(manager -> { StandardWeixinUser user = manager.getWechatUser(); if (user == null) return null; return user.getOpenId(); })) .withoutOrder() .build() , FieldBuilder.asName(Manager.class, "role") .addSelect(managerRoot -> null) .addFormat(toBi(manager -> { Set<ManageLevel> levelSet = manager.getLevelSet(); return levelSet.stream() .map(ManageLevel::title) .collect(Collectors.toList()); })) .withoutOrder() .build() , FieldBuilder.asName(Manager.class, "remark") .addSelect(managerRoot -> null) .addFormat(toBi(Manager::getComment)) .addOrder(managerRoot -> managerRoot.get("comment")) .build() , FieldBuilder.asName(Manager.class, "state") .addSelect(managerRoot -> null) .addFormat(toBi(manager -> { boolean state = manager.isEnabled(); return state ? "启用" : "禁用"; })) .addOrder(managerRoot -> managerRoot.get("enabled")) .build() , FieldBuilder.asName(Manager.class, "stateCode") .addSelect(managerRoot -> null) .addFormat(toBi(manager -> { boolean state = manager.isEnabled(); return state ? 0 : 1; })) .addOrder(managerRoot -> managerRoot.get("enabled")) .build() ); } @Override public Specification<Manager> specification() { return (root, query, cb) -> { Predicate predicate = cb.notEqual(root.get("loginName"), "root"); if (!StringUtils.isEmpty(name)) { predicate = cb.and( predicate , cb.like(root.get("loginName"), "%" + name + "%") ); } if (!StringUtils.isEmpty(department)) { predicate = cb.and( predicate , cb.equal(root.get("department"), department) ); } if (!StringUtils.isEmpty(realName)) { predicate = cb.and( predicate , cb.like(root.get("realName"), "%" + realName + "%") ); } return predicate; }; } }; } @GetMapping("/manage/bindManager{id}") BufferedImage toScanImage(@PathVariable("id") long id); @GetMapping("/manageManager") String index(); @GetMapping("/manageManagerAdd") String addIndex(@AuthenticationPrincipal Login login, Model model); @GetMapping("/manageManagerEdit") String editIndex(long id, @AuthenticationPrincipal Login login, Model model); @GetMapping("/manage/managers") @RowCustom(distinct = true, dramatizer = JQueryDataTableDramatizer.class) RowDefinition list(String name, String department, String realName); @PreAuthorize("hasAnyRole('ROOT','" + Login.ROLE_GRANT + "')") @PostMapping("/manage/manager") @Transactional String updateUser(String name, String department, String realName, boolean enable, String comment
, String[] role, @AuthenticationPrincipal Login login, long id); @PreAuthorize("hasAnyRole('ROOT','" + Login.ROLE_GRANT + "')") @PostMapping("/manage/managers") @Transactional String addUser(String name, String department, String realName, boolean enable, String comment
, String[] role, @AuthenticationPrincipal Login login, RedirectAttributes redirectAttributes); @PutMapping("/login/{id}/disable") @ResponseStatus(HttpStatus.NO_CONTENT) @Transactional void disable(@PathVariable("id") long id, @AuthenticationPrincipal Login current); @PutMapping("/login/{id}/enable") @ResponseStatus(HttpStatus.NO_CONTENT) @Transactional void enable(@PathVariable("id") long id, @AuthenticationPrincipal Login current); @DeleteMapping("/login/{id}") @ResponseStatus(HttpStatus.NO_CONTENT) @Transactional void delete(@PathVariable("id") long id, @AuthenticationPrincipal Login current); @PutMapping("/login/{id}/password") @ResponseBody @Transactional String password(@PathVariable("id") long id, @AuthenticationPrincipal Login current); } | @Test public void list() throws Exception { addUser(); mockMvc.perform( get("/manage/managers") ) .andExpect(status().isOk()) .andDo(print()); assertThat(true) .isTrue(); } |
ManageDepotController { @PreAuthorize("hasAnyRole('ROOT','"+ Login.ROLE_SUPPLY_CHAIN+"','"+Login.ROLE_LOOK+"')") @GetMapping("/manageDepot") public String index() { return "_depotManage.html"; } @PreAuthorize("hasAnyRole('ROOT','"+ Login.ROLE_SUPPLY_CHAIN+"','"+Login.ROLE_LOOK+"')") @GetMapping("/manageDepot") String index(); @GetMapping("/manageDepotAdd") String toAdd(); @PreAuthorize("hasAnyRole('ROOT','"+ Login.ROLE_SUPPLY_CHAIN+"','"+Login.ROLE_LOOK+"')") @GetMapping("/manage/depotList") @RowCustom(distinct = true, dramatizer = JQueryDataTableDramatizer.class) RowDefinition data(); @PostMapping("/manage/depotList") String add(String name, Address address, String haierCode, String type, String chargePeopleName
, String chargePeopleMobile); @PutMapping("/manage/depotList/{id}/disable") @ResponseStatus(HttpStatus.NO_CONTENT) @Transactional void disable(@PathVariable("id") long id); @PutMapping("/manage/depotList/{id}/enable") @ResponseStatus(HttpStatus.NO_CONTENT) @Transactional void enable(@PathVariable("id") long id); } | @Test public void index() throws Exception { driver.get("http: assertThat(driver.getTitle()) .isEqualTo("仓库管理"); driver.get("http: assertThat(driver.getTitle()) .isEqualTo("新仓库"); } |
ManageDepotController { @PreAuthorize("hasAnyRole('ROOT','"+ Login.ROLE_SUPPLY_CHAIN+"','"+Login.ROLE_LOOK+"')") @GetMapping("/manage/depotList") @RowCustom(distinct = true, dramatizer = JQueryDataTableDramatizer.class) public RowDefinition data() { return new DepotRows(time -> conversionService.convert(time, String.class)) { @Override public Specification<Depot> specification() { return null; } }; } @PreAuthorize("hasAnyRole('ROOT','"+ Login.ROLE_SUPPLY_CHAIN+"','"+Login.ROLE_LOOK+"')") @GetMapping("/manageDepot") String index(); @GetMapping("/manageDepotAdd") String toAdd(); @PreAuthorize("hasAnyRole('ROOT','"+ Login.ROLE_SUPPLY_CHAIN+"','"+Login.ROLE_LOOK+"')") @GetMapping("/manage/depotList") @RowCustom(distinct = true, dramatizer = JQueryDataTableDramatizer.class) RowDefinition data(); @PostMapping("/manage/depotList") String add(String name, Address address, String haierCode, String type, String chargePeopleName
, String chargePeopleMobile); @PutMapping("/manage/depotList/{id}/disable") @ResponseStatus(HttpStatus.NO_CONTENT) @Transactional void disable(@PathVariable("id") long id); @PutMapping("/manage/depotList/{id}/enable") @ResponseStatus(HttpStatus.NO_CONTENT) @Transactional void enable(@PathVariable("id") long id); } | @Test public void data() throws Exception { add(); mockMvc.perform( get("/manage/depotList") ) .andExpect(status().isOk()) .andDo(print()) .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) .andExpect(similarJQueryDataTable("classpath:/manage-view/mock/depotList.json")); } |
InitService { @PostConstruct @Transactional @Order(Ordered.HIGHEST_PRECEDENCE) public void init() throws IOException, SQLException { commons(); database(); upgrade(); managers(); productTypes(); depots(); products(); others(); mainOrderService.createExecutorToForPayOrder(); applicationEventPublisher.publishEvent(new InitDone()); } @PostConstruct @Transactional @Order(Ordered.HIGHEST_PRECEDENCE) void init(); } | @Test public void init() throws Exception { Manager root = managerRepository.findByLoginName("root"); System.out.println(root); assertThat(root) .isNotNull(); } |
ManageDepotController { @PostMapping("/manage/depotList") public String add(String name, Address address, String haierCode, String type, String chargePeopleName , String chargePeopleMobile) { Depot depot; if ("HaierDepot".equalsIgnoreCase(type)) { HaierDepot haierDepot = new HaierDepot(); haierDepot.setHaierCode(haierCode); depot = haierDepot; } else { depot = new Depot(); } depot.setEnable(true); depot.setCreateTime(LocalDateTime.now()); depot.setName(name); depot.setAddress(address); depot.setChargePeopleName(chargePeopleName); depot.setChargePeopleMobile(chargePeopleMobile); depotRepository.save(depot); return "redirect:/manageDepot"; } @PreAuthorize("hasAnyRole('ROOT','"+ Login.ROLE_SUPPLY_CHAIN+"','"+Login.ROLE_LOOK+"')") @GetMapping("/manageDepot") String index(); @GetMapping("/manageDepotAdd") String toAdd(); @PreAuthorize("hasAnyRole('ROOT','"+ Login.ROLE_SUPPLY_CHAIN+"','"+Login.ROLE_LOOK+"')") @GetMapping("/manage/depotList") @RowCustom(distinct = true, dramatizer = JQueryDataTableDramatizer.class) RowDefinition data(); @PostMapping("/manage/depotList") String add(String name, Address address, String haierCode, String type, String chargePeopleName
, String chargePeopleMobile); @PutMapping("/manage/depotList/{id}/disable") @ResponseStatus(HttpStatus.NO_CONTENT) @Transactional void disable(@PathVariable("id") long id); @PutMapping("/manage/depotList/{id}/enable") @ResponseStatus(HttpStatus.NO_CONTENT) @Transactional void enable(@PathVariable("id") long id); } | @Test public void add() throws Exception { addNewHaierDepot(); addNewManuallyDepot(); } |
ManageDepotController { @PutMapping("/manage/depotList/{id}/disable") @ResponseStatus(HttpStatus.NO_CONTENT) @Transactional public void disable(@PathVariable("id") long id) { depotRepository.getOne(id).setEnable(false); } @PreAuthorize("hasAnyRole('ROOT','"+ Login.ROLE_SUPPLY_CHAIN+"','"+Login.ROLE_LOOK+"')") @GetMapping("/manageDepot") String index(); @GetMapping("/manageDepotAdd") String toAdd(); @PreAuthorize("hasAnyRole('ROOT','"+ Login.ROLE_SUPPLY_CHAIN+"','"+Login.ROLE_LOOK+"')") @GetMapping("/manage/depotList") @RowCustom(distinct = true, dramatizer = JQueryDataTableDramatizer.class) RowDefinition data(); @PostMapping("/manage/depotList") String add(String name, Address address, String haierCode, String type, String chargePeopleName
, String chargePeopleMobile); @PutMapping("/manage/depotList/{id}/disable") @ResponseStatus(HttpStatus.NO_CONTENT) @Transactional void disable(@PathVariable("id") long id); @PutMapping("/manage/depotList/{id}/enable") @ResponseStatus(HttpStatus.NO_CONTENT) @Transactional void enable(@PathVariable("id") long id); } | @Test public void disable() throws Exception { changeEnable("disable", false); } |
ManageDepotController { @PutMapping("/manage/depotList/{id}/enable") @ResponseStatus(HttpStatus.NO_CONTENT) @Transactional public void enable(@PathVariable("id") long id) { depotRepository.getOne(id).setEnable(true); } @PreAuthorize("hasAnyRole('ROOT','"+ Login.ROLE_SUPPLY_CHAIN+"','"+Login.ROLE_LOOK+"')") @GetMapping("/manageDepot") String index(); @GetMapping("/manageDepotAdd") String toAdd(); @PreAuthorize("hasAnyRole('ROOT','"+ Login.ROLE_SUPPLY_CHAIN+"','"+Login.ROLE_LOOK+"')") @GetMapping("/manage/depotList") @RowCustom(distinct = true, dramatizer = JQueryDataTableDramatizer.class) RowDefinition data(); @PostMapping("/manage/depotList") String add(String name, Address address, String haierCode, String type, String chargePeopleName
, String chargePeopleMobile); @PutMapping("/manage/depotList/{id}/disable") @ResponseStatus(HttpStatus.NO_CONTENT) @Transactional void disable(@PathVariable("id") long id); @PutMapping("/manage/depotList/{id}/enable") @ResponseStatus(HttpStatus.NO_CONTENT) @Transactional void enable(@PathVariable("id") long id); } | @Test public void enable() throws Exception { changeEnable("enable", true); } |
ManageFactoryController { @PreAuthorize("hasAnyRole('ROOT','"+ Login.ROLE_SUPPLY_CHAIN+"','"+Login.ROLE_LOOK+"')") @GetMapping("/manageFactory") public String index() { return "_factoryManage.html"; } @PreAuthorize("hasAnyRole('ROOT','"+ Login.ROLE_SUPPLY_CHAIN+"','"+Login.ROLE_LOOK+"')") @GetMapping("/manageFactory") String index(); @GetMapping("/manageFactoryAdd") String toAdd(); @PreAuthorize("hasAnyRole('ROOT','"+ Login.ROLE_SUPPLY_CHAIN+"','"+Login.ROLE_LOOK+"')") @GetMapping("/manage/factoryList") @RowCustom(distinct = true, dramatizer = JQueryDataTableDramatizer.class) RowDefinition data(); @PostMapping("/manage/factoryList") String add(String name, Address address, String chargePeopleName
, String chargePeopleMobile); @PutMapping("/manage/factoryList/{id}/disable") @ResponseStatus(HttpStatus.NO_CONTENT) @Transactional void disable(@PathVariable("id") long id); @PutMapping("/manage/factoryList/{id}/enable") @ResponseStatus(HttpStatus.NO_CONTENT) @Transactional void enable(@PathVariable("id") long id); } | @Test public void index() throws Exception { driver.get("http: assertThat(driver.getTitle()) .isEqualTo("工厂管理"); driver.get("http: assertThat(driver.getTitle()) .isEqualTo("新工厂"); } |
ManageFactoryController { @PreAuthorize("hasAnyRole('ROOT','"+ Login.ROLE_SUPPLY_CHAIN+"','"+Login.ROLE_LOOK+"')") @GetMapping("/manage/factoryList") @RowCustom(distinct = true, dramatizer = JQueryDataTableDramatizer.class) public RowDefinition data() { return new RowDefinition<Factory>() { @Override public List<Order> defaultOrder(CriteriaBuilder criteriaBuilder, Root<Factory> root) { return Arrays.asList( criteriaBuilder.asc(root.get("enable")) , criteriaBuilder.desc(root.get("createTime")) ); } @Override public Class<Factory> entityClass() { return Factory.class; } @Override public List<FieldDefinition<Factory>> fields() { return Arrays.asList( Fields.asBasic("id") , FieldBuilder.asName(Factory.class, "address") .addSelect(root -> root.get("address")) .addFormat((object, type) -> object.toString()) .build() , Fields.asBasic("name") , Fields.asBasic("chargePeopleName") , Fields.asBasic("chargePeopleMobile") , FieldBuilder.asName(Factory.class, "createTime") .addFormat((data, type) -> conversionService.convert(data, String.class)) .build() , Fields.asBasic("enable") ); } @Override public Specification<Factory> specification() { return null; } }; } @PreAuthorize("hasAnyRole('ROOT','"+ Login.ROLE_SUPPLY_CHAIN+"','"+Login.ROLE_LOOK+"')") @GetMapping("/manageFactory") String index(); @GetMapping("/manageFactoryAdd") String toAdd(); @PreAuthorize("hasAnyRole('ROOT','"+ Login.ROLE_SUPPLY_CHAIN+"','"+Login.ROLE_LOOK+"')") @GetMapping("/manage/factoryList") @RowCustom(distinct = true, dramatizer = JQueryDataTableDramatizer.class) RowDefinition data(); @PostMapping("/manage/factoryList") String add(String name, Address address, String chargePeopleName
, String chargePeopleMobile); @PutMapping("/manage/factoryList/{id}/disable") @ResponseStatus(HttpStatus.NO_CONTENT) @Transactional void disable(@PathVariable("id") long id); @PutMapping("/manage/factoryList/{id}/enable") @ResponseStatus(HttpStatus.NO_CONTENT) @Transactional void enable(@PathVariable("id") long id); } | @Test public void data() throws Exception { add(); mockMvc.perform( get("/manage/factoryList") ) .andExpect(status().isOk()) .andDo(print()) .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) .andExpect(similarJQueryDataTable("classpath:/manage-view/mock/factoryList.json")); } |
ManageFactoryController { @PostMapping("/manage/factoryList") public String add(String name, Address address, String chargePeopleName , String chargePeopleMobile) { Factory factory = new Factory(); factory.setEnable(true); factory.setCreateTime(LocalDateTime.now()); factory.setName(name); factory.setAddress(address); factory.setChargePeopleName(chargePeopleName); factory.setChargePeopleMobile(chargePeopleMobile); factoryRepository.save(factory); return "redirect:/manageFactory"; } @PreAuthorize("hasAnyRole('ROOT','"+ Login.ROLE_SUPPLY_CHAIN+"','"+Login.ROLE_LOOK+"')") @GetMapping("/manageFactory") String index(); @GetMapping("/manageFactoryAdd") String toAdd(); @PreAuthorize("hasAnyRole('ROOT','"+ Login.ROLE_SUPPLY_CHAIN+"','"+Login.ROLE_LOOK+"')") @GetMapping("/manage/factoryList") @RowCustom(distinct = true, dramatizer = JQueryDataTableDramatizer.class) RowDefinition data(); @PostMapping("/manage/factoryList") String add(String name, Address address, String chargePeopleName
, String chargePeopleMobile); @PutMapping("/manage/factoryList/{id}/disable") @ResponseStatus(HttpStatus.NO_CONTENT) @Transactional void disable(@PathVariable("id") long id); @PutMapping("/manage/factoryList/{id}/enable") @ResponseStatus(HttpStatus.NO_CONTENT) @Transactional void enable(@PathVariable("id") long id); } | @Test public void add() throws Exception { addNewFactory(); } |
ManageFactoryController { @PutMapping("/manage/factoryList/{id}/disable") @ResponseStatus(HttpStatus.NO_CONTENT) @Transactional public void disable(@PathVariable("id") long id) { factoryRepository.getOne(id).setEnable(false); } @PreAuthorize("hasAnyRole('ROOT','"+ Login.ROLE_SUPPLY_CHAIN+"','"+Login.ROLE_LOOK+"')") @GetMapping("/manageFactory") String index(); @GetMapping("/manageFactoryAdd") String toAdd(); @PreAuthorize("hasAnyRole('ROOT','"+ Login.ROLE_SUPPLY_CHAIN+"','"+Login.ROLE_LOOK+"')") @GetMapping("/manage/factoryList") @RowCustom(distinct = true, dramatizer = JQueryDataTableDramatizer.class) RowDefinition data(); @PostMapping("/manage/factoryList") String add(String name, Address address, String chargePeopleName
, String chargePeopleMobile); @PutMapping("/manage/factoryList/{id}/disable") @ResponseStatus(HttpStatus.NO_CONTENT) @Transactional void disable(@PathVariable("id") long id); @PutMapping("/manage/factoryList/{id}/enable") @ResponseStatus(HttpStatus.NO_CONTENT) @Transactional void enable(@PathVariable("id") long id); } | @Test public void disable() throws Exception { changeEnable("disable", false); } |
ManageFactoryController { @PutMapping("/manage/factoryList/{id}/enable") @ResponseStatus(HttpStatus.NO_CONTENT) @Transactional public void enable(@PathVariable("id") long id) { factoryRepository.getOne(id).setEnable(true); } @PreAuthorize("hasAnyRole('ROOT','"+ Login.ROLE_SUPPLY_CHAIN+"','"+Login.ROLE_LOOK+"')") @GetMapping("/manageFactory") String index(); @GetMapping("/manageFactoryAdd") String toAdd(); @PreAuthorize("hasAnyRole('ROOT','"+ Login.ROLE_SUPPLY_CHAIN+"','"+Login.ROLE_LOOK+"')") @GetMapping("/manage/factoryList") @RowCustom(distinct = true, dramatizer = JQueryDataTableDramatizer.class) RowDefinition data(); @PostMapping("/manage/factoryList") String add(String name, Address address, String chargePeopleName
, String chargePeopleMobile); @PutMapping("/manage/factoryList/{id}/disable") @ResponseStatus(HttpStatus.NO_CONTENT) @Transactional void disable(@PathVariable("id") long id); @PutMapping("/manage/factoryList/{id}/enable") @ResponseStatus(HttpStatus.NO_CONTENT) @Transactional void enable(@PathVariable("id") long id); } | @Test public void enable() throws Exception { changeEnable("enable", true); } |
WechatMyController { private String myTeam(@AuthenticationPrincipal Login loginInput, Model model) { Login login = loginService.get(loginInput.getId()); if (loginService.isRegularLogin(login)) model.addAttribute("agentLevel", agentService.loginTitle(agentService.highestAgent(login))); else model.addAttribute("agentLevel", "普通用户"); return "[email protected]"; } @GetMapping("/wechatOrderList") String wechatOrderList(); @GetMapping("/wechatMallOrderList") String wechatMallOrderList(); @GetMapping(SystemService.wechatMyURi) @Transactional(readOnly = true) String my(@AuthenticationPrincipal Login login, Model model); @GetMapping(SystemService.wechatMyTeamURi) String originMyTeam(); } | @Test @Ignore public void myTeam() throws InterruptedException { Login master = newRandomAgent(); randomAgentTree(master); login = getSubAgents(master).stream() .max(new RandomComparator()).orElse(null).getLogin(); WechatMyPage myPage = getWechatMyPage(); Set<Login> agentLogin = agentLevelRepository.findAll().stream() .map(AgentLevel::getLogin) .collect(Collectors.toSet()); AgentLevel currentAgent = agentService.highestAgent(login); while (true) { final List<AgentLevel> subAgents = getSubAgents(currentAgent); if (subAgents.isEmpty()) { log.info("最后一个等级,应该可以看到爱心天使了"); myPage.assertTeamMembers( loginRepository.findByGuideUserAndSuccessOrderTrue(currentAgent.getLogin()) .stream() .filter(login1 -> !agentLogin.contains(login1)) .map(this::fromLogin) .collect(Collectors.toList()) ); myPage.assertTeamMemberNotClick(); break; } else { myPage.assertTeamMembers(subAgents.stream().map(this::fromAgentLevel).collect(Collectors.toList())); log.info("检测通过,点击下一个"); AgentLevel nextAgent = subAgents.stream().max(new RandomComparator()).orElse(null); myPage.clickMember(fromAgentLevel(nextAgent)); currentAgent = nextAgent; } } myPage = getWechatMyPage(); myPage.assertGuideTeamMembers( loginRepository.findByGuideUser(login) .stream() .filter(login1 -> !agentLogin.contains(login1)) .map(this::forGuideMember) .collect(Collectors.toList()) ); } |
WechatShareController { @GetMapping(SystemService.wechatShareUri) public String share(@AuthenticationPrincipal Login loginInput, Model model) { Login login = loginService.get(loginInput.getId()); if (!loginService.isRegularLogin(login) && !loginService.allowShare(login)) return "redirect:" + SystemService.wechatShareMoreUri; model.addAttribute("login", login); final String targetUrl = systemService.toUrl("/wechatJoin" + login.getId()); model.addAttribute("qrCodeUrl", qrController.urlForText(targetUrl).toString()); model.addAttribute("url", targetUrl); return "[email protected]"; } @GetMapping(SystemService.wechatShareUri) String share(@AuthenticationPrincipal Login loginInput, Model model); @GetMapping(SystemService.wechatShareMoreUri) String shareMore(@AuthenticationPrincipal Login login, Model model); @GetMapping("/wechatJoinSM{id}") @Transactional String joinBySalesman(@PathVariable long id, @OpenId String openId, @AuthenticationPrincipal Object login
, Model model); @GetMapping("/wechatJoin{id}") String join(@PathVariable long id, @OpenId String openId, @AuthenticationPrincipal Object login, Model model); } | @Test public void share() throws Exception { final Login newUser = createNewUserByShare(); System.out.println(newUser); } |
MiscController { @RequestMapping(method = RequestMethod.POST, value = "/misc/sendRegisterCode") @ResponseBody public ApiResult sendRegisterCode(String mobile) throws IOException { if (loginService.byLoginName(mobile) != null) { return ApiResult.withCodeAndMessage(401, "该手机号码已被人使用", null); } verificationCodeService.sendCode(mobile, loginService.registerVerificationType()); return ApiResult.withOk(); } @RequestMapping(method = RequestMethod.POST, value = "/misc/sendLoginCode") @ResponseBody ApiResult sendLoginCode(String mobile); @RequestMapping(method = RequestMethod.POST, value = "/misc/sendRegisterCode") @ResponseBody ApiResult sendRegisterCode(String mobile); } | @Test public void sendRegisterCode() throws Exception { mockMvc.perform(post("/misc/sendRegisterCode") .contentType(MediaType.APPLICATION_FORM_URLENCODED) .param("mobile", randomMobile()) ) .andExpect(status().isOk()) .andExpect(jsonPath("$.resultCode").value(200)); final String mobile = randomMobile(); loginService.newLogin(Login.class, mobile, newRandomLogin(), UUID.randomUUID().toString()); mockMvc.perform(post("/misc/sendRegisterCode") .contentType(MediaType.APPLICATION_FORM_URLENCODED) .param("mobile", mobile) ) .andExpect(status().isOk()) .andExpect(jsonPath("$.resultCode").value(401)); } |
WechatController { @GetMapping("/toLoginWechat") public String login(WeixinUserDetail detail, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.trace(detail); Login login = loginService.asWechat(detail.getOpenId()); if (login == null) return "redirect:/wechatLogin"; if (StringUtils.isEmpty(login.getUsername())) { return "redirect:/wechatRegister"; } loginToSecurity(login,request,response); SavedRequest savedRequest = requestCache.getRequest(request, response); if (savedRequest == null) { return "redirect:/wechatIndex"; } if (savedRequest.getRedirectUrl().startsWith("http: return "redirect:/" + savedRequest.getRedirectUrl().substring("http: } return "redirect:" + savedRequest.getRedirectUrl(); } @GetMapping("/wechat/bindTo{id}") @Transactional @ResponseBody String bindTo(WeixinUserDetail detail, @PathVariable("id") long id); @PostMapping("/wechatRegister") @Transactional String wechatRegister(@OpenId String openId, String name, String mobile, String authCode); @GetMapping("/wechatRegister") String wechatRegister(); @GetMapping("/toLoginWechat") String login(WeixinUserDetail detail, HttpServletRequest request, HttpServletResponse response); @GetMapping("/wechatLogout") String logout(@AuthenticationPrincipal Login login); @GetMapping(SystemService.wechatMallIndex) String index(); @GetMapping("/wechatLogin") String wechatLogin(); @PostMapping("/wechatLogin") String bindLogin(@OpenId String openId, String username, String password, String mobile, String authCode); @GetMapping("/wechatForward/{goodId}_{id}") String wechatForward(@OpenId String openId,@PathVariable Long goodId,@PathVariable Long id
, HttpServletRequest request, HttpServletResponse response); } | @Test public void bindWithPassword() throws Exception { WeixinUserDetail detail = nextCurrentWechatAccount(); LoginPage loginPage = getLoginPageForBrowseIndex(); String rawPassword = UUID.randomUUID().toString(); Login login = newRandomAgent(rawPassword); loginPage.login(login.getLoginName(), rawPassword + 1); loginPage.assertHaveTooltip(); loginPage.login(login.getLoginName(), rawPassword); initPage(MallIndexPage.class); assertThat(loginService.asWechat(detail.getOpenId())) .isNotNull(); }
@Test public void testMallIndex() throws IOException, InterruptedException { LoginPage loginPage = getLoginPageForBrowseIndex(); String rawPassword = UUID.randomUUID().toString(); Login login = newRandomAgent(rawPassword); for (TagType tagType : TagType.values()) { for (int i = 0; i < 3 + random.nextInt(2); i++) { newRandomTag(tagType); } } MainGood good = mainGoodService.forSale().stream().max(Comparator.comparing(MainGood::getId)).orElse(null); if (good == null) return; Set<Tag> tagTypeSet = new HashSet<>(); tagTypeSet.addAll(tagRepository.findByTypeAndDisabledFalseOrderByWeightDesc(TagType.LIST)); tagTypeSet.addAll(tagRepository.findByTypeAndDisabledFalseOrderByWeightDesc(TagType.SEARCH)); good.setTags(tagTypeSet); mainGoodRepository.save(good); loginPage.login(login.getLoginName(), rawPassword); MallIndexPage indexPage = initPage(MallIndexPage.class); indexPage.validatePageWithImgTag(tagRepository.findByTypeAndDisabledFalseOrderByWeightDesc(TagType.IMG)); indexPage.validatePageWithSearch(tagRepository.findByTypeAndDisabledFalseOrderByWeightDesc(TagType.SEARCH)); indexPage.validatePageWithList(tagRepository.findByTypeAndDisabledFalseOrderByWeightDesc(TagType.LIST), good); indexPage.clickSearch(); MallSearchPage mallSearchPage = initPage(MallSearchPage.class); mallSearchPage.searchGoods(good); driver.get("http: indexPage = initPage(MallIndexPage.class); Tag searchTag = tagRepository.findByTypeAndDisabledFalseOrderByWeightDesc(TagType.SEARCH).stream() .max(Comparator.comparing(Tag::getName)).orElse(null); assertThat(searchTag).isNotNull(); indexPage.clickTagSearch(searchTag); MallTagDetailPage tagDetailPage = initPage(MallTagDetailPage.class); tagDetailPage.validateGoods(Arrays.asList(good)); String propertyValue = good.getProduct().getSpecPropertyNameValues().values().stream().findAny().get(); tagDetailPage.clickTagOrPropertyValue(propertyValue); tagDetailPage.validateGoods(Arrays.asList(good)); tagDetailPage.clickTagOrPropertyValue(null); tagDetailPage.validateGoods(mainGoodService.forSale()); } |
WechatController { @GetMapping("/wechatForward/{goodId}_{id}") public String wechatForward(@OpenId String openId,@PathVariable Long goodId,@PathVariable Long id , HttpServletRequest request, HttpServletResponse response){ Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if(authentication == null || authentication instanceof AnonymousAuthenticationToken){ Login login = loginService.asWechat(openId); if(login == null){ login = wechatService.shareTo(id,openId); } loginToSecurity(login,request,response); } if(goodId > 0){ return "redirect:/wechatSearch/goodsDetail/" + goodId; }else{ return "redirect:" + SystemService.wechatMallIndex; } } @GetMapping("/wechat/bindTo{id}") @Transactional @ResponseBody String bindTo(WeixinUserDetail detail, @PathVariable("id") long id); @PostMapping("/wechatRegister") @Transactional String wechatRegister(@OpenId String openId, String name, String mobile, String authCode); @GetMapping("/wechatRegister") String wechatRegister(); @GetMapping("/toLoginWechat") String login(WeixinUserDetail detail, HttpServletRequest request, HttpServletResponse response); @GetMapping("/wechatLogout") String logout(@AuthenticationPrincipal Login login); @GetMapping(SystemService.wechatMallIndex) String index(); @GetMapping("/wechatLogin") String wechatLogin(); @PostMapping("/wechatLogin") String bindLogin(@OpenId String openId, String username, String password, String mobile, String authCode); @GetMapping("/wechatForward/{goodId}_{id}") String wechatForward(@OpenId String openId,@PathVariable Long goodId,@PathVariable Long id
, HttpServletRequest request, HttpServletResponse response); } | @Test public void wechatForwardTest(){ String rawPassword = UUID.randomUUID().toString(); Login login = newRandomAgent(rawPassword); MainGood mainGood = mainGoodService.forSale().stream().findAny().get(); String shareUrl = "http: LoginPage loginPage = getLoginPageForBrowseIndex(); loginPage.login(login.getLoginName(), rawPassword); driver.get(shareUrl); MallGoodsDetailPage testGoodDetailPage = initPage(MallGoodsDetailPage.class); testGoodDetailPage.validateShareUrl(mainGood.getId(),login.getId()); driver.get("http: driver.get(shareUrl); testGoodDetailPage = initPage(MallGoodsDetailPage.class); testGoodDetailPage.validateShareUrl(mainGood.getId(),null); testGoodDetailPage.clickBuyNow(); testGoodDetailPage.printThisPage(); WechatRegisterPage registerPage = initPage(WechatRegisterPage.class); String mobile = randomMobile(); registerPage.sendAuthCode(mobile); registerPage.submitSuccessAs(RandomStringUtils.randomAlphabetic(10)); try { Thread.sleep(1000); } catch (InterruptedException ignored) { } MallIndexPage indexPage = initPage(MallIndexPage.class); driver.get(shareUrl); testGoodDetailPage = initPage(MallGoodsDetailPage.class); testGoodDetailPage.clickBuyNow(); MallOrderPlacePage orderPlacePage = initPage(MallOrderPlacePage.class); } |
WechatCommonProblemController { @GetMapping(SystemService.helpCenterURi) public String index(){ return "wechat@helpCenter/index.html"; } @GetMapping("/commonProblemDetail/{id}") String commonProblemDetail(@PathVariable Long id, Model model); @GetMapping("/commonProblem/search") @ResponseBody Map<String, Object> search(String title); @GetMapping(SystemService.helpCenterURi) String index(); } | @Test public void index() throws Exception { String title = RandomStringUtils.randomAscii(10); commonProblemService.addAndEditCommonProblem(null, title,50 , RandomStringUtils.randomAscii(20)); driver.get("http: HelpCenterPage page = initPage(HelpCenterPage.class); page.assertHasTopic(title); HelpDetailPage helpDetailPage = page.clickHelpDetail(); helpDetailPage.asssertHasTopic(title); } |
WechatUpgradeController { @PostMapping("/wechatUpgrade") @Transactional public ModelAndView upgrade(@AuthenticationPrincipal Login login, String agentName, int newLevel, Address address , String cardFrontPath , String cardBackPath, String businessLicensePath, String upgradeMode, HttpServletRequest servletRequest) throws SystemMaintainException, IOException { PromotionRequest request = promotionRequestService.initRequest(login, agentName, newLevel, address, cardBackPath , cardFrontPath, businessLicensePath); if (request.getOrderDueAmount() == null) { promotionRequestService.submitRequest(request); return new ModelAndView("redirect:/wechatUpgradeApplySuccess"); } if ("2".equals(upgradeMode)) { promotionRequestService.submitRequest(request); return new ModelAndView("redirect:/wechatUpgradeApplySuccess"); } request.setOrderedName(readService.nameForPrincipal(login)); request.setOrderedMobile(readService.mobileFor(login)); return payAssistanceService.payOrder(login.getWechatUser().getOpenId(), servletRequest, request, false); } @GetMapping("/wechatUpgrade") @Transactional(readOnly = true) String index(@AuthenticationPrincipal Login loginInput, Model model); @GetMapping("/wechatUpgradeChecking") String checking(); @GetMapping("/wechatUpgradeApplySuccess") String applySuccess(); @PostMapping("/wechatUpgrade") @Transactional ModelAndView upgrade(@AuthenticationPrincipal Login login, String agentName, int newLevel, Address address
, String cardFrontPath
, String cardBackPath, String businessLicensePath, String upgradeMode, HttpServletRequest servletRequest); } | @Test public void upgrade1() throws Exception { upgrade(1, 4); }
@Test public void upgrade2() throws Exception { upgrade(2, 3); }
@Test public void upgrade3() throws Exception { upgrade(3, 2); } |
WelcomeController { @RequestMapping(method = RequestMethod.GET, value = {"", "/"}) public String index(@AuthenticationPrincipal Login login, @HighestAgent AgentLevel agentLevel) { if (login.isManageable()) return "redirect:/manage"; if (agentLevel != null) return "redirect:/agentMain"; throw new IllegalStateException("不知道引到至何处。"); } @RequestMapping(method = RequestMethod.GET, value = {"", "/"}) String index(@AuthenticationPrincipal Login login, @HighestAgent AgentLevel agentLevel); } | @Test public void index() throws Exception { String rawPassword = randomEmailAddress(); Manager manager = newRandomManager(rawPassword, ManageLevel.root); driver.get("http: WebLoginPage loginPage = initPage(WebLoginPage.class); loginPage.login(manager.getLoginName(), rawPassword); initPage(AgentManageMainPage.class); createWebDriver(); Login login = newRandomAgent(rawPassword); driver.get("http: loginPage = initPage(WebLoginPage.class); loginPage.login(login.getLoginName(), rawPassword); initPage(AgentManageMainPage.class); } |
CommissionController { public static String formatCommonInfo(Object origin) { String src = origin.toString(); int index = src.lastIndexOf("¥"); String first = src.substring(0, index - 1); return first + Money.format.format(new BigDecimal(src.substring(index + 1))); } static String formatCommonInfo(Object origin); @RowCustom(dramatizer = ApiDramatizer.class, distinct = true) @GetMapping("/api/commList/{type}") RowDefinition<Commission> commList(@AuthenticationPrincipal Login login, @PathVariable("type") String type); } | @Test public void formatCommonInfo() throws Exception { System.out.println(CommissionController.formatCommonInfo("1个厨下净水机 ¥2820.00000000000000000000")); NumberFormat format = NumberFormat.getPercentInstance(Locale.CHINA); format.setMaximumFractionDigits(2); System.out.println(format.format(BigDecimal.valueOf(0.05))); System.out.println(format.format(BigDecimal.valueOf(0.005))); System.out.println(format.format(BigDecimal.valueOf(0.0005))); } |
AgentNavigateController { @RequestMapping(method = RequestMethod.GET, value = "/agentMain") public String agentMain(@AuthenticationPrincipal Login login, @HighestAgent AgentLevel agentLevel, Model model) { if (login.isManageable()) { model.addAttribute("title", "管理后台"); model.addAttribute("loginAs", login.getLoginTitle()); } else if (agentLevel != null) { model.addAttribute("title", "经销商后台"); model.addAttribute("loginAs", agentService.loginTitle(agentLevel)); } return "agentMain.html"; } @RequestMapping(method = RequestMethod.GET, value = "/agentOrderManage") String agentOrderManage(); @RequestMapping(method = RequestMethod.GET, value = "/agentMain") String agentMain(@AuthenticationPrincipal Login login, @HighestAgent AgentLevel agentLevel, Model model); } | @Test public void agentMain() throws Exception { AgentManageMainPage mainPage = mainPage(); mainPage.selectMenu("fa-users"); mainPage.currentContext(AgentManagePage.class); mainPage = mainPage(); mainPage.selectMenu("fa-address-card-o"); AgentOrderManagePage agentOrderManagePage = mainPage.currentContext(AgentOrderManagePage.class); String uri = agentOrderManagePage.placeOrderUri(); driver.get("http: System.out.println(driver.getPageSource()); initPage(AgentPlaceOrderPage.class); assertThat(true) .isTrue(); } |
LoginDataController { @PreAuthorize("!isAnonymous()") @GetMapping("/loginData/select2") @RowCustom(dramatizer = Select2Dramatizer.class, distinct = true) public RowDefinition<Login> searchLoginSelect2(String search, Boolean agent, Integer level) { return searchLogin(search, agent, level); } @GetMapping("/loginData/mobileValidation") @ResponseBody boolean mobileValidation(@RequestParam String mobile); @PreAuthorize("!isAnonymous()") @GetMapping("/loginData/select2") @RowCustom(dramatizer = Select2Dramatizer.class, distinct = true) RowDefinition<Login> searchLoginSelect2(String search, Boolean agent, Integer level); @PutMapping("/login/name/{id}") @PreAuthorize("hasAnyRole('ROOT','" + Login.ROLE_AllAgent + "','" + Login.ROLE_MANAGER + "')") @ResponseBody @Transactional ApiResult changeName(@RequestBody String newName, @PathVariable("id") long id); @PutMapping("/login/guide/{id}") @PreAuthorize("hasAnyRole('ROOT','" + Login.ROLE_AllAgent + "','" + Login.ROLE_MANAGER + "')") @ResponseBody @Transactional ApiResult changeGuide(@RequestBody String newGuide, @PathVariable("id") long id, @AuthenticationPrincipal Login login); @PutMapping("/login/mobile/{id}") @PreAuthorize("hasAnyRole('ROOT','" + Login.ROLE_AllAgent + "','" + Login.ROLE_MANAGER + "')") @ResponseBody @Transactional ApiResult changeMobile(@RequestBody String mobile, @PathVariable("id") long id); @GetMapping(value = "/loginCommissionJournal", produces = "text/html") @Transactional(readOnly = true) String journal(long id, @AuthenticationPrincipal Login login, Model model); @GetMapping(value = "/agentGoodAdvancePaymentJournal", produces = "text/html") @Transactional(readOnly = true) String agentGoodAdvancePaymentJournal(long id, @AuthenticationPrincipal Login login, Model model); @GetMapping(value = "/agentGoodAdvancePaymentJournal", produces = "application/json") @RowCustom(dramatizer = JQueryDataTableDramatizer.class, distinct = true) RowDefinition<AgentGoodAdvancePaymentJournal> agentGoodAdvancePaymentJournal(long id, @AuthenticationPrincipal Login login); @GetMapping(value = "/loginData/subordinate", produces = "application/json") @RowCustom(distinct = true, dramatizer = JQueryDataTableDramatizer.class) RowDefinition<Login> subordinate(long id, String mobile, @AuthenticationPrincipal Login login); } | @Test public void searchLoginSelect2() throws Exception { int currentCount = JsonPath.read(mockMvc.perform( get("/loginData/select2") ) .andReturn().getResponse().getContentAsString(), "$.total_count"); final int count = random.nextInt(40) + 30; int i = count; String toSearch = ""; while (i-- > 0) { Login login = newRandomManager(UUID.randomUUID().toString(), ManageLevel.root); if (random.nextBoolean()) contactWayService.updateMobile(login, randomMobile()); else { final String name = randomString(); contactWayService.updateName(login, name); toSearch = name; } } mockMvc.perform( get("/loginData/select2") ) .andExpect(similarSelect2("classpath:/mock/searchLogin.json")) .andExpect(jsonPath("$.total_count").value(currentCount + count)); mockMvc.perform( get("/loginData/select2") .param("page", "2") ) .andExpect(similarSelect2("classpath:/mock/searchLogin.json")) .andExpect(jsonPath("$.total_count").value(currentCount + count)); mockMvc.perform( get("/loginData/select2") .param("search", toSearch) ) .andExpect(similarSelect2("classpath:/mock/searchLogin.json")) .andExpect(jsonPath("$.total_count").value(1)); mockMvc.perform( get("/loginData/select2") .param("agent", "true") ) .andExpect(similarSelect2("classpath:/mock/searchLogin.json")); } |
AgentController { @GetMapping("/addAgent") @PreAuthorize("hasAnyRole('ROOT','" + Login.ROLE_AllAgent + "')") public String indexForAdd() { return "addAgent.html"; } @GetMapping("/agentManage") String index(@AuthenticationPrincipal Login login); @GetMapping("/agentDetail") String detail(long id, Model model); @GetMapping("/addAgent") @PreAuthorize("hasAnyRole('ROOT','" + Login.ROLE_AllAgent + "')") String indexForAdd(); @PostMapping("/addAgent") @PreAuthorize("hasAnyRole('ROOT','" + Login.ROLE_AllAgent + "')") @Transactional String addAgent(@AuthenticationPrincipal Login login, Long superiorId, String rank, String levelTitle
, String agentName
, int firstPayment, int agencyFee, @DateTimeFormat(pattern = "yyyy-M-d") @RequestParam LocalDate beginDate
, @DateTimeFormat(pattern = "yyyy-M-d") @RequestParam LocalDate endDate
, String mobile, String password
, long guideUser, Address address, String cardFrontPath, String cardBackPath, String businessLicensePath); } | @Test public void indexForAdd() throws Exception { Manager manager = newRandomManager("", ManageLevel.customerManager); runWith(manager, () -> { mockMvc.perform(get("/addAgent")) .andExpect(status().isOk()) .andExpect(content().contentTypeCompatibleWith(MediaType.TEXT_HTML)) .andExpect(view().name("addAgent.html")); String rank = "某代理商" + RandomStringUtils.randomAlphabetic(10); String agentName = "某人" + RandomStringUtils.randomAlphabetic(10); int firstPayment = 1000 + random.nextInt(10000); int agencyFee = 500 + random.nextInt(600); LocalDate beginDate = LocalDate.now().minusMonths(2); LocalDate endDate = LocalDate.now().plusMonths(2); String mobile = randomMobile(); String password = UUID.randomUUID().toString(); Login guideUser = randomLogin(false); Address address = randomAddress(); String cardFrontPath = newRandomImagePath(); String cardBackPath = newRandomImagePath(); String businessLicensePath = newRandomImagePath(); mockMvc.perform(post("/addAgent") .contentType(MediaType.APPLICATION_FORM_URLENCODED) .param("rank", rank) .param("agentName", agentName) .param("firstPayment", String.valueOf(firstPayment)) .param("agencyFee", String.valueOf(agencyFee)) .param("beginDate", toText(beginDate)) .param("endDate", toText(endDate)) .param("mobile", mobile) .param("password", password) .param("guideUser", String.valueOf(guideUser.getId())) .param("address", address.getStandardWithoutOther()) .param("fullAddress", address.getOtherAddress()) .param("cardFrontPath", cardFrontPath) .param("cardBackPath", cardBackPath) .param("businessLicensePath", businessLicensePath) ) .andDo(print()) .andExpect(status().isFound()) ; return null; }); } |
OrderDataController { @RequestMapping(method = RequestMethod.GET, value = "/orderData/manageableList") @RowCustom(distinct = true, dramatizer = JQueryDataTableDramatizer.class) public RowDefinition manageableList(@AuthenticationPrincipal Login login, String orderId , @RequestParam(value = "phone", required = false) String mobile, Long goodId , @DateTimeFormat(pattern = "yyyy-M-d") @RequestParam(required = false) LocalDate beginDate , @DateTimeFormat(pattern = "yyyy-M-d") @RequestParam(required = false) LocalDate endDate , @DateTimeFormat(pattern = "yyyy-M-d") @RequestParam(required = false) LocalDate orderDate , OrderStatus status) { return new MainOrderRows(login, t -> conversionService.convert(t, String.class)) { @Override public Specification<MainOrder> specification() { return new AndSpecification<>( mainOrderService.search(orderId, mobile, goodId, orderDate, beginDate, endDate, status) , agentService.manageableOrder(login) ); } }; } @RequestMapping(method = RequestMethod.GET, value = "/api/orderList") @RowCustom(distinct = true, dramatizer = ApiDramatizer.class) RowDefinition myOrder(@AuthenticationPrincipal Login login, String search, OrderStatus status); @PutMapping("/orderData/settlement/{id}") @ResponseStatus(HttpStatus.NO_CONTENT) @Transactional void mockPay(@AuthenticationPrincipal Login login, @PathVariable("id") long id); @RequestMapping(method = RequestMethod.GET, value = "/orderData/manageableList") @RowCustom(distinct = true, dramatizer = JQueryDataTableDramatizer.class) RowDefinition manageableList(@AuthenticationPrincipal Login login, String orderId
, @RequestParam(value = "phone", required = false) String mobile, Long goodId
, @DateTimeFormat(pattern = "yyyy-M-d") @RequestParam(required = false) LocalDate beginDate
, @DateTimeFormat(pattern = "yyyy-M-d") @RequestParam(required = false) LocalDate endDate
, @DateTimeFormat(pattern = "yyyy-M-d") @RequestParam(required = false) LocalDate orderDate
, OrderStatus status); @RequestMapping(method = RequestMethod.GET, value = "/orderData2/manageableList") @RowCustom(distinct = true, dramatizer = JQueryDataTableDramatizer.class) RowDefinition manageableList2(@AuthenticationPrincipal Login login, String orderId
, @RequestParam(value = "phone", required = false) String mobile, Long goodId
, @DateTimeFormat(pattern = "yyyy-M-d") @RequestParam(required = false) LocalDate beginDate
, @DateTimeFormat(pattern = "yyyy-M-d") @RequestParam(required = false) LocalDate endDate
, @DateTimeFormat(pattern = "yyyy-M-d") @RequestParam(required = false) LocalDate orderDate
, OrderStatus status); } | @Test public void manageableList() throws Exception { final Login order = testLogin; newRandomOrderFor(order, order); orderDataList(null); newRandomOrderFor(order, order); String serialId = mainOrderService.allOrders().stream() .filter(mainOrder -> mainOrder.getOrderBy().equals(order)) .max(Comparator.comparing(MainOrder::getId)) .orElse(null) .getSerialId(); assertCurrentCount(builder -> builder.param("orderId", serialId), 1); String mobile = randomMobile(); int mobileCurrent = currentCount(builder -> builder.param("phone", mobile)); newRandomOrderFor(order, order); newRandomOrderFor(order, order, mobile); assertCurrentCount(builder -> builder.param("phone", mobile), mobileCurrent + 1); mainOrderService.updateOrderTime(LocalDateTime.now().minusMonths(1)); assertCurrentCount(builder -> builder.param("orderDate", localDateConverter.print(LocalDate.now(), null)), 0); newRandomOrderFor(order, order); assertCurrentCount(builder -> builder.param("orderDate", localDateConverter.print(LocalDate.now(), null)), 1); log.info("beginDate 今天只有一单"); assertCurrentCount(builder -> builder.param("beginDate", localDateConverter.print(LocalDate.now(), null)), 1); log.info("beginDate 今天+1 没有"); assertCurrentCount(builder -> builder.param("beginDate", localDateConverter.print(LocalDate.now().plusDays(1), null)), 0); log.info("endDate 32天前为0"); assertCurrentCount(builder -> builder.param("endDate", localDateConverter.print(LocalDate.now().minusDays(32), null)), 0); } |
ResourceController { @RequestMapping(method = RequestMethod.POST, value = "/webUploader") public ResponseEntity<?> webUploader(String id, MultipartFile file) throws IOException, URISyntaxException { try (InputStream inputStream = file.getInputStream()) { String path = uploadTempResource(inputStream, file); Resource resource = resourceService.getResource(path); HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8); HashMap<String, String> data = new HashMap<>(); data.put("id", path); data.put("url", resource.httpUrl().toString()); return new ResponseEntity<>(objectMapper.writeValueAsBytes(data), httpHeaders, HttpStatus.OK); } } @RequestMapping(value = "/tinyImage", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody ResponseEntity<String> tinyUpload(MultipartFile file); @RequestMapping(value = "/image", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody ResponseEntity<String> ckeditorUpload(MultipartFile upload); @RequestMapping(method = RequestMethod.POST, value = "/webUploader") ResponseEntity<?> webUploader(String id, MultipartFile file); @RequestMapping(method = RequestMethod.POST) ResponseEntity<String> upload(MultipartFile file); @RequestMapping(value = "/fine", method = RequestMethod.POST) @ResponseBody Object fineUpload(MultipartFile file); } | @Test public void webUploader() throws Exception { try (InputStream inputStream = randomPngImageResource().getInputStream()) { mockMvc.perform(fileUpload("/resourceUpload/webUploader") .file(new MockMultipartFile("file", "my_file.png", "image/png", inputStream)) ).andExpect( similarJsonObjectAs("classpath:/mock/webUploader.json") ); } } |
ManageAgentController extends AbstractLoginDetailController { @PutMapping("/agent/superior/{id}") @PreAuthorize("hasAnyRole('ROOT')") @ResponseBody @Transactional public ApiResult changeSuperior(@RequestBody String newGuide, @PathVariable("id") long id) { final AgentLevel target = agentService.getAgent(id); if (!StringUtils.isEmpty(newGuide)) { long guideId = NumberUtils.parseNumber(newGuide, Long.class); AgentLevel targetLevel = agentService.getAgent(loginService.get(guideId), target.getLevel() - 1); loginRelationCacheService.breakConnection(target); target.setSuperior(targetLevel); loginRelationCacheService.addLowestAgentLevelCache(target.getSuperior()); return ApiResult.withOk(Collections.singletonMap("name", readService.nameForAgent(targetLevel))); } return ApiResult.withCodeAndMessage(400, "没有有效的上级代理商", null); } @PutMapping("/agent/superior/{id}") @PreAuthorize("hasAnyRole('ROOT')") @ResponseBody @Transactional ApiResult changeSuperior(@RequestBody String newGuide, @PathVariable("id") long id); @PutMapping("/agent/rank/{id}") @PreAuthorize("hasAnyRole('ROOT','" + Login.ROLE_AllAgent + "','" + Login.ROLE_MANAGER + "')") @ResponseBody @Transactional ApiResult changeRank(@RequestBody String newName, @PathVariable("id") long id); @GetMapping("/manageAgentDetail") @Transactional(readOnly = true) String detail(Model model, long id); @Override String detailTitle(); @Override String parentUri(); @Override String parentTitle(); } | @Test public void go() throws Exception { Login als[] = new Login[systemService.systemLevel()]; AgentLevel as[] = new AgentLevel[systemService.systemLevel()]; initAgentSystem(als, as); updateAllRunWith(newRandomManager(ManageLevel.root)); final AgentLevel toTestAgent = as[as.length - 2]; toTestAgent.getLogin().setGuideUser(als[als.length - 1]); loginRepository.save(toTestAgent.getLogin()); System.out.println(toTestAgent.getLogin().toString()); addSubUserFor(toTestAgent.getLogin()); ManageAgentDetailPage page = ManageAgentDetailPage.of(toTestAgent, this, driver); page.assertName() .isEqualTo(readService.nameForPrincipal(toTestAgent.getLogin())); final String newName = "新名字" + RandomStringUtils.randomAlphabetic(9); page.changeName(newName); assertThat(readService.nameForPrincipal(toTestAgent.getLogin())) .isEqualTo(newName); page.refresh(); page.assertMobile() .isEqualTo(readService.mobileFor(toTestAgent.getLogin())); final String newMobile = randomMobile(); page.changeMobile(newMobile); Thread.sleep(1000L); assertThat(readService.mobileFor(toTestAgent.getLogin())) .isEqualTo(newMobile); page.refresh(); page.assertGuideName() .isEqualTo(readService.nameForPrincipal(toTestAgent.getLogin().getGuideUser())); Login newLogin = newRandomLogin(); while (loginService.get(toTestAgent.getLogin().getId()).isGuideAble(newLogin)) { newLogin = newRandomLogin(); } page.changeGuideAndFailed(newLogin); page.refresh(); newLogin = newRandomLogin(); while (!loginService.get(toTestAgent.getLogin().getId()).isGuideAble(newLogin)) { newLogin = loginService.byLoginName("master"); } page.changeGuide(newLogin); page.assertGuideName() .isEqualTo(readService.nameForPrincipal(newLogin)); assertThat(loginService.get(toTestAgent.getLogin().getId()).getGuideUser()) .isEqualTo(newLogin); Login newLevel = newRandomAgent(toTestAgent.getSuperior().getSuperior()); page.refresh(); page.assertSuperiorName() .isEqualTo(readService.nameForAgent(toTestAgent.getSuperior())); page.changeSuperior(newLevel); assertThat(agentService.getAgent(toTestAgent.getId()).getSuperior().getLogin()) .isEqualTo(newLevel); } |
ManageTagController { @GetMapping("/manageTag") public String index() { return "_tagManage.html"; } @GetMapping("/manageTag") String index(); @GetMapping("/manageTagAdd") String toAdd(); @GetMapping("/manage/tagDetail") String detail(@RequestParam String name, Model model); @GetMapping("/manage/tagEdit") String edit(@RequestParam String name, Model model); @GetMapping("/manage/tagList") @RowCustom(distinct = true, dramatizer = JQueryDataTableDramatizer.class) RowDefinition data(); @PostMapping("/manage/tagList") @Transactional String add(@RequestParam String name, Integer type
, @RequestParam(required = false, defaultValue = "0") Integer weight, String icon); @PostMapping("/manage/addTag") @ResponseBody String add(String name); @DeleteMapping("/manage/tagList") @ResponseStatus(HttpStatus.NO_CONTENT) void delete(@RequestParam String name); @GetMapping("/manage/tagList/check") @ResponseBody String checkName(@RequestParam String name); @PutMapping("/manage/tagList/disable") @ResponseStatus(HttpStatus.NO_CONTENT) @Transactional void disable(@RequestParam String name); @PutMapping("/manage/tagList/enable") @ResponseStatus(HttpStatus.NO_CONTENT) @Transactional void enable(@RequestParam String name); } | @Test public void index() throws Exception { driver.get("http: assertThat(driver.getTitle()) .isEqualTo("标签管理"); driver.get("http: assertThat(driver.getTitle()) .isEqualTo("新增标签"); } |
ManageTagController { @GetMapping("/manage/tagList") @RowCustom(distinct = true, dramatizer = JQueryDataTableDramatizer.class) public RowDefinition data() { return new TagRows(time -> conversionService.convert(time, String.class)) { @Override public Specification<Tag> specification() { return null; } }; } @GetMapping("/manageTag") String index(); @GetMapping("/manageTagAdd") String toAdd(); @GetMapping("/manage/tagDetail") String detail(@RequestParam String name, Model model); @GetMapping("/manage/tagEdit") String edit(@RequestParam String name, Model model); @GetMapping("/manage/tagList") @RowCustom(distinct = true, dramatizer = JQueryDataTableDramatizer.class) RowDefinition data(); @PostMapping("/manage/tagList") @Transactional String add(@RequestParam String name, Integer type
, @RequestParam(required = false, defaultValue = "0") Integer weight, String icon); @PostMapping("/manage/addTag") @ResponseBody String add(String name); @DeleteMapping("/manage/tagList") @ResponseStatus(HttpStatus.NO_CONTENT) void delete(@RequestParam String name); @GetMapping("/manage/tagList/check") @ResponseBody String checkName(@RequestParam String name); @PutMapping("/manage/tagList/disable") @ResponseStatus(HttpStatus.NO_CONTENT) @Transactional void disable(@RequestParam String name); @PutMapping("/manage/tagList/enable") @ResponseStatus(HttpStatus.NO_CONTENT) @Transactional void enable(@RequestParam String name); } | @Test public void data() throws Exception { toAdd(); mockMvc.perform( get(TAG_LIST_URL) ) .andExpect(status().isOk()) .andDo(print()) .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) .andExpect(similarJQueryDataTable("classpath:/manage-view/mock/tagList.json")); } |
DrillOptiq { public static LogicalExpression toDrill(DrillParseContext context, RelNode input, RexNode expr) { final RexToDrill visitor = new RexToDrill(context, input); return expr.accept(visitor); } static LogicalExpression toDrill(DrillParseContext context, RelNode input, RexNode expr); static boolean isLiteralNull(RexLiteral literal); static final String UNSUPPORTED_REX_NODE_ERROR; } | @Test public void testUnsupportedRexNode() { try { RelDataTypeFactory relFactory = new SqlTypeFactoryImpl(DrillRelDataTypeSystem.DRILL_REL_DATATYPE_SYSTEM); RexBuilder rex = new RexBuilder(relFactory); RelDataType anyType = relFactory.createSqlType(SqlTypeName.ANY); List<RexNode> emptyList = new LinkedList<>(); ImmutableList<RexFieldCollation> e = ImmutableList.copyOf(new RexFieldCollation[0]); RexNode window = rex.makeOver(anyType, SqlStdOperatorTable.AVG, emptyList, emptyList, e, null, null, true, false, false); DrillOptiq.toDrill(null, null, window); } catch (UserException e) { if (e.getMessage().contains(DrillOptiq.UNSUPPORTED_REX_NODE_ERROR)) { return; } Assert.fail("Hit exception with unexpected error message"); } Assert.fail("Failed to raise the expected exception"); } |
MaterializedField { public MaterializedField clone() { return withPathAndType(getPath(), getType()); } private MaterializedField(SchemaPath path, MajorType type); private MaterializedField(SchemaPath path, MajorType type, LinkedHashSet<MaterializedField> children); static MaterializedField create(SerializedField serField); SerializedField getSerializedField(); SerializedField.Builder getAsBuilder(); Collection<MaterializedField> getChildren(); void addChild(MaterializedField field); MaterializedField clone(); MaterializedField withType(MajorType type); MaterializedField withPath(SchemaPath path); MaterializedField withPathAndType(final SchemaPath path, final MajorType type); String getLastName(); boolean matches(SerializedField field); static MaterializedField create(String path, MajorType type); static MaterializedField create(SchemaPath path, MajorType type); SchemaPath getPath(); @Deprecated SchemaPath getAsSchemaPath(); int getWidth(); MajorType getType(); int getScale(); int getPrecision(); boolean isNullable(); DataMode getDataMode(); MaterializedField getOtherNullableVersion(); Class<?> getValueClass(); boolean matches(SchemaPath path); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); Key key(); String toExpr(); } | @Test public void testClone() { final MaterializedField cloneParent = parent.clone(); final boolean isParentEqual = parent.equals(cloneParent); assertTrue("Cloned parent does not match the original", isParentEqual); final MaterializedField cloneChild = child.clone(); final boolean isChildEqual = child.equals(cloneChild); assertTrue("Cloned child does not match the original", isChildEqual); for (final MaterializedField field:new MaterializedField[]{parent, child}) { for (Object[] args:matrix) { final SchemaPath path = SchemaPath.getSimplePath(args[0].toString()); final TypeProtos.MajorType type = TypeProtos.MajorType.class.cast(args[1]); final MaterializedField clone = field.withPathAndType(path, type); final boolean isPathEqual = path.equals(clone.getPath()); assertTrue("Cloned path does not match the original", isPathEqual); final boolean isTypeEqual = type.equals(clone.getType()); assertTrue("Cloned type does not match the original", isTypeEqual); final boolean isChildrenEqual = field.getChildren().equals(clone.getChildren()); assertTrue("Cloned children do not match the original", isChildrenEqual); } } } |
Driver implements java.sql.Driver { @Override public int getMajorVersion() { return impl.getMajorVersion(); } Driver(); static boolean load(); @Override Connection connect( String url, Properties info ); @Override boolean acceptsURL( String url ); @Override DriverPropertyInfo[] getPropertyInfo( String url, Properties info ); @Override int getMajorVersion(); @Override int getMinorVersion(); @Override boolean jdbcCompliant(); @Override java.util.logging.Logger getParentLogger(); } | @Test public void test_getMajorVersion() { assertThat( uut.getMajorVersion(), org.hamcrest.CoreMatchers.is( 0 ) ); } |
Driver implements java.sql.Driver { @Override public int getMinorVersion() { return impl.getMinorVersion(); } Driver(); static boolean load(); @Override Connection connect( String url, Properties info ); @Override boolean acceptsURL( String url ); @Override DriverPropertyInfo[] getPropertyInfo( String url, Properties info ); @Override int getMajorVersion(); @Override int getMinorVersion(); @Override boolean jdbcCompliant(); @Override java.util.logging.Logger getParentLogger(); } | @Test public void test_getMinorVersion() { assertThat( uut.getMinorVersion(), org.hamcrest.core.Is.is( 0 ) ); } |
TypeConvertingSqlAccessor implements SqlAccessor { @Override public byte getByte( int rowOffset ) throws InvalidAccessException { final byte result; switch ( getType().getMinorType() ) { case TINYINT: result = innerAccessor.getByte( rowOffset ); break; case SMALLINT: result = getByteValueOrThrow( innerAccessor.getShort( rowOffset ), "Java short / SQL SMALLINT" ); break; case INT: result = getByteValueOrThrow( innerAccessor.getInt( rowOffset ), "Java int / SQL INTEGER" ); break; case BIGINT: result = getByteValueOrThrow( innerAccessor.getLong( rowOffset ), "Java long / SQL BIGINT" ); break; case FLOAT4: result = getByteValueOrThrow( innerAccessor.getFloat( rowOffset ), "Java float / SQL REAL/FLOAT" ); break; case FLOAT8: result = getByteValueOrThrow( innerAccessor.getDouble( rowOffset ), "Java double / SQL DOUBLE PRECISION" ); break; default: result = innerAccessor.getByte( rowOffset ); break; } return result; } TypeConvertingSqlAccessor( SqlAccessor innerAccessor ); @Override MajorType getType(); @Override Class<?> getObjectClass(); @Override boolean isNull( int rowOffset ); @Override byte getByte( int rowOffset ); @Override short getShort( int rowOffset ); @Override int getInt( int rowOffset ); @Override long getLong( int rowOffset ); @Override float getFloat( int rowOffset ); @Override double getDouble( int rowOffset ); @Override BigDecimal getBigDecimal( int rowOffset ); @Override boolean getBoolean( int rowOffset ); @Override String getString( int rowOffset ); @Override byte[] getBytes( int rowOffset ); @Override Date getDate( int rowOffset ); @Override Time getTime( int rowOffset ); @Override Timestamp getTimestamp( int rowOffset ); @Override Object getObject( int rowOffset ); @Override char getChar( int rowOffset ); @Override InputStream getStream( int rowOffset ); @Override Reader getReader( int rowOffset ); } | @Test public void test_getByte_on_TINYINT_getsIt() throws InvalidAccessException { final SqlAccessor uut1 = new TypeConvertingSqlAccessor( new TinyIntStubAccessor( (byte) 127 ) ); assertThat( uut1.getByte( 0 ), equalTo( (byte) 127 ) ); final SqlAccessor uut2 = new TypeConvertingSqlAccessor( new TinyIntStubAccessor( (byte) -128 ) ); assertThat( uut2.getByte( 0 ), equalTo( (byte) -128 ) ); }
@Test public void test_getByte_on_SMALLINT_thatFits_getsIt() throws InvalidAccessException { final SqlAccessor uut = new TypeConvertingSqlAccessor( new SmallIntStubAccessor( (short) 127 ) ); assertThat( uut.getByte( 0 ), equalTo( (byte) 127 ) ); }
@Test( expected = SQLConversionOverflowException.class ) public void test_getByte_on_SMALLINT_thatOverflows_rejectsIt() throws InvalidAccessException { final SqlAccessor uut = new TypeConvertingSqlAccessor( new SmallIntStubAccessor( (short) 128 ) ); try { uut.getByte( 0 ); } catch ( Throwable e ) { assertThat( e.getMessage(), containsString( "128" ) ); assertThat( e.getMessage(), containsString( "getByte" ) ); assertThat( e.getMessage(), allOf( containsString( "short" ), containsString( "SMALLINT" ) ) ); throw e; } }
@Test public void test_getByte_on_INTEGER_thatFits_getsIt() throws InvalidAccessException { final SqlAccessor uut = new TypeConvertingSqlAccessor( new IntegerStubAccessor( -128 ) ); assertThat( uut.getByte( 0 ), equalTo( (byte) -128 ) ); }
@Test( expected = SQLConversionOverflowException.class ) public void test_getByte_on_INTEGER_thatOverflows_rejectsIt() throws InvalidAccessException { final SqlAccessor uut = new TypeConvertingSqlAccessor( new IntegerStubAccessor( -129 ) ); try { uut.getByte( 0 ); } catch ( Throwable e ) { assertThat( e.getMessage(), containsString( "-129" ) ); assertThat( e.getMessage(), containsString( "getByte" ) ); assertThat( e.getMessage(), allOf( containsString( "int" ), containsString( "INTEGER" ) ) ); throw e; } }
@Test public void test_getByte_on_BIGINT_thatFits_getsIt() throws InvalidAccessException { final SqlAccessor uut = new TypeConvertingSqlAccessor( new BigIntStubAccessor( -128 ) ); assertThat( uut.getByte( 0 ), equalTo( (byte) -128 ) ); }
@Test( expected = SQLConversionOverflowException.class ) public void test_getByte_on_BIGINT_thatOverflows_rejectsIt() throws InvalidAccessException { final SqlAccessor uut = new TypeConvertingSqlAccessor( new BigIntStubAccessor( 129 ) ); try { uut.getByte( 0 ); } catch ( Throwable e ) { assertThat( e.getMessage(), containsString( "129" ) ); assertThat( e.getMessage(), containsString( "getByte" ) ); assertThat( e.getMessage(), allOf( containsString( "long" ), containsString( "BIGINT" ) ) ); throw e; } }
@Test public void test_getByte_on_FLOAT_thatFits_getsIt() throws InvalidAccessException { final SqlAccessor uut = new TypeConvertingSqlAccessor( new FloatStubAccessor( -128.0f ) ); assertThat( uut.getByte( 0 ), equalTo( (byte) -128 ) ); }
@Test( expected = SQLConversionOverflowException.class ) public void test_getByte_on_FLOAT_thatOverflows_rejectsIt() throws InvalidAccessException { final SqlAccessor uut = new TypeConvertingSqlAccessor( new FloatStubAccessor( -130f ) ); try { uut.getByte( 0 ); } catch ( Throwable e ) { assertThat( e.getMessage(), containsString( "-130" ) ); assertThat( e.getMessage(), containsString( "getByte" ) ); assertThat( e.getMessage(), allOf( containsString( "float" ), anyOf( containsString( "REAL" ), containsString( "FLOAT" ) ) ) ); throw e; } }
@Test public void test_getByte_on_DOUBLE_thatFits_getsIt() throws InvalidAccessException { final SqlAccessor uut = new TypeConvertingSqlAccessor( new DoubleStubAccessor( 127.0d ) ); assertThat( uut.getByte( 0 ), equalTo( (byte) 127) ); }
@Test( expected = SQLConversionOverflowException.class ) public void test_getByte_on_DOUBLE_thatOverflows_rejectsIt() throws InvalidAccessException { final SqlAccessor uut = new TypeConvertingSqlAccessor( new DoubleStubAccessor( -130 ) ); try { uut.getByte( 0 ); } catch ( Throwable e ) { assertThat( e.getMessage(), containsString( "-130" ) ); assertThat( e.getMessage(), containsString( "getByte" ) ); assertThat( e.getMessage(), allOf( containsString( "double" ), anyOf( containsString( "DOUBLE PRECISION" ), containsString( "FLOAT(" ) ) ) ); throw e; } } |
TypeConvertingSqlAccessor implements SqlAccessor { @Override public short getShort( int rowOffset ) throws InvalidAccessException { final short result; switch ( getType().getMinorType() ) { case SMALLINT: result = innerAccessor.getShort( rowOffset ); break; case TINYINT: result = innerAccessor.getByte( rowOffset ); break; case INT: result = getShortValueOrThrow( innerAccessor.getInt( rowOffset ), "Java int / SQL INTEGER" ); break; case BIGINT: result = getShortValueOrThrow( innerAccessor.getLong( rowOffset ), "Java long / SQL BIGINT" ); break; case FLOAT4: result = getShortValueOrThrow( innerAccessor.getFloat( rowOffset ), "Java float / SQL REAL/FLOAT" ); break; case FLOAT8: result = getShortValueOrThrow( innerAccessor.getDouble( rowOffset ), "Java double / SQL DOUBLE PRECISION" ); break; default: result = innerAccessor.getByte( rowOffset ); break; } return result; } TypeConvertingSqlAccessor( SqlAccessor innerAccessor ); @Override MajorType getType(); @Override Class<?> getObjectClass(); @Override boolean isNull( int rowOffset ); @Override byte getByte( int rowOffset ); @Override short getShort( int rowOffset ); @Override int getInt( int rowOffset ); @Override long getLong( int rowOffset ); @Override float getFloat( int rowOffset ); @Override double getDouble( int rowOffset ); @Override BigDecimal getBigDecimal( int rowOffset ); @Override boolean getBoolean( int rowOffset ); @Override String getString( int rowOffset ); @Override byte[] getBytes( int rowOffset ); @Override Date getDate( int rowOffset ); @Override Time getTime( int rowOffset ); @Override Timestamp getTimestamp( int rowOffset ); @Override Object getObject( int rowOffset ); @Override char getChar( int rowOffset ); @Override InputStream getStream( int rowOffset ); @Override Reader getReader( int rowOffset ); } | @Test public void test_getShort_on_TINYINT_getsIt() throws InvalidAccessException { final SqlAccessor uut1 = new TypeConvertingSqlAccessor( new TinyIntStubAccessor( (byte) 127 ) ); assertThat( uut1.getShort( 0 ), equalTo( (short) 127 ) ); final SqlAccessor uut2 = new TypeConvertingSqlAccessor( new TinyIntStubAccessor( (byte) -128 ) ); assertThat( uut2.getShort( 0 ), equalTo( (short) -128 ) ); }
@Test public void test_getShort_on_SMALLINT_getsIt() throws InvalidAccessException { final SqlAccessor uut1 = new TypeConvertingSqlAccessor( new SmallIntStubAccessor( (short) 32767 ) ); assertThat( uut1.getShort( 0 ), equalTo( (short) 32767 ) ); final SqlAccessor uut2 = new TypeConvertingSqlAccessor( new SmallIntStubAccessor( (short) -32768 ) ); assertThat( uut2.getShort( 0 ), equalTo( (short) -32768 ) ); }
@Test public void test_getShort_on_INTEGER_thatFits_getsIt() throws InvalidAccessException { final SqlAccessor uut1 = new TypeConvertingSqlAccessor( new IntegerStubAccessor( 32767 ) ); assertThat( uut1.getShort( 0 ), equalTo( (short) 32767 ) ); final SqlAccessor uut2 = new TypeConvertingSqlAccessor( new IntegerStubAccessor( -32768 ) ); assertThat( uut2.getShort( 0 ), equalTo( (short) -32768 ) ); }
@Test( expected = SQLConversionOverflowException.class ) public void test_getShort_on_INTEGER_thatOverflows_throws() throws InvalidAccessException { final SqlAccessor uut = new TypeConvertingSqlAccessor( new IntegerStubAccessor( -32769 ) ); try { uut.getShort( 0 ); } catch ( Throwable e ) { assertThat( e.getMessage(), containsString( "-32769" ) ); assertThat( e.getMessage(), containsString( "getShort" ) ); assertThat( e.getMessage(), allOf( containsString( "int" ), containsString( "INTEGER" ) ) ); throw e; } }
@Test public void test_getShort_BIGINT_thatFits_getsIt() throws InvalidAccessException { final SqlAccessor uut = new TypeConvertingSqlAccessor( new BigIntStubAccessor( -32678 ) ); assertThat( uut.getShort( 0 ), equalTo( (short) -32678 ) ); }
@Test( expected = SQLConversionOverflowException.class ) public void test_getShort_on_BIGINT_thatOverflows_throws() throws InvalidAccessException { final SqlAccessor uut = new TypeConvertingSqlAccessor( new BigIntStubAccessor( 65535 ) ); try { uut.getShort( 0 ); } catch ( Throwable e ) { assertThat( e.getMessage(), containsString( "65535" ) ); assertThat( e.getMessage(), containsString( "getShort" ) ); assertThat( e.getMessage(), allOf( containsString( "long" ), containsString( "BIGINT" ) ) ); throw e; } }
@Test public void test_getShort_on_FLOAT_thatFits_getsIt() throws InvalidAccessException { final SqlAccessor uut = new TypeConvertingSqlAccessor( new FloatStubAccessor( -32768f ) ); assertThat( uut.getShort( 0 ), equalTo( (short) -32768 ) ); }
@Test( expected = SQLConversionOverflowException.class ) public void test_getShort_on_FLOAT_thatOverflows_rejectsIt() throws InvalidAccessException { final SqlAccessor uut = new TypeConvertingSqlAccessor( new FloatStubAccessor( -32769f ) ); try { uut.getShort( 0 ); } catch ( Throwable e ) { assertThat( e.getMessage(), containsString( "-32769" ) ); assertThat( e.getMessage(), containsString( "getShort" ) ); assertThat( e.getMessage(), allOf( containsString( "float" ), anyOf( containsString( "REAL" ), containsString( "FLOAT" ) ) ) ); throw e; } }
@Test public void test_getShort_on_DOUBLE_thatFits_getsIt() throws InvalidAccessException { final SqlAccessor uut = new TypeConvertingSqlAccessor( new DoubleStubAccessor( 32767d ) ); assertThat( uut.getShort( 0 ), equalTo( (short) 32767) ); }
@Test( expected = SQLConversionOverflowException.class ) public void test_getShort_on_DOUBLE_thatOverflows_rejectsIt() throws InvalidAccessException { final SqlAccessor uut = new TypeConvertingSqlAccessor( new DoubleStubAccessor( 32768 ) ); try { uut.getShort( 0 ); } catch ( Throwable e ) { assertThat( e.getMessage(), containsString( "32768" ) ); assertThat( e.getMessage(), containsString( "getShort" ) ); assertThat( e.getMessage(), allOf( containsString( "double" ), anyOf( containsString( "DOUBLE PRECISION" ), containsString( "FLOAT" ) ) ) ); throw e; } } |
TypeConvertingSqlAccessor implements SqlAccessor { @Override public int getInt( int rowOffset ) throws InvalidAccessException { final int result; switch ( getType().getMinorType() ) { case INT: result = innerAccessor.getInt( rowOffset ); break; case TINYINT: result = innerAccessor.getByte( rowOffset ); break; case SMALLINT: result = innerAccessor.getShort( rowOffset ); break; case BIGINT: result = getIntValueOrThrow( innerAccessor.getLong( rowOffset ), "Java long / SQL BIGINT" ); break; case FLOAT4: result = getIntValueOrThrow( innerAccessor.getFloat( rowOffset ), "Java float / SQL REAL/FLOAT" ); break; case FLOAT8: result = getIntValueOrThrow( innerAccessor.getDouble( rowOffset ), "Java double / SQL DOUBLE PRECISION" ); break; default: result = innerAccessor.getInt( rowOffset ); break; } return result; } TypeConvertingSqlAccessor( SqlAccessor innerAccessor ); @Override MajorType getType(); @Override Class<?> getObjectClass(); @Override boolean isNull( int rowOffset ); @Override byte getByte( int rowOffset ); @Override short getShort( int rowOffset ); @Override int getInt( int rowOffset ); @Override long getLong( int rowOffset ); @Override float getFloat( int rowOffset ); @Override double getDouble( int rowOffset ); @Override BigDecimal getBigDecimal( int rowOffset ); @Override boolean getBoolean( int rowOffset ); @Override String getString( int rowOffset ); @Override byte[] getBytes( int rowOffset ); @Override Date getDate( int rowOffset ); @Override Time getTime( int rowOffset ); @Override Timestamp getTimestamp( int rowOffset ); @Override Object getObject( int rowOffset ); @Override char getChar( int rowOffset ); @Override InputStream getStream( int rowOffset ); @Override Reader getReader( int rowOffset ); } | @Test public void test_getInt_on_TINYINT_getsIt() throws InvalidAccessException { final SqlAccessor uut1 = new TypeConvertingSqlAccessor( new TinyIntStubAccessor( (byte) 127 ) ); assertThat( uut1.getInt( 0 ), equalTo( 127 ) ); final SqlAccessor uut2 = new TypeConvertingSqlAccessor( new TinyIntStubAccessor( (byte) -128 ) ); assertThat( uut2.getInt( 0 ), equalTo( -128 ) ); }
@Test public void test_getInt_on_SMALLINT_getsIt() throws InvalidAccessException { final SqlAccessor uut1 = new TypeConvertingSqlAccessor( new SmallIntStubAccessor( (short) 32767 ) ); assertThat( uut1.getInt( 0 ), equalTo( 32767 ) ); final SqlAccessor uut2 = new TypeConvertingSqlAccessor( new SmallIntStubAccessor( (short) -32768 ) ); assertThat( uut2.getInt( 0 ), equalTo( -32768 ) ); }
@Test public void test_getInt_on_INTEGER_getsIt() throws InvalidAccessException { final SqlAccessor uut1 = new TypeConvertingSqlAccessor( new IntegerStubAccessor( 2147483647 ) ); assertThat( uut1.getInt( 0 ), equalTo( 2147483647 ) ); final SqlAccessor uut2 = new TypeConvertingSqlAccessor( new IntegerStubAccessor( -2147483648 ) ); assertThat( uut2.getInt( 0 ), equalTo( -2147483648 ) ); }
@Test public void test_getInt_on_BIGINT_thatFits_getsIt() throws InvalidAccessException { final SqlAccessor uut = new TypeConvertingSqlAccessor( new BigIntStubAccessor( 2147483647 ) ); assertThat( uut.getInt( 0 ), equalTo( 2147483647 ) ); }
@Test( expected = SQLConversionOverflowException.class ) public void test_getInt_on_BIGINT_thatOverflows_throws() throws InvalidAccessException { final SqlAccessor uut = new TypeConvertingSqlAccessor( new BigIntStubAccessor( 2147483648L ) ); try { uut.getInt( 0 ); } catch ( Throwable e ) { assertThat( e.getMessage(), containsString( "2147483648" ) ); assertThat( e.getMessage(), containsString( "getInt" ) ); assertThat( e.getMessage(), allOf( containsString( "long" ), containsString( "BIGINT" ) ) ); throw e; } }
@Test public void test_getInt_on_FLOAT_thatFits_getsIt() throws InvalidAccessException { final SqlAccessor uut = new TypeConvertingSqlAccessor( new FloatStubAccessor( 1e9f ) ); assertThat( uut.getInt( 0 ), equalTo( 1_000_000_000 ) ); }
@Test( expected = SQLConversionOverflowException.class ) public void test_getInt_on_FLOAT_thatOverflows_rejectsIt() throws InvalidAccessException { final SqlAccessor uut = new TypeConvertingSqlAccessor( new FloatStubAccessor( 1e10f ) ); try { uut.getInt( 0 ); } catch ( Throwable e ) { assertThat( e.getMessage(), containsString( "1.0E10" ) ); assertThat( e.getMessage(), containsString( "getInt" ) ); assertThat( e.getMessage(), allOf( containsString( "float" ), anyOf( containsString( "REAL" ), containsString( "FLOAT" ) ) ) ); throw e; } }
@Test public void test_getInt_on_DOUBLE_thatFits_getsIt() throws InvalidAccessException { final SqlAccessor uut = new TypeConvertingSqlAccessor( new DoubleStubAccessor( -2147483648.0d ) ); assertThat( uut.getInt( 0 ), equalTo( -2147483648 ) ); }
@Test( expected = SQLConversionOverflowException.class ) public void test_getInt_on_DOUBLE_thatOverflows_rejectsIt() throws InvalidAccessException { final SqlAccessor uut = new TypeConvertingSqlAccessor( new DoubleStubAccessor( -2147483649.0d ) ); try { uut.getInt( 0 ); } catch ( Throwable e ) { assertThat( e.getMessage(), containsString( "-2.147483649E9" ) ); assertThat( e.getMessage(), containsString( "getInt" ) ); assertThat( e.getMessage(), allOf( containsString( "double" ), containsString( "DOUBLE PRECISION" ) ) ); throw e; } } |
TypeConvertingSqlAccessor implements SqlAccessor { @Override public long getLong( int rowOffset ) throws InvalidAccessException { final long result; switch ( getType().getMinorType() ) { case BIGINT: result = innerAccessor.getLong( rowOffset ); break; case TINYINT: result = innerAccessor.getByte( rowOffset ); break; case SMALLINT: result = innerAccessor.getShort( rowOffset ); break; case INT: result = innerAccessor.getInt( rowOffset ); break; case FLOAT4: result = getLongValueOrThrow( innerAccessor.getFloat( rowOffset ), "Java float / SQL REAL/FLOAT" ); break; case FLOAT8: result = getLongValueOrThrow( innerAccessor.getDouble( rowOffset ), "Java double / SQL DOUBLE PRECISION" ); break; default: result = innerAccessor.getLong( rowOffset ); break; } return result; } TypeConvertingSqlAccessor( SqlAccessor innerAccessor ); @Override MajorType getType(); @Override Class<?> getObjectClass(); @Override boolean isNull( int rowOffset ); @Override byte getByte( int rowOffset ); @Override short getShort( int rowOffset ); @Override int getInt( int rowOffset ); @Override long getLong( int rowOffset ); @Override float getFloat( int rowOffset ); @Override double getDouble( int rowOffset ); @Override BigDecimal getBigDecimal( int rowOffset ); @Override boolean getBoolean( int rowOffset ); @Override String getString( int rowOffset ); @Override byte[] getBytes( int rowOffset ); @Override Date getDate( int rowOffset ); @Override Time getTime( int rowOffset ); @Override Timestamp getTimestamp( int rowOffset ); @Override Object getObject( int rowOffset ); @Override char getChar( int rowOffset ); @Override InputStream getStream( int rowOffset ); @Override Reader getReader( int rowOffset ); } | @Test public void test_getLong_on_TINYINT_getsIt() throws InvalidAccessException { final SqlAccessor uut1 = new TypeConvertingSqlAccessor( new TinyIntStubAccessor( (byte) 127 ) ); assertThat( uut1.getLong( 0 ), equalTo( 127L ) ); final SqlAccessor uut2 = new TypeConvertingSqlAccessor( new TinyIntStubAccessor( (byte) -128 ) ); assertThat( uut2.getLong( 0 ), equalTo( -128L ) ); }
@Test public void test_getLong_on_SMALLINT_getsIt() throws InvalidAccessException { final SqlAccessor uut1 = new TypeConvertingSqlAccessor( new SmallIntStubAccessor( (short) 32767 ) ); assertThat( uut1.getLong( 0 ), equalTo( 32767L ) ); final SqlAccessor uut2 = new TypeConvertingSqlAccessor( new SmallIntStubAccessor( (short) -32768 ) ); assertThat( uut2.getLong( 0 ), equalTo( -32768L ) ); }
@Test public void test_getLong_on_INTEGER_getsIt() throws InvalidAccessException { final SqlAccessor uut1 = new TypeConvertingSqlAccessor( new IntegerStubAccessor( 2147483647 ) ); assertThat( uut1.getLong( 0 ), equalTo( 2147483647L ) ); final SqlAccessor uut2 = new TypeConvertingSqlAccessor( new IntegerStubAccessor( -2147483648 ) ); assertThat( uut2.getLong( 0 ), equalTo( -2147483648L ) ); }
@Test public void test_getLong_on_BIGINT_getsIt() throws InvalidAccessException { final SqlAccessor uut = new TypeConvertingSqlAccessor( new BigIntStubAccessor( 2147483648L ) ); assertThat( uut.getLong( 0 ), equalTo( 2147483648L ) ); }
@Test public void test_getLong_on_FLOAT_thatFits_getsIt() throws InvalidAccessException { final SqlAccessor uut = new TypeConvertingSqlAccessor( new FloatStubAccessor( 9223372036854775807L * 1.0f ) ); assertThat( uut.getLong( 0 ), equalTo( 9223372036854775807L ) ); }
@Test( expected = SQLConversionOverflowException.class ) public void test_getLong_on_FLOAT_thatOverflows_rejectsIt() throws InvalidAccessException { final SqlAccessor uut = new TypeConvertingSqlAccessor( new FloatStubAccessor( 1.5e20f ) ); try { uut.getLong( 0 ); } catch ( Throwable e ) { assertThat( e.getMessage(), containsString( "1.5000" ) ); assertThat( e.getMessage(), containsString( "getLong" ) ); assertThat( e.getMessage(), allOf( containsString( "float" ), anyOf( containsString( "REAL" ), containsString( "FLOAT" ) ) ) ); throw e; } }
@Test public void test_getLong_on_DOUBLE_thatFits_getsIt() throws InvalidAccessException { final SqlAccessor uut = new TypeConvertingSqlAccessor( new DoubleStubAccessor( 9223372036854775807L * 1.0d ) ); assertThat( uut.getLong( 0 ), equalTo( 9223372036854775807L ) ); }
@Test( expected = SQLConversionOverflowException.class ) public void test_getLong_on_DOUBLE_thatOverflows_rejectsIt() throws InvalidAccessException { final SqlAccessor uut = new TypeConvertingSqlAccessor( new DoubleStubAccessor( 1e20 ) ); try { uut.getLong( 0 ); } catch ( Throwable e ) { assertThat( e.getMessage(), containsString( "1.0E20" ) ); assertThat( e.getMessage(), containsString( "getLong" ) ); assertThat( e.getMessage(), allOf( containsString( "double" ), containsString( "DOUBLE PRECISION" ) ) ); throw e; } } |
TypeConvertingSqlAccessor implements SqlAccessor { @Override public float getFloat( int rowOffset ) throws InvalidAccessException { final float result; switch ( getType().getMinorType() ) { case FLOAT4: result = innerAccessor.getFloat( rowOffset ); break; case INT: result = innerAccessor.getInt( rowOffset ); break; case BIGINT: result = innerAccessor.getLong( rowOffset ); break; case FLOAT8: final double value = innerAccessor.getDouble( rowOffset ); if ( Float.MIN_VALUE <= value && value <= Float.MAX_VALUE ) { result = (float) value; } else { throw newOverflowException( "getFloat(...)", "Java double / SQL DOUBLE PRECISION", value ); } break; default: result = innerAccessor.getInt( rowOffset ); break; } return result; } TypeConvertingSqlAccessor( SqlAccessor innerAccessor ); @Override MajorType getType(); @Override Class<?> getObjectClass(); @Override boolean isNull( int rowOffset ); @Override byte getByte( int rowOffset ); @Override short getShort( int rowOffset ); @Override int getInt( int rowOffset ); @Override long getLong( int rowOffset ); @Override float getFloat( int rowOffset ); @Override double getDouble( int rowOffset ); @Override BigDecimal getBigDecimal( int rowOffset ); @Override boolean getBoolean( int rowOffset ); @Override String getString( int rowOffset ); @Override byte[] getBytes( int rowOffset ); @Override Date getDate( int rowOffset ); @Override Time getTime( int rowOffset ); @Override Timestamp getTimestamp( int rowOffset ); @Override Object getObject( int rowOffset ); @Override char getChar( int rowOffset ); @Override InputStream getStream( int rowOffset ); @Override Reader getReader( int rowOffset ); } | @Test public void test_getFloat_on_FLOAT_getsIt() throws InvalidAccessException { final SqlAccessor uut1 = new TypeConvertingSqlAccessor( new FloatStubAccessor( 1.23f ) ); assertThat( uut1.getFloat( 0 ), equalTo( 1.23f ) ); final SqlAccessor uut2 = new TypeConvertingSqlAccessor( new FloatStubAccessor( Float.MAX_VALUE ) ); assertThat( uut2.getFloat( 0 ), equalTo( Float.MAX_VALUE ) ); final SqlAccessor uut3 = new TypeConvertingSqlAccessor( new FloatStubAccessor( Float.MIN_VALUE ) ); assertThat( uut3.getFloat( 0 ), equalTo( Float.MIN_VALUE ) ); }
@Test public void test_getFloat_on_DOUBLE_thatFits_getsIt() throws InvalidAccessException { final SqlAccessor uut1 = new TypeConvertingSqlAccessor( new DoubleStubAccessor( 1.125 ) ); assertThat( uut1.getFloat( 0 ), equalTo( 1.125f ) ); final SqlAccessor uut2 = new TypeConvertingSqlAccessor( new DoubleStubAccessor( Float.MAX_VALUE ) ); assertThat( uut2.getFloat( 0 ), equalTo( Float.MAX_VALUE ) ); }
@Test( expected = SQLConversionOverflowException.class ) public void test_getFloat_on_DOUBLE_thatOverflows_throws() throws InvalidAccessException { final SqlAccessor uut = new TypeConvertingSqlAccessor( new DoubleStubAccessor( 1e100 ) ); try { uut.getFloat( 0 ); } catch ( Throwable e ) { assertThat( e.getMessage(), containsString( "1.0E100" ) ); assertThat( e.getMessage(), containsString( "getFloat" ) ); assertThat( e.getMessage(), allOf( containsString( "double" ), anyOf ( containsString( "DOUBLE PRECISION" ), containsString( "FLOAT" ) ) ) ); throw e; } } |
TypeConvertingSqlAccessor implements SqlAccessor { @Override public double getDouble( int rowOffset ) throws InvalidAccessException { final double result; switch ( getType().getMinorType() ) { case FLOAT8: result = innerAccessor.getDouble( rowOffset ); break; case INT: result = innerAccessor.getInt( rowOffset ); break; case BIGINT: result = innerAccessor.getLong( rowOffset ); break; case FLOAT4: result = innerAccessor.getFloat( rowOffset ); break; default: result = innerAccessor.getLong( rowOffset ); } return result; } TypeConvertingSqlAccessor( SqlAccessor innerAccessor ); @Override MajorType getType(); @Override Class<?> getObjectClass(); @Override boolean isNull( int rowOffset ); @Override byte getByte( int rowOffset ); @Override short getShort( int rowOffset ); @Override int getInt( int rowOffset ); @Override long getLong( int rowOffset ); @Override float getFloat( int rowOffset ); @Override double getDouble( int rowOffset ); @Override BigDecimal getBigDecimal( int rowOffset ); @Override boolean getBoolean( int rowOffset ); @Override String getString( int rowOffset ); @Override byte[] getBytes( int rowOffset ); @Override Date getDate( int rowOffset ); @Override Time getTime( int rowOffset ); @Override Timestamp getTimestamp( int rowOffset ); @Override Object getObject( int rowOffset ); @Override char getChar( int rowOffset ); @Override InputStream getStream( int rowOffset ); @Override Reader getReader( int rowOffset ); } | @Test public void test_getDouble_on_FLOAT_getsIt() throws InvalidAccessException { final SqlAccessor uut1 = new TypeConvertingSqlAccessor( new FloatStubAccessor( 6.02e23f ) ); assertThat( uut1.getDouble( 0 ), equalTo( (double) 6.02e23f ) ); final SqlAccessor uut2 = new TypeConvertingSqlAccessor( new FloatStubAccessor( Float.MAX_VALUE ) ); assertThat( uut2.getDouble( 0 ), equalTo( (double) Float.MAX_VALUE ) ); final SqlAccessor uut3 = new TypeConvertingSqlAccessor( new FloatStubAccessor( Float.MIN_VALUE ) ); assertThat( uut3.getDouble( 0 ), equalTo( (double) Float.MIN_VALUE ) ); }
@Test public void test_getDouble_on_DOUBLE_getsIt() throws InvalidAccessException { final SqlAccessor uut1 = new TypeConvertingSqlAccessor( new DoubleStubAccessor( -1e100 ) ); assertThat( uut1.getDouble( 0 ), equalTo( -1e100 ) ); final SqlAccessor uut2 = new TypeConvertingSqlAccessor( new DoubleStubAccessor( Double.MAX_VALUE ) ); assertThat( uut2.getDouble( 0 ), equalTo( Double.MAX_VALUE ) ); final SqlAccessor uut3 = new TypeConvertingSqlAccessor( new DoubleStubAccessor( Double.MIN_VALUE ) ); assertThat( uut3.getDouble( 0 ), equalTo( Double.MIN_VALUE ) ); } |
ModelExtractor { public byte[] getModel(String modelUri) { return getModel(new DefaultResourceLoader().getResource(modelUri)); } ModelExtractor(); ModelExtractor(String frozenGraphFileExtension); byte[] getModel(String modelUri); byte[] getModel(Resource modelResource); final String frozenGraphFileExtension; } | @Test public void testResourceAndStringArguments() { Resource modelResource = new DefaultResourceLoader().getResource("classpath:/tensorflow/model/linear_regression_graph.proto"); byte[] model1 = new ModelExtractor().getModel(modelResource); assertThat(model1.length, is(422)); byte[] model2 = new ModelExtractor().getModel("classpath:/tensorflow/model/linear_regression_graph.proto"); assertThat(model2.length, is(422)); assertThat(model1, equalTo(model2)); }
@Test(expected = IllegalStateException.class) public void zipArchiveWithDefaultExtensionClasspath() { byte[] model = new ModelExtractor().getModel("classpath:/tensorflow/model.zip"); assertThat(model.length, is(422)); }
@Test public void zipArchiveWithCustomExtensionClasspath() { byte[] model = new ModelExtractor(".proto").getModel("classpath:/tensorflow/model.zip"); assertThat(model.length, is(422)); }
@Test public void zipArchiveWithFragmentFile() { byte[] model = new ModelExtractor().getModel("file:src/test/resources/tensorflow/model.zip#linear_regression_graph.proto"); assertThat(model.length, is(422)); }
@Test public void tarGzipArchiveWithFragmentFile() { byte[] model = new ModelExtractor().getModel("file:src/test/resources/tensorflow/model.tar.gz#linear_regression_graph.proto"); assertThat(model.length, is(422)); }
@Test public void tarGzipArchiveWithCustomExtensionFile() { byte[] model = new ModelExtractor(".proto").getModel("file:src/test/resources/tensorflow/model.tar.gz"); assertThat(model.length, is(422)); }
@Test public void tarGzipArchiveWithFragmentHttp() { byte[] model = new ModelExtractor() .getModel("https: assertThat(model.length, is(8773281)); }
@Test public void tarGzipArchiveWithDefaultExtensionHttp() { byte[] model = new ModelExtractor() .getModel("https: assertThat(model.length, is(8773281)); } |
PropertyUtils { public static <T> T get(String key, Function<String, T> parser, T defaultValue) { return get(System.getProperties(), key, parser, defaultValue); } private PropertyUtils(); static T get(String key, Function<String, T> parser, T defaultValue); static T get(Properties props, String key, Function<String, T> parser, T defaultValue); static T getOrSet(Properties props, String key, Function<String, T> parser, T defaultValue); static Properties load(String resourceFile); static Properties load(String resourceFile, Properties defaultProps); static Properties filter(String keyPrefix, Properties props); } | @Test public void testSystemGet() { assertEquals("bar", PropertyUtils.get("_foo", String::valueOf, "bar")); }
@Test public void testExistingValue() { final Properties props = new Properties(); props.put("foo", "bar"); assertEquals("bar", PropertyUtils.get(props, "foo", String::valueOf, "baz")); }
@Test public void testDefaultValue() { assertEquals("bar", PropertyUtils.get(new Properties(), "foo", String::valueOf, "bar")); } |
PropertyUtils { public static Properties filter(String keyPrefix, Properties props) { final Properties filtered = new Properties(); final Enumeration<?> keys = props.propertyNames(); while (keys.hasMoreElements()) { final String key = (String) keys.nextElement(); final String value = props.getProperty(key); if (value != null && key.startsWith(keyPrefix)) { filtered.setProperty(key, value); } } return filtered; } private PropertyUtils(); static T get(String key, Function<String, T> parser, T defaultValue); static T get(Properties props, String key, Function<String, T> parser, T defaultValue); static T getOrSet(Properties props, String key, Function<String, T> parser, T defaultValue); static Properties load(String resourceFile); static Properties load(String resourceFile, Properties defaultProps); static Properties filter(String keyPrefix, Properties props); } | @Test public void testFilterWithDefaults() { final Properties props = new Properties(); props.put("a.foo", "foo"); props.put("a.bar", "bar"); props.put("b.foo", "bar"); final Properties filtered = PropertyUtils.filter("a.", new Properties(props)); assertEquals(2, filtered.size()); assertTrue(filtered.containsKey("a.foo")); assertTrue(filtered.containsKey("a.bar")); assertFalse(filtered.containsKey("b.foo")); }
@Test public void testFilterWithDefaultsNonStrings() { final Properties props = new Properties(); props.put("a.foo", "foo"); props.put("a.bar", false); props.put("b.foo", "bar"); final Properties filtered = PropertyUtils.filter("a.", new Properties(props)); assertEquals(1, filtered.size()); assertTrue(filtered.containsKey("a.foo")); assertFalse(filtered.containsKey("a.bar")); assertFalse(filtered.containsKey("b.foo")); }
@Test public void testFilter() { final Properties props = new Properties(); props.put("a.foo", "foo"); props.put("a.bar", "bar"); props.put("b.foo", "bar"); final Properties filtered = PropertyUtils.filter("a.", props); assertEquals(2, filtered.size()); assertTrue(filtered.containsKey("a.foo")); assertTrue(filtered.containsKey("a.bar")); assertFalse(filtered.containsKey("b.foo")); } |
StochasticOscillator implements Indicator { private static <T> void add(List<T> list, T value, int cap) { list.add(value); while (list.size() > cap) list.remove(0); } StochasticOscillator(int lookback, int kPeriod); @Override StochasticOutput add(Bar bar); } | @Test public void test() { final StochasticOscillator fast = new StochasticOscillator(14, 3); assertNull(fast.add(bar(127.0090f, 125.3574f, 127.0090f))); assertNull(fast.add(bar(127.6159f, 126.1633f, 127.6159f))); assertNull(fast.add(bar(126.5911f, 124.9296f, 126.5911f))); assertNull(fast.add(bar(127.3472f, 126.0937f, 127.3472f))); assertNull(fast.add(bar(128.1730f, 126.8199f, 128.1730f))); assertNull(fast.add(bar(128.4317f, 126.4817f, 128.4317f))); assertNull(fast.add(bar(127.3671f, 126.0340f, 127.3671f))); assertNull(fast.add(bar(126.4220f, 124.8301f, 126.4220f))); assertNull(fast.add(bar(126.8995f, 126.3921f, 126.8995f))); assertNull(fast.add(bar(126.8498f, 125.7156f, 126.8498f))); assertNull(fast.add(bar(125.6460f, 124.5615f, 125.6460f))); assertNull(fast.add(bar(125.7156f, 124.5715f, 125.7156f))); assertNull(fast.add(bar(127.1582f, 125.0689f, 127.1582f))); assertNull(fast.add(bar(127.7154f, 126.8597f, 127.2876f))); assertNull(fast.add(bar(127.6855f, 126.6309f, 127.1781f))); final StochasticOutput o1 = fast.add(bar(128.2228f, 126.8001f, 128.0138f)); assertEquals(89.2021f, o1.getK(), DELTA); assertEquals(75.7497f, o1.getD(), DELTA); final StochasticOutput o2 = fast.add(bar(128.2725f, 126.7105f, 127.1085f)); assertEquals(65.8106f, o2.getK(), DELTA); assertEquals(74.2072f, o2.getD(), DELTA); } |
PropertyUtils { public static <T> T getOrSet(Properties props, String key, Function<String, T> parser, T defaultValue) { final String str = props.getProperty(key); if (str == null) { props.setProperty(key, String.valueOf(defaultValue)); return defaultValue; } else { return parser.apply(str); } } private PropertyUtils(); static T get(String key, Function<String, T> parser, T defaultValue); static T get(Properties props, String key, Function<String, T> parser, T defaultValue); static T getOrSet(Properties props, String key, Function<String, T> parser, T defaultValue); static Properties load(String resourceFile); static Properties load(String resourceFile, Properties defaultProps); static Properties filter(String keyPrefix, Properties props); } | @Test public void testGetOrSetExisting() { final Properties props = new Properties(); props.put("foo", "bar"); assertEquals("bar", PropertyUtils.getOrSet(props, "foo", String::valueOf, "baz")); assertEquals("bar", props.getProperty("foo")); }
@Test public void testGetOrSetDefault() { final Properties props = new Properties(); assertEquals("baz", PropertyUtils.getOrSet(props, "foo", String::valueOf, "baz")); assertEquals("baz", props.getProperty("foo")); } |
PropertyUtils { public static Properties load(String resourceFile) throws IOException { final URL url = PropertyUtils.class.getClassLoader().getResource(resourceFile); if (url == null) throw new FileNotFoundException("Resource not found"); final Properties props = new Properties(); try (InputStream in = url.openStream()) { props.load(in); } return props; } private PropertyUtils(); static T get(String key, Function<String, T> parser, T defaultValue); static T get(Properties props, String key, Function<String, T> parser, T defaultValue); static T getOrSet(Properties props, String key, Function<String, T> parser, T defaultValue); static Properties load(String resourceFile); static Properties load(String resourceFile, Properties defaultProps); static Properties filter(String keyPrefix, Properties props); } | @Test public void testLoadExisting() throws IOException { final Properties props = PropertyUtils.load("property-utils-test.properties"); assertTrue(props.containsKey("foo")); }
@Test public void testLoadExistingDefault() throws IOException { final Properties props = PropertyUtils.load("property-utils-test.properties", null); assertNotNull(props); assertTrue(props.containsKey("foo")); }
@Test(expected=FileNotFoundException.class) public void testLoadNonExisting() throws IOException { PropertyUtils.load("non-existing.properties"); }
@Test public void testLoadNonExistingDefault() throws IOException { final Properties def = new Properties(); def.put("foo", "bar"); final Properties props = PropertyUtils.load("non-existing.properties", def); assertTrue(props.containsKey("foo")); } |
MidaoFactory { public static QueryRunnerService getQueryRunner(DataSource ds) { return (QueryRunnerService) ProfilerFactory.newInstance(new QueryRunner(ds)); } static QueryRunnerService getQueryRunner(DataSource ds); static QueryRunnerService getQueryRunner(DataSource ds, Class<? extends TypeHandler> typeHandlerClazz); static QueryRunnerService getQueryRunner(DataSource ds, Class<? extends TypeHandler> typeHandlerClazz, Class<? extends StatementHandler> statementHandlerClazz); static QueryRunnerService getQueryRunner(Connection conn); static QueryRunnerService getQueryRunner(Connection conn, Class<? extends TypeHandler> typeHandlerClazz); static QueryRunnerService getQueryRunner(Connection conn, Class<? extends TypeHandler> typeHandlerClazz, Class<? extends StatementHandler> statementHandlerClazz); static AsyncQueryRunnerService getAsyncQueryRunner(QueryRunner runner, ExecutorService executorService); static DataSource createDataSource(Properties poolProperties); static DataSource createDataSource(String url); static DataSource createDataSource(String url, String userName, String password); static DataSource createDataSource(String driverClassName, String url, String userName, String password); static DataSource createDataSource(String driverClassName, String url, String userName, String password, int initialSize, int maxActive); } | @Test public void testGetQueryRunnerDataSource() throws Exception { Assert.assertEquals(true, MidaoFactory.getQueryRunner(ds) instanceof QueryRunner); }
@Test public void testGetQueryRunnerDataSourceTypeHandler() throws Exception { Assert.assertEquals(true, MidaoFactory.getQueryRunner(ds, EmptyTypeHandler.class) instanceof QueryRunner); }
@Test public void testGetQueryRunnerDataSourceTypeStatementHandler() throws Exception { Assert.assertEquals(true, MidaoFactory.getQueryRunner(ds, EmptyTypeHandler.class, BaseStatementHandler.class) instanceof QueryRunner); }
@Test public void testGetQueryRunnerCoonection() throws Exception { Assert.assertEquals(true, MidaoFactory.getQueryRunner(conn) instanceof QueryRunner); }
@Test public void testGetQueryRunnerConnectionTypeHandler() throws Exception { Assert.assertEquals(true, MidaoFactory.getQueryRunner(conn, EmptyTypeHandler.class) instanceof QueryRunner); }
@Test public void testGetQueryRunnerConnectionTypeStatementHandler() throws Exception { Assert.assertEquals(true, MidaoFactory.getQueryRunner(conn, EmptyTypeHandler.class, BaseStatementHandler.class) instanceof QueryRunner); } |
QueryParameters { public Object getValueByPosition(Integer position) throws NoSuchFieldException { String name = null; Object value = null; name = this.getNameByPosition(position); if (name != null) { value = this.getValue(name); } else { throw new NoSuchFieldException(); } return value; } QueryParameters(); QueryParameters(Map<String, Object> map); QueryParameters(Class<?> clazz, Object bean); QueryParameters(QueryParameters parameters); QueryParameters(ProcessedInput processedInput); QueryParameters(Object... params); void importValues(Map<String, Object> map); QueryParameters set(String key, Object value, Integer type, Direction direction, Integer position); QueryParameters set(String key, Object value, Integer type, Direction direction); QueryParameters set(String key, Object value, Direction direction); QueryParameters set(String key, Object value, Integer type); QueryParameters set(String key, Object value); QueryParameters setClassName(String className); QueryParameters updateType(String key, Integer type); QueryParameters updateDirection(String key, Direction direction); QueryParameters updatePosition(String key, Integer position); QueryParameters updateValue(String key, Object value); Integer getFirstPosition(String key); List<Integer> getOrderList(String key); boolean usedOnce(String key); Direction getDirection(String key); Integer getType(String key); Object getValue(String key); Map<String, Object> toMap(); Set<String> keySet(); boolean isOutParameter(String key); boolean isInParameter(String key); String getNameByPosition(Integer position); Object getValueByPosition(Integer position); boolean containsKey(String key); void remove(String key); void clearOrder(); int size(); int orderSize(); void setCaseSensitive(boolean newValue); boolean isCaseSensitive(); void setReturn(Object queryOutput); Object getReturn(); void removeReturn(); void update(Object[] newValues, boolean updateOutOnly); void updateAndClean(ProcessedInput processedInput); Object[] getValuesArray(); boolean isOrderSet(); void assertIncorrectOrder(); @Override String toString(); } | @Test public void testConstructorArray() throws NoSuchFieldException { QueryParameters params = new QueryParameters(superman.getName(), superman.getOrigin(), superman.getStrength()); Assert.assertEquals(superman.getName(), params.getValueByPosition(0)); Assert.assertEquals(superman.getOrigin(), params.getValueByPosition(1)); Assert.assertEquals(superman.getStrength(), params.getValueByPosition(2)); }
@Test public void testGetValueByPosition() throws Exception { QueryParameters params = new QueryParameters(superman.getClass(), superman); if (JAVA_VERSION == 1.8) { Assert.assertEquals("superman", params.getValueByPosition(2)); } else { Assert.assertEquals("superman", params.getValueByPosition(1)); } } |
QueryParameters { public void importValues(Map<String, Object> map) { for (String key : map.keySet()) { this.set(key, map.get(key)); } } QueryParameters(); QueryParameters(Map<String, Object> map); QueryParameters(Class<?> clazz, Object bean); QueryParameters(QueryParameters parameters); QueryParameters(ProcessedInput processedInput); QueryParameters(Object... params); void importValues(Map<String, Object> map); QueryParameters set(String key, Object value, Integer type, Direction direction, Integer position); QueryParameters set(String key, Object value, Integer type, Direction direction); QueryParameters set(String key, Object value, Direction direction); QueryParameters set(String key, Object value, Integer type); QueryParameters set(String key, Object value); QueryParameters setClassName(String className); QueryParameters updateType(String key, Integer type); QueryParameters updateDirection(String key, Direction direction); QueryParameters updatePosition(String key, Integer position); QueryParameters updateValue(String key, Object value); Integer getFirstPosition(String key); List<Integer> getOrderList(String key); boolean usedOnce(String key); Direction getDirection(String key); Integer getType(String key); Object getValue(String key); Map<String, Object> toMap(); Set<String> keySet(); boolean isOutParameter(String key); boolean isInParameter(String key); String getNameByPosition(Integer position); Object getValueByPosition(Integer position); boolean containsKey(String key); void remove(String key); void clearOrder(); int size(); int orderSize(); void setCaseSensitive(boolean newValue); boolean isCaseSensitive(); void setReturn(Object queryOutput); Object getReturn(); void removeReturn(); void update(Object[] newValues, boolean updateOutOnly); void updateAndClean(ProcessedInput processedInput); Object[] getValuesArray(); boolean isOrderSet(); void assertIncorrectOrder(); @Override String toString(); } | @Test public void testImportValues() throws Exception { QueryParameters params = new QueryParameters(); params.importValues(superMap); Assert.assertEquals(superMap.get("name"), params.getValue("name")); Assert.assertEquals(superMap.get("origin"), params.getValue("origin")); Assert.assertEquals(superMap.get("strength"), params.getValue("strength")); } |
QueryParameters { public QueryParameters setClassName(String className) { InputUtils.setClassName(this.values, className); return this; } QueryParameters(); QueryParameters(Map<String, Object> map); QueryParameters(Class<?> clazz, Object bean); QueryParameters(QueryParameters parameters); QueryParameters(ProcessedInput processedInput); QueryParameters(Object... params); void importValues(Map<String, Object> map); QueryParameters set(String key, Object value, Integer type, Direction direction, Integer position); QueryParameters set(String key, Object value, Integer type, Direction direction); QueryParameters set(String key, Object value, Direction direction); QueryParameters set(String key, Object value, Integer type); QueryParameters set(String key, Object value); QueryParameters setClassName(String className); QueryParameters updateType(String key, Integer type); QueryParameters updateDirection(String key, Direction direction); QueryParameters updatePosition(String key, Integer position); QueryParameters updateValue(String key, Object value); Integer getFirstPosition(String key); List<Integer> getOrderList(String key); boolean usedOnce(String key); Direction getDirection(String key); Integer getType(String key); Object getValue(String key); Map<String, Object> toMap(); Set<String> keySet(); boolean isOutParameter(String key); boolean isInParameter(String key); String getNameByPosition(Integer position); Object getValueByPosition(Integer position); boolean containsKey(String key); void remove(String key); void clearOrder(); int size(); int orderSize(); void setCaseSensitive(boolean newValue); boolean isCaseSensitive(); void setReturn(Object queryOutput); Object getReturn(); void removeReturn(); void update(Object[] newValues, boolean updateOutOnly); void updateAndClean(ProcessedInput processedInput); Object[] getValuesArray(); boolean isOrderSet(); void assertIncorrectOrder(); @Override String toString(); } | @Test public void testSetClassName() throws Exception { String className = "Superman"; QueryParameters params = new QueryParameters(superman); params.setClassName(className); Assert.assertEquals(className, InputUtils.getClassName(params.toMap())); } |
QueryParameters { public QueryParameters updateType(String key, Integer type) { this.types.put(processKey(key), type); return this; } QueryParameters(); QueryParameters(Map<String, Object> map); QueryParameters(Class<?> clazz, Object bean); QueryParameters(QueryParameters parameters); QueryParameters(ProcessedInput processedInput); QueryParameters(Object... params); void importValues(Map<String, Object> map); QueryParameters set(String key, Object value, Integer type, Direction direction, Integer position); QueryParameters set(String key, Object value, Integer type, Direction direction); QueryParameters set(String key, Object value, Direction direction); QueryParameters set(String key, Object value, Integer type); QueryParameters set(String key, Object value); QueryParameters setClassName(String className); QueryParameters updateType(String key, Integer type); QueryParameters updateDirection(String key, Direction direction); QueryParameters updatePosition(String key, Integer position); QueryParameters updateValue(String key, Object value); Integer getFirstPosition(String key); List<Integer> getOrderList(String key); boolean usedOnce(String key); Direction getDirection(String key); Integer getType(String key); Object getValue(String key); Map<String, Object> toMap(); Set<String> keySet(); boolean isOutParameter(String key); boolean isInParameter(String key); String getNameByPosition(Integer position); Object getValueByPosition(Integer position); boolean containsKey(String key); void remove(String key); void clearOrder(); int size(); int orderSize(); void setCaseSensitive(boolean newValue); boolean isCaseSensitive(); void setReturn(Object queryOutput); Object getReturn(); void removeReturn(); void update(Object[] newValues, boolean updateOutOnly); void updateAndClean(ProcessedInput processedInput); Object[] getValuesArray(); boolean isOrderSet(); void assertIncorrectOrder(); @Override String toString(); } | @Test public void testUpdateType() throws Exception { QueryParameters params = new QueryParameters(superman.getClass(), superman); Assert.assertEquals(MjdbcTypes.OTHER, params.getType("name").intValue()); params.updateType("name", 2); Assert.assertEquals(2, params.getType("name").intValue()); } |
QueryParameters { public QueryParameters updateDirection(String key, Direction direction) { this.direction.put(processKey(key), direction); return this; } QueryParameters(); QueryParameters(Map<String, Object> map); QueryParameters(Class<?> clazz, Object bean); QueryParameters(QueryParameters parameters); QueryParameters(ProcessedInput processedInput); QueryParameters(Object... params); void importValues(Map<String, Object> map); QueryParameters set(String key, Object value, Integer type, Direction direction, Integer position); QueryParameters set(String key, Object value, Integer type, Direction direction); QueryParameters set(String key, Object value, Direction direction); QueryParameters set(String key, Object value, Integer type); QueryParameters set(String key, Object value); QueryParameters setClassName(String className); QueryParameters updateType(String key, Integer type); QueryParameters updateDirection(String key, Direction direction); QueryParameters updatePosition(String key, Integer position); QueryParameters updateValue(String key, Object value); Integer getFirstPosition(String key); List<Integer> getOrderList(String key); boolean usedOnce(String key); Direction getDirection(String key); Integer getType(String key); Object getValue(String key); Map<String, Object> toMap(); Set<String> keySet(); boolean isOutParameter(String key); boolean isInParameter(String key); String getNameByPosition(Integer position); Object getValueByPosition(Integer position); boolean containsKey(String key); void remove(String key); void clearOrder(); int size(); int orderSize(); void setCaseSensitive(boolean newValue); boolean isCaseSensitive(); void setReturn(Object queryOutput); Object getReturn(); void removeReturn(); void update(Object[] newValues, boolean updateOutOnly); void updateAndClean(ProcessedInput processedInput); Object[] getValuesArray(); boolean isOrderSet(); void assertIncorrectOrder(); @Override String toString(); } | @Test public void testUpdateDirection() throws Exception { QueryParameters params = new QueryParameters(superman.getClass(), superman); Assert.assertEquals(QueryParameters.Direction.IN, params.getDirection("name")); params.updateDirection("name", QueryParameters.Direction.INOUT); Assert.assertEquals(QueryParameters.Direction.INOUT, params.getDirection("name")); } |
QueryParameters { public QueryParameters updatePosition(String key, Integer position) { while (this.order.size() < position + 1) { this.order.add(null); } this.order.set(position, processKey(key)); return this; } QueryParameters(); QueryParameters(Map<String, Object> map); QueryParameters(Class<?> clazz, Object bean); QueryParameters(QueryParameters parameters); QueryParameters(ProcessedInput processedInput); QueryParameters(Object... params); void importValues(Map<String, Object> map); QueryParameters set(String key, Object value, Integer type, Direction direction, Integer position); QueryParameters set(String key, Object value, Integer type, Direction direction); QueryParameters set(String key, Object value, Direction direction); QueryParameters set(String key, Object value, Integer type); QueryParameters set(String key, Object value); QueryParameters setClassName(String className); QueryParameters updateType(String key, Integer type); QueryParameters updateDirection(String key, Direction direction); QueryParameters updatePosition(String key, Integer position); QueryParameters updateValue(String key, Object value); Integer getFirstPosition(String key); List<Integer> getOrderList(String key); boolean usedOnce(String key); Direction getDirection(String key); Integer getType(String key); Object getValue(String key); Map<String, Object> toMap(); Set<String> keySet(); boolean isOutParameter(String key); boolean isInParameter(String key); String getNameByPosition(Integer position); Object getValueByPosition(Integer position); boolean containsKey(String key); void remove(String key); void clearOrder(); int size(); int orderSize(); void setCaseSensitive(boolean newValue); boolean isCaseSensitive(); void setReturn(Object queryOutput); Object getReturn(); void removeReturn(); void update(Object[] newValues, boolean updateOutOnly); void updateAndClean(ProcessedInput processedInput); Object[] getValuesArray(); boolean isOrderSet(); void assertIncorrectOrder(); @Override String toString(); } | @Test public void testUpdatePosition() throws Exception { QueryParameters params = new QueryParameters(superman.getClass(), superman); if (JAVA_VERSION == 1.8) { Assert.assertEquals(2, params.getFirstPosition("name").intValue()); } else { Assert.assertEquals(1, params.getFirstPosition("name").intValue()); } params.updatePosition("name", 3); if (JAVA_VERSION == 1.8) { Assert.assertEquals(2, params.getOrderList("name").get(0).intValue()); } else { Assert.assertEquals(1, params.getOrderList("name").get(0).intValue()); } Assert.assertEquals(3, params.getOrderList("name").get(1).intValue()); } |
QueryParameters { public QueryParameters updateValue(String key, Object value) { this.values.put(processKey(key), value); return this; } QueryParameters(); QueryParameters(Map<String, Object> map); QueryParameters(Class<?> clazz, Object bean); QueryParameters(QueryParameters parameters); QueryParameters(ProcessedInput processedInput); QueryParameters(Object... params); void importValues(Map<String, Object> map); QueryParameters set(String key, Object value, Integer type, Direction direction, Integer position); QueryParameters set(String key, Object value, Integer type, Direction direction); QueryParameters set(String key, Object value, Direction direction); QueryParameters set(String key, Object value, Integer type); QueryParameters set(String key, Object value); QueryParameters setClassName(String className); QueryParameters updateType(String key, Integer type); QueryParameters updateDirection(String key, Direction direction); QueryParameters updatePosition(String key, Integer position); QueryParameters updateValue(String key, Object value); Integer getFirstPosition(String key); List<Integer> getOrderList(String key); boolean usedOnce(String key); Direction getDirection(String key); Integer getType(String key); Object getValue(String key); Map<String, Object> toMap(); Set<String> keySet(); boolean isOutParameter(String key); boolean isInParameter(String key); String getNameByPosition(Integer position); Object getValueByPosition(Integer position); boolean containsKey(String key); void remove(String key); void clearOrder(); int size(); int orderSize(); void setCaseSensitive(boolean newValue); boolean isCaseSensitive(); void setReturn(Object queryOutput); Object getReturn(); void removeReturn(); void update(Object[] newValues, boolean updateOutOnly); void updateAndClean(ProcessedInput processedInput); Object[] getValuesArray(); boolean isOrderSet(); void assertIncorrectOrder(); @Override String toString(); } | @Test public void testUpdateValue() throws Exception { QueryParameters params = new QueryParameters(superman.getClass(), superman); Assert.assertEquals(superman.getName(), params.getValue("name")); params.updateValue("name", "batman"); Assert.assertEquals("batman", params.getValue("name")); } |
QueryParameters { public Integer getFirstPosition(String key) { int position = -1; String processedKey = processKey(key); if (this.values.containsKey(processedKey) == true) { position = this.order.indexOf(processedKey); } return position; } QueryParameters(); QueryParameters(Map<String, Object> map); QueryParameters(Class<?> clazz, Object bean); QueryParameters(QueryParameters parameters); QueryParameters(ProcessedInput processedInput); QueryParameters(Object... params); void importValues(Map<String, Object> map); QueryParameters set(String key, Object value, Integer type, Direction direction, Integer position); QueryParameters set(String key, Object value, Integer type, Direction direction); QueryParameters set(String key, Object value, Direction direction); QueryParameters set(String key, Object value, Integer type); QueryParameters set(String key, Object value); QueryParameters setClassName(String className); QueryParameters updateType(String key, Integer type); QueryParameters updateDirection(String key, Direction direction); QueryParameters updatePosition(String key, Integer position); QueryParameters updateValue(String key, Object value); Integer getFirstPosition(String key); List<Integer> getOrderList(String key); boolean usedOnce(String key); Direction getDirection(String key); Integer getType(String key); Object getValue(String key); Map<String, Object> toMap(); Set<String> keySet(); boolean isOutParameter(String key); boolean isInParameter(String key); String getNameByPosition(Integer position); Object getValueByPosition(Integer position); boolean containsKey(String key); void remove(String key); void clearOrder(); int size(); int orderSize(); void setCaseSensitive(boolean newValue); boolean isCaseSensitive(); void setReturn(Object queryOutput); Object getReturn(); void removeReturn(); void update(Object[] newValues, boolean updateOutOnly); void updateAndClean(ProcessedInput processedInput); Object[] getValuesArray(); boolean isOrderSet(); void assertIncorrectOrder(); @Override String toString(); } | @Test public void testGetPosition() throws Exception { QueryParameters params = new QueryParameters(superman.getClass(), superman); if (JAVA_VERSION == 1.8) { Assert.assertEquals(2, params.getFirstPosition("name").intValue()); } else { Assert.assertEquals(1, params.getFirstPosition("name").intValue()); } } |
QueryParameters { public Direction getDirection(String key) { return this.direction.get(processKey(key)); } QueryParameters(); QueryParameters(Map<String, Object> map); QueryParameters(Class<?> clazz, Object bean); QueryParameters(QueryParameters parameters); QueryParameters(ProcessedInput processedInput); QueryParameters(Object... params); void importValues(Map<String, Object> map); QueryParameters set(String key, Object value, Integer type, Direction direction, Integer position); QueryParameters set(String key, Object value, Integer type, Direction direction); QueryParameters set(String key, Object value, Direction direction); QueryParameters set(String key, Object value, Integer type); QueryParameters set(String key, Object value); QueryParameters setClassName(String className); QueryParameters updateType(String key, Integer type); QueryParameters updateDirection(String key, Direction direction); QueryParameters updatePosition(String key, Integer position); QueryParameters updateValue(String key, Object value); Integer getFirstPosition(String key); List<Integer> getOrderList(String key); boolean usedOnce(String key); Direction getDirection(String key); Integer getType(String key); Object getValue(String key); Map<String, Object> toMap(); Set<String> keySet(); boolean isOutParameter(String key); boolean isInParameter(String key); String getNameByPosition(Integer position); Object getValueByPosition(Integer position); boolean containsKey(String key); void remove(String key); void clearOrder(); int size(); int orderSize(); void setCaseSensitive(boolean newValue); boolean isCaseSensitive(); void setReturn(Object queryOutput); Object getReturn(); void removeReturn(); void update(Object[] newValues, boolean updateOutOnly); void updateAndClean(ProcessedInput processedInput); Object[] getValuesArray(); boolean isOrderSet(); void assertIncorrectOrder(); @Override String toString(); } | @Test public void testGetDirection() throws Exception { QueryParameters params = new QueryParameters(superman.getClass(), superman); Assert.assertEquals(QueryParameters.Direction.IN, params.getDirection("name")); } |
QueryParameters { public Integer getType(String key) { return this.types.get(processKey(key)); } QueryParameters(); QueryParameters(Map<String, Object> map); QueryParameters(Class<?> clazz, Object bean); QueryParameters(QueryParameters parameters); QueryParameters(ProcessedInput processedInput); QueryParameters(Object... params); void importValues(Map<String, Object> map); QueryParameters set(String key, Object value, Integer type, Direction direction, Integer position); QueryParameters set(String key, Object value, Integer type, Direction direction); QueryParameters set(String key, Object value, Direction direction); QueryParameters set(String key, Object value, Integer type); QueryParameters set(String key, Object value); QueryParameters setClassName(String className); QueryParameters updateType(String key, Integer type); QueryParameters updateDirection(String key, Direction direction); QueryParameters updatePosition(String key, Integer position); QueryParameters updateValue(String key, Object value); Integer getFirstPosition(String key); List<Integer> getOrderList(String key); boolean usedOnce(String key); Direction getDirection(String key); Integer getType(String key); Object getValue(String key); Map<String, Object> toMap(); Set<String> keySet(); boolean isOutParameter(String key); boolean isInParameter(String key); String getNameByPosition(Integer position); Object getValueByPosition(Integer position); boolean containsKey(String key); void remove(String key); void clearOrder(); int size(); int orderSize(); void setCaseSensitive(boolean newValue); boolean isCaseSensitive(); void setReturn(Object queryOutput); Object getReturn(); void removeReturn(); void update(Object[] newValues, boolean updateOutOnly); void updateAndClean(ProcessedInput processedInput); Object[] getValuesArray(); boolean isOrderSet(); void assertIncorrectOrder(); @Override String toString(); } | @Test public void testGetType() throws Exception { QueryParameters params = new QueryParameters(superman.getClass(), superman); Assert.assertEquals(MjdbcTypes.OTHER, params.getType("name").intValue()); } |
MidaoFactory { public static DataSource createDataSource(Properties poolProperties) throws SQLException { try { return MidaoFrameworkPoolBinder.createDataSource(poolProperties); } catch (NoClassDefFoundError ex) { throw new NoClassDefFoundError(ERROR_COULDNT_FIND_POOL_PROVIDER); } } static QueryRunnerService getQueryRunner(DataSource ds); static QueryRunnerService getQueryRunner(DataSource ds, Class<? extends TypeHandler> typeHandlerClazz); static QueryRunnerService getQueryRunner(DataSource ds, Class<? extends TypeHandler> typeHandlerClazz, Class<? extends StatementHandler> statementHandlerClazz); static QueryRunnerService getQueryRunner(Connection conn); static QueryRunnerService getQueryRunner(Connection conn, Class<? extends TypeHandler> typeHandlerClazz); static QueryRunnerService getQueryRunner(Connection conn, Class<? extends TypeHandler> typeHandlerClazz, Class<? extends StatementHandler> statementHandlerClazz); static AsyncQueryRunnerService getAsyncQueryRunner(QueryRunner runner, ExecutorService executorService); static DataSource createDataSource(Properties poolProperties); static DataSource createDataSource(String url); static DataSource createDataSource(String url, String userName, String password); static DataSource createDataSource(String driverClassName, String url, String userName, String password); static DataSource createDataSource(String driverClassName, String url, String userName, String password, int initialSize, int maxActive); } | @Test(expected = NoClassDefFoundError.class) public void testCreateDataSourceUrl3() throws Exception { MidaoFactory.createDataSource("", "", "", ""); }
@Test(expected = NoClassDefFoundError.class) public void testCreateDataSourceUrl4() throws Exception { MidaoFactory.createDataSource("", "", "", "", 0, 0); }
@Test(expected = NoClassDefFoundError.class) public void testCreateDataSourceProp() throws Exception { MidaoFactory.createDataSource(new Properties()); }
@Test(expected = NoClassDefFoundError.class) public void testCreateDataSourceUrl1() throws Exception { MidaoFactory.createDataSource(""); }
@Test(expected = NoClassDefFoundError.class) public void testCreateDataSourceUrl2() throws Exception { MidaoFactory.createDataSource("", "", ""); } |
QueryParameters { public Object getValue(String key) { return this.values.get(processKey(key)); } QueryParameters(); QueryParameters(Map<String, Object> map); QueryParameters(Class<?> clazz, Object bean); QueryParameters(QueryParameters parameters); QueryParameters(ProcessedInput processedInput); QueryParameters(Object... params); void importValues(Map<String, Object> map); QueryParameters set(String key, Object value, Integer type, Direction direction, Integer position); QueryParameters set(String key, Object value, Integer type, Direction direction); QueryParameters set(String key, Object value, Direction direction); QueryParameters set(String key, Object value, Integer type); QueryParameters set(String key, Object value); QueryParameters setClassName(String className); QueryParameters updateType(String key, Integer type); QueryParameters updateDirection(String key, Direction direction); QueryParameters updatePosition(String key, Integer position); QueryParameters updateValue(String key, Object value); Integer getFirstPosition(String key); List<Integer> getOrderList(String key); boolean usedOnce(String key); Direction getDirection(String key); Integer getType(String key); Object getValue(String key); Map<String, Object> toMap(); Set<String> keySet(); boolean isOutParameter(String key); boolean isInParameter(String key); String getNameByPosition(Integer position); Object getValueByPosition(Integer position); boolean containsKey(String key); void remove(String key); void clearOrder(); int size(); int orderSize(); void setCaseSensitive(boolean newValue); boolean isCaseSensitive(); void setReturn(Object queryOutput); Object getReturn(); void removeReturn(); void update(Object[] newValues, boolean updateOutOnly); void updateAndClean(ProcessedInput processedInput); Object[] getValuesArray(); boolean isOrderSet(); void assertIncorrectOrder(); @Override String toString(); } | @Test public void testGetValue() throws Exception { QueryParameters params = new QueryParameters(superman.getClass(), superman); Assert.assertEquals(superman.getName(), params.getValue("name")); }
@Test public void testConstructorMap() { QueryParameters params = new QueryParameters(superMap); Assert.assertEquals(superMap.get("name"), params.getValue("name")); Assert.assertEquals(superMap.get("origin"), params.getValue("origin")); Assert.assertEquals(superMap.get("strength"), params.getValue("strength")); }
@Test public void testConstructorBean() { QueryParameters params = new QueryParameters(superman.getClass(), superman); Assert.assertEquals(superman.getName(), params.getValue("name")); Assert.assertEquals(superman.getOrigin(), params.getValue("origin")); Assert.assertEquals(superman.getStrength(), params.getValue("strength")); }
@Test public void testConstructorProcessedInput() { ProcessedInput processedInput = new ProcessedInput("original query"); processedInput.addParameter("name", 1, 2); processedInput.addParameter("origin", 1, 2); processedInput.addParameter("strength", 1, 2); processedInput.setSqlParameterValues(Arrays.<Object>asList(superman.getName(), superman.getOrigin(), superman.getStrength())); QueryParameters params = new QueryParameters(processedInput); Assert.assertEquals(superman.getName(), params.getValue("name")); Assert.assertEquals(superman.getOrigin(), params.getValue("origin")); Assert.assertEquals(superman.getStrength(), params.getValue("strength")); } |
QueryParameters { public Map<String, Object> toMap() { return new HashMap<String, Object>(this.values); } QueryParameters(); QueryParameters(Map<String, Object> map); QueryParameters(Class<?> clazz, Object bean); QueryParameters(QueryParameters parameters); QueryParameters(ProcessedInput processedInput); QueryParameters(Object... params); void importValues(Map<String, Object> map); QueryParameters set(String key, Object value, Integer type, Direction direction, Integer position); QueryParameters set(String key, Object value, Integer type, Direction direction); QueryParameters set(String key, Object value, Direction direction); QueryParameters set(String key, Object value, Integer type); QueryParameters set(String key, Object value); QueryParameters setClassName(String className); QueryParameters updateType(String key, Integer type); QueryParameters updateDirection(String key, Direction direction); QueryParameters updatePosition(String key, Integer position); QueryParameters updateValue(String key, Object value); Integer getFirstPosition(String key); List<Integer> getOrderList(String key); boolean usedOnce(String key); Direction getDirection(String key); Integer getType(String key); Object getValue(String key); Map<String, Object> toMap(); Set<String> keySet(); boolean isOutParameter(String key); boolean isInParameter(String key); String getNameByPosition(Integer position); Object getValueByPosition(Integer position); boolean containsKey(String key); void remove(String key); void clearOrder(); int size(); int orderSize(); void setCaseSensitive(boolean newValue); boolean isCaseSensitive(); void setReturn(Object queryOutput); Object getReturn(); void removeReturn(); void update(Object[] newValues, boolean updateOutOnly); void updateAndClean(ProcessedInput processedInput); Object[] getValuesArray(); boolean isOrderSet(); void assertIncorrectOrder(); @Override String toString(); } | @Test public void testToMap() throws Exception { QueryParameters params = new QueryParameters(superman.getClass(), superman); Map<String, Object> map = params.toMap(); Assert.assertEquals(superman.getName(), map.get("name")); Assert.assertEquals(superman.getOrigin(), map.get("origin")); Assert.assertEquals(superman.getStrength(), map.get("strength")); } |
QueryParameters { public Set<String> keySet() { return this.values.keySet(); } QueryParameters(); QueryParameters(Map<String, Object> map); QueryParameters(Class<?> clazz, Object bean); QueryParameters(QueryParameters parameters); QueryParameters(ProcessedInput processedInput); QueryParameters(Object... params); void importValues(Map<String, Object> map); QueryParameters set(String key, Object value, Integer type, Direction direction, Integer position); QueryParameters set(String key, Object value, Integer type, Direction direction); QueryParameters set(String key, Object value, Direction direction); QueryParameters set(String key, Object value, Integer type); QueryParameters set(String key, Object value); QueryParameters setClassName(String className); QueryParameters updateType(String key, Integer type); QueryParameters updateDirection(String key, Direction direction); QueryParameters updatePosition(String key, Integer position); QueryParameters updateValue(String key, Object value); Integer getFirstPosition(String key); List<Integer> getOrderList(String key); boolean usedOnce(String key); Direction getDirection(String key); Integer getType(String key); Object getValue(String key); Map<String, Object> toMap(); Set<String> keySet(); boolean isOutParameter(String key); boolean isInParameter(String key); String getNameByPosition(Integer position); Object getValueByPosition(Integer position); boolean containsKey(String key); void remove(String key); void clearOrder(); int size(); int orderSize(); void setCaseSensitive(boolean newValue); boolean isCaseSensitive(); void setReturn(Object queryOutput); Object getReturn(); void removeReturn(); void update(Object[] newValues, boolean updateOutOnly); void updateAndClean(ProcessedInput processedInput); Object[] getValuesArray(); boolean isOrderSet(); void assertIncorrectOrder(); @Override String toString(); } | @Test public void testKeySet() throws Exception { QueryParameters params = new QueryParameters(superman.getClass(), superman); Assert.assertTrue(Arrays.asList(new Object[]{"strength", "name", "origin"}).containsAll(params.keySet())); } |
QueryParameters { public boolean isOutParameter(String key) { boolean isOut = false; if (this.getDirection(processKey(key)) == Direction.INOUT || this.getDirection(processKey(key)) == Direction.OUT) { isOut = true; } return isOut; } QueryParameters(); QueryParameters(Map<String, Object> map); QueryParameters(Class<?> clazz, Object bean); QueryParameters(QueryParameters parameters); QueryParameters(ProcessedInput processedInput); QueryParameters(Object... params); void importValues(Map<String, Object> map); QueryParameters set(String key, Object value, Integer type, Direction direction, Integer position); QueryParameters set(String key, Object value, Integer type, Direction direction); QueryParameters set(String key, Object value, Direction direction); QueryParameters set(String key, Object value, Integer type); QueryParameters set(String key, Object value); QueryParameters setClassName(String className); QueryParameters updateType(String key, Integer type); QueryParameters updateDirection(String key, Direction direction); QueryParameters updatePosition(String key, Integer position); QueryParameters updateValue(String key, Object value); Integer getFirstPosition(String key); List<Integer> getOrderList(String key); boolean usedOnce(String key); Direction getDirection(String key); Integer getType(String key); Object getValue(String key); Map<String, Object> toMap(); Set<String> keySet(); boolean isOutParameter(String key); boolean isInParameter(String key); String getNameByPosition(Integer position); Object getValueByPosition(Integer position); boolean containsKey(String key); void remove(String key); void clearOrder(); int size(); int orderSize(); void setCaseSensitive(boolean newValue); boolean isCaseSensitive(); void setReturn(Object queryOutput); Object getReturn(); void removeReturn(); void update(Object[] newValues, boolean updateOutOnly); void updateAndClean(ProcessedInput processedInput); Object[] getValuesArray(); boolean isOrderSet(); void assertIncorrectOrder(); @Override String toString(); } | @Test public void testIsOutParameter() throws Exception { QueryParameters params = new QueryParameters(superman.getClass(), superman); Assert.assertEquals(false, params.isOutParameter("name")); params.updateDirection("name", QueryParameters.Direction.INOUT); Assert.assertEquals(true, params.isOutParameter("name")); params.updateDirection("name", QueryParameters.Direction.OUT); Assert.assertEquals(true, params.isOutParameter("name")); params.updateDirection("name", QueryParameters.Direction.IN); Assert.assertEquals(false, params.isOutParameter("name")); } |
QueryParameters { public boolean isInParameter(String key) { boolean isIn = false; if (this.getDirection(processKey(key)) == Direction.INOUT || this.getDirection(processKey(key)) == Direction.IN) { isIn = true; } return isIn; } QueryParameters(); QueryParameters(Map<String, Object> map); QueryParameters(Class<?> clazz, Object bean); QueryParameters(QueryParameters parameters); QueryParameters(ProcessedInput processedInput); QueryParameters(Object... params); void importValues(Map<String, Object> map); QueryParameters set(String key, Object value, Integer type, Direction direction, Integer position); QueryParameters set(String key, Object value, Integer type, Direction direction); QueryParameters set(String key, Object value, Direction direction); QueryParameters set(String key, Object value, Integer type); QueryParameters set(String key, Object value); QueryParameters setClassName(String className); QueryParameters updateType(String key, Integer type); QueryParameters updateDirection(String key, Direction direction); QueryParameters updatePosition(String key, Integer position); QueryParameters updateValue(String key, Object value); Integer getFirstPosition(String key); List<Integer> getOrderList(String key); boolean usedOnce(String key); Direction getDirection(String key); Integer getType(String key); Object getValue(String key); Map<String, Object> toMap(); Set<String> keySet(); boolean isOutParameter(String key); boolean isInParameter(String key); String getNameByPosition(Integer position); Object getValueByPosition(Integer position); boolean containsKey(String key); void remove(String key); void clearOrder(); int size(); int orderSize(); void setCaseSensitive(boolean newValue); boolean isCaseSensitive(); void setReturn(Object queryOutput); Object getReturn(); void removeReturn(); void update(Object[] newValues, boolean updateOutOnly); void updateAndClean(ProcessedInput processedInput); Object[] getValuesArray(); boolean isOrderSet(); void assertIncorrectOrder(); @Override String toString(); } | @Test public void testIsInParameter() throws Exception { QueryParameters params = new QueryParameters(superman.getClass(), superman); Assert.assertEquals(true, params.isInParameter("name")); params.updateDirection("name", QueryParameters.Direction.INOUT); Assert.assertEquals(true, params.isInParameter("name")); params.updateDirection("name", QueryParameters.Direction.OUT); Assert.assertEquals(false, params.isInParameter("name")); params.updateDirection("name", QueryParameters.Direction.IN); Assert.assertEquals(true, params.isInParameter("name")); } |
QueryParameters { public String getNameByPosition(Integer position) { String name = null; name = this.order.get(position); return name; } QueryParameters(); QueryParameters(Map<String, Object> map); QueryParameters(Class<?> clazz, Object bean); QueryParameters(QueryParameters parameters); QueryParameters(ProcessedInput processedInput); QueryParameters(Object... params); void importValues(Map<String, Object> map); QueryParameters set(String key, Object value, Integer type, Direction direction, Integer position); QueryParameters set(String key, Object value, Integer type, Direction direction); QueryParameters set(String key, Object value, Direction direction); QueryParameters set(String key, Object value, Integer type); QueryParameters set(String key, Object value); QueryParameters setClassName(String className); QueryParameters updateType(String key, Integer type); QueryParameters updateDirection(String key, Direction direction); QueryParameters updatePosition(String key, Integer position); QueryParameters updateValue(String key, Object value); Integer getFirstPosition(String key); List<Integer> getOrderList(String key); boolean usedOnce(String key); Direction getDirection(String key); Integer getType(String key); Object getValue(String key); Map<String, Object> toMap(); Set<String> keySet(); boolean isOutParameter(String key); boolean isInParameter(String key); String getNameByPosition(Integer position); Object getValueByPosition(Integer position); boolean containsKey(String key); void remove(String key); void clearOrder(); int size(); int orderSize(); void setCaseSensitive(boolean newValue); boolean isCaseSensitive(); void setReturn(Object queryOutput); Object getReturn(); void removeReturn(); void update(Object[] newValues, boolean updateOutOnly); void updateAndClean(ProcessedInput processedInput); Object[] getValuesArray(); boolean isOrderSet(); void assertIncorrectOrder(); @Override String toString(); } | @Test public void testGetNameByPosition() throws Exception { QueryParameters params = new QueryParameters(superman.getClass(), superman); if (JAVA_VERSION == 1.8) { Assert.assertEquals("name", params.getNameByPosition(2)); } else { Assert.assertEquals("name", params.getNameByPosition(1)); } } |
QueryParameters { public boolean containsKey(String key) { return this.values.containsKey(processKey(key)); } QueryParameters(); QueryParameters(Map<String, Object> map); QueryParameters(Class<?> clazz, Object bean); QueryParameters(QueryParameters parameters); QueryParameters(ProcessedInput processedInput); QueryParameters(Object... params); void importValues(Map<String, Object> map); QueryParameters set(String key, Object value, Integer type, Direction direction, Integer position); QueryParameters set(String key, Object value, Integer type, Direction direction); QueryParameters set(String key, Object value, Direction direction); QueryParameters set(String key, Object value, Integer type); QueryParameters set(String key, Object value); QueryParameters setClassName(String className); QueryParameters updateType(String key, Integer type); QueryParameters updateDirection(String key, Direction direction); QueryParameters updatePosition(String key, Integer position); QueryParameters updateValue(String key, Object value); Integer getFirstPosition(String key); List<Integer> getOrderList(String key); boolean usedOnce(String key); Direction getDirection(String key); Integer getType(String key); Object getValue(String key); Map<String, Object> toMap(); Set<String> keySet(); boolean isOutParameter(String key); boolean isInParameter(String key); String getNameByPosition(Integer position); Object getValueByPosition(Integer position); boolean containsKey(String key); void remove(String key); void clearOrder(); int size(); int orderSize(); void setCaseSensitive(boolean newValue); boolean isCaseSensitive(); void setReturn(Object queryOutput); Object getReturn(); void removeReturn(); void update(Object[] newValues, boolean updateOutOnly); void updateAndClean(ProcessedInput processedInput); Object[] getValuesArray(); boolean isOrderSet(); void assertIncorrectOrder(); @Override String toString(); } | @Test public void testContainsKey() throws Exception { QueryParameters params = new QueryParameters(superman.getClass(), superman); Assert.assertEquals(true, params.containsKey("name")); Assert.assertEquals(true, params.containsKey("origin")); Assert.assertEquals(true, params.containsKey("strength")); } |
QueryParameters { public void remove(String key) { String processedKey = processKey(key); String orderKey = null; for (int i = 0; i < this.order.size(); i++) { orderKey = this.order.get(i); if (orderKey != null && orderKey.equals(processedKey) == true) { this.order.remove(i); } } this.types.remove(processedKey); this.direction.remove(processedKey); this.values.remove(processedKey); } QueryParameters(); QueryParameters(Map<String, Object> map); QueryParameters(Class<?> clazz, Object bean); QueryParameters(QueryParameters parameters); QueryParameters(ProcessedInput processedInput); QueryParameters(Object... params); void importValues(Map<String, Object> map); QueryParameters set(String key, Object value, Integer type, Direction direction, Integer position); QueryParameters set(String key, Object value, Integer type, Direction direction); QueryParameters set(String key, Object value, Direction direction); QueryParameters set(String key, Object value, Integer type); QueryParameters set(String key, Object value); QueryParameters setClassName(String className); QueryParameters updateType(String key, Integer type); QueryParameters updateDirection(String key, Direction direction); QueryParameters updatePosition(String key, Integer position); QueryParameters updateValue(String key, Object value); Integer getFirstPosition(String key); List<Integer> getOrderList(String key); boolean usedOnce(String key); Direction getDirection(String key); Integer getType(String key); Object getValue(String key); Map<String, Object> toMap(); Set<String> keySet(); boolean isOutParameter(String key); boolean isInParameter(String key); String getNameByPosition(Integer position); Object getValueByPosition(Integer position); boolean containsKey(String key); void remove(String key); void clearOrder(); int size(); int orderSize(); void setCaseSensitive(boolean newValue); boolean isCaseSensitive(); void setReturn(Object queryOutput); Object getReturn(); void removeReturn(); void update(Object[] newValues, boolean updateOutOnly); void updateAndClean(ProcessedInput processedInput); Object[] getValuesArray(); boolean isOrderSet(); void assertIncorrectOrder(); @Override String toString(); } | @Test public void testRemove() throws Exception { QueryParameters params = new QueryParameters(superman.getClass(), superman); Assert.assertEquals(true, params.containsKey("name")); Assert.assertEquals(true, params.containsKey("strength")); Assert.assertEquals(true, params.containsKey("origin")); params.remove("name"); params.remove("strength"); params.remove("origin"); Assert.assertEquals(false, params.containsKey("name")); Assert.assertEquals(false, params.containsKey("strength")); Assert.assertEquals(false, params.containsKey("origin")); } |
QueryParameters { public int size() { return this.values.size(); } QueryParameters(); QueryParameters(Map<String, Object> map); QueryParameters(Class<?> clazz, Object bean); QueryParameters(QueryParameters parameters); QueryParameters(ProcessedInput processedInput); QueryParameters(Object... params); void importValues(Map<String, Object> map); QueryParameters set(String key, Object value, Integer type, Direction direction, Integer position); QueryParameters set(String key, Object value, Integer type, Direction direction); QueryParameters set(String key, Object value, Direction direction); QueryParameters set(String key, Object value, Integer type); QueryParameters set(String key, Object value); QueryParameters setClassName(String className); QueryParameters updateType(String key, Integer type); QueryParameters updateDirection(String key, Direction direction); QueryParameters updatePosition(String key, Integer position); QueryParameters updateValue(String key, Object value); Integer getFirstPosition(String key); List<Integer> getOrderList(String key); boolean usedOnce(String key); Direction getDirection(String key); Integer getType(String key); Object getValue(String key); Map<String, Object> toMap(); Set<String> keySet(); boolean isOutParameter(String key); boolean isInParameter(String key); String getNameByPosition(Integer position); Object getValueByPosition(Integer position); boolean containsKey(String key); void remove(String key); void clearOrder(); int size(); int orderSize(); void setCaseSensitive(boolean newValue); boolean isCaseSensitive(); void setReturn(Object queryOutput); Object getReturn(); void removeReturn(); void update(Object[] newValues, boolean updateOutOnly); void updateAndClean(ProcessedInput processedInput); Object[] getValuesArray(); boolean isOrderSet(); void assertIncorrectOrder(); @Override String toString(); } | @Test public void testSize() throws Exception { QueryParameters params = new QueryParameters(superman.getClass(), superman); Assert.assertEquals(3, params.size()); params.remove("name"); Assert.assertEquals(2, params.size()); } |
QueryParameters { public void setCaseSensitive(boolean newValue) { this.isCaseSensitive = newValue; } QueryParameters(); QueryParameters(Map<String, Object> map); QueryParameters(Class<?> clazz, Object bean); QueryParameters(QueryParameters parameters); QueryParameters(ProcessedInput processedInput); QueryParameters(Object... params); void importValues(Map<String, Object> map); QueryParameters set(String key, Object value, Integer type, Direction direction, Integer position); QueryParameters set(String key, Object value, Integer type, Direction direction); QueryParameters set(String key, Object value, Direction direction); QueryParameters set(String key, Object value, Integer type); QueryParameters set(String key, Object value); QueryParameters setClassName(String className); QueryParameters updateType(String key, Integer type); QueryParameters updateDirection(String key, Direction direction); QueryParameters updatePosition(String key, Integer position); QueryParameters updateValue(String key, Object value); Integer getFirstPosition(String key); List<Integer> getOrderList(String key); boolean usedOnce(String key); Direction getDirection(String key); Integer getType(String key); Object getValue(String key); Map<String, Object> toMap(); Set<String> keySet(); boolean isOutParameter(String key); boolean isInParameter(String key); String getNameByPosition(Integer position); Object getValueByPosition(Integer position); boolean containsKey(String key); void remove(String key); void clearOrder(); int size(); int orderSize(); void setCaseSensitive(boolean newValue); boolean isCaseSensitive(); void setReturn(Object queryOutput); Object getReturn(); void removeReturn(); void update(Object[] newValues, boolean updateOutOnly); void updateAndClean(ProcessedInput processedInput); Object[] getValuesArray(); boolean isOrderSet(); void assertIncorrectOrder(); @Override String toString(); } | @Test public void testSetCaseSensitive() throws Exception { QueryParameters params = new QueryParameters(superman.getClass(), superman); params.setCaseSensitive(false); Assert.assertEquals(3, params.size()); params.set("NaMe", "batman"); Assert.assertEquals(3, params.size()); params.setCaseSensitive(true); params.set("NaMe", "batman"); Assert.assertEquals(4, params.size()); } |
QueryParameters { public boolean isCaseSensitive() { return this.isCaseSensitive; } QueryParameters(); QueryParameters(Map<String, Object> map); QueryParameters(Class<?> clazz, Object bean); QueryParameters(QueryParameters parameters); QueryParameters(ProcessedInput processedInput); QueryParameters(Object... params); void importValues(Map<String, Object> map); QueryParameters set(String key, Object value, Integer type, Direction direction, Integer position); QueryParameters set(String key, Object value, Integer type, Direction direction); QueryParameters set(String key, Object value, Direction direction); QueryParameters set(String key, Object value, Integer type); QueryParameters set(String key, Object value); QueryParameters setClassName(String className); QueryParameters updateType(String key, Integer type); QueryParameters updateDirection(String key, Direction direction); QueryParameters updatePosition(String key, Integer position); QueryParameters updateValue(String key, Object value); Integer getFirstPosition(String key); List<Integer> getOrderList(String key); boolean usedOnce(String key); Direction getDirection(String key); Integer getType(String key); Object getValue(String key); Map<String, Object> toMap(); Set<String> keySet(); boolean isOutParameter(String key); boolean isInParameter(String key); String getNameByPosition(Integer position); Object getValueByPosition(Integer position); boolean containsKey(String key); void remove(String key); void clearOrder(); int size(); int orderSize(); void setCaseSensitive(boolean newValue); boolean isCaseSensitive(); void setReturn(Object queryOutput); Object getReturn(); void removeReturn(); void update(Object[] newValues, boolean updateOutOnly); void updateAndClean(ProcessedInput processedInput); Object[] getValuesArray(); boolean isOrderSet(); void assertIncorrectOrder(); @Override String toString(); } | @Test public void testIsCaseSensitive() throws Exception { QueryParameters params = new QueryParameters(superman.getClass(), superman); Assert.assertEquals(false, params.isCaseSensitive()); } |
QueryParameters { public void setReturn(Object queryOutput) { this.set(QUERY_PARAMS_RETURN, queryOutput); } QueryParameters(); QueryParameters(Map<String, Object> map); QueryParameters(Class<?> clazz, Object bean); QueryParameters(QueryParameters parameters); QueryParameters(ProcessedInput processedInput); QueryParameters(Object... params); void importValues(Map<String, Object> map); QueryParameters set(String key, Object value, Integer type, Direction direction, Integer position); QueryParameters set(String key, Object value, Integer type, Direction direction); QueryParameters set(String key, Object value, Direction direction); QueryParameters set(String key, Object value, Integer type); QueryParameters set(String key, Object value); QueryParameters setClassName(String className); QueryParameters updateType(String key, Integer type); QueryParameters updateDirection(String key, Direction direction); QueryParameters updatePosition(String key, Integer position); QueryParameters updateValue(String key, Object value); Integer getFirstPosition(String key); List<Integer> getOrderList(String key); boolean usedOnce(String key); Direction getDirection(String key); Integer getType(String key); Object getValue(String key); Map<String, Object> toMap(); Set<String> keySet(); boolean isOutParameter(String key); boolean isInParameter(String key); String getNameByPosition(Integer position); Object getValueByPosition(Integer position); boolean containsKey(String key); void remove(String key); void clearOrder(); int size(); int orderSize(); void setCaseSensitive(boolean newValue); boolean isCaseSensitive(); void setReturn(Object queryOutput); Object getReturn(); void removeReturn(); void update(Object[] newValues, boolean updateOutOnly); void updateAndClean(ProcessedInput processedInput); Object[] getValuesArray(); boolean isOrderSet(); void assertIncorrectOrder(); @Override String toString(); } | @Test public void testSetReturn() throws Exception { QueryParameters params = new QueryParameters(superman.getClass(), superman); List<QueryParameters> paramsList = new ArrayList<QueryParameters>(); params.setReturn(paramsList); Assert.assertEquals(paramsList, params.getReturn()); } |
QueryParameters { public Object getReturn() { Object result = null; if (this.containsKey(QUERY_PARAMS_RETURN) == true) { result = this.getValue(QUERY_PARAMS_RETURN); } return result; } QueryParameters(); QueryParameters(Map<String, Object> map); QueryParameters(Class<?> clazz, Object bean); QueryParameters(QueryParameters parameters); QueryParameters(ProcessedInput processedInput); QueryParameters(Object... params); void importValues(Map<String, Object> map); QueryParameters set(String key, Object value, Integer type, Direction direction, Integer position); QueryParameters set(String key, Object value, Integer type, Direction direction); QueryParameters set(String key, Object value, Direction direction); QueryParameters set(String key, Object value, Integer type); QueryParameters set(String key, Object value); QueryParameters setClassName(String className); QueryParameters updateType(String key, Integer type); QueryParameters updateDirection(String key, Direction direction); QueryParameters updatePosition(String key, Integer position); QueryParameters updateValue(String key, Object value); Integer getFirstPosition(String key); List<Integer> getOrderList(String key); boolean usedOnce(String key); Direction getDirection(String key); Integer getType(String key); Object getValue(String key); Map<String, Object> toMap(); Set<String> keySet(); boolean isOutParameter(String key); boolean isInParameter(String key); String getNameByPosition(Integer position); Object getValueByPosition(Integer position); boolean containsKey(String key); void remove(String key); void clearOrder(); int size(); int orderSize(); void setCaseSensitive(boolean newValue); boolean isCaseSensitive(); void setReturn(Object queryOutput); Object getReturn(); void removeReturn(); void update(Object[] newValues, boolean updateOutOnly); void updateAndClean(ProcessedInput processedInput); Object[] getValuesArray(); boolean isOrderSet(); void assertIncorrectOrder(); @Override String toString(); } | @Test public void testGetReturn() throws Exception { testSetReturn(); } |
QueryParameters { public void removeReturn() { if (this.containsKey(QUERY_PARAMS_RETURN) == true) { this.remove(QUERY_PARAMS_RETURN); } } QueryParameters(); QueryParameters(Map<String, Object> map); QueryParameters(Class<?> clazz, Object bean); QueryParameters(QueryParameters parameters); QueryParameters(ProcessedInput processedInput); QueryParameters(Object... params); void importValues(Map<String, Object> map); QueryParameters set(String key, Object value, Integer type, Direction direction, Integer position); QueryParameters set(String key, Object value, Integer type, Direction direction); QueryParameters set(String key, Object value, Direction direction); QueryParameters set(String key, Object value, Integer type); QueryParameters set(String key, Object value); QueryParameters setClassName(String className); QueryParameters updateType(String key, Integer type); QueryParameters updateDirection(String key, Direction direction); QueryParameters updatePosition(String key, Integer position); QueryParameters updateValue(String key, Object value); Integer getFirstPosition(String key); List<Integer> getOrderList(String key); boolean usedOnce(String key); Direction getDirection(String key); Integer getType(String key); Object getValue(String key); Map<String, Object> toMap(); Set<String> keySet(); boolean isOutParameter(String key); boolean isInParameter(String key); String getNameByPosition(Integer position); Object getValueByPosition(Integer position); boolean containsKey(String key); void remove(String key); void clearOrder(); int size(); int orderSize(); void setCaseSensitive(boolean newValue); boolean isCaseSensitive(); void setReturn(Object queryOutput); Object getReturn(); void removeReturn(); void update(Object[] newValues, boolean updateOutOnly); void updateAndClean(ProcessedInput processedInput); Object[] getValuesArray(); boolean isOrderSet(); void assertIncorrectOrder(); @Override String toString(); } | @Test public void testRemoveReturn() throws Exception { QueryParameters params = new QueryParameters(superman.getClass(), superman); List<QueryParameters> paramsList = new ArrayList<QueryParameters>(); params.setReturn(paramsList); Assert.assertEquals(paramsList, params.getReturn()); params.removeReturn(); Assert.assertEquals(null, params.getReturn()); } |
QueryParameters { public void update(Object[] newValues, boolean updateOutOnly) { AssertUtils.assertNotNull(newValues); if (newValues.length != this.values.size()) { throw new IllegalArgumentException(ERROR_INCORRECT_LENGTH); } this.assertIncorrectOrder(); String parameterName = null; for (int i = 0; i < newValues.length; i++) { parameterName = this.getNameByPosition(i); if (updateOutOnly == false || isOutParameter(parameterName) == true) { parameterName = this.getNameByPosition(i); this.updateValue(parameterName, newValues[i]); } } } QueryParameters(); QueryParameters(Map<String, Object> map); QueryParameters(Class<?> clazz, Object bean); QueryParameters(QueryParameters parameters); QueryParameters(ProcessedInput processedInput); QueryParameters(Object... params); void importValues(Map<String, Object> map); QueryParameters set(String key, Object value, Integer type, Direction direction, Integer position); QueryParameters set(String key, Object value, Integer type, Direction direction); QueryParameters set(String key, Object value, Direction direction); QueryParameters set(String key, Object value, Integer type); QueryParameters set(String key, Object value); QueryParameters setClassName(String className); QueryParameters updateType(String key, Integer type); QueryParameters updateDirection(String key, Direction direction); QueryParameters updatePosition(String key, Integer position); QueryParameters updateValue(String key, Object value); Integer getFirstPosition(String key); List<Integer> getOrderList(String key); boolean usedOnce(String key); Direction getDirection(String key); Integer getType(String key); Object getValue(String key); Map<String, Object> toMap(); Set<String> keySet(); boolean isOutParameter(String key); boolean isInParameter(String key); String getNameByPosition(Integer position); Object getValueByPosition(Integer position); boolean containsKey(String key); void remove(String key); void clearOrder(); int size(); int orderSize(); void setCaseSensitive(boolean newValue); boolean isCaseSensitive(); void setReturn(Object queryOutput); Object getReturn(); void removeReturn(); void update(Object[] newValues, boolean updateOutOnly); void updateAndClean(ProcessedInput processedInput); Object[] getValuesArray(); boolean isOrderSet(); void assertIncorrectOrder(); @Override String toString(); } | @Test public void testUpdate() throws Exception { QueryParameters params = new QueryParameters(superman.getClass(), superman); Object[] expectedValues = new Object[]{superman.getName(), superman.getOrigin(), superman.getStrength()}; Object[] updateValues = new Object[]{null, "batman", "earth"}; Object[] updatedValues = new Object[]{100, "batman", "earth"}; org.junit.Assert.assertArrayEquals(expectedValues, new Object[]{params.getValue("name"), params.getValue("origin"), params.getValue("strength")}); params.updateDirection("name", QueryParameters.Direction.INOUT); params.updateDirection("origin", QueryParameters.Direction.INOUT); params.update(updateValues, true); Assert.assertTrue(Arrays.asList(updatedValues).containsAll(Arrays.asList(new Object[]{params.getValue("strength"), params.getValue("name"), params.getValue("origin")}))); } |
QueryParameters { public void updateAndClean(ProcessedInput processedInput) { List<String> processedParameters = new ArrayList<String>(); if (processedInput.getAmountOfParameters() > 0) { String parameterName = null; for (int i = 0; i < processedInput.getAmountOfParameters(); i++) { parameterName = processedInput.getParameterName(i); processedParameters.add(parameterName); this.updateValue(parameterName, processedInput.getSqlParameterValues().get(i)); this.updatePosition(parameterName, i); } } List<String> removeKeyList = new ArrayList<String>(); for (String key : this.keySet()) { if (processedParameters.contains(key) == false) { removeKeyList.add(key); } } for (String key : removeKeyList) { this.remove(key); } } QueryParameters(); QueryParameters(Map<String, Object> map); QueryParameters(Class<?> clazz, Object bean); QueryParameters(QueryParameters parameters); QueryParameters(ProcessedInput processedInput); QueryParameters(Object... params); void importValues(Map<String, Object> map); QueryParameters set(String key, Object value, Integer type, Direction direction, Integer position); QueryParameters set(String key, Object value, Integer type, Direction direction); QueryParameters set(String key, Object value, Direction direction); QueryParameters set(String key, Object value, Integer type); QueryParameters set(String key, Object value); QueryParameters setClassName(String className); QueryParameters updateType(String key, Integer type); QueryParameters updateDirection(String key, Direction direction); QueryParameters updatePosition(String key, Integer position); QueryParameters updateValue(String key, Object value); Integer getFirstPosition(String key); List<Integer> getOrderList(String key); boolean usedOnce(String key); Direction getDirection(String key); Integer getType(String key); Object getValue(String key); Map<String, Object> toMap(); Set<String> keySet(); boolean isOutParameter(String key); boolean isInParameter(String key); String getNameByPosition(Integer position); Object getValueByPosition(Integer position); boolean containsKey(String key); void remove(String key); void clearOrder(); int size(); int orderSize(); void setCaseSensitive(boolean newValue); boolean isCaseSensitive(); void setReturn(Object queryOutput); Object getReturn(); void removeReturn(); void update(Object[] newValues, boolean updateOutOnly); void updateAndClean(ProcessedInput processedInput); Object[] getValuesArray(); boolean isOrderSet(); void assertIncorrectOrder(); @Override String toString(); } | @Test public void testUpdateAndClean() throws Exception { QueryParameters params = new QueryParameters(superman.getClass(), superman); params.set("once_bested_by", "doomsday"); Object[] updatedValues = new Object[]{100, "batman", "earth"}; ProcessedInput processedInput = new ProcessedInput("original query"); processedInput.addParameter("name", 1, 2); processedInput.addParameter("origin", 1, 2); processedInput.addParameter("strength", 1, 2); processedInput.setSqlParameterValues(Arrays.<Object>asList(updatedValues[1], updatedValues[2], updatedValues[0])); Assert.assertEquals(4, params.size()); params.updateAndClean(processedInput); org.junit.Assert.assertArrayEquals(new Object[]{updatedValues[1], updatedValues[2], updatedValues[0]}, new Object[]{params.getValue("name"), params.getValue("origin"), params.getValue("strength")}); Assert.assertEquals(3, params.size()); } |
QueryParameters { public Object[] getValuesArray() { this.assertIncorrectOrder(); Object[] params = new Object[this.order.size()]; String parameterName = null; for (int i = 0; i < this.order.size(); i++) { parameterName = this.getNameByPosition(i); params[i] = this.getValue(parameterName); } return params; } QueryParameters(); QueryParameters(Map<String, Object> map); QueryParameters(Class<?> clazz, Object bean); QueryParameters(QueryParameters parameters); QueryParameters(ProcessedInput processedInput); QueryParameters(Object... params); void importValues(Map<String, Object> map); QueryParameters set(String key, Object value, Integer type, Direction direction, Integer position); QueryParameters set(String key, Object value, Integer type, Direction direction); QueryParameters set(String key, Object value, Direction direction); QueryParameters set(String key, Object value, Integer type); QueryParameters set(String key, Object value); QueryParameters setClassName(String className); QueryParameters updateType(String key, Integer type); QueryParameters updateDirection(String key, Direction direction); QueryParameters updatePosition(String key, Integer position); QueryParameters updateValue(String key, Object value); Integer getFirstPosition(String key); List<Integer> getOrderList(String key); boolean usedOnce(String key); Direction getDirection(String key); Integer getType(String key); Object getValue(String key); Map<String, Object> toMap(); Set<String> keySet(); boolean isOutParameter(String key); boolean isInParameter(String key); String getNameByPosition(Integer position); Object getValueByPosition(Integer position); boolean containsKey(String key); void remove(String key); void clearOrder(); int size(); int orderSize(); void setCaseSensitive(boolean newValue); boolean isCaseSensitive(); void setReturn(Object queryOutput); Object getReturn(); void removeReturn(); void update(Object[] newValues, boolean updateOutOnly); void updateAndClean(ProcessedInput processedInput); Object[] getValuesArray(); boolean isOrderSet(); void assertIncorrectOrder(); @Override String toString(); } | @Test public void testGetValuesArray() throws Exception { QueryParameters params = new QueryParameters(superman.getClass(), superman); Assert.assertTrue(Arrays.asList(new Object[]{superman.getStrength(), superman.getName(), superman.getOrigin()}).containsAll(Arrays.asList(params.getValuesArray()))); } |
QueryParameters { public boolean isOrderSet() { boolean result = true; if (this.values.size() != this.order.size()) { result = false; } return result; } QueryParameters(); QueryParameters(Map<String, Object> map); QueryParameters(Class<?> clazz, Object bean); QueryParameters(QueryParameters parameters); QueryParameters(ProcessedInput processedInput); QueryParameters(Object... params); void importValues(Map<String, Object> map); QueryParameters set(String key, Object value, Integer type, Direction direction, Integer position); QueryParameters set(String key, Object value, Integer type, Direction direction); QueryParameters set(String key, Object value, Direction direction); QueryParameters set(String key, Object value, Integer type); QueryParameters set(String key, Object value); QueryParameters setClassName(String className); QueryParameters updateType(String key, Integer type); QueryParameters updateDirection(String key, Direction direction); QueryParameters updatePosition(String key, Integer position); QueryParameters updateValue(String key, Object value); Integer getFirstPosition(String key); List<Integer> getOrderList(String key); boolean usedOnce(String key); Direction getDirection(String key); Integer getType(String key); Object getValue(String key); Map<String, Object> toMap(); Set<String> keySet(); boolean isOutParameter(String key); boolean isInParameter(String key); String getNameByPosition(Integer position); Object getValueByPosition(Integer position); boolean containsKey(String key); void remove(String key); void clearOrder(); int size(); int orderSize(); void setCaseSensitive(boolean newValue); boolean isCaseSensitive(); void setReturn(Object queryOutput); Object getReturn(); void removeReturn(); void update(Object[] newValues, boolean updateOutOnly); void updateAndClean(ProcessedInput processedInput); Object[] getValuesArray(); boolean isOrderSet(); void assertIncorrectOrder(); @Override String toString(); } | @Test public void testIsOrderSet() throws Exception { QueryParameters params = new QueryParameters(superman.getClass(), superman); Assert.assertEquals(true, params.isOrderSet()); params.remove("strength"); params.updateValue("strength", 99); Assert.assertEquals(false, params.isOrderSet()); } |
QueryParameters { public void assertIncorrectOrder() { if (this.isOrderSet() == false) { throw new IllegalArgumentException(ERROR_ORDER_NOT_INIT); } } QueryParameters(); QueryParameters(Map<String, Object> map); QueryParameters(Class<?> clazz, Object bean); QueryParameters(QueryParameters parameters); QueryParameters(ProcessedInput processedInput); QueryParameters(Object... params); void importValues(Map<String, Object> map); QueryParameters set(String key, Object value, Integer type, Direction direction, Integer position); QueryParameters set(String key, Object value, Integer type, Direction direction); QueryParameters set(String key, Object value, Direction direction); QueryParameters set(String key, Object value, Integer type); QueryParameters set(String key, Object value); QueryParameters setClassName(String className); QueryParameters updateType(String key, Integer type); QueryParameters updateDirection(String key, Direction direction); QueryParameters updatePosition(String key, Integer position); QueryParameters updateValue(String key, Object value); Integer getFirstPosition(String key); List<Integer> getOrderList(String key); boolean usedOnce(String key); Direction getDirection(String key); Integer getType(String key); Object getValue(String key); Map<String, Object> toMap(); Set<String> keySet(); boolean isOutParameter(String key); boolean isInParameter(String key); String getNameByPosition(Integer position); Object getValueByPosition(Integer position); boolean containsKey(String key); void remove(String key); void clearOrder(); int size(); int orderSize(); void setCaseSensitive(boolean newValue); boolean isCaseSensitive(); void setReturn(Object queryOutput); Object getReturn(); void removeReturn(); void update(Object[] newValues, boolean updateOutOnly); void updateAndClean(ProcessedInput processedInput); Object[] getValuesArray(); boolean isOrderSet(); void assertIncorrectOrder(); @Override String toString(); } | @Test public void testAssertIncorrectOrder() throws Exception { QueryParameters params = new QueryParameters(superman.getClass(), superman); try { params.assertIncorrectOrder(); } catch (IllegalArgumentException ex) { fail(); } params.remove("strength"); params.updateValue("strength", 99); try { params.assertIncorrectOrder(); fail(); } catch (IllegalArgumentException ex) { } } |
BaseExceptionHandler implements ExceptionHandler { public BaseExceptionHandler(String dbName) { this.dbName = dbName; } BaseExceptionHandler(String dbName); MjdbcSQLException convert(Connection conn, SQLException cause, String sql, Object... params); } | @Test public void testBaseExceptionHandler() throws SQLException { ((QueryRunner) runner).setExceptionHandler(baseExceptionHandler); try { runner.query("SQL generates Exception", new MapOutputHandler()); } catch (Exception ex) { Assert.assertEquals(" Query: SQL generates Exception Parameters: [QueryParameters CI { }]", ex.getMessage()); } } |
ProcessedInput { public void addParameter(String parameterName, int parameterStart, int parameterEnd, String parameterType, String parameterDirection) { if (this.sqlParameterNames == null) { this.sqlParameterNames = new ArrayList<String>(); this.sqlParameterBoundaries = new ArrayList<int[]>(); } this.sqlParameterNames.add(parameterName); this.sqlParameterBoundaries.add(new int[]{parameterStart, parameterEnd}); this.sqlParameterTypes.add(parameterType); this.sqlParameterDirections.add(parameterDirection); } ProcessedInput(String originalSql); ProcessedInput(ProcessedInput processedInput); ProcessedInput(String originalSql, String parsedSql, List<String> sqlParameterNames, List<int[]> sqlParameterBoundaries, List<Object> sqlParameterValues, List<String> sqlParameterTypes, List<String> sqlParameterDirections); ProcessedInput(String originalSql, String parsedSql, List<String> sqlParameterNames, List<int[]> sqlParameterBoundaries, List<Object> sqlParameterValues); void addParameter(String parameterName, int parameterStart, int parameterEnd, String parameterType, String parameterDirection); void addParameter(String parameterName, int parameterStart, int parameterEnd); String getOriginalSql(); String getParsedSql(); List<String> getSqlParameterNames(); List<int[]> getSqlParameterBoundaries(); List<Object> getSqlParameterValues(); List<String> getSqlParameterTypes(); List<String> getSqlParameterDirections(); void setParsedSql(String parsedSql); void setSqlParameterValues(List<Object> sqlParameterValues); Integer getPosition(String parameterName); String getParameterName(Integer position); Integer getAmountOfParameters(); boolean isFilled(); void fillParameterValues(Map<String, Object> valuesMap); } | @Test public void testAddParameter() throws Exception { ProcessedInput processedInput = new ProcessedInput("original SQL"); processedInput.addParameter("parameter", 3, 9); Assert.assertEquals("parameter", processedInput.getSqlParameterNames().get(0)); org.junit.Assert.assertArrayEquals(new int[]{3, 9}, processedInput.getSqlParameterBoundaries().get(0)); } |
ProcessedInput { public String getOriginalSql() { return originalSql; } ProcessedInput(String originalSql); ProcessedInput(ProcessedInput processedInput); ProcessedInput(String originalSql, String parsedSql, List<String> sqlParameterNames, List<int[]> sqlParameterBoundaries, List<Object> sqlParameterValues, List<String> sqlParameterTypes, List<String> sqlParameterDirections); ProcessedInput(String originalSql, String parsedSql, List<String> sqlParameterNames, List<int[]> sqlParameterBoundaries, List<Object> sqlParameterValues); void addParameter(String parameterName, int parameterStart, int parameterEnd, String parameterType, String parameterDirection); void addParameter(String parameterName, int parameterStart, int parameterEnd); String getOriginalSql(); String getParsedSql(); List<String> getSqlParameterNames(); List<int[]> getSqlParameterBoundaries(); List<Object> getSqlParameterValues(); List<String> getSqlParameterTypes(); List<String> getSqlParameterDirections(); void setParsedSql(String parsedSql); void setSqlParameterValues(List<Object> sqlParameterValues); Integer getPosition(String parameterName); String getParameterName(Integer position); Integer getAmountOfParameters(); boolean isFilled(); void fillParameterValues(Map<String, Object> valuesMap); } | @Test public void testGetOriginalSql() throws Exception { String originalSql = "original SQL"; ProcessedInput processedInput = new ProcessedInput(originalSql); Assert.assertEquals(originalSql, processedInput.getOriginalSql()); } |
ProcessedInput { public String getParsedSql() { return parsedSql; } ProcessedInput(String originalSql); ProcessedInput(ProcessedInput processedInput); ProcessedInput(String originalSql, String parsedSql, List<String> sqlParameterNames, List<int[]> sqlParameterBoundaries, List<Object> sqlParameterValues, List<String> sqlParameterTypes, List<String> sqlParameterDirections); ProcessedInput(String originalSql, String parsedSql, List<String> sqlParameterNames, List<int[]> sqlParameterBoundaries, List<Object> sqlParameterValues); void addParameter(String parameterName, int parameterStart, int parameterEnd, String parameterType, String parameterDirection); void addParameter(String parameterName, int parameterStart, int parameterEnd); String getOriginalSql(); String getParsedSql(); List<String> getSqlParameterNames(); List<int[]> getSqlParameterBoundaries(); List<Object> getSqlParameterValues(); List<String> getSqlParameterTypes(); List<String> getSqlParameterDirections(); void setParsedSql(String parsedSql); void setSqlParameterValues(List<Object> sqlParameterValues); Integer getPosition(String parameterName); String getParameterName(Integer position); Integer getAmountOfParameters(); boolean isFilled(); void fillParameterValues(Map<String, Object> valuesMap); } | @Test public void testGetParsedSql() throws Exception { String originalSql = "original SQL"; String parsedSql = "parsed SQL"; ProcessedInput processedInput = new ProcessedInput(originalSql); processedInput.setParsedSql(parsedSql); Assert.assertEquals(originalSql, processedInput.getOriginalSql()); Assert.assertEquals(parsedSql, processedInput.getParsedSql()); } |
ProcessedInput { public List<String> getSqlParameterNames() { return sqlParameterNames; } ProcessedInput(String originalSql); ProcessedInput(ProcessedInput processedInput); ProcessedInput(String originalSql, String parsedSql, List<String> sqlParameterNames, List<int[]> sqlParameterBoundaries, List<Object> sqlParameterValues, List<String> sqlParameterTypes, List<String> sqlParameterDirections); ProcessedInput(String originalSql, String parsedSql, List<String> sqlParameterNames, List<int[]> sqlParameterBoundaries, List<Object> sqlParameterValues); void addParameter(String parameterName, int parameterStart, int parameterEnd, String parameterType, String parameterDirection); void addParameter(String parameterName, int parameterStart, int parameterEnd); String getOriginalSql(); String getParsedSql(); List<String> getSqlParameterNames(); List<int[]> getSqlParameterBoundaries(); List<Object> getSqlParameterValues(); List<String> getSqlParameterTypes(); List<String> getSqlParameterDirections(); void setParsedSql(String parsedSql); void setSqlParameterValues(List<Object> sqlParameterValues); Integer getPosition(String parameterName); String getParameterName(Integer position); Integer getAmountOfParameters(); boolean isFilled(); void fillParameterValues(Map<String, Object> valuesMap); } | @Test public void testGetSqlParameterNames() throws Exception { List<String> sqlParameterNames = new ArrayList<String>(); sqlParameterNames.add("name"); sqlParameterNames.add("origin"); sqlParameterNames.add("strength"); ProcessedInput processedInput = new ProcessedInput(""); processedInput.addParameter(sqlParameterNames.get(0), 1, 1); processedInput.addParameter(sqlParameterNames.get(1), 1, 1); processedInput.addParameter(sqlParameterNames.get(2), 1, 1); org.junit.Assert.assertArrayEquals(sqlParameterNames.toArray(), processedInput.getSqlParameterNames().toArray()); } |
ProcessedInput { public List<int[]> getSqlParameterBoundaries() { return sqlParameterBoundaries; } ProcessedInput(String originalSql); ProcessedInput(ProcessedInput processedInput); ProcessedInput(String originalSql, String parsedSql, List<String> sqlParameterNames, List<int[]> sqlParameterBoundaries, List<Object> sqlParameterValues, List<String> sqlParameterTypes, List<String> sqlParameterDirections); ProcessedInput(String originalSql, String parsedSql, List<String> sqlParameterNames, List<int[]> sqlParameterBoundaries, List<Object> sqlParameterValues); void addParameter(String parameterName, int parameterStart, int parameterEnd, String parameterType, String parameterDirection); void addParameter(String parameterName, int parameterStart, int parameterEnd); String getOriginalSql(); String getParsedSql(); List<String> getSqlParameterNames(); List<int[]> getSqlParameterBoundaries(); List<Object> getSqlParameterValues(); List<String> getSqlParameterTypes(); List<String> getSqlParameterDirections(); void setParsedSql(String parsedSql); void setSqlParameterValues(List<Object> sqlParameterValues); Integer getPosition(String parameterName); String getParameterName(Integer position); Integer getAmountOfParameters(); boolean isFilled(); void fillParameterValues(Map<String, Object> valuesMap); } | @Test public void testGetSqlParameterBoundaries() throws Exception { List<int[]> sqlParameterBoundaries = new ArrayList<int[]>(); sqlParameterBoundaries.add(new int[]{1, 2}); sqlParameterBoundaries.add(new int[]{3, 4}); sqlParameterBoundaries.add(new int[]{5, 6}); ProcessedInput processedInput = new ProcessedInput(""); processedInput.addParameter("", sqlParameterBoundaries.get(0)[0], sqlParameterBoundaries.get(0)[1]); processedInput.addParameter("", sqlParameterBoundaries.get(1)[0], sqlParameterBoundaries.get(1)[1]); processedInput.addParameter("", sqlParameterBoundaries.get(2)[0], sqlParameterBoundaries.get(2)[1]); org.junit.Assert.assertArrayEquals(sqlParameterBoundaries.toArray(), processedInput.getSqlParameterBoundaries().toArray()); } |
ProcessedInput { public List<Object> getSqlParameterValues() { return sqlParameterValues; } ProcessedInput(String originalSql); ProcessedInput(ProcessedInput processedInput); ProcessedInput(String originalSql, String parsedSql, List<String> sqlParameterNames, List<int[]> sqlParameterBoundaries, List<Object> sqlParameterValues, List<String> sqlParameterTypes, List<String> sqlParameterDirections); ProcessedInput(String originalSql, String parsedSql, List<String> sqlParameterNames, List<int[]> sqlParameterBoundaries, List<Object> sqlParameterValues); void addParameter(String parameterName, int parameterStart, int parameterEnd, String parameterType, String parameterDirection); void addParameter(String parameterName, int parameterStart, int parameterEnd); String getOriginalSql(); String getParsedSql(); List<String> getSqlParameterNames(); List<int[]> getSqlParameterBoundaries(); List<Object> getSqlParameterValues(); List<String> getSqlParameterTypes(); List<String> getSqlParameterDirections(); void setParsedSql(String parsedSql); void setSqlParameterValues(List<Object> sqlParameterValues); Integer getPosition(String parameterName); String getParameterName(Integer position); Integer getAmountOfParameters(); boolean isFilled(); void fillParameterValues(Map<String, Object> valuesMap); } | @Test public void testGetSqlParameterValues() throws Exception { List<Object> sqlParameterValues = new ArrayList<Object>(); sqlParameterValues.add("1"); sqlParameterValues.add("2"); sqlParameterValues.add("3"); ProcessedInput processedInput = new ProcessedInput(""); processedInput.setSqlParameterValues(sqlParameterValues); Assert.assertEquals(false, sqlParameterValues == processedInput.getSqlParameterValues()); org.junit.Assert.assertArrayEquals(sqlParameterValues.toArray(), processedInput.getSqlParameterValues().toArray()); } |
ProcessedInput { public void setParsedSql(String parsedSql) { this.parsedSql = parsedSql; } ProcessedInput(String originalSql); ProcessedInput(ProcessedInput processedInput); ProcessedInput(String originalSql, String parsedSql, List<String> sqlParameterNames, List<int[]> sqlParameterBoundaries, List<Object> sqlParameterValues, List<String> sqlParameterTypes, List<String> sqlParameterDirections); ProcessedInput(String originalSql, String parsedSql, List<String> sqlParameterNames, List<int[]> sqlParameterBoundaries, List<Object> sqlParameterValues); void addParameter(String parameterName, int parameterStart, int parameterEnd, String parameterType, String parameterDirection); void addParameter(String parameterName, int parameterStart, int parameterEnd); String getOriginalSql(); String getParsedSql(); List<String> getSqlParameterNames(); List<int[]> getSqlParameterBoundaries(); List<Object> getSqlParameterValues(); List<String> getSqlParameterTypes(); List<String> getSqlParameterDirections(); void setParsedSql(String parsedSql); void setSqlParameterValues(List<Object> sqlParameterValues); Integer getPosition(String parameterName); String getParameterName(Integer position); Integer getAmountOfParameters(); boolean isFilled(); void fillParameterValues(Map<String, Object> valuesMap); } | @Test public void testSetParsedSql() throws Exception { testGetParsedSql(); } |
ProcessedInput { public void setSqlParameterValues(List<Object> sqlParameterValues) { if (sqlParameterValues != null) { this.sqlParameterValues = new ArrayList<Object>(sqlParameterValues); } else { this.sqlParameterValues = null; } } ProcessedInput(String originalSql); ProcessedInput(ProcessedInput processedInput); ProcessedInput(String originalSql, String parsedSql, List<String> sqlParameterNames, List<int[]> sqlParameterBoundaries, List<Object> sqlParameterValues, List<String> sqlParameterTypes, List<String> sqlParameterDirections); ProcessedInput(String originalSql, String parsedSql, List<String> sqlParameterNames, List<int[]> sqlParameterBoundaries, List<Object> sqlParameterValues); void addParameter(String parameterName, int parameterStart, int parameterEnd, String parameterType, String parameterDirection); void addParameter(String parameterName, int parameterStart, int parameterEnd); String getOriginalSql(); String getParsedSql(); List<String> getSqlParameterNames(); List<int[]> getSqlParameterBoundaries(); List<Object> getSqlParameterValues(); List<String> getSqlParameterTypes(); List<String> getSqlParameterDirections(); void setParsedSql(String parsedSql); void setSqlParameterValues(List<Object> sqlParameterValues); Integer getPosition(String parameterName); String getParameterName(Integer position); Integer getAmountOfParameters(); boolean isFilled(); void fillParameterValues(Map<String, Object> valuesMap); } | @Test public void testSetSqlParameterValues() throws Exception { testGetSqlParameterValues(); } |
ProcessedInput { public Integer getPosition(String parameterName) { Integer position = null; for (int i = 0; i < this.sqlParameterNames.size(); i++) { if (this.sqlParameterNames.get(i).equals(parameterName) == true) { position = i; break; } } return position; } ProcessedInput(String originalSql); ProcessedInput(ProcessedInput processedInput); ProcessedInput(String originalSql, String parsedSql, List<String> sqlParameterNames, List<int[]> sqlParameterBoundaries, List<Object> sqlParameterValues, List<String> sqlParameterTypes, List<String> sqlParameterDirections); ProcessedInput(String originalSql, String parsedSql, List<String> sqlParameterNames, List<int[]> sqlParameterBoundaries, List<Object> sqlParameterValues); void addParameter(String parameterName, int parameterStart, int parameterEnd, String parameterType, String parameterDirection); void addParameter(String parameterName, int parameterStart, int parameterEnd); String getOriginalSql(); String getParsedSql(); List<String> getSqlParameterNames(); List<int[]> getSqlParameterBoundaries(); List<Object> getSqlParameterValues(); List<String> getSqlParameterTypes(); List<String> getSqlParameterDirections(); void setParsedSql(String parsedSql); void setSqlParameterValues(List<Object> sqlParameterValues); Integer getPosition(String parameterName); String getParameterName(Integer position); Integer getAmountOfParameters(); boolean isFilled(); void fillParameterValues(Map<String, Object> valuesMap); } | @Test public void testGetPosition() throws Exception { ProcessedInput processedInput = new ProcessedInput(""); processedInput.addParameter("name", 1, 2); processedInput.addParameter("origin", 3, 4); processedInput.addParameter("strength", 5, 6); Assert.assertEquals(0, processedInput.getPosition("name").intValue()); Assert.assertEquals(1, processedInput.getPosition("origin").intValue()); Assert.assertEquals(2, processedInput.getPosition("strength").intValue()); } |
ProcessedInput { public String getParameterName(Integer position) { String name = null; if (this.sqlParameterNames != null) { name = this.sqlParameterNames.get(position); } return name; } ProcessedInput(String originalSql); ProcessedInput(ProcessedInput processedInput); ProcessedInput(String originalSql, String parsedSql, List<String> sqlParameterNames, List<int[]> sqlParameterBoundaries, List<Object> sqlParameterValues, List<String> sqlParameterTypes, List<String> sqlParameterDirections); ProcessedInput(String originalSql, String parsedSql, List<String> sqlParameterNames, List<int[]> sqlParameterBoundaries, List<Object> sqlParameterValues); void addParameter(String parameterName, int parameterStart, int parameterEnd, String parameterType, String parameterDirection); void addParameter(String parameterName, int parameterStart, int parameterEnd); String getOriginalSql(); String getParsedSql(); List<String> getSqlParameterNames(); List<int[]> getSqlParameterBoundaries(); List<Object> getSqlParameterValues(); List<String> getSqlParameterTypes(); List<String> getSqlParameterDirections(); void setParsedSql(String parsedSql); void setSqlParameterValues(List<Object> sqlParameterValues); Integer getPosition(String parameterName); String getParameterName(Integer position); Integer getAmountOfParameters(); boolean isFilled(); void fillParameterValues(Map<String, Object> valuesMap); } | @Test public void testGetParameterName() throws Exception { ProcessedInput processedInput = new ProcessedInput(""); processedInput.addParameter("name", 1, 2); processedInput.addParameter("origin", 3, 4); processedInput.addParameter("strength", 5, 6); Assert.assertEquals("name", processedInput.getParameterName(0)); Assert.assertEquals("origin", processedInput.getParameterName(1)); Assert.assertEquals("strength", processedInput.getParameterName(2)); } |
ExceptionUtils { public static void rethrow(MjdbcException cause) throws MjdbcSQLException { MjdbcSQLException ex = new MjdbcSQLException(cause.getMessage()); ex.setStackTrace(cause.getStackTrace()); throw ex; } static void rethrow(MjdbcException cause); } | @Test public void testRethrow() { try { ExceptionUtils.rethrow(new MjdbcException()); fail(); } catch (MjdbcSQLException ex) { } } |
ProcessedInput { public Integer getAmountOfParameters() { Integer size = 0; if (this.sqlParameterNames != null) { size = this.sqlParameterNames.size(); } return size; } ProcessedInput(String originalSql); ProcessedInput(ProcessedInput processedInput); ProcessedInput(String originalSql, String parsedSql, List<String> sqlParameterNames, List<int[]> sqlParameterBoundaries, List<Object> sqlParameterValues, List<String> sqlParameterTypes, List<String> sqlParameterDirections); ProcessedInput(String originalSql, String parsedSql, List<String> sqlParameterNames, List<int[]> sqlParameterBoundaries, List<Object> sqlParameterValues); void addParameter(String parameterName, int parameterStart, int parameterEnd, String parameterType, String parameterDirection); void addParameter(String parameterName, int parameterStart, int parameterEnd); String getOriginalSql(); String getParsedSql(); List<String> getSqlParameterNames(); List<int[]> getSqlParameterBoundaries(); List<Object> getSqlParameterValues(); List<String> getSqlParameterTypes(); List<String> getSqlParameterDirections(); void setParsedSql(String parsedSql); void setSqlParameterValues(List<Object> sqlParameterValues); Integer getPosition(String parameterName); String getParameterName(Integer position); Integer getAmountOfParameters(); boolean isFilled(); void fillParameterValues(Map<String, Object> valuesMap); } | @Test public void testGetAmountOfParameters() throws Exception { ProcessedInput processedInput = new ProcessedInput(""); Assert.assertEquals(0, processedInput.getAmountOfParameters().intValue()); processedInput.addParameter("name", 1, 2); processedInput.addParameter("origin", 3, 4); processedInput.addParameter("strength", 5, 6); Assert.assertEquals(3, processedInput.getAmountOfParameters().intValue()); } |
ProcessedInput { public boolean isFilled() { boolean isFilled = false; if (this.originalSql != null && this.originalSql.length() > 0) { if (this.parsedSql != null && this.parsedSql.length() > 0) { if (this.sqlParameterNames != null) { if (this.sqlParameterValues != null) { isFilled = true; } } } } return isFilled; } ProcessedInput(String originalSql); ProcessedInput(ProcessedInput processedInput); ProcessedInput(String originalSql, String parsedSql, List<String> sqlParameterNames, List<int[]> sqlParameterBoundaries, List<Object> sqlParameterValues, List<String> sqlParameterTypes, List<String> sqlParameterDirections); ProcessedInput(String originalSql, String parsedSql, List<String> sqlParameterNames, List<int[]> sqlParameterBoundaries, List<Object> sqlParameterValues); void addParameter(String parameterName, int parameterStart, int parameterEnd, String parameterType, String parameterDirection); void addParameter(String parameterName, int parameterStart, int parameterEnd); String getOriginalSql(); String getParsedSql(); List<String> getSqlParameterNames(); List<int[]> getSqlParameterBoundaries(); List<Object> getSqlParameterValues(); List<String> getSqlParameterTypes(); List<String> getSqlParameterDirections(); void setParsedSql(String parsedSql); void setSqlParameterValues(List<Object> sqlParameterValues); Integer getPosition(String parameterName); String getParameterName(Integer position); Integer getAmountOfParameters(); boolean isFilled(); void fillParameterValues(Map<String, Object> valuesMap); } | @Test public void testIsFilled() throws Exception { ProcessedInput processedInput = new ProcessedInput("a"); processedInput.addParameter("name", 1, 2); processedInput.addParameter("origin", 3, 4); processedInput.addParameter("strength", 5, 6); Assert.assertEquals(false, processedInput.isFilled()); processedInput.setParsedSql("b"); Assert.assertEquals(true, processedInput.isFilled()); } |
ProcessedInput { public void fillParameterValues(Map<String, Object> valuesMap) { AssertUtils.assertNotNull(valuesMap, "Value map cannot be null"); if (this.sqlParameterNames != null) { String parameterName = null; this.sqlParameterValues = new ArrayList<Object>(); for (int i = 0; i < this.sqlParameterNames.size(); i++) { parameterName = this.sqlParameterNames.get(i); if (valuesMap.containsKey(parameterName) == true) { this.sqlParameterValues.add(valuesMap.get(parameterName)); } else { throw new IllegalArgumentException(String.format(HandlersConstants.ERROR_PARAMETER_NOT_FOUND, parameterName)); } } } } ProcessedInput(String originalSql); ProcessedInput(ProcessedInput processedInput); ProcessedInput(String originalSql, String parsedSql, List<String> sqlParameterNames, List<int[]> sqlParameterBoundaries, List<Object> sqlParameterValues, List<String> sqlParameterTypes, List<String> sqlParameterDirections); ProcessedInput(String originalSql, String parsedSql, List<String> sqlParameterNames, List<int[]> sqlParameterBoundaries, List<Object> sqlParameterValues); void addParameter(String parameterName, int parameterStart, int parameterEnd, String parameterType, String parameterDirection); void addParameter(String parameterName, int parameterStart, int parameterEnd); String getOriginalSql(); String getParsedSql(); List<String> getSqlParameterNames(); List<int[]> getSqlParameterBoundaries(); List<Object> getSqlParameterValues(); List<String> getSqlParameterTypes(); List<String> getSqlParameterDirections(); void setParsedSql(String parsedSql); void setSqlParameterValues(List<Object> sqlParameterValues); Integer getPosition(String parameterName); String getParameterName(Integer position); Integer getAmountOfParameters(); boolean isFilled(); void fillParameterValues(Map<String, Object> valuesMap); } | @Test public void testFillParameterValues() throws Exception { ProcessedInput processedInput = new ProcessedInput("a"); processedInput.addParameter("name", 1, 2); processedInput.addParameter("origin", 3, 4); processedInput.addParameter("strength", 5, 6); org.junit.Assert.assertArrayEquals(new Object[0], processedInput.getSqlParameterValues().toArray()); Map<String, Object> superMap = new HashMap<String, Object>(); superMap.put("name", "superman"); superMap.put("origin", "krypton"); superMap.put("strength", 100); superMap.put("something_unneeded", 0); Assert.assertEquals(3, processedInput.getAmountOfParameters().intValue()); processedInput.fillParameterValues(superMap); Assert.assertEquals(3, processedInput.getAmountOfParameters().intValue()); org.junit.Assert.assertArrayEquals(new Object[]{superMap.get("name"), superMap.get("origin"), superMap.get("strength")}, processedInput.getSqlParameterValues().toArray()); } |
EmptyTypeHandler implements TypeHandler { public QueryParameters processInput(Statement stmt, QueryParameters params) { return params; } EmptyTypeHandler(Overrider overrider); QueryParameters processInput(Statement stmt, QueryParameters params); void afterExecute(Statement stmt, QueryParameters processedInput, QueryParameters params); List<QueryParameters> processOutput(Statement stmt, List<QueryParameters> paramsList); QueryParameters processOutput(Statement stmt, QueryParameters params); } | @Test public void testProcessInput() throws Exception { new EmptyTypeHandler(new Overrider()).processInput(stmt, params); MappingUtils.invokeFunction(verify(conn, never()), "createBlob", new Class[]{}, new Object[]{}); MappingUtils.invokeFunction(verify(conn, never()), "createClob", new Class[]{}, new Object[]{}); MappingUtils.invokeFunction(verify(conn, never()), "createSQLXML", new Class[]{}, new Object[]{}); MappingUtils.invokeFunction(verify(conn, never()), "createArrayOf", new Class[]{String.class, Object[].class}, new Object[]{any(String.class), any(Object[].class)}); verify(blob, never()).setBinaryStream(1); verify(clob, never()).setAsciiStream(1); MappingUtils.invokeFunction(verify(sqlXml, never()), "setBinaryStream", new Class[]{}, new Object[]{}); } |
EmptyTypeHandler implements TypeHandler { public void afterExecute(Statement stmt, QueryParameters processedInput, QueryParameters params) { } EmptyTypeHandler(Overrider overrider); QueryParameters processInput(Statement stmt, QueryParameters params); void afterExecute(Statement stmt, QueryParameters processedInput, QueryParameters params); List<QueryParameters> processOutput(Statement stmt, List<QueryParameters> paramsList); QueryParameters processOutput(Statement stmt, QueryParameters params); } | @Test public void testAfterExecute() throws Exception { QueryParameters processedParams = new QueryParameters(params); processedParams.set("array_list", processedParams.getValue("array")); processedParams.set("blob_byte", processedParams.getValue("blob")); processedParams.set("clob_byte", processedParams.getValue("clob")); processedParams.set("sqlXml_byte", processedParams.getValue("sqlXml")); new EmptyTypeHandler(new Overrider()).afterExecute(stmt, processedParams, params); MappingUtils.invokeFunction(verify(array, never()), "free", new Class[]{}, new Object[]{}); MappingUtils.invokeFunction(verify(blob, never()), "free", new Class[]{}, new Object[]{}); MappingUtils.invokeFunction(verify(clob, never()), "free", new Class[]{}, new Object[]{}); MappingUtils.invokeFunction(verify(sqlXml, never()), "free", new Class[]{}, new Object[]{}); } |
EmptyTypeHandler implements TypeHandler { public List<QueryParameters> processOutput(Statement stmt, List<QueryParameters> paramsList) { return paramsList; } EmptyTypeHandler(Overrider overrider); QueryParameters processInput(Statement stmt, QueryParameters params); void afterExecute(Statement stmt, QueryParameters processedInput, QueryParameters params); List<QueryParameters> processOutput(Statement stmt, List<QueryParameters> paramsList); QueryParameters processOutput(Statement stmt, QueryParameters params); } | @Test public void testProcessOutput() throws Exception { new EmptyTypeHandler(new Overrider()).processOutput(stmt, params); verify(array, never()).getArray(); verify(blob, never()).getBinaryStream(); verify(clob, never()).getAsciiStream(); MappingUtils.invokeFunction(verify(sqlXml, never()), "getBinaryStream", new Class[]{}, new Object[]{}); }
@Test public void testProcessOutputList() throws Exception { List<QueryParameters> paramsList = new ArrayList<QueryParameters>(); QueryParameters paramsClone = new QueryParameters(params); paramsList.add(new QueryParameters()); paramsList.add(params); paramsList.add(paramsClone); new EmptyTypeHandler(new Overrider()).processOutput(stmt, paramsList); verify(array, never()).getArray(); verify(blob, never()).getBinaryStream(); verify(clob, never()).getAsciiStream(); MappingUtils.invokeFunction(verify(sqlXml, never()), "getBinaryStream", new Class[]{}, new Object[]{}); } |
TypeHandlerUtils { public static Object convertArray(Connection conn, Object[] array) throws SQLException { Object result = null; result = createArrayOf(conn, convertJavaClassToSqlType(array.getClass().getComponentType().getSimpleName()), array); return result; } static Object convertArray(Connection conn, Object[] array); static Object convertArray(Connection conn, Collection<?> array); static Object convertBlob(Connection conn, byte[] value); static Object convertBlob(Connection conn, InputStream input); static Object convertBlob(Connection conn, String value); static Object convertBlob(Object blob, byte[] value); static Object convertBlob(Object blob, InputStream input); static Object convertBlob(Object blob, String value); static Object convertClob(Connection conn, byte[] value); static Object convertClob(Connection conn, String value); static Object convertClob(Connection conn, InputStream input); static Object convertClob(Object clob, byte[] value); static Object convertClob(Object clob, String value); static Object convertClob(Object clob, InputStream input); static String convertJavaClassToSqlType(String simpleClassName); static Object convertSqlXml(Connection conn, byte[] value); static Object convertSqlXml(Connection conn, String value); static Object convertSqlXml(Connection conn, InputStream input); static Object convertSqlXml(Object sqlXml, byte[] value); static Object convertSqlXml(Object sqlXml, String value); static Object convertSqlXml(Object sqlXml, InputStream input); static byte[] readBlob(Object blob, boolean close); static byte[] readBlob(Object blob); static byte[] readClob(Object clob, boolean close); static byte[] readClob(Object clob); static byte[] readSqlXml(Object sqlXml, boolean close); static byte[] readSqlXml(Object sqlXml); static byte[] toByteArray(InputStream input); static String toString(Reader reader); static void closeQuietly(InputStream input); static void closeQuietly(OutputStream output); static long copy(InputStream input, OutputStream output); static long copy(Reader input, StringBuilder output); static Object createBlob(Connection conn); static Object createClob(Connection conn); static Object createSQLXML(Connection conn); static Object createArrayOf(Connection conn, String typeName, Object[] elements); static boolean isJDBC3(Overrider overrider); } | @Test public void testConvertArrayArray() throws Exception { Object[] array = new String[]{"Sun"}; TypeHandlerUtils.convertArray(conn, array); MappingUtils.invokeFunction(verify(conn, times(1)), "createArrayOf", new Class[]{String.class, Object[].class}, new Object[]{"VARCHAR", array}); }
@Test public void testConvertArrayCollection() throws Exception { Object[] array = new String[]{"Venus"}; TypeHandlerUtils.convertArray(conn, Arrays.asList(array)); MappingUtils.invokeFunction(verify(conn, times(1)), "createArrayOf", new Class[]{String.class, Object[].class}, new Object[]{"VARCHAR", array}); } |
TypeHandlerUtils { public static Object convertBlob(Connection conn, byte[] value) throws SQLException { Object result = createBlob(conn); result = convertBlob(result, value); return result; } static Object convertArray(Connection conn, Object[] array); static Object convertArray(Connection conn, Collection<?> array); static Object convertBlob(Connection conn, byte[] value); static Object convertBlob(Connection conn, InputStream input); static Object convertBlob(Connection conn, String value); static Object convertBlob(Object blob, byte[] value); static Object convertBlob(Object blob, InputStream input); static Object convertBlob(Object blob, String value); static Object convertClob(Connection conn, byte[] value); static Object convertClob(Connection conn, String value); static Object convertClob(Connection conn, InputStream input); static Object convertClob(Object clob, byte[] value); static Object convertClob(Object clob, String value); static Object convertClob(Object clob, InputStream input); static String convertJavaClassToSqlType(String simpleClassName); static Object convertSqlXml(Connection conn, byte[] value); static Object convertSqlXml(Connection conn, String value); static Object convertSqlXml(Connection conn, InputStream input); static Object convertSqlXml(Object sqlXml, byte[] value); static Object convertSqlXml(Object sqlXml, String value); static Object convertSqlXml(Object sqlXml, InputStream input); static byte[] readBlob(Object blob, boolean close); static byte[] readBlob(Object blob); static byte[] readClob(Object clob, boolean close); static byte[] readClob(Object clob); static byte[] readSqlXml(Object sqlXml, boolean close); static byte[] readSqlXml(Object sqlXml); static byte[] toByteArray(InputStream input); static String toString(Reader reader); static void closeQuietly(InputStream input); static void closeQuietly(OutputStream output); static long copy(InputStream input, OutputStream output); static long copy(Reader input, StringBuilder output); static Object createBlob(Connection conn); static Object createClob(Connection conn); static Object createSQLXML(Connection conn); static Object createArrayOf(Connection conn, String typeName, Object[] elements); static boolean isJDBC3(Overrider overrider); } | @Test public void testConvertBlobConnByte() throws Exception { testConvertBlobPrepare(); TypeHandlerUtils.convertBlob(conn, "GIF".getBytes()); MappingUtils.invokeFunction(verify(conn, times(1)), "createBlob", new Class[]{}, new Object[]{}); testConvertBlobCheck(); }
@Test public void testConvertBlobConnInputStream() throws Exception { testConvertBlobPrepare(); TypeHandlerUtils.convertBlob(conn, new ByteArrayInputStream("BMP".getBytes())); MappingUtils.invokeFunction(verify(conn, times(1)), "createBlob", new Class[]{}, new Object[]{}); testConvertBlobCheck(); }
@Test public void testConvertBlobConnString() throws Exception { testConvertBlobPrepare(); TypeHandlerUtils.convertBlob(conn, "PCX"); MappingUtils.invokeFunction(verify(conn, times(1)), "createBlob", new Class[]{}, new Object[]{}); testConvertBlobCheck(); }
@Test public void testConvertBlobByte() throws Exception { testConvertBlobPrepare(); TypeHandlerUtils.convertBlob(blob, "JPEG".getBytes()); testConvertBlobCheck(); }
@Test public void testConvertBlobInputStream() throws Exception { testConvertBlobPrepare(); TypeHandlerUtils.convertBlob(blob, new ByteArrayInputStream("PNG".getBytes())); testConvertBlobCheck(); }
@Test public void testConvertBlobString() throws Exception { testConvertBlobPrepare(); TypeHandlerUtils.convertBlob(blob, "TIFF"); testConvertBlobCheck(); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.