KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > caucho > quercus > lib > file > StreamModule


1 /*
2  * Copyright (c) 1998-2006 Caucho Technology -- all rights reserved
3  *
4  * This file is part of Resin(R) Open Source
5  *
6  * Each copy or derived work must preserve the copyright notice and this
7  * notice unmodified.
8  *
9  * Resin Open Source is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * Resin Open Source is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty
17  * of NON-INFRINGEMENT. See the GNU General Public License for more
18  * details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with Resin Open Source; if not, write to the
22  *
23  * Free Software Foundation, Inc.
24  * 59 Temple Place, Suite 330
25  * Boston, MA 02111-1307 USA
26  *
27  * @author Scott Ferguson
28  */

29
30 package com.caucho.quercus.lib.file;
31
32 import com.caucho.quercus.QuercusModuleException;
33 import com.caucho.quercus.annotation.NotNull;
34 import com.caucho.quercus.annotation.Optional;
35 import com.caucho.quercus.env.*;
36 import com.caucho.quercus.module.AbstractQuercusModule;
37 import com.caucho.quercus.resources.StreamContextResource;
38 import com.caucho.util.L10N;
39 import com.caucho.vfs.TempBuffer;
40
41 import java.io.IOException JavaDoc;
42 import java.util.HashMap JavaDoc;
43 import java.util.Map JavaDoc;
44 import java.util.logging.Logger JavaDoc;
45
46 /**
47  * Handling the PHP Stream API
48  */

49 public class StreamModule extends AbstractQuercusModule {
50   private static final L10N L = new L10N(StreamModule.class);
51   private static final Logger JavaDoc log
52     = Logger.getLogger(StreamModule.class.getName());
53
54   public static final int STREAM_FILTER_READ = 1;
55   public static final int STREAM_FILTER_WRITE = 2;
56   public static final int STREAM_FILTER_ALL = 3;
57
58   public static final int PSFS_PASS_ON = 2;
59   public static final int PSFS_FEED_ME = 1;
60   public static final int PSFS_ERR_FATAL = 0;
61
62   public static final int STREAM_USE_PATH = 1;
63   public static final int STREAM_REPORT_ERRORS = 8;
64
65   public static final int STREAM_CLIENT_ASYNC_CONNECT = 2;
66   public static final int STREAM_CLIENT_CONNECT = 4;
67   public static final int STREAM_CLIENT_PERSISTENT = 1;
68
69   public static final int STREAM_SERVER_BIND = 4;
70   public static final int STREAM_SERVER_LISTEN = 8;
71
72   public static final int STREAM_URL_STAT_LINK = 1;
73   public static final int STREAM_URL_STAT_QUIET = 2;
74
75   private static final HashMap JavaDoc<String JavaDoc,Value> _constMap
76     = new HashMap JavaDoc<String JavaDoc,Value>();
77
78   private static final HashMap JavaDoc<String JavaDoc,ProtocolWrapper> _wrapperMap
79     = new HashMap JavaDoc<String JavaDoc,ProtocolWrapper>();
80
81   private static final HashMap JavaDoc<String JavaDoc,ProtocolWrapper> _unregisteredWrapperMap
82     = new HashMap JavaDoc<String JavaDoc,ProtocolWrapper>();
83
84   private static final ArrayValue _wrapperArray = new ArrayValueImpl();
85
86   /**
87    * Adds the constant to the PHP engine's constant map.
88    *
89    * @return the new constant chain
90    */

91   public Map JavaDoc<String JavaDoc,Value> getConstMap()
92   {
93     return _constMap;
94   }
95
96   /*
97   public static void stream_bucket_append(Env env,
98                                           @NotNull StreamBucketBrigade brigade,
99                                           @NotNull StreamBucket bucket)
100   {
101     brigade.append(bucket);
102   }
103
104   @ReturnNullAsFalse
105   public static Value stream_bucket_make_writable(Env env,
106       @NotNull StreamBucketBrigade brigade)
107   {
108     return brigade.popTop();
109   }
110   */

111
112   /**
113    * Creates a stream context.
114    */

115   public static Value stream_context_create(Env env,
116                                             @Optional ArrayValue options)
117   {
118     return new StreamContextResource(options);
119   }
120
121   /**
122    * Returns the options from a stream context.
123    */

124   public static Value stream_context_get_options(Env env, Value resource)
125   {
126     if (resource instanceof StreamContextResource) {
127       return ((StreamContextResource) resource).getOptions();
128     }
129     else {
130       env.warning(L.l("expected resource at '{0}'", resource));
131
132       return BooleanValue.FALSE;
133     }
134   }
135
136   /**
137    * Returns the default stream context.
138    */

139   public static Value stream_context_get_default(Env env,
140                                                  @Optional ArrayValue options)
141   {
142     StreamContextResource context = env.getDefaultStreamContext();
143
144     if (options != null)
145       context.setOptions(options);
146
147     return context;
148   }
149
150   /**
151    * Set an options for a stream context.
152    */

153   public static boolean stream_context_set_option(Env env,
154                                                   Value resource,
155                                                   String JavaDoc wrapper,
156                                                   String JavaDoc option,
157                                                   Value value)
158   {
159     if (resource instanceof StreamContextResource) {
160       StreamContextResource context = (StreamContextResource) resource;
161
162       context.setOption(wrapper, option, value);
163
164       return true;
165     }
166     else {
167       env.warning(L.l("expected resource at '{0}'", resource));
168
169       return false;
170     }
171   }
172
173   /**
174    * Sets parameters for the context
175    */

176   public static boolean stream_context_set_params(Env env,
177                                                   Value resource,
178                                                   ArrayValue value)
179   {
180     if (resource instanceof StreamContextResource) {
181       StreamContextResource context = (StreamContextResource) resource;
182
183       context.setParameters(value);
184
185       return true;
186     }
187     else {
188       env.warning(L.l("expected resource at '{0}'", resource));
189
190       return false;
191     }
192   }
193
194   /**
195    * Copies from an input stream to an output stream
196    */

197   public static long stream_copy_to_stream(Env env,
198                                            @NotNull BinaryInput in,
199                                            @NotNull BinaryOutput out,
200                                            @Optional("-1") int length,
201                                            @Optional int offset)
202   {
203     try {
204       if (in == null)
205         return -1;
206
207       if (out == null)
208         return -1;
209
210       TempBuffer temp = TempBuffer.allocate();
211       byte []buffer = temp.getBuffer();
212
213       while (offset-- > 0)
214         in.read();
215
216       if (length < 0)
217         length = Integer.MAX_VALUE;
218
219       long bytesWritten = 0;
220
221       while (length > 0) {
222         int sublen = buffer.length;
223
224         if (length < sublen)
225           sublen = (int) length;
226
227         sublen = in.read(buffer, 0, sublen);
228         if (sublen < 0)
229           return bytesWritten;
230
231         out.write(buffer, 0, sublen);
232
233         bytesWritten += sublen;
234         length -= sublen;
235       }
236
237       TempBuffer.free(temp);
238
239       return bytesWritten;
240     } catch (IOException JavaDoc e) {
241       throw new QuercusModuleException(e);
242     }
243   }
244
245   /**
246    * Returns the rest of the file as a string
247    *
248    * @param filename the file's name
249    * @param useIncludePath if true, use the include path
250    * @param context the resource context
251    */

252   public static Value stream_get_contents(Env env,
253                                           @NotNull BinaryInput in,
254                                           @Optional("-1") long maxLen,
255                                           @Optional long offset)
256   {
257     try {
258       if (in == null)
259         return BooleanValue.FALSE;
260
261       StringBuilder JavaDoc sb = new StringBuilder JavaDoc();
262
263       int ch;
264
265       if (maxLen < 0)
266         maxLen = Integer.MAX_VALUE;
267
268       while (offset-- > 0)
269         in.read();
270
271       while (maxLen-- > 0 && (ch = in.read()) >= 0) {
272         sb.append((char) ch);
273       }
274
275       // XXX: handle offset and maxlen
276

277       return new StringValueImpl(sb.toString());
278     } catch (IOException JavaDoc e) {
279       throw new QuercusModuleException(e);
280     }
281   }
282
283   /**
284    * Returns the next line
285    */

286   public static Value stream_get_line(Env env,
287                                       @NotNull BinaryInput file,
288                                       @Optional("-1") long length)
289   {
290     try {
291       if (file == null)
292         return BooleanValue.FALSE;
293
294       if (length < 0)
295         length = Integer.MAX_VALUE;
296
297       StringValue line = file.readLine(length);
298
299
300       if (line == null)
301         return BooleanValue.FALSE;
302
303       int lineLength = line.length();
304       if (lineLength == 0)
305         return line;
306
307       char tail = line.charAt(lineLength - 1);
308
309       if (tail == '\n')
310         return line.substring(0, line.length() - 1);
311       else if (tail == '\r')
312         return line.substring(0, line.length() - 1);
313       else
314         return line;
315     } catch (IOException JavaDoc e) {
316       throw new QuercusModuleException(e);
317     }
318   }
319
320   /**
321    * Returns the metadata of this stream.
322    *
323    * XXX: TODO
324    */

325   public static Value stream_get_meta_data(Env env,
326                                            BinaryStream stream )
327   {
328     if (stream == null)
329       return BooleanValue.FALSE;
330     
331     env.stub("stream_get_meta_data");
332     
333     ArrayValue array = new ArrayValueImpl();
334     array.put(new StringValueImpl("timed_out"), BooleanValue.FALSE);
335     
336     return array;
337   }
338
339   /**
340    * Returns the available transports.
341    */

342   public static Value stream_get_transports(Env env)
343   {
344     ArrayValue value = new ArrayValueImpl();
345
346     value.append(new StringValueImpl("tcp"));
347     value.append(new StringValueImpl("udp"));
348
349     return value;
350   }
351
352   /**
353    * Returns the available wrappers.
354    */

355   public static Value stream_get_wrappers(Env env)
356   {
357     return _wrapperArray;
358   }
359
360   public static boolean stream_register_wrapper(Env env, StringValue protocol,
361                                                 String JavaDoc className)
362   {
363     return stream_wrapper_register(env, protocol, className);
364   }
365
366   public static boolean stream_set_blocking(Env env,
367                                             @NotNull Value stream,
368                                             int mode)
369   {
370     if (stream == null)
371       return false;
372     
373     env.stub("stream_set_blocking");
374     return false;
375   }
376
377   public static boolean stream_set_timeout(Env env,
378                                            @NotNull Value stream,
379                                            int seconds,
380                                            @Optional("-1") int milliseconds)
381   {
382     if (stream == null)
383       return false;
384
385     env.stub("stream_set_timeout");
386
387     return true;
388   }
389
390   /**
391    * Sets the write buffer.
392    */

393   public static int stream_set_write_buffer(Env env, BinaryOutput stream,
394                                             int bufferSize)
395   {
396     return 0;
397   }
398
399   static void stream_wrapper_register(StringValue protocol,
400                                       ProtocolWrapper wrapper)
401   {
402     _wrapperMap.put(protocol.toString(), wrapper);
403     
404     _wrapperArray.append(protocol);
405   }
406
407   /**
408    * Register a wrapper for a protocol.
409    */

410   public static boolean stream_wrapper_register(Env env, StringValue protocol,
411                                                 String JavaDoc className)
412   {
413     if (_wrapperMap.containsKey(protocol.toString()))
414       return false;
415
416     QuercusClass qClass = env.getClass(className);
417
418     stream_wrapper_register(protocol, new ProtocolWrapper(qClass));
419     
420     return true;
421   }
422
423   /**
424    * Register a wrapper for a protocol.
425    */

426   public static boolean stream_wrapper_restore(Env env, StringValue protocol)
427   {
428     if (! _unregisteredWrapperMap.containsKey(protocol.toString()))
429       return false;
430
431     ProtocolWrapper oldWrapper =
432       _unregisteredWrapperMap.remove(protocol.toString());
433
434     stream_wrapper_register(protocol, oldWrapper);
435
436     return true;
437   }
438
439   /**
440    * Register a wrapper for a protocol.
441    */

442   public static boolean stream_wrapper_unregister(Env env, StringValue protocol)
443   {
444     if (! _wrapperMap.containsKey(protocol.toString()))
445       return false;
446
447     _unregisteredWrapperMap.put(protocol.toString(),
448                                 _wrapperMap.remove(protocol.toString()));
449
450     _wrapperArray.remove(protocol);
451
452     return true;
453   }
454
455   public static ProtocolWrapper getWrapper(String JavaDoc protocol)
456   {
457     return _wrapperMap.get(protocol);
458   }
459
460   static {
461     _wrapperArray.append(new StringValueImpl("quercus"));
462     _wrapperArray.append(new StringValueImpl("file"));
463     _wrapperArray.append(new StringValueImpl("http"));
464     _wrapperArray.append(new StringValueImpl("ftp"));
465   }
466
467   static {
468     _constMap.put("STREAM_URL_STAT_LINK", new LongValue(STREAM_URL_STAT_LINK));
469     _constMap.put("STREAM_URL_STAT_QUIET",
470                   new LongValue(STREAM_URL_STAT_QUIET));
471
472     _constMap.put("STREAM_FILTER_READ", new LongValue(STREAM_FILTER_READ));
473     _constMap.put("STREAM_FILTER_WRITE", new LongValue(STREAM_FILTER_WRITE));
474     _constMap.put("STREAM_FILTER_ALL", new LongValue(STREAM_FILTER_ALL));
475
476     _constMap.put("PSFS_PASS_ON", new LongValue(PSFS_PASS_ON));
477     _constMap.put("PSFS_FEED_ME", new LongValue(PSFS_FEED_ME));
478     _constMap.put("PSFS_ERR_FATAL", new LongValue(PSFS_ERR_FATAL));
479
480     _constMap.put("STREAM_USE_PATH", new LongValue(STREAM_USE_PATH));
481     _constMap.put("STREAM_REPORT_ERRORS", new LongValue(STREAM_REPORT_ERRORS));
482
483     _constMap.put("STREAM_CLIENT_ASYNC_CONNECT",
484                   new LongValue(STREAM_CLIENT_ASYNC_CONNECT));
485     _constMap.put("STREAM_CLIENT_CONNECT",
486                   new LongValue(STREAM_CLIENT_CONNECT));
487     _constMap.put("STREAM_CLIENT_PERSISTENT",
488                   new LongValue(STREAM_CLIENT_PERSISTENT));
489
490     _constMap.put("STREAM_SERVER_BIND",
491                   new LongValue(STREAM_SERVER_BIND));
492     _constMap.put("STREAM_SERVER_LISTEN",
493                   new LongValue(STREAM_SERVER_LISTEN));
494   }
495 }
496
497
Popular Tags