Sunday, December 16, 2007

linux common command

tcpdump -i eth1 -XX src host ip
ssh -L :localport:destinationIP:destinationPort username -pSSHPort -NnTv
sudo mount /dev/sdb1 /media/usbdisk/


iptables -t nat -D PREROUTING -s 192.168.0.140 -p tcp -m tcp --dport 3335 -j DNAT --to-destination 10.100.100.111:3068
ptables -t nat -A PREROUTING -s 192.168.0.140 -p tcp -m tcp --dport 3335 -j DNAT --to-destination 10.100.100.111:3068
sudo route add -net 10.100.0.0 mask 255.255.0.0 gw 192.168.0.24

du -h /home/engine/tomcat/ --max-depth=1
vim /etc/cron.daily/backup

sudo vim /etc/rc.local
netstat -a -n

sudo iptables-restore < /etc/iptables

tar -zxvf test.gz
tar -ztvf maskan.gz
tar -zcvf test test.gz

cut -d ' ' -f 6-6


install bin
chmod +x jre-1_5_0_14-linux-i586.rpm.bin
./jre-1_5_0_14-linux-i586.rpm.bin

sudo usermod -g admin peyman


sudo apt-get install -f
dpkg -i ymessenger.deb

install rpm
sudo rpm -Uvh jre-1_5_0_14-linux-i586.rpm

Wednesday, December 12, 2007

kannel url commands(kentBeck)

stopping smsc box: http://127.0.0.1:13000/cgi-bin/stop-smsc?password=&smsc=
starting smsc box: http://127.0.0.1:13000/cgi-bin/start-smsc?password=&smsc=
status: http://127.0.0.1:13000/cgi-bin/status?password=

Wednesday, November 14, 2007

j2me, Permissions

MIDlets must have permission to perform sensitive operations, like connecting to the network. Permissions have specific names, and MIDlet suites can indicate their need for certain kinds of permissions through attributes in the MIDlet suite descriptor.

In the J2ME Wireless Toolkit, you can add these permission attributes to a project by clicking on the Settings... button in KToolbar. Select the Permissions tab. The MIDlet-Permissions box shows permissions which the MIDlet must possess, while the MIDlet-Permissions-Opt box contains permissions that the MIDlet would like to have but does not need absolutley.

javax.microedition.io.PushRegistry,

javax.wireless.messaging.sms.receive,

javax.wireless.messaging.sms.send,

javax.microedition.io.Connector.sms,

javax.microedition.io.Connector.socket


j2me jad or jad

The following are required application attributes, some of which must be defined in the JAD file, and others in the JAR manifest:

  • MIDlet-Name: Mandatory in JAD, optional in manifest.
  • MIDlet-Version: Mandatory in JAD, optional in manifest. Format is Major.Minor[.Micro].
  • MIDlet-Vendor: Mandatory in JAD, optional in manifest.
  • MIDlet-Jar-URL: Mandatory in JAD.
  • MIDlet-Jar-Size: Mandatory in JAD.
  • MIDlet-: For each MIDlet. Optional in JAD, required in manifest.
  • MicroEdition-Profile: Optional in JAD, mandatory in manifest.
  • MicroEdition-Configuration: Optional in JAD, mandatory in manifest.

The following are optional attributes that can be defined in the JAD or manifest:

  • MIDlet-Description: application description.
  • MIDlet-Icon: application's icon.
  • MIDlet-Info-URL: URL for MIDlet suite information page.
  • MIDlet-Data-Size: Minimum required data space.
  • MIDlet-Permissions: Requested permissions.
  • MIDlet-Permissions-Opt: Requested optional permissions.
  • MIDlet-Push-: , , . Push static registration.
  • MIDlet-Install-Notify: URL for installation notifications..
  • MIDlet-Delete-Notify: URL for deletion notifications.
  • MIDlet-Delete-Confirm: User prompt for deletions.

The following two attributes are mandatory for trusted MIDlets, and must be defined in the JAD file:

  • MIDlet-Jar-RSA-SHA1: defines the JAR signature
  • MIDlet-Certificate--: defines the public key certificate

Sunday, October 28, 2007

mysql grant privileges

GRANT ALL PRIVILEGES ON DATABASENAME.* TO 'USERNAME'@'HOST' identified by 'PASSWORD';
flush privileges;

Sunday, October 14, 2007

java set connection timeout

System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
System.setProperty("sun.net.client.defaultReadTimeout", "10000");

Thursday, October 4, 2007

java exit signal handling

Approximately a year ago, I wrote a newsletter about hooking into the shutdown call. In that newsletter, I rather snidely remarked that the shutdown process had some deficiencies, which rendered it useless for situations where you want to abort the shutdown process and go back to the program. Once you're in shutting down state, the program will die.

After I published that newsletter, a South African friend, James Pereira, sent me a code snippet that used OS signals directly for detecting when the program was being closed. You can use this mechanism to write your own shutdown hook mechanism (even for JDK 1.2), and put in whatever features you need.

The code that he sent me used some classes from the sun.* packages to achieve this. Warning: The classes in the sun.* package hierarchy can be changed at the whim of Sun's fancy. In addition, you will probably not find a sun.* hierarchy in any VMs except Sun's, though I have not looked yet. The package that James pointed me to was sun.misc, containing a flea-market (i.e. jumble-sale) of classes, some useful, others badly designed. You've been warned - so please don't whinge if this does not work exactly like this on your IBM / MS / whatever VM.

When you press Ctrl+C in the command window, an OS signal is generated called SIGINT. This is the same on Windows and Unix. When you kill a program by pressing the little cross, or using your task manager, a SIGTERM signal is sent to your program, and it will not be back! What we can do is link into the signal handler and handle that signal any way we want to. For example:

import sun.misc.Signal;
import sun.misc.SignalHandler;

/**
* The idea for this code came from James Pereira, this code
* looks quite different to the well-structured, logically
* named class he sent me.
* The idea is that we register a handler for a Ctrl+C
* signal and then handle it.
*/

public class Aaarggh {
public static void main(String[] args) throws Exception {
Signal.handle(new Signal("INT"), new SignalHandler () {
public void handle(Signal sig) {
System.out.println(
"Aaarggh, a user is trying to interrupt me!!");
System.out.println(
"(throw garlic at user, say `shoo, go away')");
}
});
for(int i=0; i<100; i++) {
Thread.sleep(1000);
System.out.print('.');
}
}
}

When you run this program, it will print dots onto the console and if you try to stop it with Ctrl+C, it will give you the following output and merrily carry on printing dots. You can either stop it by waiting for the 100 seconds or to kill it via the task manager. (Kill sends a SIGTERM signal, which is stronger than SIGINT)

.........Aaarggh, a user is trying to interrupt me!!
(throw garlic at user, say `shoo, go away')
..

Inside the signal handler you can do anything you want to, including calling System.exit(0) or Runtime.getRuntime().halt( 0) if you don't want shutdown hooks to be called.

What signals can you catch? The answer to that question depends on the operating system you are running on. I managed to dig out a list for Windows and Solaris Sun JDK 1.2.2:

Windows: ABRT, FPE, ILL, INT, SEGV, TERM

Solaris: ABRT, ALRM, BUS, CHLD, CONT, EMT, FPE, HUP, ILL, INT, IO, KILL, PIPE, POLL, PROF, PWR, QUIT, SEGV, STOP, SYS, TERM, TRAP, TSTP TTIN, TTOU, URG, USR1, USR2, VTALRM, WINCH, XCPU, XFSZ

Please don't ask me what events generate each of those signals. It's a miracle that I found that list of signals, sun.misc.Signal is written in such a way that if you pass in an incorrect String it throws an IllegalArgumentException at you. However, it does not tell you what the possible signals are. The most significant signals from within Java are SIG and TERM.

Here is some code that is called whenever our program is killed:

import sun.misc.Signal;
import sun.misc.SignalHandler;

public class SophisticatedShutdownSequence {
private static boolean running = true;
public static void init() {
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
System.out.println("reached point of no return ...");
}
});

SignalHandler handler = new SignalHandler () {
public void handle(Signal sig) {
if (running) {
running = false;
System.out.println("Signal " + sig);
System.out.println("Shutting down database...");
} else {
// only on the second attempt do we exit
System.out.println(" database shutdown interrupted!");
System.exit(0);
}
}
};
Signal.handle(new Signal("INT"), handler);
Signal.handle(new Signal("TERM"), handler);
}

public static void main(String args[]) throws Exception {
init();
Object o = new Object();
synchronized (o) {
o.wait(10000);
}
System.exit(0);
}
}

If you run this and press Ctrl+C twice, or try kill the program once via task manager or by pressing the cross, you get the following output:

Signal SIGINT
Shutting down database...
database shutdown interrupted!
We have now reached the point of no return ...

This shutting down sequence is a good opportunity for the State Pattern (see Gang of Four book). Due to popular request, I will try and show one Java Design pattern every 4 newsletters, and I might just start with the State Pattern. In addition, I will soon start doing book reviews on books that you should definitely have in your bookshelf.

Switching off OS signals at runtime

In JDK 1.3.1, Sun sneaked in a JVM runtime parameter to stop all this nonsense of hooking into signals.

public class NoShutdownHookAllowed {
public static void main(String[] args) throws Exception {
try {
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
System.out.println("Shutdown hook going mad");
}
});
} catch(IllegalArgumentException ex) {
System.out.println("Caught " + ex);
}
Thread.sleep(10000);
}
}

Try running this with JDK 1.3.1 and beyond, and use the following command: java -Xrs NoShutdownHookAllowed The -Xrs setting reduces use of OS signals by Java/VM.

What happens is that an IllegalArgumentException is generated after the thread has been added as a shutdown hook. This means that if you try to interrupt the code after it has been started, the shutdown hook will not be called. However, if you let the program finish naturally, it will run the shutdown hook. As far as I know, the -Xrs option is

java waiting in main method

public static void main(String[] args)
{
Test test = new Test();
if(true){
out.println("gone to wait! " + new Time(System.currentTimeMillis()));
synchronized(test)
{
try
{
test.wait(1000*60*30);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
out.println("come back! " + new Time(System.currentTimeMillis()));
}
}

j2me push registery

Static Registration
To statically declare a push connection, a connection string must be specified in the Java Application Descriptor (JAD) file or the JAR manifest (depending on how the platform supports the application descriptor). Connections declared in the application descriptor follow the format:
MIDlet-Push-: , , 
MIDlet-Push-1: datagram://:444, com.gearworks.PushExample, 12.23.101.02
MIDlet-Push-1: sms://:50001, com.gearworks.PushExample,*

Dynamic Registration
Dynamic registration of push connections requires the same elements as static registration but they are specified as parameters in a call to PushRegistry.registerConnection(). The following example dynamically registers a datagram connection and is identical to the static example shown previously.PushRegistry.registerConnection("datagram://:444", "com.gearworks.PushExample", "12.23.101.02").

Dynamic registration, on the other hand, has the advantage of installing without failure. However, the user must run the application at least once to invoke the dynamic registration. Because dynamic registration is done at runtime there is more flexibility in how connections are registered. For example an application can scan for an available connection to better ensure push registration success. The following code shows how this might be accomplished, by attempting up to four different connection strings:


String base = "55";
String name = "PushMIDlet";
for(int ccnt=5; ccnt < 9; ccnt++) {
try {
String temp = base +
Integer.toString(ccnt);
PushRegistry.registerConnection(
"datagram://:"+temp, name, "*");
break;
} catch (IOException x) {
continue;
}

Condition

Dynamic Registration Response

Connection string syntax is not valid

An IllegalArgumentException is thrown

The device does not support the specified connection type (e.g. socket) or has not made the connection type available to push

A ConnectionNotFoundException is thrown

The connection is already registered by another MIDlet suite or there are insufficient resources to handle the registration request

An IOException is thrown

The MIDlet name specified in the push connection string is not declared in the application descriptor of the MIDlet suite

A ClassNotFoundException is thrown

The MIDlet suite does not have permission to register or use the specified connection

A SecurityException is thrown

The port specified by the connection string is reserved by the device

Undefined by the MIDP specification, but an IOException is most likely.

A list of connections can be obtained by calling 
PushRegistry.listConnections(boolean)

This code handles inbound datagram connections in response to a pushed datagram connection.
protected void startApp(){
if (!init) {
init = true;
String[] conns =
PushRegistry.listConnections(false);
System.out.println("Found " + conns.length +
" connections.");
for(int ccnt=0; ccnt < conns.length; ccnt++){
DatagramHandler handler =
new DatagramHandler(conns [ccnt]);
connectionHandlers.addElement(handler);
handler.start();
}
}
}

class DatagramHandler extends Thread
{
private DatagramConnection dgc;

public DatagramHandler(String c){
try {
dgc = (DatagramConnection)Connector.open(c);
} catch (IOException x){
x.printStackTrace();
}
}

public void run(){
while (true){
try{
Datagram datagram = dgc.newDatagram(20);
dgc.receive(datagram);
byte[] data = datagram.getData();
String s = new String(data);
System.out.println(s);
} catch (InterruptedIOException ignore) {
System.out.println("Done listening");
break;
} catch (IOException x) {
x.printStackTrace();
}
}
}

or

public class MySamplePushRegistry extends MIDlet
implements CommandListener, Runnable, MessageListener {

//....

public void startApp() {
smsPort = getAppProperty("SMS-Port");
String smsConnection = "sms://:" + smsPort;
if (smsconn == null) {
try {
smsconn = (MessageConnection)
Connector.open(smsConnection);


smsconn.setMessageListener(this);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
display.setCurrent(resumeScreen);
}
public void notifyIncomingMessage(MessageConnection conn) {
if (thread == null) {
thread = new Thread(this);
thread.start();
}
}
public void run() {
try {
msg = smsconn.receive();
if (msg != null) {
if (msg instanceof TextMessage) {


content.setString(((TextMessage)msg).getPayloadText());
}
display.setCurrent(content);
}
} catch (IOException e) {
e.printStackTrace();
}
}
//other methods to follow
}

Setting Alarms
Hidden away in the API of the PushRegistry is a simple little feature called an Alarm. An Alarm can be registered for a MIDlet suite much like a connection. The difference, however, is that the MIDlet associated with an Alarm is started at a certain point in time, rather than in response to network activity. Each MIDlet suite can register, at most, one Alarm at a time. Alarms are registered by making a call to PushRegistry.registerAlarm(). The following code registers an Alarm to start the MIDlet "PushDemo" 24 hours from now.

long day = 1000*60*60*24; long t = new Date().getTime()+day; PushRegistry.registerAlarm( "PushDemo", t);



http://www.devx.com/wireless/Article/20154/1954?pf=true
http://www.javaworld.com/javaworld/jw-04-2006/jw-0417-push.html?page=1
http://developer.sonyericsson.com/site/global/techsupport/tipstrickscode/java/p_tips_java_1201.jsp

j2me locallization

You can use System.getProperty("microedition.locale") to find out the language of the device. There's no way to find out the complete list of languages supported though.
http://forums.java.net/jive/thread.jspa?messageID=237376

Linux sending process to background

ctrl+z
bg (enter)

Tuesday, October 2, 2007

java code hexToByte

    private static final String HEXINDEX = "0123456789abcdef          ABCDEF";

public static byte[] hexToByte(String s) {
int l = s.length() / 2;
byte data[] = new byte[l];
int j = 0;

for (int i = 0; i < l; i++) {
char c = s.charAt(j++);
int n, b;

n = HEXINDEX.indexOf(c);
b = (n & 0xf) << 4;
c = s.charAt(j++);
n = HEXINDEX.indexOf(c);
b += (n & 0xf);
data[i] = (byte) b;
}
return data;
}

Tutos(open source project management tools )

http://demo.tutos.de/php/mytutos.php