Saturday, December 17, 2011

Thursday, December 8, 2011

PrimeFaces: ViewExpiredException Server error

You have to add the  com.sun.faces.enableRestoreView11Compatibility param-name and the javax.faces.application.ViewExpiredException exception-type to the web.xml:

<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

...
....
<context-param>
        <param-name>com.sun.faces.enableRestoreView11Compatibility</param-name>
        <param-value>true</param-value>

</context-param>
...
...
...
...
<error-page>
        <exception-type>javax.faces.application.ViewExpiredException</exception-type>
        <location>/faces/Login/Login.xhtml</location>
    </error-page>
...
...
</web-app>


Reference:
http://mariosgaee.blogspot.com/2009/12/glassfish-and-adf-faces.html

PrimeFaces: The button/link/text component needs to have a Form in its ancestry. Please add

I got this warning while using a page:

The button/link/text component needs to have a Form in its ancestry. Please add <h:form>

By googling for a while I found it is a bug of Mojarra 2.1.1, so there are two posible solutions

1. Use Mojarra 2.0.4 which is the lastest stable mojarra release.
2. Change the param-value  "Production" of the to the param-name: javax.faces.PROJECT_STAGE:

<context-param>
        <param-name>javax.faces.PROJECT_STAGE</param-name>
        <param-value>Production</param-value> 
</context-param>

Resources:
http://www.geektilidie.com/?p=40
http://www.guj.com.br/java/240027-the-buttonlinktext-component-needs-to-have-a-form-in-its-ancestry-please-add-resolvido
http://code.google.com/p/primefaces/issues/detail?id=1586

Wednesday, December 7, 2011

PrimeFaces: Dealing with ViewExpiredException on Ajax Request Response

After pressing a p:commandButton :
<p:commandButton id="refresh" value="Send" action="#{connectionDBController.createDataTable}" update="result,messages"/>

I was getting this as a response in the browser:
<partial-response>
  <error>
    <error-name>class javax.faces.application.ViewExpiredException</error-name>
    <error-message><![CDATA[viewId:/index.xhtml - View /index.xhtml could not be restored.]]>
    </error-message>
  </error>
  <changes>
    <extension primefacesCallbackParam="validationFailed">{"validationFailed":false}</extension>
  </changes>
</partial-response>


BUT in the server log, there where NO LOG ERROR.The error was ONLY being sent through the http response, so the error-page tag in the web.xml couldn't work:

http://jhonjairoroa87.blogspot.com/2011/12/primefaces-viewexpiredexception-server.html

After googling for a couple of days , I couldn't find anything so  I decided to handle that error in my way, I know it could be better, but It works.

I added the oncomplete attrib to the p:commandButton:
<p:commandButton id="refresh" oncomplete="handleAjaxRequest2(xhr, status, args);" value="Send" action="#{connectionDBController.createDataTable}" update="result,messages"/>

The handleAjaxRequest method  has:


function handleAjaxRequest2(xhr, status, args){                       
            myValidationObject1 = new validationObject({'property':'data' , 'value':'class javax.faces.application.ViewExpiredException'}, null)
            myValidationObject2 = new validationObject({'property':'localName' , 'value':'error-name'}, myValidationObject1)
            myValidationObject3 = new validationObject({'property':'localName' , 'value':'error'}, myValidationObject2)
            myValidationObject4 = new validationObject({'property':'localName' , 'value':'partial-response'}, myValidationObject3)                                   
            myBoolResult = validateInternalPropery(xhr.responseXML , myValidationObject4);           
            if (myBoolResult == true){
                //alert("myBoolResult" + myBoolResult);
                alert("Session expired, please login again")
                window.location = '/myProject/faces/Login/Login.xhtml';
            }                      
        }

The validateInternalPropery method has

function validateInternalPropery(myObj , myValidationObject){
            returnValue = false;
            console.log("myObj");
            console.log(myObj);
            console.log("myValidationObject");
            console.log(myValidationObject);           
            //myObj = xhr.responseXML;
            if(myObj.hasChildNodes() == true){ //validate has chid nodes
                for(childNode in myObj.childNodes){ // iter child nodes in object
                    if (typeof myObj.childNodes[childNode] == 'object'){ // validate if the current childnode is an object
                        if(myObj.childNodes[childNode].hasOwnProperty(myValidationObject.iniValidation.property) == true){ // validate if the childnode has the given a Property
                            if(myObj.childNodes[childNode][myValidationObject.iniValidation.property] == myValidationObject.iniValidation.value){ // evaluatee the value of given property
                                if (myValidationObject.endValidation == null){
                                    returnValue = true;
                                    break;
                                }else{
                                    validateInternalPropery(myObj.childNodes[childNode] , myValidationObject.endValidation)
                                }                               
                            }
                        }
                    }
                }
            }
            return returnValue;
        }


The validationObject class method has

function validationObject(myIniValidation, myEndValidation){
            this.iniValidation = myIniValidation;
            this.endValidation = myEndValidation;
        }

I that way I can locate the error that I want , in this case, class javax.faces.application.ViewExpiredException, and do the window.location to redirect to the login page

References:
http://forum.primefaces.org/viewtopic.php?f=3&t=5909
http://yigitdarcin.wordpress.com/2011/10/06/dealing-with-viewexpiredexception-on-regular-and-ajax-requests/ 

http://weblogs.java.net/blog/driscoll/archive/2009/05/jsf_2_ajax_even.html 
http://stackoverflow.com/questions/6946078/primefaces-pajaxstatus-onerror-not-called 

Monday, November 14, 2011

Java: Copying and Cloning Lists: public Object clone()

import java.util.ArrayList;
import java.util.List;

public class MainClass {
  public static void main(String[] a) {

    List list = new ArrayList();
    list.add("A");

    List list2 = ((List) ((ArrayList) list).clone());

    System.out.println(list);
    System.out.println(list2);

    list.clear();

    System.out.println(list);
    System.out.println(list2);
  }
}

Source:

Python: Private Variables and Methods


# Demonstrates private variables and methods


class Critter(object):
    """A virtual pet"""
    def __init__(self, name, mood):
        print "A new critter has been born!"
        self.name = name            # public attribute
        self.__mood = mood          # private attribute


    def talk(self):
        print "\nI'm", self.name
        print "Right now I feel", self.__mood, "\n"


    def __private_method(self):
        print "This is a private method."


    def public_method(self):
        print "This is a public method."
        self.__private_method()


# main
crit = Critter(name = "Poochie", mood = "happy")
crit.talk()
crit.public_method()


Source:
http://www.java2s.com/Code/Python/Class/Demonstratesprivatevariablesandmethods.htm

Sunday, November 6, 2011

Python: Great Python Manual

Javascript: get and show attributes from object


var myObject = { name: "Cody", status: "Surprised" };
for (var propertyName in myObject) {
    document.writeln(propertyName+" : "+myObject[propertyName]);
}


Source:
http://stackoverflow.com/questions/85992/how-do-i-enumerate-the-properties-of-a-javascript-object


Python: get length of a list


a = ['spam', 'eggs', 100, 1234]
print len(a) // 4


Source:
http://www.java2s.com/Code/Python/List/Builtinfunctionlengetthelengthofalist.htm

Python: formatting Datetime


import datetime

datenow = datetime.datetime.now()
formatedDateNow = datenow.strftime("%Y-%m-%d")


References:
http://docs.python.org/library/datetime.html
http://effbot.org/librarybook/datetime.htm

Python: Get variable type

Use type() function:

>>> d=['one','two']
>>> print d
['one', 'two']
>>> type(d)
<type 'list'>

Source:
http://linux.byexamples.com/archives/342/python-how-to-identify-the-type-of-your-variable/

LibreOffice: Round number up


CEILING

Rounds a number up to the nearest multiple of Significance.

Syntax

CEILING(Number; Significance; Mode) 

Example

=CEILING(56100;1000) 
//returns 57000


Source:
http://help.libreoffice.org/Calc/Mathematical_Functions#CEILING

Wednesday, November 2, 2011

HTML: Great page to generate loading gifs

HTML: Generate Custom Hex Code Colors

ExtJS: doing a preloader screen

CSS: Writting comments

/* Comment here */

{
margin: 1em; /* Comment here */
padding: 2em; 
/* color: white; */
background-color: blue;
}
/*
multi-line
comment here
*/
Source:
http://css.maxdesign.com.au/selectutorial/rules_comments.htm

Python: string replace


str = "this is string example....wow!!! this is really string";


print str.replace("is", "was");    
# thwas was string example....wow!!! thwas was really string


print str.replace("is", "was", 3); 
# thwas was string example....wow!!! thwas is really string


Source:
http://www.tutorialspoint.com/python/string_replace.htm

Python: "Extend" like method for a Dict


a = { "a" : 1, "b" : 2 }
b = { "c" : 3, "d" : 4 }
a.update(b)
print a # prints { "a" : 1, "b" : 2, "c" : 3, "d" : 4 }


Source:
http://stackoverflow.com/questions/577234/python-extend-for-a-dictionary
Reference:
http://docs.python.org/library/stdtypes.html#mapping-types-dict

Thursday, October 27, 2011

ExtJS 4 : add/read Custom Attributes in TreeNode

Add a 'fields' array to the TreePanel:

,fields:[ 'text' , 'customfield']

and add the custom attribute to the node

,root: {
        text: 'Root',
        expanded: true,
        children: [            
            {
                text: 'Administracion General'
                ,customfield:'administracionGeneral'
                ,expanded: true
            }
        ]
    }

modify the listeners and get the custom attribute from record 'rec':

,listeners:{
        itemclick: function(view,rec,item,index,eventObj)
        {
            nodeClickAction = rec.get('customfield');
            alert(nodeClickAction);            
        }
    }


i.e

var tree = new Ext.tree.TreePanel({    
    renderTo: Ext.getBody(),
    height: 300,
    width: 250,
    fields:[ 'text' , 'customfield'],
    title: 'Files',
    listeners:{
        itemclick: function(view,rec,item,index,eventObj)
        {
            nodeClickAction = rec.get('customfield');
            alert(nodeClickAction);            
        }
   }
   ,root: {
        text: 'Root',
        expanded: true,
        children: [            
            {
                text: 'Administracion General'
                ,customfield:'administracionGeneral'
                ,expanded: true
            }
        ]
    }
});


Here is a detailed example: 

#### index.html ####


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">

 <head>
  <title>Custom Tree Test</title>
  <!-- ExtJS CSS -->
  <link rel="stylesheet" type="text/css" href="./ext-4.0.7-gpl/resources/css/ext-all.css"/>   
  <!-- SCRIPT -->
  <!-- ExtJS -->   
  <script type="text/javascript" src="./ext-4.0.7-gpl/ext-all.js"></script>   
 </head>
 <body>                  
  <script type="text/javascript">
   Ext.onReady(function(){                   
    var tree3 = new Ext.tree.TreePanel({   
    // title: 'Simple Tree',
    rootVisible : false // hides root
    ,border:false // hides border
    ,fields:[ 'text' , 'onClickAction']
    //,width: 150,
    //height: 150,
    ,listeners:{
     itemclick: function(view,rec,item,index,eventObj)
      {     nodeClickAction = rec.get('onClickAction');                                                     

          alert(nodeClickAction);                                                 
      }
     }
    ,root: {
     text: 'Root',
     expanded: true,
     children: [           
      {
       text: 'Administracion General'
       ,onClickAction:'administracionGeneral'
       ,expanded: true,                             
       children: [
       {
        text: 'Bodegas'
        ,onClickAction : 'bodegaPanelId'
        ,children:[
         {
           text: 'Crear Bodega'
           ,onClickAction : 'crearBodegaPanelId'
           ,leaf: true
         },{
           text: 'Buscar Bodega'
           ,onClickAction : 'buscarBodegaPanelId'
           ,leaf: true                                            }                                                                        

]
         },{
            text: 'Tipos Producto'
            ,onClickAction : 'tipoProductoPanelId'
            ,children:[
             {
              text: 'Crear Tipo Producto'
              ,onClickAction : 'crearTipoProductoPanelId'
              ,leaf: true
            },{
             text: 'Buscar Tipo Producto'
             ,onClickAction : 'buscarTipoProductoPanelId'
             ,leaf: true                                                           }                                                                       
             ]
            },{
              text: 'Tipos Documento'
             ,onClickAction : 'tipoDocumentoPanelId'
             ,children:[
              {
                text: 'Crear Tipo Documento'
                ,onClickAction : 'crearTipoDocumentoPanelId'
                ,leaf: true
              },{

                  text: 'Buscar Tipo Documento'
                  ,onClickAction : 'buscarTipoDocumentoPanelId'
                  ,leaf: true
                                                                }                                                                       
        ]
       }                                                                   
      ]
     }                   
    ]
   }   
  });
                   
                    var west = new Ext.Panel({
                         id : 'westContentPanelId'                   
                        ,title: 'Menú Principal'
                        ,layout: 'fit'       
                        ,collapsible: false
                        ,region:'west'
                        ,width: 215
                        ,margins: '5 0 5 5'
                        ,items:[tree3]
                    });                                     
                   
  var viewportz = new Ext.Viewport({
    layout:'fit', // The Viewport renders itself to the document body, and automatically sizes itself to the size of the
    //browser viewport and manages window resizing
    renderTo: 'container',
    layoutConfig:{animate:true}
    ,items:[west]
     });
   });
    </script>   
   
    <div id="container">   
        </div>
   
    </body>
</html>



Reference:
http://www.sencha.com/forum/showthread.php?145512-Tree-node-custom-attributes

Sunday, October 23, 2011

ExtJS 4: Tree node click event

Add a listener to the TreePanel:

listeners:{
        itemclick: function(view,rec,item,index,eventObj)
        {            
            alert(index);           
        }
    }

i.e

var tree = new Ext.tree.TreePanel({    
    store: store,
    renderTo: Ext.getBody(),
    height: 300,
    width: 250,
    title: 'Files',
    listeners:{
        itemclick: function(view,rec,item,index,eventObj)
        {         
            alert(index);         
        }
    }
});


Reference:
http://stackoverflow.com/questions/6094411/handling-itemclick-event-on-tree-panel-extjs-4

Friday, October 21, 2011

Interesting Benckmark of Python Web Servers

CherryPy: URL Routing in App Engine

# main.py
import cherrypy
import wsgiref.handlers


class HelloWorld:
  @cherrypy.expose
  def index(self):
    return "Hello world!"
class GoodDay:
  @cherrypy.expose
  def index(self,num=None):
    reply = "Good Day!"
    if num is not None:
      for x in range(1,int(num)):
        reply += "
Good Day!"
    return (reply)


def main():
  root = HelloWorld()
  root.reply = GoodDay()
  app = cherrypy.tree.mount(root,"/")
  wsgiref.handlers.CGIHandler().run(app)


if __name__ == '__main__':
  main()



Source:
http://appmecha.wordpress.com/2008/10/21/cherrypy-routing-1/

Thursday, October 20, 2011

Simple Ajax with cherrypy and jQuery

Be aware of having installed CherryPy 3.X, that's all.

Source:
http://ginstrom.com/scribbles/2010/03/07/simple-ajax-with-cherrypy-and-jquery/

AS400 : JDBC Driver

Apache Error: Could not bind to address 0.0.0.0:80 on Windows 7

If you get this error when installing apache on windows 7



1. Just continue the installation.
2. When it finish , go to the installation directory i.e "C:\Program Files (x86)\Apache Software Foundation\Apache2.2"
3. Go to the folder "conf" in the installation directory
4. Open the "httpd.conf"
5. Go to the line that has:
Listen 80
6. Add the word "localhost":
Listen localhost:80
7.Save the changes
8. Start the apache services

Wednesday, October 19, 2011

Blogger: change the case of existing Labels


1. Log in to Blogger, and go to the Posting > Edit Posts tab.
2. Select all the posts with the label you want to change (eg "fred"), by clicking on this Label in the left-hand panel, and then clicking Select All.
3. Use the Label Action... drop-down menu (just above the list of posts) to: 
4. Give them a new temporary label that's not already in use (eg "xxx-temp") - when you have done this, they will all have at least two labels.
5. Remove the label that you want to change
6. Select all the posts with the temporary label
7. Give them the label that you want to change to (eg "Fred")
8. Remove the temporary label that you added in the 2nd step.


Source: 

Javascript: simple confirm example

function confirmation() {
var answer = confirm("Leave tizag.com?")
if (answer){
alert("Bye bye!")
window.location = "http://www.google.com/";
}
else{
alert("Thanks for sticking around!")
}
}

Source:
http://www.tizag.com/javascriptT/javascriptconfirm.php

AS400 : Update and Join Sql commands

I searched for a while and I found Nothing. It looks like it is mandatory to use sentences like
UPDATE PROJECT
SET DEPTNO =
       (SELECT WORKDEPT FROM EMPLOYEE
        WHERE PROJECT.RESPEMP = EMPLOYEE.EMPNO)
WHERE RESPEMP='000030'

instead of using sentences with Join command :(

Note: If you find another way to do this, please let me know :) 


References: 
http://www2.systeminetwork.com/resources/clubtech/TNT400/bo400ng/sqlupdatejoin.htm
http://publib.boulder.ibm.com/cgi-bin/bookmgr/BOOKS/QB3AQ802/5.2 
http://www.experts-exchange.com/Database/DB2/Q_22535124.html

Tuesday, October 11, 2011

MSSQL Concat string


SELECT FirstName + ' ' + LastName As FullName FROM Customers
Source:
http://www.sqlbook.com/SQL/SQL-CONCATENATE-24.aspx

MSSQL: UNION in query

SELECT * FROM Table1
UNION
SELECT * FROM Table2

Note: the items called in the select sentence have to be the same quantity 

Source:
http://msdn.microsoft.com/es-es/library/ms191141.aspx

Friday, September 23, 2011

Javascript: array sort descending


//Sort alphabetically and ascending:
var myarray=["Bob", "Bully", "Amy"]
myarray.sort() //Array now becomes ["Amy", "Bob", "Bully"]



//Sort alphabetically and descending:
var myarray=["Bob", "Bully", "Amy"]
myarray.sort()
myarray.reverse() //Array now becomes ["Bully", "Bob", "Amy"]

Source:
http://www.javascriptkit.com/javatutors/arraysort.shtml

Javascript: remove item from array

DON’T
Unfortunately the most obvioous solution leaves a “hole” in the array :-(.
>>> var list = [4,5,6];
>>> delete list[1];
true
>>> list
[4, undefined, 6]
Sad, but understandable.

DO
So do it right and use splice().
>>> var list = [4,5,6];
>>> list.splice(1, 1); // Remove one element, returns the removed ones.
[5]
>>> list
[4, 6]


Useful DO
Actually, what I mostly need is: remove a certain value from an array.
I.e. I have some list of visible IDs and I want to remove one because it’s not visible anymore. So just extend the above example a bit.
>>> var visibleIds = [4,5,6];
>>> var idx = visibleIds.indexOf(5); // Find the index
>>> if(idx!=-1) visibleIds.splice(idx, 1); // Remove it if really found!
[5]
>>> visibleIds
[4, 6]


Source:
http://wolfram.kriesing.de/blog/index.php/2008/javascript-remove-element-from-array
Resource:
http://www.w3schools.com/jsref/jsref_splice.asp
http://stackoverflow.com/questions/5767325/remove-specific-element-from-a-javascript-array

Wednesday, September 21, 2011

MS SQL 2005: varchar to datetime - La conversión del tipo de datos varchar en datetime produjo un valor fuera de intervalo error.

I was trying to execute this:

update d_entrada set fecha_radicado = cast('2011-09-21 20:41:06.000' as datetime)  where id = '123456';


and I got this error

La conversión del tipo de datos varchar en datetime produjo un valor fuera de intervalo error.

I put the datetime this way ('2011-09-21 20:41:06.000') because when I execute

select fecha_radicado from d_entrada where id = '123456';

I get

2011-09-21 20:41:06.000

But to make the update query work propertly I had to switch 09 and 21 date values:

update d_entrada set fecha_radicado = cast('2011-21-09 20:41:06.000' as datetime)  where id = '123456';


then I got:



(1 row(s) affected)


Google Chrome: start incognito mode by default

1. Right click on google chrome shorcut
2. Select "properties" option
3. At the end of the target url add a "-incongnito" i.e :

C:\Users\John\AppData\Local\Google\Chrome\Application\chrome.exe -incognito

Note, sometimes it works with -incongnito or --incongnito depending the Operating System.

Source:
http://www.makeuseof.com/tag/how-to-start-google-chrome-in-incognito-mode-by-default/

Sunday, September 18, 2011

ExtJS (2.2.1): Making ComboBox Filter work from first click.

HAdd the following properties to the combobox that you need to filter:

triggerAction: 'all',
lastQuery: '',

Source:
http://www.sencha.com/forum/showthread.php?26909-linked-combobox-onload-filter&langid=4

Friday, September 9, 2011

ExtJS (2.2.1): xtype button listeners

{
    xtype:'button'
    ,text:'add'
    ,listeners:{                                        
        'click' : function(){alert("hi!!");
        }                                        
}   
Reference:
http://stackoverflow.com/questions/2372353/extjs-how-can-i-add-event-handlers-to-a-component-in-its-raw-object-form-xtype

ExtJS (2.2.1): Ext.Button absolute position

A Button is not an Ext.BoxComponent, so it cannot be positioned using x and y properties. So the problem can be solved by adding the button to a transparent panel with the same size as the button.


var MyPanel = new Ext.Panel({
            layout:'absolute',
            width:400,
            height:200,
            items:[{
                xtype:'textfield',
                width:150,
                x:0,
                y:0
            },{
                xtype:'combo',
                width:150,
                x:160,
                y:0
            },{
                xtype:'panel',
                y:25,
                x:0,
                items:[
                {
                    xtype:'button',
                    text:'Search'
                }]
            }]
});

Source:
http://www.sencha.com/forum/showthread.php?37012-Ext.Button-absolute-position-help

HTML:Great Canvas Tutorial

Thursday, September 8, 2011

Javascript: string replace

var myString = "thisisastring";
myString.replace("i", "e");

Reference:

Java: Iterate a String


java.text.CharacterIterator;
java.text.StringCharacterIterator;
CharacterIterator it = new StringCharacterIterator("abcd");

// Iterate over the characters in the forward direction
for (char ch=it.first(); ch != CharacterIterator.DONE; ch=it.next()) {
    // Use ch ...
}
Reference:
http://www.exampledepot.com/egs/java.text/StrIter.html

Wednesday, September 7, 2011

Javascript: currency format function


function formatCurrency(num) {
   num = num.toString().replace(/\$|\,/g,'');
   if(isNaN(num))
   num = "0";
   sign = (num == (num = Math.abs(num)));
   num = Math.floor(num*100+0.50000000001);
   cents = num%100;
   num = Math.floor(num/100).toString();
   if(cents<10)
   cents = "0" + cents;
   for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
   num = num.substring(0,num.length-(4*i+3))+','+
   num.substring(num.length-(4*i+3));
   return (((sign)?'':'-') + '$' + num + '.' + cents);
}


Source:
http://javascript.internet.com/forms/currency-format.html

Java: replace chars in String

/*
        Replaces all occurrences of given character with new one
        and returns new String object.
*/

String returnString = "test string to do some change";
returnString = returnString.replace( 'o', 'd' );

Source:
http://www.javadeveloper.co.in/java-example/java-string-replace-example.html
http://javarevisited.blogspot.com/2011/12/java-string-replace-example-tutorial.html
References:
http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html