method2testcases
stringlengths 118
6.63k
|
---|
### Question:
AuthenticationFacadeImpl implements AuthenticationFacade { @Override public void setAuthentication(final Authentication authentication) { SecurityContextHolder.getContext().setAuthentication(authentication); } @Override Authentication getAuthentication(); @Override void setAuthentication(final Authentication authentication); }### Answer:
@Test public void setAuthentication() { SecurityContextHolder.clearContext(); authFacade.setAuthentication(auth); final Authentication realAuthInfo = SecurityContextHolder.getContext().getAuthentication(); final Authentication facadeAuthInfo = authFacade.getAuthentication(); assertEquals("(setAuthentication)The \"principal\" set in the authentication in the facade context " + "does not match the \"principal\" set in the authentication in the real context", realAuthInfo.getPrincipal(), facadeAuthInfo.getPrincipal()); assertEquals("(setAuthentication)The \"authorities\" set in the authentication in the facade context " + "does not match the \"authorities\" set in the authentication in the real context", realAuthInfo.getAuthorities(), facadeAuthInfo.getAuthorities()); assertEquals("(setAuthentication)The \"credentials\" set in the authentication in the facade context " + "does not match the \"credentials\" set in the authentication in the real context", realAuthInfo.getCredentials(), facadeAuthInfo.getCredentials()); } |
### Question:
JWTService { public long getATokenExpirationTime() { return sc.getATokenExpirationTime() > 0 ? (sc.getATokenExpirationTime() * THOUSAND) : DEFAULT_ACCESS_TOKEN_EXPIRATION_TIME; } long getATokenExpirationTime(); long getRTokenExpirationTime(); String createToken(final String subject); String createToken(final String subject, final long expiresIn); String createToken(final String subject, final String authorities); String createRefreshToken(final String subject, final String authorities); String createToken(final String subject, final String authorities, final long expiresIn); Map<String, Object> getClaims(final String claimsJwt, final String... key); Map<String, Object> createLoginData(final String subject, final String accessToken, final Date issuedAt,
final String authoritiesString, final String refreshToken); Map<String, Object> getClaimsExtended(final String claimsJwt, final String... key); static final String AUDIENCE; static final String EXPIRATION; static final String ID; static final String ISSUED_AT; static final String ISSUER; static final String NOT_BEFORE; static final String SUBJECT; static final long DEFAULT_ACCESS_TOKEN_EXPIRATION_TIME; static final long DEFAULT_REFRESH_TOKEN_EXPIRATION_TIME; }### Answer:
@Test public void getATokenExpirationTime() { final Object aTokenExpirationTime = ReflectionTestUtils.getField(sc, "aTokenExpirationTime"); long prev = aTokenExpirationTime != null ? Long.parseLong(aTokenExpirationTime.toString()) : -1; final long expTime = -10; ReflectionTestUtils.setField(sc, "aTokenExpirationTime", expTime); assertTrue("Expiration time for access token must be greater than zero", jwtService.getATokenExpirationTime() > 0); ReflectionTestUtils.setField(sc, "aTokenExpirationTime", prev); } |
### Question:
JWTService { public long getRTokenExpirationTime() { return sc.getRTokenExpirationTime() > 0 ? (sc.getRTokenExpirationTime() * THOUSAND) : DEFAULT_REFRESH_TOKEN_EXPIRATION_TIME; } long getATokenExpirationTime(); long getRTokenExpirationTime(); String createToken(final String subject); String createToken(final String subject, final long expiresIn); String createToken(final String subject, final String authorities); String createRefreshToken(final String subject, final String authorities); String createToken(final String subject, final String authorities, final long expiresIn); Map<String, Object> getClaims(final String claimsJwt, final String... key); Map<String, Object> createLoginData(final String subject, final String accessToken, final Date issuedAt,
final String authoritiesString, final String refreshToken); Map<String, Object> getClaimsExtended(final String claimsJwt, final String... key); static final String AUDIENCE; static final String EXPIRATION; static final String ID; static final String ISSUED_AT; static final String ISSUER; static final String NOT_BEFORE; static final String SUBJECT; static final long DEFAULT_ACCESS_TOKEN_EXPIRATION_TIME; static final long DEFAULT_REFRESH_TOKEN_EXPIRATION_TIME; }### Answer:
@Test public void getRTokenExpirationTime() { long prev = Long.parseLong(String.valueOf(ReflectionTestUtils.getField(sc, "rTokenExpirationTime"))); final long expTime = -10; ReflectionTestUtils.setField(sc, "rTokenExpirationTime", expTime); assertTrue("Expiration time for refresh token must be greater than zero", jwtService.getRTokenExpirationTime() > 0); ReflectionTestUtils.setField(sc, "rTokenExpirationTime", prev); } |
### Question:
JWTService { public String createToken(final String subject) { return getBuilder(subject).compact(); } long getATokenExpirationTime(); long getRTokenExpirationTime(); String createToken(final String subject); String createToken(final String subject, final long expiresIn); String createToken(final String subject, final String authorities); String createRefreshToken(final String subject, final String authorities); String createToken(final String subject, final String authorities, final long expiresIn); Map<String, Object> getClaims(final String claimsJwt, final String... key); Map<String, Object> createLoginData(final String subject, final String accessToken, final Date issuedAt,
final String authoritiesString, final String refreshToken); Map<String, Object> getClaimsExtended(final String claimsJwt, final String... key); static final String AUDIENCE; static final String EXPIRATION; static final String ID; static final String ISSUED_AT; static final String ISSUER; static final String NOT_BEFORE; static final String SUBJECT; static final long DEFAULT_ACCESS_TOKEN_EXPIRATION_TIME; static final long DEFAULT_REFRESH_TOKEN_EXPIRATION_TIME; }### Answer:
@Test public void createTwoTokensWithSubjectAreNotEqual() { final String sub = "TestSubjectBN"; final String token1 = jwtService.createToken(sub); final String token2 = jwtService.createToken(sub); assertNotEquals("The JWTService#createToken(String subject) method never should create two tokens " + "which are equals", token1, token2); }
@Test public void createTwoTokensWithSubjectAndExpAreNotEqual() { final String sub = "TestSubjectCV"; final long exp = 123; final String token1 = jwtService.createToken(sub, exp); final String token2 = jwtService.createToken(sub, exp); assertNotEquals("The JWTService#createToken(String subject, long expiresIn) method never should " + "create two tokens which are equals", token1, token2); }
@Test public void createTwoTokensWithSubjectAndAuthAreNotEqual() { final String sub = "TestSubjectRF"; final String auth = "ROLE_WS;ROLE_RF"; final String token1 = jwtService.createToken(sub, auth); final String token2 = jwtService.createToken(sub, auth); assertNotEquals("The JWTService#createToken(String subject, String authorities) method never should " + "create two tokens which are equals", token1, token2); }
@Test public void createTwoTokensWithSubjectAuthAndExpAreNotEqual() { final String sub = "TestSubjectBN"; final String auth = "ROLE_GT;ROLE_DE"; final long exp = 123; final String token1 = jwtService.createToken(sub, auth, exp); final String token2 = jwtService.createToken(sub, auth, exp); assertNotEquals("The JWTService#createToken(String subject, String authorities, long expiresIn) " + "method never should create two tokens which are equals", token1, token2); } |
### Question:
JWTService { public String createRefreshToken(final String subject, final String authorities) { return getBuilder(subject, authorities, getRTokenExpirationTime()).compact(); } long getATokenExpirationTime(); long getRTokenExpirationTime(); String createToken(final String subject); String createToken(final String subject, final long expiresIn); String createToken(final String subject, final String authorities); String createRefreshToken(final String subject, final String authorities); String createToken(final String subject, final String authorities, final long expiresIn); Map<String, Object> getClaims(final String claimsJwt, final String... key); Map<String, Object> createLoginData(final String subject, final String accessToken, final Date issuedAt,
final String authoritiesString, final String refreshToken); Map<String, Object> getClaimsExtended(final String claimsJwt, final String... key); static final String AUDIENCE; static final String EXPIRATION; static final String ID; static final String ISSUED_AT; static final String ISSUER; static final String NOT_BEFORE; static final String SUBJECT; static final long DEFAULT_ACCESS_TOKEN_EXPIRATION_TIME; static final long DEFAULT_REFRESH_TOKEN_EXPIRATION_TIME; }### Answer:
@Test public void createTwoRefreshTokensWithSubjectAndAuthAreNotEqual() { final String sub = "TestSubjectG"; final String auth = "ROLE_N;ROLE_C"; final String token1 = jwtService.createRefreshToken(sub, auth); final String token2 = jwtService.createRefreshToken(sub, auth); assertNotEquals("The JWTService#createRefreshToken(String subject, String authorities) method never " + "should create two tokens which are equals", token1, token2); } |
### Question:
JWTService { public Map<String, Object> getClaims(final String claimsJwt, final String... key) { Map<String, Object> r = new HashMap<>(); processClaimsJWT(claimsJwt, r, key); return r; } long getATokenExpirationTime(); long getRTokenExpirationTime(); String createToken(final String subject); String createToken(final String subject, final long expiresIn); String createToken(final String subject, final String authorities); String createRefreshToken(final String subject, final String authorities); String createToken(final String subject, final String authorities, final long expiresIn); Map<String, Object> getClaims(final String claimsJwt, final String... key); Map<String, Object> createLoginData(final String subject, final String accessToken, final Date issuedAt,
final String authoritiesString, final String refreshToken); Map<String, Object> getClaimsExtended(final String claimsJwt, final String... key); static final String AUDIENCE; static final String EXPIRATION; static final String ID; static final String ISSUED_AT; static final String ISSUER; static final String NOT_BEFORE; static final String SUBJECT; static final long DEFAULT_ACCESS_TOKEN_EXPIRATION_TIME; static final long DEFAULT_REFRESH_TOKEN_EXPIRATION_TIME; }### Answer:
@Test public void getClaims() { final String sub = "TestSubjectX"; final String auth = "ROLE_1;ROLE_2"; final String token = jwtService.createToken(sub, auth); final Map<String, Object> claims = jwtService.getClaims(token, JWTService.SUBJECT, sc.getAuthoritiesHolder(), JWTService.EXPIRATION); assertClaimsState(claims, sub, auth); } |
### Question:
JWTService { public Map<String, Object> getClaimsExtended(final String claimsJwt, final String... key) { Map<String, Object> r = new HashMap<>(); Claims claims = processClaimsJWT(claimsJwt, r, key); r.put(AUDIENCE, claims.getAudience()); r.put(EXPIRATION, claims.getExpiration()); r.put(ID, claims.getId()); r.put(ISSUED_AT, claims.getIssuedAt()); r.put(ISSUER, claims.getIssuer()); r.put(NOT_BEFORE, claims.getNotBefore()); r.put(SUBJECT, claims.getSubject()); return r; } long getATokenExpirationTime(); long getRTokenExpirationTime(); String createToken(final String subject); String createToken(final String subject, final long expiresIn); String createToken(final String subject, final String authorities); String createRefreshToken(final String subject, final String authorities); String createToken(final String subject, final String authorities, final long expiresIn); Map<String, Object> getClaims(final String claimsJwt, final String... key); Map<String, Object> createLoginData(final String subject, final String accessToken, final Date issuedAt,
final String authoritiesString, final String refreshToken); Map<String, Object> getClaimsExtended(final String claimsJwt, final String... key); static final String AUDIENCE; static final String EXPIRATION; static final String ID; static final String ISSUED_AT; static final String ISSUER; static final String NOT_BEFORE; static final String SUBJECT; static final long DEFAULT_ACCESS_TOKEN_EXPIRATION_TIME; static final long DEFAULT_REFRESH_TOKEN_EXPIRATION_TIME; }### Answer:
@Test public void getClaimsExtended() { final String sub = "TestSubjectY"; final String auth = "ROLE_X;ROLE_Y"; final long expiresIn = 99999999; final String token = jwtService.createToken(sub, auth, expiresIn); final String randomKey = "randomKey"; final Map<String, Object> claims = jwtService.getClaimsExtended(token, randomKey, sc.getAuthoritiesHolder()); assertClaimsState(claims, sub, auth); assertNull("Claims contains an incorrect pair key-value", claims.get(randomKey)); assertNotNull("Expiration time is null", claims.get(JWTService.EXPIRATION)); assertTrue("Expiration time is not an instance of Date", claims.get(JWTService.EXPIRATION) instanceof Date); if (claims.get(JWTService.EXPIRATION) != null && claims.get(JWTService.EXPIRATION) instanceof Date) { assertTrue("Expiration time is not greater than the creation time of the token", ((Date) claims.get(JWTService.EXPIRATION)).getTime() > expiresIn); } } |
### Question:
SecurityConst { public String[] getFreeURLsAnyRequest() { return freeURLsAnyRequest.split(";"); } String[] getFreeURLsAnyRequest(); String[] getFreeURLsGetRequest(); String[] getFreeURLsPostRequest(); static final String AUTHORITIES_SEPARATOR; static final String ACCESS_TOKEN_URL; static final String USERNAME_HOLDER; static final String USERNAME_REGEXP; }### Answer:
@Test public void getFreeURLsAnyRequest() { assertArrayEquals(autowiredSc.getFreeURLsAnyRequest(), freeURLsAnyRequestBind.split(SEPARATOR)); } |
### Question:
ConfigurationController { @GetMapping("sign-up") public boolean isUserRegistrationAllowed() { return configService.isUserRegistrationAllowed(); } @GetMapping("sign-up") boolean isUserRegistrationAllowed(); @GetMapping("multientity") boolean isMultiEntity(); @GetMapping Object getConfig(@RequestParam(value = "key", required = false) final String key,
@RequestParam(value = "id", required = false) final Long id); @GetMapping("{id}") Map<String, Object> getConfigByUser(@PathVariable(value = "id") final Long id); @RequestMapping(method = {RequestMethod.POST, RequestMethod.PUT}) @ResponseStatus(HttpStatus.NO_CONTENT) void saveConfig(@RequestBody final Map<String, Object> configs); }### Answer:
@Test public void isUserRegistrationAllowed() throws Exception { mvc.perform( get(apiPrefix + "/" + REQ_STRING + "/sign-up") .header(authHeader, tokenType + " " + accessToken) .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) ).andExpect(status().isOk()); } |
### Question:
ConfigurationController { @GetMapping("multientity") public boolean isMultiEntity() { return configService.isMultiEntity(); } @GetMapping("sign-up") boolean isUserRegistrationAllowed(); @GetMapping("multientity") boolean isMultiEntity(); @GetMapping Object getConfig(@RequestParam(value = "key", required = false) final String key,
@RequestParam(value = "id", required = false) final Long id); @GetMapping("{id}") Map<String, Object> getConfigByUser(@PathVariable(value = "id") final Long id); @RequestMapping(method = {RequestMethod.POST, RequestMethod.PUT}) @ResponseStatus(HttpStatus.NO_CONTENT) void saveConfig(@RequestBody final Map<String, Object> configs); }### Answer:
@Test public void isMultiEntity() throws Exception { mvc.perform( get(apiPrefix + "/" + REQ_STRING + "/multientity") .header(authHeader, tokenType + " " + accessToken) .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) ).andExpect(status().isOk()); } |
### Question:
RestOwnedEntityController { @PostMapping(path = ResourcePath.OWNED_ENTITY, produces = "application/hal+json") @ResponseStatus(HttpStatus.CREATED) public ResponseEntity<EOwnedEntity> create(@Valid @RequestBody final Resource<EOwnedEntity> entity) throws GmsGeneralException { EOwnedEntity e = entityService.create(entity.getContent()); if (e != null) { return new ResponseEntity<>(HttpStatus.CREATED); } else { throw GmsGeneralException.builder().messageI18N("entity.add.error").finishedOK(false).build(); } } @PostMapping(path = ResourcePath.OWNED_ENTITY, produces = "application/hal+json") @ResponseStatus(HttpStatus.CREATED) ResponseEntity<EOwnedEntity> create(@Valid @RequestBody final Resource<EOwnedEntity> entity); }### Answer:
@Test public void create() throws Exception { final boolean multiEntity = configService.isMultiEntity(); if (!multiEntity) { configService.setIsMultiEntity(true); } EOwnedEntity e = EntityUtil.getSampleEntity(random.nextString()); ConstrainedFields fields = new ConstrainedFields(EOwnedEntity.class); mvc.perform(post(apiPrefix + "/" + REQ_STRING) .contentType(MediaType.APPLICATION_JSON) .header(authHeader, tokenType + " " + accessToken) .content(objectMapper.writeValueAsString(e))) .andExpect(status().isCreated()) .andDo(restDocResHandler.document( requestFields( fields.withPath("name") .description("Natural name which is used commonly for referring to the entity"), fields.withPath("username") .description("A unique string representation of the {@LINK #name}. Useful " + "when there are other entities with the same {@LINK #name}"), fields.withPath("description") .description("A brief description of the entity") ) )); if (!multiEntity) { configService.setIsMultiEntity(false); } } |
### Question:
SecurityController { @PostMapping(SecurityConst.ACCESS_TOKEN_URL) public Map<String, Object> refreshToken(@Valid @RequestBody final RefreshTokenPayload payload) { String oldRefreshToken = payload.getRefreshToken(); if (oldRefreshToken != null) { try { String[] keys = {sc.getAuthoritiesHolder()}; Map<String, Object> claims = jwtService.getClaimsExtended(oldRefreshToken, keys); String sub = claims.get(JWTService.SUBJECT).toString(); String authorities = claims.get(keys[0]).toString(); Date iat = (Date) claims.get(JWTService.ISSUED_AT); String newAccessToken = jwtService.createToken(sub, authorities); String newRefreshToken = jwtService.createRefreshToken(sub, authorities); return jwtService.createLoginData(sub, newAccessToken, iat, authorities, newRefreshToken); } catch (JwtException e) { throw new GmsSecurityException(SecurityConst.ACCESS_TOKEN_URL, "security.token.refresh.invalid"); } } throw new GmsSecurityException(SecurityConst.ACCESS_TOKEN_URL, "security.token.refresh.required"); } @PostMapping("${gms.security.sign_up_url}") @ResponseStatus(HttpStatus.CREATED) @ResponseBody ResponseEntity<EUser> signUpUser(@RequestBody @Valid final Resource<? extends EUser> user); @PostMapping(SecurityConst.ACCESS_TOKEN_URL) Map<String, Object> refreshToken(@Valid @RequestBody final RefreshTokenPayload payload); }### Answer:
@Test public void refreshToken() throws Exception { final RefreshTokenPayload payload = new RefreshTokenPayload(refreshToken); final ConstrainedFields fields = new ConstrainedFields(RefreshTokenPayload.class); mvc.perform( post(apiPrefix + "/" + SecurityConst.ACCESS_TOKEN_URL).contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(payload)) ).andExpect(status().isOk()) .andDo( restDocResHandler.document( requestFields( fields.withPath("refreshToken") .description("The refresh token provided when login was " + "previously performed") ) ) ); } |
### Question:
EUser extends GmsEntity implements UserDetails { @Override public Collection<? extends GrantedAuthority> getAuthorities() { return authorities != null ? Collections.unmodifiableCollection(authorities) : null; } EUser(final String username, final String email, final String name, final String lastName,
final String password); @Override Collection<? extends GrantedAuthority> getAuthorities(); @Override boolean isAccountNonExpired(); @Override boolean isAccountNonLocked(); @Override boolean isCredentialsNonExpired(); @Override boolean isEnabled(); boolean isEmailVerified(); }### Answer:
@Test public void getAuthorities() { cleanEntity0(); ReflectionTestUtils.setField(entity0, "authorities", authoritiesS); assertArrayEquals(entity0.getAuthorities().toArray(), authoritiesS.toArray()); } |
### Question:
EUser extends GmsEntity implements UserDetails { @Override public boolean isAccountNonExpired() { return accountNonExpired == null || accountNonExpired; } EUser(final String username, final String email, final String name, final String lastName,
final String password); @Override Collection<? extends GrantedAuthority> getAuthorities(); @Override boolean isAccountNonExpired(); @Override boolean isAccountNonLocked(); @Override boolean isCredentialsNonExpired(); @Override boolean isEnabled(); boolean isEmailVerified(); }### Answer:
@Test public void isAccountNonExpired() { cleanEntity0(); ReflectionTestUtils.setField(entity0, "accountNonExpired", accountNonExpiredS); assertEquals(entity0.isAccountNonExpired(), accountNonExpiredS); } |
### Question:
EUser extends GmsEntity implements UserDetails { @Override public boolean isAccountNonLocked() { return accountNonLocked == null || accountNonLocked; } EUser(final String username, final String email, final String name, final String lastName,
final String password); @Override Collection<? extends GrantedAuthority> getAuthorities(); @Override boolean isAccountNonExpired(); @Override boolean isAccountNonLocked(); @Override boolean isCredentialsNonExpired(); @Override boolean isEnabled(); boolean isEmailVerified(); }### Answer:
@Test public void isAccountNonLocked() { cleanEntity0(); ReflectionTestUtils.setField(entity0, "accountNonLocked", accountNonLockedS); assertEquals(entity0.isAccountNonLocked(), accountNonLockedS); } |
### Question:
EUser extends GmsEntity implements UserDetails { @Override public boolean isCredentialsNonExpired() { return credentialsNonExpired == null || credentialsNonExpired; } EUser(final String username, final String email, final String name, final String lastName,
final String password); @Override Collection<? extends GrantedAuthority> getAuthorities(); @Override boolean isAccountNonExpired(); @Override boolean isAccountNonLocked(); @Override boolean isCredentialsNonExpired(); @Override boolean isEnabled(); boolean isEmailVerified(); }### Answer:
@Test public void isCredentialsNonExpired() { cleanEntity0(); ReflectionTestUtils.setField(entity0, "credentialsNonExpired", credentialsNonExpiredS); assertEquals(entity0.isCredentialsNonExpired(), credentialsNonExpiredS); } |
### Question:
EUser extends GmsEntity implements UserDetails { @Override public boolean isEnabled() { return enabled != null && enabled; } EUser(final String username, final String email, final String name, final String lastName,
final String password); @Override Collection<? extends GrantedAuthority> getAuthorities(); @Override boolean isAccountNonExpired(); @Override boolean isAccountNonLocked(); @Override boolean isCredentialsNonExpired(); @Override boolean isEnabled(); boolean isEmailVerified(); }### Answer:
@Test public void isEnabled() { cleanEntity0(); ReflectionTestUtils.setField(entity0, "enabled", enabledS); assertEquals(entity0.isEnabled(), enabledS); } |
### Question:
EUser extends GmsEntity implements UserDetails { public boolean isEmailVerified() { return emailVerified != null && emailVerified; } EUser(final String username, final String email, final String name, final String lastName,
final String password); @Override Collection<? extends GrantedAuthority> getAuthorities(); @Override boolean isAccountNonExpired(); @Override boolean isAccountNonLocked(); @Override boolean isCredentialsNonExpired(); @Override boolean isEnabled(); boolean isEmailVerified(); }### Answer:
@Test public void isEmailVerified() { cleanEntity0(); ReflectionTestUtils.setField(entity0, "emailVerified", emailVerifiedS); assertEquals(entity0.isEmailVerified(), emailVerifiedS); } |
### Question:
SecurityConst { public String[] getFreeURLsGetRequest() { return freeURLsGetRequest.split(";"); } String[] getFreeURLsAnyRequest(); String[] getFreeURLsGetRequest(); String[] getFreeURLsPostRequest(); static final String AUTHORITIES_SEPARATOR; static final String ACCESS_TOKEN_URL; static final String USERNAME_HOLDER; static final String USERNAME_REGEXP; }### Answer:
@Test public void getFreeURLsGetRequest() { assertArrayEquals(autowiredSc.getFreeURLsGetRequest(), freeURLsGetRequestBind.split(SEPARATOR)); } |
### Question:
BRole extends GmsEntity { public void addPermission(final BPermission... p) { if (permissions == null) { permissions = new HashSet<>(); } permissions.addAll(Arrays.asList(p)); } void addPermission(final BPermission... p); void removePermission(final BPermission... p); void removeAllPermissions(); }### Answer:
@Test public void addPermission() { cleanEntity0(); entity0.addPermission(sampleP); final Collection<?> permissions = (HashSet<?>) ReflectionTestUtils.getField(entity0, "permissions"); assertTrue(permissions != null && permissions.contains(sampleP)); } |
### Question:
BRole extends GmsEntity { public void removePermission(final BPermission... p) { if (permissions != null) { for (BPermission iP : p) { permissions.remove(iP); } } } void addPermission(final BPermission... p); void removePermission(final BPermission... p); void removeAllPermissions(); }### Answer:
@Test public void removePermission() { Collection<BPermission> auxP = new HashSet<>(); auxP.add(sampleP); cleanEntity0(); ReflectionTestUtils.setField(entity0, "permissions", auxP); Collection<?> permissions = (HashSet<?>) ReflectionTestUtils.getField(entity0, "permissions"); assertTrue(permissions != null && permissions.contains(sampleP)); entity0.removePermission(sampleP); permissions = (HashSet<?>) ReflectionTestUtils.getField(entity0, "permissions"); assertTrue(permissions != null && !permissions.contains(sampleP)); } |
### Question:
Application extends SpringBootServletInitializer { public static void main(final String[] args) { SpringApplication.run(Application.class, args); GMS_LOGGER.info("Application is running..."); } static void main(final String[] args); @Bean CommandLineRunner commandLineRunner(final AppService appService); @Bean BCryptPasswordEncoder bCryptPasswordEncoder(); @Bean ErrorPageRegistrar errorPageRegistrar(); }### Answer:
@Test public void mainTest() { Runnable runnable = () -> Application.main(noArgs); Thread thread = new Thread(runnable); thread.start(); } |
### Question:
Application extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(final SpringApplicationBuilder builder) { return builder.sources(Application.class); } static void main(final String[] args); @Bean CommandLineRunner commandLineRunner(final AppService appService); @Bean BCryptPasswordEncoder bCryptPasswordEncoder(); @Bean ErrorPageRegistrar errorPageRegistrar(); }### Answer:
@Test public void configureTest() { Application app = new Application(); assertNotNull(app.configure(new SpringApplicationBuilder(Application.class))); } |
### Question:
Application extends SpringBootServletInitializer { @Bean public CommandLineRunner commandLineRunner(final AppService appService) { return strings -> { if (!appService.isInitialLoadOK()) { GMS_LOGGER.error("App did not start properly and probably will fail at some point. Restarting it is " + "highly advisable"); } }; } static void main(final String[] args); @Bean CommandLineRunner commandLineRunner(final AppService appService); @Bean BCryptPasswordEncoder bCryptPasswordEncoder(); @Bean ErrorPageRegistrar errorPageRegistrar(); }### Answer:
@Test public void commandLineRunnerBeanCreationIsOK() { Application app = new Application(); assertNotNull(app.commandLineRunner(appService)); } |
### Question:
Application extends SpringBootServletInitializer { @Bean public BCryptPasswordEncoder bCryptPasswordEncoder() { return new BCryptPasswordEncoder(); } static void main(final String[] args); @Bean CommandLineRunner commandLineRunner(final AppService appService); @Bean BCryptPasswordEncoder bCryptPasswordEncoder(); @Bean ErrorPageRegistrar errorPageRegistrar(); }### Answer:
@Test public void bCryptPasswordEncoderTest() { Application app = new Application(); assertNotNull(app.bCryptPasswordEncoder()); } |
### Question:
SecurityConst { public String[] getFreeURLsPostRequest() { return freeURLsPostRequest.split(";"); } String[] getFreeURLsAnyRequest(); String[] getFreeURLsGetRequest(); String[] getFreeURLsPostRequest(); static final String AUTHORITIES_SEPARATOR; static final String ACCESS_TOKEN_URL; static final String USERNAME_HOLDER; static final String USERNAME_REGEXP; }### Answer:
@Test public void getFreeURLsPostRequest() { assertArrayEquals(autowiredSc.getFreeURLsPostRequest(), freeURLsPostRequestBind.split(SEPARATOR)); } |
### Question:
ReplayingRandom extends Random { @Override public int nextInt(int n) { if (n == 5) { return getNextValueOf(fives, indexInFives++); } else if (n == 9) { return getNextValueOf(nines, indexInNines++); } throw new UnsupportedOperationException("not expected invocation of nextInt(" + n + ")"); } ReplayingRandom(String five, String nine); @Override int nextInt(int n); }### Answer:
@Test public void shouldReturnExpectedRandomsFor5And9() { assertThat(rand.nextInt(5), equalTo(2)); assertThat(rand.nextInt(9), equalTo(3)); assertThat(rand.nextInt(5), equalTo(3)); assertThat(rand.nextInt(9), equalTo(3)); assertThat(rand.nextInt(5), equalTo(3)); assertThat(rand.nextInt(9), equalTo(8)); assertThat(rand.nextInt(5), equalTo(4)); assertThat(rand.nextInt(9), equalTo(2)); }
@Test(expected = UnsupportedOperationException.class) public void shouldFailForOthers() { rand.nextInt(3); } |
### Question:
HttpServletResponseExcelWrite implements OutputStreamDelegate { public static ExcelWrite build(InputStream inputStream, String fileName, HttpServletRequest request, HttpServletResponse response) { Objects.requireNonNull(inputStream); Objects.requireNonNull(fileName); Objects.requireNonNull(request); Objects.requireNonNull(response); return new CopyInputStreamExcelWrite(inputStream, fileName, new HttpServletResponseExcelWrite(request, response)); } private HttpServletResponseExcelWrite(HttpServletRequest request, HttpServletResponse response); @Override OutputStream createOutputStream(String fileName); static ExcelWrite build(InputStream inputStream, String fileName,
HttpServletRequest request, HttpServletResponse response); static ExcelWrite build(String fileName, HttpServletRequest request, HttpServletResponse response); }### Answer:
@Test public void testWriteExcel() { HttpServletResponseExcelWrite.build(fileName, request, response) .deal(ExcelDataList.getTitle(), get(), ExcelDataList.getTenList()) .write(); }
@Test public void testWriteExcelByInputStream() { HttpServletResponseExcelWrite.build(this.getClass().getResourceAsStream("/c.xls"), fileName, request, response) .deal(new WriteDeal<ExcelDto>() { public String[] dealBean(ExcelDto obj) { String[] result = new String[3]; result[0] = obj.getId() + ""; result[1] = obj.getName(); result[2] = obj.getAge() + ""; return result; } public int skipLine() { return 4; } @Override public Map<String, Object> additional() { Map<String, Object> map = new HashMap<>(); map.put("quoteCurrency", "ETH"); map.put("symbol", "USDT_ETH"); map.put("startTime", "2019-01-09 00:00:00"); map.put("endTime", "2019-01-09 12:00:00"); return map; } }, ExcelDataList.getTenList()) .write(); } |
### Question:
SpringProxyUtils { public static boolean isMultipleProxy(Object proxy) { try { ProxyFactory proxyFactory = getProxyFactory(proxy); if (proxyFactory == null) { return false; } ConfigurablePropertyAccessor accessor = PropertyAccessorFactory.forDirectFieldAccess(proxyFactory); TargetSource targetSource = (TargetSource) accessor.getPropertyValue("targetSource"); if (targetSource == null) { return false; } return AopUtils.isAopProxy(targetSource.getTarget()); } catch (Exception e) { throw new IllegalArgumentException("proxy args maybe not proxy " + "with cglib or jdk dynamic proxy. this method not support", e); } } static T getRealTarget(Object proxy); static boolean isMultipleProxy(Object proxy); static ProxyFactory findJdkDynamicProxyFactory(Object proxy); static ProxyFactory findCglibProxyFactory(Object proxy); static boolean isTransactional(Object proxy); static void removeTransactional(Object proxy); static boolean isAsync(Object proxy); static void removeAsync(Object proxy); }### Answer:
@Test public void testIsMultipleProxy() { Bmw bmw = new Bmw(); ProxyFactory proxyFactory1 = new ProxyFactory(); TargetSource targetSource1 = new SingletonTargetSource(bmw); proxyFactory1.setTargetSource(targetSource1); Advisor[] advisors = new Advisor[1]; advisors[0] = advisorAdapterRegistry.wrap(new TestMethodInterceptor()); proxyFactory1.addAdvisors(advisors); Object object = proxyFactory1.getProxy(); ProxyFactory proxyFactory = new ProxyFactory(); TargetSource targetSource = new SingletonTargetSource(object); proxyFactory.setTargetSource(targetSource); Class<?>[] targetInterfaces = ClassUtils.getAllInterfacesForClass(bmw.getClass()); for (Class<?> targetInterface : targetInterfaces) { proxyFactory.addInterface(targetInterface); } advisors[0] = advisorAdapterRegistry.wrap(new TestMethodInterceptor()); proxyFactory.addAdvisors(advisors); Car proxy = (Car) proxyFactory.getProxy(); assertTrue(SpringProxyUtils.isMultipleProxy(proxy)); SpringProxyUtils.getRealTarget(proxy); } |
### Question:
SpringProxyUtils { public static ProxyFactory findJdkDynamicProxyFactory(Object proxy) { InvocationHandler h = Proxy.getInvocationHandler(proxy); ConfigurablePropertyAccessor accessor = PropertyAccessorFactory.forDirectFieldAccess(h); return (ProxyFactory) accessor.getPropertyValue("advised"); } static T getRealTarget(Object proxy); static boolean isMultipleProxy(Object proxy); static ProxyFactory findJdkDynamicProxyFactory(Object proxy); static ProxyFactory findCglibProxyFactory(Object proxy); static boolean isTransactional(Object proxy); static void removeTransactional(Object proxy); static boolean isAsync(Object proxy); static void removeAsync(Object proxy); }### Answer:
@Test public void testFindJdkDynamicProxyFactory() { ProxyFactory proxyFactory = new ProxyFactory(); Bmw bmw = new Bmw(); TargetSource targetSource = new SingletonTargetSource(bmw); proxyFactory.setTargetSource(targetSource); Class<?>[] targetInterfaces = ClassUtils.getAllInterfacesForClass(bmw.getClass()); for (Class<?> targetInterface : targetInterfaces) { proxyFactory.addInterface(targetInterface); } Advisor[] advisors = new Advisor[1]; advisors[0] = advisorAdapterRegistry.wrap(new TestMethodInterceptor()); proxyFactory.addAdvisors(advisors); Car proxy = (Car) proxyFactory.getProxy(); SpringProxyUtils.findJdkDynamicProxyFactory(proxy); } |
### Question:
ServiceLocator implements ApplicationContextAware { public static ApplicationContext getFactory() { Assert.notNull(factory, "没有注入spring factory"); return factory; } static ApplicationContext getFactory(); static void setFactory(ApplicationContext context); @SuppressWarnings("unchecked") static T getBean(String beanName); static Map<String, T> getBeansOfType(Class<T> type); static Map<String, T> getBeansOfType(Class<T> type,
boolean includeNonSingletons, boolean allowEagerInit); static T getBean(Class<T> clazz); static boolean containsBean(String name); static boolean isSingleton(String name); static Class<?> getType(String name); static String[] getAliases(String name); void setApplicationContext(ApplicationContext applicationContext); }### Answer:
@Test public void testGetFactory() { try { ServiceLocator.getBean("test"); } catch (IllegalArgumentException e) { assertEquals(e.getMessage(), "没有注入spring factory"); } } |
### Question:
PlaceholderResolver { public String doParse(String strVal) { if (strVal == null) { return null; } return parseStringValue(strVal, visitedPlaceholders); } PlaceholderResolver(PlaceholderResolved resolvedInterceptor); String doParse(String strVal); boolean hasPlaceHolder(String strVal); static boolean substringMatch(CharSequence str, int index, CharSequence substring); void setPlaceholderPrefix(String placeholderPrefix); void setPlaceholderSuffix(String placeholderSuffix); static final String DEFAULT_PLACEHOLDER_PREFIX; static final String DEFAULT_PLACEHOLDER_SUFFIX; }### Answer:
@Test public void testDoParse() { final Map<String, String> placeholderVals = new HashMap<>(5); placeholderVals.put("key1", "china"); placeholderVals.put("key2", "3"); placeholderVals.put("key3", "beijin"); String testStr = "hello ${key1}"; PlaceholderResolver resolver = new PlaceholderResolver(placeholderVals::get); resolver.setPlaceholderPrefix("${"); resolver.setPlaceholderSuffix("}"); assertEquals(resolver.doParse(testStr), "hello china"); testStr = "hello ${key${key2}}"; assertEquals(resolver.doParse(testStr), "hello beijin"); } |
### Question:
JndiSupportFilter implements Filter { @Override public final void init(FilterConfig filterConfig) throws ServletException { Assert.notNull(filterConfig, "FilterConfig must not be null"); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Initializing filter '" + filterConfig.getFilterName() + "'"); } initPlaceHolderConfigure(filterConfig); try { PropertyValues pvs = new JndiSupportFilterConfigPropertyValues(filterConfig, this.requiredProperties); BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this); ResourceLoader resourceLoader = new ServletContextResourceLoader(filterConfig.getServletContext()); ServletContextPropertySource servletContextPropertySource = new ServletContextPropertySource(NAME + "_ServletContextPropertySource", filterConfig.getServletContext()); MutablePropertySources propertySources = new MutablePropertySources(); propertySources.addFirst(servletContextPropertySource); PropertySourcesPropertyResolver propertySourcesPropertyResolver = new PropertySourcesPropertyResolver(propertySources); bw.registerCustomEditor(Resource.class, new ResourceEditor(resourceLoader, propertySourcesPropertyResolver)); bw.setPropertyValues(pvs, true); } catch (BeansException ex) { String msg = "Failed to set bean properties on filter '" + filterConfig.getFilterName() + "': " + ex.getMessage(); LOGGER.error(msg, ex); throw new NestedServletException(msg, ex); } doInit(filterConfig); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Filter '" + filterConfig.getFilterName() + "' configured successfully"); } } @Override final void init(FilterConfig filterConfig); @Override void destroy(); static final String JNDI_PROPERTY_PREFIX; static final String NAME; }### Answer:
@Test public void testInit() { Company company = new Company(); BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(company); bw.setPropertyValue("name", "Some Company Inc."); PropertyValue value = new PropertyValue("name", "Some Company Inc1."); bw.setPropertyValue(value); Employee employee = new Employee(); BeanWrapper jim = PropertyAccessorFactory.forBeanPropertyAccess(employee); PropertyValue name = new PropertyValue("name", "Some Employee Inc1."); List<PropertyValue> list = new ArrayList<>(); list.add(name); PropertyValues propertyValues = new MutablePropertyValues(list); jim.setPropertyValues(propertyValues, true); jim.setPropertyValue("salary", 1L); bw.setPropertyValue("managingDirector", jim.getWrappedInstance()); Float salary = (Float) bw.getPropertyValue("managingDirector.salary"); assertEquals(salary, Float.parseFloat("1.0")); } |
### Question:
EasyUITreeServiceImpl implements EasyUITreeService<T> { private EasyUITreeModel findModel(List<T> list, Function<T, EasyUITreeModel> mc) { if (null == list) { throw new RuntimeException("没有EasyUI菜单"); } Map<Integer, EasyUITreeModel> p = new HashMap<>(list.size() + 1); EasyUITreeModel root = new EasyUITreeModel(); root.setId(0); p.put(root.getId(), root); findModel(list, p, mc); root.setId(null); return root; } @Override List<EasyUITreeModel> findChildren(List<T> list, Function<T, EasyUITreeModel> mc); void setCheck(List<EasyUITreeModel> easyUITreeModels); }### Answer:
@Test public void testFindModel() { List<EasyUITreeModel> json = service.findChildren(getList(), p -> { EasyUITreeModel m = new EasyUITreeModel(); m.setId(p.getParamId()); m.setText(p.getParamName()); m.setPid(p.getParamType()); return m; }); assertNotNull(json); } |
### Question:
ExcelRead { public static <E> void read(InputStream inputStream, ExcelReadDeal<E> deal) { Objects.requireNonNull(inputStream); Objects.requireNonNull(deal); try (Workbook wb = WorkbookFactory.create(inputStream)) { for (int i = 0; i < wb.getNumberOfSheets(); i++) { Sheet sheet = wb.getSheetAt(i); if (null == sheet) { continue; } int tmp = deal.getBatchCount(); int index = 0; List<E> l = new ArrayList<>(tmp); for (Row row : sheet) { ++index; if (index <= deal.skipLine()) { continue; } E o = deal.dealBean(row); if (null != o) { l.add(o); if (index % tmp == 0) { deal.dealBatchBean(l); l = new ArrayList<>(tmp); } } } if (!l.isEmpty()) { deal.dealBatchBean(l); } } } catch (Exception e) { e.printStackTrace(); } finally { try { inputStream.close(); } catch (IOException e) { inputStream = null; } } } static void read(InputStream inputStream, ExcelReadDeal<E> deal); }### Answer:
@Test public void testRead() { ExcelRead.read(ExcelReadTest.class.getResourceAsStream("/a.xls"), new ExcelReadDeal<ExcelReadDto>() { @Override public ExcelReadDto dealBean(Row row) { ExcelReadDto dto = new ExcelReadDto(); dto.setId(new BigDecimal(row.getCell(0).toString()).longValue()); dto.setName(row.getCell(1).toString()); dto.setAge(Integer.valueOf(row.getCell(2).toString())); return dto; } @Override public void dealBatchBean(List<ExcelReadDto> list) { Assert.assertEquals("name1", list.get(0).getName()); Assert.assertEquals("name2", list.get(1).getName()); Assert.assertEquals("name3", list.get(2).getName()); } }); } |
### Question:
CSVRead { public static <E> void read(InputStream inputStream, CSVReadDeal<E> deal) { Objects.requireNonNull(inputStream); Objects.requireNonNull(deal); try (CSVReader reader = new CSVReader(new InputStreamReader(new DataInputStream(inputStream)))) { int tmp = deal.getBatchCount(); List<E> l = new ArrayList<>(tmp); int i = 0; String [] arr; while ((arr = reader.readNext()) != null) { ++i; if (i <= deal.skipLine()) { continue; } E o = deal.dealBean(arr); if (o != null) { l.add(o); if (i % tmp == 0) { deal.dealBatchBean(l); l = new ArrayList<>(tmp); } } } if (!l.isEmpty()) { deal.dealBatchBean(l); } } catch (IOException e) { e.printStackTrace(); } finally { try { inputStream.close(); } catch (IOException e) { inputStream = null; } } } static void read(InputStream inputStream, CSVReadDeal<E> deal); static void read(InputStream inputStream, CSVReadDeal<E> deal, CSVParser parser); static void read(InputStream inputStream, CSVReadDeal<E> deal, Function<Reader, CSVReader> function); }### Answer:
@Test public void testRead() { CSVRead.read(CSVReadTest.class.getResourceAsStream("/a.csv"), new CSVReadDeal<CsvReadDto>() { @Override public CsvReadDto dealBean(String[] arr) { CsvReadDto dto = new CsvReadDto(); dto.setId(Long.valueOf(arr[0])); dto.setName(arr[1]); dto.setAge(Integer.valueOf(arr[2])); return dto; } @Override public void dealBatchBean(List<CsvReadDto> list) { Assert.assertEquals("name1", list.get(0).getName()); Assert.assertEquals("name2", list.get(1).getName()); Assert.assertEquals("name3", list.get(2).getName()); } }); }
@Test public void testRead1() { CSVParser parser = new CSVParserBuilder().withSeparator('|').withIgnoreQuotations(true).build(); CSVRead.read(CSVReadTest.class.getResourceAsStream("/a1.csv"), new CSVReadDeal<CsvReadDto>() { @Override public CsvReadDto dealBean(String[] arr) { CsvReadDto dto = new CsvReadDto(); dto.setId(Long.valueOf(arr[0])); dto.setName(arr[1]); dto.setAge(Integer.valueOf(arr[2])); return dto; } @Override public void dealBatchBean(List<CsvReadDto> list) { Assert.assertEquals("name1", list.get(0).getName()); Assert.assertEquals("name2", list.get(1).getName()); Assert.assertEquals("name3", list.get(2).getName()); } }, parser); } |
### Question:
FilePdfWrite extends AbstractPdfWrite { public static FilePdfWrite build(String fileName) { Objects.requireNonNull(fileName); return new FilePdfWrite(fileName); } private FilePdfWrite(String fileName); @Override PdfWrite createOutputStream(); static FilePdfWrite build(String fileName); }### Answer:
@Test public void testWrite() { String path = FilePdfWriteTest.class.getResource("/d.html").getPath(); FilePdfWrite.build(fileName) .addFontPath(fontPath) .deal(() -> { File file = new File(path); String html = null; try { html = FileUtils.readFileToString(file, Charset.forName("GBK")); } catch (IOException e) { e.printStackTrace(); } String[] h = html.split("\\$\\$\\{}"); List<String> htmls = Collections.unmodifiableList(Arrays.asList(h)); StringBuilder sb = new StringBuilder(); sb.append(htmls.get(0)); sb.append("20183732736"); sb.append(htmls.get(1)); sb.append("机械"); sb.append(htmls.get(2)); sb.append("物流"); sb.append(htmls.get(3)); sb.append("20180064"); sb.append(htmls.get(4)); sb.append("2,567"); sb.append(htmls.get(5)); sb.append("食品"); sb.append(htmls.get(6)); sb.append("箱"); sb.append(htmls.get(7)); sb.append("80"); sb.append(htmls.get(8)); sb.append("10"); sb.append(htmls.get(9)); sb.append("30"); sb.append(htmls.get(10)); sb.append("浙江杭州"); sb.append(htmls.get(11)); sb.append("陕西西安"); sb.append(htmls.get(12)); sb.append("开发"); sb.append(htmls.get(13)); sb.append("测试"); sb.append(htmls.get(14)); return sb.toString(); }) .write(); } |
### Question:
HttpServletResponsePdfWrite extends AbstractPdfWrite { public static HttpServletResponsePdfWrite build(String fileName, HttpServletRequest request, HttpServletResponse response) { Objects.requireNonNull(fileName); Objects.requireNonNull(request); Objects.requireNonNull(response); return new HttpServletResponsePdfWrite(fileName, request, response); } HttpServletResponsePdfWrite(String fileName,
HttpServletRequest request, HttpServletResponse response); @Override PdfWrite createOutputStream(); static HttpServletResponsePdfWrite build(String fileName,
HttpServletRequest request, HttpServletResponse response); }### Answer:
@Test public void testWrite() { String path = FilePdfWriteTest.class.getResource("/d.html").getPath(); HttpServletResponsePdfWrite.build(fileName, request, response) .addFontPath(fontPath) .deal(() -> { File file = new File(path); String html = null; try { html = FileUtils.readFileToString(file, Charset.forName("GBK")); } catch (IOException e) { e.printStackTrace(); } String[] h = html.split("\\$\\$\\{}"); List<String> htmls = Collections.unmodifiableList(Arrays.asList(h)); StringBuilder sb = new StringBuilder(); sb.append(htmls.get(0)); sb.append("20183732736"); sb.append(htmls.get(1)); sb.append("机械"); sb.append(htmls.get(2)); sb.append("物流"); sb.append(htmls.get(3)); sb.append("20180064"); sb.append(htmls.get(4)); sb.append("2,567"); sb.append(htmls.get(5)); sb.append("食品"); sb.append(htmls.get(6)); sb.append("箱"); sb.append(htmls.get(7)); sb.append("80"); sb.append(htmls.get(8)); sb.append("10"); sb.append(htmls.get(9)); sb.append("30"); sb.append(htmls.get(10)); sb.append("浙江杭州"); sb.append(htmls.get(11)); sb.append("陕西西安"); sb.append(htmls.get(12)); sb.append("开发"); sb.append(htmls.get(13)); sb.append("测试"); sb.append(htmls.get(14)); return sb.toString(); }) .write(); } |
### Question:
SystemException extends BaseSystemException { public String getMessage(Throwable t) { String oldMessage; if (t instanceof InvocationTargetException) { oldMessage = getMessage(((InvocationTargetException) t).getTargetException()); } else if (t instanceof SystemException) { oldMessage = t.getMessage(); } else if (t instanceof SQLException) { oldMessage = getSQLException(t); } else if (t instanceof RuntimeException) { if (t.getMessage() != null) { oldMessage = t.getMessage(); } else if (null != t.getCause() && null != t.getCause().getMessage()) { oldMessage = t.getCause().getMessage(); } else { oldMessage = getCommonMessage(t); } } else { oldMessage = getCommonMessage(t); } return oldMessage; } SystemException(String msg, Throwable t, String... args); SystemException(String msg); SystemException(Throwable t); SystemException(String msg, Throwable t); String getMessage(Throwable t); }### Answer:
@Test public void testGetMessageCustomExceptionAndCustomMessage() { try { try { String s = null; s.toString(); } catch (Exception e) { String[] str = {"a", "b"}; throw new SystemException("first={0}, second={1}", e, str); } } catch (Exception e) { assertEquals(e.getMessage(), "first=a, second=b"); } }
@Test public void testGetMessageCustomMessage() { try { try { String s = null; s.toString(); } catch (Exception e) { throw new SystemException("自定义异常信息"); } } catch (Exception e) { assertEquals(e.getMessage(), "自定义异常信息"); } }
@Test public void testGetMessageNullPointerException() { try { try { String s = null; s.toString(); } catch (Exception e) { throw new SystemException(e); } } catch (SystemException e) { assertEquals(e.getMessage(), "空指针异常"); } }
@Test public void testGetMessageCustomExceptionAndMessage() { try { try { String s = null; s.toString(); } catch (Exception e) { throw new SystemException("自定义异常信息", e); } } catch (Exception e) { assertEquals(e.getMessage(), "空指针异常"); } } |
### Question:
PathPatternMatcher { public static boolean match(String pattern, String str) { if (str.startsWith("/") != pattern.startsWith("/")) { return false; } List patDirs = tokenizePath(pattern); List strDirs = tokenizePath(str); int patIdxStart = 0; int patIdxEnd = patDirs.size() - 1; int strIdxStart = 0; int strIdxEnd = strDirs.size() - 1; while (patIdxStart <= patIdxEnd && strIdxStart <= strIdxEnd) { String patDir = (String) patDirs.get(patIdxStart); if ("**".equals(patDir)) { break; } if (!matchStrings(patDir, (String) strDirs.get(strIdxStart))) { return false; } patIdxStart++; strIdxStart++; } if (strIdxStart > strIdxEnd) { for (int i = patIdxStart; i <= patIdxEnd; i++) { if (!patDirs.get(i).equals("**")) { return false; } } return true; } else { if (patIdxStart > patIdxEnd) { return false; } } while (patIdxStart <= patIdxEnd && strIdxStart <= strIdxEnd) { String patDir = (String) patDirs.get(patIdxEnd); if ("**".equals(patDir)) { break; } if (!matchStrings(patDir, (String) strDirs.get(strIdxEnd))) { return false; } patIdxEnd--; strIdxEnd--; } if (strIdxStart > strIdxEnd) { for (int i = patIdxStart; i <= patIdxEnd; i++) { if (!patDirs.get(i).equals("**")) { return false; } } return true; } while (patIdxStart != patIdxEnd && strIdxStart <= strIdxEnd) { int patIdxTmp = -1; for (int i = patIdxStart + 1; i <= patIdxEnd; i++) { if (patDirs.get(i).equals("**")) { patIdxTmp = i; break; } } if (patIdxTmp == patIdxStart + 1) { patIdxStart++; continue; } int patLength = patIdxTmp - patIdxStart - 1; int strLength = strIdxEnd - strIdxStart + 1; int foundIdx = -1; strLoop: for (int i = 0; i <= strLength - patLength; i++) { for (int j = 0; j < patLength; j++) { String subPat = (String) patDirs.get(patIdxStart + j + 1); String subStr = (String) strDirs.get(strIdxStart + i + j); if (!matchStrings(subPat, subStr)) { continue strLoop; } } foundIdx = strIdxStart + i; break; } if (foundIdx == -1) { return false; } patIdxStart = patIdxTmp; strIdxStart = foundIdx + patLength; } for (int i = patIdxStart; i <= patIdxEnd; i++) { if (!patDirs.get(i).equals("**")) { return false; } } return true; } static boolean isPattern(String str); static boolean match(String pattern, String str); }### Answer:
@Test public void testMatch() { String s = "/time/;jsessionid=6E697A0D5DDDBC4F7206250E5E594305js/frame/menuModel.js"; assertTrue(PathPatternMatcher.match("*.js", s)); } |
### Question:
BigDecimalUtil { public static double add(double v1, double v2) { return add(v1, v2, Constant.DEFAULT_SCALE); } static double add(double v1, double v2); static double add(double v1, double v2, int scale); static BigDecimal add(BigDecimal v1, BigDecimal v2); static BigDecimal add(BigDecimal v1, BigDecimal v2, int scale); static double sub(double v1, double v2); static double sub(double v1, double v2, int scale); static BigDecimal sub(BigDecimal v1, BigDecimal v2); static BigDecimal sub(BigDecimal v1, BigDecimal v2, int scale); static double mul(double v1, double v2); static double mul(double v1, double v2, int scale); static BigDecimal mul(BigDecimal v1, BigDecimal v2); static BigDecimal mul(BigDecimal v1, BigDecimal v2, int scale); static double div(double v1, double v2); static double div(double v1, double v2, int scale); static BigDecimal div(BigDecimal v1, BigDecimal v2); static BigDecimal div(BigDecimal v1, BigDecimal v2, int scale); }### Answer:
@Test public void testAdd() { assertEquals(BigDecimalUtil.add(123, 234), 357.0); }
@Test public void testAdd1() { BigDecimal v1 = new BigDecimal(123); BigDecimal v2 = new BigDecimal(234); assertEquals(BigDecimalUtil.add(v1, v2), new BigDecimal("357.00")); } |
### Question:
BigDecimalUtil { public static double sub(double v1, double v2) { return sub(v1, v2, Constant.DEFAULT_SCALE); } static double add(double v1, double v2); static double add(double v1, double v2, int scale); static BigDecimal add(BigDecimal v1, BigDecimal v2); static BigDecimal add(BigDecimal v1, BigDecimal v2, int scale); static double sub(double v1, double v2); static double sub(double v1, double v2, int scale); static BigDecimal sub(BigDecimal v1, BigDecimal v2); static BigDecimal sub(BigDecimal v1, BigDecimal v2, int scale); static double mul(double v1, double v2); static double mul(double v1, double v2, int scale); static BigDecimal mul(BigDecimal v1, BigDecimal v2); static BigDecimal mul(BigDecimal v1, BigDecimal v2, int scale); static double div(double v1, double v2); static double div(double v1, double v2, int scale); static BigDecimal div(BigDecimal v1, BigDecimal v2); static BigDecimal div(BigDecimal v1, BigDecimal v2, int scale); }### Answer:
@Test public void testSub() { assertEquals(BigDecimalUtil.sub(123, 234), -111.0); }
@Test public void testSub1() { BigDecimal v1 = new BigDecimal(123); BigDecimal v2 = new BigDecimal(234); assertEquals(BigDecimalUtil.sub(v1, v2), new BigDecimal("-111.00")); } |
### Question:
BigDecimalUtil { public static double mul(double v1, double v2) { return mul(v1, v2, Constant.DEFAULT_SCALE); } static double add(double v1, double v2); static double add(double v1, double v2, int scale); static BigDecimal add(BigDecimal v1, BigDecimal v2); static BigDecimal add(BigDecimal v1, BigDecimal v2, int scale); static double sub(double v1, double v2); static double sub(double v1, double v2, int scale); static BigDecimal sub(BigDecimal v1, BigDecimal v2); static BigDecimal sub(BigDecimal v1, BigDecimal v2, int scale); static double mul(double v1, double v2); static double mul(double v1, double v2, int scale); static BigDecimal mul(BigDecimal v1, BigDecimal v2); static BigDecimal mul(BigDecimal v1, BigDecimal v2, int scale); static double div(double v1, double v2); static double div(double v1, double v2, int scale); static BigDecimal div(BigDecimal v1, BigDecimal v2); static BigDecimal div(BigDecimal v1, BigDecimal v2, int scale); }### Answer:
@Test public void testMul() { assertEquals(BigDecimalUtil.mul(10, 23), 230.0); }
@Test public void testMul1() { BigDecimal v1 = new BigDecimal(10); BigDecimal v2 = new BigDecimal(23); assertEquals(BigDecimalUtil.mul(v1, v2), new BigDecimal("230.00")); } |
### Question:
BigDecimalUtil { public static double div(double v1, double v2) { return div(v1, v2, Constant.DEFAULT_SCALE); } static double add(double v1, double v2); static double add(double v1, double v2, int scale); static BigDecimal add(BigDecimal v1, BigDecimal v2); static BigDecimal add(BigDecimal v1, BigDecimal v2, int scale); static double sub(double v1, double v2); static double sub(double v1, double v2, int scale); static BigDecimal sub(BigDecimal v1, BigDecimal v2); static BigDecimal sub(BigDecimal v1, BigDecimal v2, int scale); static double mul(double v1, double v2); static double mul(double v1, double v2, int scale); static BigDecimal mul(BigDecimal v1, BigDecimal v2); static BigDecimal mul(BigDecimal v1, BigDecimal v2, int scale); static double div(double v1, double v2); static double div(double v1, double v2, int scale); static BigDecimal div(BigDecimal v1, BigDecimal v2); static BigDecimal div(BigDecimal v1, BigDecimal v2, int scale); }### Answer:
@Test public void testDiv() { assertEquals(BigDecimalUtil.div(23, 10), 2.3); }
@Test public void testDiv1() { BigDecimal v1 = new BigDecimal(23); BigDecimal v2 = new BigDecimal(10); assertEquals(BigDecimalUtil.div(v1, v2), new BigDecimal("2.30")); }
@Test public void testDiv2() { BigDecimal v1 = new BigDecimal(23); BigDecimal v2 = new BigDecimal(0); assertEquals(BigDecimalUtil.div(v1, v2), BigDecimal.ZERO); } |
### Question:
JsonUtil { public static String toJson(Object obj, String... ignoreProperties) { return gson(ignoreProperties).toJson(obj); } static T fromJson(String json, Class<T> clazz); static String toJson(Object obj, String... ignoreProperties); static Gson gson(String... ignoreProperties); static Gson gson1(String... ignoreProperties); static ExclusionStrategy getExclusionStrategy(String... ignoreProperties); }### Answer:
@Test public void testToJson() { User user = new User(); user.setName("名称"); user.setDesc("测试"); user.setAge(27); assertEquals("{\"name\":\"名称\",\"age\":27}", JsonUtil.toJson(user, "desc")); } |
### Question:
MapDistance { public static double getDistance(double lng1, double lat1, double lng2, double lat2) { double radLat1 = rad(lng1); double radLat2 = rad(lng2); double difference = radLat1 - radLat2; double mdifference = rad(lat1) - rad(lat2); double distance = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(difference / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(mdifference / 2), 2))); distance = distance * EARTH_RADIUS; distance = Math.round(distance * 10000) / 10000; return distance; } static double getDistance(double lng1, double lat1, double lng2, double lat2); static Map<String, Double> getAround(double lng, double lat, double raidusMile); static final double EARTH_RADIUS; }### Answer:
@Test public void testGetDistance() { assertEquals(MapDistance.getDistance(116.327396, 39.938416, 120.332685, 37.617222), 462.0); assertEquals(MapDistance.getDistance(120.332685, 37.617222, 116.327396, 39.938416), 462.0); } |
### Question:
MapDistance { public static Map<String, Double> getAround(double lng, double lat, double raidusMile) { Map<String, Double> map = new HashMap<>(); double degree = (24901 * 1609) / 360.0; double mpdLng = Double.parseDouble((degree * Math.cos(lng * (Math.PI / 180)) + "").replace("-", "")); double dpmLng = 1 / mpdLng; double radiusLng = dpmLng * raidusMile; double minLat = lat - radiusLng; double maxLat = lat + radiusLng; double dpmLat = 1 / degree; double radiusLat = dpmLat * raidusMile; double minLng = lng - radiusLat; double maxLng = lng + radiusLat; map.put("minLat", minLat); map.put("maxLat", maxLat); map.put("minLng", minLng); map.put("maxLng", maxLng); return map; } static double getDistance(double lng1, double lat1, double lng2, double lat2); static Map<String, Double> getAround(double lng, double lat, double raidusMile); static final double EARTH_RADIUS; }### Answer:
@Test public void testGetAround() { Map<String, Double> map = MapDistance.getAround(117.11811, 36.68484, 13000); assertEquals(map.get("maxLat"), Double.valueOf("36.941095784459634")); assertEquals(map.get("minLat"), Double.valueOf("36.42858421554037")); assertEquals(map.get("minLng"), Double.valueOf("117.001301883613")); assertEquals(map.get("maxLng"), Double.valueOf("117.234918116387")); } |
### Question:
Num62 { public static String longToN62(long l) { return longToNBuf(l, N62_CHARS).reverse().toString(); } static String longToN62(long l); static String longToN36(long l); static String longToN62(long l, int length); static String longToN36(long l, int length); static long n62ToLong(String n62); static long n36ToLong(String n36); static final char[] N62_CHARS; static final char[] N36_CHARS; static final int LONG_N36_LEN; static final int LONG_N62_LEN; }### Answer:
@Test public void testLongToN62() throws Exception { assertEquals(Num62.longToN62(Long.MAX_VALUE), "AzL8n0Y58m7"); } |
### Question:
MapUtil { public static <K, V> MapPlain<K, V> build() { return new MapPlain<>(); } static MapPlain<K, V> build(); static MapPlain<K, V> build(int cap); static Map<String, Object> toMap(Object o, Map<String, String> map, String... ignoreProperties); static Map<String, Object> toMap(Object o, String... ignoreProperties); static void toObject(Map<String, Object> source, Object target, String... ignoreProperties); static List<Map<String, Object>> mapConvertToList(Map<K, V> map); static List<Map<String, Object>> mapConvertToList(Map<K, V> map, Object defaultValue); }### Answer:
@Test public void testMapPlainPut() { Map<String, Object> map = MapUtil.<String, Object>build(1).put("name", "name").get(); assertEquals(map.get("name"), "name"); }
@Test public void testMapPlainPutAll() { Map<String, Object> mapAll = new HashMap<>(); mapAll.put("name", "name"); mapAll.put("age", 25); Map<String, Object> map = MapUtil.<String, Object>build().putAll(mapAll).get(); assertEquals(map.get("name"), "name"); assertEquals(map.get("age"), 25); }
@Test public void testMapPlainPutAllEmpty() { Map<String, Object> mapAll = new HashMap<>(); Map<String, Object> map = MapUtil.<String, Object>build().putAll(mapAll).get(); assertEquals(map.size(), 0); } |
### Question:
MapUtil { public static Map<String, Object> toMap(Object o, Map<String, String> map, String... ignoreProperties) { PropertyDescriptor[] ts = ReflectUtil.getPropertyDescriptors(o); List<String> ignoreList = (ignoreProperties != null && ignoreProperties.length > 0) ? Arrays.asList(ignoreProperties) : null; Map<String, Object> m = new HashMap<>(ts.length); for (PropertyDescriptor t : ts) { Method r = t.getReadMethod(); String name = t.getName(); if (r != null && (ignoreList == null || !ignoreList.contains(name))) { try { if (!Modifier.isPublic(r.getDeclaringClass().getModifiers())) { r.setAccessible(true); } String value; if (null != map && (value = map.get(name)) != null) { m.put(value, r.invoke(o)); } else { m.put(name, r.invoke(o)); } } catch (Throwable e) { throw new RuntimeException("Could not copy property '" + name + "' from source to target", e); } } } return m; } static MapPlain<K, V> build(); static MapPlain<K, V> build(int cap); static Map<String, Object> toMap(Object o, Map<String, String> map, String... ignoreProperties); static Map<String, Object> toMap(Object o, String... ignoreProperties); static void toObject(Map<String, Object> source, Object target, String... ignoreProperties); static List<Map<String, Object>> mapConvertToList(Map<K, V> map); static List<Map<String, Object>> mapConvertToList(Map<K, V> map, Object defaultValue); }### Answer:
@Test public void testDefaultToMap() { A a = new A(); a.setName("name"); a.setAge(25); Map<String, Object> params = MapUtil.toMap(a); assertEquals(params.get("name"), "name"); assertEquals(params.get("age"), 25); }
@Test public void testAliasMapToMap() { Map<String, String> alias = new HashMap<>(); alias.put("name", "testName"); A a = new A(); a.setName("name"); a.setAge(25); Map<String, Object> params = MapUtil.toMap(a, alias); assertEquals(params.get("testName"), "name"); assertEquals(params.get("age"), 25); } |
### Question:
MapUtil { public static void toObject(Map<String, Object> source, Object target, String... ignoreProperties) { PropertyDescriptor[] ts = ReflectUtil.getPropertyDescriptors(target); List<String> ignoreList = (ignoreProperties != null && ignoreProperties.length > 0) ? Arrays.asList(ignoreProperties) : null; for (PropertyDescriptor t : ts) { String name = t.getName(); if (ignoreList == null || !ignoreList.contains(name)) { Object value; if (null != source && (value = source.get(name)) != null) { ReflectUtil.setValueByField(target, name, value); } } } } static MapPlain<K, V> build(); static MapPlain<K, V> build(int cap); static Map<String, Object> toMap(Object o, Map<String, String> map, String... ignoreProperties); static Map<String, Object> toMap(Object o, String... ignoreProperties); static void toObject(Map<String, Object> source, Object target, String... ignoreProperties); static List<Map<String, Object>> mapConvertToList(Map<K, V> map); static List<Map<String, Object>> mapConvertToList(Map<K, V> map, Object defaultValue); }### Answer:
@Test public void testToObject() { Map<String, Object> params = new HashMap<>(); params.put("name", "name"); params.put("age", 25); A a = new A(); MapUtil.toObject(params, a); assertEquals(a.getName(), "name"); assertEquals(a.getAge(), 25); } |
### Question:
MapUtil { public static <K, V> List<Map<String, Object>> mapConvertToList(Map<K, V> map) { return mapConvertToList(map, null); } static MapPlain<K, V> build(); static MapPlain<K, V> build(int cap); static Map<String, Object> toMap(Object o, Map<String, String> map, String... ignoreProperties); static Map<String, Object> toMap(Object o, String... ignoreProperties); static void toObject(Map<String, Object> source, Object target, String... ignoreProperties); static List<Map<String, Object>> mapConvertToList(Map<K, V> map); static List<Map<String, Object>> mapConvertToList(Map<K, V> map, Object defaultValue); }### Answer:
@Test public void testEmptyMapConvertToList() { Map<String, Object> map = new HashMap<>(); List<Map<String, Object>> list = MapUtil.mapConvertToList(map); assertEquals(list.size(), 0); }
@Test public void testMapConvertToList() { Map<String, Object> map = new HashMap<>(); map.put("name", "name"); map.put("age", 25); List<Map<String, Object>> list = MapUtil.mapConvertToList(map); assertEquals(list.size(), 2); assertEquals(list.get(0).get("value"), "name"); assertEquals(list.get(1).get("value"), "age"); }
@Test public void testMapConvertToListDefaultValue() { Map<String, Object> map = new HashMap<>(); map.put("name", "name"); map.put("age", 25); List<Map<String, Object>> list = MapUtil.mapConvertToList(map, "age"); assertTrue((Boolean) list.get(1).get("selected")); } |
### Question:
WebUtil { public static String guessContentType(String fileName) { return URLConnection.getFileNameMap().getContentTypeFor(fileName); } static String guessContentType(String fileName); static String encodeContentDisposition(String userAgent, String fileName); }### Answer:
@Test public void testGuessContentType() throws Exception { assertEquals(WebUtil.guessContentType("1.jpg"), "image/jpeg"); assertNull(WebUtil.guessContentType("2.xlsx")); assertEquals(WebUtil.guessContentType("3.png"), "image/png"); assertNull(WebUtil.guessContentType("4.csv")); assertEquals(WebUtil.guessContentType("5.zip"), "application/zip"); assertEquals(WebUtil.guessContentType("6.txt"), "text/plain"); assertNull(WebUtil.guessContentType("7.docx")); assertNull(WebUtil.guessContentType("8.doc")); assertNull(WebUtil.guessContentType("9.ppt")); assertEquals(WebUtil.guessContentType("10.pdf"), "application/pdf"); assertNull(WebUtil.guessContentType("11.xls")); } |
### Question:
WebUtil { public static String encodeContentDisposition(String userAgent, String fileName) { try { String lowUserAgent = userAgent.toLowerCase(); if (lowUserAgent.contains("msie") || lowUserAgent.contains("trident")) { return "attachment;filename=" + StringUtils.replace(URLEncoder.encode(fileName, StandardCharsets.UTF_8.name()), "+", "%20"); } else if (lowUserAgent.contains("opera")) { return "attachment;filename*=UTF-8''" + fileName; } else if (lowUserAgent.contains("safari") || lowUserAgent.contains("applewebkit") || lowUserAgent.contains("mozilla")) { return "attachment;filename=" + new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1); } else { return "attachment;filename=" + MimeUtility.encodeWord(fileName); } } catch (UnsupportedEncodingException e) { String charset = MimeUtility.getDefaultJavaCharset(); throw new RuntimeException("default java charset [" + charset + "]", e); } } static String guessContentType(String fileName); static String encodeContentDisposition(String userAgent, String fileName); }### Answer:
@Test public void testEncodeContentDisposition() throws Exception { assertEquals(MimeUtility.encodeWord("1.jpg"), "1.jpg"); } |
### Question:
DateUtil { public static String dateRedMonthBegin(Date date, int n) { String str = ""; int year = year(date); int month = month(date); if (n >= 12) { int m = n % 12; int s = n / 12; month = 12 - m + month; year = year - s; } else { month = month - n; } if (month == 0) { year = year - 1; month = 12; } if (month < 10) { str = "0" + month; } else { str = month + ""; } return year + "-" + str + "-01"; } static DateFormat getDateFormat(String format); static String format(String format, Date date); static Date parse(String format, String date); static String getDateStr(Date date, String format, int i, int j); static boolean isLeapYear(int year); static int maxDayOfMonth(int year, int month); static int year(Date date); static int month(Date date); static int day(Date date); static int getTimeNumber(Date date, int i); static int week(Date date); static int getQuarter(Date date); static int dayOfQuarter(Date date); static int days(Date date); static int dayOfYear(Date date); static String dateRedMonthBegin(Date date, int n); static String dateRedMonthEnd(Date date, int n); static Date getDateByCalendar(Date date, int i, int j); static long getBetweenDiff(Date startDate, Date endDate, long time); static boolean isDBDefaultDate(Date date); static final String YYYYMMDD; static final String YYYY_MM_DD; static final String DDMMYY; static final String YYYY_MM; static final String YYYY_MM_DD_HH_MM_SS; static final String YYMMDDHHMMSS; static final String YYYYMMDDHH; static final String YYYYMMDDHHMMSS; static final String HH_MM_SS; static final String HHMMSS; static final String HH_MM; static final long SECOND_TIME; static final long MINUTE_TIME; static final long HOUR_TIME; static final long DAY_TIME; }### Answer:
@Test public void testDateRedMonthBegin() { Date date = DateUtil.parse(DateUtil.YYYY_MM, "201603"); String startDate = DateUtil.dateRedMonthBegin(date, 0); assertEquals(startDate, "2016-03-01"); } |
### Question:
DateUtil { public static String dateRedMonthEnd(Date date, int n) { String str = ""; int year = year(date); int month = month(date); if (n >= 12) { int m = n % 12; int s = n / 12; month = 12 - m + month; year = year - s; } else { month = month - n; } if (month == 0) { year = year - 1; month = 12; } if (month < 10) { str = "0" + month; } else { str = month + ""; } return year + "-" + str + "-" + maxDayOfMonth(year, month); } static DateFormat getDateFormat(String format); static String format(String format, Date date); static Date parse(String format, String date); static String getDateStr(Date date, String format, int i, int j); static boolean isLeapYear(int year); static int maxDayOfMonth(int year, int month); static int year(Date date); static int month(Date date); static int day(Date date); static int getTimeNumber(Date date, int i); static int week(Date date); static int getQuarter(Date date); static int dayOfQuarter(Date date); static int days(Date date); static int dayOfYear(Date date); static String dateRedMonthBegin(Date date, int n); static String dateRedMonthEnd(Date date, int n); static Date getDateByCalendar(Date date, int i, int j); static long getBetweenDiff(Date startDate, Date endDate, long time); static boolean isDBDefaultDate(Date date); static final String YYYYMMDD; static final String YYYY_MM_DD; static final String DDMMYY; static final String YYYY_MM; static final String YYYY_MM_DD_HH_MM_SS; static final String YYMMDDHHMMSS; static final String YYYYMMDDHH; static final String YYYYMMDDHHMMSS; static final String HH_MM_SS; static final String HHMMSS; static final String HH_MM; static final long SECOND_TIME; static final long MINUTE_TIME; static final long HOUR_TIME; static final long DAY_TIME; }### Answer:
@Test public void testDateRedMonthEnd() { Date date = DateUtil.parse(DateUtil.YYYY_MM, "201603"); String endDate = DateUtil.dateRedMonthEnd(date, 0); assertEquals(endDate, "2016-03-31"); } |
### Question:
DateUtil { public static String format(String format, Date date) { return date != null ? getDateFormat(format).format(date) : null; } static DateFormat getDateFormat(String format); static String format(String format, Date date); static Date parse(String format, String date); static String getDateStr(Date date, String format, int i, int j); static boolean isLeapYear(int year); static int maxDayOfMonth(int year, int month); static int year(Date date); static int month(Date date); static int day(Date date); static int getTimeNumber(Date date, int i); static int week(Date date); static int getQuarter(Date date); static int dayOfQuarter(Date date); static int days(Date date); static int dayOfYear(Date date); static String dateRedMonthBegin(Date date, int n); static String dateRedMonthEnd(Date date, int n); static Date getDateByCalendar(Date date, int i, int j); static long getBetweenDiff(Date startDate, Date endDate, long time); static boolean isDBDefaultDate(Date date); static final String YYYYMMDD; static final String YYYY_MM_DD; static final String DDMMYY; static final String YYYY_MM; static final String YYYY_MM_DD_HH_MM_SS; static final String YYMMDDHHMMSS; static final String YYYYMMDDHH; static final String YYYYMMDDHHMMSS; static final String HH_MM_SS; static final String HHMMSS; static final String HH_MM; static final long SECOND_TIME; static final long MINUTE_TIME; static final long HOUR_TIME; static final long DAY_TIME; }### Answer:
@Test public void testFormat() { int count = 2; int j = 2; while (j > 0) { Thread[] threads = new Thread[count]; for (int i = 0; i < count; i++) { Thread thread = new Thread(() -> { String date = DateUtil.format(DateUtil.YYYY_MM_DD_HH_MM_SS, new Date()); assertNotNull(date); date = DateUtil.format(DateUtil.YYYY_MM_DD, new Date()); assertNotNull(date); }); threads[i] = thread; } for (int i = 0; i < count; i++) { threads[i].start(); } j--; } } |
### Question:
CsvUtil { public static void writeCsvFile(HttpServletResponse response, HttpServletRequest request, String filename, String[] title, List<String[]> bodyList) { response.setContentType("application/octet-stream;charset=GBK"); String fileName = FileUtilies.getFileName(filename, request); response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".csv"); try (CSVWriter writer = new CSVWriter(response.getWriter())) { write(writer, title, bodyList); } catch (IOException e) { throw new RuntimeException("write csv file of response fail ", e); } } static void writeCsvFile(HttpServletResponse response, HttpServletRequest request,
String filename, String[] title, List<String[]> bodyList); static void writeCsvFile(HttpServletResponse response, HttpServletRequest request,
String filename, String[] title, List<T> objs, Function<T, String[]> function); static void writeCsvFile(String filename, String[] title, List<String[]> bodyList); static void writeCsvFile(String filename, String[] title, List<T> objs,
Function<T, String[]> function); }### Answer:
@Test public void testStringArrayWriteCsvFile() { String[] title = {"id" , "name"}; List<String[]> bodyList = new ArrayList<>(); String[] data = new String[2]; data[0] = "1"; data[1] = "张三"; bodyList.add(data); data = new String[2]; data[0] = "2"; data[1] = "李四"; bodyList.add(data); CsvUtil.writeCsvFile(fileName, title, bodyList); }
@Test public void testObjectWriteCsvFile() { String[] title = {"id" , "name"}; List<User> objs = new ArrayList<>(); User user = new User(); user.setId(1); user.setName("张三"); objs.add(user); user = new User(); user.setId(2); user.setName("李四"); objs.add(user); CsvUtil.writeCsvFile(fileName, title, objs, t -> { String[] bodyList = new String[2]; bodyList[0] = t.getId() + ""; bodyList[1] = t.getName(); return bodyList; }); } |
### Question:
SystemPropertyUtil { public static String get(String key) { return get(key, null); } private SystemPropertyUtil(); static boolean contains(String key); static String get(String key); static String get(final String key, String def); static int getInt(String key, int def); }### Answer:
@Test(expectedExceptions = NullPointerException.class) public void testGetWithKeyNull() { SystemPropertyUtil.get(null, null); }
@Test(expectedExceptions = IllegalArgumentException.class) public void testGetWithKeyEmpty() { SystemPropertyUtil.get("", null); }
@Test public void testGetDefaultValueWithPropertyNull() { assertEquals("default", SystemPropertyUtil.get("key", "default")); }
@Test public void testGetPropertyValue() { System.setProperty("key", "value"); assertEquals("value", SystemPropertyUtil.get("key")); } |
### Question:
SystemPropertyUtil { public static int getInt(String key, int def) { String value = get(key); if (value == null) { return def; } value = value.trim(); try { return Integer.parseInt(value); } catch (Exception e) { } return def; } private SystemPropertyUtil(); static boolean contains(String key); static String get(String key); static String get(final String key, String def); static int getInt(String key, int def); }### Answer:
@Test public void getIntDefaultValueWithPropertyNull() { assertEquals(1, SystemPropertyUtil.getInt("key", 1)); }
@Test public void getIntWithPropertValueIsInt() { System.setProperty("key", "123"); assertEquals(123, SystemPropertyUtil.getInt("key", 1)); }
@Test public void getIntDefaultValueWithPropertValueIsNotInt() { System.setProperty("key", "NotInt"); assertEquals(1, SystemPropertyUtil.getInt("key", 1)); } |
### Question:
DbManager { public Connection getConnection() { try { Class.forName(this.driveName); return DriverManager.getConnection(this.url, this.user, this.password); } catch (ClassNotFoundException e) { throw new RuntimeException("load database class exception : " + e.getMessage(), e); } catch (SQLException e) { throw new RuntimeException("get database connection : " + e.getMessage(), e); } } DbManager(); DbManager(String url, String user, String password); Connection getConnection(); PreparedStatement getPreparedStatement(Connection connection, String sql); ResultSet getResultSet(PreparedStatement preparedStatement); ResultSet getTables(Connection connection, String localCatalog, String localSchema, String localTableName); ResultSet getColumns(Connection connection, String localCatalog, String localSchema, String localTableName); ResultSet getPrimaryKeys(Connection connection, String localCatalog,
String localSchema, String localTableName); ResultSetMetaData getResultSetMetaData(ResultSet resultSet); DatabaseMetaData getDatabaseMetaData(Connection connection); void close(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet); void close(Connection connection); void close(PreparedStatement preparedStatement); void close(ResultSet resultSet); String getDriveName(); void setDriveName(String driveName); String getUrl(); void setUrl(String url); String getUser(); void setUser(String user); String getPassword(); void setPassword(String password); }### Answer:
@Test public void testGetConnection() { Connection connection = dbManager.getConnection(); assertNotNull(connection); dbManager.close(connection); } |
### Question:
DbManager { public PreparedStatement getPreparedStatement(Connection connection, String sql) { try { return connection.prepareStatement(sql); } catch (SQLException e) { throw new RuntimeException("get PrepareStatement exception : " + e.getMessage(), e); } } DbManager(); DbManager(String url, String user, String password); Connection getConnection(); PreparedStatement getPreparedStatement(Connection connection, String sql); ResultSet getResultSet(PreparedStatement preparedStatement); ResultSet getTables(Connection connection, String localCatalog, String localSchema, String localTableName); ResultSet getColumns(Connection connection, String localCatalog, String localSchema, String localTableName); ResultSet getPrimaryKeys(Connection connection, String localCatalog,
String localSchema, String localTableName); ResultSetMetaData getResultSetMetaData(ResultSet resultSet); DatabaseMetaData getDatabaseMetaData(Connection connection); void close(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet); void close(Connection connection); void close(PreparedStatement preparedStatement); void close(ResultSet resultSet); String getDriveName(); void setDriveName(String driveName); String getUrl(); void setUrl(String url); String getUser(); void setUser(String user); String getPassword(); void setPassword(String password); }### Answer:
@Test public void testGetPreparedStatement() { Connection connection = dbManager.getConnection(); PreparedStatement preparedStatement = dbManager.getPreparedStatement(connection, "select count(1) as count from tb_user"); assertNotNull(preparedStatement); dbManager.close(connection, preparedStatement, null); } |
### Question:
DbManager { public ResultSet getResultSet(PreparedStatement preparedStatement) { try { return preparedStatement.executeQuery(); } catch (SQLException e) { throw new RuntimeException("get ResultSet exception : " + e.getMessage(), e); } } DbManager(); DbManager(String url, String user, String password); Connection getConnection(); PreparedStatement getPreparedStatement(Connection connection, String sql); ResultSet getResultSet(PreparedStatement preparedStatement); ResultSet getTables(Connection connection, String localCatalog, String localSchema, String localTableName); ResultSet getColumns(Connection connection, String localCatalog, String localSchema, String localTableName); ResultSet getPrimaryKeys(Connection connection, String localCatalog,
String localSchema, String localTableName); ResultSetMetaData getResultSetMetaData(ResultSet resultSet); DatabaseMetaData getDatabaseMetaData(Connection connection); void close(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet); void close(Connection connection); void close(PreparedStatement preparedStatement); void close(ResultSet resultSet); String getDriveName(); void setDriveName(String driveName); String getUrl(); void setUrl(String url); String getUser(); void setUser(String user); String getPassword(); void setPassword(String password); }### Answer:
@Test public void testGetResultSet() throws Exception { Connection connection = dbManager.getConnection(); PreparedStatement preparedStatement = dbManager.getPreparedStatement(connection, "select count(1) as count from tb_user"); ResultSet resultSet = dbManager.getResultSet(preparedStatement); assertNotNull(resultSet); resultSet.next(); long count = resultSet.getLong("count"); assertEquals(count, 0); dbManager.close(connection, preparedStatement, resultSet); } |
### Question:
DbManager { public ResultSet getTables(Connection connection, String localCatalog, String localSchema, String localTableName) { try { return getDatabaseMetaData(connection).getTables(localCatalog, localSchema, localTableName, null); } catch (SQLException e) { throw new RuntimeException("get tables exception : " + e.getMessage(), e); } } DbManager(); DbManager(String url, String user, String password); Connection getConnection(); PreparedStatement getPreparedStatement(Connection connection, String sql); ResultSet getResultSet(PreparedStatement preparedStatement); ResultSet getTables(Connection connection, String localCatalog, String localSchema, String localTableName); ResultSet getColumns(Connection connection, String localCatalog, String localSchema, String localTableName); ResultSet getPrimaryKeys(Connection connection, String localCatalog,
String localSchema, String localTableName); ResultSetMetaData getResultSetMetaData(ResultSet resultSet); DatabaseMetaData getDatabaseMetaData(Connection connection); void close(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet); void close(Connection connection); void close(PreparedStatement preparedStatement); void close(ResultSet resultSet); String getDriveName(); void setDriveName(String driveName); String getUrl(); void setUrl(String url); String getUser(); void setUser(String user); String getPassword(); void setPassword(String password); }### Answer:
@Test public void testGetTables() throws Exception { Connection connection = dbManager.getConnection(); ResultSet resultSet = dbManager.getTables(connection, "", "test_tmp", ""); assertNotNull(resultSet); int size = 0; while (resultSet.next()) { size++; } assertEquals(size, 1); dbManager.close(connection, null, resultSet); } |
### Question:
DbManager { public ResultSet getColumns(Connection connection, String localCatalog, String localSchema, String localTableName) { try { return getDatabaseMetaData(connection).getColumns(localCatalog, localSchema, localTableName, null); } catch (SQLException e) { throw new RuntimeException("get columns exception : " + e.getMessage(), e); } } DbManager(); DbManager(String url, String user, String password); Connection getConnection(); PreparedStatement getPreparedStatement(Connection connection, String sql); ResultSet getResultSet(PreparedStatement preparedStatement); ResultSet getTables(Connection connection, String localCatalog, String localSchema, String localTableName); ResultSet getColumns(Connection connection, String localCatalog, String localSchema, String localTableName); ResultSet getPrimaryKeys(Connection connection, String localCatalog,
String localSchema, String localTableName); ResultSetMetaData getResultSetMetaData(ResultSet resultSet); DatabaseMetaData getDatabaseMetaData(Connection connection); void close(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet); void close(Connection connection); void close(PreparedStatement preparedStatement); void close(ResultSet resultSet); String getDriveName(); void setDriveName(String driveName); String getUrl(); void setUrl(String url); String getUser(); void setUser(String user); String getPassword(); void setPassword(String password); }### Answer:
@Test public void testGetColumns() throws Exception { Connection connection = dbManager.getConnection(); ResultSet resultSet = dbManager.getColumns(connection, "", "test_tmp", "tb_user"); assertNotNull(resultSet); int size = 0; while (resultSet.next()) { size++; } assertEquals(size, 6); dbManager.close(connection, null, resultSet); } |
### Question:
DbManager { public ResultSet getPrimaryKeys(Connection connection, String localCatalog, String localSchema, String localTableName) { try { return getDatabaseMetaData(connection).getPrimaryKeys(localCatalog, localSchema, localTableName); } catch (SQLException e) { throw new RuntimeException("get primary key exception : " + e.getMessage(), e); } } DbManager(); DbManager(String url, String user, String password); Connection getConnection(); PreparedStatement getPreparedStatement(Connection connection, String sql); ResultSet getResultSet(PreparedStatement preparedStatement); ResultSet getTables(Connection connection, String localCatalog, String localSchema, String localTableName); ResultSet getColumns(Connection connection, String localCatalog, String localSchema, String localTableName); ResultSet getPrimaryKeys(Connection connection, String localCatalog,
String localSchema, String localTableName); ResultSetMetaData getResultSetMetaData(ResultSet resultSet); DatabaseMetaData getDatabaseMetaData(Connection connection); void close(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet); void close(Connection connection); void close(PreparedStatement preparedStatement); void close(ResultSet resultSet); String getDriveName(); void setDriveName(String driveName); String getUrl(); void setUrl(String url); String getUser(); void setUser(String user); String getPassword(); void setPassword(String password); }### Answer:
@Test public void testGetPrimaryKeys() throws Exception { Connection connection = dbManager.getConnection(); ResultSet resultSet = dbManager.getPrimaryKeys(connection, "", "test_tmp", "tb_user"); assertNotNull(resultSet); int size = 0; while (resultSet.next()) { size++; } assertEquals(size, 1); dbManager.close(connection, null, resultSet); } |
### Question:
DbManager { public ResultSetMetaData getResultSetMetaData(ResultSet resultSet) { try { return resultSet.getMetaData(); } catch (SQLException e) { throw new RuntimeException("get ResultSetMetaData exception : " + e.getMessage(), e); } } DbManager(); DbManager(String url, String user, String password); Connection getConnection(); PreparedStatement getPreparedStatement(Connection connection, String sql); ResultSet getResultSet(PreparedStatement preparedStatement); ResultSet getTables(Connection connection, String localCatalog, String localSchema, String localTableName); ResultSet getColumns(Connection connection, String localCatalog, String localSchema, String localTableName); ResultSet getPrimaryKeys(Connection connection, String localCatalog,
String localSchema, String localTableName); ResultSetMetaData getResultSetMetaData(ResultSet resultSet); DatabaseMetaData getDatabaseMetaData(Connection connection); void close(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet); void close(Connection connection); void close(PreparedStatement preparedStatement); void close(ResultSet resultSet); String getDriveName(); void setDriveName(String driveName); String getUrl(); void setUrl(String url); String getUser(); void setUser(String user); String getPassword(); void setPassword(String password); }### Answer:
@Test public void testGetResultSetMetaData() throws Exception { Connection connection = dbManager.getConnection(); PreparedStatement preparedStatement = dbManager.getPreparedStatement(connection, "select count(1) as count from tb_user"); ResultSet resultSet = dbManager.getResultSet(preparedStatement); ResultSetMetaData resultSetMetaData = dbManager.getResultSetMetaData(resultSet); assertNotNull(resultSetMetaData); assertEquals(resultSetMetaData.getColumnCount(), 1); } |
### Question:
DbManager { public DatabaseMetaData getDatabaseMetaData(Connection connection) { try { return connection.getMetaData(); } catch (SQLException e) { throw new RuntimeException("get DatabaseMetaData exception : " + e.getMessage(), e); } } DbManager(); DbManager(String url, String user, String password); Connection getConnection(); PreparedStatement getPreparedStatement(Connection connection, String sql); ResultSet getResultSet(PreparedStatement preparedStatement); ResultSet getTables(Connection connection, String localCatalog, String localSchema, String localTableName); ResultSet getColumns(Connection connection, String localCatalog, String localSchema, String localTableName); ResultSet getPrimaryKeys(Connection connection, String localCatalog,
String localSchema, String localTableName); ResultSetMetaData getResultSetMetaData(ResultSet resultSet); DatabaseMetaData getDatabaseMetaData(Connection connection); void close(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet); void close(Connection connection); void close(PreparedStatement preparedStatement); void close(ResultSet resultSet); String getDriveName(); void setDriveName(String driveName); String getUrl(); void setUrl(String url); String getUser(); void setUser(String user); String getPassword(); void setPassword(String password); }### Answer:
@Test public void testGetDatabaseMetaData() throws Exception { Connection connection = dbManager.getConnection(); DatabaseMetaData databaseMetaData = dbManager.getDatabaseMetaData(connection); assertNotNull(databaseMetaData); assertEquals(databaseMetaData.getDatabaseProductName().toLowerCase(), "mysql"); dbManager.close(connection); } |
### Question:
Coder { public static int ASCIIToEBCDIC(int ascii) { return ASCII.AToE[ascii & 0xff] & 0xff; } static int ASCIIToEBCDIC(int ascii); static int EBCDICToASCII(int ebcdic); static byte[] ASCIIToEBCDIC(byte[] ascii); static byte[] EBCDICToASCII(byte[] ebcdic); static String ASCIIToEBCDIC(String ascii); static String EBCDICToASCII(String ebcdic); static void ASCIIToEBCDIC(String fromFile, String toFile); static void EBCDICToASCII(String fromFile, String toFile); }### Answer:
@Test public void testASCIIToEBCDIC() { byte[]c = new byte[]{1,2,3,4}; byte[] a = Coder.ASCIIToEBCDIC(c); assertEquals(a[0], 1); assertEquals(a[1], 2); assertEquals(a[2], 3); assertEquals(a[3], 55); } |
### Question:
ValidateUtils { public static <T> void validate(T bean, Class<?>... groups) { validate(bean, true, groups); } static void validate(T bean, Class<?>... groups); static void validate(T bean, boolean flag, Class<?>... groups); }### Answer:
@Test public void testValidate() { User user = new User(); user.setRealName("a"); try { ValidateUtils.validate(user); } catch (Exception e) { String str = e.getMessage(); assertEquals(str, "用户id不能为空"); } }
@Test public void testFastValidate() { User user = new User(); try { ValidateUtils.validate(user, false); } catch (Exception e) { String str = e.getMessage(); String [] arrays = str.split(","); assertEquals(arrays.length, 2); } }
@Test public void testValidateSuccess() { User user = new User(); user.setId(1L); user.setRealName("a"); ValidateUtils.validate(user); } |
### Question:
PBE { public static byte[] initSalt() { byte[] salt = new byte[8]; Random random = new Random(); random.nextBytes(salt); return salt; } static byte[] encrypt(byte[] data, byte[] key, byte[] salt); static byte[] decrypt(byte[] data, byte[] key, byte[] salt); static Key generateRandomKey(byte[] key); static AlgorithmParameterSpec getAlgorithmParameterSpec(byte[] salt); static byte[] initSalt(); }### Answer:
@Test public void testInitSalt() { assertNotNull(PBE.initSalt()); } |
### Question:
AES { public static byte[] encrypt(byte[] data, byte[] key) { validation(data, key); Key secretKeySpec = Symmetry.generateRandomKey(key, AES_ALGORITHM); return Symmetry.encrypt(AES_ALGORITHM, secretKeySpec, data); } static byte[] encrypt(byte[] data, byte[] key); static byte[] decrypt(byte[] data, byte[] key); static void validation(byte[] data, byte[] key); }### Answer:
@Test public void encrypt() { String data = "root1"; byte[] key = "1111111111111111".getBytes(); byte[] encryption = AES.encrypt(data.getBytes(), key); assertEquals(Base64.getEncoder().encodeToString(encryption), "8/mudtZ/bQOhcV/K6JFrug=="); String decryptData = new String(AES.decrypt(encryption, key)); assertEquals(decryptData, data); } |
### Question:
HMAC { public static byte[] initMacKey() { try { KeyGenerator keyGenerator = KeyGenerator.getInstance(ISecurity.HMAC_ALGORITHM); SecretKey secretKey = keyGenerator.generateKey(); return secretKey.getEncoded(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("获取自增密钥错误", e); } } static byte[] encrypt(byte[] data, byte[] key); static byte[] initMacKey(); }### Answer:
@Test public void testInitMacKey() { assertNotNull(HMAC.initMacKey()); } |
### Question:
HMAC { public static byte[] encrypt(byte[] data, byte[] key) { try { SecretKey secretKey = new SecretKeySpec(key, ISecurity.HMAC_ALGORITHM); Mac mac = Mac.getInstance(secretKey.getAlgorithm()); mac.init(secretKey); return mac.doFinal(data); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("无此算法错误", e); } catch (InvalidKeyException e) { throw new RuntimeException("无效密钥错误", e); } } static byte[] encrypt(byte[] data, byte[] key); static byte[] initMacKey(); }### Answer:
@Test public void testEncrypt() { byte[] key = Base64.getDecoder().decode("aDoeS0jpEa7R6YssPU7gZvf95RYH4slqbQgr2gpijhviXyOa16xxOAYmlg0VqBKTE0QPYB26wySLruNJNsbO3A=="); byte[] data = "aaaa".getBytes(); byte[] encryptData = HMAC.encrypt(data, key); String result = Base64.getEncoder().encodeToString(encryptData); assertEquals(result, "omXf1QfFYGlZ+SshA2twjw=="); } |
### Question:
SHA { public static String digest(byte[] bytes) { try { MessageDigest md = MessageDigest.getInstance(ISecurity.SHA_ALGORITHM); BigInteger bigInteger = new BigInteger(md.digest(bytes)); return bigInteger.toString(16); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("无此[" + ISecurity.SHA_ALGORITHM + "]算法", e); } } static String digest(byte[] bytes); }### Answer:
@Test public void testDigest() { byte[] data = "aaa".getBytes(); String result = SHA.digest(data); assertEquals(result, "7e240de74fb1ed08fa08d38063f6a6a91462a815"); } |
### Question:
MD5 { public static String digest(byte[] bytes) { try { MessageDigest md = MessageDigest.getInstance(ISecurity.MD5_ALGORITHM); BigInteger bigInteger = new BigInteger(md.digest(bytes)); return bigInteger.toString(16); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("无此[" + ISecurity.MD5_ALGORITHM + "]算法", e); } } static String digest(byte[] bytes); }### Answer:
@Test public void testDigest() { byte[] data = "aaa".getBytes(); String result = MD5.digest(data); assertEquals(result, "47bce5c74f589f4867dbd57e9ca9f808"); } |
### Question:
WeatherSecurity { public static String standardURLEncoder(String data, String key) { try { Mac mac = Mac.getInstance("HmacSHA1"); SecretKeySpec spec = new SecretKeySpec(key.getBytes(), "HmacSHA1"); mac.init(spec); byte[] byteHMAC = mac.doFinal(data.getBytes()); if (byteHMAC != null) { String oauth = encode(byteHMAC); return URLEncoder.encode(oauth, "utf8"); } } catch (Exception e1) { e1.printStackTrace(); } return ""; } static String standardURLEncoder(String data, String key); static String encode(byte[] from); }### Answer:
@Test public void testExecuteGet() { try { String type = "forecast_f"; String appid = "0efe9e3c08151b8d"; String date = "201503030741"; String areaid = "101010100"; String key = "a0f6ac_SmartWeatherAPI_cd7e788"; String data = "http: String str = WeatherSecurity.standardURLEncoder(data + appid, key); assertEquals(str, "ocxOZEXG%2BM9aqzMKw0eZK0mXcaA%3D"); String result = data + appid.substring(0, 6) + "&key=" + str; assertEquals(result, "http: } catch (Exception e) { e.printStackTrace(); } } |
### Question:
RSAC { public static byte[] encryptByPublicKey(byte[] data, String ns, String es) { return encryptByPublicKey(data, ns, es, ISecurity.RSA_ECB_ALGORITHM); } static byte[] encryptByPublicKey(byte[] data, String ns, String es); static byte[] encryptByPublicKey(byte[] data, String ns, String es, String cipherS); static byte[] decryptByPrivateKey(byte[] data, String ns, String ds); static byte[] decryptByPrivateKey(byte[] data, String ns, String ds, String cipherS); }### Answer:
@Test public void testEncryptByPublicKey() { String data = "abc"; byte[] result = RSAC.encryptByPublicKey(data.getBytes(), ns, es); assertEquals(ISOUtil.hexString(result), "AD04F695A18D6C400F301C3704EA472F6AB875967B66A6F196558E163173F783C1BD8CADD277E518603C2BD819DCB3B8364C9B2E2A89B769A32A678EAD345A1F"); } |
### Question:
RSAC { public static byte[] decryptByPrivateKey(byte[] data, String ns, String ds) { return decryptByPrivateKey(data, ns, ds, ISecurity.RSA_ECB_ALGORITHM); } static byte[] encryptByPublicKey(byte[] data, String ns, String es); static byte[] encryptByPublicKey(byte[] data, String ns, String es, String cipherS); static byte[] decryptByPrivateKey(byte[] data, String ns, String ds); static byte[] decryptByPrivateKey(byte[] data, String ns, String ds, String cipherS); }### Answer:
@Test public void testDecryptByPrivateKey() { String data = "AD04F695A18D6C400F301C3704EA472F6AB875967B66A6F196558E163173F783C1BD8CADD277E518603C2BD819DCB3B8364C9B2E2A89B769A32A678EAD345A1F"; byte[] result = RSAC.decryptByPrivateKey(ISOUtil.hex2byte(data), ns, ds); assertEquals(new String(result).trim(), "abc"); } |
### Question:
CreditCardTypeConverter implements TypeConverter<String> { public String convert(String input, Class<? extends String> targetType, Collection<ValidationError> errors) { String cardNumber = input.replaceAll("\\D", ""); if (getCardType(cardNumber) != null) { return cardNumber; } errors.add(new ScopedLocalizableError("converter.creditCard", "invalidCreditCard")); return null; } void setLocale(Locale locale); String convert(String input, Class<? extends String> targetType, Collection<ValidationError> errors); static Type getCardType(String cardNumber); }### Answer:
@Test(groups = "fast") public void validNumber() { CreditCardTypeConverter c = new CreditCardTypeConverter(); Assert.assertEquals(c.convert("4111111111111111", String.class, new ArrayList<ValidationError>()), "4111111111111111"); }
@Test(groups = "fast") public void invalidNumber() { CreditCardTypeConverter c = new CreditCardTypeConverter(); Assert.assertNull(c.convert("4111111111111110", String.class, new ArrayList<ValidationError>())); }
@Test(groups = "fast") public void stripNonNumericCharacters() { CreditCardTypeConverter c = new CreditCardTypeConverter(); Assert.assertEquals(c.convert("4111-1111-1111-1111", String.class, new ArrayList<ValidationError>()), "4111111111111111"); } |
### Question:
BigDecimalTypeConverter extends NumberTypeConverterSupport implements TypeConverter<BigDecimal> { public BigDecimal convert(String input, Class<? extends BigDecimal> targetType, Collection<ValidationError> errors) { return (BigDecimal) parse(input, errors); } BigDecimal convert(String input,
Class<? extends BigDecimal> targetType,
Collection<ValidationError> errors); }### Answer:
@Test(groups = "fast") public void basicParse() throws Exception { TypeConverter<BigDecimal> converter = new BigDecimalTypeConverter(); converter.setLocale(Locale.US); BigDecimal result = converter.convert("12345.67", BigDecimal.class, errors()); Assert.assertEquals(result, new BigDecimal("12345.67")); }
@Test(groups = "fast") public void parseBigNumber() throws Exception { String number = "7297029872767869231987623498756389734567893246934298765342987563489723497" + ".97982730927907092387409872340987234698750987129872348970982374076283764"; TypeConverter<BigDecimal> converter = new BigDecimalTypeConverter(); converter.setLocale(Locale.US); BigDecimal result = converter.convert(number, BigDecimal.class, errors()); Assert.assertEquals(result, new BigDecimal(number)); }
@Test(groups = "fast") public void parseWithGroupingCharacters() throws Exception { String number = "7297029872767869231987623498756389734567876534.2987563489723497"; String grouped = "7,297,029,872,767,869,231,987,623,498,756,389,734,567,876,534.2987563489723497"; TypeConverter<BigDecimal> converter = new BigDecimalTypeConverter(); converter.setLocale(Locale.US); BigDecimal result = converter.convert(grouped, BigDecimal.class, errors()); Assert.assertEquals(result, new BigDecimal(number)); }
@Test(groups = "fast") public void parseAlternateLocale() throws Exception { String number = "123456789.99"; String localized = "123.456.789,99"; TypeConverter<BigDecimal> converter = new BigDecimalTypeConverter(); converter.setLocale(Locale.GERMANY); BigDecimal result = converter.convert(localized, BigDecimal.class, errors()); Assert.assertEquals(result, new BigDecimal(number)); }
@Test(groups = "fast") public void invalidInput() throws Exception { String number = "a1b2vc3d4"; TypeConverter<BigDecimal> converter = new BigDecimalTypeConverter(); converter.setLocale(Locale.US); Collection<ValidationError> errors = errors(); @SuppressWarnings("unused") BigDecimal result = converter.convert(number, BigDecimal.class, errors); Assert.assertEquals(errors.size(), 1); } |
### Question:
BigIntegerTypeConverter extends NumberTypeConverterSupport implements TypeConverter<BigInteger> { public BigInteger convert(String input, Class<? extends BigInteger> targetType, Collection<ValidationError> errors) { BigDecimal decimal = (BigDecimal) parse(input, errors); if (errors.size() == 0) { return decimal.toBigInteger(); } else { return null; } } BigInteger convert(String input,
Class<? extends BigInteger> targetType,
Collection<ValidationError> errors); }### Answer:
@Test(groups = "fast") public void basicParse() throws Exception { TypeConverter<BigInteger> converter = new BigIntegerTypeConverter(); converter.setLocale(Locale.US); BigInteger result = converter.convert("1234567", BigInteger.class, errors()); Assert.assertEquals(result, new BigInteger("1234567")); }
@Test(groups = "fast") public void parseBigNumber() throws Exception { String number = String.valueOf(Long.MAX_VALUE) + "8729839871981298798234"; TypeConverter<BigInteger> converter = new BigIntegerTypeConverter(); converter.setLocale(Locale.US); BigInteger result = converter.convert(number, BigInteger.class, errors()); Assert.assertEquals(result, new BigInteger(number)); Assert.assertEquals(result.toString(), number); }
@Test(groups = "fast") public void parseWithGroupingCharacters() throws Exception { String number = "7297029872767869231987623498756389734567876534"; String grouped = "7,297,029,872,767,869,231,987,623,498,756,389,734,567,876,534"; TypeConverter<BigInteger> converter = new BigIntegerTypeConverter(); converter.setLocale(Locale.US); BigInteger result = converter.convert(grouped, BigInteger.class, errors()); Assert.assertEquals(result, new BigInteger(number)); }
@Test(groups = "fast") public void parseAlternateLocale() throws Exception { String number = "123456789"; String localized = "123.456.789"; TypeConverter<BigInteger> converter = new BigIntegerTypeConverter(); converter.setLocale(Locale.GERMANY); BigInteger result = converter.convert(localized, BigInteger.class, errors()); Assert.assertEquals(result, new BigInteger(number)); }
@Test(groups = "fast") public void decimalTruncation() throws Exception { TypeConverter<BigInteger> converter = new BigIntegerTypeConverter(); converter.setLocale(Locale.US); BigInteger result = converter.convert("123456789.98765", BigInteger.class, errors()); Assert.assertEquals(result, new BigInteger("123456789")); Assert.assertEquals(result.toString(), "123456789"); }
@Test(groups = "fast") public void invalidInput() throws Exception { String number = "a1b2vc3d4"; TypeConverter<BigInteger> converter = new BigIntegerTypeConverter(); converter.setLocale(Locale.US); Collection<ValidationError> errors = errors(); @SuppressWarnings("unused") BigInteger result = converter.convert(number, BigInteger.class, errors); Assert.assertEquals(errors.size(), 1); } |
### Question:
UrlBuilder { @Override public String toString() { if (url == null) { url = build(); } if (this.anchor != null && this.anchor.length() > 0) { return url + "#" + StringUtil.uriFragmentEncode(this.anchor); } else { return url; } } UrlBuilder(Locale locale, String url, boolean isForPage); UrlBuilder(Locale locale, Class<? extends ActionBean> beanType, boolean isForPage); protected UrlBuilder(Locale locale, boolean isForPage); String getEvent(); UrlBuilder setEvent(String event); String getParameterSeparator(); void setParameterSeparator(String parameterSeparator); UrlBuilder addParameter(String name, Object... values); UrlBuilder addParameters(Map<? extends Object, ? extends Object> parameters); String getAnchor(); UrlBuilder setAnchor(String anchor); @Override String toString(); }### Answer:
@Test(groups = "fast") public void testBasicUrl() throws Exception { String path = "/test/page.jsp"; UrlBuilder builder = new UrlBuilder(Locale.getDefault(), path, false); String result = builder.toString(); Assert.assertEquals(result, path); } |
### Question:
HtmlUtil { public static String combineValues(Collection<String> values) { if (values == null || values.size() == 0) { return ""; } else { StringBuilder builder = new StringBuilder(values.size() * 30); for (String value : values) { builder.append(value).append(FIELD_DELIMITER_STRING); } return encode(builder.toString()); } } static String encode(String fragment); static String combineValues(Collection<String> values); static Collection<String> splitValues(String value); }### Answer:
@Test(groups = "fast") public void testJoinWithNoStrings() throws Exception { String combined = HtmlUtil.combineValues(null); Assert.assertEquals(combined, ""); combined = HtmlUtil.combineValues(new HashSet<String>()); Assert.assertEquals(combined, ""); } |
### Question:
HtmlUtil { public static Collection<String> splitValues(String value) { if (value == null || value.length() == 0) { return Collections.emptyList(); } else { String[] splits = FIELD_DELIMITER_PATTERN.split(value); return Arrays.asList(splits); } } static String encode(String fragment); static String combineValues(Collection<String> values); static Collection<String> splitValues(String value); }### Answer:
@Test(groups = "fast") public void testSplitWithNoValues() throws Exception { Collection<String> values = HtmlUtil.splitValues(null); Assert.assertNotNull(values); Assert.assertEquals(values.size(), 0); values = HtmlUtil.splitValues(""); Assert.assertNotNull(values); Assert.assertEquals(values.size(), 0); } |
### Question:
CollectionUtil { public static boolean empty(String[] arr) { if (arr == null || arr.length == 0) { return true; } for (String s : arr) { if (s != null && !"".equals(s)) { return false; } } return true; } static boolean contains(Object[] arr, Object item); static boolean empty(String[] arr); static boolean applies(String events[], String event); static Object[] asObjectArray(Object in); static List<Object> asList(Object in); static List<T> asList(Iterable<T> in); }### Answer:
@Test(groups = "fast") public void testEmptyOnNullCollection() { Assert.assertTrue(CollectionUtil.empty(null)); }
@Test(groups = "fast") public void testEmptyOnCollectionOfNulls() { Assert.assertTrue(CollectionUtil.empty(new String[]{null, null, null})); }
@Test(groups = "fast") public void testEmptyZeroLengthCollection() { Assert.assertTrue(CollectionUtil.empty(new String[]{})); }
@Test(groups = "fast") public void testEmptyOnCollectionOfEmptyStrings() { Assert.assertTrue(CollectionUtil.empty(new String[]{"", null, ""})); }
@Test(groups = "fast") public void testEmptyOnNonEmptyCollection1() { Assert.assertFalse(CollectionUtil.empty(new String[]{"", null, "foo"})); }
@Test(groups = "fast") public void testEmptyOnNonEmptyCollection2() { Assert.assertFalse(CollectionUtil.empty(new String[]{"bar"})); }
@Test(groups = "fast") public void testEmptyOnNonEmptyCollection3() { Assert.assertFalse(CollectionUtil.empty(new String[]{"bar", "splat", "foo"})); } |
### Question:
CollectionUtil { public static boolean applies(String events[], String event) { if (events == null || events.length == 0) { return true; } boolean isPositive = events[0].charAt(0) != '!'; if (isPositive) { return contains(events, event); } else { return !contains(events, "!" + event); } } static boolean contains(Object[] arr, Object item); static boolean empty(String[] arr); static boolean applies(String events[], String event); static Object[] asObjectArray(Object in); static List<Object> asList(Object in); static List<T> asList(Iterable<T> in); }### Answer:
@Test(groups = "fast") public void testApplies() { Assert.assertTrue(CollectionUtil.applies(null, "foo")); Assert.assertTrue(CollectionUtil.applies(new String[]{}, "foo")); Assert.assertTrue(CollectionUtil.applies(new String[]{"bar", "foo"}, "foo")); Assert.assertFalse(CollectionUtil.applies(new String[]{"bar", "f00"}, "foo")); Assert.assertFalse(CollectionUtil.applies(new String[]{"!bar", "!foo"}, "foo")); Assert.assertTrue(CollectionUtil.applies(new String[]{"!bar", "!f00"}, "foo")); } |
### Question:
CollectionUtil { public static List<Object> asList(Object in) { if (in == null || !in.getClass().isArray()) { throw new IllegalArgumentException("Parameter to asObjectArray must be a non-null array."); } else { int length = Array.getLength(in); LinkedList<Object> list = new LinkedList<Object>(); for (int i = 0; i < length; ++i) { list.add(i, Array.get(in, i)); } return list; } } static boolean contains(Object[] arr, Object item); static boolean empty(String[] arr); static boolean applies(String events[], String event); static Object[] asObjectArray(Object in); static List<Object> asList(Object in); static List<T> asList(Iterable<T> in); }### Answer:
@Test(groups = "fast") public void testAsList() { List<Object> list = CollectionUtil.asList(new String[]{"foo", "bar"}); Assert.assertEquals(list.get(0), "foo"); Assert.assertEquals(list.get(1), "bar"); list = CollectionUtil.asList(new String[]{}); Assert.assertEquals(list.size(), 0); list = CollectionUtil.asList(new int[]{0, 1, 2, 3}); Assert.assertEquals(list.get(0), new Integer(0)); Assert.assertEquals(list.get(1), new Integer(1)); Assert.assertEquals(list.get(2), new Integer(2)); Assert.assertEquals(list.get(3), new Integer(3)); } |
### Question:
CryptoUtil { public static String decrypt(String input) { if (input == null) { return null; } Configuration configuration = StripesFilter.getConfiguration(); if (configuration != null && configuration.isDebugMode()) { return input; } byte[] bytes = Base64.decode(input, BASE64_OPTIONS); if (bytes == null || bytes.length < 1) { log.warn("Input is not Base64 encoded: ", input); return null; } if (bytes.length < CIPHER_BLOCK_LENGTH * 2 + CIPHER_HMAC_LENGTH) { log.warn("Input is too short: ", input); return null; } SecretKey key = getSecretKey(); byte[] mac = new byte[CIPHER_HMAC_LENGTH]; try { hmac(key, bytes, 0, bytes.length - CIPHER_HMAC_LENGTH, mac, 0); } catch (Exception e1) { log.warn("Unexpected error performing hmac on: ", input); return null; } boolean validCiphertext; try { validCiphertext = hmacEquals(key, bytes, bytes.length - CIPHER_HMAC_LENGTH, mac, 0); } catch (Exception e1) { log.warn("Unexpected error validating hmac of: ", input); return null; } if (!validCiphertext) { log.warn("Input was not encrypted with the current encryption key (bad HMAC): ", input); return null; } Cipher cipher = getCipher(key, Cipher.DECRYPT_MODE, bytes, 0, CIPHER_BLOCK_LENGTH); byte[] output; try { output = cipher.doFinal(bytes, CIPHER_BLOCK_LENGTH, bytes.length - CIPHER_HMAC_LENGTH - CIPHER_BLOCK_LENGTH); } catch (IllegalBlockSizeException e) { log.warn("Unexpected IllegalBlockSizeException on: ", input); return null; } catch (BadPaddingException e) { log.warn("Unexpected BadPaddingException on: ", input); return null; } return new String(output); } static String encrypt(String input); static String decrypt(String input); static synchronized void setSecretKey(SecretKey key); static final String CONFIG_ENCRYPTION_KEY; }### Answer:
@Test(groups = "fast") public void decryptNullTest() throws Exception { String input = null; String decrypted = CryptoUtil.decrypt(input); Assert.assertNull(decrypted, "Decrypting null should give back null."); }
@Test(groups = "fast") public void decryptBogusInputTest() throws Exception { String input = "_sipApTvfAXjncUGTRUf4OwZJBdz4Mbp2ZxqVyzkKio="; String decrypted = CryptoUtil.decrypt(input); Assert.assertNull(decrypted, "Decrypting a bogus input should give back null."); } |
### Question:
CryptoUtil { public static String encrypt(String input) { if (input == null) { input = ""; } Configuration configuration = StripesFilter.getConfiguration(); if (configuration != null && configuration.isDebugMode()) { return input; } try { byte[] inbytes = input.getBytes(); final int inputLength = inbytes.length; byte[] output = new byte[calculateCipherbytes(inputLength) + CIPHER_HMAC_LENGTH]; SecretKey key = getSecretKey(); byte[] iv = generateInitializationVector(); System.arraycopy(iv, 0, output, 0, CIPHER_BLOCK_LENGTH); Cipher cipher = getCipher(key, Cipher.ENCRYPT_MODE, iv, 0, CIPHER_BLOCK_LENGTH); cipher.doFinal(inbytes, 0, inbytes.length, output, CIPHER_BLOCK_LENGTH); hmac(key, output, 0, output.length - CIPHER_HMAC_LENGTH, output, output.length - CIPHER_HMAC_LENGTH); return Base64.encodeBytes(output, BASE64_OPTIONS); } catch (Exception e) { throw new StripesRuntimeException("Could not encrypt value.", e); } } static String encrypt(String input); static String decrypt(String input); static synchronized void setSecretKey(SecretKey key); static final String CONFIG_ENCRYPTION_KEY; }### Answer:
@Test(groups = "fast") public void failOnECB() throws Exception { String input1 = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; String encrypted1 = CryptoUtil.encrypt(input1); String encrypted2 = CryptoUtil.encrypt(input1); for (int i = 0; i < encrypted1.length() - 4; i++) { Assert.assertFalse( encrypted2.contains(encrypted1.substring(i, i + 4)), "Predictable ECB detected: " + encrypted1 + " " + encrypted2); } } |
### Question:
ReflectUtil { public static Method findAccessibleMethod(final Method m) { if (isPublic(m.getModifiers()) && isPublic(m.getDeclaringClass().getModifiers())) { return m; } if (m.isAccessible()) { return m; } final Class<?> clazz = m.getDeclaringClass(); final String name = m.getName(); final Class<?>[] ptypes = m.getParameterTypes(); for (Class<?> iface : clazz.getInterfaces()) { try { Method m2 = iface.getMethod(name, ptypes); if (m2.isAccessible()) { return m2; } if (isPublic(iface.getModifiers()) && isPublic(m2.getModifiers())) { return m2; } } catch (NoSuchMethodException nsme) { } } Class<?> c = clazz.getSuperclass(); while (c != null) { try { Method m2 = c.getMethod(name, ptypes); if (m2.isAccessible()) { return m2; } if (isPublic(c.getModifiers()) && isPublic(m2.getModifiers())) { return m2; } } catch (NoSuchMethodException nsme) { } c = c.getSuperclass(); } return m; } private ReflectUtil(); static boolean isDefault(Method method); @SuppressWarnings("rawtypes") // this allows us to assign without casting static Class findClass(String name); static String toString(Annotation ann); static Collection<Method> getMethods(Class<?> clazz); static Collection<Field> getFields(Class<?> clazz); static PropertyDescriptor getPropertyDescriptor(Class<?> clazz, String property); static Method findAccessibleMethod(final Method m); static Field getField(Class<?> clazz, String property); static Object getDefaultValue(Class<?> clazz); static Set<Class<?>> getImplementedInterfaces(Class<?> clazz); static Type[] getActualTypeArguments(Class<?> clazz, Class<?> targetType); static PropertyDescriptor[] getPropertyDescriptors(Class<?> clazz); static Method resolveBridgedReadMethod(PropertyDescriptor pd); static Method resolveBridgedWriteMethod(PropertyDescriptor pd); static Class<?> resolvePropertyType(PropertyDescriptor pd); }### Answer:
@Test(groups = "fast") public void testAccessibleMethodBaseCase() throws Exception { Method m = Object.class.getMethod("getClass"); Method m2 = ReflectUtil.findAccessibleMethod(m); Assert.assertSame(m, m2); } |
### Question:
ReflectUtil { public static PropertyDescriptor getPropertyDescriptor(Class<?> clazz, String property) { if (!propertyDescriptors.containsKey(clazz)) { getPropertyDescriptors(clazz); } return propertyDescriptors.get(clazz).get(property); } private ReflectUtil(); static boolean isDefault(Method method); @SuppressWarnings("rawtypes") // this allows us to assign without casting static Class findClass(String name); static String toString(Annotation ann); static Collection<Method> getMethods(Class<?> clazz); static Collection<Field> getFields(Class<?> clazz); static PropertyDescriptor getPropertyDescriptor(Class<?> clazz, String property); static Method findAccessibleMethod(final Method m); static Field getField(Class<?> clazz, String property); static Object getDefaultValue(Class<?> clazz); static Set<Class<?>> getImplementedInterfaces(Class<?> clazz); static Type[] getActualTypeArguments(Class<?> clazz, Class<?> targetType); static PropertyDescriptor[] getPropertyDescriptors(Class<?> clazz); static Method resolveBridgedReadMethod(PropertyDescriptor pd); static Method resolveBridgedWriteMethod(PropertyDescriptor pd); static Class<?> resolvePropertyType(PropertyDescriptor pd); }### Answer:
@Test(groups = "fast") public void testCovariantProperty() { abstract class Base { abstract Object getId(); } class ROSub extends Base { protected String id; @Override public String getId() { return id; } } class RWSub extends ROSub { @SuppressWarnings("unused") public void setId(String id) { this.id = id; } } PropertyDescriptor pd = ReflectUtil.getPropertyDescriptor(ROSub.class, "id"); Assert.assertNotNull(pd.getReadMethod(), "Read method is null"); Assert.assertNull(pd.getWriteMethod(), "Write method is not null"); pd = ReflectUtil.getPropertyDescriptor(RWSub.class, "id"); Assert.assertNotNull(pd.getReadMethod(), "Read method is null"); Assert.assertNotNull(pd.getWriteMethod(), "Write method is null"); } |
### Question:
ReflectUtil { public static Type[] getActualTypeArguments(Class<?> clazz, Class<?> targetType) { return getActualTypeArguments(clazz, targetType, null); } private ReflectUtil(); static boolean isDefault(Method method); @SuppressWarnings("rawtypes") // this allows us to assign without casting static Class findClass(String name); static String toString(Annotation ann); static Collection<Method> getMethods(Class<?> clazz); static Collection<Field> getFields(Class<?> clazz); static PropertyDescriptor getPropertyDescriptor(Class<?> clazz, String property); static Method findAccessibleMethod(final Method m); static Field getField(Class<?> clazz, String property); static Object getDefaultValue(Class<?> clazz); static Set<Class<?>> getImplementedInterfaces(Class<?> clazz); static Type[] getActualTypeArguments(Class<?> clazz, Class<?> targetType); static PropertyDescriptor[] getPropertyDescriptors(Class<?> clazz); static Method resolveBridgedReadMethod(PropertyDescriptor pd); static Method resolveBridgedWriteMethod(PropertyDescriptor pd); static Class<?> resolvePropertyType(PropertyDescriptor pd); }### Answer:
@Test(groups = "fast") public void testResolveTypeArgsOfSuperInterface() { class Impl implements C { } Type[] typeArgs = ReflectUtil.getActualTypeArguments(Impl.class, A.class); Assert.assertEquals(typeArgs.length, 3); Assert.assertEquals(typeArgs[0], Long.class); Assert.assertEquals(typeArgs[1], String.class); Assert.assertEquals(typeArgs[2], Integer.class); }
@Test(groups = "fast") public void testResolveTypeArgsOfSuperclass() { abstract class BaseClass1<S, T, U> { } abstract class BaseClass2<V, W> extends BaseClass1<W, String, V> {} class Impl1<X> extends BaseClass2<Integer, X> { } class Impl2 extends Impl1<Long> { } class Impl3 extends Impl2 { } Type[] typeArgs = ReflectUtil.getActualTypeArguments(Impl3.class, BaseClass1.class); Assert.assertEquals(typeArgs.length, 3); Assert.assertEquals(typeArgs[0], Long.class); Assert.assertEquals(typeArgs[1], String.class); Assert.assertEquals(typeArgs[2], Integer.class); } |
### Question:
AnnotatedClassActionResolver implements ActionResolver { public Class<? extends ActionBean> getActionBeanByName(String actionBeanName) { return actionBeansByName.get(actionBeanName); } @Override void init(Configuration configuration); UrlBindingFactory getUrlBindingFactory(); String getUrlBindingFromPath(String path); String getUrlBinding(Class<? extends ActionBean> clazz); String getHandledEvent(Method handler); Class<? extends ActionBean> getActionBeanType(String path); ActionBean getActionBean(ActionBeanContext context); ActionBean getActionBean(ActionBeanContext context, String path); String getEventName(Class<? extends ActionBean> bean, ActionBeanContext context); Method getHandler(Class<? extends ActionBean> bean, String eventName); Method getDefaultHandler(Class<? extends ActionBean> bean); Collection<Class<? extends ActionBean>> getActionBeanClasses(); Class<? extends ActionBean> getActionBeanByName(String actionBeanName); static final String PACKAGES; }### Answer:
@Test(groups = "fast") public void findByName() { Class<? extends ActionBean> actionBean = resolver.getActionBeanByName("SimpleActionBean"); Assert.assertNotNull(actionBean); }
@Test(groups = "fast") public void multipleActionBeansWithSameSimpleName() { Class<? extends ActionBean> actionBean = resolver.getActionBeanByName("OverloadedActionBean"); Assert.assertNull(actionBean); } |
### Question:
NameBasedActionResolver extends AnnotatedClassActionResolver { @Override public String getUrlBinding(Class<? extends ActionBean> clazz) { String binding = super.getUrlBinding(clazz); if (binding == null && !Modifier.isAbstract(clazz.getModifiers())) { binding = getUrlBinding(clazz.getName()); } return binding; } @Override void init(Configuration configuration); @Override String getUrlBinding(Class<? extends ActionBean> clazz); @Override String getHandledEvent(Method handler); static boolean isAsyncEventHandler(Method handler); @Override ActionBean getActionBean(ActionBeanContext context,
String urlBinding); static final Set<String> BASE_PACKAGES; static final String DEFAULT_BINDING_SUFFIX; static final List<String> DEFAULT_ACTION_BEAN_SUFFIXES; }### Answer:
@Test(groups = "fast") public void generateBinding() { String binding = this.resolver.getUrlBinding("foo.bar.web.admin.ControlCenterActionBean"); Assert.assertEquals(binding, "/admin/ControlCenter.action"); }
@Test(groups = "fast") public void generateBindingForNonPackagedClass() { String binding = this.resolver.getUrlBinding("ControlCenterActionBean"); Assert.assertEquals(binding, "/ControlCenter.action"); }
@Test(groups = "fast") public void generateBindingForClassWithSingleBasePackage() { String binding = this.resolver.getUrlBinding("www.ControlCenterActionBean"); Assert.assertEquals(binding, "/ControlCenter.action"); }
@Test(groups = "fast") public void generateBindingWithMultipleBasePackages() { String binding = this.resolver.getUrlBinding("foo.web.stripes.bar.www.ControlCenterActionBean"); Assert.assertEquals(binding, "/ControlCenter.action"); }
@Test(groups = "fast") public void generateBindingWithMultipleBasePackages2() { String binding = this.resolver.getUrlBinding("foo.web.stripes.www.admin.ControlCenterActionBean"); Assert.assertEquals(binding, "/admin/ControlCenter.action"); }
@Test(groups = "fast") public void generateBindingWithoutSuffix() { String binding = this.resolver.getUrlBinding("foo.web.stripes.www.admin.ControlCenter"); Assert.assertEquals(binding, "/admin/ControlCenter.action"); }
@Test(groups = "fast") public void generateBindingWithDifferentSuffix() { String binding = this.resolver.getUrlBinding("foo.web.stripes.www.admin.ControlCenterBean"); Assert.assertEquals(binding, "/admin/ControlCenter.action"); }
@Test(groups = "fast") public void generateBindingWithDifferentSuffix2() { String binding = this.resolver.getUrlBinding("foo.web.stripes.www.admin.ControlCenterAction"); Assert.assertEquals(binding, "/admin/ControlCenter.action"); }
@Test(groups = "fast") public void testWithAnnotatedClass() { String name = net.sourceforge.stripes.test.TestActionBean.class.getName(); String binding = this.resolver.getUrlBinding(name); Assert.assertEquals(binding, "/test/Test.action"); binding = this.resolver.getUrlBinding(net.sourceforge.stripes.test.TestActionBean.class); Assert.assertEquals(binding, net.sourceforge.stripes.test.TestActionBean.class. getAnnotation(UrlBinding.class).value()); } |
### Question:
NameBasedActionResolver extends AnnotatedClassActionResolver { protected List<String> getFindViewAttempts(String urlBinding) { List<String> attempts = new ArrayList<String>(3); int lastPeriod = urlBinding.lastIndexOf('.'); String path = urlBinding.substring(0, urlBinding.lastIndexOf("/") + 1); String name = (lastPeriod >= path.length()) ? urlBinding.substring(path.length(), lastPeriod) : urlBinding.substring(path.length()); if (name.length() > 0) { attempts.add(path + name + ".jsp"); name = Character.toLowerCase(name.charAt(0)) + name.substring(1); attempts.add(path + name + ".jsp"); StringBuilder builder = new StringBuilder(); for (int i = 0; i < name.length(); ++i) { char ch = name.charAt(i); if (Character.isUpperCase(ch)) { builder.append("_"); builder.append(Character.toLowerCase(ch)); } else { builder.append(ch); } } attempts.add(path + builder.toString() + ".jsp"); } return attempts; } @Override void init(Configuration configuration); @Override String getUrlBinding(Class<? extends ActionBean> clazz); @Override String getHandledEvent(Method handler); static boolean isAsyncEventHandler(Method handler); @Override ActionBean getActionBean(ActionBeanContext context,
String urlBinding); static final Set<String> BASE_PACKAGES; static final String DEFAULT_BINDING_SUFFIX; static final List<String> DEFAULT_ACTION_BEAN_SUFFIXES; }### Answer:
@Test(groups = "fast") public void testGetFindViewAttempts() { String urlBinding = "/account/ViewAccount.action"; List<String> viewAttempts = this.resolver.getFindViewAttempts(urlBinding); Assert.assertEquals(viewAttempts.size(), 3); Assert.assertEquals(viewAttempts.get(0), "/account/ViewAccount.jsp"); Assert.assertEquals(viewAttempts.get(1), "/account/viewAccount.jsp"); Assert.assertEquals(viewAttempts.get(2), "/account/view_account.jsp"); } |
### Question:
LocalizationUtility { public static String makePseudoFriendlyName(String fieldNameKey) { StringBuilder builder = new StringBuilder(fieldNameKey.length() + 10); char[] characters = fieldNameKey.toCharArray(); builder.append(Character.toUpperCase(characters[0])); boolean upcaseNextChar = false; for (int i = 1; i < characters.length; ++i) { if (characters[i] == '.') { builder.append(' '); upcaseNextChar = true; } else if (Character.isUpperCase(characters[i])) { builder.append(' ').append(characters[i]); upcaseNextChar = false; } else if (upcaseNextChar) { builder.append(Character.toUpperCase(characters[i])); upcaseNextChar = false; } else { builder.append(characters[i]); upcaseNextChar = false; } } return builder.toString(); } static String getLocalizedFieldName(String fieldName,
String actionPath,
Class<? extends ActionBean> beanclass,
Locale locale); static String makePseudoFriendlyName(String fieldNameKey); static String getErrorMessage(Locale locale, String key); static String getSimpleName(Class<?> c); }### Answer:
@Test(groups = "fast") public void testBaseCase() throws Exception { String input = "Hello"; String output = LocalizationUtility.makePseudoFriendlyName(input); Assert.assertEquals(output, input); }
@Test(groups = "fast") public void testSimpleCase() throws Exception { String input = "hello"; String output = LocalizationUtility.makePseudoFriendlyName(input); Assert.assertEquals(output, "Hello"); }
@Test(groups = "fast") public void testWithPeriod() throws Exception { String input = "bug.name"; String output = LocalizationUtility.makePseudoFriendlyName(input); Assert.assertEquals(output, "Bug Name"); }
@Test(groups = "fast") public void testWithStudlyCaps() throws Exception { String input = "bugName"; String output = LocalizationUtility.makePseudoFriendlyName(input); Assert.assertEquals(output, "Bug Name"); }
@Test(groups = "fast") public void testComplexName() throws Exception { String input = "bug.submittedBy.firstName"; String output = LocalizationUtility.makePseudoFriendlyName(input); Assert.assertEquals(output, "Bug Submitted By First Name"); } |
### Question:
LocalizationUtility { public static String getSimpleName(Class<?> c) { if (c.getEnclosingClass() == null) { return c.getSimpleName(); } else { return prefixSimpleName(new StringBuilder(), c).toString(); } } static String getLocalizedFieldName(String fieldName,
String actionPath,
Class<? extends ActionBean> beanclass,
Locale locale); static String makePseudoFriendlyName(String fieldNameKey); static String getErrorMessage(Locale locale, String key); static String getSimpleName(Class<?> c); }### Answer:
@Test(groups = "fast") public void testSimpleClassName() throws Exception { String output = LocalizationUtility.getSimpleName(TestEnum.class); Assert.assertEquals(output, "LocalizationUtilityTest.TestEnum"); output = LocalizationUtility.getSimpleName(A.B.C.class); Assert.assertEquals(output, "LocalizationUtilityTest.A.B.C"); } |
### Question:
MockRoundtrip { public void addParameter(String name, String... value) { if (this.request.getParameterValues(name) == null) { setParameter(name, value); } else { String[] oldValues = this.request.getParameterMap().get(name); String[] combined = new String[oldValues.length + value.length]; System.arraycopy(oldValues, 0, combined, 0, oldValues.length); System.arraycopy(value, 0, combined, oldValues.length, value.length); setParameter(name, combined); } } MockRoundtrip(MockServletContext context, Class<? extends ActionBean> beanType); MockRoundtrip(MockServletContext context,
Class<? extends ActionBean> beanType,
MockHttpSession session); MockRoundtrip(MockServletContext context, String actionBeanUrl); MockRoundtrip(MockServletContext context, String actionBeanUrl, MockHttpSession session); MockHttpServletRequest getRequest(); MockHttpServletResponse getResponse(); MockServletContext getContext(); void setParameter(String name, String... value); void addParameter(String name, String... value); void setSourcePage(String url); void execute(); void execute(String event); @SuppressWarnings("unchecked") A getActionBean(Class<A> type); ValidationErrors getValidationErrors(); List<Message> getMessages(); byte[] getOutputBytes(); String getOutputString(); String getDestination(); String getForwardUrl(); String getRedirectUrl(); static final String DEFAULT_SOURCE_PAGE; }### Answer:
@Test(groups = "fast") public void testAddParameter() throws Exception { MockRoundtrip trip = new MockRoundtrip(getMockServletContext(), TestMockRoundtrip.class); trip.addParameter("param", "a"); trip.addParameter("param", "b"); trip.execute(); TestMockRoundtrip bean = trip.getActionBean(TestMockRoundtrip.class); String[] params = bean.getContext().getRequest().getParameterValues("param"); Assert.assertEquals(2, params.length); Assert.assertEquals(new String[]{"a", "b"}, params); } |
### Question:
RedirectResolution extends OnwardResolution<RedirectResolution> { @SuppressWarnings("unchecked") @Override public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (permanent) { response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); response = new HttpServletResponseWrapper(response) { @Override public void setStatus(int sc) { } @Override public void sendRedirect(String location) throws IOException { setHeader("Location", location); } }; } if (this.includeRequestParameters) { addParameters(request.getParameterMap()); } if (this.beans != null) { FlashScope flash = FlashScope.getCurrent(request, true); for (ActionBean bean : this.beans) { flash.put(bean); } } FlashScope flash = FlashScope.getCurrent(request, false); if (flash != null) { addParameter(StripesConstants.URL_KEY_FLASH_SCOPE_ID, flash.key()); } String url = getUrl(request.getLocale()); if (prependContext) { String contextPath = request.getContextPath(); if (contextPath.length() > 1) { url = contextPath + url; } } url = response.encodeRedirectURL(url); log.trace("Redirecting ", this.beans == null ? "" : "(w/flashed bean) ", "to URL: ", url); response.sendRedirect(url); AsyncResponse asyncResponse = AsyncResponse.get(request); if (asyncResponse != null) { asyncResponse.complete(); } } RedirectResolution(String url); RedirectResolution(String url, boolean prependContext); RedirectResolution(Class<? extends ActionBean> beanType); RedirectResolution(Class<? extends ActionBean> beanType, String event); @Override String getAnchor(); @Override RedirectResolution setAnchor(String anchor); RedirectResolution includeRequestParameters(boolean inc); RedirectResolution flash(ActionBean bean); @SuppressWarnings("unchecked") @Override void execute(HttpServletRequest request, HttpServletResponse response); RedirectResolution setPermanent(boolean permanent); }### Answer:
@Test(groups = "fast") public void testTemporaryRedirect() throws Exception { RedirectResolution resolution = new RedirectResolution("http: MockHttpServletResponse response = new MockHttpServletResponse(); resolution.execute(buildMockServletRequest(), response); Assert.assertEquals(response.getStatus(), HttpServletResponse.SC_MOVED_TEMPORARILY); Assert.assertEquals(response.getRedirectUrl(), "http: }
@Test(groups = "fast") public void testTemporaryRedirectWithParameters() throws Exception { RedirectResolution resolution = new RedirectResolution("http: MockHttpServletResponse response = new MockHttpServletResponse(); resolution.execute(buildMockServletRequest(), response); Assert.assertEquals(response.getStatus(), HttpServletResponse.SC_MOVED_TEMPORARILY); Assert.assertEquals(response.getRedirectUrl(), "http: } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.