Thursday, August 31, 2006

Connect to a network through VPN

Connect to a network through VPN

  1. Click My Network Places
  2. Click View network connection
  3. Click Create A New Connection
  4. Click Next
  5. Select Connect to the network at my workplace
  6. Select VPN Connection
  7. Enter a name
  8. Select Do not dial the initial connection
  9. Enter IP of the network
  10. Click finish
  11. Use user id and password to login the network

Friday, August 25, 2006

Run Java class in jar file

Specify a default class to run in jar file:
Code the class name and classpath in manifest.txt file (use space between classpath items):

Main-Class: CompileServlet
Class-path: /QIBM/ProdData/OS400/jt400/lib/jt400Native.jar /context/WEB-INF/lib/log4j-1.2.9.jar

Then merge this manifest file with the jar file:

C:\temp>jar muf manifest.txt mygenerator.jar


To run the class:

java -jar mygenerator.jar p1 p2

Wednesday, August 23, 2006

SQL server 2005 JDBC driver name

Microsoft uses a new JDBC driver for SQL server 2005. The driver is contained in sqlserver.jar file. The driver can be downloaded from Microsoft SQL Server 2005 JDBC Driver. The driver name and the connection url string are:

com.microsoft.sqlserver.jdbc.SQLServerDriver

jdbc:sqlserver:



For SQL server 2003, the driver name and the connection url string are:

com.microsoft.jdbc.sqlserver.SQLServerDriver

jdbc:microsoft:sqlserver:



When using the old driver name to access SQL server 2005, the java code gets this error:

java.sql.SQLException: The incoming tabular data stream (TDS) remote procedure call (RPC) protocol stream is incorrect. Parameter 1 (""): The supplied value is not a valid instance of data type ...

Monday, August 21, 2006

Break a List into a list of lists

List records contains cells. We break it into lists of size gridCol and store these lists in List grid. (Note in for loop we have a variable n for performance).

int gridCol = 5;
List grid = new ArrayList();
for (int i = 0, n = records.size(); i < n; i += gridCol) {
int toIndex = i + gridCol > n ? n : i + gridCol;
grid.add(records.subList(i, toIndex));
}

Thursday, August 17, 2006

Test web page multiple thread support


package test2;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.InputStreamReader;
import java.net.URL;

public class ThreadSafetyTest implements Runnable {

public static void main(String args[]) {
long t0 = System.currentTimeMillis();
Runnable run = new ThreadSafetyTest();

/** 20 consecutice accesses used ms */
// for (int i = 0; i < 20; i++) {
// run.run();
//}

/** 20 concurrent accesses used ms (the last thread time */
for (int i = 0; i < 10; i++) {
Thread thread = new Thread(run);
// thread.setDaemon(true); // so program can exit
thread.start();
}

long t1 = System.currentTimeMillis();
System.out.println("Program time used = " + (t1 - t0) + " ms.");
}

public void run() {
long t0 = System.currentTimeMillis();
DataInputStream dis;

try {
String urlString = "http://localhost:8011/mrcjava/servlet/MRCJAVALIB.I00116a";
//String urlString = "http://www.ibm.com";
URL url = new URL(urlString);
dis = new DataInputStream(url.openConnection().getInputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(dis));
String total = "";
String line = "";
while ((line = in.readLine()) != null) {
total += line;
}
in.close();

long t1 = System.currentTimeMillis();
System.out.println("Response size = " + total.length()
+ ", time used = " + (t1 - t0) + " ms.");
} catch (Exception e) {
System.out.println(e);
}
}

}


Lets run it against a server on a windows XP box.

When accessing a page that does not support multiple threading (I00116s) the output is:

Response size = 16602, time used = 531 ms.
Response size = 16602, time used = 969 ms.
Response size = 16602, time used = 1391 ms.
Response size = 16602, time used = 1766 ms.
Response size = 16602, time used = 2266 ms.
Response size = 16602, time used = 2672 ms.
Response size = 16602, time used = 3078 ms.
Response size = 16602, time used = 3453 ms.
Response size = 16602, time used = 3844 ms.
Response size = 16602, time used = 4234 ms.

You can see the longest response time is 4,234 mini seconds.

When accessing a page that supports multiple threading (I00116a) the output is:

Response size = 17399, time used = 281 ms.
Response size = 17399, time used = 359 ms.
Response size = 17399, time used = 672 ms.
Response size = 17399, time used = 719 ms.
Response size = 17399, time used = 875 ms.
Response size = 17399, time used = 922 ms.
Response size = 17399, time used = 953 ms.
Response size = 17399, time used = 953 ms.
Response size = 17399, time used = 969 ms.
Response size = 17399, time used = 969 ms.

You can see the longest response time is 969 mini seconds.

Run Threads in Java


package test2;

/**
* The output is something like 0 3 4 1 2 5 6 7 8 9
* Note all threads are associated with one object.
*/
public class ThreadTest implements Runnable {
int counter;

public static void main(String args[]) {
Runnable run = new ThreadTest();
for (int i = 0; i < 10; i++) {
Thread thread = new Thread(run);
thread.setDaemon(true); // so program can exit
thread.start();
}
}

public void run() {
System.out.println(counter++);
for (int j = 0; j < 100000000; j++) {
String x = "" + Math.sqrt(1.2111);
}
System.out.println( " counter=" + counter++);
}
}

Request web page in Java example


long t0 = System.currentTimeMillis();
DataInputStream dis;
try {
String urlString = "http://www.ibm.com";
URL url = new URL(urlString);
dis = new DataInputStream(url.openConnection().getInputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(dis));
String total = "";
String line = "";
While ((line = in.readLine()) != null) {
total += line;
}
in.close();
} catch (Exception e) {
System.out.println(e);
}
long t1 = System.currentTimeMillis();
System.out.println("time used = " + (t1-t0) + " ms.");

You can Writing to a URLConnection too.

Monday, August 14, 2006

Java Strategy Design Pattern

See comments for three different types of behaviors:

public abstract class Duck {
FlyBehavior flyBehavior;
QuackBehavior quackBehavior;
public Duck() {
}
public void setFlyBehavior (FlyBehavior fb) {
flyBehavior = fb;
}
public void setQuackBehavior(QuackBehavior qb) {
quackBehavior = qb;
}
/******************************************************
* May vary from duck to duck.
*****************************************************/
public void performFly() {
flyBehavior.fly();
}
public void performQuack() {
quackBehavior.quack();
}
/******************************************************
* Common to all ducks
*****************************************************/
public void swim() {
System.out.println("All ducks float, even decoys!");
}
/******************************************************
* Different for all ducks
*****************************************************/
abstract void display();
}

This is an implementation. See how it got three different types of behaviors.

/**
* 1. Provide fly and quack behaviors
* 2. Impliment display behavior
* 3. Inherit swim behavior
*/
public class RubberDuck extends Duck {

public RubberDuck() {
flyBehavior = new FlyNoWay();
quackBehavior = new Squeak();
}
public void display() {
System.out.println("I'm a rubber duckie");
}
}

Friday, August 11, 2006

Java regular expression example

Example 1: match ${*}

package test;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegExpr {
public static void main(String args[]) {
Pattern pat = Pattern.compile("\\Q${\\E[^}]*}");// ${.*}
String input = "123 ${abc} 456 ${xyz} abc ";
Matcher matcher = pat.matcher(input);

while (matcher.find()) {
int start = matcher.start();
int end = matcher.end();
System.out.println("start=" + start + ", end=" + end
+ ", match string=" + input.substring(start, end));
}
}
}

Output:
start=4, end=10, match string=${abc}
start=15, end=21, match string=${xyz}



Example 2: match [*]

package test;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegExpr2 {
public static void main(String args[]) {

Pattern pat = Pattern.compile("\\Q[\\E[^]]*]");// [xxx]
String input = "123 [abc] 456 [xyz] abc ";
Matcher matcher = pat.matcher(input);

while (matcher.find()) {
int start = matcher.start();
int end = matcher.end();
System.out.println("start=" + start + ", end=" + end
+ ", match=" + input.substring(start+1, end-1));
}
}
}

Output:
start=4, end=9, match string=abc
start=14, end=19, match string=xyz

Wednesday, August 09, 2006

Install MS SQL Server for jdbc

- Install MSDE (MS SQL Server developer edition) server on XP
- On server open enterprise manager, right click server name and select properties. Click on the Security tab. Under Authenication, select SQL Server and Windows. That's Mixed Mode, meaning it will allow Windows Authenication mode as well as logins defined in the database.
- To define your own login to the DB, go to security in the expanding tree. Then click on Logins. Right click on the blank space in the right pane and select new Login. Type a name, and select SQL Server Authenication, then type a password. On the next tab (Server Roles), check the System Administrators box. Now click OK.
- Under general tab, network configuration needs to have correct port (default 1433)

Java code:
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
String sys = "jdbc:microsoft:sqlserver://192.168.0.131";
conn = DriverManager.getConnection(sys, "n", "p");
System.out.println("Connecting to: " + sys);
Statement stmt = conn.createStatement();
String sql = "SELECT fname , lname FROM pubs.dbo.employee ";
ResultSet rs = stmt.executeQuery(sql);

Verify TCP connectivity for MS SQL

Installed MS SQL Server on a laptop but can not connect to it. Get error:
"java.sql.SQLException: [Microsoft][SQLServer 2000 Driver for JDBC]Error establishing socket".

To verify TCP connectivity for MS SQL Server:
C:\ >telnet 192.168.0.131 1433
Connecting To 192.168.0.131...Could not open connection to the host, on port 143
3: Connect failed

If I telnet to another MS SQL server:
C:\ >telnet 192.168.0.151 1433

The screen goes blank, indicating telnet OK.

Installing a service pack solved the problem. Now telnet gets a blank screen instead of error message. JDBC code also worked.

Monday, August 07, 2006

Find all jar files in a directory

All jar files in a directory:


import java.io.File;
import java.io.FilenameFilter;

public class AllFilesInDir {

public static void main(String[] args) {
String cp = getClasspath("c:/temp/WEB-INF/lib");
System.out.println("cp=" + cp);
}

private static String getClasspath (String jarlib) {
String cp = "";
File dir = new File(jarlib);
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".jar");
}
};
String[] children = dir.list(filter);
if (children == null) {
return cp;
}
String os = System.getProperty("os.name");
int pos = os.indexOf("400");
String deli = pos < 0 ? ";" : ":";
for (int i=0; i<children.length; i++) {
String f = children[i];
cp += f + deli;
//System.out.println("file=" + f);
}

return cp;
}
}

Friday, August 04, 2006

Copy File in Java

Copy disk file:


private void copyFile(String fromDir, String todir, String frfile, String tofile) {

String fromFile = fromDir + sep + frfile;
String outFileName = todir + sep + tofile;
try {
FileChannel src = new FileInputStream(fromFile).getChannel();
FileChannel dst = new FileOutputStream(outFileName).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
log.info("Created file: " + outFileName);
} catch (IOException e) {
log.error("Error copying file " + frfile + " from " + fromDir, e);
}
}

Notes

this:jin..3/ir..go../iutop.
manning:bruce/ir..ma..

aim pro: bruceatmrc/ir.airo/somto

forum.java.sun.com: mrcemail i...s.n
forum.springframework.org brucejin i...s..k
System iNetwork brucejin i...p..h

apress mrcemail ir......