How to Manipulate Data of MySQL Tables on Mac OS X

Published on February 27, 2011 by Amir Sedighi

I was looking for a tutorial to fetch data from MySQL on Mac OS X or Linux flavors. This helped me. I just modified it a bit. After saving the following code as myclient.c:

/*
 See url for more info:

http://www.cyberciti.biz/tips/linux-unix-connect-mysql-c-api-program.html

 */
#include
#include 

#define Q1 "insert into test (a , b) values (? , ?)"

int main(void) {
	MYSQL *conn;
	MYSQL_RES *res;
	MYSQL_ROW row;
	/* Change me */
	char *server = "localhost";
	char *user = "root";
	char *password = "";
	char *database = "SALESMANAGER";
	int i=0;
	conn = mysql_init(NULL);

	/* Connect to database */
	if (!mysql_real_connect(conn, server,
							user, password, database, 0, NULL, 0)) {
		fprintf(stderr, "%s\n", mysql_error(conn));
		exit(1);
	}

	/* send SQL query */
	if (mysql_query(conn, "select * from countries")) {
		fprintf(stderr, "%s\n", mysql_error(conn));
		exit(1);
	}

	res = mysql_use_result(conn);

	/* output table name */
	printf("Result:\n");
	while ((row = mysql_fetch_row(res)) != NULL){
		for(i=0;i<mysql_num_fields(res);i++){
			printf("%s \t", row[i]);
		}
		printf("\n");
	}

	/*  INSERTING USING PREPARED STATEMENT */

	MYSQL_STMT *s1;
	MYSQL_BIND b1[2];
	long testint1=0;
	long testint2=0;
	int ii;

	s1=mysql_stmt_init(conn);
	if (!s1)
	{
		fprintf(stderr, " mysql_stmt_init(), out of memory\n");
		exit(-1);
	}

	memset(b1, 0, sizeof(b1));
	b1[0].buffer_type=MYSQL_TYPE_LONG;
	b1[0].buffer=(void *) &testint1;

	b1[1].buffer_type=MYSQL_TYPE_LONG;
	b1[1].buffer=(void *) &testint2;

	if (mysql_stmt_prepare(s1, Q1, strlen(Q1)))
	{
		fprintf(stderr, " mysql_stmt_prepare(), 1 INSERT failed\n");
		fprintf(stderr, " %s\n", mysql_stmt_error(s1));
		exit(0);
	}
	if (mysql_stmt_bind_param(s1, b1))
	{
		fprintf(stderr, " mysql_stmt_bind_param() failed\n");
		fprintf(stderr, " %s\n", mysql_stmt_error(s1));
		exit(0);
	}

	for (ii=0;ii<20;ii++)
	{
		testint1=ii;
		testint2=ii*2;
		if (mysql_stmt_execute(s1))
		{
			fprintf(stderr, " mysql_stmt_execute(), 1 failed\n");
			fprintf(stderr, " %s\n", mysql_stmt_error(s1));
			exit(0);
		}
	}

	/* close connection */
	mysql_free_result(res);
	mysql_close(conn);

	return 0;
}

Just run the following command in terminal to build myclientRunable which is excuteable:

gcc -o myclientRunable $(mysql_config --cflags) myclient.c $(mysql_config --libs)

Posted in Cocoa/Objective-C, Linux

Does Google Chrome Have Got A Potentiel Security Weakness?

Published on January 30, 2011 by Amir Sedighi

I personally love Google’s products. Every developer has a respect for Google creativities even the ones who work for Bill Gates or Steve Jobs. This is just a warning about the weakness of a new facility of Google Chrome. Users almost trust the famous products such as Google Chrome and Mozilla Firefox. I mean we didn’t much care about security concerns and security holes at the time we use a good product from IT giants companies. This itself may be the thing we should care about.
I’ve just noticed that Google Chrome let users change the tab pages when a pop-up is waiting to get a user information to grab and insert it to the page which has raised it. I am not sure if it is really a security hole or not. So I posted it on my unofficial blog hexican.com.

Posted in JavaScript

Simplest Captcha in Java

Published on January 22, 2011 by Amir Sedighi

This is a simple captcha image renderer. I just modified this sample and make it a bit hard to recognize for software robots. I hope it remains still readable to the human. Just add it as a simple servlet and enjoy it.

package datis.general.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.GradientPaint;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.*;

import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.*;
import javax.servlet.http.*;

public class CaptchaServlet extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        int width = 300;
        int height = 60;
        int fontSize = 26;
        int xGap = 30 ;
        int yGap = 25 ;
        String fontName = "Arial" ;
        Color gradiantStartColor = new Color(60, 60, 60); // dark grey
        Color gradiantEndColor = new Color(140, 140, 140); // light grey
        Color textColor =  new Color(255, 153, 0); // orange

        String[] newData = {"hiworld", "orlando", "global", "publish", "looky"}; // you add more words or read them from db or something...

        BufferedImage bufferedImage = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB);

        Graphics2D g2d = bufferedImage.createGraphics();

        RenderingHints rh = new RenderingHints(
                RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);

        rh.put(RenderingHints.KEY_RENDERING,
                RenderingHints.VALUE_RENDER_QUALITY);

        g2d.setRenderingHints(rh);

        GradientPaint gp = new GradientPaint(0, 0, gradiantStartColor , 0, height / 2, gradiantEndColor, true);

        g2d.setPaint(gp);
        g2d.fillRect(0, 0, width, height);

        Random r = new Random();

        for (int i = 0; i < width - 10; i = i + 25) {
            int q = Math.abs(r.nextInt()) % width;
            int colorIndex = Math.abs(r.nextInt()) % 200;
            g2d.setColor(new Color(colorIndex, colorIndex, colorIndex));
            g2d.drawLine(i, q, width, height);
            g2d.drawLine(q, i, i, height);
        }

        g2d.setColor(textColor);

        int index = Math.abs(r.nextInt()) % newData.length;

        String captcha = newData[index];
        request.getSession().setAttribute("captcha", captcha);

        int x = 0;
        int y = 0;

        for (int i = 0; i < newData[index].length(); i++) {
            Font font = new Font(fontName , Font.BOLD, fontSize);
            g2d.setFont(font);
            x += xGap + (Math.abs(r.nextInt()) % 15);
            y = yGap + Math.abs(r.nextInt()) % 20;

            g2d.drawChars(newData[index].toCharArray(), i, 1, x, y);
        }

        for (int i = 0; i < width - 10; i = i + 25) {
            int p = Math.abs(r.nextInt()) % width;
            int q = Math.abs(r.nextInt()) % width;
            int colorIndex = Math.abs(r.nextInt()) % 200;
            g2d.setColor(new Color(colorIndex, colorIndex, colorIndex));
            g2d.drawLine(p, 0, i + p, q);
            g2d.drawLine(p, 0, i + 25, height);
        }

        g2d.dispose();

        response.setContentType("image/png");
        OutputStream os = response.getOutputStream();
        ImageIO.write(bufferedImage, "png", os);
        os.close();
    }

    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }
}

Posted in Java

Diving into Objective-C

Published on January 15, 2011 by Amir Sedighi

Introduction
After many years of development I just wondered at the time I got familiar with Objective C. I’ve had long experience with Java, Delphi and C#. Also I was familiar with modern DSLs such as Groovy. However, Objective C looks pretty different when you start to learn it. After two weeks of challenges I just abstracted this article that consists a fast booting steps for everyone who just starts to learn Objective C.

Develop Interface First
In java developing an interface is recommended but it is not a necessary step to develop a class. However in Objective C you always have to start with the interface.
Interface file has a “.h” extension such as Contact.h that you can see it’s content below:

@interface Contact : NSObject {
	NSString *name;
	NSNumber *age;
}

@property(readwrite, retain) NSString* name;
@property(readwrite, retain) NSNumber* age;

@end

Interface starts with @interface annotation. Contact is the name of the class which we want to implement. NSObject is just like Object in Java or TObject in Delphi. I mean it is the most primitive object that you can use to develop your customized entities based on it.
NSString is just String. Unfortunately Apple didn’t choose better names for it’s primitive datatypes during years. “NS” comes from NeXTStep that is an old project that managed by Steve Jobs long time ago. The star before name variable is just the pointer sign. Don’t worry about it. It doesn’t make any problem.
A Property declares with @property annotation. Check this out to know what does it mean.
“readwrite” Indicates that the property should be treated as read/write. This is the default.

Implementation Next

This is the time to develop the implementation of the interface. Implementation always has a “.m” extension such as following:

#import "Contact.h"

@implementation Contact
@synthesize name, age;

@end

The implementation part starts with importing the interface first. Then it declares that is an implementation of the Contact interface. The most interesting definition that I’ve found in Objective C is @synthesize annotation. Here both a getter and setter method of properties will be required in the @implementation. If you use @synthesize in the implementation block, the getter and setter methods are synthesized automatically.

Main Program

Here is the main program. NSAutoreleasePool is the most convenient way for automatically releasing Objective C objects. I believe Java and C# object’s releasing mechanism is more advanced over Objective C. In Objective C you can release objects by releasing them one by one or adding them into a autorelease pool. I prefer second way. Below is a main() method sample that uses Contact.h. Here we defined and initiated an autorelease pool (NSAutoreleasePool). Then we defined an instance of Contact class that is also autorelease. It is not such a Java or C# self describing and clear code. But there is no other way to develop on iOS.

#import
#import "Contact.h"

int main (int argc, const char * argv[]) {

	NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    Contact *myFriend = [[Contact alloc] autorelease];

    NSNumber *newAge = [NSNumber numberWithInt:30];

    [myCar setAge:newAge];
    [myCar setName:@"Sara"];

    NSLog(@"The contact is: %@", [myFriend name]);
    NSLog(@"The his/her age is: %@", [myFriend age]);

    [myFriend release];

	[pool drain];

	return 0;
}

Objective C has a different syntax and conventions in compare with other popular programming languages. It is not as much easy as Java in my experience. But practice makes perfect. So just do it.

Posted in Cocoa/Objective-C

Sending HTML emails with attachments via SMTP and Java mail API.

Published on December 9, 2010 by Amir Sedighi

The code is clear enough and you won’t need any explanation…

package mail.send.datis.com;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
import javax.mail.internet.MimeMultipart;
import java.util.ArrayList;
import java.util.Date;
import java.util.Properties;

public class SMTPClient {

    private final String _CONTENT_HTML = "text/html";
    private final String _CONTENT_HOST = "mail.datispars.com";
    private final String _PORT = "25";
    private final String _USERNAME = "amir@datispars.com";
    private final String _PASSWORD = "your_password";

	public static void main(String[] args) throws MessagingException {
        SMTPClient sender = new SMTPClient();

       // sending mail, without attachment.
        sender.send("amir@datispars.com","kamran@datak.net", "Hi Kamran, how is going?" , "

this is a h1 tag so, it may appears in huge size! :D

"); // sending another mail, with 2 attachments. ArrayList fileNames = new ArrayList(); fileNames.add("/home/amir/Documents/hi_world.pdf"); fileNames.add("/home/amir/projects/datis/sendSMTP.zip"); sender.send("amir@datispars.com","kamran@datak.net", "Hi Kamran, how is going?" , "

this is a h1 tag so, it may appears in huge size! :D

", fileNames); } private void send(String from, String to, String subject, String body) throws MessagingException { Message message = new MimeMessage(getSession()); message.addRecipient(RecipientType.TO, new InternetAddress(to)); message.addFrom(new InternetAddress[] { new InternetAddress(from) }); message.setSubject(subject); message.setContent(body, _CONTENT_HTML); Transport.send(message); } private void send(String from, String to, String subject, String body, ArrayList attachments) throws MessagingException { Message message = new MimeMessage(getSession()); message.addRecipient(RecipientType.TO, new InternetAddress(to)); message.addFrom(new InternetAddress[] { new InternetAddress(from) }); message.setSubject(subject); MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setText(body); mbp1.setContent(body, _CONTENT_HTML); Multipart mp = new MimeMultipart(); mp.addBodyPart(mbp1); for (String fileName: attachments){ MimeBodyPart mbp = new MimeBodyPart(); FileDataSource fds = new FileDataSource(fileName); mbp.setDataHandler(new DataHandler(fds)); mbp.setFileName(fds.getName()); mp.addBodyPart(mbp); } message.setContent(mp); message.setSentDate(new Date()); Transport.send(message); } private Session getSession() { Authenticator authenticator = new Authenticator(); Properties properties = new Properties(); properties.setProperty("mail.smtp.submitter", authenticator.getPasswordAuthentication().getUserName()); properties.setProperty("mail.smtp.auth", "true"); properties.setProperty("mail.smtp.host", _CONTENT_HOST); properties.setProperty("mail.smtp.port", _PORT); return Session.getInstance(properties, authenticator); } private class Authenticator extends javax.mail.Authenticator { private PasswordAuthentication authentication; public Authenticator() { authentication = new PasswordAuthentication(_USERNAME, _PASSWORD); } protected PasswordAuthentication getPasswordAuthentication() { return authentication; } } }

Posted in Java

The way I use SSH

Published on September 25, 2010 by Amir Sedighi

“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 be somewhere else

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 call a service that is hosted on a remote machine using a third-one machine
Assume a service such as MYSql or anything else 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 service uses the port number 1433.
So, you need to connect to the ssh server machine using ssh root@100.101.102.103 moreover you need to forward 192.168.0.100:1433 to your 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:

your machine           ssh server            remote service
127.0.0.1:1433 .... 100.101.102.103 .... 192.168.0.100:1433

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

Posted in Linux

How to access the folders outside Tomcat

Published on September 7, 2010 by Amir Sedighi

The best way for accessing the folders outside Tomcat webapps folder is mapping folders using mount-points. Assume the application folder located in below path: (MyApplication)

/home/amir/java/tomcat/webapps/MyApplication/

I need to upload files into another machine so I just created a folder “hugeSizeFolder” into the “MyApplication” folder.
Then I mapped it to a remote shared folder.
Assume the remote shared folder located in : “//192.168.137.69/shareStorage”.
Then just follow below steps:

$ mkdir /home/amir/java/tomcat/webapps/MyApplication/hugeSizeFolder
$ sudo chmod -R 777 /home/amir/java/tomcat/webapps/MyApplication/hugeSizeFolder
$ sudo smbmount //192.168.137.69/shareStorage   /home/amir/java/tomcat/webapps/MyApplication/hugeSizeFolder

Done. The local folder will keep synchronize with the remote shared one in OS level automatically. The mapping is transparent to Tomcat.

Posted in Java, Linux

Exploring under hood of Java applications using JMX – Part 2

Published on August 28, 2010 by Amir Sedighi

Introduction

Here you will find how to monitor an application which is hosted in Apache Tomcat. There are many reasons for monitoring an application in run time. In our case the client was looking for some measurable factors that shows slap of business ratios on demand. Moreover, the technical department was looking for fine-grain informations such as user uptime, most visited pages, idle time and any possible exception that occurs in run time. JMX is the perfect answer for this kind of requirements. Connecting to the Tomcat using JMX has a straight forward procedure.

Let Tomcat listens to the out side world

We should declare multiple environmental variables that notify Tomcat for using JMX. They also specify the listener port.
There are different ways to introduce environment variables to Tomcat. But, I’v found that using setenv.sh in Linux or setenv.bat in Windoes is the best one:
Create “setenv.sh” with exactly below content:

export CATALINA_OPTS="-Dcom.sun.management.jmxremote
-Dcom.sun.management.jmxremote.port=9898
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.ssl=false
-Djava.rmi.server.hostname=100.101.102.103"

Now make it executable:

chmod +x setenv.sh

Note: 9898 is the JMX listener on tomcat. 100.101.102.103 is the IP of tomcat server.

2. Put “setenv.sh” in “bin” directory of tomcat.

3. Turn the fire wall off or run below command on the Tomcat machine:

sudo /sbin/iptables -I INPUT -s 100.101.102.150 -p tcp --destination-port 9898 -j ACCEPT

Note:
100.101.102.150 is the JConsole machine. Also 9898 is the same as port that you defined in setenv,sh

4. Re-start tomcat.

5. Run jconsole and connect to a remote process using : 100.101.102.103:9898

The MBean objects are observe able now. Also you may call remote behaviors that are implemented the MBean interface.

Authentication

If you need to secure jmx connection then follow bellow steps and restart tomcat:
1. Create a new text file called “jmxremote.password” under “/tomcat/conf” folder:
Note: use TAB for separating words in each line:

amir      thepassword
admin   applepie

2. Create a new text file called “jmxremote.access” under “/tomcat/conf” folder:
Note: use TAB for separating words in each line:

amir      readonly
admin   readwrite

3. Make those readonly:

$ chmod 600 /conf/jmxremote.password
$ chmod 600 /conf/jmxremote.access

4. Update setenv.sh to looks like below:

export CATALINA_OPTS="-Dcom.sun.management.jmxremote
-Dcom.sun.management.jmxremote.port=9898
-Dcom.sun.management.jmxremote.ssl=false
-Djava.rmi.server.hostname=100.101.102.103
-Dcom.sun.management.jmxremote.authenticate=true
-Dcom.sun.management.jmxremote.password.file=/home/amir/tomcat/conf/jmxremote.password
-Dcom.sun.management.jmxremote.access.file=/home/amir/tomcat/conf/jmxremote.access"

Trouble Shooting

The procedure seems to be easy. In Datispars we have deployed successfully the solution over Ubuntu 9.04 and FreeBSD 7.2. . However, Anyway keep attention about below items:
-Do download a new Tomcat from apache repository rather using a customized version that you have gotten by Linux package managers.
-First of all be sure you there is no any space around “=” in setenv.sh because, the syntax is pretty important.
-Also for checking the listener use “telnet” or “netstat” to find out the port is open and is listening.
-Check /etc/hosts if it is correct or not. In my case a wrong definition made troubles.

Posted in Java, Linux, Software Engineering

Exploring under hood of Java applications using JMX – Part 1

Published on August 25, 2010 by Amir Sedighi

Introduction.

A business company was looking for a proper method to monitor it’s business applications. They were almost implemented by Java. Firstly I was going to implement another application for this purpose. Fortunately a friend of mine shows the way. We planned to use JMX. Here is a tutorial that clearly shows you how to let a Java application to be exposed using JMX.
At first have a look on JMX technical introductions. I used to send SNMP messages for making a communication between applications during run time JMX has many advantages over SNMP. JMX simply enables you to start a listener in the application that could be watched. This makes the monitor side enable to touch and trace public methods of every classes that implements MBean interface. Dont worry if you have a legacy application that is not armored with MBean interfaces. You need just develop an API that expose the critical variables for the out side.

MBean Interface
I developed an interface that its name finished by MBean. This is a contract that should be respected to continue.

package com.datispars.monitoring;

public interface JmxSampleMBean {
    public void getMessage();
    public int add(int x, int y);
    public String getTitle();
    public int getTimeOut();
    public void setTimeOut(int size);
}

MBean Implementation
Now I just implemented an implementation of the MBean. The sample is as much easy as talk without a comment.

package com.datispars.monitoring;

public class JmxSample implements JmxSampleMBean {

    private final String title = "JMX Sample";
    private int timeOut = 20;

    public void getMessage() {
		System.out.println("Hi," + getTitle());
	}

	public int add(int x, int y) {
        int result = x + y;
        System.out.println(x + "+" + y + "= " + result);
		return result;
	}

	public String getTitle() {
        System.out.println("the " + title + " has been called.");
		return this.title;
	}

	public int getTimeOut() {
		return this.timeOut;
	}

	public synchronized void setTimeOut(int value) {
		this.timeOut = value;
		System.out.println("time out has been changed to " + this.timeOut + " seconds.");
	}
}

MBean Factory
The main method consists a MBean server and a MBean registration and nothing else:

package com.datispars.monitoring;

import java.lang.management.*;
import javax.management.*;

public class Main {
   public static void main(String[] args) throws Exception {
      // instantiating MBean server
      MBeanServer mbServer = ManagementFactory.getPlatformMBeanServer();
      // declaring name and type of MBean
      ObjectName mBeanName = new ObjectName("com.datispars.monitoring:type=JmxSample");
      // instantiating MBean
      JmxSample jmxSample = new JmxSample();
      // regisring onject as MBean
      mbServer.registerMBean(jmxSample, mBeanName);
      // waiting for jmx requests.
      System.out.println("Listening...");
      Thread.sleep(Integer.MAX_VALUE);
   }
}

Big Brother Is Watching You
Now it is the time to watch what is happening within the application. Run the application. Open a terminal and just run “jconsole“. Click on the local application name. The jconsole looks fantastic!. Alive diagrams that draw by the information which are provided by JVM let you know how is the situation. Go to the MBean tab and find the MBean declarations of your application. Call “add” with integer numbers. Have a look on the console output of the application. It is great! That is why I love Java. You can find always engineering solutions for the problem.
In next part we will set up an Apache Tomcat monitoring with MBean objects.

Posted in Java, Linux, Software Engineering

Faster Revoking by Sending Fat Messages

Published on July 10, 2010 by Amir Sedighi

Introduction
Here is an approach to speed up object/service invoking. This solutions may apply to a web-based application or any other service that works using a series of interactions and transactions. Here I don’t refer to any specific technology or platform, because it is a pretty general technique. It is all about sending a bigger message that carries more parameters for multiple methods instead of sending multiple messages to the multiple methods. In other word this article is about favoring fatty messaging instead of chatty messaging.

Converting A “Chatty” Messaging To A “Fatty” One
Monitoring an application in runtime appears that how much a big UI transaction may consists a lot of inner interactions between client application and server side services. This may happens even between servers such as application server and database server. In many cases you need to perform a macro interaction that needs many input parameters to get finish. These input parameters may should provides by user or any other external system. Below sample shows a chatty approach that gets some input parameters at start point and some others during the process.

Assume we have below three methods in class B:

public int sum ( int a , int b ) {
	return a + b;
}

public int multi ( int a , int b ) {
	return a * b;
}

public int power ( int a , int b ) {
	int result = 1;
	for ( int a = 1 ; a < b ; a ++ ){
		result = result * a ;
	}
	return result;
}

Now if class A use to call these three methods sequentially then we will have such a sequence as below:

		A (Caller) 				B (Callee)
		----------------------------------------------------------------------
		B bObject = new B();
		firstVal = bObject.sum(1 , 2)
							B returns 3  

		secondVal = bObject.multiply( firstVal , 2 )

							B returns 3 * 2 = 6		

		thirdVal = bObject.power( secondVal , 2 )

							B returns 6 * 6 = 36

Assume B hosted in a remote machine. Something like RMI or even web-service calling. As you can see we have three remote method invoking that all are synchronized. Regardless of process consuming in B machine, we have at least 3 remote call that each one has one return value passing. Instead of this chatty talking between A and B we can use an onetime fatty calling by implementing a wrapper in B as below:

public int whatANeeds ( int a , int b, int multiValue, int powerValue ) {
	int firstVal = this.sum(a,b);
	int secondVal = this.multi(firstVal,  multiValue );
	return this.power(secondVal,  powerValue );
}

Now sequence of remote method calling will be as below:

		A (Caller) 				B (Callee)
		----------------------------------------------------------------------
		B bObject = new B();
		final = bObject.whatANeeds (1 , 2 , 2 , 2);
							B returns 36

An Old Fashion High Performance Approach
We can extend this kind of method invoking in another special that B is a RDBMS. Assume B is a RDBMS and A is the application server that calls some queries or runs some data manipulating SQL commands remotely. In this case stored-procedures could be useful. Everybody knows the most significant bottleneck is the low capacity of I/O and data transfer systems. So calling server-side methods in fatty messaging is always pretty effective in improving performance. Implementing stored-procedures in RDBMS is so old fashion for new age of developers. But it is really the fastest way that helps a business application to run faster. As a result we almost can convert multiple chatty methods invoking to a fatty one that runs faster. This could be useful everywhere in internal or external method/service invoking.

Posted in Software Engineering

« Older Entries

Categories

Archives