Wednesday, March 16, 2016

Async patterns in javascript

Generators (Yield) 

The generator will pause itself and the iterator will resume it.  It can start and stop infinite number of time.

function* gen(){
    console.log("Hello");
    //The function will resume itself waiting for the next iterator
    yield null;
    console.log("World");
}

var it=gen();
it.next();   //prints "Hello"
it.next();   //print  "World"










Saturday, March 12, 2016

Create a widget using javascript

Javascript code

function Widget(width,height){
    this.width=width||50;
    this.height=height||50;
    this.$elem=null;
}

Widget.prototype.render=function($where){
    if(this.$elem){
        this.$elem.css({
            width:this.width+"px",
            height:this.height+"px"
        }).appendTo($where);
    }
};

function Button(width,height,label){
    Widget.call(this,width,height);
    this.label=label;
    this.$elem=$("<button>").text(this.label);
}

Button.prototype.render=function($where){
    Widget.prototype.render.call(this,$where);
    this.$elem.bind("click",this.onClick.bind(this));
};

Button.prototype.onClick=function(event){
    //We used this here because we use the hard binding in render function
    console.log("Button '"+ this.label+"' Was clicked");
};

$(document).ready(function(){
    var $body=$(document.body);
    var btn1=new Button(100,50,'Hola');
    var btn2= new Button(200,50,'Hello');

    btn1.render($body);
    btn2.render($body);
});


Equivalent javascript code

var Widget ={
    init: function(width,height){
        this.width=width||50;
        this.height=height||50;
        this.$elem=null;
    },
    insert: function($where){
        if(this.$elem){
            this.$elem.css({
                width:this.width+"px",
                height:this.height+"px"
            }).appendTo($where);
        }
    }
};

var Button =Object.create(Widget);

Button.setup=function(width,height,label){
    this.init(width,height);
    this.label=label||"Default";
    this.$elem=$("<button>").text(this.label);
};

Button.build=function($where){
    this.insert($where);
    this.$elem.click(this.onClick.bind(this));
};

Button.onClick=function(){
    console.log("Button '"+ this.label+"' clicked!");
};

$(document).ready( function(){
    var $body=$(document.body);

    var btn1=Object.create(Button);
    btn1.setup(125,30,"Hello");

    var btn2=Object.create(Button);
    btn2.setup(150,60,"Hola");

    btn1.build($body);
    btn2.build($body);

});


Html code

<html>

<head>
    <script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script type="text/javascript" src="widget.js"></script>
</head>

<body>

</body>


</html>



Friday, March 11, 2016

OLOO: Object Linked to Other Object

I was watching a session by Kyle Simpson about the object inheritance in javascript and he introduced this term that he called OLOO. Where b1 delegates to Bar delegates to Foo as in the example below:

Code

var Foo={
A screenshot from Kyle Simpson slides


    init: function(who){
        this.me=who;
    },
    identify:function(){
        return "I am "+ this.me;
    }
};

var Bar=Object.create(Foo);

Bar.speak=function(){
   
    alert("Hello, "+this.identify() +".");
};

var b1=Object.create(Bar);
b1.init("b1");
b1.speak();








Equivalent complicated code -->


Wednesday, March 2, 2016

Module patterns in javascript


Classic module pattern




ar classicModulePattern=(function(){
   
    var greeting={text: "hi"};

    return {
        sayHi: function(){
            console.log(greeting.text);
        }
    }   

})();


Modified module pattern 

The good thing about this module is that you can update it, you can remove and add attributes while in the classic module you will not be able to update the returned object.

var modifiedModulePattern= (function(){
    var publicAPI={
        sayHi: function(){
            publicAPI.sayBye();
        },
        sayBye:function(){
            console.log('Bye');
        }

    };
    return publicAPI;
})();

modifiedModulePattern.sayHi();


this keyword rules in javascript

I wrote down these notes while watching one of Kyle Simpson workshops about javascript and would like to share them with Y'all :

"Every function, while executing, has a reference to its current execution context, called this. "

There are 4 rules of how this word gets bound in JavaScript: 

"1.Was the function called with 'new' ?
2.Was the function called with 'call' or apply specifying explicit 'this' ?
3. Was the function called via a containing/owning object (context)?
4. Default : global object  "



Rule 1: Default binding rule
When the call site is the default "plain" like in the lines, the function stands alone by itself. The default binding rule applies.

function foo(){
    console.log(this.hi);
}

foo();   <---- function stands alone by itself.

If you are in strict mode, then default is undefined , otherwise define it in the global.


Rule 2: Implicit binding rule
It owns the content of the call site.

function foo(){
    console.log(this.hi);
}

var object1 ={hi:1984,func:foo};
var object2= {hi:2016,func:foo};

 object1.foo();  <---- //1984
object2.foo();   <---- //2016

Rule 3:

Explicit binding
If you use .call or .apply on the call side, They take their parameter as a this.

function sayHi(){
    console.log(this.hi);
} 

var hi="Hola";
var object1={hi:"Hi"};

sayHi();                      <----- //Hola
sayHi.call(object1);    <----- //Hi

Hard binding 
Predictably reference the object that it has to reference.
function sayHi(){
      console.log(this.hi);
}


var object1 ={hi:"Hi"};
var object2 ={hi:"Hola"};


var orig=foo;
sayHi= function(){orig.call(object1)};


sayHi();                     <----- //Hi
sayHi.call(object2);   <----- //Hi



Rule 4: The new key word
There are 4 things happen when the new key word put in front of a function call 
1. A brand new object will be created 
2. That object gets linked to different object    <---- More  clarifications later
3. That object gets bound as this  key word
4.  If that object return nothing, It will implicitly returns this .









 
Example :
var object1={
      var name="Saif";
      printName:function(){
         console.log(name);
      }
}

var object2= {name:"Khaled", printName:object1.printName};

var name="Belal";
var printMe=object1.printMe; 

object1.printMe();    <---- Saif
object1.printMe();    <---- Khaled
printMe();                 <---- Belal



Tuesday, March 1, 2016

Hoisting in javascript

The variables deceleration will be moved to the top during the compilation phase and the variables in the screenshots below will not be printed as undefined.









While in the function example below, We will have undefined values.










The key word let in javascript


let vs. var 

let will hijack implicitly whatever block it appears in.
If you define a variable in the for loop using var, that variable will be available within the function, but if you define it using the let key word, it will be available within the for block only.






 ** I took these snapshots from Kyle Simpson workshop called "Advanced JavaScript"

You should avoid the with keyword in javascript

While watching one of Kyle Simpson workshops, he tried to explain why it is important to avoid using with key word, he even called it more evil than eval (eval is modifying existing lexical scope, the with key creating a whole new lexical scope). In the example below 'd' is not an attribute in obj, javascript will create a 'd' variable in the global scope instead of adding it to obj.


Should I use eval in my #javascript code ? The answer is NO NO NO

While watching one of Kyle Simpson workshops he insisted not to use eval in JavaScript because it impacts the JavaScript performance. 


Three major negatives for using anonymous function expression in JavaScript

While watching one of Kyle Simpson workshops about  JavaScript, he gave three major negatives for using anonymous function expression in JavaScript  as compared to a named function expressions:

1. There is noway inside the function to refers to itself, Say if you want to create recursion. There is noway for the function to refer to itself within itself.

2. They don't play well in debugging, especially in minified code. But if you give it a name, that name will help in the debug trace.

3. give it a name makes it self documented code.




Saturday, February 27, 2016

Closure in JavaScript


 Here are some questions that I solved during one of the online courses. Hope they will help you to understand closure in JavaScript


//Write a function, `nonsense` that takes an input `string`.
//This function contains another function, `blab` which alerts `string`
//and is immediately called inside the function `nonsense`.
// `blab` should look like this inside of the `nonsense` function:



    var nonsense(string){
         var function blab(){
             alert(string);
         };

         blab();
    }



//In your function, `nonsense`,
//change the immediate call to a setTimeout so that the call to `blab` comes after 2 seconds.
//The `blab` function itself should stay the same as before.

    var nonsense(string){
         var function blab(){
             alert(string);
         };
        
         setTimeout(blab(),2000);
    }


//Now, instead of calling `blab` inside of `nonsense`, return `blab` (without invoking it).
//Call `nonsense` with some string and store the returned value (the `blab` function) in a variable called `blabLater`.
//Call `nonsense` again with a different string and store the returned value in a variable called `blabAgainLater`.


     var nonsense(string){
         var function blab(){
             alert(string);
         };
        
         return blab();
    }

    var blabLater=nonsense('My name is Saif');
    var blabAgainLater=nonsense('My name is Khan');


//Write a function with a closure. The first function should only take one argument,
//someone's first name, and the inner function should take one more argument, someone's last name.
//The inner function should console.log both the first name and the last name.

    
    var lastName= function(firstName){
       
        var innerFunction=function(lastName){
            console.log(firstName + ' ' + lastName);
        };

        return innerFunction;
    } 
      

//Create a `storyWriter` function that returns an object with two methods. One method,
//`addWords` adds a word to your story and returns the story while the other one, `erase`,
//resets the story back to an empty string. Here is an implementation:


    var storyWriter= function(){
        var story='';
        return{
            addWords: function(word) {
              story+=' '+ word;
              },
            erase:function(){
                story='';
            },
            logStory:function(){
                console.log(story);
            }
        };
    };


I ran into interesting example that was given by Kyle Simpson about misunderstanding in
 In the first snapshot, We expected the console to print 1, 2, 3 ,4 ,5 but it printed 6,6,6,6,6 instead of that. 
To solve that issue, Kyle suggested to use iffy so that each function will have its own 'i'. 

for (var i=1;i<=5;i++){
    setTimeout(function(){
    console.log("i: "+i);

    },i*1000);
}

for (var i=1;i<=5;i++){
    (function(i){
        setTimeout(function(){
        console.log("i: "+i);

        },i*1000);
    })(i);
}



Sunday, September 13, 2015

Create a custom validation in Spring MVC4

There are few simple steps to create your custom validation :

1- Create a new package (ex. com.yourcompany.view)
2- Create a new annotation like in the screenshot below




3- Add the following annotation to your annotation interface as in the code below

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.Payload;


@Documented
@Constraint(validatedBy=PhoneConstraintValidator.class)
@Target({ElementType.METHOD,ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Phone {

    String message() default "{Phone}";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}


4- Define another class called PhoneConstraintValidator in the same package and the below code

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class PhoneConstraintValidator implements ConstraintValidator<Phone, String> {

    @Override
    public void initialize(Phone phone) {
       
    }


    @Override
    public boolean isValid(String phoneField, ConstraintValidatorContext cxt) {
        if (phoneField == null){
            return false;
        }

        return phoneField.matches("[0-9()-]*");
    }

}



5- Add the annotation to your bean.

Easy !!! Yeah :)


 

Wednesday, July 8, 2015

Rest & Angular - Spring MVC4

To implement Rest & Angular client in MVC4, you need to :

1- Create the rest controller 

@RestController
public class ReleasesReportController {

    @RequestMapping("/releases")
    public List<Release> getReleases(){
        List<Release> releases=new ArrayList<Release>();
       
        Release release1 =new Release();
        release1.setName("Strong bad");
       
        Release release2 =new Release();
        release2.setName("Back to the feature");
       
        Release release3 =new Release();
        release3.setName("Trogdor");
       
        releases.add(release1);
        releases.add(release2);
        releases.add(release3);
       
        return releases;
       
    }
}

2- Add JSON mapping to the WebAppInitializer class 

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        WebApplicationContext context = getContext();
        servletContext.addListener(new ContextLoaderListener(context));
        ServletRegistration.Dynamic dispatcher = servletContext.addServlet("DispatcherServlet", new DispatcherServlet(context));
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("*.html");
        dispatcher.addMapping("*.pdf");
        dispatcher.addMapping("*.json");

    }


3- Bind it to the front end 


<html ng-app>

<head>
<title> Hello Releases Tracker</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js" > </script>
<script type="text/javascript" src="releases.js"></script>
</head>

<body>
    <div ng-controller="Releases">
        I have {{releases.length}} releases !
       
        <ul class="releases-container">
            <li ng-repeat="release in releases">
            {{release.name}}
             </li>
       
        </ul>
    </div>

</body>

</html>


4- Create the angular file (releases.js) under src/main/webapp folder

function Releases($scope, $http){
  
    $http.get('http://localhost:8080/ReleaseTracker/releases.json').
        success(function(data){
        $scope.releases=data;
    });
  
}

Custom validation example - Spring MVC 4


To build a custom validation example you need to:

1-Create an Interface
2-Create a class that implements ConstraintValidator
3-Use the  custom validation in the Bean


 Step 1: 

@Documented
@Constraint(validatedBy=PhoneConstraintValidator.class)
@Target({ElementType.METHOD,ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Phone {

    String message() default "{Phone}";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}


Step 2:

public class PhoneConstraintValidator implements ConstraintValidator<Phone, String> {

    @Override
    public void initialize(Phone phone) {
       
     }

    @Override
    public boolean isValid(String phoneField, ConstraintValidatorContext cxt) {
        if (phoneField == null){
            return false;
        }
        return phoneField.matches("[0-9()-]*");
    }

}


Step 3: 

@NotEmpty @Phone
    private String phoneNumber;

Tuesday, July 7, 2015

Famous Exceptions in Spring MVC 4

java.lang.UnsupportedOperationException: Cannot change HTTP accept header
 
 
The DispatcherServlet  looks for a bean with the name localeResolver.
If this isn't detected it will use the default, 
which is a AcceptHeaderLocaleResovler. 
 
 @Bean
 public MessageSource messageSource(){
  
  ResourceBundleMessageSource messageSource=new 
                ResourceBundleMessageSource();
  messageSource.setBasename("messages");
  return messageSource;
  
 }
 
 @Bean
 public LocaleResolver localeResolver(){
  SessionLocaleResolver resolver =new SessionLocaleResolver();
  resolver.setDefaultLocale(Locale.ENGLISH);
  return resolver;
 }
 
 @Override
 public void addInterceptors(InterceptorRegistry registry)
 {
  LocaleChangeInterceptor changeInterceptor=new 
                LocaleChangeInterceptor();
  changeInterceptor.setParamName("language");
  registry.addInterceptor(changeInterceptor);
 } 

Monday, July 6, 2015

Spring - MVC4 - web.xml file sample

<web-app id="WebApp_ID" version="3.0"
 xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
 http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

 <display-name>Archetype Created Web Application</display-name>

 <servlet>
   <servlet-name>springDispatcherServlet</servlet-name>
   <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  
   <init-param>
       <param-name>contextConfigLocation</param-name>
       <param-value>com.saifmasadeh.WebConfig</param-value>
   </init-param>
  
   <init-param>
       <param-name>contextClass</param-name>
       <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
   </init-param>
  
   <load-on-startup>1</load-on-startup>
 </servlet>

 <servlet-mapping>
   <servlet-name>springDispatcherServlet</servlet-name>
   <url-pattern>*.html</url-pattern>
 </servlet-mapping>

</web-app>

Friday, January 11, 2013

Localization in struts2

1- add this line to the struts.xml file :

<constant name="struts.custom.i18n.resources" value="global" />

2-add the (global.properties) under source package



3-in the (global.properties)

connection.success.message=Connection Success %s


4-to use it in the action, just write the following :

getText("connection.success.message")

Friday, January 4, 2013

Connect multiple DB per Transaction using Hibernate, Struts2 and Spring

Hi Everyone,

I find a solution to connect multiple DB per one transaction using  Hibernate, Struts2 and Spring.
To do that in your project, you need to add Spring Jars:



org.springframework.aop-3.0.5.RELEASE.jar
org.springframework.asm-3.0.5.RELEASE.jar
org.springframework.aspects-3.0.5.RELEASE.jar
org.springframework.beans-3.0.5.RELEASE.jar
org.springframework.context-3.0.5.RELEASE.jar
org.springframework.context.support-3.0.5.RELEASE.jar
org.springframework.core-3.0.5.RELEASE.jar
org.springframework.expression-3.0.5.RELEASE.jar
org.springframework.instrument-3.0.5.RELEASE.jar
org.springframework.instrument.tomcat-3.0.5.RELEASE.jar
org.springframework.jdbc-3.0.5.RELEASE.jar
org.springframework.jdbc.jar
org.springframework.jms-3.0.5.RELEASE.jar
org.springframework.orm-3.0.5.RELEASE.jar
org.springframework.orm.jar
org.springframework.oxm-3.0.5.RELEASE.jar
org.springframework.test-3.0.5.RELEASE.jar
org.springframework.transaction-3.0.0.RELEASE.jar
org.springframework.transaction-3.0.5.RELEASE.jar
org.springframework.web-3.0.2.RELEASE.jar
org.springframework.web-3.0.5.RELEASE.jar
org.springframework.web.jar
org.springframework.web.portlet-3.0.5.RELEASE.jar
org.springframework.web.servlet-3.0.5.RELEASE.jar
org.springframework.web.struts-3.0.5.RELEASE.jar
spring-context-3.0.5.RELEASE.jar
spring-core.jar
commons-dbcp-1.4.jar
commons-pool-1.6.jar

you might don't need all of them. 

and here is the file hierarchies:


applicationContext.xml 


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
 
<bean id="dataSourceBean" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost/test" /> 
<property name="username" value="root" />
<property name="password" value="root" />
</bean>

<bean id="sessionFactoryBean"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSourceBean" />
<property name="mappingResources">
<list>
<value>tracking/User.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<value>hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.hbm2ddl.auto=update
hibernate.show_sql=true
</value>
</property>
</bean>
 
<bean id="hibernateTemplateBean" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory">
<ref bean="sessionFactoryBean" />
</property>
</bean>
<bean id="userDAOBean" class="tracking.UserDAO">
<property name="hibernateTemplate" ref="hibernateTemplateBean" />
</bean>
<bean id="userAction" class="tracking.UserAction">
<property name="userDAO" ref="userDAOBean" />
</bean>
</beans>

UserAction.java

package tracking;

import java.util.ArrayList;
import java.util.List;

import java.sql.Types;

import javax.sql.DataSource;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import tracking.*;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

public class UserAction extends ActionSupport implements ModelDriven<User>

{

private static final long serialVersionUID = 1L;

private User          user         = new User();
private UserDAO          userDAO;

public User getModel()
{
return user;
}


public String test(){
System.out.println(" I am in test I " );
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml", UserAction.class);
System.out.println("ApplicationContext "+ac );
   DataSource dataSource = (DataSource) ac.getBean("dataSourceBean");
   // DataSource mysqlDataSource = (DataSource) ac.getBean("mysqlDataSource");
   System.out.println("dataSource "+dataSource );
   JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
   System.out.println("jdbcTemplate "+jdbcTemplate );
   jdbcTemplate.batchUpdate(new String[] { "update user set idUser = 8 where idUser=1",
       "update user set idUser = 9 where idUser=2" });
    
   return Action.SUCCESS;
}

/**
     * @return the user
     */
    public User getUser()
    {
    return user;
    }

/**
     * @param user the user to set
     */
    public void setUser(User user)
    {
    this.user = user;
    }

/**
     * @return the userDAO
     */
    public UserDAO getUserDAO()
    {
    return userDAO;
    }

/**
     * @param userDAO the userDAO to set
     */
    public void setUserDAO(UserDAO userDAO)
    {
    this.userDAO = userDAO;
    }
}

User.hbm.xml


<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping default-access="field">
    <class name="tracking.User" schema="test" table="user">
     
        <id name="idUser" type="java.lang.Integer">
            <column length="15" name="idUser" />
            <generator class="assigned" />
        </id>
   
    </class>
</hibernate-mapping>


!!!!!!!!!!  Important Note !!!!!!!!!! 

if you get exception while trying to connect the DB, 

TNS:listener does not currently know of SID given in connect descriptor 


use this in the applicationContext.xml 


<bean id="XXX" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=1.1.1.1) (PORT=1525))(CONNECT_DATA=(SERVICE_NAME=XXX)))"/>
<property name="username" value="xxx" />
<property name="password" value="xxx" />
</bean>



http://www.mkyong.com/spring/spring-jdbctemplate-querying-examples/

http://www.mkyong.com/spring/spring-error-classnotfoundexception-org-springframework-web-context-contextloaderlistener/

http://francisoud.blogspot.com/2008/11/simple-jdbc.html

http://www.nabisoft.com/tutorials/struts2/basic-struts2-project-setup#Step4


Tuesday, October 2, 2012

custom converter for BigDecimal struts2

if you are trying to map a BigDecimal field in jsp to the Action, you may get exception,
to solve this exception you need a converter to convert it.

1-you need to define file by the name Action_Name-conversion.properties


attrb1=com.a.b.BigDecimalConverter
attrb2=com.a.b.BigDecimalConverter

2-add the BigDecimalConverter in the package you want


public class BigDecimalConverter extends StrutsTypeConverter{

@Override
public Object convertFromString(Map context, String[] values, Class toClass) {
if(values!=null && values.length>0){
String s=values[0];
if(s!=null && s.trim().length()>0){
BigDecimal bd = new BigDecimal(s);
return bd.setScale(2, BigDecimal.ROUND_HALF_UP);
}
}
return null;
}

@Override
public String convertToString(Map context, Object o) {
return o.toString();

}