Rest or SOAP? Which one to use?

As a developer we might have worked on REST as well as SOAP based services. However when it comes to decide which one to use then many developers are not very clear with the answer. Let’s see in this article what are the differences in these two ways of creating web services. Before we dig-down into the differences here is a short history about REST and SOAP.

REST: REST(representational state transfer) was introduced and defined in 2000 by Roy Thomas Fielding in PhD dissertation “Architectural Styles and the Design of Network-based Software Architectures”. Rest facilitates philosophy of open web.

SOAP: SOAP(Simple Object Access Protocol) was introduced in 1998 by Dave Winer in collaboration with Microsoft. SOAP is mainly used to address the goals of the enterprise market.

Basic Concept

REST SOAP
Makes data available as a resources. E.g. AccountInformation, Invoice Makes application logic available as a servies. E.g. getAccountInformation, PayInvoice
It’s an architectural style. It’s a protocol.

Advantages

REST SOAP
It uses standard HTTP. Hence easy to implement. Works on top of any communication protocol
Returns data in many different formats (JSON,XML etc.) It can be fully described using WSDL
Better performance and scalability. Reads can be cached. Provides end-to-end reliability and successful/retry logic is built in
REST allows better support for browser clients due to its support for JSON. Security and authorization are part of protocol

Disadvantages

REST SOAP
Only works on top of HTTP protocol Hard to implement and not so popular among web and mobile developers
No built-in standards for security or reliability Permits XML data format only
No constraints on the payload SOAP defines standards to be strictly followed.
Requires more bandwidth and resource than REST.

When to use what

REST SOAP
When your bandwidth is very limited. When performing transactions that involves multiple calls.
When client and server operates on a web environment When you want to enforce a strict contract between client and server
Examples: Social Media Service, Web chat service Examples: Financial services, telecommunication services

 

In nutshell , identify your project need and goal you want to achieve before you pick any of the approaches.

Are you looking for fast android emulator?

After few years break back to mobile technologies again. Word of mobile development has changed a lot and at fast peace. I was feeling excited to work on Android again, however my excitement didn’t last long when I launched my application in emulator.

I was using default emulator provided by android SDK and to my goodness it was taking a long time.

5 min, 10 mins , 15 mins..Went for a coffee break …came back….but emulator was still loading.

Finally I decided to look on internet for a solution and I came across Genymotion emulator. Genymoyion is a commercial product from Genymobile which provides android emulator that is pretty fast and can be easily integrated with Eclipse and Android studio. Below are main feature

  •  Plugins for android studio and eclipse. Compatible with Android SDK tools
  •  High performance
  •  Easy integration with testing and continuous integration server.
  •  Powerful features: GPS, Battery, Screencast, Network quality and performance, Call interruption, SMS emulation etc.
  •  available for Windows, Mac and Linux
  •  Basic version for free with premium license which adds more features to the emulator

Let’s see how to use genymotion with android studio and emulator

Installing Genymotion on windows

  1. Got to genymotion site https://www.genymotion.com/#!/download and sign up
  2. There are two options to download one with virtual box and one without virtual box.For just emulator we will opt for option 2 i.e without virtual box. Go to link https://www.genymotion.com/#!/download/freemium/windows/withoutVirtualBox
  1. Now run the downloaded genymotion-x.x.x.exe and install the Genymotion on your PC.
  2. Then launch Genymotion and login with your Username and Password.

Instal1

5. Then select a device from the list and click next.

Instal2

6. It will create a new virtual device.

Integrating with android studio

  1. Go to File->Settings->Plugins
  2. Search for Genymotion

and1

4. If not displayed click on Browse link shown in above image.

5.It will display the plugin

and2

5. Click on Install plugin button.

6. Restart android studio once plugin is installed

7. When you click on device manager button

and3

For first time it will ask for path where Genymotion is installed

and4

8. Once this path is set you can launch Genymotion device manager displayed below.

and5

9. Using this device manager you can launch emulator

and6

Integrating with eclipse

  1. Select Help->Install New Software.
  2. Enter the URL http://plugins.genymotion.com/eclipse and press Enter.
  3. Genymotion Eclipse Tools will be shown, select it and click next.

ecl1

4.  Genymotion Eclipse Plug-in will be downloaded and installed.

5. Now restart Eclipse IDE the plug-in will be active.

ecl2

That’s it. You are ready to use genymotion now.

Scrum + Kanban = Scrumban

Why scrum is so popular because it is a framework. A framework in turn is an abstraction or structure which helps in building something more meaningful and that can expand.

While much is written about advantages of scrum over traditional approaches like waterfall, in a single line it makes things easier for all the stake holders of project.

Kanban on the other hand is a lean manufacturing process. It is used for logistic control system.

Kanban is a Japanese term which means “Visual board” or “Card you can see”.

Scrumban is a hybrid of scrum and kanban process.

Scrumban = Srucm + Kanban

Let’s see main characteristics of both methodologies

Scrum:

  1. Cross-functional, self organized teams.
  2. Time boxed approach where iterative development leads to potentially shippable code.
  3. Inspect and adapt approach
  4. A prioritized list of features to be worked upon in a given sprint

Kanban:

  1. Visualize workflow
  2. Use named column to indicate current state of item in workflow
  3. Limit work in process: By assigning explicit limit on items in work it helps a lot for situations where there is a constant need for re- reprioritization of items and task switching.

Scrumban can be used :

  • For maintenance of different applications
  • For event-driven work like IT support – help-desk
  • Projects with frequent and unexpected user stories.

Here is a typical workflow or Kanban board for maintenance project

Kanban

Why scrumban suits for maintenance project:

  • High priority / show stopper items can popup any time
  • Need to work on items as and when they appear. No prioritized and committed PBIs
  • Still go in a time boxed approach using scrum with having limit on WIP
  • Can easily visualize work items
  • Instead of velocity, a kanban metric cycle time is used which gives is more realistic information i.e. a time a ticket takes to complete; measured from when it is first began.
  • You can still use sprint retrospective , to identify what was done right and what can be improved

Life is all about experiences…

Today had an opportunity to be volunteer for a social cause. A group of people from IT industry along with NGO did a tree plantation near Pune city at katkari wasti. We also distributed school stationary to under privileged children. It was nice to see their faces smiling and glittering.

Looking at these people I felt we are so blessed. We have so many comfort and luxury which these people may not have for generations. We should thank God for giving us wonderful life and contribute as much as we can to these people from our society.

Lean and Kanban in personal life

For decades water-fall was the traditional method of project management and developing software. But now a day’s many project management methodologies are used like Agile,RAD,FDD, XP , Lean development and many more. Out of this Agile is becoming more popular because of constant changing needs of customer and dynamic team structure.

I know about lean concepts but never got a opportunity to use it practically. Recently I got a chance to work on a project which was using both scrum and Kanban. And I realized that Kanban can be easily integrated with scrum to produce better result.

I was just thinking if Kanban can be used in personal life as well?

Here is my thought on the same.

PersonalKanban

Workflow:

  1. Backlog -At the end of the month prepare a list of to-dos which you want to do in next month. We will call this as BACKLOG.
  2. Prioritize – Pick the most important items which you want to do in next week .Assign priority to each item picked from backlog and put it in this column. You can add items from backlog as and when you have space in this column.
  3. Doing – Pick items from Prioritize column on which you want to work starting from high priority. You can distribute those among your family members.
  4. Done- Once done you move items from Doing columns to this. Give pat on the back 🙂 to family member to whom the task was assigned to make it Done.

Well as an added flavor 🙂 you can apply Lean concepts as well :

  1. Eliminate MUDA(waste): Eliminate delays in above workflow. Work on most important tasks
  2. Outsourcing: When you are working on a task think if it is adding value. For e.g. Family pick nick. You cannot outsource this task to your neighbor or relatives J . of course they can accompany you, but your presence is must. However tasks like car servicing can be outsourced.
  3. Kaisan :This is Japanese term which means “continuous improvement.” Always think what will make your process improve so that you can have more items done at the end of the month with grater satisfaction
  4. Respect yourselves and your family members: This will help in having good family environment, greater satisfaction, well prioritized to-do list.

Wouldn’t it help you make your life more organized?

 Well I forgot to mention what is meaning of term Kanban. Kanban is again a Japanese term which means “Visual board” or “Card you can see”.

Sometimes it does matter what people think of you!

Somewhere read “What others think of you is none of your business!”. True , agreed. But sometimes it does matter.

In my opinion it is a very good way of looking at yourselves from others eyes. It can be a painful or it cab be feel good experience.

Today was my last day at a organization where I was working until today. Its hardly a year I was working here, but enjoyed it a lot. I was not aware that unknowingly I have made so many friends…I have made emotional bonding with so many colleagues. I came to know when I dropped a goodbye mail. So many overwhelming responses. Felt so good……. It really made me feel so good……

 

Telepathy….yes it exist!

Some time we go through such experience that we are thinking about some person and that person suddenly visit you or ring you. Yes it happens….it is not coincidence but it something called telepathy.

Telepathy (from the Ancient Greek τῆλε, tele meaning “distant” and πάθος, pathos or -patheia meaning “feeling, perception, passion, affliction, experience“) is the purported transmission of information from one person to another without using any of our known sensory channels or physical interaction.- Source Wikkipedia.

I have experienced it many time. There is one of my friend, well wisher…whatever you name it. Whenever I think about her I get a phone call from her. This has happened many times. I don’t know what is our bonding but whenever I strongly feel like taking to her or I just remember her , there is always a phone call from her.

There are other experiences as well. Like I am thinking about some one and I just cross that person. This has also happened many times with this persons for whom I have strong boding, feelings.

It also makes me think and believe about the concept of “Oneness”.

Spring Batch- Code example

In last article of Spring Batch we gone through concepts and interfaces provided by spring batch framework.

In this article let’s see how we can use those concepts to create a batch job.

For simplicity, below is a simple batch job we will be taking as an example.

  • Read from a csv file.
  • Process data – select only records where age > 30
  • Write to another csv file.
  1.  configuration file snippet for this job

<batch:job id=“reportJob”>

<batch:listeners>

<batch:listener ref=“customJobListener” />

</batch:listeners>

<batch:step id=“step1”>

<tasklet>

<chunk reader=“csvFileItemReader” writer=“cvsFileItemWriter” processor=“filterCSVProcessor”commit-interval=“1”>

<listeners>

<listener ref=“customStepListener” />

<listener ref=“customItemReaderListener” />

<listener ref=“customItemWriterListener” />

<listener ref=“customItemProcessListener” />

</listeners>

</chunk>

</tasklet>

</batch:step>

</batch:job>

In this configuration file you first define a job with job id. Then you define any listeners which pprovide call-backs at specific points in the lifecycle of a Job like before or after start of job.

Then you define a step which also has unique ID. Then you define the steps which are required for performing your job. These steps are defined in terms of item reader/processor/writers, and whole as a unit are defined with chunk element.

  • reader – The ItemReader that provides items for processing.
  • writer – The ItemWriter that processes the items provided by the ItemReader.
  • commit-interval – The number of items that will be processed before the transaction is committed.

Then you define listeners for step which are again call-backs at specific points in the lifecycle of a step like before or after start of step or before and after reading item etc.

The chunk element is defined within tasklet tag.

Below is a code snippet for item reader listener.

public class CustomItemReaderListener implements ItemReadListener<User> {

public void afterRead(User arg0) {

System.out.println(“CustomItemReaderListener : ” +”afterRead()”);

}

public void beforeRead() {

System.out.println(“CustomItemReaderListener : ” +”beforeRead()”);

}

public void onReadError(Exception arg0) {

System.out.println(“CustomItemReaderListener : ” +”onReadError()”);

}

}

Similarly you define other listeners for job, step, reader/writer/processor etc which are implementations of respective listeners interfaces provided by spring batch framework.

 

  1. Then we need to launch this job. Here is a code snippet.

String[] springConfig = {

“spring/batch/config/context.xml”,

“spring/batch/jobs/job-report.xml”

};

ApplicationContext context =

new ClassPathXmlApplicationContext(springConfig);

JobLauncher jobLauncher = (JobLauncher) context.getBean(“jobLauncher”);

Job job = (Job) context.getBean(“reportJob”);

try {

JobExecution execution = jobLauncher.run(job, new JobParameters());

System.out.println(“Job Exit Status : ” + execution.getStatus());

} catch (Exception e) {

e.printStackTrace();

}

System.out.println(“Done with batch”);

First you create a JobLauncher instance from “jobLauncher” bean defined in context.xml

Then you create a Job instance from “reportJob” which is defined in job configuration file.

When you run your Job instance with help of JobLauncher you will get a JobExecution instance which provides you the status whether your job executed successfully or not.

 

  1. Now let’s see how reader and writers are configured in our job-report.xml

<bean id=”csvFileItemReader” class=”org.springframework.batch.item.file.FlatFileItemReader”>

<!– Read a csv file –>

<property name=”resource” value=”file:csv/input/read.csv” />

<property name=”lineMapper”>

<bean class=”org.springframework.batch.item.file.mapping.DefaultLineMapper”>

<!– split it –>

<property name=”lineTokenizer”>

<bean                                                                                           class=”org.springframework.batch.item.file.transform.DelimitedLineTokenizer”>

<property name=”names” value=”name,age,phone” />

</bean>

</property>

<property name=”fieldSetMapper”>

<!– map to an object –>

<bean                                                                                              class=”org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper”>

<property name=”prototypeBeanName” value=”user” />

</bean>

</property>

</bean>

</property>

</bean>

<bean id=”cvsFileItemWriter” class=”org.springframework.batch.item.file.FlatFileItemWriter”>

<!– write to this csv file –>

<property name=”resource” value=”file:csv/output/write.csv” />

<property name=”shouldDeleteIfExists” value=”true” />

<property name=”lineAggregator”>

<bean                                                               class=”org.springframework.batch.item.file.transform.DelimitedLineAggregator”>

<property name=”delimiter” value=”,” />

<property name=”fieldExtractor”>

<bean                                     class=”org.springframework.batch.item.file.transform.BeanWrapperFieldExtractor”>

<property name=”names” value=”name,age,phone” />

</bean>

</property>

</bean>

</property>

</bean>

</beans>

You first define beans which are responsible for reading and writing. In this example we are using readers and writers provided by spring batch framework i.e. FlatFileItemReader and FlatFileItemWriter as we are using comma separated records. You can have your custom classes as well.

Then you define a csv file to be read or written using property resource.

  1. Reading

We have defined a line maper . Line mappers are used for tokenizing lines into FieldSet in our case domain class User , followed by mapping to items.

  1. Writing:

We have defined a line aggregator that converts an object into a delimited list of strings. The default delimiter is a comma.

Then we need to extract our fields from our domain object user. For this we use field extractor to which given an array of property names, it will reflectively call getters on the item and return an array of all the values.

  1. Processing:

We have our custom file processor as we want to filter out records where age > 30.

For this we defined a bean

<bean id=“filterCSVProcessor” class=“com.springbatch.processor.FilterCSVProcessor” />

And here is implementation

public class FilterCSVProcessor implements ItemProcessor<User, User>{

public User process(User user) throws Exception {

if( user.getAge() > 30)

return user;

else

return null;

}

}

That’s all. Complete source code can be found here.

 

 

 

 

Spring Batch – Concepts and interfaces

Recently I came across a very interesting incident which was related to spring batch, where a write skip count was not getting updated properly. I never worked on spring batch and almost knew nothing about it before working on this incident.

So after understanding what the incident is about, I started reading how spring batch works.

Let’s see what spring batch is and how it works.

In general terms “BATCH” is the execution of a series of programs on a computer without manual intervention.

Where batch processing can be used:

  • Data Export
  • Invoice generation
  • Bulk database updates
  • Automated transaction processing
  • Processing digital images

What is Spring Batch: Spring Batch is an open source framework for batch processing. It is a lightweight framework based on top of spring framework.

Features:

  • Transaction management
  • Chunk based processing
  • Start/Stop/Restart
  • Retry/Skip

Let’s first understand the terms which are core to Spring Batch framework.

Batch: execution of a series of jobs

Job: A sequence of one or more steps and associated configuration that belong to the batch job. A job is indented to be executed without interruption.

JobInstance : A uniquely identifiable job run.

JobExecution : A single attempt to run a job. A JobInstance will be considered complete only when JobExecution completes successfully.

Step : A Step is a part of a Job and contains all the necessary information to execute the batch processing actions that are expected to be done at that phase of the job. A Step is a single state within the flow of a job.

StepExecution: An attempt to execute a step. Contains information about commit count and access to the Execution Context.

Job Repositories: Job repositories provides CRUD persistence operations for all job related metadata like the results obtained, their instances, the parameters used for the Jobs executed and the context where the processing runs.

JobLauncher: Responsible for launching jobs with their job parameters.

Batch application can be divided in three main parts:

  • Reading the data (from a database, file system, etc.)
  • Processing the data (filtering, grouping, calculating, validating…)
  • Writing the data (to a database, reporting, distributing…)

There are various reader and writer interfaces provided by spring batch framework.

Key Interfaces are:

  • ItemReader :
  • ItemWriter
  • ItemProcessor

ItermReader : Readers are abstractions responsible of the data retrieval. Here is a list of readers

  • AmqpItemReader
  • AggregateItemReader
  • FlatFileItemReader
  • HibernateCursorItemReader
  • HibernatePagingItemReader
  • IbatisPagingItemReader
  • ItemReaderAdapter
  • JdbcCursorItemReader
  • JdbcPagingItemReader
  • JmsItemReader
  • JpaPagingItemReader
  • ListItemReader
  • MongoItemReader
  • Neo4jItemReader
  • RepositoryItemReader
  • StoredProcedureItemReader
  • StaxEventItemReader

ItemWriter: Writers are abstractions responsible of writing the data to the desired output database or system. Here is a list of writers

  • AbstractItemStreamItemWriter
  • AmqpItemWriter
  • CompositeItemWriter
  • FlatFileItemWriter
  • GemfireItemWriter
  • HibernateItemWriter
  • IbatisBatchItemWriter
  • ItemWriterAdapter
  • JdbcBatchItemWriter
  • JmsItemWriter
  • JpaItemWriter
  • MimeMessageItemWriter
  • MongoItemWriter
  • Neo4jItemWriter
  • StaxEventItemWriter
  • RepositoryItemWriter

ItemProcessor: Processors are in responsible for modifying the data records converting it from the input format to the output desired one. These are optional. Here is a list

  • ValidatingItemProcessor
  • PassThroughItemProcessor
  • ScriptItemProcessor

And many other.

To put it all together this is how it looks

SpringBatch

 

Ok. So now how these batch jobs are processed. There are two ways.

1.Chunk oriented processing:

Chunk oriented processing refers to reading the data one at a time, and creating ‘chunks’ that will be written out, within a transaction boundary. One item is read in from an ItemReader, handed to an ItemProcessor, and aggregated. Once the number of items read equals the commit interval, the entire chunk is written out via the ItemWriter, and then the transaction is committed.

chunk-oriented-processing

Configuring step for chunk oriented processing:

<job id="sampleJob" job-repository="jobRepository">
    <step id="step1">
        <tasklet transaction-manager="transactionManager">
            <chunk reader="itemReader" writer="itemWriter" commit-interval="10"/>
        </tasklet>
    </step>
</job>

 

 

2.Tasklet oriented processing: Sometimes step consists of simple operations consisting of a single task like simple stored procedure call or deleting a file etc.

For such case Tasklet interface is provided.

The Tasklet is a simple interface that has one method, execute, which will be a called repeatedly by the TaskletStep until it either returns RepeatStatus.FINISHED or throws an exception to signal a failure.

Configuration of step as a tasklet:

<step id=”step1″>

<tasklet ref=”myTasklet”/>

</step>       

 

In next article we will see how these concepts are used /applied to create a batch job application.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Ajax in Apache wicket

First a bit about JavaScript:JavaScript, aka Mocha, aka LiveScript and many other names, is a client-side (i.e. the browser) scripting language. That means it takes out burden of processing data from your server making it more responsive.

As there are advantages of using JavaScript as speed, simplicity etc. there are downsides as well like it is frequently turned off in browsers because of security concerns, it can be easily exploited etc.

Ajax(Asynchronous JavaScript+XML) is based on JavaScript with some other technologies like HTML and CSS and is used to dynamically update parts of the UI without having to reload the page.

While Ajax can be used with many java frameworks like Spring MVC,Struts , JFS etc, it is very easy to use Ajax with wicket. You don’t even need to write a single line of JavaScript as Wicket has bunch of Ajax enabled components.

Here are advantages of Ajax in wicket :

  1. As a java developer you can focus on pure java without need to learn JavaScript.
  2. Many built-in AJAX components, also Ajax behavior encapsulated in wickets reusable components.
  3. It is easy to replace components on the fly.
  4. Faster, more responsive user interfaces, as Ajax requests do not completely refresh whole page.
  5. It has excellent debugging utility for debugging Ajax calls

 

So let’s see how easy it is to use Ajax with wicket than traditional approach.

 

Let’s see how to submit a form without writing a single line of JavaScript.

 

You just need to add a button that can be used to submit the form via Ajax
form.add(new AjaxButton(“ajax-button”, form)
{
@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form)
{
// repaint the feedback panel so that it is hidden
target.add(feedback);
}

@Override
protected void onError(AjaxRequestTarget target, Form<?> form)
{
// repaint the feedback panel so errors are shown
target.add(feedback);
}
});

And that’s all. No JavaScript in HTML i.e.markup file of your wicket application!!!

Note: above piece of code is from Wicket Library examples and complete example can be found here.