java.sql.SQLException: Missing IN or OUT parameter at index:: 2 - java

I am getting java.sql.SQLException: Missing IN or OUT parameter at index:: 2 error when trying to access a stored proc(created in oracle) which is having client name (varchar) as input param & cursor as output param. The error is coming when i test it thru a JSP page but when I tested the stroed proc thru a Junit i am not getting the error. So I am quite confused. Please find below my stored proc & also the DAOImpl class which is having the call. I can see that the JSP page is properly passing the name from a input text box to the name input param of stored proc.
PROCEDURE sp_get_client_details_by_name (
p_client_name IN ncr.ncr_parties.full_legal_name%TYPE,
p_result_set OUT SYS_REFCURSOR)
AS
BEGIN
OPEN p_result_set FOR
SELECT np.newedge_party_id AS client_id,
np.full_legal_name AS client_name,
np.city,
nc.name residence_country_name,
np.life_cycle_status AS status,
ec_addr.addr2 AS client_address1,
ec_addr.title_dist_compl AS client_address2,
ec_addr.zip AS client_address3,
ec_addr.state AS client_address4,
ec_addr.title_compl AS client_address_tc,
ec_addr.locality_compl AS client_address_lc,
le.newedge_legal_entity_id AS legal_entity_id,
le.full_legal_name AS legal_entity_name,
le_addr.addr2 AS legal_entity_address1,
le_addr.title_dist_compl AS legal_entity_address2,
le_addr.zip AS legal_entity_address3,
le_addr.state AS legal_entity_address4,
le_addr.title_compl AS legal_entity_address_tc,
le_addr.locality_compl AS legal_entity_address_lc
FROM ncr.ncr_parties np
JOIN ncr_legal_entities le
ON np.legal_entity_key = le.legal_entity_key
JOIN ncrglobalcountryview_vw nc
ON nc.country_alias_key = np.residence_country_aliases_key
JOIN ncr_cpty_addresses ec_addr
ON ec_addr.cpty_key = np.party_key
AND ec_addr.cpty_level = 'P'
AND ec_addr.addr_type_key = 1
JOIN ncr_cpty_addresses le_addr
ON le_addr.cpty_key = le.legal_entity_key
AND le_addr.cpty_level = 'LE'
AND le_addr.addr_type_key = 1
WHERE np.full_legal_name LIKE '%' || p_client_name || '%';
EXCEPTION
WHEN OTHERS
THEN
DBMS_OUTPUT.put_line (
SQLERRM || ' backtrace: ' || DBMS_UTILITY.format_error_backtrace);
raise_application_error (
'-20000',
'Unknown exception occurred. Please contact support.' || SQLERRM);
END sp_get_client_details_by_name;
END pkg_ocr_gui;
public class ECIDDetailsDAOImpl implements ECIDDetailsDAO {
private DataSource dataSource;
private static final String SP_GET_ECID_DETAILS = "ncr.pkg_ocr_gui.sp_get_client_details_by_name";
private static final String EC_ID_NAME_PARAM = "p_client_name";
private static final String ECID_CUR_TYPES = "p_result_set";
public DataSource getDataSource() {
return dataSource;
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public List<ECIDDetails> getECIDDetails(String elementaryClientName) {
GetECIDDetailsStoredProcedure getECIDDetailsStoreProc = new GetECIDDetailsStoredProcedure(dataSource, SP_GET_ECID_DETAILS);
Map<String, Object> resultsMap = getECIDDetailsStoreProc.executeECIDetails(elementaryClientName);
List<ECIDDetails> ecidDetails = (List<ECIDDetails>) resultsMap.get(ECID_CUR_TYPES);
return ecidDetails;
}
class GetECIDDetailsStoredProcedure extends StoredProcedure {
public GetECIDDetailsStoredProcedure(DataSource dataSource, String sprocName) {
super(dataSource, sprocName);
declareParameter(new SqlParameter(EC_ID_NAME_PARAM, java.sql.Types.VARCHAR));
declareParameter(new SqlOutParameter(ECID_CUR_TYPES, OracleTypes.CURSOR, new BeanPropertyRowMapper<ECIDDetails>(ECIDDetails.class)));
compile();
}
public Map<String, Object> executeECIDetails(String elementaryClientName) {
Map <String, Object> inputs = new HashMap<String, Object>();
inputs.put(EC_ID_NAME_PARAM, elementaryClientName);
return super.execute(inputs);
}
}
}
Below is my JUnit test which is giving back proper data
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = {"classpath*:test-applicationcontext.xml"})
public class ECIDFetchServiceTest {
#Autowired
ECIDDetailsDAOImpl ecIDDAO;
#Test
public void validategetECIDDetails() {
List<ECIDDetails> ecidDetails = new ArrayList<ECIDDetails>();
ecidDetails = ecIDDAO.getECIDDetails("ABN");
assertNotNull(ecidDetails);
assertTrue(ecidDetails.size() > 0);
}
}
Hi Priyesh,
I am using JSF to create the UI. Please find below the necessary codes.
JSF Code
<h:panelGrid columns="3" cellspacing="5" cellpadding="5">
<h:outputLabel value="Elementary Client Name" />
<h:inputText value="#{ecIDBean.elementaryClientName}" />
<h:commandButton value="Get EC" action="#{ecIDBean.executeEcIDList}">
</h:commandButton>
</h:panelGrid>
Managed Bean Class
public class ECIDFetchBean {
private String elementaryClientName;
private List<ECIDDetails> ecIDList;
private ECIDFetchService ecIDFetchService;
public ECIDFetchBean() {
ApplicationContext ctx = ApplicationContextProvider.getApplicationContext();
ecIDFetchService = (ECIDFetchServiceImpl)ctx.getBean("ecIDFetchService");
}
public String getElementaryClientName() {
return elementaryClientName;
}
public void setElementaryClientName(String elementaryClientName) {
this.elementaryClientName = elementaryClientName;
}
public List<ECIDDetails> getEcIDList() {
return ecIDList;
}
public void setEcIDList(List<ECIDDetails> ecIDList) {
this.ecIDList = ecIDList;
}
public void executeEcIDList() {
ecIDList = ecIDFetchService.getECIDDetails(elementaryClientName);
}
}
Service Class
public class ECIDFetchServiceImpl implements ECIDFetchService {
private ECIDDetailsDAO ecidDetailsDAO;
public List<ECIDDetails> getECIDDetails(String elementaryClientName) throws OCRReportingException {
return ecidDetailsDAO.getECIDDetails(elementaryClientName);
}
Hi Priyesh,
JSP is also pointing to same Database. I changed my DAOImpl class to call stored proc using
SimpleJdbcCall & it's working fine now from both JUnit as well as JSP.
public List<ECIDDetails> getECIDDetailsBySimpleJDBCCall(String elementaryClientName){
SimpleJdbcCall simpleJdbcCall = new SimpleJdbcCall(dataSource);
simpleJdbcCall.withCatalogName("ncr.pkg_ocr_gui").withProcedureName("sp_get_client_details_by_name")
.withoutProcedureColumnMetaDataAccess()
.declareParameters(new SqlParameter(EC_ID_NAME_PARAM, java.sql.Types.VARCHAR),
new SqlOutParameter(ECID_CUR_TYPES, OracleTypes.CURSOR, new BeanPropertyRowMapper<ECIDDetails>(ECIDDetails.class)));
MapSqlParameterSource sqlParameterSource = new MapSqlParameterSource();
sqlParameterSource.addValue(EC_ID_NAME_PARAM, elementaryClientName);
Map<String, Object> results = simpleJdbcCall.execute(sqlParameterSource);
List<ECIDDetails> ecidDetails = (List<ECIDDetails>) results.get(ECID_CUR_TYPES);
return ecidDetails;
}

Related

Exception in combination of #DirtiesContext and FlywayConfig bean in integration test

I have a problem when adding new test. And the problem is I think related to #DirtiesContext. I tried removing and adding it but nothing works in combination. Test 1 is using Application Context as well.
the following two are running together and no issue.
Test 1
#ActiveProfiles({"aws", "local"})
#RunWith(SpringJUnit4ClassRunner.class)
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class UnauthorizedControllerTest {
private static final Logger LOGGER = LoggerFactory.getLogger(UnauthorizedControllerTest.class);
#Autowired
private TestRestTemplate testRestTemplate;
#LocalServerPort
private int port;
#Autowired
private ApplicationContext context;
private Map<Class<?>, List<String>> excludedMethodsPerController;
#Before
public void setUp() {
excludedMethodsPerController = excludedMethodsPerController();
}
#Test
public void contextStarts() {
assertNotNull(context);
}
#Test
public void controllerCall_WithoutAuthorization_ReturnsUnauthorized() {
Map<String, Object> controllerBeans = context.getBeansWithAnnotation(Controller.class);
for (Object controllerInstance : controllerBeans.values()) {
LOGGER.info("Checking controller {}", controllerInstance);
checkController(controllerInstance);
}
}
public void checkController(Object controllerInstance) {
// Use AopUtils for the case that spring wraps the controller in a proxy
Class<?> controllerClass = AopProxyUtils.ultimateTargetClass(controllerInstance);
Method[] allMethods = controllerClass.getDeclaredMethods();
for (Method method : allMethods) {
LOGGER.info("Checking method: {}", method.getName());
if (!isCallable(controllerClass, method)) {
continue;
}
String urlPrefix = urlPrefix(controllerClass);
Mapping mapping = Mapping.of(method.getAnnotations());
for (String url : mapping.urls) {
for (RequestMethod requestMethod : mapping.requestMethods) {
ResponseEntity<String> exchange = exchange(urlPrefix + url, requestMethod);
String message = String.format("Failing %s.%s", controllerClass.getName(), method.getName());
assertEquals(message, HttpStatus.UNAUTHORIZED, exchange.getStatusCode());
}
}
}
}
private ResponseEntity<String> exchange(String apiEndpoint, RequestMethod requestMethod) {
return testRestTemplate.exchange(url(replacePathVariables(apiEndpoint)), HttpMethod.resolve(requestMethod.name()), null, String.class);
}
private String urlPrefix(Class<?> aClass) {
if (!aClass.isAnnotationPresent(RequestMapping.class)) {
return "";
}
RequestMapping annotation = aClass.getAnnotation(RequestMapping.class);
return annotation.value()[0];
}
private String url(String url) {
return "http://localhost:" + port + url;
}
private boolean isCallable(Class<?> controller, Method method) {
return Modifier.isPublic(method.getModifiers())
&& !isExcluded(controller, method)
&& !isExternal(controller);
}
private boolean isExcluded(Class<?> controller, Method method) {
List<String> excludedMethodsPerController = this.excludedMethodsPerController.getOrDefault(controller, new ArrayList<>());
return excludedMethodsPerController.contains(method.getName());
}
private boolean isExternal(Class<?> controller) {
return controller.getName().startsWith("org.spring");
}
private String replacePathVariables(String url) {
return url.replaceAll("\\{[^\\/]+}", "someValue");
}
/**
* There must be a really good reason to exclude the method from being checked.
*
* #return The list of urls that must not be checked by the security
*/
private static Map<Class<?>, List<String>> excludedMethodsPerController() {
Map<Class<?>, List<String>> methodPerController = new HashMap<>();
methodPerController.put(AuthenticationController.class, Collections.singletonList("generateAuthorizationToken"));
methodPerController.put(SystemUserLoginController.class, Arrays.asList("systemUserLogin", "handleException"));
methodPerController.put(ValidationController.class, Collections.singletonList("isValid"));
return methodPerController;
}
}
Test 2
#RunWith(SpringJUnit4ClassRunner.class)
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
#ActiveProfiles({"aws", "local"})
public class RoleAdminControllerAuditTest {
private static final String DOMAIN_NAME = "testDomain";
private static final String APP_NAME_1 = "testApp_1";
private static final String APP_NAME_2 = "testApp_2";
private static final String ROLE_NAME = "testRole";
private static final String USER_NAME = "testUser";
#Autowired
AuditRepository auditRepository;
#Autowired
RoleAdminController roleAdminController;
#MockBean
RoleAdminService roleAdminService;
#MockBean
RoleAdminInfoBuilder infoBuilder;
#MockBean
AppInfoBuilder appInfoBuilder;
#MockBean
BoundaryValueService boundaryValueService;
#MockBean
RoleService roleService;
#MockBean
private SecurityService securityService;
private static final String URS_USER = "loggedInUser";
private static final String BOUNDARY_VALUE_KEY = "11";
private static final String BOUNDARY_VALUE_NAME = "Schulenberg";
private String auditEventDate = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
#BeforeClass
public static void setupTestEnv() {
// https://github.com/localstack/localstack/issues/592
System.setProperty("com.amazonaws.sdk.disableCbor", "true");
}
#Before
public void setUp() throws Exception {
auditRepository.clean();
when(securityService.getLoggedInUser()).thenReturn(new TestHelper.FakeUser(URS_USER));
//when(roleService.addRoleToApp(any(), any(), eq(ROLE_NAME))).thenReturn(TestHelper.initRole(ROLE_NAME));
when(boundaryValueService.findBoundaryValueById(eq(123L))).thenReturn(initBoundaryValue(BOUNDARY_VALUE_KEY, BOUNDARY_VALUE_NAME));
when(boundaryValueService.findBoundaryValueById(eq(666L))).thenReturn(initBoundaryValue(BOUNDARY_VALUE_KEY, BOUNDARY_VALUE_NAME));
}
#Test
public void addUserAsRoleAdminLogged() throws UserIsAlreadyRoleAdminException, RoleNotFoundException, BoundaryValueNotFoundException {
User user = initUser(USER_NAME);
List<RoleAdminInfo> roleAdminInfos = getRoleAdminInfos();
roleAdminController.addUserAsRoleAdmin(user, roleAdminInfos);
List<String> result = auditRepository.readAll();
assertEquals("some data", result.toString());
}
#Test
public void removeUserAsRoleAdminLogged() throws RoleNotFoundException, BoundaryValueNotFoundException {
User user = initUser(USER_NAME);
Long roleId = Long.valueOf(444);
Role role = initRole("test-role");
role.setApp(initApp("test-app"));
role.setDomain(initDomain("test-domain"));
when(roleService.getRoleByIdOrThrow(roleId)).thenReturn(role);
roleAdminController.removeUserAsRoleAdmin(user, roleId, Long.valueOf(666));
List<String> result = auditRepository.readAll();
assertEquals("some data", result.toString());
}
#Test
public void removeRoleAdminPermission() throws RoleNotFoundException, BoundaryValueNotFoundException {
User user = initUser(USER_NAME);
List<RoleAdminInfo> roleAdminInfos = getRoleAdminInfos();
roleAdminController.removeRoleAdminPermission(user, roleAdminInfos);
List<String> result = auditRepository.readAll();
assertEquals(1, result.size());
assertEquals("some data", result.toString());
}
private List<RoleAdminInfo> getRoleAdminInfos() {
RoleAdminInfo info1 = initRoleAdminInfo(DOMAIN_NAME, ROLE_NAME, APP_NAME_1);
RoleAdminInfo info2 = initRoleAdminInfo(DOMAIN_NAME, ROLE_NAME, APP_NAME_2);
info1.setBoundaryValueId(123L);
info1.setBoundaryValueKey(BOUNDARY_VALUE_KEY);
info1.setBoundaryValueName(BOUNDARY_VALUE_NAME);
return Arrays.asList(info1, info2);
}
}
Test 3 (newly added one)
#RunWith(SpringJUnit4ClassRunner.class)
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = FlywayConfig.class)
#DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
#ActiveProfiles({"aws", "local"})
public class BoundaryValueDeltaControllerTest {
private static final String API_V1 = "/api/v1/";
#Autowired
TestRestTemplate testRestTemplate;
#Autowired
private DomainBuilder domainBuilder;
#Autowired
private AppBuilder appBuilder;
#Autowired
private UserBuilder userBuilder;
#Autowired
private DomainAdminBuilder domainAdminBuilder;
#Autowired
private BoundarySetBuilder boundarySetBuilder;
#MockBean
private LoginUserProvider loginUserProvider;
#MockBean
private LoginTokenService loginTokenService;
#MockBean
private BoundaryServiceAdapter serviceAdapter;
#LocalServerPort
private int port;
LoginUserInfo loggedInUser;
#Before
public void setUp() {
clear();
}
#After
public void tearDown() {
clear();
}
#Test
public void updateBoundaryValuesFromApi() throws UrsBusinessException {
Domain domain = domainBuilder.persist();
App app = appBuilder.persist(domain);
BoundarySet boundarySet = boundarySetBuilder.persist(domain);
User user = userBuilder.persist(domain.getAuthor().getUsername());
aLoggedInUser(domain.getAuthor().getUsername());
domainAdminBuilder.persist(user, domain);
mockReadInfoFromApiUsingApp();
ResponseEntity<String> response = callUpdateBoundaryValuesFromApi(domain, boundarySet, app);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertNotNull(response.getBody());
}
private void mockReadInfoFromApiUsingApp() throws UrsBusinessException {
BoundaryValueInfo boundaryValueInfo = new BoundaryValueInfo();
boundaryValueInfo.setBoundaryValueId(10L);
boundaryValueInfo.setBoundaryValueKey("boundaryValueKey");
boundaryValueInfo.setBoundaryValueName("boundaryValuename");
when(serviceAdapter.readInfoFromApiUsingApp(any(), any(), any())).thenReturn(new BoundaryValueInfo[]{boundaryValueInfo});
}
private ResponseEntity<String> callUpdateBoundaryValuesFromApi(Domain domain, BoundarySet boundarySet, App app) {
String url = url(API_V1 + "domains/" + domain.getName() + "/boundarysets/" + boundarySet.getBoundarySetName() + "/app/" + app.getName()+ "/updatefromapi/");
return testRestTemplate.exchange(url,HttpMethod.GET, null, String.class);
}
private String url(String url) {
return "http://localhost:" + port + url;
}
private void aLoggedInUser(String username) {
Claims claims = Jwts.claims();
claims.put("username", username);
loggedInUser = LoginUserInfo.parse(claims);
when(loginUserProvider.getLoggedInUser()).thenReturn(loggedInUser);
when(loginTokenService.parseToken(any())).thenReturn(loggedInUser);
}
private void clear() {
appBuilder.deleteAll();
boundarySetBuilder.deleteAll();
domainAdminBuilder.deleteAll();
domainBuilder.deleteAll();
userBuilder.deleteAll();
}
}
Flyway config
#TestConfiguration
public class FlywayConfig {
#Bean
public FlywayMigrationStrategy clean() {
return flyway -> {
flyway.clean();
flyway.migrate();
};
}
}
And I am getting below exception while running all together.
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:125)
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java.....
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'flywayInitializer' defined in class path resource [org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration$FlywayConfiguration.class]: Invocation of init method failed; nested exception is org.flywaydb.core.internal.exception.FlywaySqlException:
Unable to obtain connection from database: Too many connections
---------------------------------------------------------------
SQL State : 08004
Error Code : 1040
Message : Too many connections
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1762)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:593)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
... 49 more
Caused by: org.flywaydb.core.internal.exception.FlywaySqlException:
Unable to obtain connection from database: Too many connections
I am struggling since yesterday's and you might find duplicate but I tried to add the more details today. please guide me here.
you must add the configuration for flyway
flyway.url=jdbc:postgresql://xxx.eu-west-2.rds.amazonaws.com:5432/xxx
flyway.user=postgres
flyway.password=xxx

Unable to set correct expectation in Junit. Facing mockit.internal.UnexpectedInvocation

Below is my test method.
#Test
public void testSaveUserPreference() throws Exception {
final long userId = 1L;
final String category = "category";
final UserPreference userPreference = createMockedUserPreference(userId, category);
final UserPreferenceDTO userPreferenceDTO = createMockedUserPreferenceDTO(userId, category);
final Date lastAccessed = userPreference.getLastAccessedDate();
userPreferenceDTO.setLastAccessedDate(lastAccessed);
//override the convert method to control the object being "saved"
final UserPreference document = new UserPreference();
new MockUp<UserPreferenceUtils>() {
#Mock
UserPreference convertFromDTO(UserPreferenceDTO dto) {
document.setUserId(userPreference.getUserId());
document.setCategory(userPreference.getCategory());
document.setProperties(userPreference.getProperties());
return document;
}
};
new Expectations() {{
component.getUserPreference(userId, category);
returns(userPreference);
component.saveUserPreference(userPreference);
returns(userPreference);
}};
UserPreferenceDTO actual = service.savePreference(userPreferenceDTO);
assertNotNull(actual);
assertEquals(userPreference.getUserId(), actual.getUserId());
assertEquals(userPreference.getCategory(), actual.getCategory());
assertEquals(userPreference.getProperties(), actual.getProperties());
assertNotNull(actual.getCreatedDate());
assertTrue(lastAccessed.before(actual.getLastAccessedDate()));
}
Below is the service method in which I am facing the error.
#Transactional
public UserPreferenceDTO savePreference(UserPreferenceDTO userPreference) {
UserPreference preference = UserPreferenceUtils.convertFromDTO(userPreference);
UserPreference existingPreference = userPreferenceComponent.getUserPreference(userPreference.getUserId(), userPreference.getCategory());
if(existingPreference!=null && !CollectionUtils.isEmpty(existingPreference.getProperties())) {
Map<String,Object> report = (Map<String, Object>) preference.getProperties().get("favoriteFilters");
Map<String,Object> existingRep = (Map<String, Object>) existingPreference.getProperties().get("favoriteFilters");
existingRep.putAll(report);
existingPreference.getProperties().put("favoriteFilters",existingRep);
} else {
existingPreference = preference;
}
if (existingPreference.getCreatedDate() == null) {
existingPreference.setCreatedDate(new Date());
}
existingPreference.setLastAccessedDate(new Date());
UserPreferenceDTO savedPreference = UserPreferenceUtils.convertFromDocument(userPreferenceComponent.saveUserPreference(existingPreference));
return savedPreference;
}
When calling the save method in the second last line, it is giving this error.
mockit.internal.UnexpectedInvocation: Parameter "userPreference" of com.curaspan.platformsupportservice.components.preference.UserPreferenceComponent#saveUserPreference(com.curaspan.platformsupportservice.mongo.document.UserPreference userPreference) expected com.curaspan.platformsupportservice.mongo.document.UserPreference#3d3fcdb0, got com.curaspan.platformsupportservice.mongo.document.UserPreference#636be97c
The userPreference object in the Expectation and the actual method is not matching, though I have all the parameters same. Is there anything I am missing out?

NullPointer Exception - JSF Event Handling ( ValueChangeListener )

I am learning JSF Event Handling and when I try to run some sample code, I am getting a Null Pointer Exception.
This is my index.xhtml snippet,
<h:form>
<h2>Implement valueChangeListener</h2>
<hr />
<h:panelGrid columns="2">
Selected Locale:
<h:selectOneMenu value="#{userData.selectedCountry}" onchange="submit()">
<f:valueChangeListener type="com.cyb3rh4wk.test.LocaleChangeListener" />
<f:selectItems value="#{userData.countries}" />
</h:selectOneMenu>
Country Name:
<h:outputText id="countryInterface" value="#{userData.selectedCountry}" />
</h:panelGrid>
</h:form>
UserData.java
#ManagedBean(name = "userData", eager = true)
#ApplicationScoped
public class UserData implements Serializable{
private static Map<String, String> countryMap;
private String selectedCountry = "United Kingdom";
static {
countryMap = new LinkedHashMap<String, String>();
countryMap.put("en", "United Kingdon");
countryMap.put("fr", "French");
countryMap.put("de", "German");
countryMap.put("def", "Default");
}
public String getSelectedCountry() {
return selectedCountry;
}
public void setSelectedCountry(String selectedCountry) {
this.selectedCountry = selectedCountry;
System.out.println("Locale set");
}
public Map<String, String> getCountries() {
return countryMap;
}
public void localeChanged(ValueChangeEvent event) {
selectedCountry = event.getNewValue().toString();
}
}
LocaleChangeListener.java
public class LocaleChangeListener implements ValueChangeListener {
#Override
public void processValueChange(ValueChangeEvent event) throws AbortProcessingException {
UserData userData = (UserData) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("userData");
String newLocale = event.getNewValue().toString();
if (newLocale != null)
userData.setSelectedCountry(newLocale);
else
userData.setSelectedCountry("Default");
}
}
When I run these on Glassfish Server, I get an error,
java.lang.NullPointerException
at com.cyb3rh4wk.test.LocaleChangeListener.processValueChange(LocaleChangeListener.java:25)
at com.sun.faces.facelets.tag.jsf.core.ValueChangeListenerHandler$LazyValueChangeListener.processValueChange(ValueChangeListenerHandler.java:128)
at javax.faces.event.ValueChangeEvent.processListener(ValueChangeEvent.java:134)
Can anyone help me with this ?
You are getting NullPointerException because userData is not found in the session scope.
The reason this is happening is that you put the userData in the application scope (#ApplicationScoped annotation on your managed bean) and searching it in the session scope.
Eventhough you verified that userData is null it still prints Locale set because the bean is in the application scope as described in 2. above.
So what is the solution? Either change #ApplicationScoped to #SessionScoped or access your userData by changing:
UserData userData = (UserData) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("userData");
to
FacesContext ctx = FacesContext.getCurrentInstance();
UserData userData = (UserData)ctx.getExternalContext().getApplicationMap().get("userData");

Nested Query in DynamoDB returns nothing

I'm using DynamoDB with the Java SDK, but I'm having some issues with querying nested documents. I've included simplified code below. If I remove the filter expression, then everything gets returned. With the filter expression, nothing is returned. I've also tried using withQueryFilterEntry(which I'd prefer to use) and I get the same results. Any help is appreciated. Most of the documentation and forums online seem to use an older version of the java sdk than I'm using.
Here's the Json
{
conf:
{type:"some"},
desc: "else"
}
Here's the query
DynamoDBQueryExpression<JobDO> queryExpression = new DynamoDBQueryExpression<PJobDO>();
queryExpression.withFilterExpression("conf.Type = :type").addExpressionAttributeValuesEntry(":type", new AttributeValue(type));
return dbMapper.query(getItemType(), queryExpression);
Is it a naming issue? (your sample json has "type" but the query is using "Type")
e.g. the following is working for me using DynamoDB Local:
public static void main(String [] args) {
AmazonDynamoDBClient client = new AmazonDynamoDBClient(new BasicAWSCredentials("akey1", "skey1"));
client.setEndpoint("http://localhost:8000");
DynamoDBMapper mapper = new DynamoDBMapper(client);
client.createTable(new CreateTableRequest()
.withTableName("nested-data-test")
.withAttributeDefinitions(new AttributeDefinition().withAttributeName("desc").withAttributeType("S"))
.withKeySchema(new KeySchemaElement().withKeyType("HASH").withAttributeName("desc"))
.withProvisionedThroughput(new ProvisionedThroughput().withReadCapacityUnits(1L).withWriteCapacityUnits(1L)));
NestedData u = new NestedData();
u.setDesc("else");
Map<String, String> c = new HashMap<String, String>();
c.put("type", "some");
u.setConf(c);
mapper.save(u);
DynamoDBQueryExpression<NestedData> queryExpression = new DynamoDBQueryExpression<NestedData>();
queryExpression.withHashKeyValues(u);
queryExpression.withFilterExpression("conf.#t = :type")
.addExpressionAttributeNamesEntry("#t", "type") // returns nothing if use "Type"
.addExpressionAttributeValuesEntry(":type", new AttributeValue("some"));
for(NestedData u2 : mapper.query(NestedData.class, queryExpression)) {
System.out.println(u2.getDesc()); // "else"
}
}
NestedData.java:
#DynamoDBTable(tableName = "nested-data-test")
public class NestedData {
private String desc;
private Map<String, String> conf;
#DynamoDBHashKey
public String getDesc() { return desc; }
public void setDesc(String desc) { this.desc = desc; }
#DynamoDBAttribute
public Map<String, String> getConf() { return conf; }
public void setConf(Map<String, String> conf) { this.conf = conf; }
}

Play2 Java - InvalidPropertyException when testing controller with form

I'd like to test a controller method named authenticate(), which has very simple logic: validating email and password from request and returning the result as JSON.
public class Users extends Controller {
static Form<User> userForm = Form.form(User.class);
public static Result login() {
return ok(views.html.users.login.render(userForm));
}
public static Result authenticate() {
Form<User> filledForm = userForm.bindFromRequest();
if (filledForm.hasErrors()) {
return badRequest(views.html.users.login.render(filledForm));
} else {
ObjectNode result = Json.newObject();
User u = filledForm.get();
if (User.isAuthValid(u.email, u.password))
result.put("status", "OK");
else
result.put("status", "Authentication failed");
return ok(result);
}
}
}
Following is the test code for authenticate():
#Test
public void callAuthenticate() {
Map<String, String> formData = Maps.newHashMap();
formData.put("email", "aaa#bbb.com");
formData.put("password", "password");
Result result = callAction(controllers.routes.ref.Users.authenticate(),
fakeRequest().withFormUrlEncodedBody(formData));
assertThat(status(result)).isEqualTo(Http.Status.OK);
}
But I got an error with following stacktrace:
javax.validation.ValidationException: HV000041: Call to TraversableResolver.isReachable() threw an exception.
at org.hibernate.validator.internal.engine.ValidatorImpl.isValidationRequired(ValidatorImpl.java:1230)
at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraint(ValidatorImpl.java:438)
at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForDefaultGroup(ValidatorImpl.java:387)
at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForCurrentGroup(ValidatorImpl.java:351)
at org.hibernate.validator.internal.engine.ValidatorImpl.validateInContext(ValidatorImpl.java:303)
at org.hibernate.validator.internal.engine.ValidatorImpl.validate(ValidatorImpl.java:133)
at org.springframework.validation.beanvalidation.SpringValidatorAdapter.validate(SpringValidatorAdapter.java:194)
at play.data.Form.bind(Form.java:327)
at play.data.Form.bindFromRequest(Form.java:215)
at controllers.Users.authenticate(Users.java:50)
at controllers.ref.ReverseUsers$$anonfun$authenticate$1.apply(routes_reverseRouting.scala:477)
at controllers.ref.ReverseUsers$$anonfun$authenticate$1.apply(routes_reverseRouting.scala:477)
at play.core.Router$HandlerInvoker$$anon$6$$anon$2.invocation(Router.scala:164)
at play.core.j.JavaAction$$anon$1.call(JavaAction.scala:31)
at play.core.j.JavaAction$$anon$2.apply(JavaAction.scala:74)
at play.core.j.JavaAction$$anon$2.apply(JavaAction.scala:73)
at play.libs.F$Promise$PromiseActor.onReceive(F.java:420)
at akka.actor.UntypedActor$$anonfun$receive$1.applyOrElse(UntypedActor.scala:159)
at akka.actor.ActorCell.receiveMessage(ActorCell.scala:425)
at akka.actor.ActorCell.invoke(ActorCell.scala:386)
at akka.dispatch.Mailbox.processMailbox(Mailbox.scala:230)
at akka.dispatch.Mailbox.run(Mailbox.scala:212)
at akka.dispatch.ForkJoinExecutorConfigurator$MailboxExecutionTask.exec(AbstractDispatcher.scala:502)
at scala.concurrent.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:262)
at scala.concurrent.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:975)
at scala.concurrent.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1478)
at scala.concurrent.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:104)
Caused by: org.springframework.beans.InvalidPropertyException: Invalid property 'email' of bean class [models.User]: No property 'email' found
at org.springframework.beans.BeanWrapperImpl.getPropertyDescriptor(BeanWrapperImpl.java:337)
at play.db.ebean.Model._idAccessors(Model.java:47)
at play.db.ebean.Model._getId(Model.java:67)
at play.db.ebean.Model.hashCode(Model.java:208)
at org.hibernate.validator.internal.engine.resolver.SingleThreadCachedTraversableResolver$TraversableHolder.buildHashCode(SingleThreadCachedTraversableResolver.java:153)
at org.hibernate.validator.internal.engine.resolver.SingleThreadCachedTraversableResolver$TraversableHolder.<init>(SingleThreadCachedTraversableResolver.java:114)
at org.hibernate.validator.internal.engine.resolver.SingleThreadCachedTraversableResolver$TraversableHolder.<init>(SingleThreadCachedTraversableResolver.java:96)
at org.hibernate.validator.internal.engine.resolver.SingleThreadCachedTraversableResolver.isReachable(SingleThreadCachedTraversableResolver.java:41)
at org.hibernate.validator.internal.engine.ValidatorImpl.isValidationRequired(ValidatorImpl.java:1221)
... 26 more
When testing on the browser, it worked as expected. But only JUnit test fails with InvalidPropertyException. What's wrong with my test code?
FYI, here's the model User:
#Entity
public class User extends Model {
#Id
#Required
#NonEmpty
public String email;
public String nickname;
#Required
public String password;
public String salt;
public static Finder<String, User> find = new Finder<String, User>(
String.class, User.class);
public static User findByEmail(String email) {
return find.where().eq("email", email).findUnique();
}
public static boolean isAuthValid(String email, String password) {
User user = findByEmail(email);
if (user == null)
return false;
return user.isValidPassword(password);
}
public boolean isValidPassword(String password) {
return this.password.equals(DigestUtils.md5Hex(password + this.salt));
}
}
Thanks for any advices/corrections.
You need to run the test inside a "Fake" application, so the binding can work. So, you're Test will look like this:
#Test
public void callAuthenticate() {
running(fakeApplication(), new Runnable() {
public void run() {
Map<String, String> formData = Maps.newHashMap();
formData.put("email", "aaa#bbb.com");
formData.put("password", "password");
Result result = callAction(controllers.routes.ref.Users.authenticate(),
fakeRequest().withFormUrlEncodedBody(formData));
assertThat(status(result)).isEqualTo(Http.Status.OK);
}
}
}

Categories