KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > compiere > util > Util


1 /******************************************************************************
2  * The contents of this file are subject to the Compiere License Version 1.1
3  * ("License"); You may not use this file except in compliance with the License
4  * You may obtain a copy of the License at http://www.compiere.org/license.html
5  * Software distributed under the License is distributed on an "AS IS" basis,
6  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
7  * the specific language governing rights and limitations under the License.
8  * The Original Code is Compiere ERP & CRM Business Solution
9  * The Initial Developer of the Original Code is Jorg Janke and ComPiere, Inc.
10  * Portions created by Jorg Janke are Copyright (C) 1999-2001 Jorg Janke, parts
11  * created by ComPiere are Copyright (C) ComPiere, Inc.; All Rights Reserved.
12  * Contributor(s): ______________________________________.
13  *****************************************************************************/

14 package org.compiere.util;
15
16 import java.awt.Color JavaDoc;
17 import java.awt.font.TextAttribute JavaDoc;
18 import java.text.AttributedCharacterIterator JavaDoc;
19 import java.text.AttributedString JavaDoc;
20 import java.util.HashSet JavaDoc;
21 import java.util.Iterator JavaDoc;
22 import java.util.Map JavaDoc;
23 import java.util.Set JavaDoc;
24
25 /**
26  * General Utilities
27  *
28  * @author Jorg Janke
29  * @version $Id: Util.java,v 1.12 2003/09/27 11:13:28 jjanke Exp $
30  */

31 public class Util
32 {
33     /**
34      * Replace String values.
35      * @param value string to be processed
36      * @param oldPart old part
37      * @param newPart replacement
38      * @return String with replaced values
39      */

40     public static String JavaDoc replace (String JavaDoc value, String JavaDoc oldPart, String JavaDoc newPart)
41     {
42         if (value == null || value.length() == 0
43             || oldPart == null || oldPart.length() == 0)
44             return value;
45         //
46
int oldPartLength = oldPart.length();
47         String JavaDoc oldValue = value;
48         StringBuffer JavaDoc retValue = new StringBuffer JavaDoc();
49         int pos = oldValue.indexOf(oldPart);
50         while (pos != -1)
51         {
52             retValue.append(oldValue.substring(0, pos));
53             if (newPart != null && newPart.length() > 0)
54                 retValue.append(newPart);
55             oldValue = oldValue.substring(pos+oldPartLength);
56             pos = oldValue.indexOf(oldPart);
57         }
58         retValue.append(oldValue);
59     // Log.trace(Log.l5_DData, "Env.replace - " + value + " - Old=" + oldPart + ", New=" + newPart + ", Result=" + retValue.toString());
60
return retValue.toString();
61     } // replace
62

63     /**
64      * Remove CR / LF from String
65      * @param in input
66      * @return cleaned string
67      */

68     public static String JavaDoc removeCRLF (String JavaDoc in)
69     {
70         char[] inArray = in.toCharArray();
71         StringBuffer JavaDoc out = new StringBuffer JavaDoc (inArray.length);
72         for (int i = 0; i < inArray.length; i++)
73         {
74             char c = inArray[i];
75             if (c == '\n' || c == '\r')
76                 ;
77             else
78                 out.append(c);
79         }
80         return out.toString();
81     } // removeCRLF
82

83
84     /**
85      * Mask HTML content.
86      * i.e. replace characters with &values;
87      * @param content content
88      * @return masked content
89      */

90     public static String JavaDoc maskHTML (String JavaDoc content)
91     {
92         if (content == null || content.length() == 0 || content.equals(" "))
93             return "&nbsp";
94         //
95
String JavaDoc temp = replace (content, "<", "&lt;");
96         temp = replace (temp, ">", "&gt;");
97         temp = replace (temp, "\"", "&quot;");
98         temp = replace (temp, "&", "&amp;");
99         return temp;
100     } // maskHTML
101

102     /**
103      * Get the number of occurances of countChar in string.
104      * @param string String to be searched
105      * @param countChar to be counted character
106      * @return number of occurances
107      */

108     public static int getCount (String JavaDoc string, char countChar)
109     {
110         if (string == null || string.length() == 0)
111             return 0;
112         int counter = 0;
113         char[] array = string.toCharArray();
114         for (int i = 0; i < array.length; i++)
115         {
116             if (array[i] == countChar)
117                 counter++;
118         }
119         return counter;
120     } // getCount
121

122     /*************************************************************************/
123
124     /**
125      * Find index of search character in str.
126      * This ignores content in () and 'texts'
127      * @param str string
128      * @param search search character
129      * @return index or -1 if not found
130      */

131     public static int findIndexOf (String JavaDoc str, char search)
132     {
133         return findIndexOf(str, search, search);
134     } // findIndexOf
135

136     /**
137      * Find index of search characters in str.
138      * This ignores content in () and 'texts'
139      * @param str string
140      * @param search1 first search character
141      * @param search2 second search character (or)
142      * @return index or -1 if not found
143      */

144     public static int findIndexOf (String JavaDoc str, char search1, char search2)
145     {
146         if (str == null)
147             return -1;
148         //
149
int endIndex = -1;
150         int parCount = 0;
151         boolean ignoringText = false;
152         int size = str.length();
153         while (++endIndex < size)
154         {
155             char c = str.charAt(endIndex);
156             if (c == '\'')
157                 ignoringText = !ignoringText;
158             else if (!ignoringText)
159             {
160                 if (parCount == 0 && (c == search1 || c == search2))
161                     return endIndex;
162                 else if (c == ')')
163                         parCount--;
164                 else if (c == '(')
165                     parCount++;
166             }
167         }
168         return -1;
169     } // findIndexOf
170

171     /**
172      * Find index of search character in str.
173      * This ignores content in () and 'texts'
174      * @param str string
175      * @param search search character
176      * @return index or -1 if not found
177      */

178     public static int findIndexOf (String JavaDoc str, String JavaDoc search)
179     {
180         if (str == null || search == null || search.length() == 0)
181             return -1;
182         //
183
int endIndex = -1;
184         int parCount = 0;
185         boolean ignoringText = false;
186         int size = str.length();
187         while (++endIndex < size)
188         {
189             char c = str.charAt(endIndex);
190             if (c == '\'')
191                 ignoringText = !ignoringText;
192             else if (!ignoringText)
193             {
194                 if (parCount == 0 && c == search.charAt(0))
195                 {
196                     if (str.substring(endIndex).startsWith(search))
197                         return endIndex;
198                 }
199                 else if (c == ')')
200                         parCount--;
201                 else if (c == '(')
202                     parCount++;
203             }
204         }
205         return -1;
206     } // findIndexOf
207

208     /*************************************************************************/
209
210     /**
211      * Return Hex String representation of byte b
212      * @param b byte
213      * @return Hex
214      */

215     static public String JavaDoc toHex (byte b)
216     {
217         char hexDigit[] = {
218             '0', '1', '2', '3', '4', '5', '6', '7',
219             '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
220         };
221         char[] array = { hexDigit[(b >> 4) & 0x0f], hexDigit[b & 0x0f] };
222         return new String JavaDoc(array);
223     }
224
225     /**
226      * Return Hex String representation of char c
227      * @param c character
228      * @return Hex
229      */

230     static public String JavaDoc toHex (char c)
231     {
232         byte hi = (byte) (c >>> 8);
233         byte lo = (byte) (c & 0xff);
234         return toHex(hi) + toHex(lo);
235     } // toHex
236

237     /*************************************************************************/
238
239     /**
240      * Init Cap Words With Spaces
241      * @param in string
242      * @return init cap
243      */

244     public static String JavaDoc initCap (String JavaDoc in)
245     {
246         if (in == null || in.length() == 0)
247             return in;
248         //
249
boolean capitalize = true;
250         char[] data = in.toCharArray();
251         for (int i = 0; i < data.length; i++)
252         {
253             if (data[i] == ' ' || Character.isWhitespace(data[i]))
254                 capitalize = true;
255             else if (capitalize)
256             {
257                 data[i] = Character.toUpperCase (data[i]);
258                 capitalize = false;
259             }
260             else
261                 data[i] = Character.toLowerCase (data[i]);
262         }
263         return new String JavaDoc (data);
264     } // initCap
265

266     /*************************************************************************/
267
268     /**
269      * Return a Iterator with only the relevant attributes.
270      * Fixes implementation in AttributedString, which returns everything
271      * @param aString attributed string
272      * @param relevantAttributes relevant attributes
273      * @return iterator
274      */

275     static public AttributedCharacterIterator JavaDoc getIterator (AttributedString JavaDoc aString, AttributedCharacterIterator.Attribute JavaDoc[] relevantAttributes)
276     {
277         AttributedCharacterIterator JavaDoc iter = aString.getIterator();
278         Set JavaDoc set = iter.getAllAttributeKeys();
279     // System.out.println("AllAttributeKeys=" + set);
280
if (set.size() == 0)
281             return iter;
282         // Check, if there are unwanted attributes
283
Set JavaDoc unwanted = new HashSet JavaDoc(iter.getAllAttributeKeys());
284         for (int i = 0; i < relevantAttributes.length; i++)
285             unwanted.remove(relevantAttributes[i]);
286         if (unwanted.size() == 0)
287             return iter;
288
289         // Create new String
290
StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
291         for (char c = iter.first(); c != AttributedCharacterIterator.DONE; c = iter.next())
292             sb.append(c);
293         aString = new AttributedString JavaDoc(sb.toString());
294
295         // copy relevant attributes
296
Iterator JavaDoc it = iter.getAllAttributeKeys().iterator();
297         while (it.hasNext())
298         {
299             AttributedCharacterIterator.Attribute JavaDoc att = (AttributedCharacterIterator.Attribute JavaDoc)it.next();
300             if (!unwanted.contains(att))
301             {
302                 for (char c = iter.first(); c != AttributedCharacterIterator.DONE; c = iter.next())
303                 {
304                     Object JavaDoc value = iter.getAttribute(att);
305                     if (value != null)
306                     {
307                         int start = iter.getRunStart(att);
308                         int limit = iter.getRunLimit(att);
309                     // System.out.println("Attribute=" + att + " Value=" + value + " Start=" + start + " Limit=" + limit);
310
aString.addAttribute(att, value, start, limit);
311                         iter.setIndex(limit);
312                     }
313                 }
314             }
315         // else
316
// System.out.println("Unwanted: " + att);
317
}
318         return aString.getIterator();
319     } // getIterator
320

321
322     /**
323      * Dump a Map (key=value) to out
324      * @param map Map
325      */

326     static public void dump (Map JavaDoc map)
327     {
328         System.out.println("Dump Map - size=" + map.size());
329         Iterator JavaDoc it = map.keySet().iterator();
330         while (it.hasNext())
331         {
332             Object JavaDoc key = it.next();
333             Object JavaDoc value = map.get(key);
334             System.out.println(key + "=" + value);
335         }
336     } // dump (Map)
337

338     /*************************************************************************/
339
340     /**
341      * Test
342      * @param args args
343      */

344     public static void main (String JavaDoc[] args)
345     {
346         AttributedString JavaDoc aString = new AttributedString JavaDoc ("test test");
347         aString.addAttribute(TextAttribute.FOREGROUND, Color.blue);
348         aString.addAttribute(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON, 2, 4);
349         getIterator (aString, new AttributedCharacterIterator.Attribute JavaDoc[] {TextAttribute.UNDERLINE});
350     } // main
351

352 } // Util
353
Popular Tags