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.
<cfscript>
    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", "java.io.FileInputStream");
        var outStream = createObject("java", "java.io.FileOutputStream");
        var gzInStream = createObject("java", "java.util.zip.GZIPInputStream");
        
        //OutPut File Name
        outFileName = left(inputFileName, (len(inputFileName) - 3));
        
        try{
            
            //File UnZip Operation
            inStream.init(inputFilePath);
            gzInStream.init(inStream);
            outStream.init(outPath & outFileName);
            
            //Read the file stream into buffer and write into out put file
            do{
                bufferLen = gzInStream.read(buffer, 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){
            WriteDump(e);abort;
            
            //Store the error message in the return string
            returnString = e.message & "Details: #e.Detail#";
        } finally{
            try{
                //Close all Opened file Streams
                outStream.close();
                gzInStream.close();
                inStream.close();
            }catch(Any e){}
        }
        
        return returnString;
    }
    
   request.fileAfterUnZip = unzipGZ("D:\YMLDP_Data\Temp\listings-leaserental.txt.gz");
   WriteDump(request.fileAfterUnZip);
</cfscript>

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
</script>

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

This question is answered at this :

http://www.mindfirelabs.com/forum/viewtopic.php?f=13&t=481


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="#local.fileList.name#" overwrite="true">
 </cfzip>

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

javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated.
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: 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:

"javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: 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.
  6.  
  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.

Wednesday, April 04, 2012

Working with .net dll Object in ColdFusion

Usually in a ColdFusion Application we do all the logic implementation using ColdFusion. There is no need of any other server side language. But sometimes we need to access the library created by some other languages like .net, java etc . ColdFusion runs on java platform so there is no issue in consuming the java library. The question here is how we can use the .net library.

The answer is by creating a "dll" in .net. Then ColdFusion will access the methods of the dll file by creating Object of that dll.

Example:
Now, I am going to create a Calculator library in .net(a dll file) which will have two methods addition and subtraction using the following .net code.

using System;
namespace Calculator
{
    public class Calculator
    {
        public int addition(int a, int b)
        {
            return a + b;
        }

        public int subtraction(int a, int b)
        {
            return a - b;
        }
    }
}


Then, I wrote the following lines of ColdFusion code to create object of that ".dll" file.

 <cfscript>
   variables.dotNetObject = createObject("dotnet", "Calculator", "#expandPath('./Calculator.dll')#").init();
   WriteDump(variables.dotNetObject);
</cfscript>

But, I got the one error message:

"DotNet Side does not seem to be running. Ensure that the DotNet agent is running and you have provided the correct host and port information "



Solution:

1. Go to the window services viewer and see whether  "ColdFusion  .NET Service" service is running or not. If not running then start the service. If the service is not Present then go to step 3.
2. After that check whether the code is again throwing the same error or not.
3. If it again throwing the same error then go to "http://help.adobe.com/en_US/ColdFusion/9.0/Installing/WSc3ff6d0ea77859461172e0811cdec18969-7ff1.html" and follow the instructions to reinstall/install the ColdFusion .net Service.

After, following  all the instructions and reinstalling the ColdFusion .net Service I again run the code. I got the following error:

"Class Calculator not found in the specified assembly list.The assembly that contains the class must be provided to the assembly attribute. "



Solution:-

In the above ColdFusion code, in the function createObject we are passing the class name as "Calculator" in the argument. Our class name in the above .net code is aslo "Calculator". Then what is the cause of the problem???

While creating a .net class we have to specify the name space of that class, if you are not specifying the name space then the Project will be taken as the default name space.
So, in the .net code our name space will be "" and during accesing the class we must have to sppecify the name space like this:"<name-space>.<class>".
In ColdFusion code instead of passing "Calculator" we have to pass "Calculator.Calculator". The out put of the Dump will be as follow:



The dump shows the object have two function addition and subtraction. Now, we can perform the operation like general ColdFusion Object.

NOTE: If you want to download the "Calculator.dll" then you can download it from this url:

https://docs.google.com/open?id=0B2GDR5_Jv000NUR2ZXMxeWhTbm0yQWZ0NUozVjRkZw



Followers