Reputation: 3593
When I want a unique key for documents I'm partial to using @Unique(). I like that it's based on username and time.
Is there a way to get that from inside a Java bean?
If not, what's the best way to get a unique number in Java that would not repeat?
Thanks
Upvotes: 5
Views: 1031
Reputation: 816
Yes you can. When you get a handle to Session call evaluate. You can evaluate any formula expressions with this method.
String ID = (String)session.evaluate("@Unique").elementAt(0);
Upvotes: 5
Reputation: 380
The following is the LotusScript code I developed a long time ago as part of my .DominoFramework to reproduce the behavior of @Unique(). You should be able to convert this to Java to get a set of values similar to what you are used to.
Function unique() As String
Dim Index As Integer
Try:
On Error GoTo Catch
Randomize
Unique = ""
For Index% = 1 To 4
Unique$ = Unique$ + Chr$(CInt(Rnd(Index%)*26)+65)
Next Index%
Unique$ = Unique$ + "-"
For Index% = 6 To 11
Unique$ = Unique$ + Chr$(CInt(Rnd(Index%)*26)+65)
Next Index%
Exit Function
Catch:
Stop
DominoException.throw Me, Nothing
Exit Function
End Function
Upvotes: 0
Reputation: 3395
What about this:
public String getUnique() {
try {
return (String) getCurrentSession().evaluate("@Unique").elementAt(0);
} catch (NotesException e) {
return "";
}
}
// retrieve handle to a Notes-Domino object in the bean class
public static Session getCurrentSession() {
FacesContext context = FacesContext.getCurrentInstance();
return (Session) context.getApplication().getVariableResolver()
.resolveVariable(context, "session");
}
It will return a familiar Unique string. Unfortunately with the signature of your server, not the current username when it runs in a browser. I the client it will work as intended.
Upvotes: 0
Reputation: 3355
Russell's answer is correct. But if you need a shorter unique key, you can also try this alternative:
public static String getUnique() {
String CHARLIST = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
long number=System.currentTimeMillis();
int base=CHARLIST.length();
String result="";
while (number > 0){
result = CHARLIST.charAt((int)(number%base))+result;
number = number/base;
}
return result;
}
This is basically converts the number of milliseconds from 1970 to 62-base number. You can even shorten this by getting time since 2012/12/31 or so.
Upvotes: 0
Reputation: 378
This is what I use whenever I need a unique number:
String controlNumber = UUID.randomUUID().toString();
Upvotes: 9