Truong's territory

Just another experiance!

Java classloader

Posted by truongngh on October 22, 2009

Understanding Extension Class Loading

The extension framework makes use of the class-loading delegation mechanism. When the runtime environment needs to load a new class for an application, it looks for the class in the following locations, in order:

  1. Bootstrap classes: the runtime classes in rt.jar, internationalization classes in i18n.jar, and others.
  2. Installed extensions: classes in JAR files in the lib/ext directory of the JRE, and in the system-wide, platform-specific extension directory (such as /usr/jdk/packages/lib/ext on the SolarisTM Operating System, but note that use of this directory applies only to JavaTM 6 and later).
  3. The class path: classes, including classes in JAR files, on paths specified by the system property java.class.path. If a JAR file on the class path has a manifest with the Class-Path attribute, JAR files specified by the Class-Path attribute will be searched also. By default, the java.class.path property’s value is ., the current directory. You can change the value by using the -classpath or -cp command-line options, or setting the CLASSPATH environment variable. The command-line options override the setting of the CLASSPATH environment variable.

The precedence list tells you, for example, that the class path is searched only if a class to be loaded hasn’t been found among the classes in rt.jar, i18n.jar or the installed extensions.

Unless your software instantiates its own class loaders for special purposes, you don’t really need to know much more than to keep this precedence list in mind. In particular, you should be aware of any class name conflicts that might be present. For example, if you list a class on the class path, you’ll get unexpected results if the runtime environment instead loads another class of the same name that it found in an installed extension.

The Java Class Loading Mechanism

The Java platform uses a delegation model for loading classes. The basic idea is that every class loader has a “parent” class loader. When loading a class, a class loader first “delegates” the search for the class to its parent class loader before attempting to find the class itself.Here are some highlights of the class-loading API:

  • Constructors in java.lang.ClassLoader and its subclasses allow you to specify a parent when you instantiate a new class loader. If you don’t explicitly specify a parent, the virtual machine’s system class loader will be assigned as the default parent.
  • The loadClass method in ClassLoader performs these tasks, in order, when called to load a class:
    1. If a class has already been loaded, it returns it.
    2. Otherwise, it delegates the search for the new class to the parent class loader.
    3. If the parent class loader does not find the class, loadClass calls the method findClass to find and load the class.
  • The findClass method of ClassLoader searches for the class in the current class loader if the class wasn’t found by the parent class loader. You will probably want to override this method when you instantiate a class loader subclass in your application.
  • The class java.net.URLClassLoader serves as the basic class loader for extensions and other JAR files, overriding the findClass method of java.lang.ClassLoader to search one or more specified URLs for classes and resources.

To see a sample application that uses some of the API as it relates to JAR files, see the Using JAR-related APIs lesson in this tutorial.

Class Loading and the java Command

The Java platform’s class-loading mechanism is reflected in the java command.

  • In the java tool, the -classpath option is a shorthand way to set the java.class.path property.
  • The -cp and -classpath options are equivalent.
  • The -jar option runs applications that are packaged in JAR files. For a description and examples of this option, see the Running JAR-Packaged Software lesson in this tutorial.

Class Loaders in JEE

Java Platform, Enterprise Edition (JEE) application servers typically load classes from a deployed WAR or EAR archive by a tree of Classloaders, isolating the application from other applications, but sharing classes between deployed modules. So-called “servlet containers” are typically implemented in terms of multiple classloaders[2][7]

Posted in java | Tagged: , , , | Leave a Comment »

Java syntax

Posted by truongngh on August 14, 2009

int _a; int $c; int ______2_w; int _$; int this_is_a_very_detailed_name_for_an_identifier;

public void setMyValue(int v)

public int getMyvalue()

public boolean isMyStatus()

public void addMyListener(MyListener m)

public void removeMyListener(MyListener m)

Source File Declaration Rules

Before we dig into class declarations, let’s do a quick review of the rules associated with declaring classes, import statements, and package statements in a source file:

  • There can be only one public class per source code file.
  • Comments can appear at the beginning or end of any line in the source code file; they are independent of any of the positioning rules discussed here.
  • If there is a public class in a file, the name of the file must match the name of the public class. For example, a class declared as public class Dog { } must be in a source code file named Dog.java.
  • If the class is part of a package, the package statement must be the first line in the source code file, before any import statements that may be present.
  • If there are import statements, they must go between the package statement (if there is one) and the class declaration. If there isn’t a package statement, then the import statement(s) must be the first line(s) in the source code file. If there are no package or import statements, the class declaration must be the first line in the source code file.
  • import and package statements apply to all classes within a source code file. In other words, there’s no way to declare multiple classes in a file and have them in different packages, or use different imports.
  • A file can have more than one nonpublic class.
  • Files with no public classes can have a name that does not match any of the classes in the file.

Class Declarations and Modifiers

Although nested (often called inner) classes are on the exam, we’ll save nested class declarations for Chapter 8. You’re going to love that chapter. No, really. Seriously. The following code is a bare-bones class declaration:

class MyClass { }

This code compiles just fine, but you can also add modifiers before the class declaration. Modifiers fall into two categories:

  • Access modifiers: public, protected, private.
  • Non-access modifiers (including strictfp, final, and abstract).

public abstract interface Rollable { } == public interface Rollable { }

Declaring an Interface

  • All interface methods are implicitly public and abstract. In other words, you do not need to actually type the public or abstract modifiers in the method declaration, but the method is still always public and abstract.
  • All variables defined in an interface must be public, static, and final—in other words, interfaces can declare only constants, not instance variables.
  • Interface methods must not be static.
  • Because interface methods are abstract, they cannot be marked final, strictfp, or native. (More on these modifiers later.)
  • An interface can extend one or more other interfaces.
  • An interface cannot extend anything but another interface.
  • An interface cannot implement another interface or class.
  • An interface must be declared with the keyword interface.
  • Interface types can be used polymorphically (see Chapter 2 for more details).
Table 1-2: Determining Access to Class Members
Visibility Public Protected Default Private
From the same class Yes Yes Yes Yes
From any class in the same package Yes Yes Yes No
From a subclass in the same package Yes Yes Yes No
From a subclass outside the same package Yes Yes, through inheritance No No
From any non-subclass class outside the package Yes No No No

Final Methods

The final keyword prevents a method from being overridden in a subclass, and is often used to enforce the API functionality of a method

It is illegal to have even a single abstract method in a class that is not explicitly declared abstract! Look at the following illegal class:

public class IllegalClass{
  public abstract void doIt();
}

You can, however, have an abstract class with no abstract methods. The following example will compile fine:

public abstract class LegalClass{
   void goodMethod() {
      // lots of real implementation code here
   }
}

Abstract Methods

A method can never, ever, ever be marked as both abstract and final, or both abstract and private. furthermore, the abstract modifier can never be combined with the static modifier.

Methods with Variable Argument Lists (var-args)

Legal:

void doStuff(int... x) { }  // expects from 0 to many ints
                            // as parameters
void doStuff2(char c, int... x)  { }  // expects first a char,
                                      // then 0 to many ints
void doStuff3(Animal... animal) { }   // 0 to many Animals

Illegal:

void doStuff4(int x...) { }             // bad syntax
void doStuff5(int... x, char... y) { }  // too many var-args
void doStuff6(String... s, byte b) { }  // var-arg must be last
Table 1-3: Ranges of Numeric Primitives
Type Bits Bytes Minimum Range Maximum Range
byte 8 1 -27 27-1
short 16 2 -215 215-1
int 32 4 -231 231-1
long 64 8 -263 263-1
float 32 4 n/a n/a
double 64 8 n/a n/a

Modifier for variable and method, class

Class: final, public, abstract

Local Variables: final

Variables (non-local):final public protected private static transient volatile

Methods: final public protected private staticabstract synchronized strictfp native

Static modifier

Things you can mark as static:

  • Methods
  • Variables
  • A class nested within another class, but not within a method
  • Initialization blocks

Things you can’t mark as static:

  • Constructors (makes no sense; a constructor is used only to create instances)
  • Classes (unless they are nested)
  • Interfaces
  • Method local inner classes
  • Inner class methods and instance variables
  • Local variables

Variable initialization

Local variable is not initialized like instance variable.

Array elements are given their default values (0, false, null, ‘\u0000′, etc.) regardless of whether the array is declared as an instance or local variable

Default Values for Primitives and Reference Types: Object->null; byte, short, int, long -> 0;  float, double -> 0.0; boolean -> false; char -> ‘\u0000′

Boxing

In order to save memory, two instances of the following wrapper objects will always be = = when their primitive values are the same:

  • Boolean
  • Byte
  • Character from \u0000 to \u007f (7f is 127 in decimal)
  • Short and Integer from -128 to 127

The compiler will bias:

  • Widening beats boxing
  • Widening beats var-args
  • Boxing beats var-args

Thread

Java Thread Life

Java Thread Life

  • A call to Thread.sleep() Guaranteed to cause the current thread to stop executing for at least the specified sleep duration (although it might be interrupted before its specified time).
  • A call to Thread.yield() Not guaranteed to do much of anything, although typically it will cause the currently running thread to move back to runnable so that a thread of the same priority can have a chance.
  • A call to join() Guaranteed to cause the current thread to stop executing until the thread it joins with (in other words, the thread it calls join() on) completes, or if the thread it’s trying to join with is not alive, however, the current thread won’t need to back out.

Synchronize:

  • Each object has just one lock.
  • You can synchronize a block of code rather than a method.
  • If a thread goes to sleep, it holds any locks it has—it doesn’t release them.
Give Up Locks Keep Locks Class Defining the Method
wait () notify() (Although the thread will probably exit the synchronized code shortly after this call, and thus give up its locks.) java.lang.Object
join() java.lang.Thread
sleep() java.lang.Thread
yield() java.lang.Thread

Thread-Safe Classes: even when a class is “thread-safe,” it is often dangerous to rely on these classes to provide the thread protection you need

Thread interaction:

wait(): call this, current thread will release lock and wait for notification from to locking object. For safe reason, wait() should be call in a loop, this will prevent a notify() call happen before a wait() call.

notify(): an object calls this method to notify a thread waiting on this object’s lock; the rest thread waiting on this lock will keep waiting.

notifyAll(): an object invokes this method to notify all thread waiting on it’s lock; then, only one can get the lock; the rest will not get the lock and they do not waiting for notification anymore; each in the rest tries to gain lock to continue doing it’s task.

File

Stream classes are used to read and write bytes, and Readers and Writers are used to read and write characters. Since all of the file I/O on the exam is related to characters, if you see API class names containing the word “Stream”, for instance DataOutputStream, then the question is probably about serialization, or something unrelated to the actual I/O objective.

Serializable

If you are a serializable class, but your superclass is NOT serializable, then any instance variables you INHERIT from that superclass will be reset to the values they were given during the original construction of the object. This is because the non-serializable class constructor WILL run!

[for Array/Collection] If you serialize a collection or an array, every element must be serializable! A single non-serializable element will cause serialization to fail. Note also that while the collection interfaces are not serializable, the concrete collection classes in the Java API are.

transient variable is not serialized.

Pattern

In general, a regex search runs from left to right, and once a source’s character has been used in a match, it cannot be reused.

java.util.regex.Pattern (Pattern) and java.util.regex.Matcher (Matcher)

Metacharacter

  • \d : A digit
  • \s : A whitespace character
  • \w : A word character (letters, digits, or “_” (underscore))
  • . : any character can serve here

Qualifier

  • + : 1 to many occurrences (greedy) (+? is reluctant)
  • * : 0 to many occurrences (greedy) (*? is reluctant)
  • ? : 0 to 1 occurrence (greedy) (?? is reluctant)
  • ^:  is the negation symbol in regex

Example: distinguish greedy and reluctant qualifier

  • source:  yyxxxyxx
  • pattern:  .*xx   => result: “0 yyxxxyxx”
  • pattern:  .*?xx   => result: “0 yyxx” and “4 xyxx”

Metacharacters and Strings Collide

  • String pattern = “\d”;    // compiler error!
  • String pattern = “\\d”;    // a compilable metacharacter
  • String p = “.”;   // regex sees this as the “.” metacharacter
  • String p = “\.”;  // the compiler sees this as an illegal Java escape sequence
  • String p = “\\.”; // the compiler is happy, and regex sees a dot, not a metacharacter

Example

import java.util.regex.*;
class Regex {
public static void main(String [] args) {
Pattern p = Pattern.compile(args[0]);
Matcher m = p.matcher(args[1] );
boolean b = false;
System.out.println(“Pattern is ” + m.pattern());
while(b = m.find()) {
System.out.println(m.start() + ” ” + m.group());
}
}
}

import java.util.Scanner;
class ScanNext {
public static void main(String [] args) {
boolean b2, b;
int i;
String s, hits = ” “;
Scanner s1 = new Scanner(args[0]);
Scanner s2 = new Scanner(args[0]);
while(b = sl.hasNext()) {
s = s1.next();  hits += “s”;
}
while(b = s2.hasNext()) {
if (s2.hasNextInt()) {
i = s2.nextlnt();  hits += “i”;
} else if (s2.hasNextBoolean()) {
b2 = s2.nextBoolean(); hits += “b”;
} else {
s2.next();  hits += “s2″;
}
}
System.out.printl.n(“hits ” + hits);
}
}

equals() method and hashCode() method

  • x.equals(y)==true => x.hashCode()==y.hashCode()   (inverted direction is just recommended)
  • x.hashCode()!=y.hashCode() => x.equals(y)==false

The equals() Contract

  • It is reflexive. For any reference value x, x.equals(x) should return true.
  • It is symmetric. For any reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
  • It is transitive. For any reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) must return true.
  • It is consistent. For any reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the object is modified.
  • For any non-null reference value x, x.equals(null) should return false.

Posted in Uncategorized | 2 Comments »

Explaining java.lang.OutOfMemoryError: PermGen space

Posted by truongngh on August 12, 2009

Most probably, a lot of Java developers have seen OutOfMemory error one time or other. However these errors come in different forms and shapes. The more common is: “Exception in thread “main” java.lang.OutOfMemoryError: Java heap space” and indicates that the Heap utilization has exceeded the value set by -Xmx. This is not the only error message, of this type, however.

One more interesting flavor of the same error message, less common but hence even more troublesome is: “java.lang.OutOfMemoryError: PermGen space”. Most of the memory profiler tools are unable to detect this problem, so it is
even more troublesome and therefor – interesting.

To understand this error message and fix it, we have to remember that, for optimized, more efficient garbage-collecting Java Heap is managed in generations – memory segments holding objects of different ages. Garbage collection algorithms in each generation are different. Objects are allocated in a generation for younger objects – the Young Generation, and because of infant mortality most objects die there. When the young generation fills up it causes a Minor Collection. Assuming high infant mortality, minor collections are garbage-collected frequently. Some surviving objects are moved to a Tenured Generation. When the Tenured Generation needs to be collected there is a Major Collection that is often much slower because it involves all live objects. Each generation contains variables of different length of life and different GC policies are applied to them.

There is a third generation too – Permanent Generation. The permanent generation is special because it holds meta-data describing user classes (classes that are not part of the Java language). Examples of such meta-data are objects describing
classes and methods and they are stored in the Permanent Generation. Applications with large code-base can quickly fill up this segment of the heap which will cause java.lang.OutOfMemoryError: PermGen no matter how high your -Xmx and how much memory you have on the machine.

Sun JVMs allow you to resize the different generations of the heap, including the permanent generation. On a Sun JVM (1.3.1 and above) you can configure the initial permanent generation size and the maximum permanent generation size.

To set a new initial size on Sun JVM use the -XX:PermSize=64m option when starting the virtual machine. To set the maximum permanent generation size use -XX:MaxPermSize=128m option. If you set the initial size and maximum size to equal values you may be able to avoid some full garbage collections that may occur if/when the permanent generation needs to be resized. The default values differ from among different versions but for Sun JVMs upper limit is typically 64MB.

Some of the default values for Sun JVMs are listed below.

JDK 1.3.1_06 Initial Size Maximum Size
Client JVM 1MB 32MB
Server JVM 1MB 64MB
JDK 1.4.1_01 Initial Size Maximum Size
Client JVM 4MB 64MB
Server JVM 4MB 64MB
JDK 1.4.2 Initial Size Maximum Size
Client JVM 4MB 64MB
Server JVM 16MB 64MB
JDK 1.5.0 Initial Size Maximum Size
Client JVM 8MB 64MB
Server JVM 16MB 64MB

Source: http://www.freshblurbs.com/explaining-java-lang-outofmemoryerror-permgen-space

More reference:

http://blogs.sun.com/fkieviet/entry/classloader_leaks_the_dreaded_java

http://truongngh.wordpress.com/2009/06/26/jvm-monitoring-with-jconsole/

http://my.opera.com/karmazilla/blog/2007/03/13/good-riddance-permgen-outofmemoryerror

Posted in Programming, java | Tagged: , , , | Leave a Comment »

20 qui luật ám ảnh khi sử dụng công nghệ

Posted by truongngh on August 6, 2009

Đây là các luật cơ bản mà tạp chí PC World và người dùng Facebook đã “đúc kết”:

- Mỗi bản vá Windows Update sẽ phá hỏng ít nhất hai thứ khác trên máy tính của bạn.

- Ổ cứng luôn lỗi ngay khi bạn định sao lưu dữ liệu (backup).

- Dữ liệu sẽ gặp trục trặc ngay trước khi bạn cắm ổ rời để backup.

- Số cổng USB trên máy Mac luôn ít hơn một so với nhu cầu của bạn tại bất cứ thời điểm nào.

- Sức ép sửa máy tính nhanh chóng sẽ càng khiến bạn kéo dài thời gian hơn.

- Sau khi sửa máy, nếu vặn ốc vít trên case rồi mới kiểm tra, máy tính đó sẽ không hoạt động. Nhưng nếu kiểm tra trước khi đóng case, nó sẽ chạy trơn tru.

- Sửa máy tính cho bạn bè hoặc người thân, bạn sẽ trở thành người hỗ trợ kỹ thuật cho họ một thời gian dài, thậm chí cả đời.

- Lắp ráp máy tính cho ai đó, họ sẽ “sở hữu” bạn.

- Nếu bạn giới thiệu một sản phẩm tốt cho bạn bè, người đó đi mua và lập tức sẽ thấy sản phẩm đó thật tệ và phải đem trả lại.

- Chỉ một lần thể hiện kỹ năng IT tại công sở, bộ phận kỹ thuật sẽ bắt đầu khuyên các đồng nghiệp “nhờ vả” bạn mỗi khi họ gặp rắc rối với máy tính.

- Nếu có trục trặc mà bạn sửa mãi không xong và phải gọi hỗ trợ, vấn đề sẽ được khắc phục ngay khi bạn còn đang mô tả lỗi cho kỹ thuật viên.

- Chỉ trong một tháng đồng ý trở thành “bạn” của sếp trên Facebook, bạn sẽ cảm thấy hối hận. (Sếp sẽ biết bạn vào Facebook bao nhiêu lần trong giờ làm việc cũng như không khó để nắm rõ mọi “đường đi nước bước” của bạn trên mạng này).

- Khi điền Captcha (chuỗi ký tự xác thực) trên một website, bạn luôn gõ số 1 thay cho chữ l (L thường) và chữ O thay cho số 0.

- Những e-mail ác ý luôn tìm được cách đến tay người nhận dù bạn còn đang cân nhắc chưa muốn gửi.

- Sạc pin điện thoại hiện tại của bạn sẽ không tương thích với chiếc điện thoại tiếp theo bạn sẽ mua (nhiều người than phiền họ có cả một bộ sưu tập sạc pin).

- Pin laptop luôn hết nhanh gấp hai lần so với bình thường bất cứ khi nào bạn rời nhà mà quên mang theo sạc.

- Điện thoại sẽ hỏng ngay khi hợp đồng 2 năm với nhà cung cấp sắp hết, buộc bạn phải mua mẫu máy mới. (Tại Mỹ và nhiều quốc gia khác, người sử dụng có thể sở hữu điện thoại với giá thấp hơn giá thị trường nhưng phải ký hợp đồng 1-2 năm với nhà cung cấp).

- Khi đi du lịch, thẻ nhớ máy ảnh của bạn thường nằm “an toàn” trong đầu đọc thẻ mà bạn để quên ở nhà.

- Trang hỗ trợ trực tuyến của nhà cung cấp phần mềm chứa mọi hướng dẫn chi tiết để khắc phục các trục trặc, trừ vấn đề bạn đang gặp.

- 9 trong số 10 lần can thiệp vào Registry để sửa lỗi hệ thống sẽ tạo ra một vấn đề mới còn nghiêm trọng hơn vấn đề ban đầu.

Châu An (theo PC World)

It’s definitely precise….. =)))

Posted in Funny, Life corner, Technologies | Tagged: , | Leave a Comment »

BECAUSE OF & DUE TO

Posted by truongngh on July 21, 2009

The word pairs “because of” and “due to” are not interchangeable. The reason they are not is that they “grew up” differently in the language.
“Because of” grew up as an adverb; “due to” grew up as an adjective. Remember that adjectives modify only nouns or pronouns, whereas adverbs usually modify verbs. (The fact that adverbs occasionally modify other adverbs or even adjectives and entire phrases is not relevant to this particular discussion.)
To be more precise, with their attendant words, “due to” and “because of” operate as adjectival and adverbial prepositional phrases. To understand how the functions of “due to” and “because of” vary, look at these sentences.

1. His defeat was due to the lottery issue.

2. He was defeated because of the lottery issue.

In sentence #1, his is a possessive pronoun that modifies the noun defeat. The verb “was” is a linking verb. So, to create a sentence, we need a subject complement after the verb “was.” The adjectival prepositional phrase “due to the lottery issue” is that complement, linked to the  subject by “was.” Thus, it modifies the noun defeat.
But in sentence #2, the pronoun “he” has become the sentence’s subject. The verb is now “was defeated.” As reconstructed, “He was defeated” could in fact be a complete sentence. And “due to” has nothing to modify. It’s an adjective, remember? It can’t very well modify the pronoun “he,” can it?
Neither can it refer to “was defeated” because adjectives don’t modify verbs. Sentence 2, therefore, should read: “He was defeated because of the lottery issue.” Now the “why” of the verb “was defeated” is explained, properly, by an adverbial prepositional phrase, “because of.”
In informal speech, we probably can get by with such improper usage as “His defeat was because of the lottery issue,” and “He was defeated due to the lottery issue.” But we shouldn’t accept that kind of sloppiness in writing. We don’t want to look stupid among those in the audience who know better. If we show them we don’t care about the language, how can we expect them to believe us when we tell them that we care about the facts?

OK, how well do you know it? A little practice makes perfect. Click here, if you’re game.

Source: http://web.ku.edu/~edit/

Posted in English | Tagged: , | 1 Comment »

Recover Grub boot loader from Ubuntu Installation CD

Posted by truongngh on July 15, 2009

Overwriting the Windows bootloader

This will overwrite your Windows Boot Loader. It is OK to do this, in fact that is the goal of this how to (in order to boot Ubuntu)

Boot from a Live CD and open a terminal. You’ll need to run a few commands as root so you can use sudo -i to get a root shell and run them normally instead of using sudo on each of them. Be extra careful when running a root shell, especially for typos!

We’ll need to find which partition your Ubuntu system is installed on. Type the command fdisk -l. It will output a list of all your partitions, for example :

fdisk -l

Disk /dev/hda: 120.0 GB, 120034123776 bytes
255 heads, 63 sectors/track, 14593 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1               1           8       64228+  83  Linux
/dev/sda2               9        1224     9767520   83  Linux
/dev/sda3   *        1225        2440     9767520   a5  FreeBSD
/dev/sda4            2441       14593    97618972+   5  Extended
/dev/sda5           14532       14593      498015   82  Linux swap / Solaris
/dev/sda6            2441       14530    97112862   83  Linux

Partition table entries are not in disk order

Here I have three Linux partitions. /dev/sda2 is my root partition, /dev/sda1 is my /boot partition and /dev/sda6 is my /home partitions. If you only have one, obviously this is the one your Ubuntu system is installed on. If you have more than one and you don’t know which one your Ubuntu is installed on, we’ll look for it later. First, create a mountpoint for your partition, for example :

mkdir /media/root

Then mount your partition in it. If you don’t know which one it is, then mount any of them, we’ll see if it’s the correct one.

mount /dev/sda2 /media/root

Of course, replace /dev/sda2 with the correct name of your partition. You can check if it’s the correct one by running ls /media/root, which should output something like this :

bin    dev      home        lib    mnt   root     srv  usr
boot   etc      initrd      lib64  opt   sbin     sys  var
cdrom  initrd.img  media  proc  selinux  tmp  vmlinuz

If what you have looks not at all like this, you didn’t mount the correct partition. Do umount /media/root to unmount it and try another one. You also need to mount your /boot partition if you made one, like this :

mount /dev/sda1 /media/root/boot

To make sure it was the correct one, run ls /media/root/boot, which should output something like this :

config-2.6.18-3-686      initrd.img-2.6.18-3-686.bak  System.map-2.6.18-3-686
grub                     lost+found                   vmlinuz-2.6.18-3-686
initrd.img-2.6.18-3-686  memtest86+.bin

Once again, if what you have doesn’t fit, unmount it and try another partition.

Now that everything is mounted, we just need to reinstall GRUB :

sudo grub-install --root-directory=/media/root /dev/sda

If you got BIOS warnings try:

sudo grub-install --root-directory=/media/root /dev/sda --recheck

Of course, replace /dev/sda with the location you want to install GRUB on. If all went well, you should see something like this :

Installation finished. No error reported.
This is the contents of the device map /boot/grub/device.map.
Check if this is correct or not. If any of the lines is incorrect,
fix it and re-run the script `grub-install'.

(hd0)   /dev/sda

Reboot (to your hard drive). Grub should be installed and both Ubuntu and Windows should have been automatically detected.

If, after installing grub, Windows does not appear in the boot menu you will need to edit /boot/grub/menu.lst (That is a small “L” and not the number 1 in menu.lst)

Open a terminal and enter :

gksu gedit /boot/grub/menu.lst

Or, in Kubuntu:

kdesu kate /boot/grub/menu.lst

Your Windows stanza should look something like this :

title Windows XP/Vista # You can use any title you wish, this will appear on your grub boot menu
rootnoverify (hd0,0) # This is the location of the windows partition
makeactive
chainloader +1

Note: Put your Windows stanza before or after AUTOMAGIC KERNEL LIST in the menu.lst

Preserving Windows Bootloader

This method allows you to restore GRUB and keep the Windows bootloader as your primary bootloader. Thanks to Ubuntu’s support for NTFS writing it’s now an absolute cinch.

The method shown above puts GRUB back on the MBR (master boot record) of the hard drive instead of in the root partition. But you probably won’t want that, if you use a third-party boot manager like Boot Magic or System Commander. (The original poster also suggested that this would be useful to restore the Grub menu after a re-ghosting.) In that case, use this alternative.

If you have your Linux system in a second (or third…) hard disk this method will not work. Please check Super Grub Disk’s method that address this problem.

Restoring GRUB

1. Boot from a Live CD, like Ubuntu Live, Knoppix, Mepis, or similar. Ideally use Ubuntu 8.04 or higher as this has NTFS write support and makes life a bit easier; this isn’t necessary, just handy.

2. Open a Terminal. Open a root terminal (that is, type “su” in a non-Ubuntu distro, or “sudo -i” in Ubuntu). Enter root passwords as necessary.

3. Type “grub” which makes a GRUB prompt appear.

4. Type “find /boot/grub/stage1″. You’ll get a response like “(hd0)” or in my case “(hd0,3)”. Use whatever your computer spits out for the following lines. Note that you should have mounted the partition which has your Linux system before typing this command. (e.g. In Knoppix Live CD partitions are shown on the desktop but they’re not mounted until you double-click on them or mount them manually)

5. Type “root (hd0,3)” note the space between root and (hd0,3).

6. Type “setup (hd0,3)”. This is key. Other instructions say to use “(hd0)”, and that’s fine if you want to write GRUB to the MBR. If you want to write it to your linux root partition, then you want the number after the comma, such as “(hd0,3)”.

7. Type “quit”.

8. At this stage you can either restart the system and install your own bootloader, or you can continue and tell the Windows bootloader where to find GRUB which will handle booting Linux.

Making Windows Load GRUB (and then Linux)

This is taken from Dual-Boot Linux and Windows 2000/Windows XP with GRUB HOWTO which has been helping people dual boot since 2005, or maybe before.

1. In Linux open a command window.

2. Mount a drive which you can share with Windows; this could be a USB drive, a FAT32 partition on your machine, or if you are using a Linux distro which supports NTFS writing like Ubuntu 8.04+ (maybe earlier?) then you can mount the actual Windows c:\ drive itself! The big bonus of writing to the windows drive is that you are going to need to put a file there, so it saves copying a file around. For example

#mkdir /tmp/windows
#mount /dev/sda1 /tmp/windows

3. Now you are going to make a copy of your boot partition; finding what this is called is not 100% deterministic because Linux might call your drives sdX or hdX, whereas GRUB always calls them hdX and Linux names them [hd|sd][Letter][Number] whereas GRUB names them as hd[Number][Number]; note that df won’t work as you are booted from a live CD. But let’s have a go; if you installed GRUB on (hd0,0), then /boot is on hda1 or sda1, (hd1,0) == hdb1 or sdb1, (hd0,1) == hda2 or sda2, etc… this narrows you down to two possibilities, now issuing ls /dev |grep hd will let you know if you have that drive on your machine, if nothing comes up which matches, then you must have an sd drive. OK, great…

4. Having hopefully determined your boot partition issue the command (as root)

#dd if=/dev/sda2 of=/tmp/windows/linux.bin bs=512 count=1

Where /dev/sda2 is your boot partition and /tmp/windows/ is the drive you want to copy the boot sector image to.

5. If you haven’t created linux.bin in the Windows drive then you need to copy it there now.

6. Reboot into Windows, open c:\boot.ini in notepad, and on a new line at the bottom, add c:\linux.bin="Linux". This file might be write protected, if it is enable write in the right click context menu -> properties; you should disable write afterwards. Make sure that at the top of the boot.ini file there is a timeout set, i.e timeout=5. (Ah ha, you say, now I have NTFS support, why don’t I just edit boot.ini in Linux, the answer to this is that Linux and Windows represent line breaks in different ways, so even though you can edit the file, it won’t add a new line 残念)

7. That’s it, reboot and you will be given the option of booting into Linux, selecting that will chainload GRUB and this will let you boot into your Linux distro.

From: http://ubuntuforums.org/showpost.php?p=121355&postcount=5

Posted in Uncategorized | 1 Comment »

Slimming Down Windows XP Professional Using nLite

Posted by truongngh on July 13, 2009

See also: Related discussion thread

Note from torowl: I have used nLite slim down XP and installed in my EEE. I’m posting the step by step instructions here to share my experience. After installation, XP take about 687M SSD, this is the best result I can get so far. And this includes hotfixes and few addon softwares includes Windows Media Player 10. I also installed Office 2003 and Divx, didn’t get any issue, so far so good.

I’m not an XP expert. All options that removed are based on my limited knowledge. Some options removal may be wrong. You are welcome to point out for discussion.

nLite Installation and Startup

1. Download nLite from http://www.nliteos.com/download.html. I’m using version 1.4.

2. Download hotfixes: SP3 hot fix is available now. Use either SP2 or SP3 hotfix depending on the version you’re using (SP3 is preferred).

3. Also you can find a lot of addons from http://www.nliteos.com/addons. For more addons, you can find them from here http://www.winaddons.com.

4. Install nLite.

5. Create a folder and copy the XP installation files (everything) from CD to that folder.

6. Run nLite, in the welcome window, click Next to Locating the Windows installation window. Click the “Browse” button to locate the folder that you created. Click “Next” and nLite will check your Windows version information. If you do not have SP3, slipstream SP3 in first.

nLite browse dialog nLite browse dialog contains a browse button. Read only text of Windows operating system version name, Language, Service Pack version, windows version number, path to the files and size. All dialogs contain a back button, next button and cancel button. They also contain a Tray button, where you can drop the program to the system tray to retrieve later.

Preset Window

7. Click “Next” to Preset window. In the first run, you don’t have any preset ini files. It will show empty here. Click Next.

nLite presets dialog nLite presets dialog contains a list box of possible presets and their dates which is empty , and an import button.

Task Selection Window

8. In the Task Selection window, select all except Service Pack and Drivers. We already have SP3, or have slipstreamed it if necessary. If you select driver, nLite can embed the drivers into XP installation. I think it is not a good idea to add Eee drivers into XP installation, because we need to run ACPI before install Eee drivers.

nLite task selection dialog nLite task selection dialog shows a series of buttons which are grouped by a set of labels to their left. All buttons are pressed except for service packs and drivers.

Hotfixes, Addons and Update Packs Window

9. Click “Next” to Hotfixes, Addons and Update Packs window. Click “insert” to insert hotfixes and addons. I didn’t add Adobe Acrobat Reader, Windows Live Messenger and Divx addons, somehow these don’t work well for me.

Hotfixes, Addons and Update Packs dialog nlite Hotfixes, Addons and Updates contains a list of patches to be applied, with column headers of Name, Description, Language, Build Date, Size and Mor Info. More info column contains URLs.

Components Window

10. Click “Next” to Components window, and also in the popup Compatibility window. This is just to avoid you accidentally removing important components for selected function. You don’t need to select anything and click OK.

nLite compatibility dialog nLite compatibility dialog contains a series of checkboxes. None of them are selected.

11. In the Components window, you can select the listed items that you feel you won’t need on your Eee.

nLite components dialog nLite components dialog contains a tree view of items with check boxes next to them. All 10 items are not checked.

Here were my selections:

Applications:

I think Defragmenter is no use for 4G SSD, but I keep Defragmenter anyway, no biggee.

nLite components dialog Applications tree nLite components dialog Applications tree. All items are selected except Calcuator, Charmap, Defragmenter and Paint. Therefore these are the items that will be kept.

Drivers:

Select “All” to be removed because we have the Eee driver CD.
nLite components dialog Drivers tree nLite components dialog drivers tree. All items are selected for removal.

If you are planning on using PDAnet so that you can use your Windows Mobile phone as a modem, you need to leave the drivers for “modem” unchecked.

Hardware Support:

  • Windows Image Acquisition: If deleted, will loss transparent icon text in desktop. (Hahutzy)
  • Modem Support: Don’t remove it if you want 3G wireless. (goofy)
  • Bluetooth Support: I recommend to leave BT support. If you buy a USB BT dongle, without BT support it would not work. (michalbit)
  • Multi-processor support: If you have an Intel Atom processor, you will need this for SMT support. It can be removed in Celeron models

nLite components dialog Hardware support nLite components dialog hardware support tree. Items that aren’t selected for removal are AGP filters, Battery, CPU Intel, Intel PCI IDE controllers, Logical Disk Manager, Microsoft colour Management (ICM), Multi-Processor Support (for Atom) Ports (COM and LPT), Printer Support, Secure Digital Host Controller, Teletext codec, USB Audio Support, USB Ethernet, USB video capture devices, video capture and Windows Image Acquisition.

Keyboards:

If you need IME, you need to keep the keyboard that you need. Select all to remove except what you need.

nLite components dialog Keyboard tree nLite components dialog keyboard tree.

Languages:

Select all to remove except the language that you need. (In my case, I keep Simplified Chinese).

nLite components dialog language tree nLite components dialog language tree.

Multimedia:

  • Windows Media Player: If removed, may cause issues for iTunes, NTI CD Maker 7, and Winamp 5. (_Mazza_)
  • DirectX Diagnostic Tool: Very helpful if you are having trouble installing some games.

note from robuust: I remove Windows sounds, because i don’t have sound switched on while working (and the onboard speakers are not that good either :P )
also speech support can be safely removed, and you can always download and install later if needed.
nLite components dialog multimedia treenLite components dialog multimedia tree. Items selected for removal are AOL Art Image Support, DirectX Diagnostic Tool, Images and Backgrounds, Intel Indeo Codecs, Mouse Cursors, Movie Maker, Music Samples, Old CDPlayer and Sound Recorder, Tablet PC.

Network:

I kept Windows Messenger because Live Messenger has annoying ad bars that are not good for the Eee’s 800×480 resolution.

nLite components dialog network treenLite components dialog network tree. Items selected for removal are Client for Netware Networks, Communication Tools, Control Test Terminal Program, Connection Manager, Frontpage Extension, Internet Information Services, MSN Explorer, Netshell Cmd-Tool, Network Monitor Driver and Tool, NWLink IPX/SPX/NetBIOS protocol, Peer to Peer, Synchronisation Manager, Vector Graphics Rendering (VML), Web Folders.

Operating System Options:

  • 16-bit Support: Don’t remove if you intend to install applications that use older versions of InstallShield or plan to make bootable USB flash drives. (Jay Jech)

nLite components dialog Operating System Options treenLite components dialog Operating System Options tree. Items not selected for removal are Color Schemes, Disk Cleanup, Extra Fonts, File System Filter Manager, Format Drive Support, Group Policy Management Controller, Help Engine, Input Method Editor, Internet Explorer Core, Jet Database Engine, Local Security Settings, Login Notification, MDAC, Out of Box Experience (OOBE)Shell Media Handler, User account pictures, Visual Basic 5 runtime, Visual Basic 6 runtime, Visual Basic Scripting Support, Zip Folders

Do not check Manual Install and Upgrade, if you want to install XP from USB pendrive according to http://www.eeeguides.com/2007/11/installing-windows-xp-from-usb-thumb.html. This cannot be emphasized enough. If you have trouble installing using a USB flash drive, check this setting first!

Services:

  • Background Intelligent Transfer Service (BITS): You may need to keep this if you are going to install Dot Net CF 3.0 (citivolus). Also removing BITS may cause issues with Windows update (ma10). Picture is updated to preserve BITS.
  • Task Scheduler: Required for Prefetcher to function properly. (kaiserpc)

nLite components dialog Servicess options treenLite components dialog Servicess options tree. items not selected for removal are Background Intelleigent Transfer Service, DHCP Client, DNS Client, Event Log, HTTP SSL, Keberos Key Distribution Center, Network Location Awareness (NLA), Network Privisioning, Protected Storage, Shell Services, System Event Notification (SENS), System Monitor, Text Services Framework, Universal Plug and Play Device Host, Windows Firewall/Internet Connection Sharing (ICS), Windows Management Instrumentation, Windows Time, Wireless Configuration.

Directories:

nLite components dialog Directories treenLite components dialog Directories tree; all items are selected for removal.

Unattended Window

12. Click Next to Unattended window. In the General tag, input your XP serial number and it will not ask for it later during installation. Also, check “Turn off Hibernate”.

nLite unattended windows dialog gemeral tab nLite unattended windows dialog gemeral tab A dialog with combo boxes and check boxes. most options are set to their defaults. Turn off Hibernate is checked.

Users tab:

nLite unattended window dialog users tabnLite unattended window dialog users tab contains controls for adding users, setting passwords, setting automatic login counts, password expirey etc.

Owner and Network ID tab:

nLite unattended window dialog Owner and Network ID tabnLite unattended window dialog Owner and Network ID tab has edit boxes to set computer name, workgroup name, full name and organisation.

Regional tab:

nLite unattended window dialog regional tabnLite unattended window dialog regional tab contains controls to set language, location, keyboard and time zone.

Desktop Themes tab:

nLite unattended window dialog desktop theme tabnLite unattended window dialog desktop theme tab. Sets the default desktop theme. Windows classic will allow for better performance and will give the classic windows start menu.

Display tab:

nLite unattended window dialog display tabnLite unattended window dialog display tab. set colour depth, screen resolution and refresh rate. Defaults are used.

For the other tabs, you can leave them as they are.

Options Window

13. Click “Next” to Options window. In the General tab, you don’t need change anything.

nLite options window general tab nLite options window general tab. a list of options and values beside each option in a combo box.

In the Patches tab, choose Disable SFC.
nLite options window patches tabnLite options window patches tab. Lists Three different options with descriptions and a disable button for each.

Tweaks Window

14. Click Next to bring up the Tweaks window.

 nLite tweaks windownLite tweaks window has two tabs; general and services. the general tab has a tree view of 13 items with checkboxes next to them.

Here are my settings in General tab:

Boot and Shutdown:

nLite tweaks window boot up options treenLite tweaks window boot up options tree. Each item in this tree has a sub tree with disable and enable radio buttons. To select an item for deletion, the disable button must be activated. Options selected for disabling are control alt del at logon, Do not parse autoexec.bat, and numlock.

Desktop:

nLite tweaks window Desktop optionsnLite tweaks window Desktop options. Each item has a sub tree of radio buttons. Items selected are: desktop icon size is set to 32, internet explore icon is set to show, my computer icon is set to show, my documents icon is set to show, my network places icon is set to hide, recycle bin button is set to show.

Explorer:

nLite tweaks window explorer optionsnLite tweaks window explorer options. A lot of these are user preference, especially for users of screenreaders. Options checked in the graphic are Classic Control Panel, Disable Prefix Shortcut to, Remove Send To on context menu, Show Drive Letters in front of Drive Names, Show estensions of known file types, Show Map Network Drives buttons in Explorer Bar, use small icons in explorer bar.

Internet Explorer:

nLite tweaks window Internet Explorer treenLite tweaks window Internet Explorer tree. Items checked for inclusion are Disable download complete notification, Disable Market Place Bookmarks, Disable Media Player 6.4 created bookmarks, Disable Password Caching, Enable Google Url/Search

My Computer and Network:

nLite tweaks window My Computer and Network treenLite tweaks window My Computer and Network tree. Once again user preference. The only item selected here is Remove shared documents

Performance:

nLite tweak window performance treenLite tweak window performance tree. Most items are checked. items that aren’t checked are Process scheduling and Use Windows classic folders/No Task Sidepanel.

Privacy:

nLite tweaks window privacy treenLite tweaks window privacy tree the only option checked is Remove Alexa.

Start Menu:

nLite tweaks window start menu treenLite tweaks window start menu tree. options selected are: clear most recently opened documents list on logoff, disable and remove Documents list from the Start Menu, Disable Drag and Drop, Disable Highlight newly installed programs, Disable popup on first boot, Hide Run button. My network Places has a radio button subtree set to Don’t display this item. Printers and faxes has a radio button sub tree set to don’t display this item. Other items selected are Remove Logoff User, Remove Search For People from Search, Remove Search the Internet from Search, remove Set Program Access and Defaults, Remove Windows Catalog shortcut, Remove Windows Update Shortcut, use small icons on Start menu.

Taskbar:

nLite tweaks window Taskbar treenLite tweaks window taskbar tree. The only item selected is Hide Volume Control Icon in System Tray.

Visual Effects:

nLite tweaks window Visual Effects treenLite tweaks window Visual Effects tree. No items are selected.

Windows Media Player:

nLite tweaks window Windows Media Player treenLite tweaks window Windows Media Player tree. Items not selected are disable all streaming protocols, do not show anchor in Designmode, No virtualisation, Remove all context menu entries, Zoom video to windowsize.

Services:

(I didn’t change anything in Services)

nLite tweaks window services tabnLite tweaks window services tab. The second tab of the tweaks window. a lisst of services and their status, all of which on this screen are set to default.

Implementing the Changes

15. Click “Next” and nLite will process changes base on your previous choices.

nLite processing window nLite processing window. The processes it will undertake are listed, the current one is bolded and the rest are greyed out. Underneath this is a progress bar. Underneath that is text of what is being done, in this case extracting cabs. The next button is greyed out and the Cancel and Tray buttons are available.

It will take a while. After it is done, it shows the new installation files size.

nLite processing screen when donenLite processing screen when done. The same screen as previous but the list of processes is all greyed out and the status bar is gone. The text now reads “Finished! Total size is 189.53MB. The installation was reduced by 429.33MB.” The next button is now available.

Italic Text

Bootable ISO Window

16. Click “Next” to Bootable ISO window. Click “Make ISO” button to generate a new ISO file.

nLite bootable ISO windownLite bootable ISO window. Contains options for creating an ISO/burning a disc. options include Mode combo box, label edit field, ISO Engine combo box, Boot sectore combo box. There is an Empty progress bar and Make ISO button. Information text reads “If you want to include additional files on your CD/DVD, copy them to the working directory before starting, or just click next if you want to make the ISO later”.

17. Use Nero or some other tool to burn ISO file, and then you are ready to install Windows XP for Eee.

Posted in Software | Tagged: , , , | Leave a Comment »

Installing WinXP on EEE PC by USB-Stick

Posted by truongngh on July 13, 2009

Please note this tutorial works on all computers not just the Asus EEE PC.
To complete this tutorial you need a 32bit version of Windows XP or Windows Vista installed on your home PC.

What you’ll need:
USB_PREP8 (alternative download)
PeToUSB (alternative download)

Bootsect.exe (alternative download)

Special Note: If you use the program Nlite be sure to keep the manual installation files as the USB_prep8 script relies on these files. (In the Components window (nLite app), Operating System Options: Do not check Manual Install and Upgrade)
Extract the files in Bootsect.zip
The next step is to extract USB_prep8 and PeToUSB.
Next copy the PeToUSB executable into the USB_prep8 folder.
Inside of the USB_prep8 folder double click the executable named usb_prep8.cmd.

The window that opens will look like this:

Press any key to continue

You next window will look like this:
These settings are preconfigured for you all you need to do now is click start.
Once the format is complete DO NOT close the window just leave everything as it is and open a command prompt from your start menu (type cmd in the search bar or run box depending on your version of windows.).

Inside of the command windows go to the directory you have bootsect.exe saved.
(use the cd directoryname command to switch folders)

Now type “bootsect.exe /nt52 R:” NOTE R: is the drive letter for my USB stick if yours is different you need to change it accordingly. What this part does is write the correct boot sector to your USB stick, this allows your PC to boot from the USB stick without it nothing works.
Please note: When running the bootsect.exe command you cannot have any windows open displaying the content of your USB stick, if you have a window open bootsect.exe will be unable to lock the drive and write the bootsector correctly.

If all went well you should see “Bootcode was successfully updated on all targeted volumes.”

Now you can close this command prompt (don’t close the usbprep8 one by mistake) and the petousb window.

You window you see now should look like this:

If it doesn’t try pressing enter.

Now you need to enter the correct information for numbers 1-3.
Press 1 and then enter. A folder browse window will open for you to browse to the location of you XP setup files (aka your cdrom drive with xp cd in)
Press 2 and enter a letter not currently assigned to a drive on your PC
Press 3 and enter the drive letter of your USB stick
Press 4 to start the process.

The script will ask you if its ok to format drive T:. This is just a temp drive the program creates to cache the windows installation files. Press Y then enter.

Once it’s done formating press enter to continue again, you can now see the program copying files to the temp drive it created. Once this is done press enter to continue again.

Next you will see a box pop up asking you to copy the files to USB drive yes/no you want to click yes.

Once the script has completed copy files a popup window asking if you would like to USB drive to be preferred boot drive U: select YES on this window.

Now select yes to unmount the virtual drive.

Ok we are done the hard part, close the usbprep8 window.

Now make sure your EEE pc is configured with USB as the primary boot device.
Insert your USB drive and boot up the EEE.

On the startup menu you have two options, select option number 2 for text mode setup.

From this point on it is just like any other windows XP installation delete/recreate the primary partition on your EEE pc and format it using NTFS. Make sure you delete ALL partitions and recreate a single partition or you will get the hal.dll error message.

Once the text mode portion of setup is complete it will boot into the GUI mode (you can press enter after the reboot if your too excited to wait the 30 seconds)

Once the GUI portion of setup is complete you will again have to boot into GUI mode this will complete the XP installation and you will end up at you XP desktop. It is very important that you DO NOT REMOVE THE USB STICK before this point. Once you can see your start menu it is safe to remove the usb stick and reboot your pc to make sure everything worked.

This method has advantages over all current no cdrom methods of installing XP to the EEE. You do not have to copy setup files in DOS to the SSD and install from there. It gives you access to the recovery console by booting into text mode setup, and it gives you the ability to run repair installations of XP if you have problems later on.

I hope this worked out for you and please post feedback to the comments section.
Please note due to the amount of comments this article has received you must now click on “Post a Comment” below the existing comments to view the most recent feedback in a popup window.

Posted in Software | Tagged: , , , , , | 1 Comment »

JVM Monitoring with JConsole

Posted by truongngh on June 26, 2009

Setting System Properties

To enable and configure the out-of-the-box JMX agent so that it can monitor and manage the Java VM, you must set certain system properties when you start the Java VM. You set a system property on the command-line as follows.

java -Dproperty=value ...

You can set any number of system properties in this way. If you do not specify a value for a management property, then the property is set with its default value.

Configuration for JVM monitor

  1. Enable the JMX agent (another name for the platform MBean server) when you start the Java VM. You can enable the JMX agent for:
    • Local monitoring, for a client management application running on the local system.
    • Remote monitoring, for a client management application running on a remote system.
  2. Monitor the Java VM with a tool that complies to the JMX specification, such as JConsole. See Chapter 3, Using JConsole for more information about Console.

Local Monitoring and Management

Under previous releases of the Java SE platform, to allow the JMX client access to a local Java VM, you had to set the following system property when you started the Java VM or Java application.

com.sun.management.jmxremote

Setting this property registered the Java VM platform’s MBeans and published the Remote Method Invocation (RMI) connector via a private interface to allow JMX client applications to monitor a local Java platform, that is, a Java VM running on the same machine as the JMX client.

NOTICE:

  • In the Java SE 6 platform, it is no longer necessary to set this system property. Any application that is started on the Java SE 6 platform will support the Attach API, and so will automatically be made available for local monitoring and management when needed.
  • On Windows platforms, for security reasons, local monitoring and management is only supported if your default temporary directory is on a file system that allows the setting of permissions on files and directories (for example, on a New Technology File System (NTFS) file system). It is not supported on a File Allocation Table (FAT) file system, which provides insufficient access controls.

Remote Monitoring and Management

To enable monitoring and management from remote systems, you must set the following system property when you start the Java VM.

com.sun.management.jmxremote.port=portNum

In the property above, portNum is the port number through which you want to enable JMX RMI connections. Be sure to specify an unused port number. In addition to publishing an RMI connector for local access, setting this property publishes an additional RMI connector in a private read-only registry at the specified port using a well known name, "jmxrmi".

Security

We can use password for authentication, SSL can be used also. For configuring these settings, refer to the source at the bottom of this entry.

Problem with Linux

Question: I am having problem using JConsole to connect to a JVM running on Linux. Connecting to JVM running on Windows and Solaris works fine.

Answer: This is most likely a configuration problem on the Linux machine or the management properties specified to run the application. Please also see FAQ #4 about using SSL.

You should check the following:

  • Check if the hostname correctly resolves to the host address.Run "hostname -i" command. If it reports 127.0.0.1, JConsole would not be able to connect to the JVM running on that Linux machine. To fix this issue, edit /etc/hosts so that the hostname resolves to the host address.
  • Check if the Linux machine is configured to accept packets from the host where JConsole runs on to connect to the application.Packet filtering is built in the Linux kernel. You can run "/sbin/iptables --list" to determine if an external client is allowed to connect to the JMX agent created for remote management. You can use the following command to add a rule to allow an external client such as JConsole to connect: /usr/sbin/iptables -I INPUT -s jconsole-host -p tcp --destination-port jmxremote-port -j ACCEPT where jconsole-host is either the hostname or the host address on which JConsole runs on and jmxremote-port is the port number set for com.sun.management.jmxremote.port for remote management.

Question: problem when using a multi network device.

Answer: must specify RMI binding interface to the address that you want to connect to for monitoring. Set this parameter to jvm:

java -Djava.rmi.server.hostname=<hostname/IP>

Example: for Apache Tomcat, change bin/catalina.sh as follow to make it be monitored and managed remotely.

if [ "$1" = "remotemonitor" ] ; then
     CATALINA_OPTS="$CATALINA_OPTS  -Dcom.sun.management.jmxremote.port=9090 "
     CATALINA_OPTS="$CATALINA_OPTS  -Dcom.sun.management.jmxremote.authenticate=false "
     CATALINA_OPTS="$CATALINA_OPTS -Dcom.sun.management.jmxremote.ssl=false "
     CATALINA_OPTS="$CATALINA_OPTS -Djava.rmi.server.hostname=10.120.6.2 "
 shift
fi

Logging for monitoring problem

  • jconsole -J-Djava.util.logging.config.file=<logging.properties> . where <logging.properties> is your logging.properties file. More information can be found here.
  • If it’s a security related problem (using SSL) you may also want to use
    jconsole -J-Djava.security.debug=all
    or if you want to reduce the amount of security traces you can get a list
    of debug options by typing:
    java -Djava.security.debug=help foo

Using JConsole for mornitoring and management

Refer to source at the bottom of the entry.

Source: http://download.java.net/jdk7/docs/technotes/guides/management/agent.html

Source: http://download.java.net/jdk7/docs/technotes/guides/management/faq.html

Source: http://java.sun.com/javase/6/docs/technotes/guides/management/agent.html

Source: http://blogs.sun.com/jmxetc/entry/troubleshooting_connection_problems_in_jconsole

Source: http://java.sun.com/javase/6/docs/technotes/guides/management/jconsole.html

Source: http://blogs.sun.com/jmxetc/resource/logging.properties

Source: http://java.sun.com/performance/jvmstat/ (sample code for monitor jvm)

Posted in Uncategorized | 1 Comment »

Axis2 Maven2 plugin

Posted by truongngh on June 26, 2009

Generate client-side/server-side code from a wsdl file.

Insert these lines in to pom.xml between tag <plugins>:

<plugin>
  <groupId>org.apache.axis2</groupId>
  <artifactId>axis2-wsdl2code-maven-plugin</artifactId>
  <version>1.4</version>
  <configuration>
    <packageName>com.mobivi.rxsecd</packageName>
    <wsdlFile>wsdl/rxsecd.wsdl</wsdlFile>
    <databindingName>jaxbri</databindingName>
  </configuration>
  <dependencies>
    <dependency>
      <groupId>org.apache.axis2</groupId>
      <artifactId>axis2-jaxbri</artifactId>
      <version>${axis2.version}</version>
    </dependency>
  </dependencies>
  <executions>
    <execution>
      <phase>generate-resources</phase>
      <goals>
        <goal>wsdl2code</goal>
      </goals>
    </execution>
  </executions>
</plugin>

Configuration for this plugin:

Parameter Name Command Line Property Description Default Value
databindingName ${axis2.wsdl2code.databindingName} Data binding framework, which is being used by the generated sources. adb
generateAllClasses ${axis2.wsdl2code.generateAllClasses} Whether to generate simply all classes. This is only valid in conjunction with “generateServerSide”. false
generateServerSide ${axis2.wsdl2code.generateServerSide} Whether server side sources are being generated. false
generateServerSideInterface ${axis2.wsdl2code.generateServerSideInterface} Whether to generate the server side interface. false
generateServicesXml ${axis2.wsdl2code.generateServicesXml} Whether a “services.xml” file is being generated. false
generateTestcase ${axis2.wsdl2code.generateTestCase} Whether a test case is being generated. false
language ${axis2.wsdl2code.language} Programming language of the generated sources. java
namespaceToPackages ${axis2.wsdl2code.namespaceToPackages} Map of namespace URI to packages in the format uri1=package1,uri2=package2,… Using this parameter is discouraged. In general, you should use the namespaceUris parameter. However, the latter cannot be set on the command line.
namespaceURIs Map of namespace URI to packages. Example: <namespaceURIs> <namespaceURI> <uri>uri1</uri> <packageName>package1</packageName> </namespaceURI> …….. </namespaceURI>
outputDirectory ${axis2.wsdl2code.target} Target directory, where sources are being target/generated-sources/axis2/wsdl2code generated.
packageName ${axis2.wsdl2code.package} Package name of the generated sources.
portName ${axis2.wsdl2code.portName} Port name, for which sources are being generated. By default, sources are generated for a randomly picked port.
allPorts ${axis2.wsdl2code.allPorts} Set this to true to generate code for all ports. false
serviceName ${axis2.wsdl2code.serviceName} Service name, for which sources are being generated. By default, sources are generated for all services.
syncMode ${axis2.wsdl2code.syncMode} Sync mode, for which sources are being generated; either of “sync”, “async”, or “both” (default). both
unpackClasses ${axis2.wsdl2code.unpackClasses} Whether to unpack classes.
wsdlFile ${axis2.wsdl2code.wsdl} Location of the WSDL file, which is read as input src/main/axis2/service.wsdl

Source: http://ws.apache.org/axis2/tools/1_4_1/maven-plugins/maven-wsdl2code-plugin.html

Posted in Uncategorized | Leave a Comment »