How add LocalDate list to myList in Java - java

How add Local date list to myList in java
Please find the below code and check where I made a mistake to add dates to myList
I declare List as Local date now need to convert to myModel
error occurs in // myList.addAll(employeeReportsModel.getReportFromDt());
#RequestMapping(value = "/getMusterRollDateBased", method = RequestMethod.GET)
public ModelAndView getMusterRollDateBased(EmployeeReportsModel employeeReportsModel) {
ModelAndView mv = new ModelAndView();
String tablePrefix = "at_hr_logs_";
try {
System.out.println("refort from date.."+employeeReportsModel.getReportFromDt());
System.out.println("refort to date.."+employeeReportsModel.getReportToDt());
String fromdate = employeeReportsModel.getReportFromDt();
String todate = employeeReportsModel.getReportToDt();
Date date1 = new SimpleDateFormat("yyyy-MM-dd").parse(fromdate);
Date date2 = new SimpleDateFormat("yyyy-MM-dd").parse(todate);
System.out.println(date1 + "-----" + date2);
// parse the date into another format
SimpleDateFormat sdfDestination = new SimpleDateFormat("yyyy-MM-dd");
String fromdate1 = sdfDestination.format(date1);
String todate1 = sdfDestination.format(date2);
employeeReportsModel.setReportFromDt(fromdate1);
// get dates between two dates
String startString = fromdate1;
String endString = todate1;
LocalDate incrementingDate = LocalDate.parse(startString);
LocalDate endDate = LocalDate.parse(endString);
List<LocalDate> allDates = new ArrayList<>();
while (!incrementingDate.isAfter(endDate)) {
allDates.add(incrementingDate);
incrementingDate = incrementingDate.plusDays(1);
}
System.err.println(allDates);
List<EmployeeReportsModel> myList = null;
mv.addObject("allDates",allDates);
for (LocalDate date : allDates) {
//System.out.println();
System.out.println("dates is..." + date);
employeeReportsModel.setReportFromDt(date.toString());
String[] parts = date.toString().split("-");
String part1 = parts[0]; // 004
String part2 = parts[1]; // 034556
System.out.println("year ....." + part1);
System.out.println("Month....." + part2);
String tableName = tablePrefix + part1 + '_' + part2;
System.out.println("hks table name is.." + tableName);
employeeReportsModel.setDynamicTableName(tableName);
myList.addAll(employeeReportsModel.getReportFromDt());
//here we get a problem to add
}
} catch (Exception e) {
e.printStackTrace();
}
mv.setViewName("/" + moduleName + "/employeeMusterRollBasedOnDateInter");
return mv;
}

First thing is that you call myList.addAll() on a null object. Your list should be initialized properly like myList = new ArrayList().
Then you are trying to store a String type in your list which expects an object of type EmployeeReportsModel.
So you either change your myList to look like List<String> or change your return type of the getReportFromDt() method.
I suggest you to rethink your current code.
Currently you are basically doing the following:
get a local date > create a String out of it > store it with setReportFromDt > call getReportFromDt > try to store LocalDate in string form into a List of type EmployeeReportsModel

Related

Divide Subject, From, and To values from headers

I'm fetching the messages from authorized email but the problem is the separation of Subject, From, and To values from headers in java, I succeed in that below code is working fine but it is taking more time for separation, I have gone through so much Gmail API documentation but I didn't get the solution.
ListMessagesResponse listResponse = service.users().messages().list(user).setMaxResults(10L)
.setLabelIds(labelidlist).setQ(query).execute();
List<Message> listofmesssages = listResponse.getMessages();
HashMap<String, Object> msgsMap;
List messageslist = new ArrayList();
for (Message message : listofmesssages) {
Message fullmessage = service.users().messages().get("me", message.getId()).setFormat("full").execute();
msgsMap = new LinkedHashMap<String, Object>();
/*Adding threadid for threadid is required when delete operation has happen*/
msgsMap.put("threadid", message.getThreadId());
List<MessagePartHeader> headers = fullmessage.getPayload().getHeaders();
if (!headers.isEmpty()) {
for (MessagePartHeader header : headers) {
String name = header.getName();
msgsMap.put("msgid", message.getId());
if (name.equalsIgnoreCase("Subject")) {
subject = header.getValue();
msgsMap.put("subject", subject);
} else if (name.equalsIgnoreCase("From")) {
from = header.getValue().split("<")[0];
msgsMap.put("from", from);
} else if (name.equalsIgnoreCase("To")) {
to = header.getValue().split(" ")[0];
msgsMap.put("to", to);
} else if (name.equalsIgnoreCase("Date")) {
String date = header.getValue();
java.util.Date fecha = new java.util.Date(date);
DateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.US);
Date date1;
date1 = (Date) formatter.parse(fecha.toString());
Calendar cal = Calendar.getInstance();
cal.setTime(date1);
String formatedDate = cal.get(Calendar.DATE) + "/" + (cal.get(Calendar.MONTH) + 1) + "/"
+ cal.get(Calendar.YEAR);
msgsMap.put("date", formatedDate);
}
}
}
messageslist.add(msgsMap);
}
return messageslist;
If you look at the message resource JSON, you can see that headers is an array of objects that contain properties name and value. There is no property key called To, or Subject. That's the reason the library you're using has no methods called getTo, or getSubject.
This makes sense, since headers might not always be the same ones.
Because of this, you cannot specifically fetch a certain header name.
Reference:
Users.messages
getHeaders()

JAVA8, parsing text file and parsing its values to objects

I have specific text file looking like this:
name: meeting_name1
description:
04/18/2012 00:00:00
05/18/2012 00:00:00
... (more dates)
07/18/2012 00:00:00
name: meeting_name2
description: some_desc
04/18/2012 00:00:00
05/18/2012 00:00:00
... (more dates)
07/18/2012 00:00:00
(etc)
I have java object looking like this:
class Meeting {
String name;
String description;
List<Date> dates;
}
My point is to read the file, parse values, create objects and save them to database.
I can read the file line by line and convert it to List<String>, ie. all data together.
`I can make and fill one java object with values and save it to database.
My issue here is how to find out that I'm at the end of dates and lines (name: meeting_name2) of new object begin.
So I could make something like List<List<String>> where List<String> would be equal to one object, ie. List<Meeting>?
Not sure if its understandable, sorry for formatting.
Assumption that you could read the file data to List variable. (See above answer)
List<String> lines = Files.readAllLines(Paths.get("FILE_NAME"));
Now, you can see below code as a demo. It is the simple loop and if else statament.
Hope it will help you.
public static void main(String[] args) throws ParseException {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
List<String> data = new ArrayList<>();
data.add("name: meeting_name1");
data.add("description: some_desc");
data.add("07/18/2012 00:00:00");
data.add("07/18/2012 00:00:00");
data.add("name: meeting_name2");
data.add("description: some_desc");
data.add("07/18/2012 00:00:00");
List<Meeting> result = new ArrayList<>();
Meeting temp = null;
for (String line : data) {
if (line.startsWith("name:")) {
temp = new Meeting(line.split(":")[1].trim());
result.add(temp);
} else if (line.startsWith("description:")) {
temp.setDescription(line.split(":")[1].trim());
} else {
temp.getDates().add(simpleDateFormat.parse(line)); // Use date for
}
}
System.out.println(result.get(0).getName() + ": " + result.get(0).getDates().size()); // meeting_name1: 2
System.out.println(result.get(1).getName() + ": " + result.get(1).getDates().size()); // meeting_name2: 1
}
static class Meeting {
String name;
String description;
List<Date> dates;
public String getName() {
return name;
}
public List<Date> getDates() {
return dates;
}
Meeting(String name) {
this.name = name;
this.dates = new ArrayList<>();
}
public void setDescription(String description) {
this.description = description;
}
}
One possibility would be to read all lines first. You would not need to worry about the end of lines with:
List<String> lines = Files.readAllLines(Paths.get("FILE_NAME"));
then iterarate through the array,
if a line starts with "name:" you make a new object and add the data like that:
List<Meeting> meetings = new ArrayList();
Meeting currentMeeting;
for (String line : lines) {
if(line.startsWith("name:"))
{
currentMeeting = new Meeting();
meetings.add(currentMeeting);
//...add data (name)
}
//...add more data (description and dates)
}

how to create active directory users with accountExpires attribute from java

I want to create an AD user with accountExpires attribute. I am doing like this
public boolean addUser(
String firstName,
String lastName,
String userName,
String password,
String organisationUnit) throws NamingException {
if (findUser(userName, firstName, lastName, organisationUnit)) {
return false;
} else {
// Create a container set of attributes
BasicAttributes container = new BasicAttributes();
// Create the objectclass to add
Attribute objClasses = new BasicAttribute("objectClass");
objClasses.add("top");
objClasses.add("person");
objClasses.add("organizationalPerson");
objClasses.add("user");
// Assign the username, first name, and last name
String cnValue = new StringBuffer(firstName).append(" ").append(lastName).toString();
Attribute cn = new BasicAttribute("cn", cnValue);
Attribute sAMAccountName = new BasicAttribute("sAMAccountName", userName);
Attribute mac = new BasicAttribute("msNPCallingStationID", "ab-ab-ab-b7-6t");
Attribute principalName = new BasicAttribute("userPrincipalName", userName + "#atamunet.com");
Attribute givenName = new BasicAttribute("givenName", firstName);
Attribute sn = new BasicAttribute("sn", lastName);
Attribute uid = new BasicAttribute("uid", userName);
Attribute fullName = new BasicAttribute("displayName", "fullName");
Attribute gender = new BasicAttribute("initials", "gender");
Attribute dob = new BasicAttribute("description", "dob");
Attribute FatherName = new BasicAttribute("physicalDeliveryOfficeName", "FatherName");
Attribute Email = new BasicAttribute("mail", "Email");
Attribute mobile = new BasicAttribute("mobile", "mobile");
Attribute department = new BasicAttribute("department", "department");
Attribute HallName = new BasicAttribute("streetAddress", "HallName");
Attribute FacultyName = new BasicAttribute("company", "FacultyName");
Attribute CourseName = new BasicAttribute("title", "CourseName");
Attribute accountExpires = new BasicAttribute("accountExpires", new Date());
//some useful constants from lmaccess.h
int UF_ACCOUNTENABLE = 0x0001;
//int UF_ACCOUNTDISABLE = 0x0002;
int UF_PASSWD_NOTREQD = 0x0020;
int UF_PASSWD_CANT_CHANGE = 0x0040;
int UF_NORMAL_ACCOUNT = 0x0200;
int UF_DONT_EXPIRE_PASSWD = 0x10000;
//int UF_PASSWORD_EXPIRED = 0x800000;
Attribute enabled = new BasicAttribute("userAccountControl", Integer.toString(UF_NORMAL_ACCOUNT + UF_PASSWD_NOTREQD + UF_DONT_EXPIRE_PASSWD + UF_ACCOUNTENABLE));
// Add password
Attribute userPassword = new BasicAttribute("userpassword", password);
// Add these to the container
container.put(objClasses);
container.put(sAMAccountName);
container.put(principalName);
container.put(cn);
container.put(sn);
container.put(givenName);
container.put(uid);
container.put(userPassword);
container.put(mac);
container.put(gender);
container.put(dob);
container.put(FatherName);
container.put(Email);
container.put(mobile);
container.put(department);
container.put(HallName);
container.put(FacultyName);
container.put(CourseName);
container.put(fullName);
container.put(enabled);
container.put(accountExpires);
// Create the entry
try {
ctx.createSubcontext(getUserDN(cnValue, organisationUnit), container);
return true;
} catch (Exception e) {
System.out.println(e.getMessage() + "add");
return false;
}
}
}
How can I add user with accountExpires attribute. Is there anybody can help me. Without this line
Attribute accountExpires = new BasicAttribute("accountExpires", new Date());
Everything goes fine but I want the expiry date as well.
You are setting the attribute to the current date, but this is not correct.
First of all because the attribute is an interval of 100-nanoseconds, according to the Microsoft documentation and this.
What you have to do is set your desired expiration date, then convert to the value of 100-nanoseconds, that in Java are represented by long.
Here is a trivial code example that show you how to do it with Java 8:
UPDATED:
Calendar cal = Calendar.getInstance();
// First you need to get the start date
// according to the documentation it is
// the 1th January of 1601
cal.set(1601, Calendar.JANUARY, 1);
// print the current date
System.out.println(String.format("Start date: %tc", cal));
Date startDate = cal.getTime();
// Reset the calendar to today
cal.set(Calendar.MILLISECOND, System.currentTimeMillis());
// Set the desired expiration date
// here is 1 year in the future
cal.set(Calendar.YEAR, cal.get(Calendar.YEAR) + 1);
// print the current date
System.out.println(String.format("Expire date: %tc", cal));
// Get the date from Calendar
Date expireDate = cal.getTime();
// Create an interval from the startDate to the expireDate
// and convert it to nanoseconds interval
long expirationInterval = TimeUnit.NANOSECONDS.toNanos(expireDate.getTime()-startDate.getTime());
// set the attribute value
Attribute accountExpires = new BasicAttribute("accountExpires", expirationInterval);
Thanks for your help what gave me the idea and this code worked for me
/**
* Difference between Filetime epoch and Unix epoch (in ms).
*/
private static final long FILETIME_EPOCH_DIFF = 11644473600000L;
/**
* One millisecond expressed in units of 100s of nanoseconds.
*/
private static final long FILETIME_ONE_MILLISECOND = 10 * 1000;
public static long filetimeToMillis(final long filetime) {
return (filetime / FILETIME_ONE_MILLISECOND) - FILETIME_EPOCH_DIFF;
}
public static long millisToFiletime(final long millis) {
return (millis + FILETIME_EPOCH_DIFF) * FILETIME_ONE_MILLISECOND;
}
SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
String dateInString = "01-07-2017 10:20:56";
Date date = sdf.parse(dateInString);
final long dd = date.getTime();
Attribute accountExpires = new BasicAttribute("accountExpires", Long.toString(millisToFiletime(dd)));

Check whether dates are within the date range in selenium web driver ( Java)

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.

SimpleDateFormat returning wrong time value ( 00:00:00) [duplicate]

This question already has answers here:
JDBC ResultSet getDate losing precision
(3 answers)
Closed 7 years ago.
I'm having an issue using the SimpleDateFormat component.
I have a date stored in my database as a DateTime, and i would like to get the value of this datetime in my application.
I'm using a SimpleDateFormat in order to do this, but the problem is that it always returns me 00:00:00 as Time. The date is well returned though.
So i'm doing as follows :
private final static SimpleDateFormat ft = new SimpleDateFormat("dd.MM - HH:mm:ss");
public Push(int idp, String titrefr, String contenufr, String titreuk, String contenuuk, String pays, String marche, String type, Date datep, int isImportant, String image) {
super();
this.idp = idp;
this.titrefr = titrefr;
this.contenufr= contenufr;
this.titreuk = titreuk;
this.contenuuk= contenuuk;
this.pays = pays;
this.marche = marche;
this.type = type;
this.datep = ft.format(datep);
this.isImportant = isImportant;
this.image = image;
System.out.println(this.datep);
}
Here is the method where I get the date :
Modele.java:
public List<Push> getPushfr() {
String queryPushfr = "SELECT idp,titrefr,contenufr,titreuk,contenuuk,pays,marche,type,datep,isImportant, image FROM push WHERE datep > DATE_SUB(CURRENT_DATE, INTERVAL 3 MONTH) ORDER BY datep DESC;";
try {
connexion = ConnexionBDD.getConnexion();
PreparedStatement pstmt = connexion.prepareStatement(queryPushfr);
resultat = pstmt.executeQuery(queryPushfr);
while (resultat.next()) {
int idp = resultat.getInt("idp");
String titrefr = resultat.getString("titrefr");
String contenufr = resultat.getString("contenufr");
String titreuk = resultat.getString("titreuk");
String contenuuk = resultat.getString("contenuuk");
String pays = resultat.getString("pays");
String marche = resultat.getString("marche");
String type = resultat.getString("type");
Date datep = resultat.getDate("datep");
int isImportant = resultat.getInt("isImportant");
String image = resultat.getString("image");
this.pushfr.add(
new Push(idp, titrefr, contenufr, titreuk, contenuuk, pays, marche, type, datep, isImportant,image));
}
} catch (Exception ex) {
System.err.println(ex.getMessage());
}
return pushfr;
}
In my database the date is :
2015-09-03 16:13:09
The output i get from my System.out.println(datep) is
03.09 - 00:00:00
I've no idea why it's not returning me the time properly..
If you are using java.sql.Date you will lose information about the time.
java.sql.Date corresponds to SQL DATE which means it stores years,
months and days while hour, minute, second and millisecond are
ignored.
Change code to:
public List<Push> getPushfr() {
String queryPushfr = "SELECT idp,titrefr,contenufr,titreuk,contenuuk,pays,marche,type,datep,isImportant, image FROM push WHERE datep > DATE_SUB(CURRENT_DATE, INTERVAL 3 MONTH) ORDER BY datep DESC;";
try {
connexion = ConnexionBDD.getConnexion();
PreparedStatement pstmt = connexion.prepareStatement(queryPushfr);
resultat = pstmt.executeQuery(queryPushfr);
while (resultat.next()) {
int idp = resultat.getInt("idp");
String titrefr = resultat.getString("titrefr");
String contenufr = resultat.getString("contenufr");
String titreuk = resultat.getString("titreuk");
String contenuuk = resultat.getString("contenuuk");
String pays = resultat.getString("pays");
String marche = resultat.getString("marche");
String type = resultat.getString("type");
Date datep = resultat.getTimestamp("datep");
int isImportant = resultat.getInt("isImportant");
String image = resultat.getString("image");
this.pushfr.add(
new Push(idp, titrefr, contenufr, titreuk, contenuuk, pays, marche, type, datep, isImportant,image));
}
} catch (Exception ex) {
System.err.println(ex.getMessage());
}
return pushfr;
}
PD:I recomend you to store the TimeStamt in milisecons in the database.
If you are loading results from a ResultSet, use getTimestamp method, not getDate. See JDBC ResultSet getDate losing precision

Categories

Resources