Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Tuesday, June 6, 2017

Set JAVA_HOME in Ubuntu


Ref from 'askubuntu.com'


Three files you could edit, '/etc/environment' is the one prefered in web post:
/etc/environment
/etc/profile
~/.bashrc

But I chose adding file: /etc/profile.d/dnm-build-envsetting.sh

- Reboot pc, and all environments variables settings remains.
        qyang@lgm-pc:~$ cat /etc/environment
        PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games"
        qyang@lgm-pc:~$ cat /etc/profile.d/dnm-build-envsetting.sh
        # Some environmental variables required for DmM builder to work for android build.
        # 2017-JUN-09
        JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64
        ANDROID_HOME=/home/qyang/sandbox/android-sdk-linux
        QTDIR=/home/qyang/sandbox/qt-everywhere-opensource-4.8.7
        export JAVA_HOME
        export ANDROID_HOME
        export QTDIR


My old settings:
yang@lgm-pc:~/testsetupscript$ cat /etc/environment
PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games"
qyang@lgm-pc:~/testsetupscript$ cat /etc/profile
# /etc/profile: system-wide .profile file for the Bourne shell (sh(1))
# and Bourne compatible shells (bash(1), ksh(1), ash(1), ...).

if [ "$PS1" ]; then
  if [ "$BASH" ] && [ "$BASH" != "/bin/sh" ]; then
    # The file bash.bashrc already sets the default PS1.
    # PS1='\h:\w\$ '
    if [ -f /etc/bash.bashrc ]; then
      . /etc/bash.bashrc
    fi
  else
    if [ "`id -u`" -eq 0 ]; then
      PS1='# '
    else
      PS1='$ '
    fi
  fi
fi

# The default umask is now handled by pam_umask.
# See pam_umask(8) and /etc/login.defs.

if [ -d /etc/profile.d ]; then
  for i in /etc/profile.d/*.sh; do
    if [ -r $i ]; then
      . $i
    fi
  done
  unset i
fi

JAVA_HOME=/usr/local/java/jdk1.8.0_25
PATH=$PATH:$HOME/bin:$JAVA_HOME/bin
export JAVA_HOME
export PATH

Monday, August 22, 2011

Java call C function

[1] One Pdf document 'Java call C via JNI'
[2] Sun link of using JNI
[3] Java call C on power PC
[4] Sun book of JNI
[5] JNI and JNA in Wiki
[6] JNA intro on wiki
[7] where to download jna.jar

The JNA library uses a small native library called foreign function interface library (libffi) to dynamically invoke native code. [6]



Java Native Interface[5]

The Java Native Interface has a high overhead associated with it, making it costly to cross the boundary between code running on the JVM and native code.[69][70] Java Native Access (JNA) provides Java programs easy access to native shared libraries (DLLs on Windows) without writing anything but Java code—no JNI or native code is required. This functionality is comparable to Windows' Platform/Invoke and Python's ctypes. Access is dynamic at runtime without code generation. But it comes with a cost and JNA is usually slower than JNI.[71]

Sunday, August 7, 2011

C Call Java function under Linux/Windows

[1] Ref from codeproject



[q.yang@localhost CTest]$ ll
total 16
-rwxr--r-- 1 q.yang developer 7298 2011-08-05 15:03 CTest.cpp
drwxr-xr-x 2 q.yang developer 4096 2011-08-08 11:31 debug
-rwxr--r-- 1 q.yang developer 838 2011-08-08 11:32 makefile
[q.yang@localhost CTest]$ echo $JAVA_HOME
/usr/java/default
[q.yang@localhost CTest]$ pwd
/home/q.yang/EclipseCDT/qywkspace/Sandbox/Sample_017_CCallJava_via_JNI/CTest
[q.yang@localhost CTest]$ cat makefile
DESTDIR = ./debug
PROGRAM = $(DESTDIR)/CCallJava
SRCDIR = ./
CC = g++
OBJS := $(addprefix $(DESTDIR)/,CTest.o)
DEBUG = -g
CFLAGS = -Wall -c $(DEBUG) -D GSN_HOST_NOT_SUPPORT_RD_CONFIG
INCL = -I ./include -I $(JAVA_HOME)/include -I $(JAVA_HOME)/include/linux
LIB_FLAGS = -ljvm
LD_FLAGS = -L $(JAVA_HOME)/jre/lib/i386/server/ -L $(JAVA_HOME)/jre/lib/i386/
#-----------------------------------------------
#Compile and Link Image
#------------------------------------------------
all: $(PROGRAM)
$(PROGRAM): $(OBJS)
$(CC) -o $(PROGRAM) $(OBJS) -pthread $(LD_FLAGS) $(LIB_FLAGS)
$(DESTDIR)/%.o:$(SRCDIR)/%.cpp
$(CC) -c $(CFLAGS) $< -o $@ $(INCL)
#-----------------------------------------------
#Clean obj and image files.
#------------------------------------------------
clean :
rm -f $(OBJS)
rm -f $(PROGRAM)



COMPILE ALL JAVA PROGRAM
------------------------------
[q.yang@localhost TestStruct]$ javac *.java


RUN C PROGRAM TO CALL JAVA FUNCTION
------------------------------------
[q.yang@localhost Sandbox]$ tree Sample_017_CCallJava_via_JNI/
Sample_017_CCallJava_via_JNI/
|-- CTest
| |-- CTest.cpp
| |-- debug
| | |-- CCallJava
| | `-- CTest.o
| `-- makefile
|-- JavaSrc
| `-- TestStruct
| |-- ControlDetail.class
| |-- ControlDetail.java
| |-- HelloWorld.class
| |-- HelloWorld.java
| |-- ReturnData.class
| |-- ReturnData.java
| |-- WorkOrder.class
| `-- WorkOrder.java
`-- readme.txt


[q.yang@localhost CTest]$ export LD_LIBRARY_PATH=$JAVA_HOME/jre/lib/i386/server/:$JAVA_HOME/jre/lib/i386/
[q.yang@localhost CTest]$ echo $LD_LIBRARY_PATH
/usr/java/default/jre/lib/i386/server/:/usr/java/default/jre/lib/i386/

[q.yang@localhost debug]$ ./CCallJava
Struct Created in C has values:
ID:11
Name:HR-HW
IP:10.32.164.133
Port:9099
Hello World!
This is the main function in HelloWorld class

TestCall:Called from the C Program


Going to Call DisplayStruct
Structure is:
-------------------------
Name:HR-HW
IP:10.32.164.133
Port9099


Going to call DisplayStructArray From C

WorkOrders are Given hereunder:
----------------------------
<---Work Order Number:1<---
Sum_Serial_ID: 2000
Access_Number: 2878430
Action_Type: 04
Effective_Date: 25-12-2007 12:20:30 PM
Fetch_Flag: 0
Reason: Executed Successfully
Access_Source: PMS
<---Work Order Number:2<---
Sum_Serial_ID: 1000
Access_Number: 2878000
Action_Type: T4
Effective_Date: 25-12-2007 11:20:30 PM
Fetch_Flag: 0
Reason:
Access_Source: RMS
Going to return an object from java


Values Returned from Object are:
returnValue=1
Log=Successfull function call
[q.yang@localhost debug]$

Friday, August 5, 2011

Install Java SE JDK6 under Fedora 9

[1] http://www.oracle.com/technetwork/java/javase/install-linux-rpm-137089.html
[2] http://fedoraunity.org/Members/zcat/using-sun-java-instead-of-openjdk

[q.yang@localhost Download]$ ./jdk-6u26-linux-i586-rpm.bin
[q.yang@localhost Download]$ ./jdk-6u26-linux-i586-rpm.bin
Unpacking...
Checksumming...
Extracting...
UnZipSFX 5.50 of 17 February 2002, by Info-ZIP (Zip-Bugs@lists.wku.edu).
inflating: jdk-6u26-linux-i586.rpm
inflating: sun-javadb-common-10.6.2-1.1.i386.rpm
inflating: sun-javadb-core-10.6.2-1.1.i386.rpm
inflating: sun-javadb-client-10.6.2-1.1.i386.rpm
inflating: sun-javadb-demo-10.6.2-1.1.i386.rpm
inflating: sun-javadb-docs-10.6.2-1.1.i386.rpm
inflating: sun-javadb-javadoc-10.6.2-1.1.i386.rpm
error: can't create transaction lock on /var/lib/rpm/__db.000
Installing JavaDB
error: can't create transaction lock on /var/lib/rpm/__db.000

Done.
[q.yang@localhost Download]$ su
Password:
[root@localhost Download]# ./jdk-6u26-linux-i586-rpm.bin
Unpacking...
Checksumming...
Extracting...
UnZipSFX 5.50 of 17 February 2002, by Info-ZIP (Zip-Bugs@lists.wku.edu).
replace jdk-6u26-linux-i586.rpm? [y]es, [n]o, [A]ll, [N]one, [r]ename: y
inflating: jdk-6u26-linux-i586.rpm
replace sun-javadb-common-10.6.2-1.1.i386.rpm? [y]es, [n]o, [A]ll, [N]one, [r]ename: y
inflating: sun-javadb-common-10.6.2-1.1.i386.rpm
replace sun-javadb-core-10.6.2-1.1.i386.rpm? [y]es, [n]o, [A]ll, [N]one, [r]ename: y
inflating: sun-javadb-core-10.6.2-1.1.i386.rpm
replace sun-javadb-client-10.6.2-1.1.i386.rpm? [y]es, [n]o, [A]ll, [N]one, [r]ename: y
inflating: sun-javadb-client-10.6.2-1.1.i386.rpm
replace sun-javadb-demo-10.6.2-1.1.i386.rpm? [y]es, [n]o, [A]ll, [N]one, [r]ename: y
inflating: sun-javadb-demo-10.6.2-1.1.i386.rpm
replace sun-javadb-docs-10.6.2-1.1.i386.rpm? [y]es, [n]o, [A]ll, [N]one, [r]ename: y
inflating: sun-javadb-docs-10.6.2-1.1.i386.rpm
replace sun-javadb-javadoc-10.6.2-1.1.i386.rpm? [y]es, [n]o, [A]ll, [N]one, [r]ename: A
inflating: sun-javadb-javadoc-10.6.2-1.1.i386.rpm
Preparing... ########################################### [100%]
1:jdk ########################################### [100%]
Unpacking JAR files...
rt.jar...
jsse.jar...
charsets.jar...
tools.jar...
localedata.jar...
plugin.jar...
javaws.jar...
deploy.jar...
Installing JavaDB
Preparing... ########################################### [100%]
1:sun-javadb-common ########################################### [ 17%]
2:sun-javadb-core ########################################### [ 33%]
3:sun-javadb-client ########################################### [ 50%]
4:sun-javadb-demo ########################################### [ 67%]
5:sun-javadb-docs ########################################### [ 83%]
6:sun-javadb-javadoc ########################################### [100%]

Java(TM) SE Development Kit 6 successfully installed.

Product Registration is FREE and includes many benefits:
* Notification of new versions, patches, and updates
* Special offers on Oracle products, services and training
* Access to early releases and documentation

Product and system data will be collected. If your configuration
supports a browser, the JDK Product Registration form will
be presented. If you do not register, none of this information
will be saved. You may also register your JDK later by
opening the register.html file (located in the JDK installation
directory) in a browser.

For more information on what data Registration collects and
how it is managed and used, see:
http://java.sun.com/javase/registration/JDKRegistrationPrivacy.html

Press Enter to continue.....


Done.
[root@localhost Download]# exit
exit
[q.yang@localhost Download]$ java -version
java version "1.6.0"
OpenJDK Runtime Environment (build 1.6.0-b09)
OpenJDK Client VM (build 1.6.0-b09, mixed mode)
[q.yang@localhost Download]$


CHANGE DEFAULT JDK TO SUN INSTEAD OF OPEN JDK [2]
----------------------------------------------
[q.yang@localhost ~]$ source /etc/profile.d/sunjava.sh
[q.yang@localhost ~]$ echo $PATH
/usr/java/default/bin:/usr/java/default/bin:/usr/kerberos/bin:/usr/lib/ccache:/usr/local/bin:/bin:/usr/bin:/home/q.yang/bin:/sbin:/usr/sbin:/opt/wx/2.8/bin:/opt/freescale/usr/local/gcc-4.1.2-glibc-2.5-nptl-3/arm-none-linux-gnueabi/bin:/opt/codeblocks20100721-svn/bin/:/home/q.yang/CodeSourcery/arm-2010q1/bin:/opt/codeblocks20100721-svn/bin:/home/q.yang/EclipseCDT/eclipse
[q.yang@localhost ~]$ java -version
java version "1.6.0_26"
Java(TM) SE Runtime Environment (build 1.6.0_26-b03)
Java HotSpot(TM) Client VM (build 20.1-b02, mixed mode, sharing)
[q.yang@localhost ~]$ cat /etc/profile.d/sunjava.sh
export JAVA_HOME=/usr/java/default
export PATH=$JAVA_HOME/bin:$PATH

Wednesday, May 25, 2011

Running Java on Embedded Linux

[1] Libffi Official Link
[2] http://www.linuxquestions.org/questions/linux-kernel-70/locale-support-in-linux-kernel-811248/
[3] http://java.sun.com/developer/technicalArticles/JavaTechandLinux/RedHat/ ---NPTL from RedHat
[4] http://en.wikipedia.org/wiki/NPTL#cite_note-0 ---NPTL
[5] http://en.wikipedia.org/wiki/LinuxThreads ---NPTL replace LinuxThreads
[6] http://dev.maxtrack.com.br/index.php/Td60_notes#Set_Locale --- locale issue
[7] http://sourceware.org/ml/libffi-discuss/2009/msg00004.html --- mail list for using libffi for power pc.
[8] http://www.linuxquestions.org/questions/linux-general-1/locale-cannot-set-lc_all-to-default-locale-no-such-file-or-directory-218622/ --- check locale
[9] http://www.busybox.net/ --- busy box home page
[10] http://groups.google.com/group/netusg20/tree/browse_frm/month/2010-01/2d17cfad90f32150?rnum=31&lnk=ol --- localedef crash (same as locale-gen crash)
[11] http://www.linuxquestions.org/questions/linux-newbie-8/detect-glibc-version-based-on-libpthread-so-627968/ --- check Glibc version
[12] http://ubuntuforums.org/showthread.php?t=829866 ---- java class library loading error.
[13] http://www.coderanch.com/t/110728/Linux-UNIX/find-vma-failed-warning ---VM Stack warning.
[14] http://www.velocityreviews.com/forums/t149023-cant-detect-initial-thread-stack-location.html --- JVM Stack warning.
[15] Embedded JRE Download from Oracle --- EJRE
[16] http://www.linux-mtd.infradead.org/faq/jffs2.html#L_bbhandle ---- jffs2 file system CRC error on node



RUN REST SERVER ON LINUX USING JAVA
------------------------------------
[root@10 HandMade]# java -jar Make.jar &
[1] 384
[root@10 HandMade]# Jan 3, 1970 1:52:04 AM org.restlet.engine.http.connector.HttpServerHelper start
INFO: Starting the internal HTTP server on port 8182

From Browser:
http://10.10.20.89:8182/powergridiq/datapac
[root@10 HandMade]# ps -A --sort -rss -o comm,pmem |head -n 11
COMMAND %MEM
java 57.7
sh 5.5
ps 3.0
init 0.9
head 0.8
kthreadd 0.0
ksoftirqd/0 0.0
events/0 0.0
khelper 0.0
async/mgr 0.0
[root@10 HandMade]# cat /proc/meminfo
MemTotal: 28952 kB
MemFree: 1424 kB
Buffers: 0 kB
Cached: 11684 kB
SwapCached: 0 kB
Active: 13344 kB
Inactive: 12100 kB
Active(anon): 6732 kB
Inactive(anon): 7028 kB
Active(file): 6612 kB
Inactive(file): 5072 kB
Unevictable: 0 kB
Mlocked: 0 kB
SwapTotal: 0 kB
SwapFree: 0 kB
Dirty: 0 kB
Writeback: 0 kB
AnonPages: 13792 kB
Mapped: 4444 kB
Shmem: 0 kB
Slab: 1100 kB
SReclaimable: 256 kB
SUnreclaim: 844 kB
KernelStack: 264 kB
PageTables: 116 kB
NFS_Unstable: 0 kB
Bounce: 0 kB
WritebackTmp: 0 kB
CommitLimit: 14476 kB
Committed_AS: 31352 kB
VmallocTotal: 745472 kB
VmallocUsed: 428 kB
VmallocChunk: 744912 kB





Access REST server from browser
http://10.10.20.89:8182/powergridiq/datapac



WORKAROUND FOR CLASS LIBRARY LOADING ERROR
----------------------------------------------
Here's a workaround. It's for making the package install and configure properly, not for actually running java in the chrooted environment.

1. Install sun-java6-bin. It fails to configure.
2. Find out where libjli.so is. Do "locate libjli.so". In my case it was here:

/opt/jdk1.7.0/jre/lib/i386/jli/libjli.so

3. Set the LD_LIBRARY_PATH variable so that the package can configure properly. Enter the following command (using your location of libjli.so):

LD_LIBRARY_PATH=/opt/jdk1.7.0/jre/lib/i386/jli dpkg --configure -a

Hopefully it's now installed and configured correctly.


TRY RUNNING JAVA PROGRAM AFTER LOCALE IS SET CORRECTLY
-----------------------------------------------------
[root@10 HandMade]# java -jar Make.jar
Java HotSpot(TM) Client VM warning: Can't detect initial thread stack location - find_vma failed
Jan 1, 1970 12:44:27 AM org.restlet.engine.http.connector.HttpServerHelper start
INFO: Starting the internal HTTP server on port 8182



Calling C function from Java. [1]
-----------------------------------


CHECK GLIBC VERSION [11]
-------------------
[root@GsnCommsModule lib]# cat /lib/libpthread.so.0 |grep GLIBC
GLIBC_2.4
GLIBC_PRIVATE
pthread_cond_timedwait@@GLIBC_2.4
__libc_dlopen_mode@@GLIBC_PRIVATE
tfind@@GLIBC_2.4
pthread_attr_getaffinity_np@@GLIBC_2.4
__fsetlocking@@GLIBC_2.4



SOLVE LOCALE ISSUE TO GET EMBEDDED JAVA RUN IN EMBEDDED LINUX [2]
-----------------------------------------------------------------
From [8]
[root@GsnCommsModule /]# locale
LANG=
LC_CTYPE="POSIX"
LC_NUMERIC="POSIX"
LC_TIME="POSIX"
LC_COLLATE="POSIX"
LC_MONETARY="POSIX"
LC_MESSAGES="POSIX"
LC_PAPER="POSIX"
LC_NAME="POSIX"
LC_ADDRESS="POSIX"
LC_TELEPHONE="POSIX"
LC_MEASUREMENT="POSIX"
LC_IDENTIFICATION="POSIX"
LC_ALL=
[root@GsnCommsModule /]# locale -a
C
POSIX
[root@GsnCommsModule /]#

AFTER USING CODESOURCERY arm-2010q1 COMPILER
----------------------------------------------
arm-2010q1 is using newer version GCC (GCC4.41)
So all locale and language suit are generated in LTIB
Extra folders are removed so that only support wanted languages and font coding.

[root@LIQ-GateWay /]# locale
LANG=en_US.UTF-8
LC_CTYPE="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_PAPER="en_US.UTF-8"
LC_NAME="en_US.UTF-8"
LC_ADDRESS="en_US.UTF-8"
LC_TELEPHONE="en_US.UTF-8"
LC_MEASUREMENT="en_US.UTF-8"
LC_IDENTIFICATION="en_US.UTF-8"
LC_ALL=en_US.UTF-8
[root@LIQ-GateWay /]# locale -a
C
en_GB
en_GB.utf8
en_US
en_US.utf8
POSIX

[root@LIQ-GateWay /]# locale -m
UTF-8

Wednesday, August 18, 2010

FW: Top Ten Errors Java Programmers Make

From: http://www.javacoffeebreak.com/articles/toptenerrors.html


Top Ten Errors Java Programmers Make
(How to spot them. How to fix/prevent them.)

By David Reilly

Whether you program regularly in Java, and know it like the back of your hand, or whether you're new to the language or a casual programmer, you'll make mistakes. It's natural, it's human, and guess what? You'll more than likely make the same mistakes that others do, over and over again. Here's my top ten list of errors that we all seem to make at one time or another, how to spot them, and how to fix them.
10. Accessing non-static member variables from static methods (such as main)

Many programmers, particularly when first introduced to Java, have problems with accessing member variables from their main method. The method signature for main is marked static - meaning that we don't need to create an instance of the class to invoke the main method. For example, a Java Virtual Machine (JVM) could call the class MyApplication like this :-

MyApplication.main ( command_line_args );

This means, however, that there isn't an instance of MyApplication - it doesn't have any member variables to access! Take for example the following application, which will generate a compiler error message.

public class StaticDemo
{
public String my_member_variable = "somedata";

public static void main (String args[])
{
// Access a non-static member from static method
System.out.println ("This generates a compiler error" +
my_member_variable );
}
}

If you want to access its member variables from a non-static method (like main), you must create an instance of the object. Here's a simple example of how to correctly write code to access non-static member variables, by first creating an instance of the object.

public class NonStaticDemo
{
public String my_member_variable = "somedata";

public static void main (String args[])
{
NonStaticDemo demo = new NonStaticDemo();

// Access member variable of demo
System.out.println ("This WON'T generate an error" +
demo.my_member_variable );
}
}

9. Mistyping the name of a method when overriding

Overriding allows programmers to replace a method's implementation with new code. Overriding is a handy feature, and most OO programmers make heavy use of it. If you use the AWT 1.1 event handling model, you'll often override listener implementations to provide custom functionality. One easy trap to fall into with overriding, is to mistype the method name. If you mistype the name, you're no longer overriding a method - you're creating an entirely new method, but with the same parameter and return type.

public class MyWindowListener extends WindowAdapter {
// This should be WindowClosed
public void WindowClose(WindowEvent e) {
// Exit when user closes window
System.exit(0);
}
});

Compilers won't pick up on this one, and the problem can be quite frustrating to detect. In the past, I've looked at a method, believed that it was being called, and taken ages to spot the problem. The symptom of this error will be that your code isn't being called, or you think the method has skipped over its code. The only way to ever be certain is to add a println statement, to record a message in a log file, or to use good trace debugger (like Visual J++ or Borland JBuilder) and step through line by line. If your method still isn't being called, then it's likely you've mistyped the name.
8. Comparison assignment ( = rather than == )

This is an easy error to make. If you're used other languages before, such as Pascal, you'll realize just how poor a choice this was by the language's designers. In Pascal, for example, we use the := operator for assignment, and leave = for comparison. This looks like a throwback to C/C++, from which Java draws its roots.

Fortunately, even if you don't spot this one by looking at code on the screen, your compiler will. Most commonly, it will report an error message like this : "Can't convert xxx to boolean", where xxx is a Java type that you're assigning instead of comparing.
7. Comparing two objects ( == instead of .equals)

When we use the == operator, we are actually comparing two object references, to see if they point to the same object. We cannot compare, for example, two strings for equality, using the == operator. We must instead use the .equals method, which is a method inherited by all classes from java.lang.Object.

Here's the correct way to compare two strings.

String abc = "abc"; String def = "def";

// Bad way
if ( (abc + def) == "abcdef" )
{
......
}

// Good way
if ( (abc + def).equals("abcdef") )
{
.....
}

6. Confusion over passing by value, and passing by reference

This can be a frustrating problem to diagnose, because when you look at the code, you might be sure that its passing by reference, but find that its actually being passed by value. Java uses both, so you need to understand when you're passing by value, and when you're passing by reference.

When you pass a primitive data type, such as a char, int, float, or double, to a function then you are passing by value. That means that a copy of the data type is duplicated, and passed to the function. If the function chooses to modify that value, it will be modifying the copy only. Once the function finishes, and control is returned to the returning function, the "real" variable will be untouched, and no changes will have been saved. If you need to modify a primitive data type, make it a return value for a function, or wrap it inside an object.

When you pass a Java object, such as an array, a vector, or a string, to a function then you are passing by reference. Yes - a String is actually an object, not a primitive data type. So that means that if you pass an object to a function, you are passing a reference to it, not a duplicate. Any changes you make to the object's member variables will be permanent - which can be either good or bad, depending on whether this was what you intended.

On a side note, since String contains no methods to modify its contents, you might as well be passing by value.
5. Writing blank exception handlers

I know it's very tempting to write blank exception handlers, and to just ignore errors. But if you run into problems, and haven't written any error messages, it becomes almost impossible to find out the cause of the error. Even the simplest exception handler can be of benefit. For example, put a try { .. } catch Exception around your code, to catch ANY type of exception, and print out the message. You don't need to write a custom handler for every exception (though this is still good programming practice). Don't ever leave it blank, or you won't know what's happening.

For example

public static void main(String args[])
{
try {
// Your code goes here..
}
catch (Exception e)
{
System.out.println ("Err - " + e );
}
}

4. Forgetting that Java is zero-indexed

If you've come from a C/C++ background, you may not find this quite as much a problem as those who have used other languages. In Java, arrays are zero-indexed, meaning that the first element's index is actually 0. Confused? Let's look at a quick example.

// Create an array of three strings
String[] strArray = new String[3];

// First element's index is actually 0
strArray[0] = "First string";

// Second element's index is actually 1
strArray[1] = "Second string";

// Final element's index is actually 2
strArray[2] = "Third and final string";

In this example, we have an array of three strings, but to access elements of the array we actually subtract one. Now, if we were to try and access strArray[3], we'd be accessing the fourth element. This will case an ArrayOutOfBoundsException to be thrown - the most obvious sign of forgetting the zero-indexing rule.

Other areas where zero-indexing can get you into trouble is with strings. Suppose you wanted to get a character at a particular offset within a string. Using the String.charAt(int) function you can look this information up - but under Java, the String class is also zero-indexed. That means than the first character is at offset 0, and second at offset 1. You can run into some very frustrating problems unless you are aware of this - particularly if you write applications with heavy string processing. You can be working on the wrong character, and also throw exceptions at run-time. Just like the ArrayOutOfBoundsException, there is a string equivalent. Accessing beyond the bounds of a String will cause a StringIndexOutOfBoundsException to be thrown, as demonstrated by this example.

public class StrDemo
{
public static void main (String args[])
{
String abc = "abc";

System.out.println ("Char at offset 0 : " + abc.charAt(0) );
System.out.println ("Char at offset 1 : " + abc.charAt(1) );
System.out.println ("Char at offset 2 : " + abc.charAt(2) );

// This line should throw a StringIndexOutOfBoundsException
System.out.println ("Char at offset 3 : " + abc.charAt(3) );
}
}

Note too, that zero-indexing doesn't just apply to arrays, or to Strings. Other parts of Java are also indexed, but not always consistently. The java.util.Date, and java.util.Calendar classes start their months with 0, but days start normally with 1. This problem is demonstrated by the following application.

import java.util.Date;
import java.util.Calendar;

public class ZeroIndexedDate
{
public static void main (String args[])
{
// Get today's date
Date today = new Date();

// Print return value of getMonth
System.out.println ("Date.getMonth() returns : " +
today.getMonth());

// Get today's date using a Calendar
Calendar rightNow = Calendar.getInstance();

// Print return value of get ( Calendar.MONTH )
System.out.println ("Calendar.get (month) returns : " +
rightNow.get ( Calendar.MONTH ));

}
}

Zero-indexing is only a problem if you don't realize that its occurring. If you think you're running into a problem, always consult your API documentation.
3. Preventing concurrent access to shared variables by threads

When writing multi-threaded applications, many programmers (myself included) often cut corners, and leave their applications and applets vulnerable to thread conflicts. When two or more threads access the same data concurrently, there exists the possibility (and Murphy's law holding, the probability) that two threads will access or modify the same data at the same time. Don't be fooled into thinking that such problems won't occur on single-threaded processors. While accessing some data (performing a read), your thread may be suspended, and another thread scheduled. It writes its data, which is then overwritten when the first thread makes its changes.

Such problems are not just limited to multi-threaded applications or applets. If you write Java APIs, or JavaBeans, then your code may not be thread-safe. Even if you never write a single application that uses threads, people that use your code WILL. For the sanity of others, if not yourself, you should always take precautions to prevent concurrent access to shared data.

How can this problem be solved? The simplest method is to make your variables private (but you do that already, right?) and to use synchronized accessor methods. Accessor methods allow access to private member variables, but in a controlled manner. Take the following accessor methods, which provide a safe way to change the value of a counter.

public class MyCounter
{
private int count = 0; // count starts at zero

public synchronized void setCount(int amount)
{
count = amount;
}

public synchronized int getCount()
{
return count;
}
}

2. Capitalization errors

This is one of the most frequent errors that we all make. It's so simple to do, and sometimes one can look at an uncapitalized variable or method and still not spot the problem. I myself have often been puzzled by these errors, because I recognize that the method or variable does exist, but don't spot the lack of capitalization.

While there's no silver bullet for detecting this error, you can easily train yourself to make less of them. There's a very simple trick you can learn :-

* all methods and member variables in the Java API begin with lowercase letters
* all methods and member variables use capitalization where a new word begins e.g - getDoubleValue()

If you use this pattern for all of your member variables and classes, and then make a conscious effort to get it right, you can gradually reduce the number of mistakes you'll make. It may take a while, but it can save some serious head scratching in the future.
(drum roll)
And the number one error that Java programmers make !!!!!


1. Null pointers!

Null pointers are one of the most common errors that Java programmers make. Compilers can't check this one for you - it will only surface at runtime, and if you don't discover it, your users certainly will.

When an attempt to access an object is made, and the reference to that object is null, a NullPointerException will be thrown. The cause of null pointers can be varied, but generally it means that either you haven't initialized an object, or you haven't checked the return value of a function.

Many functions return null to indicate an error condition - but unless you check your return values, you'll never know what's happening. Since the cause is an error condition, normal testing may not pick it up - which means that your users will end up discovering the problem for you. If the API function indicates that null may be returned, be sure to check this before using the object reference!

Another cause is where your initialization has been sloppy, or where it is conditional. For example, examine the following code, and see if you can spot the problem.

public static void main(String args[])
{
// Accept up to 3 parameters
String[] list = new String[3];

int index = 0;

while ( (index < args.length) && ( index < 3 ) )
{
list[index++] = args[index];
}

// Check all the parameters
for (int i = 0; i < list.length; i++)
{
if (list[i].equals "-help")
{
// .........
}
else
if (list[i].equals "-cp")
{
// .........
}
// else .....
}
}

This code (while a contrived example), shows a common mistake. Under some circumstances, where the user enters three or more parameters, the code will run fine. If no parameters are entered, you'll get a NullPointerException at runtime. Sometimes your variables (the array of strings) will be initialized, and other times they won't. One easy solution is to check BEFORE you attempt to access a variable in an array that it is not equal to null.
Summary

These errors represent but some of the many that we all make. Though it is impossible to completely eliminate errors from the coding process, with care and practice you can avoid repeating the same ones. Rest assured, however, that all Java programmers encounter the same sorts of problems. It's comforting to know, that while you work late into the night tracking down an error, someone, somewhere, sometime, will make the same mistake!
We'd like to thank the readers of the comp.lang.java.programmer newsgroup for their suggestions for the top ten. Regrettably, due to the number of submissions, not every error could be featured - but we think this "Top Ten" list represents the most popular and frequent errors people make.

Tuesday, October 6, 2009

java socket comms

/**
* SimpleSocketClient.java
*
* Created on October 2, 2002, 5:34 PM
*/

import java.awt.*;
import java.net.*; //contains socket class
import java.io.*; //The java.io package provides input and output classes that we will use to extract the data from the response

import java.applet.Applet;


/**
*
* @author Stephen Potts
*/
public class AppletSocketClient // extends Applet

{
Socket socket1;
int portNumber = 20000;
String str = "";


ObjectInputStream ois;

InputStream istream;
OutputStream ostream;

byte[] theByteArray;

/** Creates a new instance of AppletSocketClient */
public AppletSocketClient()
{



try
{


// socket1 = new Socket(InetAddress.getLocalHost(), portNumber);

socket1 = new Socket("192.168.0.201", portNumber);

// socket1 = new Socket("192.168.0.201", portNumber,"192.168.0.1", 8000);

System.out.println("--Debug: build socket ");

istream=socket1.getInputStream();

// ois = new ObjectInputStream(istream);

System.out.println("--Debug: build input stream ");

ostream=socket1.getOutputStream();

// ObjectOutputStream oos = new ObjectOutputStream(socket1.getOutputStream());

System.out.println("--Debug: build output stream ");

str = "initialize";

System.out.println("--Debug: about to send string "+str);

theByteArray=str.getBytes();

ostream.write(theByteArray);

// oos.writeObject(str);

// System.out.println("--Debug: out string"+str);;
//
// str = (String) ois.readObject();
//
// System.out.println("--Debug: input string"+str);
//
// oos.writeObject("bye");



// while ((str = (String) ois.readObject()) == null);

// while ((str = (String) ois.readObject()) != null)
// {
// System.out.println(str);
// oos.writeObject("bye");
//
// if (str.equals("bye bye"))
// break;
// }

System.out.println("--Debug:ois close, oos close, socket close");

// ois.close();
// oos.close();
socket1.close();

} catch (Exception e)
{
System.out.println("Exception " + e);
}
}

public void paint(Graphics g)
{
g.drawString("Hello, Applet", 10, 10);
}


public static void main(String args[])
{
System.out.println("--Debug: main start ");

AppletSocketClient lsp = new AppletSocketClient();
}

}



++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

/*
* LoopingSocketServer.java
*
* Created on October 2, 2002, 5:24 PM
*/

import java.net.*;
import java.io.*;

/**
*
* @author Stephen Potts
*/
public class AppSocketServer
{
ServerSocket servSocket;
Socket fromClientSocket;
int cTosPortNumber = 20000;
String str;


/** Creates a new instance of LoopingSocketServer */
public AppSocketServer()
{
// Create ServerSocket to listen for connections
try
{
servSocket = new ServerSocket(cTosPortNumber);

// Wait for client to connnect, then get Socket
System.out.println("ServerSocket created");
System.out.println("Waiting for a connection on " + cTosPortNumber);

fromClientSocket = servSocket.accept();
System.out.println("fromClientSocket accepted");

// Use ObjectOutputStream to send String to the client
ObjectOutputStream oos =
new ObjectOutputStream(fromClientSocket.getOutputStream());

//Use ObjectInputStream to get String from client
ObjectInputStream ois =
new ObjectInputStream(fromClientSocket.getInputStream());


while ((str = (String) ois.readObject()) != null)
{
System.out.println("The message from client is *** " + str);

if (str.equals("bye"))
{
oos.writeObject("bye bye");
break;
}
else
{
str = "Server returns " + str;
oos.writeObject(str);
}

}
oos.close();

// Close Sockets
fromClientSocket.close();
} catch (Exception e)
{
System.out.println("Exception " + e);
}
}

public static void main(String args[])
{
AppSocketServer lss = new AppSocketServer();
}


}

Thursday, January 15, 2009

提高Java代码可重用性的三个措施

From: http://www.java114.com/278/content4210.html


提高Java代码可重用性的三个措施
 本文介绍了三种修改现有代码提高其可重用性的方法,它们分别是:改写类的实例方法,把参数类型改成接口,选择最简单的参数接口类型。  

措施一:改写类的实例方法  通过类继承实现代码重用不是精确的代码重用技术,因此它并不是最理想的代码重用机制。换句话说,如果不继承整个类的所有方法和数据成员,我们无法重用该类里面的单个方法。继承总是带来一些多余的方法和数据成员,它们总是使得重用类里面某个方法的代码复杂化。另外,派生类对父类的依赖关系也使得代码进一步复杂化:对父类的改动可能影响子类;修改父类或者子类中的任意一个类时,我们很难记得哪一个方法被子类覆盖、哪一个方法没有被子类覆盖;最后,子类中的覆盖方法是否要调用父类中的对应方法有时并不显而易见。  任何方法,只要它执行的是某个单一概念的任务,就其本身而言,它就应该是首选的可重用代码。为了重用这种代码,我们必须回归到面向过程的编程模式,把类的实例方法移出成为全局性的过程。为了提高这种过程的可重用性,过程代码应该象静态工具方法一样编写:它只能使用自己的输入参数,只能调用其他全局性的过程,不能使用任何非局部的变量。这种对外部依赖关系的限制简化了过程的应用,使得过程能够方便地用于任何地方。当然,由于这种组织方式总是使得代码具有更清晰的结构,即使是不考虑重用性的代码也同样能够从中获益。  在Java中,方法不能脱离类而单独存在。为此,我们可以把相关的过程组织成为独立的类,并把这些过程定义为公用静态方法。  例如,对于下面这个类:  class Polygon {  .   .   public int getPerimeter() {...}   public boolean isConvex() {...}  public boolean containsPoint(Point p) {...}   .   .   }   我们可以把它改写成:  class Polygon {  .   .   public int getPerimeter() {return pPolygon.computePerimeter(this);}  public boolean isConvex() {return pPolygon.isConvex(this);}   public boolean containsPoint(Point p) {return pPolygon.containsPoint(this, p);}   .  }   其中,pPolygon是:  class pPolygon {   static public int computePerimeter(Polygon polygon) {...}   static public boolean isConvex(Polygon polygon) {...}   static public boolean   containsPoint(Polygon polygon, Point p) {...}   }   从类的名字pPolygon可以看出,该类所封装的过程主要与Polygon类型的对象有关。名字前面的p表示该类的唯一目的是组织公用静态过程。在Java中,类的名字以小写字母开头是一种非标准的做法,但象pPloygon这样的类事实上并不提供普通Java类的功能。也就是说,它并不代表着一类对象,它只是Java语言组织代码的一种机制。  在上面这个例子中,改动代码的最终效果是使得应用Polygon功能的客户代码不必再从Polygon继承。Polygon类的功能现在已经由pPolygon类以过程为单位提供。客户代码只使用自己需要的代码,无需关心Polygon类中自己不需要的功能。但它并不意味着在这种新式过程化编程中类的作用有所削弱。恰恰相反,在组织和封装对象数据成员的过程中,类起到了不可或缺的作用,而且正如本文接下来所介绍的,类通过多重接口实现多态性的能力本身也带来了卓越的代码重用支持。然而,由于用实例方法封装代码功能并不是首选的代码重用手段,所以通过类继承达到代码重用和多态性支持也不是最理想的。  

措施二:把参数类型改成接口  正如Allen Holub在《Build User Interfaces for Object-Oriented Systems》中所指出的,在面向对象编程中,代码重用真正的要点在于通过接口参数类型利用多态性,而不是通过类继承:  “……我们通过对接口而不是对类编程达到代码重用的目的。如果某个方法的所有参数都是对一些已知接口的引用,那么这个方法就能够操作这样一些对象:当我们编写方法的代码时,这些对象的类甚至还不存在。从技术上说,可重用的是方法,而不是传递给方法的对象。”  在“措施一”得到的结果上应用Holub的看法,当某块代码能够编写为独立的全局过程时,只要把它所有类形式的参数改为接口形式,我们就可以进一步提高它的可重用能力。经过这个改动之后,过程的参数可以是实现了该接口的所有类的对象,而不仅仅是原来的类所创建的对象。由此,过程将能够对可能存在的大量的对象类型进行操作。  例如,假设有这样一个全局静态方法:  static public boolean contains(Rectangle rect, int x, int y) {...}   这个方法用于检查指定的点是否包含在矩形里面。在这个例子中,rect参数的类型可以从Rectangle类改变为接口类型,如下所示:  static public boolean contains(Rectangular rect, int x, int y) {...}   而Rectangular接口的定义是:  public interface Rectangular {Rectangle getBounds();}   现在,所有可以描述为矩形的类(即,实现了Rectangular接口的类)所创建的对象都可以作为提供给pRectangular.contains()的rect参数。通过放宽参数类型的限制,我们使方法具有更好的可重用性。  不过,对于上面这个例子,Rectangular接口的getBounds方法返回Rectangle,你可能会怀疑这么做是否真正值得。换言之,如果我们知道传入过程的对象会在被调用时返回一个Rectangle,为什么不直接传入Rectangle取代接口类型呢?之所以不这么做,最重要的原因与集合有关。让我们假设有这样一个方法:  static public boolean areAnyOverlapping(Collection rects) {...}   该方法用于检查给定集合中的任意矩形对象是否重叠。在这个方法的内部,当我们用循环依次访问集合中的各个对象时,如果我们不能把对象cast成为Rectangular之类的接口类型,又如何能够访问对象的矩形区域呢?唯一的选择是把对象cast成为它特有的类形式(我们知道它有一个方法可以返回矩形),它意味着方法必须事先知道它所操作的对象类型,从而使得方法的重用只限于那几种对象类型。而这正是前面这个措施力图先行避免的问题!  


措施三:选择最简单的参数接口类型  在实施第二个措施时,应该选用哪一种接口类型来取代给定的类形式?答案是哪一个接口完全满足过程对参数的需求,同时又具有最少的多余代码和数据。描述参数对象要求的接口越简单,其他类实现该接口的机会就越大——由此,其对象能够作为参数使用的类也越多。从下面这个例子可以很容易地看出这一点:  static public boolean areOverlapping(Window window1, Window window2) {...}   这个方法用于检查两个窗口(假定是矩形窗口)是否重叠。如果这个方法只要求从参数获得两个窗口的矩形坐标,此时相应地简化这两个参数是一种更好的选择:  static public boolean areOverlapping(Rectangular rect1, Rectangular rect2) {...}   上面的代码假定Window类型实现了Rectangular接口。经过改动之后,对于任何矩形对象我们都可以重用该方法的功能。  有些时候可能会出现描述参数需求的接口拥有太多方法的情况。此时,我们应该在全局名称空间中定义一个新的公共接口供其他面临同一问题的代码重用。  当我们需要象使用C语言中的函数指针一样使用参数时,创建唯一的接口描述参数需求是最好的选择。例如,假设有下面这个过程:  static public void sort(List list, SortComparison comp) {...}   该方法运用参数中提供的比较对象comp,通过比较给定列表list中的对象排序list列表。sort对comp对象的唯一要求是要调用一个方法进行比较。因此,SortComparison应该是只带有一个方法的接口:  public interface SortComparison {  boolean comesBefore(Object a, Object b);  }   SortComparison接口的唯一目的在于为sort提供一个它所需功能的钩子,因此SortComparison接口不能在其他地方重用。  总而言之,本文三个措施适合于改造现有的、按照面向对象惯例编写的代码。这三个措施与面向对象编程技术结合就得到了一种可在以后编写代码时使用的新式代码编写技术,它能够简化方法的复杂性和依赖关系,同时提高方法的可重用能力和内部凝聚力。  当然,这里的三个措施不能用于那些天生就不适合重用的代码。不适合重用的代码通常出现在应用的表现层。例如,创建程序用户界面的代码,以及联结到输入事件的控制代码,都属于那种在程序和程序之间千差万别的代码,这种代码几乎不可能重用。

Wednesday, January 7, 2009

Java - Serial port communication

1. Java Development Environment set up under winxp.

a. download Eclipse IDE (Eclipse IDE for Java Developers (85 MB)) from
http://www.eclipse.org/downloads/
b. download JDK (Java SE Development Kit (JDK) 6 Update 11 72.9MB) from
http://java.sun.com/javase/downloads/?intcmp=1281

Installing JavaVM (JDK,JRE), and IDE.
The JDK files are placed at C:\Program Files\Java\jdk1.6.0_11\ and the runtime files are placed at C:\Program Files\Java\jdk1.6.0_11\. Ensure the System Variable "path" (held in My Computer->properties->Advanced->Environment Varables->System Variables) includes ";C:\Program Files\Java\jdk1.6.0_11\bin" at the end.

"C:\Program Files\Java\jre6" have JRE installed.

2. Download 'RXTX-2.1-7r2(stable) Binary rxtx-2.1-7-bins-r2.zip ' zip file from
http://www.rxtx.org/ wiki

a. Install RXTX
This involves placing rxtxSerial.dll and rxtxParallell.dll in both C:\Program Files\Java\jdk1.6.0_11\jre\bin and C:\Program Files\Java\jre6\bin. It also involves placing RXTXcomm.jar in both C:\Program Files\Java\jdk1.6.0_11\jre\lib\ext and C:\Program Files\Java\jre6\lib\ext.

b. Example is in link path: usage(Using RXTX)->Code Examples->Writing "Hello World" to a USB to serial converter

This example shows how write a Java program to write out "Hello World" to a serial port or to a USB to serial converter. Before you start you will need to ensure that a suitable Java VM is installed, along with the RXTX Libraries (see platform specifc instructions below).
These instructions all make use of the SimpleWrite.java example file, which you will need to download.


This Java program can be compiled and run by typing the following from the command line:
D:\MyDocXp\MyJavaEclipse\HelloWorld\src> javac SimpleWrite.java
D:\MyDocXp\MyJavaEclipse\HelloWorld\src>java SimpleWrite

"Hello World" should then appear on the device connected to the serial port, assuming that it has been set up to receive a 19200 baud rate, 8 data bits, 1 stop bit, no parity and no handshaking.


c. SimpleWrite.java

import java.io.*;
import java.util.*;
//import javax.comm.*;
import gnu.io.*;
/** * Class declaration * * * @author * @version 1.10, 08/04/00 */public class SimpleWrite { static Enumeration portList;
static CommPortIdentifier portId;
static String messageString = "Hello, world!";
static SerialPort serialPort;
static OutputStream outputStream;
static boolean outputBufferEmptyFlag = false;
/** * Method declaration * * * @param args * * @see */ public static void main(String[] args) { boolean portFound = false;
//String defaultPort = "/dev/term/a";
String defaultPort = "COM4";
if (args.length > 0) { defaultPort = args[0];
}
portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements()) { portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
if (portId.getName().equals(defaultPort)) { System.out.println("Found port " + defaultPort);
portFound = true;
try { serialPort = (SerialPort) portId.open("SimpleWrite", 2000);
} catch (PortInUseException e) { System.out.println("Port in use.");
continue;
}
try { outputStream = serialPort.getOutputStream();
} catch (IOException e) {}
try { serialPort.setSerialPortParams(19200, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException e) {}
try { serialPort.notifyOnOutputEmpty(true);
} catch (Exception e) { System.out.println("Error setting event notification");
System.out.println(e.toString());
System.exit(-1);
}
System.out.println( "Writing \""+messageString+"\" to " +serialPort.getName());
try { outputStream.write(messageString.getBytes());
} catch (IOException e) {}
try { Thread.sleep(2000); // Be sure data is xferred before closing } catch (Exception e) {} serialPort.close();
System.exit(1);
} } }
if (!portFound) { System.out.println("port " + defaultPort + " not found.");
} }
}

struts开发实践—曲线图实例

From: http://www.7880.com/Info/Article-456d7000.html

本案主要功能是完成曲线图的绘制,并将曲线图生成jpg图形并显示。
1。画图的主要函数说明
Graphics g
g.drawRect(x_top,x_bottom,width,height):画矩形
g.setColor(color):指定颜色;
g.fillRect(x_top,x_bottom,width,height):画填充的矩形//
g.drawRoundRect(x_top,x_bottom,width,height):画圆边矩形
g.fillRoundRect(x_top,x_bottom,width,height):画一个填充的圆边矩形
g.drawArc(beg_x,beg_y,width,height,beg_tangle,end_tangle):画弧线
g.fillArc(beg_x,beg_y,width,height,beg_tangle,end_tangle):填充弧
g.drawLine(beg_x,beg_y,end_x,end_y):画一条直线
g.drawString(theString,stringTopLeft_x,StringTopLeft_y):画字
g.setFont(font):设置画笔的字体
g.setPaint(color):设置画笔的颜色
2。曲线图绘制文件
/*****************program CurveFrame begin************************/
package test;
import java.awt.*;
import java.awt.geom.*;
import java.awt.image.*;
import javax.swing.JFrame;
import java.lang.Math;
/** *曲线图绘制 */
public class CurveFrame
extends JFrame {
/**数据*/
private double[] result;
/**数据项名称*/
private String[] title;
/**参数:结果集,名称集*/
public CurveFrame(double[] result, String[] title) {
this.result = result;
this.title = title;
}
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
Dimension dim = this.getSize();
g2.setColor(Color.white);
g2.fillRect(0, 0, dim.width, dim.height);
//写title;
Font font = g2.getFont().deriveFont(12.0f);
g2.setFont(font);
FontMetrics metrics = g2.getFontMetrics();
g2.setPaint(Color.black);
g2.drawString(title[0], (dim.width - title[0].length() * 5) / 2, 10);
// draw the x and y axis
g2.setStroke(new BasicStroke(2.0f));
g2.draw(new Line2D.Double(40, 30, 40, dim.height - 30));
g2.draw(new Line2D.Double(40, dim.height - 30,
dim.width - 20, dim.height - 30));
long unit=(Math.round((result[0]+750)/1500))*50;
long yMax = result[0] == 0 ? unit : Math.round((result[0]+unit/2)/unit) * unit;
int widthPer = (dim.width - 40) / result.length;
long heightPer = (dim.height - 60) / (yMax / unit);
//draw the y axis scale;
g2.setPaint(Color.lightGray);
g2.setStroke(new BasicStroke(1.0f));
for (int i = 0; i<=yMax / unit; i++) {
g2.draw(new Line2D.Double(40, dim.height - 30 - i * heightPer,
dim.width - 40, dim.height - 30 - i * heightPer));
String ylabel = String.valueOf(i * unit);
g2.drawString(ylabel, 35 - metrics.stringWidth(ylabel),
dim.height - 30 - (i * heightPer));
}
//draw x title;
GeneralPath path = new GeneralPath(GeneralPath.WIND_EVEN_ODD,
result.length - 2);
for (int i = 1; i < result.length; i++) {
//draw x scale;
g2.setPaint(Color.lightGray);
g2.setStroke(new BasicStroke(1.0f));
g2.draw(new Line2D.Double(40 + (i - 1) * widthPer, dim.height - 30,
40 + (i - 1) * widthPer,30));
font = g2.getFont().deriveFont(10.0f);
g2.setFont(font);
g2.setPaint(Color.black);
g2.drawString(title[i], 40 + widthPer * (i - 1)-metrics.stringWidth(title[i])/2, dim.height - 10);
g2.setPaint(Color.red);
g2.setStroke(new BasicStroke(2.0f));
if (i == 1) {
path.moveTo(40,
Math.round(dim.height - 30 -
(result[i] / unit) * heightPer));
}
else {
path.lineTo(Math.round(widthPer * (i - 1)) + 40,
Math.round(dim.height - 30 -
(result[i] / unit) * heightPer));
}
}
g2.draw(path);
}

}
/*****************program end************************/
3。生成jpg图形并显示
/*****************program begin************************/
package test;

import org.apache.struts.action.*;
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
import java.util.*;

import java.awt.*;
import java.awt.image.*;
import com.sun.image.codec.jpeg.*;


/**
* 变化曲线
*/
public class WageChangeCurveAction
extends Action {
private static final String CONTENT_TYPE = "image/gif";
private static final int WIDTH = 700;
private static final int HEIGHT = 500;
public ActionForward perform(ActionMapping mapping, ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws IOException,
ServletException {
response.setContentType(CONTENT_TYPE);
ServletOutputStream out = response.getOutputStream();
double[] result=。。。String[] title = 。。。//获得图形数据
try {
CurveFrame dummy = new CurveFrame(result,title);
dummy.setSize(new Dimension(WIDTH, HEIGHT));
BufferedImage image = new BufferedImage(WIDTH, HEIGHT,
BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = image.createGraphics();
dummy.paint(g2);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(image);
out.flush();
}
catch (Throwable e) {
e.printStackTrace();
}
return mapping.findForward("success");
}

}
/*****************program end************************/

Tuesday, January 6, 2009

Java IDE选择

From: http://www.knowsky.com/362256.html

随着Java应用程序越做越大、越做越复杂。Java IDE在其中所起的作用也日益显著。有了Java IDE,使软件的生产率倍增。但目前Java IDE的种类繁多,功能也各不相同。这就给我们的选择带来了诸多不便。因此,本文就目前比较流行的几种Java IDE做了一个深入的对比。主要比较4种Java IDE,它们是Eclipse、Netbeans、Jbuilder和Jcreator。本文将从以下8个方面进行探讨。   一、 Java IDE介绍   1. Eclipse   Eclipse是一个非常成功的开源项目。在世纪之交的时候,IBM为了对抗微软越来越强的垄断地位,投入了10亿美元进行Linux、pc、笔记本电脑以及服务器等产品的研发。在这一系列举措中,影响最深远的就是Eclipse。   Eclipse是IBM“日独计划”的产物。在2001年6月,IBM将价值4000万美元的Eclipse捐给了开源组织。Eclipse由四个计划组成:Eclipse Project、Eclipse Tools Project、Eclipse Technology Project和Eclipse Web Tools Platform Project。每一个计划都遵照CPL1.0协议发布。经过几年的发展,Eclipse已经成为目前最流行的Java IDE。并且拥有了很多的Eclipse社区和新闻组。目前,Eclipse已经成为开发Java程序的首选IDE。   2. Netbeans   Netbeans是Sun自己的开源Java IDE。随着Eclipse逐渐兴起,Sun也在试探性地向Eclipse靠拢。但同时又在不移余力地开发自己的Java IDE:Netbeans。Netbeans在功能上和Eclipse类似。但和Eclipse也有一此区别。如Netbeans集成了Web开发以及最近流行的ajax,而Eclipse要想达到这一点,必须得安装其它的第三方插件。还有Eclipse鼓励使用SWT做为Java的GUI库,而Netbeans使用的是更纯正的Java GUI库:Swing/AWT。   3.Jbuilder   Jbuilder是Borland开发的Java IDE。它在Eclipse和Netbeans出现之前是非常流行了。原因很简单,因为那时Jbuilder是唯一能够真正称得上IDE的产品。但在 Eclipse和Netbeans出现之后Jbuilder就每况愈下。发生这种情况的原因很多。可能是因为Jbuilder是收费的,而Eclipse 和Netbeans是免费的;也可能是因为Borland的产品有一个最大的缺点。就是不管功能多强,而它的代码编辑器和其它辅助书写代码的工具差不多未发生什么变化。从Jbuilder2和Jbuilder9似乎都差不多。   4. Jcreator   以上介绍的都是大家伙。而Jcreator则是一个轻量型的Java IDE。它的功能非常单一。最核心的功能就是可能编写Java源程序,并且支持代码变色和code complete。但Jcreator有一个最显著的优点。就是运行速度快,并且占用资源少。这主要是因为Eclipse、Netbeans和 Jbuilder本身都是使用Java编写的。在启动时必须得先启动Java虚拟机。而Jcreator使用的是本地代码。因而速度更快。假如你的机器配置不高(如只有64M或128M内存),还是使用Jcreator为好。
  二、 Java IDE是否能跨平台 由于Java是跨平台的,因此,它的IDE最好也能跨平台。由于Eclipse、Netbeans和Jbuilder都是使用Java编写的,因此它们也是跨平台的。但由于Eclipse采用的GUI接口是 SWT。而这个库并未加入Sun JCP。因此,Eclipse的跨平台要受到SWT的限制,即SWT所能跨的平台数也就是Eclipse所跨的平台数。而对于Jcreator来说,目前只有Windows版本。这也不能不说是一个遗憾。不过由于大多数的Java开发都是在Windows上,因此。支持Windows平台是几乎是所有的 Java IDE最先考虑的事情。   三、 Java IDE是否收费   这个问题是决定一个IDE是否能够流行的重要原因之一。众所周知,假如一个软件是收费的,那么获得这个软件的方法一般有两种。一种是购买正版的软件。另一种就是使用盗版的软件。而在一些对盗版打击很严厉的国家可能使用正版软件就成为最佳的选择。然而,使用正版软件将会带来很大的成本。所以一但有一种或几种免费的软件,并且在功能上足可以取代收费软件时,人们就会马上转向这些免费的软件。在上述的4种Java IDE中Eclipse和Netbeans不仅是完全免费的,而且是开源的。因此,它们一出现,就对收费Jbuilder产生了很大的威胁。目前 Eclipse和Netbeans的使用率已经超过了Jbuilder。而Jcreator虽然也是收费的。但是费用也并不高。因此,以Jcreator 为首的一些小型的Java IDE以其体积小,占用系统资源少等优点也会占有一定的比例(尽管这个比例并不大)。   四、 Java IDE的界面友好程度   界面是否友好是决定一个IDE是否成功的另一个重要原因。对于界面来说,Eclipse和Netbeans差不多。只是Eclipse是使用SWT开发的。因此,它的界面看起来更像是本地的程序。而Netbeans的界面风格是Java的标准风格。