Archive

Posts Tagged ‘Java’

The Java Modeling Language (JML)

November 17th, 2006 admin No comments

JML makes it possible to specify the behavior of java modules. it combines the design by contract approach and the model-based specification approach. In another words, we can use JML to make strong the interface of java classes and easily checking return values.

Design by Contract with JML
Gary T. Leavens and Yoonsik Cheon (Jan 11, 2006)

There are two important check point, properties which are right before starting a method and properties which are right after finished a method including return value. We can catch those properties with requires clauses and ensures clauses.

//@ requires x >= 0.0;
/*@ ensures JMLDouble.approximatelyEqualTo(x, \result * \result, eps); @*/
public static double sqrt (double x) {
/* some codes. */
}

a requires clauses to specify the client’s obligation and an ensures clauses to specify the implementor’s obligation. A method’s precondition which is specified requires clauses says what must be true to call it. And, a method’s postcondition which is specified ensures clauses says what must be true when it terminates. Otherwise it throws an exception.

We also can define some contracts for not only methods but entire class.

/*@ public invariant !name.equals(“”)
@ && weight >= 0;
@*/

an invariant is a property that should hold in all client-visible states. It must be true when control is not inside the object’s methods. That is, invariant must hold at the end of each constructor’s execution, and at the beginning and end of all methods.

Formal documentation is another benefit of using JML. It makes more easier to read method’s behaviors.

Categories: Software Eng Tags: , ,

The Java Virtual Machine Tool Interface (JVMTI)

November 17th, 2006 admin No comments

JVMTI is a new native interface available in J2SDK1.5.0. JVMPI is still also available though, SUN plan to drop JVMPI soon or later.

“JVMTI provides for all the functional capabilities of the previous native interfaces JVMDI and JVMPI. However, it does not have many of the limitations of those older interfaces. Some of the JVMPI capabilities require the use of JVMTI and the technique called Byte Code Insertion (BCI), sometimes referred to as Byte Code Injection or Byte Code Instrumentation. JVMTI allows for all JVM functionality to continue to operate, like JIT or JVM compilation and different GC implementations. Certain JVMTI features are controlled by asking for JVMTI Capabilities, and some of these can cause changes in JVM performance, but most features are available while the JVM is running “full speed”. All JVMTI object handles are JNI handles, and JVMTI Event callbacks always include a JNIEnv* argument to facilitate JNI usage. Multiple JVMTI agents can operate in a single JVM and all interfaces return an error code to determine success or failure of the request. It is the intention of JVMTI to displace both JVMPI and JVMDI, and to ultimately be the single native tool interface into the JVM. ” The JVMPI Transition to JVMTI

There is my sample code.

simpleAgent.c

#include
#include
#include
#include “jvmti.h”

static jvmtiEnv *jvmti = NULL;
static jvmtiCapabilities capa;

//****** Implementation from here ******//

static void
check_jvmti_error(jvmtiEnv *jvmti, jvmtiError errnum, const char *str)
{
if ( errnum != JVMTI_ERROR_NONE ) {
char *errnum_str;

errnum_str = NULL;
(void)(*jvmti)->GetErrorName(jvmti, errnum, &errnum_str);

printf(“ERROR: JVMTI: %d(%s): %s\n”, errnum, (errnum_str==NULL?”Unknown”:errnum_str), (str==NULL?”":str));
}
}

static void JNICALL
callbackVMInit(jvmtiEnv *jvmti_env, JNIEnv* jni_env, jthread thread)
{
printf(“JVMTI_EVENT_VM_INIT is captured\n”);
}

static void
JNICALL callbackVMDeath(jvmtiEnv *jvmti_env, JNIEnv* jni_env)
{
printf(“JVMTI_EVENT_VM_DEATH is captured\n”);
}

static void JNICALL
callbackVMObjectAlloc(jvmtiEnv *jvmti_env, JNIEnv* jni_env, jthread thread, jobject object, jclass object_klass, jlong size)
{
printf(“JVMTI_EVENT_VM_OBJECT_ALLOC is captured:\n”);
}

/* Agent_OnLoad() is called first, we prepare for a VM_INIT event here. */
JNIEXPORT jint JNICALL
Agent_OnLoad(JavaVM *jvm, char *options, void *reserved)
{

jint res;
jvmtiEventCallbacks callbacks;
jvmtiError error;

res = (*jvm)->GetEnv(jvm, (void **) &jvmti, JVMTI_VERSION);

if (res != JNI_OK || jvmti == NULL) {
/* This means that the VM was unable to obtain this version of the
* JVMTI interface, this is a fatal error.
*/
printf(“ERROR: Unable to access JVMTI Version 1 (0x%x),”
” is your J2SE a 1.5 or newer version?”
” JNIEnv’s GetEnv() returned %d\n”,
JVMTI_VERSION_1, res);

}

memset(&capa, 0, sizeof(jvmtiCapabilities));
error = (*jvmti)->GetPotentialCapabilities(jvmti, &capa);
if (error == JVMTI_ERROR_NONE) {
error = (*jvmti)->AddCapabilities(jvmti, &capa);
check_jvmti_error(jvmti, error, “Unable to get necessary JVMTI capabilities.”);
}

memset(&callbacks, 0, sizeof(callbacks));
callbacks.VMInit = &callbackVMInit; /* JVMTI_EVENT_VM_INIT */
callbacks.VMDeath = &callbackVMDeath; /* JVMTI_EVENT_VM_DEATH */
callbacks.VMObjectAlloc = &callbackVMObjectAlloc;/* JVMTI_EVENT_VM_OBJECT_ALLOC */

error = (*jvmti)->SetEventCallbacks(jvmti, &callbacks, (jint)sizeof(callbacks));
check_jvmti_error(jvmti, error, “Cannot set jvmti callbacks”);

error = (*jvmti)->SetEventNotificationMode(jvmti, JVMTI_ENABLE, JVMTI_EVENT_VM_INIT, (jthread)NULL);
error = (*jvmti)->SetEventNotificationMode(jvmti, JVMTI_ENABLE, JVMTI_EVENT_VM_DEATH, (jthread)NULL);
error = (*jvmti)->SetEventNotificationMode(jvmti, JVMTI_ENABLE, JVMTI_EVENT_VM_OBJECT_ALLOC, (jthread)NULL);
check_jvmti_error(jvmti, error, “Cannot set event notification”);

return JNI_OK;

}

/* Agent_OnUnload() is called last */
JNIEXPORT void JNICALL
Agent_OnUnload(JavaVM *vm)
{
}

JVMTI Reference

Categories: Java Tags: ,

Java memory management

November 17th, 2006 admin No comments

JVM with the -verbose:gc or -Xloggc:
a diagnostic message is printed on the console or to a log file every time the GC runs, including how long it took, the current heap usage, and how much memory was recovered. Logging GC usage is not intrusive, and so it is reasonable to enable GC logging in production by default in the event you ever need to analyze memory problems or tune the garbage collector.

JVM with the -Xrunhprof[:suboption=value]
Enables cpu, heap, or monitor profiling.
java -Xrunhprof:help to obtain a list of suboptions and their default values.

GC Portal
The GC Portal enables analysis and performance tuning of Java applications from a garbage collection (GC) perspective by mining the verbose:gc logs generated by the JVM.

HPjtune
HPjtune is a Java Garbage Collection visualization tool for analyzing garbage collection activity in a Java program. The analysis is carried out off-line or on-line, based on the output of the JVM via the -Xloggc or -Xverbosegc output file.

JavaTM HotSpot VM Options

Categories: Java Tags: ,

Java millisecond precision

November 17th, 2006 admin No comments

There is another useful method under System class. usually I use just in, out, or err something like those methods under System. But,

long current = System.currentTimeMillis(); // Returns the current time in milliseconds.
definitely I need this to work with network program.

Class System

Categories: Programming Tags: , ,

Java NumberFormat

November 17th, 2006 admin No comments

There is useful class to make the number looks pretty. this class is not convenient as much as programming with C though, we can do whatever we want in java

import java.text.NumberFormat;

NumberFormat formatter = new DecimalFormat(“#.00″);
System.out.println(formatter.format((float)totalTime/(float)gotPacket));

as it implaies, the output looks like “XX.00 ”

Class NumberFormat

Random Numbers – shuffling (and $300 Million)

November 17th, 2006 admin No comments

$300 Million, is this enough amount of money for a good tiny program?
of course it is!
Well, current estimated jackpot is $300 million for this Saturday. oh my god! huh?
okay then, let make a tiny program to get me a luck.
- This is my idea.
1. I need to generate five random numbers form 1 to 55 without repeat.
2. another number from 1 to 42 independently.
int powerBall = generator.nextInt(42)+1;
3. open a text file of past winning numbers and, count those numbers.
4. add weight to generate random numbers based on the past winning numbers.

To implement, I think shuffling array would be the most easiest way.

int[] numbers = new int[55];
int length = numbers.length;

for (int i=0; i < length ; i++)
numbers[i] = i+1;

for (int i=0; i < length; i++) {
int position = generator.nextInt(length);
int tmp = numbers[i];
numbers[i] = numbers[position];
numbers[position] = tmp;
}

then we can pick 5 of them. with our lucky algorithm.

good luck!!

Past winning numbers

Categories: Programming Tags: , ,

Java Random Numbers

November 17th, 2006 admin 4 comments

Java has a rich toolkit for generating random numbers, in a class named “Random”. This document is a quick guide to using Random. Random can generate many kinds of random number, not all of which I discuss here.

The best way to think of class Random is that its instances are random number generator objects — objects that go around spitting out random numbers of various sorts in response to messages from their clients.

Creating Random Number Generators

The easiest way to initialize a random number generator is to use the parameterless constructor, for example

Random generator = new Random();

However, beware of one thing when you use this constructor: Algorithmic random number generators are not truly random, they are really algorithms that generate a fixed but random-looking sequence of numbers. When you create a random number generator, it initializes its sequence from a value called its “seed”. The parameterless constructor for Random uses the current time as a seed, which is usually as good a seed as any other. However, the time is only measured to a resolution of 1 millisecond, so if you create two random number generators within one millisecond of each other, they will both generate exactly the same sequence of numbers.

If you prefer, there is also a constructor for Random that allows you to provide your own seed. You can use any long integer as a seed with this constructor. Note that there is no magic way of picking “good” seeds. For example, the following creates a random number generator with seed 19580427:

Random generator2 = new Random( 19580427 );

Generating Random Integers

To generate a random integer from a Random object, send the object a “nextInt” message. This message takes no parameters, and returns the next integer in the generator’s random sequence. Any Java integer, positive or negative, may be returned. Integers returned by this message are uniformly distributed over the range of Java integers. Here is an example, assuming that “generator” is an instance of Random:

int r = generator.nextInt();

Often, programmers want to generate random integers between 0 and some upper bound. For example, perhaps you want to randomly pick an index into an array of n elements. Indices to this array, in Java, range from 0 to n-1. There is a variation on the “nextInt” message that makes it easy to do this: If you provide an integer parameter to “nextInt”, it will return an integer from a uniform distribution between 0 and one less than the parameter. For example, here is how you could use a random number generator object to generate the random array index suggested a minute ago:

int randomIndex = generator.nextInt( n );

Generating Random Real Numbers

Random number generators can also generate real numbers. There are several ways to do so, depending on what probablity distribution you want the numbers drawn from.

To generate a random real number uniformly distributed between 0 and 1, use the “nextDouble” message. This message takes no parameters. For example…

double r = generator.nextDouble();

To generate a random number from a normal distribution, use “nextGaussian”. This message takes no parameters and returns a random number from a normal distribution with mean 0 and standard deviation 1. In layman’s terms, this means that the results may be either positive or negative, with both being equally likely; the numbers will almost always have small absolute values (about 70% will lie between -1 and 1, about 95% between -2 and 2). For example…

double r = generator.nextGaussian();

Translating and Scaling Random Numbers

Random number generators often return numbers in some limited range, typically 0 to b for some upper bound b. Sometimes you need your random numbers to lie in a different range. You can make random numbers lie in a longer or shorter range by multiplying them by a scale factor (scaling). You can make random numbers lie in a range that is shifted to higher or lower numbers than the original by adding (or subtracting) an offset from the random numbers (translating).

Here are some examples of these operations:

* Suppose you are writing a game program that simulates throwing dice, and so need a random integer in the range 1 to 6. “nextInt” can give you one in the range 0 to 5, and you can translate this to the range you need:

int throw = generator.nextInt(6) + 1;

* In drawing a pattern made up of random lines, you want to pick a random angle between 0 and 360 degrees at which to draw a line. The angle can be any real number. The “nextDouble” message will give you a random real number, but between 0 and 1. You can use scaling to turn this into a real number between 0 and 360:

double angle = generator.nextDouble() * 360.0;

* Suppose the same pattern-drawing program also needs to pick random lengths for the lines, but that the lines should never be shorter than 10 units, nor longer than 50. Line lengths can be any real number between these limits. Thus you need random lengths from a 40-unit range starting at 10. You can use scaling and translation together to generate these numbers from “nextDouble”:

double length = generator.nextDouble() * 40.0 + 10.0;

Random Numbers in Java by Doug Baldwin

java.util.Random

Categories: Programming Tags: , ,

Getting input from keyboard

November 17th, 2006 admin No comments

import java.io.*;
InputStreamReader yetBufferedInput = new InputStreamReader(System.in);
BufferedReader bufferedInput = new BufferedReader(yetBufferedInput);
// Once you have created a BufferedReader, you can read either individual characters, or whole lines, from it.

try {
String inputLine = bufferedInput.readLine();

if ( inputLine != null ) {
// … process “inputLine” …
} else {
System.err.println( “No more keyboard input.” );
}
} catch ( IOException error ) {
System.err.println( “Error reading keyboard: ” + error );
}

try {
int input = bufferedInput.read();
if ( input >= 0 ) {
char c = (char) input;
// … process the input character in variable “c”
} else {
System.err.println( “No more keyboard input.” );
}
} catch( IOException error ) {
System.err.println(“Error reading keyboard:”+error );
}

readLine() can be used to read a line of text from BufferedReader, and read() reads a charactor.

try {
bufferedInput.close();
} catch ( IOException error ) {
System.err.println(“Couldn’t close the reader:” + error);
}

after that, you may close the connection to the stream and data source.

Categories: Programming Tags: , , ,

He Returns To J2EE Standards!

November 17th, 2006 admin 1 comment

He didn’t mention why EJB3.0 is better than other frameworks though, it’s quite meaningful in terms of unification. That’s true there are too many frameworks out there!!

Spring + Hibernate EJB3, POJO + JDBC?
— In the beginning there was nothing: no Java and no data. Then someone said, let there be data and relational databases with SQL were born. And someone said, let Java talk to databases, and JDBC was born. And someone saw that JDBC was good, but someone else saw that JDBC was bad, and EJB with CMP were created. And someone said, J2EE containers are bad and POJO has resurrected. And entity beans were slow and heavy; Hibernate was born and people forgot SQL, which was a sin.

Categories: J2EE Tags: , , ,

Easy installation of Struts

November 11th, 2006 admin No comments

It seems like that Struts is a part of J2EE now, so I think it should be included in J2EE default package!! or maybe I should try JSF.
Download Struts from http://struts.apache.org

1. Extract downloaded file

2. COPY war files which are under “<Struts>/webapps dir” INTO “<Tomcat>/webapps dir”

3. COPY jar files which are under “<Struts>/lib dir” INTO “<J2SDK>/jre/lib/ext dir”

4. Tomcat restart, That’s it!

Categories: J2EE Tags: , , ,