Validate hibernate date as long - java

I want to validate a date in Long type to be greater than the current time.
I've seen #Past, #Future and so on... but It is not applicable to Long data type.
I'm looking for something like this:
#FutureOrPresent
private Long dateStart;
#Future
private Long dateEnd;
But working for Long values.
How can I validate date > System.currentTimeMillis() ?
Thanks in advance.

In case you want to use existing constraint annotations but the types (Long in your case) on which you want to apply them are not supported you need to:
Create your own implementation of ConstraintValidator, for example:
public class FutureLongValidator implements ConstraintValidator<Future, Long> {
public boolean isValid(Long value, ConstraintValidatorContext context) {
if ( value == null ) {
return true;
}
return value > System.currentTimeMillis();
}
}
Then register it so that HV knows about it and can use it for validation. There are a few ways how this can be done. I'd suggest using the ServiceLoader approach. To do that a file META-INF/services/javax.validation.ConstraintValidator must be created and the fully qualified name of the validator added to it:
some.package.FutureLongValidator
some.package.FutureOrPresentLongValidator
for a more detailed instructions and a sample project check out this post that covers the topic in details - Adding custom constraint definitions via the Java service loader

Related

Mockito when checking for specific object property value

I have the following in a working test:
when(client.callApi(anyString(), isA(Office.class))).thenReturn(responseOne);
Note that client is a Mock of class Client.
I want to change "isA(Office.class)" to tell it to match where the "id" property of an Office instance is "123L". How can I specify that I want a specific argument value in the method of a mocked object?
Edit: Not a duplicate because I'm trying to use it on a "when" and the linked question (and other resources I've found) are using ArgumentCaptor and ArgumentMatcher on "verify" and "assert". I'm thinking I can't actually do what I'm trying and will try out another way. Of course, I'm willing to be shown otherwise.
Reopening as requested, but the solution (use an ArgumentMatcher) is identical to the one in the linked answer. Naturally, you can't use an ArgumentCaptor when stubbing, but everything else is the same.
class OfficeWithId implements ArgumentMatcher<Office> {
long id;
OfficeWithId(long id) {
this.id = id;
}
#Override public boolean matches(Office office) {
return office.id == id;
}
#Override public String toString() {
return "[Office with id " + id + "]";
}
}
when(client.callApi(anyString(), argThat(new IsOfficeWithId(123L)))
.thenReturn(responseOne);
Because ArgumentMatcher has a single method, you can even make it a lambda in Java 8:
when(client.callApi(anyString(), argThat(office -> office.id == 123L))
.thenReturn(responseOne);
If you're already using Hamcrest, you can adapt a Hamcrest matcher using MockitoHamcrest.argThat, or use the built-in hasProperty:
when(client.callApi(
anyString(),
MockitoHamcrest.argThat(
hasProperty("id", equalTo(123L)))))
.thenReturn(responseOne);
I ended up going with "eq". This was ok in this case because the objects are pretty simple. First I created an object that is the same as what I expect to get back.
Office officeExpected = new Office();
officeExpected.setId(22L);
Then my 'when' statement becomes:
when(client.callApi(anyString(), eq(officeExpected))).thenReturn(responseOne);
This allows me to have better checking than "isA(Office.class)".
adding an answer for anyone with a more complex object.
answer from OP uses eq which works for simple objects.
However, I had a more complex object with many more fields. Its quite painful to create Mock object and fill in all the fields
public class CreateTenantRequest {
#NotBlank private String id;
#NotBlank private String a;
#NotBlank private String b;
...
...
}
I was able to use refEq to achieve the same thing without setting a value of each field.
Office officeExpected = new Office();
officeExpected.setId(22L);
verify(demoMock, Mockito.atLeastOnce()).foobarMethod(refEq(officeExpected, "a", "b"));

Guava cache: how to set expiration on 'CacheLoader.load()' instead of during CacheBuilder.newBuilder()?

I am trying to create a cache using guava cache library. One my main requirement is that I want to set the cache expiry after the CacheLoader.load(..) function instead of something most of the examples I encountered on the web, like the one below.
LoadingCache<String, MyClass> myCache =
CacheBuilder.newBuilder().maximumSize(MAX_SIZE).expireAfterWrite(10, TimeUnit.Minutes).build(cacheLoader);
The reason for this is that the object retrieved from the database by the CacheLoader.load(...) function contains the expiration data. So I want to use this information instead of some "random" static value.
I want something like this.
LoadingCache<String, MyClass> myCache =
CacheBuilder.newBuilder().maximumSize(MAX_SIZE).build(cacheLoader);
...
CacheLoader meCacheLoder = new CacheLoader<String MyClass>(){
#Override
public MyClass load(String key) throws Exception {
// Retrieve the MyClass object from database using 'key'
MyClass myObj = getMyObjectFromDb(key);
int expiry = myObj.getExpiry();
// Now somehow set this 'expiry' value with the cache
????
return myObj;
}
};
OR
Is there any better option available than Guava cache for this purpose?
There is no such feature in Guava, as Louis already pointed out.
For example you can use EHCache or cache2k. For cache2k I can give you quick directions since this is a core feature we use regularly:
You can either implement the interface ValueWithExpiryTime on your value object, which is:
interface ValueWithExpiryTime {
long getCacheExpiryTime();
}
Or, you can register a EntryExpiryCalculator to extract the time value. The cache is build as follows:
Cache<Key, Value> cache =
CacheBuilder.newCache(Key.class, Value.class)
.expiryCalculator(new EntryExpiryCalculator<Key, Value>() {
#Override
public long calculateExpiryTime(
final Key key, final Value value,
final long loadTime, final CacheEntry<Key, Value> oldEntry) {
return value.getExpiry();
}
}
)
.build();
The time is the standard long type represented in milliseconds since the epoch. By default the expiry will happen not exactly at the specified time, but zero or a few milliseconds later, depending on your machine load. This is the most effective mode. If this is a problem, add sharpExpiry(true).
Disclaimer: I am the author of cache2k....

When to use Long vs long in java?

Below is my Interface -
public interface IDBClient {
public String read(ClientInput input);
}
This is my Implementation of the Interface -
public class DatabaseClient implements IDBClient {
#Override
public String read(ClientInput input) {
}
}
Now I have a factory which gets the instance of DatabaseClient like this -
IDBClient client = DatabaseClientFactory.getInstance();
....
Now I need to make a call to read method of my DatabaseClient which accepts the ClientInput parameter and below is the class for the same. This class was not written by me so that is the reason I am having a question on this and I am pretty much sure this is the wrong way of doing it.
public final class ClientInput {
private Long userid;
private Long clientid;
private Long timeout_ms = 20L;
private boolean debug;
private Map<String, String> parameterMap;
public ClientInput(Long userid, Long clientid, Map<String, String> parameterMap, Long timeout_ms, boolean debug) {
this.userid = userid;
this.clientid = clientid;
this.parameterMap = parameterMap;
this.timeout_ms = timeout_ms;
this.debug = debug;
}
}
So when customer make a call to read method of DatabaseClient, they will create the ClientInput parameter like this and then use the factory to get the Instance of DatabaseClient and then call the read method accordingly.
Map<String, String> paramMap = new HashMap<String, String>();
paramMap.put("attribute", "segmentation");
ClientInput input = new ClientInput(109739281L, 20L, paramMap, 1000L, true);
IDBClient client = DatabaseClientFactory.getInstance();
client.read(input);
Problem Statement:-
So my first question is does the userid, clientid, timeout_ms should be Long object or just simply long in ClientInput class?
Second question I have is, it might be possible that customer can pass wrong information such as negative user ids, negative client id, negative timeout value etc etc.. Then where I should do this validation? Should I do this validation check in the constructor of ClientInput class or at some other place? What's the better way of doing this and how should I do the validation?
long is a primitive, which must have a value. Simple.
Long is an object, so:
it can be null (meaning whatever you like, but "unknown" is a common interpretation)
it can be passed to a method that accepts an Object, Number, Long or long parameter (the last one thanks to auto-unboxing)
it can be used as a generic parameter type, ie List<Long> is OK, but List<long> is not OK
it can be serialized/deserialized via the java serialization mechanism
Always use the simplest thing that works, so if you need any of the features of Long, use Long otherwise use long. The overhead of a Long is surprisingly small, but it is there.
I don't think there's a single correct answer. A few suggestions:
The biggest difference I see between long and Long in this context is that Long may be null. If there's a possibility you might have missing values, the Long object will be helpful as null can indicate missing values. If you're using primitives, you'll have to use some special value to indicate missing, which is probably going to be a mess. Speed or size is not likely to be an issue unless you're planning on making an array of a million of these things and then serializing.
My preference for validation logic is to throw some sort of custom ValidationException at the point at which the thing could fail. If you're just creating these things with a constructor, the simplest thing would be just to validate there, e.g.
public ClientInput(Long userid, Long clientid, Map<String, String> parameterMap, Long timeout_ms, boolean debug) throws ValidationException {
if (userid == null) throw new ValidationException("UserId is required");
...etc, etc...
}
Ultimately, the ValidationException is only useful if you can catch it at a point where you can do something useful with it - echo it back to a user or whatever.
1 Long is the object orientated counter part of long. The difference is as follows, and it applies to Float to float, Integer to integer etc.
long is a primitive type, while Long is a Java class (and so it will inherit Object).
long must be assigned with a valid number, while Long can be null
long instances can't use the benefits of OO, while instances of Long are real Java objects
Long is a serializable so it will be very useful when doing file, database or network IO
long is more efficient than Long considering memory space and processing speed
If you are doing heavy calculations, use primitive types. Otherwise if you're concerning more about design, the object counter parts will be very useful.
2 Since you are not using any frameworks if I'm observing correctly, I suggest you make an interface like Validated with a method bool validate(). And every time you try to put a input into the database call validate in advance.
1) Use Long if you need to treat the value as an object. Use long otherwise; it's more efficient.
2) Judgement call, really. Putting it deeper means you're going to check even when the value is coming from a source you trust, but that may catch errors in other code. Putting it closer to the user input means you lose that deep sanity-check (and may need to check in more than one place) but avoids spending time checking things you've already checked. What's best depends on how you plan on using/enhancing this code in the future.
As Long is wrapper class privimitive type long and Long is a class, which indicate its instance could be null. In my perspective use wrapper class is better than primitive type because there could have null state in it, which could tells us more information.
In addition, wrapper class will automatically initialized with 0, it is good for lazy using.
For data validation, I think you'd better do it in controller rather than DAO, then have a good method to handle this or alert user to modify them!
The advantage of the Long class is that the value can be null. In your case, if no Long ID is supplied, if you quickly detect this with something like..
public ClientInput(Long userid, Long clientid, Map<String, String> parameterMap, Long timeout_ms, boolean debug) {
if (userid == null) {
throw new IllegalArgumentException("userid is null");
}
To your second question, you could place your ID validation in the constructor as well. This ensures that if the ID is null or invalid, a ClientInput can never be created. But there is no "best" answer for where you put this validation, it depends on the structure of the rest of your code, but ideally you want to catch such things as early as possible.
public ClientInput(Long userid, Long clientid, Map<String, String> parameterMap, Long timeout_ms, boolean debug) {
if (userid == null || userid < USER_ID_MIN || userid > USER_ID_MAX ) {
throw new IllegalArgumentException("userid is invalid");
}
Another option is to accept the userid parameter as a Long, testing it for null, but then store it as a private, primitive long, once you know its valid.
I try to keep Bean objects as simple as possible, which would mean handling validation elsewhere - either in a separate Validator class or in a validate() method. The general algorithm is the same:
validateInputParametres()
readDb()
I would do something like:
final ClientInput input = new ClientInput(109739281L, 20L, paramMap, 1000L, true);
validate(input); // throw/handle exceptions here
final Map<String, String> paramMap = new HashMap<String, String>();
paramMap.put("attribute", "segmentation");
final IDBClient client = DatabaseClientFactory.getInstance();
client.read(input);
People forgot to mention that long cannot be used in logical comparison because its contains string in it, simple logical conditions wont work like == ,!= , >, < to do this you have to use compareTo() function that comes with Long object class.

Best practice for storing global data in J2EE App using Hibernate

I'm looking for the best solution to store Java EE application's global data using Hibernate. It will consist of key value pairs. Example:
projectStarted = "10-11-11"
developerNumber = 3
teamLeader = "John"
As you see, all of this entries have different types.
For now I see two options:
1) Create GlobalData entity. Each field of it will be represented as unique column in the table and will contain unique setting. This way I have no problems with type casting, but I would like to avoid it in case where there will be big amount of settings.
2) Create Setting entity. Each of it will contain two fields: key(Primary key) and value and will be represented as unique record in the table. This is preferable solution, but It's seems to me that I will get a lot of type casting, because settings can be any type.
So basically, I'm looking for the way to implement second solution without getting a lot of troubles from different types. Can anybody help me?
Thanks.
Edit 1.
Yeah, thanks Christian. Just got similar idea.
What if I will have Settings entity, which will be like:
#Entity
#Table(name = "settings")
public class Setting {
#Column
private String key;
#Column
private String value;
#Column
private String converterClassFullName; //example by.lugovsky.MyConverter
//Getters, setters
}
And GlobalData class.
public class GlobalData {
private Date projectStarted;
private int developerNumber;
private String teamLeader;
Set<Setting> settings;
//Getters and setters for all, except settings.
}
So basically my idea is to convert Setting entity before persisting/updating/ etc. I can do this in my DAO, but I was wondering, if I could annotate GlobalData class with #Entity annotation as well without creating new table. This way I can set OneToMany annotation to Setting's set and Perform conversions in the internal #PrePersist etc. methods.
Will Hibernate allow me to do this?
Thanks again
You could store a Converter-Class into the db and the let it run through the given converter for a property before using the value. JSF offers Converter API:
public interface Converter{
public Object getAsObject(FacesContext fc, UIComponent component, String value) throws ConverterException;
public String getAsString(FacesContext fc, UIComponent component, Object obj) throws ConverterException;
}
If you have a schema with
name: String
value: String
converter: Class
then you could do something like this:
PropertyEntry pe = // Get from OR-Mapper
Converter c = (Converter) pe.getConverter().newInstance();
Object o = c.getAsObject(null, null, pe.getValue());
// use the object o instead of value
For even more coolness you could also define a field in the class which will not be persisted which you could use to hold the converted value within the object.

How to express "never" with java.util.Date?

I have a class with the fields "deletionDate" and "experiationDate" which could both be undefined, what would mean that the object is whether deleted nor has an expiration date.
My first approach was:
private Date deletionDate = null; // null means not deleted
Having the book "Clean Code" in mind I remember to better use expressive names instead of comments. So my current solutions is:
private static final Date NEVER = null;
private Date deletionDate = NEVER;
I could user a wrapper class around Date, but that would complicate JPA mapping.
What do you think of it? How would you express "never"?
well never is never, not the 1/1/2999.
I would stay with your 1st solution. a Null date means it has not yet happened.
maybe you can wrap it with something like :
boolean isNeverDeleted(){
return deletionDate == null;
}
You can think about null date as "not available" or "not applicable". If that's the case "NO DATE" is fine for "never".
Don't subtype Date only for a very exquisite style requirement.
A better option is to add semantic to your model object. If your have a Thing object with a deletionDate property you can do:
class Thing
+ deletionDate
+ isNeverDeleted: boolean { return deletionDate == null; }
and it will be practical and documentative, both in the class and in your client code:
if(myThing.isNeverDeleted())
I consider null appropriate. It clearly indicates "not set".
Depending on how complicated you want to get, though, you could have a Enum and have some state like 'NeverExpires' as the 'UserState' (or whatever it is you're representing). This is probably preferable, but could be uselessly complex, depending on what your system.
Let the default value be treated as "never"
I would just choose a far-future date as the value for the constant NEVER. Then to check for deletion/expiry, just compare against NEVER.
I would not use Date but timestamps, using -1 for never and 0 for immediately;
public static final long IMMEDIATE = 0;
public static final long NEVER = -1L;
private long expires = NEVER;
interpretation of the attribute should be in a getter, like:
public boolean isExpired() {
return (NEVER == expires) ? false : (expires < System.currentTimeMillies());
}
Deletion follows the same pattern.
Update I know that 0 and -1 are valid timestamps, but as expiration and deletion of files and other resources rarely (never say never :-)) happen in 1970 or before, it is a useful constant, imho.

Categories

Resources