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..

Play with pyPDF

#----Basic Of Pdf operartion using python-----------------------
#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()
input1 = PdfFileReader(file("document.pdf", "rb"))

# print the title of document1.pdf
print "title = %s" % (input1.getDocumentInfo().title)

print input1.getNumPages();

#add page 1 from input1 to output document, unchanged
output.addPage(input1.getPage(0))

# add page 2 from input1, but rotated clockwise 90 degrees
output.addPage(input1.getPage(1).rotateClockwise(90))

#add page 3 from input1, rotated the other way:
output.addPage(input1.getPage(2).rotateCounterClockwise(90))
# alt: output.addPage(input1.getPage(2).rotateClockwise(270))

# add page 4 from input1, but first add a watermark from another pdf:
page4 = input1.getPage(9)
watermark = PdfFileReader(file("watermark.pdf", "rb"))
wtmrk=page4.mergePage(watermark.getPage(0))
#output.addPage(wtmrk)


# add page 5 from input1, but crop it to half size:
page5 = input1.getPage(4)
page5.mediaBox.upperRight = (
page5.mediaBox.getUpperRight_x() / 2,
page5.mediaBox.getUpperRight_y() / 2
)
output.addPage(page5)

# print how many pages input1 has:
print "document1.pdf has %s pages." % input1.getNumPages()



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

Wednesday, April 27, 2011

Download Books from google book(tested/working)

This is the most powerful and stable way to download Google Book. You can easily download any book from books.google.com using Greasemonkey script. Just follow the simple steps below.


1 This hack only works with firefox browser. Make sure you install firefox browser.

2 Now install Greasemonkey Script
3.restart firefox
3 then install Google book downloader userscript.

4 Install Flashgot to firefox browser
5. restart your firefox browser.
6 Search any book on books.google.com and you’ll notice a download button at the sidebar as shown in screenshot.
7. Click the download button to download the images of each. Select the pages you wish to download and then right click and select FlashGot Selection to download the selected pages.
8. use igame to pdf converter to convert all into single pdf file

9.Njoy..

Sending Automated email in JSP/Java

This summary is not available. Please click here to view the post.

Wednesday, April 20, 2011

Upload files using jsp


<%@ page import="java.io.*" %>
<%
String contentType = request.getContentType();
System.out.println("Content type is :: " +contentType);
if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0))
{
DataInputStream in = new DataInputStream(request.getInputStream());
int formDataLength = request.getContentLength();
byte dataBytes[] = new byte[formDataLength];
int byteRead = 0;
int totalBytesRead = 0;
while (totalBytesRead < formDataLength)
{
byteRead = in.read(dataBytes, totalBytesRead, formDataLength);
totalBytesRead += byteRead;
}
String file = new String(dataBytes);
String saveFile = file.substring(file.indexOf("filename=\"") + 10);
//out.print("FileName:" + saveFile.toString());
saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
//out.print("FileName:" + saveFile.toString());
saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,saveFile.indexOf("\""));
//out.print("FileName:" + saveFile.toString());
//out.print(dataBytes);
int lastIndex = contentType.lastIndexOf("=");
String boundary = contentType.substring(lastIndex + 1,contentType.length());
//out.println(boundary);
int pos;
pos = file.indexOf("filename=\"");
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
int boundaryLocation = file.indexOf(boundary, pos) - 4;
int startPos = ((file.substring(0, pos)).getBytes()).length;
int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
saveFile = "D:\\java\tomcat5\\webapps\\ROOT\\images\\" + saveFile;
FileOutputStream fileOut = new FileOutputStream(saveFile);
//fileOut.write(dataBytes);
fileOut.write(dataBytes, startPos, (endPos - startPos));
fileOut.flush();
fileOut.close();
out.println("File saved as " +saveFile);
}
%>
















Select a file to upload :










Read and write file in jsp

<%@ page import="java.io.*" %>


Read write file JSP



<%
String fileName=getServletContext().getRealPath("jsp.txt");

File f=new File(fileName);

InputStream in = new FileInputStream(f);

BufferedInputStream bin = new BufferedInputStream(in);

DataInputStream din = new DataInputStream(bin);
StringBuffer sb=new StringBuffer();
while(din.available()>0)
{
sb.append(din.readLine());
}

try {
PrintWriter pw = new PrintWriter(new FileOutputStream("c:/file.txt"));// save file
pw.println(sb.toString());
pw.close();
} catch(IOException e) {
e.getMessage();
}

in.close();
bin.close();
din.close();
%>
Successfully write file

Tuesday, April 19, 2011

sqlite.JDBC Sample code..

//run by
//java -classpath ".;sqlite-jdbc-3.5.7.jar" Sample

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


class Test
{

String path="jdbc:sqlite:C:/Documents and Settings/Dipankar/Desktop/Dropbox/mq/sample.db";

//=======================logic strat from here add user..===================[DONE]

public void adduser(String username,String filename,String content)
{

// load the sqlite-JDBC driver using the current class loader
Connection connection = null;



//auto calculete id
int uid=0;
try{
connection = DriverManager.getConnection(path);
Statement statement1 = connection.createStatement();
ResultSet rs1=statement1.executeQuery("select count(*) from userinfo");
uid=rs1.getInt(1)+1;
}
catch(Exception e)
{
System.out.println("Error here");
}
finally
{
try
{
if(connection != null)
connection.close();
}

catch(SQLException e)
{
// connection close failed.
System.err.println(e);
}
}
System.out.println("insert into userinfo values("+uid+",'"+username+"','"+filename+"','"+content+"')");









try
{

connection = DriverManager.getConnection(path);
Statement statement = connection.createStatement();

statement.executeUpdate("insert into userinfo values("+uid+",'"+username+"','"+filename+"','"+content+"')");
}
catch(SQLException e)
{
// if the error message is "out of memory",
// it probably means no database file is found
System.err.println(e.getMessage());
}
finally
{
try
{
if(connection != null)
connection.close();
}

catch(SQLException e)
{
// connection close failed.
System.err.println(e);
}
}



}
//=======================END==================================================================





//=======================logic strat from here view user..===================[DONE]
public void showinfo(int userid)
{



// load the sqlite-JDBC driver using the current class loader
Connection connection = null;


try
{

connection = DriverManager.getConnection(path);
Statement statement = connection.createStatement();

ResultSet rs = statement.executeQuery("select * from userinfo where userid="+userid);
while(rs.next())
{
// read the result set
System.out.println("id = " + rs.getInt("userid"));
System.out.println("name = " + rs.getString("username"));
System.out.println("finemane = " + rs.getString("filename"));
System.out.println("file conetct = " + rs.getString("filecontent"));

}

}
catch(SQLException e)
{
// if the error message is "out of memory",
// it probably means no database file is found
System.err.println(e.getMessage());
}
finally
{
try
{
if(connection != null)
connection.close();
}

catch(SQLException e)
{
// connection close failed.
System.err.println(e);
}
}



}
//=======================END===================================================================


//=======================logic strat from here view user..===================[DONE]
public void removeuser(int userid)
{

// load the sqlite-JDBC driver using the current class loader
Connection connection = null;


try
{

connection = DriverManager.getConnection(path);
Statement statement = connection.createStatement();

statement.executeUpdate("delete from userinfo where userid="+userid);

}
catch(SQLException e)
{
// if the error message is "out of memory",
// it probably means no database file is found
System.err.println(e.getMessage());
}
finally
{
try
{
if(connection != null)
connection.close();
}

catch(SQLException e)
{
// connection close failed.
System.err.println(e);
}
}

}

//=======================END===================================================================


}

public class TestDB
{


public static void main(String[] args) throws ClassNotFoundException
{
// load the sqlite-JDBC driver using the current class loader
Class.forName("org.sqlite.JDBC");

Test x= new Test();
x.showinfo(0);
}
}

Monday, April 18, 2011

Java Fille I/0

import java.io.*;

public class FileReader {
public static void main (String[] args) {
System.out.println ("Program to demonstrate reading from a file");
BufferedReader br = null;
String fileName = args[0];
// If an error occurs, go to the "catch" block
try {
// FileInputStream fis = new FileInputStream (fileName);
FileReader fis = new FileReader (fileName);
br = new BufferedReader (fis);
// continue to read lines while there are still some left to read
while ( br.ready() ) {
System.out.println (br.readLine());
}
// Close the input stream
br.close();
} catch (Exception e) {
// Handle any error in opening the file
System.err.println("File input error");
}
} // End of main method
} // End of the class FileReader

Monday, March 21, 2011

Installing Flash Player Plugin on Firefox without having Administrator Access or Premissions

In the cybercafe in our hostel , i face this problem

in CC , mozila firefox is install in each computer but flash player was not install . as admin permission is not given to us, we cannot install flash player their. they make this thing to restrict from viewing Youtube video in CC.

you cannot install adobe flash player without admin permission.

but there is an alternative way to add flash plugin in firefox, shown step by step as below
it does not require any Admin permission,

This is how I managed to install it without administrator permissions:
step 1: Download the XPI archive of the Flash Player Plugin to your hard disk (right click on the download link then "Save link as.."). XPI archives are only ZIP files containing the files used by the plugins. A of the plugin is also available http://fpdownload.macromedia.com/get/flashplayer/xpi/current/flashplayer-win.xpi

So you can safely rename the file you just downloaded, called flashplayer-win.xpi, into flashplayer-win.zip (you are changing its extension from .xpi to .zip)


step 2: Extract the files in the archive. You can use any program capable of opening .zip files (WinZip, WinRAR or the free and great 7-zip). There are also websites which can uncompress archives: wobzip.org.

step 3:
Copy the files flashplayer.xpt and NPSWF32.dll to %APPDATA%\Mozilla\Plugins\

%APPDATA% is not a real folder. It's an alias. By inserting it in your windows explorer address bar, you'll be redirected to the real folder which holds your applications profiles and settings. The location of this folder depends on various setting that's why we need the alias and not an absolute path.


You can open this folder simply choosing "Start → Run → Type in %APPDATA% → OK".
In case you don't have a Plugins folder you can create one and place your files there.


step 4:

Restart Firefox

last step:..


Enjoy your flash websites!

Why this blog:

Art of the Everyday Experience is my second blog. In this blog i will provide some problem which i face in my life and solution to over come them...
This is something related to computer problem internet problem., hacking and lot's more..

if u find any better solution ..please post the solution as comment

your comment and suggestions will be highly appreciated...




thankyou
-DD

Download tips from Esnips

here i will give a tips to download file from esnips without install their software...

u can do this like as below..:

step 0:
find the URL from address bar

http://www.esnips.com/doc/091ce370-a0f9-4dd0-96c4-357d22fa8697/Sera-Satyajit

Step 1: remove "
Sera-Satyajit" [basically the end part of the link]

Step 2: change doc to nsdoc

eg;
http://www.esnips.com/doc/091ce370-a0f9-4dd0-96c4-357d22fa8697/
converted to
http://www.esnips.com/nsdoc/091ce370-a0f9-4dd0-96c4-357d22fa8697/

Step 3: add "ts_id/1210669366469/ns_flash/file1.mp3?action=forceDL" at the end of the string..


so finally ur link should look like this:
http://www.esnips.com/nsdoc/091ce370-a0f9-4dd0-96c4-357d22fa8697/ts_id/1210669366469/ns_flash/file1.mp3?action=forceDL


Step 4:
Add this link in IDM:
open IDM:
-->Add URl
--->paste the above url
--> Download and Njoy...