View Javadoc

1   /*
2    * Copyright 2007-2008 the original author or authors.
3    * 
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * 
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    * 
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package org.gwe.utils;
18  
19  import java.io.BufferedInputStream;
20  import java.io.BufferedOutputStream;
21  import java.io.ByteArrayInputStream;
22  import java.io.ByteArrayOutputStream;
23  import java.io.File;
24  import java.io.FileInputStream;
25  import java.io.FileNotFoundException;
26  import java.io.FileOutputStream;
27  import java.io.FileReader;
28  import java.io.IOException;
29  import java.io.InputStream;
30  import java.io.InputStreamReader;
31  import java.io.ObjectInputStream;
32  import java.io.ObjectOutputStream;
33  import java.io.OutputStream;
34  import java.nio.channels.FileChannel;
35  import java.util.HashSet;
36  import java.util.Set;
37  
38  /**
39   * @author Marco Ruiz
40   * @since Jun 13, 2007
41   */
42  public class IOUtils {
43  //	private static final String FILE_SEPARATOR = System.getProperty("file.separator");
44  	public static final String FILE_SEPARATOR = "/";
45  
46  	public static boolean makeFilePath(String file) {
47          return new File(IOUtils.getFilePath(file)).mkdirs();
48      }
49  	
50      public static void copyFile(File in, File out) throws IOException {
51  		FileChannel inChannel = new FileInputStream(in).getChannel();
52  		FileChannel outChannel = new FileOutputStream(out).getChannel();
53  		try {
54  			inChannel.transferTo(0, inChannel.size(), outChannel);
55  		} catch (IOException e) {
56  			throw e;
57  		} finally {
58  			if (inChannel != null) inChannel.close();
59  			if (outChannel != null) outChannel.close();
60  		}
61  	}
62  	
63  	public static String getFileBase(String uriStr) {
64  		String base = uriStr.replaceAll("[*?\\[].*", "");
65          if (!base.endsWith(FILE_SEPARATOR)) base = base.replaceFirst("/[^/]*$","/");
66  		return base;
67  	}
68  	
69  	public static String getFileName(String file) {
70          int indexOfLastSeparator = file.lastIndexOf(FILE_SEPARATOR);
71  		return (indexOfLastSeparator == -1) ? "" : file.substring(indexOfLastSeparator + 1); 
72  	}
73  
74  	public static String getFilePath(String file) {
75          int indexOfLastSeparator = file.lastIndexOf(FILE_SEPARATOR);
76          return (indexOfLastSeparator == -1) ? file : file.substring(0, indexOfLastSeparator);
77      }
78  	
79  	public static void createLocalFolder(String fullPath) {
80  		new File(fullPath).mkdir();
81  	}
82  	
83  	public static String createLocalExecutableFile(String fullFileName, String contents) throws IOException {
84  //		if (mkdirs) createLocalFolder(getFilePath(fullFileName));
85  		FileOutputStream fos = new FileOutputStream(fullFileName, false);
86  		fos.close();
87  		Runtime.getRuntime().exec("chmod a+x " + fullFileName);
88  		fos = new FileOutputStream(fullFileName, false);
89  		fos.write(contents.getBytes());
90  		fos.close();
91  		return fullFileName;
92  	}
93  	
94  	public static String concatenatePaths(Object... paths) {
95  		if (paths == null || paths.length < 1) return "";
96  		Object result = paths[0];
97  		for (int idx = 1; idx < paths.length; idx++) 
98  			result = concatenatePaths(result.toString(), paths[idx].toString());
99  		return result.toString();
100     }
101 
102 	public static String concatenatePaths(String filePath, String fileName) {
103 		if (filePath == null || fileName == null) return null;
104 		if (filePath.endsWith(FILE_SEPARATOR))   filePath = filePath.substring(0, filePath.length() - 1);
105 		if (fileName.startsWith(FILE_SEPARATOR)) fileName = (fileName.length() == 1) ? "" : fileName.substring(1);
106 		return concatenate(filePath, FILE_SEPARATOR, fileName);
107     }
108 	
109 	public static String concatenate(Object... args) {
110 		StringBuffer buf = new StringBuffer();
111 		for (int idx = 0; idx < args.length; idx++) buf.append(args[idx]);
112 		return buf.toString();
113 	}
114 
115 	public static String readFile(File f) throws FileNotFoundException, IOException {
116 		return readReader(new FileReader(f));
117 	}
118 
119 	public static String readReader(InputStreamReader fr) throws IOException {
120 		StringBuffer sb = new StringBuffer();
121 		char[] buff = new char[1024];
122 		for (int num_read = fr.read(buff); num_read >= 0; num_read = fr.read(buff)) {
123 		    for (int ii = 0; ii < num_read; ++ii) {
124 		        sb.append(buff[ii]);
125 		    }
126 		}
127 		fr.close();
128 		return sb.toString();
129 	}
130 	
131 	public static byte[] readFile(String filename) throws IOException, FileNotFoundException {
132 	    return (filename == null || "".equals(filename)) ? null : readStream(new FileInputStream(new File(filename)), null).toByteArray();
133     }
134 	
135 	public static String readClassPathFile(String fileName) {
136 		InputStream is = IOUtils.class.getClassLoader().getResourceAsStream(fileName);
137 		StringBuffer sb = new StringBuffer();
138 		int nextChar;
139 		try {
140 			while ((nextChar = is.read()) != -1) sb.append((char)nextChar);
141 		} catch (IOException e) {
142 			// TODO: Do something and/or rethrow the exception
143 		}
144 		try {
145 			is.close();
146 		} catch (IOException e) {
147 			// Do nothing.
148 		}
149 		return sb.toString();
150 	}
151 	
152 	public static int pipeStreams(InputStream is, OutputStream os) throws IOException {
153 		return pipeStreams(is, os, false);
154 	}
155 
156 	public static ByteArrayOutputStream readStream(InputStream is, OutputStream myOs) throws IOException {
157 		return readStream(is, myOs, null);
158 	}
159 
160 	public static String readStream(InputStream is) throws IOException {
161 		return new String(IOUtils.readStream(is, null).toByteArray());
162 	}
163 	
164 	public static ByteArrayOutputStream readStream(InputStream is, OutputStream myOs, String endTag) throws IOException {
165 		ByteArrayOutputStream os = new ByteArrayOutputStream();
166 		Set<OutputStream> osSet = new HashSet<OutputStream>();
167 		osSet.add(os);
168 		if (myOs != null) osSet.add(myOs);
169 		pipeStreams(is, osSet, false, endTag);
170 		return os;
171 	}
172 
173 	public static int pipeStreams(InputStream is, OutputStream os, boolean closeStreams) throws IOException {
174 		Set<OutputStream> osSet = new HashSet<OutputStream>();
175 		osSet.add(os);
176 		return pipeStreams(is, osSet, closeStreams, null);
177 	}
178 	
179 	public static int pipeStreams(InputStream is, Set<OutputStream> osSet, boolean closeStreams, String endTag) throws IOException {
180 		String latestEndTag = "";
181 		long start = System.currentTimeMillis();
182 		int totalPiped = 0;
183 		InputStream in = null;
184 		Set<BufferedOutputStream> outs = new HashSet<BufferedOutputStream>();
185 		try {
186 			in = new BufferedInputStream(is);
187 			for (OutputStream os : osSet) outs.add(new BufferedOutputStream(os));
188 
189 		    byte[] buffer = new byte[1024 * 64];
190 			while (true) {
191 				int amountRead = in.read(buffer);
192 				if (amountRead == -1) break;
193 				for (BufferedOutputStream out : outs) {
194 					out.write(buffer, 0, amountRead);
195 					out.flush();
196 				}
197 				if (endTag != null) {
198 					int shift = Math.max(latestEndTag.length() - endTag.length() - 1, 0);
199 					latestEndTag = latestEndTag.substring(shift) + new String(buffer, 0, amountRead);
200 					if (latestEndTag.contains(endTag)) break;
201 				}
202 				totalPiped += amountRead;
203 			}
204 		} finally {
205 			if (in != null) in.close();
206 			if (closeStreams)
207 				for (BufferedOutputStream out : outs) out.close();
208 		}
209 //		LogFactory.getLog(IOUtils.class).trace("Transfered " + totalPiped + " bytes.");
210 		long duration = System.currentTimeMillis() - start;
211 		return totalPiped;
212 	}
213 	
214 /*	
215 	public static int pipeStreams(InputStream is, Set<OutputStream> osSet, boolean closeStreams) throws IOException {
216 		long start = System.currentTimeMillis();
217 		int totalPiped = 0;
218 		int numRead = 0;
219 		try {
220 			while ((numRead = is.read(buffer)) >= 0) {
221 				for (OutputStream os : osSet) {
222 				    os.write(buffer, 0, numRead);
223 				    // TODO: Make sure flushing works for VFS. Currently it is broken and the whole flushing occurs at 
224 				    // output stream closing time; which represents a memory problem (the latest vfs version has problems 
225 				    // with zip and tar files!)
226 		            os.flush(); 
227 				}
228 	
229 	            totalPiped += numRead;
230 			}
231 		} finally {
232 			if (closeStreams) {
233 				for (OutputStream os : osSet) os.close();
234 			    is.close();
235 			}
236 		}
237 		log.trace("Transfered " + totalPiped + " bytes.");
238 		long duration = System.currentTimeMillis() - start;
239 	    return totalPiped;
240 	}
241 */
242 	
243 	public static void serializeObject(Object obj, String fileName) throws IOException {
244 		serializeObject(new FileOutputStream(fileName));
245 	}
246 
247 	public static void serializeObject(Object obj, OutputStream os) throws IOException {
248 	    os.write(serializeObject(obj));
249 	    os.close();
250 	}
251 
252 	public static <T> byte[] serializeObject(T obj) throws IOException {
253 		ByteArrayOutputStream resultOS = new ByteArrayOutputStream();
254 		ObjectOutputStream out = new ObjectOutputStream(resultOS);
255 		out.writeObject(obj);
256 		out.close();
257 		byte[] result = resultOS.toByteArray();
258 		resultOS.close();
259 		return result;
260 	}
261 
262 	public static <T> T deserializeObject(byte[] stream) throws IOException, ClassNotFoundException {
263 		return (T)deserializeObject(new ByteArrayInputStream(stream));
264 	}
265 
266 	public static <T> T deserializeObject(InputStream is) throws IOException, ClassNotFoundException {
267 		ObjectInputStream in = new ObjectInputStream(is);
268     	T result = (T)in.readObject();
269     	in.close();
270     	return result;
271 	}
272 }