formatting work

This commit is contained in:
eugenp 2017-08-24 15:30:33 +03:00
parent 1cba1b043c
commit b00a9e61bc
36 changed files with 628 additions and 616 deletions

View File

@ -16,7 +16,8 @@ import java.util.UUID;
public class JWTCsrfTokenRepository implements CsrfTokenRepository { public class JWTCsrfTokenRepository implements CsrfTokenRepository {
private static final String DEFAULT_CSRF_TOKEN_ATTR_NAME = CSRFConfig.class.getName().concat(".CSRF_TOKEN"); private static final String DEFAULT_CSRF_TOKEN_ATTR_NAME = CSRFConfig.class.getName()
.concat(".CSRF_TOKEN");
private static final Logger log = LoggerFactory.getLogger(JWTCsrfTokenRepository.class); private static final Logger log = LoggerFactory.getLogger(JWTCsrfTokenRepository.class);
private byte[] secret; private byte[] secret;
@ -27,7 +28,9 @@ public class JWTCsrfTokenRepository implements CsrfTokenRepository {
@Override @Override
public CsrfToken generateToken(HttpServletRequest request) { public CsrfToken generateToken(HttpServletRequest request) {
String id = UUID.randomUUID().toString().replace("-", ""); String id = UUID.randomUUID()
.toString()
.replace("-", "");
Date now = new Date(); Date now = new Date();
Date exp = new Date(System.currentTimeMillis() + (1000 * 30)); // 30 seconds Date exp = new Date(System.currentTimeMillis() + (1000 * 30)); // 30 seconds
@ -50,8 +53,7 @@ public class JWTCsrfTokenRepository implements CsrfTokenRepository {
if (session != null) { if (session != null) {
session.removeAttribute(DEFAULT_CSRF_TOKEN_ATTR_NAME); session.removeAttribute(DEFAULT_CSRF_TOKEN_ATTR_NAME);
} }
} } else {
else {
HttpSession session = request.getSession(); HttpSession session = request.getSession();
session.setAttribute(DEFAULT_CSRF_TOKEN_ATTR_NAME, token); session.setAttribute(DEFAULT_CSRF_TOKEN_ATTR_NAME, token);
} }

View File

@ -30,21 +30,16 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
SecretService secretService; SecretService secretService;
// ordered so we can use binary search below // ordered so we can use binary search below
private String[] ignoreCsrfAntMatchers = { private String[] ignoreCsrfAntMatchers = { "/dynamic-builder-compress", "/dynamic-builder-general", "/dynamic-builder-specific", "/set-secrets" };
"/dynamic-builder-compress",
"/dynamic-builder-general",
"/dynamic-builder-specific",
"/set-secrets"
};
@Override @Override
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http http.addFilterAfter(new JwtCsrfValidatorFilter(), CsrfFilter.class)
.addFilterAfter(new JwtCsrfValidatorFilter(), CsrfFilter.class)
.csrf() .csrf()
.csrfTokenRepository(jwtCsrfTokenRepository) .csrfTokenRepository(jwtCsrfTokenRepository)
.ignoringAntMatchers(ignoreCsrfAntMatchers) .ignoringAntMatchers(ignoreCsrfAntMatchers)
.and().authorizeRequests() .and()
.authorizeRequests()
.antMatchers("/**") .antMatchers("/**")
.permitAll(); .permitAll();
} }
@ -63,8 +58,7 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
// ignore if the request path is in our list // ignore if the request path is in our list
Arrays.binarySearch(ignoreCsrfAntMatchers, request.getServletPath()) < 0 && Arrays.binarySearch(ignoreCsrfAntMatchers, request.getServletPath()) < 0 &&
// make sure we have a token // make sure we have a token
token != null token != null) {
) {
// CsrfFilter already made sure the token matched. Here, we'll make sure it's not expired // CsrfFilter already made sure the token matched. Here, we'll make sure it's not expired
try { try {
Jwts.parser() Jwts.parser()

View File

@ -16,7 +16,8 @@ public class BaseController {
JwtResponse response = new JwtResponse(); JwtResponse response = new JwtResponse();
response.setStatus(JwtResponse.Status.ERROR); response.setStatus(JwtResponse.Status.ERROR);
response.setMessage(e.getMessage()); response.setMessage(e.getMessage());
response.setExceptionType(e.getClass().getName()); response.setExceptionType(e.getClass()
.getName());
return response; return response;
} }

View File

@ -29,10 +29,7 @@ public class DynamicJWTController extends BaseController {
public JwtResponse dynamicBuilderGeneric(@RequestBody Map<String, Object> claims) throws UnsupportedEncodingException { public JwtResponse dynamicBuilderGeneric(@RequestBody Map<String, Object> claims) throws UnsupportedEncodingException {
String jws = Jwts.builder() String jws = Jwts.builder()
.setClaims(claims) .setClaims(claims)
.signWith( .signWith(SignatureAlgorithm.HS256, secretService.getHS256SecretBytes())
SignatureAlgorithm.HS256,
secretService.getHS256SecretBytes()
)
.compact(); .compact();
return new JwtResponse(jws); return new JwtResponse(jws);
} }
@ -42,10 +39,7 @@ public class DynamicJWTController extends BaseController {
String jws = Jwts.builder() String jws = Jwts.builder()
.setClaims(claims) .setClaims(claims)
.compressWith(CompressionCodecs.DEFLATE) .compressWith(CompressionCodecs.DEFLATE)
.signWith( .signWith(SignatureAlgorithm.HS256, secretService.getHS256SecretBytes())
SignatureAlgorithm.HS256,
secretService.getHS256SecretBytes()
)
.compact(); .compact();
return new JwtResponse(jws); return new JwtResponse(jws);
} }
@ -95,13 +89,11 @@ public class DynamicJWTController extends BaseController {
} }
private void ensureType(String registeredClaim, Object value, Class expectedType) { private void ensureType(String registeredClaim, Object value, Class expectedType) {
boolean isCorrectType = boolean isCorrectType = expectedType.isInstance(value) || expectedType == Long.class && value instanceof Integer;
expectedType.isInstance(value) ||
expectedType == Long.class && value instanceof Integer;
if (!isCorrectType) { if (!isCorrectType) {
String msg = "Expected type: " + expectedType.getCanonicalName() + " for registered claim: '" + String msg = "Expected type: " + expectedType.getCanonicalName() + " for registered claim: '" + registeredClaim + "', but got value: " + value + " of type: " + value.getClass()
registeredClaim + "', but got value: " + value + " of type: " + value.getClass().getCanonicalName(); .getCanonicalName();
throw new JwtException(msg); throw new JwtException(msg);
} }
} }

View File

@ -11,22 +11,16 @@ public class HomeController {
@RequestMapping("/") @RequestMapping("/")
public String home(HttpServletRequest req) { public String home(HttpServletRequest req) {
String requestUrl = getUrl(req); String requestUrl = getUrl(req);
return "Available commands (assumes httpie - https://github.com/jkbrzt/httpie):\n\n" + return "Available commands (assumes httpie - https://github.com/jkbrzt/httpie):\n\n" + " http " + requestUrl + "/\n\tThis usage message\n\n" + " http " + requestUrl + "/static-builder\n\tbuild JWT from hardcoded claims\n\n" + " http POST "
" http " + requestUrl + "/\n\tThis usage message\n\n" + + requestUrl + "/dynamic-builder-general claim-1=value-1 ... [claim-n=value-n]\n\tbuild JWT from passed in claims (using general claims map)\n\n" + " http POST " + requestUrl
" http " + requestUrl + "/static-builder\n\tbuild JWT from hardcoded claims\n\n" + + "/dynamic-builder-specific claim-1=value-1 ... [claim-n=value-n]\n\tbuild JWT from passed in claims (using specific claims methods)\n\n" + " http POST " + requestUrl
" http POST " + requestUrl + "/dynamic-builder-general claim-1=value-1 ... [claim-n=value-n]\n\tbuild JWT from passed in claims (using general claims map)\n\n" + + "/dynamic-builder-compress claim-1=value-1 ... [claim-n=value-n]\n\tbuild DEFLATE compressed JWT from passed in claims\n\n" + " http " + requestUrl + "/parser?jwt=<jwt>\n\tParse passed in JWT\n\n" + " http " + requestUrl
" http POST " + requestUrl + "/dynamic-builder-specific claim-1=value-1 ... [claim-n=value-n]\n\tbuild JWT from passed in claims (using specific claims methods)\n\n" + + "/parser-enforce?jwt=<jwt>\n\tParse passed in JWT enforcing the 'iss' registered claim and the 'hasMotorcycle' custom claim\n\n" + " http " + requestUrl + "/get-secrets\n\tShow the signing keys currently in use.\n\n" + " http " + requestUrl
" http POST " + requestUrl + "/dynamic-builder-compress claim-1=value-1 ... [claim-n=value-n]\n\tbuild DEFLATE compressed JWT from passed in claims\n\n" + + "/refresh-secrets\n\tGenerate new signing keys and show them.\n\n" + " http POST " + requestUrl
" http " + requestUrl + "/parser?jwt=<jwt>\n\tParse passed in JWT\n\n" + + "/set-secrets HS256=base64-encoded-value HS384=base64-encoded-value HS512=base64-encoded-value\n\tExplicitly set secrets to use in the application.";
" http " + requestUrl + "/parser-enforce?jwt=<jwt>\n\tParse passed in JWT enforcing the 'iss' registered claim and the 'hasMotorcycle' custom claim\n\n" +
" http " + requestUrl + "/get-secrets\n\tShow the signing keys currently in use.\n\n" +
" http " + requestUrl + "/refresh-secrets\n\tGenerate new signing keys and show them.\n\n" +
" http POST " + requestUrl + "/set-secrets HS256=base64-encoded-value HS384=base64-encoded-value HS512=base64-encoded-value\n\tExplicitly set secrets to use in the application.";
} }
private String getUrl(HttpServletRequest req) { private String getUrl(HttpServletRequest req) {
return req.getScheme() + "://" + return req.getScheme() + "://" + req.getServerName() + ((req.getServerPort() == 80 || req.getServerPort() == 443) ? "" : ":" + req.getServerPort());
req.getServerName() +
((req.getServerPort() == 80 || req.getServerPort() == 443) ? "" : ":" + req.getServerPort());
} }
} }

View File

@ -32,10 +32,7 @@ public class StaticJWTController extends BaseController {
.claim("scope", "admins") .claim("scope", "admins")
.setIssuedAt(Date.from(Instant.ofEpochSecond(1466796822L))) // Fri Jun 24 2016 15:33:42 GMT-0400 (EDT) .setIssuedAt(Date.from(Instant.ofEpochSecond(1466796822L))) // Fri Jun 24 2016 15:33:42 GMT-0400 (EDT)
.setExpiration(Date.from(Instant.ofEpochSecond(4622470422L))) // Sat Jun 24 2116 15:33:42 GMT-0400 (EDT) .setExpiration(Date.from(Instant.ofEpochSecond(4622470422L))) // Sat Jun 24 2116 15:33:42 GMT-0400 (EDT)
.signWith( .signWith(SignatureAlgorithm.HS256, secretService.getHS256SecretBytes())
SignatureAlgorithm.HS256,
secretService.getHS256SecretBytes()
)
.compact(); .compact();
return new JwtResponse(jws); return new JwtResponse(jws);

View File

@ -16,7 +16,8 @@ public class JwtResponse {
SUCCESS, ERROR SUCCESS, ERROR
} }
public JwtResponse() {} public JwtResponse() {
}
public JwtResponse(String jwt) { public JwtResponse(String jwt) {
this.jwt = jwt; this.jwt = jwt;

View File

@ -61,7 +61,6 @@ public class SecretService {
return TextCodec.BASE64.decode(secrets.get(SignatureAlgorithm.HS384.getValue())); return TextCodec.BASE64.decode(secrets.get(SignatureAlgorithm.HS384.getValue()));
} }
public Map<String, String> refreshSecrets() { public Map<String, String> refreshSecrets() {
SecretKey key = MacProvider.generateKey(SignatureAlgorithm.HS256); SecretKey key = MacProvider.generateKey(SignatureAlgorithm.HS256);
secrets.put(SignatureAlgorithm.HS256.getValue(), TextCodec.BASE64.encode(key.getEncoded())); secrets.put(SignatureAlgorithm.HS256.getValue(), TextCodec.BASE64.encode(key.getEncoded()));

View File

@ -50,13 +50,17 @@ public class StoredProcedureIntegrationTest {
public void findCarsByYearNamedProcedure() { public void findCarsByYearNamedProcedure() {
final StoredProcedureQuery findByYearProcedure = entityManager.createNamedStoredProcedureQuery("findByYearProcedure"); final StoredProcedureQuery findByYearProcedure = entityManager.createNamedStoredProcedureQuery("findByYearProcedure");
final StoredProcedureQuery storedProcedure = findByYearProcedure.setParameter("p_year", 2015); final StoredProcedureQuery storedProcedure = findByYearProcedure.setParameter("p_year", 2015);
storedProcedure.getResultList().forEach(c -> Assert.assertEquals(new Integer(2015), ((Car) c).getYear())); storedProcedure.getResultList()
.forEach(c -> Assert.assertEquals(new Integer(2015), ((Car) c).getYear()));
} }
@Test @Test
public void findCarsByYearNoNamed() { public void findCarsByYearNoNamed() {
final StoredProcedureQuery storedProcedure = entityManager.createStoredProcedureQuery("FIND_CAR_BY_YEAR", Car.class).registerStoredProcedureParameter(1, Integer.class, ParameterMode.IN).setParameter(1, 2015); final StoredProcedureQuery storedProcedure = entityManager.createStoredProcedureQuery("FIND_CAR_BY_YEAR", Car.class)
storedProcedure.getResultList().forEach(c -> Assert.assertEquals(new Integer(2015), ((Car) c).getYear())); .registerStoredProcedureParameter(1, Integer.class, ParameterMode.IN)
.setParameter(1, 2015);
storedProcedure.getResultList()
.forEach(c -> Assert.assertEquals(new Integer(2015), ((Car) c).getYear()));
} }
@AfterClass @AfterClass

View File

@ -27,10 +27,14 @@ public class ELSampleBean {
@PostConstruct @PostConstruct
public void init() { public void init() {
pageCounter = randomIntGen.nextInt(); pageCounter = randomIntGen.nextInt();
FacesContext.getCurrentInstance().getApplication().addELContextListener(new ELContextListener() { FacesContext.getCurrentInstance()
.getApplication()
.addELContextListener(new ELContextListener() {
@Override @Override
public void contextCreated(ELContextEvent evt) { public void contextCreated(ELContextEvent evt) {
evt.getELContext().getImportHandler().importClass("com.baeldung.springintegration.controllers.ELSampleBean"); evt.getELContext()
.getImportHandler()
.importClass("com.baeldung.springintegration.controllers.ELSampleBean");
} }
}); });
} }
@ -48,7 +52,8 @@ public class ELSampleBean {
} }
public Long multiplyValue(LambdaExpression expr) { public Long multiplyValue(LambdaExpression expr) {
Long theResult = (Long) expr.invoke(FacesContext.getCurrentInstance().getELContext(), pageCounter); Long theResult = (Long) expr.invoke(FacesContext.getCurrentInstance()
.getELContext(), pageCounter);
return theResult; return theResult;
} }

View File

@ -1,6 +1,5 @@
package com.baeldung.springintegration.dao; package com.baeldung.springintegration.dao;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
@ -34,5 +33,4 @@ public class UserManagementDAOImpl implements UserManagementDAO {
public UserManagementDAOImpl() { public UserManagementDAOImpl() {
} }
} }

View File

@ -18,8 +18,11 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat; import static org.junit.Assert.assertThat;
public class OperationIntegrationTest { public class OperationIntegrationTest {
private InputStream jsonInputStream = this.getClass().getClassLoader().getResourceAsStream("intro_api.json"); private InputStream jsonInputStream = this.getClass()
private String jsonDataSourceString = new Scanner(jsonInputStream, "UTF-8").useDelimiter("\\Z").next(); .getClassLoader()
.getResourceAsStream("intro_api.json");
private String jsonDataSourceString = new Scanner(jsonInputStream, "UTF-8").useDelimiter("\\Z")
.next();
@Test @Test
public void givenJsonPathWithoutPredicates_whenReading_thenCorrect() { public void givenJsonPathWithoutPredicates_whenReading_thenCorrect() {
@ -38,21 +41,27 @@ public class OperationIntegrationTest {
@Test @Test
public void givenJsonPathWithFilterPredicate_whenReading_thenCorrect() { public void givenJsonPathWithFilterPredicate_whenReading_thenCorrect() {
Filter expensiveFilter = Filter.filter(Criteria.where("price").gt(20.00)); Filter expensiveFilter = Filter.filter(Criteria.where("price")
List<Map<String, Object>> expensive = JsonPath.parse(jsonDataSourceString).read("$['book'][?]", expensiveFilter); .gt(20.00));
List<Map<String, Object>> expensive = JsonPath.parse(jsonDataSourceString)
.read("$['book'][?]", expensiveFilter);
predicateUsageAssertionHelper(expensive); predicateUsageAssertionHelper(expensive);
} }
@Test @Test
public void givenJsonPathWithCustomizedPredicate_whenReading_thenCorrect() { public void givenJsonPathWithCustomizedPredicate_whenReading_thenCorrect() {
Predicate expensivePredicate = context -> Float.valueOf(context.item(Map.class).get("price").toString()) > 20.00; Predicate expensivePredicate = context -> Float.valueOf(context.item(Map.class)
List<Map<String, Object>> expensive = JsonPath.parse(jsonDataSourceString).read("$['book'][?]", expensivePredicate); .get("price")
.toString()) > 20.00;
List<Map<String, Object>> expensive = JsonPath.parse(jsonDataSourceString)
.read("$['book'][?]", expensivePredicate);
predicateUsageAssertionHelper(expensive); predicateUsageAssertionHelper(expensive);
} }
@Test @Test
public void givenJsonPathWithInlinePredicate_whenReading_thenCorrect() { public void givenJsonPathWithInlinePredicate_whenReading_thenCorrect() {
List<Map<String, Object>> expensive = JsonPath.parse(jsonDataSourceString).read("$['book'][?(@['price'] > $['price range']['medium'])]"); List<Map<String, Object>> expensive = JsonPath.parse(jsonDataSourceString)
.read("$['book'][?(@['price'] > $['price range']['medium'])]");
predicateUsageAssertionHelper(expensive); predicateUsageAssertionHelper(expensive);
} }

View File

@ -18,12 +18,16 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat; import static org.junit.Assert.assertThat;
public class ServiceTest { public class ServiceTest {
private InputStream jsonInputStream = this.getClass().getClassLoader().getResourceAsStream("intro_service.json"); private InputStream jsonInputStream = this.getClass()
private String jsonString = new Scanner(jsonInputStream, "UTF-8").useDelimiter("\\Z").next(); .getClassLoader()
.getResourceAsStream("intro_service.json");
private String jsonString = new Scanner(jsonInputStream, "UTF-8").useDelimiter("\\Z")
.next();
@Test @Test
public void givenId_whenRequestingRecordData_thenSucceed() { public void givenId_whenRequestingRecordData_thenSucceed() {
Object dataObject = JsonPath.parse(jsonString).read("$[?(@.id == 2)]"); Object dataObject = JsonPath.parse(jsonString)
.read("$[?(@.id == 2)]");
String dataString = dataObject.toString(); String dataString = dataObject.toString();
assertThat(dataString, containsString("2")); assertThat(dataString, containsString("2"));
@ -33,8 +37,10 @@ public class ServiceTest {
@Test @Test
public void givenStarring_whenRequestingMovieTitle_thenSucceed() { public void givenStarring_whenRequestingMovieTitle_thenSucceed() {
List<Map<String, Object>> dataList = JsonPath.parse(jsonString).read("$[?('Eva Green' in @['starring'])]"); List<Map<String, Object>> dataList = JsonPath.parse(jsonString)
String title = (String) dataList.get(0).get("title"); .read("$[?('Eva Green' in @['starring'])]");
String title = (String) dataList.get(0)
.get("title");
assertEquals("Casino Royale", title); assertEquals("Casino Royale", title);
} }
@ -59,8 +65,12 @@ public class ServiceTest {
Arrays.sort(revenueArray); Arrays.sort(revenueArray);
int highestRevenue = revenueArray[revenueArray.length - 1]; int highestRevenue = revenueArray[revenueArray.length - 1];
Configuration pathConfiguration = Configuration.builder().options(Option.AS_PATH_LIST).build(); Configuration pathConfiguration = Configuration.builder()
List<String> pathList = JsonPath.using(pathConfiguration).parse(jsonString).read("$[?(@['box office'] == " + highestRevenue + ")]"); .options(Option.AS_PATH_LIST)
.build();
List<String> pathList = JsonPath.using(pathConfiguration)
.parse(jsonString)
.read("$[?(@['box office'] == " + highestRevenue + ")]");
Map<String, String> dataRecord = context.read(pathList.get(0)); Map<String, String> dataRecord = context.read(pathList.get(0));
String title = dataRecord.get("title"); String title = dataRecord.get("title");
@ -83,7 +93,8 @@ public class ServiceTest {
long latestTime = dateArray[dateArray.length - 1]; long latestTime = dateArray[dateArray.length - 1];
List<Map<String, Object>> finalDataList = context.read("$[?(@['director'] == 'Sam Mendes' && @['release date'] == " + latestTime + ")]"); List<Map<String, Object>> finalDataList = context.read("$[?(@['director'] == 'Sam Mendes' && @['release date'] == " + latestTime + ")]");
String title = (String) finalDataList.get(0).get("title"); String title = (String) finalDataList.get(0)
.get("title");
assertEquals("Spectre", title); assertEquals("Spectre", title);
} }

View File

@ -32,11 +32,7 @@ public class FastJsonUnitTest {
@Test @Test
public void whenJavaList_thanConvertToJsonCorrect() { public void whenJavaList_thanConvertToJsonCorrect() {
String personJsonFormat = JSON.toJSONString(listOfPersons); String personJsonFormat = JSON.toJSONString(listOfPersons);
assertEquals( assertEquals(personJsonFormat, "[{\"FIRST NAME\":\"Doe\",\"LAST NAME\":\"John\",\"DATE OF BIRTH\":" + "\"24/07/2016\"},{\"FIRST NAME\":\"Doe\",\"LAST NAME\":\"Janette\",\"DATE OF BIRTH\":" + "\"24/07/2016\"}]");
personJsonFormat,
"[{\"FIRST NAME\":\"Doe\",\"LAST NAME\":\"John\",\"DATE OF BIRTH\":"
+ "\"24/07/2016\"},{\"FIRST NAME\":\"Doe\",\"LAST NAME\":\"Janette\",\"DATE OF BIRTH\":"
+ "\"24/07/2016\"}]");
} }
@Test @Test
@ -44,8 +40,10 @@ public class FastJsonUnitTest {
String personJsonFormat = JSON.toJSONString(listOfPersons.get(0)); String personJsonFormat = JSON.toJSONString(listOfPersons.get(0));
Person newPerson = JSON.parseObject(personJsonFormat, Person.class); Person newPerson = JSON.parseObject(personJsonFormat, Person.class);
assertEquals(newPerson.getAge(), 0); // serialize is set to false for age attribute assertEquals(newPerson.getAge(), 0); // serialize is set to false for age attribute
assertEquals(newPerson.getFirstName(), listOfPersons.get(0).getFirstName()); assertEquals(newPerson.getFirstName(), listOfPersons.get(0)
assertEquals(newPerson.getLastName(), listOfPersons.get(0).getLastName()); .getFirstName());
assertEquals(newPerson.getLastName(), listOfPersons.get(0)
.getLastName());
} }
@Test @Test
@ -58,18 +56,13 @@ public class FastJsonUnitTest {
jsonObject.put("DATE OF BIRTH", "2016/12/12 12:12:12"); jsonObject.put("DATE OF BIRTH", "2016/12/12 12:12:12");
jsonArray.add(jsonObject); jsonArray.add(jsonObject);
} }
assertEquals( assertEquals(jsonArray.toString(), "[{\"LAST NAME\":\"Doe0\",\"DATE OF BIRTH\":" + "\"2016/12/12 12:12:12\",\"FIRST NAME\":\"John0\"},{\"LAST NAME\":\"Doe1\"," + "\"DATE OF BIRTH\":\"2016/12/12 12:12:12\",\"FIRST NAME\":\"John1\"}]");
jsonArray.toString(),
"[{\"LAST NAME\":\"Doe0\",\"DATE OF BIRTH\":"
+ "\"2016/12/12 12:12:12\",\"FIRST NAME\":\"John0\"},{\"LAST NAME\":\"Doe1\","
+ "\"DATE OF BIRTH\":\"2016/12/12 12:12:12\",\"FIRST NAME\":\"John1\"}]");
} }
@Test @Test
public void givenContextFilter_whenJavaObject_thanJsonCorrect() { public void givenContextFilter_whenJavaObject_thanJsonCorrect() {
ContextValueFilter valueFilter = new ContextValueFilter() { ContextValueFilter valueFilter = new ContextValueFilter() {
public Object process(BeanContext context, Object object, public Object process(BeanContext context, Object object, String name, Object value) {
String name, Object value) {
if (name.equals("DATE OF BIRTH")) { if (name.equals("DATE OF BIRTH")) {
return "NOT TO DISCLOSE"; return "NOT TO DISCLOSE";
} }
@ -87,18 +80,16 @@ public class FastJsonUnitTest {
public void givenSerializeConfig_whenJavaObject_thanJsonCorrect() { public void givenSerializeConfig_whenJavaObject_thanJsonCorrect() {
NameFilter formatName = new NameFilter() { NameFilter formatName = new NameFilter() {
public String process(Object object, String name, Object value) { public String process(Object object, String name, Object value) {
return name.toLowerCase().replace(" ", "_"); return name.toLowerCase()
.replace(" ", "_");
} }
}; };
SerializeConfig.getGlobalInstance().addFilter(Person.class, formatName); SerializeConfig.getGlobalInstance()
String jsonOutput = JSON.toJSONStringWithDateFormat(listOfPersons, .addFilter(Person.class, formatName);
"yyyy-MM-dd"); String jsonOutput = JSON.toJSONStringWithDateFormat(listOfPersons, "yyyy-MM-dd");
assertEquals( assertEquals(jsonOutput, "[{\"first_name\":\"Doe\",\"last_name\":\"John\"," + "\"date_of_birth\":\"2016-07-24\"},{\"first_name\":\"Doe\",\"last_name\":" + "\"Janette\",\"date_of_birth\":\"2016-07-24\"}]");
jsonOutput,
"[{\"first_name\":\"Doe\",\"last_name\":\"John\","
+ "\"date_of_birth\":\"2016-07-24\"},{\"first_name\":\"Doe\",\"last_name\":"
+ "\"Janette\",\"date_of_birth\":\"2016-07-24\"}]");
// resetting custom serializer // resetting custom serializer
SerializeConfig.getGlobalInstance().put(Person.class, null); SerializeConfig.getGlobalInstance()
.put(Person.class, null);
} }
} }

View File

@ -32,8 +32,7 @@ public class Person {
@Override @Override
public String toString() { public String toString() {
return "Person [age=" + age + ", lastName=" + lastName + ", firstName=" return "Person [age=" + age + ", lastName=" + lastName + ", firstName=" + firstName + ", dateOfBirth=" + dateOfBirth + "]";
+ firstName + ", dateOfBirth=" + dateOfBirth + "]";
} }
public int getAge() { public int getAge() {

View File

@ -20,13 +20,15 @@ public class JsoupParserIntegrationTest {
@Before @Before
public void setUp() throws IOException { public void setUp() throws IOException {
doc = Jsoup.connect("https://spring.io/blog").get(); doc = Jsoup.connect("https://spring.io/blog")
.get();
} }
@Test @Test
public void loadDocument404() throws IOException { public void loadDocument404() throws IOException {
try { try {
doc = Jsoup.connect("https://spring.io/will-not-be-found").get(); doc = Jsoup.connect("https://spring.io/will-not-be-found")
.get();
} catch (HttpStatusException ex) { } catch (HttpStatusException ex) {
assertEquals(404, ex.getStatusCode()); assertEquals(404, ex.getStatusCode());
} }
@ -77,10 +79,13 @@ public class JsoupParserIntegrationTest {
@Test @Test
public void examplesExtracting() { public void examplesExtracting() {
Element firstArticle = doc.select("article").first(); Element firstArticle = doc.select("article")
Element timeElement = firstArticle.select("time").first(); .first();
Element timeElement = firstArticle.select("time")
.first();
String dateTimeOfFirstArticle = timeElement.attr("datetime"); String dateTimeOfFirstArticle = timeElement.attr("datetime");
Element sectionDiv = firstArticle.select("section div").first(); Element sectionDiv = firstArticle.select("section div")
.first();
String sectionDivText = sectionDiv.text(); String sectionDivText = sectionDiv.text();
String articleHtml = firstArticle.html(); String articleHtml = firstArticle.html();
String outerHtml = firstArticle.outerHtml(); String outerHtml = firstArticle.outerHtml();
@ -88,24 +93,30 @@ public class JsoupParserIntegrationTest {
@Test @Test
public void examplesModifying() { public void examplesModifying() {
Element firstArticle = doc.select("article").first(); Element firstArticle = doc.select("article")
Element timeElement = firstArticle.select("time").first(); .first();
Element sectionDiv = firstArticle.select("section div").first(); Element timeElement = firstArticle.select("time")
.first();
Element sectionDiv = firstArticle.select("section div")
.first();
String dateTimeOfFirstArticle = timeElement.attr("datetime"); String dateTimeOfFirstArticle = timeElement.attr("datetime");
timeElement.attr("datetime", "2016-12-16 15:19:54.3"); timeElement.attr("datetime", "2016-12-16 15:19:54.3");
sectionDiv.text("foo bar"); sectionDiv.text("foo bar");
firstArticle.select("h2").html("<div><span></span></div>"); firstArticle.select("h2")
.html("<div><span></span></div>");
Element link = new Element(Tag.valueOf("a"), "") Element link = new Element(Tag.valueOf("a"), "").text("Checkout this amazing website!")
.text("Checkout this amazing website!")
.attr("href", "http://baeldung.com") .attr("href", "http://baeldung.com")
.attr("target", "_blank"); .attr("target", "_blank");
firstArticle.appendChild(link); firstArticle.appendChild(link);
doc.select("li.navbar-link").remove(); doc.select("li.navbar-link")
firstArticle.select("img").remove(); .remove();
firstArticle.select("img")
.remove();
assertTrue(doc.html().contains("http://baeldung.com")); assertTrue(doc.html()
.contains("http://baeldung.com"));
} }
} }

View File

@ -24,9 +24,6 @@ public class AssumptionUnitTest {
@Test @Test
void assumptionThat() { void assumptionThat() {
String someString = "Just a string"; String someString = "Just a string";
assumingThat( assumingThat(someString.equals("Just a string"), () -> assertEquals(2 + 2, 4));
someString.equals("Just a string"),
() -> assertEquals(2 + 2, 4)
);
} }
} }

View File

@ -24,40 +24,33 @@ public class DynamicTestsExample {
@TestFactory @TestFactory
Collection<DynamicTest> dynamicTestsWithCollection() { Collection<DynamicTest> dynamicTestsWithCollection() {
return Arrays.asList( return Arrays.asList(DynamicTest.dynamicTest("Add test", () -> assertEquals(2, Math.addExact(1, 1))), DynamicTest.dynamicTest("Multiply Test", () -> assertEquals(4, Math.multiplyExact(2, 2))));
DynamicTest.dynamicTest("Add test", () -> assertEquals(2, Math.addExact(1, 1))),
DynamicTest.dynamicTest("Multiply Test", () -> assertEquals(4, Math.multiplyExact(2, 2))));
} }
@TestFactory @TestFactory
Iterable<DynamicTest> dynamicTestsWithIterable() { Iterable<DynamicTest> dynamicTestsWithIterable() {
return Arrays.asList( return Arrays.asList(DynamicTest.dynamicTest("Add test", () -> assertEquals(2, Math.addExact(1, 1))), DynamicTest.dynamicTest("Multiply Test", () -> assertEquals(4, Math.multiplyExact(2, 2))));
DynamicTest.dynamicTest("Add test", () -> assertEquals(2, Math.addExact(1, 1))),
DynamicTest.dynamicTest("Multiply Test", () -> assertEquals(4, Math.multiplyExact(2, 2))));
} }
@TestFactory @TestFactory
Iterator<DynamicTest> dynamicTestsWithIterator() { Iterator<DynamicTest> dynamicTestsWithIterator() {
return Arrays.asList( return Arrays.asList(DynamicTest.dynamicTest("Add test", () -> assertEquals(2, Math.addExact(1, 1))), DynamicTest.dynamicTest("Multiply Test", () -> assertEquals(4, Math.multiplyExact(2, 2))))
DynamicTest.dynamicTest("Add test", () -> assertEquals(2, Math.addExact(1, 1))),
DynamicTest.dynamicTest("Multiply Test", () -> assertEquals(4, Math.multiplyExact(2, 2))))
.iterator(); .iterator();
} }
@TestFactory @TestFactory
Stream<DynamicTest> dynamicTestsFromIntStream() { Stream<DynamicTest> dynamicTestsFromIntStream() {
return IntStream.iterate(0, n -> n + 2).limit(10).mapToObj( return IntStream.iterate(0, n -> n + 2)
n -> DynamicTest.dynamicTest("test" + n, () -> assertTrue(n % 2 == 0))); .limit(10)
.mapToObj(n -> DynamicTest.dynamicTest("test" + n, () -> assertTrue(n % 2 == 0)));
} }
@TestFactory @TestFactory
Stream<DynamicTest> dynamicTestsFromStream() { Stream<DynamicTest> dynamicTestsFromStream() {
// sample input and output // sample input and output
List<String> inputList = List<String> inputList = Arrays.asList("www.somedomain.com", "www.anotherdomain.com", "www.yetanotherdomain.com");
Arrays.asList("www.somedomain.com", "www.anotherdomain.com", "www.yetanotherdomain.com"); List<String> outputList = Arrays.asList("154.174.10.56", "211.152.104.132", "178.144.120.156");
List<String> outputList =
Arrays.asList("154.174.10.56", "211.152.104.132", "178.144.120.156");
// input generator that generates inputs using inputList // input generator that generates inputs using inputList
Iterator<String> inputGenerator = inputList.iterator(); Iterator<String> inputGenerator = inputList.iterator();
@ -81,12 +74,11 @@ public class DynamicTestsExample {
DomainNameResolver resolver = new DomainNameResolver(); DomainNameResolver resolver = new DomainNameResolver();
List<String> inputList = List<String> inputList = Arrays.asList("www.somedomain.com", "www.anotherdomain.com", "www.yetanotherdomain.com");
Arrays.asList("www.somedomain.com", "www.anotherdomain.com", "www.yetanotherdomain.com"); List<String> outputList = Arrays.asList("154.174.10.56", "211.152.104.132", "178.144.120.156");
List<String> outputList =
Arrays.asList("154.174.10.56", "211.152.104.132", "178.144.120.156");
return inputList.stream().map(dom -> DynamicTest.dynamicTest("Resolving: " + dom, () -> { return inputList.stream()
.map(dom -> DynamicTest.dynamicTest("Resolving: " + dom, () -> {
int id = inputList.indexOf(dom); int id = inputList.indexOf(dom);
assertEquals(outputList.get(id), resolver.resolveDomain(dom)); assertEquals(outputList.get(id), resolver.resolveDomain(dom));
})); }));
@ -95,18 +87,18 @@ public class DynamicTestsExample {
@TestFactory @TestFactory
Stream<DynamicTest> dynamicTestsForEmployeeWorkflows() { Stream<DynamicTest> dynamicTestsForEmployeeWorkflows() {
List<Employee> inputList = List<Employee> inputList = Arrays.asList(new Employee(1, "Fred"), new Employee(2), new Employee(3, "John"));
Arrays.asList(new Employee(1, "Fred"), new Employee(2), new Employee(3, "John"));
EmployeeDao dao = new EmployeeDao(); EmployeeDao dao = new EmployeeDao();
Stream<DynamicTest> saveEmployeeStream = inputList.stream().map(emp -> Stream<DynamicTest> saveEmployeeStream = inputList.stream()
DynamicTest.dynamicTest("saveEmployee: " + emp.toString(), () -> { .map(emp -> DynamicTest.dynamicTest("saveEmployee: " + emp.toString(), () -> {
Employee returned = dao.save(emp.getId()); Employee returned = dao.save(emp.getId());
assertEquals(returned.getId(), emp.getId()); assertEquals(returned.getId(), emp.getId());
})); }));
Stream<DynamicTest> saveEmployeeWithFirstNameStream Stream<DynamicTest> saveEmployeeWithFirstNameStream = inputList.stream()
= inputList.stream().filter(emp -> !emp.getFirstName().isEmpty()) .filter(emp -> !emp.getFirstName()
.isEmpty())
.map(emp -> DynamicTest.dynamicTest("saveEmployeeWithName" + emp.toString(), () -> { .map(emp -> DynamicTest.dynamicTest("saveEmployeeWithName" + emp.toString(), () -> {
Employee returned = dao.save(emp.getId(), emp.getFirstName()); Employee returned = dao.save(emp.getId(), emp.getFirstName());
assertEquals(returned.getId(), emp.getId()); assertEquals(returned.getId(), emp.getId());

View File

@ -33,12 +33,14 @@ public class EmployeesTest {
public void whenAddEmployee_thenGetEmployee() throws SQLException { public void whenAddEmployee_thenGetEmployee() throws SQLException {
Employee emp = new Employee(1, "john"); Employee emp = new Employee(1, "john");
employeeDao.add(emp); employeeDao.add(emp);
assertEquals(1, employeeDao.findAll().size()); assertEquals(1, employeeDao.findAll()
.size());
} }
@Test @Test
public void whenGetEmployees_thenEmptyList() throws SQLException { public void whenGetEmployees_thenEmptyList() throws SQLException {
assertEquals(0, employeeDao.findAll().size()); assertEquals(0, employeeDao.findAll()
.size());
} }
public void setLogger(Logger logger) { public void setLogger(Logger logger) {

View File

@ -13,8 +13,7 @@ class FirstUnitTest {
@Test @Test
void lambdaExpressions() { void lambdaExpressions() {
List<Integer> numbers = Arrays.asList(1, 2, 3); List<Integer> numbers = Arrays.asList(1, 2, 3);
assertTrue(numbers assertTrue(numbers.stream()
.stream()
.mapToInt(i -> i) .mapToInt(i -> i)
.sum() > 5, "Sum should be greater than 5"); .sum() > 5, "Sum should be greater than 5");
} }
@ -23,11 +22,7 @@ class FirstUnitTest {
@Test @Test
void groupAssertions() { void groupAssertions() {
int[] numbers = { 0, 1, 2, 3, 4 }; int[] numbers = { 0, 1, 2, 3, 4 };
assertAll("numbers", assertAll("numbers", () -> assertEquals(numbers[0], 1), () -> assertEquals(numbers[3], 3), () -> assertEquals(numbers[4], 1));
() -> assertEquals(numbers[0], 1),
() -> assertEquals(numbers[3], 3),
() -> assertEquals(numbers[4], 1)
);
} }
@Test @Test

View File

@ -18,7 +18,8 @@ public class LiveTest {
@TestFactory @TestFactory
public Stream<DynamicTest> translateDynamicTestsFromStream() { public Stream<DynamicTest> translateDynamicTestsFromStream() {
return in.stream().map(word -> DynamicTest.dynamicTest("Test translate " + word, () -> { return in.stream()
.map(word -> DynamicTest.dynamicTest("Test translate " + word, () -> {
int id = in.indexOf(word); int id = in.indexOf(word);
assertEquals(out.get(id), translate(word)); assertEquals(out.get(id), translate(word));
})); }));

View File

@ -25,13 +25,15 @@ public class TestLauncher {
//@formatter:on //@formatter:on
TestPlan plan = LauncherFactory.create().discover(request); TestPlan plan = LauncherFactory.create()
.discover(request);
Launcher launcher = LauncherFactory.create(); Launcher launcher = LauncherFactory.create();
SummaryGeneratingListener summaryGeneratingListener = new SummaryGeneratingListener(); SummaryGeneratingListener summaryGeneratingListener = new SummaryGeneratingListener();
launcher.execute(request, new TestExecutionListener[] { summaryGeneratingListener }); launcher.execute(request, new TestExecutionListener[] { summaryGeneratingListener });
launcher.execute(request); launcher.execute(request);
summaryGeneratingListener.getSummary().printTo(new PrintWriter(System.out)); summaryGeneratingListener.getSummary()
.printTo(new PrintWriter(System.out));
} }
} }

View File

@ -12,7 +12,9 @@ public class EmployeeDaoParameterResolver implements ParameterResolver {
@Override @Override
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException { public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
return parameterContext.getParameter().getType().equals(EmployeeJdbcDao.class); return parameterContext.getParameter()
.getType()
.equals(EmployeeJdbcDao.class);
} }
@Override @Override

View File

@ -10,7 +10,9 @@ public class LoggingExtension implements TestInstancePostProcessor {
@Override @Override
public void postProcessTestInstance(Object testInstance, ExtensionContext context) throws Exception { public void postProcessTestInstance(Object testInstance, ExtensionContext context) throws Exception {
Logger logger = LogManager.getLogger(testInstance.getClass()); Logger logger = LogManager.getLogger(testInstance.getClass());
testInstance.getClass().getMethod("setLogger", Logger.class).invoke(testInstance, logger); testInstance.getClass()
.getMethod("setLogger", Logger.class)
.invoke(testInstance, logger);
} }
} }

View File

@ -30,9 +30,10 @@ public class AssertionsExampleTest {
List<Integer> list = Arrays.asList(1, 2, 3); List<Integer> list = Arrays.asList(1, 2, 3);
Assertions.assertAll("List is not incremental", () -> Assertions.assertEquals(list.get(0) Assertions.assertAll("List is not incremental", () -> Assertions.assertEquals(list.get(0)
.intValue(), 1), .intValue(), 1), () -> Assertions.assertEquals(
() -> Assertions.assertEquals(list.get(1) list.get(1)
.intValue(), 2), .intValue(),
2),
() -> Assertions.assertEquals(list.get(2) () -> Assertions.assertEquals(list.get(2)
.intValue(), 3)); .intValue(), 3));
} }

View File

@ -12,36 +12,45 @@ public class InvalidPersonParameterResolver implements ParameterResolver {
/** /**
* The "bad" (invalid) data for testing purposes has to go somewhere, right? * The "bad" (invalid) data for testing purposes has to go somewhere, right?
*/ */
public static Person[] INVALID_PERSONS = { public static Person[] INVALID_PERSONS = { new Person().setId(1L)
new Person().setId(1L).setLastName("Ad_ams").setFirstName("Jill,"), .setLastName("Ad_ams")
new Person().setId(2L).setLastName(",Baker").setFirstName(""), .setFirstName("Jill,"),
new Person().setId(3L).setLastName(null).setFirstName(null), new Person().setId(2L)
new Person().setId(4L).setLastName("Daniel&").setFirstName("{Joseph}"), .setLastName(",Baker")
new Person().setId(5L).setLastName("").setFirstName("English, Jane"), .setFirstName(""),
new Person().setId(3L)
.setLastName(null)
.setFirstName(null),
new Person().setId(4L)
.setLastName("Daniel&")
.setFirstName("{Joseph}"),
new Person().setId(5L)
.setLastName("")
.setFirstName("English, Jane"),
new Person()/* .setId(6L).setLastName("Fontana").setFirstName("Enrique") */, new Person()/* .setId(6L).setLastName("Fontana").setFirstName("Enrique") */,
// TODO: ADD MORE DATA HERE // TODO: ADD MORE DATA HERE
}; };
@Override @Override
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
throws ParameterResolutionException {
Object ret = null; Object ret = null;
// //
// Return a random, valid Person object if Person.class is the type of Parameter // Return a random, valid Person object if Person.class is the type of Parameter
/// to be resolved. Otherwise return null. /// to be resolved. Otherwise return null.
if (parameterContext.getParameter().getType() == Person.class) { if (parameterContext.getParameter()
.getType() == Person.class) {
ret = INVALID_PERSONS[new Random().nextInt(INVALID_PERSONS.length)]; ret = INVALID_PERSONS[new Random().nextInt(INVALID_PERSONS.length)];
} }
return ret; return ret;
} }
@Override @Override
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
throws ParameterResolutionException {
boolean ret = false; boolean ret = false;
// //
// If the Parameter.type == Person.class, then we support it, otherwise, get outta here! // If the Parameter.type == Person.class, then we support it, otherwise, get outta here!
if (parameterContext.getParameter().getType() == Person.class) { if (parameterContext.getParameter()
.getType() == Person.class) {
ret = true; ret = true;
} }
return ret; return ret;

View File

@ -41,13 +41,7 @@ public class PersonValidator {
} }
private static final String[] ILLEGAL_NAME_CHARACTERS = { private static final String[] ILLEGAL_NAME_CHARACTERS = { ",", "_", "{", "}", "!" };
",",
"_",
"{",
"}",
"!"
};
/** /**
* Validate the first name of the specified Person object. * Validate the first name of the specified Person object.
@ -70,14 +64,12 @@ public class PersonValidator {
if (person.getFirstName() == null) { if (person.getFirstName() == null) {
throw new ValidationException("Person FirstName is null (not allowed)!"); throw new ValidationException("Person FirstName is null (not allowed)!");
} }
if (person.getFirstName().isEmpty()) { if (person.getFirstName()
.isEmpty()) {
throw new ValidationException("Person FirstName is an empty String (not allowed)!"); throw new ValidationException("Person FirstName is an empty String (not allowed)!");
} }
if (!isStringValid(person.getFirstName(), ILLEGAL_NAME_CHARACTERS)) { if (!isStringValid(person.getFirstName(), ILLEGAL_NAME_CHARACTERS)) {
throw new ValidationException( throw new ValidationException("Person FirstName (" + person.getFirstName() + ") may not contain any of the following characters: " + Arrays.toString(ILLEGAL_NAME_CHARACTERS) + "!");
"Person FirstName (" + person.getFirstName() + ") may not contain any of the following characters: "
+ Arrays.toString(ILLEGAL_NAME_CHARACTERS)
+ "!");
} }
return ret; return ret;
} }
@ -104,14 +96,12 @@ public class PersonValidator {
if (person.getFirstName() == null) { if (person.getFirstName() == null) {
throw new ValidationException("Person FirstName is null (not allowed)!"); throw new ValidationException("Person FirstName is null (not allowed)!");
} }
if (person.getFirstName().isEmpty()) { if (person.getFirstName()
.isEmpty()) {
throw new ValidationException("Person FirstName is an empty String (not allowed)!"); throw new ValidationException("Person FirstName is an empty String (not allowed)!");
} }
if (!isStringValid(person.getFirstName(), ILLEGAL_NAME_CHARACTERS)) { if (!isStringValid(person.getFirstName(), ILLEGAL_NAME_CHARACTERS)) {
throw new ValidationException( throw new ValidationException("Person LastName (" + person.getLastName() + ") may not contain any of the following characters: " + Arrays.toString(ILLEGAL_NAME_CHARACTERS) + "!");
"Person LastName (" + person.getLastName() + ") may not contain any of the following characters: "
+ Arrays.toString(ILLEGAL_NAME_CHARACTERS)
+ "!");
} }
return ret; return ret;
} }

View File

@ -12,36 +12,47 @@ public class ValidPersonParameterResolver implements ParameterResolver {
/** /**
* The "good" (valid) data for testing purposes has to go somewhere, right? * The "good" (valid) data for testing purposes has to go somewhere, right?
*/ */
public static Person[] VALID_PERSONS = { public static Person[] VALID_PERSONS = { new Person().setId(1L)
new Person().setId(1L).setLastName("Adams").setFirstName("Jill"), .setLastName("Adams")
new Person().setId(2L).setLastName("Baker").setFirstName("James"), .setFirstName("Jill"),
new Person().setId(3L).setLastName("Carter").setFirstName("Samanta"), new Person().setId(2L)
new Person().setId(4L).setLastName("Daniels").setFirstName("Joseph"), .setLastName("Baker")
new Person().setId(5L).setLastName("English").setFirstName("Jane"), .setFirstName("James"),
new Person().setId(6L).setLastName("Fontana").setFirstName("Enrique"), new Person().setId(3L)
.setLastName("Carter")
.setFirstName("Samanta"),
new Person().setId(4L)
.setLastName("Daniels")
.setFirstName("Joseph"),
new Person().setId(5L)
.setLastName("English")
.setFirstName("Jane"),
new Person().setId(6L)
.setLastName("Fontana")
.setFirstName("Enrique"),
// TODO: ADD MORE DATA HERE // TODO: ADD MORE DATA HERE
}; };
@Override @Override
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
throws ParameterResolutionException {
Object ret = null; Object ret = null;
// //
// Return a random, valid Person object if Person.class is the type of Parameter // Return a random, valid Person object if Person.class is the type of Parameter
/// to be resolved. Otherwise return null. /// to be resolved. Otherwise return null.
if (parameterContext.getParameter().getType() == Person.class) { if (parameterContext.getParameter()
.getType() == Person.class) {
ret = VALID_PERSONS[new Random().nextInt(VALID_PERSONS.length)]; ret = VALID_PERSONS[new Random().nextInt(VALID_PERSONS.length)];
} }
return ret; return ret;
} }
@Override @Override
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
throws ParameterResolutionException {
boolean ret = false; boolean ret = false;
// //
// If the Parameter.type == Person.class, then we support it, otherwise, get outta here! // If the Parameter.type == Person.class, then we support it, otherwise, get outta here!
if (parameterContext.getParameter().getType() == Person.class) { if (parameterContext.getParameter()
.getType() == Person.class) {
ret = true; ret = true;
} }
return ret; return ret;