Sunday, December 16, 2012

Exploring CFX(Java) in ColdFusion-9(Part-2)

NOTE: Please take a look into this URL to start from beginning.

Before writing some real business logic in a CFX tag we need to know the working and structure of CFX.

If we look into the java code of “” file present in “C:\ColdFusion9\cfx\java\distrib\examples” for ColdFusion developer installation in Windows machine then we will find the following text.

The first line of the code contains “import com.allaire.cfx.* ”. This means we are using some features of one existing java package(com.allaire.cfx). The jar file for package is present in “cf_root/wwwroot/WEB-INF/lib” for server configuration and present in “cf_webapp_root/WEB-INF/lib” for J2EE configuration.

In second line code it is just creating one public class called “HelloColdFusion”, it will be the name of our class in CFX tag and this class imports/extends another java interface called “CustomTag” which is present in “com.allaire.cfx” package. We are extending/importing that interface to get the functionality of that interface in our defined class “HelloColdFusion”.

In the next step we are creating one overloaded java method “processRequest”. The interface “CustomTag” contains one method, processRequest, which is passed Request and Response objects that are then used to do the work of the tag.

So, for each custom tag we must write the method “processRequest” and which is the start point for CFX tag execution. When we will call the CFX tag we don’t need to bother about the Request and Response Object from the ColdFusion side. This two Object holds information about what are the parameters passed to the custom tags and their properties and what are the response parameters passed back to ColdFusion and their properties.

I have listed the functions what we can access by the Request Object and their details. For more details click on the function.
Request Object:

attributeExistsChecks whether the attribute was passed to this tag.
debugChecks whether the tag contains the debug attribute.
getAttributeRetrieves the value of the passed attribute.
getAttributeListRetrieves a list of all attributes passed to the tag.
getIntAttributeRetrieves the value of the passed attribute as an integer.
getQueryRetrieves the query that was passed to this tag, if any.
getSettingRetrieves the value of a global custom tag setting.

Response Object:
Followings are the response Object methods. For details about each method click on that method.

writeOutputs text to the calling page.
setVariableSets a variable in the calling page.
addQueryAdds a query to the calling page.
writeDebugOutputs text to the debug stream.

Back to our code “String strName = request.getAttribute( "NAME" ) ” in this line we are just getting the value of the attribute “NAME” which we will pass during executing the CFX tag. Then, in the next line “response.write( "Hello, " + strName ) ” we are just writing some text back to the client. It will be display in the browser if we will run the page which contains that CFX  through browser.

We can also return some variable to the calling page by writing the following code:
response.setVariable("Status", "true");

Now, you can compile your “.java” file to get “.class” file what we require.

In the next post we will see how we can implement some real business logic here and how we can pass one query object to custom tags and how we can return some query/Struct/variable from the custom tags.

Saturday, December 15, 2012

Google URL Shortening API by ColdFusion

I was trying to use Google URL shortening API by using ColdFusion. I have written two ColdFusion function which will take Short/Long URL as input parameter then it will return a structure which would have been returned by Google contains both Short/Long URL for the passed value in input parameter.

If you will  try with the following example:

Long URL:
Short URL:

We will get the following result:

Thursday, December 13, 2012

Add Space Before Capital Letter

In one of my recent project my requirement was to add a space before a capital letter like, if our word is "HiAmbika" then we have to convert it to "Hi Ambika".

Input String: "RajaRamMohamRoy"
Output       :  "Raja Ram Mohan Roy"

I just used regular expression in ColdFusion to achieve this as follows.

We can also do other advance string matching functionality with back referencing. We will see that latter.

Wednesday, December 12, 2012

Extract Text from HTML Code in ColdFusion

Our Goal:
How we could extract text from HTML code using ColdFusion?

We will use some regular expression to achieve this.

 Use regular expression "<.*?>" to extract HTML text. This one will work fine until there is no JavaScript(JS) or CSS code is present inside the HTML. When any JS/CSS code is present in HTML then it can't omit those.Then use a second regular expression to remove JS and CSS code from HTML.

To replace JS and CSS code we have to use "<(script|style).*?</\1>".

So, if we will combine the two regular expression then we can get actual text from the HTML code which may contain some CSS and JS code.

The final regular expression will be "<(script|style).*?</\1>|<.*?>".

Our HTML code is:

So, the final ColdFusion code to extract text from above HTML would be follows:

After, all these steps we will get following text as the out put.

In the final regular expression "<(script|style).*?</\1>|<.*?>", we have used expression to remove any CSS/JS first then remove the HTML. As if we will change the order to "<.*?>|<(script|style).*?</\1>" then the CSS/JS code will be there in the final output. As the CSS/JS code will match with the first part and it will treat as normal HTML code.

Friday, November 30, 2012

New Structure Declaration in ColdFusion 10

In ColdFusion 10 a new structure declaration type is introduced.  This is very similar to JavaScript Object declaration and it is as follows:

Here we are using colon as separator between key and value rather than '='. Above I have mentioned keys as case sensitive. This means not case sensitive to ColdFusion but other technology like JavaScript.(If we are returning this structure by any AJAX call)

Wednesday, November 28, 2012

Setting Cookie by cfscript in ColdFusion 10

Now a days in ColdFusion coding most of us generally using script version of CF more than tag version. Sometimes we feel upset when we don't get the script version for a particular tag. In  such cases we write our own function to use that in script code. CFCOOKIE is one tag which used to set cookie and which doesn't have any script version before ColdFusion 10.

   In ColdFusion 10, script version for CFCOOKIE  introduced. We can set cookie by cfscript in ColdFusion 10 as follows.

In the above code two ways are quite similar, here we are creating a structure where the key of the structure is exactly same as the attributes of the cfcookie tag. If we are using cfscript  to set cookie then we don't need to set name of the cookie in the structure as we usually do for cfcookie.

Also in ColdFusion 10, two new attributes added for setting cookie. These are follows:

preserveCase : Specify if you want to make cookie name case sensitive. This is an optional parameter and default value is "false."

encodeValue : Specify if cookie value should be encoded. This is an optional parameter and default value is "false".

Hope it will help you.

Wednesday, November 21, 2012

For-In Loop Over query and struct object

After a long gap now I got some time for my own blog.

Recently I just studied few new functionality which has been added in ColdFusion 10. For-in loop one of the functionality liked.

Lets take a look into the following code to use for-in loop for looping over any structure or any query object.

    //Create an Query Object
    qryEmployeeList = queryNew("empID, firstName, lastName", "BigInt, VarChar, VarChar");
    queryAddRow(qryEmployeeList, 2);
    querySetCell(qryEmployeeList, "empID", 1, 1);
    querySetCell(qryEmployeeList, "firstName", "Sachin", 1);
    querySetCell(qryEmployeeList, "lastName", "Tendulkar", 1);

    querySetCell(qryEmployeeList, "empID", 2, 2);
    querySetCell(qryEmployeeList, "firstName", "Rahul", 2);
    querySetCell(qryEmployeeList, "lastName", "Dravid", 2);

    //Create Struct
    strEmployeeInfo = structNew();
    strEmployeeInfo['empID'] = "3";
    strEmployeeInfo['firstName'] = "Saurav";
    strEmployeeInfo['lastName'] = "Ganguly";

    //Loop Over Query Object using for in
    for( employee in qryEmployeeList) {
        WriteOutPut(employee.empID & " : " & employee.firstName & " " & employee.lastName & "<br/>");

    //Loop Over struct Object using for in
    for(strfieldName in strEmployeeInfo) {
        WriteOutPut(strfieldName & " : " & structFind(strEmployeeInfo, strfieldName) & "<br/>");

Happy Coding. Lets wait for some new interesting things in ColdFusion 10.

Wednesday, June 20, 2012

CFX(Java) Custom tags in ColdFusion-9(Part-1)

For  ColdFusion - 9 some sample java source files are present in “{ColdFusion_Root}/cfx\java\distrib\examples\” for windows and in “{ColdFusion_Root}/cfx/java/examples” directory for linux system.

<cfx_HelloColdFusion name="Mr. X">

Take the example of “CFX_HelloColdFusion” from the specified source codes present. If you directly execute that CFX tag with the above code without doing anything to the server you will get the following error message.

"Error processing CFX custom tag CFX_HelloColdFusion.
The CFX custom tag CFX_HelloColdFusion was not found in the custom tag database. You must add custom tags to the database before using them. If you have added your tag to the database, check the spelling of the tag within your template to ensure that it matches the database entry."

So you need to follow the following steps in order to install that source code as a CFX tag.

  1. Compile the source code ("") file  from the sample files of the ColdFusion installation  by using the command prompt or by using any IDE and generate the "HelloColdFusion.class" file.
  2. For testing the CFX tag place the  HelloColdFusion.class  file in “cf_root/wwwroot/WEB-INF/lib” in Server configuration and place in “cf_webapp_root/WEB-INF/lib” for J2EE configuration. In this place when you make any changes to the java code you only need to replace the new .class file with the existing one. You don't need to restart the ColdFusion server on each changes to the .class built.
  3. You can also place your .class files in your specific directory by changing the Class path settings in ColdFusion administrator.(Server Settings->Java and JVM -> ColdFusion Class Path). After that you need to restart your ColdFusion server.
  4. Then you need to register your CFX tag in ColdFusion admin:
  • Go to Extensions =>CFX Tags => Click Register Java CFX in ColdFusion admin. You will see a screen like below. 
  •  CFX tag name starts with the prefix "cfx_" then the class name of the java code in our case the class name is "HelloColdFusion". So the vale for tag name input will be "cfx_HelloColdFusion".
  •  In Class Name field we need to provide the class name without any .class extension. e.g-"HelloColdFusion".
  •  In Description text area we need to add some description for that tag. e.g-This tag shows greeting message. This field is Optional we can skip it. But, it helps us when we have very large no of CFX tags.
After all these steps if I will run the CFX code which I have written on the top of this page, I will get the following message as the output.
"Hello, Mr. X"

For more details on CFX(java)  in ColdFusion-9 have to wait for the next post. Thanks :)

1. CFX Custom Tag Part II

Wednesday, June 13, 2012

Understanding writeOutPut function in ColdFusion

I was doing some some funny testing with writeOutPut() method of ColdFusion with iif() method.
My Code was:
<cfset iif(false, WriteOutput("It will execute IF TRUE"), WriteOutput("It will execute IF FALSE"))>

I got the out put:

It will execute IF TRUEIt will execute IF FALSE
then Error

Variable YES is undefined.

Here the question is why I am getting this error?

Then I made the testing with the following code:

<cfset c = writeoutput("hi")><cfoutput>#c#</cfoutput>

The out put of the above code was:

"hi YES".

After this out put I got my answer to first question i.e the writeOutPut() function returning some Boolean value but in "YES" and "NO"  format and iif() function treats that YES and NO as variable not as a Boolean value.

But, another question arises here When we gets the value NO/false in calling writeOutPut()?

If anyone know the answer of my question or my understanding is wrong . Please write your comment.

Saturday, June 09, 2012

ColdFusion Query Of Queries and local scope

Few days ago I was working with  QueryOfQuery and I faced one situation where I got stucked for few hour . After few Googling I found the silly mistake I was making.

I am just trying to generate the same situation with some sample code below.

<cfset local.qryGetArtists = queryNew("") />
<cfset local.qryGetSelctedArtist = queryNew("") />

<cfquery name="local.qryGetArtists" datasource="cfartgallery">
<cfdump var="#local.qryGetArtists#">

<cfquery name="local.qryGetSelctedArtist" dbtype="query">
    SELECT * FROM local.qryGetArtists WHERE LOWER(LASTNAME) LIKE '%#lCase("Buntel")#%'
<cfdump var="#local.qryGetSelctedArtist#">

In this code, the first dump give the query Object which contains the list of artist details and after that I am just filtering that query object using Query Of Queries(QoQ) and dumping that result.

For the second dump, I got one big error message:

"Query Of Queries syntax error. Encountered "local"

Where and Why We Got This Error?
The error is due to the local scope as per the error message then why this error. In ColdFusion there are some reserved keywords are there and we can't use that reserve keyword  inside Query Of Queries directly.

This is also mentioned in the ColdFusion Documentation here.

How To Solve This Issue?

The solution is escape the reserve keyword like this:

"SELECT * FROM [local].qryGetArtists WHERE LOWER(LASTNAME) LIKE '%#lCase("Buntel")#%'"

So, the final Code for the Query Of Queries will be like below.

<cfquery name="local.qryGetSelctedArtist" dbtype="query">
    SELECT * FROM [local].qryGetArtists WHERE LOWER(LASTNAME) LIKE '%#lCase("Buntel")#%'
<cfdump var="#local.qryGetSelctedArtist#">

For more details about Query Of Queries go to the ColdFusion live document. (ColdFusion Query Of Queries)

Friday, June 08, 2012

Extract Tar File In ColdFusion

In ColdFusion it doesn't have any built in function to extract a ".tar" or any ".gz" Compression. For ".gz" compression I have already posted a tip. Now, I am just going to give show you a ColdFusion function using which can be used to extract tar files. This function uses Apache java library to extract the ".tar" file.
Lets start:

    @inTarFilePath = input tar file absolute path
    @outExtractPath = The out put directory to which the files will be extract.
    tarExtract("D:\Temp\pics-leaserental-20120530.tar", "D:\Temp\TarResult\");
    function tarExtract(inTarFilePath, outExtractPath)
        var fileInStream = createObject("java", "");
        var fileOutStream = createObject("java", "");
        var tarInStream = createObject("java", "");
        var tarEntry = createObject("java", "");
        var destFileName = "";


            //Read tar stream
            tarEntry = tarInStream.getNextEntry();

            //Loop each tar entry and write in the specific directory
            while(! isNull(tarEntry)){
                destFileName = arguments.outExtractPath & '/' & tarEntry.getName();

                //If the tar entry is not a directory(means it is a file) then write write that in a file
                if(! tarEntry.isDirectory()){
                tarEntry = tarInStream.getNextEntry();


            //Close all opened file streams

            return true;
        } catch(Any e){
            return false;

Hope it will help you in sometime...

Friday, May 04, 2012

Conditionally Change the Color Of a Cell Text In cfgrid

This topic consists of three parts

1. Grid display page.
2. ColdFusion component and function to bind the grid.
3. JavaScript for changing the color of specific grid Cell.

1. cfgridDemo.cfm(Grid Display Page)

        <script type="text/javascript" src="./cfgridDemo.js"></script>
            <!-- This is grid display Order information of a online Shop. orderID, Order Date, Customer Name, Order Status
                   The order status can be complete, pending, Shipped, etc.Depending on the order status the color of the status text will change
        <cfform name="displayGridForm" format="html">
            <cfgrid format="html" name="displayGrid" autoWidth="true" pagesize="50" selectmode="row" bind="cfc:testCode.cfgridDemo.getGridData({cfgridpagesize},{cfgridpage},{cfgridsortcolumn},{cfgridsortdirection})" sort="true">
                <cfgridcolumn name="ORDERID"            width="150"        header="Order ID"    headerbold="true" />
                <cfgridcolumn name="ORDERDATE"        width="100"        header="Order Date"    headerbold="true"  type="date" />
                <cfgridcolumn name="CUSTOMERFIRSTNAME"    width="150"        header="Customer First Name"    headerbold="true" />
                <cfgridcolumn name="CUSTOMERLASTNAME"        width="150"     header="Customer Last Name"    headerbold="true" />
                <cfgridcolumn name="ORDERSTATUSID"    width="100"        header="Order Status ID"        headerbold="true" />
                <cfgridcolumn name="STATUS"        width="100"        header="Status"        headerbold="true" />
        <cfset ajaxOnLoad("init") />

2. cfgridDemo.cfc(ColdFusion component and function to bind the grid)

    <cffunction name="getGridData" access="remote" returntype="Struct" output="false">
        <cfargument name="pageSize" required="false" default="30" hint="No of records to display in each page of cfgrid" />
        <cfargument name="pageNo" required="false" default="1" hint="Current page no of cfgrid which you want to view" />
        <cfargument name="sortColumnName" required="false" default="ORDERID" hint="Default sort column for query sorting" />
        <cfargument name="sortDirection" required="false" default="ASC" hint="Default query sort direction" />
        <cfset variables.qryGetMedia = queryNew("") />
        <!--- Default Sort Coulmn name if the sortColumn contains empty strings --->
        <cfif len(arguments.sortColumnName)>
            <cfset variables.sortColumnName = arguments.sortColumnName />
            <cfset variables.sortColumnName = "ORDERID" />
        <!--- Default Sort direction if the sort direction contains empty string --->
        <cfif len(arguments.sortDirection)>
            <cfset variables.sortDirection = arguments.sortDirection />
            <cfset variables.sortDirection = "ASC" />
        <!--- Here I have used the dafualt datasource created during ColdFusion installation.
            So you can run the code directly. --->
        <cfquery datasource="cfartgallery" name="variables.qryGetMedia">
            FROM ORDERS
            ORDER BY #variables.sortColumnName# #variables.sortDirection#
        <!--- Convert the query Object into cfgrid compatible structure --->
        <cfreturn queryConvertForGrid(variables.qryGetMedia, arguments.pageNo, arguments.pageSize) />

3. cfgridDemo.js(JavaScript for changing the color of specific grid Cell.)

var init = function(){
    //get the grid Object
    grid = ColdFusion.Grid.getGridObject('displayGrid');
    //get grid Column Model
    var gridCM = grid.getColumnModel();
    //Call the color renderer function to render the color
    gridCM.setRenderer(gridCM.getIndexById('STATUS'), colorRenderer);

//Function to color renderer
function colorRenderer(value)
    if( > -1)
        return '<b style="color:#00FF00;">' + value + '</b>';
    else if( > -1)
        return '<b style="color:#FF0000;">' + value + '</b>';
    else if( > -1) 
        return '<b style="color:#00FFFF;">' + value + '</b>';
    else if( > -1) 
        return '<b style="color:#0000FF;">' + value + '</b>';
        return value;

After all these steps if we will run cfgridDemo.cfm we will get the following out put. We can also change the display style by changing the JavaScript as I have done.

Other Grid related topics:
1. Starting with CFGRID( part - 1 )
2. Starting with CFGRID( part - 2 )(Auto Refreshing CFGRID)
3. Export cfgrid Data or Table Data in Excel, Pdf and CSV Format(ColdFusion - 9)
4. Search Functionality in CFGRID

Friday, April 27, 2012

Unzip a ".gz" file in ColdFusion

Below is the code for ColdFusion function to unzip a ".gz" file. The code describes each logic with comment line. Hope it will not create any trouble for understanding.
    function unzipGZ(inputFilePath)
        var returnString = "";
        var outFileName = "";
        var outPath = GetDirectoryFromPath(inputFilePath);
        var inputFileName = getFileFromPath(arguments.inputFilePath);
        var buffer = repeatString(" ",1024).getBytes(); //Create a buffer of 1024 bytes
        var bufferLen = 0;
        var inStream = createObject("java", "");
        var outStream = createObject("java", "");
        var gzInStream = createObject("java", "");
        //OutPut File Name
        outFileName = left(inputFileName, (len(inputFileName) - 3));
            //File UnZip Operation
            outStream.init(outPath & outFileName);
            //Read the file stream into buffer and write into out put file
                bufferLen =, 0, 1024);
                if( bufferLen != -1 )
                    outStream.write(buffer, 0, bufferLen);
            } while(bufferLen != -1);
            //Store the OutPut File Path in the function return string
            returnString = outPath & outFileName;
        } catch(Any e){
            //Store the error message in the return string
            returnString = e.message & "Details: #e.Detail#";
        } finally{
                //Close all Opened file Streams
            }catch(Any e){}
        return returnString;
   request.fileAfterUnZip = unzipGZ("D:\YMLDP_Data\Temp\listings-leaserental.txt.gz");

Wednesday, April 25, 2012

Regular Expression To Replace All Comma(,) Present Outside Double Quotes by Pipe(|)

While parsing CSV file many times we need to replace the comma outside the double quotes by some other characters like pipe(|).

We can do that by using regular expression in a very simple way.

Lets see some example:

Input String:       Japan,"Washington, DC,Prabhu,aju",New York,"Beijing, shanghai",Tokyo,Delhi
Out Put String:   Japan|"Washington, DC,Prabhu,aju"|New York|"Beijing, shanghai"|Tokyo|Delhi

Input String:       "abc,def","xyz,",",def",""
Out put String:   "abc,def"|"xyz,"|",def"|""

If we will do this by JavaScript then:

Use the Regular Expression: ",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)"

<script type="text/javascript">
    var inputStr = "";//Your String
    var result = Regex.Replace(inputStr, ",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)","|");//Resulted String

This produce the string with all comma(,) present out side the double quote will be replaced by pipe(|).

This question is answered at this :

Hope it will save your ...

Tuesday, April 24, 2012

Filtering CFZIP file extraction Operation

To extract a zip file in ColdFusion we have a wonderful tag "cfzip". By, using which we can list the files available in that zip or we can give password for password encrypted zip  to extract all files.

Sometimes we need to extract only 1/2 files from the zip bundles then how can we extract only the required files using cfzip.

<cfzip action="unzip" file="#local.inFilePath#" destination="#local.outputPath#" recurse="true" filter="" overwrite="true">

file: Takes the input zip file.
destination: It's the destination directory in which you want to extract the files.
recurse: Specifies whether action applies to sub directories in the zip bundle.
overwrite: If a file exists with the same name in the destination directory then it will overwrite.
filter:Filter the files which you need to extract.

Case 1: Extract All text files from the zip bundle

filter = "*.txt";

Case 2: Extract a specific file(xyz.jpg) from the zip bundle 

filter = "xyz.jpg";

Case 3: Extract all files whose file name contains string "listing"

filter = "*listing*.txt"

Case 4: Extract more than one files with specific file names

filter = "abc.txt|xyz.txt". It will extract only abc.txt and xyz.txt

The filter is applicable to the following actions of "cfzip"

1. delete
2. list
3. unzip
4. zip

Hope it will help you...

Thursday, April 19, 2012 peer not authenticated. PKIX path building failed: unable to find valid certification path to requested target

Few days back I have worked in one payment gateway integration project in ColdFusion 9 and we have delivered that successfully but after 8 months the client called us and said that there is some issue in the Payment gateway and he has not changed a single line of code. He sent us the following error message:

" PKIX path building failed: unable to find valid certification path to requested target".

After some research I found that the issue was due to the SSL validation error in the web service call of the Payment gateway:

These are the steps which I followed to recover from that issue:

  1. Browse the SSL enabled url(wsdl url from web service) from the FireFox.
  2. Click the extreme left of your browser URL address bar to view the SSL certificate.As shown below.     
  3. Click on "More Information" button as shown below.                                                                          
  4. Click on "View Certificate" button as shown below.                                                                            
  5. Click on "export" button as shown below.
  7. Save the file in some location then change the extension of the file to ".cer" from any other extension.
  8. Copy the file into “{ColdFusion-Root}\runtime\jre\lib\security” .
  9. Open your command prompt then go to "{ColdFusion-Root}\runtime\jre\lib\security".
  10. Run the following command:
  11. "keytool -import -keystore cacerts -alias <any Unique Name> -file <fileName>.cer"
  12. Enter the password: "changeit"(This is the default password and it will not be visible to the user while typing)
  13. Then you will get one confirm message in command prompt type "Yes".
  14. After that you will get one message :"Certificate was added to keystore".

After the above steps restart your ColdFusion Server. Then the web service will work.