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
}
}
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 new to Java and my problem here is a Simple Age Calculator. Here is my Code:
public class Client {
public int findAge(String birthDate) throws InvalidDateFormatException {
// InvalidDateFormatException is a custom defined
int age = 0;
try {
Calendar past = new GregorianCalendar();
Calendar present = Calendar.getInstance();
past.setTime(new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH).parse(birthDate));
age = present.get(Calendar.YEAR) - past.get(Calendar.YEAR);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return (age >= 0) ? age : 0;
}
In main,
try {
System.out.println(c.findAge("08-09-1015"));
} catch (InvalidDateFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Now, this is throwing a ParseException every time i pass a String in the wrong Format. Is there any way in which I can make it throw an InvalidDateFormatException Exception instead?
Also, please leave a comment on the style and quality of my Code, provided I'm following the correct coding standards and adhering to best practices.
To answer your prime question, you need to throw the custom exception in the catch block:
try {
Calendar past = new GregorianCalendar();
Calendar present = Calendar.getInstance();
past.setTime(new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH).parse(birthDate));
age = present.get(Calendar.YEAR) - past.get(Calendar.YEAR);
} catch (ParseException e) {
throw new InvalidDateFormatException("invalid date: " + birthDate);
}
Regarding your code, I have a couple of suggestions:
Do not use new GregorianCalendar() and prefer Calendar.getInstance().
The way you calculate the age is broken: you don't take into account the month and the day (let's say we are 2015-09-20, and the birth date is 2014-12-01, your code will output 1 even if the baby is not 1 year old yet).
Consider giving a Date argument instead of a String argument. It should not be the responsibility of the findAge method to parse the birth date.
If you are using Java 8, consider using the new Java Time API.
Define Custom Exception class for InvalidDateFormatException as below:
public class InvalidDateFormatException extends RuntimeException {
private String errorMessage;
public InvalidDateFormatException(String errorMessage, Exception exe) {
super(errorMessage);
exe.printStackTrace();
}
}
Modify your catch block to throw the exception as below :
public class Client {
public int findAge(String birthDate) throws InvalidDateFormatException {
int age = 0;
try {
Calendar past = new GregorianCalendar();
Calendar present = Calendar.getInstance();
past.setTime(new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH).parse(birthDate));
age = present.get(Calendar.YEAR) - past.get(Calendar.YEAR);
} catch (ParseException e) {
throw new InvalidDateFormatException("Invalid Date Format while finding Age", e);
}
return (age >= 0) ? age : 0;
}
}
Also, I would suggest you go through the below site:
https://docs.oracle.com/javase/tutorial/essential/exceptions/creating.html
I am trying to change the account expiration date in windows active directory.
I can able to change the Never option in account expiry using the below code .
final Modification mod = new Modification(ModificationType.REPLACE,
"accountExpires", "9223372036854775807");//Can change the required date with milliseconds
LDAPResult result=connection.modify(userDN, mod);
But , If I tried to change the account expiry date means , the code executed successfully and success was printed in console . But the date is not changed in the AD.
Here is my code to change or extend the account expiry date.
public class AccountExpireSetting {
public void ChangeAccountExpires(String userDN,String password , String dateToChange) throws LDAPException
{
LDAPConnection connection=null;
String someDate = null;
try {
connection = new LDAPConnectionObject().getConnection();
} catch (LDAPException e1) {
e1.printStackTrace();
}
try{
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
Date date = sdf.parse(dateToChange);
System.out.println("Date to MillSeconds : "+date.getTime());
someDate = String.valueOf(date.getTime());
Date date1=new Date(date.getTime());
System.out.println("MillSeconds to Date : "+date1);
}
catch(Exception e){
e.printStackTrace();
}
try{
System.out.println("Going to replace account expires to never");
final Modification mod = new Modification(ModificationType.REPLACE,
"accountExpires", someDate);// 9223372036854775807 milliseconds can change the password to never expire
// 9223372036854775807
LDAPResult result=connection.modify(userDN, mod);
System.out.println("Account expires status : " + result); // Password status : LDAPResult(resultCode=0 (success), messageID=2, opType='modify')
}catch(LDAPException e) {
// TODO Auto-generated catch block
System.out.println("Error in replacing account expires to never");
e.printStackTrace();
}finally
{
System.out.println("Closing the connection.");
connection.close();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String temp="CN=Anand,OU=Java,OU=Chennai,OU=Department,dc=tstdmn,dc=com";
try {
new AccountExpireSetting().ChangeAccountExpires(temp, "password#123","08.06.2014");
} catch (LDAPException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Hope you people will give a better solution.
The acountExpires is not milliseconds but rather the number of 100 nanosecond intervals since January 1, 1601 (UTC).
If a user object in Active Directory has never had an expiration date, the accountExpires attribute is set to a huge number. The actual value is 2^63 – 1, or 9,223,372,036,854,775,807. This is because 64-bit numbers can range from -2^63 to 2^63 - 1, making this the largest number that can be saved as a 64-bit value. Obviously this represents a date so far in the future that it cannot be interpreted. In fact, AccountExpirationDate raises an error if it attempts to read this value. If a user object has an expiration date, and then you remove this date in ADUC by selecting "Never" on the "Account" tab, the GUI sets accountExpires to 0. Thus, the values 0 and 2^63 - 1 both really mean "Never"
For one way to change in Java try looking at this discussion.
-jim
I am pulling 2 time values (as strings) from an XML file using xpath, these values (for example) are as follows:
00:07
08:00
00:07 is equal to 7 minutes
08:00 means 8am, with no date associated or needed (that is handled elsewhere)
Each of these values is subject to change in each XML file that i read. What i am attempting to do is as follows:
I need to subtract or add (depending on the situation) the 7mins from the 8am and give me a hh:mm time (eg: 07:53 or 08:07) in a string that i can eventually output to CSV
Next i need to produce 2 additional strings, 1 min before and 1 min after (eg: 07:52 and 07:54 OR 08:06 and 08:08) which also need to be output to CSV
I have tried everything and i can think of in relation to the time interpretation and manipulation to get the minutes subtracted/added to the time and then +/- 1 min from there, but being a complete novice i am totally stuck despite reading and testing as much as i could find. Spent the last 2 days working with Joda Time for the first time but i must be missing something fundamental as i cannot get the desired result with this either.
The question is - how can i achieve this?
Some sample code that gets me reading from the XML and printing the time
FileInputStream file = null;
try {
file = new FileInputStream(new File("Output/XmlConfig.xml"));
} catch (FileNotFoundException ex) {
Logger.getLogger(KATT.class.getName()).log(Level.SEVERE, null, ex);
}
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
try {
builder = builderFactory.newDocumentBuilder();
} catch (ParserConfigurationException ex) {
Logger.getLogger(KATT.class.getName()).log(Level.SEVERE, null, ex);
}
Document xmlDocument = null;
try {
xmlDocument = builder.parse(file);
} catch (SAXException ex) {
Logger.getLogger(KATT.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(KATT.class.getName()).log(Level.SEVERE, null, ex);
}
XPath xPath = XPathFactory.newInstance().newXPath();
//get In Early rule from XML
String exceptionInEarlyXML = "Root/Response/WSAExceptionRule/#InEarly";
NodeList nodeListInEarly = null;
try {
nodeListInEarly = (NodeList) xPath.compile(exceptionInEarlyXML).evaluate(xmlDocument, XPathConstants.NODESET);
} catch (XPathExpressionException ex) {
Logger.getLogger(KATT.class.getName()).log(Level.SEVERE, null, ex);
}
String exceptionInEarly = (nodeListInEarly.item(1).getFirstChild().getNodeValue());
String InEarly = exceptionInEarly;
SimpleDateFormat format = new SimpleDateFormat("hh:mm");
Date d2 = null;
try {
d2 = format.parse(InEarly);
} catch (ParseException ex) {
Logger.getLogger(KATT.class.getName()).log(Level.SEVERE, null, ex);
}
DateTime dt2 = new DateTime(d2);
System.out.println(dt2);
This give me an output of 1970-01-01T00:07:00.000+10:00
I have tried so many permutations of code that i am at the point of deleting and starting again from scratch as it is un-compilable, and i am not experienced enough yet to be able to solve this issue.
Once you have the Date object for the parsed time, use getTime() to get the time in milliseconds and save it into a long variables. Then parse the offset time format and use a NumberFormat to get the number of minutes to offset. Add or subtract as needed. Take the result and create a new Date(millis) then apply your format to it.
Here is a working example:
String sTime = "08:00";
String sOffset ="00:07";
SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm");
Date dtTime = null;
try {
dtTime = dateFormat.parse(sTime);
} catch (ParseException e) {
// handle exception
return;
}
String[] offsetHrsMins = null;
NumberFormat numberFormat = NumberFormat.getNumberInstance();
long offsetMillis = 0;
try {
offsetHrsMins = sOffset.split(":");
long offsetHrs = (Long) numberFormat.parse(offsetHrsMins[0]);
long offsetMins = (Long) numberFormat.parse(offsetHrsMins[1]);
offsetMillis = 1000 * 60 * ((offsetHrs * 60) + offsetMins);
} catch (ParseException e) {
// handle exception
return;
}
long lTime = dtTime.getTime();
System.out.println("Adding minutes: " + dateFormat.format(new Date(lTime + offsetMillis)));
System.out.println("Subtracting minutes: " + dateFormat.format(new Date(lTime - offsetMillis)));
output:
Adding minutes: 08:07
Subtracting minutes: 07:53
First, you need to use SimpleDateFormat to parse the Date String to a Java.util.Date Object.
Second, After getting the Date Object, you can easily add/substract some time, and get another Date Object.
Last, you can use another SimpleDateFormat object to format the Date Object you got in second step to String.
SimpleDateFormat is very useful in Processing Date Strings. You can refer to the Javadoc in JDK or search some examples by Google.
Try passing the strings into a method aswel as what you are subrtacting by
Then converting them to ints
Then have an if statment that if the subtraction amount is greater that the minets int
then it subtracts 1 from the hours int and sets the new minets int to 60 subtract the subtraction int
Then convert them back to Strings
Here is the code exept for turing it back into a string
public class Main {
static String hours="8";
static String minets="7";
static String minus="17";
public static void main(String[] args) {
Main m = new Main();
m.timechange(hours,minets,minus);
}
void timechange(String hour, String minuet, String subtract){
int h = Integer.parseInt(hour);
int m = Integer.parseInt(minuet);
int s = Integer.parseInt(subtract);
if(s>m){
h-=1;
m=60-s;
}
else{
m-=s;
}
if ((m>9)&&(h>9)) {
System.out.println(h+":"+m);
} else {if ((m<10)&&(h<10)) {
System.out.println("0"+h+":0"+m);
}else {if ((m<10)&&(h>9)) {
System.out.println(h+":0"+m);
}else {if ((m>9)&&(h<10)) {
System.out.println("0"+h+":"+m);
}
}
}
}
}}
I wasnt sure if you wanted the back to String.
Hopeful that answers your question
The same can be done for when the minets reach over 60 if that ever happens.
Here a genuine Joda-Time answer because OP wants Joda-Time (and I also consider that library as superior to java.util.Date, java.text.SimpleDateFormat etc.):
Joda-Time has the big advantage of having several different temporal types. The right type for handling plain wall times is LocalTime. It also defines a method to add minutes.
Your task:
I need to subtract or add (depending on the situation) the 7mins from the 8am and give me a hh:mm time (eg: 07:53 or 08:07) in a string that i can eventually output to CSV
Next i need to produce 2 additional strings, 1 min before and 1 min after (eg: 07:52 and 07:54 OR 08:06 and 08:08) which also need to be output to CSV
The solution (only for part one, the other part is very similar):
LocalTime time = new LocalTime(8, 0); // corresponds to 08:00
LocalTime laterBy8Minutes = time.plusMinutes(7);
LocalTime earlierBy8Minutes = time.minusMinutes(7);
String sLaterBy8Minutes = laterBy8Minutes.toString("HH:mm"); // 08:07
String sEarlierBy8Minutes = earlierBy8Minutes.toString("HH:mm"); // 07:53
One additional note: If you start with another type like java.util.Date and wish to convert it to LocalTime then you can use the constructor
new LocalTime(jdkDate, DateTimeZone.forID("Europe/Moscow")) // example
or for default timezone:
new LocalTime(jdkDate)
I have a window that contains a HH:mm time TextField in it, in 24 hours format
I need to validate if the user entered any non valid hour, like 28:00, 99:00, 24:01.
What's the best and simpler way to do that ?
some code below of what is currently doing that job wrong and giving errors in date parsed.
Today I get an random hour and an user hit 99:99 in that text field.
This code is not mine, but I gotta fix it.
I am stuck with it, tried to validate as a String is useless, and I cannot find a nice way to make it a Date without having to put year, month, etc... too.
Please forget about the return -1 instead of throwing an exception this is old code and this cannot be changed.
to help understand :
Statics.hF2 = SimpleDateFormat (HH:mm)
this.cmpHora.getText() = Is the field with the value
Statics.df_ddmmyy = Another date format
Statics.m2ms = converts minutes to milliseconds
//CODE
public long getDataEmLong ()
{
try
{
Calendar hour= Calendar.getInstance();
new GregorianCalendar().
hour.setTime( Statics.hF2.parse( this.cmpHora.getText() ) );
return Statics.df_ddmmyy.parse( this.cmpData.getText() ).getTime() + Statics.m2ms( hour.get( Calendar.HOUR_OF_DAY ) * 60 ) + Statics.m2ms( hour.get( Calendar.MINUTE ) );
} catch ( Exception e )
{
e.printStackTrace();
return -1;
}
}
Cheers !
Regular expressions to the rescue:
public boolean validTime24(String time) {
return time.matches("^([01]\d|2[0-3]):[0-5]\d$")
}
This will validate the format of the string. Then you can parse out the time from there.
Insert this in your class, and perform the validateTime method from inside your junk code.
public boolean validateTime(String timeString) {
if (timeString.length() != 5) return false;
if (!timeString.substring(2, 3).equals(":")) return false;
int hour = validateNumber(timeString.substring(0, 2));
int minute = validateNumber(timeString.substring(3));
if (hour < 0 || hour >= 24) return false;
if (minute < 0 || minute >= 60) return false;
return true;
}
public int validateNumber(String numberString) {
try {
int number = Integer.valueOf(numberString);
return number;
} catch (NumberFormatException e) {
return -1;
}
}
You can use JFormattedTextField with proper Date or Time Format set. The field will return you proper values.
Since Java 8 you can use DateTimeFormatter:
public boolean validate(String time) {
try {
DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm");
timeFormatter.parse(time);
return true;
} catch (DateTimeParseException e) {
return false;
}
}