rss

The Java Native Interface (JNI)

Monday, August 31, 2009

The Java Native Interface (JNI) enables the integration of code written in the Java programming language with code written in other languages such as C, C++ and assembly. Therefore, you can natively run heavy tasks in pursuance of a better performance.

Is it platform-independent?

Your application can be platform-independent if you store the compiled JNI libraries (for all possible architectures) in the jar alongside the class files. However, since System.load() can't cope with loading libraries from within a jar, you'll therefore need a custom loader which extracts the library to a temporary file at runtime.

So, what do I need ?

  • Microsoft Windows SDK (recomended if you are using Windows)
  • Microsoft Visual Studio (same here)
  • Java SDK

And, which are the magic steps?

1. Declare your native methods in a normal Java class.
public class JavaJNI {

static {
System.loadLibrary("NativeLib");
}

public static native String write(String s);

public static void main(String[] argv) {
System.out.print(JavaJNI.write("Hello"));
}

}


2. Compile the Java file normally.
javac JavaJNI.java

3. Generate the .h file.
javah -jni JavaJNI

4. Write the native code using the file generated above.

In this case you will find the following method inside:
JNIEXPORT jstring JNICALL 
Java_JavaJNI_write(JNIEnv *, jclass, jstring);
Now you have the green light to implement it.
#include "JavaJNI.h"

JNIEXPORT jstring JNICALL Java_JavaJNI_write(JNIEnv *env, 
jobject thisobject, jstring js){
const char *temp;
jstring result = NULL;
temp = (*env)->GetStringUTFChars(env, js, 0);

/** Your normal C code */
printf("Input: %s", temp);

result = (*env)->NewStringUTF(env, 
(const char*) "\nResult: http://www.think-techie.com");
(*env)->ReleaseStringUTFChars(env, js, temp);
return result;
}

If you are trying to use C++ use the following methods instead:
env->GetStringUTFChars(js, 0);
env->NewStringUTF((const char*) temp);
env->ReleaseStringUTFChars(js, temp);

5. Compile the code

Windows with MS C++ Compiler
cl -c /Ic:\Programs\JavaSDK\include /I"C:\Programs\Microsoft Visual Studio 9.0\VC\include" /Ic:\Programs\JavaSDK\include\win32 NativeLib.c

link -LIBPATH:"C:\Programs\Microsoft SDKs\Windows\v6.0\VC\LIB" -LIBPATH:"C:\Programs\Microsoft SDKs\Windows\v6.0\Lib" NativeLib.obj /dll
Or this one:
cl -I C:\Programs\JavaSDK\include -I C:\Programs\JavaSDK\include\win32 -LD NativeLib.c -FeNativeLib.dll
Solaris with Sun Compiler
cc -G -I JavaSDK/include -I JavaSDK/include/solaris -o libNativeLib.so NativeLib.c
Linux with GCC
gcc -fPIC -I JavaSDK/include -I JavaSDK/include/linux -shared -o libNativeLib.so NativeLib.c
If your prefer to use Ant take a look at cc Task.

6. Run the example
java JavaJNI
Application output:
Input: Hello
Result: http://www.think-techie.com
7. Did you got errors ?

There are some common errors such as:
java.lang.UnsatisfiedLinkError: no NativeLib in 
java.library.path
at java.lang.ClassLoader.loadLibrary(Unknown Source)
at java.lang.Runtime.loadLibrary0(Unknown Source)
at java.lang.System.loadLibrary(Unknown Source)
at ...
The manner through which java searches for the needed files are different in each scenario:
  1. Java searches for *.class files through the "-cp"/"-classpath" command line switch. If neither are specified on the command line, CLASSPATH is searched.
  2. Java searches for JNI files through the "-Djava.library.path" command line switch. If "-Djava.library.path" is not specified, LD_LIBRARY_PATH is searched, but the /etc/ld.so.conf mechanism is not used.
  3. The way a JNI glue library searches for the underlying C++ *.so libraries is not controlled by the Java process at all. The normal operating system rules are applied (LD_LIBRARY_PATH, /etc/ld.so.conf, etc.).
Consequently, one way of fixing this is to include the current location of your newly compiled shared library. If you are using linux you can do this:
LD_LIBRARY_PATH=`pwd`
export LD_LIBRARY_PATH
Another way is to define the location when running the program:
java -Djava.library.path=. JavaJNI
8. Did you got more errors ?
java.lang.UnsatisfiedLinkError: <library location>: 
<library location>: only ET_DYN and ET_EXEC can be loaded
at java.lang.ClassLoader$NativeLibrary.load(Native Method)
at java.lang.ClassLoader.loadLibrary0(ClassLoader.java:1778)
at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1674)
at java.lang.Runtime.load0(Runtime.java:770)
at java.lang.System.load(System.java:1005)
...
If you are using g++, try to include the option "-shared" when compiling the cpp file.
g++ -shared NativeLib.cpp -o NativeLib.so -I JavaSDK/include
-I JavaSDK/include/linux
Do not include the "-c" option. It will skip the linking stage.

References

[1] JNI – Java Native Interface. White Magician. wmagician.wordpress.com

Firefox extensions that every user must have

Thursday, August 27, 2009

Firefox's extensibility is one of its great advantages. There are so many plug-ins that it's hard to tell which add-ons are worth of install. So don't waste more time - here's my 15 essential Firefox extensions.


1. Copy plain text

Ever copied something from the web into a document only to have it ruined because the formatting is also copied? Fix this by getting Copy as Plain Text. Once it's installed, highlight some text, right-click on it and choose 'Copy as plain text' to do just that.


2. Encrypt and decrypt or data

Send and receive data over the internet can be very unsafe. FireGPG is a Firefox extension under MPL which brings an interface to encrypt, decrypt, sign or verify the signature of text in any web page using GnuPG.


3. Get TinyURLs

This add-on lets you create shortened URLs without having to go to a separate web page. Install TinyURL Creator. Now browse to the site you want to share, right-click anywhere and choose 'Create TinyURL for this page'. The result is automatically copied to the clipboard.


4. Use hyperwords

For the Swiss army knife of text add-ons, get Hyperwords. Once installed, it provides you with a dizzying array of options for highlighted text through its right-click menu. Choose 'Search' and then select from Google, the current site or a range of news sites and social-networking services for immediate search results. You can also look up the selection in a range of reference sites, including Wikipedia and the Urban Dictionary. There are also options to translate the text or share it with others.


5. Resurrect pages

When a website that you need goes down, you can hunt through each of the various caching services manually to find a snapshot of it, but this can be time-consuming. The Resurrect Pages extension does the hard work for you, replacing the standard 'page cannot be displayed' message with one that includes links to web cache services. Use these to quickly see if a service has a cached version of the page you want.


6. Avoid typos

It's easy to make a mistake when typing in a web address. URL Fixer anticipates common mistakes and sets them right so that you're not left with a broken link. It won't catch every slip, but it will help reduce your irritation levels a little.


7. Block ads

Adverts can be a big irritation. The AdBlock Plus extension enables you to block adverts that you don't want to see while allowing you to permit them for other sites. You can also set it up to block content from a number of different subscription services, and opt to turn off its filter for sites that you approve of.


8. Block script

Some sites execute code without your explicit permission. In a few cases, like that of the Twitter worm Mikeyy, this can be abused. No Script blocks all third-party scripts – including JavaScript, Java and Flash objects – until you give your permission for them to run. You can also identify sites as trusted so that you're not constantly vetting scripts on familiar pages.


9. Pretend to be IE

Some webmasters are wise to the fact that Firefox users can block ads and scripts with plug-ins, so they prevent access to their sites for people using Firefox. User Agent Switcher disguises your browser as Internet Explorer to get round this restriction. The utility adds a sub-menu to the Tools menu that enables you to select the browser and OS that you want to display to sites.


10. Run IE in Firefox

Some sites need Internet Explorer to render properly. Rather than close Firefox, try IE Tab. Right-click and choose 'Open Page in IE tab' to open a new tab that emulates Internet Explorer.


11. Add Google Bookmarks

Use the GMarks extension to integrate your Google Bookmarks with Firefox. Log into your Google account to replace the existing Bookmarks menu and Bookmarks Toolbar folder with GMarks. This is a handy way to keep all of your bookmarks in one place.


12. Add Delicious Bookmarks

Delicious Bookmarks is the official Firefox add-on for Delicious, the world's leading social bookmarking service (formerly del.icio.us). It integrates your bookmarks and tags with Firefox and keeps them in sync for easy, convenient access.


13. Add bookmarks from IE

Another bookmark synchronising add-on is Xmarks that has evolved from an earlier extension known as Foxmarks. You can use it to synchronise your bookmarks with Internet Explorer and Safari, meaning that you'll have quick access to your favourite pages no matter which browser you're using. It also provides site suggestions and community feedback.


14. Check site security

McAfee's Site Advisor add-on provides a service that's focused on making sure that you're safe online. When you run a Google search, each result is either rated as 'safe' or has any potential problems flagged. Hover over the Site Advisor icon next to the result to find out more.


15. Hide your tabs

You want to leave some page running but you have too many pages opened ? Use the add-on to hide/unhide individual tabs.

Top Google Search Tricks

Friday, August 7, 2009

When it comes to the Google search box, you already know some tricks: finding exact phrases matches using quotes or searching a single site using site:example.com gmail. But there are many more oblique, clever, and lesser-known search recipes and operators that work from that unassuming little input box. Dozens of Google search guides detail the tips you already know, but today i will present my favorite obscure Google web search tricks.

1. Explicit Phrase:

Lets say you are looking for content about internet marketing. Instead of just typing internet marketing into the Google search box, you will likely be better off searching explicitly for the phrase. To do this, simply enclose the search phrase within double quotes.

Example: "internet marketing"


2. Exclude Words:

Lets say you want to search for content about internet marketing, but you want to exclude any results that contain the term advertising. To do this, simply use the "-" sign in front of the word you want to exclude.

Example Search: internet marketing -advertising


3. Site Specific Search:

Often, you want to search a specific website for content that matches a certain phrase. Even if the site doesn’t support a built-in search feature, you can use Google to search the site for your term. Simply use the "site:somesite.com" modifier.

Example: "internet marketing" site:wikipedia.org


4. Similar Words and Synonyms:

Let’s say you are want to include a word in your search, but want to include results that contain similar words or synonyms. To do this, use the "~" in front of the word.

Example: castle ~glossary


5. Specific Document Types:

If you’re looking to find results that are of a specific type, you can use the modifier "filetype:". For example, you might want to find only PowerPoint presentations related to internet marketing.

Example: "internet marketing" filetype:ppt


6. This OR That:

By default, when you do a search, Google will include all the terms specified in the search. If you are looking for any one of one or more terms to match, then you can use the OR operator. (Note: The OR has to be capitalized).

Example: internet marketing OR advertising


7. Phone Listing:

Let’s say someone calls you on your mobile number and you don’t know how it is. If all you have is a phone number, you can look it up on Google using the phonebook feature.

Example: phonebook:617-555-1212
Note: You’ll have to use a real number to get any results


8. Numeric Ranges:

This is a rarely used, but highly useful tip. Let’s say you want to find results that contain any of a range of numbers. You can do this by using the X..Y modifier (in case this is hard to read, what’s between the X and Y are two periods. This type of search is useful for years (as shown below), prices or anywhere where you want to provide a series of numbers.

Example: president 1940..1950


9. Calculator:

The next time you need to do a quick calculation, instead of bringing up the Calculator applet, you can just type your expression in to Google.

Example: 48512 * 1.02


10. Word Definitions:

If you need to quickly look up the definition of a word or phrase, simply use the "define:" command.

Example: define:plethora


11. Get the local time anywhere

What time is it in Bangkok right now? Ask Google. Enter simply time and the place to get the local time in big cities around the world.

Example: time hong kong


12. Track flight status

Enter the airline and flight number into the Google search box. Notice that Google now tells you if your flight is on time or delayed, as well as the estimated departure and arrival times.

Example: BA 0011 (It must exist)


13. Convert currency, metrics, bytes, and more

Google's powerful built-in converter calculator can help you out whether you're cooking dinner, traveling abroad, or building a PC. Find out how many teaspoons are in a quarter cup (quarter cup in teaspoons) or how many seconds there are in a year (seconds in a year) or how many euros there are to five dollars (5 USD in Euro). For the geekier set, bits in kilobytes (155473 bytes in kilobytes) and numbers in hex or binary (19 in binary) are also pretty useful.


14. Compare and find similar items

Simply search for, in quotes: "better than _keyword_"

The results will almost always lead you to discovering alternatives to whatever it is you're searching for. Using the same concept, you can use this trick to discover new music or movies. For example, " reminds me of _someband_" or "sounds like _someband_" will pull up artists people have thought sounded similar to the one you typed in. This is also a great way to find good, no-name musicians you'd probably never know of otherwise.

Examples:
Results 1 - 100 of about 550 English pages for " better than WinAmp".
Results 1 - 57 of 57 English pages for " better than mIRC".
Results 1 - 88 of 88 English pages for " reminds me of Metallica".
Results 1 - 36 of 36 English pages for " similar to Garden State".
Results 1 - 66 of 66 English pages for " sounds like The Shins".

Just get creative and you'll, without a doubt, find cool new stuff you probably never knew existed.


15. Use Google as a free proxy

What, your company blocks that hip new web site just because it drops the F bomb occasionally? Use Google's cache to take a peek even when the originating site's being blocked, with cache:example.com.

Example: cache:google.com


16. Remove affiliate links from product searches

When you're sick of seeing duplicate product search results from the likes of eBay, Bizrate, Pricerunner, and Shopping.com, clear 'em out by stacking up the -site:ebay.com -site:bizrate.com -site:shopping.com operator. Alternately, check out Give Me Back My Google, a service that does all that known reseller cleaning up for you when you search for products.

Example: Compare this GMBMG search for a Cruzer 1GB flash drive to the regular Google results.


17. Find related terms and documents

Ok, this one's direct from any straight-up advanced search operator cheat sheet, but it's still one of the lesser-used tricks in the book. Adding a tilde (~) to a search term will return related terms. For example, Googling ~nutrition returns results with the words nutrition, food, and health in them.


18. Find music and comic books

Using a combination of advanced search operators that specify music files available in an Apache directory listing, you can turn Google into your personal Napster. The same type of search recipe can find other types of content as well.

Examples:
-inurl:(htm|html|php) intitle:"index of" +"last modified" +"parent directory" +description +size +(wma|mp3) "Beatles"
-inurl:htm -inurl:html intitle:"index of" "Last modified" spider-man cbr
-inurl:htm -inurl:html intitle:"index of" "Last modified" simpsons cbr


19. ID people, objects, and foreign language words and phrases with Google Image Search

Google Image search results show you instead of tell you about a word. Don't know what beans looks like? Not sure if the person named "Priti" who you're emailing with is a woman or a man? Spanish rusty and you forgot what "corazon" is? Pop your term into Google Image Search (or type image beans into the regular search box) to see what your term's about.


20. Find live webcams with Google

The trick to find and search for open unprotected Internet webcams that broadcast to the web, is by using the following query: intitle:”Live View / – AXIS” | inurl:view/view.shtml^


21. Make Google recognize faces

If you're doing an image search for Paris Hilton and you don't want any of the French city, a special URL parameter in Google's Image search will do the trick. Add &imgtype=face to the end of your image search to just get images of faces, without any inanimate objects. Try it out with a search for rose (which returns many photos of flowers) versus rose with the face parameter.


Sources:

1. Top 10 Obscure Google Search Tricks
2. 12 Quick Tips To Search Google Like An Expert


What's your favorite ninja Google search technique?

Prevent websites from resizing Firefox's browser window

Wednesday, August 5, 2009

Firefox is my browser of choice. This browser is now more secure than ever, rock solid, very polished and popular enough that you had dozens of extensions to customize it to your liking.

Now, one of the most obvious tweaks you can apply to your Firefox installation is removing the annoyance of letting websites resize the window at their will. Despite of the more sophisticated pop-up blocker that comes in most recent versions of the browser, many websites still do away with popping those up and in many cases resizing either your main window or maximizing the pop-up window to get your full attention (just before you hit the X button).

You won’t even need an add-on to do this.

  1. Go to Tools > Options
  2. Click on the Content tab
  3. Next to where it says "Enable Javascript", click on Advanced
  4. Uncheck the option "Move or resize existing windows"
  5. It is also a good idea uncheck the option "Raise or lower windows"

Click on the OK button twice to save the changes, and then you’re done. This will disallow any website to adjust the size of your browser window. It’s a great way to make sure your browsing experience stays yours.


How to reproduce this annoying feature ?

A simple way to do it is using JavaScript:


<script type="text/javascript">

The screen width, height can be obtained from: screen.width and screen.height

var w = screen.width;
var h = screen.height;

To move a browser window to a specific location on the users screen using JS:

window.moveTo(0, h - 100);

To resize the browser window: window.resize(width, height);

window.moveTo(w/2, h/2);

</script>


This code is usually written in the HTML page within the tag <body>. If you want to test if you have this annoying feature enabled click here.