http://www.precisejava.com/javaperf/j2ee/JDBC.htm#JDBC110
I found this very useful link on net.
I wrote a program to grab 5million rows of data from DB and to store it on my harddrive.
It took almost 12 hours
I used the following function from ResultSet to improve the performance.
resultSet.setFetchSize(2000);
By default the FetchSize is 10 rows, By varying size you see the performance change.
Below are the statistics for pulling 100000 rows
setFetchSize Minutes
10 12
2000 4.5
20000 2.6
100000 java.lang.OutOfMemoryError: requested array is larger than heap
Showing posts with label java. Show all posts
Showing posts with label java. Show all posts
Friday, October 14, 2011
Saturday, June 25, 2011
CachedRowSet
ResultSet resultSet = stmt.executeQuery(query); CachedRowSet crs = new CachedRowSetImpl();//com.sun.rowset.CachedRowSetImplcrs.populate(resultSet);
Access DB Connection from standalone application
public static Connection getDatabaseConn() throws NamingException{ Context ctx=null; Connection conn = null; Properties env = new Properties(); env.put(Context.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WLInitialContextFactory"); env.put(Context.PROVIDER_URL,"t3://127.0.0.1:7001"); ctx = new InitialContext(env); try { dataSource = (DataSource) ctx.lookup("ExtDevDB");//jndi datasource name} catch (NamingException e) { e.printStackTrace(); } try{ conn = dataSource.getConnection(); }catch(Exception e){ e.printStackTrace(); }finally{ } return conn; }
Use t3 protocol to connect Weblogic server.
Saturday, January 22, 2011
Degrees Minutes Seconds to Decimal Degrees
public class LongLat {
public static void main(String args[]){
double LongDouble=0;
double direction=0;
int checkDegree=0;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input=null;
System.out.println("Enter Longitude or Latitude");
try{
input=br.readLine().toUpperCase();
}catch(Exception e){
System.out.println("IO error");
System.exit(1);
}
Pattern p=Pattern.compile("[NEWS]");
Matcher m=p.matcher(input);
if(input.contains("N") || input.contains("E"))
direction=1;
else if(input.contains("W") || input.contains("S"))
direction=-1;
if(input.contains("N") || input.contains("S"))
checkDegree=90;
else if(input.contains("W") || input.contains("E"))
checkDegree=180;
input=m.replaceFirst("");
input=input.trim();
String[] LongDMS=input.split(" ");
if(!(Integer.parseInt(LongDMS[0])<=checkDegree)){
System.out.println("Degree should be less than "+checkDegree);
System.exit(1);
}
if(!(Integer.parseInt(LongDMS[1])<=60)){
System.out.println("Minutes should be in between 0 and "+60);
System.exit(1);
}
if(!(Integer.parseInt(LongDMS[2])<=60)){
System.out.println("Second should be in between 0 and "+60);
System.exit(1);
}
if(LongDMS.length==3)
LongDouble=Double.valueOf(LongDMS[0])+((Double.valueOf(LongDMS[1])*60)+Double.valueOf(LongDMS[2]))/3600;
LongDouble=LongDouble*direction;
System.out.println(LongDouble);
}
}
Enter Longitude or Latitude
W87 43 41
-87.72805555555556
Friday, November 26, 2010
Random number generator
private static int RandomNumberGenerator(int aStart, int aEnd, Random aRandom){ if ( aStart > aEnd ) { throw new IllegalArgumentException("Start cannot exceed End."); } long range = (long)aEnd - (long)aStart + 1; long fraction = (long)(range * aRandom.nextDouble()); int randomNumber = (int)(fraction + aStart); return randomNumber; }
Sending an Email
java.util.Properties props = new java.util.Properties();
props.put("mail.smtp.host", "here you have to give the smtp host address");
props.put("mail.smtp.port", "smtp port number, it may or may not required");
Session session = Session.getDefaultInstance(props, null);
// Construct the message
try {
Message msg = new MimeMessage(session);
String emailfrom=request.getParameter("emailfrom");
String emailto=request.getParameter("emailto");
String comment="Hi there";
msg.setContent(comment,"text/html");
msg.setFrom(new InternetAddress(request.getParameter("emailfrom")));
msg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(request.getParameter("emailto")));
msg.setSubject("Enter the subject here");
msg.setSentDate(new Date());
// Sends the message
Transport.send(msg);
response.getWriter().print("success");
} catch (AddressException e) {
// TODO Auto-generated catch block
response.getWriter().print("failed");
e.printStackTrace();
} catch (MessagingException e) {
// TODO Auto-generated catch block
response.getWriter().print("failed");
e.printStackTrace();
}
Sunday, November 21, 2010
How to use Proxy in java
Proxy proxy =null;
URL url;
String decodedXml=null;
DataInputStream inStream=null;
proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(ProxyAddress, ProxyPort));
// Above line creates proxy with given address and port
url = new URL(getUrl); // you need to give your url here
URLConnection conn = url.openConnection(proxy);// it creates a connection using proxy
String flag;
inStream = new DataInputStream(conn.getInputStream());
Monday, October 11, 2010
Friday, October 8, 2010
Calculating Time in milliseconds, in java
long start = System.currentTimeMillis();
float elapsedTimeMillis;
float elapsedTimeMillis;
Put the code here
elapsedTimeMillis = (System.currentTimeMillis()-start);
elapsedTimeMillis =elapsedTimeMillis/1000;
System.out.println("getting xml rowset"+elapsedTimeMillis);
Monday, March 29, 2010
Use of getServletContext()
When i was doing a project there was a necessity to send an object from one servlet to another servlet. Actually, i was implementing MVC architecture so you can understand in between servlets there is a JSP. So, here is the problem. How to forward an object between servlets?
I came up with an idea of putting the object into session. But, my brother told session is not at all a good idea because it takes lot of server resource. Later, I came up with an idea of using request object and faced trouble sending the objects in request object.
I was thing to implement the logic in different way so that i do not need to send the object to other servlet and i did it with the help of javascript.
Even after the completion of the project, i have question in my mind Is there any other way to send an object between servlets? i found the answer, that is getServletContext()
In servlet1
Resident r=new Resident();
...
...
getServletContext().setAttribute("Obj",r);
In servlet2
Object o= getServletContext().getAttribute("Obj");
Resident r=(Resident)o;
Wednesday, February 3, 2010
tricky question on switch-case
#include
int main()
{
int a=10;
switch(a)
{
case '1': // even if a=1 this case doest not work because it is checking for char '1';
printf("ONE\n");
break;
case '2':
printf("TWO\n");
break;
defa1ut:
printf("NONE\n");
}
return 0;
}
int main()
{
int a=10;
switch(a)
{
case '1': // even if a=1 this case doest not work because it is checking for char '1';
printf("ONE\n");
break;
case '2':
printf("TWO\n");
break;
defa1ut:
printf("NONE\n");
}
return 0;
}
The above program compiles with out any error, but when you run it, it does not give any output
The reason is spelling of key word default is wrong.
Java basic program
Here i am demonstrating a simple program
public class test{public static void main(String args[]){System.out.println("Hello");}}
Save the above file as test.java
Compile the above program: javac test.java
run the program: java test
Output would be: Hello
In Java we write every thing in class. A class should contain a main method which is static and should return void. String args[] is used to take command line arguments.
so far we learned basic program we into some more depth
we will learn different ways of calling a method
public class test{public static void main(String args[]){int i;test1 t=new test1(); // creating a instance of test1i=t.normal(); // calling a method in class test1System.out.println(i);}}class test1 // this class should not be public{public int normal(){try{return 10;}finally{return 20;}}}
Save the above file as test.java
Compile the above program: javac test.java
run the program: java test
Output would be: 20
Above program we wrote two classes, and accessing a method in one class from another class.
public class test{public static int normal(){ // this method should be statictry{return 10;}finally{return 20;}}public static void main(String args[]){int i;test1 t=new test1(); // creating a instance of test1i=t.normal(); // calling a method in class test1System.out.println(i);}}
Save the above file as test.java
Compile the above program: javac test.java
run the program: java test
Output would be: 20
In the above above program we wrote two methods in one class and both method are static. We made normal method static because we want to access it from main method.
Friday, May 8, 2009
Singleton
Singleton design patters are used where there is only one instance of an object is required.
Here is an example of singleton class.
public class singleton
{
private static singleton instance=null;
static public singleton getInstance()
{
if(instance==null)
instance=new singleton();
return instance;
}
private singleton()
{}
.
.
.
.
}
Here is an example of singleton class.
public class singleton
{
private static singleton instance=null;
static public singleton getInstance()
{
if(instance==null)
instance=new singleton();
return instance;
}
private singleton()
{}
.
.
.
.
}
Friday, March 27, 2009
Remote Method Invocation (RMI)
Following file are needed to put on Client
Conversion.java
ConversionClient.java
Data.java
On server:
Conversion.java
ConversionImpl.java
ConversionServer.java
Data.java
Conversion.java
public interface Conversion extends java.rmi.Remote
{
public Data conversion1(Data km) throws java.rmi.RemoteException;
public Data conversion2(Data km) throws java.rmi.RemoteException;
}
Data.java
import java.io.*;
public class Data implements Serializable {
private static final long serialVersionUID = 1L;
private float km;
private int miles;
private long foot;
public Data() {
}
public float getKm() {
return km;
}
public void setKm(float km) {
this.km = km;
}
public int getMiles() {
return miles;
}
public void setMiles(int miles) {
this.miles =miles ;
}
public long getFoot() {
return foot;
}
public void setFoot(long foot) {
this.foot = foot;
}
}
ConversionClient.java
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.net.MalformedURLException;
import java.rmi.NotBoundException;
import java.io.*;
import java.util.*;
import java.net.*;
public class ConversionClient
{
public static void main(String[] args) throws Exception
{
// Converting the hostname to ip address
InetAddress ia=InetAddress.getByName(args[0]);
// Looking up for the remote object in remote server
Conversion c=(Conversion) Naming.lookup("rmi://"+ia.getHostAddress()+":3000/ConversionServer");
// Enter kilometers
System.out.println("Enter Kilometers\n");
Scanner ob=new Scanner(System.in);
float km=ob.nextFloat();
System.out.println("val is "+km);
Data d=new Data();
d.setKm(km);
//passing values to two methods
int s=c.conversion1(d).getMiles();
long t=c.conversion2(d).getFoot();
// printing out the values
System.out.println(km+"Kilometers ="+s+"Miles ");
System.out.println(km+"Kilometers ="+t+"Foot ");
}
}
ConversionImpl.java
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.net.MalformedURLException;
import java.rmi.NotBoundException;
public class ConversionImpl extends java.rmi.server.UnicastRemoteObject implements Conversion
{
private static final long serialVersionUID = 1L;
public ConversionImpl() throws java.rmi.RemoteException
{
super();
}
// converts from Km to Miles
public synchronized Data conversion1(Data value) throws java.rmi.RemoteException
{
int r=(int)Math.round(value.getKm() * 0.62137119);
//System.out.println("r="+r);
value.setMiles(r);
return value;
}
// converts from Km to Foot
public synchronized Data conversion2(Data value) throws java.rmi.RemoteException
{
long r=(long)Math.round(value.getKm() * 3280.8399);
//System.out.println("r="+r);
value.setFoot(r);
return value;
}
}
ConversionServer.java
// This program is used to put the object referrence in rmiregistry
import java.rmi.*;
import java.net.*;
public class ConversionServer
{
public static void main(String args[])throws Exception
{
Conversion c=new ConversionImpl();
InetAddress ia=InetAddress.getLocalHost();
String h=ia.getHostName();
Naming.rebind("rmi://"+ia.getHostAddress()+":3000/ConversionServer",c); // putting the object referrence in rmi registry
}
}
To Compile:
1.a. Copy the folder "client" to the machine where you want to run client.
b. Go to the folder "client" and run the command
% javac *.java
2.a. Copy the folder "server" to the machine where you want to run the server.
b. Go to the folder "server" and run the command
% javac *.java
To Run the program:
1.On server machine
a. Open a window to start rmiregistry
% rmiregistry 3000
b. Go to the folder "server"
c. Start the Server on another window
java ConversionServer
2.a Go to the folder "client" in client machine
b. Start the client using the command
java ConversionClient
Friday, February 27, 2009
I/O in Java
To read Float from command line:
import java.util.Scanner;
Scanner s=new Scanner(System.in);
float f=s.nextFloat();
Scanner: To scan the text
System.in: To receive data from standard input stream
Subscribe to:
Posts (Atom)