001/*
002 * Copyright (c) 2011+, HL7, Inc
003 * All rights reserved.
004 * 
005 * Redistribution and use in source and binary forms, with or without modification,
006 * are permitted provided that the following conditions are met:
007 * 
008 * Redistributions of source code must retain the above copyright notice, this
009 * list of conditions and the following disclaimer.
010 * Redistributions in binary form must reproduce the above copyright notice,
011 * this list of conditions and the following disclaimer in the documentation
012 * and/or other materials provided with the distribution.
013 * Neither the name of HL7 nor the names of its contributors may be used to
014 * endorse or promote products derived from this software without specific
015 * prior written permission.
016 * 
017 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
018 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
019 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
020 * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
021 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
022 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
023 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
024 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
025 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
026 * POSSIBILITY OF SUCH DAMAGE.
027 * 
028 */
029package org.hl7.fhir.utilities;
030
031/*
032 * #%L
033 * HAPI FHIR - Core Library
034 * %%
035 * Copyright (C) 2014 - 2017 University Health Network
036 * %%
037 * Licensed under the Apache License, Version 2.0 (the "License");
038 * you may not use this file except in compliance with the License.
039 * You may obtain a copy of the License at
040 * 
041 *      http://www.apache.org/licenses/LICENSE-2.0
042 * 
043 * Unless required by applicable law or agreed to in writing, software
044 * distributed under the License is distributed on an "AS IS" BASIS,
045 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
046 * See the License for the specific language governing permissions and
047 * limitations under the License.
048 * #L%
049 */
050
051import java.io.File;
052import java.io.IOException;
053import java.util.Arrays;
054
055public class Utilities {
056
057        // private static final String TOKEN_REGEX = "^a-z[A-Za-z0-9]*$";
058
059        // private static final String OID_REGEX = "[0-2](\\.(0|[1-9]([0-9])*))*";
060        //
061        //
062        //
063        public static boolean isInteger(String string) {
064                try {
065                        int i = Integer.parseInt(string);
066                        return i != i + 1;
067                } catch (Exception e) {
068                        return false;
069                }
070        }
071
072        public static boolean isHex(String string) {
073                try {
074                        int i = Integer.parseInt(string, 16);
075                        return i != i + 1;
076                } catch (Exception e) {
077                        return false;
078                }
079        }
080
081        public static String escapeJson(String value) {
082                if (value == null)
083                        return "";
084
085                StringBuilder b = new StringBuilder();
086                for (char c : value.toCharArray()) {
087                        if (c == '\r')
088                                b.append("\\r");
089                        else if (c == '\n')
090                                b.append("\\n");
091                        else if (c == '"')
092                                b.append("\\\"");
093                        else if (c == '\'')
094                                b.append("\\'");
095                        else if (c == '\\')
096                                b.append("\\\\");
097                        else
098                                b.append(c);
099                }
100                return b.toString();
101        }
102
103        public static boolean isDecimal(String string) {
104                if (Utilities.noString(string))
105                        return false;
106                try {
107                        float r = Float.parseFloat(string);
108                        return r != r + 1; // just to suppress the hint
109                } catch (Exception e) {
110                        return false;
111                }
112        }
113
114        public static String escapeXml(String doco) {
115                if (doco == null)
116                        return "";
117
118                StringBuilder b = new StringBuilder();
119                for (char c : doco.toCharArray()) {
120                        if (c == '<')
121                                b.append("&lt;");
122                        else if (c == '>')
123                                b.append("&gt;");
124                        else if (c == '&')
125                                b.append("&amp;");
126                        else if (c == '"')
127                                b.append("&quot;");
128                        else
129                                b.append(c);
130                }
131                return b.toString();
132        }
133
134        //
135        //
136        public static String capitalize(String s) {
137                if (s == null)
138                        return null;
139                if (s.length() == 0)
140                        return s;
141                if (s.length() == 1)
142                        return s.toUpperCase();
143
144                return s.substring(0, 1).toUpperCase() + s.substring(1);
145        }
146
147        //
148        // public static void copyDirectory(String sourceFolder, String destFolder, FileNotifier notifier) throws IOException, FHIRException {
149        // CSFile src = new CSFile(sourceFolder);
150        // if (!src.exists())
151        // throw new FHIRException("Folder " +sourceFolder+" not found");
152        // createDirectory(destFolder);
153        //
154        // String[] files = src.list();
155        // for (String f : files) {
156        // if (new CSFile(sourceFolder+File.separator+f).isDirectory()) {
157        // if (!f.startsWith(".")) // ignore .svn...
158        // copyDirectory(sourceFolder+File.separator+f, destFolder+File.separator+f, notifier);
159        // } else {
160        // if (notifier != null)
161        // notifier.copyFile(sourceFolder+File.separator+f, destFolder+File.separator+f);
162        // copyFile(new CSFile(sourceFolder+File.separator+f), new CSFile(destFolder+File.separator+f));
163        // }
164        // }
165        // }
166        //
167        // public static void copyFile(String source, String dest) throws IOException {
168        // copyFile(new File(source), new File(dest));
169        // }
170        //
171        // public static void copyFile(File sourceFile, File destFile) throws IOException {
172        // if(!destFile.exists()) {
173        // if (!new CSFile(destFile.getParent()).exists()) {
174        // createDirectory(destFile.getParent());
175        // }
176        // destFile.createNewFile();
177        // }
178        //
179        // FileChannel source = null;
180        // FileChannel destination = null;
181        //
182        // try {
183        // source = new FileInputStream(sourceFile).getChannel();
184        // destination = new FileOutputStream(destFile).getChannel();
185        // destination.transferFrom(source, 0, source.size());
186        // }
187        // finally {
188        // if(source != null) {
189        // source.close();
190        // }
191        // if(destination != null) {
192        // destination.close();
193        // }
194        // }
195        // }
196        //
197        // public static boolean checkFolder(String dir, List<String> errors)
198        // throws IOException
199        // {
200        // if (!new CSFile(dir).exists()) {
201        // errors.add("Unable to find directory "+dir);
202        // return false;
203        // } else {
204        // return true;
205        // }
206        // }
207        //
208        // public static boolean checkFile(String purpose, String dir, String file, List<String> errors)
209        // throws IOException
210        // {
211        // if (!new CSFile(dir+file).exists()) {
212        // errors.add("Unable to find "+purpose+" file "+file+" in "+dir);
213        // return false;
214        // } else {
215        // return true;
216        // }
217        // }
218        //
219        // public static String asCSV(List<String> strings) {
220        // StringBuilder s = new StringBuilder();
221        // boolean first = true;
222        // for (String n : strings) {
223        // if (!first)
224        // s.append(",");
225        // s.append(n);
226        // first = false;
227        // }
228        // return s.toString();
229        // }
230        //
231        // public static String asHtmlBr(String prefix, List<String> strings) {
232        // StringBuilder s = new StringBuilder();
233        // boolean first = true;
234        // for (String n : strings) {
235        // if (!first)
236        // s.append("<br/>");
237        // s.append(prefix);
238        // s.append(n);
239        // first = false;
240        // }
241        // return s.toString();
242        // }
243        //
244        // public static void clearDirectory(String folder) throws IOException {
245        // File dir = new File(folder);
246        // if (dir.exists())
247        // FileUtils.cleanDirectory(dir);
248        //// String[] files = new CSFile(folder).list();
249        //// if (files != null) {
250        //// for (String f : files) {
251        //// File fh = new CSFile(folder+File.separatorChar+f);
252        //// if (fh.isDirectory())
253        //// clearDirectory(fh.getAbsolutePath());
254        //// fh.delete();
255        //// }
256        //// }
257        // }
258        //
259        // public static void createDirectory(String path) throws IOException{
260        // new CSFile(path).mkdirs();
261        // }
262        //
263        // public static String changeFileExt(String name, String ext) {
264        // if (name.lastIndexOf('.') > -1)
265        // return name.substring(0, name.lastIndexOf('.')) + ext;
266        // else
267        // return name+ext;
268        // }
269        //
270        // public static String cleanupTextString( String contents )
271        // {
272        // if( contents == null || contents.trim().equals("") )
273        // return null;
274        // else
275        // return contents.trim();
276        // }
277        //
278        //
279        public static boolean noString(String v) {
280                return v == null || v.equals("");
281        }
282
283        //
284        //
285        // public static byte[] saxonTransform(Map<String, byte[]> files, byte[] source, byte[] xslt) throws TransformerException {
286        // TransformerFactory f = new net.sf.saxon.TransformerFactoryImpl();
287        // f.setAttribute("http://saxon.sf.net/feature/version-warning", Boolean.FALSE);
288        // StreamSource xsrc = new StreamSource(new ByteArrayInputStream(xslt));
289        // f.setURIResolver(new ZipURIResolver(files));
290        // Transformer t = f.newTransformer(xsrc);
291        //
292        // t.setURIResolver(new ZipURIResolver(files));
293        // StreamSource src = new StreamSource(new ByteArrayInputStream(source));
294        // ByteArrayOutputStream out = new ByteArrayOutputStream();
295        // StreamResult res = new StreamResult(out);
296        // t.transform(src, res);
297        // return out.toByteArray();
298        // }
299        //
300        // public static byte[] transform(Map<String, byte[]> files, byte[] source, byte[] xslt) throws TransformerException {
301        // TransformerFactory f = TransformerFactory.newInstance();
302        // f.setAttribute("http://saxon.sf.net/feature/version-warning", Boolean.FALSE);
303        // StreamSource xsrc = new StreamSource(new ByteArrayInputStream(xslt));
304        // f.setURIResolver(new ZipURIResolver(files));
305        // Transformer t = f.newTransformer(xsrc);
306        //
307        // t.setURIResolver(new ZipURIResolver(files));
308        // StreamSource src = new StreamSource(new ByteArrayInputStream(source));
309        // ByteArrayOutputStream out = new ByteArrayOutputStream();
310        // StreamResult res = new StreamResult(out);
311        // t.transform(src, res);
312        // return out.toByteArray();
313        // }
314        //
315        // public static void bytesToFile(byte[] content, String filename) throws IOException {
316        // FileOutputStream out = new FileOutputStream(filename);
317        // out.write(content);
318        // out.close();
319        //
320        // }
321        //
322        // public static String saxonTransform(String source, String xslt) throws TransformerException, FileNotFoundException {
323        // TransformerFactoryImpl f = new net.sf.saxon.TransformerFactoryImpl();
324        // f.setAttribute("http://saxon.sf.net/feature/version-warning", Boolean.FALSE);
325        // StreamSource xsrc = new StreamSource(new FileInputStream(xslt));
326        // Transformer t = f.newTransformer(xsrc);
327        // StreamSource src = new StreamSource(new FileInputStream(source));
328        // StreamResult res = new StreamResult(new ByteArrayOutputStream());
329        // t.transform(src, res);
330        // return res.getOutputStream().toString();
331        // }
332        //
333        // public static void saxonTransform(String xsltDir, String source, String xslt, String dest, URIResolver alt) throws FileNotFoundException, TransformerException {
334        // saxonTransform(xsltDir, source, xslt, dest, alt, null);
335        // }
336        //
337        // public static void saxonTransform(String xsltDir, String source, String xslt, String dest, URIResolver alt, Map<String, String> params) throws FileNotFoundException, TransformerException {
338        // TransformerFactoryImpl f = new net.sf.saxon.TransformerFactoryImpl();
339        // f.setAttribute("http://saxon.sf.net/feature/version-warning", Boolean.FALSE);
340        // StreamSource xsrc = new StreamSource(new FileInputStream(xslt));
341        // f.setURIResolver(new MyURIResolver(xsltDir, alt));
342        // Transformer t = f.newTransformer(xsrc);
343        // if (params != null) {
344        // for (Map.Entry<String, String> entry : params.entrySet()) {
345        // t.setParameter(entry.getKey(), entry.getValue());
346        // }
347        // }
348        //
349        // t.setURIResolver(new MyURIResolver(xsltDir, alt));
350        // StreamSource src = new StreamSource(new FileInputStream(source));
351        // StreamResult res = new StreamResult(new FileOutputStream(dest));
352        // t.transform(src, res);
353        // }
354        //
355        // public static void transform(String xsltDir, String source, String xslt, String dest, URIResolver alt) throws FileNotFoundException, TransformerException {
356        //
357        // TransformerFactory f = TransformerFactory.newInstance();
358        // StreamSource xsrc = new StreamSource(new FileInputStream(xslt));
359        // f.setURIResolver(new MyURIResolver(xsltDir, alt));
360        // Transformer t = f.newTransformer(xsrc);
361        //
362        // t.setURIResolver(new MyURIResolver(xsltDir, alt));
363        // StreamSource src = new StreamSource(new FileInputStream(source));
364        // StreamResult res = new StreamResult(new FileOutputStream(dest));
365        // t.transform(src, res);
366        //
367        // }
368        //
369        //
370        public static String appendSlash(String definitions) {
371                return definitions.endsWith(File.separator) ? definitions : definitions + File.separator;
372        }
373
374        //
375        // public static String appendForwardSlash(String definitions) {
376        // return definitions.endsWith("/") ? definitions : definitions+"/";
377        // }
378        //
379        //
380        // public static String fileTitle(String file) {
381        // if (file == null)
382        // return null;
383        // String s = new File(file).getName();
384        // return s.indexOf(".") == -1? s : s.substring(0, s.indexOf("."));
385        // }
386        //
387        //
388        // public static String systemEol()
389        // {
390        // return System.getProperty("line.separator");
391        // }
392        //
393        public static String normaliseEolns(String value) {
394                return value.replace("\r\n", "\r").replace("\n", "\r").replace("\r", "\r\n");
395        }
396
397        //
398        //
399        // public static String unescapeXml(String xml) throws FHIRException {
400        // if (xml == null)
401        // return null;
402        //
403        // StringBuilder b = new StringBuilder();
404        // int i = 0;
405        // while (i < xml.length()) {
406        // if (xml.charAt(i) == '&') {
407        // StringBuilder e = new StringBuilder();
408        // i++;
409        // while (xml.charAt(i) != ';') {
410        // e.append(xml.charAt(i));
411        // i++;
412        // }
413        // if (e.toString().equals("lt"))
414        // b.append("<");
415        // else if (e.toString().equals("gt"))
416        // b.append(">");
417        // else if (e.toString().equals("amp"))
418        // b.append("&");
419        // else if (e.toString().equals("quot"))
420        // b.append("\"");
421        // else if (e.toString().equals("mu"))
422        // b.append((char)956);
423        // else
424        // throw new FHIRException("unknown XML entity \""+e.toString()+"\"");
425        // } else
426        // b.append(xml.charAt(i));
427        // i++;
428        // }
429        // return b.toString();
430        // }
431        //
432        //
433        //
434        //
435        // public static String padRight(String src, char c, int len) {
436        // StringBuilder s = new StringBuilder();
437        // s.append(src);
438        // for (int i = 0; i < len - src.length(); i++)
439        // s.append(c);
440        // return s.toString();
441        // }
442        //
443        //
444        public static String padLeft(String src, char c, int len) {
445                StringBuilder s = new StringBuilder();
446                for (int i = 0; i < len - src.length(); i++)
447                        s.append(c);
448                s.append(src);
449                return s.toString();
450        }
451
452        //
453        //
454        public static String path(String... args) throws IOException {
455                StringBuilder s = new StringBuilder();
456                boolean d = false;
457                for (String arg : args) {
458                        if (!d)
459                                d = !noString(arg);
460                        else if (!s.toString().endsWith(File.separator))
461                                s.append(File.separator);
462                        String a = arg;
463                        a = a.replace("\\", File.separator);
464                        if (s.length() > 0 && a.startsWith(File.separator))
465                                a = a.substring(File.separator.length());
466
467                        while (a.startsWith(".." + File.separator)) {
468                                String p = s.toString().substring(0, s.length() - 1);
469                                if (!p.contains(File.separator))
470                                        throw new IOException("illegal path underrun " + Arrays.asList(args));
471                                s = new StringBuilder(p.substring(0, p.lastIndexOf(File.separator)) + File.separator);
472                                a = a.substring(3);
473                        }
474                        if ("..".equals(a)) {
475                                int i = s.substring(0, s.length() - 1).lastIndexOf(File.separator);
476                                s = new StringBuilder(s.substring(0, i + 1));
477                        } else
478                                s.append(a);
479                }
480                return s.toString();
481        }
482
483        public static String pathReverse(String... args) {
484                StringBuilder s = new StringBuilder();
485                boolean d = false;
486                for (String arg : args) {
487                        if (!d)
488                                d = !noString(arg);
489                        else if (!s.toString().endsWith("/"))
490                                s.append("/");
491                        s.append(arg);
492                }
493                return s.toString();
494        }
495
496        //
497        //
498        //
499        //// public static void checkCase(String filename) {
500        //// File f = new CSFile(filename);
501        //// if (!f.getName().equals(filename))
502        //// throw new FHIRException("Filename ")
503        ////
504        //// }
505        //
506        // public static String nmtokenize(String cs) {
507        // StringBuilder s = new StringBuilder();
508        // for (int i = 0; i < cs.length(); i++) {
509        // char c = cs.charAt(i);
510        // if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '-' || c == '_')
511        // s.append(c);
512        // else if (c != ' ')
513        // s.append("."+Integer.toString(c));
514        // }
515        // return s.toString();
516        // }
517        //
518        //
519        // public static boolean isToken(String tail) {
520        // if (tail == null || tail.length() == 0)
521        // return false;
522        // boolean result = isAlphabetic(tail.charAt(0));
523        // for (int i = 1; i < tail.length(); i++) {
524        // result = result && (isAlphabetic(tail.charAt(i)) || isDigit(tail.charAt(i)) || (tail.charAt(i) == '_') || (tail.charAt(i) == '[') || (tail.charAt(i) == ']'));
525        // }
526        // return result;
527        // }
528        //
529        //
530        // private static boolean isDigit(char c) {
531        // return (c >= '0') && (c <= '9');
532        // }
533        //
534        //
535        // private static boolean isAlphabetic(char c) {
536        // return ((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z'));
537        // }
538        //
539        //
540        // public static String getDirectoryForFile(String filepath) {
541        // File f = new File(filepath);
542        // return f.getParent();
543        // }
544        //
545        // public static String appendPeriod(String s) {
546        // if (Utilities.noString(s))
547        // return s;
548        // s = s.trim();
549        // if (s.endsWith(".") || s.endsWith("?"))
550        // return s;
551        // return s+".";
552        // }
553        //
554        //
555        // public static String removePeriod(String s) {
556        // if (Utilities.noString(s))
557        // return s;
558        // if (s.endsWith("."))
559        // return s.substring(0, s.length()-1);
560        // return s;
561        // }
562        //
563        //
564        // public static String stripBOM(String string) {
565        // return string.replace("\uFEFF", "");
566        // }
567        //
568        //
569        // public static String oidTail(String id) {
570        // if (id == null || !id.contains("."))
571        // return id;
572        // return id.substring(id.lastIndexOf(".")+1);
573        // }
574        //
575        //
576        // public static String oidRoot(String id) {
577        // if (id == null || !id.contains("."))
578        // return id;
579        // return id.substring(0, id.indexOf("."));
580        // }
581        //
582        public static String escapeJava(String doco) {
583                if (doco == null)
584                        return "";
585
586                StringBuilder b = new StringBuilder();
587                for (char c : doco.toCharArray()) {
588                        if (c == '\r')
589                                b.append("\\r");
590                        else if (c == '\n')
591                                b.append("\\n");
592                        else if (c == '"')
593                                b.append("\\\"");
594                        else if (c == '\\')
595                                b.append("\\\\");
596                        else
597                                b.append(c);
598                }
599                return b.toString();
600        }
601
602        //
603        //
604        // public static String[] splitByCamelCase(String name) {
605        // List<String> parts = new ArrayList<String>();
606        // StringBuilder b = new StringBuilder();
607        // for (int i = 0; i < name.length(); i++) {
608        // if (i > 0 && Character.isUpperCase(name.charAt(i))) {
609        // parts.add(b.toString());
610        // b = new StringBuilder();
611        // }
612        // b.append(Character.toLowerCase(name.charAt(i)));
613        // }
614        // parts.add(b.toString());
615        // return parts.toArray(new String[] {} );
616        // }
617        //
618        //
619        // public static String encodeUri(String v) {
620        // return v.replace(" ", "%20").replace("?", "%3F").replace("=", "%3D");
621        // }
622        //
623        //
624        //
625        public static String normalize(String s) {
626                if (noString(s))
627                        return null;
628                StringBuilder b = new StringBuilder();
629                boolean isWhitespace = false;
630                for (int i = 0; i < s.length(); i++) {
631                        char c = s.charAt(i);
632                        if (!Character.isWhitespace(c)) {
633                                b.append(Character.toLowerCase(c));
634                                isWhitespace = false;
635                        } else if (!isWhitespace) {
636                                b.append(' ');
637                                isWhitespace = true;
638                        }
639                }
640                return b.toString().trim();
641        }
642
643        //
644        // public static String normalizeSameCase(String s) {
645        // if (noString(s))
646        // return null;
647        // StringBuilder b = new StringBuilder();
648        // boolean isWhitespace = false;
649        // for (int i = 0; i < s.length(); i++) {
650        // char c = s.charAt(i);
651        // if (!Character.isWhitespace(c)) {
652        // b.append(c);
653        // isWhitespace = false;
654        // } else if (!isWhitespace) {
655        // b.append(' ');
656        // isWhitespace = true;
657        // }
658        // }
659        // return b.toString().trim();
660        // }
661        //
662        //
663        // public static void copyFileToDirectory(File source, File destDir) throws IOException {
664        // copyFile(source, new File(path(destDir.getAbsolutePath(), source.getName())));
665        // }
666        //
667        //
668        // public static boolean isWhitespace(String s) {
669        // boolean ok = true;
670        // for (int i = 0; i < s.length(); i++)
671        // ok = ok && Character.isWhitespace(s.charAt(i));
672        // return ok;
673        //
674        // }
675        //
676        //
677        // public static String URLEncode(String string) {
678        // try {
679        // return URLEncoder.encode(string, "UTF-8");
680        // } catch (UnsupportedEncodingException e) {
681        // throw new Error(e.getMessage());
682        // }
683        // }
684        //
685        //
686        public static boolean charInSet(char value, char... array) {
687                for (int i : array)
688                        if (value == i)
689                                return true;
690                return false;
691        }
692
693        //
694        //
695        // public static boolean charInRange(char ch, char a, char z) {
696        // return ch >= a && ch <= z;
697        // }
698        //
699        public static boolean existsInList(String value, String... array) {
700                if (value == null)
701                        return false;
702                for (String s : array)
703                        if (value.equals(s))
704                                return true;
705                return false;
706        }
707
708        public static boolean existsInList(int value, int... array) {
709                for (int i : array)
710                        if (value == i)
711                                return true;
712                return false;
713        }
714
715        public static boolean existsInListNC(String value, String... array) {
716                for (String s : array)
717                        if (value.equalsIgnoreCase(s))
718                                return true;
719                return false;
720        }
721
722        //
723        //
724        // public static String getFileNameForName(String name) {
725        // return name.toLowerCase();
726        // }
727        //
728        // public static void deleteTempFiles() throws IOException {
729        // File file = createTempFile("test", "test");
730        // String folder = getDirectoryForFile(file.getAbsolutePath());
731        // String[] list = new File(folder).list(new FilenameFilter() {
732        // public boolean accept(File dir, String name) {
733        // return name.startsWith("ohfu-");
734        // }
735        // });
736        // if (list != null) {
737        // for (String n : list) {
738        // new File(path(folder, n)).delete();
739        // }
740        // }
741        // }
742        //
743        // public static File createTempFile(String prefix, String suffix) throws IOException {
744        // // this allows use to eaily identify all our dtemp files and delete them, since delete on Exit doesn't really work.
745        // File file = File.createTempFile("ohfu-"+prefix, suffix);
746        // file.deleteOnExit();
747        // return file;
748        // }
749        //
750        //
751        // public static boolean isAsciiChar(char ch) {
752        // return ch >= ' ' && ch <= '~';
753        // }
754        //
755        //
756        // public static String makeUuidUrn() {
757        // return "urn:uuid:"+UUID.randomUUID().toString().toLowerCase();
758        // }
759        //
760        public static boolean isURL(String s) {
761                boolean ok = s.matches("^http(s{0,1})://[a-zA-Z0-9_/\\-\\.]+\\.([A-Za-z/]{2,5})[a-zA-Z0-9_/\\&\\?\\=\\-\\.\\~\\%]*");
762                return ok;
763        }
764
765        //
766        //
767        // public static String escapeJson(String value) {
768        // if (value == null)
769        // return "";
770        //
771        // StringBuilder b = new StringBuilder();
772        // for (char c : value.toCharArray()) {
773        // if (c == '\r')
774        // b.append("\\r");
775        // else if (c == '\n')
776        // b.append("\\n");
777        // else if (c == '"')
778        // b.append("\\\"");
779        // else if (c == '\'')
780        // b.append("\\'");
781        // else if (c == '\\')
782        // b.append("\\\\");
783        // else
784        // b.append(c);
785        // }
786        // return b.toString();
787        // }
788        //
789        // public static String humanize(String code) {
790        // StringBuilder b = new StringBuilder();
791        // boolean lastBreak = true;
792        // for (char c : code.toCharArray()) {
793        // if (Character.isLetter(c)) {
794        // if (lastBreak)
795        // b.append(Character.toUpperCase(c));
796        // else {
797        // if (Character.isUpperCase(c))
798        // b.append(" ");
799        // b.append(c);
800        // }
801        // lastBreak = false;
802        // } else {
803        // b.append(" ");
804        // lastBreak = true;
805        // }
806        // }
807        // if (b.length() == 0)
808        // return code;
809        // else
810        // return b.toString();
811        // }
812        //
813        //
814        public static String uncapitalize(String s) {
815                if (s == null)
816                        return null;
817                if (s.length() == 0)
818                        return s;
819                if (s.length() == 1)
820                        return s.toLowerCase();
821
822                return s.substring(0, 1).toLowerCase() + s.substring(1);
823        }
824
825        public static int charCount(String s, char c) {
826                int res = 0;
827                for (char ch : s.toCharArray())
828                        if (ch == c)
829                                res++;
830                return res;
831        }
832
833        //
834        // // http://stackoverflow.com/questions/3780406/how-to-play-a-sound-alert-in-a-java-application
835        // public static float SAMPLE_RATE = 8000f;
836        //
837        // public static void tone(int hz, int msecs) {
838        // tone(hz, msecs, 1.0);
839        // }
840        //
841        // public static void tone(int hz, int msecs, double vol) {
842        // try {
843        // byte[] buf = new byte[1];
844        // AudioFormat af =
845        // new AudioFormat(
846        // SAMPLE_RATE, // sampleRate
847        // 8, // sampleSizeInBits
848        // 1, // channels
849        // true, // signed
850        // false); // bigEndian
851        // SourceDataLine sdl;
852        // sdl = AudioSystem.getSourceDataLine(af);
853        // sdl.open(af);
854        // sdl.start();
855        // for (int i=0; i < msecs*8; i++) {
856        // double angle = i / (SAMPLE_RATE / hz) * 2.0 * Math.PI;
857        // buf[0] = (byte)(Math.sin(angle) * 127.0 * vol);
858        // sdl.write(buf,0,1);
859        // }
860        // sdl.drain();
861        // sdl.stop();
862        // sdl.close();
863        // } catch (Exception e) {
864        // }
865        // }
866        //
867        //
868        // public static boolean isOid(String cc) {
869        // return cc.matches(OID_REGEX) && cc.lastIndexOf('.') > 5;
870        // }
871        //
872        //
873        // public static boolean equals(String one, String two) {
874        // if (one == null && two == null)
875        // return true;
876        // if (one == null || two == null)
877        // return false;
878        // return one.equals(two);
879        // }
880        //
881        //
882        // public static void deleteAllFiles(String folder, String type) {
883        // File src = new File(folder);
884        // String[] files = src.list();
885        // for (String f : files) {
886        // if (new File(folder+File.separator+f).isDirectory()) {
887        // deleteAllFiles(folder+File.separator+f, type);
888        // } else if (f.endsWith(type)) {
889        // new File(folder+File.separator+f).delete();
890        // }
891        // }
892        //
893        // }
894        //
895        // public static boolean compareIgnoreWhitespace(File f1, File f2) throws IOException {
896        // InputStream in1 = null;
897        // InputStream in2 = null;
898        // try {
899        // in1 = new BufferedInputStream(new FileInputStream(f1));
900        // in2 = new BufferedInputStream(new FileInputStream(f2));
901        //
902        // int expectedByte = in1.read();
903        // while (expectedByte != -1) {
904        // boolean w1 = isWhitespace(expectedByte);
905        // if (w1)
906        // while (isWhitespace(expectedByte))
907        // expectedByte = in1.read();
908        // int foundByte = in2.read();
909        // if (w1) {
910        // if (!isWhitespace(foundByte))
911        // return false;
912        // while (isWhitespace(foundByte))
913        // foundByte = in2.read();
914        // }
915        // if (expectedByte != foundByte)
916        // return false;
917        // expectedByte = in1.read();
918        // }
919        // if (in2.read() != -1) {
920        // return false;
921        // }
922        // return true;
923        // } finally {
924        // if (in1 != null) {
925        // try {
926        // in1.close();
927        // } catch (IOException e) {}
928        // }
929        // if (in2 != null) {
930        // try {
931        // in2.close();
932        // } catch (IOException e) {}
933        // }
934        // }
935        // }
936        //
937        // private static boolean isWhitespace(int b) {
938        // return b == 9 || b == 10 || b == 13 || b == 32;
939        // }
940        //
941        //
942        // public static boolean compareIgnoreWhitespace(String fn1, String fn2) throws IOException {
943        // return compareIgnoreWhitespace(new File(fn1), new File(fn2));
944        // }
945        //
946        //
947        public static boolean isAbsoluteUrl(String ref) {
948                // FIXME null access on ref cause by OR clause.
949                return ref != null && ref.startsWith("http:") || ref.startsWith("https:") || ref.startsWith("urn:uuid:") || ref.startsWith("urn:oid:");
950        }
951
952        public static boolean equivalent(String l, String r) {
953                if (Utilities.noString(l) && Utilities.noString(r))
954                        return true;
955                if (Utilities.noString(l) || Utilities.noString(r))
956                        return false;
957                return l.toLowerCase().equals(r.toLowerCase());
958        }
959
960        public static boolean equivalentNumber(String l, String r) {
961                if (Utilities.noString(l) && Utilities.noString(r))
962                        return true;
963                if (Utilities.noString(l) || Utilities.noString(r))
964                        return false;
965                l = l.toLowerCase().trim();
966                r = r.toLowerCase().trim(); // not that this should make any difference
967                return l.startsWith(r) || r.startsWith(l);
968        }
969        //
970        //
971        // public static String getFileExtension(String fn) {
972        // return fn.contains(".") ? fn.substring(fn.lastIndexOf(".")+1) : "";
973        // }
974        //
975        //
976        // public static String unCamelCase(String name) {
977        // StringBuilder b = new StringBuilder();
978        // boolean first = true;
979        // for (char c : name.toCharArray()) {
980        // if (Character.isUpperCase(c)) {
981        // if (!first)
982        // b.append(" ");
983        // b.append(Character.toLowerCase(c));
984        // } else
985        // b.append(c);
986        // first = false;
987        // }
988        // return b.toString();
989        // }
990        //
991        //
992        // public static boolean isAbsoluteFileName(String source) {
993        // if (isWindows())
994        // return (source.length() > 2 && source.charAt(1) == ':') || source.startsWith("\\\\");
995        // else
996        // return source.startsWith("//");
997        // }
998        //
999        //
1000        // private static boolean isWindows() {
1001        // return System.getProperty("os.name").startsWith("Windows");
1002        // }
1003        //
1004        //
1005
1006}