KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > caucho > quercus > lib > VariableModule


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;
31
32 import com.caucho.quercus.QuercusModuleException;
33 import com.caucho.quercus.annotation.Optional;
34 import com.caucho.quercus.annotation.ReadOnly;
35 import com.caucho.quercus.annotation.Reference;
36 import com.caucho.quercus.annotation.UsesSymbolTable;
37 import com.caucho.quercus.env.*;
38 import com.caucho.quercus.module.AbstractQuercusModule;
39 import com.caucho.util.L10N;
40 import com.caucho.util.LruCache;
41 import com.caucho.vfs.WriteStream;
42
43 import java.io.IOException JavaDoc;
44 import java.lang.reflect.Method JavaDoc;
45 import java.util.HashMap JavaDoc;
46 import java.util.IdentityHashMap JavaDoc;
47 import java.util.Map JavaDoc;
48 import java.util.logging.Level JavaDoc;
49 import java.util.logging.Logger JavaDoc;
50
51 /**
52  * Information about PHP variables.
53  */

54 public class VariableModule extends AbstractQuercusModule {
55   private static final Logger JavaDoc log
56     = Logger.getLogger(VariableModule.class.getName());
57   private static final L10N L = new L10N(VariableModule.class);
58
59   private static final LruCache<StringValue,Value> _unserializeCache
60     = new LruCache<StringValue,Value>(256);
61
62   /**
63    * Returns a constant
64    *
65    * @param env the quercus calling environment
66    * @param name the constant name
67    */

68   public static Value constant(Env env, String JavaDoc name)
69   {
70     return env.getConstant(name);
71   }
72
73   /**
74    * Prints a debug version of the variable
75    *
76    * @param env the quercus calling environment
77    * @param v the variable to print
78    * @return the escaped stringPhp
79    */

80   public static Value debug_zval_dump(Env env, @ReadOnly Value v)
81   {
82     try {
83       debug_impl(env, v, 0);
84
85       return NullValue.NULL;
86     } catch (IOException JavaDoc e) {
87       throw new QuercusModuleException(e);
88     }
89   }
90
91   /**
92    * Prints a debug version of the variable
93    *
94    * @param env the quercus calling environment
95    * @param v the variable to print
96    * @return the escaped stringPhp
97    */

98   public static Value var_dump(Env env, @ReadOnly Value v)
99   {
100     try {
101       if (v == null)
102     env.getOut().print("NULL#java");
103       else
104     v.varDump(env, env.getOut(), 0, new IdentityHashMap JavaDoc<Value,String JavaDoc>());
105
106       env.getOut().println();
107
108       return NullValue.NULL;
109     } catch (IOException JavaDoc e) {
110       throw new QuercusModuleException(e);
111     }
112   }
113
114   /**
115    * Defines a constant
116    *
117    * @param env the quercus calling environment
118    * @param name the constant name
119    * @param value the constant value
120    */

121   public static Value define(Env env,
122                  String JavaDoc name,
123                  Value value,
124                  @Optional boolean isCaseInsensitive)
125   {
126     return env.addConstant(name, value, isCaseInsensitive);
127   }
128
129   /**
130    * Returns true if the constant is defined.
131    *
132    * @param env the quercus calling environment
133    * @param name the constant name
134    */

135   public static boolean defined(Env env, StringValue name)
136   {
137     return env.isDefined(name.toString());
138   }
139
140   /**
141    * Converts to a double
142    *
143    * @param v the variable to convert
144    * @return the double value
145    */

146   public static Value doubleval(@ReadOnly Value v)
147   {
148     return floatval(v);
149   }
150
151   /**
152    * Returns true for an empty variable.
153    *
154    * @param v the value to test
155    *
156    * @return true if the value is empty
157    */

158   public static boolean empty(@ReadOnly Value v)
159   {
160     v = v.toValue();
161
162     if (v instanceof NullValue)
163       return true;
164     else if (v instanceof StringValue) {
165       String JavaDoc s = v.toString();
166
167       return (s.equals("") || s.equals("0"));
168     }
169     else if (v instanceof LongValue) {
170       return v.toLong() == 0;
171     }
172     else if (v instanceof BooleanValue) {
173       return ! v.toBoolean();
174     }
175     else if (v instanceof ArrayValue) {
176       ArrayValue array = (ArrayValue) v;
177
178       return array.getSize() == 0;
179     }
180     else
181       return false;
182   }
183
184   /**
185    * Converts to a double
186    *
187    * @param v the variable to convert
188    * @return the double value
189    */

190   public static Value floatval(@ReadOnly Value v)
191   {
192     return new DoubleValue(v.toDouble());
193   }
194
195   /**
196    * Returns the defined variables in the current scope.
197    */

198   @UsesSymbolTable
199   public static Value get_defined_vars(Env env)
200   {
201     ArrayValue result = new ArrayValueImpl();
202
203     HashMap JavaDoc<String JavaDoc,Var> map = env.getEnv();
204
205     for (Map.Entry JavaDoc<String JavaDoc,Var> entry : map.entrySet()) {
206       result.append(new StringValueImpl(entry.getKey()),
207             entry.getValue().toValue());
208     }
209
210     HashMap JavaDoc<String JavaDoc,Var> globalMap = env.getGlobalEnv();
211     if (map != globalMap) {
212       for (Map.Entry JavaDoc<String JavaDoc,Var> entry : globalMap.entrySet()) {
213     result.append(new StringValueImpl(entry.getKey()),
214               entry.getValue().toValue());
215       }
216     }
217
218     return result;
219   }
220
221   /**
222    * Returns the type string for the variable
223    */

224   public static String JavaDoc gettype(@ReadOnly Value v)
225   {
226     return v.getType();
227   }
228
229   public static Value get_resource_type(Value v)
230   {
231     if (! (v instanceof JavaValue))
232       return BooleanValue.FALSE;
233
234     Object JavaDoc obj = v.toJavaObject();
235
236     try {
237       Method JavaDoc m = obj.getClass().getMethod("getResourceType",
238                       new Class JavaDoc[0]);
239
240       if (m != null)
241     return StringValue.create(String.valueOf(m.invoke(obj)));
242     } catch (Exception JavaDoc e) {
243     }
244     
245     return StringValue.create("Unknown");
246   }
247
248   /**
249    * Imports request variables
250    *
251    * @param types the variables to import
252    * @param prefix the prefix
253    */

254   public static boolean import_request_variables(Env env,
255                          String JavaDoc types,
256                          @Optional String JavaDoc prefix)
257   {
258     if ("".equals(prefix))
259       env.notice(L.l("import_request_variables should use a prefix argument"));
260
261     for (int i = 0; i < types.length(); i++) {
262       char ch = types.charAt(i);
263
264       Value value = null;
265
266       if (ch == 'c' || ch == 'C')
267     value = env.getGlobalValue("_COOKIE");
268       else if (ch == 'g' || ch == 'G')
269     value = env.getGlobalValue("_GET");
270       else if (ch == 'p' || ch == 'P')
271     value = env.getGlobalValue("_POST");
272
273       if (! (value instanceof ArrayValue))
274     continue;
275
276       ArrayValue array = (ArrayValue) value;
277
278       for (Map.Entry JavaDoc<Value,Value> entry : array.entrySet()) {
279     String JavaDoc key = entry.getKey().toString();
280
281     env.setGlobalValue(prefix + key,
282              array.getRef(entry.getKey()));
283       }
284     }
285
286     return true;
287   }
288
289   /**
290    * Converts to a long
291    *
292    * @param v the variable to convert
293    * @return the double value
294    */

295   public static long intval(@ReadOnly Value v)
296   {
297     return v.toLong();
298   }
299
300   /**
301    * Returns true for an array.
302    *
303    * @param v the value to test
304    *
305    * @return true for an array
306    */

307   public static boolean is_array(@ReadOnly Value v)
308   {
309     return v.isArray();
310   }
311
312   /**
313    * Returns true for a boolean
314    *
315    * @param v the value to test
316    *
317    * @return true for a boolean
318    */

319   public static Value is_bool(@ReadOnly Value v)
320   {
321     return (v.toValue() instanceof BooleanValue
322         ? BooleanValue.TRUE
323         : BooleanValue.FALSE);
324   }
325
326   /**
327    * Returns true for a scalar
328    *
329    * @param v the value to test
330    *
331    * @return true for a scalar
332    */

333   public static boolean is_scalar(@ReadOnly Value v)
334   {
335     if (v==null)
336       return false;
337
338     Value value = v.toValue();
339     return
340       value instanceof DoubleValue ||
341       value instanceof StringValue ||
342       value instanceof LongValue ||
343       value instanceof BooleanValue;
344   }
345
346   /**
347    * Returns the type string for the variable
348    */

349   public static boolean is_callable(Env env,
350                     Value v,
351                     @Optional boolean isSyntaxOnly,
352                     @Optional @Reference Value nameRef)
353   {
354     if (v instanceof StringValue) {
355       if (nameRef != null)
356     nameRef.set(v);
357
358       if (isSyntaxOnly)
359     return true;
360       else
361     return env.findFunction(v.toString().intern()) != null;
362     }
363     else if (v instanceof ArrayValue) {
364       Value obj = v.get(LongValue.ZERO);
365       Value name = v.get(LongValue.ONE);
366
367       if (! (name instanceof StringValue))
368     return false;
369
370       if (nameRef != null)
371     nameRef.set(name);
372
373       if (obj instanceof StringValue) {
374     if (isSyntaxOnly)
375       return true;
376
377     QuercusClass cl = env.findClass(obj.toString().intern());
378     if (cl == null)
379       return false;
380
381     return (cl.findFunction(name.toString().intern()) != null);
382       }
383       else if (obj.isObject()) {
384     if (isSyntaxOnly)
385       return true;
386
387     return obj.findFunction(name.toString().intern()) != null;
388       }
389       else
390     return false;
391     }
392     else
393       return false;
394   }
395
396   /**
397    * Returns true for a double
398    *
399    * @param v the value to test
400    *
401    * @return true for a double
402    */

403   public static boolean is_double(@ReadOnly Value v)
404   {
405     return is_float(v);
406   }
407
408   /**
409    * Returns true for a double
410    *
411    * @param v the value to test
412    *
413    * @return true for a double
414    */

415   public static boolean is_float(@ReadOnly Value v)
416   {
417     return (v.toValue() instanceof DoubleValue);
418   }
419
420   /**
421    * Returns true for an integer
422    *
423    * @param v the value to test
424    *
425    * @return true for a double
426    */

427   public static Value is_int(@ReadOnly Value v)
428   {
429     return (v.toValue() instanceof LongValue
430         ? BooleanValue.TRUE
431         : BooleanValue.FALSE);
432   }
433
434   /**
435    * Returns true for an integer
436    *
437    * @param v the value to test
438    *
439    * @return true for a double
440    */

441   public static Value is_integer(@ReadOnly Value v)
442   {
443     return is_int(v);
444   }
445
446   /**
447    * Returns true for an integer
448    *
449    * @param v the value to test
450    *
451    * @return true for a double
452    */

453   public static Value is_long(@ReadOnly Value v)
454   {
455     return is_int(v);
456   }
457
458   /**
459    * Returns true for null
460    *
461    * @param v the value to test
462    *
463    * @return true for null
464    */

465   public static boolean is_null(@ReadOnly Value v)
466   {
467     return v.isNull();
468   }
469
470   /**
471    * Returns true for numeric
472    *
473    * @param env the calling environment
474    * @param v the value to test
475    *
476    * @return true for numeric
477    */

478   public static boolean is_numeric(Env env, @ReadOnly Value v)
479   {
480     return v.isNumeric();
481   }
482
483   /**
484    * Returns true for an object
485    *
486    * @param env the calling environment
487    * @param v the value to test
488    *
489    * @return true for object
490    */

491   public static boolean is_object(Env env, @ReadOnly Value v)
492   {
493     return v.isObject();
494   }
495
496   /**
497    * Returns true for a real
498    *
499    * @param v the value to test
500    *
501    * @return true for a real
502    */

503   public static boolean is_real(@ReadOnly Value v)
504   {
505     return is_float(v);
506   }
507
508   /**
509    * Returns true if the value is a resource
510    */

511   public boolean is_resource(@ReadOnly Value value)
512   {
513     return (value.toValue() instanceof ResourceValue);
514   }
515
516   // XXX: is_scalar
517

518   /**
519    * Returns true if the value is a string
520    */

521   public boolean is_string(@ReadOnly Value value)
522   {
523     return (value.toValue() instanceof StringValue);
524   }
525
526   /**
527    * Returns the type string for the variable
528    */

529   public static boolean isset(@ReadOnly Value v)
530   {
531     return v.isset();
532   }
533
534   /**
535    * Converts to a string
536    *
537    * @param env the quercus calling environment
538    * @param v the variable to convert
539    * @return the double value
540    */

541   public static Value strval(Env env, @ReadOnly Value v)
542   {
543     if (v instanceof StringValue)
544       return (StringValue) v;
545     else
546       return new StringValueImpl(v.toString());
547   }
548
549   /**
550    * Escapes a string using C syntax.
551    *
552    * @param env the quercus calling environment
553    * @param v the variable to print
554    * @return the escaped stringPhp
555    */

556   public static Value print_r(Env env,
557                   @ReadOnly Value v,
558                   @Optional Value isRet)
559   {
560     // XXX: isRet is ignored
561

562     try {
563       WriteStream out = env.getOut();
564
565       v.printR(env, out, 0, new IdentityHashMap JavaDoc<Value, String JavaDoc>());
566
567       return BooleanValue.FALSE;
568     } catch (IOException JavaDoc e) {
569       throw new QuercusModuleException(e);
570     }
571   }
572
573   private static void printDepth(WriteStream out, int depth)
574     throws IOException JavaDoc
575   {
576     for (int i = 0; i < depth; i++)
577       out.print(' ');
578   }
579
580   /**
581    * Serializes the value to a string.
582    */

583   public static String JavaDoc serialize(@ReadOnly Value v)
584   {
585     StringBuilder JavaDoc sb = new StringBuilder JavaDoc();
586
587     v.serialize(sb);
588
589     return sb.toString();
590   }
591
592   /**
593    * Converts the variable to a specified tyep.
594    */

595   public static boolean settype(Env env,
596                 @Reference Value var,
597                 String JavaDoc type)
598   {
599     Value value = var.toValue();
600
601     if ("null".equals(type)) {
602       var.set(NullValue.NULL);
603       return true;
604     }
605     else if ("boolean".equals(type) || "bool".equals(type)) {
606       var.set(value.toBoolean() ? BooleanValue.TRUE : BooleanValue.TRUE);
607       return true;
608     }
609     else if ("string".equals(type)) {
610       var.set(new StringValueImpl(value.toString()));
611       return true;
612     }
613     else if ("int".equals(type) || "integer".equals(type)) {
614       var.set(new LongValue(value.toLong()));
615       return true;
616     }
617     else if ("float".equals(type) || "double".equals(type)) {
618       var.set(new DoubleValue(value.toDouble()));
619       return true;
620     }
621     else if ("object".equals(type)) {
622       var.set(value.toObject(env));
623       return true;
624     }
625     else if ("array".equals(type)) {
626       if (value.isArray())
627     var.set(value);
628       else
629     var.set(new ArrayValueImpl().append(value));
630       return true;
631     }
632     else
633       return false;
634   }
635
636   /**
637    * Unserializes the value from a string.
638    */

639   public static Value unserialize(Env env, StringValue s)
640   {
641     Value v = _unserializeCache.get(s);
642
643     if (v != null)
644       return v.copy(env);
645     
646     try {
647       UnserializeReader is = new UnserializeReader(s);
648
649       v = is.unserialize(env);
650     } catch (Throwable JavaDoc e) {
651       log.log(Level.FINE, e.toString(), e);
652
653       env.notice(e.toString());
654
655       v = BooleanValue.FALSE;
656     }
657
658     _unserializeCache.put(s, v.copy(env));
659
660     return v;
661   }
662
663   /**
664    * Serializes the value to a string.
665    */

666   public static Value var_export(Env env,
667                  @ReadOnly Value v,
668                  @Optional boolean isReturn)
669   {
670     StringBuilder JavaDoc sb = new StringBuilder JavaDoc();
671
672     v.varExport(sb);
673
674     if (isReturn)
675       return new StringValueImpl(sb.toString());
676     else {
677       env.print(sb);
678
679       return NullValue.NULL;
680     }
681   }
682
683   private static void debug_impl(Env env, Value v, int depth)
684     throws IOException JavaDoc
685   {
686     WriteStream out = env.getOut();
687
688     if (v instanceof Var)
689       out.print("&");
690
691     v = v.toValue();
692
693     if (v instanceof ArrayValue) {
694       ArrayValue array = (ArrayValue) v;
695
696       out.println("Array");
697       printDepth(out, 2 * depth);
698       out.println("(");
699
700       for (Map.Entry JavaDoc<Value,Value> mapEntry : array.entrySet()) {
701     ArrayValue.Entry entry = (ArrayValue.Entry) mapEntry;
702
703         printDepth(out, 2 * depth);
704         out.print(" [");
705         out.print(entry.getKey());
706         out.print("] => ");
707         debug_impl(env, entry.getValue(), depth + 1); // XXX: recursion
708
}
709       printDepth(out, 2 * depth);
710       out.println(")");
711     }
712     else if (v instanceof BooleanValue) {
713       if (v.toBoolean())
714     out.print("bool(true)");
715       else
716     out.print("bool(false)");
717     }
718     else if (v instanceof LongValue) {
719       out.print("int(" + v.toLong() + ")");
720     }
721     else if (v instanceof DoubleValue) {
722       out.print("float(" + v.toDouble() + ")");
723     }
724     else if (v instanceof StringValue) {
725       out.print("string(" + v.toString() + ")");
726     }
727     else if (v instanceof NullValue) {
728       out.print("NULL");
729     }
730     else {
731       v.print(env);
732     }
733   }
734 }
735
736
Popular Tags