如果找到了对您有用的资料,烦请点击右手边的Google广告支持我继续共享知识,谢谢! http://dengpeng.spaces.live.com/

2010年2月8日星期一

Rebirth of this blog

It is now migrated to independent WordPress located at here:

http://www.sensorapp.net/

2009年9月22日星期二

Pachube Java Tutorial

Pachube is a webapp aggragate sensor data around the world. The tutorials given on this site is not well written I think. So, I decide to try it out and blog this simple example. Hope it will be helpfull to you.

Pachube + Java depend Libraries:
1. EEML: http://www.eeml.org/library/eeml.zip
2. Processing: http://processing.org/download/

This is a manual (casual) update example source code. remember to call the setup() before draw():

import eeml.*;
import processing.core.PApplet;

/**
*
* @author pdeng
*/

public class HelloPachube {

DataOut dOut;

void setup() {

PApplet p = new PApplet();
dOut = new DataOut(p, "YOUR_FEED_URL", "YOUR_API_KEY");

// and add and tag a datastream
dOut.addData(0, "temperature");
}

void draw() {
System.out.println("ready to POST: ");
dOut.update(0, 22.5f); // update the datastream
int response = dOut.updatePachube(); // updatePachube() updates by an authenticated PUT HTTP request
System.out.println(response);
}
}

2009年9月15日星期二

Smack API Tutorial

Version: Smack 3.1.0 Beta
Smack is a Java XMPP library. You can create your own GTalk with this.
Digested from: http://www.javaprogrammingforums.com/java-tips-tutorials/551-how-write-simple-xmpp-jabber-client-using-smack-api.html

package jabberhelloworld;

import java.util.*;
import java.io.*;

import java.util.logging.Level;
import java.util.logging.Logger;
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.SASLAuthentication;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;

public class Main implements MessageListener {

XMPPConnection connection;

public void login(String userName, String password) throws XMPPException {
ConnectionConfiguration config = new ConnectionConfiguration("jabber.org", 5222, "jabber.org");
connection = new XMPPConnection(config);

connection.connect();
SASLAuthentication.supportSASLMechanism("PLAIN", 0);
connection.login(userName, password);
}

public void sendMessage(String message, String to) throws XMPPException {
Chat chat = connection.getChatManager().createChat(to, this);
chat.sendMessage(message);
}

public void displayBuddyList() {
Roster roster = connection.getRoster();
Collection<RosterEntry> entries = roster.getEntries();

System.out.println("\n\n" + entries.size() + " buddy(ies):");
for (RosterEntry r : entries) {
System.out.println(r.getUser());
}
}

public void disconnect() {
connection.disconnect();
}

public void processMessage(Chat chat, Message message) {
if (message.getType() == Message.Type.chat) {
System.out.println(chat.getParticipant() + " says: " + message.getBody());
try {
chat.sendMessage(message.getBody() + " echo");
} catch (XMPPException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}

public static void main(String args[]) throws XMPPException, IOException {
// declare variables
Main c = new Main();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String msg;


// turn on the enhanced debugger
XMPPConnection.DEBUG_ENABLED = true;


// Enter your login information here
c.login("yourusername", "yourpassword");

c.displayBuddyList();

System.out.println("-----");

System.out.println("Who do you want to talk to? - Type contacts full email address:");
String talkTo = br.readLine();

System.out.println("-----");
System.out.println("All messages will be sent to " + talkTo);
System.out.println("Enter your message in the console:");
System.out.println("-----\n");

while (!(msg = br.readLine()).equals("bye")) {
c.sendMessage(msg, talkTo);
}

c.disconnect();
System.exit(0);
}
}

Sun SPOT offline sensing client

To monitor an activity, sometimes base station is not in communication range. SPOT should be able to store data in its internal memory. When the base station is avaliable, it could send data back to PC.
this is how it works:
1. start SPOT
2. before your activity, click left button on SPOT,and it is recording
3. click left button again to pause recording
4. take it back, click right button on SPOT to send recoreded back to base station

SPOT Side:

/*
* StartApplication.java
*
* Created on Sep 15, 2009 4:32:39 PM;
*/

package org.sunspotworld;

import com.sun.spot.sensorboard.EDemoBoard;
import com.sun.spot.sensorboard.peripheral.ISwitch;
import com.sun.spot.sensorboard.peripheral.ITriColorLED;
import com.sun.spot.peripheral.radio.RadioFactory;
import com.sun.spot.io.j2me.radiostream.*;
import com.sun.spot.peripheral.NoRouteException;
import com.sun.spot.sensorboard.peripheral.IAccelerometer3D;
import com.sun.spot.sensorboard.peripheral.ILightSensor;
import com.sun.spot.sensorboard.peripheral.ISwitchListener;
import com.sun.spot.sensorboard.peripheral.ITemperatureInput;
import com.sun.spot.util.*;

import java.io.*;
import java.util.Date;
import javax.microedition.io.*;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;
import javax.microedition.rms.RecordStoreNotOpenException;

/**
* The startApp method of this class is called by the VM to start the
* application.
*
* The manifest specifies this class as MIDlet-1, which means it will
* be selected for execution.
*/

public class StartApplication extends MIDlet implements ISwitchListener {

private ITriColorLED[] leds = EDemoBoard.getInstance().getLEDs();
ISwitch switch0 = EDemoBoard.getInstance().getSwitches()[0];
ISwitch switch1 = EDemoBoard.getInstance().getSwitches()[1];
boolean switch0Status = false;
boolean switch1Status = false;
RecordStore rms;
int recordStoreIndex = 0;
private IAccelerometer3D accel = EDemoBoard.getInstance().getAccelerometer();
private ITemperatureInput tempSensor = EDemoBoard.getInstance().getADCTemperature();
private ILightSensor lightSensor = EDemoBoard.getInstance().getLightSensor();

protected void startApp() throws MIDletStateChangeException {
new BootloaderListener().start(); // monitor the USB (if connected) and recognize commands from host

long ourAddr = RadioFactory.getRadioPolicyManager().getIEEEAddress();
System.out.println("Our radio address = " + IEEEAddress.toDottedHex(ourAddr));

//add listeners to two switchs
switch0.addISwitchListener(this);
switch1.addISwitchListener(this);

//set the default LED indicator
leds[0].setRGB(100, 100, 0);
leds[0].setOn();

//uncomment this line below would delete all RecordStore
//deleteRecordStore();

while (true) {
//click the left button to start/stop recording
if (switch0Status) {
try {
//create or open RecordStore
rms = RecordStore.openRecordStore("Record", true);
} catch (RecordStoreException ex) {
ex.printStackTrace();
}
//get values from sensors and store
while (switch0Status) {
try {
String msg = String.valueOf(accel.getAccelX()) + "," +
String.valueOf(accel.getAccelY()) + "," +
String.valueOf(accel.getAccelZ()) + "," +
String.valueOf(accel.getTiltX()) + "," +
String.valueOf(accel.getTiltY()) + "," +
String.valueOf(accel.getTiltZ()) + "," +
String.valueOf(tempSensor.getCelsius()) + "," +
String.valueOf(lightSensor.getValue() + "," +
new Date().getTime());
System.out.println(msg);
Utils.sleep(10);
//add value to RecordStore
rms.addRecord(msg.getBytes(), 0, msg.getBytes().length);
} catch (Exception ex) {
ex.printStackTrace();
}
}
try {
//add a spliter for each of activities
rms.addRecord("finish".getBytes(), 0, "finish".getBytes().length);
} catch (RecordStoreNotOpenException ex) {
ex.printStackTrace();
} catch (RecordStoreException ex) {
ex.printStackTrace();
}
}

//click the right button to send data to server
if (switch1Status) {
leds[0].setOff();
//send data
try {
sendout();
} catch (Exception ex) {
ex.printStackTrace();
}
switch1Status = false;
leds[7].setOff();
leds[0].setRGB(100, 100, 0);
leds[0].setOn();
}
}
}

protected void pauseApp() {
// This is not currently called by the Squawk VM
}

/**
* Called if the MIDlet is terminated by the system.
* I.e. if startApp throws any exception other than MIDletStateChangeException,
* if the isolate running the MIDlet is killed with Isolate.exit(), or
* if VM.stopVM() is called.
*
* It is not called if MIDlet.notifyDestroyed() was called.
*
* @param unconditional If true when this method is called, the MIDlet must
* cleanup and release all resources. If false the MIDlet may throw
* MIDletStateChangeException to indicate it does not want to be destroyed
* at this time.
*/

protected void destroyApp(boolean unconditional) throws MIDletStateChangeException {
for (int i = 0; i < 8; i++) {
leds[i].setOff();
}
}

public void switchPressed(ISwitch sw) {
}

public void switchReleased(ISwitch sw) {
if (sw == switch0) {
System.out.println("switch 0 released");
if (switch0Status == false) {
switch0Status = true;
leds[0].setRGB(100, 0, 0);
leds[0].setOn();
} else {
switch0Status = false;
leds[0].setRGB(100, 100, 0);
leds[0].setOn();
}
} else if (sw == switch1) {
System.out.println("switch 1 released");
if (switch1Status == false) {
switch1Status = true;
leds[7].setRGB(100, 0, 0);
leds[7].setOn();
} else {
switch1Status = false;
leds[7].setRGB(100, 100, 0);
leds[7].setOn();
}
}
}

private void sendout() throws Exception {
RadiostreamConnection conn =
(RadiostreamConnection) Connector.open("radiostream://0014.4F01.0000.4bfd:100");
DataInputStream dis = conn.openDataInputStream();
DataOutputStream dos = conn.openDataOutputStream();
try {

for (int j = 1; j < rms.getNumRecords(); j++) {
dos.writeUTF(new String(rms.getRecord(j)));
}
dos.flush();
} catch (NoRouteException e) {
System.out.println("No route to 0014.4F01.0000.0006");
} finally {
dis.close();
dos.close();
conn.close();
}
}

private void deleteRecordStore() {
if (RecordStore.listRecordStores().length > 0) {
for (int k = 0; k < RecordStore.listRecordStores().length; k++) {
try {
RecordStore.deleteRecordStore(RecordStore.listRecordStores()[k]);
} catch (RecordStoreException ex) {
ex.printStackTrace();
}
}
}
}
}


Host Side:



/*
* SunSpotHostApplication.java
*
* Created on Sep 15, 2009 4:03:06 PM;
*/

package org.sunspotworld;

import com.sun.spot.peripheral.radio.RadioFactory;
import com.sun.spot.io.j2me.radiostream.*;
import com.sun.spot.peripheral.NoRouteException;
import com.sun.spot.util.IEEEAddress;

import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.microedition.io.*;

/**
* Sample Sun SPOT host application
*/

public class SunSpotHostApplication {

FileWriter fc = null;
PrintWriter pc = null;

/**
* Print out our radio address.
*/

public void run() {
try {
fc = new java.io.FileWriter("C:\\value.dat", true);
} catch (IOException ex) {
ex.printStackTrace();
}
pc = new java.io.PrintWriter(fc);
long ourAddr = RadioFactory.getRadioPolicyManager().getIEEEAddress();
System.out.println("Our radio address = " + IEEEAddress.toDottedHex(ourAddr));
try {
receive();
} catch (IOException ex) {
Logger.getLogger(SunSpotHostApplication.class.getName()).log(Level.SEVERE, null, ex);
}
}

/**
* Start up the host application.
*
* @param args any command line arguments
*/

public static void main(String[] args) {
SunSpotHostApplication app = new SunSpotHostApplication();
app.run();
}

private void receive() throws IOException {
RadiostreamConnection conn =
(RadiostreamConnection) Connector.open("radiostream://0014.4F01.0000.46e0:100");
DataInputStream dis = conn.openDataInputStream();
DataOutputStream dos = conn.openDataOutputStream();
try {
while (true) {
String question = dis.readUTF();
write2File(question);
}
} catch (NoRouteException e) {
System.out.println("No route to 0014.4F01.0000.0007");
} finally {
dis.close();
dos.close();
conn.close();
pc.close();
try {
fc.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}

private void write2File(String question) {
pc.println(question);
}
}

2009年8月17日星期一

Use NetBeans IDE 6.7 to Combine JAR Files Into a Single JAR File

This article is digested from http://java.sun.com/developer/technicalArticles/java_warehouse/single_jar/

1. Create Mars Rover Viewer project in Samples folder in NetBeans

2. Switch to Files tab, and open build.xml which is ANT script

3. Edit the file, add following text at the bottom of build.xml and before </project> tag

<target name="package-for-store" depends="jar">

<!-- Change the value of this property to be the name of your JAR,
minus the .jar extension. It should not have spaces.
<property name="store.jar.name" value="MyJarName"/>
-->

<property name="store.jar.name" value="MarsRoverViewer"/>

<!-- don't edit below this line -->

<property name="store.dir" value="store"/>
<property name="store.jar" value="${store.dir}/${store.jar.name}.jar"/>

<echo message="Packaging ${application.title} into a single JAR at ${store.jar}"/>

<delete dir="${store.dir}"/>
<mkdir dir="${store.dir}"/>

<jar destfile="${store.dir}/temp_final.jar" filesetmanifest="skip">
<zipgroupfileset dir="dist" includes="*.jar"/>
<zipgroupfileset dir="dist/lib" includes="*.jar"/>

<manifest>
<attribute name="Main-Class" value="${main.class}"/>
</manifest>
</jar>

<zip destfile="${store.jar}">
<zipfileset src="${store.dir}/temp_final.jar"
excludes="META-INF/*.SF, META-INF/*.DSA, META-INF/*.RSA"/>
</zip>

<delete file="${store.dir}/temp_final.jar"/>

</target>



4. Note, this line above



<property name="store.jar.name" value="MarsRoverViewer"/>



The "MarsRoverViewer" is the name of the compiled single jar file you finally get, change it if you want



5. When you done your coding, right click on the build.xml—>Run Target—>Other Targets—>package-for-store



6. a folder called Store should appear in your project folder and the MarsRoverViewer.jar should sit in there



7. double click it and run!



For more detail, please go to http://java.sun.com/developer/technicalArticles/java_warehouse/single_jar/

2009年6月30日星期二

China: 2009 Declaration of the Anonymous Netizens

2009 Declaration of the Anonymous Netizens

To the Internet censors of China,

We are the Anonymous Netizens. We have seen your moves on the Internet. You have deprived your netizens of the freedom of speech. You have come to see technology as your mortal enemy. You have clouded and distorted the truth in collaboration with Party mouthpieces. You have hired commentators to create the “public opinion” you wanted to see. All these are etched into our collective memory. More recently, you forced the installation of Green Dam on the entire population and smothered Google with vicious slander. It is now clear as day: what you want is the complete control and censorship of the Internet. We hereby declare that we, the Anonymous Netizens, are going to launch our attack worldwide on your censorship system starting on July 1st, 2009.

For the freedom of the Internet, for the advancement of Internetization, and for our rights, we are going to acquaint your censorship machine with systematic sabotage and show you just how weak the claws of your censorship really are. We are going to mark you as the First Enemy of the Internet. This is not a single battle; it is but the beginning of a war. Play with your artificial public opinion to your heart's content, for you will soon be submerged in the sea of warring netizens. Your archaic means of propaganda, your epithets borrowed straight from the Cultural Revolution era, your utter ignorance of the Internet itself - these are the tolls of your death bell. You cannot evade us, for we are everywhere. Violence of the state cannot save you - for every one of us that falls, another ten rises. We are familiar with your intrigues. You label some of us as the “vicious few” and dismiss the rest of us as unknowing accomplices; that way you can divide and rule. Go ahead and do that. In fact, we encourage you to do that; the more accustomed you are to viewing your netizens this way, the deeper your self-deception.

You are trying in vain to halt the wheels of history. Even with your technocratic reinforcements, you will not understand the Internet in the foreseeable future. We congratulate you on your adherence to your Cultural-Revolution style conspiracy theories in your dealings with dissent; for we too get nostalgic at times. We toast to your attempts to erect a Great Wall among your netizens, for such epic folly adds spice to any historical narrative. Still, there's something we feel obliged to tell you.

NOBODY wants to topple your regime. We take no interest whatsoever in your archaic view of state power and your stale ideological teachings. You do not understand how your grand narrative dissipated in the face of Internetization. You do not understand why appealing to statism and nationalism no longer works. You cannot break free from your own ignorance of the Internet. Your regime is not our enemy. We are not affiliated in any way with any country or organization, and we are not waging this war on any country or organization, not even on you. YOU are waging this war on yourself. YOU are digging your own grave through corruption and antagonization. We are not interested in you, destined for the sewage of history. You cannot stop the Internetization of the human race. In fact, we won't bat an eyelid even if you decide to sever the transpacific information cables in order to obtain the total control you wanted. The harder you try to roll back history, the more you strain the already taut strings, and the more destructive their final release. You are accelerating your own fall. The sun of tomorrow does not shine on those who are fearing tomorrow itself.

We are the Anonymous Netizens. We are the sum of the world's entire online population. We are coordinated. We are dominant. We are innumerable. For every one of us that falls, another ten joins. We are omnipresent. We are omnipotent. We are unstoppable. We have no weaknesses. We utilize every weakness. We are the humanity under every mask. We are the mirrors of conscience. We are created equal. We are born free. We are an army. We do not forgive. We do not forget.

LIBERTY LEADS THE INTERNET.

WE'RE COMING.

2009年6月2日星期二

I am BACK…

I have not update my tech blog for ages. Sorry, subscribersSmile

I was working on SensorWeb project directed by Dr. Rajkumar Buyya in University of Melbourne. My part of the project is finish. It is an honor to work in this innovative lab.

Here is a introduction of the project:

The SensorWeb project aims at developing Open SensorWeb Architecture (OSWA) and implementing standards compliant platform and middleware for integration of sensor networks with emerging distributed computing platforms such as Grids. It confirms to Web Services standard defined by the W3C (World-Wide Web) and SensorML (Sensor Model Language) standard defined by the OpenGeospatial Consortium. This integration of sensor networks with Grid computing brings out dual benefits:
(i) sensor networks can off-load heavy processing activities to the Grid and
(ii) Grid-based sensor applications can provide advance services for smart-sensing by deploying scenario-specific operators at runtime.

Our Open SensorWeb Architecture consists of four layers: sensor fabric layer, core services, user-level services, and applications. Core services are provided by lower-level layer components whereas components at the user-level layer provide tools for creation of applications and management of life-cycle of data captured through sensor networks. The project primarily aims to develop (a) an interactive development environment, (b) an open and standards-compliant SensorWeb application services middleware, and (c) a coordination language to support the development of sensor applications in various domains including water observation networks, safe road transportation management systems, and Tsunami detection network for the early warning systems. The OSWA-based platform provides a number of sensor and actuation services, such as:
* sensor notification, collection and observation,
* data collection, aggregation and archiving,
* sensor coordination and data processing,
* faulty sensor data correction & management, and
* sensor configuration and directory services.

Now, I am re-focusing on Sun SPOT. This blog focuses on explore and study the fundemental knowledge, skill, experience and idea of not only Sun SPOT but all WSN.

2009年2月24日星期二

SunSPOT BroadcastSample Code

/*
* Copyright (c) 2007 Sun Microsystems, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
**/


package org.sunspotworld.demo;

import java.io.IOException;

import javax.microedition.io.Connector;
import javax.microedition.io.Datagram;
import javax.microedition.io.DatagramConnection;
import javax.microedition.midlet.MIDletStateChangeException;

import com.sun.spot.io.j2me.radiogram.RadiogramConnection;

import com.sun.spot.util.Utils;

/**
* @author: David Mercier <david.mercier@sun.com>
*
* This simple demo shows you how to use the radio to broadcast
* some data to any listening SPOT(s).
*
* There is one thread (startSenderThread) that sends data on a particular
* channel.
* There is a second thread (startReceiverThread) that receives
* data on that same channel.
*
*/

public class BroadcastSample extends javax.microedition.midlet.MIDlet {

protected void startApp() throws MIDletStateChangeException {

System.out.println("I'm about to rock that SPOT !");

startSenderThread();
startReceiverThread();
}

/**
* The receiver thread blocks on the receive function
* so you don't have to sleep between each receive.
*/

public void startReceiverThread() {
new Thread() {
public void run() {
String tmp = null;
RadiogramConnection dgConnection = null;
Datagram dg = null;

try {
dgConnection = (RadiogramConnection) Connector.open("radiogram://:37");
// Then, we ask for a datagram with the maximum size allowed
dg = dgConnection.newDatagram(dgConnection.getMaximumLength());
} catch (IOException e) {
System.out.println("Could not open radiogram receiver connection");
e.printStackTrace();
return;
}

while(true){
try {
dg.reset();
dgConnection.receive(dg);
tmp = dg.readUTF();
System.out.println("Received: " + tmp + " from " + dg.getAddress());
} catch (IOException e) {
System.out.println("Nothing received");
}
}
}
}.start();
}

/**
* The sender thread sends a string each 500 ms
*/

synchronized public void startSenderThread() {
new Thread() {
public void run() {
// We create a DatagramConnection
DatagramConnection dgConnection = null;
Datagram dg = null;
try {
// The Connection is a broadcast so we specify it in the creation string
dgConnection = (DatagramConnection) Connector.open("radiogram://broadcast:37");
// Then, we ask for a datagram with the maximum size allowed
dg = dgConnection.newDatagram(dgConnection.getMaximumLength());
} catch (IOException ex) {
System.out.println("Could not open radiogram broadcast connection");
ex.printStackTrace();
return;
}

while(true){
try {
// We send the message (UTF encoded)
dg.reset();
dg.writeUTF("I rock");
dgConnection.send(dg);
System.out.println("Broadcast is going through");
} catch (IOException ex) {
ex.printStackTrace();
}
Utils.sleep(500);
}
}
}.start();
}

protected void pauseApp() {
}

/**
* Called if the MIDlet is terminated by the system.
* I.e. if startApp throws any exception other than MIDletStateChangeException,
* if the isolate running the MIDlet is killed with Isolate.exit(), or
* if VM.stopVM() is called.
*
* It is not called if MIDlet.notifyDestroyed() was called.
*
* @param unconditional If true when this method is called, the MIDlet must
* cleanup and release all resources. If false the MIDlet may throw
* MIDletStateChangeException to indicate it does not want to be destroyed
* at this time.
*/

protected void destroyApp(boolean unconditional) throws MIDletStateChangeException {
}

}

2008年12月24日星期三

PASSED! Sun Certificated Specialist for NetBeans IDE

Dear Peng (Certification ID#: SUN484247)

Congratulations on completing all the requirements for the
Sun Certified Specialist for NetBeans IDE certification. You were certified on 10/31/2008.

......
......

Congratulations!

SCNBI_Page1_Covered

Certification Department

Credential Verification Report

 

Actually, this is my first IT skill certificate Big Grin

Sun NetBeans Ccertificate

Simple EHCACHE Application

Ehcache is a widely used java distributed cache for general purpose caching, Java EE and light-weight containers.
It features memory and disk stores, replicate by copy and invalidate, listeners, cache loaders, cache extensions, cache exception handlers, a gzip caching servlet filter and much more ...
Ehcache is available under an Apache open source license and is actively developed, maintained and supported.

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package helloehcache;

import java.util.Random;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

/**
*
* @author Administrator
*/

public class Main {

/**
* @param args the command line arguments
*/

public static void main(String[] args) {
//Create a CacheManager instance using defaults.
CacheManager manager = new CacheManager();
//Create a Cache and add it to the CacheManager, then use it.
/*
* @param name the name of the cache. Note that "default" is a reserved name for the defaultCache.
* @param maxElementsInMemory the maximum number of elements in memory, before they are evicted
* @param overflowToDisk whether to use the disk store
* @param eternal whether the elements in the cache are eternal, i.e. never expire
* @param timeToLiveSeconds the default amount of time to live for an element from its creation date
* @param timeToIdleSeconds the default amount of time to live for an element from its last accessed or modified date
*/

Cache memoryOnlyCache = new Cache("CacheName", 5000, true, false, 7, 2);
manager.addCache(memoryOnlyCache);
Cache testCache = manager.getCache("CacheName");

for (int i = 0; i < 10; i++) {
//Queries are coming
Random random = new Random();
String key = "Key" + String.valueOf((int) (random.nextFloat() * 10f));
String value = "Value" + String.valueOf(random.nextFloat() * 10f);
System.out.println(i + ". Quering " + key);
if (testCache.get(key) == null) {
System.out.print("Cache is not hit! ");
testCache.put(new Element(key, value));
System.out.print(key + " " + value + " has been put into cache.");
} else {
System.out.print("Cache is hit! ");
Element cachedResult = testCache.get(key);
System.out.print("The value is " + cachedResult.getObjectValue());
}
System.out.println();
System.out.println();
}
System.out.println(testCache.getStatistics().getCacheMisses() + "/10 missing");
manager.shutdown();
}
}


For more code samples, please visit: http://ehcache.sourceforge.net/documentation/samples.html

2008年11月14日星期五

ISSNIP Summer School 2008

I gave a talk in Intelligent Sensors, Sensor Networks and Information Processing (ISSNIP) yesterday. My talk covers 2 topics, one is Sensor Network Analyzer from company I am working for and Sun SPOT.

Issnip Presentation
View SlideShare presentation or Upload your own.

Daintree's Sensor Network Analyzer (SNA) provides the industry's most comprehensive solution for ZigBee and 802.15.4 testing, analysis and commissioning. For more information, please check: http://www.daintree.net/

For more information about ISSNIP, please check:http://www.ee.unimelb.edu.au/ISSNIP/events/summerschool08.html

2008年10月25日星期六

XMLBeans and SensorML conflict

Digested from: http://forums.sun.com/thread.jspa?threadID=5332907

Hi all,
i have run out of all ideas and i am in a desperate need of help here, our project is stuck in the middle because of this.
I am using xmlbeans to bind xml to java objects. We are using OM, SWE and GML (opengis.net) schema specifications for our xmls. Xmlbeans has no problem creating schema if i am not importing any of the above schemas but when i try to i get the following error

addNewLocation() in net.opengis.sensorML.x101.AbstractDerivableComponentType clashes with addNewLocation() in net.opengis.gml.AbstractFeatureType; attempting to use incompatible return type
found: net.opengis.sensorML.x101.LocationDocument.Location
required: net.opengis.gml.LocationPropertyType

I've researched this for a while and found out that the problem is within SensorML schema and here is a apparent fix for this: [ https://52north.org/twiki/bin/view/Sensornet/SensorML| https://52north.org/twiki/bin/view/Sensornet/SensorML]
Now I am assuming that I am to download (using xmlbeans' sdownload tool) the system.xsd from SensorML folder (schemas.opengis.net) and make that change and since sdownload will create a catalog file, i use that catalog file when compiling the schema and xmlbean will look at the system.xsd on my local machine and go to the net for everything else.
The above is obviously not working since I don't think it ever looks at the system.xsd on my local machine but go to the net for it and obviously stumbles upon the problem.
Does anybody have any idea what i am talking about and how i can fix this?
I will greatly appreciate any insights into this problem. Our project is stuck at this and we can't move forward until this is resolved. thanks

so fixed my own problem :D, oh what a relief.
here is what i did in case some other poor soul encounters this issue.
- I downloaded SCHEMAS_OPENGIS_NET.zip from http://schemas.opengis.net/
- made the changes to the system.xsd file that were suggested here: https://52north.org/twiki/bin/view/Sensornet/SensorML
- my xsd file imported name space like the following

here is what i did in case some other poor soul encounters this issue.
- I downloaded SCHEMAS_OPENGIS_NET.zip from http://schemas.opengis.net/
- made the changes to the system.xsd file that were suggested here: https://52north.org/twiki/bin/view/Sensornet/SensorML
- my xsd file imported name space like the following

<import namespace="http://www.opengis.net/gml" schemaLocation="http://schemas.opengis.net/gml/3.1.1/base/gml.xsd"/>
<import namespace="http://www.opengis.net/swe/1.0.1" schemaLocation="http://schemas.opengis.net/sweCommon/1.0.1/swe.xsd"/>
<include schemaLocation="http://schemas.opengis.net/om/1.0.0/om.xsd"/>


I replaced the url to the name of the above folder. in my case it was SCHEMAS_OPENGIS_NET so now i've



<import namespace="http://www.opengis.net/gml" schemaLocation="SCHEMAS_OPENGIS_NET/gml/3.1.1/base/gml.xsd"/>
<import namespace="http://www.opengis.net/swe/1.0.1" schemaLocation="SCHEMAS_OPENGIS_NET/sweCommon/1.0.1/swe.xsd"/>
<include schemaLocation="SCHEMAS_OPENGIS_NET/om/1.0.0/om.xsd"/>


and that it, compile away :)

reply to this thread if u need help with this issue, i'll try to help if i can :)






Here below is text from https://52north.org/twiki/bin/view/Sensornet/SensorML



Sensor Model Language (SensorML)


SensorML defines concepts and XML encodings for descriptions of sensors, processes and systems. SensorML is used in several OGC SWE web services (e.g. SOS, SPS, SAS).

Compiling SensorML with XmlBeans


If you want to compile the sensorML.xsd schema into Java classes with XmlBeans, you have to do a small change in the schema. Open the system.xsd file and navigate to the definition of sml:AbstractDerivableComponentType. This type is an extension of sml:AbstractProcessType, which is an extension of gml:Feature. That is, why every sml:AbstractDerivableComponent has a location element with type gml:location. The sml:AbstractDerivableComponentType also contains a second location element, which is of type sml:location Having two location elements defined in the sml:AbstractDerivableComponentType leads to compiler errors when compiling the XmlBeans created Java classes.

Solution: The sml:location restricts gml:location to gml:Point and gml:_CurveType. The easiest way to get around with that, is to change the type of the location defined in the sml:AbstractDerivableComponentType at line 24 from sml:location to "gml:location". Although this keeps back the restriction to gml:Point and gml:_CurveType, you can use these types and the schema could be compiled with XmlBeans.



Please write, if you know a better solution!



Validating SensorML with Altova XmlSpy



For those developers, who are using XmlSpy 2005: If you comment out the xs:element name="parameter" type="swe:DataComponentPropertyType" maxOccurs="unbounded" element in line 298, the validation of schema system.xsd should work! -- ChristophStasch - 19 Jun 2007



To validate all SensorML schema with XmlBeans? 2005 rel 3, you also have to outcomment the parameters element in the TransducerType. This is quick and dirty and I will try to see, whether there are better workarounds for this issue. Nevertheless the whole schema do validate for now... -- ChristophStasch - 23 Jun 2007






My comment:



I can successfully compile SensorML using XMLBeans by following the solution from https://52north.org/twiki/bin/view/Sensornet/SensorML. I am not sure why I need to modify the schema location according to http://forums.sun.com/thread.jspa?threadID=5332907. If you have any idea, please let me know. Thanks!

2008年10月21日星期二

SunSPOT Application Template Updated

It seems some API has been changed, but the template file has not reflect these changes yet. Here is the latest template file:

/*
* StartApplication.java
*
* Created on Oct 21, 2008 9:42:46 PM;
*/


package org.sunspotworld;

import com.sun.spot.peripheral.Spot;
import com.sun.spot.sensorboard.EDemoBoard;
import com.sun.spot.sensorboard.peripheral.ISwitch;
import com.sun.spot.sensorboard.peripheral.ITriColorLED;
import com.sun.spot.util.*;

import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

/**
* The startApp method of this class is called by the VM to start the
* application.
*
* The manifest specifies this class as MIDlet-1, which means it will
* be selected for execution.
*/

public class StartApplication extends MIDlet {

private ITriColorLED [] leds = EDemoBoard.getInstance().getLEDs();

protected void startApp() throws MIDletStateChangeException {
System.out.println("Hello, world");
new BootloaderListener().start(); // monitor the USB (if connected) and recognize commands from host

// long ourAddr = RadioFactory.getRadioPolicyManager().getIEEEAddress();
long ourAddr = Spot.getInstance().getRadioPolicyManager().getIEEEAddress();

System.out.println("Our radio address = " + IEEEAddress.toDottedHex(ourAddr));

ISwitch sw1 = EDemoBoard.getInstance().getSwitches()[EDemoBoard.SW1];
leds[0].setRGB(100,0,0); // set color to moderate red
while (sw1.isOpen()) { // done when switch is pressed
leds[0].setOn(); // Blink LED
Utils.sleep(250); // wait 1/4 seconds
leds[0].setOff();
Utils.sleep(1000); // wait 1 second
}
notifyDestroyed(); // cause the MIDlet to exit
}

protected void pauseApp() {
// This is not currently called by the Squawk VM
}

/**
* Called if the MIDlet is terminated by the system.
* I.e. if startApp throws any exception other than MIDletStateChangeException,
* if the isolate running the MIDlet is killed with Isolate.exit(), or
* if VM.stopVM() is called.
*
* It is not called if MIDlet.notifyDestroyed() was called.
*
* @param unconditional If true when this method is called, the MIDlet must
* cleanup and release all resources. If false the MIDlet may throw
* MIDletStateChangeException to indicate it does not want to be destroyed
* at this time.
*/

protected void destroyApp(boolean unconditional) throws MIDletStateChangeException {
for (int i = 0; i < 8; i++) {
leds[i].setOff();
}
}
}


Please note the 2 lines in bold. This bug only happens when you are using SunSPOTApplicationTemplate 1.8 with Purple SDK, in new Blue SDK, it is not a problem. This problem is because the API change.

2008年9月21日星期日

The future of mobile 一起畅想一下手机的未来

The Internet has had an enormous impact on people's lives around the world in the ten years since Google's founding. It has changed politics, entertainment, culture, business, health care, the environment and just about every other topic you can think of. Which got us to thinking, what's going to happen in the next ten years? How will this phenomenal technology evolve, how will we adapt, and (more importantly) how will it adapt to us? We asked ten of our top experts this very question, and during September (our 10th anniversary month) we are presenting their responses. As computer scientist Alan Kay has famously observed, the best way to predict the future is to invent it, so we will be doing our best to make good on our experts' words every day. - Karen Wickre and Alan Eagle, series editors
There are currently about 3.2 billion mobile subscribers in the world, and that number is expected to grow by at least a billion in the next few years. Today, mobile phones are more prevalent than cars (about 800 million registered vehicles in the world) and credit cards (only 1.4 billion of those). While it took 100 years for landline phones to spread to more than 80% of the countries in the world, their wireless descendants did it in 16. And fewer teens are wearing watches now because they use their phones to tell time instead (somewhere Chester Gould is wondering how he got it backwards). So it's safe to say that the mobile phone may be the most prolific consumer product ever invented.
However, have you ever considered just exactly how powerful these ubiquitous devices are? The phone that you have in your pocket, pack, or handbag is probably ten times more powerful than the PC you had on your desk only 8 or 9 years ago (assuming you even had a PC; most mobile users never have). It has a range of sensors that would do a martian lander proud: a clock, power sensor (how low is that battery?), thermometer (because batteries charge poorly at low temperatures), and light meter (to determine screen backlighting) on the more basic phones; a location sensor, accelerometer (detects vector and velocity of motion), and maybe even a compass on more advanced ones. And most importantly, it is by its very nature always connected.
Project out these trends another ten years. You will be carrying with you, 24x7 (a recent study of Chinese mobile customers showed that the majority of them sleep within a meter of their phones), a very powerful, always connected, sensor-rich device. And the cool thing is, so will everyone else. So what are you going to do with it that you aren't doing now? Here are some possibilities:
Smart alerts: Your phone will be smart about your situation and alert you when something needs your attention. This is already happening today -- eBay can text you when you've been outbid, and alert services (such as Google News) can deliver news, sports, or stock updates to you. In the future these applications will get smarter, patiently monitoring your personalized preferences (which will be stored in the network cloud) and delivering only the information you desire. One very useful scenario: your phone knows that you are heading downtown for dinner, and alerts you of transit conditions or the best places to park.
Augmented reality: Your phone uses its arsenal of sensors to understand your situation and provide you information that might be useful. For example, do you really want to know how much is that doggy in the window? Your phone, with its GPS and compass, knows what you are looking at, so it can tell you before you even ask. Plus, what breed it is and the best way to train him.
Crowd sourcing goes mainstream: Your phone is your omnipresent microphone to the world, a way to publish pictures, emails, texts, Twitters, and blog entries. When everyone else is doing the same, you have a world where people from every corner of the planet are covering their experiences in real-time. That massive amount of content gets archived, sorted, and re-deployed to other people in new and interesting ways. Ask the web for the most interesting sites in your vicinity, and your phone shows you reviews and pictures that people have uploaded of nearby attractions. Like what you see? It will send you directions on how to get there.
Sensors everywhere: Your phone knows a lot about the world around you. If you take that intelligence and combine it in the cloud with that of every other phone, we have an incredible snapshot of what is going on in the world right now. Weather updates can be based on not hundreds of sensors, but hundreds of millions. Traffic reports can be based not on helicopters and road sensors, but on the density, speed, and direction of the phones (and people) stuck in the traffic jams.
Tool for development: Your phone may be more than just a convenience, it may be your livelihood. Already, this is true for people in many parts of the world: in southern India, fishermen use text messaging to find the best markets for their daily catch, in South Africa, sugar farmers can receive text messages advising them on how much to irrigate their crops, and throughout sub-Saharan Africa entrepreneurs with mobile phones become phone operators, bringing communications to their villages. These innovations will only increase in the future, as mobile phones become the linchpin for greater economic development.
The future-proof device: Your phone will open up, as the Internet already has, so it will be easy for developers to create or improve applications and content. The ones that you care about get automatically installed on your phone. Let's say you have a piece of software on your phone to improve power management (and therefore battery life). Let's say a developer makes an improvement to the software. The update gets automatically installed on your phone, without you lifting a finger. Your phone actually gets better over time.

Safer software through trust and verification: Your phone will provide tools and information to empower you to decide what to download, what to see, and what to share. Trust is the most important currency in the always connected world, and your phone will help you stay in control of your information. You may choose to share nothing at all (the default mode), or just share certain things with certain people -- your circle of trusted friends and family. You'll make these decisions based on information you get from the service and software providers, and the collective ratings of the community as well. Your phone is like your trusted valet: it knows a lot about you, and won't disclose an iota of it without your OK.

Now, if we can just train it to do your laundry ...
Posted by Andy Rubin, Engineering Director

http://googleblog.blogspot.com/2008/09/future-of-mobile.html


设计师常会讨论到“设计能不能改变世界”这个问题,“改变世界”通常是我们作为个体追求的一种最高理想,我们可以退而求其次,“科技改变世界”是一条公认的真理,在中国也是,当然还有一条是我们不太“想”谈的,但我们可以光明正大来谈“科技”是如何改变人们的生活,如何改变这个社会。什么科技在改变着我们,如果我们把范围定在这几年,第一答案一定会是“互联网”,接下来的也许就是我们这篇文章的主题——“手机”,到2008年上半年中国手机用户已达 6亿,没有什么比它更普及更接近每一个个人,调查显示大部分的中国人睡觉时离手机的距离在1米之内。

这个“1米之内”的数据引用之 Google 官方 Blog 的一篇文章“The future of mobile”,这篇文章谈论了移动和手机的未来。文中说到现在全球已有32亿的手机用户,它的普及率超过了汽车、信用卡和固定电话,手机的16年就完成了固定电话百年的扩展,年轻人更少戴手表因为手机会显示时间,手机无疑是最普及的消费产品。现在手机的功能已经超过8,9年前的PC,而且它有一系列的传感探测器诸如时钟、电能、光感、温度、地理以及动力速度等。文章从几方面出发谈论了手机未来的各种可能性。

1,智能提醒。根据你的所处情况为主动你提供各种信息,诸如建议,各种即使信息等。结合你的个人信息(储存在云网络中)为你提供恰巧需要的信息。

2,AR,虚拟扩增。我们在对 Android 的期待中谈到过一些,手机的传感器可以将物理世界和虚拟信息更主动相连,比如你想知道那窗户内的小狗什么价格出卖时,在你问之前,你的手机会告诉你,甚至更多的信息,如何喂养如何训练。

3,走向主流的群体信息源。你的手机是你面向世界的麦克风,世界每一个角落每一个人都在用手机发布他们的照片、邮件、短信、 Twiiters,Blog等他们的实时体验,这些信息被索引,储存,并通过不同方式重新分发。当你在一地想知道有什么好玩的东西,你手机会告诉你别人的体验。

4,无处不在的传感探测器。手机作为机器可以了解更多周遭的世界,比如基于手机的交通情况。

5,生产工具。印度南方的渔夫使用短信可以找到最好的市场,南非的糖农可以接受到建议短信关于灌溉作物的量度等。

6,自我完善的设备。就和我们电脑上的软件自动更新一样,你的手机也将会一次次的完善成长。

7,经过信用认证的安全。控制分享的信息,基于社区评价的决定等等。

虽然在现在从一个手机来说,它并没有和其他一些数字消费品相差多少,但是由于它被使用的环境,它发挥的作用有些是我们始料未及的,如我们开头说的改变着生活改变着社会改变着世界,那么你来畅想一下手机的未来,它会是怎样,或者说你希望它怎样呢?欢迎发表你的意见。

http://www.hi-id.com/?p=1963