jdbcTemplate.batchUpdate issue - spring

How to convert this to return a jdbcTemplate.batchUpdate?
It needs to be executed to several tables.
#Override
public int delete(int id) {
String sql = "update user set deleted=1 where user_id = ?";
Object[] params = new Object[] { id };
try {
return jdbcTemplate.update(sql, params);
} catch (IncorrectResultSizeDataAccessException e) {
throw new UserNotFoundException("User.not.found");
}
}

#Override
public void delete(List<Integer> ids) {
String sql = "update user set deleted=1 where user_id = ?";
jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
#Override
public void setValues(PreparedStatement ps, int i) throws SQLException {
Integer userId = ids.get(i);
ps.setLong(1, userId );
}
#Override
public int getBatchSize() {
return ids.size();
}
});
}

Related

Mockito tests pass except one verify

I have all my tests pass except this line in the first test
verify(reimbursementDAO).getById(REIMBURSEMENT_TO_PROCESS.getId());
see code below.
package com.revature.services;
public class ReimbursementServiceTest {
private static ReimbursementService reimbursementService;
private static ReimbursementDAO reimbursementDAO;
private Reimbursement REIMBURSEMENT_TO_PROCESS;
private Reimbursement GENERIC_REIMBURSEMENT_1;
private Optional<Reimbursement>
GENERIC_REIMBURSEMENT_2;
private List<Reimbursement> GENERIC_ALL_PENDING_REIMBURSEMENTS;
private User GENERIC_EMPLOYEE_1;
private User GENERIC_FINANCE_MANAGER_1;
#BeforeClass
public static void setUpBeforeClass() throws Exception {
reimbursementDAO=mock(ReimbursementDAO.class);//(IReimbursementDAO.class);
reimbursementService = new ReimbursementService(reimbursementDAO);
//reimbursementDAO=new ReimbursementDAO();
}
#Before
public void setUp() throws Exception {
GENERIC_EMPLOYEE_1 = new User(1, "genericEmployee1", "genericPassword", Role.EMPLOYEE);
GENERIC_FINANCE_MANAGER_1 = new User(1, "genericManager1", "genericPassword", Role.FINANCE_MANAGER);
REIMBURSEMENT_TO_PROCESS = new Reimbursement(2, Status.PENDING, GENERIC_EMPLOYEE_1, null, 150.00);
GENERIC_REIMBURSEMENT_1 = new Reimbursement(1, Status.PENDING, GENERIC_EMPLOYEE_1, null, 100.00);
GENERIC_REIMBURSEMENT_2 = Optional.ofNullable(new Reimbursement(2, Status.APPROVED, GENERIC_EMPLOYEE_1,
GENERIC_FINANCE_MANAGER_1, 150.00));
GENERIC_ALL_PENDING_REIMBURSEMENTS = new ArrayList<Reimbursement>();
GENERIC_ALL_PENDING_REIMBURSEMENTS.add(GENERIC_REIMBURSEMENT_1);
}
#Test
public void testProcessPassesWhenUserIsFinanceManagerAndReimbursementExistsAndUpdateSuccessful()
throws Exception{
when(reimbursementDAO.getById(anyInt())).thenReturn(Optional.of(GENERIC_REIMBURSEMENT_1));
when(reimbursementDAO.update(any())).thenReturn(GENERIC_REIMBURSEMENT_2);
assertEquals(GENERIC_REIMBURSEMENT_2,
reimbursementService.process(REIMBURSEMENT_TO_PROCESS, Status.APPROVED,
GENERIC_FINANCE_MANAGER_1));
//verify(reimbursementDAO).getById(REIMBURSEMENT_TO_PROCESS.getId());
verify(reimbursementDAO).update(REIMBURSEMENT_TO_PROCESS);
}
#Test
public void testGetReimbursementByStatusPassesWhenReimbursementsAreSuccessfullyReturned() {
when(reimbursementDAO.getBystatus(any())).thenReturn(GENERIC_ALL_PENDING_REIMBURSEMENTS);
assertEquals(GENERIC_ALL_PENDING_REIMBURSEMENTS,
reimbursementService.getReimbursementsByStatus(Status.PENDING));
verify(reimbursementDAO).getBystatus(Status.PENDING);
}
}
public class ReimbursementDAO extends AbstractReimbursement
{
public Optional< Reimbursement> getById(int id) {
try(Connection conn = ConnectionFactory.getConnection())
{
String sql="select * from ers_reimbursements where reimb_id=?;";
PreparedStatement ps=conn.prepareStatement(sql);
ps.setInt(1,id);
ResultSet rs= ps.executeQuery();
Reimbursement reimb=null;
UserService usrv=new UserService();
//reimb_id ,amount, submitted,resolved,description,author,receipt ,resolver,status,reimb_type
while(rs.next())
{
int reid=rs.getInt("reimb_id");
double ramount=rs.getInt("reimb_amount");
int res=rs.getInt( "resolver");
User resolver=null;
String description=rs.getString("description");
User rauthor= usrv.getUserById( rs.getInt("author")).get();
if(res>0)
{ resolver= usrv.getUserById(res).get(); }
int rstatus= rs.getInt("reimb_status");
Status r_status=Status.values()[--rstatus];
int reimb_type= rs.getInt("reimb_type");
ReimbType retype=ReimbType.values()[--reimb_type];
User oth=rauthor;
User re=resolver;
reimb=new Reimbursement(reid, r_status,oth,re,ramount);
return Optional.ofNullable(reimb);
}
}catch(SQLException e) { e.printStackTrace();};
return Optional.empty();
}
public List<Reimbursement> getBystatus(Status status) {
try(Connection conn = ConnectionFactory.getConnection())
{
String sql="select * from ers_reimbursements where reimb_status=?;";
PreparedStatement ps=conn.prepareStatement(sql);//,Statement.RETURN_GENERATED_KEYS);
int sta_id= status.ordinal()+1;
ps.setInt(1,sta_id);
ResultSet rs= ps.executeQuery();
Reimbursement reimb=null;
List<Reimbursement> reimbList=new ArrayList<Reimbursement>();
IUserService usrv=new UserService();
//reimb_id ,amount, submitted,resolved,description,author,receipt ,resolver,status,reimb_type
while(rs.next())
{
//int id, Status status, User author, User resolver, double amount
int reid=rs.getInt("reimb_id");
double ramount=rs.getInt("reimb_amount");
Optional<User> rauthor= usrv.getUserById( rs.getInt("author"));
User oth=null;
if(rauthor.isPresent())
{ oth=rauthor.get(); }
int resol=rs.getInt( "resolver");
Optional<User> resolver= usrv.getUserById(resol);
User re=null;
if(resolver.isPresent())
{ re=resolver.get(); }
else {re=null;}
int rstatus= rs.getInt("reimb_status");
Status r_status=Status.values()[--rstatus];//.PENDING;
int reimb_type= rs.getInt("reimb_type");
ReimbType retype=ReimbType.values()[--reimb_type];//.TRAVEL;
reimb=new Reimbursement(reid, r_status,oth,re,ramount);
reimbList.add(reimb);
}
return reimbList;
}catch(SQLException e) { e.printStackTrace();};
return null;
}
public Optional<Reimbursement> update(Reimbursement unprocessedReimbursement) {
try(Connection conn=ConnectionFactory.getConnection()) {
String sql="update ers_reimbursements set reimb_status=?,"
+ " resolver=?, resolved=? where reimb_id=?;";
PreparedStatement ps=conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
int id=unprocessedReimbursement.getId();
Status st=unprocessedReimbursement.getStatus();
ps.setObject(1,st);
ps.setInt(2,unprocessedReimbursement.getResolver().getId());
ps.setObject(3, LocalDateTime.now());
ps.setInt(4,id);
ps.executeUpdate();
try (ResultSet generatedKeys = ps.getGeneratedKeys()) {
if (generatedKeys.next()) {
int reimid=generatedKeys.getInt(1);
Optional<Reimbursement> reim=getById(reimid);
System.out.println("Reimb " + reim.get()+ " upLocalTimed!");
return reim;
}
}catch(SQLException e) {};
}catch(SQLException e) { e.printStackTrace();}
return Optional.empty();
}
}
public class ReimbursementService{
{
private final ReimbursementDAO reimbDao;
public ReimbursementService() {
this(new ReimbursementDAO());
}
public ReimbursementService(ReimbursementDAO userDAO2) {
this.reimbDao = userDAO2;
}
public Optional< Reimbursement> process(Reimbursement unprocessedReimbursement,
Status finalStatus, User resolver) throws Exception{
if (!resolver.getRole().equals(Role.FINANCE_MANAGER)) {
throw new RegistrationUnsuccessfulException("Resolver must be Finance Manager ");
}
// List<Reimbursement> l=DAO.getByStatus(Status.PENDING);
if(unprocessedReimbursement.getId()==0)
{ throw new Exception(" reimbursement not found"); }
if(unprocessedReimbursement.getStatus().equals(Status.PENDING))
{
unprocessedReimbursement.setResolver(resolver);
unprocessedReimbursement.setStatus(finalStatus);
Optional<Reimbursement> reimb=this.reimbDao.update(unprocessedReimbursement );
if(reimb.isPresent())
{ return reimb; }
else { throw new Exception("unsuccessful update");}
}
return Optional.ofNullable(null);
}
}
The verification
verify(reimbursementDAO).getById(REIMBURSEMENT_TO_PROCESS.getId());
fails because your service does not call the getById() method of your DAO.
It happens that your real DAO's update() method calls its own getById() method, but in your test you are using a mock DAO, where all functionality has been stubbed out. The update() method of the mock DAO does nothing more than return GENERIC_REIMBURSEMENT_2 because that's what your test sets it up to do.

Parse JSON array data in android using Volley

JSON data format:
I am trying to fetch this array json data but not getting it.
[{"Items":"Chicken Burger","Price":"250","Quantity":"2"},
{"Items":"Hamburger","Price":"230","Quantity":"3"}]
MyCartActivity class:
I tried using Volley and I am now getting that JSONArray cannot be converted to JSONObject error. Can you mention where to change so that I can get my data?
final JsonObjectRequest request = new JsonObjectRequest (Request.Method.POST, fetchurl, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("");
for (int i=0; i < jsonArray.length(); i++){
JSONObject object = jsonArray.getJSONObject(i);
String Price = object.getString("Price");
String Name = object.getString("Items");
String Quantity = object.getString("Quantity");
adapter = new CartAdapter(MyCartActivity.this, list);
list.add(new CartPojo(Price, Name, Quantity));
adapter.notifyDataSetChanged();
progressbar.setVisibility(View.GONE);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
requestQueue.add(request);
}
Adapter class:
public CartAdapter(Activity activity, List datalist) {
this.activity = activity;
this.datalist = datalist;
}
#Override
public int getCount() {
return datalist.size();
}
#Override
public Object getItem(int position) {
return datalist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.cart_item_layout, null);
TextView ItemName = convertView.findViewById(R.id.item_name);
TextView Price = convertView.findViewById(R.id.item_price);
TextView Quantity = convertView.findViewById(R.id.items_quantity);
CartPojo pojo = datalist.get(position);
ItemName.setText(String.valueOf(pojo.getName()));
Price.setText(String.valueOf(pojo.getPrice()));
Quantity.setText(String.valueOf(pojo.getQuantity()));
return convertView;
}
Please provide me some solutions....
The response can't be parsed into JSONObject, because its not that, but a JSONArray. You can send a simple StringRequest and then parse the response string into an JSONArray using JSONArray(response) constructor.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONArray arr = new JSONArray(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
Or use the JsonArrayRequest. Here's an example.

Retrieve a user's id and keep it as long as the session is active in jsf

I have a web application in jsf where I would retrieve the id of the user for reuse in other managedbeans.
Each user has a session that is created as soon as it is autehtification the data are stored in a Mysql DB. I would like to retrieve and keep the id of the user store as long as the session is active. Can you help me please?
this are my managedBean
#ManagedBean
#SessionScoped
public class ProfManagedBeans {
private int idp;
private String email, pwd;
public HttpSession hs;
public ProfManagedBeans() {
}
public int getIdp() {
return idp;
}
public void setIdp(int id) {
this.idp = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public static PreparedStatement pstmt=null;
public static ResultSet rs = null;
public String query="";
public int dbid;
public String dbemail, dbpwd;
public String getDbemail() {
return dbemail;
}
public String getDbpwd() {
return dbpwd;
}
public void dbData(String uEmail){
DbConnect.getConnection();
query = "SELECT * FROM professeur where email='" + uEmail +"'";
try {
pstmt = DbConnect.conn.prepareStatement(query);
ResultSet rs = pstmt.executeQuery();
while(rs.next()){
dbid = rs.getInt("id_pr");
dbemail = rs.getString("email");
dbpwd = rs.getString("pwd");
}
} catch (SQLException e) {
e.printStackTrace();
System.out.println("Exception " + e);
}
}
public int getIdProf(){
dbData(email);
String ids = hs.getId();
if(ids == hs.getId()){
idp = dbid;
return idp;
}
return 0;
}
public String login(){
dbData(email);
if (email.equals(dbemail)==true&&pwd.equals(dbpwd)==true) {
hs = Util.getSession();
hs.setAttribute("email", dbemail);
System.out.println(hs.getId());
System.out.println(getIdProf());
return "success.xhtml";
}
else {
FacesMessage fm = new FacesMessage("Email error", "ERROR MSG");
fm.setSeverity(FacesMessage.SEVERITY_ERROR);
FacesContext.getCurrentInstance().addMessage(null, fm);
return "LoginProf.xhtml";
}
}
public String logout() {
hs.invalidate();
return "/LoginProf.xhtml";
}
}
public class QuestionManagedBeans {
private int id,id_pr;
private String nomDesc, question, type;
private String reponse;
private double noteV, noteF;
private String niveau, matiere,chapitre, explication;
public static PreparedStatement pstmt=null;
public static ResultSet rs = null;
public String query="";
private ArrayList<Niveau> list ;
public QuestionManagedBeans() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNomDesc() {
return nomDesc;
}
public void setNomDesc(String nomDesc) {
this.nomDesc = nomDesc;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getReponse() {
return reponse;
}
public void setReponse(String reponse) {
this.reponse = reponse;
}
public double getNoteV() {
return noteV;
}
public void setNoteV(double noteV) {
this.noteV = noteV;
}
public double getNoteF() {
return noteF;
}
public void setNoteF(double noteF) {
this.noteF = noteF;
}
public String getNiveau() {
return niveau;
}
public void setNiveau(String niveau) {
this.niveau = niveau;
}
public String getMatiere() {
return matiere;
}
public void setMatiere(String matiere) {
this.matiere = matiere;
}
public String getExplication() {
return explication;
}
public String getChapitre() {
return chapitre;
}
public void setChapitre(String chapitre) {
this.chapitre = chapitre;
}
public void setExplication(String explication) {
this.explication = explication;
}
public int getId_pr() {
return id_pr;
}
public void setId_pr() {
ProfManagedBeans p = new ProfManagedBeans();
this.id_pr = p.getIdProf();
}
public boolean insertQuestion() throws SQLException {
Question q = new Question(id,nomDesc, question, type,reponse,noteV, noteF,niveau, matiere, chapitre ,explication,id_pr);
setNomDesc("");
setQuestion("");
setType("");
setReponse("");
setNoteV(0.0);
setNoteF(0.0);
setNiveau("");
setMatiere("");
setChapitre("");
setExplication("");
return new InsertDao().insertQuestionTF(q);
}
}
I want to recover the id of the proffessor as soon as it is authenticated to be able to add it to the question table
In InsertDao.java
public boolean insertQuestionTF(Question qu) throws SQLException{
DbConnect.getConnection();
ProfManagedBeans p = new ProfManagedBeans();
query ="INSERT INTO `question_tf` (`nomdesc`, `question`, `type`, `reponse`, `noteV`, `noteF`, `niveau`, `matiere`, `chapitre`, `explication`, `id_pr`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
pstmt = DbConnect.conn.prepareStatement(query);
pstmt.setString(1, qu.getNomDesc());
pstmt.setString(2, qu.getQuestion());
pstmt.setString(3, qu.getType());
pstmt.setString(4, qu.getReponse());
pstmt.setDouble(5, qu.getNoteV());
pstmt.setDouble(6, qu.getNoteF());
pstmt.setString(7, qu.getNiveau());
pstmt.setString(8, qu.getMatiere());
pstmt.setString(9, qu.getChapitre());
pstmt.setString(10, qu.getExplication());
pstmt.setInt(11, p.getIdProf());
System.out.println("insert " + p.getIdProf());
if (pstmt == null) {
throw new SQLException();
} else {
return pstmt.executeUpdate() > 0;
}
}

Regarding DataControl in adf

I am developing an ADF web application with Oracle EBS as the backend to call the procedure(Jdeveloper 12 c).
I have invoked a method calling EBS procedure (return type is list) and the result is stored in arraylist. the list is used to create Data control.
What my problem is i have set values to the data control but when i added that dc to view it shows nothing. But on debugging it shows all the values are set in the array list.
Bean class calling EBS procedure in ApplicationModule
BindingContainer bindings = getBindings();
OperationBinding operationBinding = (OperationBinding) bindings.getOperationBinding("getIexpenseLogin");
List<EmployeePojo> result = (List<EmployeePojo>) operationBinding.execute();
System.out.println("Result= " + result);
employeeDC.getEmployeeLogin(result); // Here the list is passed to the Employee DC class to create data controll.
ApplicationModule Containing Custom Procedure
public List getIexpenseLogin(String username,String password){
CallableStatement cs=null;
List<EmployeePojo> empList=new ArrayList<>();
try{
cs=getDBTransaction().createCallableStatement("begin xx_oie_mob_login.oie_mob_login(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?); end;",0);
cs.setString(1,username);
cs.setString(2, password);
cs.registerOutParameter(3, Types.NUMERIC);
cs.registerOutParameter(4, Types.VARCHAR);
cs.registerOutParameter(5, Types.VARCHAR);
cs.registerOutParameter(6, Types.NUMERIC);
cs.registerOutParameter(7, Types.VARCHAR);
cs.registerOutParameter(8, Types.NUMERIC);
cs.registerOutParameter(9, Types.VARCHAR);
cs.registerOutParameter(10, Types.NUMERIC);
cs.registerOutParameter(11, Types.VARCHAR);
cs.registerOutParameter(12, Types.NUMERIC);
cs.registerOutParameter(13, Types.BLOB);
cs.registerOutParameter(14, Types.VARCHAR);
cs.registerOutParameter(15, Types.VARCHAR);
cs.executeUpdate();
if(cs!=null)
{
EmployeePojo ePojo=new EmployeePojo();
ePojo.setEmployeeId(cs.getString(3));
ePojo.setEmployeeName(cs.getString(4));
ePojo.setEmployeeNumber(cs.getString(5));
ePojo.setManagerId(cs.getString(6));
ePojo.setManagerName(cs.getString(7));
ePojo.setJobId(cs.getString(8));
ePojo.setJobName(cs.getString(9));
ePojo.setOrgId(cs.getString(10));
ePojo.setOrgName(cs.getString(11));
ePojo.setImgId(cs.getString(12));
ePojo.setImage(cs.getBlob(13));
empList.add(ePojo);
}
return empList;
}catch(SQLException e){
throw new JboException(e);
}
}
EmployeeDC class used to create Data controll
public class EmployeeDC {
public EmployeeDC() {
super();
}
BindingContainer bindings = null;
private List<EmployeePojo> employee_data_controll=null;
private PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);
public void setEmployee_data_controll(List<EmployeePojo> employee_data_controll) {
List<EmployeePojo> oldEmployee_data_controll = this.employee_data_controll;
this.employee_data_controll = employee_data_controll;
propertyChangeSupport.firePropertyChange("employee_data_controll", oldEmployee_data_controll,
employee_data_controll);
}
public List<EmployeePojo> getEmployee_data_controll() {
return employee_data_controll;
}
public void setPropertyChangeSupport(PropertyChangeSupport propertyChangeSupport) {
PropertyChangeSupport oldPropertyChangeSupport = this.propertyChangeSupport;
this.propertyChangeSupport = propertyChangeSupport;
propertyChangeSupport.firePropertyChange("propertyChangeSupport", oldPropertyChangeSupport,
propertyChangeSupport);
}
public PropertyChangeSupport getPropertyChangeSupport() {
return propertyChangeSupport;
}
public void getEmployeeLogin(List<EmployeePojo> result) {
setEmployee_data_controll(result);
getEmployee_data_controll();
System.out.println("DataControl=>"+getEmployee_data_controll().get(0));
}
public void addPropertyChangeListener(PropertyChangeListener l) {
propertyChangeSupport.addPropertyChangeListener(l);
}
public void removePropertyChangeListener(PropertyChangeListener l) {
propertyChangeSupport.removePropertyChangeListener(l);
}
}
EmployeePojo Class
public class EmployeePojo {
private String employeeId;
private String employeeName;
private String employeeNumber;
private String managerId;
private String managerName;
private String jobId;
private String jobName;
private String orgId;
private String orgName;
private String imgId;
private Blob image;
private PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);
public void setPropertyChangeSupport(PropertyChangeSupport propertyChangeSupport) {
this.propertyChangeSupport = propertyChangeSupport;
}
public PropertyChangeSupport getPropertyChangeSupport() {
return propertyChangeSupport;
}
public void setEmployeeId(String employeeId) {
String oldEmployeeId = this.employeeId;
this.employeeId = employeeId;
propertyChangeSupport.firePropertyChange("employeeId", oldEmployeeId, employeeId);
}
public String getEmployeeId() {
return employeeId;
}
public void setEmployeeName(String employeeName) {
String oldEmployeeName = this.employeeName;
this.employeeName = employeeName;
propertyChangeSupport.firePropertyChange("employeeName", oldEmployeeName, employeeName);
}
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeNumber(String employeeNumber) {
String oldEmployeeNumber = this.employeeNumber;
this.employeeNumber = employeeNumber;
propertyChangeSupport.firePropertyChange("employeeNumber", oldEmployeeNumber, employeeNumber);
}
public String getEmployeeNumber() {
return employeeNumber;
}
public void setManagerId(String managerId) {
String oldManagerId = this.managerId;
this.managerId = managerId;
propertyChangeSupport.firePropertyChange("managerId", oldManagerId, managerId);
}
public String getManagerId() {
return managerId;
}
public void setManagerName(String managerName) {
String oldManagerName = this.managerName;
this.managerName = managerName;
propertyChangeSupport.firePropertyChange("managerName", oldManagerName, managerName);
}
public String getManagerName() {
return managerName;
}
public void setJobId(String jobId) {
String oldJobId = this.jobId;
this.jobId = jobId;
propertyChangeSupport.firePropertyChange("jobId", oldJobId, jobId);
}
public String getJobId() {
return jobId;
}
public void setJobName(String jobName) {
String oldJobName = this.jobName;
this.jobName = jobName;
propertyChangeSupport.firePropertyChange("jobName", oldJobName, jobName);
}
public String getJobName() {
return jobName;
}
public void setOrgId(String orgId) {
String oldOrgId = this.orgId;
this.orgId = orgId;
propertyChangeSupport.firePropertyChange("orgId", oldOrgId, orgId);
}
public String getOrgId() {
return orgId;
}
public void setOrgName(String orgName) {
String oldOrgName = this.orgName;
this.orgName = orgName;
propertyChangeSupport.firePropertyChange("orgName", oldOrgName, orgName);
}
public String getOrgName() {
return orgName;
}
public void setImgId(String imgId) {
String oldImgId = this.imgId;
this.imgId = imgId;
propertyChangeSupport.firePropertyChange("imgId", oldImgId, imgId);
}
public String getImgId() {
return imgId;
}
public void setImage(Blob image) {
Blob oldImage = this.image;
this.image = image;
propertyChangeSupport.firePropertyChange("image", oldImage, image);
}
public Blob getImage() {
return image;
}
public void addPropertyChangeListener(PropertyChangeListener l) {
propertyChangeSupport.addPropertyChangeListener(l);
}
public void removePropertyChangeListener(PropertyChangeListener l) {
propertyChangeSupport.removePropertyChangeListener(l);
}
}

HttpSession attribute getting removed abnormally after adding

*After I add a session attribute using
WebUtils.setSessionAttribute(request, VBWebConstants.SESSION_ORDER_BEAN,sellerDetails);
#RequestMapping(value="/minasidor/step1",method=RequestMethod.GET)
public ModelAndView step1(HttpServletRequest request,HttpSession session){
if(logger.isTraceEnabled())logger.trace("VbSellerController ::: step1 ::: start");
if(logger.isDebugEnabled())logger.debug("[Order Step1] [Start]");
ModelAndView mav=new ModelAndView("vz-new/mina-sidor/v-orderstep1");
LoginBean user = (LoginBean) WebUtils.getSessionAttribute(request, VBWebConstants.SESSION_USER);
mav.addObject("submenu",3);
if(!checkOrderLifeCycle()){
mav.addObject("orderNotAllowed", false);
return mav;
}
try{
String orderValue = "";
orderValue = InMemoryCache.getCaProperty(PropertyEnum.MIN_ORDER_VALUE.getDatabasekey());
int minimumOrderValue = CawebUtil.isInt(orderValue);
CpSellerDetails sellerDetails=vbOrderService.getStep1Data(user.getGrp_seller_id(),user.getCatalogue_id());
if(sellerDetails != null){
mav.addObject("productlist",sellerDetails.getSellerList());
mav.addObject("totalValue",sellerDetails.getTotalOrderValue());
mav.addObject("allowedfororder",sellerDetails.getTotalOrderValue() > minimumOrderValue);
// mav addobject add discount details Discount Object ArrayList
WebUtils.setSessionAttribute(request, VBWebConstants.SESSION_ORDER_STEP_COMPLETED,"step1");
WebUtils.setSessionAttribute(request, VBWebConstants.SESSION_ORDER_BEAN,sellerDetails);
}else{
mav.addObject("allowedfororder",false);
WebUtils.setSessionAttribute(request, VBWebConstants.SESSION_ORDER_STEP_COMPLETED,null);
}
}catch(DataNotFoundException e){
logger.trace("Exception in retrieving data for step1",e);
if(logger.isDebugEnabled())logger.debug("[Order Step1 Exception]",e);
}
if(logger.isTraceEnabled())logger.trace("VbSellerController ::: step1 ::: end");
if(logger.isDebugEnabled())logger.debug("[Order Step1] [end]");
return mav;
}
Within this step1 method the VBWebConstants.SESSION_ORDER_BEAN session attribute is getting removed instantly after the step1() method finishes executing where as the other session attributes remains the same.When i debug the below Http Listener class
public class MyHttpSessionListener implements HttpSessionListener,HttpSessionAttributeListener {
public static final Logger logger = Logger.getLogger(MyHttpSessionListener.class);
public void sessionCreated(HttpSessionEvent se) {
//String ipAddr = ((ServletRequestAttributes)RequestContextHolder.currentRequestAttributes()).getRequest().getRemoteAddr();
HttpSession session = se.getSession();
if(logger.isDebugEnabled()){
StringBuilder sbuilder = new StringBuilder();
sbuilder.append("\n").append("----------- Session Created -------------- ");
Enumeration<String> sessionAttrs = session.getAttributeNames();
while (sessionAttrs.hasMoreElements()) {
String name = sessionAttrs.nextElement();
sbuilder.append("\n").append(" session created ").append(name);
}
sbuilder.append("\n").append(" session created time "+ CawebUtil.getTimeStampInString(new Timestamp(session.getCreationTime())));
sbuilder.append("\n").append("---------------------------------------------------- ").append("\n");
logger.debug(sbuilder.toString());
}
}
public void sessionDestroyed(HttpSessionEvent se) {
HttpSession session = se.getSession();
if(logger.isDebugEnabled()){
try{
String ipAddr = ((ServletRequestAttributes)RequestContextHolder.currentRequestAttributes()).getRequest().getRemoteAddr();
logger.debug(" session destroyed " +ipAddr);
}catch (Exception e) {
}
}
}
public void attributeAdded(HttpSessionBindingEvent se) {
String ipAddr = ((ServletRequestAttributes)RequestContextHolder.currentRequestAttributes()).getRequest().getRemoteAddr();
HttpSession session = se.getSession();
if(logger.isDebugEnabled()){
StringBuilder sbuilder = new StringBuilder();
sbuilder.append("\n").append("----------- Attribute added -------------- from ").append(ipAddr);
sbuilder.append("\n").append(" session max inactive time "+ session.getMaxInactiveInterval());
sbuilder.append("\n").append(" session id "+ session.getId());
sbuilder.append("\n").append(" session attribute added "+ se.getName()).append(" = ").append(se.getValue());
sbuilder.append("\n").append(" session created time "+ CawebUtil.getTimeStampInString(new Timestamp(session.getCreationTime())));
}
}
public void attributeRemoved(HttpSessionBindingEvent se) {
if(logger.isDebugEnabled() ){
StringBuilder sbuilder = new StringBuilder();
sbuilder.append("\n").append("----------- Attribute removed -------------- from ");//.append(ipAddr);
sbuilder.append("\n").append(" session attribute removed "+ se.getName()).append(" = ").append(se.getValue());
}
}
public void attributeReplaced(HttpSessionBindingEvent se) {
if(logger.isDebugEnabled()){
StringBuilder sbuilder = new StringBuilder();
sbuilder.append("\n").append("----------- Attribute replaced -------------- from ");//.append(ipAddr);
sbuilder.append("\n").append(" session attribute "+ se.getName()).append(" = ").append(se.getValue());
}
}
}
I found that the session attribute is getting removed.Checked through the entire code I couldn't find what's the reason...???
Here is the CPSellerDetails class which i try to add to the session there are other 2 session attributes among which one is a string object and other is a bean.could it the size of the class that is the cause for session attribute being removed abnormally
public class CpSellerDetails implements Serializable{
/**
*
*/
private static final long serialVersionUID = -4627284179051380310L;
private List<SellerProduct> sellerList ;
private float totalOrderValue ;
private VbCpInfoBean cpinfoBean;
private Integer orderno;
private float invoiceAmount;
private Date orderedDate;
private ArrayList<DiscountVO> discounts;
private Address billingInfo;
public VbCpInfoBean getCpInfoBean() {
return cpinfoBean;
}
public void setCpInfoBean(VbCpInfoBean infoBean) {
this.cpinfoBean = infoBean;
}
public List<SellerProduct> getSellerList() {
return sellerList;
}
public void setSellerList(List<SellerProduct> sellerList) {
this.sellerList = sellerList;
}
public float getTotalOrderValue() {
return totalOrderValue;
}
public void setTotalOrderValue(float totalOrderValue) {
this.totalOrderValue = totalOrderValue;
}
public float getInvoiceAmount() {
return invoiceAmount;
}
public void setInvoiceAmount(float invoiceAmount) {
this.invoiceAmount = invoiceAmount;
}
public Integer getOrderno() {
return orderno;
}
public void setOrderno(Integer orderno) {
this.orderno = orderno;
}
public Date getOrderedDate() {
return orderedDate;
}
public void setOrderedDate(Date orderedDate) {
this.orderedDate = orderedDate;
}
public ArrayList<DiscountVO> getDiscounts() {
return discounts;
}
public void setDiscounts(ArrayList<DiscountVO> discounts) {
this.discounts = discounts;
}
public Address getBillingInfo() {
return billingInfo;
}
public void setBillingInfo(Address billingInfo) {
this.billingInfo = billingInfo;
}
}*

Resources