001/*
002Copyright (c) 2011+, HL7, Inc
003All rights reserved.
004
005Redistribution and use in source and binary forms, with or without modification, 
006are 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
017THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
018ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
019WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
020IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
021INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 
022NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 
023PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
024WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
025ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
026POSSIBILITY OF SUCH DAMAGE.
027
028 */
029package org.hl7.fhir.instance.utilities;
030
031import java.io.BufferedInputStream;
032import java.io.ByteArrayInputStream;
033import java.io.ByteArrayOutputStream;
034import java.io.File;
035import java.io.FileInputStream;
036import java.io.FileOutputStream;
037import java.io.FilenameFilter;
038import java.io.IOException;
039import java.io.InputStream;
040import java.io.UnsupportedEncodingException;
041import java.net.URLEncoder;
042import java.nio.channels.FileChannel;
043import java.util.ArrayList;
044import java.util.List;
045import java.util.Map;
046import java.util.UUID;
047
048import javax.sound.sampled.AudioFormat;
049import javax.sound.sampled.AudioSystem;
050import javax.sound.sampled.SourceDataLine;
051import javax.xml.transform.Transformer;
052import javax.xml.transform.TransformerFactory;
053import javax.xml.transform.URIResolver;
054import javax.xml.transform.stream.StreamResult;
055import javax.xml.transform.stream.StreamSource;
056
057
058import org.apache.commons.io.FileUtils;
059
060public class Utilities {
061
062//       private static final String TOKEN_REGEX = "^a-z[A-Za-z0-9]*$";
063
064
065  private static final String OID_REGEX = "[0-2](\\.(0|[1-9]([0-9])*))*";
066
067  /**
068     * Returns the plural form of the word in the string.
069     * 
070     * Examples:
071     * 
072     * <pre>
073     *   inflector.pluralize(&quot;post&quot;)               #=&gt; &quot;posts&quot;
074     *   inflector.pluralize(&quot;octopus&quot;)            #=&gt; &quot;octopi&quot;
075     *   inflector.pluralize(&quot;sheep&quot;)              #=&gt; &quot;sheep&quot;
076     *   inflector.pluralize(&quot;words&quot;)              #=&gt; &quot;words&quot;
077     *   inflector.pluralize(&quot;the blue mailman&quot;)   #=&gt; &quot;the blue mailmen&quot;
078     *   inflector.pluralize(&quot;CamelOctopus&quot;)       #=&gt; &quot;CamelOctopi&quot;
079     * </pre>
080     * 
081     * 
082     * 
083     * Note that if the {@link Object#toString()} is called on the supplied object, so this method works for non-strings, too.
084     * 
085     * 
086     * @param word the word that is to be pluralized.
087     * @return the pluralized form of the word, or the word itself if it could not be pluralized
088     * @see #singularize(Object)
089     */
090    public static String pluralizeMe( String word ) {
091        Inflector inf = new Inflector();
092        return inf.pluralize(word);
093    }
094    
095  
096        public static boolean isInteger(String string) {
097                try {
098                        int i = Integer.parseInt(string);
099                        return i != i+1;
100                } catch (Exception e) {
101                        return false;
102                }
103        }
104        
105        public static boolean isDecimal(String string) {
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 camelCase(String value) {
115          return new Inflector().camelCase(value.trim().replace(" ", "_"), false);
116        }
117        
118        public static String escapeXml(String doco) {
119                if (doco == null)
120                        return "";
121                
122                StringBuilder b = new StringBuilder();
123                for (char c : doco.toCharArray()) {
124                  if (c == '<')
125                          b.append("&lt;");
126                  else if (c == '>')
127                          b.append("&gt;");
128                  else if (c == '&')
129                          b.append("&amp;");
130      else if (c == '"')
131        b.append("&quot;");
132                  else 
133                          b.append(c);
134                }               
135                return b.toString();
136        }
137
138        
139        public static String capitalize(String s)
140        {
141                if( s == null ) return null;
142                if( s.length() == 0 ) return s;
143                if( s.length() == 1 ) return s.toUpperCase();
144                
145                return s.substring(0, 1).toUpperCase() + s.substring(1);
146        }
147        
148  public static void copyDirectory(String sourceFolder, String destFolder, FileNotifier notifier) throws Exception {
149    CSFile src = new CSFile(sourceFolder);
150    if (!src.exists())
151      throw new Exception("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  public static byte[] saxonTransform(Map<String, byte[]> files, byte[] source, byte[] xslt) throws Exception {
285    TransformerFactory f = new net.sf.saxon.TransformerFactoryImpl();
286    f.setAttribute("http://saxon.sf.net/feature/version-warning", Boolean.FALSE);
287    StreamSource xsrc = new StreamSource(new ByteArrayInputStream(xslt));
288    f.setURIResolver(new ZipURIResolver(files));
289    Transformer t = f.newTransformer(xsrc);
290 
291    t.setURIResolver(new ZipURIResolver(files));
292    StreamSource src = new StreamSource(new ByteArrayInputStream(source));
293    ByteArrayOutputStream out = new ByteArrayOutputStream();
294    StreamResult res = new StreamResult(out);
295    t.transform(src, res);
296    return out.toByteArray();    
297  }
298  
299  public static byte[] transform(Map<String, byte[]> files, byte[] source, byte[] xslt) throws Exception {
300    TransformerFactory f = TransformerFactory.newInstance();
301    f.setAttribute("http://saxon.sf.net/feature/version-warning", Boolean.FALSE);
302    StreamSource xsrc = new StreamSource(new ByteArrayInputStream(xslt));
303    f.setURIResolver(new ZipURIResolver(files));
304    Transformer t = f.newTransformer(xsrc);
305
306    t.setURIResolver(new ZipURIResolver(files));
307    StreamSource src = new StreamSource(new ByteArrayInputStream(source));
308    ByteArrayOutputStream out = new ByteArrayOutputStream();
309    StreamResult res = new StreamResult(out);
310    t.transform(src, res);
311    return out.toByteArray();    
312  }
313  
314  public static void bytesToFile(byte[] content, String filename) throws Exception {
315    FileOutputStream out = new FileOutputStream(filename);
316    out.write(content);
317    out.close();
318    
319  }
320
321
322  public static void transform(String xsltDir, String source, String xslt, String dest, URIResolver alt) throws Exception {
323
324    TransformerFactory f = TransformerFactory.newInstance();
325    StreamSource xsrc = new StreamSource(new FileInputStream(xslt));
326    f.setURIResolver(new MyURIResolver(xsltDir, alt));
327    Transformer t = f.newTransformer(xsrc);
328
329    t.setURIResolver(new MyURIResolver(xsltDir, alt));
330    StreamSource src = new StreamSource(new FileInputStream(source));
331    StreamResult res = new StreamResult(new FileOutputStream(dest));
332    t.transform(src, res);
333    
334  }
335
336
337  public static String appendSlash(String definitions) {
338            return definitions.endsWith(File.separator) ? definitions : definitions+File.separator;
339          }
340
341  public static String appendForwardSlash(String definitions) {
342            return definitions.endsWith("/") ? definitions : definitions+"/";
343          }
344
345
346  public static String fileTitle(String file) {
347    if (file == null)
348      return null;
349    String s = new File(file).getName();
350    return s.indexOf(".") == -1? s : s.substring(0, s.indexOf("."));
351  }
352
353
354  public static String systemEol()
355  {
356          return System.getProperty("line.separator");
357  }
358
359  public static String normaliseEolns(String value) {
360    return value.replace("\r\n", "\r").replace("\n", "\r").replace("\r", "\r\n");
361  }
362
363
364  public static String unescapeXml(String xml) throws Exception {
365    if (xml == null)
366      return null;
367    
368    StringBuilder b = new StringBuilder();
369    int i = 0;
370    while (i < xml.length()) {
371      if (xml.charAt(i) == '&') {
372        StringBuilder e = new StringBuilder();
373        i++;
374        while (xml.charAt(i) != ';') {
375          e.append(xml.charAt(i));
376          i++;
377        }
378        if (e.toString().equals("lt")) 
379          b.append("<");
380        else if (e.toString().equals("gt")) 
381          b.append(">");
382        else if (e.toString().equals("amp")) 
383          b.append("&");
384        else if (e.toString().equals("quot")) 
385          b.append("\"");
386        else if (e.toString().equals("mu"))
387          b.append((char)956);          
388        else
389          throw new Exception("unknown XML entity \""+e.toString()+"\"");
390      }  else
391        b.append(xml.charAt(i));
392      i++;
393    }   
394    return b.toString();
395  }
396
397
398  public static boolean isPlural(String word) {
399    word = word.toLowerCase();
400    if ("restricts".equals(word) || "contains".equals(word) || "data".equals(word) || "specimen".equals(word))
401      return false;
402    Inflector inf = new Inflector();
403    return !inf.singularize(word).equals(word);
404  }
405
406
407  public static String padLeft(String src, char c, int len) {
408    StringBuilder s = new StringBuilder();
409    for (int i = 0; i < len - src.length(); i++)
410      s.append(c);
411    s.append(src);
412    return s.toString();
413    
414  }
415
416
417  public static String path(String... args) {
418    StringBuilder s = new StringBuilder();
419    boolean d = false;
420    for(String arg: args) {
421      if (!d)
422        d = !noString(arg);
423      else if (!s.toString().endsWith(File.separator))
424        s.append(File.separator);
425      String a = arg;
426      a = a.replace("\\", File.separator);
427      if (s.length() > 0 && a.startsWith(File.separator))
428        a = a.substring(File.separator.length());
429        
430      if ("..".equals(a)) {
431        int i = s.substring(0, s.length()-1).lastIndexOf(File.separator);
432        s = new StringBuilder(s.substring(0, i+1));
433      } else
434        s.append(a);
435    }
436    return s.toString();
437  }
438
439  public static String pathReverse(String... args) {
440    StringBuilder s = new StringBuilder();
441    boolean d = false;
442    for(String arg: args) {
443      if (!d)
444        d = !noString(arg);
445      else if (!s.toString().endsWith("/"))
446        s.append("/");
447      s.append(arg);
448    }
449    return s.toString();
450  }
451
452
453
454//  public static void checkCase(String filename) {
455//    File f = new CSFile(filename);
456//    if (!f.getName().equals(filename))
457//      throw new Exception("Filename  ")
458//    
459//  }
460
461  public static String nmtokenize(String cs) {
462    StringBuilder s = new StringBuilder();
463    for (int i = 0; i < cs.length(); i++) {
464      char c = cs.charAt(i);
465      if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '-' || c == '_')
466        s.append(c);
467      else if (c != ' ')
468        s.append("."+Integer.toString(c));
469    }
470    return s.toString();
471  }
472
473
474  public static boolean isToken(String tail) {
475    if (tail == null || tail.length() == 0)
476      return false;
477    boolean result = isAlphabetic(tail.charAt(0));
478    for (int i = 1; i < tail.length(); i++) {
479        result = result && (isAlphabetic(tail.charAt(i)) || isDigit(tail.charAt(i)) || (tail.charAt(i) == '_')  || (tail.charAt(i) == '[') || (tail.charAt(i) == ']'));
480    }
481    return result;
482  }
483
484
485  private static boolean isDigit(char c) {
486    return (c >= '0') && (c <= '9');
487  }
488
489
490  private static boolean isAlphabetic(char c) {
491    return ((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z'));
492  }
493
494
495  public static String getDirectoryForFile(String filepath) {
496    File f = new File(filepath);
497    return f.getParent();
498  }
499
500  public static String appendPeriod(String s) {
501    if (Utilities.noString(s))
502      return s;
503    s = s.trim();
504    if (s.endsWith(".") || s.endsWith("?"))
505      return s;
506    return s+".";
507  }
508
509
510  public static String removePeriod(String s) {
511    if (Utilities.noString(s))
512      return s;
513    if (s.endsWith("."))
514      return s.substring(0, s.length()-1);
515    return s;
516  }
517
518
519        public static String stripBOM(String string) {
520          return string.replace("\uFEFF", "");
521  }
522
523
524  public static String oidTail(String id) {
525    if (id == null || !id.contains("."))
526      return id;
527    return id.substring(id.lastIndexOf(".")+1);
528  }
529
530
531  public static String oidRoot(String id) {
532    if (id == null || !id.contains("."))
533      return id;
534    return id.substring(0, id.indexOf("."));
535  }
536
537  public static String escapeJava(String doco) {
538    if (doco == null)
539      return "";
540    
541    StringBuilder b = new StringBuilder();
542    for (char c : doco.toCharArray()) {
543      if (c == '\r')
544        b.append("\\r");
545      else if (c == '\n')
546        b.append("\\n");
547      else if (c == '"')
548        b.append("\\\"");
549      else if (c == '\\')
550        b.append("\\\\");
551      else 
552        b.append(c);
553    }   
554    return b.toString();
555  }
556
557
558  public static String[] splitByCamelCase(String name) {
559    List<String> parts = new ArrayList<String>();
560    StringBuilder b = new StringBuilder();
561    for (int i = 0; i < name.length(); i++) {
562      if (i > 0 && Character.isUpperCase(name.charAt(i))) {
563        parts.add(b.toString());
564        b = new StringBuilder();
565      }
566      b.append(Character.toLowerCase(name.charAt(i)));
567    }
568    parts.add(b.toString());
569    return parts.toArray(new String[] {} );
570  }
571
572
573  public static String encodeUri(String v) {
574    return v.replace(" ", "%20").replace("?", "%3F").replace("=", "%3D");
575  }
576  
577
578
579        public static String normalize(String s) {
580                if (noString(s))
581                        return null;
582          StringBuilder b = new StringBuilder();
583          boolean isWhitespace = false;
584          for (int i = 0; i < s.length(); i++) {
585                char c = s.charAt(i);
586                if (!Character.isWhitespace(c)) { 
587                        b.append(Character.toLowerCase(c));
588                        isWhitespace = false;
589                } else if (!isWhitespace) {
590                        b.append(' ');
591                        isWhitespace = true;                    
592                } 
593          }
594          return b.toString().trim();
595  }
596
597  public static String normalizeSameCase(String s) {
598    if (noString(s))
599      return null;
600    StringBuilder b = new StringBuilder();
601    boolean isWhitespace = false;
602    for (int i = 0; i < s.length(); i++) {
603      char c = s.charAt(i);
604      if (!Character.isWhitespace(c)) { 
605        b.append(c);
606        isWhitespace = false;
607      } else if (!isWhitespace) {
608        b.append(' ');
609        isWhitespace = true;        
610      } 
611    }
612    return b.toString().trim();
613  }
614
615
616  public static void copyFileToDirectory(File source, File destDir) throws IOException {
617        copyFile(source, new File(path(destDir.getAbsolutePath(), source.getName())));
618  }
619
620
621        public static boolean isWhitespace(String s) {
622          boolean ok = true;
623          for (int i = 0; i < s.length(); i++)
624                ok = ok && Character.isWhitespace(s.charAt(i));
625          return ok;
626          
627  }
628
629
630  public static String URLEncode(String string) {
631    try {
632      return URLEncoder.encode(string, "UTF-8");
633    } catch (UnsupportedEncodingException e) {
634      throw new Error(e.getMessage());
635    }
636  }
637
638
639  public static boolean existsInList(String value, String... array) {
640    for (String s : array)
641      if (value.equals(s))
642          return true;
643    return false;
644  }
645
646  public static boolean existsInListNC(String value, String... array) {
647    for (String s : array)
648      if (value.equalsIgnoreCase(s))
649          return true;
650    return false;
651  }
652
653
654  public static String getFileNameForName(String name) {
655    return name.toLowerCase();
656  }
657
658  public static void deleteTempFiles() throws IOException {
659    File file = createTempFile("test", "test");
660    String folder = getDirectoryForFile(file.getAbsolutePath());
661    String[] list = new File(folder).list(new FilenameFilter() {
662      public boolean accept(File dir, String name) {
663        return name.startsWith("ohfu-");
664      }
665    });
666    if (list != null) {
667      for (String n : list) {
668        new File(path(folder, n)).delete();
669      }
670    }
671  }
672
673  public static File createTempFile(String prefix, String suffix) throws IOException {
674 // this allows use to eaily identify all our dtemp files and delete them, since delete on Exit doesn't really work.
675    File file = File.createTempFile("ohfu-"+prefix, suffix);  
676    file.deleteOnExit();
677    return file;
678  }
679
680
681        public static boolean isAsciiChar(char ch) {
682                return ch >= ' ' && ch <= '~'; 
683  }
684
685
686  public static String makeUuidUrn() {
687    return "urn:uuid:"+UUID.randomUUID().toString().toLowerCase();
688  }
689
690  public static boolean isURL(String s) {
691    boolean ok = s.matches("^http(s{0,1})://[a-zA-Z0-9_/\\-\\.]+\\.([A-Za-z/]{2,5})[a-zA-Z0-9_/\\&\\?\\=\\-\\.\\~\\%]*");
692    return ok;
693 }
694
695
696  public static String escapeJson(String value) {
697    if (value == null)
698      return "";
699    
700    StringBuilder b = new StringBuilder();
701    for (char c : value.toCharArray()) {
702      if (c == '\r')
703        b.append("\\r");
704      else if (c == '\n')
705        b.append("\\n");
706      else if (c == '"')
707        b.append("\\\"");
708      else if (c == '\'')
709        b.append("\\'");
710      else if (c == '\\')
711        b.append("\\\\");
712      else 
713        b.append(c);
714    }   
715    return b.toString();
716  }
717
718  public static String humanize(String code) {
719    StringBuilder b = new StringBuilder();
720    boolean lastBreak = true;
721    for (char c : code.toCharArray()) {
722      if (Character.isLetter(c)) {
723        if (lastBreak)
724          b.append(Character.toUpperCase(c));
725        else { 
726          if (Character.isUpperCase(c))
727            b.append(" ");          
728          b.append(c);
729        }
730        lastBreak = false;
731      } else {
732        b.append(" ");
733        lastBreak = true;
734      }
735    }
736    if (b.length() == 0)
737      return code;
738    else 
739      return b.toString();
740  }
741
742
743  public static String uncapitalize(String s) {
744    if( s == null ) return null;
745    if( s.length() == 0 ) return s;
746    if( s.length() == 1 ) return s.toLowerCase();
747    
748    return s.substring(0, 1).toLowerCase() + s.substring(1);
749  }
750
751
752  public static int charCount(String s, char c) {
753          int res = 0;
754          for (char ch : s.toCharArray())
755                if (ch == c)
756                  res++;
757          return res;
758  }
759
760
761  // http://stackoverflow.com/questions/3780406/how-to-play-a-sound-alert-in-a-java-application
762  public static float SAMPLE_RATE = 8000f;
763  
764  public static void tone(int hz, int msecs) {
765      tone(hz, msecs, 1.0);
766   }
767
768  public static void tone(int hz, int msecs, double vol) {
769    try {
770      byte[] buf = new byte[1];
771      AudioFormat af = 
772          new AudioFormat(
773              SAMPLE_RATE, // sampleRate
774              8,           // sampleSizeInBits
775              1,           // channels
776              true,        // signed
777              false);      // bigEndian
778      SourceDataLine sdl;
779      sdl = AudioSystem.getSourceDataLine(af);
780      sdl.open(af);
781      sdl.start();
782      for (int i=0; i < msecs*8; i++) {
783        double angle = i / (SAMPLE_RATE / hz) * 2.0 * Math.PI;
784        buf[0] = (byte)(Math.sin(angle) * 127.0 * vol);
785        sdl.write(buf,0,1);
786      }
787      sdl.drain();
788      sdl.stop();
789      sdl.close();
790    } catch (Exception e) {
791    }
792  }
793
794
795  public static boolean isOid(String cc) {
796    return cc.matches(OID_REGEX) && cc.lastIndexOf('.') > 5;
797  }
798
799
800  public static boolean equals(String one, String two) {
801    if (one == null && two == null)
802      return true;
803    if (one == null || two == null)
804      return false;
805    return one.equals(two);
806  }
807
808
809  public static void deleteAllFiles(String folder, String type) {
810    File src = new File(folder);
811    String[] files = src.list();
812    for (String f : files) {
813      if (new File(folder+File.separator+f).isDirectory()) {
814        deleteAllFiles(folder+File.separator+f, type);
815      } else if (f.endsWith(type)) {
816        new File(folder+File.separator+f).delete();
817      }
818    }
819    
820  }
821
822  public static boolean compareIgnoreWhitespace(File f1, File f2) throws IOException {
823    InputStream in1 = null;
824    InputStream in2 = null;
825    try {
826      in1 = new BufferedInputStream(new FileInputStream(f1));
827      in2 = new BufferedInputStream(new FileInputStream(f2));
828
829      int expectedByte = in1.read();
830      while (expectedByte != -1) {
831        boolean w1 = isWhitespace(expectedByte);
832        if (w1)
833          while (isWhitespace(expectedByte))
834            expectedByte = in1.read();
835        int foundByte = in2.read();
836        if (w1) {
837          if (!isWhitespace(foundByte))
838            return false;
839          while (isWhitespace(foundByte))
840            foundByte = in2.read();
841        }
842        if (expectedByte != foundByte) 
843          return false;
844        expectedByte = in1.read();
845      }
846      if (in2.read() != -1) {
847        return false;
848      }
849      return true;
850    } finally {
851      if (in1 != null) {
852        try {
853          in1.close();
854        } catch (IOException e) {}
855      }
856      if (in2 != null) {
857        try {
858          in2.close();
859        } catch (IOException e) {}
860      }
861    }
862  }
863  
864  private static boolean isWhitespace(int b) {
865    return b == 9 || b == 10 || b == 13 || b == 32;
866  }
867
868
869  public static boolean compareIgnoreWhitespace(String fn1, String fn2) throws IOException {
870    return compareIgnoreWhitespace(new File(fn1), new File(fn2));
871  }
872
873
874  public static boolean isAbsoluteUrl(String ref) {
875    return ref.startsWith("http:") || ref.startsWith("https:") || ref.startsWith("urn:uuid:") || ref.startsWith("urn:oid:") ;
876  }
877
878
879}