formatting work
This commit is contained in:
parent
1cba1b043c
commit
b00a9e61bc
@ -16,7 +16,8 @@ import java.util.UUID;
|
||||
|
||||
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 byte[] secret;
|
||||
@ -27,7 +28,9 @@ public class JWTCsrfTokenRepository implements CsrfTokenRepository {
|
||||
|
||||
@Override
|
||||
public CsrfToken generateToken(HttpServletRequest request) {
|
||||
String id = UUID.randomUUID().toString().replace("-", "");
|
||||
String id = UUID.randomUUID()
|
||||
.toString()
|
||||
.replace("-", "");
|
||||
|
||||
Date now = new Date();
|
||||
Date exp = new Date(System.currentTimeMillis() + (1000 * 30)); // 30 seconds
|
||||
@ -50,8 +53,7 @@ public class JWTCsrfTokenRepository implements CsrfTokenRepository {
|
||||
if (session != null) {
|
||||
session.removeAttribute(DEFAULT_CSRF_TOKEN_ATTR_NAME);
|
||||
}
|
||||
}
|
||||
else {
|
||||
} else {
|
||||
HttpSession session = request.getSession();
|
||||
session.setAttribute(DEFAULT_CSRF_TOKEN_ATTR_NAME, token);
|
||||
}
|
||||
|
@ -30,21 +30,16 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
SecretService secretService;
|
||||
|
||||
// ordered so we can use binary search below
|
||||
private String[] ignoreCsrfAntMatchers = {
|
||||
"/dynamic-builder-compress",
|
||||
"/dynamic-builder-general",
|
||||
"/dynamic-builder-specific",
|
||||
"/set-secrets"
|
||||
};
|
||||
private String[] ignoreCsrfAntMatchers = { "/dynamic-builder-compress", "/dynamic-builder-general", "/dynamic-builder-specific", "/set-secrets" };
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
http
|
||||
.addFilterAfter(new JwtCsrfValidatorFilter(), CsrfFilter.class)
|
||||
http.addFilterAfter(new JwtCsrfValidatorFilter(), CsrfFilter.class)
|
||||
.csrf()
|
||||
.csrfTokenRepository(jwtCsrfTokenRepository)
|
||||
.ignoringAntMatchers(ignoreCsrfAntMatchers)
|
||||
.and().authorizeRequests()
|
||||
.and()
|
||||
.authorizeRequests()
|
||||
.antMatchers("/**")
|
||||
.permitAll();
|
||||
}
|
||||
@ -63,8 +58,7 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
// ignore if the request path is in our list
|
||||
Arrays.binarySearch(ignoreCsrfAntMatchers, request.getServletPath()) < 0 &&
|
||||
// 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
|
||||
try {
|
||||
Jwts.parser()
|
||||
|
@ -16,7 +16,8 @@ public class BaseController {
|
||||
JwtResponse response = new JwtResponse();
|
||||
response.setStatus(JwtResponse.Status.ERROR);
|
||||
response.setMessage(e.getMessage());
|
||||
response.setExceptionType(e.getClass().getName());
|
||||
response.setExceptionType(e.getClass()
|
||||
.getName());
|
||||
|
||||
return response;
|
||||
}
|
||||
|
@ -29,10 +29,7 @@ public class DynamicJWTController extends BaseController {
|
||||
public JwtResponse dynamicBuilderGeneric(@RequestBody Map<String, Object> claims) throws UnsupportedEncodingException {
|
||||
String jws = Jwts.builder()
|
||||
.setClaims(claims)
|
||||
.signWith(
|
||||
SignatureAlgorithm.HS256,
|
||||
secretService.getHS256SecretBytes()
|
||||
)
|
||||
.signWith(SignatureAlgorithm.HS256, secretService.getHS256SecretBytes())
|
||||
.compact();
|
||||
return new JwtResponse(jws);
|
||||
}
|
||||
@ -42,10 +39,7 @@ public class DynamicJWTController extends BaseController {
|
||||
String jws = Jwts.builder()
|
||||
.setClaims(claims)
|
||||
.compressWith(CompressionCodecs.DEFLATE)
|
||||
.signWith(
|
||||
SignatureAlgorithm.HS256,
|
||||
secretService.getHS256SecretBytes()
|
||||
)
|
||||
.signWith(SignatureAlgorithm.HS256, secretService.getHS256SecretBytes())
|
||||
.compact();
|
||||
return new JwtResponse(jws);
|
||||
}
|
||||
@ -95,13 +89,11 @@ public class DynamicJWTController extends BaseController {
|
||||
}
|
||||
|
||||
private void ensureType(String registeredClaim, Object value, Class expectedType) {
|
||||
boolean isCorrectType =
|
||||
expectedType.isInstance(value) ||
|
||||
expectedType == Long.class && value instanceof Integer;
|
||||
boolean isCorrectType = expectedType.isInstance(value) || expectedType == Long.class && value instanceof Integer;
|
||||
|
||||
if (!isCorrectType) {
|
||||
String msg = "Expected type: " + expectedType.getCanonicalName() + " for registered claim: '" +
|
||||
registeredClaim + "', but got value: " + value + " of type: " + value.getClass().getCanonicalName();
|
||||
String msg = "Expected type: " + expectedType.getCanonicalName() + " for registered claim: '" + registeredClaim + "', but got value: " + value + " of type: " + value.getClass()
|
||||
.getCanonicalName();
|
||||
throw new JwtException(msg);
|
||||
}
|
||||
}
|
||||
|
@ -11,22 +11,16 @@ public class HomeController {
|
||||
@RequestMapping("/")
|
||||
public String home(HttpServletRequest req) {
|
||||
String requestUrl = getUrl(req);
|
||||
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 " + 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 + "/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 + "/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 + "/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.";
|
||||
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 "
|
||||
+ 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
|
||||
+ "/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
|
||||
+ "/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
|
||||
+ "/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) {
|
||||
return req.getScheme() + "://" +
|
||||
req.getServerName() +
|
||||
((req.getServerPort() == 80 || req.getServerPort() == 443) ? "" : ":" + req.getServerPort());
|
||||
return req.getScheme() + "://" + req.getServerName() + ((req.getServerPort() == 80 || req.getServerPort() == 443) ? "" : ":" + req.getServerPort());
|
||||
}
|
||||
}
|
||||
|
@ -32,10 +32,7 @@ public class StaticJWTController extends BaseController {
|
||||
.claim("scope", "admins")
|
||||
.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)
|
||||
.signWith(
|
||||
SignatureAlgorithm.HS256,
|
||||
secretService.getHS256SecretBytes()
|
||||
)
|
||||
.signWith(SignatureAlgorithm.HS256, secretService.getHS256SecretBytes())
|
||||
.compact();
|
||||
|
||||
return new JwtResponse(jws);
|
||||
|
@ -16,7 +16,8 @@ public class JwtResponse {
|
||||
SUCCESS, ERROR
|
||||
}
|
||||
|
||||
public JwtResponse() {}
|
||||
public JwtResponse() {
|
||||
}
|
||||
|
||||
public JwtResponse(String jwt) {
|
||||
this.jwt = jwt;
|
||||
|
@ -61,7 +61,6 @@ public class SecretService {
|
||||
return TextCodec.BASE64.decode(secrets.get(SignatureAlgorithm.HS384.getValue()));
|
||||
}
|
||||
|
||||
|
||||
public Map<String, String> refreshSecrets() {
|
||||
SecretKey key = MacProvider.generateKey(SignatureAlgorithm.HS256);
|
||||
secrets.put(SignatureAlgorithm.HS256.getValue(), TextCodec.BASE64.encode(key.getEncoded()));
|
||||
|
@ -50,13 +50,17 @@ public class StoredProcedureIntegrationTest {
|
||||
public void findCarsByYearNamedProcedure() {
|
||||
final StoredProcedureQuery findByYearProcedure = entityManager.createNamedStoredProcedureQuery("findByYearProcedure");
|
||||
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
|
||||
public void findCarsByYearNoNamed() {
|
||||
final StoredProcedureQuery storedProcedure = entityManager.createStoredProcedureQuery("FIND_CAR_BY_YEAR", Car.class).registerStoredProcedureParameter(1, Integer.class, ParameterMode.IN).setParameter(1, 2015);
|
||||
storedProcedure.getResultList().forEach(c -> Assert.assertEquals(new Integer(2015), ((Car) c).getYear()));
|
||||
final StoredProcedureQuery storedProcedure = entityManager.createStoredProcedureQuery("FIND_CAR_BY_YEAR", Car.class)
|
||||
.registerStoredProcedureParameter(1, Integer.class, ParameterMode.IN)
|
||||
.setParameter(1, 2015);
|
||||
storedProcedure.getResultList()
|
||||
.forEach(c -> Assert.assertEquals(new Integer(2015), ((Car) c).getYear()));
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
|
@ -27,10 +27,14 @@ public class ELSampleBean {
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
pageCounter = randomIntGen.nextInt();
|
||||
FacesContext.getCurrentInstance().getApplication().addELContextListener(new ELContextListener() {
|
||||
FacesContext.getCurrentInstance()
|
||||
.getApplication()
|
||||
.addELContextListener(new ELContextListener() {
|
||||
@Override
|
||||
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) {
|
||||
Long theResult = (Long) expr.invoke(FacesContext.getCurrentInstance().getELContext(), pageCounter);
|
||||
Long theResult = (Long) expr.invoke(FacesContext.getCurrentInstance()
|
||||
.getELContext(), pageCounter);
|
||||
return theResult;
|
||||
}
|
||||
|
||||
|
@ -1,6 +1,5 @@
|
||||
package com.baeldung.springintegration.dao;
|
||||
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Repository;
|
||||
@ -34,5 +33,4 @@ public class UserManagementDAOImpl implements UserManagementDAO {
|
||||
public UserManagementDAOImpl() {
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
@ -18,8 +18,11 @@ import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
public class OperationIntegrationTest {
|
||||
private InputStream jsonInputStream = this.getClass().getClassLoader().getResourceAsStream("intro_api.json");
|
||||
private String jsonDataSourceString = new Scanner(jsonInputStream, "UTF-8").useDelimiter("\\Z").next();
|
||||
private InputStream jsonInputStream = this.getClass()
|
||||
.getClassLoader()
|
||||
.getResourceAsStream("intro_api.json");
|
||||
private String jsonDataSourceString = new Scanner(jsonInputStream, "UTF-8").useDelimiter("\\Z")
|
||||
.next();
|
||||
|
||||
@Test
|
||||
public void givenJsonPathWithoutPredicates_whenReading_thenCorrect() {
|
||||
@ -38,21 +41,27 @@ public class OperationIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void givenJsonPathWithFilterPredicate_whenReading_thenCorrect() {
|
||||
Filter expensiveFilter = Filter.filter(Criteria.where("price").gt(20.00));
|
||||
List<Map<String, Object>> expensive = JsonPath.parse(jsonDataSourceString).read("$['book'][?]", expensiveFilter);
|
||||
Filter expensiveFilter = Filter.filter(Criteria.where("price")
|
||||
.gt(20.00));
|
||||
List<Map<String, Object>> expensive = JsonPath.parse(jsonDataSourceString)
|
||||
.read("$['book'][?]", expensiveFilter);
|
||||
predicateUsageAssertionHelper(expensive);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenJsonPathWithCustomizedPredicate_whenReading_thenCorrect() {
|
||||
Predicate expensivePredicate = context -> Float.valueOf(context.item(Map.class).get("price").toString()) > 20.00;
|
||||
List<Map<String, Object>> expensive = JsonPath.parse(jsonDataSourceString).read("$['book'][?]", expensivePredicate);
|
||||
Predicate expensivePredicate = context -> Float.valueOf(context.item(Map.class)
|
||||
.get("price")
|
||||
.toString()) > 20.00;
|
||||
List<Map<String, Object>> expensive = JsonPath.parse(jsonDataSourceString)
|
||||
.read("$['book'][?]", expensivePredicate);
|
||||
predicateUsageAssertionHelper(expensive);
|
||||
}
|
||||
|
||||
@Test
|
||||
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);
|
||||
}
|
||||
|
||||
|
@ -18,12 +18,16 @@ import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
public class ServiceTest {
|
||||
private InputStream jsonInputStream = this.getClass().getClassLoader().getResourceAsStream("intro_service.json");
|
||||
private String jsonString = new Scanner(jsonInputStream, "UTF-8").useDelimiter("\\Z").next();
|
||||
private InputStream jsonInputStream = this.getClass()
|
||||
.getClassLoader()
|
||||
.getResourceAsStream("intro_service.json");
|
||||
private String jsonString = new Scanner(jsonInputStream, "UTF-8").useDelimiter("\\Z")
|
||||
.next();
|
||||
|
||||
@Test
|
||||
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();
|
||||
|
||||
assertThat(dataString, containsString("2"));
|
||||
@ -33,8 +37,10 @@ public class ServiceTest {
|
||||
|
||||
@Test
|
||||
public void givenStarring_whenRequestingMovieTitle_thenSucceed() {
|
||||
List<Map<String, Object>> dataList = JsonPath.parse(jsonString).read("$[?('Eva Green' in @['starring'])]");
|
||||
String title = (String) dataList.get(0).get("title");
|
||||
List<Map<String, Object>> dataList = JsonPath.parse(jsonString)
|
||||
.read("$[?('Eva Green' in @['starring'])]");
|
||||
String title = (String) dataList.get(0)
|
||||
.get("title");
|
||||
|
||||
assertEquals("Casino Royale", title);
|
||||
}
|
||||
@ -59,8 +65,12 @@ public class ServiceTest {
|
||||
Arrays.sort(revenueArray);
|
||||
|
||||
int highestRevenue = revenueArray[revenueArray.length - 1];
|
||||
Configuration pathConfiguration = Configuration.builder().options(Option.AS_PATH_LIST).build();
|
||||
List<String> pathList = JsonPath.using(pathConfiguration).parse(jsonString).read("$[?(@['box office'] == " + highestRevenue + ")]");
|
||||
Configuration pathConfiguration = Configuration.builder()
|
||||
.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));
|
||||
String title = dataRecord.get("title");
|
||||
@ -83,7 +93,8 @@ public class ServiceTest {
|
||||
|
||||
long latestTime = dateArray[dateArray.length - 1];
|
||||
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);
|
||||
}
|
||||
|
@ -32,11 +32,7 @@ public class FastJsonUnitTest {
|
||||
@Test
|
||||
public void whenJavaList_thanConvertToJsonCorrect() {
|
||||
String personJsonFormat = JSON.toJSONString(listOfPersons);
|
||||
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\"}]");
|
||||
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\"}]");
|
||||
}
|
||||
|
||||
@Test
|
||||
@ -44,8 +40,10 @@ public class FastJsonUnitTest {
|
||||
String personJsonFormat = JSON.toJSONString(listOfPersons.get(0));
|
||||
Person newPerson = JSON.parseObject(personJsonFormat, Person.class);
|
||||
assertEquals(newPerson.getAge(), 0); // serialize is set to false for age attribute
|
||||
assertEquals(newPerson.getFirstName(), listOfPersons.get(0).getFirstName());
|
||||
assertEquals(newPerson.getLastName(), listOfPersons.get(0).getLastName());
|
||||
assertEquals(newPerson.getFirstName(), listOfPersons.get(0)
|
||||
.getFirstName());
|
||||
assertEquals(newPerson.getLastName(), listOfPersons.get(0)
|
||||
.getLastName());
|
||||
}
|
||||
|
||||
@Test
|
||||
@ -58,18 +56,13 @@ public class FastJsonUnitTest {
|
||||
jsonObject.put("DATE OF BIRTH", "2016/12/12 12:12:12");
|
||||
jsonArray.add(jsonObject);
|
||||
}
|
||||
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\"}]");
|
||||
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\"}]");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenContextFilter_whenJavaObject_thanJsonCorrect() {
|
||||
ContextValueFilter valueFilter = new ContextValueFilter() {
|
||||
public Object process(BeanContext context, Object object,
|
||||
String name, Object value) {
|
||||
public Object process(BeanContext context, Object object, String name, Object value) {
|
||||
if (name.equals("DATE OF BIRTH")) {
|
||||
return "NOT TO DISCLOSE";
|
||||
}
|
||||
@ -87,18 +80,16 @@ public class FastJsonUnitTest {
|
||||
public void givenSerializeConfig_whenJavaObject_thanJsonCorrect() {
|
||||
NameFilter formatName = new NameFilter() {
|
||||
public String process(Object object, String name, Object value) {
|
||||
return name.toLowerCase().replace(" ", "_");
|
||||
return name.toLowerCase()
|
||||
.replace(" ", "_");
|
||||
}
|
||||
};
|
||||
SerializeConfig.getGlobalInstance().addFilter(Person.class, formatName);
|
||||
String jsonOutput = JSON.toJSONStringWithDateFormat(listOfPersons,
|
||||
"yyyy-MM-dd");
|
||||
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\"}]");
|
||||
SerializeConfig.getGlobalInstance()
|
||||
.addFilter(Person.class, formatName);
|
||||
String jsonOutput = JSON.toJSONStringWithDateFormat(listOfPersons, "yyyy-MM-dd");
|
||||
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\"}]");
|
||||
// resetting custom serializer
|
||||
SerializeConfig.getGlobalInstance().put(Person.class, null);
|
||||
SerializeConfig.getGlobalInstance()
|
||||
.put(Person.class, null);
|
||||
}
|
||||
}
|
||||
|
@ -32,8 +32,7 @@ public class Person {
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Person [age=" + age + ", lastName=" + lastName + ", firstName="
|
||||
+ firstName + ", dateOfBirth=" + dateOfBirth + "]";
|
||||
return "Person [age=" + age + ", lastName=" + lastName + ", firstName=" + firstName + ", dateOfBirth=" + dateOfBirth + "]";
|
||||
}
|
||||
|
||||
public int getAge() {
|
||||
|
@ -20,13 +20,15 @@ public class JsoupParserIntegrationTest {
|
||||
|
||||
@Before
|
||||
public void setUp() throws IOException {
|
||||
doc = Jsoup.connect("https://spring.io/blog").get();
|
||||
doc = Jsoup.connect("https://spring.io/blog")
|
||||
.get();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loadDocument404() throws IOException {
|
||||
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) {
|
||||
assertEquals(404, ex.getStatusCode());
|
||||
}
|
||||
@ -77,10 +79,13 @@ public class JsoupParserIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void examplesExtracting() {
|
||||
Element firstArticle = doc.select("article").first();
|
||||
Element timeElement = firstArticle.select("time").first();
|
||||
Element firstArticle = doc.select("article")
|
||||
.first();
|
||||
Element timeElement = firstArticle.select("time")
|
||||
.first();
|
||||
String dateTimeOfFirstArticle = timeElement.attr("datetime");
|
||||
Element sectionDiv = firstArticle.select("section div").first();
|
||||
Element sectionDiv = firstArticle.select("section div")
|
||||
.first();
|
||||
String sectionDivText = sectionDiv.text();
|
||||
String articleHtml = firstArticle.html();
|
||||
String outerHtml = firstArticle.outerHtml();
|
||||
@ -88,24 +93,30 @@ public class JsoupParserIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void examplesModifying() {
|
||||
Element firstArticle = doc.select("article").first();
|
||||
Element timeElement = firstArticle.select("time").first();
|
||||
Element sectionDiv = firstArticle.select("section div").first();
|
||||
Element firstArticle = doc.select("article")
|
||||
.first();
|
||||
Element timeElement = firstArticle.select("time")
|
||||
.first();
|
||||
Element sectionDiv = firstArticle.select("section div")
|
||||
.first();
|
||||
|
||||
String dateTimeOfFirstArticle = timeElement.attr("datetime");
|
||||
timeElement.attr("datetime", "2016-12-16 15:19:54.3");
|
||||
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"), "")
|
||||
.text("Checkout this amazing website!")
|
||||
Element link = new Element(Tag.valueOf("a"), "").text("Checkout this amazing website!")
|
||||
.attr("href", "http://baeldung.com")
|
||||
.attr("target", "_blank");
|
||||
firstArticle.appendChild(link);
|
||||
|
||||
doc.select("li.navbar-link").remove();
|
||||
firstArticle.select("img").remove();
|
||||
doc.select("li.navbar-link")
|
||||
.remove();
|
||||
firstArticle.select("img")
|
||||
.remove();
|
||||
|
||||
assertTrue(doc.html().contains("http://baeldung.com"));
|
||||
assertTrue(doc.html()
|
||||
.contains("http://baeldung.com"));
|
||||
}
|
||||
}
|
||||
|
@ -24,9 +24,6 @@ public class AssumptionUnitTest {
|
||||
@Test
|
||||
void assumptionThat() {
|
||||
String someString = "Just a string";
|
||||
assumingThat(
|
||||
someString.equals("Just a string"),
|
||||
() -> assertEquals(2 + 2, 4)
|
||||
);
|
||||
assumingThat(someString.equals("Just a string"), () -> assertEquals(2 + 2, 4));
|
||||
}
|
||||
}
|
||||
|
@ -24,40 +24,33 @@ public class DynamicTestsExample {
|
||||
|
||||
@TestFactory
|
||||
Collection<DynamicTest> dynamicTestsWithCollection() {
|
||||
return Arrays.asList(
|
||||
DynamicTest.dynamicTest("Add test", () -> assertEquals(2, Math.addExact(1, 1))),
|
||||
DynamicTest.dynamicTest("Multiply Test", () -> assertEquals(4, Math.multiplyExact(2, 2))));
|
||||
return Arrays.asList(DynamicTest.dynamicTest("Add test", () -> assertEquals(2, Math.addExact(1, 1))), DynamicTest.dynamicTest("Multiply Test", () -> assertEquals(4, Math.multiplyExact(2, 2))));
|
||||
}
|
||||
|
||||
@TestFactory
|
||||
Iterable<DynamicTest> dynamicTestsWithIterable() {
|
||||
return Arrays.asList(
|
||||
DynamicTest.dynamicTest("Add test", () -> assertEquals(2, Math.addExact(1, 1))),
|
||||
DynamicTest.dynamicTest("Multiply Test", () -> assertEquals(4, Math.multiplyExact(2, 2))));
|
||||
return Arrays.asList(DynamicTest.dynamicTest("Add test", () -> assertEquals(2, Math.addExact(1, 1))), DynamicTest.dynamicTest("Multiply Test", () -> assertEquals(4, Math.multiplyExact(2, 2))));
|
||||
}
|
||||
|
||||
@TestFactory
|
||||
Iterator<DynamicTest> dynamicTestsWithIterator() {
|
||||
return Arrays.asList(
|
||||
DynamicTest.dynamicTest("Add test", () -> assertEquals(2, Math.addExact(1, 1))),
|
||||
DynamicTest.dynamicTest("Multiply Test", () -> assertEquals(4, Math.multiplyExact(2, 2))))
|
||||
return Arrays.asList(DynamicTest.dynamicTest("Add test", () -> assertEquals(2, Math.addExact(1, 1))), DynamicTest.dynamicTest("Multiply Test", () -> assertEquals(4, Math.multiplyExact(2, 2))))
|
||||
.iterator();
|
||||
}
|
||||
|
||||
@TestFactory
|
||||
Stream<DynamicTest> dynamicTestsFromIntStream() {
|
||||
return IntStream.iterate(0, n -> n + 2).limit(10).mapToObj(
|
||||
n -> DynamicTest.dynamicTest("test" + n, () -> assertTrue(n % 2 == 0)));
|
||||
return IntStream.iterate(0, n -> n + 2)
|
||||
.limit(10)
|
||||
.mapToObj(n -> DynamicTest.dynamicTest("test" + n, () -> assertTrue(n % 2 == 0)));
|
||||
}
|
||||
|
||||
@TestFactory
|
||||
Stream<DynamicTest> dynamicTestsFromStream() {
|
||||
|
||||
// sample input and output
|
||||
List<String> inputList =
|
||||
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> inputList = 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");
|
||||
|
||||
// input generator that generates inputs using inputList
|
||||
Iterator<String> inputGenerator = inputList.iterator();
|
||||
@ -81,12 +74,11 @@ public class DynamicTestsExample {
|
||||
|
||||
DomainNameResolver resolver = new DomainNameResolver();
|
||||
|
||||
List<String> inputList =
|
||||
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> inputList = 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");
|
||||
|
||||
return inputList.stream().map(dom -> DynamicTest.dynamicTest("Resolving: " + dom, () -> {
|
||||
return inputList.stream()
|
||||
.map(dom -> DynamicTest.dynamicTest("Resolving: " + dom, () -> {
|
||||
int id = inputList.indexOf(dom);
|
||||
assertEquals(outputList.get(id), resolver.resolveDomain(dom));
|
||||
}));
|
||||
@ -95,18 +87,18 @@ public class DynamicTestsExample {
|
||||
|
||||
@TestFactory
|
||||
Stream<DynamicTest> dynamicTestsForEmployeeWorkflows() {
|
||||
List<Employee> inputList =
|
||||
Arrays.asList(new Employee(1, "Fred"), new Employee(2), new Employee(3, "John"));
|
||||
List<Employee> inputList = Arrays.asList(new Employee(1, "Fred"), new Employee(2), new Employee(3, "John"));
|
||||
|
||||
EmployeeDao dao = new EmployeeDao();
|
||||
Stream<DynamicTest> saveEmployeeStream = inputList.stream().map(emp ->
|
||||
DynamicTest.dynamicTest("saveEmployee: " + emp.toString(), () -> {
|
||||
Stream<DynamicTest> saveEmployeeStream = inputList.stream()
|
||||
.map(emp -> DynamicTest.dynamicTest("saveEmployee: " + emp.toString(), () -> {
|
||||
Employee returned = dao.save(emp.getId());
|
||||
assertEquals(returned.getId(), emp.getId());
|
||||
}));
|
||||
|
||||
Stream<DynamicTest> saveEmployeeWithFirstNameStream
|
||||
= inputList.stream().filter(emp -> !emp.getFirstName().isEmpty())
|
||||
Stream<DynamicTest> saveEmployeeWithFirstNameStream = inputList.stream()
|
||||
.filter(emp -> !emp.getFirstName()
|
||||
.isEmpty())
|
||||
.map(emp -> DynamicTest.dynamicTest("saveEmployeeWithName" + emp.toString(), () -> {
|
||||
Employee returned = dao.save(emp.getId(), emp.getFirstName());
|
||||
assertEquals(returned.getId(), emp.getId());
|
||||
|
@ -33,12 +33,14 @@ public class EmployeesTest {
|
||||
public void whenAddEmployee_thenGetEmployee() throws SQLException {
|
||||
Employee emp = new Employee(1, "john");
|
||||
employeeDao.add(emp);
|
||||
assertEquals(1, employeeDao.findAll().size());
|
||||
assertEquals(1, employeeDao.findAll()
|
||||
.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetEmployees_thenEmptyList() throws SQLException {
|
||||
assertEquals(0, employeeDao.findAll().size());
|
||||
assertEquals(0, employeeDao.findAll()
|
||||
.size());
|
||||
}
|
||||
|
||||
public void setLogger(Logger logger) {
|
||||
|
@ -13,8 +13,7 @@ class FirstUnitTest {
|
||||
@Test
|
||||
void lambdaExpressions() {
|
||||
List<Integer> numbers = Arrays.asList(1, 2, 3);
|
||||
assertTrue(numbers
|
||||
.stream()
|
||||
assertTrue(numbers.stream()
|
||||
.mapToInt(i -> i)
|
||||
.sum() > 5, "Sum should be greater than 5");
|
||||
}
|
||||
@ -23,11 +22,7 @@ class FirstUnitTest {
|
||||
@Test
|
||||
void groupAssertions() {
|
||||
int[] numbers = { 0, 1, 2, 3, 4 };
|
||||
assertAll("numbers",
|
||||
() -> assertEquals(numbers[0], 1),
|
||||
() -> assertEquals(numbers[3], 3),
|
||||
() -> assertEquals(numbers[4], 1)
|
||||
);
|
||||
assertAll("numbers", () -> assertEquals(numbers[0], 1), () -> assertEquals(numbers[3], 3), () -> assertEquals(numbers[4], 1));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -18,7 +18,8 @@ public class LiveTest {
|
||||
@TestFactory
|
||||
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);
|
||||
assertEquals(out.get(id), translate(word));
|
||||
}));
|
||||
|
@ -25,13 +25,15 @@ public class TestLauncher {
|
||||
|
||||
//@formatter:on
|
||||
|
||||
TestPlan plan = LauncherFactory.create().discover(request);
|
||||
TestPlan plan = LauncherFactory.create()
|
||||
.discover(request);
|
||||
Launcher launcher = LauncherFactory.create();
|
||||
SummaryGeneratingListener summaryGeneratingListener = new SummaryGeneratingListener();
|
||||
launcher.execute(request, new TestExecutionListener[] { summaryGeneratingListener });
|
||||
launcher.execute(request);
|
||||
|
||||
summaryGeneratingListener.getSummary().printTo(new PrintWriter(System.out));
|
||||
summaryGeneratingListener.getSummary()
|
||||
.printTo(new PrintWriter(System.out));
|
||||
|
||||
}
|
||||
}
|
||||
|
@ -12,7 +12,9 @@ public class EmployeeDaoParameterResolver implements ParameterResolver {
|
||||
|
||||
@Override
|
||||
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
|
||||
return parameterContext.getParameter().getType().equals(EmployeeJdbcDao.class);
|
||||
return parameterContext.getParameter()
|
||||
.getType()
|
||||
.equals(EmployeeJdbcDao.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
@ -10,7 +10,9 @@ public class LoggingExtension implements TestInstancePostProcessor {
|
||||
@Override
|
||||
public void postProcessTestInstance(Object testInstance, ExtensionContext context) throws Exception {
|
||||
Logger logger = LogManager.getLogger(testInstance.getClass());
|
||||
testInstance.getClass().getMethod("setLogger", Logger.class).invoke(testInstance, logger);
|
||||
testInstance.getClass()
|
||||
.getMethod("setLogger", Logger.class)
|
||||
.invoke(testInstance, logger);
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -30,9 +30,10 @@ public class AssertionsExampleTest {
|
||||
List<Integer> list = Arrays.asList(1, 2, 3);
|
||||
|
||||
Assertions.assertAll("List is not incremental", () -> Assertions.assertEquals(list.get(0)
|
||||
.intValue(), 1),
|
||||
() -> Assertions.assertEquals(list.get(1)
|
||||
.intValue(), 2),
|
||||
.intValue(), 1), () -> Assertions.assertEquals(
|
||||
list.get(1)
|
||||
.intValue(),
|
||||
2),
|
||||
() -> Assertions.assertEquals(list.get(2)
|
||||
.intValue(), 3));
|
||||
}
|
||||
|
@ -12,36 +12,45 @@ public class InvalidPersonParameterResolver implements ParameterResolver {
|
||||
/**
|
||||
* The "bad" (invalid) data for testing purposes has to go somewhere, right?
|
||||
*/
|
||||
public static Person[] INVALID_PERSONS = {
|
||||
new Person().setId(1L).setLastName("Ad_ams").setFirstName("Jill,"),
|
||||
new Person().setId(2L).setLastName(",Baker").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"),
|
||||
public static Person[] INVALID_PERSONS = { new Person().setId(1L)
|
||||
.setLastName("Ad_ams")
|
||||
.setFirstName("Jill,"),
|
||||
new Person().setId(2L)
|
||||
.setLastName(",Baker")
|
||||
.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") */,
|
||||
// TODO: ADD MORE DATA HERE
|
||||
};
|
||||
|
||||
@Override
|
||||
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext)
|
||||
throws ParameterResolutionException {
|
||||
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
|
||||
Object ret = null;
|
||||
//
|
||||
// Return a random, valid Person object if Person.class is the type of Parameter
|
||||
/// 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)];
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext)
|
||||
throws ParameterResolutionException {
|
||||
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
|
||||
boolean ret = false;
|
||||
//
|
||||
// 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;
|
||||
}
|
||||
return ret;
|
||||
|
@ -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.
|
||||
@ -70,14 +64,12 @@ public class PersonValidator {
|
||||
if (person.getFirstName() == null) {
|
||||
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)!");
|
||||
}
|
||||
if (!isStringValid(person.getFirstName(), ILLEGAL_NAME_CHARACTERS)) {
|
||||
throw new ValidationException(
|
||||
"Person FirstName (" + person.getFirstName() + ") may not contain any of the following characters: "
|
||||
+ Arrays.toString(ILLEGAL_NAME_CHARACTERS)
|
||||
+ "!");
|
||||
throw new ValidationException("Person FirstName (" + person.getFirstName() + ") may not contain any of the following characters: " + Arrays.toString(ILLEGAL_NAME_CHARACTERS) + "!");
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
@ -104,14 +96,12 @@ public class PersonValidator {
|
||||
if (person.getFirstName() == null) {
|
||||
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)!");
|
||||
}
|
||||
if (!isStringValid(person.getFirstName(), ILLEGAL_NAME_CHARACTERS)) {
|
||||
throw new ValidationException(
|
||||
"Person LastName (" + person.getLastName() + ") may not contain any of the following characters: "
|
||||
+ Arrays.toString(ILLEGAL_NAME_CHARACTERS)
|
||||
+ "!");
|
||||
throw new ValidationException("Person LastName (" + person.getLastName() + ") may not contain any of the following characters: " + Arrays.toString(ILLEGAL_NAME_CHARACTERS) + "!");
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
@ -12,36 +12,47 @@ public class ValidPersonParameterResolver implements ParameterResolver {
|
||||
/**
|
||||
* The "good" (valid) data for testing purposes has to go somewhere, right?
|
||||
*/
|
||||
public static Person[] VALID_PERSONS = {
|
||||
new Person().setId(1L).setLastName("Adams").setFirstName("Jill"),
|
||||
new Person().setId(2L).setLastName("Baker").setFirstName("James"),
|
||||
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"),
|
||||
public static Person[] VALID_PERSONS = { new Person().setId(1L)
|
||||
.setLastName("Adams")
|
||||
.setFirstName("Jill"),
|
||||
new Person().setId(2L)
|
||||
.setLastName("Baker")
|
||||
.setFirstName("James"),
|
||||
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
|
||||
};
|
||||
|
||||
@Override
|
||||
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext)
|
||||
throws ParameterResolutionException {
|
||||
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
|
||||
Object ret = null;
|
||||
//
|
||||
// Return a random, valid Person object if Person.class is the type of Parameter
|
||||
/// 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)];
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext)
|
||||
throws ParameterResolutionException {
|
||||
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
|
||||
boolean ret = false;
|
||||
//
|
||||
// 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;
|
||||
}
|
||||
return ret;
|
||||
|
Loading…
x
Reference in New Issue
Block a user