Monday, November 23, 2009

How To Get OpenVPN to Work Under Vista

Ha....
It took me a good amount of time to find out which version of OpenVPN is supported by Windows Vista. Went thru all forums and blogs but no use. My laptop was throwing me challenge each day. Atlast OpenVPN release candidate 22 from version 2.1 on 2009.11.20 fixed my issue.

http://openvpn.net/release/openvpn-2.1_rc22-install.exe

support.real-time.com

Tuesday, July 07, 2009

Skype problem with audio playback

I installed Ubuntu 8.10 & 9.04 version. When ever I make a skype call, I get "problem with audio playback". This problem sucks. I was fetching for same issue in different forums and each one has given different ways to solve it.

Dont be panic. Simple solution is , goto >> skype >> options >> sound devices

Select proper device for "Sound In", "Sound Out" and "Ringing"
Each & every time select and try "make a test sound" or "Make test call".

And keep the checkbox "Allow skype to automatically...." checked.

This should work 100%.

Thursday, June 19, 2008

Cross Site Scripting (XSS)

For now here’s what you need to do. When you see something like this:
<%= @asset.description %>
Make sure you that you consider it a potential for XSS code execution
and simply fix it like so:
<%= h(@asset.description) %>

Tainting or (http://code.google.com/p/xss-shield)
XSS Shield protects your views against cross-site scripting attacks without error-prone manual escaping with h().

Instead of:

<%= h(item.name) %>


<%= link_to "#{h(item.first_name)}'s stuff", :action => :view, :id => item %>



You will be able to write:

<%= item.name %>


<%= link_to "#{item.first_name}'s stuff", :action => :view, :id => item %>



and all your views will be automatically protected. Protection works by tagging strings you trust - which are only those escaped by h(), generated by trusted helpers (like link_to, text_area, will_paginate etc.), or explicitly marked as trusted by you. If untrusted string is to be displayed in a template it is h-escaped first.

XSS Shield supports RHTML and HAML.

To install the plugin run:

./script/plugin install -x http://xss-shield.googlecode.com/svn/trunk/xss-shield/


Referred from google and peepcode

Sunday, May 18, 2008

Print Page functionality

Generate HTML code that includes two stylesheets. One for screen and another one for Print.
or say like below

style .............. /style
style media="print" ........ /style

body{
font-family:serif
}
.new-next, .new-print-btn{
display:none;
}
a:after { content:' [' attr(href) '] '}

The first style is for "Screen" (by default if do not specify one..)

Things to be noted in "Print"

Fonts should be serif (not sans-serif) for printing
Hide images as much as possible
Hide ads
Hide navigational elements
Use a black-on-white colour scheme
Underline links if any
Add the actual URL to your links (see below)
To add the actual URL in the href-part of your link to the name of your link add the following to you print stylesheet:

[css]a:after { content:’ [' attr(href) '] ‘}[/css]

Final thing add "javascript:print()" to the button

input type="button" value="Print" onclick = "javascript:print()"

[Ref: http://ariejan.net/2007/01/19/print-this-page-with-ruby-on-rails/ ]

Thursday, March 27, 2008

Removing Stale Rails Sessions

By default rails does not clear out stale sessions from the session store. To implement this feature I added the following small snippet of code;

class SessionCleaner
def self.remove_stale_sessions
CGI::Session::ActiveRecordStore::Session.
"destroy_all( ['updated_on end
end
And then invoke the remove_stale_sessions method every 10 minutes via;

Reference: http://www.realityforge.org/articles/2006/03/01/removing-stale-rails-sessions

Monday, April 09, 2007

Ruby and Rails blog links

Ruby and Rails blog links

http://www.wayne-robinson.com/ - nice blogs from this guy
http://www.railsenvy.com/2007/2/19/acts-as-ferret-tutorial- About full text indexing
http://del.icio.us/subramani.athikunte - subu

Multiple Values from Scriptaculous' Autocomplete

Multiple Values from Scriptaculous' Autocomplete
in ruby


refered from
http://www.wayne-robinson.com/display/ShowJournal?moduleId=549828&categoryId=40943

This example will auto-populate a state and postcode based on the user's selected suburb

The first step is to create a view for the page containing the autocomplete field and for the autocomplete field itself.

Controller:

def new
# This is the main controller that will
# contain the autocomplete field
@contact = Contact.new
end

def auto_complete_for_suburb
suburb = params[:suburb]
@surburbs = Suburb.find_by_name(suburb,
:order => "name", :limit => 20)
render :partial => "auto_complete_suburb"
end

View for the new action (assume an application.rhtml template has been created, this template must include the Prototype and Script.aculo.us javascript libraries):

<%= form_tag({:action => :create}, {:method => :post}) %>

















Name: <%= text_field(:contact, :name) %>
Suburb: <%= text_field_with_autcomplete(:contact, :suburb,
:select => "value",
:after_update_element =>
"function (ele, value) {
$("contact_state").value =
Ajax.Autocompleter.extract_value(value,
'STATE');
$("contact_postcode").value =
Ajax.Autocompleter.extract_value(value,
'POSTCODE'); }
") %>
State: <%= text_field(:contact, :state, :size => 10) %>
Postcode: <%= text_field(:contact, :postcode,
:size => 10) %>

<%= end_form_tag %>

Before we continue any further, it is worth-while defining the _auto_complete_suburb.rhtml partial.


    <% unless @suburbs.nil? -%>
    <% @suburbs.each do | suburb | -%>

  • <%= h("#{suburb[:name]}, #{suburb[:state]}" +
    "#{suburb[:postcode]}") %>




  • <% end -%>
    <% end -%>

The autocompleter view has three (3) hidden

tags which contain the extra data used by the base Autocompleter Javascript methods as well as the new one (extract_value) that will be defined below.

You may also want to cast your eye over the suburb field definition in the new contact view as this is where most of the action is. There are two options to note:

  • the :value option which specifies the class name of the element which contains the value to place in attribute (the default would be whatever is within the rendered
  • field which, as we will find out below, will contain more than just the selected suburb)
  • the :after_update_element option which specifies a piece of Javascript to execute when the item is selected. You will see that this Javascript executes the Ajax.Autocompleter.extract_value function twice. This function does not exist in Script.aculo.us but is provides an easy way to extract extra values from an autocomplete list.

The Script.aculo.us Autocompleter methods conviently pass the complete contents of the

  • field to the method specified in the :after_update_element option. This allows us to extract any additional values from this data. I have created a simple addition to the Ajax.Autocompleter class below that speeds this extraction:

    Additional method for Ajax.Autocompleter class. This can be declared anywhere after the inital Script.aculo.us script inclusion. For my purposes I put this at the top of my application.js file.

    Ajax.Autocompleter.extract_value =
    function (value, className) {
    var result;

    var elements =
    document.getElementsByClassName(className, value);
    if (elements && elements.length == 1) {
    result = elements[0].innerHTML.unescapeHTML();
    }

    return result;
    };
  • Friday, September 22, 2006

    Inversion of Control

    IoC means you have registered some part of your code with the framework, and the framework will
    call this code when the client requests it. This is also referred to as the Hollywood principle. (“Don’t call us. We’ll call you.”)


    Inversion of Control, also known as IOC, is an important object-oriented programming principle that can be used to reduce coupling inherent in computer programs.

    IOC is also known as the Dependency Inversion Principle [#wp-endnote_Martin 2002_none (Martin 2002:127)]. The Dependency injection [#wp-endnote_Fowler 2004_none (Fowler 2004)] techinque is used in almost every framework and it's a simple example of the IoC principle applied. It has been applied by programmers using object-oriented programming languages such as SmallTalk, [[C++]], Java or any .NET language.

    Technical description

    Terms and definitions

    Class X depends on class Y if any of the following applies:

    * X has a Y and calls it
    * X is a Y
    * X depends on some class Z that depends on Y (transitivity)

    X depends on Y does not imply Y depends on X. If both happen to be true this is called a cyclic dependency: X can't then be used without Y, and vice versa. The existence of a large number of cyclic dependencies in an object oriented program might be an indicator for suboptimal program design.

    If an object x (of class X) calls methods of an object y (of class Y), then class X depends on Y. The dependency can now be inverted by introducing a third class, namely an interface class I that must contain all methods that x might call on y. Furthermore, Y must be changed such that it implements interface I. X and Y are now both dependent on interface I and class X no longer depends on class Y, presuming that x does not instantiate Y.

    This elimination of the dependency of class X on Y by introducing an interface I is said to be an inversion of control (or a dependency inversion).

    It must be noted that Y might depend on other classes. Before the transformation had been applied, X depended on Y and thus X depended indirectly on all classes that Y depends on. By applying Inversion of control, all those indirect dependencies have been completely broken up too, not only the dependency from X on Y. The newly introduced interface I depends on nothing.

    Friday, August 04, 2006

    JSTL function tag ${fn:length....}

    c:set var="tempStr" value="I love Java an www.java2s.com"

    The length of the test String: ${fn:length(tempStr)}


    Does the test String contain "test"? ${fn:contains(tempStr,"test")}


    Putting the String into upper case using fn:toUpperCase(): ${fn:toUpperCase(tempStr)}


    Splitting the String into a String array using fn:split(), and returning the array length: ${fn:length(fn:split(tempStr," "))}

    how to do i find out the length of this arraylist using JSTL tags...





    or if

    <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
    ${fn:length(theList)}

    how to do i find out the length of this arraylist
    using JSTL tags...

    /That depends on what version of what server (and JSTL) you are using. If you are using JSTL 1.1 (JSP 2.0 server like Tomcat 5.0) then you can use:



    If you are Using JSTL 1.0 and a JSP 1.2 server (like Tomcat 4), then you will either have to use a scriptlet, or run a c:forEach:

    //scriptlet
    <%
    List array = (List)request.getAttribute("array");
    Integer count = new Integer(array.size());
    pageContext.setAttribute("count", count);
    %>
    //c:forEach

    Wednesday, August 02, 2006

    sort a table comparator

    http://java.sun.com/docs/books/tutorial/uiswing/components/example-1dot4/TableSorter.java

    http://java.sun.com/docs/books/tutorial/uiswing/components/example-1dot4/TableSorterDemo.java

    BeanComparator

    import java.text.SimpleDateFormat;
    import java.util.Comparator;
    import java.util.Date;

    import org.apache.commons.beanutils.PropertyUtils;
    import org.apache.commons.collections.comparators.ComparableComparator;
    import org.apache.commons.collections.comparators.ReverseComparator;


    public class BeanComparator implements Comparator {

    private String attribute;
    private String sortBy;
    private String javaType;

    private Comparator comp = new ComparableComparator();

    public BeanComparator(String attrib, String sortBy, String javaType) {
    this.attribute = attrib;
    this.sortBy = sortBy;
    this.javaType = javaType;

    if(this.sortBy!= null && !this.sortBy.equals("") && this.sortBy.equals("descending") )
    comp = new ReverseComparator();
    else if (this.sortBy!= null && !this.sortBy.equals("") && this.sortBy.equals("ascending") )
    comp = new ComparableComparator();

    }

    public int compare(Object o1, Object o2) {
    if(o1 == null) {
    return 1;
    } else
    if(o2 == null) {
    return -1;
    }

    try {
    Object ret1 = PropertyUtils.getProperty(o1, this.attribute);
    Object ret2 = PropertyUtils.getProperty(o2, this.attribute);
    return this.comp.compare(ret1, ret2);

    } catch(Exception e) {
    return 0;
    }
    }

    }

    Reverse Comparator

    + static class ReverseComparator implements Comparator, Serializable
    + {
    + public int compare(Object a, Object b)
    + {
    + return -((Comparable) a).compareTo(b);
    + }
    + }
    +
    + static ReverseComparator rcInstance = new ReverseComparator();
    +
    /**
    * Get a comparator that implements the reverse of natural ordering. This is
    * intended to make it easy to sort into reverse order, by simply passing
    * Collections.reverseOrder() to the sort method. The return value of this
    * method is Serializable.
    */
    - // The return value isn't Serializable, because the spec is broken.
    public static Comparator reverseOrder()
    {
    - return new Comparator()
    - {
    - public int compare(Object a, Object b)
    - {
    - return -((Comparable) a).compareTo(b);
    - }
    - };
    + return rcInstance;
    }

    Date Comparator

    // Create Date Comparator for ChangeLogEntry's
    Comparator comparator = new Comparator() {
    public int compare(Object object1, Object object2) {
    ChangeLogEntry entry1 = (ChangeLogEntry)object1;
    ChangeLogEntry entry2 = (ChangeLogEntry)object2;

    // Compare Dates
    int compare = entry1.getDate().compareTo(entry2.getDate());

    // Invert so that sort is descending
    return (compare * -1);
    }
    };

    // Sort the entries
    Collections.sort(filteredEntries, comparator);

    NumericString Java Comparator

    Collection coll = getPersons(); // full of Person objects.

    // Person.getName exists
    Collections.sort(coll, new BeanComparator("name"));

    or to improve performance:

    Collections.sort(coll, BeanComparator.getInstance("name"));

    This sits on top of an ObjectComparator which aims to compare any
    primitive object. So it uses a UrlComparator, and a ComparableComparator.
    Plan is to add more as time goes by.

    Then there's a SoundexComparator, a PackageNameComparator (java package
    names, ie) java.util comes before com.sun) and a ReverseComparator.

    The ReverseComparator is something I love. Very tiny code, big value.

    Collections.sort(coll, new
    ReverseComparator(BeanComparator.getInstance("name")));

    will happily sort in reverse order :) Obviously the implementation is
    just:

    return -1 * subComparator.compare(o1,o2);

    So this reverses a list with no performance problem :) Number of times
    I've seen people passing a 'reverse' flag to their comparators.

    Anyway, I think this is a pretty nice system and that it might be worthy
    of being a sub-package 'compare' inside Commons Collections.

    Any thoughts?

    Bay

    package com.generationjava.compare;

    import java.util.Comparator;

    /**
    * A Comparator which deals with alphabet characters 'naturally', but
    * deals with numerics numerically. Leading 0's are ignored numerically,
    * but do come into play if the number is equal. Thus aaa119yyyy comes before
    * aaa0119xxxx regardless of x or y.
    *
    * The comparison should be very performant as it only ever deals with
    * issues at a character level and never tries to consider the
    * numerics as numbers.
    *
    * @author [EMAIL PROTECTED]
    */
    public class NumericStringComparator implements Comparator {

    public NumericStringComparator() {
    }

    public int compare(Object o1, Object o2) {
    if(o1 == null) {
    return 1;
    } else
    if(o2 == null) {
    return -1;
    }

    String s1 = o1.toString();
    String s2 = o2.toString();

    // find the first digit.
    int idx1 = getFirstDigitIndex(s1);
    int idx2 = getFirstDigitIndex(s2);

    if( ( idx1 == -1 ) ||
    ( idx2 == -1 ) ||
    ( !s1.substring(0,idx1).equals(s2.substring(0,idx2)) )
    )
    {
    return s1.compareTo(s2);
    }

    // find the last digit
    int edx1 = getLastDigitIndex(s1, idx1);
    int edx2 = getLastDigitIndex(s2, idx2);

    String sub1 = null;
    String sub2 = null;

    if(edx1 == -1) {
    sub1 = s1.substring(idx1);
    } else {
    sub1 = s1.substring(idx1, edx1);
    }

    if(edx2 == -1) {
    sub2 = s2.substring(idx2);
    } else {
    sub2 = s2.substring(idx2, edx2);
    }

    // deal with zeros at start of each number
    int zero1 = countZeroes(sub1);
    int zero2 = countZeroes(sub2);

    sub1 = sub1.substring(zero1);
    sub2 = sub2.substring(zero2);

    // if equal, then recurse with the rest of the string
    // need to deal with zeroes so that 00119 appears after 119
    if(sub1.equals(sub2)) {
    int ret = 0;
    if(zero1 > zero2) {
    ret = 1;
    } else
    if(zero1 < zero2) {
    ret = -1;
    }
    if(edx1 != -1) {
    int comp = compare(s1.substring(edx1), s2.substring(edx2));
    if(comp != 0) {
    ret = comp;
    }
    }
    return ret;
    } else {
    // if a numerical string is smaller in length than another
    // then it must be less.
    if(sub1.length() != sub2.length()) {
    return ( sub1.length() < sub2.length() ) ? -1 : 1;
    }
    }


    // now we get to do the string based numerical thing :)
    // going to assume that the individual character for the
    // number has the right order. ie) '9' > '0'
    // possibly bad in i18n.
    char[] chr1 = sub1.toCharArray();
    char[] chr2 = sub2.toCharArray();

    int sz = chr1.length;
    for(int i=0; i // this should give better speed
    if(chr1[i] != chr2[i]) {
    return (chr1[i] < chr2[i]) ? -1 : 1;
    }
    }

    return 0;
    }

    private int getFirstDigitIndex(String str) {
    return getFirstDigitIndex(str, 0);
    }
    private int getFirstDigitIndex(String str, int start) {
    return getFirstDigitIndex(str.toCharArray(), start);
    }
    private int getFirstDigitIndex(char[] chrs, int start) {
    int sz = chrs.length;

    for(int i=start; i if(Character.isDigit(chrs[i])) {
    return i;
    }
    }

    return -1;
    }

    private int getLastDigitIndex(String str, int start) {
    return getLastDigitIndex(str.toCharArray(), start);
    }
    private int getLastDigitIndex(char[] chrs, int start) {
    int sz = chrs.length;

    for(int i=start; i if(!Character.isDigit(chrs[i])) {
    return i;
    }
    }

    return -1;
    }

    public int countZeroes(String str) {
    int count = 0;

    // assuming str is small...
    for(int i=0; i if(str.charAt(i) == '0') {
    count++;
    } else {
    break;
    }
    }

    return count;
    }

    // UNUSED
    private boolean containsOnly(String str, char ch) {
    return containsOnly( str.toCharArray(), ch );
    }
    private boolean containsOnly(char[] chrs, char ch) {
    int sz = chrs.length;

    for(int i=0; i if(chrs[i] != ch) {
    return false;
    }
    }

    return true;
    }

    }

    How to Access parameteters (request.getParameter) in JSF

    How to Access parameteters in JSF -- request.getParameter()...

    you cannot use #{request.getParameter("c"}. Such syntax is not acceptable.

    From the Specification:
    param—An immutable Map of the request parameters for this request, keyed by
    parameter name. Only the first value for each parameter name is included.

    So, #{param} are loaded from request Parameters by definition :-)

    Just for testing purpose, put somewhere on your page to see what the #{param} contains.

    You cannot use the session scope bean, because its properties cannot be initialized with the objects that have the shorter scope.


    EXAMPLE 1
    You can access your current request's instance in backing bean like :
    String paramValue = ((HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest()).getParameter("paramName");


    OR
    EXAMPLE 2



    OR
    EXAMPLE 3
    The easiest way to resolve this is to use a commandLink instead of a commandButton. Within your commandLink use f:param to send the subLink1 parameter:

    Then in faces.config use the managed property and the implicit JSF expression variable "param" to set the parameter in your managed bean. Something like:

    Then add a setter method in your managed bean for subLink1.



    Struts Nested Tags

    Struts Nested Tags
    Since the version 1.1 of Struts, the tag library “nested” is included in Struts. In this tutorial we want to explain what are the features of the new nested tag library and show some little examples howyou can use it.

    Copied from www.laliluna.de/struts-nested-iteration-tutorial.html

    The nested tag library
    Nested tags make it easy to manage nested beans. For example a list like the following:
    Department A
    Customer A
    Customer B
    Customer C
    Department B
    Customer D


    All nested tags inside a nested tag refers to the tag which surrounds them. For example your form bean holds an object department and you want the property name of the department. Normally you can use a dot notation to get the name of the department.


    With a nested:nest tag you do not need the dot notation any more.


    The following example shows a dot notation to output the name of a department bean:



    The tags inside the nested:nest can refers directly to the properties of the department. When you have many properties this is quite an advantage. The most functionality elements of the other tag libraries are rebuild as nested tags, like
    bean:write is nested:write, logic:iterate is nested:iterate etc. You will find a complete list of all supported tags by the nested tab library in the Apache Struts Nested Tag Library API.


    Usage of the nested tags
    Create a new struts 1.1 project to get more familiar with the nested tags.
    Add a package de.laliluna.tutorial.nested to the src folder of the project.


    Object class Customer
    Create a new java class Customer in the package de.laliluna.tutorial.nested.object.
    Add two properties, id of type int and name of type String. Provide a getter and setter method for each property. Create a constructor that allow you to set the properties on initialization.


    The following source code shows the class Customer :
    /**
    * Object Class Customer
    */
    public class Customer {
    private int id;
    private String name;
    //constructors
    public Customer(){}
    public Customer(int id, String name){
    this.id = id;
    this.name = name;
    }
    public int getId() {
    return id;
    }
    public void setId(int id) {
    this.id = id;
    }
    public String getName() {
    return name;
    }
    public void setName(String name) {
    this.name = name;
    }
    }


    Object class Department
    Create a second java class Departments in the same package de.laliluna.tutorial.nested.object. Add two properties, id of type int and name of type String and one property customers of type Collection, which holds a list of customers. Provide a getter and setter method for each property.
    Create a constructor that allows you to set the properties on initialization.


    The following source code shows the class Department :
    /**
    * Object Class Department
    */
    public class Department {
    private int id;
    private String name;
    //customers collection
    private Collection customers;
    //constructors
    public Department() {}
    public Department(int id, String name, Collection customers){
    this.id = id;
    this.name = name;
    this.customers = customers;
    }
    public Collection getCustomers() {
    return customers;
    }
    public void setCustomers(Collection customers) {
    this.customers = customers;
    }
    public int getId() {
    return id;
    }
    public void setId(int id) {
    this.id = id;
    }
    public String getName() {
    return name;
    }
    public void setName(String name) {
    this.name = name;
    }
    }


    Action form class ExampleForm
    Create a java class ExampleForm in the package de.laliluna.tutorial.nested.form, which extends the class ActionForm of struts. Add a property department of type Department. Provide a getter and setter method for the property department.
    Implement the reset() method of the ActionForm class and provide some dummy data.


    The following source code shows the class ExampleForm:
    /**
    * Action Form Class ExampleForm
    */
    public class ExampleForm extends ActionForm {
    Department department;
    public Department getDepartment() {
    return department;
    }
    public void setDepartment(Department department) {
    this.department = department;
    }
    /**
    * Reset method
    * @param mapping
    * @param request
    */
    public void reset(ActionMapping mapping,
    HttpServletRequest request) {
    //initial a dummy collection of customers
    Collection customers = new ArrayList();
    customers.add(new Customer(1, "Maria"));
    customers.add(new Customer(2, "Klaus"));
    customers.add(new Customer(3, "Peter"));
    //initial a dummy department
    department = new Department(1, "Department A", customers);
    }
    }


    Action class ExampleAction
    Create a java class ExampleAction in the package de.laliluna.tutorial.nested.action, which extends the class Action of struts. Return the forward example.


    The following source code shows the class ExampleAction:
    /**
    * Action Class ExampleAction
    */
    public class ExampleAction extends Action {
    /**
    * Method execute
    * @param mapping
    * @param form
    * @param request
    * @param response
    * @return ActionForward
    */
    public ActionForward execute(
    ActionMapping mapping,
    ActionForm form,
    HttpServletRequest request,
    HttpServletResponse response) {
    ExampleForm exampleForm = (ExampleForm) form;
    return mapping.findForward("example");
    }
    }


    Configure the struts-config.xml
    Open the struts-config.xml and add the form bean and action mapping.


    The following source code shows the content of the struts-config.xml.


    type="de.laliluna.tutorial.nested.form.ExampleForm" />


    attribute="exampleForm"
    input="/form/example.jsp"
    name="exampleForm"
    path="/example"
    scope="request"
    type="de.laliluna.tutorial.nested.action.ExampleAction"
    validate="false" >






    The JSP file
    Create a new JSP file example.jsp in the folder /WebRoot/form.
    Add the reference to the tag library nested at the top of the file. The following source code shows the JSP file. The bold line at the top is the reference to the
    nested tag library.




    Inside the element you insert the following examples.
    Example 1
    In the first example we show the usage of dot notation to get the properties form the department


    object of the form bean.



    Example 2
    The second example shows the usage of the nested:nest tag to use the properties inside the
    nested:nest tag without dot notation. The attribute property of the nested:nest element refers to
    the property department of our form bean.
    The nested:text elements inside the nested:nest element refers to the properties of the surrounds
    nested tag. The attribute property of the nested:text element refers to a property of the object
    class Department.



    Example 3
    Example 3 shows the usage of an iteration inside a nested:nest tag. The nested:iteration element works like the logic:iteration element, but refers to a property of the parent nested tag.