Usman Saleem Java HelloWorld
Powered By
JBoss Web/7.0.13.Final
JavaServer Faces API - 2.0.1.Final
PostgreSQL 8.4.20
Primefaces
Openshift
Uzi's Blog - Main
pp12345678910pp

Gruveo is an excellent anonymous Flash/browser based very simple video\audio chat website). Due to some weird bug in Ubuntu 13.10 which doesn't allow to change camera settings on individual website (such as Gruveo) through Flash settings popup, following workaround can be used through Flash's global settings.

Visit http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager06.html Select monitor with the eye tab (5th from the left), scroll down and select required site, http://www.gruveo.com, and then click radio button "Always Allow" (see following screenshot). Restart the browser and refresh gruveo again. The video chat is now working.

Screenshot:

Recently I switched from Fedora 18 to Ubuntu 13.10 on my personal Acer Aspire V5 laptop (a wrong decision when I bought it - anyways...). There are two annoying issues when using both Fedora and Ubuntu on this laptop

Skype Dark Video Screen issue

Skype works on both Fedora and Ubuntu, however, there is this darn issue of dark video screen. This can be fixed by using guvcview and/or from command line tool uvcdynctrl as discussed by this guy in detail.

To ease up calling uvcdynctrl, you can create a launcher and add it to the dash. Follow this link to create desktop launcher in Ubuntu.

Fn keys Screen Brightness issue

The second issue is that screen brightness doesn't work, neither Fn Brightness (blue Fn - left right keys) nor from System Settings ... Brightness & Lock.

To fix the issue for System Settings, we need to add acpi_backlight=vendor to kernel command line parameter as part of grub config. For Fedora follow similar approach for grub2, following approach works in Ubuntu. Update GRUB_CMDLINE_LINUX in /etc/default/grub then run update-grub and restart.

To make the Fn key work again, try fixing /etc/acpi/asus-keyboard-backlight.sh and update KEYS_DIR to KEYS_DIR=/sys/class/backlight/intel_backlight. This will allow Fn scripts to call the correct scripts instead of default values (which doesn't work anymore after using acpi_backlight=vendor). Restart to test it.

P.S. Ubuntu seems to have become more user friendly than Fedora (shh...don't tell my former colleagues back at Red Hat ;-))

My favorite Java Decompiler tool. JD-GUI. The only free tool to reverse engineer and understand Java 5 and above code. A must have tool under your belt as a Java coder.

Added http://usman.id.au which also points to (via CNAME) this application hosted on OpenShift, similar to my existing domain, http://www.usmans.info.

Java 7 introduced two major changes:
  • Project Coin
  • NIO-2
Major changes introduced by Project Coin are as follows:
  • try-with-resources construct to automatically close resources (such as IO resources etc.)
  • Enhanced switch statement to handle String
  • Enhanced numeric literals (for improved readability)
  • Handling multiple exceptions in single catch block
  • Diamond syntax for generics to avoid excessive code.
  • Fixes for varargs warnings
NIO-2 changes include:
  • Path construct for dealing with files and files like entities.
  • Files utility class (similar to what Arrays does for arrays)
  • Future and call-back based asynchronous IO
Lets see above features with help of some java code.

switch for Strings


public class TestSwitch {

  public static void testSwitch(String day_of_week) {
	switch(day_of_week.toLowerCase()) {
		case "monday": System.out.println("Monday"); break;
		case "tuesday": System.out.println("Tuesday"); break;
		case "wednesday": System.out.println("Wednesday"); break;
		case "thursday": System.out.println("Thursday"); break;
		case "friday": System.out.println("Friday"); break;
		case "saturday": System.out.println("Saturday"); break;
		case "sunday": System.out.println("Sunday"); break;
		default: System.out.println("Unknown day:" + day_of_week);
		
	}
  }

  public static void main(String a[]) {
	testSwitch("monday");
	testSwitch("Thursday");
	testSwitch("somwar");
  }

}

Enhanced Numeric Literals

In java7, binary literals can be specified by using 0b prefix. In previous versions, we would have to use parseInt with base 2 to get such behavior (which means calling a method, no ability to use in switch statement, possiblity of RuntimeException due to misrepresentation of binary literal etc.) Consider:

int x1 = Integer.parseInt("1000101100001111", 2);
can now be replaced with:

int x1 = 0b1000101100001111;
In addition, as you may notice above may be difficult to read, Java7 introduces _ to improve readibility:

int x1 = 0b1000_1011_0000_1111;

Enhanced Exception handling

Java7 introduces enhanced exception handling. It now allows you to specify alternate exceptions in single catch block aka multi-catch and final rethrow. The syntax is:

try {

} catch(Exception1 | Exception2 e) {

}
The 'e' will represent super class of Exception1 and Exception2, which is generally Exception or Throwable. The alternate exception i.e. Exception2 must not be superclass of Exception1. For example, following will produce compile time error:

 public static void testNewException(){
          FileReader fr = null;
          try {
                char[] buf = new char[100];
                fr = new FileReader("somefile.txt");
                fr.read(buf);
          } catch(FileNotFoundException | IOException e) {
              e.printStackTrace();
          }
  }
will result:

 error: Alternatives in a multi-catch statement cannot be related by subclassing
          } catch(final FileNotFoundException | IOException e) {
                                                ^
  Alternative FileNotFoundException is a subclass of alternative IOException
1 error
Following is a more better approach:

public static void testNewException(){
          FileReader fr = null;
          try {
                fr = new FileReader("somefile.prop");
                java.util.Properties prop = new java.util.Properties();
                prop.load(fr);
          } catch(FileNotFoundException fne) {
              System.err.println("File Not found");
          } catch(IOException | IllegalArgumentException e) {
              System.err.println("Error handling properties file:" + e.getMessage());
          }
}
The final rethrow allows you to write a single catch block, yet only throw related exception. For instance, in earlier version, we may write this code to signal that calling code should handle the exception:

 public static void testOldGeneralException() throws Exception{
          FileReader fr = null;
          try {
                fr = new FileReader("somefile.prop");
                java.util.Properties prop = new java.util.Properties();
                prop.load(fr);
          } catch(Exception e) {
              System.err.println("Problem dealing with file, rethrowing...");
              throw e;
          }
  }
This allows to consume all exceptions and then throw general exception. However, the calling side also has to handle the general exception .... a bad idea. In Java7, the above can be rewritten as:

 public static void testNewFinalException() throws 
      FileNotFoundException, IOException, IllegalArgumentException{
          FileReader fr = null;
          try {
                fr = new FileReader("somefile.prop");
                java.util.Properties prop = new java.util.Properties();
                prop.load(fr);
          } catch(final Exception e) {
              System.err.println("Problem dealing with file, rethrowing...");
              throw e;
          }
  }

public static void main(String a[]) {
        try {
                testNewFinalException();
        }catch(FileNotFoundException fne) {
              System.err.println("File Not found");
        }catch(IOException e) {
              System.err.println("Error handling properties file:" + e.getMessage());
        }

}
You don't have to specify "final" in catch block, but it helps in understanding the semantics.

Try-With-Resource (TWR)

Consider the above example of Filehandling, it misses the close operation. Usually in pre-Java7, we would have to write it as:

public static void testNewException(){
          FileReader fr = null;
          try {
                fr = new FileReader("somefile.prop");
                java.util.Properties prop = new java.util.Properties();
                prop.load(fr);
          } catch(FileNotFoundException fne) {
              System.err.println("File Not found");
          } catch(IOException | IllegalArgumentException e) {
              System.err.println("Error handling properties file:" + e.getMessage());
          } finally {
              if(fr != null) {
               try {
                 fr.close();
               }catch(IOException e) {
                 System.err.println("Error closing file, nothing to do");
               }
              }
          }
  }
I have to write similar code for handling JDBC artifacts as well (ResultSet, Statement, Connection etc.) In Java7, the try syntax has been changed, consider this:

public static void testNewTry() throws FileNotFoundException, IOException{
          try(FileReader fr = new FileReader("somefile.prop")) {
                java.util.Properties prop = new java.util.Properties();
                prop.load(fr);
           }
  }
However, note that try-with-resources block might still cause unclosed resources if you are not careful, consider:

public static void testNewTry2() throws 
            FileNotFoundException, IOException{
          try(ObjectInputStream os = new ObjectInputStream(
                                                        new FileInputStream("somefile.bin"))) {
           }
  }
In above example, FileInputStream may open an invalid file, which will cause ObjectInputStream to not be created, however, FileInputStream will not be closed. The correct approach would be:

public static void testNewTryr3() throws 
                              FileNotFoundException, IOException{
          try(FileInputStream fis = new FileInputStream("somefile.bin");
ObjectInputStream os = new ObjectInputStream(fis)) {
             //...
           }
}
The above code will make sure to close both FileInputStream and ObjectInputStream.

Diamond syntax for generics

This one is easy and beautiful. Consider following code:
 Map<Integer, Map<String, String>> map = new HashMap<Integer, Map<String,String>>();
The above is declaring a map, identifiable by an integer id which contains another map containing further lookup values. This could be rewritten as:
 Map<Integer, Map<String, String>> map = new HashMap<>();
Java7 will work out the details on right-hand side. It is backward compatible i.e. you can replace the above syntax for your old code. Stay tuned for NIO2 related changes.

So you decided to use a custom module in JBoss EAP6/AS 7 and your setup is domain mode where your host and domain are on separate machines, and you add a module in your domain controller ... and still getting errors in logs that JBoss is unable to find required module?

Make sure to add the module to your host instance as well since domain mode only pushes deployable contents onto hosts, and module is not a deployable content.

Keep Jbossing....

The JSF implementation in JBoss AS 7/EAP 6 has a small annoyance when it comes to handling of default page in default (root) context and outcome attribute, such as in h:link.

For instance, consider my domain, www.usmans.info. In my blog software, the JSF servlet handles *.xhtml extensions. The default welcome page is set to index.xhtml.

The problem is, if someone hits just the domain, the JSF components which contains 'outcome' attribute does not generate proper URL. For instance, rather then generating http://www.usmans.info/notes.xhtml, it will generate /notes.xhtml only.

To fix this annoyance, I had to set default welcome page as index.jsp, which did a redirect to index.xhtml. However, this workaround caused an unnecessary browser redirect.

To avoid the browser redirect, I introduced a web filter which detects this particular use-case and internally forwards to index.xhtml. This fix the issue and JSF engine renders all targets/outcome correctly. Here is the code:


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;

/**
* This filter is to fix an invonvinence where 
* JSF link tag's 'outcome' is not calculated correctly
* if application is accessed with just the domain name
* i.e http://www.usmans.info .
* 
* We forward the request to index.xhtml if the request URI is just /. 
* This is probably just JBoss/Mojarra issue, but we needed this fix
* to avoid having index.jsp which redirect to index.xhtml
*
* @author Usman Saleem
* @version 1.0
*/
@WebFilter(urlPatterns={"/*"})
public class FixRootURIFilter implements Filter {

    private FilterConfig filterConfig = null;

    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
	if(request instanceof HttpServletRequest) {
		HttpServletRequest httpReq = (HttpServletRequest) request;
		String uri = httpReq.getRequestURI();
		if(uri != null && uri.equals("/")) {
			RequestDispatcher rd = filterConfig.
                                  getServletContext().
                                  getRequestDispatcher("/index.xhtml");
			if(rd != null) {
				rd.forward(request, response);
				return;
			}
		}
	}

	//default handling - do nothing and forward reqeust to filter chain
        chain.doFilter(request, response);

    }
    @Override
    public void destroy() {    }
}


Updated my blog software to provide blog sections. Ideally these are suppose to be "blog categories" while categories are suppose to be "tags", since I already had used "categories", I named then as "Blog Section". For now, there is Experiments section. In future I am planning to add Urdu only sections etc.

New browsers are capable of showing custom embedded fonts which can be specified by using @font-face css tag. This allows web designers to use custom fonts which users don't need to install on their machine.

With custom font (Hussaini Nastaleeq):

پروگرامنگ کی دنیا میں خوش آمدید . یہ ایک اردو فونٹ ٹیسٹ ہے

Without custom font (System default):

پروگرامنگ کی دنیا میں خوش آمدید . یہ ایک اردو فونٹ ٹیسٹ ہے

If font style is same in all above samples, you are probably not using most recent browser capable of using font-face css style.

The custom font `Hussaini Nastaleeq` is a fork of Nafees Nastaleeq and is available here. The font is quite small in size (~ 300K) and browser should only download them if they are used by the page.

Tested on Linux (Fedora 17) on Chrome Version 22.0.1229.94 and Firefox Version 16.0.1, Opera (Windows) and Chrome (Windows). The best rendering is on Firefox though.

Numerous efforts are made to make this font work on IE 8 (which uses eot), however, still not able to make it work on IE8 unfortunately. The font is converted from ttf to eot on Linux using ttf2eot eot-utilities.

On JBoss side (if using JSF), you probably need to specify correct mime types for the font types. Here are the implementation details:

- web.xml:



        ttf
        application/octet-stream
  
  
        eot
        application/vnd.ms-fontobject
  
- css file:

/* Required first for IE, no format */
@font-face
{
  font-family: u; 
  src:  url("#{resource['fonts:nafees_riqa.eot']}");
}

@font-face
{
  font-family: u;
  src: url("#{resource['fonts:nafees_riqa.ttf']}") format('opentype');
}

#nrfont {
  font-family: u;
  font-size: x-large;
}
- JSF template:

  <h:outputStylesheet name="uzi.css" library="css" />
- Applying font:

<div id="nrfont"> ... 

Just moved the datasource to use jta. Last time it was not working, looks like it started working now ... strange!