Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-9 of 9 total  RSS 

Call a function on all items in an array and collect responses

   1  
   2  # The invisible proxy allows seamless calling of a method on all objects of an array.
   3  # When an array is wrapped (passed into) one of these objects, you can call a function
   4  # on all objects in the array with one line.
   5  
   6  # This is not how this works exactly, but a good resource:
   7  #   http://alisdair.mcdiarmid.org/2005/12/20/invisible-proxies-with-ruby
   8  
   9  class InvisibleProxyToArray
  10  
  11    instance_methods.each do |m|
  12      undef_method(m) unless m =~ /(^__|^nil\\?|^send)/
  13    end
  14    
  15    def initialize(collection)
  16      @collection = collection
  17    end
  18  
  19    def respond_to?(symbol)
  20      @collection.first.respond_to?(symbol)
  21    end
  22     
  23    # calls a method on every member of the proxied array
  24    # and totals the return values
  25    def total(total_symbol)
  26      total=0
  27      @collection.each{|obj|total= total + obj.send(total_symbol)}
  28      total
  29    end
  30    
  31    
  32    # gives a string indicating object responses to being sent a symbol (which calls a property or method)
  33    # summarize(:status) will produce:  running (2), stopping (13)
  34    def summarize(summarize_symbol)
  35      msgs=[]
  36      hsh=hash_by_result(summarize_symbol, @collection)
  37      hsh.each {|status, resources_arr| msgs << "#{status} (#{resources_arr.length})"}
  38      msgs.join(',')
  39    end
  40    
  41    # returns a hash like {"running"=>[a , b], "dead"=>[a]} for :status or other messages
  42    # where a and b would be resources whose response for :status was "running"
  43    def hash_by_result(property_symbol,object_array)
  44      hsh={} 
  45      object_array.each do |obj|
  46        hsh[obj.send(property_symbol)] ||= []
  47        hsh[obj.send(property_symbol)] << obj 
  48      end
  49      hsh
  50    end
  51     
  52    
  53    private
  54  
  55    def method_missing(method, *args, &block)
  56      @collection.each {|item| item.send(method, *args, &block)}
  57    end
  58    
  59  end

Creating a Service Class for Amfphp

Here is a very helpful script for creating a connection between your Flex/Flash application and amfphp.

We are mimicking the available methods that are on our server. You could easily add methods to both ends to create more functionality.

Code is used as follows:


   1  
   2  package com.jonniespratley.snippr.services
   3  {
   4      import com.jonniespratley.snippr.model.ModelLocator;
   5      import com.jonniespratley.snippr.vo.SnippetVO;
   6      
   7      import flash.net.NetConnection;
   8      import flash.net.Responder;
   9      import flash.utils.ByteArray;
  10      
  11      import mx.collections.ArrayCollection;
  12      import mx.controls.Alert;
  13      import mx.controls.Image;
  14      import mx.controls.Text;
  15      import mx.core.Window;
  16      import mx.rpc.events.ResultEvent;
  17      
  18      /**
  19       * This file is for use without! using the services-config.xml file 
  20       * @author Jonnie
  21       * 
  22       */    
  23      public class SnipprService
  24      {
  25          private static var _service:NetConnection;
  26          private var model:ModelLocator = ModelLocator.getInstance();
  27          
  28          //Here we are creating a new connection to our amfphp service, when this is instantiated, it connects to our service
  29          public function SnipprService()
  30          {
  31              _service = new NetConnection();
  32              _service.connect( "http://localhost/snippr/amfphp/gateway.php" );
  33          }        
  34          
  35          
  36          /* ***************************************
  37          *** Service Calls
  38          *****************************************/
  39          
  40          //Here we are calling the getSnippets on our server (amfphp) and setting the result and fault handlers
  41          public function getSnippets():void
  42          {
  43              _service.call( "snippr.SnipprService.getSnippets", new Responder( snippetResultHandler, snipprFaultHandler ) );
  44          }
  45          
  46          //We take one argument here, and that is a snippet, because our server (amfphp) is expecting a snippetVO
  47          public function saveSnippet( snippet:SnippetVO ):void
  48          {
  49              _service.call( "snippr.SnipprService.saveSnippet", new Responder( snippetSavedHandler, snipprFaultHandler ), snippet );
  50          }
  51          
  52          //We take one argument here, and that is the id of the snippet we are wanting to remove
  53          public function removeSnippet( snippet_id:uint ):void
  54          {
  55              _service.call( "snippr.SnipprService.removeSnippet", new Responder( snippetRemoveHandler, snipprFaultHandler ), snippet_id );
  56          }
  57          
  58          //We take two arguments here, one is a byte array and the other is the filename of the file
  59          public function takeSnapshot( bytes:ByteArray, filename:String ):void
  60          {
  61              _service.call( "snippr.SnipprService.takeSnapshot", new Responder( snapshotResultHandler, snipprFaultHandler ), bytes, filename );
  62          }        
  63          
  64          /* ***************************************
  65          *** Result and Fault Handlers
  66          *****************************************/
  67          
  68          //Here we are handling the result coming back as an array of snippets, then we add our snippets to our model        
  69          private function snippetResultHandler( data:Array ):void
  70          {            
  71              model.snippetCollection = initVO( data );
  72          }
  73          
  74          private function snapshotResultHandler( data:Object ):void
  75          {
  76              var result:ResultEvent = data as ResultEvent;
  77                          
  78              /* This is just for some fun */
  79              var w:Window = new Window();
  80                  w.width = 600;
  81                  w.height = 500;
  82                  w.layout = "vertical";
  83                  
  84              var i:Image = new Image();                                
  85                  i.source = data.result;
  86                  
  87              var t:Text = new Text();
  88                  t.text = "Nice shot, and nice app, Here is the link for the screenshot.\n " + data.result;
  89                  
  90                  w.addChild( i );
  91                  w.addChild( t );            
  92                  w.open();            
  93                  
  94              trace( data.result );
  95          }
  96          
  97          //Helper for the result
  98          private function initVO( resultArray:Array ):ArrayCollection
  99          {
 100              var tempArray:ArrayCollection = new ArrayCollection();
 101              
 102              for ( var s:String in resultArray )
 103              {
 104                  tempArray.addItem( new SnippetVO( resultArray[s] ) );
 105                  
 106              }
 107              return tempArray;
 108          }
 109          
 110          //Here we are handling the result and adding it to the value of serviceResponse in our model
 111          private function snippetSavedHandler( data:Object ):void
 112          {
 113              ModelLocator.getInstance().serviceResponse = data.toString();
 114          }
 115          
 116          /*
 117          Here we are handling the result that is being returned, which will be the id of the removed snippet, and 
 118          removing it from our model, at the snippet index
 119          */
 120          private function snippetRemoveHandler( data:Object ):void
 121          {
 122              getSnippets();
 123          }
 124          
 125          //Here we are alerting the user that there was an error connection to our server
 126          private function snipprFaultHandler( fault:Object ):void
 127          {
 128  
 129              Alert.show( "There was an error connecting to the server.", "Snippr Service Error" );
 130          }        
 131      }        
 132  }


Here is the value object for this class

   1  
   2  package com.jonniespratley.snippr.vo
   3  {	
   4  	[RemoteClass(alias="vo.SnippetVO")]
   5  	
   6  	/**
   7   	* VOs are used to create a layer of business objects that can be 
   8   	* transferred between tiers, instead of using records, results sets, and datasets.
   9   	*/
  10  	[Bindable]
  11  	public class SnippetVO
  12  	{
  13  		public var snippet_id:int;
  14  		public var snippet_title:String;
  15  		public var snippet_code:String;
  16  		public var snippet_type:String;
  17  		public var snippet_created:String;
  18  		public var snippet_user:String;		
  19  		
  20  		/**
  21  		 * Helper function for building the data. 
  22  		 * @param source
  23  		 * 
  24  		 */		
  25  		public function SnippetVO( source:Object = null )
  26  		{
  27  			if ( source != null )
  28  			{
  29  				for ( var item:String in source )
  30  				{
  31  					try 
  32  					{
  33  						this[item] = source[item];
  34  					}
  35  					catch ( error:Error )
  36  					{
  37  						throw new Error( "SnippetVO: " + error );
  38  					}
  39  				}
  40  			}
  41  		}
  42  	}
  43  }

Squid Conf file

Personal squid conf file. Allowing AIM ports and all web browsing.

   1  
   2  cache_dir ufs /Users/dave/Library/Caches/squid 100 16 256
   3  acl dontcacheanything src 0/0
   4  no_cache deny dontcacheanything
   5  maximum_object_size 32768 KB
   6  http_port 28080
   7  visible_hostname localhost
   8  cache_access_log /Users/dave/Library/Logs/squid-access.log
   9  cache_log /Users/dave/Library/Logs/squid-cache.log
  10  cache_store_log /Users/dave/Library/Logs/squid-store
  11  pid_filename /tmp/squid.pid
  12  hierarchy_stoplist cgi-bin ?
  13  acl QUERY urlpath_regex cgi-bin 
  14  no_cache deny QUERY
  15  acl all src 0.0.0.0/0.0.0.0
  16  acl AIM_ports port 5190 9898 6667
  17  acl AIM_domains dstdomain .oscar.aol.com .blue.aol.com .freenode.net
  18  acl AIM_domains dstdomain .messaging.aol.com .aim.com
  19  acl AIM_hosts dstdomain login.oscar.aol.com login.glogin.messaging.aol.com toc.oscar.aol.com irc.freenode.net
  20  acl AIM_nets dst 64.12.0.0/255.255.0.0
  21  acl AIM_methods method CONNECT
  22  http_access allow AIM_methods AIM_ports AIM_nets
  23  http_access allow AIM_methods AIM_ports AIM_hosts
  24  http_access allow AIM_methods AIM_ports AIM_domains
  25  acl manager proto cache_object
  26  acl localhost src 127.0.0.1/255.255.255.255
  27  acl SSL_ports port 443 563 1863 5190 5222 5050 6667 8443
  28  acl Safe_ports port 80 81 21 443 563 70 210 1025-65535 280 488 591 777
  29  acl CONNECT method CONNECT
  30  http_access allow manager localhost
  31  http_access deny manager
  32  http_access deny !Safe_ports
  33  http_access deny CONNECT !SSL_ports
  34  http_access allow all
  35  http_access deny all
  36  always_direct deny all

Using an Apache proxy RewriteRule

This Apache Rewrite instruction uses the url http://mywebsite.com/cards as a proxy to access another web server within the LAN.

   1  
   2          RewriteEngine on
   3          RewriteRule ^cards$ http://192.168.1.15/ [P]

Exposing an interface at runtime using a proxy class

Force an object expose an interface at runtime, through a generated proxy class. It must implement all required methods.
Requires BCEL.

UPDATED: does verification at bridge generation time.
expose(Object, Class) will search for the correct public target type to use.
UPDATED: performance hacks.

Example usage:
   1  public class BridgeTest {
   2    public interface CharList {
   3      public int length();
   4      public char charAt(int i);
   5    }
   6    void print(CharList l) {
   7      for(int i=0; i<l.length(); i++)
   8        System.out.print(l.charAt(i));
   9    }
  10    public static void main(String args[]) {
  11      CharList list = Bridge.expose("Hello world\n", CharList.class);
  12      print(list);
  13    }
  14  }


Bridge.java:
   1  /* Make an object expose an interface at runtime */
   2  
   3  import org.apache.bcel.generic.*;
   4  import org.apache.bcel.Constants;
   5  
   6  import java.lang.reflect.Method;
   7  import java.util.*;
   8  
   9  public abstract class Bridge<C,I> {
  10  	protected C __target; // the implementation of the interface
  11  	private final void __init(Object target) { this.__target = (C)target; }
  12  
  13  	// cache already-generated bridges
  14  	private static HashMap<Class, HashMap<Class, Class>> cache 
  15  		= new HashMap<Class, HashMap<Class, Class>>();
  16  	// allow injection of classes from byte arrays
  17  	private static InjectingClassLoader loader = new InjectingClassLoader();
  18  
  19  	private static final void cacheSet(Class key1, Class key2, Class value) {
  20  		HashMap<Class,Class> intermediate = cache.get(key1);
  21  		if(intermediate == null)
  22  			cache.put(key1, intermediate = new HashMap<Class,Class>());
  23  		intermediate.put(key2, value);
  24  	}
  25  	private static final Class cacheGet(Class key1, Class key2) {
  26  		HashMap<Class,Class> intermediate = cache.get(key1);
  27  		if(intermediate == null)
  28  			return null;
  29  		return intermediate.get(key2);
  30  	}
  31  
  32  	// returns [ [ifaceMethods...] [fromMethods...] ]
  33  	private static Method[][] getMapping(Class from, Class iface) throws NoSuchMethodException,IllegalAccessException {
  34  		if(!iface.isInterface())
  35  			throw new IllegalArgumentException(iface.getName()+" is not an interface");
  36  		if(!java.lang.reflect.Modifier.isPublic(from.getModifiers()))
  37  			throw new IllegalAccessException(from.getName()+" is not public");
  38  		java.lang.reflect.Method[][] map = new java.lang.reflect.Method[2][];
  39  		map[0] = iface.getMethods();
  40  		map[1] = new java.lang.reflect.Method[map[0].length];
  41  
  42  		for(int i=0;i<map[0].length;i++) {
  43  			try {
  44  				Method match = from.getMethod(map[0][i].getName(), map[0][i].getParameterTypes());
  45  				if(!map[0][i].getReturnType().isAssignableFrom(match.getReturnType()))
  46  					throw new NoSuchMethodException("Return type "+match.getReturnType().getName()+
  47  						" of "+toString(match)+" is not compatible with return type "+
  48  						map[0][i].getReturnType().getName()+" of "+toString(map[0][i]));
  49  				map[1][i] = match;
  50  			} catch (NoSuchMethodException e) {
  51  				throw new NoSuchMethodException("Couldn't find "+toString(map[0][i])+" in "+
  52  					from.getName());
  53  			}			
  54  		}
  55  		return map;
  56  	}
  57  	private static String toString(Method m) {
  58  		StringBuffer sb = new StringBuffer(m.getDeclaringClass().getName());
  59  		sb.append(".").append(m.getName()).append("(");
  60  		boolean first=true;
  61  		for(Class c : m.getParameterTypes()) {
  62  			if(!first)
  63  				sb.append(", ");
  64  			sb.append(c.getName());	
  65  			first=false;
  66  		}
  67  		sb.append(")");
  68  		return sb.toString();
  69  	}
  70  
  71  	private static <C,I> Class<? extends Bridge<C,I>> create(Class<C> from, Class<I> iface) {
  72  		try {
  73  			Method[][] map = getMapping(from, iface);
  74  
  75  			String bridgeName = "Bridge_"+from.getSimpleName()+"_"+iface.getSimpleName();
  76  			// public class Bridge_Thing_Mungible extends Bridge<Thing,Mungible> implements Mungible
  77  			ClassGen cg = new ClassGen(
  78  				bridgeName,
  79  				Bridge.class.getName(), // superclass name
  80  				"<generated>", // source file name
  81  				Constants.ACC_PUBLIC | Constants.ACC_FINAL | Constants.ACC_SUPER, // flags
  82  				new String [] { iface.getName() } // interfaces
  83  			);
  84  
  85  			ConstantPoolGen cpg = cg.getConstantPool();
  86  			InstructionFactory factory = new InstructionFactory(cg, cpg);
  87  
  88  			ReferenceType targetType = (ReferenceType)Type.getType(from);
  89  
  90  			for(int i=0; i<map[0].length; i++) {
  91  				Method imeth = map[0][i];
  92  				Method fmeth = map[1][i];
  93  
  94  				Type 	ireturnType = Type.getType(imeth.getReturnType()),
  95  					freturnType = Type.getType(fmeth.getReturnType());
  96  				Class[]	iargs = imeth.getParameterTypes(), 
  97  					fargs = fmeth.getParameterTypes();
  98  				Type[] 	iargsT = new Type[iargs.length],
  99  					fargsT = new Type[fargs.length];
 100  				String[] argNames = new String[iargs.length];
 101  				for(int j=0; j<iargs.length; j++) {
 102  					iargsT[j] = Type.getType(iargs[j]);
 103  					fargsT[j] = Type.getType(fargs[j]);
 104  					argNames[j] = "arg"+i;
 105  				}
 106  
 107  				InstructionList il = new InstructionList();
 108  				// public int munge(Object arg0, int arg1) {
 109  				MethodGen mg = new MethodGen(
 110  					Constants.ACC_PUBLIC,
 111  					ireturnType,
 112  					iargsT,
 113  					argNames,
 114  					imeth.getName(),
 115  					bridgeName,
 116  					il, cpg);
 117  
 118  				// (Thing)this.__target
 119  				il.append(new ALOAD(0));
 120  				il.append(factory.createFieldAccess(
 121  					Bridge.class.getName(), 
 122  					"__target", 
 123  					Type.OBJECT, 
 124  					Constants.GETFIELD));
 125  				il.append(factory.createCheckCast(targetType));
 126  				
 127  				// .munge(arg0, arg1);
 128  				int position = 1;
 129  				for(int j=0;j<iargs.length;j++) {
 130  					il.append(factory.createLoad(iargsT[j], position));
 131  					position += iargsT[j].getSize();
 132  				}
 133  				il.append(factory.createInvoke(
 134  					from.getName(), 
 135  					fmeth.getName(), 
 136  					freturnType, 
 137  					fargsT, 
 138  					from.isInterface() ? Constants.INVOKEINTERFACE : Constants.INVOKEVIRTUAL));
 139  
 140  				// return (last result, if any)
 141  				il.append(factory.createReturn(ireturnType));
 142  
 143  				mg.setMaxStack();
 144  				cg.addMethod(mg.getMethod());
 145  				il.dispose(); // Allow instruction handles to be reused
 146  			}
 147  
 148  			// public Bridge_Thing_Mungible() { super(); }
 149  			cg.addEmptyConstructor(Constants.ACC_PUBLIC);
 150  
 151  			try { cg.getJavaClass().dump("proxy.class"); } catch(Exception e) { throw new RuntimeException(e); }
 152  
 153  			byte[] classData = cg.getJavaClass().getBytes();
 154  			Class c = loader.load(cg.getClassName(), classData);
 155  			return (Class<Bridge<C,I>>)c;
 156  		} catch (IllegalAccessException e) { 
 157  			throw new BridgeFailure(from, iface, e); 
 158  		} catch (NoSuchMethodException e) { 
 159  			throw new BridgeFailure(from, iface, e); 
 160  		}
 161  	}
 162  	private static <C,I> Class<? extends Bridge<C,I>> get(Class<C> from, Class<I> iface) {
 163  //		Pair<Class,Class> key = new Pair<Class,Class>(from, iface);
 164  		Class<? extends Bridge<C,I>> bridgeClass = (Class<? extends Bridge<C,I>>)cacheGet(from, iface);
 165  		if(bridgeClass == null) {
 166  			bridgeClass = create(from, iface);
 167  			cacheSet(from, iface, bridgeClass);
 168  		}
 169  		return bridgeClass;
 170  	}
 171  
 172  	// Expose interface iface by creating a proxy. 
 173  	// the type of target must be from, a subclass of from, or a class implementing from.
 174  	// from must be public, and must expose all methods in iface.
 175  	public static <I> I expose(Object target, Class from, Class<I> iface) {
 176  		try {
 177  			Class<? extends Bridge<?,I>> c = Bridge.get(from, iface);
 178  			Bridge<?,I> proxy = c.newInstance();
 179  			proxy.__init(target);
 180  			return (I)proxy;
 181  		} catch (InstantiationException e) {
 182  			throw new RuntimeException(e);
 183  		} catch (IllegalAccessException e) {
 184  			throw new RuntimeException(e);
 185  		}
 186  	}
 187  	
 188  	// Expose interface iface by creating a proxy. 
 189  	// Tries expose(target, target.getClass(), iface) first.
 190  	// then works up the class hierarchy. If doesn't find a public superclass 
 191  	// that exposes all methods, it tries interfaces.
 192  	// if you know in advance the class or interface that exposes the needed methods,
 193  	// use expose(target, Class.forName("ExposingClass"), iface).
 194  	public static <I> I expose(Object target, Class<I> iface) {
 195  		Class tClass = target.getClass();
 196  
 197  		Class from = tClass;
 198  		do {			
 199  			try {
 200  				I result = expose(target, from, iface);
 201  				if(tClass != from) // if tClass == tFrom then get() sets the cache
 202  					cacheSet(tClass, iface, result.getClass());
 203  				return result;
 204  			} catch (BridgeFailure e) {
 205  				Throwable cause = e.getCause();
 206  				if(cause instanceof NoSuchMethodException) {
 207  					// have traced superclass up until the interface isn't satisfied.
 208  					// try interfaces and then give up.
 209  					// in the case of a private implementation of a public interface, 
 210  					// this allows you to subset the interface.
 211  					Class[] targetIfaces = target.getClass().getInterfaces();
 212  					for(Class targetIface : targetIfaces) 
 213  						try {
 214  							I result = expose(target, targetIface, iface);
 215  							cacheSet(tClass, iface, result.getClass()); // perf hack
 216  							return result;
 217  							// ignore, reported exception is that for class hierarchy.
 218  						} catch (BridgeFailure ex) {} 
 219  					throw new BridgeFailure(target, iface, e);
 220  				} else if(!(cause instanceof IllegalAccessException))
 221  					throw e;
 222  			}
 223  			from = from.getSuperclass();
 224  		} while(from != null);
 225  		throw new RuntimeException("Object "+target+" ("+target.getClass().getName()+") has no public superclass");
 226  	}
 227  }
 228  class BridgeFailure extends RuntimeException {
 229  	public BridgeFailure(Class from, Class iface, Exception cause) {
 230  		super("Could not map class "+from.getName()+" to interface "+iface.getName());
 231  		initCause(cause);
 232  	}
 233  	public BridgeFailure(Object target, Class iface, Exception cause) {
 234  		super("Could not map first public supertype of " + target +
 235  			" (" + target.getClass().getName() + ")," +
 236  			" or any implemented interface, to interface " + iface.getName());
 237  		initCause(cause);
 238  	}
 239  }
 240  // ClassLoader implementation to let you load classes from byte arrays
 241  class InjectingClassLoader extends ClassLoader { 
 242  	public InjectingClassLoader() {
 243  		super(InjectingClassLoader.class.getClassLoader());
 244  	}
 245  	public Class load(String name, byte[] buffer) {  
 246  		return defineClass(name, buffer, 0, buffer.length);  
 247  	}  
 248  }

Using a proxy for Sockets

   1  
   2  // http or all?
   3  System.getProperties().put( "http.proxyHost", "myProxyMachineName" );
   4  System.getProperties().put( "http.proxyPort", "85" );

Using an HTTP proxy with Universal Feed Parser

without using http_proxy environment variable..

   1  import urllib2, feedparser
   2  
   3  proxy = urllib2.ProxyHandler( {"http":"http://your.proxy.here:8080/"} )
   4  d = feedparser.parse('http://feedparser.org/docs/examples/atom10.xml', handlers = [proxy])

Apache2 proxy to local port

Apache as the receptionist, forwarding requests to and from an internal server (e.g. webrick or lighttpd).

   1  
   2  <VirtualHost *>
   3          ServerName www.example.com
   4          ProxyPass / http://localhost:3000/
   5          ProxyPassReverse / http://localhost:3000/
   6          ProxyPreserveHost On
   7  </VirtualHost>


Change 3000 to whatever port you need and make sure the internal server is set up to answer requests on that port (not port 80). The ProxyPreserveHost line is critical to keep all your URLs working correctly.

Google free proxy

From Google Hack
   1  
   2  http://www.google.com/translate?langpair=en|en&u=www.forbiddensite.com
« Newer Snippets
Older Snippets »
Showing 1-9 of 9 total  RSS