Saturday, August 20, 2011

Liferay >>> open Liferay popup in web content

This post is about the solution to the problem i faced in liferay where i need to open one or more Liferay styled modal popups from web content portlet or similarly from any other portlet. In my case the popup i need to open is that of feedback from user. The steps i took to get it working are:

  1. To start with add an anchor tag in the web content portlet on which you want to open up a feedback popup
    <a id="" class="feedback_popup"> Submit Feedback</a>

  2. Now you need to go to the theme/javascript folder and edit javascript.js file. Add to it the code

    jQuery(document).ready(
    function() {
    th_FeedbackPopup()
    }
    );

    function th_FeedbackPopup() {
    jQuery(document).find("a.feedback_popup").click(function() {
    var url = new Liferay.PortletURL.createRenderURL();
    url.setPortletId("FEEDBACK_1");
    url.setWindowState("exclusive");
    url.setPortletMode("view");
    url.setParameter("struts_action", "/ext/feedvack/view");
    var popup = Liferay.Popup({
    draggable:false,
    width:500,
    height:'auto',
    url:url.toString(),
    resizable:false,
    modal:true,
    title:'Submit Feedback',
    position:[250,20]
    });
    });
    }
    The idea behing javascript is to bind the click event of all anchor elements on page having class "feedback_popup" to open a modal popup. Make sure that you should bind the event based on class name and not on element id as a page can have multiple such elements.

Better Faster Lighter Java

The section is designed to help you make the most effective use of the Java™ programming language and its fundamental libraries, java.lang, java.util, and, to a lesser extent, java.util.concurrent and java.io. It discusses other libraries from time to time, but it does not cover graphical user interface programming, enterprise APIs, or mobile devices. Section consists of 9 items, each of which conveys one rule. The rules capture practices generally held to be beneficial by the best and most experienced programmers. Many new features were added to the platform in Java 5. Most of the items here try to cover these features in some way.
  1. Minimize the scope of local variablesBy minimizing the scope of local variables, you increase the readability and maintainability of your code and reduce the likelihood of error. The most powerful technique for minimizing the scope of a local variable is to declare it where it is first used. Declaring a local variable prematurely can cause its scope not only to extend too early, but also to end too late. The scope of a local variable extends from the point where it is declared to the end of the enclosing block. If a variable is declared outside of the block in which it is used, it remains visible after the program exits that block. If a variable is used accidentally before or after its region of intended use, the consequences can be disastrous. Nearly every local variable declaration should contain an initializer. If you don’t yet have enough information to initialize a variable sensibly, you should postpone the declaration until you do.
    // Preferred idiom for iterating over a collection
    for (Element e : c) {
    doSomething(e);
    }
    Here is another loop idiom that minimizes the scope of local variables:
    for (int i = 0, n = expensiveComputation(); i < n; i++)
    {
    doSomething(i);
    }
    A final technique to minimize the scope of local variables is to keep methods small and focused. If you combine two activities in the same method, local variables relevant to one activity may be in the scope of the code performing the other activity. To prevent this from happening, simply separate the method into two: one for each activity.
  2. Know and use the librariesDon’t reinvent the wheel. If you need to do something that seems like it should be reasonably common, there may already be a class in the libraries that does what you want. If there is, use it; if you don’t know, check. Generally speaking, library code is likely to be better than code that you’d write and is likely to improve over time. Advantages of using library are:- Firstly by using a standard library, you take advantage of the knowledge of the experts who wrote it and the experience of those who used it before you. A second advantage of using the libraries is that you don’t have to waste your time writing ad hoc solutions to problems that are only marginally related to your work. Third advantage of using standard libraries is that their performance tends to improve over time, with no effort on your part. Because many people use them and because they’re used in industry-standard benchmarks also. Many of the Java platform libraries have been rewritten over the years, sometimes repeatedly, resulting in dramatic performance improvements. A final advantage of using the standard libraries is that you place your code in the mainstream. Such code is more easily readable, maintainable, and reusable by the multitude of developers.

  3. Prefer primitive types to boxed primitivesJava has a two-part type system, consisting of primitives, such as int, double, and boolean, and reference types, such as String and List. Every primitive type has a boxed primitives corresponding to it, like int, double, and boolean are Integer, Double, and Boolean. To summarize, use primitives in preference to boxed primitives whenever you have the choice. Primitive types are simpler and faster. If you must use boxed primitives, be careful! Autoboxing reduces the verbosity, but not the danger, of using boxed primitives. When your program compares two boxed primitives with the == operator, it does an identity comparison, which is almost certainly not what you want. When your program does mixed-type computations involving boxed and unboxed primitives, it does unboxing, and when your program does unboxing, it can throw a NullPointerException. Finally, when your program boxes primitive values, it can result in costly and unnecessary object creations.
  4. Avoid strings where other types are more appropriateStrings are designed to represent text, and they do a fine job of it. Because strings are so common and so well supported by the language, there is a natural tendency to use strings for purposes other than those for which they were designed. This item discusses a few things that you shouldn’t do with strings.
    • Strings are poor substitutes for other value types.
    • Strings are poor substitutes for enum types.
    • Strings are poor substitutes for aggregate types.
    • Strings are poor substitutes for capabilities.
    To summarize, avoid the natural tendency to represent objects as strings when better data types exist or can be written. Used inappropriately, strings are more cumbersome, less flexible, slower, and more error-prone than other types. Types for which strings are commonly misused include primitive types, enums, and aggregate types.
  5. Beware the performance of string concatenationThe string concatenation operator (+) is a convenient way to combine a few strings into one. It is fine for generating a single line of output or for constructing the string representation of a small, fixed-size object, but it does not scale. Using the string concatenation operator repeatedly to concatenate n strings requires time quadratic in n. It is an unfortunate consequence of the fact that strings are immutable. When two strings are concatenated, the contents of both are copied.
    // Inappropriate use of string concatenation - Performs horribly!
    public String statement() {
    String result = "";
    for (int i = 0; i < numItems(); i++)
    result += lineForItem(i);
    // String concatenation return result;
    }
    This method performs abysmally if the number of items is large. To achieve acceptable performance, use a StringBuilder in place of a String to store the statement under construction. The StringBuilder class, added in release 1.5, is an unsynchronized replacement for StringBuffer, which is now obsolete. The difference in performance is dramatic.
  6. Use loggingWhile building an application or doing debugging to trace out the control flow to rectify a bug always use standard logging libraries. Below are wrong and right way do keep control over logging.
    WRONG
    public void bar() {
    try {
    //doSomething()
    }
    catch (JMSException e) {
    System.out.println("exception occurred"); e.printStackTrace();
    }
    finally {
    System.out.println("cleaning up");
    }
    }
    RIGHT
    public void bar() {
    try {
    // ...
    }
    catch (JMSException e) {
    logger.log(Level.WARNING, "JMS Problem", e);
    } finally {
    logger.info("cleaning-up");
    }
    }

    Wrap complex logging expressions into conditions
    if (logger.isDebugEnabled()) {
    logger.debug("Message: " + object.calculateSomething() + ", count=" + cnt);
    }
  7. Code Formatting and stylingThere are 2 standard plugins available for Eclipse PMD and CheckStyle which comes to rescue
    • CheckStyle
      • http://checkstyle.sourceforge.net/index.html
      • Checkstyle is a development tool to help programmers write Java code that adheres to a coding standard.
      • Checkstyle will help you during your programming by checking your coding style i.e braces, naming etc. Simple things but very numerous!
      • Checkstyle is highly configurable and can be made to support almost any coding standard.
      • Historically it's main functionality has been to check code layout issues
      • Checkstyle is most useful if you integrate it in your build process or your development environment.
    • PMD
      • http://pmd.sourceforge.net/
      • PMD scans Java source code and looks for potential problems like:
        • Possible bugs - empty try/catch/finally/switch statements
        • Dead code - unused local variables, parameters and private methods
        • Suboptimal code - wasteful String/StringBuffer usage
        • Overcomplicated expressions - unnecessary if statements, for loops that could be while loops Duplicate code - copied/pasted code means copied/pasted bugs
      • PMD is also able to point out questionable coding practices and its output is generally more relevant and useful.
      • PMD will help you by checking more complicate rules like during the design of your classes, or for more special problems like implementing correctly the clone function. Simply, PMD will check your programming style
      • PMD to find problematic code areas and next refactoring targets
    Checkstyle and PMD both are good at checking coding standards and are easy to extend. But PMD has additional rules to check for cyclomatic complexity,Npath complexity,etc which allows you write healthy code.
  8. Adhere to generally accepted naming conventions
    The Java platform has a well-established set of naming conventions, many of which are contained in The Java Language Specification. Loosely speaking, naming conventions fall into two categories: typographical and grammatical. There are only a handful of typographical naming conventions, covering packages, classes, interfaces, methods, fields, and type variables. You should rarely violate them and never without a very good reason. If an API violates these conventions, it may be difficult to use. If an implementation violates them, it may be difficult to maintain. In both cases, violations have the potential to confuse and irritate other programmers who work with the code and can cause faulty assumptions that lead to errors.

Sunday, August 14, 2011

HTTPComponents client 4.1.2 >>> Invalid use of SingleClientConnManager: connection still allocated

In most of the ideal case scenarios single inialization of DefaultHttpClient will serve the purpose. However this singleton implementaion approach can lead to some problems. Since the resource designed as Singleton pattern becomes effectively global, doing things like modifying the time out value, or forcibly closing the connection manager (as one commenter pointed out), could lead to the HttpClient to be in an invalid or undesired state when reused at a different time or in a differentscenario in the same application.

Luckily, after much surfing I stumbled upon Jason Hudgin’s site where he created a convenience method that avoids this problem.
To overcome this the modified basic implemntaion will lead to something written below:

public static DefaultHttpClient getThreadSafeClient() {

DefaultHttpClient httpClient = new DefaultHttpClient();
ClientConnectionManager mgr = httpClient.getConnectionManager();
HttpParams params = httpClient .getParams();

httpClient = new DefaultHttpClient(
new ThreadSafeClientConnManager(params,
mgr.getSchemeRegistry()), params);

return httpClient ;
}

The right place to use something like this is when you want to download multiple items from a single remote machine, for example, if you need to make concurrent requests to any service on server to download image or do any CRUD operation and all requests sharing one HttpClient instance, reusing HTTP connections as they became available.