יום רביעי, 21 במאי 2014

Ruby define_method simple sample‏

The following Ruby code demonstrates the use of rubies define_method in order to define methods dynamically.

class MyCls
      %w(getData1 getData2).each do |meth|
      define_method(meth) {
        @data[meth.to_sym] = @data[:User] * 2
        @data[meth.to_sym]
        }
  def initialize()
    @data = {}
    @data[:User]= 15 
    end
  end
end
theMyCls = MyCls.new()
puts  theMyCls.getData2
 

Resources
#http://ruby-doc.org/core-2.0/Module.html#method-i-define_method
#http://www.trottercashion.com/2011/02/08/rubys-define_method-method_missing-and-instance_eval.html

יום שלישי, 20 במאי 2014

Zero MQ Pub Sub Simple Sample

The following is a simple 0MQ tcp pub sub simple sample:
The main:

        ZMQ.Context context = ZMQ.context(1);
   
        ZeroMqPubServer theZeroMqPubServer = new ZeroMqPubServer(context);
        theZeroMqPubServer.start();
      
        ZeroMqSubClient theZeroMqSubClient = new ZeroMqSubClient(context);
        
        theZeroMqSubClient.start();
The server

import java.util.logging.Level;
import java.util.logging.Logger;
import org.zeromq.ZMQ;
public class ZeroMqPubServer  extends Thread{
    
    ZMQ.Context  mContext;
    public ZeroMqPubServer(ZMQ.Context pContext) {
        this.mContext = pContext;
    }
    
     @Override
     public void run()
     {
         ZMQ.Socket publisher = mContext.socket(ZMQ.PUB);
        publisher.bind("tcp://*:5556");
        int theCounter = 0 ; 
         while (!Thread.currentThread ().isInterrupted ()) {
            try {
                theCounter++;
                //  Send message to all subscribers
                String update = String.format("MyTopic %d ", theCounter);
                
                publisher.send(update, 0);
                
                Thread.sleep(100);
            }
            // context.term ();
            catch (InterruptedException ex) {
                Logger.getLogger(ZeroMqPubServer.class.getName()).log(Level.SEVERE, null, ex);
            }          
        }
     }
}

The client


import java.nio.charset.Charset;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.zeromq.ZMQ;
public class ZeroMqSubClient  extends Thread{
    
      ZMQ.Context  mContext;
    public ZeroMqSubClient(ZMQ.Context pContext) {
        this.mContext = pContext;
    }
    
    
     @Override
     public void run()
     {
          try {
              Thread.sleep(3000 );
              
              ZMQ.Socket subscriber = mContext.socket(ZMQ.SUB);
              subscriber.connect("tcp://localhost:5556");
              
              //  Subscribe to zipcode, default is NYC, 10001
              String filter =  "MyTopic";
              subscriber.subscribe(filter.getBytes());
              
              while (!Thread.currentThread ().isInterrupted ()) {
                  
                  //  Use trim to remove the tailing '0' character
                  String theStr = subscriber.recvStr(Charset.defaultCharset());
                  
                  System.out.println("Recieved:" + theStr);
              }
              subscriber.close();
              //  mContext.term();
          } catch (InterruptedException ex) {
              Logger.getLogger(ZeroMqSubClient.class.getName()).log(Level.SEVERE, null, ex);
          }
    }
}

The result
debug:
Start
Recieved:MyTopic 31
Recieved:MyTopic 32
Recieved:MyTopic 33
Recieved:MyTopic 34
Recieved:MyTopic 35
Recieved:MyTopic 36
Recieved:MyTopic 37
Recieved:MyTopic 38
Recieved:MyTopic 39
Recieved:MyTopic 40
Recieved:MyTopic 41
Recieved:MyTopic 42
Recieved:MyTopic 43
Recieved:MyTopic 44
Recieved:MyTopic 45
Recieved:MyTopic 46
Recieved:MyTopic 47
Recieved:MyTopic 48
Recieved:MyTopic 49
Recieved:MyTopic 50
Recieved:MyTopic 51
Recieved:MyTopic 52
Recieved:MyTopic 53
Recieved:MyTopic 54
Recieved:MyTopic 55

יום רביעי, 14 במאי 2014

functools partial

The functools.partial allow to  wrapped a method with anew method that has only  partial of the parameters of the wrapped function .
In constract to using lambda for this ‘the functools.partial keep the parameters as reference that can be changed after declaring the wrapper function
Example:

import functools
fullName = lambda pName , pFamily : pName + " "+ pFamily
n = "Zvika"
GetName = lambda y: fullName(n, y)
GetName2 = functools.partial(fullName, n)
print ("n set before creating the lambda")
print (GetName("Peer"), GetName2("Peer"))
print ("n set after creating the lambda")
n = "Alon"
print (GetName("Peer"), GetName2("Peer"))

And the results: 
 n set before creating the lambda
Zvika Peer Zvika Peer
n set after creating the lambda
Alon Peer Zvika Peer


Resources:
http://stackoverflow.com/questions/3252228/python-why-is-functools-partial-necessary

functools @wraps

The functools @wrap allow to keep attributed function original  name
For an example:

from functools import wraps
def myAttribute(func):
    @wraps(func)
    def WrapprintName (*args, **kwargs):
        print ("The method is: " + func.__name__ )
        return func(*args, **kwargs)
    return WrapprintName
@myAttribute
def printName (pName ):
    """Print my name """
    print (pName)
print (printName.__name__)  # prints 'f'
print (printName.__doc__)   # prints 'does some math'
printName ("Zvika")
And the result:
printName
Print my name
The method isprintName
Zvika

The printName method name was kept although the printName method was annotated with @myAttribute

יום ראשון, 11 במאי 2014

Using Jetty and Camel

I wants to switch from Tomcat to jetty in my Camel CFXRS sample .
The first stage is a basic test of the combination of Jetty and Camel.
Add to the pom:

<groupId>org.apache.camel</groupId>
	<artifactId>camel-jetty</artifactId>
	<version>2.12.1</version>
Note: All the Camel compoenents version must match otherwise linkage between components problems may raise.
Add a very simple Route :

   public void configure() {
       
        from("jetty:http://localhost:8080/SayHello").process(new ReplaySimpleHtml());

The request – replay processor:


public class ReplaySimpleHtml implements Processor {
    public void process(Exchange exchange) throws Exception {
        // just get the body as a string
        String body = exchange.getIn().getBody(String.class);
 
        // we have access to the HttpServletRequest here and we can grab it if we need it
        HttpServletRequest req = exchange.getIn().getBody(HttpServletRequest.class);
     
        // send a html response
        exchange.getOut().setBody("<html><body><H3>Hello Mazal Saadon</H3></body></html>");
    }
}

Executing the sample result:


Capture59
Resources:
http://camel.apache.org/jetty.html

should-you-always-pass-the-bare-minimum-data-needed-into-a-function‏

I have found the following architecture dilemma in the following post In my opinion the method: void Authenticate (User pUser )  cause decoupling between the User class and the authenticator class.
In case we will want to authenticate a Roll the Roll should implement inherits from 
User. 
What about IAuthenticatee interface?
This raise the problem of authenticate not using name password group , so I change the name of the interface to INPGAuthenticatee  
Note : 
I think that creating an interface INPGAuthenticatee   that inherits from IAuthenticatee  make thinks too complicated at the first stages of the development and design process in order to KISS at the first stage we will use just the INPGAuthenticatee    interface and if there will be a need to authenticate using other information the authentication  in advanced stages  of the project the authentication mechanism will be refactor. 

I don’t like the option to give the User option to call authenticate directly because it will prevent the option to apply policy for example after 3 authentication failure to lock the account. 
(The policy component should be separate from the authenticate component)

Capture58

Resources:

http://programmers.stackexchange.com/questions/216371/should-you-always-pass-the-bare-minimum-data-needed-into-a-function‏


 

יום שישי, 9 במאי 2014

asyncRequestBody con’t 1

I wanted to check the asyncRequestBody method in more complicated scenarios from the last post.
I Created the following route

   public void configure() {
        
        from("direct:cafeEnterence").to("bean:hostess?method=getTable").to("seda:nextStage");
        
        from("seda:nextStage").to("bean:hostess?method=getVipTable");

and I changed the hostess class to


public class hostess {
    public CafeTable getTable (Guest pGuest)
    {
       System.out.println ("No of people  :" + Integer.toString(pGuest.getmNoOfP()));
        
        return new CafeTable ("Not in the smoking Zone");
    }    
    public CafeTable getVipTable (CafeTable pCafeTable)
    {
        return new CafeTable (pCafeTable.getmLocation() + " and in vip area." );
    }
}

Executing the code:
No of people  :4
The table :CafeTable{mLocation=Not in the smoking Zone and in vip area.}

The future waits for the route to end until it executes its code.

Now lets split the route
Add the guestspliter


public class GuestSplitter {
      public List<Guest> split(Guest pGuest) {
          List<Guest> RetValue = new ArrayList<Guest>();
          for ( int i = 0 ; i < pGuest.getmNoOfP() ; i ++)
          {
              RetValue.add(new Guest ( i) );
          }
          
          return RetValue;
    }
}

Change the route


 from("direct:cafeEnterence").split().method("GuestSplitter").to("bean:hostess?method=getTable");

Now the response of
CafeTable response = future.get(1, TimeUnit.MINUTES);
is null