Your First Groovy



Your First Groovy



//hello.groovy
println “hello, world”

for (arg in this.args ) {

println “Argument:” + arg;

}

// this is a comment

/* a block comment, commenting out an alternative to above:

this.args.each{ arg -> println “hello, ${arg}”}

*/

To run it from command line



groovy hello.groovy MyName yourName HisName


Overview


Groovy classes compile down to Java bytecode and so there’s a 1-1 mapping between a Groovy class and a Java class.

Indeed each Groovy class can be used inside normal Java code – since it is a Java class too.


Probably the easiest way to get groovy is to try working with collections. In Groovy List (java.util.List) and Map (java.util.Map) are both first class objects in the syntax. So to create a List of objects you can do the following…



def list = [1, 2, ‘hello’, new java.util.Date()]

assert list.size() == 4

assert list.get(2) == ‘hello’

assert list[2] == ‘hello’

Notice that everything is an object (or that auto-boxing takes place when working with numbers). To create maps…



def map = [‘name’:’James’, ‘location’:’London’]

assert map.size() == 2

assert map.get(‘name’) == ‘James’

assert map[‘name’] == ‘James’

Iterating over collections is easy…



def list = [1, 2, 3]

for (i in list) { println i }

Once you have some collections you can then use some of the new collection helper methods or try working with closures…



Working with closures


Closures are similar to Java’s inner classes, except they are a single method which is invokable, with arbitrary parameters. A closure can have as many parameters as you wish…



def closure = { param -> println(“hello ${param}”) }

closure.call(“world!”)

closure = { greeting, name -> println(greeting + name) }

closure.call(“hello “, “world!”)


If no parameter(s) is(are) specified before -> symbol then a default named parameter, called ‘it’ can be used. e.g.



def closure = { println “hello “ + it }

closure.call(“world!”)

Using closures allows us to process collections (arrays, maps, strings, files, SQL connections and so forth) in a clean way. e.g



[1, 2, 3].each ({ item -> print “${item}-“ })

[“k1”:“v1”, “k2”:“v2”].each {key, value -> println key + “=” + value}

Note: If a given closure is the last parameter of a method, its definition can reside outside of the parentheses. Thus the following code is valid:



def fun(int i, Closure c) {

c.call(i)

}

// put Closure out of ()

[1, 2, 3].each() { item -> print “${item}-“ } // 1-2-3-

fun(123) { i -> println i } // 123

// omit ()



[1, 2, 3].each ({ item -> print “${item}-“ }) // 1-2-3-



// omit enclosing ()
[1, 2, 3].each { item -> print “${item}-“ } // 1-2-3-

// normal
[1, 2, 3].each(({ item -> print “${item}-“ })) // 1-2-3-

// using the fun function to do the same thing
[1,2,3].each {fun(it,{item -> print “${item}-“})} // 1-2-3-

def closure = { i -> println i}

//[1, 2, 3].each() closure // error. closure has been previously defined

Here are a number of helper methods available on collections & strings…



each


iterate via a closure



[1, 2, 3].each { item -> print “${item}-“ }


collect


collect the return value of calling a closure on each item in a collection



def value = [1, 2, 3].collect { it * 2 }

assert value == [2, 4, 6]


find


finds first item matching closure predicate



def value = [1, 2, 3].find { it > 1 }

assert value == 2


findAll


finds all items matching closure predicate



def value = [1, 2, 3].findAll { it > 1 }

assert value == [2, 3]


inject


allows you to pass a value into the first iteration and then pass the result of that iteration into the next iteration and so on. This is ideal for counting and other forms of processing



def value = [1, 2, 3].inject(‘counting: ‘) { str, item -> str + item }

assert value == “counting: 123”

value = [1, 2, 3].inject(0) { count, item -> count + item }

assert value == 6


In addition there’s 2 new methods for doing boolean logic on some collection…



every


returns true if all items match the closure predicate



def value = [1, 2, 3].every { it < 5 }

assert value

value = [1, 2, 3].every { item -> item < 3 }

assert ! value



any


returns true if any item match the closure predicate



def value = [1, 2, 3].any { it > 2 }

assert value

value = [1, 2, 3].any { item -> item > 3 }

assert value == false


Other helper methods include:



max / min


returns the max/min values of the collection – for Comparable objects



value = [9, 4, 2, 10, 5].max()

assert value == 10

value = [9, 4, 2, 10, 5].min()

assert value == 2

value = [‘x’, ‘y’, ‘a’, ‘z’].min()

assert value == ‘a’


join


concatenates the values of the collection together with a string value



def value = [1, 2, 3].join(‘-‘)

assert value == ‘1-2-3’

install Groovy in RedHat as4

官方网是这样写的:
1,first, Download a binary distribution of Groovy and unpack it into some file on your local file system
2,set your GROOVY_HOME environment variable to the directory you unpacked the distribution
3,add GROOVY_HOME/bin to your PATH environment variable
4,set your JAVA_HOME environment variable to point to your JDK. On OS X this is /Library/Java/Home, on other unixes its often /usr/java etc. If you’ve already installed tools like Ant or Maven you’ve probably already done this step.

但会出现错误:
# groovysh
java.lang.NoClassDefFoundError: org/objectweb/asm/ClassVisitor
        at groovy.lang.GroovySystem.<clinit>(GroovySystem.java:27)
        at org.codehaus.groovy.runtime.Invoker.<init>(Invoker.java:38)
        at org.codehaus.groovy.runtime.InvokerHelper.<clinit>(InvokerHelper.java:44)
        at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.invokeNewN(ScriptBytecodeAdapter.java:225)
        at org.codehaus.groovy.tools.shell.Main.<clinit>(Main.groovy:34)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at org.codehaus.groovy.tools.GroovyStarter.rootLoader(GroovyStarter.java:101)
        at org.codehaus.groovy.tools.GroovyStarter.main(GroovyStarter.java:130)


解决办法:
#vi /etc/profile

加入GROOVY_HOME
export GROOVY_HOME=”/home1/software/groovy-1.5.0/”

修改CLASSPATH
export CLASSPATH=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar:”/home1/lib/”:$GROOVY_HOME/lib/ant-1.7.0.jar:$GROOVY_HOME/lib/asm-2.2.jar:$GROOVY_HOME/lib/bsf-2.4.0.jar:$GROOVY_HOME/lib/jline-0.9.93.jar:$GROOVY_HOME/lib/mx4j-3.0.2.jar:$GROOVY_HOME/lib/ant-junit-1.7.0.jar:$GROOVY_HOME/lib/asm-analysis-2.2.jar:$GROOVY_HOME/lib/commons-cli-1.0.jar:$GROOVY_HOME/lib/jsp-api-2.0.jar:$GROOVY_HOME/lib/servlet-api-2.4.jar:$GROOVY_HOME/lib/ant-launcher-1.7.0.jar:$GROOVY_HOME/lib/asm-tree-2.2.jar:$GROOVY_HOME/lib/commons-logging-1.1.jar:$GROOVY_HOME/lib/junit-3.8.2.jar:$GROOVY_HOME/lib/xpp3_min-1.1.3.4.O.jar:$GROOVY_HOME/lib/antlr-2.7.6.jar:$GROOVY_HOME/lib/asm-util-2.2.jar:$GROOVY_HOME/lib/groovy-1.5.0.jar:$GROOVY_HOME/lib/mockobjects-core-0.09.jar:$GROOVY_HOME/lib/xstream-1.2.2.jar

mysqlbinlog 資料庫處理二進制日誌檔案的實用工具

當然,系統剛弄好是沒有開啟 mysqlbinlog 的功能,至少在 CentOS4.4 上面我還要去開啟,不過 ubuntu 系統預設就已經開啟了,不過沒關係,只要利用下面方法就可以達到了


修改 my.cnf [ CentOS: /etc/my.cnf Ubuntu: /etc/mysql/my.cnf ],加入下面語法



# Replication Master Server (default)
# binary logging is required for replication
log-BIN=mysql-BIN


不過話說當你開啟這個功能之後,你會發現在 /var/lib/mysql/ 底下多出很多檔案



-rw-rw—-   1 mysql mysql  33164904  117 15:44 mysql-bin.000001
-rw-rw—-   1 mysql mysql      4007  117 15:50 mysql-bin.000002
-rw-rw—-   1 mysql mysql  70288989  129 22:38 mysql-bin.000003
-rw-rw—-   1 mysql mysql     16665  129 22:41 mysql-bin.000004
-rw-rw—-   1 mysql mysql      4792  129 22:42 mysql-bin.000005
-rw-rw—-   1 mysql mysql  56274069  210 06:25 mysql-bin.000006
-rw-rw—-   1 mysql mysql 893963240  329 09:21 mysql-bin.000007
-rw-rw—-   1 mysql mysql 666605284  329 09:39 mysql-bin.000008
-rw-rw—-   1 mysql mysql    151946  329 10:02 mysql-bin.000009
-rw-rw—-   1 mysql mysql   3450785  329 22:38 mysql-bin.000010

上面就是產生 mysqlbinlog 檔案,當然如果你要觀看那一個檔案下指令吧



shell> mysqlbinlog binlog.0000003


裏面的語法包跨 每個語句花費的時間、客戶發出的線程ID、發出線程時的時間戳,也可以遠端觀看


當讀取遠程二進制日誌時,可以通過連接參數選項來指示如何連接伺服器,但它們經常被忽略掉,除非您還指定了–read-from-remote-server選項。這些選項是–host、–password、–port、–protocol、–socket和–user。


底下來說明一下用法~


1. 指定恢復時間語法


假如你今天早上9點不小心砍掉哪個資料庫的資料表,你可以利用下面語法來恢復



mysqlbinlog –stop-date=“2007-03-29 8:59:59”  /var/lib/mysql/bin.000001 | mysql -u root -p

如果你想恢復後面9點以後sql語法 可以使用



mysqlbinlog –start-date=“2007-03-29 9:00:00”  /var/lib/mysql/bin.000001 | mysql -u root -p

或者是 你想恢復 9點到10點之間的sql語法,則下面語法是您想要的



mysqlbinlog –start-date=“2007-03-29 9:00:00”  –stop-date=“2007-03-29 10:00:00” /var/lib/mysql/bin.000001 | mysql -u root -p

其實你也可以不要執行,先把sql語法輸出到 /tmp/restore.sql



mysqlbinlog –start-date=“2007-03-29 9:00:00”  –stop-date=“2007-03-29 10:00:00” /var/lib/mysql/bin.000001 &gt; /tmp/restore.sql

當然 你也可以指定你要輸出的 database,免的檔案很大



database=db_name,-d db_name
host=host_name,-h host_name

Timer Server

import java.io.InterruptedIOException;
import javax.microedition.io.Connector;
import javax.microedition.io.Datagram;
import javax.microedition.io.DatagramConnection;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.StringItem;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

public class TimeMIDlet extends MIDlet
                    implements CommandListener, Runnable {

    private Display display;
    private Form addressForm;
    private Form connectForm;
    private Form displayForm;
    private Command backCommand;
    private Command exitCommand;
    private Command okCommand;
    private StringItem messageLabel;
    private TextField serverName;

    protected void startApp() throws MIDletStateChangeException {
        if (display == null) {
            initialize();
            display.setCurrent(addressForm);
        }
    }

    protected void pauseApp() {
    }

    protected void destroyApp(boolean unconditional)
                        throws MIDletStateChangeException {
    }

    public void commandAction(Command cmd, Displayable d) {
        if (cmd == okCommand) {
            Thread t = new Thread(this);
            t.start();
        else if (cmd == backCommand) {
            display.setCurrent(addressForm);
        else if (cmd == exitCommand) {
            try {
                destroyApp(true);
            catch (MIDletStateChangeException ex) {
            }
            notifyDestroyed();
        }
    }

    public void run() {
        DatagramConnection conn = null;
        display.setCurrent(connectForm);

        try {
            // Build the name string for the Connector open method
            String server = serverName.getString();
            String name = “datagram://” + server + “:” 13;
            conn = (DatagramConnection)Connector.open(name,
                                    Connector.READ_WRITE, false);

            // Build and send an empty datagram
            Datagram dg = conn.newDatagram(10);
            dg.setData(“Hello”.getBytes()05);
            conn.send(dg);

            // Receive the reply
            Datagram rdg = conn.newDatagram(512);
            conn.receive(rdg);
            messageLabel.setText(new String(rdg.getData()0, rdg.getLength()));
            display.setCurrent(displayForm);

        catch (InterruptedIOException iex) {
            display.callSerially(new Runnable() {
                public void run() {
                    Alert alert = new Alert(“No Reply”,
                        “No reply was received.\n” +
                        “Please check the server address and try again.”, null,
                        AlertType.ERROR);
                    alert.setTimeout(Alert.FOREVER);
                    display.setCurrent(alert, addressForm);
                }
            });
            return;
        catch (Exception ex) {
            display.callSerially(new Runnable() {
                public void run() {
                    Alert alert = new Alert(“Invalid Address”,
                        “The supplied address is invalid\n” +
                        “Please correct it and try again.”, null,
                        AlertType.ERROR);
                    alert.setTimeout(Alert.FOREVER);
                    display.setCurrent(alert, addressForm);
                }
            });
            return;
        catch (Error err) {
            System.out.println(err);
            err.printStackTrace();
        }
    }

    private void initialize() {
        display = Display.getDisplay(this);

        // Commands
        exitCommand = new Command(“Exit”, Command.EXIT, 0);
        okCommand = new Command(“OK”, Command.OK, 0);
        backCommand = new Command(“Back”, Command.BACK, 0);

        // The address form
        addressForm = new Form(“Network Time”);
        serverName = new TextField(“Time Server name:”“tock.usno.navy.mil”,
                                            256, TextField.ANY);
        addressForm.append(serverName);
        addressForm.addCommand(okCommand);
        addressForm.addCommand(exitCommand);
        addressForm.setCommandListener(this);

        // The connect form
        connectForm = new Form(“Sending”);
        messageLabel = new StringItem(null,
                    “Sending the datagram…\nPlease wait.”);
        connectForm.append(messageLabel);
        connectForm.addCommand(backCommand);
        connectForm.setCommandListener(this);

        // The display form
        displayForm = new Form(“Server Reply”);
        messageLabel = new StringItem(null, null);
        displayForm.append(messageLabel);
        displayForm.addCommand(backCommand);
        displayForm.setCommandListener(this);
    }
}

J2ME Datagram Receiver

import java.io.IOException;
import javax.microedition.io.Connector;
import javax.microedition.io.Datagram;
import javax.microedition.io.DatagramConnection;

public class DatagramReceiver {
    public static void main(String[] args) {
        if (args.length != 1) {
            System.out.println(“Usage: DatagramReceiver port”);
            System.exit(1);
        }
        
        try {
            DatagramConnection receiver = 
                    (DatagramConnection)Connector.open(“datagram://:” + args[0]);
            byte[] buffer = new byte[256];
            Datagram dgram = receiver.newDatagram(buffer, buffer.length);
            for ($$) {
                dgram.setLength(buffer.length);
                receiver.receive(dgram);
                int length = dgram.getLength();
                System.out.println(“Datagram received. Length is ” + length);

                // Show the content of the datagram.
                for (int i = 0; i < length; i++) {
                    System.out.print(buffer[i” “);
                }
                System.out.println();
                
                // Send it back…
                receiver.send(dgram);
            }
        catch (IOException ex) {
            System.out.println(“IOException: ” + ex);
        }
    }
}


J2ME DatagramSender

import java.io.IOException;
import javax.microedition.io.Connector;
import javax.microedition.io.Datagram;
import javax.microedition.io.DatagramConnection;

public class DatagramSender {
    public static void main(String[] args) {
        if (args.length != 2) {
            System.out.println(“Usage: DatagramSender port length”);
            System.exit(1);
        }
        
        try {
            DatagramConnection sender = 
                    (DatagramConnection)Connector.open(“datagram://localhost:” + args[0]);
            int length = Integer.parseInt(args[1]);
            byte[] buffer = new byte[length];
            for (int i = 0; i < length; i++) {
                buffer[i(byte)(‘0’ (i % 10));
            }
            Datagram dgram = sender.newDatagram(buffer, buffer.length);
            sender.send(dgram);
            
            // Wait for the packet to be returned
            for (int i = 0; i < length; i++) {
                buffer[i(byte)0;
            }
            sender.receive(dgram);
            length = dgram.getLength();
            System.out.println(“Received return packet, length is ” + length);
            
            // Show the content of the datagram.
            for (int i = 0; i < length; i++) {
                System.out.print(buffer[i” “);
            }
            System.out.println();
        catch (IOException ex) {
            System.out.println(“IOException: ” + ex);
        }
    }
}


Demonstrates the functionality of DatagramConnection framework.

/*** Chapter 5 Sample Code for Datagram functionality ***/

import 
javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import java.util.*;

public class DatagramTest extends MIDlet {

  // Port 9001 is used for datagram communication
    static final int receiveport  = 9001;
  Receive receiveThread = new Receive();

    public DatagramTest() {
  }

    public void startApp() {
        // Start the listening thread
        receiveThread.start();
        // Send message Hello World!
        sendMessage(“Hello World!”);
    }

    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional)  {
    }

  // This function sends a datagram message on port 9001.
    void sendMessage(String msg)  {
    String destAddr = “datagram://localhost:” + receiveport;
        DatagramConnection dc = null;
    Datagram dgram;
    byte[] bMsg = msg.getBytes();

    try {
           dc = (DatagramConnection)Connector.open(destAddr);
      // Create a datagram socket and send
            dgram= dc.newDatagram(bMsg,bMsg.length,destAddr);
            dc.send(dgram);
      System.out.println(“Sending Packet:” +  msg);
            dc.close();
        }
        catch (Exception e)  {
            System.out.println(“Exception Connecting: ” + e.getMessage());
    }
    finally {
            if (dc != null) {
                try {
                    dc.close();
                }
                catch (Exception e) {
                   System.out.println(“Exception Closing: ” + e.getMessage());
                }
            }
        }
    }

  // This function is a listener. It waits to receive datagram packets on 9001 port
    class Receive extends Thread  {
        public void run() {
        doReceive();
        }

        void doReceive() {
            DatagramConnection dc = null;
            Datagram dgram;
      try {
        // Open Server side datagram connection
                dc = (DatagramConnection)Connector.open(“datagram://:”+receiveport);
          String receivedMsg;
          while (true) {
                    dgram = dc.newDatagram(dc.getMaximumLength());
                try {
             dc.receive(dgram);
          catch (Exception e) {
            System.out.println(“Exception in receiving message:” + e.getMessage());
          }
                    receivedMsg = new String(dgram.getData()0,dgram.getLength());
                    System.out.println(“Received Message: ” + receivedMsg);
                    try {
                       Thread.sleep(500);
                    }
                    catch (Exception e) {
                      System.out.println(“Exception doReceive(): ” + e.getMessage());
                    }
                }

            }
          catch (Exception e) {
          System.out.println(“Exception doReceive(): ” + e.getMessage());
       }
       finally {
          if (dc != null) {
          try {
                       dc.close();
                   }
                   catch (Exception e) {
                      System.out.println(“Exception Closing: ” + e.getMessage());
                   }
               }
          }

        }
     }
 }


j2me:Socket connection

/*
J2ME: The Complete Reference


James Keogh

Publisher: McGraw-Hill

ISBN 0072227109

*/
// jad file (Please verify the jar size first)
/*
MIDlet-Name: socketconnection
MIDlet-Version: 1.0
MIDlet-Vendor: MyCompany
MIDlet-Jar-URL: socketconnection.jar
MIDlet-1: socketconnection, , socketconnection
MicroEdition-Configuration: CLDC-1.0
MicroEdition-Profile: MIDP-1.0
MIDlet-JAR-SIZE: 100

*/
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.io.*;
import javax.microedition.io.*;
public class socketconnection extends MIDlet implements CommandListener {
  private Command exit, start;
  private Display display;
  private Form form;
  public socketconnection () 
  {
    display = Display.getDisplay(this);
    exit = new Command(“Exit”, Command.EXIT, 1);
    start = new Command(“Start”, Command.EXIT, 1);
    form new Form(“Read Write Socket”);
    form.addCommand(exit);
    form.addCommand(start);
    form.setCommandListener(this);
  }
  public void startApp() throws MIDletStateChangeException 
  {
    display.setCurrent(form);
  }
  public void pauseApp() 
  {
  }
  public void destroyApp(boolean unconditional
  {
  }
  public void commandAction(Command command, Displayable displayable
  {
    if (command == exit
    {
      destroyApp(false);
      notifyDestroyed();
    }
    else if (command == start
    {
      try 
      {
       StreamConnection connection = (StreamConnectionConnector.open(“socket://www.myserver.com:80”);
       PrintStream output = 
         new PrintStream(connection.openOutputStream() );
       output.println“GET /my.html HTTP/0.9\n\n” );
       output.flush();
       InputStream in = connection.openInputStream();
       int ch;
       while( ( ch = in.read() ) != –)
      {
         System.out.print( (charch );
       }
       in.close();
       output.close();
       connection.close();
     }
      catchConnectionNotFoundException error )
       {
         Alert alert = new Alert(
            “Error”“Cannot access socket.”, null, null);
         alert.setTimeout(Alert.FOREVER);
         alert.setType(AlertType.ERROR);
         display.setCurrent(alert);      
        }
        catchIOException error )
        {
         Alert alert = new Alert(“Error”, error.toString(), null, null);
         alert.setTimeout(Alert.FOREVER);
         alert.setType(AlertType.ERROR);
         display.setCurrent(alert);
        }
    }
  }
}


Developing Applications with the Java APIs for Bluetooth (JSR-82)

Developing Applications with the Java APIs for Bluetooth (JSR-82)



This paper covers the Java API for Bluetooth (JSR-82) with respect to Sony Ericsson devices. It starts by introducing the Bluetooth technology, followed by the Java APIs for Bluetooth, and how to use them.


Currently, these APIs are currently available in the Sony Ericsson P900/P908 handsets.


Click here to view “Developing Applications with the Java APIs for Bluetooth (JSR-82)”



Click here to view the Training Materials (.zip) associated with this article.