001: /*
002: * Copyright (c) 2004-2006, Jean-François Brazeau. All rights reserved.
003: *
004: * Redistribution and use in source and binary forms, with or without
005: * modification, are permitted provided that the following conditions are met:
006: *
007: * 1. Redistributions of source code must retain the above copyright notice,
008: * this list of conditions and the following disclaimer.
009: *
010: * 2. Redistributions in binary form must reproduce the above copyright
011: * notice, this list of conditions and the following disclaimer in the
012: * documentation and/or other materials provided with the distribution.
013: *
014: * 3. The name of the author may not be used to endorse or promote products
015: * derived from this software without specific prior written permission.
016: *
017: * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
018: * IMPLIEDWARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
019: * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
020: * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
021: * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
022: * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
023: * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
024: * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
025: * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
026: * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
027: */
028: package jfb.tools.activitymgr.core.util;
029:
030: import java.io.ByteArrayOutputStream;
031: import java.io.IOException;
032: import java.io.InputStream;
033: import java.io.LineNumberReader;
034: import java.io.StringReader;
035: import java.math.BigDecimal;
036: import java.text.SimpleDateFormat;
037: import java.util.ArrayList;
038: import java.util.Calendar;
039:
040: import org.apache.log4j.Logger;
041:
042: /**
043: * Classe offrant des services de manipulation de chaines de caractères.
044: */
045: public class StringHelper {
046:
047: /** Logger */
048: private static Logger log = Logger.getLogger(StringHelper.class);
049:
050: /** Tableau de caractères utilisé pour la transformation Hexadécimale */
051: private static final char[] c = new char[] { '0', '1', '2', '3',
052: '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
053:
054: /** Formatteur de date */
055: private static SimpleDateFormat sdf = new SimpleDateFormat(
056: "yyyyMMdd");
057:
058: /**
059: * Convertit un octet en hexadécimal.
060: * @param b l'octet à convertir.
061: * @return la valeur hexadécimale.
062: */
063: public static String toHex(byte b) {
064: char[] result = new char[2];
065: result[0] = c[(b >> 4) & 0x0F];
066: result[1] = c[b & 0x0F];
067: return new String(result);
068: }
069:
070: /**
071: * Convertit une chaine hexadécimal en octet.
072: * @param hex la chaine à convertir.
073: * @return la valeur binaire.
074: */
075: public static byte toByte(String hex) {
076: return (byte) Integer.parseInt(hex, 16);
077: }
078:
079: /**
080: * Convertit une date en chaine de caractère.
081: * @param cal la date à convertir.
082: * @return la date convertie.
083: */
084: public static String toYYYYMMDD(Calendar cal) {
085: return sdf.format(cal.getTime());
086: }
087:
088: /**
089: * Convertit une valeur en centièmes en valeur au format
090: * de saisie.
091: * @param hundredth la valeur en centièmes.
092: * @return la valeur convertie au format de saisie.
093: */
094: public static String hundredthToEntry(long hundredth) {
095: StringBuffer buf = new StringBuffer(String.valueOf(hundredth));
096: switch (buf.length()) {
097: case 0:
098: buf.insert(0, "000");
099: break;
100: case 1:
101: buf.insert(0, "00");
102: break;
103: case 2:
104: buf.insert(0, "0");
105: break;
106: }
107: // Insertion du point
108: buf.insert(buf.length() - 2, '.');
109: // Retour du résultat
110: return buf.toString();
111: }
112:
113: /**
114: * Convertit une saisie utilisateur en centièmes.
115: * @param entry l'entrée de l'utilisateur.
116: * @return la valeur convertie en centièmes.
117: * @throws StringFormatException levé en cas de problème de format de la saisie.
118: */
119: public static long entryToHundredth(String entry)
120: throws StringFormatException {
121: BigDecimal decimal = null;
122: try {
123: decimal = new BigDecimal(entry);
124: } catch (NumberFormatException e) {
125: log.debug("Wrong format", e);
126: throw new StringFormatException("Wrong format (XXXXXX.XX)");
127: }
128: decimal = decimal.movePointRight(2);
129: if (decimal.scale() > 0)
130: throw new StringFormatException("Too many digits");
131: return decimal.longValue();
132: }
133:
134: /**
135: * Retourne le contenu d'un flux sous forme d'une chaîne de
136: * caractères.
137: * @param in le flux de lecture.
138: * @return la chaîne de caractère.
139: * @throws IOException levé en cas d'incident I/O.
140: */
141: public static String fromInputStream(InputStream in)
142: throws IOException {
143: ByteArrayOutputStream out = new ByteArrayOutputStream();
144: int n = -1;
145: byte[] buf = new byte[1024];
146: while ((n = in.read(buf)) > 0) {
147: out.write(buf, 0, n);
148: }
149: in.close();
150: return new String(out.toByteArray());
151: }
152:
153: /**
154: * Découpe un script pour en extraire les requêtes SQL.
155: * @param script le script à découper.
156: * @return les requêtes.
157: */
158: public static String[] getQueries(String script) {
159: ArrayList queries = new ArrayList();
160: LineNumberReader lnr = new LineNumberReader(new StringReader(
161: script.trim()));
162: StringBuffer buf = new StringBuffer();
163: boolean proceed = true;
164: do {
165: String line = null;
166: // On ne lit dans le flux que si la ligne courante n'est pas
167: // encore totalement traitée
168: if (line == null) {
169: try {
170: line = lnr.readLine();
171: } catch (IOException e) {
172: log
173: .debug(
174: "Unexpected I/O error while reading memory stream!",
175: e);
176: throw new Error(
177: "Unexpected I/O error while reading memory stream!",
178: null);
179: }
180: log.debug("Line read : '" + line + "'");
181: }
182: // Si le flux est vide, on sort de la boucle
183: if (line == null) {
184: proceed = false;
185: }
186: // Sinon on traite la ligne
187: else {
188: line = line.trim();
189: // Si la ligne est un commentaire on l'ignore
190: if (line.startsWith("--")) {
191: line = null;
192: } else {
193: // Sinon on regarde si la ligne possède
194: // un point virgule
195: int idx = line.indexOf(';');
196: // Si c'est le cas, on découpe la chaîne et on
197: // exécute la requête
198: if (idx >= 0) {
199: buf.append(line.subSequence(0, idx));
200: line = line.substring(idx);
201: String sql = buf.toString();
202: buf.setLength(0);
203: log.debug(" - sql='" + sql + "'");
204: if (!"".equals(sql))
205: queries.add(sql);
206: }
207: // sinon on ajoute la ligne au buffer de requeête
208: else {
209: buf.append(line);
210: buf.append('\n');
211: }
212: }
213: }
214:
215: } while (proceed);
216: // Ajout de la dernière requête (éventuellement)
217: if (buf.length() != 0)
218: queries.add(buf.toString());
219: return (String[]) queries.toArray(new String[queries.size()]);
220: }
221:
222: }
|