001    package opendreams.proxy;
002    
003    /**
004     * A classe <code>TStamp</code> representa um time stamp unico no
005     * sistema.
006     */
007    public class TStamp {
008      private final int NCHARS = 9; /* Numero de caractres da string de tempo */
009      /*
010       * String de conversao <=> Base64 Encoding Table
011       * 
012       * Referencia: http://www.faqs.org/rfcs/rfc3548.html
013       * 
014       * The "URL and Filename safe" Base 64 Alphabet
015       * 
016       * Value Encoding Value Encoding Value Encoding Value Encoding
017       * 0 A 17 R 34 i 51 z
018       * 1 B 18 S 35 j 52 0
019       * 2 C 19 T 36 k 53 1
020       * 3 D 20 U 37 l 54 2
021       * 4 E 21 V 38 m 55 3
022       * 5 F 22 W 39 n 56 4
023       * 6 G 23 X 40 o 57 5
024       * 7 H 24 Y 41 p 58 6
025       * 8 I 25 Z 42 q 59 7
026       * 9 J 26 a 43 r 60 8
027       * 10 K 27 b 44 s 61 9
028       * 11 L 28 c 45 t 62 - (minus)
029       * 12 M 29 d 46 u 63 _ (understrike)
030       * 13 N 30 e 47 v
031       * 14 O 31 f 48 w
032       * 15 P 32 g 49 x
033       * 16 Q 33 h 50 y
034       */
035      private final String str_conv =
036        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
037    
038      private static Long lastStamp = 0l;
039    
040      private String uniq_id;
041      private long tstamp;
042    
043      @Override
044      public String toString() {
045        return uniq_id;
046      }
047    
048      public long toLong() {
049        return tstamp;
050      }
051    
052      public TStamp() {
053        this.tstamp = System.currentTimeMillis(); // PASSAR PARA us (Java 1.5)
054    
055        synchronized (lastStamp) {
056          if (tstamp <= lastStamp) {
057            tstamp = ++lastStamp;
058          }
059        }
060        this.uniq_id = "";
061        /*
062         * Cada caracter corresponde a 6 bits
063         * O primeiro caracter corresponde aos 6 bits mais significativos
064         */
065        long tempo_us = tstamp;
066        for (int i = NCHARS - 1; i >= 0; i--) {
067          /* 0x3F hex = 63 dec = 00111111 bin */
068          uniq_id = str_conv.charAt((int) (tempo_us & 0x3F)) + uniq_id;
069          tempo_us = tempo_us >> 6;
070        }
071      }
072    
073      public TStamp(String uniq_id) {
074        /*
075         * Zera o numero que contem o timestamp em usec
076         */
077        this.uniq_id = uniq_id;
078        tstamp = 0;
079    
080        /*
081         * Transforma da base64 p/ base10
082         */
083        for (int i = 0; i < NCHARS; i++) {
084          tstamp = tstamp << 6;
085          for (int j = 0; j <= 63; j++)
086            if (uniq_id.charAt(i) == str_conv.charAt(j)) {
087              tstamp = tstamp + j;
088              break;
089            }
090        }
091      }
092    }