Mockito tests pass except one verify - jdbc

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.

Related

How to make Hibernate use setFixedCHAR instead of setString

Can I somehow modify the way Hibernate binds parameters to the query?
For example, I want hibernate to use OracleResultSet.setFixedChar() when executing on an string column, instead of rs.setString() when executing a JPA query via Spring data.
This is how I would do it without Hibernate:
try(PreparedStatement ps = con.executeQuery("...")) {
if(ps.isWrapped(OraclePreparedStatement.class) {
ps.unwrap(OraclePreparedStatement.class).setFixedCHAR(0, myStringField);
} else {
ps.setString(0, myStringField);
}
try(ResultSet rs = ps.getResultSet()) {
while(rs.next()) {
... do stuff ...
}
}
}
Repository method (Spring data JPA):
List<Object> findByMyStringField(String myStringField);
How can I influence how Hibernate binds my variable. With the above example setString is used always.
As background: the problem is that all our Legacy DB's use CHAR columns and not VARCHAR2, so we have to deal with whitespace and setFixedCHAR should do exactly what we would want.
Found a solution by implementing a SqlTypeDescriptor & Custom Dialect:
#Autowired
private DataSource source;
#Bean
public HibernateJpaVendorAdapter getHibernateJPAVendorAdapter() {
return new CustomHibernateJpaVendorAdaptor();
}
private static class CustomHibernateJpaVendorAdaptor extends HibernateJpaVendorAdapter {
#Override
protected Class<?> determineDatabaseDialectClass(Database database) {
// if HSQL is copied from Spring Sourcecode to keep everything the same
if (Database.HSQL.equals(database)) {
return CustomHsqlDialect.class;
}
try {
if (source.isWrapperFor(OracleDataSource.class)) {
return CustomOracleDialect.class;
}
} catch (SQLException e) {
}
return super.determineDatabaseDialectClass(database);
}
private class CustomHsqlDialect extends HSQLDialect {
public CustomHsqlDialect() {
registerColumnType(Types.BOOLEAN, "boolean");
registerHibernateType(Types.BOOLEAN, "boolean");
}
}
}
#NoArgsConstructor
public static class CustomOracleDialect extends Oracle12cDialect {
private static final OracleCharFix INSTANCE = new OracleCharFix();
#Override
protected SqlTypeDescriptor getSqlTypeDescriptorOverride(final int sqlCode) {
switch (sqlCode) {
case Types.VARCHAR:
return INSTANCE;
default:
return super.getSqlTypeDescriptorOverride(sqlCode);
}
}
}
#Slf4j
private static class OracleCharFix extends CharTypeDescriptor {
#Override
public <X> ValueBinder<X> getBinder(final JavaTypeDescriptor<X> javaTypeDescriptor) {
return new BasicBinder<>(javaTypeDescriptor, this) {
#Override
protected void doBind(PreparedStatement st, X value, int index, WrapperOptions options)
throws SQLException {
if (st.isWrapperFor(OraclePreparedStatement.class)) {
OraclePreparedStatement ops = st.unwrap(OraclePreparedStatement.class);
if (ops.getParameterMetaData().getParameterType(index) == Types.CHAR) {
ops.setFixedCHAR(index, javaTypeDescriptor.unwrap(value, String.class, options));
} else {
st.setString(index, javaTypeDescriptor.unwrap(value, String.class, options));
}
} else {
st.setString(index, javaTypeDescriptor.unwrap(value, String.class, options));
}
}
#Override
protected void doBind(CallableStatement st, X value, String name, WrapperOptions options)
throws SQLException {
//Is nolonger used by Hibernate in the current Version
st.setString(name, javaTypeDescriptor.unwrap(value, String.class, options));
}
private boolean checkIfCHARByName(ResultSetMetaData metadata, String name)
throws SQLException {
for (int i = 1; i <= metadata.getColumnCount(); i++) {
if (metadata.getColumnType(i) == Types.CHAR && Objects.equals(metadata.getColumnName(i), name)) {
return true;
}
}
return false;
}
};
}

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

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

jdbcTemplate.batchUpdate issue

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

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