Checking if access token isnt expired - java

I have application which gives access token after authentication and I want to check if token is not expired
#JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private String expires_in;
public boolean isNotExpired() {
return ! Instant.now().isBefore(Instant.parse(expires_in));
}
But after I run application I get errors:
JSON encoding error: Text '3600' could not be parsed at index 4; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Text '3600' could not be parsed at index 4 (through reference chain: com.Auth.AuthInfo["notExpired"])
How can I fix this?

Why do you keep the value of 3600 there instead of the actual date-time of the expiration?
It will easily solve your problem.
If you want to keep how long the token is valid you would also need the issue time of the token to check that the diff of current time - issue time is not greater than the value of a field like validFor.

Related

Handle validation for non numeric characters getting passed to Integer variable

Is there an annotation that could be used to prevent the following error from getting thrown by my Java application if I send a non numerical value for year in my GET request?
I currently have this:
#NotNull
#Digits(integer = 4, fraction = 0, message = "Provide valid Year in the format YYYY")
#Min(value = 1900, message = "Year must be greater than 1900")
private Integer year;
When I pass a value with letters I get a NumberFormatException before #Digits and #Min is executed. I also tried #Pattern with a regex value but that caused a 500 error.
"Failed to convert property value of type 'java.lang.String' to required type 'java.lang.Integer' for property 'yearOfReg'; nested exception is java.lang.NumberFormatException: For input string: \"20c15\"
The answer is very short: no. That's because the validation is configured for the Integer year field. That means that the field must get populated before it can be validated. That population fails if you submit a value that cannot be parsed to an Integer.
The best way to handle this case is to add error handling for the mapping exception. For Jackson that's a MismatchedInputException.
An alternative is to change the field to a String. That allows you to use #Pattern, but you will need to convert yourself. That can be done in the class itself using a getter.

String cannot be cast to Integer session Attribute

Hello I am getting this error:
java.lang.ClassCastException: java.lang.String cannot be cast to
java.lang.Integer
at this line of the code:
int est;
est=(Integer) session.getAttribute("estado");
I think that the problem is that "estado" is not filled yet. I use this session-attribubute in order to see if session has been signed in and so that it doesnt need to log in again.
You cannot type-cast here, as Integer is not compatible with String.
Use Integer#parseInt to parse it as an int
est = Integer.parseInt(session.getAttribute("estado"));
The session.getAttribute("estado"); returns the session attribute held in estado, What happened here that, the JVM has found (during runtime) the returned value's type is String so when you tried to cast it into Integer it fired a ClassCastException
What you need here is to parse the result returned by the attribute estado using Integer.parseInt(session.getAttribute("estado"));, which was suggested in the answers
NOTE: you maybe questioning that you have added an integer (not a String) to that attribute, but trace your code carefully considering that request.getParameter("attrName") returns a String, just an assumption
use Integer.parseInt
int est= Integer.parseInt(session.getAttribute("estado").toString());

AzureDocumentDB MongoDB protocol support: Failing to create TTL index

I'm currently using Spring Data MongoDB to abstract MongoDB operations, and using an Azure DocumentDB database with MongoDB protocol support. I've also run into this using the latest MongoDB Java driver by itself.
There is an issue with setting a TTL index in this process.
I'm receiving the following exception.
`Caused by: com.mongodb.CommandFailureException: { "serverUsed" : "****-****-test.documents.azure.com:****" , "_t" : "OKMongoResponse" , "ok" : 0 , "code" : 2 , "errmsg" : "The 'expireAfterSeconds' option has invalid value. Ensure to provide a nonzero positive integer, or '-1'` which means never expire." , "$err" : "The 'expireAfterSeconds' option has invalid value. Ensure to provide a nonzero positive integer, or '-1' which means never expire."}
at com.mongodb.CommandResult.getException(CommandResult.java:76)
at com.mongodb.CommandResult.throwOnError(CommandResult.java:140)
at com.mongodb.DBCollectionImpl.createIndex(DBCollectionImpl.java:399)
at com.mongodb.DBCollection.createIndex(DBCollection.java:597)
This is a simple representation of the POJO that I'm using.
public class Train{
#JsonProperty
private String id;
#JsonProperty("last_updated")
#Indexed(expireAfterSeconds = 1)
private Date lastUpdated;
// Getters & Setters
.
.
.
}
This was my initial approach of initializing the index (via the #Indexed annotation).
I've also attempted to initialize the index via:
mongoTemplate.indexOps(collection.getName())
.ensureIndex(new Index("last_updated", Sort.Direction.DESC)
.expire(1, TimeUnit.SECONDS));
Both ways of setting the index throw that same execption.
I've also seen an error saying that it can only be done on the '_ts' field. I think this is due to Azure DocumentDB using the '_ts' field for it's own TTL operation. So I've tried the following with the same results:
Added a new field, Long '_ts', to the pojo and tried with the annotation.
Attempted to set the index via the ensureIndex method with '_ts' field.
Did the same things above but changing the type of '_ts' to Date.
I'm new to these technologies (DocumentDB and MongoDB), so I'm probably missing something obvious.
Any thoughts?
Revisiting my question I had posted a while back to reply with the solution that I figured out.
Note that DocumentDB has been renamed to CosmosDB since I posted this question.
There was an issue with type casting in either the Spring framework or the CosmosDB/DocumentDB platform side. Despite documentation saying it needs an integer, you actually need to pass it a double value.
I'm using something along the lines of the following and it works
dcoll.createIndex(new BasicDBObject("_ts", 1)
, new BasicDBObject("expireAfterSeconds", 10.0));
This works for me.
db.coll.createIndex( { "_ts": 1 }, { expireAfterSeconds: 3600 } )
Using Spring Boot and Spring Data in a ContextListener:
private final MongoTemplate mongoTemplate;
#EventListener(ContextRefreshedEvent.class)
public void ensureIndexes() {
mongoTemplate.indexOps(YourCollection.class)
.ensureIndex(
new Index()
.on("_ts", Sort.Direction.ASC)
.expire(30, TimeUnit.SECONDS)
);
}
The Azure console is a little confusing in the "Settings" options for the collection, it says "To enable time-to-live (TTL) for your collection/documents, create a TTL index" - it will say this even if you do already have such an index created.
Confirmed working January 2023 with Spring Boot 2.7.6 and Azure CosmosDB.
According to the blog DocumentDB now supports Time-To-Live (TTL) & the section Setting TTL on a document of the offical tutorial Expire data in DocumentDB collections automatically with time to live, the TTL setting on Azure DocumentDB is different from MongoDB, although Azure support do the operater on DocumentDB via MongoDB drive & spring-data in Java.
The TTL should be defined as a property on DocumentDB to set a nonzero positive integer value, so please try to change your code as below.
public class Train{
#JsonProperty
private String id;
#JsonProperty("last_updated")
private Date lastUpdated;
/*
* Define a property as ttl and set the default value 1.
*/
#JsonProperty("ttl")
private int expireAfterSeconds = 1;
// Getters & Setters
.
.
.
}
Hope it helps. Any concern, please feel free to let me know.
Update:
Notice the below content at https://learn.microsoft.com/en-us/azure/documentdb/documentdb-time-to-live#configuring-ttl.
By default, time to live is disabled by default in all DocumentDB collections and on all documents.
So please first enable the feature TIME TO LIVE on Azure portal as the figure below, or follow the above link to enable it programmatically.

SharedPreferences getString NULL parameter

Will I receive an error (Exception) on some devices if I set the second parameter of SharedPreferences.getString NULL?
SharedPreferences settings = ...
String data = settings.getString(_.PREFIX , null);
Will it cause an exception or an error on at least one device? Or I have to wrap this part of code in try-catch block?
If you are asking if you will get an exception if you set the second parameter to null, the answer is no (at least not unless you reference the result without first checking it is not null). The second parameter in the getString() method is the default value (i.e. the value that will be returned if there is nothing found for your prefix. So, it is perfectly acceptable to set null as your default value, as long as you realize (and account for) the fact that the value returned by your getString() could be null.
String data = settings.getString(_.PREFIX , null/Null here is default value/);
null - u can receive when your SraredPreferences have not this item(For example if u call/get this string before setting to this field any info or user clear cash of application from settings of device). I think it's can be normal situation, and u can remove "null" with some default value if you hope to got it(some emum field).
If u don't suppose get null validate data before using.
I thin'k your app must be ready get both variant, because user can change normal workflow.

OData4j 0.7 Exception while retrieving workitems

I am trying to retrieve workitems from TFS Server using OData4j 0.7 in Java.
Here is my code:
public List<TFSWorkItem> getWorkItems(final String projectName)
{
final List<TFSWorkItem> tfsWorkItems = new ArrayList<TFSWorkItem>();
String filter = String.format("Project eq '%s'", projectName);
Enumerable<OEntity> workItems = consumer.getEntities("WorkItems").filter(filter).execute();
for (OEntity workitem : workItems)
{
System.out.println(workitem.getProperty("Title", String.class));
}
}
When I run this code I get a
Exception in thread "main" java.lang.IllegalArgumentException: Illegal datetime format 2013-03-15T14:22:08.077+05:30
at org.odata4j.internal.InternalUtil.parseDateTimeFromXml(InternalUtil.java:96)
On further debugging the code I found that OData4j when trying to map the retrieved date from TFS server finds it incompatible .
Date retrieved from TFS :
2013-03-15T14:22:08.077+05:30
Date expected by OData4j :
2013-03-15T14:22:08.077
Is there a way where I can avoid this?
Updated
For anybody who is facing the same issue.
I have modified my code to :
final String fields = "Id,Project,Title";
Enumerable<OEntity> workItems = consumer.getEntities("WorkItems").filter(filter).select(fields.toString()).execute();
for (OEntity workitem : workItems)
{
System.out.println("Id : " + workitem.getProperty("Id").getValue());
System.out.println("Project : "+workitem.getProperty("Project").getValue());
System.out.println("Title : "+workitem.getProperty("Title").getValue());
}
Since I need only these fields to process I have given a select query to select "Id","Project" and "Title" instead of fetching all fields.
This is a temporary fix unless I find a better solution.
I think I figured this out. Check out this post: OData4J exception
Basically, it boils down to setting the value of an Edm.DateTime column in C# code using DateTime.Now. The OData Producer should be using DateTime.UtcNow.
DateTime.Now includes local time zone information. Microsoft's code sees the local time zone info in the DateTime structure and sends back the Edm.DataTime field formatted as an Edm.DateTimeOffset string. The DateTime.UtcNow property does not include any time zone information, so it is correctly formatted as an Edm.DateTime string when it is sent back to the OData Consumer.
I suspect this might be a bug in Microsoft's WCF Data Services stack or their Entity Framework.

Categories

Resources