Eclipse RCP Miscs Series 2


Eclipse RCP Miscs Series 2

Perspective listener
-- Define the behavior what to do when perspective is activated or changed.
IWorkbenchWindow.addPerspectiveListener(IPerspectiveListener listener) and removePerspectiveListener(IPerspectiveListener listener).

Allow user to bring job dialog back
After checked the Checkbox "always run in background", there would be no way to re-show it, so RCP application should define one preference to allow user to reshow the dialog.
    protected void createFieldEditors()
    {
       runInBackground = new BooleanFieldEditor(
           IPreferenceConstants.RUN_IN_BACKGROUND,
           "Always run in background",
           getFieldEditorParent());
       addField(runInBackground);
}
    public boolean performOk()
    {
       try
       {
           WorkbenchPlugin
               .getDefault()
               .getPreferenceStore()
               .setValue(IPreferenceConstants.RUN_IN_BACKGROUND, runInBackground.getBooleanValue());
       }
       catch (IOException e)
       {
           e.printStackTrace();
       }
       return super.performOk();
    }
ToolTip for TreeItem

Since SWT/JFace 3.3, your TreeViewer's lable provider can extend ColumnLabelProvider, and implement the cool getTooltip() methods, and enable it by ColumnViewerToolTipSupport.enableFor (viewer);

1. Outside of your rcp project, type
mvn3
org.sonatype.tycho:maven-tycho-plugin:generate-poms -DgroupId=se.mattiasholmqvist -Dtycho.targetPlatform=~/dev/eclipse-3.6.1-delta/
This will create a pom.xml for the current directory (parent project) and a pom.xml for each eclipse project.
2. Building the product
mvn3
clean package -Dtycho.targetPlatform=~/dev/eclipse-3.6.1-delta/

Export product to other platforms
1. Download and install Eclipse DelatPack
In the page, http://download.eclipse.org/eclipse/downloads/, search DeltaPack.
2. Configure org.sonatype.tycho/maven-osgi-packaging-plugin in pom.xml: set the environment values for the target platform.
You can get these values form the delta pack:
org.eclipse.equinox.launcher.${ws}.${os}.${arch}_1.1.0.v20100503
For instance, from
org.eclipse.equinox.launcher.motif.aix.ppc_1.1.0.v20100503, we can see to build a AIX product:
ws should be motif, os should be aix, arch should be ppc.


A concrete example:

Java Basics


The Get and Put Principle
- "Producer Extends, Consumer Super"
- use an extends wildcard when you only get values out of a structure, use a super wildcard when you only put values into a structure, and don’t use a wildcard when you both get and put.
public static <T> void copy(List<? super T> dest, List<? extends T> src)

Type erasure
- fix it - pass class type
- no way to find out the runtime type of generic type parameters in Java
- pass the Class of the type parameter
- create(Class<T> type)
new ArrayList<Integer>().getClass() == new ArrayList<String>().getClass(); // true
Difference between ArrayList<? extends T> and ArrayList<? super T>

Unbounded Wildcards - Class<?>
printList(List<?> list)
List<Object> and List<?> are not the same.
- can only insert null into a List<?>.

Upper Bounded Wildcards -- List<? extends Foo> list
- List<Number> is more restrictive than List<? extends Number>
Lower Bounded Wildcards -- List<? super Integer> list

NoClassDefFoundError
- it's an Error - LinkageError
- class was present during time of compilation but not available at runtime when class loader is trying to load it
- error on static initializer block can also result in NoClassDefFoundError.

ClassNotFoundException
- checked exception - must handled in the code
- load a class in runtime using Reflection, such as Class.forName(), ClassLoader.loadClass()

prefer double over float
- float: single (32 bit) precision
- double: double (64 bit) precision

Static method
- static method is always resolved at compile time by using Type of reference variable
- can not access non static member inside static context
- static variables are also not serialized During Serialization

Why String is immutable
String Pool
Multithreading Benefits
Optimization and Performance
- hashcode is cached
HashMap keys

Service provider interface (SPI)
- an API intended to be implemented or extended by a third party
Service Provider
ServiceLoader
- Load drivermanager

Checked vs RuntimeException
- Use exceptions only for exceptional scenarios
- Use checked exceptions for recoverable conditions and runtime exceptions for programming errors
- Use checked exceptions when want to force to client to think how to handle the recoverable exceptional situation. Otherwise use RuntimeException

- Avoid unnecessary use of checked exceptions
- Favor the use of standard exceptions
- If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.
- Don't use Exceptions for control flow
- Use a checked exception for conditions client code can reasonably be expected to handle.

RXjava Exceptions.propagate()
- throw a RuntimeException and Error directly or wrap any other exception type into a RuntimeException.
Thread.setDefaultUncaughtExceptionHandler(handler);

String.CASE_INSENSITIVE_ORDER

Java NIO
Stream Oriented vs. Buffer Oriented
Blocking vs. Non-blocking IO
- only get what is currently available, or nothing at all
- not wait for it to be fully written

Selectors
- an object that can monitor multiple channels for events
Channels
- FileChannel,FileChannel,DatagramChannel,ServerSocketChannel
Buffers
- ByteBuffer, CharBuffer, IntBuffer,LongBuffer,ShortBuffer

Why can't we define a static method in an interface?
Suppose we could do it, if interface A declares methodF, two class B, C both implement interface A. then if we can interfaceA.methodF(), what implementation it should call. JVM just can't figure it out.
Annotations
Annotations (also known as metadata) provide a formalized way to add information to the code so later other tools can easily use these metadata.
Annotations themselves are hardly more useful than comments, more valuable thing is the tools that read and process them.
Annotations are partly motivated by a general trend toward combining metadata with source-code files, instead of keeping it in external documents. In many cases, this can simplify maintenance significantly.
It can provide cleaner looking code, compile-time checking, IDE support, annotation API to get and process these added information.
Annotations are widely used by frameworks such as web services, EJB3, hibernate, that require some sort of additional information to accompany your source code.

Multithread
Why double checked locking doesn't work in Java?
Double checked locking in java is usually implemented like the following:
public class Singleton {
    private Singleton instance;
    public static Singleton getInstance() {
     if (instance == null) {
       synchronized(this) {
         if (instance == null) {
           instance = new Singleton ();
         }
       }
     }
     return this.theGadget;
    }
}
The main reason is that the new operation is not atomic.
At First, one thread pass the null check and tries to initialize the object, because the new operation is not atomic, the process - start allocating and writing the object to the field, contains several writes to memory without guaranteed ordering.
During this period, another thread can come in, see the partially written object.
It would pass the null check, and return the partially allocated object. This can happen with objects, longs type on a 32-bit platform.

ThreadLocal
Definition
ThreadLocal is used to create thread-local variable, each thread will have its own Thread Local variable. One thread can not access/modify other thread’s Thread Local variables, meanwhile they can be accessed from anywhere inside that thread.
ThreadLocal provides get and set accessor methods that maintain a separate copy of the value for each thread that uses it. When a thread calls ThreadLocal.get for the first time, initialValue is consulted to provide the initial value for that thread.
ThreadLocal can be used as an alternative to synchronization to improve scalability and performance. Classes encapsulated in ThreadLocal are automatically thread-safe in a pretty simple way, since it’s clear that anything stored in ThreadLocal is not shared between threads.
When to use ThreadLocal?
ThreadLocal can be used as an alternative to synchronization. In some cases, this can improve scalability and performance significantly.
ThreadLocal can be used to reuse non-trivial objects, just as a resource/object pool.
ThreadLocal is widely used in implementing application frameworks to maintain some context related to the current thread.
For example, J2EE containers use ThreadLocal to associate a transaction context with an executing thread for the duration of an EJB call.
Caveats
It is easy to abuse ThreadLocal by treating its thread confinement property as a license to use global variables or as a means of creating "hidden" method arguments.
Thread-local variables can detract from reusability and introduce hidden couplings among classes, and should therefore be used with care.


Resource
Think in Java (4th Edition)
Oracle JRockit: The Definitive Guide
Thread-local variables in Java
Java Thread Local – How to Use and Code Sample
When and how should I use a ThreadLocal variable?

Remember Knowledge Is Power


Remember Knowledge Is Power

Ten years ago, I didn't write any diary.
Four years ago, when I worked as an intern at one company, I observed and realized that when I asked questions to my mentor, she can always quickly find the answer from her computer diary.

I thought this was really a good habit, and began to write diary.
But at first I usually just write them and forget them, rarely review them.

Three yeas ago, I began to try to blog in English as a way to improve my English writing skills.
Write down some notes and review then up when I needed them.

Recently, when we discussed one problem with my colleague, he tried to type the one a-little-complex command. Usually I do this by copy and paste. But my colleague tried to analyze and remember this command when he was typing. This reminded me that how many times that I Google searched, and found some solutions, some commands, or even posted to my blog, but I just can't remember them, next time, I had to do Google search or look up in my blog again. This was so inefficient, and wasted my time. So if these information and solutions are really valuable, why I don't try to remember them.

I really should try to remember more, remember them when I am using them - of course, not all knowledge is worthy remembering.
This sway, I can save time, work more efficiently, provide answer/solution more quickly, and can make me look cooler and smarter :)

Also one of my colleagues is really very cute, seems he is really good at remembering things, defect number, event date and etc, I Admire him.

I really should read some books about how to improving memory, how to use my whole brain during studying and working, improve these abilities, and improve my skills to do, study and work effectively.

Bug Analysis Part 1


Bug Analysis Part 1

- StreamCorruptedException: unexpected block data


We met a field defect recently, client sent a command to server, but didn't get response. At Server there was no log indicating that it received the command.

At first, we thought it maybe a network related problem, as from client logs, we can see user tried same command several times, and run this command immediately after connected to server.

From server logs, we can see each time, after connection was created successfully and the application tried to read command, the application would throw 'StreamCorruptedException: unexpected block data ', and connection would be closed.

But we can't understand that if it’s a network connection problem, why it happened so frequently.
And we shouldn't blame the network easily, without real evidence, right?

From this book Debug It!, we learn that - it’s too easy to point the finger of blame to other components or hardware, we should suspect your own code first.

Meanwhile we didn't find some obvious problems about network.

What we should do next?
One of the most important skills for problem analysis is to think divergently, come up all possibilities, and check and test then in the order of probability.

Look at the Javadoc, StreamCorruptedException:
Thrown when control information that was read from an object stream violates internal consistency checks.

Maybe the connection was good, but only this type of command failed. – We should look at the log: does this client ever successfully executed one of this type of command, does it successfully executed other types of command?

Are the client and server version same and compatible? Version mismatch is a common source of bug in client/server application.

So check the version of client and server. Yep, it's different, client is new, and server is old.


What to do next?
In Debug It!, it teaches us that Always Reproduce the Problem First.
Sometimes we think we are just smart and we can find the root cause of the problem just by thinking, but if we can't reproduce it, how we can verify what we think is really the root cause, and how to verify that our fix does fix the problem in future.
Or sometimes, we are just lazy, as trying to reproduce the problem is usually not easy.
But this always pay off, as if we can find the way to produce the problem, then finding the root cause and fixing it would be easy.
Remember to use exact same version application as one used in client environment is important.

So next we used exact same client/server application and executed the command. Immediately we recreated the problem!

Next part is about the technical stuff.
Simply put, the reason is because in new version client, the command implementation changes, it introduces a new command class, and sends the new command object to server.

The old server doesn't have this command class, and can't deserialize the command object.

But normally, if one class is missing, java deserialization should throw ClassNotFoundException, why StreamCorruptedException? Is our analysis correct?

To figure it the reason, we wrote a simple java application, it writes the command object to the file, and reads it back.

During deserialization, we deleted the new command class, it does throw the StreamCorruptedException.

Check the source code, we figure it out this may be because the command overrides readObject and writeObject.

Sample code:
public class Deserialization
{
    public static void main(String[] args) throws Exception
    {
       writeZippedObject();
       readZippedObject();
    }

    private static void writeZippedObject() throws FileNotFoundException, IOException, SecurityException,
       NoSuchMethodException
    {
       FileOutputStream fos = new FileOutputStream("command");
       GZIPOutputStream gos = new GZIPOutputStream(fos);
       ObjectOutputStream oos = new ObjectOutputStream(gos);

       Method method = Math.class.getMethod("sqrt", new Class[] { double.class });
       Command command = new ConfigCommand(method, new Object[] { Integer.valueOf(4) });
       oos.writeObject(command);
       oos.close();
       fos.close();
       System.out.println("write command: " + command);
    }

    private static void readZippedObject() throws FileNotFoundException, IOException, ClassNotFoundException
    {
       FileInputStream fis = new FileInputStream("command");
       GZIPInputStream gis = new GZIPInputStream(fis);
       ObjectInputStream ois = new ObjectInputStream(gis);

       Command command = (Command) ois.readObject();
       System.out.println("read command: " + command);
       fis.close();
    }
}

class Command implements Serializable
{
    private static final long serialVersionUID = 1L;
    private String serviceString = null;
    private String methodName = null;
    protected Object[] params = null;

    public Command(Method method, Object[] params)
    {
       methodName = method.getName();
       Class service = method.getDeclaringClass();
       serviceString = service.getName();
       this.params = params;
    }

    private Map fieldsTable = new HashMap();

    public String toString()
    {
       return "[serviceString: " + serviceString + ", methodName: " + methodName + "]";
    }

    private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException
    {
       fieldsTable = (HashMap) in.readObject();
       serviceString = (String) fieldsTable.get("serviceString");
       methodName = (String) fieldsTable.get("methodName");
       params = (Object[]) fieldsTable.get("params");
    }

    private void writeObject(ObjectOutputStream out) throws IOException
    {
       fieldsTable.put("serviceString", serviceString);
       fieldsTable.put("methodName", methodName);
       fieldsTable.put("params", params);
       out.writeUnshared(fieldsTable);
    }
}

class ConfigCommand extends Command
{
    public ConfigCommand(Method method, Object[] params)
    {
       super(method, params);
    }
    private static final long serialVersionUID = 1L;
}

Without readObject/writeObject in Command class and ConfigCommand class, it would throw ClassNotFoundException.

With these 2 serialization-related methods, deserialization without the ConfigCommand would throw ‘StreamCorruptedException: unexpected block data’:
Exception in thread "main" java.io.StreamCorruptedException: unexpected end of block data
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1355)
    at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1951)
    at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1875)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1757)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1333)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:352)
    at objectio.Deserialization.readZippedObject(Deserialization.java:47)
    at objectio.Deserialization.main(Deserialization.java:22)

Lesson Learned
Know your code well, and know its change history well, write them down.
If we know the implementation of this command changed significantly, we might find out the root cause faster.

Read defect description carefully, but keep your mind open, the report might not give too much information, or even give misleading or wrong information.

Think whether the same problem may occur elsewhere, and ensure it not occur again.

Why this bug go into field, and why it is not caught up in unit test and regression test.
Whether our unit test and regression test should be improved?

Client/server mismatch is a very common problem, in development we should think whether our change would cause client/server mismatch, if yes, do unit test carefully for all possible combinations, old client/new server, new client/old server, new client/new server.
And always run regression test for all possible combinations.

Aphorisms


Aphorisms

Learn
Practice makes perfect.
Nurture passes nature.
Rome was not built in a day.
Strike while the iron is hot.
Thoughts are free from toll.
A fall into the pit, a gain in your wit.
A young idler, an old beggar.
An idle youth, a needy age.
Clumsy birds have to start flying early.
Custom makes all things easy.
Difficult the first time, easy the second.
Experience is the best teacher.
A young idler, an old beggar.
Time tries all things.
There is no royal road to learning.
A good medicine tastes bitter.
Live and learn.
In doing we learn.
Reading makes a full man. 读书长见识。
The best horse needs breeding, and the aptest child needs teaching.
Learn young, learn fair. 学习趁年轻,学就要学好。
Nothing is more frequently overlooked than the obvious.
—Thomas Temple Hoyne
Wisdom in the mind is better than money in the hand.
Learn to walk before you run. 循序渐进
Activity is the only road to knowledge.

Book
Books, like friends, should be few and well chosen.
A book is the same today as it always was and it will never change.

Personality
Poverty is stranger to industry. 勤劳之人不受穷。
Sense comes with age.
He that promises too much means nothing.
Any fool can defend his or her mistakes—and most fools do.
—Dale Carnegie
He that once deceives is ever suspected.

Life
Home is where the heart is.
Life is a span.
If you are not inside a house, you don not know about its leaking.
You never know till you have tried.
What is done cannot be undone.
It is never too late to mend.
Keep something for a rainy day. 未雨绸缪。
Man proposes, God disposes. 谋事在人,成事在天。
Meet plot with plot. 将计就计。
Merry meet, merry part. 好聚好散。
First impressions are half the battle.
All time is no time when it is past.
Bad luck often brings good luck.
Courtesy costs nothing. 礼多人不怪。
Desire has no rest.
Do not change horses in mid-stream.
Do not pull all your eggs in one basket.
Do not teach fish to swim.
East or west, home is the best.
Fact is stranger than fiction.
Out of sight, out of mind.
One who has seen the ocean thinks nothing of mere rivers.
Friendship
A friend in need is a friend indeed.
It is good to have friends in trouble.
A long road tests a horse's strength and a long task proves a man's heart 路遥知马力,日久见人心
The best of friends must part.
A life without a friend is a life without a sun.
A trouble shared is a trouble halved.
No road is long with good company.
We shall never have friends if we expect to find them without fault.
Friendship is to be strengthened by truth and devotion.
Be slow in choosing a friend, slower in changing. -----Franklin
选择朋友要慢, 换朋友更要慢。
To find friendship, offer friendship.
True friendship lasts forever.
Friendship is like wine---the older the better.
Fire is the test of gold, adversity of friendship.
Life without a friend is death without a witness.
A man is known by the company he keeps.
Two persons cannot long be friends if they cannot forgive each other’s little failings.
Men have to have friends even in hell.
Friends come and go, but enemies accumulate.

Love
Love looks not with eyes but with the mind. - Shakespeare
If this is not love, I don't know what it is.
Love and friendship exclude each other.

Health
An apple a day keeps the doctor away.
He who has health has hope, and he who has hope has everything.
Sound in body, sound in mind.
The best physicians are Dr. Diet, Dr. Quiet, and Dr. Merryman.
节食博士、精心博士、快乐博士,三人都是最好的医生

Habit
Habit is a second nature.

Mistake
Lifeless, faultless. 只有死人才不会犯错误。
He who makes no mistakes makes nothing.

Aspiration
No pain, no gain.
No guts, no glory.
No courage, no success
The path to glory is always rugged.
Where there is a will, there is a way.
Nothing is difficult to the man who will try.
Where there is life, there is hope.
Nothing is impossible to a willing mind.
Early bird gets the worm.
Better late than never.
Great hopes make great man.
Art is long, but life is short.
Stick to it, and you‘ll succeed.
God helps those who help themselves.
Diligence is the mother of success.
No man is born wise or learned.
Living without an aim is like sailing without a compass.
Time and tide waits for no man. 岁月不等人。
If you want knowledge, you must toil for it.
Nothing venture, nothing have. 不入虎穴,焉得虎子。
Nothing for nothing. 不费力气,一无所得。
Of nothing comes nothing. 无中不能生有
Nothing seek, nothing find.
A little of every thing is nothing in the main. 每事浅尝辄止,事事都告无成。

Behavior
Look before you leap. First think, then act.
All roads lead to Rome.
Early to bed and early to rise makes a man healthy, wealthy, and wise.
Haste makes waste.
More haste, less speed.
What may be done at any time will be done at no time.
Action speak louder than words.
No man is wise at all times.
Take care of the pence, and the pounds will take care of themselves. 积少自然成多。
No man is wise at all times.
Never put off till tomorrow what you can do today.
Industry is fortune‘s right hand, and frugality her left.
Genius is one percent inspiration and 99 percent perspiration.
An ounce of prevention is worth a pound of cure.

Virtue
Virtue never grows old.
Never hit a man when he is down.
Never judge by appearances
Courage and resolution are the spirit and soul of virtue.

Spirit
United we stand, divided we fall.
Joys shared with others are more enjoyed.

Money
Money is a good servant but a bad master.

Analysis
There is no smoke without fire.

Trick
It‘s hard sailing when there is no wind.
You can‘t make something out of nothing.
A bad beginning makes a bad ending.

Others
Wine in, truth out.
The heart is seen in wine.
Good wine needs no bush.
The older the wiser.
You cannot burn the candle at both ends
You cannot have your cake and eat it.
No fire without smoke.
In peace prepare for war.
All rivers run into the sea.
Just has long arms.
An apple a day keeps the doctor away.
Business is business.
Do not have too many irons in the fire. 贪多嚼不烂。
One swallow does not make a summer. 一燕不成夏。(一花独放不是春。)
You are only young once.
Walls have ears.
A bird in the hand is worth two imaginary ones in the bush.
Measure twice, cut once.
The best defense is a good offense.
Too much a good thing is a bad thing.
Light come, light go.
Time is money.
Kill two birds with one stone.
It never rains but it pours. 祸不单行。
Easier said than done.
He who laughs last laughs best.
Many hands make light work. 人多好办事。
Once bitten, twice shy.
Seeing is believing. 百闻不如一见。
Quality matters more than quantity.
The on-looker sees most of the game. 旁观者清
A great ship asks deep waters. 蛟龙要在海中游.
Nothing is as good as it seems beforehand.

Resources
http://www.aphorism4all.com/
http://zhidao.baidu.com/question/104506681
http://zhidao.baidu.com/question/141497187.html?fr=qrl&cid=197&index=4&fr2=query
http://zhidao.baidu.com/question/138856296.html?fr=qrl&cid=197&index=5&fr2=query

Labels

adsense (5) Algorithm (69) Algorithm Series (35) Android (7) ANT (6) bat (8) Big Data (7) Blogger (14) Bugs (6) Cache (5) Chrome (19) Code Example (29) Code Quality (7) Coding Skills (5) Database (7) Debug (16) Design (5) Dev Tips (63) Eclipse (32) Git (5) Google (33) Guava (7) How to (9) Http Client (8) IDE (7) Interview (88) J2EE (13) J2SE (49) Java (186) JavaScript (27) JSON (7) Learning code (9) Lesson Learned (6) Linux (26) Lucene-Solr (112) Mac (10) Maven (8) Network (9) Nutch2 (18) Performance (9) PowerShell (11) Problem Solving (11) Programmer Skills (6) regex (5) Scala (6) Security (9) Soft Skills (38) Spring (22) System Design (11) Testing (7) Text Mining (14) Tips (17) Tools (24) Troubleshooting (29) UIMA (9) Web Development (19) Windows (21) xml (5)