Change account expiration date in "active directory" using Unbound Id? - java

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

Related

Java Parse Exception to Custom Exception

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

Java time manipulation - subtracting 2 strings

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)

Converting items inside ArrayList to different types

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

Android - Try Catch is not catching the exception and it's not displaying my toast message

I'm new to Android programming and taking a Coursera class. In my assignment app, I'm trying to catch any exceptions when the user does not enter or enters incorrect time information (HH:MM:SS).
My app crashes right after user error instead of displaying my Toast message or displaying a Log message to Logcat.
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
try {
Date dt = formatter.parse(MileTime);
Calendar cal = Calendar.getInstance();
cal.setTime(dt);
int hours = cal.get(Calendar.HOUR);
int minutes = cal.get(Calendar.MINUTE);
int seconds = cal.get(Calendar.SECOND);
int duration = 3600 * hours + 60 * minutes + seconds;
int steps_per_second = 3;
int running_rate = duration * steps_per_second;
//pleaseStop = false; //DouglasZare example, don't need this.
mHandler = new Handler(); // .os package class when importing
mLeftfoot = findViewById(R.id.leftfoot);
mRightfoot = findViewById(R.id.rightfoot);
mFootAnim = AnimationUtils.loadAnimation(this, R.anim.foot); //this looks to the foot.xml file for the animations
stepRecursive();
} catch (ParseException e) {
e.printStackTrace();
Log.e(TAG, "Invalid Mile Time Entry", e);
Toast.makeText(Assignment3MainActivity_V3_DouglasZare_AnimationCancel.this,
"Please Enter Valid Time Stamp HH:MM:SS", Toast.LENGTH_LONG).show();
}
The error log is here: http://pastebin.com/By7FWxLk.
This error makes perfect sense and is intentional.
Caused by: java.text.ParseException: Unparseable date: ""
What do I fix to get my catch statement to prevent this?
Fixed. Ugh. I changed ParseException to just Exception. It doesn't make any sense to me...The Exception I want to catch IS ParseException.
catch (Exception e) {
e.printStackTrace();
Log.e(TAG, "Invalid Mile Time Entry", e);
Toast.makeText(Assignment3MainActivity_V3_DouglasZare_AnimationCancel.this,
"Please Enter Valid Time Stamp HH:MM:SS", Toast.LENGTH_LONG).show();
}
The reason is the exception being thrown is IllegalStateException not ParseException.
If you look at line 5 of your crash log, you'll see the exception that gets passed up to you is an IllegalStateException. This is because the ParseException is caught and then an IllegalStateException is re-thrown afterwards.
Here's an example of multiple catch blocks.
try {
//some code that can throw an exception
} catch (IllegalStateException e) {
//catch the IllegalStateExeption
} catch (Exception e) {
//catch all the ones I didn't think of.
}

How to check if a password is over one year old?

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

Categories

Resources