Adsense-HeaderAd-Script


Advertisement #Header

18 Jul 2014

Online Generator tool for Code Syntax formatting


With this tool you can quickly generate the styled html for your source code.  It generate styles for different IDE's like Eclipse, Emacs, Django, etc.  It supports 25 programming languages like Java, HTML, PHP, CSS, Scala, Groovy, etc.

In this new version of Code Syntax Highlighter (v3.0), it uses more modern and minimal styled UI's.

Advantages of Code Syntax Format Tool

  1. Loads vey quickly your styled code rather losing time generating the code via javscript for every time the user visits your site.
  2. It displays the formatted code even if the Javascript is disabled.
  3. Never shows your code in blant plain format initially when your page is loaded.
  4. Simple UI to config the settings
  5. It supports many languages and themes.

To check out the Online Generator follow this link, Online Code Syntax Generator tool

Steps to Generate the Formatted Code Syntax.

  1. Insert the source code to the text area.
  2. Select the Language
  3. Select the Theme style
  4. Click on the Get Formatted HTML  button
  5. Copy the HTML generated and paste it in your website.
  6. Add the external Theme CSS and Javascript library to your website.
<script type="text/javascript" src="http://ajblk.github.io/SyntaxHighlightGenerator-v3.0/scripts/sh-v3.0-min.js"></script>
For the CSS file, choose from the Themes at the bottom of this blog.
  1. Add the below <script> snippet before the </body> end tag.
<script type="text/javascript">
    SyntaxHighlighter.initialize();
</script>

Advanced Options


When Show Gutter  and Show ToolBar  is enabled

img of gutter and toolbar when its enabled in code syntax generator

When Collapse All  is enabled
img of collapse all, when this config is enabled in code syntax generator
The source code is hidden and it is displayed when expand source is clicked

When Start Line number = 8,  Title Above Code = Simple Demo  and
When Line no. padding = 3, the line number is padded with zeros for 3 digits.

img of code with padding of 3 digits and title above the code



Link to Try out the Generator - Online Code Syntax Format Generator



13 Jul 2014

Regular Expression to hack a source code


There are many quality open source code available in github and code.google . Now if we wish to hack some source code, the best way to learn how it works is to see a log where the function name is displayed in the order it is executed.

Insert Debug Code using Regular Expression

By this technique, we can find the function using regular expression and insert our debug code inside each function.

Lets illustrate with a Javascript  Source Code and Notepad++ IDE

Regular Expression to Find functions

((\w*)\s*[:|=]\s*function\(\w*\)\s*\{)

Debug Code to insert inside each functions

console.log("functionName");

Regular Expression to Insert Debug Code inside Functions

$1 \n\tconsole\.log\("$2"\)\;

A sample Javascript before inserting Debug code
var SyntaxHighlighter = function() {
    var sh = {
        all: function(params)
        {
            attachEvent(
                window,'description'
            );
        }
    };
}();

Javascript code after inserting Debug code using Regular Expression
var SyntaxHighlighter = function() {
      console.log("SyntaxHighlighter");
    var sh = {
        all: function(params)
        {
            console.log("all");
            attachEvent(
                window,'description'
            );
        }
    };
}();


Note: Please enable "Regular expression" and ". matches newline" in Search Mode in Replace box in Notepad++ for inserting inside more than 1 function using regular expression.



How this Regular Expression Works


Find Regex :
((\w*)\s*[:|=]\s*function\(\w*\)\s*\{)
Replace Regex:
$1 \n\tconsole\.log\("$2"\)\;

6 Jul 2014

Why Use Spring Framework?

  1. Dependency Injection
  2. Coding to Interface
  3. Aspect Oriented Programming

 What is Dependency Injection?

Dependency Injection is used to decouple the dependence between the objects within a class and to provide the dependency (i.e. instantiation, initialization) from outside configuration to the class.

Factory Design Pattern is used in Spring Framework.  Means instead of directly instantiating an object, we ask the particular Object Factory to manage (create, maintain lifecycle, destroy) the object and pass to us a reference of the object.

Spring uses:
1. BeanFactory
2. ApplicationContext

5 Jul 2014

Online Source Code Syntax Formatter


We can use source code syntax highlighter to format the code style to put in online media's like for e.g: blog or website. One common method is to use javascript to format the source code whenever the page is loaded. ( like SyntaxHighlighter )

SyntaxHighligher has very modern looking code syntax styles and  supports lot of programming languages like  Java, Javascript, PHP, C#, C++, CSS, HTML,  XML, SQL, VB, Python, Ruby.

The only issue with the javascript method is that it takes time to generate the code syntax styles and load the page every time. Its because  javascript tries to search the code for keywords and then renders and build the styles for each page request on the fly.

This issue can be solved, by using Code Syntax Highlight Generator, it builds the source code style only one time and then just simply reuse the rendered style for each page request. This technique notably decreases the load time of the page.

For Online Code Syntax Highlight Generator, visit this link : Online Tool for Syntax Highlight Generator

Steps to use Source Code Syntax Highlight Generator

  1. Insert the source code to the online generator.
  2. Configure the language and display style options
  3. Place the generated HTML to the your desired blog or website.
  4. Add the below CSS and Javascript  library to your blog.
http://ajblk.github.io/codeSyntaxHighlight-Generator/stylesheets/css/stylehighlighter01.css
http://ajblk.github.io/codeSyntaxHighlight-Generator/javascripts/js/sh-min.js
  1. Add the below <script> code snippet  just before the </body> close tag
<script language='javascript'>
var args={presourcecode:"presourcecode",highlighterMainDivId:"highlighterMainDiv"};
//dp.SyntaxHighlighter.BloggerMode(); //Uncomment for Google Blogger.
dp.SyntaxHighlighter.Initialize(args);</script>

A Sample Template:

<html> <head> <link type="text/css" href="stylesheets/css/stylehighlighter01.css" rel="stylesheet"/> <script type='text/javascript' src='javascripts/js/sh-min.js'></script> </head> <body> <!-- Insert The Generated HTML Below This --> <!-- Insert The Generated HTML Above This --> <script language='javascript'> var args = { presourcecode: "presourcecode", highlighterMainDivId: "highlighterMainDiv" }; //dp.SyntaxHighlighter.BloggerMode(); //Uncomment for Google Blogger. dp.SyntaxHighlighter.Initialize(args); </script> </body> </html>



2 Jul 2014

Event Handling in Java using Spring Framework



For Handling of Events, there are first 3 core things that is necessary.
  1. Event
  2. Event Publisher
  3. Event Listener
Luckily in Spring Framework there is support for handling events.

In this blog, we will try 3 different ways to implement event handling using Spring. First from simple direct usage of Spring  and then to a method where the business logic is decoupled from direct Spring usage.


Method 1 : Simple Direct Usage of Spring Framework

 

 Event


Using Spring Framework ApplicationEvent  we will create a OfferEvent class.
package com.test2;

import org.springframework.context.ApplicationEvent;

public class OfferEvent  extends ApplicationEvent{

       private static final long serialVersionUID = 3029215982265408049L;

       public OfferEvent(Object source) {
              super(source);
              // TODO Auto-generated constructor stub
       }
      
       public String toString(){
              return "OfferEvent2";
       }
      

}

Event Publisher


Using ApplicationEventPublisherAware  Interface we will be able to set the ApplicationEventPublisher from the Spring Context to publish our events.

package com.test2;

import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;

public class Service implements ApplicationEventPublisherAware {

   private ApplicationEventPublisher publisher;

  //implemented method
   public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
      this.publisher = applicationEventPublisher;
  }

   public void service(){
      OfferEvent event = new OfferEvent(this); 
      this.publisher.publishEvent(event);
  }
}

Event Listener


Using ApplicationListener of Spring Framework, we can listen to ApplicationEvents and perform actions when an event occurs.

package com.test2;

import org.springframework.context.ApplicationListener;

public class OfferEventListener implements ApplicationListener<OfferEvent> {

   //implemented method
   public void onApplicationEvent(OfferEvent event) {
     System.out.println("OfferEvent received =" + event.getClass()
        + "\n At =" + event.getTimestamp()
        + "\n Source =" + event.getSource().getClass()
        + "\n Msg =" + event.toString() );
   }

}

Main application

package com.test2;

import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {

  public static void main(String[] args)
  {
   AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("springbeanconfig02.xml");
   Service serv = (Service)ctx.getBean("ServiceBean");
   serv.service();

   ctx.registerShutdownHook();
  }
}
 

 Spring Bean XML Configuration

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

<bean id="ServiceBean" class="com.test2.Service"></bean>

<bean class="com.test2.OfferEventListener"></bean>

</beans>


Issue 


In this implementation the  ApplicationEvent  dependency is hardcoded into Service class which means  for this Service to use any different type of ApplicationEvent we have to rewrite the code. We can solve this using next Method.


Method2: Injecting ApplicationEvent Dependency using Spring


In Service class using setEvent we will inject ApplicationEvent from a Spring XML bean configuration.
package com.test3;

import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;

 public class Service implements ApplicationEventPublisherAware {

  private ApplicationEventPublisher publisher;
  private ApplicationEvent event;

  public void setEvent(ApplicationEvent event) {
    this.event = event;
  }

  //implemented method
  public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
    this.publisher = applicationEventPublisher;
  }
  public void service(){
    this.publisher.publishEvent(this.event);
  }

}
 

 Spring Bean 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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

 <bean id="ServiceBean" class="com.test3.Service">
   <property name="event">
        <ref bean="OfferEventBean" />
      </property>
 </bean>

 <bean id="OfferEventBean" class="com.test3.OfferEvent">
    <constructor-arg>
        <ref bean="ServiceBean" />
    </constructor-arg>
 </bean>

 <bean class="com.test3.OfferEventListener"></bean>
 
</beans>
 

 Issue

 In this implementation, the main business class Service is directly dependent on Spring ApplicationEventPublisherAware interface, ApplicationEventPublisher, and ApplicationEvent. So the issue is it would be difficult to change in future if we wish to use any other tool or framework. We can solve this using the next method.

Method3: Event Handling without Business Logic having Direct Dependence on Spring


Inorder to Decouple the Business Logic class from  the Spring framework, first we will create our version of ApplicationEvent.
package com.test4;

import org.springframework.context.ApplicationEvent;

public abstract class MyAppEvent extends ApplicationEvent{
   private static final long serialVersionUID = -6092666752131453519L;

   public MyAppEvent(Object source) {
       super(source);
   }
}
 
 Now for every ApplicationEvents which we wish to create we will extend that from MyAppEvent.

package com.test4;

public class OfferEvent extends MyAppEvent{
   private static final long serialVersionUID = -2857555740801485476L;

     public OfferEvent(Object source) {
        super(source);
  }

  public String toString(){
       return "OfferEvent4";
  }
}

 We will also create a our version of ApplicationEventPublisher.
package com.test4;

import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;

public class MyAppEventPublisher implements ApplicationEventPublisherAware{
   private ApplicationEventPublisher publisher;
     public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher){
        this.publisher = applicationEventPublisher;
   }

     public void publishEvent(ApplicationEvent event ) {
        this.publisher.publishEvent(event);
   }
}
 
 Now in our Business Logic Service class, we have freed it from any direct dependence on Spring framework.
package com.test4;

public class Service {

   private MyAppEvent event;
     private MyAppEventPublisher publisher;

     public void setEvent(MyAppEvent event) {
        this.event = event;
   }

     public void setPublisher(MyAppEventPublisher publisher) {
        this.publisher = publisher;
   }

   public void service(){
        this.publisher.publishEvent(this.event);
   }
}


Using Spring XML configuration we will inject the properties MyAppevent and MyAppEventPublisher to the Service class
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

 <bean id="ServiceBean" class="com.test4.Service">
    <property name="event">
       <ref bean="OfferEventBean" />
    </property>
    <property name="publisher">
       <ref bean="MyAppEventPublisherBean" />
    </property>
 </bean>

 <bean id="OfferEventBean" class="com.test4.OfferEvent">
    <constructor-arg>
       <ref bean="ServiceBean" />
    </constructor-arg>
 </bean>

 <bean class="com.test4.OfferEventListener" />

 <bean id="MyAppEventPublisherBean" class="com.test4.MyAppEventPublisher"/>

</beans>