Tuesday, June 5, 2012

JavaBeans Introspection

Java Bean are plain old java classes defined as per the patterns laid out by JavaBean Specification.

For an instance, consider the following class.It is a Java Bean with a property 'name';Similar conventions will be used to declare methods and events in Java Bean.

There is fat document that specifies guidelines on how to write compliant java beans.

public class MyJavaBean implements Serializable{
  private String name;
  public String getName(){

 }

 public void setName(){

 }

}

Java Bean came into existence with a sole purpose of allowing software component development, a reusable component.

Reflection is a way for a java programmer to reflect  a class definition programatically.Evey loaded class is associated with an object of type Class in the heap. class 'Class' has got methods that allow one to derive the methods , variables present in a class definition.

Introspection is for java Bean.There is a class 'Introspector' in java.beans package that given a java bean class will fetch JavaBeanInfo object with information like properties, method, events for given java bean class.

In essence it uses reflection api and the guidelines laid out by javabean spec to fetch the above information.

Saturday, May 19, 2012

prototype vs __proto__ or proto Javascript

JavaScript prototype concept ,like closure, is very critical for efficient programming.
ECMA Script specification defines object type as collection of properties.

Each object has an internal property [[prototype]] which is the basis for all the prototype buzz in java script world. Internal property  means a.prototype (a is an object) is undefined.

function chandu(){

}

above declaration creates an object with the following properties

[[prototype]] ::: built in function prototype object
[[construct]]
[[call]]
[[class]] ::: Function
prototype ::: {constructor:chandu}
...

 As you can see we have two prototype properties
(i) [[prototype]] --- this is the object which is searched for when we try to access a property on any object if that property does not exist in the object.

(ii) prototype --- exists only for function objects.This is assigned to [[prototype]] property of any object created using the above function as constructor.
-this object is constructed using the express new Object() where Object is the built in constructor function.
-Object.prototype = the built in Object Prototype Object whose [[prototype]] ==null.This is where the prototype chain ends.

var a = new chandu();

-a is now an object created using chandu() as constructor function
-a's [[prototype]]  now holds the object referred to by the prototype(not the internal one) property of the chandu.
- there is no prototype own property in 'a' like what we had for chandu function object.

a.x  will first see if there is any property in 'a'.If not present it will search in the object referred by [[prototype]] property  of 'a'.


Lets see how the prototype chain looks for 'a'

p1 = a[[prototype]]
p2 = p[[prototype]]
p2 is the built in Object prototype object
p2[[prototype]]=null

Inheritance is achieved through the [[prototype]] internal property.And every ECMA object has this internal property.

Tuesday, May 15, 2012

Obfuscate JavaScript

https://developers.google.com/closure/compiler/docs/overview
Advanced options
https://developers.google.com/closure/compiler/docs/api-tutorial3#export

What is the Closure Compiler?

The Closure Compiler is a tool for making JavaScript download and run faster. It is a true compiler for JavaScript. Instead of compiling from a source language to machine code, it compiles from JavaScript to better JavaScript. It parses your JavaScript, analyzes it, removes dead code and rewrites and minimizes what's left. It also checks syntax, variable references, and types, and warns about common JavaScript pitfalls.
The Closure Compiler has been integrated with Page Speed, which makes it easier to evaluate the performance gains you can get by using the compiler.

How can I use the Closure Compiler?

You can use the Closure Compiler as:


  • An open source Java application that you can run from the command line.
  • A simple web application.
  • A RESTful API.
  • To get started with the compiler, see "How do I start" to the right.

    What are the benefits of using Closure Compiler?

    • Efficiency. The Closure Compiler reduces the size of your JavaScript files and makes them more efficient, helping your application to load faster and reducing your bandwidth needs.
    • Code checking. The Closure Compiler provides warnings for illegal JavaScript and warnings for potentially dangerous operations, helping you to produce JavaScript that is less buggy and easier to maintain.

    javascript : with Statement Considered Harmful


    Mynotes :

    with(obj) , adds the current object to the start of the current execution context's scope.
    with(obj){
      x=10;
    y=10;
    z=10;
    }
     if  the obj does not have a variable x as its property, x will be searched through the rest of the objects in scope and set if any x is found.
     Only if you are sure obj has x use with .

     Code A will rightly assign 11 to propery x of the object passed.
     However Code B will assign 11 to the global variable which is not intended.

    Things are trivial here but i tried to emphasize what 'with' can do if not properly understood and used.

    Code A
     <script>
                var x =10;
                with({x:10}){
                        x=11;
                }
                alert(x);
        </script>

     Code B
     <script>
                var x =10;
                with({y:10}){
                        x=11;
                }
                alert(x);
        </script>

     

    with Statement Considered Harmful

    April 11, 2006 at 7:52 am by Douglas Crockford | In Development | 64 Comments JavaScript’s with statement was intended to provide a shorthand for writing recurring accesses to objects. So instead of writing
    ooo.eee.oo.ah_ah.ting.tang.walla.walla.bing = true;
    ooo.eee.oo.ah_ah.ting.tang.walla.walla.bang = true;
    You can write
    with (ooo.eee.oo.ah_ah.ting.tang.walla.walla) {
        bing = true;
        bang = true;
    }
    That looks a lot nicer. Except for one thing. There is no way that you can tell by looking at the code which bing and bang will get modifed. Will ooo.eee.oo.ah_ah.ting.tang.walla.walla be modified? Or will the global variables bing and bang get clobbered? It is impossible to know for sure.
    The with statement adds the members of an object to the current scope. Only if there is a bing in ooo.eee.oo.ah_ah.ting.tang.walla.walla will ooo.eee.oo.ah_ah.ting.tang.walla.walla.bing be accessed.
    If you can’t read a program and be confident that you know what it is going to do, you can’t have confidence that it is going to work correctly. For this reason, the with statement should be avoided.
    Fortunately, JavaScript also provides a better alternative. We can simply define a var.
    var o = ooo.eee.oo.ah_ah.ting.tang.walla.walla;
    o.bing = true;
    o.bang = true;
    
    Now there is no ambiguity. We can have confidence that it is ooo.eee.oo.ah_ah.ting.tang.walla.walla.bing and ooo.eee.oo.ah_ah.ting.tang.walla.walla.bang that are being set, and not some hapless variables.

    nice crockford articles

    http://www.crockford.com/javascript/

    minification javascript --- Javascript Minifier

    courtesy :
    http://javascript.crockford.com/jsmin.html
    http://yuiblog.com/blog/2006/03/06/minification-v-obfuscation/

    jsmin <fulljslint.js >jslint.js "(c)2002 Douglas Crockford"

    JSMin is a filter which removes comments and unnecessary whitespace from JavaScript files. It typically reduces filesize by half, resulting in faster downloads. It also encourages a more expressive programming style because it eliminates the download cost of clean, literate self-documentation.

    What JSMin Does

    JSMin is a filter that omits or modifies some characters. This does not change the behavior of the program that it is minifying. The result may be harder to debug. It will definitely be harder to read.
    JSMin first replaces carriage returns ('\r') with linefeeds ('\n'). It replaces all other control characters (including tab) with spaces. It replaces comments in the // form with linefeeds. It replaces comments in the /* */ form with spaces. All runs of spaces are replaced with a single space. All runs of linefeeds are replaced with a single linefeed.
    It omits spaces except when a space is preceded and followed by a non-ASCII character or by an ASCII letter or digit, or by one of these characters:
    \ $ _
    It is more conservative in omitting linefeeds, because linefeeds are sometimes treated as semicolons. A linefeed is not omitted if it precedes a non-ASCII character or an ASCII letter or digit or one of these characters:
    \ $ _ { [ ( + -
    and if it follows a non-ASCII character or an ASCII letter or digit or one of these characters:
    \ $ _ } ] ) + - " '
    No other characters are omitted or modified.
    JSMin knows to not modify quoted strings and regular expression literals.
    JSMin does not obfuscate, but it does uglify.
    Before:
    // is.js
    
    // (c) 2001 Douglas Crockford
    // 2001 June 3
    
    
    // is
    
    // The -is- object is used to identify the browser.  Every browser edition
    // identifies itself, but there is no standard way of doing it, and some of
    // the identification is deceptive. This is because the authors of web
    // browsers are liars. For example, Microsoft's IE browsers claim to be
    // Mozilla 4. Netscape 6 claims to be version 5.
    
    var is = {
        ie:      navigator.appName == 'Microsoft Internet Explorer',
        java:    navigator.javaEnabled(),
        ns:      navigator.appName == 'Netscape',
        ua:      navigator.userAgent.toLowerCase(),
        version: parseFloat(navigator.appVersion.substr(21)) ||
                 parseFloat(navigator.appVersion),
        win:     navigator.platform == 'Win32'
    }
    is.mac = is.ua.indexOf('mac') >= 0;
    if (is.ua.indexOf('opera') >= 0) {
        is.ie = is.ns = false;
        is.opera = true;
    }
    if (is.ua.indexOf('gecko') >= 0) {
        is.ie = is.ns = false;
        is.gecko = true;
    }
    After:
    var is={ie:navigator.appName=='Microsoft Internet Explorer',java:navigator.javaEnabled(),ns:navigator.appName=='Netscape',ua:navigator.userAgent.toLowerCase(),version:parseFloat(navigator.appVersion.substr(21))||parseFloat(navigator.appVersion),win:navigator.platform=='Win32'}
    is.mac=is.ua.indexOf('mac')>=0;if(is.ua.indexOf('opera')>=0){is.ie=is.ns=false;is.opera=true;}
    if(is.ua.indexOf('gecko')>=0){is.ie=is.ns=false;is.gecko=true;}

    Character Set

    JSMin requires, but does not verify, that the character set encoding of the input program is either ASCII or UTF-8. It might not work correctly with other encodings.

    Caution

    Be sure to retain your original source file. JSMin is a one-way trip: Once done, it cannot be undone.
    Do not put raw control characters inside a quoted string. That is an extremely bad practice. Use \xhh notation instead. JSMin will replace control characters with spaces or linefeeds.
    Use parens with confusing sequences of + or -. For example, minification changes
    a + ++b
    into
    a+++b
    which is interpreted as
    a++ + b
    which is wrong. You can avoid this by using parens:
    a + (++b)
    JSLint checks for all of these problems. It is suggested that JSLint be used before using JSMin.

    Command Line Options

    Optional parameters will be listed at the beginning of the output as comments. This is a convenient way of replacing copyright messages and other documentation.
    Example:
    jsmin <fulljslint.js >jslint.js "(c)2002 Douglas Crockford"

    Errors

    JSMin can produce three error messages to stderr:
    Unterminated comment. Unterminated string constant.
    Unterminated regular expression.
    It ignores all other errors that may be present in your source program.

    Get Minified

    You can get a zip file containing an MS-DOS.exe file, or you can get the C source code and build it yourself.
    Copyright 2001 Douglas Crockford. All Rights Reserved Wrrrldwide.

    IE Memory leak javascript

    http://javascript.crockford.com/memory/leak.html