Java HeadlessException error

Hi there,

According to the officiaj java documenation:
[public class HeadlessException extends UnsupportedOperationException]
Thrown when code that is dependent on a keyboard, display, or mouse is called in an environment that does not support a keyboard, display, or mouse.

Error has been noticed on Ubuntu system when running some app from command line.

Quick fix:
1. sudo apt-get install default-jre
2. sudo apt-get install default-jre-headless

Works fine after that but one downside:
From now on the system is using default OpenJDK java version!

Don't you worry, follow the instruction in the post about updating alternatives for Java in Linux based system:
update-alternatives system configuration for JAVA


Cheers!

Java not found or wrong java version - update-alternatives on Linux environment


Hola!

OK so let's rock... here are the possible problems:
0. No java / javac found.
1. Somehow you have two or more java (JRE or/and JDK) installed on the system.
2. Setting JAVA_HOME to your preferred version does not help as some stuff still use system default version
3. Cannot find javac or java even if JAVA_HOME set.


Strange but can happen if more than one version installed.

Time for some fixes:
Let say your preferred JAVA_HOME is pointing to /home/user/jdk

For setting JAVA_HOME and PATH please refer to the post:
Setting JAVA_HOME environment variable

System alternatives and updates

1. Install some java alternatives:
sudo update-alternatives --install /usr/bin/java java /home/user/jdk/bin/java 1
sudo update-alternatives --install /usr/bin/javac javac /home/user/jdk/bin/javac 1
sudo update-alternatives --install /usr/bin/javac javaws /home/user/jdk/bin/javaws 1

2. Set / notify the system:
sudo update-alternatives --set java /home/user/jdk/bin/java
sudo update-alternatives --set javac /home/user/jdk/bin/javac
sudo update-alternatives --set javaws /home/user/jdk/bin/javaws

3. Set the preferred one if have more alternatives
sudo update-alternatives --config java
sudo update-alternatives --config javac
sudo update-alternatives --config javaws


This is it! You should be up an running with your old new great JAVA world :)


Java - how to parse and format date

Hello,

This is about another common scenario when it comes to parse a date from a String or other way - format a text to a date.

Java has some build-in classes that can help in java.text package which are:
  • SimpleDateFormat
  • DateFormat
Parsing date from text:
String dateString = "22/10/2013";
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date date = sdf.parse(dateString);

Format text to date:
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
String dateString = sdf.format(date);

Constructor take one argument for actual date format type which can also include time. For example: dd/MM/yyyy, dd-MM-yyyy, yyyy-MM-dd HH:mm

For full documentation visit official java docs page.

Using the JDK versions could be enough for single-threaded environments. However it's not always the best way to parse or format dates. For example it's not thread safe and also it's not always the fastest way.

Luckily there are very good alternatives:
  • FastDateFormat from Apache Commons - thread-safe and fast but only formatting is supported (sorry no parsing from a String)
  • DateTimeFormat from Joda - thread safe and immutable support both parsing and formatting
API for both are pretty simple and intuitive but for more specific details see related documentation.

I would recommend using Joda instead of JDK version or if you need only formatting the best would be FastDateFormat.

Cheers!


Object serialization and deserialization in Java

Hola!

Java provides an API for nice and simple mechanism of serializing and deserializing objects.

In order to serialize an object it has to implement Serializable interface, e.g.

public class Person implements Serializable {
     
    private static final long serialVersionUID = 1L; //  kind of version that must be the same if you want to deseriazlie object later

...
}

Also note the serialVersionUID has been defined. This is important to match that this is the same object type when it will come to de-serialization. In simple words it used to verify if the objects are compatible.

That's all with the pre-requirements So next you want to serialize Person object. Here is kind of generic method which can do the job:

public static final void serialize(Object object, String filename) {
    try {
        FileOutputStream f_out = new FileOutputStream(new File(filename));
        ObjectOutputStream obj_out = new ObjectOutputStream(f_out);
        obj_out.writeObject(object);
        obj_out.close();
    } catch (Exception e) {
        // log error with serialization
    }

}

Basically you can call it for any serializable object, e.g.
serialize(person, "person.dat"); // serialize single person object
seriazlie(persons, "persons.dat"); // serialize collection of persons

In order to deserialize object from file you can use following bit of code:
public static final Object deserialize(String filename) {
    try {
        FileInputStream f_in = new FileInputStream(new File(filename));
        ObjectInputStream obj_in = new ObjectInputStream(f_in);
        Object object = obj_in.readObject();
        obj_in.close();
        return object;
    } catch (Exception e) {
         
    }
    return null;
}



For example:
Person person = deserialize("person.dat");


That should do the job.



How to access Windows registry from Java?

Hi,

Many desktop applications may require access to the Windows registry in order to store or retrieve some data. For example it can be an application in trial version that needs to store installation date and time or expired date.

The Java Development Kit (JDK) contains required code to do it. It's available in WindowsPreferences class from java.util.prefs package. However the code is declared as private which makes it invisible.

The "magic" trick is to use reflecation API to access private methods. I will not include code directly here because it would pretty long copy-paste and I am too lazy for that.

Instead please refer to Real's HowTo at the following link:
Real's HowTo - accessing windows registry


That's it! Have check it myself and it works like a charm :)

Cheers!

Java: quick way to read or write to file

Hi there,

Reading and writing to files in Java is very common use case. Sometimes you may not remember how to do it quickly and often need to search for it on google.

So here it is...

For file writing here comes FileWriter Java class. You can use constructor which takes either File or String as an argument. For example let say you want to create/write to a file named test.txt:

FileWriter writer = new FileWriter("test.txt"); // creates or overrides existing file
// or FileWriter writer = new FileWriter( new File("test.txt") );

writer.append("blah blah blah"); // append some text to the file
writer.append("\n"); // new line

// and at the end
writer.flush(); // flush the stream
writer.close();


Simple as that - file has been saved to your current working directory.

Now it's FileReader who reads data from files. For example:
FileReader fileReader = new FileReader(new File("test.txt"));

// now you may want to read line by line so here comes BufferedReader

BufferedReader br = new BufferedReader(fileReader);

String line = null;
// if no more lines the readLine() returns null
while ((line = br.readLine()) != null) {
     // reading lines until the end of the file

}

That's it. Simple stuff but worth of having it here to find quickly.

Cheers :)

Java: how to get website source code as a String

Hi all,

Getting a website source code can be useful in many programs esepcially when it come to getting and/or parsing some third party data. This can be achive very easy in Java. Few steps to note:
1. Open URL connection based on www address.
2. Using reader to read the input.
3. StringBuilder can be used to store the data.
4. Close the stream.

Above in java can look like the following code:
public static String getPageSource(String urlstr) {
  StringBuilder sb = new StringBuilder();
  try {
    URL url = new URL(urlstr);
    URLConnection yc = url.openConnection();
    BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
    String inputLine;
    while ((inputLine = in.readLine()) != null) {
      sb.append(inputLine);
    }
    in.close();

    return sb.toString();
  } catch (Exception e) {
    // log / throw exception depending what you want
  }


  return null;
}


Cheers :)

JAVA: how to open URL in a browser programatically?

Hi there,

It's been a while since last post but here we go again :)

OK so sometimes you may want to open internet website from within your java application. It may sound complicated but in the end it's very simple.

If program is running on Windows OS you can do it by using default system program (browser) associated with the given file type, try using following code:

String url = "http://www.google.com/"; // example www
Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);


For other system you may want to find which browser are present and ready for action:

String[] browsers = { "firefox", "opera", "mozilla", "netscape" }; // common browser names
String browser = null;
for (int count = 0; count < browsers.length && browser == null; count++)
  if (Runtime.getRuntime().exec(new String[] { "which", browsers[count] }).waitFor() == 0)
    browser = browsers[count]; // have found a browser

Runtime.getRuntime().exec(new String[] { browser, url }) // open using a browser


This is it :)



Ubuntu: capture audio and record to MP3

Hi,

Many times if you listen to music via the streaming service or radio you may want to record it so you can listen to it later in offline mode.

Audio Recorder is a great tool which can record internal audio stream into many popular music formats, e.g. mp3, flac, ogg and more.

To install on Ubuntu:


sudo apt-add-repository ppa:osmoma/audio-recorder

sudo apt-get update && sudo apt-get install audio-recorder


It's very simple to use... just choose audio format and hit 'start recording'.

That's it!



Linux, Ubuntu unmet dependencies problem (32-bit - 64-bit)


Hi,

Recently I have come across tricky issue related to the intalling 32bit version of flash debugger on 64 bit version Ubuntu. Following the previous post related to it:
Flash Player debugger for Linux x64 (How To)

Everything went well up to installation of nspluginwrapper.

     sudo apt-get install nspluginwrapper

End up with the following error:
"""
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 package1 : Depends: package2 (>= 1.8) but 1.7.5-1ubuntu1 is to be installed
E: Broken packages

"""


Before going further, you can try following commands:
sudo apt-get clean;
sudo apt-get autoclean
sudo apt-get -f install
sudo dpkg --configure -a
sudo apt-get -f install
sudo apt-get -u dist-upgrade
sudo apt-get -o Debug::pkgProblemResolver=yes dist-upgrade


If no luck with the above please continue reading below...

First step to resolve is to try compile and build sources manually.
1. download nspluginwrapper
2. ./configure

Result: more errors with missing dependencies.

After few hours of investigation here are the workarounds:
Step 1: Try to install unmet deps automatically
1. sudo apt-get install auto-apt
2. sudo auto-apt update
3. sudo auto-apt updatedb && sudo auto-apt update-local
4. sudo auto-apt run ./configure

Possible errors: some dependencies still cannot be found

Step 2: Try find missing deps manually end install it.
Possible errors: you found it but it cannot be installed because of
impossible situation with unmet dependencies ;)


Step 3: Install ia32-libs
sudo apt-get install ia32-libs
Possible errors: still impossible situation :D

Step 4: Do some hacking:
1. sudo touch /etc/apt/preferences
2. sudo gedit /etc/apt/preferences:
Package: *      
Pin: release a=precise*
Pin-Priority: 2012

3. sudo apt-get dist-upgrade
5. sudo apt-get install ia32-libs


Possible errors: missing multiarch or anything

Step 5: Enable multiarch and try again:
1. echo foreign-architecture i386 | sudo tee /etc/dpkg/dpkg.cfg.d/multiarch
2. sudo apt-get install ia32-libs
// finally OK!
3. sudo apt-get check
4. sudo rm /etc/apt/preferences // can now delete it


Problem was almost fixed for me:
sudo auto-apt run ./configure
Went further but still some unmets and I gave up,

BUT after all above have tried below again:
sudo apt-get install nspluginwrapper

SUCCESS!

I guess above workarounds can be used to install ANY 32 bit package on 64 bit version of Ubuntu or other Linux OS.

Hope that helps.
Cheers!

Eclipse IDE and IntelliJ IDEA shortcuts and tips

Useful and best practice IDE settings include:
  • show line numbers
  • show whitespace characters
  • line delimiter type UNIX
  • encoding UTF8
  • using spaces instead of TABS
  • limit startup plugins / extensions

Eclipse startup and performance settings
1. eclipse.ini - specify custom java location:
-vm
/home/mnoor/jdk1.6.0_45/bin

2. eclipse.ini - performance tweaks:
-XX:MaxPermSize=512m
-Xms128m
-Xmx1024m

IntelliJ startup and performance settings
1. idea.vmoptions - memory settings:

-Xms128m
-Xmx512m
-XX:MaxPermSize=250m
-XX:ReservedCodeCacheSize=64m

2. idea.sh - additional VM args, JAVA location, etc.


Some Common and useful shortcuts:
1. Open class/type:IntelliJ - CTRL+N
Eclipse - CTRL+SHIFT+T

2. Open resource / any file:
IntelliJ - CTRL+SHIFT+N
Eclipse - CTRL+SHIFT+R

3. See documentation:
IntelliJ - CTRL+Q
Eclipse - F2

4. See declaration:
IntelliJ - ALT+Q
Eclipse - F2

5. Navigate to declaration:
IntelliJ - CTRL+B
Eclipse - F3

6. Find usages / references:
IntelliJ - ALT+F7
Eclipse - SHIFT+CTRL+G

7. Refactor / rename:
IntelliJ - SHIFT+F6
Eclipse - SHIFT+ALT+R

8. Implement abstract methods from abstract base class or interface.
IntelliJ - CTRL+I
Eclipse - CTRL+1 -> add unimplemented methods

9. Code completion:
IntelliJ - CTRL+SHIFT+SPACE
Eclipse - CTRL+SPACE

10. Search in files
IntelliJ - CTRL+SHIFT+F
Eclipse - CTRL+H

11. Back to previously edited place:
IntelliJ - CTRL+SHIFT+BACKSPACE
Eclipse - ALT+LEFT, ALT+RIGHT

12. Comments
IntelliJ - CTRL+/, CTRL+SHIFT+/
Eclipse - CTRL+SHIFT+C

13. Navigate to the implementation
IntelliJ - CTRL+ALT+B
Eclipse - CTRL+T

That's it, cheers!


Linux: setting environment variable, e.g. JAVA_HOME

In many situation you need to have some variable set on the system in order to use some applications.
The common are vars like JAVA_HOME or MAVEN_HOME pointing to the corresponding directories.

The main thing you will need to do is to set it as bellow. Additionally you can add it to the current PATH (or rather add its executables) and export updated PATH:

# java home directoy
JAVA_HOME=/path/to/java/home/dir
# additional adding bin executables to the current path
PATH=$PATH:$JAVA_HOME/bin
# exporting the updated path var
export PATH

Now depeding on where will you put above content config will be slightly different:
Option 1. Setting environment vars for user only - this will be set only for the currently logged in user:
gedit ~/.bashrc

Option 2. Setting globally for all logged in users
sudo gedit /etc/bash.bashrc

Option 3. Global at system level regardless if user is logged in or not. This one is probably the best way.
sudo gedit /etc/environment


So I were using Option 1 way until I've come into error running application from the desktop that requires JAVA. If you run it from console it can see the JAVA_HOME, however if run from desktop it does not see it.

Going with the Option 3 and setting variable globally solved that problem!

Cheers!

HTML auto redirect website to a different URL

There are several ways of achieving above...

One of it is using just HTML and editing <HEAD> block in the main index.html (or index.htm) file:

Scenario:
  1. You have website on the server, e.g. www.mywebsite.com
  2. You want to redirect it to any other url location either remote or local to your server website, e.g.
www.mywebesite/folder/page2.html

Try putting the following inside <HEAD> of you index.html file:
<meta http-equiv="refresh" content="0;URL=www.mywebesite/folder/page2.html" />

where value zero (0) means the time before the redirection will take process - in that case immediately.

This is it, cheers!

Dual monitors configuration for Linux

Having problems with setting up multiple screens?

Recently I have come into issue with setting second monitor connected to the laptop.
If standard nVidia setting are not available for some reasons you can use XRandR tool.

The basic use of the command is following:

For HDMI connected device on the left of your screen:

xrandr --output HDMI1 --auto --left-of LVDS1


For VGA output:

xrandr --output VGA1 --auto --left-of LVDS1


You can also provide parameter to set up the resolution of the device, for example:

xrandr --output HDMI1 --mode 1600x1050 --left-of LVDS1


Cheers!

Ubuntu missing window title bars and footers

Hi,

Few times I have noticed after log in to the Ubuntu or XUbuntu system there are no title bars and footers on application windows.

One of the reason can be that xfwm window manager has crashed. You can try restoring it by running the following command:

xfwm4 --display=:0.0 --replace

This did the trick for me.

If it doesn't help try to investigate by view logs of xsession errors available in home directory file .xsession-errors

less ~/.xsession-errors


Hope that helps!

Debug mode timeout and disconnects.

Hi there,

This will be very quick post about tweaking debugging problems in cases of:
  • timeout
  • disconnection
If you debug from you environment standalone desktop application you can just set it in the options of debug configurations. Look for the timeout settings.

If you debug web application running in web browser there is something else you can set to improve it.
For example in Firefox there is special settings site that allows you to configure advanced properties:
  1. In Firefox browser URL field type in: about:config
  2. You should get a warning about risk of changing advanced settings so please continue at your own risk.
  3. Then there are plenty of properties to choose from but we are interesting in increasing timeouts related stuff. You can update following keys:
  • devtools.debugger.remote-timeout
  • dom.ipc.plugins.timeoutSecs
  • dom.ipc.plugins.timeout.secs
  • dom.ipc.plugins.processLaunchTimeoutSecs
  • dom.ipc.plugins.parentTimeoutSecs
  • dom.min_background_timeout_value
  • dom.min_timeout_value

Note for some properties value comes in seconds for others in milliseconds. You will need to experiment a bit with it. Usually setting timeout to -1 means unlimited.


Cheers!

Fix for java.awt.AWTError: Assistive Technology not found

Hey,

I have found this "weird" error on one of the Windows 7 64-bit machine. After hours of "googling" it comes that the common cause is missing or invalid Java Access Bridge library.

It needs to be manually installed:

1. Download from oracle:
http://www.oracle.com/technetwork/java/javase/downloads/jab-2-0-2-download-354311.html

2. Follow the instructions on official docs:
http://docs.oracle.com/javase/accessbridge/2.0.2/setup.htm

3. Set the system environment variable to point to the related JAB files:

For example:

ORACLE_OEM_CLASSPATH=C:\Program Files\Java\jdk\jre\lib\jaccess.jar;C:\Program Files\Java\jdk\jre\lib\access-bridge.jar

Hope thats helpful :)

Flash Player debugger for Linux x64

Hi,

In order to use flash in the debug mode you will need the flash player debugger version. Unfortunately there is no support for Linux 64 bit version :/

There is a workaround which kind of works :)

Follow the steps below:

  • Download the 32 bit version of flash debugger:
 http://fpdownload.macromedia.com/pub/flashplayer/updaters/11/flashplayer_11_plugin_debug.i386.tar.gz

  • Unzip it and replace current plugin (if exists):
sudo cp libflashplayer.so /usr/lib/mozilla/plugins/libflashplayer.so (Firefox)

  • Install nspluginwrapper
It may be easy as 'sudo apt get install nspluginwrapper' or much more tricky - you may need to resolve all required dependencies).

  • Use the nspluginwrapper to "wrap" the 32 libriary:
sudo nspluginwrapper -i/usr/lib/mozilla/plugins/libflashplayer.so

  • Check your flash player version:
  http://flashbuilder.eu/flash-player-version.html



If all OK you should see 'debugger' version.


Have fun :)



QuakeNet: How to request Q bot?

Hello,

If you like being on IRC then you may also want to have your own channel. If so it is worth to have always someone there. This "person" can actually be a bot named Q. This post will cover requesting Q on irc.quakenet.org server.

First step is to register yourself on QuakeNet:
/msg Q HELLO youremail@address youremail@address

You should get your password on the given e-mail address. Then you can authorize:
/msg Q@CServe.quakenet.org AUTH username password

It is also good to change your generated password:
/msg Q@CServe.quakenet.org NEWPASS oldpassword newpassword newpassword


Next you will just need to join an empty channel so you will have OP status there. Then please invite at least three other users to your channel so including yourself channel should have at least 4 people. You should not give them operator status at that point.

You can start to request Q every 15-20 minutes:
/msg R REQUESTBOT #channel
or
/msg Q REQUESTBOT #channel

Make sure users are still there but at least noone needs to talk :)

It may take from up to few hours to finally get that BOT.

Once everything is OK, Q will finally send you "congratulation" message and he should join your channel.

When you got it make sure your channel is "alive" which means do not leave it empty for too long time. Otherwise Q will get bored and he will just leave the channel :)

Enjoy!




XUbuntu: missing title bars and footers

Hi there,

Recently I have noticed problem with missing title bars and footers after login to the XFCE desktop.

To investigate the real cause you can check for you session errors logged in the file .xsession-errors in your home directory.

For workaround there are some simple steps you can do:

1. ALT+F2 and run:  

xfwm4 --display=:0.0 --replace

This should revert your bars but may not resolve the problem permanently but you can always try to add it as default startup command.


2. remove cached sessions folder:

rm -fr ~/.cache/sessions


That's it for now.

Cheers!