View Javadoc

1   //
2   //  ========================================================================
3   //  Copyright (c) 1995-2013 Mort Bay Consulting Pty. Ltd.
4   //  ------------------------------------------------------------------------
5   //  All rights reserved. This program and the accompanying materials
6   //  are made available under the terms of the Eclipse Public License v1.0
7   //  and Apache License v2.0 which accompanies this distribution.
8   //
9   //      The Eclipse Public License is available at
10  //      http://www.eclipse.org/legal/epl-v10.html
11  //
12  //      The Apache License v2.0 is available at
13  //      http://www.opensource.org/licenses/apache2.0.php
14  //
15  //  You may elect to redistribute this code under either of these licenses.
16  //  ========================================================================
17  //
18  
19  package org.eclipse.jetty.util;
20  import java.io.ByteArrayOutputStream;
21  import java.io.File;
22  import java.io.FileInputStream;
23  import java.io.FileOutputStream;
24  import java.io.IOException;
25  import java.io.InputStream;
26  import java.io.InputStreamReader;
27  import java.io.OutputStream;
28  import java.io.PrintWriter;
29  import java.io.Reader;
30  import java.io.StringWriter;
31  import java.io.Writer;
32  import java.nio.charset.Charset;
33  
34  import org.eclipse.jetty.util.log.Log;
35  import org.eclipse.jetty.util.log.Logger;
36  import org.eclipse.jetty.util.thread.QueuedThreadPool;
37  
38  /* ======================================================================== */
39  /** IO Utilities.
40   * Provides stream handling utilities in
41   * singleton Threadpool implementation accessed by static members.
42   */
43  public class IO 
44  {
45      private static final Logger LOG = Log.getLogger(IO.class);
46      
47      /* ------------------------------------------------------------------- */
48      public final static String
49          CRLF      = "\015\012";
50  
51      /* ------------------------------------------------------------------- */
52      public final static byte[]
53          CRLF_BYTES    = {(byte)'\015',(byte)'\012'};
54  
55      /* ------------------------------------------------------------------- */
56      public static final int bufferSize = 64*1024;
57  
58      /* ------------------------------------------------------------------- */
59      static class Job implements Runnable
60      {
61          InputStream in;
62          OutputStream out;
63          Reader read;
64          Writer write;
65  
66          Job(InputStream in,OutputStream out)
67          {
68              this.in=in;
69              this.out=out;
70              this.read=null;
71              this.write=null;
72          }
73          Job(Reader read,Writer write)
74          {
75              this.in=null;
76              this.out=null;
77              this.read=read;
78              this.write=write;
79          }
80          
81          /* ------------------------------------------------------------ */
82          /* 
83           * @see java.lang.Runnable#run()
84           */
85          public void run()
86          {
87              try {
88                  if (in!=null)
89                      copy(in,out,-1);
90                  else
91                      copy(read,write,-1);
92              }
93              catch(IOException e)
94              {
95                  LOG.ignore(e);
96                  try{
97                      if (out!=null)
98                          out.close();
99                      if (write!=null)
100                         write.close();
101                 }
102                 catch(IOException e2)
103                 {
104                     LOG.ignore(e2);
105                 }
106             }
107         }
108     }
109     
110     /* ------------------------------------------------------------------- */
111     /** Copy Stream in to Stream out until EOF or exception.
112      */
113     public static void copy(InputStream in, OutputStream out)
114          throws IOException
115     {
116         copy(in,out,-1);
117     }
118     
119     /* ------------------------------------------------------------------- */
120     /** Copy Reader to Writer out until EOF or exception.
121      */
122     public static void copy(Reader in, Writer out)
123          throws IOException
124     {
125         copy(in,out,-1);
126     }
127     
128     /* ------------------------------------------------------------------- */
129     /** Copy Stream in to Stream for byteCount bytes or until EOF or exception.
130      */
131     public static void copy(InputStream in,
132                             OutputStream out,
133                             long byteCount)
134          throws IOException
135     {     
136         byte buffer[] = new byte[bufferSize];
137         int len=bufferSize;
138         
139         if (byteCount>=0)
140         {
141             while (byteCount>0)
142             {
143                 int max = byteCount<bufferSize?(int)byteCount:bufferSize;
144                 len=in.read(buffer,0,max);
145                 
146                 if (len==-1)
147                     break;
148                 
149                 byteCount -= len;
150                 out.write(buffer,0,len);
151             }
152         }
153         else
154         {
155             while (true)
156             {
157                 len=in.read(buffer,0,bufferSize);
158                 if (len<0 )
159                     break;
160                 out.write(buffer,0,len);
161             }
162         }
163     }  
164     
165     /* ------------------------------------------------------------------- */
166     /** Copy Reader to Writer for byteCount bytes or until EOF or exception.
167      */
168     public static void copy(Reader in,
169                             Writer out,
170                             long byteCount)
171          throws IOException
172     {  
173         char buffer[] = new char[bufferSize];
174         int len=bufferSize;
175         
176         if (byteCount>=0)
177         {
178             while (byteCount>0)
179             {
180                 if (byteCount<bufferSize)
181                     len=in.read(buffer,0,(int)byteCount);
182                 else
183                     len=in.read(buffer,0,bufferSize);                   
184                 
185                 if (len==-1)
186                     break;
187                 
188                 byteCount -= len;
189                 out.write(buffer,0,len);
190             }
191         }
192         else if (out instanceof PrintWriter)
193         {
194             PrintWriter pout=(PrintWriter)out;
195             while (!pout.checkError())
196             {
197                 len=in.read(buffer,0,bufferSize);
198                 if (len==-1)
199                     break;
200                 out.write(buffer,0,len);
201             }
202         }
203         else
204         {
205             while (true)
206             {
207                 len=in.read(buffer,0,bufferSize);
208                 if (len==-1)
209                     break;
210                 out.write(buffer,0,len);
211             }
212         }
213     }
214 
215     /* ------------------------------------------------------------ */
216     /** Copy files or directories
217      * @param from
218      * @param to
219      * @throws IOException
220      */
221     public static void copy(File from,File to) throws IOException
222     {
223         if (from.isDirectory())
224             copyDir(from,to);
225         else
226             copyFile(from,to);
227     }
228 
229     /* ------------------------------------------------------------ */
230     public static void copyDir(File from,File to) throws IOException
231     {
232         if (to.exists())
233         {
234             if (!to.isDirectory())
235                 throw new IllegalArgumentException(to.toString());
236         }
237         else
238             to.mkdirs();
239         
240         File[] files = from.listFiles();
241         if (files!=null)
242         {
243             for (int i=0;i<files.length;i++)
244             {
245                 String name = files[i].getName();
246                 if (".".equals(name) || "..".equals(name))
247                     continue;
248                 copy(files[i],new File(to,name));
249             }
250         }
251     }
252     
253     /* ------------------------------------------------------------ */
254     public static void copyFile(File from,File to) throws IOException
255     {
256         try (InputStream in=new FileInputStream(from);
257                 OutputStream out=new FileOutputStream(to))
258         {
259             copy(in,out);
260         }
261     }
262     
263     /* ------------------------------------------------------------ */
264     /** Read input stream to string.
265      */
266     public static String toString(InputStream in)
267         throws IOException
268     {
269         return toString(in,(Charset)null);
270     }
271     
272     /* ------------------------------------------------------------ */
273     /** Read input stream to string.
274      */
275     public static String toString(InputStream in,String encoding)
276         throws IOException
277     {
278         return toString(in, encoding==null?null:Charset.forName(encoding));
279     }
280 
281     /** Read input stream to string.
282      */
283     public static String toString(InputStream in, Charset encoding)
284             throws IOException
285     {
286         StringWriter writer=new StringWriter();
287         InputStreamReader reader = encoding==null?new InputStreamReader(in):new InputStreamReader(in,encoding);
288 
289         copy(reader,writer);
290         return writer.toString();
291     }
292 
293     /* ------------------------------------------------------------ */
294     /** Read input stream to string.
295      */
296     public static String toString(Reader in)
297         throws IOException
298     {
299         StringWriter writer=new StringWriter();
300         copy(in,writer);
301         return writer.toString();
302     }
303 
304 
305     /* ------------------------------------------------------------ */
306     /** Delete File.
307      * This delete will recursively delete directories - BE CAREFULL
308      * @param file The file to be deleted.
309      */
310     public static boolean delete(File file)
311     {
312         if (!file.exists())
313             return false;
314         if (file.isDirectory())
315         {
316             File[] files = file.listFiles();
317             for (int i=0;files!=null && i<files.length;i++)
318                 delete(files[i]);
319         }
320         return file.delete();
321     }
322 
323     /* ------------------------------------------------------------ */
324     /**
325      * closes an input stream, and logs exceptions
326      *
327      * @param is the input stream to close
328      */
329     public static void close(InputStream is)
330     {
331         try
332         {
333             if (is != null)
334                 is.close();
335         }
336         catch (IOException e)
337         {
338             LOG.ignore(e);
339         }
340     }
341 
342     /**
343      * closes a reader, and logs exceptions
344      * 
345      * @param reader the reader to close
346      */
347     public static void close(Reader reader)
348     {
349         try
350         {
351             if (reader != null)
352                 reader.close();
353         } catch (IOException e)
354         {
355             LOG.ignore(e);
356         }
357     }
358 
359     /**
360      * closes a writer, and logs exceptions
361      * 
362      * @param writer the writer to close
363      */
364     public static void close(Writer writer)
365     {
366         try
367         {
368             if (writer != null)
369                 writer.close();
370         } catch (IOException e)
371         {
372             LOG.ignore(e);
373         }
374     }
375     
376     /* ------------------------------------------------------------ */
377     public static byte[] readBytes(InputStream in)
378         throws IOException
379     {
380         ByteArrayOutputStream bout = new ByteArrayOutputStream();
381         copy(in,bout);
382         return bout.toByteArray();
383     }
384     
385     /* ------------------------------------------------------------ */
386     /**
387      * closes an output stream, and logs exceptions
388      *
389      * @param os the output stream to close
390      */
391     public static void close(OutputStream os)
392     {
393         try
394         {
395             if (os != null)
396                 os.close();
397         }
398         catch (IOException e)
399         {
400             LOG.ignore(e);
401         }
402     }
403 
404     /* ------------------------------------------------------------ */
405     /** 
406      * @return An outputstream to nowhere
407      */
408     public static OutputStream getNullStream()
409     {
410         return __nullStream;
411     }
412 
413     /* ------------------------------------------------------------ */
414     /** 
415      * @return An outputstream to nowhere
416      */
417     public static InputStream getClosedStream()
418     {
419         return __closedStream;
420     }
421     
422     /* ------------------------------------------------------------ */
423     /* ------------------------------------------------------------ */
424     private static class NullOS extends OutputStream                                    
425     {
426         @Override
427         public void close(){}
428         @Override
429         public void flush(){}
430         @Override
431         public void write(byte[]b){}
432         @Override
433         public void write(byte[]b,int i,int l){}
434         @Override
435         public void write(int b){}
436     }
437     private static NullOS __nullStream = new NullOS();
438 
439     
440     /* ------------------------------------------------------------ */
441     /* ------------------------------------------------------------ */
442     private static class ClosedIS extends InputStream                                    
443     {
444         @Override
445         public int read() throws IOException
446         {
447             return -1;
448         }
449     }
450     private static ClosedIS __closedStream = new ClosedIS();
451     
452     /* ------------------------------------------------------------ */
453     /** 
454      * @return An writer to nowhere
455      */
456     public static Writer getNullWriter()
457     {
458         return __nullWriter;
459     }
460     
461     /* ------------------------------------------------------------ */
462     /** 
463      * @return An writer to nowhere
464      */
465     public static PrintWriter getNullPrintWriter()
466     {
467         return __nullPrintWriter;
468     }
469     
470     /* ------------------------------------------------------------ */
471     /* ------------------------------------------------------------ */
472     private static class NullWrite extends Writer                                    
473     {
474         @Override
475         public void close(){}
476         @Override
477         public void flush(){}
478         @Override
479         public void write(char[]b){}
480         @Override
481         public void write(char[]b,int o,int l){}
482         @Override
483         public void write(int b){}
484         @Override
485         public void write(String s){}
486         @Override
487         public void write(String s,int o,int l){}
488     }
489     private static NullWrite __nullWriter = new NullWrite();
490     private static PrintWriter __nullPrintWriter = new PrintWriter(__nullWriter);
491 }
492 
493 
494 
495 
496 
497 
498 
499 
500