Showing posts with label cf. Show all posts
Showing posts with label cf. Show all posts

28 April 2013

Building a CF SOAP Webservice


I recently needed to create a web service which pleased me as its very easy with coldFusion.


Although, that said, one thing that has often puzzled me is the Application.cfc and the cfc initialization. You probably wouldn’t want to use your normal Application.cfc as it’s likely a bit excessive. To my mind webservice requests could take place weeks apart, or just minutes and should be lightening fast, so a very lightweight initialization process would be ideal.

Lets assume a very basic webservice.cfc:


<cfcomponent output="false">
    
    <cffunction name="getUsers" access="remote" returnType="query" output="false" hint="I get some users">
        <cfreturn application.oUsers.getUsers() />
    </cffunction>
    
</cfcomponent>

So oUsers is our DAO or Business object which we use in our application. Normally it would be passed in with an init method, but with a webservice we don’t have the same concept of init’ing objects. So how does one go about initializing our DAO? In the past I’ve seen many takes on this. I’ve seen:

In the method:
<cffunction ...>
    <cfset var oUsers = createObject(...)>
    <cfreturn var oUsers.getUsers()>

In the actual webservice.cfc, scoping it this/variables/application
<cfcomponent output="false">
    <cfset variables.oUsers = createObject(...)>
    <cffunction ...


Both of the above involve the dao cfc being re-created on every web-service request. Not exactly ideal in terms of performance.

So I think the best idea I’ve seen so far is create an application.cfc like so:


<cfcomponent output="false">
    <cfset this.strDsn            = "mydsn" />
    
    <cffunction name="onApplicationStart" access="public" returnType="boolean" output="false">
        <cfset application.oUsers    = createObject("component","usersDao").init(strDsn    = this.strDsn) />
        <cfreturn true />
    </cffunction>
    
</cfcomponent>


This gives a lightweight application scope in which we can initialize our object and then call throughout our webservices! Excellent!

If you’ve got any suggestions on how to improve this, please feel free to comment.

05 February 2013

Checking the hash of a file

You know when you download a file and you're informed what the hash is, so you can verify your download? We'll I've often seen that and have a working knowledge of hash functions but have never bothered to try it.

Anyway, I thought I'd give it a go, and I'm pleased to say its incredibly easy if you have a CF server kicking around:

<cffile action="read" file="#form.fileupload#" variable="variables.myFile" />
<cfoutput>#hash(variables.myFile,"#form.sel_hash#")#</cfoutput>


Here's a slightly more completed code fragment if it helps:
<div class="jumbotron">
    <h1>Hash Your File!</h1>
    <cfif structKeyExists(form, "fileupload")>
        <cffile action="read" file="#form.fileupload#" variable="variables.myFile" />
        <p class="alert alert-info"><cfoutput>#hash(variables.myFile,"#form.sel_hash#")#</cfoutput></p>
    <cfelse>
        <p class="lead">I help you calculate the hash of a file</p>
    </cfif>
    <form class=".form-horizontal" method="POST" enctype="multipart/form-data" action="test3.cfm">
        <select name="sel_hash">
            <option value="MD5">MD5</option>
            <option value="SHA">SHA</option>
            <option value="SHA-256">SHA-256</option>
            <option value="SHA-384">SHA-384</option>
            <option value="SHA-512">SHA-512</option>
        </select>
        <br />
        <div class="fileinputs">
            <input name="fileupload" type="file" />
        </div>
        
        <br /><br />
        <button type="submit" class="btn btn-primary">Submit</button>
    </form>
</div><!-- /jumbotron -->

25 October 2012

Hamlet’s Monkey - Code for fun :)

Hamlet’s Monkey

We’ve all heard the jokes before that a monkey could do that job, or a monkey could type better than you. You may have even heard of the Infinite Monkey Theorem, well its something that made me laugh and an interesting programmatic problem:

http://en.wikipedia.org/wiki/Infinite_monkey_theorem

Given infinite time, could a monkey actually type out the works of William Shakespeare? Well I decided the complete works was a bit hard on our poor monkey. Lets start with just Hamlet!

A friend at work and I got to talking, how would we approach this programmatically? How would the monkey actually get on?
So it occurred to me there are two way of approaching this, the easy way and the hard way.

A few notes

  • My random character generator just generates A-Z
  • Case is just not fair, so I’ve made all strings lowercase
  • I’ve removed all punctuation

Green Light

I called it this because as soon as the monkey guesses a letter correctly, he gets a green light and moves onto the next letter. The correct letter is “banked” and he never has to start over. The hard bit here was really only how to progress, should we be removing the last letter added or just moving on?

Pastebin
<!--- Static Variables --->
<cfset variables.lstAlphabet         = "ABCDEFGHIJKLMNOPQRSTUVWXYZ">
<cfset variables.intNumLoops        = 100>
<cfset variables.Shakespeare        = "All your base are belong to me">

<cffunction name="generateRandomLetter" access="public" returntype="string" output="false">
    <cfset var strLowerCaseAlpha = "abcdefghijklmnopqrstuvwxyz">
    <cfreturn Mid(strLowerCaseAlpha,RandRange( 1, Len( strLowerCaseAlpha ) ),1)>
</cffunction>

<cfscript>
    variables.intCount                 = 0;
    variables.bProgress                = true;
    variables.strSubString            = "";
    variables.strShakespeare        = lcase(variables.Shakespeare.replaceAll("[^a-zA-Z]", "")); //Shakespeare without spaces etc
    variables.stuJson                = {};
    variables.strMonkeyString        = "";

    while (variables.intCount < variables.intNumLoops) {
        variables.intCount++;
        
        if(variables.bProgress EQ true){
            //we're adding a new letter
            variables.strMonkeyString    =    variables.strMonkeyString & generateRandomLetter();
        }else if(len(variables.strMonkeyString) EQ 1){
            //monkey string is just 1 char, just re-guess
            variables.strMonkeyString    =    generateRandomLetter();
        }else{
            //we're re-guessing the last letter, so we need to remove it, then add a new one.
            variables.strMonkeyString    =    left(variables.strMonkeyString,len(variables.strMonkeyString)-1) & generateRandomLetter();
        }
        
        //what we're expecting so far
        variables.strSubString    =    left(variables.strShakespeare,len(variables.strMonkeyString));

        //Did monkey do it?
        if(variables.strMonkeyString EQ variables.strSubString){
            if(variables.strMonkeyString EQ variables.strShakespeare){
                //100%
                customOutput("**WINNER**: " & variables.strMonkeyString);
                break;
            }else{
                //Good so far, progress to next letter
                variables.bProgress    =    true;
            }
        }else{
            variables.bProgress    =    false;
        }
    }
    
    writeoutput(variables.intCount);
    writeoutput("<br />");
    writeoutput(left(variables.strMonkeyString,len(variables.strMonkeyString)-1));
</cfscript>

Red Light

This is the hard way, the monkey has to get every letter of Hamlet correct and sequentially. If he makes a mistake, he starts from the beginning. I think this is the way the theorem is intended, but it probably won’t result in much success for the poor monkey! The code is actually pretty simple.

Pastebin
<!--- Static Variables --->
<cfset variables.lstAlphabet         = "ABCDEFGHIJKLMNOPQRSTUVWXYZ">
<cfset variables.intNumLoops        = 500>
<cfset variables.Shakespeare        = "All your base are belong to me">

<cffunction name="generateRandomLetter" access="public" returntype="string" output="false">
    <cfset var strLowerCaseAlpha = "abcdefghijklmnopqrstuvwxyz">
    <cfreturn Mid(strLowerCaseAlpha,RandRange( 1, Len( strLowerCaseAlpha ) ),1)>
</cffunction>

<cfscript>
    variables.intCount                 = 0;
    variables.strSubString            = "";
    variables.strShakespeare        = lcase(variables.Shakespeare.replaceAll("[^a-zA-Z]", "")); //Shakespeare without spaces etc
    variables.strMonkeyString        = "";
    variables.strBestSoFar            = "";
    
    while (variables.intCount LT variables.intNumLoops) {
        variables.intCount++;
        
        //generate the random guess, one keystroke at a time
        variables.strMonkeyString    = variables.strMonkeyString & generateRandomLetter();
        
        variables.strSubString        = left(variables.strShakespeare,len(variables.strMonkeyString));
        
        //check if we have a match
        if(variables.strMonkeyString EQ variables.strSubString){
            if(len(variables.strSubString) GT len(variables.strBestSoFar)){
                variables.strBestSoFar    =    variables.strSubString;
            }
        }else{
            variables.strMonkeyString    = "";
        }
    }
    
    writeoutput(variables.intCount);
    writeoutput("<br />");
    writeoutput(variables.strBestSoFar);
</cfscript>

Critisicm, comments and feedback welcome, but just a bit of fun.

13 July 2012

13 May 2012

ColdFusion Railo deployment with Jelastic

I thought I'd try one of the cloud java hosting platforms out there and I must say I'm delighted I did. I wanted to start up a Jelastic instance and throw Railo on it and see how it worked out.

First up sign in is super simple, just your email and thats all you need. The user interface is clean, powerful and incredibly simple. With simple drop downs to create your environment and configure the number of instances etc that you need. In just a few minutes you can be up and running.
So i chose Tomcat 6. I did initally try Tomcat 7 but apparently they have a few problems with 7 at the moment. Not to worry 6 is fine. Deploy your environment and then wait for it to be deployed. This takes just a minute or so while they build your instance.

Then down at the bottom you'll see the deployment manager tab, under that you should see upload. You'll need to upload your Railo.war you can upload one you've downloaded, or I believe, upload direct from www.getrailo.org:

Once you've uploaded the .war file, you need to deploy it. Simple, still in the deployment manager tab, click on the box dropdown and click deploy. It'll ask you to confirm "ROOT" as the context, but root is fine. Once this is done you should be able to click the "launch in browser" button and see the railo admin show.

That's it, you're basically done. I expect you want your own application to run, but that's just as easy. If you click on the spanner / config option next to Tomcat 6 a settings tab will open and you can tweak the tomcat settings. Expand webapps and root. This is your application home, you can delete everything in there except for the WEB-INF folder. Then upload your cfm files and you're done!

I think this is a brilliant hosting environment and so brethlessly simple I'm very impressed.

08 March 2012

Setup an AWS EC2 Instance Running Railo

Setup an AWS EC2 Instance Running Railo

OK so you want to delve deep into cloud computing and start your own instance Amazon Web Services (AWS) Elastic Cloud Compute (EC2) instance? Sadly the “official” Railo AMI seems to have died, so here we’ll be starting our own new one. We’ll be running firmly within the free criteria here and choosing options appropriately, most significantly this means linux! We’ll also be using putty to connect to our instance. For part of this tutorial we’re going to be running alongside the official Amazon starting an instance guide. So I will skimp on the details already covered by Amazon themselves:

http://docs.amazonwebservices.com/AWSEC2/latest/GettingStartedGuide/GetStartedLinux.html

Start-up an Instance

  1. Click the giant “Launch an Instance” button. Select Basic Amazon Linux AMI I choose 32bit because it’s cheaper and (at the moment) free.
  2. Ensure you’ve selected a micro instance.
  3. Skip the instance details section, just accepting the defaults.
  4. Create and download a Key Pair. This is important as it allows us to log onto our instance securely.
  5. Next is the firewall or security groups section. This bit is important as it configures what applications and ports are allowed to access your instance. Create a new security group. You should select SSH and HTTP as a minimum, you can accept the default of 0.0.0.0 but that allows any IP access to these ports. This is fine for HTTP but if your ISP has given you a static IP then put this in for SSH.
  6. Done, your instance will begin powering up. Watch the instances dashboard to see it’s status, eventually the status will flick to green, display “running” and the status checks will show 2/2. Once that happens we’re ready to logon.


Connect to your instance
I’m going to leave this bit a little to Amazon to explain. You’ll need to download and install putty and convert your key pair file (from step 4 above) into a putty private key file. Then grab your amazon public dns value (something like ec2-11-11-111-111.compute-1.amazonaws.com) and connect to it using putty. Don’t forget to enter the username ec2-user.

Get Linux straight & Install Railo

  1. First lets get Linux to update itself:
sudo yum update
  1. Download Railo to the instance:
wget http://www.getrailo.org/down.cfm?item=/railo/remote/download/3.3.1.000/tomcat/linux/railo-3.3.1.000-pl1-linux-installer.run
  1. Assign permissions
sudo chmod 777 railo-3.3.1.000-pl1-linux-installer.run
  1. Run Railo
sudo ./railo-3.3.1.000-pl1-linux-installer.run

Here you’ll want to accept all the defaults except three. First change the default password to something good. Second you should set the port to 80 (not 8888). This will allow normal connections to your server and links into why we had to allow HTTP (port 80) in the EC2 security group. Lastly you should say no to the apache connectors. This sets up railo with tomcat and installs tomcat for you. Of course if you’re more familiar with apache then go with that.

Hit your url
http://ec2-11-11-111-111.compute-1.amazonaws.com
The above link (customized for your public DNS) should show you the default Railo welcome page.

Use putty and VI to change your cfm files
  1. Navigate to the webroot:
cd /opt/railo/tomcat/webapps/ROOT/
  1. Remove all these files
sudo rm -rf *
  1. Create a new index.cfm file
sudo vi index.cfm
VI - Linux editor
  1. In vi to delete the contents of the whole file type
  2. :1,$d
  3. To swap between command and insert modes just press escape

  4. To exit without saving, switch to command mode and press
  5. :q!
  6. To exit and save switch to command mode and press
  7. :x

09 February 2012

ColdFusion and Amazon AWS SES - Simple Email Service

Amazon Web Services (AWS) have a service called Simple Email Service (SES), SES is an excellent e-mail sending service for businesses and developers. It enables developers to quickly and easily send emails without having to go through the pains of setting up an SMTP server or any of that nonsense. It is intended for bulk sending marketing material, but you can also use it in very low volumes and it becomes a great tool.

To demonstrate the service, we’re going to use SES to send an email to ourselves using coldFusion. First and foremost you’ll need to sign up to SES (https://aws.amazon.com/ses/) and verify an email address. SES starts up in “development mode” where you have to verify every email address you want to send mail too. This is a fantastic feature that prevents accidental sending of email and lets you test out the functionality. For the purpose of this example development mode is perfect, so sign up and verify your own email address.

There are quite a few ways to get SES to send an email for you, we’re going to use what I think is the easiest to get started with, a POST request. It’s basically just liked submitting a form, but we’re going to use cfhttp to mimic a form post. First though, there’s a few things we need to setup before we actually do any coding.

1) Security details
Obviously it would be a pretty crummy service if anyone could use your email service to send emails to anyone, spam would run rampant! So there a few security details we need to get from amazon to authenticate each SES request. I won’t go into too much detail but you’ll need an “Access Key ID” and a “Secret Access Key”. You get these from amazon by logging into your aws account and clicking security credentials from the top right drop down. Look at this page for a bit more info:
http://docs.amazonwebservices.com/ses/latest/DeveloperGuide/QueryInterface.Authentication.html#QueryInterface.Authentication.Signatures

2) HMAC - Hash-based Message Authentication Code
http://en.wikipedia.org/wiki/HMAC
To authenticate our message Amazon requires use of a security algorithm called HMAC. The theory being if we (us and Amazon) have a shared private key, we can encrypt a known variable and authenticate ourselves. This is a very very brief introduction if you’ve never come across HMAC. HMAC is a cryptography method of creating a hash using a secret key. Normally a hash takes any value and creates a fixed length string. For example, using the MD5 hash in CF:


 hash(‘all your base are belong to us’)  
would return
847DBEB849668D30722D8A67BCED1C59

With HMAC we introduce a secret key to add an extended element of cryptography and security to the proceedings. Here’s an example:
 

 toString(toBase64(HMAC_SHA1('password','all your base are belong to us')))  
z0A498Rx0aNzXNOwfbjSKkhBdbA=

HMAC can use MD5 or SHA1 and Amazon does support both, but we’re going to use SHA1. Now coldFusion doesn’t offer the HMAC function by default, but that’s not to say we can’t write or borrow our own..



 <cffunction name="HMAC_SHA1" returntype="binary" access="public" output="false" hint="I create an HMAC hashed string from a given message and secret key.">  
      <cfargument name="signKey" type="string" required="true" hint="Secret key with which to encrypt message" />  
      <cfargument name="signMessage" type="string" required="true" hint="Message you want to hash"/>  
      <cfset var jMsg = JavaCast("string",arguments.signMessage).getBytes("iso-8859-1") />  
      <cfset var jKey = JavaCast("string",arguments.signKey).getBytes("iso-8859-1") />  
      <cfset var key = createObject("java","javax.crypto.spec.SecretKeySpec") />  
      <cfset var mac = createObject("java","javax.crypto.Mac") />  
      <cfset key = key.init(jKey,"HmacSHA1") />  
      <cfset mac = mac.getInstance(key.getAlgorithm()) />  
      <cfset mac.init(key) />  
      <cfset mac.update(jMsg) />  
      <cfreturn mac.doFinal() />  
 </cffunction>  

3) Create your Amazon authenticated header

Next we want to create our HMAC hash to pass to Amazon, they require us to encrypt the date and time, so to do so looks a little like this:
 <cfset variables.dteOldDate = now() />  
 <cfset variables.strDateString = "#DateFormat(variables.dteOldDate, 'ddd, dd mmm yyyy')# #timeFormat(variables.dteOldDate,'HH:mm:ss')# GMT" />  
 <!--- encrypt date --->  
 <cfset variables.xxxHMac = toString(toBase64(HMAC_SHA1(“yoursecretaccesskeygoeshere”,variables.strDateString))) />  

Next we need to integrate our hashed date with a header called a X-Amzn-Authorization

 <cfset variables.strAmazonHeader = "AWS3-HTTPS AWSAccessKeyId=#youraccesskeyidgoeshere#, Algorithm=HmacSHA1, Signature=#xxxHMac#" />  

So obviously replace youraccesskeyidgoeshere with the Access Key you got from Amazon.


4) Make the httpd call

That’s the complicated bit done, now all we have to do is make the cfhttpd call.

 <cfhttp url="https://email.us-east-1.amazonaws.com/" method="post" result="result">  
      <cfhttpparam type="header"       name="X-Amzn-Authorization" value="#variables.strAmazonHeader#" />  
      <cfhttpparam type="header"       name="Date" value="#variables.strDateString#" />  
      <cfhttpparam type="formfield"      name="Action" value="SendEmail" />  
      <cfhttpparam type="formfield"      name="Destination.ToAddresses.member.1" value="#yourToEmailAddressGoesHere#" />  
      <cfhttpparam type="formfield"      name="Message.Body.Text.Data" value="#yourEmailContentGoesHere#" />  
      <cfhttpparam type="formfield"      name="Message.Subject.Data" value="#yourEmailSubjectGoesHere#" />  
      <cfhttpparam type="formfield"      name="Source" value="yourFromEmailGoesHere" />  
 </cfhttp>   

That's it, run your code and you should receive an email!

24 September 2009

Open Blue Draggon and Google App Engine

Hey Guys,

Anyone following cloud computing and coldFusion should absolutely check out some amazing work by a friend of mine Paul Kukiel:

http://blog.kukiel.net/2009/09/coldfusion-on-google-app-engine-with.html

He's built on some great work Google / Blue Dragon have been doing with porting a basic cloud computing style java cf instance (open Blue Dragon) onto Google app engine. It looks like it's work in progress but it's super exciting to see.

You can even try it yourself, go on it's easier than you think!