Monthly Archives: November 2012

Rapid Prototyping with Xcode Storyboard

Recently I wanted to rapid prototype a working application and show it to my team to understand the user flow. The options I had to do this was to use a HTML prototyping. Since I was learning Xcode and Objective C, I was curious to try out Xcode. I was impressed.

The use case is I wanted to build hierarchy of List of Category => List of Manufacturers => List of Brands => List of Model within the brands. Each these objects will have a set of attributes that the user can update.

In Xcode we will create a Tabbed Application and include the Storyboard option. We can target this application for iPad for better screen layout.

The front page looks as below,

From the storyboard enable Detail Disclosure and connect this ViewController to the next ViewController by dragging from the “>” to the next ViewController.

The code to populate the default value is below,


- (void)viewDidLoad
{

[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.myTableView.delegate = self;
self.myTableView.dataSource = self;
self.colorNames = [[NSArray alloc]
initWithObjects:@"Car", @"Video Console", @"SmartPhone", @"Phone", @"Camera", @"LED", nil];
}

Implementing Back button,

Rapid Prototyping, Back button

You can connect the “Back” button to “action” in the .h file. The code to make the Back button work is as below,

-(void)backButton:(id)sender{
[self dismissViewControllerAnimated:NO completion:nil];
}

Conclusion

If you notice that we can built a medium complex application prototype Rapidly using Xcode.

I hope this blog helped you.

Advertisements

Sample iPad app to work with JSon based Machine Learning System

For people in hurry get the iPad app Sample code and steps to run here.

GoSmarter is a JSon based Machine Learning System, to which, if you pass a Natural Language (NLP) Query, it will return a list of recommended products, primarily Used cars, Electronic Gadgets,  Video Consoles and others. This Machine Learning also uses Social networking capabilities to recommend products based on your friends.

In this sample, I have written a iPad based application, which is a 2 tabbed application, in the first tab, it will return all the popular items among GoSmarter user base. In the tab 2, we can pass any query and it will return list of products that are current from Amazon, eBay and other sources. Some of the iOS Programming capabilities it demonstrate are,

As a starter in Xcode it is easy to create a Tabbed Application with Default Storyboard with 2 Tabs. While creating the project, you just have to tell Xcode this application is better configured for iPad.

Refer this youtube Searchbar samples by iffytheperfect1983, In our sample, we got the query from the Searchbar and passed to GoSmarter JSon RESTful API Code is as below,

-(void)loadData: (NSString *)searchString {
NSString *baseUrlString = @"http://gosmarter.net/gosmarter/searchwall.do?query=";
NSString* escapedUrlString = [searchString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSString *urlString = [baseUrlString stringByAppendingString:escapedUrlString];
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest * request = [NSURLRequest requestWithURL:url];
connection = [NSURLConnection connectionWithRequest:request delegate:self];

if(connection){
webData = [[NSMutableData alloc]init];
}
[self.myTableView resignFirstResponder];
}

-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
NSString *searchQuery = searchBar.text;
[self loadData:searchQuery];
}

There is a good youtube demo for sharing data between 2 applications by iffytheperfect1983, there is also a good blog Storyboards Segue Tutorial: Pass Data Between View Controllers. These 2 show how to share data between 2 View Controllers. In our sample, the usecase is, when user selects a popular item, it should pass this query to the 2nd Tab View Controller and it should automatically return all the results in that query. UI is as below,

Storyboard Segue UI for sharing data between View Controller

Storyboard Segue UI for sharing data between View Controller

//First View Controller:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
SecondViewController *viewController = segue.destinationViewController;
NSIndexPath *indexPath = [self.myTableView indexPathForSelectedRow];
viewController.onLoad = YES;
viewController.searchString = [nameArray objectAtIndex:indexPath.row];
}

//Second View Controller</pre>
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
if(onLoad){
[self loadData:searchString];
}
}

There is a youtube video on creating Custom Table View Cell. We created a Custom TableView cell and associated with 2 Label one for Name and another for Price as below,

Custom UITableViewCell

Custom UITableViewCell

The code for Custom Cell,

@interface CustomTableViewCell : UITableViewCell
@property (weak, nonatomic) IBOutlet UILabel *label1;
@property (weak, nonatomic) IBOutlet UILabel *label2;
@end

To conclude in this sample, we demonstrated some of the fundamental capabilities of iOS Programming. 

You can also tryout NLP queries in this Machine Learning system as we have defined Product Ontology,

  • iPod below $25
  • Mario < $25
  • Mario > $25
  • Mario less than $25
  • iPad greater than $250
  • Car near 01702
  • Toys for boys, Toys for girls
  • Mobile phones for old people
  • “42” LED
  • Low cost Smartphones
  • Cheap Phones
  • New LED
  • Samsung: will return Samsung Smartphone, because in Product Ontology, brand identification for Samsung is Smartphone

iOS Programming using Xcode IDE and Objective C: My take


For people in hurry get the latest code and open this example in Xcode IDE and run the example.

In my 22 yrs, all along I have been either a Microsoft technology programmer or a Java programmer. I always wanted to understand “the dark side” of application development, iOS Programming using Xcode IDE and Objective C. iOS Programming is all about Programming for iPad and iPhone class of devices. This weekend, I had an opportunity to tryout few things,

  • How can you compare Xcode IDE to something like Eclipse or Visual Studio? Are there any build tools like Ant or Maven in this part of the world? Are there any tools for Dependency management similar to Maven repository?
  • How similar or different is Objective C compared to Java or C++

After trying out, my opinion has changed about iOS programming. I really started liking it. As with any tools, there is a learning curve. Once you get past it, it is cool. Xcode IDE is very well integrated with iPhone/iPad simulators.

If you want to start development, as a prerequisite, we need a Mac system and you need to download Xcode. If you want to upload your applications in App Store you need to signup for $99 iOS developer program. This will also get you ton of goodies like Beta tools you can try out.

Xcode: My take

My couple of days experience with Xcode, I started liking it. For a starter, there are few tutorials on youtube from iffytheperfect1983, please try out these and you will quickly get a grasp of Xcode, Objective C, Cocoa, Cocoa Touch. Cocoa framework is used to develop OS X applications and Cocoa Touch is used to develop iPad/iPhone based application. I tried JSon Parsing tutorial, SQLite tutorial and Grand Central Dispatch tutorial and liked all of them. There is also a Basic Calculator tutorial, you will like it. I suggest, open your Xcode and work along these tutorials, you will quickly get a hang of Xcode and Objective C. Xcode also has SenTest a good unit testing framework, I haven’t explored it yet.

Xcodebuild: My take

There is a materials on the web that talks about Xcodebuild and CocoaPod. I tried Xcodebuild, this is similar to ant. They say CocoaPod is a dependency management tool similar to Maven. I haven’t tried it, in my next few blogs I will try and let you know. To run a simple xcodebuild command on a Xcode project you need to type in below command,


xcodebuild clean build CODE_SIGN_IDENTITY="" CODE_SIGNING_REQUIRED=NO

Objective C: My take

This language looks very convoluted at first glance, but if someone knows C, they can pick this up. Reading through the web, it is clear Apple team consciously took decision to go with Objective C. Someone also spoke about Objective C philosophy. Someone compared C++ with Objective C.

Sample JSon Rendering application for iPhone

This is a simple example, where when we click a button, it will get the RSS feed of top 10 albums and bind it to a table view. The JSon structure looks as below,

iOS Programming using Xcode IDE and Objective C: JSon Rendering exercise

JSon structure to be used for iPhone/xcode application

The code sample is as below,


-(void)connectionDidFinishLoading:(NSURLConnection *)connection{

NSDictionary *allDataDictionary = [NSJSONSerialization JSONObjectWithData:webData options:0 error:nil];

NSDictionary *feed = [allDataDictionary objectForKey:@"feed"];

NSArray *arrayOfEntry = [feed objectForKey:@"entry"];

for (NSDictionary *dictionary in arrayOfEntry) {

NSDictionary *title = [dictionary objectForKey:@"title"];

NSString *label = [title objectForKey:@"label"];

[array addObject:label];

}

[[self myTableView]reloadData];

}

- (IBAction)getTop10AlbumButton:(id)sender {

[array removeAllObjects];

NSURL *url = [NSURL URLWithString:@"https://itunes.apple.com/us/rss/topalbums/limit=10/json"];

NSURLRequest * request = [NSURLRequest requestWithURL:url];

connection = [NSURLConnection connectionWithRequest:request delegate:self];

if(connection){
webData = [[NSMutableData alloc]init];
}
}

For more details, import my project into Xcode and run the example and understand the code flow.

I hope this example helped.

Managing Raw SOAP message within Spring Integration – Part 2

In my earlier blog, Managing Raw SOAP message within Spring Integration, I demonstrated how to get the raw SOAP message from int-http:inbound-gateway and process the SOAP message.

There are few scenarios, where in the Spring Integration flow is invoked by an event. Where Spring Integration flow, should get a payload from source Webservice and just transfer it to target Webservice, acting as a Proxy, retaining all the properties of the source and target systems.

In this blog I will demonstrate how you can create a Proxy and how int-ws-outbound-gateway can call the Proxy service when calling Source Webservice. If you notice int-ws-outbound-gateway carefully, we can configure the security keystore and other properties. These properties will be retained, when the payload is passed to the Proxy. Once the request payload is in the Proxy, it can be sent to the source Webservice and once we get the response, we can bind it to another channel, which can be processed further or sent to the target Webservice.

Managing Raw SOAP message within Spring Integration

Managing Raw SOAP message within Spring Integration


<int:channel id="ws.outbound" />

 <int-ws:outbound-gateway id="ws.gateway"
 request-channel="ws.inbound" reply-channel="ws.outbound"
 ignore-empty-responses="true" message-sender="common.message.sender.ws"
 uri="http://localhost:8080/http-proxy-for-ws/receiveGateway" />

 <int-http:inbound-gateway id="http.proxy.gateway"
 request-channel="http.proxy.inbound" name="/receiveGateway"
 supported-methods="POST" />

 <int:channel id="http.proxy.inbound" />

 <int:service-activator input-channel="http.proxy.inbound"
 id="httpProxyServiceActivator" ref="httpProxyServiceActivatorBean"
 method="sendXml" />

 <int:channel id="http.proxy.outbound" />

 <bean id="httpProxyServiceActivatorBean">
 <property name="uri"
 value="http://www.webservicex.net/CurrencyConvertor.asmx" />
 <property name="soapAction" value="http://www.webserviceX.NET/ConversionRate" />
 <property name="wsOutboundChannel" ref="http.proxy.outbound" />
 </bean>

 <int:service-activator input-channel="http.proxy.outbound"
 id="finalProcessorServiceActivator" ref="finalProcessorServiceActivatorBean"
 method="sendXml" />

 <bean id="finalProcessorServiceActivatorBean" />
 

Managing Raw SOAP message within Spring Integration

In Spring Integration if we use int-ws:outbound-gateway, once a message is associated to the request channel, the Spring Integration container add the SOAP header information and sends the SOAP payload to the target system to be processed. Most of the time, this is what is needed, but sometimes, we just need the integration layer to act as a proxy. The SOAP payload coming from the source system is just handed to the target system retaining all the properties of source system like security, enrichment and others.

In this case the trick is instead of using int-ws:outbound-gateway, we should use int-http:inbound-gateway and int-http:outbound-gateway. This way you can fool the target system to accept this as a SOAP message. We can also make it aware what soapAction we need to execute is a below,


<int-http:inbound-gateway id="webservice.inbound.gateway"
request-channel="http.outbound.enrich.in" reply-channel="ws.outbound"
name="/receiveGateway" supported-methods="POST" />

<int:header-enricher input-channel="http.outbound.enrich.in"
output-channel="ws.inbound">
<int:header name="Content-Type" value="text/xml;charset=UTF-8" />
<int:header name="SoapAction"
value="http://www.webserviceX.NET/ConversionRate" />
</int:header-enricher>

<int:channel id="ws.outbound" />

<int-http:outbound-gateway id="webservice.outbound.gateway"
request-channel="ws.inbound" reply-channel="ws.outbound"
url="http://www.webservicex.net/CurrencyConvertor.asmx"
expected-response-type="java.lang.String" />

The Spring Integration flow is as below,

Managing Raw SOAP message within Spring Integration

Managing Raw SOAP message within Spring Integration

I hope this blog helped you.

ScalaTest a MapReduce using Akka

For people in hurry here is the MapReduce with ScalaTest and Akka code and steps

I was trying to learn Scala and I wanted to kill several birds in one shot. Let me tell you, I am not disappointed, I feel comfortable working with Scala. If you are coming from Java world, Scala is comparatively more complex, but once you get past initial hurdle you will like it. I wanted to learn

One usecase I wanted to tryout was a simple Word Count MapReduce, this is a hello world of MapReduce. MapReduce is a function programming technique popularly associated with Hadoop Parallel computing. There is a good MapReduce example using Java and Akka. There is a decent MapReduce example, and an other one here and an another one. Below diagram from the source describe the flow,

Word Count MapReduce with Akka and Java by Munish Gupta

Word Count MapReduce with Akka and Java by Munish Gupta

In this example, I am taking advantage of Akka‘s Actor supports for breaking chunk of tasks and processing in parallel and aggregate the final results.

For a starter, SBT is a build tool similar to Maven, extensively used for Scala development. Refer project/plugins.sbt, this has integration with Eclipse IDE. Once you get the code from github, run the below command, you notice 2 files .project and .classpath got generated.


sbt eclipse

Now import the project in Eclipse as Import => “Existing project into workspace”. Once the project is imported into Eclipse, we can take advantage of IntelliSense and other IDE features and develop the application in a easy way compared to writing the scala code in TextPad.

As always, I will start writing a test, the lowest level test is the aggregation test, which takes a map of words and the number of times it has occurred and aggregates it. I used WordSpec for this ScalaTest as below,

"Aggregrate actor" must {
"send back Map message" in {
// create the aggregate Actor
val aggregateActor = system.actorOf(Props[AggregateActor]);
var map: Map[String, Int] = Map[String, Int]("ak" -> 1, "kp" -> 2)
aggregateActor ! map
var map1: Map[String, Int] = Map[String, Int]("ak" -> 1, "kp" -> 2)
aggregateActor ! map1
Thread.sleep(1000)
var output = Map("kp" -> 4, "ak" -> 2)
aggregateActor ! "DISPLAY_LIST"
expectMsg(output)
}
}

Now I write a Reduce unit test, which takes a Result object and create a Map object and publish it to Aggregator object for future aggregation.

"Reduce actor" must {
"send back Map message" in {
// create the aggregate Actor
val aggregateActor = system.actorOf(Props[AggregateActor]);
// create the list of reduce Actors
val reduceRouter = system.actorOf(Props(new ReduceActor(aggregateActor)))
val list: List[Result] = List[Result](new Result("kp", 1), new Result("ak", 2))
reduceRouter ! list
val list1: List[Result] = List[Result](new Result("ak", 1), new Result("kp", 2))
reduceRouter ! list1
Thread.sleep(1000)
var output = Map("kp" -> 3, "ak" -> 3)
aggregateActor ! "DISPLAY_LIST"
expectMsg(output)
}
}

Write a Map unit test to take a line and create a Result object. If you notice carefully, the map and reduce object implements Akka’s Roundrobin Routers where the line is processed by multiple threads in a roundrobbin way.

"Map actor" must {
"send back Map message" in {
// create the aggregate Actor
val aggregateActor = system.actorOf(Props[AggregateActor]);
// create the list of reduce Actors
val reduceRouter = system.actorOf(Props(new ReduceActor(aggregateActor)).withRouter(RoundRobinRouter(nrOfInstances = 2)))
// create the list of map Actors
val mapRouter = system.actorOf(Props(new MapActor(reduceRouter)).withRouter(RoundRobinRouter(nrOfInstances = 2)))
var line = "Aditya Krishna Kartik Manjula"
mapRouter ! line
Thread.sleep(1000)
var output = Map("Kartik" -> 1, "Krishna" -> 1, "Aditya" -> 1, "Manjula" -> 1)
aggregateActor ! "DISPLAY_LIST"
expectMsg(output)
}
}

We write a listController which tests end to end integrating map/reduce/aggregator and assert the values,

"List Reader Controller actor" must {
"send back Map message" in {
// create the aggregate Actor
 val aggregateActor = system.actorOf(Props[AggregateActor]);
// create the list of reduce Actors
 val reduceRouter = system.actorOf(Props(new ReduceActor(aggregateActor)).withRouter(RoundRobinRouter(nrOfInstances = 2)))
// create the list of map Actors
 val mapRouter = system.actorOf(Props(new MapActor(reduceRouter)).withRouter(RoundRobinRouter(nrOfInstances = 2)))
val controller = system.actorOf(Props(new ControllerActor(aggregateActor, mapRouter)))
val lineReadActor = system.actorOf(Props[LineReadActor])
var list = List[String]("Aditya Krishna Kartik Manjula", "Manjula Anand Aditya Kartik", "Anand Vani Phani Aditya", "Kartik Krishna Manjula Aditya", "Vani Phani Anand Manjula")
lineReadActor.tell(list, controller)
Thread.sleep(1000)
var output = Map("Anand" -> 3, "Kartik" -> 3, "EOF" -> 1, "Krishna" -> 2, "Vani" -> 2, "Phani" -> 2, "Aditya" -> 4, "Manjula" -> 4)
 aggregateActor ! "DISPLAY_LIST"
 expectMsg(output)
 }
 }

Finally we will write a fileReaderActor and pass a large file to it to do MapReduce.

Now if you see the actual code, refer MapActor.scala, there is a keyword called yield. yield helps you to create another datatype from one collection. The syntax is as below,

def evaluateExpression(line: String): List[Result] = {
var result = for (word <- line split (" ") toList; if !STOP_WORDS.contains(word.toLowerCase))
yield (new Result(word, 1))
return result
}

Refer ReduceActor.scala you will find the code as “result =>” called as Lambda expression. Lambda expressions are fundamental to functional programming language like Scala,

def reduce(list: List[Result]): Map[String, Int] = {
var results: Map[String, Int] = new HashMap[String, Int]

list.foreach(result => {
if (results.contains(result.word)) {
results(result.word) += result.noOfInstances
} else {
results(result.word) = result.noOfInstances
}
})
return results;
}

Conclusion

If you notice, in this example, I have used and learnt,

  • Scala programming aspects like, Collection, keyword yield, lambda expressions
  • Akka‘s Roundrobin Routers for threading and concurrency
  • SBT for integration with Eclipse
  • ScalaTest for TDD

I hope this blog helped.

Play 2.0: Building Web Application using Scala

For people in hurry, here is the code and some steps to run few demo samples.

Disclaimer: I am still learning Scala and Play 2.0, please point to me if something is incorrect.

Few years back I had tried Scala and it was difficult for me to learn it with the lack of good IDE and an integrated stack for building any application primarily Web Application. After the advent of Play 2.0, Scala IDE for eclipse and Play 2.0 integration with Eclipse things have improved. Lift is also another framework to do Scala Web Application development

If you see the net you will see quite a few articles comparing Java with Scala like, From Scala back to Java and Scala or Java? Exploring myths and facts, There are also articles comparing Scala to other languages Ruby like, Scala, is it comparable to Ruby?. Primarily the debate is about if Scala is ready for Enterprise development.

In this blog I will call an external REST call using Akka Actor and display results using Scala. While building this sample application, I will consider few factors and how Play 2.0 and other tools help in this.

Scala IDE support

Refer the blog Setup and use Play framework 2.0 in Scala IDE 2.0. It has a good writeup on how we create a Scala project in Play 2.0, how we Eclipsify, how we import a project in Eclipse and start development. The IDE has a good intellisense support. When I run the application in STS IDE, I had to add target/scala-2.9.1/src_managed/main in the build path.

Database access support

Refer the blog Tutorial: Play Framework 2 with Scala, Anorm, JSON, CoffeeScript, jQuery & Heroku. This has a good writeup on how we write a simple Database CRUD based application in Scala. It also demonstrates how we can return JSON object to the browser. Play 2.0 is bundled with Anorm a lightweight Object mapper. This is not a ORM tool, this is just a simple data retriever and object mapper. If you see the application I demonstrated the usage. Refer the .scala class models.Bar for more details. Below is a simple code snippet of this,

def findAll(): Seq[Bar] = {
DB.withConnection { implicit connection =>
SQL("select * from bar").as(Bar.simple *)
}
}

Akka/Actor: taking advantage of asynchronous model

As mentioned in my earlier blog, Harnessing New Java Web Development stack: Play 2.0, Akka, Comet, Play 2.0 uses Netty an asynchronous event-driven network application framework for high performance Web Application. In the below snipped, I will demonstrate how we retrieve a remote webservice payload in a non blocking. I have not benchmarked this yet.

def listProducts() = Action {
val system = ActorSystem("MySystem")
val myActor = system.actorOf(Props[ProductJsonActor], name = "myactor")

Async {
implicit  val timeout= Timeout(20.seconds)

(myActor ? "hello").mapTo[String].asPromise.map {
response => Ok(response).as("application/json")
}
}
}

def receive = {
case _ => {
val response = WS.url("https://www.googleapis.com/shopping/search/v1/public/products").get()
val body = response.await(5000).get.body
log.debug("body****" + body)
sender ! body
}
}

Language capabilities: OOP vs Functional Programming

There are good blogs comparing Functional Programming and OOP Language like Java. The concept of Functional Programming is not that easy to understand in the beginning, but once we get used to it, we can write good compact code.

Conclusion

Language capability wise Scala has good support. Java 8 has lot of features which are similar to Scala and if you get into Scala bandwagon you will not be left out to take advantage of the new capabilities of Java. Here is a good comparison of Java 8 vs Scala. With Play 2.0 I clearly demonstrated how to build a decent Web application. Hope this blog helped you.