Wednesday, January 19, 2011

Hexican.com

I just started my own blog here. I just appreciate Google's hosting for blogger. Follow my posts in hexican.com.
Amir.

Saturday, January 8, 2011

Setters and Getters

Every Java or C# developer knows how getter/setter methodes make the code messy and noisy because you have to define them explicitly in those languages. I just like the idea of using annotations to reduce amount of the code that should be written. Objective C has defined an annotation to define getter/setter methods implicitly. See below example:


@interface SimpleCar : NSObject {
NSString* make;
NSString* model;
NSNumber* vin;
}

@property(readwrite, retain) NSString* make;
@property(readwrite, retain) NSString* model;
@property(readwrite, retain) NSNumber* vin;

@end


The implementation:

#import "SimpleCar.h"

@implementation SimpleCar
@synthesize make, model, vin;
@end

There is no sign of setter/getter methods however, they actually will be accessible during runtime. This is the most clear implementation that I've ever seen. Interface is more declarative.

Friday, January 7, 2011

It is not a big deal to start a smaller one.

There are two kinds of software project I think. The one is large scale projects that consume a lot of time/resources and you cant always estimate if it gets done successfully or not. The other one is small size project which you can accomplish them by yourself. Some kinds of small software widgets and iPhone or Android applications are in this category.
The atmosphere of these two kinds of projects are pretty different. An enterprise project needs long time frequently meetings and professionals while each one is just responsible for some parts of the project and not more. It also needs expensive servers and environmental tools, configuration management and administration. These projects run just by millions. Their failover also is a catastrophe. I remember the time that I was involved into developing, deploying and testing an enterprise Java based core banking solution which was run over IBM technologies. It was the worst nightmare that I've ever seen. Each step was just going more into the mud and sludge.
However, a small size project needs one or two developer who know perfectly the whole project. They need just a brilliant idea and one or two notebooks and nothing more. They gain wonderful experience in each step. Aslo it is not a big deal at all if the project fails. There is just an attempting to build a cash cow.
After some years of playing with harmful enterprise toys I just need to get rest by developing small mac applications. So I've started to learn Objective C, iOS and Mac OS concepts and technologies. They are really simple solutions to sweet success.

Wednesday, January 5, 2011

They've cared about details.

MacBook Pro isn't just beautiful. It has a perfect design and material. When you use it you find soon some intelligent behaviors and perfect arrangement of the things and functionalities that made it a brilliant. For example you never hit caps lock key wrongly when you are typing quickly. Caps lock has a delay to response that let you keep typing so fast without caring about hitting caps lock instead of tab button. They have cared about details. Watch this video and enjoy how they make things.

Wednesday, December 29, 2010

Sending SOAP messages through HTTPS using SAAJ

Introduction
A month ago a task assigned to me. It was calling the API of a network management device by sending SOAP messages through HTTPS. It wasn't so easy and straight forward to me.

SAAJ
I've used SAAJ for calling web services. It is well known for Java developers.

Steps
The process contains below steps:
1. Export the HTTPS Certificate into a file
2. Import the HTTPS Certificate into Java HTTPS certificates
3. Creating a SOAP connection
4. Creating a SOAP message
5. Populating the message
6. Trust to HTTPS certificates
7. Sending the message
8. Retrieving the reply

Get the Certificate
Assume WSDL address is:
https://192.168.10.1:8991/wsdl/balance.wsdl

Read this to find out how to get the certificate for access to the upper WSDL address.
Here I saved the certificate in "amirssw.cer" file.
Java HTTPS certificates stored in
$JAVA_HOME/jre/lib/security/cacerts

To import your new certificate into "cacerts" run below command:
sudo keytool -import -file amirssw.cer -keystore cacerts

The password is "changeit".

SOAP message
In my sample SOAP message stored in a file: "/home/amir/projects/mine/p8/message/helloWorld.msg".
You can find a sample SOAP message here.

Java Code
This is a simple code that shows clearly how to send a SOAP message through HTTPS. The only different between sending the message on HTTP over HTTPS is the URL and doTrustToCertificates() method call just before sending the message.


package com.neverhood.webssl;

import javax.net.ssl.*;
import javax.xml.soap.*;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.FileInputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.SecureRandom;
import java.security.Security;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Iterator;
import java.util.Vector;

public class Client {

public static void main(String[] args) {
talk("https://192.168.10.1:8991/balance/soap", "/home/amir/projects/mine/p8/message/helloWorld.msg");
}

private static void talk(String urlval, String msgPath) {
try {
// Create message
MessageFactory mf = MessageFactory.newInstance();
SOAPMessage msg = mf.createMessage();

// Object for message parts
SOAPPart sp = msg.getSOAPPart();
StreamSource prepMsg = new StreamSource(new FileInputStream(msgPath));
sp.setContent(prepMsg);

// Save message
msg.saveChanges();

// View input
System.out.println("\n Soap request:\n");
msg.writeTo(System.out);
System.out.println();

// Trust to certificates
doTrustToCertificates();

//SOAPMessage rp = conn.call(msg, urlval);
SOAPMessage rp = sendMessage(msg, urlval);

// View the output
System.out.println("\nXML response\n");

// Create transformer
TransformerFactory tff = TransformerFactory.newInstance();
Transformer tf = tff.newTransformer();

// Get reply content
Source sc = rp.getSOAPPart().getContent();

// Set output transformation
StreamResult result = new StreamResult(System.out);
tf.transform(sc, result);
System.out.println();

// now GET the Response and PARSE IT !
Vector list = new Vector();
SOAPBody soapBody = rp.getSOAPBody();
Iterator iterator1 = soapBody.getChildElements();
while (iterator1.hasNext()) {
SOAPBodyElement ThisBodyElement = (SOAPBodyElement) iterator1.next();
Iterator it2 = ThisBodyElement.getChildElements();
while (it2.hasNext()) {
SOAPElement child2 = (SOAPElement) it2.next();
Iterator it3 = child2.getChildElements();
while (it3.hasNext()) {
SOAPElement child3 = (SOAPElement) it3.next();
String value = child3.getValue();
list.addElement(value);
}
}
}
for (int i = 0; i < list.size(); i++) {
System.out.println(list.elementAt(i));
}
}
catch (Exception e) {
System.out.println(e.getMessage());
}

}

static public SOAPMessage sendMessage(SOAPMessage message, String endPoint) throws MalformedURLException, SOAPException {
SOAPMessage result = null;
if (endPoint != null && message != null) {
URL url = new URL(endPoint);
SOAPConnectionFactory scf = SOAPConnectionFactory.newInstance();
SOAPConnection connection = null;
long time = System.currentTimeMillis();
try {
connection = scf.createConnection(); //point-to-point connection
result = connection.call(message, url);
} finally {
if (connection != null) {
try {
connection.close();
} catch (SOAPException soape) {
System.out.print("Can't close SOAPConnection:" + soape);
}
}
}
}
return result;
}

static public void doTrustToCertificates() throws Exception {
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}

public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException {
return;
}

public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException {
return;
}
}
};

SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String urlHostName, SSLSession session) {
if (!urlHostName.equalsIgnoreCase(session.getPeerHost())) {
System.out.println("Warning: URL host '" + urlHostName + "' is different to SSLSession host '" + session.getPeerHost() + "'.");
}
return true;
}
};
HttpsURLConnection.setDefaultHostnameVerifier(hv);
}
}


Done.

Saturday, September 25, 2010

Port Forwarding, The way I use SSH

"Secure Shell or SSH is a network protocol that allows data to be exchanged using a secure channel between two networked devices." Wikipedia.
That is just an abstract definition. I use SSH to do much more. Here are just some simple commands that I used to run for such a different reasons:

Whenever I need to pass stupid filtering of stupid government

ssh -D 8888 root@100.101.102.103

"100.101.102.103" is just the host that you want to connect it. I assumed that 100.101.102.103 is a SSH enabled machine.
This command simply forwards the remote machine's HTTP port to my local machine. So I just need to use a socks4 proxy like this : 127.0.0.1:8888.
So whatever you do using your browser will forward to the remote machine. The channel between your local machine and the remote one is pretty secured. However, the remote machine should be trusted.


Whenever I need to connect a remote MS-SQLServer on a windows machine using my Linux machine
Assume a service such as SQLServer which runs on a machine that is hosted in a remote LAN with [192.168.0.100] IP address. Assume you just can connect to another machine that is hosted in the same LAN using:
ssh root@100.101.102.103

Assume again the MS-SQLServer uses the port number 1433.
I need to connect to the ssh server machine using ssh root@100.101.102.103 moreover I need to forward 192.168.0.100:1433 to my local machine. This is the simple solution:
ssh -L 1433:192.168.0.100:1433 root@100.101.102.103 -N

The pattern is "ssh -L myPort:host:hostPort". -N is useful for just forwarding ports and nothing else.

The connections could be same as below map:


my machine ssh server MS-SQLServer
127.0.0.1 <===> 100.101.102.103 <===> 192.168.0.100

Note:
-Install OpenSSH if you need to provide SSH over Windows servers.
-To access ports under 1024 you should have root privilege.

Saturday, September 18, 2010

MuleSoft's Tcat, an Enterprise view to the Tomcat

Apache Tomcat is the most convenient and reliable tool that I've ever seen. Here are Tomcat's power points that I've founded during my experiences:

-Tomcat works cross platforms. Just by copying from a machine to another one it serves applications. For example from a Linux to a Windows just a copy is enough.

-Tomcat is fast to deploy and easy to use. In most cases you just need to copy the WAR and forget about later configurations.

-Tomcat doesn't need as much resources as others.

While Tomcat doesn't claim to provide hosting services for the enterprise level of business we developers used to overused it.
It is long time that market is expecting such as plugin or solution that give Tomcat the capabilities which developer and administrators need.

Now MuleSoft made it. I just downloaded and try TCat server of Mulesoft. The amasing thing is that it remained a Tomcat. The major different is that they developed and deployed an application that is hosted within the TCat. It called "Console". TCat's console gives some missed features such as "Profile". I used to have different Tomcats on my machine depends on the projects. I work on Tele-communication and monitoring solutions using SNMP, TR-069 and JMX. In In another team I just develop web-based business applications. So I have to separate Tomcats regarding to different natures of companies and purposes. Now TCat profiles solved this problem. Also TCat has provided a repository that helps you to keep and manage your WARs. TCat has an embedded JRE! Also it is possible to use your pre-installed JRE. Anyway this gives TCat more enterprise shape!
I prefer to use an enterprise Apache Tomcat rather an IBM Webspher. :)

Monday, September 13, 2010

When Tomcat looks different cross Linux flavors

Some days ago at the time I was working on different Linux flavors to setup a uniform solution, I have notified that there are many differences in Tomcat installed files and configuration even when you have same Tomcat version. The mission was setting up a centralized monitoring system that makes user enable to track what is happening within Tomcat and its applications on different Linux machines such as CentOS, FreeBSD and Ubuntu. I was developed the solution in my notebook that uses Ubuntu 9.04, Sun Java 1.6 and Tomcat 6.0. Also I qualified the solution on an Ubuntu server edition. The tests passed perfectly so I tried to migrate it to FreeBSD and CentOS. The system administrator was worry about any major modification on his servers configuration that both were pretty busy. On both FreeBSD and CentOS I had different OS, Java and Tomcat. FreeBSD 7.2 had its own Java runtime and JDK that called Diablo. It used a Tomcat version 5.5. The CentOs machine had an OpenJDK Java edition. Also It uses Tomcat 5.5.
Differences between Sun JDK, OpenJDK and Diablo didn't make any trouble in using JMX. The biggest incompatibility was different installations of the same version of Tomcat that was installed in different ways by CentOS and FreeBSD package managers!
The administrators has been installed a same version of Tomcat using package managers. It seems each package manager installs a customized version of Tomcat that is more respects to the OS concerns rather than development. In CentOS I didn't find "catalina.sh" that is a well known startup routine.
Any way JMX listener didn't work and I guessed that could be caused by different Java editions. Fortunately the administrator rejected my suggestion for using Sun Java on both machine. So I tried other ways.
In latest try I just copied my Tomcat to FreeBSD and CentOS both and it worked like a charm!
Different flavors use their own package managers that install just customized versions of the packages. While any Java developer needs to produce more compatible solutions that are more usable with minor differences cross platforms. Compatibility and scalability are the most advantages of Java over other solutions. This is why we use Java. Every Java developer prefer to keep compatibility over customization.
As a suggestion just use a more secured copy of your own Tomcat over all target servers rather than muted and morphed versions that installed by package managers.
Here is a step by step tutorial of what I have done....

Saturday, July 3, 2010

"In Iran a large scale software project implementation is just like somehow to completing a puzzle that you don't have all pieces. The map is out of date. Moreover you have to use some pieces of other different puzzles to cover some areas of your puzzle with them. Some how there are missing pieces that you have to develop them. Finely you have to integrate them all."
I've just posted an article about Software Development in Iran.

Saturday, June 12, 2010

Object Orientation in Javascript

This could wired for whom used to program using Javascript that they can create objects. I didn't know till some while ago. Here is an example.

Saturday, June 5, 2010

An Opportunity for Investment

I just wrote an article for datispars.com. "How to be a successful investor in software development field" is an article that talks about software development opportunities such as outsourcing. The article tries to explain easy ways of develop better applications using better approaches, regardless of business restrictions and technologies.

Saturday, May 8, 2010

Using A More Specific Programming Language

Whichever programming language you are using in a software application development for, be sure to choose the proper language that exactly fits requirements. This needs to be familiar a bit more with some other technologies and programming languages such as domain specific languages.
Migrating from a multi purpose programming language such as Java to a domain specific programming language such as Groovy and Grails is just like choosing a more specific wrench rather than a general purpose. A handy man who knows just hammer then will recognize every problem as a nail. The same as this story may occur in software development projects too. The developer which uses only Java or .Net as a general purpose technology may loose a lot of resources to make an adoption between the solution and the problem rather than the one who uses a domain specific programming language such as Scala and Groovy.
I think being familiar with other tools, frameworks and technologies give us the opportunity to choose the better solution in many situations. In the case I experienced learning curve of being familiar with Groovy and Grails was pretty shorter than starting a Java project even based on basic configuration that I have provided before. The concept of “convention over configuration” boosts software projects. You don't need to build everything from scratch. The framework prepares a customized and standard basic configuration that is pretty well formed. A Groovy domain class itself describes the business more clearly and more abstracted rather than Java POJOs. Moreover built in naming convention that respected by Grails makes a terminology between developers.
All together the developers that uses DSLs are able to develop relevantly with a smaller knowledge base and terminology. In addition learning of Groovy and Grails is based on samples that called “Learning by Example” and Learning by example is a smooth way that we learned it when we were child.

Friday, April 23, 2010

Using Clear Source Java Codes In A Groovy/Grails Application

Groovy/Grails boosts the development process in many ways. The convention over configuration approach helps the developer to develop as fast as possible. Groovy and Grails talk in a much higher level language over than Java.

Something just like the creation of Java it self, is happening again. Software market place needs to talking in a more higher level languages rather than Java I think. Business on demand pressures the market to create and use more productive tools and technologies.

However, I as a developer need to write some parts of the applications using a little bit lower level language in many situations. Moreover, the huge amounts of developed and ready to use Java libraries such as source codes, jar files, and open source solutions warn me to prevent of reinventing the wheel. So, I align my approach with using the Groovy and Grails and Java classes in source code together just to boost the development and walk with bigger steps; Furthermore, I keep using of Java libraries whenever I need.

There are many situations that you need to use Java in a Grails application. This is more than using just JVM and importing jar libraries. I mean I prefer to user clear Java source code in the Grails application to have respect for the scripting concept of Groovy even in Java classes.

Here we will use a particular Java source code in a Grails application.
Assume below particular Java class:

package com.amir.util;

class HelloWorld {

public static String getMessage() {
return "Hello World!";
}

public static String getMessageFor(String str) {
return "Hello "+ str +"!";
}
}

I am going to use HelloWorld.java instead of HelloWorld.class. Then I will be able to modify it whenever I need and Grails will compile during each "grails run-app".

To create HelloWorld Grails application you first need to give the grails a create-app command:

$> grails create-app helloworld

This will create a new directory inside the current one that contains the project. You should now navigate to this directory in terminal:

$> cd helloworld/src/java

Now you need to create the packging folders:

$> mkdir com
$> mkdir com/amir
$> mkdir com/amir/util

The Java class should be find in this path:

helloworld/src/java/com/amir/util/HelloWorld.java

Now come back to the helloworld folder which is the root folder of the application and create a hello controller:

$> grails create-controller hello

This will create a new controller in the grails-app/controllers directory called HelloController.groovy. You need to modify it to call the Java HelloWorld class.

$> gedit grails-app/controllers/HelloController.groovy

And make it as below:

class HelloController {
def world = {
render HelloWorld.getMessage() + " , "
render HelloWorld.getMessageFor(" Amir ")
}
}

Now start-up the container with run-app command:

$> grails run-app

This will start-up a server on port 8080 and you should now be able to access your application with the URL: http://localhost:8080/helloworld

Job done! You used a clear source Java class instead of the compiled one in a Grails application. Everything is just scripted!

Monday, April 19, 2010

Building A Blog Using 7 Simple Steps In Grails

Building a regular web application using Grails should be the minimalistic activity that any Java developer may involved in. Just follow below 7 steps to develop your first Grails blog.

1. To create an application using Grails we should run a "grails create-app applicationName" command:

$> grails create-app com.datispars.blog

2. Change directory to the currently built directory of the application:

$> cd com.datispars.blog

3. At this point we create domain classes. Domain classes will consist the logic part of MVC model:

$> grails create-domain-class com.datispars.blog.Content
$> grails create-domain-class com.datispars.blog.Comment
$> grails create-domain-class com.datispars.blog.Author

4. To put some business policy into the model area we should modify domain classes

$> gedit grails-app/domain/com/datispars/blog/Content.groovy

You should modify Content class as below:

package com.datispars.blog

class Content {
String title
String body
Category category
Author author
static hasMany=[comments:Comment]
static constraints = {
title(blank:false, nullable: false, size:3..80)
body(blank:false, nullable:false,size:3..500)
author(nullable:false)
}
}
.....

$> gedit grails-app/domain/com/datispars/blog/Author.groovy

package com.datispars.blog

class Author {
String name
String email
String webpage
static constraints = {
name (blank:false, nullable:false, size:3..30,
matches:"[a-zA-Z1-9_]+")
email (email:true)
webpage (url:true)
}

String toString(){
return name;
}
}
....

$> gedit grails-app/domain/com/datispars/blog/Comment.groovy

package com.datispars.blog

class Comment {
static belongsTo=[content:Content]
Author author;
String comment
static constraints = {
comment (blank:false, nullable: false, size:5..200)
author (nullable: true) // Comments are allowed without a author
}

String toString(){
if (comment.size()>20){
return comment.substring(0,12);
} else
return comment;
}
}

5. To create the Controller part of MVC based on the domain classes you should run below commands:

$> grails generate-controller com.datispars.blog.Content
$> grails generate-controller com.datispars.blog.Author
$> grails generate-controller com.datispars.blog.Comment

6. Now you need to modify three controller that you have built to use Scaffold functionality of Grails:

$> gedit grails-app/controllers/com/datispars/
blog/ContentController.groovy

Scaffolding allows you to auto-generate a whole application for a given domain class. The simplest way to get started with scaffolding is to enable scaffolding via the "scaffold" property. So add the commented line (def scaffold = true) in the start part of the ContentController.groovy class:

package com.datispars.blog

class ContentController {

def scaffold = true // The only modification
// in the controller you should do...

static allowedMethods = [save: "POST", update: "POST",
delete: "POST"]

def index = {
redirect(action: "list", params: params)
}
....


Do just the same operatoion for AuthorController.groovy and CommentController.groovy (Same as 12 step) .

7. Run the application:

$> grails run-app

After running the server you should see below response in the terminal:

Server running. Browse to http://localhost:8080/com.datispars.blog

So, you browse http://localhost:8080/com.datispars.blog

Grails Over Rails

After a few research around rapid application development tools and frameworks, I started to try Groovy and Grails. This just happened after a couple of weeks using of Ruby on Rails. Ruby on Rails has excited me when I knew Groovy and Grails. I have had some difficulties with Ruby on Rails at initiating days that I didn't touch them again during using of Groovy and Grails.

At first I needed to install Grails. This was as much easy as you imagine. Later, I have explained how I installed Ruby on Rails on Ubuntu Linux in the previous article in current web log that shows rails installation needs some struggles to the end of deployment. But, Grails installation is just like a piece of cake in my experience. There is a binary version that is available as a zipped file that just needs to download and extract it. Then you should set two environmental variable. I am using Grails on Ubuntu Linux. So I had to fix a stupid bug at first try. In fact, Groovy and Grails are more indicated for Java developers because they can leverage their knowledge on Java platform and they can also turn to Java whenever they feel so, since Groovy runs on top of JVM. After all you have Spring and Hibernate ready available. Grails is very easy to get started with for Java developers. Also, You'll be able to continue using the same libraries that you used to (among many other things). The wide and enriched Java libraries are mostly accessible to your Grails application. All the code you developed and bug fixed routines are reusable in the Groovy applications. So you wont repeat all you have done.

I think Grails follows Rails track but in a more organized way. The main different is Java compatibility of Grails I think. If you try to deploy a Rails application on a JEE application server you will find that there is not a straight forward procedure at all. I found that setting up the environment to develop Rails application needs gathering some very dependent components that you have to arrange them just like a puzzle and I don't know why they did not put them all in the same package!. In the opposite, Grails gives the same functionality by a more consistent and integrated solution. For making a war of the Grails application that you developed, this is enough to give it a "grails war" in the root folder of the application.

Furthermore I found Groovy scripts meaningful and more conceptual. This may be just because the background I had from Java. I know Ruby is so abstracted and sharp but I used to explain exactly what I need, even by using a bit more symbols and reserve words. I cant feel the Japanese culture of Ruby short hands!

Here is a piece of Groovy code:

class User {
String name
String email
String webpage
static constraints = {
name (blank:false, nullable:false, size:3..30, matches:"[a-zA-Z1-9_]+")
email (email:true)
webpage (url:true)
}

String toString(){
return name;
}
}

I have never seen any implementation of the validation routines as much simplified as Groovy codes. The "constraints" block has described validation rules clearly. Email and webpage validations are brilliant:

email (email:true)
webpage (url:true)

I think Grails accelerates the outlet of the development process for the everyone who needs to build Java compatible web applications using new generation of RAD tools and scripts.

During working with Grail I've used this article from Lars Vogel. This could be an easy tutorial that shows how Grails works.