Accessing field called Date and Time in Event Viewer through Java - java

I would like to access the field called Date and time from Event Viewer through Java. I managed to get the EventID :
EVENTLOGRECORD record = new EVENTLOGRECORD(pevlr);
if (record.EventID.shortValue() == 4624) {
System.out.println("Successful log in: " + " Event ID: " + record.EventID.shortValue());
}
if (record.EventID.shortValue() == 4634) {
System.out.println("Successful log out: " + " Event ID: " + record.EventID.shortValue());
}
And now the next step would be to get the Date and time
If anyone could help i would really appreciate it !

Meanwhile I figured out how to get the Date and time field. Just used :
long timestamp = record.TimeGenerated.longValue() * 1000;
Date d = new Date(timestamp);

Related

How to extend expiration time java json web token?

I try to create Json Web Token in Java with jjwt library
But I have problem when I try to extend the expiration time.
I try it by the code below.
public class Main {
public static void main(String args[]) {
byte[] key = new byte[64];
new SecureRandom().nextBytes(key);
Date date = new Date();
long t = date.getTime();
Date expirationTime = new Date(t + 5000l); // set 5 seconds
String compact = Jwts.builder().setSubject("Joe").setExpiration(expirationTime).signWith(SignatureAlgorithm.HS256, key).compact();
System.out.println("compact : " + compact);
try {
String unpack = Jwts.parser().setSigningKey(key).parseClaimsJws(compact).getBody().getSubject();
System.out.println("unpackage 0 : " + unpack);
// check if the expiration work.
Thread.sleep(3000);
System.out.println("unpackage 1 : " + Jwts.parser().setSigningKey(key).parseClaimsJws(compact).getBody().getSubject());
//extend the expration time.
Date date1 = new Date();
long t1 = date1.getTime();
Date expirationTime1 = new Date(t1 + 5000l); //prolongation 5 seconds
Jwts.parser().setSigningKey(key).parseClaimsJws(compact).getBody().setExpiration(expirationTime1).getSubject();
// check if the extend expiration work.
Thread.sleep(3000);
System.out.println("unpackage 2 : " + Jwts.parser().setSigningKey(key).parseClaimsJws(compact).getBody().getSubject());
} catch (InterruptedException | ExpiredJwtException ex) {
System.out.println("exception : " + ex.getMessage());
Thread.currentThread().interrupt();
}
}
The result is :
compact : eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJKb2UiLCJleHAiOjE0Mjk2NjU1MjB9.oMY2mDHvNoMZqBfic41LbiKvAyi93wIfu_WgIADb9Wc
unpackage 0 : Joe
unpackage 1 : Joe
exception : JWT expired at 2015-04-22T08:18:40+0700. Current time: 2015-04-22T08:18:42+0700
So it mean, the unpackage2 cant run, Because it was expiration.
I trying to extend the expiration time.
Because I apply the code on web application.
If user still connect with my application, He should not get token timeout.
I have found another question like mine.
The problem is with the parsing code:
Jwts.parser().setSigningKey(key).parseClaimsJws(compact).getBody().setExpiration(expirationTime1).getSubject();
In this line, you're modifying the JWT that is returned by the parser. In other words, the above is equivalent to this:
Jws<Claims> jws = Jwts.parser().setSigningKey(key).parseClaimsJws(compact);
jws.getBody().setExpiration(expirationTime1).getSubject();
Notice how this code modifies the JWT returned by the parser? It does not - and cannot - modify the JWT represented by the original compact String.
Your next line of code after that tries to parse the original (unmodified) compact String:
// check if the extend expiration work.
Thread.sleep(3000);
System.out.println("unpackage 2 : " + Jwts.parser().setSigningKey(key).parseClaimsJws(compact).getBody().getSubject());
But we know this won't work because changing the state of the JWT returned by the parser does not have any effect on the original compact String.
If your user presents a JWT to your web application and you want to 'extend the life' of the token so it won't expire, you must generate a new JWT and send that JWT back to the user. The user should send the new JWT back on future requests. You keep repeating this process for as long as you want to allow the user to keep talking to your web application without having to re-login again.
I should point out that if you don't want to worry about any of this stuff, Stormpath can perform user and JWT token authentication between the browser and your app automatically for you - you don't have to build any of this yourself (disclosure: I'm Stormpath's CTO).
Finally, you might be interested to know that JJWT's test suite already validates the correct behavior in numerous places for both expired and premature token use cases:
https://github.com/jwtk/jjwt/blob/0.4/src/test/groovy/io/jsonwebtoken/JwtParserTest.groovy#L163-L189
https://github.com/jwtk/jjwt/blob/0.4/src/test/groovy/io/jsonwebtoken/JwtParserTest.groovy#L307-L335
https://github.com/jwtk/jjwt/blob/0.4/src/test/groovy/io/jsonwebtoken/JwtParserTest.groovy#L421-L454
But, you don't have to take my word for it :) Here is your code, modified so that your expiration modifications function as described:
public class Main {
public static void main(String args[]) {
byte[] key = new byte[64];
new SecureRandom().nextBytes(key);
Date date = new Date();
long t = date.getTime();
Date expirationTime = new Date(t + 5000l); // set 5 seconds
String compact = Jwts.builder().setSubject("Joe").setExpiration(expirationTime).signWith(SignatureAlgorithm.HS256, key).compact();
System.out.println("compact : " + compact);
try {
String unpack = Jwts.parser().setSigningKey(key).parseClaimsJws(compact).getBody().getSubject();
System.out.println("unpackage 0 : " + unpack);
// check if the expiration work.
Thread.sleep(3000);
System.out.println("unpackage 1 : " + Jwts.parser().setSigningKey(key).parseClaimsJws(compact).getBody().getSubject());
//Create a *new* token that reflects a longer extended expiration time.
Date date1 = new Date();
long t1 = date1.getTime();
Date expirationTime1 = new Date(t1 + 5000l); //prolongation 5 seconds
String compact2 = Jwts.builder().setSubject("Joe").setExpiration(expirationTime1).signWith(SignatureAlgorithm.HS256, key).compact();
// check if the extend expiration work.
Thread.sleep(3000);
System.out.println("unpackage 2 : " + Jwts.parser().setSigningKey(key).parseClaimsJws(compact2).getBody().getSubject());
Thread.sleep(1000);
} catch (InterruptedException | ExpiredJwtException ex) {
System.out.println("exception : " + ex.getMessage());
Thread.currentThread().interrupt();
}
}
}
Notice that a 2nd new JWT (compact2) needed to be generated to reflect the new/latest expiration time. You cannot modify a parsed JWT and expect the changes to apply to the original compact value.
In summary, use Jwts.parser() when you need to parse a JWT string to get a nice Java object representation of the JWT. Use Jwts.builder() when you need to create or modify a JWT to produce a new compact String representation.
I hope that helps!

how to parse and change values in sqlite

I have sqlite db(around 10k entries) with time stored in following format: hh:mmam/pm for example 12:40pm, 6:50am and I need it in milliseconds so they can be compared. Is there a way to make it happen? I am working with Java.
EDIT: Sorry, my question is ambiguous. I want to take value, transform it to milliseconds and overwrite it back, so all values will be stored in milliseconds rather than current format.
Problem was solved with the following python code, post it just in case anyone else will need to do something similar. After prog is done had to manually change type of the column from TEXT to NUMERIC
import sqlite3
from datetime import datetime
def unix_time(dt):
"""Takes datetime object and returns its unix time since epoch"""
epoch = datetime.utcfromtimestamp(0) #January 1st 1970
delta = dt - epoch
return delta.total_seconds()
def unix_time_millis(dt):
return unix_time(dt) * 1000 #milliseconds
db = sqlite3.connect("your_db.sqlite")#connect to initial database
cursor = db.cursor()
cursor.execute("select * from fancy_table")
all_entries = cursor.fetchall() #get our stuff
#new database. Make a copy of initial to prevent serious damage
db_new = sqlite3.connect("your_db_new.sqlite")
for entry in all_entries:
entry = str(entry[0].strip())#cursor returns tuple
#since it is time not a date, get milliseconds of the epoch
date_object = datetime.strptime("Jan 1 1970 " + entry, '%b %d %Y %I:%M%p')
new_time = unix_time_millis(date_object)
#print(entry + " to " + str(new_time))
cursor_update = db_new.cursor()#new cursor
try:
#updating
cursor_update.execute("UPDATE fancy_table SET time = '" + str(new_time) + "' WHERE arr_time = '" + entry + "'")
except Exception as error:
print(error)
db_new.commit()#needs to be commited to take affect
print("done")

Relative time for views in Play Framework 2.1

It seems like the Play Framework used(?) to have a since() function to get relative time (like "4 minutes ago") in views for Play 1.x. This is mentioned as a Date Extension here
However in Play 2.1 this doesn't appear to work anymore. I get value since is not a member of java.util.Date ... Additionally I can't find any other references to since() (in the context of Play 2.1) online.
Is there a proper/default way of handling this common case? I feel like I must be missing something important since this seems to no longer be supported?
Thanks!
The since() method is unavailable since beginning of the 2.0 branch.
Not a direct answer, but if it's possible I'd suggest to use JavaScript plugin for this task for an example: timeago jQuery plugin reasons:
It doesn't require calculating it in the controller
You can cache your site (for an example in the memory) for long time, and since time will be still displayed correctly as it's updated on the client-side.
It auto updates even without page refresh (like here, on the Stack Overflow)
#Jack suggested a pretty good answer.
Here is a version of his code that might be useful because it'll enable some composition if needed (the check function is not composing but could be easily changed to compose and show a more detailed since value)
package object pimps {
import java.util.Date
import org.joda.time.DateTime;
import org.joda.time.Period;
def step(f:Period => Int)(fi:String):Period => Option[String] = {
def g(i:Int = 1) = i + " " + fi + (if (i==1) "" else "s") + " ago"
(p:Period) => {
f(p) match {
case 0 => None
case 1 => Some(g())
case x => Some(g(x))
}
}
}
val yearsStep = step(_.getYears)("year")
val monthsStep = step(_.getMonths)("month")
val daysStep = step(_.getDays)("day")
val hoursStep = step(_.getHours)("hour")
val minutesStep = step(_.getMinutes)("minute")
val secondsStep = step(_.getSeconds)("second")
val steps = Seq(yearsStep, monthsStep, daysStep, hoursStep, minutesStep, secondsStep)
val check =
(p:Period) =>
steps.collectFirst {
case f if f(p).isDefined => f(p).get
}
implicit class PimpedDate(col: Date) {
def since() = {
val period: Period = new Period(new DateTime(col), DateTime.now);
check(period)
}
}
}
As you can see, for now we stop at the first matching level, and also we repeat the getter (getYears if matching will be called twice).
Nevertheless, another thing to note is the usage of implicit class which has been introduced in Scala 2.10 to ease the pimping
As far as I can tell this isn't possible to do any more (by default in Play2.1). Please correct me if I am wrong. Here's how I recreated it. As mentioned here I "pimped" the "Date" class:
// File app/views/pimps.scala
package views
package object pimps {
import java.util.Date
import org.joda.time.DateTime;
import org.joda.time.Period;
class PimpedDate(col: Date) {
def since() = {
def addS(b: Int) = if (b == 1) "" else "s"
val now: DateTime = new DateTime();
val period: Period = new Period(new DateTime(col), now);
var r: String = "";
if (period.getYears() > 0) {
r = period.getYears() + " year" + addS(period.getYears()) + " ago";
} else if (period.getWeeks() > 0) {
r = period.getWeeks() + " week" + addS(period.getWeeks()) + " ago";
} else if (period.getMonths() > 0) {
r = period.getMonths() + " month" + addS(period.getMonths()) + " ago";
} else if (period.getDays() > 0) {
r = period.getDays() + " day" + addS(period.getDays()) + " ago";
} else if (period.getHours() > 0) {
r = period.getHours() + " hour" + addS(period.getHours()) + " ago";
} else if (period.getMinutes() > 0) {
r = period.getMinutes() + " minute" + addS(period.getMinutes()) + " ago";
} else {
r = period.getSeconds() + " second" + addS(period.getSeconds()) + " ago";
}
r
}
}
implicit def pimpDate(col: Date) = new PimpedDate(col)
}
Then in my view I can just import the above:
#import views.pimps._
and then use since() just as you could in Play1
<td>#record.created_on.since()</td>
Please comment/answer if there's a better way to do this or write the scala code...

Android - how to check which calendar event is currently in progress?

I would like to check in internal Android calendar for event which is currently in progress (started before current time, and ends after current time). I'm using Android 2.2
I was playing around with this piece of code - I was trying to set start time to now but this doesn't work, it returns events that started after this moment.
//building query uri
Uri.Builder builder = Uri.parse("content://com.android.calendar/instances/when").buildUpon();
long now = new Date().getTime();
ContentUris.appendId(builder, now - DateUtils.MINUTE_IN_MILLIS * 80);
ContentUris.appendId(builder, now + DateUtils.MINUTE_IN_MILLIS * 80);
Log.d("AlarmReciever", "querying for calendar with id:" + calendarId);
//interating over events
Cursor eventCursor = contentResolver.query(builder.build(), new String[] { "title" }, "Calendars._id=" + calendarId, null, null);
while (eventCursor.moveToNext()) {
final String title = eventCursor.getString(0);
Toast.makeText(context, "title: " + title, Toast.LENGTH_LONG).show();
}
I would appreciate if someone could show me how to do this correctly. Thanks!

Calculate client-server time difference in Borland Starteam server 8

Problem. I need a way to find Starteam server time through Starteam Java SDK 8.0. Version of server is 8.0.172 so method Server.getCurrentTime() is not available since it was added only in server version 9.0.
Motivation. My application needs to use views at specific dates. So if there's some difference in system time between client (where the app is running) and server then obtained views are not accurate. In the worst case the client's requested date is in the future for server so the operation results in exception.
After some investigation I haven't found any cleaner solution than using a temporary item. My app requests the item's time of creation and compares it with local time. Here's the method I use to get server time:
public Date getCurrentServerTime() {
Folder rootFolder = project.getDefaultView().getRootFolder();
Topic newItem = (Topic) Item.createItem(project.getTypeNames().TOPIC, rootFolder);
newItem.update();
newItem.remove();
newItem.update();
return newItem.getCreatedTime().createDate();
}
If your StarTeam server is on a Windows box and your code will be executing on a Windows box, you could shell out and execute the NET time command to fetch the time on that machine and then compare it to the local time.
net time \\my_starteam_server_machine_name
which should return:
"Current time at \\my_starteam_server_machine_name is 10/28/2008 2:19 PM"
"The command completed successfully."
We needed to come up with a way of finding the server time for use with CodeCollab. Here is a (longish) C# code sample of how to do it without creating a temporary file. Resolution is 1 second.
static void Main(string[] args)
{
// ServerTime replacement for pre-2006 StarTeam servers.
// Picks a date in the future.
// Gets a view, sets the configuration to the date, and tries to get a property from the root folder.
// If it cannot retrieve the property, the date is too far in the future. Roll back the date to an earlier time.
DateTime StartTime = DateTime.Now;
Server s = new Server("serverAddress", 49201);
s.LogOn("User", "Password");
// Getting a view - doesn't matter which, as long as it is not deleted.
Project p = s.Projects[0];
View v = p.AccessibleViews[0]; // AccessibleViews saves checking permissions.
// Timestep to use when searching. One hour is fairly quick for resolution.
TimeSpan deltaTime = new TimeSpan(1, 0, 0);
deltaTime = new TimeSpan(24 * 365, 0, 0);
// Invalid calls return faster - start a ways in the future.
TimeSpan offset = new TimeSpan(24, 0, 0);
// Times before the view was created are invalid.
DateTime minTime = v.CreatedTime;
DateTime localTime = DateTime.Now;
if (localTime < minTime)
{
System.Console.WriteLine("Current time is older than view creation time: " + minTime);
// If the dates are so dissimilar that the current date is before the creation date,
// it is probably a good idea to use a bigger delta.
deltaTime = new TimeSpan(24 * 365, 0, 0);
// Set the offset to the minimum time and work up from there.
offset = minTime - localTime;
}
// Storage for calculated date.
DateTime testTime;
// Larger divisors converge quicker, but might take longer depending on offset.
const float stepDivisor = 10.0f;
bool foundValid = false;
while (true)
{
localTime = DateTime.Now;
testTime = localTime.Add(offset);
ViewConfiguration vc = ViewConfiguration.CreateFromTime(testTime);
View tempView = new View(v, vc);
System.Console.Write("Testing " + testTime + " (Offset " + (int)offset.TotalSeconds + ") (Delta " + deltaTime.TotalSeconds + "): ");
// Unfortunately, there is no isValid operation. Attempting to
// read a property from an invalid date configuration will
// throw an exception.
// An alternate to this would be proferred.
bool valid = true;
try
{
string testname = tempView.RootFolder.Name;
}
catch (ServerException)
{
System.Console.WriteLine(" InValid");
valid = false;
}
if (valid)
{
System.Console.WriteLine(" Valid");
// If the last check was invalid, the current check is valid, and
// If the change is this small, the time is very close to the server time.
if (foundValid == false && deltaTime.TotalSeconds <= 1)
{
break;
}
foundValid = true;
offset = offset.Add(deltaTime);
}
else
{
offset = offset.Subtract(deltaTime);
// Once a valid time is found, start reducing the timestep.
if (foundValid)
{
foundValid = false;
deltaTime = new TimeSpan(0,0,Math.Max((int)(deltaTime.TotalSeconds / stepDivisor), 1));
}
}
}
System.Console.WriteLine("Run time: " + (DateTime.Now - StartTime).TotalSeconds + " seconds.");
System.Console.WriteLine("The local time is " + localTime);
System.Console.WriteLine("The server time is " + testTime);
System.Console.WriteLine("The server time is offset from the local time by " + offset.TotalSeconds + " seconds.");
}
Output:
Testing 4/9/2009 3:05:40 PM (Offset 86400) (Delta 31536000): InValid
Testing 4/9/2008 3:05:40 PM (Offset -31449600) (Delta 31536000): Valid
...
Testing 4/8/2009 10:05:41 PM (Offset 25200) (Delta 3): InValid
Testing 4/8/2009 10:05:38 PM (Offset 25197) (Delta 1): Valid
Run time: 9.0933426 seconds.
The local time is 4/8/2009 3:05:41 PM
The server time is 4/8/2009 10:05:38 PM
The server time is offset from the local time by 25197 seconds.
<stab_in_the_dark>
I'm not familiar with that SDK but from looking at the API if the server is in a known timezone why not create and an OLEDate object whose date is going to be the client's time rolled appropriately according to the server's timezone?
</stab_in_the_dark>

Categories

Resources