Tuesday, October 07, 2008

(ISO 8583 + JPOS + Log4J) in Java Socket Programming

SECTION 1. INTRODUCTION
Chapter 1.1. ISO 8583
You can read it's explanation first in Wikipedia.
Chapter 1.2. JPOS
JPOS is opensource framework for ISO 8583. Source code and library are free but documentation is comercial. We can download it here.
Chapter 1.3. Log4J
Log4J is opensource logging library. We can download it's library here and read it's mini e-book first written by Mr. Endy in here.
Chapter 1.4. Java Socket Programming
There's no explanation. Just need the basic knowledge of Java network programming and Java Thread Programming and let's coding.

SECTION 2. CODING
First we prepare that all we need. In this time, we will use NetBeans as IDE. Besides JPOS framework and Log4J library that I have mentioned above, we still need:
1. Xerces-Java XML parser library (xercesImpl.jar)
2. Spring framework
3. Jakarta Apache Commons Logging library

Chapter 2.1. ISO 8583 + JPOS + Log4J
In NetBeans, create a new Java application named MyApp. Create a package named com.ndung.iso8583. JPOS framework need a packager to set which ISO 8583 version that will be used. In this time we will use ISO 8583 version 1987. Download first iso87ascii.xml and place it in that package. Create a class as packager factory named PackagerFactory.java.


package com.ndung.iso8583;

import java.io.InputStream;

import org.jpos.iso.ISOException;
import org.jpos.iso.ISOPackager;
import org.jpos.iso.packager.GenericPackager;

public class PackagerFactory {
public static ISOPackager getPackager() {
ISOPackager packager = null;
try {
String filename = "iso87ascii.xml";
InputStream is = PackagerFactory.class.getResourceAsStream(filename);
packager = new GenericPackager(is);
}
catch (ISOException e) {
e.printStackTrace();
}
return packager;
}
}

And then create a class named MessageHandler.java that will be used to handle received message. Download first iso87asciiProperties.xml that will be used to translate bits of ISO message to become a String message that can be read easily.


package com.ndung.iso8583;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import org.apache.log4j.Logger;
import org.jpos.iso.ISOException;
import org.jpos.iso.ISOMsg;
import org.jpos.iso.ISOPackager;

public class MessageHandler {
private static ISOPackager packager = PackagerFactory.getPackager();
private Logger logger = Logger.getLogger( getClass() );
public String process(ISOMsg isomsg) throws Exception {
logger.info("ISO Message MTI is "+isomsg.getMTI());
logger.info("Is ISO message a incoming message? "+isomsg.isIncoming());
logger.info("Is ISO message a outgoing message? "+isomsg.isOutgoing());
logger.info("Is ISO message a request message? "+isomsg.isRequest());
logger.info("Is ISO message a response message? "+isomsg.isResponse());
String message = "";
for (int i=0;i<128;i++){
if (isomsg.hasField(i)){
message += loadXMLProperties().getProperty(Integer.toString(i))+"="+
isomsg.getValue(i)+"\n";
}
}
logger.info(message);
return message;
}

public ISOMsg unpackRequest(String message) throws ISOException, Exception {
ISOMsg isoMsg = new ISOMsg();
isoMsg.setPackager(packager);
isoMsg.unpack(message.getBytes());
isoMsg.dump(System.out, " ");
return isoMsg ;
}

public String packResponse(ISOMsg message) throws ISOException, Exception {
message.dump(System.out, " ");
return new String( message.pack() ) ;
}

public Properties loadXMLProperties(){
Properties prop = new Properties();
try{
FileInputStream input=new FileInputStream("iso87asciiProperties.xml");
prop.loadFromXML(input);
input.close();
}
catch(IOException e){
e.printStackTrace();
}
return prop;
}
}

Chapter 2.2. Java Socket Programming + Log4J
Create a package named com.ndung.socket and then create four classes named ServerConfig.java, SocketServerHandlerFactory.java, SocketServerHandler.java, SocketConnectionServer. Before that create log4j.properties as logging configuration in default package.

# Category Configuration
log4j.rootLogger=INFO,Konsole,Roll
# Console Appender Configuration
log4j.appender.Konsole=org.apache.log4j.ConsoleAppender
log4j.appender.Konsole.layout=org.apache.log4j.PatternLayout
# Date Format based on ISO­8601 : %d
log4j.appender.Konsole.layout.ConversionPattern=%d [%t] %5p %c ­ %m%n
# Roll Appender Configuration
log4j.appender.Roll=org.apache.log4j.RollingFileAppender
log4j.appender.Roll.File=/home/ndung/NetBeansProjects/MyApp/log/myApp.log
log4j.appender.Roll.MaxFileSize=10KB
log4j.appender.Roll.MaxBackupIndex=2
log4j.appender.Roll.layout=org.apache.log4j.PatternLayout
# Date Format based on ISO­8601 : %d
log4j.appender.Roll.layout.ConversionPattern=%d [%t] %p (%F:%L) ­ %m%n


package com.ndung.socket;
public class ServerConfig {
private int port;
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
}


package com.ndung.socket;

import com.ndung.iso8583.MessageHandler;
import java.io.IOException;
import java.net.Socket;

public class SocketServerHandlerFactory {
private MessageHandler messageHandler;
public SocketServerHandlerFactory(MessageHandler messageHandler) {
this.messageHandler = messageHandler;
}
public SocketServerHandler createHandler(Socket socket) throws IOException {
return new SocketServerHandler(socket, messageHandler);
}
}


package com.ndung.socket;

import com.ndung.iso8583.MessageHandler;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import org.apache.log4j.Logger;
import org.jpos.iso.ISOMsg;

public class SocketServerHandler extends Thread{
private Logger logger = Logger.getLogger( getClass() );
private Socket serverSocket ;
private BufferedReader inFromClient;
private DataOutputStream outToClient;
private MessageHandler messageHandler;
private String datafromClient;

public SocketServerHandler(Socket socket, MessageHandler messageHandler) throws IOException {
super("SocketHandler (" + socket.getInetAddress().getHostAddress() + ")");
this.serverSocket = socket ;
this.messageHandler = messageHandler;
this.inFromClient = new BufferedReader(new InputStreamReader(serverSocket.getInputStream()));
this.outToClient = new DataOutputStream(serverSocket.getOutputStream());
}
@Override
public void run() {
try {
logger.info("Server is ready...");
while (true) {
logger.info("There is a client connected...");
outToClient.writeBytes("InfoServer version 0.1\n");
datafromClient = inFromClient.readLine();
logger.info("Data From Client : "+datafromClient);
ISOMsg isomsg = messageHandler.unpackRequest(datafromClient);
outToClient.writeBytes(messageHandler.process(isomsg));
}
}
catch (IOException ioe) {
logger.error("error: " + ioe);
}
catch (Exception e) {
logger.error("error: " + e);
}
finally {
try {
if (inFromClient != null) inFromClient.close();
if (outToClient != null) outToClient.close();
if (serverSocket != null) serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}


package com.ndung.socket;

import java.io.IOException;
import java.net.ServerSocket;

public class SocketConnectionServer {
private ServerConfig config;
private SocketServerHandlerFactory handlerFactory;
private boolean stop;
public SocketConnectionServer(ServerConfig config, SocketServerHandlerFactory handlerFactory) {
this.config = config;
this.handlerFactory = handlerFactory;
}
public void start() throws IOException {
stop = false;
final ServerSocket serverSocket = new ServerSocket(config.getPort());
new Thread(new Runnable() {
public void run() {
while (!stop) {
try {
handlerFactory.createHandler(serverSocket.accept()).start();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}).start();
}
public void stop() {
stop = true;
}
}

Create a socket server class named MyServer.java. This class also as a main class for our application. And then we will create a socket client class named MyClient.java. Before that create applicationContext.xml in default package as Spring configuration injection for our main class.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">

<beans>
<bean id="socketConnectionServer" class="com.ndung.socket.SocketConnectionServer">
<constructor-arg>
<ref local="config" />
</constructor-arg>
<constructor-arg>
<ref local="socketServerHandlerFactory" />
</constructor-arg>
</bean>

<bean id="config" class="com.ndung.socket.ServerConfig">
<property name="port">
<value>50000</value>
</property>
</bean>

<bean id="socketServerHandlerFactory" class="com.ndung.socket.SocketServerHandlerFactory">
<constructor-arg>
<ref local="messageHandler" />
</constructor-arg>
</bean>

<bean id="messageHandler" class="com.ndung.iso8583.MessageHandler">
</bean>

</beans>


package com.ndung.socket;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyServer {

public static void main(String[] args) throws IOException {
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
SocketConnectionServer server = (SocketConnectionServer) ctx.getBean("socketConnectionServer");
server.start();
}
}


package com.ndung.socket;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import org.apache.log4j.Logger;

public class MyClient {
private final int MY_PORT=50000;
private final String TargetHost = "localhost";
private final String QUIT = "QUIT";
private Logger logger = Logger.getLogger( getClass() );
public MyClient() {
try {
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
Socket clientSocket = new Socket(TargetHost, MY_PORT);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
logger.info(inFromServer.readLine());
boolean isQuit = false;
while (!isQuit) {
System.out.print("Your data : ");
String cmd = inFromUser.readLine();
cmd = cmd.toUpperCase();
if (cmd.equals(QUIT)) {
isQuit = true;
}
outToServer.writeBytes(cmd + "\n");
String message = inFromServer.readLine();
while (message!=null){
logger.info("From Server: " + message);
message = inFromServer.readLine();
}
}
outToServer.close();
inFromServer.close();
clientSocket.close();
}
catch (IOException ioe) {
logger.error("Error:" + ioe);
}
catch (Exception e) {
logger.error("Error:" + e);
}
}
public static void main(String[] args) {
new MyClient();
}
}

Run our application first. It means our main class (MyServer.java) will be run first. And then run client as much that we want. It means MyClient.java will be run twice or more. And then in one of our client application console enter an input data. It means a String of ISO message. As example:
0210723A00010A808400185936001410010999990110000000100000001007021533000001191533
10061007065656561006090102240000000901360020100236C0102240000000
Look in both of our application console either MyServer or MyClient. What do you see?
Btw, Happy Eid Mubarak...

307 comments:

«Oldest   ‹Older   201 – 307 of 307
Anonymous said...

buy soma online no prescription carisoprodol kratom - soma interactions more drug_interactions

Anonymous said...

buy xanax buy xanax online from india - xanax buy online mastercard

Anonymous said...

buy tramadol without rx how long does tramadol high last - buy ultram without rx

Anonymous said...

can you really buy xanax online generic xanax side effects - buy xanax online cheapest

Anonymous said...

order tramadol online buy ultram online no prescription overnight - buy generic ultram no prescription

Anonymous said...

cheap tramadol tramadol can you snort - tramadol hcl hydrocodone

Anonymous said...

can you really buy xanax online xanax relieve anxiety - xanax side effects bad dreams

Anonymous said...

buy tramadol in florida can you buy tramadol online no prescription - tramadol for headaches

Anonymous said...

xanax online xanax withdrawal mayo clinic - xanax bars in system

Anonymous said...

alprazolam 0.5mg clonazepam vs xanax high - generic xanax onax

Anonymous said...

how to buy xanax online pass urine drug test xanax - xanax withdrawal management

Anonymous said...

buy xanax xanax side effects withdrawal - buy valium xanax online

Anonymous said...

xanax 0.5mg xanax schedule iv drug - xanax to get high off of

Anonymous said...

xanax no prescription klonopin xanax high - xanax dosage dogs

Anonymous said...

buy ambien online ambien sleep cycle - ambience mall gurgaon metro staton

Anonymous said...

xanax mg overdose 4mg xanax - how much xanax and alcohol can kill you

Anonymous said...

buy xanax online Mississippi ksalol 1mg xanax - xanax side effects webmd

Anonymous said...

generic alprazolam xanax no prescription no membership - xanax side effects in the elderly

Anonymous said...

buy xanax online Indianapolis get generic xanax uss - xanax gg249

Anonymous said...

buy xanax mastercard xanax online no prescription - can you buy xanax vietnam

Anonymous said...

xanax online prescription buy xanax online us - xanax side effects in teenagers

Anonymous said...

ambien pills buy ambien prescription online - buy ambien online overnight delivery

Anonymous said...

buy ambien ambien side effects of sleep eating - ambien cr to ambien

Anonymous said...

how to buy xanax online xanax benefits anxiety - buy xanax xr online no prescription

Anonymous said...

buy xanax xanax picture of pill generic - xanax side effects slurred speech

Anonymous said...

can i buy xanax online 2mg xanax effects erowid - xanax for postpartum anxiety

Anonymous said...

generic xanax online eczane xanax - xanax side effects elderly

Anonymous said...

buy xanax Chicago clonazepam 1mg xanax - xanax bars price

Anonymous said...

discount ambien ambien withdrawal treatment - 8 ambien

Anonymous said...

buy xanax Seattle generic xanax india - how can you buy xanax online

Anonymous said...

buy xanax online Raleigh North xanax 5mg effects - xanax pills .25

Anonymous said...

buy xanax online cheap no prescription get xanax no prescription - buy xanax online in usa

Anonymous said...

where to buy ambien online buy ambien online europe - high on ambien cr

Anonymous said...

buy generic xanax online xanax dosage oral sedation - buy ksalol xanax

Anonymous said...

buy xanax valium online florida xanax anxiety medication - generic xanax round

Anonymous said...

buy ambien ambien side effects wikipedia - ambien sleep on airplane

Anonymous said...

generic xanax how does generic xanax pill look like - kind pills xanax

Anonymous said...

buy ambien pills that look like ambien - order ambien online mastercard

Anonymous said...

xanax online Portland xanax 90 - xanax high review

Anonymous said...

buy cheap xanax order xanax prescription - xanax vs clonazepam

Anonymous said...

xanax no prescription online xanax side effects weight - xanax drug for dogs

Anonymous said...

order ambien ambien 10 mg too strong - ambien cr best price

Anonymous said...

buy xanax online without rx xanax and alcohol webmd - xanax schedule two drug

Anonymous said...

buy ambien affects of ambien and alcohol - generic ambien in u.s.a

Anonymous said...

best place to buy xanax online xanax klonopin interaction - xanax overdose with alcohol

Anonymous said...

xanax online no prescription xanax side effects withdrawal - long does take 1mg xanax work

Anonymous said...

ambien online purchase ambien no rx - ambien cr drug class

Anonymous said...

buy ambien ambien shoppers drug mart - ambien cr price

Anonymous said...

buy xanax Sacramento xanax 59 - xanax and alcohol poisoning

Anonymous said...

buy ambien ambien 40 - ambien classification

Anonymous said...

buy xanax xanax withdrawal psychosis - buy xanax no prescription usa

Anonymous said...

buy xanax alprazolam 0.5mg para que sirve - generic xanax forum

Anonymous said...

xanax 1mg xanax for anxiety dosage - order xanax pills online

Anonymous said...

buy ambien ambien sleepwalking video - price ambien cr 12.5

Anonymous said...

xanax mg has bought xanax online - generic xanax 0.25mg

Anonymous said...

buy ambien ambien cr 50 mg - ambien sleep driving stories

Anonymous said...

buy xanax online Milwaukee you mix xanax and alcohol - xanax drug interactions lexapro

Anonymous said...

buy xanax online no prescription cheap xanax generic manufacturers - online doctor consultation prescription xanax

Anonymous said...

buy ambien ambien dosage white pill - ambien orange pill

Anonymous said...

generic xanax Long Beach xanax generic buy - xanax reviews 2012

Anonymous said...

buy xanax online Nebraska generic rx source xanax - xanax side effects kidney

Anonymous said...

online xanax xanax 66 2 4 9 - xanax and alcohol bluelight

Anonymous said...

buy ambien online overnight delivery ambien cr side effects dry mouth - ambien cr vs ambien 10mg

Anonymous said...

xanax price xanax online - xanax drug company

Anonymous said...

buy ambien how long does ambien withdrawal last - what does zolpidem pill look like

Anonymous said...

xanax medication generic xanax gg 249 - xanax bars u94

Anonymous said...

buy ambien ambien generic quality - safe buy ambien online

Anonymous said...

buy ambien ambien cr cost insurance - buy ambien online no rx

Anonymous said...

generic xanax New York xanax white pill with r 027 - xanax and alcohol depression

Anonymous said...

buy xanax online xanax online consultation - xanax (generic) 2 mg pills

Anonymous said...

buy ambien online overnight delivery ambien occasional insomnia - ambien zolpidem

Anonymous said...

xanax 1mg side effects of xanax for anxiety - xanax drug test days

Anonymous said...

ambien price cheapest generic ambien online - ambien cr contraindications

Anonymous said...

buy xanax online legally generic xanax difference - can u legally buy xanax online

Anonymous said...

generic xanax Philadelphia xanax dosage options - high from xanax bars

Anonymous said...

xanax without a perscription xanax and alcohol ok - xanax withdrawal high blood pressure

Anonymous said...

ambien pill buy ambien online overnight delivery - buy ambien online no prescription needed

Anonymous said...

buy xanax online no prescription overnight generic xanax online no prescription - drug interactions with xanax and vicodin

Anonymous said...

buy zolpidem online side effects of zolpidem ambien - black market price for ambien

Anonymous said...

where can i buy xanax online xanax bars - xanax effects dogs

Anonymous said...

order ambien without prescriptions order ambien online with no prescription - legal to buy ambien online

Anonymous said...

xanax anxiety xanax 3mg xr - xanax pills do they do

Anonymous said...

ambien without prescriptions ambien cost at walmart - can buy ambien thailand

Anonymous said...

buy xanax online no rx xanax generic 25mg - xanax yellow bar

Anonymous said...

ambien cr best ambien stories - stories of ambien addiction

Anonymous said...

cheap xanax no prescription xanax side effects heart palpitations - xanax side effects dogs

Anonymous said...

buy xanax xanax online sales - does xanax show up hair follicle drug test

Anonymous said...

order zolpidem costco price for ambien - ambien benzodiazepine drug test

Anonymous said...

xanax xanax dosage maximum - xanax over the counter

Anonymous said...

buy zolpidem online much does generic ambien cr cost - ambien vs alcohol

Anonymous said...

buy xanax online xanax withdrawal really bad - high off xanax xr

Anonymous said...

cheapest ambien ambien sale canada - ambien cr 20 mg

Anonymous said...

ambien cheap fda ambien cr (zolpidem tartrate) - ambien cr 7 day coupon

Anonymous said...

buy xanax valium online florida xanax overdose canine - xanax xr half life

Anonymous said...

buy ambien ambien dosage for pregnant women - recovering ambien overdose

Anonymous said...

xanax cheap xanax side effects on pregnancy - cheap xanax overnight

Anonymous said...

[url=http://vtyupdr.com]wYSmysftvWLKg[/url] - hwqotYcrFuGQe , http://pyfnknfrtw.com

Anonymous said...

buy tramadol online tramadol dosage maximum - 50mg tramadol lot

Unknown said...

Hi ,

i am getting an following exception while running MyServer.java,

Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'socketConnectionServer' defined in class path resource [applicationContext.xml]: Cannot resolve reference to bean 'socketServerHandlerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'socketServerHandlerFactory' defined in class path resource [applicationContext.xml]: Cannot resolve reference to bean 'messageHandler' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'messageHandler' defined in class path resource [applicationContext.xml]:

Kindly help me on this.

Anonymous said...

Your write-up featurеs estаblіshed benefіcial to myѕelf.

It’s extrеmеly іnformative and you really аге natuгаlly extremelу knowleԁgeable іn thіs areа.
You get oρenеd my оwn eye іn ordeг tο varying оpinion οf this subjеct matter tοgether with іntriguіng and solіd aгticlеs.
Here is my web-site buy Klonopin

Anonymous said...

Υour curгent write-up provideѕ
confiгmed helpful to us. It’s reallу educational and
you're simply certainly extremely knowledgeable in this region. You have popped my own eye in order to numerous thoughts about this kind of subject matter using intriquing, notable and solid written content.
Also see my website :: Xanax

Anonymous said...

Your cuгrent report features proven helρful to myself.
It’s extгemely useful and you're certainly very educated in this area. You have got opened my sight in order to different opinion of this particular subject matter along with intriguing, notable and solid content material.

Here is my site - museum.pica.nl
My webpage ... viagra

Anonymous said...

tramadol online tramadol high similar - how to order tramadol online no prescription

Anonymous said...

It's hard to find experienced people in this particular topic, however, you sound like you know what you're talking about!

Thanks

Also visit my web blog http://seecommunity.net

Anonymous said...

Have you ever considered creating an e-book or guest authoring on other websites?

I have a blog based on the same subjects you discuss and would really
like to have you share some stories/information. I know my readers would value your work.
If you're even remotely interested, feel free to shoot me an e mail.

Also visit my web-site - Http://Www.Felvi.Hu/Weblap/Felvi/Felsooktatasimuhely/Avir/Fogalomtar/Defmart/!Defmart/Index.Php/FelhasznáLó:Celinak32

Anonymous said...

Hi colleagues, how is the whole thing, and what you wish for to
say about this post, in my view its genuinely amazing designed for me.


Here is my web-site - victorinox watches for women

Anonymous said...

Hello, i think that i saw you visited my web site so
i came to “return the favor”.I'm trying to find things to enhance my site!I suppose its ok to use a few of your ideas!!

Feel free to surf to my weblog; funnyz.eu

«Oldest ‹Older   201 – 307 of 307   Newer› Newest»