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);
}
}
}
Related
am trying to implement depends on methods
i have given depends on login as agent for booking an appointment but its showing non exist method
ihave given #data provider and depends on method
this is login test case
public class TC001_Login extends ProjectSpecificMethods{
#BeforeTest
public void setValues() {
testCaseName = "Login";
testDescription = "This test is to verify whether user able to login and logout";
nodes = "login";
authors = "manoj";
category = "Smoke";
}
#Test(priority = 0)
public void loginAsAgent() throws InterruptedException, IOException {
new LoginPage(driver, node)
.enterUserName()
.enterPassword()
.enterCaptchAndClickLogin()
.clickOnLogout()
.verifyLogout();
}
}
this is appointment booking test case
public class TC003_BookAppointment extends ProjectSpecificMethods {
#BeforeTest
public void setValues() {
testCaseName = "bookappointment";
testDescription = "booking an appointment";
nodes = "appointment,appointment1";
authors = "manoj";
category = "Smoke";
dataSheetName = "ScheduleAppointment";
sheetName = "TestData";
}
#Test(dataProvider = "fetchData",dependsOnMethods = {"loginAsAgent"})
public void bookappointment(String visatype,String VscCode,String noofapplicants,String date,String path) throws IOException, Exception {
new LoginPage(driver, node)
.enterUserName()
.enterPassword()
.enterCaptchAndClickLogin()
.clickGroupScheduling()
.selectVisaType(visatype)
.selectVscCenter(VscCode)
.selectNumberOfApplicants(noofapplicants)
.enterCaptcha()
.selectDate_Normal(date)
.selectTime()
.confirmSlot_Normal()
.submitScheduling_Normal()
.generatePassportNumber()
.uploadexcel(path)
.clickUploadexcel()
.clickConsentcheckbox()
.clickSaveApplicantDetais()
.downloadAppointmentslip()
.downloadGroupSchedulingForm()
.verifyGroupid();
}
}
tried to give classname.methodname but not working
I need to validate my ui data and api responses are same,
here is my code I tried,
private ValidateContentPage cp = new ValidateContentPage();
public void getTitle() {
String UITitle = driver.findElement(titlepage).getText();
System.out.println(UITitle);
Assert.assertEquals(UITitle, cp.getAPICall(),"Passed");
}
here im getting my api responses,
public class ValidateContentPage {
public common cm = new common();
public Properties prop;
public void baseURI() {
prop = cm.getProperties("./src/test/API/IndiaOne/propertyfile/EndpointURL.properties");
RestAssured.baseURI = prop.getProperty("baseURI");
}
public String getAPICall() {
objectpojo ps = given().expect().defaultParser(Parser.JSON).when().get(prop.getProperty("resources")).as(objectpojo.class, cm.getMapper());
int number = ps.getPosts().size();
System.out.println(number);
System.out.println(ps.getPosts().get(0).getTitle());
return ps.getPosts().get(0).getTitle();
}
If i validate both using testng assertion it throwing null pointer exception, anyone help me on how to validate my ui data and api responses.
You need to call your ValidateContentPage from #Test itself or from #BeforeTest
#Test
public void getTitle() {
String UITitle = driver.findElement(titlepage).getText();
System.out.println(UITitle);
ValidateContentPage cp = new ValidateContentPage();
Assert.assertEquals(UITitle, cp.getAPICall(),"Passed");
}
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
here's my code for the controller:
I have put my object in a map in the "doLogin" method below and I am trying to access it in my "logout" function but I am getting null value when I am trying to fetch value of my session attribute using "map.get(key)"
#Controller
#SessionAttributes(value={"session1"})
public class CredentialsController {
#Autowired
private Authentication authenticationDao;
#Autowired
private User userDao;
#RequestMapping(value="/start",method=RequestMethod.GET) //Default Method
public String doStart(#ModelAttribute CredentialsBean credentialsBean)
{
return "login";
}
#RequestMapping(value="/login",method=RequestMethod.GET) //Default Method
public String doLogin(#ModelAttribute CredentialsBean credentialsBean,Map<String,Object> map)
{
String result="";
if(credentialsBean!=null){
if(authenticationDao.authenticate(credentialsBean)){
String userType=authenticationDao.authorize(credentialsBean.getUserID());
if(userType.equalsIgnoreCase("A")){
CredentialsBean cBean= authenticationDao.changeLoginStatus(credentialsBean, 1);
map.put("session1",cBean); ----->Here I am putting the object inside a map .
result= "admin";
//map.put("username",credentialsBean.getProfileBean().getFirstName());
}
else{
CredentialsBean cBean=authenticationDao.changeLoginStatus(credentialsBean, 1);
map.put("session1",cBean.getUserID());
//System.out.println(cBean.getUserID());
result= "customer";
//map.put("username",credentialsBean.getProfileBean().getFirstName());
}
}
else{
result="ERROR";
}
}
return result;
}
#RequestMapping(value="/logout",method=RequestMethod.GET) //Default Method
public String doLogout(Map<String,Object > map)
{
CredentialsBean credentialsBean=(CredentialsBean)map.get("session1");
//System.out.println(userID);
System.out.println(credentialsBean.getUserID());
if(credentialsBean!=null){
if(userDao.logout(credentialsBean.getUserID())){
return "logout";
}
else{
return "error1";
}
}
else{
return "error";
}
}
}
Here is the way I would do it:
in your doLogin method you should add HttpSession session:
#RequestMapping(value="/login",method=RequestMethod.GET) //Default Method
public String doLogin(#ModelAttribute CredentialsBean credentialsBean, HttpSession session)
{
String result="";
if(credentialsBean!=null){
if(authenticationDao.authenticate(credentialsBean)){
String userType=authenticationDao.authorize(credentialsBean.getUserID());
if(userType.equalsIgnoreCase("A")){
CredentialsBean cBean= authenticationDao.changeLoginStatus(credentialsBean, 1);
// add object to session
session.setAttribute("session1",cBean);
result= "admin";
//map.put("username",credentialsBean.getProfileBean().getFirstName());
}
else{
CredentialsBean cBean=authenticationDao.changeLoginStatus(credentialsBean, 1);
session.setAttribute("session1",cBean);
result= "customer";
}
}
else{
result="ERROR";
}
}
return result;
}
Note, that you should add to session objects of the same type in order to safely retrieve it later (because now you added different objects cBean and cBean.getUserID() for the same key session1)
Then in your logout:
#RequestMapping(value="/logout",method=RequestMethod.GET) //Default Method
public String doLogout(HttpSession session)
{
CredentialsBean credentialsBean=(CredentialsBean)session.getAttribute("session1");
.....
}
But anyway, since you're implementing login\logout here I encourage you to learn more about Spring Security.
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;
}