KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > freecs > util > CookieGenerator


1 /**
2  * Copyright (C) 2003 Manfred Andres
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
17  */

18 package freecs.util;
19
20 import freecs.core.*;
21
22 public class CookieGenerator {
23    private static int COOKIE_LENGTH = 32;
24
25    private CookieGenerator () {
26       // not instanciable
27
}
28
29     /**
30      * Ceckfunction to check the validity of a FreeCS-Cookie
31      * FIXME: has to get better (e.g. include ip-address)
32      * @param cookie
33      * @return boolean true if cookie is valid, false if not
34      */

35     public static boolean checkValidity (String JavaDoc cookie) {
36         if (cookie == null || cookie.length() != COOKIE_LENGTH)
37             return false;
38         return true;
39     }
40
41    public static String JavaDoc generateCookie () {
42       String JavaDoc cval = "";
43       for (boolean ok = false; !ok; ) {
44          StringBuffer JavaDoc c = new StringBuffer JavaDoc ();
45          while (c.length () < COOKIE_LENGTH) {
46             char x = (char) Math.ceil(Math.random() * 34);
47             if (x < 10) x = (char) (x + 48);
48             else x = (char) (x + 87);
49             c.append(x);
50          }
51          cval = c.toString ();
52          User u = UserManager.mgr.getUserByCookie (cval);
53          if (u != null) continue;
54          ok = true;
55       }
56       return cval;
57    }
58
59    public static void main (String JavaDoc args[]) {
60       System.out.println ("generating cookie");
61       long start = System.currentTimeMillis();
62       for (int i = 0; i < 100000; i++) {
63          String JavaDoc c = generateCookie ();
64       }
65       StringBuffer JavaDoc tsb = new StringBuffer JavaDoc ("spent ").append ((System.currentTimeMillis () - start)).append (" millis");
66       System.out.println (tsb.toString ());
67       System.out.println ("cookie generated");
68    }
69 }
Popular Tags