Divide Subject, From, and To values from headers - java

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

Related

Selenium webdriver- get performance logs- unknown date timestamp (12345.12345)

I have been using selenium webdriver and chrome and logs recently. But any timestamp values are coming back in a weird date time stamp format. I've search all over, and I cannot figure what it is. Furthermore, other values besides timestamp (like requestId or walltime) are also in new unknown formats. What format is this and how can I get it into a normal (MM DD YYYY HH:MM:SS..) format?
timestamp was 2484894.662632 around June 23rd 2021, 10:53:23.118
timestamp was 2486019.900761 around June 23rd 2021, 11:12:01.277
timestamp was 2581839.545059 around June 24th 2021, 13:49:09.354
Example:
"requestId":"30432.634","timestamp":87693.142713,"type":"XHR","wallTime":1624556888.229531}
Code snippet:
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.BROWSER, Level.ALL);
logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
flavorCapability.setCapability("goog:loggingPrefs", logPrefs);
driver.manage().logs().get(LogType.PERFORMANCE).getAll();
There is two way to get the desired result:
1) Simple way:
LogEntries entries = driver.manage().logs().get(LogType.PERFORMANCE);
for(LogEntry entry: entries){
System.out.println(entry.getTimestamp());
System.out.println(entry.getLevel());
System.out.println(entry.getMessage());
System.out.println(entry.toJson());
System.out.println(new Date(entry.getTimestamp()));
}
2) Second way to do it:
import org.json.JSONException;
import org.json.JSONObject;
LogEntries logs = driver.manage().logs().get("performance");
for (Iterator<LogEntry> it = logs.iterator(); it.hasNext();) {
LogEntry entry = it.next();
try {
JSONObject json = new JSONObject(entry.getMessage());
JSONObject message = json.getJSONObject("message");
String method = message.getString("method");
System.out.println(method);
if (method != null && "Network.responseReceived".equals(method)) {
JSONObject params = message.getJSONObject("params");
JSONObject response = params.getJSONObject("response");
JSONObject headers = response.getJSONObject("headers");
String timestamp = headers.getString("date");
String url = response.getString("url");
int status = response.getInt("status");
System.out.println("Response = " + response);
System.out.println("URL = "+ url);
System.out.println("Status Code = "+ status);
System.out.println("headers: " + response.get("headers"));
System.out.println("Timestamp: " + timestamp);
}
} catch (JSONException e) {
System.out.println(e.getMessage());
}
}
Ref: https://chromedevtools.github.io/devtools-protocol/tot/Network/
Note: Please provide the exact requirement, what exactly you want to get?
Subtracting the timestamp as seconds from the 3 datetimes you got these stamps, I could deduce that the timestamp means number of seconds that have passed since 16:38:25 +- 5 sec on the 25th of May 2021. All three timestamps agree that this is the origin.
Don't ask me why the origin is at that time. Maybe the computer booted at that time, or some number overflowed and started from 0 again.

How add LocalDate list to myList in 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

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

If statement on the server side using iText results in Connection failed

I am using GWT, java, iText to produce a PDF and want to reformat the date. However, this code, on the server side, results in the message "Connection failed" on the client side (there are no error messages in the log) and no output:
String storedName = " ";
DateTimeFormat sdf = DateTimeFormat.getFormat("dd-MM-yyyy");
for (final Transcript scoutNamesDescription : listymAwards) {
if (scoutNamesDescription.getSection().equals(storedName)){
table.addCell(" ");
}else{
storedName = scoutNamesDescription.getSection();
table.addCell(scoutNamesDescription.getSection());
}
table.addCell(scoutNamesDescription.getAwardName());
Date awardedDate = sdf.parse(scoutNamesDescription.getAwardedDate());
String awardedString = DateTimeFormat.getFormat("dd-MM-yyyy").format(awardedDate);
table.addCell(awardedString);
}
preface.add(table);
document.add(preface);
When I comment out the date reformatting this works.
I have tried replacing the reformatting with:
System.out.println(scoutNamesDescription.getAwardedDate());
formatedDate = StringUtils.substring(scoutNamesDescription.getAwardedDate(), 8, 2) +
StringUtils.substring(scoutNamesDescription.getAwardedDate(), 4, 4) +
StringUtils.substring(scoutNamesDescription.getAwardedDate(), 0, 2);
System.out.println(formatedDate);
And this also produces the same error between the two println.
Based on Andrei Volgin's reply I have the following:
String storedName = null;
DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
DateFormat df2 = new SimpleDateFormat("dd-MM-yyyy");
for (final Transcript scoutNamesDescription : listymAwards) {
if (scoutNamesDescription.getSection().equals(storedName)){
table.addCell(" ");
}else{
storedName = scoutNamesDescription.getSection();
table.addCell(scoutNamesDescription.getSection());
}
table.addCell(scoutNamesDescription.getAwardName());
Date awardedDate = df1.parse(scoutNamesDescription.getAwardedDate());
String awardedString = df2.format(awardedDate);
table.addCell(awardedString);
}
preface.add(table);
document.add(preface);
}
You cannot use GWT code on the server side. And in this case there is no need.
Use standard Java tools for formatting dates:
Convert java.util.Date to String

Same date is always returned when accessing Android history through Cursor

I am developing an application which displays a user's broswer history.
I'm successfully displaying the page title and URL, but I'm allways getting the same date - regardless of when the site was last visited.
The date is always 28/10/2015/20:55
TextView view = (TextView) findViewById(R.id.tv);
String[] projection = new String[]{
Browser.BookmarkColumns.TITLE
, Browser.BookmarkColumns.URL
,Browser.BookmarkColumns.DATE
};
Cursor mCur = managedQuery(android.provider.Browser.BOOKMARKS_URI,
projection, null, null, null
);
String date="";
mCur.moveToFirst();
int titleIdx = mCur.getColumnIndex(Browser.BookmarkColumns.TITLE);
int urlIdx = mCur.getColumnIndex(Browser.BookmarkColumns.URL);
date = mCur.getString(mCur.getColumnIndex(Browser.BookmarkColumns.DATE));
Long timestamp = Long.parseLong(date);
SimpleDateFormat dateFormat = new SimpleDateFormat( "dd/MM/yyyy/HH:mm");
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(timestamp);
String finaldate = dateFormat.format(calendar.getTime());
String smsDate = finaldate.toString();
while (mCur.isAfterLast() == false) {
view.append("Tite: " + mCur.getString(titleIdx)+"\n");
view.append("Url: " + mCur.getString(urlIdx)+"\n");
view.append("date: " + smsDate +"\n");
view.append("\n");
mCur.moveToNext();
}
Any help would be greatly appreciated.
The Title & Url are outputting correctly, but not the date.
I've obviously done something wrong in getting the date, but I'm not sure what.

Categories

Resources