HttpSession attribute getting removed abnormally after adding - spring

*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;
}
}*

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.

Spring JDBC insert into DB will not work

For some reason my jdbctemplate is not picking up the info in my application.properties file. I can only insert in my db when I make my own connection exposing my username and password in the file. Why isn't spring boot picking this up? Please help!
I am calling the addTaglocation mode while I am still reading tags from multiple RFID readers. Would this cause the issue? If so how do I solve it. Thanks in advance.
I start reading the tag from multiple rfid readers from a controller.
Full class where I am calling the create method (addTaglocation method):
public class TagInventory extends AlienClass1Reader implements
MessageListener, TagTableListener{
private final int MAX_THREAD = 50;
private Thread[] m_run_process = new Thread[MAX_THREAD];
private AlienReader[] m_inventory = new AlienReader[MAX_THREAD];
public boolean stopInventory = false;
ReaderProfileService rps;
VehicleService vs;
private boolean ThreadStop = true;
private int lastThreadId = -1;
private MessageListenerService service;
private TagTable tagTable = new TagTable();
private TagTableListener tagTableListener;
private static final Logger log =LogManager.getLogger(TagInventory.class);
#Autowired
TaglocationDAOJdbc taglocationDAOJdbc;
public TagInventory() throws AlienReaderException, IOException{
Start();
}
public void stopTag() throws AlienReaderException{
Stop();
}
private void Stop() throws AlienReaderException{
ThreadStop = true;
for (lastThreadId=0; lastThreadId < Reader.ipAddress.length;
lastThreadId++){
if(m_inventory[lastThreadId] != null){
m_inventory[lastThreadId].stopInventory = true;
service.stopService();
try{
Thread.sleep(200);
}catch(Exception e){
e.getMessage();
}
//m_inventory[lastThreadId].close();
m_inventory[lastThreadId].open();
m_inventory[lastThreadId].autoModeReset();
m_inventory[lastThreadId].setAutoMode(AlienClass1Reader.OFF);
m_inventory[lastThreadId].setNotifyMode(AlienClass1Reader.OFF);
m_inventory[lastThreadId].close();
}
}
}
private void Start() throws AlienReaderException, IOException{
ThreadStop = false;
service= new MessageListenerService(3900);
service.setMessageListener(this);
service.startService();
for (lastThreadId = 0; lastThreadId < Reader.ipAddress.length; lastThreadId++)
{
m_inventory[lastThreadId] = new AlienReader(Reader.ipAddress[lastThreadId], Reader.port, Reader.username[lastThreadId], Reader.password[lastThreadId]);
log.info("taginventory reader: "+ Reader.ipAddress[lastThreadId]+"Thread: "+lastThreadId);
m_run_process[lastThreadId] = new Thread(new StartInventoryThread(Reader.ipAddress[lastThreadId], Reader.port, Reader.username[lastThreadId], Reader.password[lastThreadId], m_inventory[lastThreadId]));
m_run_process[lastThreadId].start();
}
--lastThreadId;
try
{
Thread.sleep(1000);
}
catch (Exception ex)
{
ex.getMessage();
}
}
class StartInventoryThread implements Runnable{
private String ip;
private int port;
private String user;
private String pwd;
private AlienReader ar;
StartInventoryThread(String ip, int port, String user, String pwd, AlienReader ar){
this.ip=ip;
this.port=port;
this.user=user;
this.pwd=pwd;
this.ar=ar;
}
#Override
public void run() {
try {
while(!stopInventory){
startRead(ip,port,user,pwd);
}
} catch (AlienReaderException | InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
public void tagAdded(Tag tag) {
log.info("NEW TAG: " + tag.getTagID()+ " LAST SEEN DATE: "+ tag.getRenewTime());
}
#Override
public void tagRemoved(Tag tag) {
// TODO Auto-generated method stub
}
#Override
public void tagRenewed(Tag tag) {
// TODO Auto-generated method stub
}
#Override
public synchronized void messageReceived(Message msg) {
if(msg instanceof ErrorMessage){
// log.info("Notify error from " + msg.getReaderIPAddress());
}else if (msg.getTagCount() == 0){
log.info("No tags!");
}else{
//log.info("Message received from: "+msg.getReaderIPAddress());
Tag[] tagL=msg.getTagList();
//String[] tagLString=new String[tagL.length];
for (int i=0;i<msg.getTagCount(); i++){
Tag tag = msg.getTag(i);
//System.out.println("Tag ID: "+tag.getTagID()+ " Last Seen: "+tag.getRenewTime());
this.tagTable.addTag(tag);
// log.info("Tag ID: "+tag.getTagID()+ " Last Seen: "+tag.getRenewTime()+ " Receive Antenna: "+tag.getReceiveAntenna());
//System.out.println("Tag: "+tag+ " Last Seen: "+tag.getRenewTime());
}
}
//check readerprofile
try {
updateLocation(Reader.ipAddress[this.lastThreadId]);
this.tagTable.removeOldTags();
} catch (NoReaderInfoException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoVehicleException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void addTaglocation(Taglocation tl){
Taglocation newtagloca= new Taglocation(tl.getReadername(),tl.getRfidtag(),tl.getZone(), tl.getTaggingsource(), tl.getVineight(), tl.getZonedate());
taglocationDAOJdbc.addtaglocation(newtagloca);
log.info("ADDED TAGG INFO!");
}
public void updateLocation(String read) throws NoReaderInfoException, NoVehicleException{
//update location of vehicle when tag read by readers
log.info("IN UPDATE LOCATION with reader: "+read);
Tag[] temp;
temp=this.tagTable.getTagList();
for (int i = 0; i < temp.length; i++) {
log.info("get taglist");
Tag tag = temp[i];
String rfid=tag.getTagID();
Timestamp newDate=new Timestamp(Calendar.getInstance().getTime().getTime());
Taglocation tl=new Taglocation(read, rfid, read, "", "vineight", newDate);
addTaglocation(tl);
}
}
public void startRead(String ip, int port, String user, String password) throws AlienReaderException, InterruptedException, UnknownHostException{
String myIP=InetAddress.getLocalHost().getHostAddress();
System.out.println("ip"+ ip);
AlienReader ar= new AlienReader(ip, port, user, password);
ar.open();
log.info("Reader" + ar.getIPAddress());
ar.setNotifyAddress(myIP, 3900);
ar.setNotifyFormat(AlienClass1Reader.TEXT_FORMAT);
ar.setNotifyTrigger("TrueFalse");
ar.setNotifyMode(AlienClass1Reader.ON);
ar.autoModeReset();
ar.setAutoStopTimer(5000); // Read for 5 seconds
ar.setAutoMode(AlienClass1Reader.ON);
tagTable.setTagTableListener(tagTableListener);
tagTable.setPersistTime(5000);
//tagTable.setPersistTime(1800000);
ar.close();
long runTime = 10000; // milliseconds
long startTime = System.currentTimeMillis();
do {
Thread.sleep(1000);
} while(service.isRunning()
&& (System.currentTimeMillis()-startTime) < runTime);
// Reconnect to the reader and turn off AutoMode and TagStreamMode.
log.info("\nResetting Reader");
ar.open();
ar.autoModeReset();
ar.setNotifyMode(AlienClass1Reader.OFF);
ar.close();
}
}
(UPDATED)
Application.properties file:
spring.datasource.url=jdbc:mysql://localhost:3306/DB
spring.datasource.username=
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
(UPDATED)
taglocationJDBCTemplate file
#Repository
public class TaglocationJDBCTemplate implements TaglocationDAO {
#Autowired
JdbcTemplate jdbcTemplate;
public void create(Taglocation tl){
KeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(new PreparedStatementCreator(){
public PreparedStatement createPreparedStatement(final Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement("INSERT INTO TAGLOCATION (READERNAME, RFIDTAG, TAGGINGSOURCE, ZONE, VINEIGHT, ZONEDATE) VALUES (?,?,?,?,?,?)",
Statement.RETURN_GENERATED_KEYS);
ps.setString(1, tl.getReadername());
ps.setString(2,tl.getRfidtag());
ps.setString(3, tl.getTaggingsource());
ps.setString(4, tl.getZone());
ps.setString(5, tl.getVineight());
ps.setTimestamp(6, new Timestamp(System.currentTimeMillis()));
return ps;
}
}, keyHolder);
return (Integer) keyHolder.getKey();
}
controller file:
#RestController
public class TagInventoryController {
#Autowired
TagService tagService;
#RequestMapping("/runTasks")
public String tagRead(){
tagService.startTagRead();
return "Readers are activated.";
}
}

In spring accessing service class in controller and storing response in embedded class

I have dao class is below
#Override
public List<PersonDTO> getAllEmployees(long companyId) {
Query query = getCurrentSession().getNamedQuery(User.class.getName() + ".getAllEmployee");
query.setParameter("companyId", companyId);
query.setResultTransformer(Transformers.aliasToBean(PersonDTO.class));
return query.list();
}
I have services class is below
public List<PersonDTO> getAllEmployees(long companyId) {
try {
return userDAO.getAllEmployees(companyId);
} catch (Exception e) {
throw new ApplicationException(e);
}
}
I have Embedded class
public class EntityListResponce implements Serializable {
private static final long serialVersionUID = 1L;
private List<PersonDTO> personDTO;
public List<PersonDTO> getPersonDTO() {
return PersonDTO;
}
public void setPersonDTO(List<PersonDTO> employeesList) {
this.PersonDTO = employeesList;
}
}
I written a controller like below.
#RequestMapping("/getAllEntitys.htm")
public void getAllEntities(HttpServletRequest request, HttpServletResponse response) {
try {
ZSession zSession = getZSession(request);
Long companyId = zSession.getCompanyId();
EntityListResponce entityListResponce = new EntityListResponce();
List<PersonDTO> employeesList = personService.getAllEmployees(companyId);
WebUtils.writeJSONResponse(response,
getSerializer(request, EXCLUDE_FILES).deepSerialize(entityListResponce));
} catch (Exception e) {
writeException(request, response, e);
}
}
}
Is it proper way to collect all the employeesList like this
List<PersonDTO> employeesList = personService.getAllEmployees(companyId);
I am getting not getting all the employeesList in response.

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;
}
}

Dynamic Routing key on RabbitListener Annotation

I need to create a queue linked to Direct Exchange for every user who has logged in to the application. The basement routing will be 'user_' + userId.
That is, every time I receive a message through the user management queue that a user is logged on. Instantiate a bean with scope 'prototype' that contains a method annotated with RabbitListener to declare its queue. To this bean, I passed the userId to be able to configure the name of the queue and routingKey. But I can not access this instance variable in the Spel expression due to a circular reference error.
Here I put the bean with which declares the queue:
#Component("usersHandler")
#Scope(value = "prototype")
public class UsersHandler {
private static Logger logger = LoggerFactory.getLogger(UsersHandler.class);
private Long userId;
public UsersHandler(Long userId) {
this.userId = userId;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
#RabbitListener(bindings
= #QueueBinding(
value = #Queue(
value = "#{'queue_'.concat(usersHandler.userId)}",
durable = "false",
autoDelete = "true",
arguments = {
#Argument(
name = "x-message-ttl",
value = "#{rabbitCustomProperties.directExchange.queueArguments['x-message-ttl']}",
type = "java.lang.Integer"
)
,
#Argument(
name = "x-expires",
value = "#{rabbitCustomProperties.directExchange.queueArguments['x-expires']}",
type = "java.lang.Integer"
)
,
#Argument(
name = "x-dead-letter-exchange",
value = "#{rabbitCustomProperties.directExchange.queueArguments['x-dead-letter-exchange']}",
type = "java.lang.String"
)
}
),
exchange = #Exchange(
value = "#{rabbitCustomProperties.directExchange.name}",
type = ExchangeTypes.DIRECT,
durable = "#{rabbitCustomProperties.directExchange.durable}",
autoDelete = "#{rabbitCustomProperties.directExchange.autoDelete}",
arguments = {
#Argument(
name = "alternate-exchange",
value = "#{rabbitCustomProperties.directExchange.arguments['alternate-exchange']}",
type = "java.lang.String"
)
}
),
key = "#{'user_'.concat(usersHandler.userId)}")
)
public void handleMessage(#Payload Notification notification) {
logger.info("Notification Received : " + notification);
}
}
This is the other bean in charge of creating as many UserHandler as users have logged in:
#Component("adminHandler")
public class AdminHandler implements UsersManadgementVisitor {
#Autowired
private ApplicationContext appCtx;
private Map<Long, UsersHandler> handlers = new HashMap<Long, UsersHandler>();
private static Logger logger = LoggerFactory.getLogger(AdminHandler.class);
#RabbitListener(queues="#{rabbitCustomProperties.adminExchange.queues['users'].name}")
public void handleMessage(#Payload UsersManadgementMessage message) {
logger.info("Message -> " + message);
message.getType().accept(this, message.getId());
}
#Override
public void visitUserConnected(Long idUser) {
logger.info("Declare new queue for user: " + idUser );
UsersHandler userHandler = appCtx.getBean(UsersHandler.class, idUser);
handlers.put(idUser, userHandler);
}
#Override
public void visitUserDisconnected(Long idUser) {
logger.info("Remove queue for user: " + idUser );
handlers.remove(idUser);
}
}
My question is this:
How can I make the variable userId available in the evaluation context of the SpEL expressions?
You could use a ThreadLocal and the T operator...
#SpringBootApplication
public class So43717710Application {
public static void main(String[] args) throws Exception {
ConfigurableApplicationContext context = SpringApplication.run(So43717710Application.class, args);
UserHolder.setUser("someUser");
context.getBean(Listener.class);
UserHolder.clearUser();
context.getBean(RabbitTemplate.class).convertAndSend("foo", "user_someUser", "bar");
Thread.sleep(5000);
context.close();
}
#Bean
#Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public Listener listener() {
return new Listener();
}
public static class Listener {
#RabbitListener(bindings = #QueueBinding(value = #Queue("#{'queue_' + T(com.example.UserHolder).getUser()}"),
exchange = #Exchange(value = "foo"),
key = "#{'user_' + T(com.example.UserHolder).getUser()}"))
public void listen(String in) {
System.out.println(in);
}
}
}
public class UserHolder {
private static final ThreadLocal<String> user = new ThreadLocal<String>();
public static void setUser(String userId) {
user.set(userId);
}
public static String getUser() {
return user.get();
}
public static void clearUser() {
user.remove();
}
}
If the ThreadLocal is in a #Bean you can use a bean reference...
#SpringBootApplication
public class So43717710Application {
public static void main(String[] args) throws Exception {
ConfigurableApplicationContext context = SpringApplication.run(So43717710Application.class, args);
UserHolder.setUser("someUser");
context.getBean(Listener.class);
UserHolder.clearUser();
context.getBean(RabbitTemplate.class).convertAndSend("foo", "user_someUser", "bar");
Thread.sleep(5000);
context.close();
}
#Bean
public UserHolder holder() {
return new UserHolder();
}
#Bean
#Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public Listener listener() {
return new Listener();
}
public static class Listener {
#RabbitListener(bindings = #QueueBinding(value = #Queue("#{'queue_' + #holder.user}"),
exchange = #Exchange(value = "foo"),
key = "#{'user_' + #holder.user}"))
public void listen(String in) {
System.out.println(in);
}
}
}

Resources