Monday, May 30, 2011

Running Two Tomcat Instances on One Machine

Introduction

GRIA is designed to allow the various services to be installed on different machines, and for this reason internal communication between services uses SOAP. Sometimes, it is desirable to install multiple war files (typically the basic application services and the service provider management services) on a single machine.

In GRIA 5.0, there is a known problem with this approach. In order to prevent tomcat from running out of memory and crashing when there are a large number of incoming requests to service, the number of threads should be limited using the maxThreads setting in the $TOMCAT_HOME/conf/server.xml file. But, this can cause dead-lock in the following situation:

The service is configured to allow a maximum of n threads.
A client makes n calls to a job or data service operation that requires confirmation from the SLA service.
The job or data service tries to invoke the SLA service (over SOAP), but no threads are available.
The service waits until a thread becomes free for the SLA service, but none of them ever will because they are all processing requests to an application service that are waiting for a free SLA thread.

The recommended solution to this problem is to run two instances of tomcat on the single machine, one running the management services and one running the application services. Because the threads are then not shared between the two, an SLA operation will never block because a thread is taken by an application service and the system will not deadlock.
Set Up

To install two instances of tomcat in this way:

Download tomcat, and unpack it twice, into two separate directories.
Edit the conf/server.xml file in one of the copies in the following way:
Change the port on the root Server element to a different number (e.g. 8006)
Change the port attributes on the Connector elements to a different number (e.g. 8010 instead of 8009, 8081 instead of 8080 and 8444 instead of 8443)

You should now be able to run the bin/startup.sh scripts in both installations to get two running tomcats. Connect using port 8080 and install the basic application services, and then connect using port 8081 to install the service provider management services.

Friday, May 27, 2011

Unable to Start a Program with an .exe File Extension..

This problem i face when i was in sydney..
the problem is that ..when i click any exe file they opened in a open as " window prompt..... this is due to some Virus problem... It seems that i have to format my comp and reload my Os again..

Think how i resolve the solution when cmd,taskmanager, regedit, gpedit.msc, msconfig, internet explorer, any exe file and other tool is not working at all...................

before that i search to the internet and find the cause and solution..

Symptom

When you try to launch an application (.exe files), the following error message appears and the program does not run.

Cause

This problem occurs if the .exe file association in the registry is corrupt. This behavior is generally caused by viruses; one of which is SirCam virus, which modifies the .exe file association in registry.

Resolution
Method 1: Fixing the association settings automatically

Download exefix_xp.com utility(http://www.winhelponline.com/exefix_xp.com) and save to Desktop. Double-click the file to run it. This utility fixes the exefile association in the registry automatically.

Additional tip: To run the utility silently (without any prompts), use the -silent parameter. Open a Command window (Command.com) and type:

C:\Utilities\exefix_xp.com -silent

Assuming that the exefix_xp.com is placed in the C:\Utilities directory.
Method 2: Fixing the association settings using Registry editor

Click Start, Run and type Command
Type the following commands one by one:

cd\windows
regedit

If Registry Editor opens successfully, then navigate to the following key:

HKEY_CLASSES_ROOT \ exefile \ shell \ open \ command

Double-click the (Default) value in the right pane
Delete the current value data, and then type:

"%1" %*
(ie., quote-percent-one-quote-space-percent-asterisk.)

Navigate to:

HKEY_CLASSES_ROOT\.exe

In the right-pane, set (default) to exefile
Exit the Registry Editor.

If you're unable to launch Regedit.exe even from Command Prompt, try this:

copy regedit.exe regedit.com
regedit.com


at last i was able to solve the problem and everything is working as before..
thanks god.........

Thursday, May 19, 2011

Graph plot in java..

import java.awt.BasicStroke;
import java.awt.Color;
import java.io.FileOutputStream;

import org.jfree.chart.*;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.DeviationRenderer;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.xy.*;
import org.jfree.data.*;


public class xyLine{

public static void main(String arg[]){
XYSeries series = new XYSeries("Average Weight");
series.add(20.0, 20.0);
series.add(40.0, 25.0);
series.add(55.0, 50.0);
series.add(70.0, 65.0);
XYDataset xyDataset = new XYSeriesCollection(series);
JFreeChart chart = ChartFactory.createXYLineChart
("Performance test", "Encryption time", "Decryption time", xyDataset, PlotOrientation.VERTICAL, true, true, false);
chart.setBackgroundPaint (Color.white);
XYPlot plot = (XYPlot) chart.getPlot();
plot.setBackgroundPaint (Color.white);
plot.setDomainGridlinesVisible(true);
plot.setRangeGridlinesVisible(true);
plot.setDomainGridlinePaint(Color.blue);
plot.setRangeGridlinePaint(Color.green);
/*
DeviationRenderer renderer = new DeviationRenderer(true, false);
renderer.setSeriesStroke (0, new BasicStroke (3.0f, BasicStroke.CAP_ROUND,
BasicStroke.JOIN_ROUND));
renderer.setSeriesStroke (1, new BasicStroke (3.0f, BasicStroke.CAP_ROUND,
BasicStroke.JOIN_ROUND));
renderer.setSeriesStroke (2, new BasicStroke (3.0f, BasicStroke.CAP_ROUND,
BasicStroke.JOIN_ROUND));
renderer.setSeriesPaint(2, new Color(0x00, 0x00, 0x00));
renderer.setSeriesPaint(1, new Color(0x99, 0x00, 0x00));
renderer.setSeriesPaint(0, new Color(0x99, 0x99, 0x00));
renderer.setSeriesFillPaint(2, new Color(0x00, 0x00, 0x00));
renderer.setSeriesFillPaint(1, new Color(0x99, 0x00, 0x00));
renderer.setSeriesFillPaint(0, new Color(0x99, 0x99, 0x00));
renderer.setAlpha(0.25f);
plot.setRenderer(renderer);
*/
ValueAxis rangeAxis = plot.getRangeAxis();
rangeAxis.setTickMarkPaint(Color.black);




ChartFrame frame1=new ChartFrame("XYLine Chart",chart);
frame1.setVisible(true);
frame1.setSize(300,300);
}
}

sample on PyCrypto

####################################################################################
##
## author : dipankar dutta
## module need: http://www.voidspace.org.uk/downloads/pycrypto-2.3.win32-py2.7.zip
##
##
########################################################################################

from Crypto.Hash import MD5
from Crypto.Cipher import DES
from Crypto.Cipher import DES3
from Crypto import Random
from Crypto.PublicKey import RSA
import os



def hash(x):
m=MD5.new()
m.update(x)
print m.hexdigest()


def hashfile(filename):
h = MD5.new()
chunk_size = 8192
with open(filename, 'r') as f:
while True:
chunk = f.read(chunk_size)
if len(chunk) == 0:
break
h.update(chunk)
return h.hexdigest()




def encrypt_file(in_filename, out_filename, chunk_size, key, iv):
des3 = DES3.new(key, DES3.MODE_CFB, iv)

with open(in_filename, 'r') as in_file:
with open(out_filename, 'w') as out_file:
while True:
chunk = in_file.read(chunk_size)
if len(chunk) == 0:
break
elif len(chunk) % 16 != 0:
chunk += ' ' * (16 - len(chunk) % 16)
out_file.write(des3.encrypt(chunk))

def decrypt_file(in_filename, out_filename, chunk_size, key, iv):
des3 = DES3.new(key, DES3.MODE_CFB, iv)

with open(in_filename, 'r') as in_file:
with open(out_filename, 'w') as out_file:
while True:
chunk = in_file.read(chunk_size)
if len(chunk) == 0:
break
out_file.write(des3.decrypt(chunk))


def keygen():
random_generator = Random.new().read
key = RSA.generate(1024, random_generator)
print key.can_encrypt(),key.can_sign(),key.has_private()
return key

def RSAencrypt_file(in_filename, out_filename,pubkey):
with open(in_filename, 'r') as in_file:
with open(out_filename, 'w') as out_file:
chunk = in_file.read()
cipher=public_key.encrypt(chunk, 32) # encyption..
print cipher
out_file.write(str(cipher)) # strored as string hece tuple-->string


def RSAdecrypt_file(in_filename, out_filename, key):
with open(in_filename, 'r') as in_file:
with open(out_filename, 'w') as out_file:
string = in_file.read()
#-need convert string-->tuple
if string[0] + string[-1] == "()":
items = string[1:-1]
items = items.split(',')
print items
tuples=tuple(items)
print tuples
out_file.write(key.decrypt(tuples)) # decription..


def sign(msg,key):
hash = MD5.new(msg).digest()
signature = key.sign(hash, '')
return signature


def varify(msg,sign,pubkey):
hash = MD5.new(msg).digest()
return pubkey.verify(hash, sign)




#-simple hash--------
hash('dipankar')
hash('dipankar')

#---hash file---
print hashfile('input.txt');

#-----sysmmentic key encryption-----IV and Key is shared.......
##iv = Random.get_random_bytes(8)
##key='1234567890123456' # 16 byte.........
##f=open('input.txt', 'r')
##print 'input.txt: %s' % f.read()
##
##encrypt_file('input.txt', 'to_enc.enc', 8192, key, iv)
##f=open('to_enc.enc', 'r')
##print 'to_enc.enc: %s' % f.read()
##
##
##decrypt_file('to_enc.enc', 'to_enc.dec', 8192, key, iv)
##f=open('to_enc.dec', 'r')
##print 'to_enc.dec: %s' % f.read()
##

#-------Asymetic key encription..............
##
##key =keygen()
##print key
##
##f=open('input.txt', 'r')
##print 'Org here:: %s' % f.read()
##
##public_key = key.publickey()
##RSAencrypt_file('input.txt', 'to_enc.enc',public_key )
##f=open('to_enc.enc', 'r')
##print '\n\n\n\nCipher here:: %s' % f.read()
##
##
##RSAdecrypt_file('to_enc.enc', 'to_enc.dec', key)
##f=open('to_enc.dec', 'r')
##print '\n\nhurree get back here: %s' % f.read()
##

#--------------Digital signature-----------


text = 'dipankar'
key = keygen()
public_key=key.publickey()

signature = sign(text,key);

print varify(text,signature,public_key)

Thursday, May 5, 2011

Fun With Python: play tone when ur friend become online

=======play.py=========================

import pyaudio
import wave
import sys
def play():
chunk = 1024

x='C:/Documents and Settings/Dipankar/Desktop/Dropbox/IITR/Python Exp/PythonAudio/tone.wav'

wf = wave.open(x, 'rb')

p = pyaudio.PyAudio()

# open stream
stream = p.open(format =
p.get_format_from_width(wf.getsampwidth()),
channels = wf.getnchannels(),
rate = wf.getframerate(),
output = True)

# read data
data = wf.readframes(chunk)

# play stream
while data != '':
stream.write(data)
data = wf.readframes(chunk)

stream.close()
p.terminate()

==========================================
import xmpp
import sys
import time
import thread
import play
#this function for break the infinite loop-------or on log out--------
def StepOn(conn):
try:
conn.Process(1)
except KeyboardInterrupt:
return 0
return 1

def GoOn(conn):
while StepOn(conn):
pass
#---------------------------Sending SMS routine----------------------------------
def SendSMS(cl):
#for i in range(0,10):
cl.send(xmpp.Message( "dutta.dipankar08@gmail.com" ,"This is an Experimental WOrk..!!!!..My Gtalk Is now Automated...PLZ Config AI system" ))

##-------------------------------Reciving sms routine------------------------------------------------
def messageCB(cl,msg):
Sender=msg.getFrom()
print "Content: " + str(msg.getBody())
#print msg
#SendSMS(cl);
cl.send(xmpp.Message(Sender ,"his is an Experimental WOrk..!!!!..My Gtalk Is now Automated...PLZ Config AI system" ))
play.play()
##-------------------------------Presence sms routine------------------------------------------------
def presenceCB(conn,msg):
#print str(msg)
prs_type=msg.getType()
who=msg.getFrom()
status=msg.getStatus()
print msg.getType(),who,status
if prs_type == "subscribe":
conn.send(xmpp.Presence(to=who, typ = 'subscribed'))
#conn.send(xmpp.Presence(to=who, typ = 'subscribe'))


#----------update status1: TIMER---------------------------------------------
def updateStatus1(conn):
while(1):
localtime = time.asctime( time.localtime(time.time()) )
pres = xmpp.Presence()
pres.setStatus(str(localtime))
conn.send(pres)
time.sleep(1)
#-------------------ROTATE GOOGLE CHAT STATUS>>>..........................
#def updateStatus2(conn):
# Status= " My Gtalk Under Experiment ..Plz donot Ping now.. You may get Unexpected result.."
# while(1):
# pres = xmpp.Presence()
# pres.setStatus(Status)
# conn.send(pres)
# Status=Status[1:len(Status)]+Status[0:1]
# print Status
# time.sleep(.5)


def RECV_MSG(cl):
cl.RegisterHandler('message', messageCB)


#================================main program stat here===============
def main():
#userID = 'dutta.dipankar08@gmail.com'
userID = 'dutta.subhankar123@gmail.com'
password = 'xxxx'
ressource = 'Script'

jid = xmpp.protocol.JID(userID)
cl = xmpp.Client(jid.getDomain(), debug=[])

connection = cl.connect(('talk.google.com',5222))

if not connection:
sys.stderr.write('Could not connect\n')
else:
sys.stderr.write('Connected with %s\n' % connection)

auth = cl.auth(jid.getNode(), password, ressource)
if not auth:
sys.stderr.write("Could not authenticate\n")
else:
sys.stderr.write('Authenticate using %s\n' % auth)

cl.sendInitPresence(requestRoster=1)


# check connection
print cl.isConnected()

#send message--
#SendSMS(cl)

##reciving message.............
#RECV_MSG(cl)
cl.RegisterHandler('message', messageCB)


#---get presence CB........
cl.RegisterHandler('presence', presenceCB)


#------------change the status...----------DONE
try:
#thread.start_new_thread(updateStatus1,(cl,))
print 'hello'
except:
print " error is thread cration"

#--get contact list-----------------
#ros=cl.getRoster()
#for i in ros:
#print "a"

#run the main thread for ever...
GoOn(cl)

cl.disconnect()

main()

Tuesday, May 3, 2011

Atomated Gtalk using python

import xmpp
import sys
import time
import thread
#this function for break the infinite loop-------or on log out--------
def StepOn(conn):
try:
conn.Process(1)
except KeyboardInterrupt:
return 0
return 1

def GoOn(conn):
while StepOn(conn):
pass
#---------------------------Sending SMS routine----------------------------------
def SendSMS(cl):
#for i in range(0,10):
cl.send(xmpp.Message( "dutta.dipankar08@gmail.com" ,"This is an Experimental WOrk..!!!!.." ))

##-------------------------------Reciving sms routine------------------------------------------------
def messageCB(cl,msg):
print "Sender: " + str(msg.getFrom())
print "Content: " + str(msg.getBody())
#print msg
SendSMS(cl);

##-------------------------------Presence sms routine------------------------------------------------
def presenceCB(conn,msg):
#print str(msg)
prs_type=msg.getType()
who=msg.getFrom()
status=msg.getStatus()
print msg.getType(),who,status
if prs_type == "subscribe":
conn.send(xmpp.Presence(to=who, typ = 'subscribed'))
#conn.send(xmpp.Presence(to=who, typ = 'subscribe'))


#----------update status1: TIMER---------------------------------------------
#def updateStatus1(conn):
# while(1):
# localtime = time.asctime( time.localtime(time.time()) )
# pres = xmpp.Presence()
# pres.setStatus(str(localtime))
# conn.send(pres)
# time.sleep(1)
#-------------------ROTATE GOOGLE CHAT STATUS>>>..........................
#def updateStatus2(conn):
# Status= " Hi ! This is Dipankar..."
# while(1):
# pres = xmpp.Presence()
# pres.setStatus(Status)
# conn.send(pres)
# Status=Status[1:len(Status)]+Status[0:1]
# print Status
# time.sleep(.5)


def RECV_MSG(cl):
cl.RegisterHandler('message', messageCB)



def main():
#userID = 'dutta.dipankar08@gmail.com'
userID = 'dutta.subhankar123@gmail.com'
password = 'xxxxxxx'
ressource = 'Script'

jid = xmpp.protocol.JID(userID)
cl = xmpp.Client(jid.getDomain(), debug=[])

connection = cl.connect(('talk.google.com',5222))

if not connection:
sys.stderr.write('Could not connect\n')
else:
sys.stderr.write('Connected with %s\n' % connection)

auth = cl.auth(jid.getNode(), password, ressource)
if not auth:
sys.stderr.write("Could not authenticate\n")
else:
sys.stderr.write('Authenticate using %s\n' % auth)

cl.sendInitPresence(requestRoster=1)


# check connection
print cl.isConnected()

#send message--
#SendSMS(cl)

##reciving message.............
#RECV_MSG(cl)
cl.RegisterHandler('message', messageCB)


#---get presence CB........
cl.RegisterHandler('presence', presenceCB)


#------------change the status...----------DONE
try:
#thread.start_new_thread(updateStatus,(cl,))
print 'hello'
except:
print " error is thread cration"

#--get contact list-----------------
ros=cl.getRoster()
for i in ros:
print "a"

#run the main thread for ever...
GoOn(cl)

cl.disconnect()

main()

Sunday, May 1, 2011

How to create ebook using python

1. download all png file from Google books(discussed in my previous blog)
2. now lets discuss how to marge all png file into single pdf using python as below:
2 a)Download http://www.reportlab.com/ftp/reportlab-2.5.win32-py2.7.exe and install
in python lib.

2.b)write downl the following code for createing png to image as below:
import os
---------------------------------------------------
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Image

filename = './python-logo.png'

doc = SimpleDocTemplate("image.pdf", pagesize=letter)
parts = []
parts.append(Image(filename))
doc.build(parts)
---------------------------------------------------------
2.c) write following script to marge all pdf into single one:

#----join multiple pdf into single one...-----------------------
#Author : Dipankar Dutta

##Step 1: Install python and py python from http://pybrary.net/pyPdf/pyPdf-1.13.win32.exe






#Import...
from pyPdf import PdfFileWriter, PdfFileReader


## open writer.........
output = PdfFileWriter()
n= raw_input("enter the number of file to marge: ");
raw_input("Note that all file must reside in same dir: ");
name=raw_input("enter genearal file name eg. hello10.pdf ..enter hello: ");
outfilename=raw_input("enter the outputfile name: ");

for i in range(0,int(n)):

input = PdfFileReader(file(name+str(i)+'.pdf', "rb"))
for page in range(0,input.getNumPages()):
print "\tadding page %d" % page
output.addPage(input.getPage(page))





# finally, write "output" to document-output.pdf
outputStream = file(outfilename+".pdf", "wb")
output.write(outputStream)
outputStream.close()


step 3> Njoy..