KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > ubermq > util > Utility


1 package com.ubermq.util;
2
3 import EDU.oswego.cs.dl.util.concurrent.*;
4 import java.io.*;
5 import java.nio.*;
6 import java.nio.charset.*;
7 import java.text.*;
8 import java.util.*;
9 import org.apache.log4j.*;
10
11 /**
12  * General-purpose utility functions.
13  */

14 public class Utility
15 {
16     // random # generator
17
private static final Random random;
18
19     // the Uber logger
20
private static final Logger log;
21
22     // LUID numbers
23
private static SynchronizedInt nextInt = new SynchronizedInt(0);
24     private static SynchronizedLong nextLong = new SynchronizedLong(0);
25
26     // encoding information
27
public static final String JavaDoc ENCODING_NAME = "UTF-8";
28     private static final Charset encoding;
29     private static final CharsetEncoder encoder;
30     private static final CharsetDecoder decoder;
31
32
33     // static initializer
34
static
35     {
36         // set up logger
37
log = Logger.getLogger("com.ubermq");
38
39         // set up random # generator
40
try
41         {
42             random = new Random();
43         } catch(Exception JavaDoc x) {
44             log.fatal("", x);
45             throw new Error JavaDoc();
46         }
47
48         // set up charset encoder/decoders
49
encoding = Charset.forName(ENCODING_NAME);
50         encoder = encoding.newEncoder();
51         decoder = encoding.newDecoder();
52
53         // configure the encoders.
54
encoder.onMalformedInput(CodingErrorAction.REPLACE);
55         decoder.onMalformedInput(CodingErrorAction.REPLACE);
56     }
57
58     /**
59      * Displays the contents of a ByteBuffer as a neatly
60      * formatted hex dump (similar to Unix hexdump) to stdout.
61      */

62     public static void outputBuffer(ByteBuffer b)
63     {
64         System.out.println(displayBuffer(b));
65     }
66
67     /**
68      * Formats the contents of a ByteBuffer as a neat
69      * hex dump (similar to Unix hexdump), and returns it.
70      * @return a string containing the formatted buffer contents
71      */

72     public static String JavaDoc displayBuffer(ByteBuffer b)
73     {
74         ByteBuffer bb = b.duplicate();
75         StringBuffer JavaDoc sz = new StringBuffer JavaDoc();
76
77         int n=0;
78         bb.rewind();
79         while(bb.hasRemaining())
80         {
81             int v = bb.get() & 0xFF;
82             sz.append(((v <= 15) ? "0" : "") + Integer.toHexString(v).toUpperCase() + " ");
83             if (0 == (++n % 16)) sz.append("\n");
84         }
85
86         return sz.toString();
87     }
88
89     /**
90      * Generates a LUID (locally unique identifier).
91      *
92      * @return an integer that is guaranteed to be different from the result
93      * of another call to this method within the same JVM.
94      */

95     public static int allocateLocallyUniqueInt()
96     {
97         return nextInt.increment();
98     }
99
100     /**
101      * Generates a LUID (locally unique identifier).
102      *
103      * @return a long that is guaranteed to be different from the result
104      * of another call to this method within the same JVM.
105      */

106     public synchronized static long allocateLocallyUniqueLong()
107     {
108         return nextLong.increment();
109     }
110
111     /**
112      * Generates a pseudo-GUID.
113      *
114      * @return a long that has a low probability of being returned by another
115      * invocation of this method across all processes.
116      */

117     public static long allocateGloballyUniqueLong()
118     {
119         return ( (long)(random.nextInt() << 32) + (int)(System.currentTimeMillis() & 0xFFFFFFFF));
120     }
121
122     /**
123      * Encodes a String into an existing ByteBuffer using the standard
124      * UberMQ encoding.
125      *
126      * @see com.ubermq.Utility.ENCODING_NAME
127      * @param sz the string to encode
128      * @param out the buffer to output the String into.
129      */

130     public static void encode(String JavaDoc sz, ByteBuffer out)
131     {
132         synchronized(encoder)
133         {
134             encoder.reset();
135             if (encoder.encode(CharBuffer.wrap(sz), out, true) == CoderResult.OVERFLOW)
136                 throw new BufferOverflowException();
137             if (encoder.flush(out) == CoderResult.OVERFLOW)
138                 throw new BufferOverflowException();
139         }
140     }
141
142     /**
143      * Encodes a String into a newly allocated ByteBuffer using the standard
144      * UberMQ encoding.
145      *
146      * @see com.ubermq.Utility.ENCODING_NAME
147      * @param sz the string to encode
148      * @return a new ByteBuffer containing the encoded string
149      */

150     public static ByteBuffer encode(String JavaDoc sz)
151     {
152         // TODO: optimize this method to keep an LRU
153
// cache of encoded byte sequences. We end up
154
// performing the same encodings multple times
155
// unnecessarily, esp. on servers.
156
synchronized(encoder)
157         {
158             try
159             {
160                 return encoder.encode(CharBuffer.wrap(sz));
161             }
162             catch (CharacterCodingException e) {
163                 return ByteBuffer.allocate(0);
164             }
165         }
166     }
167
168     /**
169      * Encodes a char sequence from a ByteBuffer using the
170      * standard UberMQ encoding.<p>
171      *
172      * @see com.ubermq.Utility.ENCODING_NAME
173      * @param szb a byte buffer containing a character sequence.
174      * @return a character buffer containing the decoded string.
175      */

176     public static CharBuffer decode(ByteBuffer szb)
177     {
178         // TODO: optimize this method to keep an LRU
179
// cache of decoded byte sequences. We end up
180
// performing the same decodings multple times
181
// unnecessarily.
182
synchronized(decoder)
183         {
184             try
185             {
186                 return decoder.decode(szb);
187             }
188             catch(CharacterCodingException cee)
189             {
190                 getLogger().error("", cee);
191                 return CharBuffer.allocate(0);
192             }
193         }
194     }
195
196     public static final String JavaDoc escapeForHTML(String JavaDoc text)
197     {
198         return text.replaceAll("&", "&amp;")
199                 .replaceAll("<", "&lt;")
200                 .replaceAll(">", "&gt;")
201                 .replaceAll("\"", "&quot;");
202     }
203
204     /**
205      * Obtains a logger instance.
206      *
207      * @return the logger used for UberMQ.
208      * @deprecated You should use your own logger for your class.
209      */

210     public static final Logger getLogger()
211     {
212         return log;
213     }
214
215     /**
216      * Formats log messages to look like log4j, in a more compact single line
217      * format than Sun's ugly SimpleFormatter.
218      */

219     private static class UberFormatter
220         extends java.util.logging.Formatter JavaDoc
221     {
222         private static final DateFormat df = new SimpleDateFormat("dd MMM yy HH:mm:ss.SSS");
223
224         /**
225          * Format the given log record and return the formatted string.
226          * <p>
227          * The resulting formatted String will normally include a
228          * localized and formated version of the LogRecord's message field.
229          * The Formatter.formatMessage convenience method can (optionally)
230          * be used to localize and format the message field.
231          * <p>
232          * for example:<br>
233          * LEVEL,date/time,class:line,msg
234          *
235          * @param record the log record to be formatted.
236          * @return the formatted log record
237          */

238         public String JavaDoc format(java.util.logging.LogRecord JavaDoc record)
239         {
240             String JavaDoc className = record.getSourceClassName();
241
242             StringBuffer JavaDoc fmt = new StringBuffer JavaDoc();
243             fmt.append(record.getLevel());
244             fmt.append(" ");
245             synchronized(df) {
246                 fmt.append(df.format(new Date(record.getMillis())));
247             }
248             fmt.append(" ");
249             fmt.append(className.substring(className.lastIndexOf('.')+1));
250             fmt.append(".");
251             fmt.append(record.getSourceMethodName());
252             fmt.append(" ");
253
254             if (record.getThrown() != null) {
255                 StringWriter sw = new StringWriter();
256                 record.getThrown().printStackTrace(new PrintWriter(sw));
257                 fmt.append(sw.toString());
258             } else {
259                 fmt.append(record.getMessage());
260             }
261
262             fmt.append("\n");
263
264             return fmt.toString();
265         }
266     }
267 }
268
Popular Tags