Artificial Intelligence in BPOs

Machines to replace humans in IPsoft‘s BPOs


IPsoft, which relies on artificial intelligence to manage computer networks, is ready to disrupt the business process outsourcing (BPO) industry by using what it calls "cognitive technology" that enables machines to do the work of humans, the India-born founder of the New York-based company said.

"By Christmas you will see it in action in one of the largest media companies," founder and chief executive officer Chetan Dube told ET in an exclusive interview. IPsoft's cognitive technology assimilates information just like the human brain and processes it with reliability of computers to solve problems, he said. A global investment bank and a large media company will be among the first users of the cutting-edge technology, Dube said, but declined to identify the customers.

Going beyond call centres
Earlier this year, Infosys tied up with IPsoft to use the latter's technology to provide IT infrastructure management solutions to its global customers. Its autonomic artificial intelligence engine picks trends by analysing hundreds of pieces of information all at once to diagnose and solve problems on computer networks with minimal human intervention.

IPsoft expects cognitive technology-based solutions, which it is introducing soon, to go well beyond basic call centre jobs to include other services such as disease diagnosis or even medicine prescription, typically the domain of trained practitioners with specialised knowledge.

"If you think autonomics has changed the world, wait till you see cognitive technologies," Dube, 44, said. "It is not going to be just great; it is going to be a phenomenon." IPsoft was founded in 1998 by Dube, a former associate professor of mathematics at New York University. The company tops $700 million (Rs 4,500 crore) in sales, and counts Morgan Stanley and BT among its clients.

Its India head-office is in Bangalore, where it employs 800 staff and is in the process of opening a second campus. Dube, a computer science graduate from IIT-Delhi, has been arguing that the era of outsourcing simple manual tasks to low-wage countries is nearing an end and will be replaced by intelligent, selflearning machines doing the same job at a fraction of the cost.

IPsoft, he said, is at the forefront of such a "creative destruction" that will transform the "bloated" IT industry. Nearly two-thirds of all problems on computer networks are being solved by IPsoft with no human intervention at all, Dube said, resulting in cost savings of at least 30%. In the aftermath of the 2008 global financial crisis, corporations in the US and Europe have been looking for ways to reduce costs and such technologies have been driving greater outsourcing in infrastructure management business, making it one of the fastest-growing services lines for the industry.

Dube said the company does not require capital for its current needs, but it is considering the possibility of going public. Ernst & Young is advising it on a potential IPO that, if it happens, will take place within 24 months. The intent of going public would be to help the company expand and invest more in research to be able to bring about more innovative technologies, the CEO said. "Now we don't have to report quarter by quarter; we can chase the 15-year dream."

CPU within Rs 25,000

Buyers‘ guide: CPU within Rs 25,000


I am looking for a CPU within a budget of Rs 25,000. It should have a good processor along with a decent graphics card for gaming. 

— Ashley George, Mayank Shah, K Srinivasan 

Assuming you already have a monitor, keyboard, and mouse, here are our suggestions for your CPU components... 

Processor
Buy the Pentium G2020. It is spiffy enough for everyday tasks such as web browsing, image and video editing, office work and gaming. 
Cost: Rs 3,500 

Motherboard
Here, go with Gigabyte's GA-H 61M-DS 2. This board supports the processor we have selected, but make sure that you pick its third-revision (mentioned on its box or on the motherboard itself). 

Cost: Rs 2,900 

RAM
Get a single stick of 4GB DDR3 1333MHz RAM from Transcend or Kingston. The motherboard we've selected has two RAM slots so you can add more memory in the future, if required. 

Cost: Rs 2,000 

Hard disk
Given that you will install games, opt for a 500GB hard disk from either Seagate or Western Digital. 

Cost: Rs 3,100 

Graphics card
Go for AMD Radeon HD 7770 (1GB) from brands such as PowerColor, Gigabyte or HIS. This card is capable of handling most video games in full HD resolution. 

Cost: Rs 8,500 

Chassis and power supply unit (PSU)
Here, we suggest the Cooler Master Elite 311 chassis and the Corsair VS 450 PSU. Both are good products that will not only support this hardware, but also a better graphics card in the future. 

Cost: Rs 2,000 and Rs 2,200, respectively 

Optical drive
Pick any DVD drive that supports 22X or 24X writing speed. Samsung and LG are reliable bets. 

Cost: Rs 1,000 
This configuration costs around Rs 25,200. But if you can spend 3,000 more, you can opt for Intel's Core i3 3210 processor. The i3 chip is a better processor than the Pentium G2020 and promises smoother operations.

How to locate your misplaced Android phone

How to locate your misplaced Android phone


Often we misplace our phone. If you muted the ring, then you can't even call from another phone to locate it. 

That's when Android Device Manager comes in handy. Go to google.com/android/devicemanager. The site will automatically connect to your phone and display a message like: "Last located at 6:42 PM; Manekshaw Parade Grounds Bus Stop, Cubbon Road, Shivaji Nagar, Bangalore, Karnataka 560001, India - Accurate to 574 meters. Last used August 14, 2013". 

To locate the device, click on Ring. The device will ring at full volume for 5 minutes. You have to press the power button to stop it ringing.

Best browser for OS

Best browser: which should you be using?

Competition among browsers is more fierce than ever. Chrome and Firefox release 72 new versions every week, Microsoft has redesigned Internet Explorer to make it finger-friendly, and as we all race to tablets and smartphones we're being tempted with all kinds of alternatives to systems' stock browsers.
But which is the best browser for you and your hardware? Let's find out.
We tested the latest official releases of the big browsers - Internet Explorer 10, Firefox 19, Safari 5, Chrome 25 and Opera 12 - on a Core i5 PC running Windows 8 Pro. It's worth noting that Safari on Macs running OS X Mountain Lion is at version 6, but the PC version and older Mac versions are one behind.
Whether you've got a Windows PC, Mac OS X laptop, an Android tablet or something in between, we've got it covered.

The best browser for speed





Best browser: which should you be using?
Both versions of IE 10 are speed demons, but others have better standards support
Every browser we tested felt perfectly snappy in everyday browsing, but as ever we put them through the Sunspider benchmark tests to see how well they fared. IE raced through the tests in 97ms in desktop mode, while the touch-based IE took 113.7 milliseconds. Those numbers are amazing: it wasn't that long ago that IE benchmarks were measured in millennia.
Chrome was next, at 147.2ms, Firefox was narrowly behind with 176.6ms, Opera scored 180.5ms and Safari was narrowly beaten into last place with 182.7ms.

The best browser for add-ons





Best browser: which should you be using?
Firefox 18 is so last week. All the cool kids upgraded to version 19, like, hours ago
Firefox has always been the king here, its combination of add-ons, App Tabs for web apps and Greasemonkey scripts making it the power user's friend. That's still the case, but Chrome is catching up fast, its Web Store positively packed. Apple and Microsoft's selections are fairly thin, but Opera's selection includes commonly used add-ons such as ad blockers, password managers and so on.
Opera deserves a special mention here because it's more than just a browser. It has integrated email, newsgroups and IRC chat, the Opera Unite file server, Opera Turbo to improve performance on crappy mobile connections, and Sidebar-style widgets for games, web applications and utilities.

The best browser for Windows 7





Best browser: which should you be using?
IE enables you to add all kinds of toolbars to its minimalist interface. Don't do it!
Safari simply doesn't cut it in this company: it's last year's browser, the slowest here, and we don't like the user interface very much. There's nothing particularly wrong with it, but there's nothing particularly right with it either.
Long-term browser battle fans will be highly amused by IE's performance these days: it's really, really quick, comfortably ahead of its rivals, and now everyone's making their browsers as minimalist as possible there's no horrible UI to get angry at unless you start going crazy with third-party toolbars. Please don't. For sheer speed on Windows 7 PCs, IE is the browser to go for.

The best browser for Windows 8

If you're sold on the new touchy-feely direction of Windows 8 then Internet Explorer is the star, at least in Metro/Modern mode: it's a very nice touch-based browser, although it doesn't support Flash. Firefox has a Metro version in development, but it's not quite ready for prime time just yet.
In desktop mode it's the same story as with Windows 7: Safari knocked out first, IE winning on sheer speed and Chrome and Firefox competing on syncing and extensions support.

The best browser for Windows XP

Internet Explorer takes an early bath here, because it no longer supports Windows XP or Windows Vista. Our pick here would be Chrome: its system requirements are tiny (Pentium 4, 100MB of disk space, 128MB of free RAM), making it particularly good on even very modest hardware.

The best browser for OS X





Best browser: which should you be using?
Safari on Windows, partying like it's 2012. Apple has clearly lost interest in this one
We tried the main browsers on a Core i5 iMac, and while the results were similar on paper - Safari went through Sunspider in a reported 197.4ms, only slightly behind Chrome's 164ms and slightly faster than Opera's 201ms and Firefox's 204ms - the reality was different: where the other browsers raced through Sunspider in a matter of seconds, Safari took several minutes.
We also found its performance nose-dived when we had more than a handful of tabs open, and opening image-heavy sites such as Tumblr archives was a fairly reliable way to kill it completely. The other browsers felt noticeably nippier visiting the same sites.
There's more to the browsers than just speed, of course. Safari offers a clutter-free reading mode, Reading List for reading interesting things later on and iCloud syncing with iOS devices; Firefox has Firefox Sync; Opera has the Unite file sharing system and Visual Tabs and so on.
For simply browsing we think Chrome has the edge here, but you might find that your chosen sync service - iCloud? Firefox? Chrome? - makes the browser choice for you.

The best browser for privacy





Best browser: which should you be using?
Opera's visual tabs are nifty and browsing is a joy. Next year's will be Webkit-powered
While each browser offers a decent range of privacy protection, they're not all enabled by default - so for example Firefox's Do Not Track button is unchecked when you install it, and so is Opera's.
Safari for Windows doesn't have a Do Not Track setting - as we've already said, it's a comparatively old browser - and Chrome buries its privacy controls in the Advanced Settings section.
We like Microsoft's approach here: its Tracking Protection Lists offer something more useful than a broad-brush Do Not Track system, enabling you to block specific kinds of tracking such as advertisers who really want to flog stuff to your kids.

The best browser for HTML5





Best browser: which should you be using?
Chrome for desktop is fast, has excellent standards compliance and lots of add-ons
HTML5 is the lingua franca of the modern web, and the better your browser's standards support the happier your online life will be. Using HTML5test.com, which awards up to 500 points for standards compliance, we found Chrome the clear winner with 448 points and 13 bonus points.
Opera had 404 and 9 bonus points, Firefox 393 and 13, Safari (OS X) 393 and 13, Internet Explorer 320 and 6, and finally Safari (Windows) had just 278 and 2 bonus points.

The best browser for Android





Best browser: which should you be using?
Chrome is a star on Android too, if your OS is new enough
Android users are spoilt for choice these days. In our head-to-head of the best Android browsers, several apps shone.
Chrome shone for its speed and its integration with its desktop sibling; Dolphin Browser HD for its bulging features list; and Skyfire for its many bright ideas. Once again Chrome has the edge here in the speed stakes, but it's worth looking at rivals' features before committing to it.

The best browser for iPad





Best browser: which should you be using?
Browsers are increasingly part of wider systems, so most offer syncing between devices
The lack of tabs in Apple's Safari drove us daft on the original iPad, but now it's got tabbed browsing and iCloud syncing we think it's the best browser on the platform, especially on the newest devices.
In our experience it's faster and more reliable than iCab Mobile, considerably nicer to look at than Atomic Browser, and less likely to dump you back to the home screen for no good reason than non-Apple browsers.
That's unless you use Chrome on the desktop and want to sync tabs, bookmarks and passwords, in which case Chrome's the one to go for.

 

How to protect yourself from apps that make Wi-Fi hacking simple

How to protect yourself from apps that make Wi-Fi hacking simple

It's not paranoia: Using public or open Wi-Finetworks without taking your security into consideration is a bad idea. You don't even have to crack the network's passwords to grab tons of data from unsuspecting users on the network-We've shown you how to do it, and how to stop it from happening to you. Now, dSploit, a security toolkit for Android, makes that process so simple anyone can do it. Here's how it works, and how to protect yourself.

What is dSploit?
dSploit is actually a suite of security tools bundled together in one application. It runs on rooted Android (2.3+) devices, its code is freely available at GitHub, and it's actually a great utility if you're a security professional or otherwise enjoy the ins and outs of network security, hacking, and penetration testing. We want to be clear that we're not villainizing the tool here; unlike apps like Firesheep, Faceniff, and Droidsheep, dSploit isn't made for the sole purpose of cracking networks or hijacking user sessions. It can certainly sniff out passwords transmitted in plain text on an open network, and it can crack poorly secured Wi-Fi networks. It can also scan networks for vulnerabilities, crack keys on common routers, and of course, hijack browser, website, or social network sessions and hold on to them. You can see a full list of the tool's features here.

For a security professional, an amateur looking for an affordable way to learn more about network security (or who's been tasked by their office to secure their Wi-Fi but can't afford professional pen-testers), or someone looking to protect their own network, dSploit can be a valuable resource. It can also be a valuable resource for people looking to steal your data. That's why we're going to talk about how it works and how you can protect your passwords and private data from anyone else using it.

How dSploit (and other apps like it) work
dSploit makes it easy to do two things: Sniff out passwords being sent unencrypted, and hijack active browser sessions so you can masquerade as someone who's already logged in to a site or service. In both cases, they're really one-touch operations once you have the app installed. The former is easy to do. If someone is visiting a site, or logging in to a service without using HTTPS or SSL, your password is likely being sent in clear text. Anyone sniffing packets on a network can capture them without having to do any real kind of packet inspection, and once they have it, they'll try it on as many sites and services as possible to see if you use it for other accounts. The video above, from OpenSourceGangster, explains how the app works in detail, and how to use it.

The latter is a bit more intricate. If you're not familiar with session hijacking, it's the process of capturing cookies to exploit a valid active session that another user has with a secured service in order to impersonate that other user. Since no sensitive data like a login or password is transmitted in the cookie, they're usually sent in the clear, and in most cases they're used by web sites and social networks as a way of identifying a user with a current session so the site doesn't forget who you are every time you reload. This is the most common attack vector for apps that sniff out passwords and sessions via Wi-Fi. We showed you how this works when Disconnect, one of our favorite privacy protecting browser extensions, added protection against widget jacking and session hijacking, if you want to see an example.

dSploit approaches session hijacking in a similar manner to the other tools we've mentioned, mostly because it works well. The folks over at MakeUseOf explain how the app works in further detail, including some of the things you can do with it. Many web sites just encrypt your username and password, and once that handoff is made, everything else is unencrypted. While many sites have moved to HTTPS (and there are tools to help that we'll get to a little later), most require you to activate their HTTPS features. Many other sites haven't bothered moving to HTTPS universally at all.

What's the real risk here?
The real risk from tools like this varies. The odds of you encountering someone in your local coffee shop running dSploit, Firesheep, or any other app like them to capture passwords and hijack sessions is pretty slim, but as we've mentioned, it only takes one person to ruin your day.

Someone could just capture as many Facebook or Twitter sessions as they can (after which they can change a user's password and keep the Facebook account for themselves), hijack Amazon shopping sessions and grab address and credit card information, read your email and chats, and so on. The risk goes up with more and more tools available that are easy for anyone to use, and with the number of people out there who simply don't protect themselves by encrypting their data.

How can I protect myself?
Protecting yourself from these tools like it is actually remarkably easy if you put in the effort to actually do it:

* Turn on HTTPS on every site that allows you to connect with it, and install HTTPS Everywhere. This will make sure you're using HTTPS at all times, whenever possible, and none of your web browsing traffic is sent unencrypted.

* Get a privacy-protecting browser extension like Disconnect, which also protects against widget jacking or side-jacking. Disconnect is our favorite, but it shouldn't be the only tool in your toolkit.

* Use a VPN when browsing on public, free, or other open networks. We've explained why you should have a VPN before. We've even explained how to tell if a VPN is trustworthy. Using a VPN is the best way to make sure all of your data is encrypted and safe from anyone else on the same network, whether it's wired or wireless, public or private.

* Use your head, and practice good internet hygiene. Hone your phishing and scam detection skills, turn your BS detecter up to max, and learn how to protect yourself from online fraud. Someone doesn't have to hijack your session or passwords to get to you-they could just as easily replace the website you're on with one that looks like it but insists you give it a ton of data first. Be smart.

* It doesn't take much to use HTTPS everywhere you can, fire up a VPN if you're going to be working from the library, or just not to use public Wi-Fi and wait until you get home or tether to your phone instead (that's always another option). However, if everyone did it, unscrupulous use of tools like these wouldn't' be an issue and only the people who needed them would use them. However, as long as they're so effective, it makes sense for you to take the necessary steps to protect yourself.

10 Common Mistakes Java Developers Make when Writing SQL

10 Common Mistakes Java Developers Make when Writing SQL

Java developers mix object-oriented thinking with imperative thinking, depending on their levels of:
  • Skill (anyone can code imperatively)
  • Dogma (some use the “Pattern-Pattern”, i.e. the pattern of applying patterns everywhere and giving them names)
  • Mood (true OO is more clumsy to write than imperative code. At first)
But when Java developers write SQL, everything changes. SQL is a declarative language that has nothing to do with either object-oriented or imperative thinking. It is very easy to express a query in SQL. It is not so easy to express it optimally or correctly. Not only do developers need to re-think their programming paradigm, they also need to think in terms of set theory.
Here are common mistakes that a Java developer makes when writing SQL (in no particular order):

1. Forgetting about NULL

Misunderstanding NULL is probably the biggest mistake a Java developer can make when writing SQL. This is also (but not exclusively) due to the fact that NULL is also called UNKNOWN. If it were only called UNKNOWN, it would be easier to understand. Another reason is that JDBC maps SQL NULL to Java null when fetching data or when binding variables. This may lead to thinking that NULL = NULL (SQL) would behave the same way as null == null (Java)

One of the crazier examples of misunderstanding NULL is when NULL predicates are used with row value expressions.

Another, subtle problem appears when misunderstanding the meaning of NULL in NOT IN anti-joins.

The Cure:

Train yourself. There’s nothing but explicitly thinking about NULL, every time you write SQL:

Is this predicate correct with respect to NULL?
Does NULL affect the result of this function?
2. Processing data in Java memory

Few Java developers know SQL very well. The occasional JOIN, the odd UNION, fine. But window functions? Grouping sets? A lot of Java developers load SQL data into memory, transform the data into some appropriate collection type, execute nasty maths on that collection with verbose loop structures (at least, before Java 8′s Collection improvements).

But some SQL databases support advanced (and SQL standard!) OLAP features that tend to perform a lot better and are much easier to write. A (non-standard) example is Oracle’s awesome MODEL clause. Just let the database do the processing and fetch only the results into Java memory. Because after all some very smart guys have optimised these expensive products. So in fact, by moving OLAP to the database, you gain two things:

Simplicity. It’s probably easier to write correctly in SQL than in Java
Performance. The database will probably be faster than your algorithm. And more importantly, you don’t have to transmit millions of records over the wire.
The Cure:

Every time you implement a data-centric algorithm in Java, ask yourself: Is there a way to let the database perform that work for me?

3. Using UNION instead of UNION ALL

It’s a shame that UNION ALL needs an extra keyword compared to UNION. It would be much better if the SQL standard had been defined to support:

UNION (allowing duplicates)
UNION DISTINCT (removing duplicates)
Not only is the removal of duplicates rarely needed (or sometimes even wrong), it is also quite slow for large result sets with many columns, as the two subselects need to be ordered, and each tuple needs to be compared with its subsequent tuple.

Note that even if the SQL standard specifies INTERSECT ALL and EXCEPT ALL, hardly any database implements these less useful set operations.

The Cure:

Every time you write a UNION, think if you actually wanted to write UNION ALL.

4. Using JDBC Paging to page large results

Most databases support some way of paging ordered results through LIMIT .. OFFSET, TOP .. START AT, OFFSET .. FETCH clauses. In the absence of support for these clauses, there is still the possibility for ROWNUM (Oracle) or ROW_NUMBER() OVER() filtering (DB2, SQL Server 2008 and less), which is much faster than paging in memory. This is specifically true for large offsets!

The Cure:

Just use those clauses, or a tool (such as jOOQ) that can simulate those clauses for you.

5. Joining data in Java memory

From early days of SQL, some developers still have an uneasy feeling when expressing JOINs in their SQL. There is an inherent fear of JOIN being slow. This can be true if a cost-based optimiser chooses to perform a nested loop, possibly loading complete tables into database memory, before creating a joined table source. But that happens rarely. With appropriate predicates, constraints and indexes, MERGE JOIN and HASH JOIN operations are extremely fast. It’s all about the correct metadata (I cannot cite Tom Kyte often enough for this). Nonetheless, there are probably still quite a few Java developers who will load two tables from separate queries into maps and join them in Java memory in one way or another.

The Cure:

If you’re selecting from various tables in various steps, think again to see if you cannot express your query in a single statement.

6. Using DISTINCT or UNION to remove duplicates from an accidental cartesian product

With heavy joining, one can loose track of all the relations that are playing a role in a SQL statement. Specifically, if multi-column foreign key relationships are involved, it is possible to forget to add the relevant predicates in JOIN .. ON clauses. This might result in duplicate records, but maybe only in exceptional cases. Some developers may then choose to use DISTINCT to remove those duplicates again. This is wrong in three ways:

It (may) solve the symptoms but not the problem. It may as well not solve the symptoms in edge-cases.
It is slow for large result sets with many columns. DISTINCT performs an ORDER BY operation to remove duplicates.
It is slow for large cartesian products, which will still load lots of data into memory
The Cure:

As a rule of thumb, when you get unwanted duplicates, always review your JOIN predicates. There’s probably a subtle cartesian product in there somewhere.

7. Not using the MERGE statement

This isn’t really a mistake, but probably some lack of knowledge or some fear towards the powerful MERGE statement. Some databases know other forms of UPSERT statements, e.g. MySQL’s ON DUPLICATE KEY UPDATE clause. But MERGE is really so powerful, most importantly in databases that heavily extend the SQL standard, such as SQL Server.

The Cure:

If you’re UPSERTING by chaining INSERT and UPDATE or by chaining SELECT .. FOR UPDATE and then INSERT or UPDATE, think again. Apart from risking race conditions, you might be able to express a simpler MERGE statement.

8. Using aggregate functions instead of window functions

Before the introduction of window functions, the only means to aggregate data in SQL was by using a GROUP BY clause along with aggregate functions in the projection. This works well in many cases, and if aggregation data needed to be enriched with regular data, the grouped query can be pushed down into a joined subquery.

But SQL:2003 defined window functions, which are implemented by many popular database vendors. Window functions can aggregate data on result sets that are not grouped. In fact, each window function supports its own, independent PARTITION BY clause, which is an awesome tool for reporting.

Using window functions will:

Lead to more readable SQL (less dedicated GROUP BY clauses in subqueries)
Improve performance, as a RDBMS is likely to optimise window functions more easily
The Cure:

When you write a GROUP BY clause in a subquery, think again if this cannot be done with a window function.

9. Using in-memory sorting for sort indirections

The SQL ORDER BY clause supports many types of expressions, including CASE statements, which can be very useful for sort indirections. You should probably never sort data in Java memory because you think that

SQL sorting is too slow
SQL sorting cannot do it
The Cure:

If you sort any SQL data in memory, think again if you cannot push sorting into your database. This goes along well with pushing paging into the database.

10. Inserting lots of records one by one

JDBC knows batching, and you should use it. Do not INSERT thousands of records one by one, re-creating a new PreparedStatement every time. If all of your records go to the same table, create a batch INSERT statement with a single SQL statement and multiple bind value sets. Depending on your database and database configuration, you may need to commit after a certain amount of inserted records, in order to keep the UNDO log slim.

The Cure:

Always batch-insert large sets of data.

Source: http://goo.gl/Gkwz5E

Apache Camel

Introduction to Apache Camel


Apache Camel is a open source implementation of famous Enterprise Integration Patterns.   Camel is a Routing and Mediation Engine and facilitates the developers to create routes and mediation rules in variety of Domain Specific language(DSL) such as java, Spring/XML, scala etc.

Camel is versatile

Camel uses URIs to supports large number of transport and messaging models such as HTTP, JMS, JBI, Mina, SCA, CXF  it also  works well with external components and dataformats. To get a  feel of versatility of Camel you can browse the list of Components and URIs it supports in the link below. http://camel.apache.org/components.html

Camel is easy to use

Camel allows us to use same set of APIs to create routes and mediate messages between various components. This makes it extremely easy to use

Unit Testing camel is a breeze

Unit testing is essential to writing any quality code. Camel makes this facade of software development extremely easy. It provides bunch of ready make components like CamelContextSupport,  camel-guice, camel-test-blueprint for easily testing the code. More of this in a future post.

The Camel Terminologies/Classes/Interfaces

Endpoint

Endpoints are places where the exchange of messages takes place. It may refer to an address, a POJO, email address, webservice uri, queue uri, file etc. In camel an endpoint is implemented by implemented Endpoint interface. The endpoints are wrapped by something called routes.

CamelContext

CamelContext is at heart of all camel application and it represents Camel run time system.

Create camelcontext.
Add endpoints or components.
Add Routes to connect the endpoints.
Invoke camelcontext.start() – This starts all the camel-internal threads which are responsible for receiving, sending and processing messages in the endpoints.
Lastly invoking camelcontext.stop() when all the messages are exchanged and processed. This will gracefully stop all the camel-internal threads and endpoints.
CamelTemplate

This is a thin wrapper around the CamelContext object and it is responsible to sending exchange or messages to an endpoint.

Component

Component is really an endpoint factory. As camel supports lots of different kind of resources, each of these resources have different kind of endpoints. In practical cases application don’t create endpoints directly using Components. Instead CamelContext decideds which component to instantiate and then uses that component instance to create endpoints. So in app we will have. CamelContext.getEndpoint(“pop3://john.smith@mailserv.example.com?password=myPassword”); Now pop3 in this case is name of the component. CamelContext maps all the component name with the component classes and using the name it instantiates the instance. Once it has handle to the component it instantiates the endpoint by calling. Component.createInstance() method.

Message

Mesaage represents a single concrete message ie request, reply or exception. All concrete message class impements a message interface for example JmsMessage class.

Exchange

Exchange is a container of message. It is created when a message is received by a consumer during routing process.

Processor

Processor interface represents a class that processes a message. It contains a single method public void process(Exchange exchange) throws exception Application developers can implement this interface to preform business logic on the message when message is received by the consumer.

Routes and RouteBuilder

Route is the step by step movement of message from a source, through arbitrary types of decision by filters or routers to a destination. They are configured by help of DSL (Domain Specific language). Java DSL is created by implementing routebuilder interface. It has single method called configure() which defines the entire route of message. Routes can also be configured via xml file using spring.

A Small Example of Camel code.

Lets follow this with a small example to get a taste of what Camel can do. In this example we will move group of files present in a folder to a different folder. In this process we will do following

Checkout the dependencies for Camel.
Create a simple RouterBuilder.
Registering CamelContext in a spring file.
Injecting the routerbuilder in a the CamelContext Bean
Executing the class by starting the Camelcontext and finally stopping it once the execution is done.
1. Dependencies – Add following dependencies in your pom.xml

01
02
            org.apache.camel
03
            camel-core
04
            ${camel-version}
05
       
06
 
07
       
08
            org.apache.camel
09
            camel-spring
10
            ${camel-version}
11
       
12
 
13
       
14
            org.apache.camel
15
            camel-aws
16
            ${camel-version}
17
       
2. Create RouterBuilder - RouterBuilder can be created by extending org.apache.camel.builder.RouterBuilder class and overriding configure() method. Here is an example

01
import org.apache.camel.builder.RouteBuilder;
02
 
03
/**
04
 * Created by IntelliJ IDEA.
05
 * User: Niraj Singh
06
 * Date: 7/28/13
07
 * Time: 10:29 AM
08
 * To change this template use File | Settings | File Templates.
09
 */
10
public class MyFirstRouterBuilder extends RouteBuilder {
11
     @Override
12
    public void configure() throws Exception {
13
        try{
14
            from( "file:d:/vids").to("file:d:/temp");
15
        }catch(Exception e){
16
 
17
        }
18
     }
19
}
From() is the source endpoint and contains uri of file or directory which camel will be polling.
to() represents the target endpoint and contains name of target file or directory.
The file component uri is of form “file://nameOfFileOrDirectory“.
3. Registering CamelContext in spring and injecting RouterBuilder in spring.

01
02
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
03
       xsi:schemaLocation="
04
          http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
05
          http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">
06
 
07
   
08
         
09
   
10
 
11
   
12
 
13
4. Starting the camel context and executing the code and stopping the camel context.

01
import org.apache.camel.CamelContext;
02
import org.springframework.context.ApplicationContext;
03
import org.springframework.context.support.FileSystemXmlApplicationContext;
04
 
05
/**
06
 * Created by IntelliJ IDEA.
07
 * User: Niraj Singh
08
 * Date: 4/16/13
09
 * Time: 11:21 AM
10
 * To change this template use File | Settings | File Templates.
11
 */
12
public class CamelHello {
13
    public static void main(String args[]) throws Exception {
14
        try {
15
                ApplicationContext springcontext = new FileSystemXmlApplicationContext("D:/samayik/awsdemo/src/main/resources/hellocamel.xml");
16
                CamelContext context = springcontext.getBean("firstCamelContext", CamelContext.class);
17
                context.start();
18
                Thread.sleep(10000);
19
                context.stop();
20
 
21
            } catch ( Exception e ) {
22
                System.out.println(e);
23
            }
24
 
25
    }
26
}
If you run this class then first we load the camelcontext from the spring config file. Inject the router builder in it. After the context starts then all the file from source directory is copied to the target directory. Once all the file are copied then try copying a new file to the source directory, it will be copied to target as well until the context is running 10000 ms in this case.

I have few more advanced tutorials on camel. Perhaps you will find them useful. There links are listed in the reference sections.

References

http://camel.apache.org/
http://camel.apache.org/enterprise-integration-patterns.html
http://architects.dzone.com/articles/enterprise-integration
http://weblog4j.com/2013/05/14/amazon-sqs-listening-to-sqs-using-apache-camel-the-spring-dsl-way/
http://weblog4j.com/2013/04/17/amazon-sqs-listening-to-amazon-sqs-queue-using-apache-camel/
That is all folks. Though no one will write comments, but I like to persevere, and still request folks to drop in a line or two if you like this tutorial. 

Warm Regards
Harry

Google GSON

Getting Started with Google GSON

  

In Java world,  JSON is becoming de facto standard for data exchange format over XML because of its ease of use and efficiency in terms of transferring it.

If you don’t know about JSON, it is Javascript object notation, a text based data exchange format which is collection of name-value where name is strictly of string type and value can be int, boolean, array or another json object.

GSON is open source Java library developed by Google. It is an API for converting a Java object to/from json representation.

Why should you use it ?

Converts any Java object i.e new object or any existing/legacy object, to JSON and vice-versa.
Finest support for generic objects
Simple, convenient methods for conversions
No need of any annotation for fields for conversions
All the fields by default are included in conversions even private fields
If don’t want to include the field in conversion, use transient modifier for that field
It handles the null fields gracefully, by not including them in serialization output but during deserialization it is initialized back to null
How do you add it to project ?

Add it as dependency using one of following way

Using Maven

Add the following dependency to project’s pom.xml

1
2
    com.google.code.gson
3
    gson
4
    2.2.4
5
Using Gradle

Add following to project’s build.gradle

1
repositories {
2
    mavenCentral()
3
}
4
  
5
dependencies {
6
    compile 'com.google.code.gson:gson:2.2.4'
7
}
Use as unmanaged dependency

If you are not using any build tool, you can add gson jar to directly classpath or build path.

Download the latest jar from GSON project’s downloads page. The downloaded zip file contains 3 jar files – the binary, the source code and the javadoc. Grab the binary jar file and add it to your project classpath.

How to use it ?

For conversion of an object to/from json, you need to use the Gson class and its following 2 methods.

toJson()  => converts an object provided to json string, takes object to be converted as argument and returns the json representation string

fromJSon() => converts the json string to object, takes first param as json string as object and class literal of destination object and returns the destination object

You can use Gson instance/object multiple times as it does not maintain any state.

Following are few examples stating the use of GSON API.

Example 1 : For simple object

Consider the following model object for conversion purpose, but remember that you can convert any object

ModelObject.java

01
package in.ajduke.ap012;
02
/**
03
* An model for gson demo 
04
05
* @author ajduke
06
*/
07
public class ModelObject {
08
  String name;
09
  int val;
10
  boolean status;
11
  double f;
12
   
13
  public ModelObject(String name, int val, 
14
  boolean status, double f) {
15
    super();
16
    this.name = name;
17
    this.val = val;
18
    this.status = status;
19
    this.f = f;
20
  }
21
   
22
  @Override
23
  public String toString() {
24
    return "ModelObject [name=" + name + ",
25
    val=" + val + ", status="
26
    + status + ", f=" + f + "]";
27
  }
28
 
29
}
Following is listing for conversion object to json representation,

Example1.java

01
final Gson gson = new Gson();
02
// original object instantiation
03
ModelObject modelObject = new ModelObject("myname", 12, true, 2.3);
04
System.out.println("toJson ---");
05
System.out.println("Original Java object : " + modelObject);
06
// converting an object to json object
07
String json = gson.toJson(modelObject);
08
System.out.println("Converted JSON string is : " + json);
09
 
10
System.out.println("fromJson----");
11
// getting object from json representation
12
System.out.println("Original JSON string is : " + json);
13
// converting json to object
14
ModelObject modelObject1 = gson.fromJson(json, ModelObject.class);
15
System.out.println("Converted Java object : " + modelObject1);
Note the signature of fromJson() it takes second argument as the class literal of destination object.

Output as follows,

Example-1-output

toJson ---
Original Java object : ModelObject [name=myname, val=12, status=true, f=2.3]
Converted JSON string is : {"name":"myname","val":12,"status":true,"f":2.3}
fromJson----
Original JSON string is : {"name":"myname","val":12,"status":true,"f":2.3}
Converted Java object : ModelObject [name=myname, val=12, status=true, f=2.3]
Example 2 : For generic objects

For converting back the generic object to java object from json representation, we need to use use extra object as shown in follows

Type collectionType =new TypeToken<{ generic-object-with-type-information }>(){}.getType();

You need to provide the destination class type to TypeToken type parameter information as shown above. This is to form the Type instance and this we need to pass it to fromJson() method as second argument.

Following listing shows example for conversion of generic classes or the classes from collections framework to/from json

GenericModel.java

01
package in.ajduke.ap012;
02
/**
03
* An generified model for demo of gson conversion
04
* @author ajduke
05
*/
06
public class GenericModel {
07
  T value;
08
   
09
  public GenericModel(T value) {
10
    super();
11
    this.value = value;
12
  }
13
   
14
  @Override
15
  public String toString() {
16
    return "Model2 [value=" + value + "]";
17
  }
18
}
Example2.java

01
Gson gson = new Gson();
02
 
03
System.out.println("A generic object demo");
04
// a generified object
05
GenericModel model = new GenericModel<>(12);
06
 
07
// converting to json representation
08
String json = gson.toJson(model);
09
System.out.println("json representation :" + json);
10
 
11
// converting back to object
12
Type collectionType = new TypeToken>() {
13
}.getType();
14
GenericModel modelObj =
15
                  gson.fromJson(json, collectionType);
16
System.out.println("converted object representation: " + modelObj);
17
 
18
System.out.println("\nA object from collection framework\n");
19
// for collection framework objects
20
List listOfString = new ArrayList<>();
21
listOfString.add("ajduke");
22
listOfString.add("ajduchess");
23
 
24
// conversion to json
25
String jsonStr = gson.toJson(listOfString);
26
System.out.println("json representation :" + jsonStr);
27
 
28
Type collectionType2 = new TypeToken>() {
29
}.getType();
30
List listObj = gson.fromJson(jsonStr, collectionType2);
31
System.out.println("converted object representation: " + listObj);
Output as follows

Example2-output

A generic object demo
json representation :{"value":12}
converted object representation: Model2 [value=12]
 
A object from collection framework
 
json representation :["ajduke","ajduchess"]
converted object representation: [ajduke, ajduchess]
Example 3 : using transient

If you don’t want to include some field in json representation, you can use transient modifier to an variable declaration, then while converting it to json representation, GSON ignores that variable. But when converting back to an object from json string it initializes its default value depending on variable type.

Consider our ModelObject and lets skip the integer val from json representation so, modify the its declaration to transient as in following listing

ModelObject2.java

01
package in.ajduke.ap012;
02
/**
03
* An model for demo of gson conversion
04
*
05
* @author ajduke
06
*/
07
public class ModelObject {
08
  String name;
09
  transient int val;
10
  boolean status;
11
  double f;
12
   
13
  public ModelObject(String name, int val,
14
   boolean status, double f) {
15
    super();
16
    this.name = name;
17
    this.val = val;
18
    this.status = status;
19
    this.f = f;
20
  }
21
   
22
  @Override
23
  public String toString() {
24
    return "ModelObject [name=" + name + ",
25
    val=" + val + ", status="
26
    + status + ", f=" + f + "]";
27
  }
28
}
Following is listing

Example3.java

01
Gson gson = new Gson();
02
// original object
03
ModelObject modelObject = new ModelObject("namesake", 50, true, 4.3);
04
System.out.print("Original Java object : ");
05
System.out.println(modelObject);
06
 
07
// converting to an json representation
08
String json = gson.toJson(modelObject);
09
System.out.print("Converted JSON string is : ");
10
System.out.println(json);
11
 
12
// getting back the object from json representation
13
ModelObject modelObject3 = gson.fromJson(json, ModelObject.class);
14
System.out.print("Converted Java object : ");
15
System.out.println(modelObject3);
So, while converting it GSON ignores and output of above as follows

example3-output

Original Java object : ModelObject [name=namesake, val=50, status=true, f=4.3]
Converted JSON string is : {"name":"namesake","status":true,"f":4.3}
Converted Java object : ModelObject [name=namesake, val=0, status=true, f=4.3]
Thats all folks, for GSON introduction !!
Note: I had given small code snippet for all examples, to access full length listing go to this gist on github

What’s next ?

In next some articles, i will show you some extra goodies of GSON library,

so, stay tuned !!!