Friday, 2 August 2013

IT hiring to fall in 2013: Nasscom

HYDERABAD: The additional personnel requirement in the IT sector of the country may come down by nearly 50,000 in the current fiscal as there is a large scale backlog of recruitments last year, IT-BPO industry body Nasscom said.


"Last year we added 1.8 lakh jobs net. This year it will be 1.3 to 1.5 lakh jobs. Last year there was filling up back logs because we had shrunk our pipeline. We are still the largest employers of white collar sectors of the country which has 3 million young people at the age of 27," Nasscom President Som Mittal told reporters here.

"Secondly, our business is not linear any more. There was time where for every dollar you added so many hours. But today it is IP-led and innovation, which we don't repeat (the job) which is good for the country," he added.

Replying to a query, he said the IT industry is expected to grow at 12 to 14 per cent in dollar terms in the current fiscal.

"This year we will probably add $13 to 15 billion new business in both domestic and exports," Mittal said.

According to him, the IT industry witnessed $76 billion exports and $32 billion domestic business which includes hardware last year. In 2012-13, the industry has grown 10.2 per cent in pure dollar terms and 10.9 per cent in constant currencies and 21 to 22 per cent in rupee term.

On attrition rate of the industry, Mittal said it has come down as demand and supply adjusts.

Currently, it hovers in 13-15 per cent on the higher side. Meanwhile, as a next step to its recently launched '10,000 startups' programme, the Nasscom signed a MoU with Hyderabad Angels, TiE Incubator and IIIT Hyderabad Incubator to collaborate and support the creation of a vibrant ecosystem to foster technology entrepreneurship in India.

Mittal said that they are inviting of applications from innovative technology startups across the country for an insightful engagement with its accelerator and funding partners.

The Association has already received over 1,000 applications from various budding startups since the launch of the program and is expected to cross over 5,000 startup applications in the next eight weeks.

Source : TOI

India Inc presses layoff button; IT jobs take a hit

While fresh hiring has already taken a hit, thanks to the slowing economy, India Inc has for the first time acknowledged that large-scale layoffs are already underway and the job market is likely to get much worse if growth isn't revived fast.

"Layoffs of contractual staff have already started and this could soon move to permanent employees," Ficci president Naina Lal Kidwai has said, warning the government of "a grim employment scenario" unless growth is revived urgently.

"With the slowdown becoming more discernible, fresh hiring is already taking a hit. Unless the growth trajectory is reversed, we will be facing a grim employment scenario," Kidwai said ahead of the meeting of the Prime Minister's Council of Trade and Industry on Monday evening. Estimates indicate that about 10 million people join the workforce every year; however, there remains a yawning gap between the skills acquired by these new entrants and skill set required by the employer.

An internal note of Ficci reviewed by ET states that the job market is 'gloomy' with sectors such as auto, IT and banking seeing thousands of job losses, while most companies have imposed a hiring freeze.

"Particularly in the auto sector, which has been operating at low capacity due to weak demand, thousands of temporary staff has already been laid off and fresh hiring is on a complete freeze," Ficci said. "Job market in other sectors also reflects a slowdown. UBS recently surrendered its commercial banking licence to the RBI and had begun firing employees from its commercial banking division."

The surrender of the banking licence by UBS reflects a growing disenchantment among foreign investors about India's prospects in the near to medium term. Since procuring such an asset like an operating licence in the country entails long and complex procedures, often running into years, this indicates that it doesn't expect the Indian market to be lucrative for a while to come.

" IBM, as a part of its restructuring process, had already started laying off employees in North America and more jobs are likely to be cut in other nations like India," the FICCI note states. Headhunters said the stress in the job market is visible, though it hasn't become an across-the-board phenomenon yet.

"We are seeing a lot of CVs coming from employees in the banking and technology sectors, looking for opportunities in other sectors," said Dony Kuriakose, director of Edge Executive Search, adding that a bigger re-alignment is underway in hiring strategies.

"No one is looking at mass hiring or entry-level recruitments off campus, instead the focus is now on niche, specialised hiring," he said. This poses a serious threat for new entrants into the job market and could lead to high youth unemployment. Over 10 million young Indians join the workforce every year but a mismatch in the skills they have acquired and the skill sets industry is looking for makes it difficult for them to get formal employment.

Industry-wide surveys conducted by Assocham and Ficci show a steady decline in the number of firms that expect to hire more people, which also euphemistically implies that there are greater pressures to downsize staff numbers. For instance, FICCI's Business Confidence Survey found that just 20% respondents expect hiring to go up in the second quarter of 2013-14, down sharply from 30% of firms who indicated the same in the previous quarter.

A similar poll by Assocham found that almost three out of every four firms doesn't expect any new jobs to be created this year. Another indication of harder times in the job market is the sharp decline in margins across the services and manufacturing sectors, which is forcing companies to curb operational costs.

Data compiled by the Centre for Monitoring the Indian Economy (CMIE) shows that net sales growth in manufacturing sector eased from 9.3% in the third quarter of 2012-13 to 5.2% in the fourth quarter. The sales decline had hit sectors across the board: food and chemicals, metals, steel, cement and transport equipments.

Profit margins and operating expenses also saw a similar decline in that period, and industry believes things have got worse in the first quarter of this year, with no tangible revival in any of the core economic barometers.

Source : TOI

  Infy, TCS, Wipro see hiring fall in Q1

Hiring by TCS, Infosys and Wipro, which account for a major chunk of job opportunities in the sector, slowed down by a hefty 60% in the April-June quarter as the big three hired only around 3,400 persons.

In the April-June 2012, these three companies had hired over 8,700 persons on a net basis.

The country's largest IT company TCS added 1,390 persons in the June quarter this year, against net addition of 4,962 persons in the year ago period.

Infosys hired 575 persons during the quarter against 1,157 net additions in the same period last year.

Wipro added 1,469 people to its IT services division in June quarter compared to over 2,600 people in the year ago period.

In the January-March quarter, the three companies had hired over 16,500 persons.

While TCS and Infosys saw gross additions of 10,000 each during June 2013 quarter, net addition subtracts the number of people leaving the company from the gross additions.

Experts consider the net number as a better indicator of actual increase in staff count.

"IT companies are cautious in their hiring plans currently. They are hiring on requirement and project basis," Uday Sodhi of job portal Head Honchos said.

Hiring in the sunrise sector has been sluggish for quite a quarters as the outsourcing industry is under duress amid clients cutting back on IT spends fearing a further weakening of the economic conditions.

TCS while announcing its results this month had said that its hiring had come down due to low attrition rate. The company witnessed a low attrition rate of 9.55% for IT division and 15.77% for BPO segment.

A recent survey by IT industry body Nasscom had said that attrition rate in the IT sector has come down to around 14% in 2012-13 from 19% in 2010-11 for IT and KPO segments.

The survey, which rated TCS, Infosys and Wipro among top five IT employers, also said that hiring by companies would grow at a slower rate this year.

Moreover, there has been a change in hiring pattern by software and services companies, which may lower net additions this year, it said.

Project based 'just-in-time' hiring is the dominant way at present, it added.

Source : TOI

Sunday, 28 July 2013

Principles of Package Design

Agile Software Development is really an incredible book. After reading it, a lot had been talked about the Object-Oriented Principles on this blog . Today, I’ll be talking about another section of the book, which introduces principles used to maintain high package cohesion and a desirable package dependency, known as Principles of Package Design.
Packages are used to organize larger projects. More than this, they are containers of classes used to manage the development and distribution on software. Package’s goal is separate classes in an application according to some criteria. However, classes often have dependencies on other classes, creating package dependencies relationships. To help manage this situation, some principles were created to govern the creation, interrelationship and use of packages.
The three principles in sequence are related to package cohesion, useful in deciding how to partition classes into packages.
The Reuse-Release Equivalence Principle (REP): the granule of reuse if the granule of release
REP states that anything that we reuse must also be released and tracked. Reusability is not only the creation. It comes only after there is a track system in place that offers the guarantees of support that reusers will need. Since reusability is based on packages, if some software is going to be reused, then it must be partitioned in a convenient structure for this purpose, so all classes in a package become reusable by the same audience.
The Common-Reuse Principle (CRP): the classes in a package are reused together
CRP helps in deciding which classes should be placed into a package. This can be determined by reuse characteristics. Classes that tend to be reused together should be placed in the same package. Remember: if you reuse one class in a package, you reuse them all. Although the CRP tells us what classes put together, it also says what classes do not put in the same package. If a class depends on another class in a different package, it depends on the entire package. Every time the used package is released, the using package must be revalidated and rereleased, even the change was made in a different class that the using package depends on. Therefore, CRP also says that classes which are not tightly related to each other should not be in the same package, so every time I depend on a package, I depend on every class in that package.
The Common-Closed Principle (CCP): a change that affects a package affects all the classes in that package and no other packages.
This is the same as SRP, but applied for the packages context. Such as classes should have just one reason to change, CCP states that packages should not have multiple reasons to change. It’s preferable that changes occur in just one package rather than distributed along the whole system.
Now, we are going to take a look at principles related to package relationship and dependency.
The Acyclic-Dependencies Principle (ADP): allow no cycles in the package-dependency graph.
Package cycles create immediate problems, and the most obvious one is when you have to release a package that was modified. In order to release the package, it must be compatible with all other packages that it depends on. A cycle in your package-dependency graph makes release harder since you increase the number of packages that you have to be compatible with. For example, take the Figure 1 and Figure 2. To release package C in the first situation we must be compatible with package E and F. However, in the second case we also must be compatible with package A, B and D. Even worst, if you want to test package C, we must link and build all other packages in the system, instead of just two of them.
no-cycle
To break the cycle, two solutions are suggested:
  1. apply Dependecy-Inversion Principle.
  2. create a new package between C and A, and move the classes that they both depend on into that new package.
The Stable-Dependencies Principle (SDP): depend in the direction of stability.
Stability has nothing directly to do with frequency of change, but to the amount of work required to make the change. In software, package stability is measured in number of classes inside this package that depend on classes outside this package and number of classes outside this package that depend on classes within this package. Thus, a package is called instable if it is easy to change, in other words, just a few or none packages have dependency relationship with it. A package is called stable if it is hard to change, or a lot of classes outside this package depend on it. The book also brings a method to calculate stability metrics, but I’ll not be such detailed. Just have in mind that a good design contains some instable package and some stable package. Instable packages are on top and depend on stable packages at the bottom, just shown below.
figura1
The Stable-Abstractions Principle (SAP): a package should be as abstract as it is stable.
This principle states that a stable package should also be abstract so that its stability does not prevent it from being extended, and an instable package should be concrete since its instability allows the concrete code within it to be easily changed. Thus, stable packages consist of abstract classes and instable packages of implementations classes.
Conclusion
After some posts of OOP, we already know how to create a good class design. However, in big systems, classes are separate into packages which corresponds a very important part of the system’s release and deploy. So, a new concern is how to divide classes between packages and maintain the system’s consistency. In this post we introduced six principles explained in Robert Martin book which help us in solve a lot of package design problems. You can find a lot of more information in the book, which I strictly recommend.
See you,

Singleton (Anti-) Pattern

I’ve implemented my first design patterns at college, while creating a web system during the software engineer course. My classmates and I needed a facade class with a single instance of it throughout the system. So, because we’re really smart, we’ve applied the Facade and Singleton pattern. Actually, we’ve implemented the patterns without knowledge of the design patterns catalog. For us, it was just a way to get what we need.
This week, while doing my daily work, I realized how dangerous the Singleton pattern is. Well, I would have noticed it before, if I have used Test-First Programming. Even knowing the benefits of TDD, I decided to write some code in advance, since I don’t have much experience on the platform used and on its supported tests framework.
My task was to create a GPS abstraction and use it in a mobile Navigator module. My first thought was making my GPS abstraction a Singleton class. It looked very obvious for me: a mobile device has only one GPS and different GPS intances will provide the same data set. So, what I need is just a single GPS instance troughout the system.
After some minutes writing code, I’ve created abstractions similar to the Java sample below.
GPSProvider.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import java.util.List;
 
public class GPSProvider implements LBSPositionObserver {
 
 private static GPSProvider INSTANCE = new GPSProvider();
 private Position lastCoordinate;
 private List<GPSListener> listeners;
 
 private GPSProvider() {
 this.listeners = new ArrayList<GPSListener>();
 }
 
 //retrive the class instance
 public static GPSProvider GetInstance() {
 return INSTANCE;
 }
 
 // perform GPS initialization
 public void initGPSService() {
 (...)
 }
 
 // add a new listener to the gps class
 public void attach(GPSListener listener) {
 this.listeners.add(listener);
 }
 
 // remove a listener from the class list
 public void dettach(GPSListener listener) {
 this.listeners.remove(listener);
 }
 
 @Override
 // set lastCoordinate and notify all listeners about the update
 public void positionUpdated(Position position) {
 this.lastCoordinate = position;
 for ( GPSListener listener : this.listeners ) {
 listener.positionUpdated(position);
 }
 }
 
 @Override
 // notify all listener about the update
 public void setStatus(int status) {
 for ( GPSListener listener : this.listeners ) {
 listener.statusUpdated(status);
 }
 }
 
 // return the last known coordinate
 public Position getLastCoordinate() {
 return this.lastCoordinate;
 }
 
}
GPSListener.java
1
2
3
4
5
6
7
public interface GPSListener {
 
 void positionUpdated(Position position);
 
 void statusUpdated(int status);
 
}
LBSPositionObserver.java – native GPS interface
1
2
3
4
5
6
7
public interface LBSPositionObserver {
 
 void positionUpdated(Position position);
 
 void setStatus(int status);
 
}
Navigator.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
public class Navigator implements GPSListener {
 
 private NavigatorObserver observer;
 
 public Navigator(NavigatorObserver observer) {
 this.observer = observer;
 }
 
 // start navigation by listening to gps updates
 public void navigate(Route route) {
 GPSProvider gps = GPSProvider.GetInstance();
 gps.attach(this);
 }
 
 // pause navigation by not receiving gps updates
 public void pause() {
 GPSProvider gps = GPSProvider.GetInstance();
 gps.dettach(this);
 }
 
 @Override
 // everytime the position is updated, the navigator gives directions if needed
 public void positionUpdated(Position position) {
 // navigate user through route.
 int step = this.verifyStepUpdated();
 if ( step != -1 ) {
 this.observer.StepUpdated(step);
 }
 
 if ( this.achievedDestination() ) {
 this.observer.DestinationAchived(position);
 }
 }
 
 // calculate if achieved destination
 private boolean achievedDestination() {
 (...)
 }
 
 // verify is have to change direction
 private int verifyStepUpdated() {
 (...)
 }
 
 @Override
 public void statusUpdated(int status) {
 // send status to end user.
 }
}
Now, since I’ve finished my Navigator module, I want to test it to make sure it’s working correctly. In order to test the Navigator module, I need a GPS data log and a route to walk through it, simulating a person walking and being navigated by the system. The route is not a problem because I pass it as a parameter of “navigate” method. However, there is no way to simulate a GPS log with the code above, unless I use some Dependency Injection Framework, which is not the case.
That’s the Singleton disadvantage. I can’t inject a GPS mock in my Navigator module because I always use the native gps implementation represented in my Singleton GPSProvider class. Everytime I need some GPS information, I use the GPSProvider.GetInstance() static method to retrieve the only GPS instance I have access to.
To solve this problem, I found a simple solution: not using Singleton. I removed  the Singleton pattern from GPSProvider and change every class that uses GPSProvider.GetInstance() to receive the current GPS intance. In the Navigator module, I passed the GPS instance through its class’ constructor.
GPSAbstractProvider.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import java.util.ArrayList;
import java.util.List;
 
public abstract class GPSAbstractProvider {
 
 private List<GPSListener> listeners;
 
 public GPSAbstractProvider() {
 this.listeners = new ArrayList<GPSListener>();
 }
 
 public abstract void initGPSService();
 
 public void attach(GPSListener listener) {
 this.listeners.add(listener);
 }
 
 public void dettach(GPSListener listener) {
 this.listeners.remove(listener);
 }
 
 public void notifyPositionUpdated(Position position) {
 for ( GPSListener listener : this.listeners ) {
 listener.positionUpdated(position);
 }
 }
 
 public void notifyStatusUpdated(int status) {
 for ( GPSListener listener : this.listeners ) {
 listener.statusUpdated(status);
 }
 }
 
}
GPSProvider.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class GPSProvider extends GPSAbstractProvider implements LBSPositionObserver {
 private Position lastCoordinate;
 
 private GPSProvider() {
 super();
 }
 
 @Override
 // perform GPS initialization
 public void initGPSService() {
 (...)
 }
 
 @Override
 public void positionUpdated(Position position) {
 this.lastCoordinate = position;
 this.notifyPositionUpdated(position);
 }
 
 @Override
 public void setStatus(int status) {
 this.notifyStatusUpdated(status);
 }
 
 public Position getLastCoordinate() {
 return this.lastCoordinate;
 }
 
}
Navigator.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
public class Navigator implements GPSListener {
 
 private NavigatorObserver observer;
 private GPSAbstractProvider gps;
 
 public Navigator(NavigatorObserver observer, GPSAbstractProvider gps) {
 this.observer = observer;
 this.gps = gps;
 }
 
 public void navigate(Route route) {
 this.gps.attach(this);
 }
 
 public void pause() {
 this.gps.dettach(this);
 }
 
 @Override
 public void positionUpdated(Position position) {
 // navigate user through route.
 int step = this.verifyStepUpdated();
 if ( step != -1 ) {
 this.observer.StepUpdated(step);
 }
 
 if ( this.achievedDestination() ) {
 this.observer.DestinationAchived(position);
 }
 }
 
 private boolean achievedDestination() {
 (...)
 }
 
 private int verifyStepUpdated() {
 (...)
 }
 
 @Override
 public void statusUpdated(int status) {
 // send status to end user.
 }
}
Much better! Notice that I still have just one single instance of my GPS class. All I have to do is creating my GPS at the beginning of the program and pass it through classes that use it.
Doing this, testing my code became very simple. I inject my GPS mock to simulate GPS data in my tests,  just as below.
NavigatorTest.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import java.util.ArrayList;
import java.util.List;
 
import junit.framework.TestCase;
 
public class NavigatorTest extends TestCase implements NavigatorObserver {
 
 private Navigator navigator;
 private GPSAbstractProvider gps;
 
 public void testNavigate() throws Exception {
 List<Position> gpsPositions = new ArrayList<Position>();
 this.addPositions(gpsPositions);
 this.gps = new GPSTestProvider(gpsPositions);
 
 this.navigator = new Navigator(this, this.gps);
 this.navigator.navigate(this.createSimpleRoute());
 
 gps.initGPSService();
 
 assert(...);
 assert(...);
 }
 
 private Route createSimpleRoute() {
 (...)
 }
 
 private void addPositions(List<Position> gpsPositions) {
 (...)
 }
 
 @Override
 public void DestinationAchived(Position destination) {
 (...)
 }
 
 @Override
 public void StepUpdated(int step) {
 (...)
 }
 
}
As you can see, I can use any GPS provider in my tests, making them much more easy and flexible.
In addition to the disavantage presented, Alex Miller discuss some points why he hates Singleton pattern.
From here, trying avoiding this pattern in situations like that. Think twice before applying Singleton in your project.
See you

Internet through the sky


Hi,
it’s incredible how Internet is in everywhere. After Wi-Fi, WiMax and 3G make possible the internet access in shoppings and airports, it’s time to read your favority blog inside the airplane.
According to American Airlines, their passengers will be able to test in-flight Internet access. At the beginning, just two flights will provide this service: New York – Los Angeles and San Francisco – Miami, both in Boing 7676-200. However, the company have plans to enlarge the service in two weeks.
Passengers will be able to use e-mail, instant messaging, to download video and connect to secure networks on notebook computers or other wireless devices such as smart phones through three wireless access points on the plane. Unfortunately, this service will not be free of taxs. Facing record high fuel prices, American plans to charge $9.95 to $12.95 for Internet service, depending on flight length.
Well, it seems a good entertainment alternative for that long/boring flights and to help in some late job.

Even LINQ for JavaScript

LINQ is one of my favorite features in the C# language so far. There is no such a thing as filtering, ordering and grouping data using an easy and fluent API. In the last weeks I found myself writing lot of JavaScript code. More than just ajax calls, DOM manipulation and fancy animations, my team and I maintain a huge js model which includes entities, controllers and repositories. Because of that, many of the operations that we regularly implement in server-side are implemented in client-side as well such as finding, sorting and grouping elements in data collections. On the server we use LINQ to perform such operations, but how to implement them in JavaScript?
Luckly, there is a JavaScript library that provides all LINQ operations with a very similar sintaxe. Just as C#, LINQ for JavaScript operates under IEnumerable objects. Therefore, the first thing to do is create an IEnumarable object with the FROM function. To illustrate the library usage, I will start with an array of people. The code below includes the Person object definition and the creation of an enumerable of people from an array. Very straightforward.
init-person
Since the enumerable is created, we are free to perform all LINQ operation on it. Let’s start with a simple search: I want to find the person whose name is ‘Fernando’. The code below illustrates that. Notice the sintaxt used by the library. While in C# we write lambda expressions (x => x.Name), here we use the symbol $.
first
Next, we filter the collection with the people with age greater then 25 and select their names.
where
Next, we order the collection by age and select their names.
order
Finally, we group the collection by sex. In addition, each group is ordered by name.
groupBy
As you can see, there is no secret. The sintaxe is really really similiar. I could show others the operations here, but they are all avaible in the library’s documentation. So, if you got interested by LINQ for JavaScript, take a look in the project page on codeplex. It helped me a lot and hope it can bu useful for you as well.
See you,

Relational Persistence for Java and .NET

Historically, Hibernate facilitated the storage and retrieval of Java domain objects via Object/Relational Mapping.  Today, Hibernate is a collection of related projects enabling developers to utilize POJO-style domain models in their applications in ways extending well beyond Object/Relational Mapping.

Hibernate News

JBoss Community Recognition Awards: Voting ends tomorrow!
Jul 25, 2013 5:24 AM by Sanne Grinovero
The voting for the JBoss Community Recognition Awards 2013 ends tomorrow; if you haven't done it yet please vote for our contributors. Among other…
Hibernate ORM 4.2.3.Final Released
Jul 3, 2013 12:06 PM by Brett Meyer
Hibernate ORM 4.2.3.Final was just released. The full changelog can be viewed here HHH-8112 fully documented the OSGi capabilities and included mu…
View more hibernate news

Small Project on Bus Reservation 

Implement a bus reservation system asume bus' seats are as follows
HHHHHH
HHHHHH
HHHHHH
. . . . . . . .
you can assume 10 rows in bus.

Now if user enters 4 as required seat no then the prefrence order would be
4
3,1
2,2
2,1,1
1,1,1,1
and the function should return the seat number.

1. Bus.java


package com.cobra.entity;

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

public class Bus {

private List<Row> rowList = new ArrayList<Row>();
private static int seatAvailable;

public Bus() {
// TODO Auto-generated constructor stub
}

public List<Row> getRowList() {
return rowList;
}

public void setRowList(List<Row> rowList) {
this.rowList = rowList;
}

public int getSeatAvailable() {
return seatAvailable;
}

public void setSeatAvailable(int seatAvailable) {
Bus.seatAvailable = seatAvailable;
}

}

2. Row.java


package com.cobra.entity;
import java.util.ArrayList;
import java.util.List;
public class Row {
private List<Seat> seatList = new ArrayList<Seat>();
private int seatsAvailable;
public Row() {
this.seatsAvailable = 5;
}
public List<Seat> getSeatList() {
return seatList;
}
public void setSeatList(List<Seat> seatList) {
this.seatList = seatList;
}
public int getSeatsAvailable() {
return seatsAvailable;
}
public void setSeatsAvailable(int seatsAvailable) {
this.seatsAvailable = seatsAvailable;
}
}
3. Seat.java

package com.cobra.entity;
public class Seat {
private int seatNo;
private boolean isAvailable;
public Seat() {
// TODO Auto-generated constructor stub
}
public Seat(int seatNo) {
this.seatNo = seatNo;
this.isAvailable = true;
}
public int getSeatNo() {
return seatNo;
}
public void setSeatNo(int seatNo) {
this.seatNo = seatNo;
}
public boolean isAvailable() {
return isAvailable;
}
public void setAvailable(boolean isAvailable) {
this.isAvailable = isAvailable;
}
}
4. BusControl.java


package com.cobra.program;
import com.cobra.entity.Bus;
import com.cobra.entity.Row;
import com.cobra.entity.Seat;
public class BusControl {
public static Bus populate()
{
Bus bus = new Bus();
/*
*  create new row
*  add seats to that new row
*/
Row row = null;
for(int i=0 ;i <=9 ;i++)
{
row = new Row();
row.getSeatList().add(new Seat((1)+((i)*5)));
row.getSeatList().add(new Seat((2)+((i)*5)));
row.getSeatList().add(new Seat((3)+((i)*5)));
row.getSeatList().add(new Seat((4)+((i)*5)));
row.getSeatList().add(new Seat((5)+((i)*5)));
bus.getRowList().add(row);
bus.setSeatAvailable(bus.getSeatAvailable()+5);
}
return bus;
}
public static void allocate(Bus bus,int seatsRequired)
{
//if required seat is <= 0 return
if(seatsRequired <= 0)
return;
for(Row row:bus.getRowList())
{
//if the row has more seats than required seats then allocate
if(row.getSeatsAvailable()>=seatsRequired)
{
for(Seat seat:row.getSeatList())
{
if(seat.isAvailable()==true && seatsRequired >0)
{
System.out.print(seat.getSeatNo()+" ");
seat.setAvailable(false);
bus.setSeatAvailable(bus.getSeatAvailable()-1);
row.setSeatsAvailable(row.getSeatsAvailable()-1);
seatsRequired--;
}
if(seatsRequired==0)
return;
}
if(seatsRequired==0)
return;
}
}
//recursion process
allocate(bus,seatsRequired-1);
allocate(bus,1);
}
}
5. MainApp.java
package com.cobra.program;
import com.cobra.entity.Bus;
public class MainApp {
public static void main(String[] args) {
// populate bus seat numbers
Bus bus = BusControl.populate();
// First Allocating Three Seats
int seatRequired = 3;
// check for availability of seat in the bus;
if (bus.getSeatAvailable() < seatRequired) {
System.out.println("Seats are not Available");
} else {
BusControl.allocate(bus, seatRequired);
}
                System.out.println("");
// Second Allocation Four Seats
seatRequired = 4;
// check for availability of seat in the bus;
if (bus.getSeatAvailable() < seatRequired) {
System.out.println("Seats are not Available");
} else {
BusControl.allocate(bus, seatRequired);
}
                   System.out.println("");
// Third Allocating Two Seats
seatRequired = 2;
// check for availability of seat in the bus;
if (bus.getSeatAvailable() < seatRequired) {
System.out.println("Seats are not Available");
} else {
BusControl.allocate(bus, seatRequired);
}
}
}
Output:  1 2 3 
               6 7 8 9
               4 5