I am trying to use cron job for executing some work once a day. I am using automatic scaling. Using cron job i am sending emails once a day. I have 2 conditions:
Whenever i set time once a day for example every day 18:00 then cron job run successfully but its only executing 3, 4 lines of CronJob implementation class.
In logger I am getting only 4 lines are executing like this:-
whenever i set time as every 2 minutes or every 5 minutes then cron job run successfully and cron job implementation class executed successfully means its send email successfully.
Why is the first condition not sending email?
Is there may be app is at that time idle and that's why it's not executing?
Any help?
Cron.xml :-
<?xml version="1.0" encoding="UTF-8"?>
<cron>
<url>/slick_erp/cronCustomerService</url>
<description>Implemented for due services of customer.</description>
<schedule>every day 11:30</schedule>
</cron>
</cronentries>
Web.xml:-
<servlet>
<servlet-name>CustomerServiceCronJobImpl</servlet-name>
<servlet-class>com.slicktechnologies.server.cronjobimpl.CustomerServiceCronJobImpl</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CustomerServiceCronJobImpl</servlet-name>
<url-pattern>/slick_erp/cronCustomerService</url-pattern>
</servlet-mapping>
My cronjob implementation class :-
public class CustomerServiceCronJobImpl extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = -6268357776825855510L;
private SimpleDateFormat fmt = new SimpleDateFormat("dd-MMM-yyyy");
private SimpleDateFormat fmt1 = new SimpleDateFormat("dd/MM/yyyy");
Logger logger = Logger.getLogger("NameOfYourLogger");
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
servicecontactlist();
}
private void servicecontactlist() {
fmt.setTimeZone(TimeZone.getTimeZone("IST"));
fmt1.setTimeZone(TimeZone.getTimeZone("IST"));
Email cronEmail = new Email();
Date today=DateUtility.getDateWithTimeZone("IST", new Date());
/**
* Adding 1 day extra to date
*/
logger.log(Level.SEVERE,"Date Before Adding One Day"+today);
DateFormat dateFormat=new SimpleDateFormat("dd/MM/yyyy");
Calendar cal=Calendar.getInstance();
cal.setTime(today);
cal.add(Calendar.DATE, 0);
Date dateForFilter=null;
try {
dateForFilter=dateFormat.parse(dateFormat.format(cal.getTime()));
cal.set(Calendar.HOUR_OF_DAY,23);
cal.set(Calendar.MINUTE,59);
cal.set(Calendar.SECOND,59);
cal.set(Calendar.MILLISECOND,999);
dateForFilter=cal.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
logger.log(Level.SEVERE,"Date After Adding One Date"+dateForFilter);
/*************************************End*********************************/
try{
logger.log(Level.SEVERE,"In service ContactList");
logger.log(Level.SEVERE,"Date After Adding One Date=="+dateForFilter);
logger.log(Level.SEVERE," 1 ");
/********************************Adding status in the list ***********************/
logger.log(Level.SEVERE," 2 ");
ArrayList<String> obj = new ArrayList<String>();
obj.add("Scheduled");
obj.add("Pending");
obj.add("Rescheduled");
logger.log(Level.SEVERE," 3 ");
/******************************Converting todayDate to String format*****************/
logger.log(Level.SEVERE," 4 ");
Date todaysDate = new Date();
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
logger.log(Level.SEVERE," 5 ");
String todayDateString = df.format(todaysDate);
logger.log(Level.SEVERE," 6 ");
System.out.println("String in dd/MM/yyyy format is: " + todayDateString);
logger.log(Level.SEVERE," 7 ");
/********************************Adding Companies in the list ***********************/
logger.log(Level.SEVERE," 8 ");
List<Company> compEntity = ofy().load().type(Company.class).list();
logger.log(Level.SEVERE," 9 ");
if(compEntity.size()>0){
logger.log(Level.SEVERE,"If compEntity size > 0");
logger.log(Level.SEVERE,"Size of compEntity"+compEntity.size());
for(int i=0;i<compEntity.size();i++){
Company c=compEntity.get(i);
logger.log(Level.SEVERE,"In the for loop");
logger.log(Level.SEVERE,"Company Name="+c);
logger.log(Level.SEVERE,"The value of i is:" +i);
logger.log(Level.SEVERE,"Date After Adding One Date"+dateForFilter);
/********************************Checking prosname & prosconfig for each company ***********************/
ProcessName prosName = ofy().load().type(ProcessName.class).filter("processName","CronJob").filter("status",true).filter("companyId", compEntity.get(i).getCompanyId()).first().now();
ProcessConfiguration prosconfig = ofy().load().type(ProcessConfiguration.class).filter("processList.processName", "CronJob").filter("processList.processType", "ServiceDailyMail").filter("processList.status",true).filter("companyId", compEntity.get(i).getCompanyId()).first().now();
logger.log(Level.SEVERE,"after 3 filters for ProcessConfigurations");
System.out.println("after 3 filters for ProcessConfigurations");
if(prosName!=null){
logger.log(Level.SEVERE,"In the prossName");
if(prosconfig!=null){
logger.log(Level.SEVERE,"In the ProsConfifg !=null ");
/********************************Reading services from Service entity ***********************/
List<Service> serEntity = ofy().load().type(Service.class).filter("companyId",compEntity.get(i).getCompanyId()).filter("serviceDate <=",dateForFilter).filter("status IN",obj).list();
logger.log(Level.SEVERE,"Today date Is:"+dateForFilter);
logger.log(Level.SEVERE,"service entity size:"+serEntity.size());
// email id is added to emailList
ArrayList<String> toEmailList=new ArrayList<String>();
toEmailList.add(compEntity.get(i).getPocEmail());
String mailTitl = "Services Due As On Date";
if(serEntity.size()>0){
ArrayList<String> tbl_header = new ArrayList<String>();
tbl_header.add("Branch");
tbl_header.add("Customer Id");
tbl_header.add("Customer Name");
tbl_header.add("Customer Contact No");
tbl_header.add("Crontact Id");
tbl_header.add("Service Id");
tbl_header.add("Service Date");
tbl_header.add("Service Engineer");
tbl_header.add("Product Name");
tbl_header.add("Status");
tbl_header.add("Ageing");
/********************************Sorting table with Branch & Service Date ***********************/
Comparator<Service> serviceDateComparator2 = new Comparator<Service>() {
public int compare(Service s1, Service s2) {
Date date1 = s1.getServiceDate();
Date date2 = s2.getServiceDate();
//ascending order
return date1.compareTo(date2);
}
};
Collections.sort(serEntity, serviceDateComparator2);
Comparator<Service> serviceDateComparator = new Comparator<Service>() {
public int compare(Service s1, Service s2) {
String branch1 = s1.getBranch();
String branch2 = s2.getBranch();
//ascending order
return branch1.compareTo(branch2);
}
};
Collections.sort(serEntity, serviceDateComparator);
/********************************Getting serviceEntity data and adding in the tbl1 List ***********************/
ArrayList<String> tbl1=new ArrayList<String>();
for(int j=0;j<serEntity.size();j++){
tbl1.add(serEntity.get(j).getBranch()+"");
tbl1.add(serEntity.get(j).getPersonInfo().getCount()+"");
tbl1.add(serEntity.get(j).getPersonInfo().getFullName()+"");
tbl1.add(serEntity.get(j).getPersonInfo().getCellNumber()+"");
tbl1.add(serEntity.get(j).getContractCount()+"");
tbl1.add(serEntity.get(j).getCount()+"");
tbl1.add(fmt.format(serEntity.get(j).getServiceDate()) +"");
/**************** for getting ageing for each service******/
String StringServiceDate = fmt1.format(serEntity.get(j).getServiceDate());
// String StringServiceDate = df.format(serviceDate);
Date d1 = null;
Date d2 = null;
d1 = df.parse(StringServiceDate);
d2 = df.parse(todayDateString);
long diff = d2.getTime() - d1.getTime();
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.println("Ageing:"+diffDays);
logger.log(Level.SEVERE,"Ageing:"+diffDays);
tbl1.add(serEntity.get(j).getEmployee()+"");
tbl1.add(serEntity.get(j).getProduct().getProductName()+"");
tbl1.add(serEntity.get(j).getStatus()+"");
tbl1.add(diffDays +"");
}
logger.log(Level.SEVERE,"In the ProsConfig !=null 3 ");
/********************************Calling cronsendEmail Method ***********************/
// Email e=new Email();
try {
System.out.println("Before send mail method");
logger.log(Level.SEVERE,"Before send method call to send mail ");
cronEmail.cronSendEmail(toEmailList, "Services Due As On Date"+" "+ todayDateString, mailTitl +" "+ todayDateString, c, tbl_header, tbl1, null, null, null, null);
logger.log(Level.SEVERE,"After send mail method ");
//+" "+
} catch (IOException e1) {
logger.log(Level.SEVERE,"In the catch block ");
e1.printStackTrace();
}
}
else{ // else block for if(serviceEntity.size()>0){
System.out.println("Sorry no services found for this company");
logger.log(Level.SEVERE,"Sorry no services found for this company");
//
mailTitl = "No Services Found Due";
cronEmail.cronSendEmail(toEmailList, "Services Due As On Date"+" "+ todayDateString, mailTitl , c, null, null, null, null, null, null);
}
}
else{ //else block for prosconfig
logger.log(Level.SEVERE,"ProcessConfiguration is null");
System.out.println("ProcessConfiguration is null");
}
}else{ //else block for pross!=null
logger.log(Level.SEVERE,"Cron job status is Inactive");
System.out.println("Cron job status is Inactive");
}
} //end of for loop
}
else{ //else block for if(compEntity.size()>0)
logger.log(Level.SEVERE,"No Company found from cron job completed");
System.out.println("No Company found from cron job completed");
}
}catch(Exception e2){
e2.printStackTrace();
}
}
}
Related
In my website, I can select a date range and list all the transactions within the date range. My test case is to verify whether listed transactions dates are within the selected date range .
This is my code. I get all the transaction dates into a LinkedList. Comp_Dates method will compare the actual date is within the ‘From’ and ‘To’ dates.
The problem is this code will always return True. I have changed the FromDate and ToDate to test the false scenario, But still code will return True.
Can you please help? What’s the problem in this code?
//Set From Date
driver.findElement(By.id("ctl00_ContentPlaceHolderMain_container_container_Block_172_tabPanelMyAccounts_dtDateFrom_txtDate")).sendKeys(Keys.chord(Keys.CONTROL, "a"),"01/03/2016");
//Set To date
driver.findElement(By.id("ctl00_ContentPlaceHolderMain_container_container_Block_172_tabPanelMyAccounts_dtDateTo_txtDate")).sendKeys(Keys.chord(Keys.CONTROL, "a"),"30/04/2016");
driver.findElement(By.id("ctl00_ContentPlaceHolderMain_container_container_Block_172_tabPanelMyAccounts_btnList")).click();
List<WebElement> Date =
driver.findElements(By.xpath(".//* [#id='ctl00_ContentPlaceHolderMain_container_container_Block_172_tabPanelMyAccounts_stxOutstandingTransactions_gvOSTransactions']/tbody/tr[*]/td[1]"));
List<String> Dates = new LinkedList<String>();
for(int i=0;i<Date.size();i++)
{
Dates.add(Date.get(i).getText());
System.out.println(Dates);
}
boolean result = comp_Dates(Dates);
if (result=true)
{
System.out.println(result + ", Address are within the range");
}
else
{
System.out.println(result + ", Addresses are not within the range. Test Case Failed");
}
}
private static boolean comp_Dates(List<String> Dates) {
try
{
SimpleDateFormat fmt = new SimpleDateFormat("dd/MM/yyyy");
//Date date = fmt.parse("2013-05-06");
String FromDate= "01/05/2016";
String ToDate= "30/06/2016";
java.util.Date Fdate =fmt.parse(FromDate);
java.util.Date Tdate =fmt.parse(ToDate);
for(String e : Dates)
{
java.util.Date ActualDate = fmt.parse(e);
if (ActualDate.compareTo(Fdate)>=0 & ActualDate.compareTo(Tdate)<=0 );
{
return true;
}
}
}
catch (Exception ex ){
System.out.println(ex);
}
return false;
}
}
Transactions dates in Linked list is [18/04/2016, 14/04/2016, 13/04/2016]
I have specified dates as below in the code.
String FromDate= "01/05/2016";
String ToDate= "30/06/2016";
When compare these dates, code should return false as dates doesn’t fall on within From and To dates. But it returns True. What am I doing wrong here?
Thanks
When you are returning true, it will exit the function whenever it founds a date in the range. Thus it would not check for all dates in the list.
If you want to check for all dates, proper comp_Dates method could be:
//Set From Date
driver.findElement(By.id("ctl00_ContentPlaceHolderMain_container_container_Block_172_tabPanelMyAccounts_dtDateFrom_txtDate")).sendKeys(Keys.chord(Keys.CONTROL, "a"), "01/03/2016");
//Set To date
driver.findElement(By.id("ctl00_ContentPlaceHolderMain_container_container_Block_172_tabPanelMyAccounts_dtDateTo_txtDate")).sendKeys(Keys.chord(Keys.CONTROL, "a"), "30/04/2016");
driver.findElement(By.id("ctl00_ContentPlaceHolderMain_container_container_Block_172_tabPanelMyAccounts_btnList")).click();
List<WebElement> Date =
driver.findElements(By.xpath(".//* [#id='ctl00_ContentPlaceHolderMain_container_container_Block_172_tabPanelMyAccounts_stxOutstandingTransactions_gvOSTransactions']/tbody/tr[*]/td[1]"));
for (int i = 0; i < Date.size(); i++) {
String date = Date.get(i).getText();
boolean result = comp_Dates(date);
if (result) {
System.out.println(result + ", Address are within the range");
} else {
System.out.println(result + ", Addresses are not within the range. Test Case Failed");
}
}
private static boolean comp_Dates(String date) {
try {
SimpleDateFormat fmt = new SimpleDateFormat("dd/MM/yyyy");
String FromDate = "01/05/2016";
String ToDate = "30/06/2016";
java.util.Date Fdate = fmt.parse(FromDate);
java.util.Date Tdate = fmt.parse(ToDate);
java.util.Date ActualDate = fmt.parse(date);
if (ActualDate.compareTo(Fdate) >= 0 && ActualDate.compareTo(Tdate) <= 0) {
return true;
}
} catch (Exception ex) {
System.out.println(ex);
}
return false;
}
N.B: There are many typos in your code. You should fix these.
I'm not sure how the start and end date work with the whole find appointments. I am getting all the rooms for a public group, then getting the rooms for the group, then getting the appointments within a date range.
But the ranges act weird, I know there are appointments on 12-19 to 12-16, but if I set the start date range to 2013-10-10 and the end date to 2013-12-28, I get nothing.
If I set the end date to 2014-01-28, I get tons of stuff that is in the range previously mentioned. Why is that?
ExchangeService service = new ExchangeService();
ExchangeCredentials credentials = new WebCredentials( "username", "pw");
service.setCredentials( credentials );
service.setUrl( new URI("my mail url") );
Folder inbox = Folder.bind(service, WellKnownFolderName.Inbox);
System.out.println("messages: " + inbox.getTotalCount());
CalendarFolder cf = CalendarFolder.bind(service, WellKnownFolderName.Calendar);
//Get all new appts?
java.text.SimpleDateFormat formatter= new java.text.SimpleDateFormat("YYYY-mm-dd");
Date startDate1 = formatter.parse("2013-11-25");
Date endDate1 = formatter.parse("2014-01-28 ");
EmailAddressCollection myRoomLists = service.getRoomLists();
for (EmailAddress item : myRoomLists)
{
System.out.println("Room Email========"+ item.toString());
NameResolutionCollection nameResolutions = service.resolveName(
item.getName(),
ResolveNameSearchLocation.DirectoryOnly,
true);
for (NameResolution nameResolution : nameResolutions)
{
ExpandGroupResults groupResults;
//System.out.println(nameResolution.getMailbox().getAddress());
try {
groupResults = service.expandGroup(nameResolution.getMailbox().getAddress());
} catch (microsoft.exchange.webservices.data.ServiceResponseException e){
groupResults=null;
System.out.println("NO INFO FOR "+nameResolution.getMailbox().getAddress());
}
if (groupResults!=null){
for (EmailAddress member : groupResults.getMembers())
{
if (member.getAddress().indexOf("rm.Cary")>-1){
System.out.println(member.getName() + " <" + member.getAddress() + ">");
FolderId folderid = new FolderId(WellKnownFolderName.Calendar, new Mailbox(member.getAddress()));
try {
FindItemsResults<Appointment> aps = service.findAppointments(folderid, new CalendarView(startDate1,endDate1));
for (Item items : aps.getItems())
{
Appointment appt = (Appointment)items;
System.out.println("SUBJECT===== " + appt.getSubject());
System.out.println("Location======== " + appt.getLocation());
System.out.println("Start Time========" + appt.getStart());
System.out.println("End Time========"+appt.getEnd());
System.out.println("Email Address========"+ appt.getOrganizer().getAddress());
System.out.println("Last Modified Time========"+appt.getLastModifiedTime());
System.out.println("Start time========"+appt.getStart());
System.out.println("End Time========"+appt.getEnd());
System.out.println("Is recurring========"+appt.getIsRecurring());
System.out.println("Duration========"+appt.getDuration().toString());
System.out.println("Organizer========"+appt.getOrganizer());
System.out.println("Required Attendees========"+appt.getRequiredAttendees().getCount());
System.out.println("Optional Attendees========"+appt.getOptionalAttendees().getCount());
System.out.println("");
}
} catch (microsoft.exchange.webservices.data.ServiceResponseException e){
System.out.println(e.getMessage());
}
}
}
}
}
}
System.out.println("End");
Change it to:
java.text.SimpleDateFormat formatter= new java.text.SimpleDateFormat("yyyy-MM-dd");
I have questions on how to use the scheduler properly.
I'm running a scheduler that trigger a job that sends list of emails at 10:00 am on working days.
The scheduler will trigger the job every 1 minute. However, the execution time for sending an email will take around 5 seconds.
Therefore, if I have 20 emails to send out for a day, it will take 20x5sec = 100 sec.
The scheduler will trigger after 1 minute, before the 20 emails being sent out completely.
Therefore, some emails will be left unsent.
Please kindly advise me on how do I send out the email completely before the next trigger time ?
Below is my sample code.
//CalendarReminder.java
// Job 1 & Group 1
JobDetail job = new JobDetail();
job.setName("Job1");
job.setJobClass(SendEmailJob.class);
job.setGroup("group1");
//example of adding an excluded day of the week - This excludes sundays from job
//firing schedule
WeeklyCalendar weeklyOff = new WeeklyCalendar();
weeklyOff.setDayExcluded(Calendar.SUNDAY, true);
// Trigger 1
//configure the scheduler time
SimpleTrigger trigger = new SimpleTrigger();
trigger.setStartTime(new Date(System.currentTimeMillis() + 1000));
trigger.setRepeatCount(SimpleTrigger.REPEAT_INDEFINITELY);
trigger.setRepeatInterval(60000); // Trigger every 1 min
trigger.setGroup("group1");
trigger.setName("trigger1");
try{
//schedule the job
scheduler = new StdSchedulerFactory().getScheduler();
scheduler.addCalendar("weeklyOff", weeklyOff, false, true);
scheduler.start();
scheduler.scheduleJob(job, trigger);
}catch(Exception ex){
}
-----------------------------------------------------------------------------
//SendEmailJob.java
try {
//getting database connection to MySQL server
dbCon = DriverManager. getConnection(dbURL, username, password);
//getting PreparedStatment to execute query
stmt = dbCon.prepareStatement(query);
//Resultset returned by query
rs = stmt.executeQuery(query);
while(rs.next()){
Str_Company = rs.getString("erscheduledemail.company");
Str_Dept = rs.getString("erscheduledemail.dept");
Str_EventType = rs.getString("erscheduledemail.eventtype");
Str_OneTimeDate = rs.getString("erscheduledemail.onetimedate");
Str_TimeSend = rs.getString("erscheduledemail.timesend");
Str_EmailFrom = rs.getString("erscheduledemail.emailfrom");
Str_EmailTo = rs.getString("erscheduledemail.emailto");
Str_EmailCCTo = rs.getString("erscheduledemail.emailccto");
Str_EmailSubject = rs.getString("erscheduledemail.emailsubject");
Str_EmailMessage = rs.getString("erscheduledemail.emailmessage");
Str_DeliveryStatus = rs.getString("erscheduledemail.deliverystatus");
Str_ActiveStatus = rs.getString("erscheduledemail.activestatus");
// Retrieve Scheduled Records Date yyyy-mm-dd & Time hh:mm:ss
Int_Year = Integer.parseInt(Str_OneTimeDate.substring(0, 4));
Int_Month = Integer.parseInt(Str_OneTimeDate.substring(5, 7));
Int_Day = Integer.parseInt(Str_OneTimeDate.substring(8,10));
Int_Hour = Integer.parseInt(Str_TimeSend.substring(0, 2));
Int_Min = Integer.parseInt(Str_TimeSend.substring(3, 5));
Int_Sec = Integer.parseInt(Str_TimeSend.substring(6, 8));
// Retrieve Computer System Date & Time
Calendar SysCalen = Calendar.getInstance();
int sys_calYear = SysCalen.get(Calendar.YEAR);
int sys_calMonth = SysCalen.get(Calendar.MONTH) + 1;
int sys_calDay = SysCalen.get(Calendar.DAY_OF_MONTH);
int sys_calHour = SysCalen.get(Calendar.HOUR_OF_DAY);
int sys_calMinute = SysCalen.get(Calendar.MINUTE);
int sys_calSecond = SysCalen.get(Calendar.SECOND);
// If the time match at 10:00 am
if(sys_calYear == Int_Year && sys_calMonth == Int_Month && sys_calDay == Int_Day &&
sys_calHour == Int_Hour && sys_calMinute == Int_Min /*&& sys_calSecond == Int_Sec*/){
System.out.println( " The time now" + String.valueOf(sys_calHour) + ":" +
String.valueOf(sys_calMinute) + ":" + String.valueOf(sys_calSecond));
System.out.println( " company: " +Str_Company);
SendingEmail(Str_EmailFrom,Str_EmailTo,Str_EmailCCTo, Str_EmailSubject, Str_
EmailMessage);
// Update deliverystatus to Yes and ActiveStatus to No
stm = dbCon.createStatement();
sql = "UPDATE erscheduledemail SET deliverystatus = 'Y', activestatus = 'N' "
+
"WHERE company = '"+Str_Company+"' and dept = '"+Str_Dept+"' and onetimedate =
'"+Str_OneTimeDate+"' and eventtype = '"+Str_EventType+"' ";
//Execute INSERT SQL Statement
stm.executeUpdate(sql) ;
}
}
dbCon.close();
} catch (SQLException ex) {
//System.out.println("SQL Exception thrown :" + ex);
System.out.println("SQL Exception thrown :" + ex);
}
Thanks & Regards,
Goshen
I have a part inside my program where the user logs into have access to the application, when the user logs in I have a time stamp being taken and stored into an ArrayList. When the user logs out I have another time stamp taken for when they logged out. I have been trying to subtract the 2 times from each other, but it is not allowing me to. They are stored in a String ArrayList, I am aware you can't subtract String, so I have tried converting to double, int, date, etc... None of it works for me. My question is that I would like the difference between the two times. I am also aware that there are other question similar to this on SO, but none specific to this exact question, that is why I posted it. I am not trying to post a duplicate.
Code:
loginButton.addActionListener(
new ActionListener()
{
//method for events that will be performed when 'loginButton' is pressed
public void actionPerformed(ActionEvent e)
{
try
{
//gets texts from specified text fields and assigns to instance variable
String userNameFromLogin = userNameTextBox.getText().trim();
String password = passwordTextBox.getText().trim();
//instance variable and object that holds currrent time when logged in
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm");
Date date = new Date();
String loginTime = dateFormat.format(date);
//sql statement that check if username and password exist
String sql5 = "SELECT User_name,Password FROM Employee_Table WHERE User_name = '" + userNameFromLogin + "' and Password = '" + password + "'";
//execute query, assigning all records in db to 'rs5'
rs5 = st.executeQuery(sql5);
//instance variables
int count = 0;
//loops until reaches end up 'rs5'
while(rs5.next())
{
count++;
}
//statement and actions if 'userName' and 'password' match
if(count == 1)
{
//sets 'welcomeFrame' to true
welcomeFrame.setVisible(true);
//sets 'loginFrame' to false
loginFrame.setVisible(false);
//sets text fields to blank
userNameTextBox.setText("");
passwordTextBox.setText("");
//adds 'userNameFromLogin' to array
loginArray.add(userNameFromLogin);
//adds 'loginTime' to array
loginArray.add(loginTime);
//sets label to current username logged in
userNameLabel.setText("logged in as: " + userNameFromLogin);
}
//statement and actions if 'userName' and 'password' do not match
else
{
JOptionPane.showMessageDialog(null, "Username or password incorrect!");
userNameTextBox.setText("");
passwordTextBox.setText("");
}
}
catch(Exception ex)
{
}
}
});
}
logoutHomeButton.addActionListener(
new ActionListener()
{
//method for events that will be performed when 'employeeFormButton' is pressed
public void actionPerformed(ActionEvent e)
{
try
{
//instance variable and object that holds currrent time when logged in
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm");
Date date = new Date();
String logoutTime = dateFormat.format(date);
//sets 'loginFrame' to visible
loginFrame.setVisible(true);
//sets 'welcomeFrame' to not visible
welcomeFrame.setVisible(false);
//adds 'logoutTime' to array
loginArray.add(logoutTime);
//statement that selects everything from our 'Login_Info'
String sql7 = "SELECT * FROM Login_Info";
//execute query, assigning all records in db to 'rs7'
rs7 = st.executeQuery(sql7);
//moves cursor to next row
rs7.moveToInsertRow();
//inserts record into db
rs7.updateString("User_Name", loginArray.get(0));
rs7.updateString("Login_Time", loginArray.get(1));
rs7.updateString("Logout_Time", loginArray.get(2));
//inserts data into db
rs7.insertRow();
JOptionPane.showMessageDialog(null, "You have successfully logged out!");
}
catch(Exception ex)
{
}
}
});
}
The ArrayList is a global variable at the top of my program. The two variable names I will be subtracting are loginTime and logoutTime and their respected indexes inside the ArrayList.
Thanks for any guidance
You can convert the strings back to dates using your SimpleDateFormat.parse(). Once they are both in Date format:
long elapsed = logoutDate.getTime() - loginDate.getTime(); // Elapsed time in ms
I am trying to develop user login/signup using JSP in MVC. The program will be doing a simple login, create and update for the user. In the model part I am supposed to return 0, 1, 2, 3 based on the following criteria.
0 if the user is validated successfully
1 if the user is validated successfully but has a weak password
2 if the user is validated successfully but has an expired password (over 1 year old)
3 if the user is not validated
Here is the code for the validate method which I have done till now,
public int Validate() {
try {
Class.forName(driverName).newInstance();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
Connection connection = DriverManager.getConnection(dbURL,
username, password);
String verifyQuery = "SELECT COUNT(email), dateSet, strength FROM users WHERE email=? AND hashPassword=SHA2(CONCAT(?, salt), 256)";
PreparedStatement verify = connection.prepareStatement(verifyQuery);
verify.setString(1, email);
verify.setString(2, pass);
ResultSet verified = verify.executeQuery();
while (verified.next()) {
if (verified.getInt(1) == 1) {
email_db = verified.getString(2);
pass_db = verified.getString(3);
date = verified.getDate(5);
strength = verified.getString(6);
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (email_db.equals(email) && pass_db.equals(pass)) {
status = 0;
}
if (email_db.equals(email) && pass_db.equals(pass)
&& strength.equals("weak")) {
status = 1;
}
if (email_db.equals(email) && pass_db.equals(pass) && date> ){
}
return status;
}
I am confused about the Date part, any suggestions? Should I write a new method for the Date part?
Using plain Java, you can achieve this using the java.util.Calendar and java.util.Date classes. Here's a code sample for a function that checks if it has passed a year using the current datetime
public boolean hasPassedAYear(Date date) {
long currentDate = Calendar.getInstance().getTimeInMillis();
long dateToEval = date.getTime();
// 1000 => milliseconds to seconds
// 60 => seconds to minutes
// 60 => minutes to hours
// 24 => hours to days
long days = (currentDate - dateToEval) / (1000 * 60 * 60 * 24);
return days >= 365;
}
Still, if you want a good code (like everyone), you should use Joda Time that provides a better Date/Time handling. This would be the same function but using Joda time library:
public boolean hasPassedAYear(Date date) {
DateTime currentDate = new DateTime();
DateTime dateToEval = new DateTime(date);
Interval interval = new Interval(dateToEval, currentDate);
return interval.toPeriod().getYears() >= 1;
}
It's up to you which method to choose. IMHO, I would use the code with Joda Time for the ease of readability, understanding and maintenance.
I assume the date that you get from the database is the date when the password was created/last modified . In that case will a compare to today's date to get the number of days not work ?
Check this post and answers for sample code .
Try below code
java.util.Date lastDate = result.getTimestamp("date");
java.util.Date todaysDate = new java.util.Date(System.currentTimeMillis());
long days1 = lastDate.getTime()/(60*60*24*1000);
long days2 = todaysDate.getTime()/(60*60*24*1000);
long difference = days2-days1;
You can use use this code..
if (email_db.equals(email) && pass_db.equals(pass) ){
Date dt = date;//Your Date from database
Calendar passCreatedOn = Calendar.getInstance();
passCreatedOn.setTime(dt);
Calendar today=Calendar.getInstance();
Integer noOfDays=( (today.getTime() - passCreatedOn.getTime()) / (1000 * 60 * 60 * 24));
if(noOfDays>365)
{
return 2
}
}