I'm experiencing difficulties with a jwt token, turns out it's because coldfusion is converting an int to a float. I'm not sure where the problem is or how to fix it.
Token timestamp and expiration:
<cfset TimeStamp = '#VAL( int( getTickCount() / 1000 ) )#' >
<cfset Exp = '#VAL( int( (getTickCount() / 1000)+43200 ) )#' >
<cfscript>
Variables.payload = StructNew();
Variables.payload[ "nbf" ] = "#TimeStamp#";
Variables.payload[ "exp" ] = "#Exp#";
Variables.result = JWT.encode( payload, Variables.secretKey);
</cfscript>
The JWT.Encode call looks like this:
<cffunction name="encode" access="public" returntype="String">
<!--- ****************** Arguments ************************ --->
<cfargument name="payload" type="any" required="true">
<cfargument name="key" type="string" required="true">
<cfargument name="algo" type="string" required="false" default="HS256">
<!--- ****************** /Arguments *********************** --->
<!--- define our variables here --->
<cfset var currentTime = getCurrentUtcTime()>
<cfset var header = createObject("java", "java.util.LinkedHashMap").init() /> <!--- StructNew doesnt work because coldfusion 8 orders the keys --->
<cfset var claims = createObject("java", "java.util.LinkedHashMap").init() /> <!--- StructNew doesnt work because coldfusion 8 orders the keys --->
<cfset var segments = ArrayNew(1)>
<!---
creation of first segment of our JWT: the header
--->
<cfset header[ "typ" ] = "JWT">
<cfset header[ "alg" ] = "HS256">
<!--- add header an json with base64 encoding to segment array --->
<cfset arrayAppend( segments, replace( toBase64( serializeJSON( header ) ), "=", "", "all" ) )>
<!---
creation of the middle segment: the claims set
--->
<cfset claims = Arguments.payload>
<!---
escape forward slashes in generated JSON
--->
<cfset claimsJson = replace( serializeJSON( claims ), "/", "\/", "all" )>
<!--- add header and json with base64 encoding (with padding REMOVED!) to segment array --->
<cfset arrayAppend( segments, replace( toBase64( claimsJson ), "=", "", "all" ) )>
<!---
create the last segment: the signature
--->
<cfset signingInput = ArrayToList( segments, "." )>
<cfset signature = sign( signingInput, Arguments.key, Arguments.algo )>
<!---
add signature as last the element to our string
--->
<cfreturn ListAppend( signingInput, signature, ".")>
</cffunction>
Run through a base64 decoder, I get something like exp":1.498696809E9,"nbf":1.498653609E9
Get Nathan Mische's JSONUtil.cfc. Then replace the line
<cfset claimsJson = replace( serializeJSON( claims ), "/", "\/", "all" )>
with
<cfset jsonTool = createobject("component","jsonutil")>
<cfset claimsJson = replace(jsonTool.serializeJSON(claims,false,true), "/", "\/", "all" )>
Related
I have the following working Calendar page (lqCalendar.cfm) that places events from MySQL to the calendar.
<html>
<head>
<link rel="stylesheet" href="../fullcalendar-3.1.0/fullcalendar.min.css" />
<script src="../fullcalendar-3.1.0/lib/jquery.min.js"></script>
<script src="../fullcalendar-3.1.0/lib/moment.min.js"></script>
<script src="../fullcalendar-3.1.0/fullcalendar.min.js"></script>
<script>
$(document).ready(function() {
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
var calendar = $('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
selectable: true,
selectHelper: true,
select: function(start, end, allDay) {
var title = prompt('Event Title:');
if (title) {
calendar.fullCalendar('renderEvent',
{
title: title,
start: start,
end: end,
allDay: allDay
},
true // make the event "stick"
);
}
calendar.fullCalendar('unselect');
},
editable: true,
events: "getLeaveRequests.cfc?method=getMyData",
eventDrop: function(event, delta) {
alert(event.title + ' was moved ' + delta + ' days\n' +
'(should probably update your database)');
}
});
});
</script>
</head>
<body>
<div id='calendar'>
</div>
</body>
</html>
Here is my working CFC (getLeaveRequests.cfc) which queries the data:
<!--- Don't forget to VAR scope all local variables. --->
<cfset var getEvents = "">
<cfset var row = "">
<cfset var result = "">
<cfquery name="getEvents" datasource="care">
SELECT lqID AS id,
lqStartDate AS myStart,
lqEndDate AS myEnd,
CONCAT(lqUser, " (",lqTotalHours,") ", (COALESCE(lqDescription,'')),"") AS title
FROM tblleaverequest
</cfquery>
<cfset result = []>
<cfloop query="getEvents">
<!--- start new structure. must use array notation to preserve case of structure keys--->
<cfset row = {}>
<cfset eventurl ="leave_request_a01z.cfm?id=" & "id">
<cfset row["id"] = id>
<cfset row["title"] = title>
<cfset row["start"] = myStart>
<cfset row["end"] = myEnd>
<!--- append to results --->
<cfset arrayAppend(result, row)>
</cfloop>
<!--- convert to json --->
<cfreturn serializeJSON(result)>
<!---
<cfreturn getEvents>
--->
</cffunction>
</cfcomponent>
What is the best way to "color" the calendar items based on the value of "lqUser"?
- The colors can be dynamically assigned, or if needed, I can add a color field to the User table for each user, but how do I assign it to the FullCalendar?
Here is my updated CFC trying to get colors to work: (using code from "dwayne anderson" post on Raymond Camden site)
- I added a field to my User table called "category_id", then assigned values 1 thru 9 for colors.
The page gives me no errors, just a blank calendar?
<!--- Component to get all of the Leave Request Dates and place on FullCalendar page--->
<cfcomponent>
<cfsetting showDebugOutput='No'>
<cffunction name="getMyData" output="false" access="remote" returntype="any" returnformat="JSON">
<cfargument name="filter" type="string" required="no" default="">
<cfquery name="getallevents" datasource="care">
SELECT lqID AS id,
lqStartDate AS event_start_datetime,
lqEndDate AS event_end_datetime,
IF(category_id IS NULL, '1', category_id) AS color_id,
CONCAT(lqUser, " (",lqTotalHours,") ", (COALESCE(lqDescription,'')),"") AS title
FROM tblusers RIGHT OUTER JOIN tblleaverequest ON tblusers.username = tblleaverequest.lqUser
</cfquery>
<cfquery name="getallcolors" dbtype="query">
Select distinct color_id
from getallevents
</cfquery>
<cfset colorlist="red,green,blue,yellow,black,brown,aqua,orange,darkred">
<cfset colorpos=1>
<cfset colors = []>
<cfloop query = "getallcolors">
<cfset thecolor='#listgetat(colorlist,colorpos)#'>
<cfif colorpos eq listlen(colorlist)>
<cfset colorpos=0>
</cfif>
<cfset colorpos=colorpos+1>
<cfset colors[#color_id#] = thecolor>
</cfloop>
<cfset url.returnformat="json">
<cfset results = []>
<cfloop query = "getallevents">
<cfset eventurl ="eventdetails.cfm?id=" & "id">
<cfset eventcolor ="#colors[color_id]#">
<cfset s = structnew()>
<cfset s["id"] = id>
<cfset s["title"] = title>
<cfset s["start"] = getEpochTime(event_start_datetime)>
<cfset s["end"] = getEpochTime(event_end_datetime)>
<cfset s["url"] = eventurl>
<cfset s["color"] = eventcolor>
<cfset s["allDay"] = false>
<cfset arrayappend(results, s)>
</cfloop>
<cfreturn results>
</cffunction>
<cffunction access="private" name="getEpochTime" returntype="date">
<cfargument name="thedatetime" type="date"/>
<cfif (ArrayLen(Arguments) is 0)>
<cfset thedatetime = Now() />
<cfelseif IsDate(Arguments[1])>
<cfset thedatetime=Arguments[1] />
<cfelse>
return NULL;
</cfif>
<cfreturn DateDiff("s", DateConvert("utc2Local", "January 1 1970 00:00"), thedatetime) />
</cffunction>
</cfcomponent>
What is the best way to "color" the calendar items based on the value of "lqUser"?
You have two options if I am understanding this correctly.
You could set the color for the user in the query itself so its easier to manage at query level via case statments or any other logic
You could do div with classes for specific user or type of user.
HTH.
Got it working! Here is the final & working CFC that includes coloring the calendar events. Thanks for the help.
<!--- Component to get all of the Leave Request Dates and place on FullCalendar page--->
<cfcomponent>
<cfsetting showDebugOutput='No'>
<cffunction name="getMyData" output="false" access="remote" returntype="any" returnformat="JSON">
<cfargument name="filter" type="string" required="no" default="">
<!--- Don't forget to VAR scope all local variables. --->
<cfset var getEvents = "">
<cfset var row = "">
<cfset var result = "">
<cfset var getallcolors = "">
<!--- Query the Leave Requests table and get data for all employees --->
<cfquery name="getEvents" datasource="care">
SELECT lqID AS id,
lqStartDate AS myStart,
lqEndDate AS myEnd,
IF(category_id IS NULL, "", category_id) AS color_id,
CONCAT(lqUser, " (",lqTotalHours,") ", (COALESCE(lqDescription,'')),"") AS title
FROM tblusers RIGHT OUTER JOIN tblleaverequest ON tblusers.username = tblleaverequest.lqUser
</cfquery>
<!--- Do a Query of Queries to get all of the users color values --->
<cfquery name="getallcolors" dbtype="query">
Select distinct color_id
FROM getEvents
</cfquery>
<cfset result = []>
<!--- Assign colors to be used by the FullCalendar variable --->
<cfset colorlist="red,green,blue,black,gray,brown,orange,darkred,darkgreen,darkblue,darkgrey,purple,darkorange,">
<cfset colorpos=1>
<cfset colors = []>
<cfloop query = "getallcolors">
<cfset thecolor='#listgetat(colorlist,colorpos)#'>
<cfif colorpos eq listlen(colorlist)>
<cfset colorpos=0>
</cfif>
<cfset colorpos=colorpos+1>
<cfset colors[#color_id#] = thecolor>
</cfloop>
<cfloop query="getEvents">
<!--- start new structure. must use array notation to preserve case of structure keys--->
<cfset row = {}>
<cfset eventcolor ="#colors[color_id]#">
<cfset eventurl ="leave_request_a01z.cfm?id=" & "id">
<cfset row["id"] = id>
<cfset row["title"] = title>
<cfset row["start"] = myStart>
<cfset row["end"] = myEnd>
<cfset row["color"] = eventcolor>
<!--- append to results --->
<cfset arrayAppend(result, row)>
</cfloop>
<!--- convert to json --->
<cfreturn serializeJSON(result)>
<!---
<cfreturn getEvents>
--->
</cffunction>
</cfcomponent>
I am using the easySocket udf and code below to send a 2 byte header length of the actual message via tcp/ip. However the UTF-8 character (i.e ( ) (8D hex) is received as ? (3F hex)). I have used that following code that I have also checked on stackoverflow. Is there a way to send byte equivalent of the length so that there will be no character encoding involve? Thanks.
<cffunction name="easySocket" access="private" returntype="any" hint="Uses Java Sockets to connect to a remote socket over TCP/IP" output="false">
<cfargument name="host" type="string" required="yes" default="localhost" hint="Host to connect to and send the message">
<cfargument name="port" type="numeric" required="Yes" default="8080" hint="Port to connect to and send the message">
<cfargument name="message" type="string" required="yes" default="" hint="The message to transmit">
<cfset var result = "">
<cfset var socket = createObject( "java", "java.net.Socket" )>
<cfset var streamOut = "">
<cfset var output = "">
<cfset var input = "">
<cftry>
<cfset socket.init(arguments.host,arguments.port)>
<cfcatch type="Object">
<cfset result = "#cfcatch.Message#<br>Could not connected to host <strong>#arguments.host#</strong>, port <strong>#arguments.port#</strong>.">
<cfreturn result>
</cfcatch>
</cftry>
<cfif socket.isConnected()>
<cfset streamOut = socket.getOutputStream()>
<cfset output = createObject("java", "java.io.PrintWriter").init(streamOut)>
<cfset streamInput = socket.getInputStream()>
<cfset inputStreamReader= createObject( "java", "java.io.InputStreamReader").init(streamInput)>
<cfset input = createObject( "java", "java.io.BufferedReader").init(InputStreamReader)>
<cfset output.print(chr(1) & chr(141) & arguments.message)>
<cfset output.flush()>
<cfset result='Success: '& arguments.message >
<cfset socket.close()>
<cfelse>
<cfset result = "Could not connected to host <strong>#arguments.host#</strong>, port <strong>#arguments.port#</strong>.">
</cfif>
<cfreturn result>
</cffunction>
<cfset txt_msg ='<COS MSG_TYPE_ID="0100" MCC="5999" POS_ENTRY_MODE="012" POS_COND="00" CARD_NUMBER="6417801234567890" ACQUIRER_ID="00000002" TERMINAL_ID="CAL100 " PROC_CODE="300000" STAN="000129" RETRIEVAL_REFERENCE="330145181129" DATE_LOCAL_TRAN="1111" TIME_LOCAL_TRAN="173654" TRANSM_DATE_TIME="1111173654" CARD_ACPT_ID_CODE="TESTDTA" CARD_ACPT_NAME_LOC="TSTESTSTE" />'>
<cfoutput>#easySocket('172.16.0.23','9095',txt_msg)#</cfoutput>
According to the API, "... if you omit the encoding identifier, InputStreamReader and OutputStreamWriter rely on the default encoding." - which may not be "UTF-8". It is usually Cp1252 on windows machines. You can view the default by checking the system properties:
<cfset system = createObject("java", "java.lang.System")>
<cfset defaultEncoding = system.getProperty("file.encoding", "unknown")>
.. or the encoding of your PrintWriter:
<cfdump var="#output.getEncoding()#">
Anyway, try specifying the encoding explicitly when you create the output stream. That should fix the issue.
...
<cfset streamOut = socket.getOutputStream()>
<cfset writer = createObject("java", "java.io.OutputStreamWriter").init(streamOut, "UTF-8")>
<cfset output = createObject("java", "java.io.PrintWriter").init(writer)>
...
Can anyone help me by suggesting a function to extract a .7z file in ColdFusion? I use ColdFusion 10 and cfscript based code. Indeed we have the cfzip tag, but it only extracts .zip and .jar files.
You can use cfexecute, which unfortunately is not availble in cfscript, to execute the 7z extractor on your server and pass through the various commands to extract the file to a place of your choosing.
Luckily for you, it seems Raymond Camden has gone into it in some detail:
http://www.raymondcamden.com/index.cfm/2011/2/21/Working-with-RARs-in-ColdFusion
Function to unrar .rar file in given destination.. use cfexecute tag to run rar exe in command line
<cffunction name="Unrar" access="public" returnType="boolean" output="false">
<cfargument name="archivefile" type="string" required="true">
<cfargument name="destination" type="string" required="true">
<cfset var exeName = "">
<cfset var result = "">
<cfset var errorresult = "">
<cfif not fileExists(arguments.archivefile)>
<cfthrow message="Unable to work with #arguments.arvhiefile#, it does not exist.">
</cfif>
<cfif findnocase(".rar",arguments.archivefile)>
<cfset var exeName = expandpath("WinRAR\rar.exe")>
<cfset var args = []>
<cfif directoryExists(#arguments.destination#)>
<cfset args[1] = "x +o">
<cfelse>
<cfset directoryCreate(#arguments.destination#)>
<cfset args[1] = "x">
</cfif>
<cfset args[2] = arguments.archivefile>
<cfset args[3] = "#arguments.destination#">
</cfif>
<cfexecute name="#exeName#" arguments="#args#" variable="result" errorvariable="errorresult" timeout="99" />
<cfif findNoCase("OK All OK", result)>
<cfreturn true>
<cfelse>
<cfreturn false>
</cfif>
</cffunction>
Trying to display structExcelResult["strUrl"] created by the function on my .cfm page.
<cffunction name="getBuyerReport" output="false" access="public" returntype="struct">
<cfargument name="intRegionId" required="yes">
<cfargument name="intBuyerId" required="yes">
<cfargument name="intStage" required="yes">
<cfargument name="strSortField" required="yes">
<cfargument name="strSortDirection" required="yes">
<cfset var structExcelResult = StructNew()>
<cfset var qRead="" />
<cfquery name="qRead" datasource="#variables.dsn#">
SELECT CONVERT(varchar,t.RECEIVED_DATE,101) AS [Received Date]
, t.REQUISITION_NO AS [Requisition Number]
, t.REQUISITION_TITLE AS [Requisition Title]
, t.TECHNICAL_AUTHORITY_NAME AS [Technical Authority]
, bm.BID_START_DATE AS [Solicitation Date]
, bm.BID_END_DATE AS [Closing Date]
, CAST(t.REQ_AMOUNT AS MONEY) AS [Requisition Value]
, CAST(t.APPROVAL_AMOUNT AS MONEY) AS [Approval Value]
, t.CURRENT_STAGE AS [Current Stage]
, CONVERT(varchar,t.ESTIMATED_AWARD_DATE,101) AS [Estimated Award Date]
, replace(replace(n.NOTE,CHAR(13),''),CHAR(10),'') as [Comments]
, DATEDIFF(day, t.RECEIVED_DATE, getdate()) AS [Age of Requisition (days)]
, cb.USER_NAME as [Buyer Name]
, o.OFFICE_LOCATION_NAME as [Office Location]
FROM VW__TOMBSTONES__CLIENT_CODES t
LEFT OUTER JOIN TB__OFFICE_LOCATIONS o
ON o.ID = t.OFFICE__ID
LEFT OUTER JOIN TB__USERS cb
ON t.CURRENT_BUYER__ID = cb.ID
LEFT OUTER JOIN TB__BID_MANAGEMENTS bm
ON bm.TB__TOMBSTONES__ID = t.ID
LEFT OUTER JOIN TB__REQUISITIONS r
ON r.TOMBSTONES__ID = t.ID
LEFT OUTER JOIN TB__NOTES n
ON n.REQUISITION__ID = r.ID
AND t.CURRENT_STAGE = n.NOTE_TYPE
WHERE t.CURRENT_STAGE <= 4
AND n.NOTE_TYPE BETWEEN 1 AND 4
AND t.REGION__ID = #arguments.intRegionId#
</cfquery>
<!--- Create new spreadsheet --->
<cfset sObj = SpreadsheetNew()>
<!--- Excel Functions --->
<cfset countFormula="COUNTA(A8:A20000)">
<cfset sumFormula="SUM(G2:G2000)">
<!--- Create header row --->
<cfset SpreadsheetMergeCells(sObj,1,1,1,2)>
<cfset SpreadsheetSetCellValue(sObj, "BUYER REGISTER REPORT",1,1)>
<cfset SpreadsheetFormatRow(sObj, {bold=TRUE, alignment="center"}, 1)>
<cfset SpreadsheetSetCellValue(sObj, "Report Generated Date:",3,1)>
<cfset SpreadsheetFormatCell(sObj, {bold=TRUE, alignment="right"}, 3,1)>
<cfset SpreadsheetSetCellValue(sObj, "#ToString(DateFormat(now(), "mmmm d yyyy"))#",3,2 )>
<cfset SpreadsheetFormatCell(sObj, {bold=TRUE, alignment="left"}, 3,2)>
<cfset SpreadsheetSetCellValue(sObj, "Number of Requisitions:",4,1)>
<cfset SpreadsheetFormatCell(sObj, {bold=TRUE, alignment="right"}, 4,1)>
<cfset SpreadsheetSetCellFormula(sObj,countFormula, 4, 2)>
<cfset SpreadsheetFormatCell(sObj, {bold=TRUE, alignment="left"}, 4,2)>
<cfset SpreadsheetSetCellValue(sObj, "Value of Requisitions:",5,1 )>
<cfset SpreadsheetFormatCell(sObj, {bold=TRUE, alignment="right"}, 5,1)>
<cfset SpreadsheetSetCellFormula(sObj,sumFormula, 5, 2)>
<cfset SpreadsheetFormatCell(sObj, {bold=TRUE, alignment="left"}, 5,2)>
<cfset SpreadsheetFormatCell(sObj, {dataformat="$##,##0.00"}, 5,2)>
<cfset SpreadsheetAddRow(sObj, "" )>
<cfset SpreadsheetAddRow(sObj, "RECEIVED DATE,REQUISITION NUMBER,REQUISITION TITLE,TECHNICAL AUTHORITY,SOLICITATION DATE,CLOSING DATE,REQUISITION VALUE,APPROVAL VALUE,CURRENT STAGE,ESTIMATED AWARD DATE,COMMENTS,AGE OF REQUISITION (DAYS),BUYER NAME,OFFICE LOCATION")>
<cfset SpreadsheetFormatRow(sObj, {bold=TRUE}, 7)>
<!--- Add orders from query --->
<cfset SpreadsheetAddRows(sObj, qRead)>
<cfset SpreadsheetFormatColumns(sObj, {dataformat="$##,##0.00"}, "7-8")>
<cfset SpreadsheetFormatColumns(sObj, {alignment="center"}, "9-10")>
<cfset SpreadsheetFormatColumns(sObj, {alignment="center"}, "12-15")>
<!--- Excel document naming and storing location --->
<cfset strDir=GetDirectoryFromPath(GetCurrentTemplatePath())&"/../assets/generatedXLS/">
<cfset strFilePrepend = "-BuyerReport-" />
<cfset strFileNameStamp = "Galileo" & "#strFilePrepend#" & "#ToString(DateFormat(now(), "yy-mm-dd"))#" & "-#ToString(TimeFormat(now(), "HHmmss"))#" & ".xls"/>
<cfspreadsheet action="write"
filename="#strDir##strFileNameStamp#"
name="sObj"
overwrite="true"
sheetname="Active (Stages 1-4)">
<cfset structExcelResult["strURL"] = "/web_apps/app/assets/generatedXLS/" & #strFileNameStamp# />
<cfset structExcelResult["strNoRecordsFoundMsg"] = "" />
<cfreturn structExcelResult>
How do I fetch that data (structExcelResult["strURL"]) and display it on my .cfm page?
I'm new at this and going through Ben Forta books... Thanks!
Since you have a cfreturn in your code, I'll assume that was meant to have been wrapped in cffunction.
You can call a cffunction a couple of different ways. It could be on the same .cfm page that you're on:
<cffunction name="sayHello" output="false">
<cfargument name="username" type="string" required="false" default="Anonymous" />
<cfreturn "Hello, " & username />
</cffunction>
<cfoutput>#sayHello( 'Charlie' )#</cfoutput>
However, it's more likely that your function is part of a ColdFusion Component (CFC). To call a function that's part of a CFC, you first have to instantiate the CFC:
<cfset myCFC = createObject( 'component', 'path.to.my.cfc' ) />
Now you can call any method that resides in the CFC via:
<cfoutput>#myCFC.myFunction( 'foo' )#</cfoutput>
Going back to my first (very simple) example, let's say the sayHello() function resided in the Greeting.cfc file that was at /com/Greeting.cfc.
<cfset greeting = createObject( 'component', 'com.greeting' ) />
<cfoutput>#greeting.sayHello( 'Charlie' )#</cfoutput>
You can use anything you'd like for the name. It doesn't have to be myCFC or greeting. It's just a variable that represents a hook into your component.
Hope that helps.
UPDATED CODE TO LATEST ITERATION
The following function consumes a webservice that returns address details based on zip code (CEP). I'm using this function to parse the xml and populate an empty query with the address details. I would like to know if there is a more elegant way to achieve the same result. It seems to be a waste to create an empty query and populate it...
Any ideas could my method be modified or the code factored/simplified?
<!--- ****** ACTION: getAddress (consumes web-service to retrieve address details) --->
<cffunction name="getAddress" access="remote" returntype="any" output="false">
<!--- Defaults: strcep (cep (Brazilian zip-code) string webservice would look for), search result returned from webservice --->
<cfargument name="cep" type="string" default="00000000">
<cfset var searchResult = "">
<cfset var nodes = "">
<cfset var cfhttp = "">
<cfset var stateid = 0>
<cfset var tmp = structNew()>
<!--- Validate cep string --->
<cfif IsNumeric(arguments.cep) AND Len(arguments.cep) EQ 8>
<cftry>
<!--- Consume webservice --->
<cfhttp method="get" url="http://www.bronzebusiness.com.br/webservices/wscep.asmx/cep?strcep=#arguments.cep#"></cfhttp>
<cfset searchResult = xmlparse(cfhttp.FileContent)>
<cfset nodes = xmlSearch(searchResult, "//tbCEP")>
<!--- If result insert address data into session struct --->
<cfif arrayLen(nodes)>
<cfset tmp.streetType = nodes[1].logradouro.XmlText>
<cfset tmp.streetName = nodes[1].nome.XmlText>
<cfset tmp.area = nodes[1].bairro.XmlText>
<cfset tmp.city = nodes[1].cidade.XmlText>
<cfset tmp.state = nodes[1].uf.XmlText>
<cfset tmp.cep = arguments.cep>
<!--- Get state id and add to struct --->
<cfset stateid = model("state").findOneByStateInitials(tmp.state)>
<cfset tmp.stateid = stateid.id>
<cfreturn tmp>
</cfif>
<!--- Display error if any --->
<cfcatch type="any">
<cfoutput>
<h3>Sorry, but there was an error.</h3>
<p>#cfcatch.message#</p>
</cfoutput>
</cfcatch>
</cftry>
</cfif>
</cffunction>
<!--- ****** END ACTION getAddress --->
The calling code:
<!--- Get address data based on CEP --->
<cfset session.addressData = getAddress(cep=params.newMember.cep)>
I can't test this because I don't have an example XML file / CEP to test with, but here is a minor rewrite that addresses four things:
Instead of using cfparam and some strange "params" structure, you should pass the CEP into the function as an argument.
The function shouldn't directly modify session data. Instead, you should return the result and let the calling code assign it to the session (or wherever else it might be needed). I'll show this in a 2nd code example.
Cache the xml result per CEP -- assuming this doesn't change often. (You'll have to improve it further if you want time-based manual cache invalidation, but I can help add that if necessary)
Don't use StructInsert. It's not necessary and you're just writing it the long way for the sake of writing it the long way. There is no benefit.
Again, this isn't tested, but hopefully it's helpful:
<cffunction name="getAddress" access="remote" returntype="any" output="false">
<cfargument name="cep" type="string" default="00000000" /><!--- (cep (Brazilian zip-code) string webservice would look for) --->
<cfset var searchResult = "">
<cfset var nodes = "">
<cfset var cfhttp = "">
<cfset var stateid = 0 />
<cfset var tmp = structNew()>
<!--- Validate cep string --->
<cfif IsNumeric(arguments.cep) AND Len(arguments.cep) EQ 8>
<cfif not structKeyExists(application.cepCache, arguments.cep)><!--- or cache is expired: you'd have to figure this part out --->
<!--- Consume webservice --->
<cftry>
<cfhttp method="get" url="http://www.bronzebusiness.com.br/webservices/wscep.asmx/cep?strcep=#arguments.cep#" />
<cfset searchResult = xmlparse(cfhttp.FileContent)>
<cfset nodes = xmlSearch(searchResult, "//tbCEP")>
<!--- If result insert address data into session struct --->
<cfif arrayLen(nodes)>
<cfset tmp.streetType = nodes[1].logradouro.XmlText />
<cfset tmp.streetName = nodes[1].nome.XmlText />
<cfset tmp.area = nodes[1].bairro.XmlText />
<cfset tmp.city = nodes[1].cidade.XmlText />
<cfset tmp.state = nodes[1].uf.XmlText />
<cfset tmp.cep = arguments.cep />
<!--- Get state id and add to struct --->
<cfset stateid = model("state").findOneByStateInitials(session.addressData.state)>
<cfset tmp.stateid = stateid.id />
</cfif>
<cfreturn duplicate(tmp) />
<!--- Display error if any --->
<cfcatch type="any">
<h3>Sorry, but there was an error.</h3>
<p>#cfcatch.message#</p>
</cfcatch>
</cftry>
<cfelse>
<!--- cache exists and is not expired, so use it --->
<cfreturn duplicate(application.cepCache[arguments.cep]) />
</cfif>
</cfif>
<!---
<!--- Redirect to page two of the sign up process --->
<cfset redirectTo(controller="assine", action="perfil")>
--->
</cffunction>
Notice that I commented out the redirect you had at the end. That's because with my function, you'll be returning a value, and the redirect should be done after that, like so:
<cfset session.addressData = getAddress("some-CEP-value") />
<cfset redirectTo(controller="assine", action="perfil")>
If you're going to leave out the caching (As you say in a comment you will), then here is a version that makes no attempt at caching:
<cffunction name="getAddress" access="remote" returntype="any" output="false">
<cfargument name="cep" type="string" default="00000000" /><!--- (cep (Brazilian zip-code) string webservice would look for) --->
<cfset var searchResult = "">
<cfset var nodes = "">
<cfset var cfhttp = "">
<cfset var stateid = 0 />
<cfset var tmp = structNew()>
<!--- Validate cep string --->
<cfif IsNumeric(arguments.cep) AND Len(arguments.cep) EQ 8>
<!--- Consume webservice --->
<cftry>
<cfhttp method="get" url="http://www.bronzebusiness.com.br/webservices/wscep.asmx/cep?strcep=#arguments.cep#" />
<cfset searchResult = xmlparse(cfhttp.FileContent)>
<cfset nodes = xmlSearch(searchResult, "//tbCEP")>
<!--- If result insert address data into session struct --->
<cfif arrayLen(nodes)>
<cfset tmp.streetType = nodes[1].logradouro.XmlText />
<cfset tmp.streetName = nodes[1].nome.XmlText />
<cfset tmp.area = nodes[1].bairro.XmlText />
<cfset tmp.city = nodes[1].cidade.XmlText />
<cfset tmp.state = nodes[1].uf.XmlText />
<cfset tmp.cep = arguments.cep />
<!--- Get state id and add to struct --->
<cfset stateid = model("state").findOneByStateInitials(session.addressData.state)>
<cfset tmp.stateid = stateid.id />
</cfif>
<cfreturn duplicate(tmp) />
<!--- Display error if any --->
<cfcatch type="any">
<h3>Sorry, but there was an error.</h3>
<p>#cfcatch.message#</p>
</cfcatch>
</cftry>
</cfif>
<!---
<!--- Redirect to page two of the sign up process --->
<cfset redirectTo(controller="assine", action="perfil")>
--->
</cffunction>
Note that I did leave in the use of duplicate(). What this does is return a duplicate of the object (in this case, the struct). This is much more important when you start to work on applications where you're passing complex values into and out of functions over and over again. Using duplicate() causes things to be passed by value instead of by reference. It may not bite you in this case, but it's a good habit to get into.
I would also still use the function argument and return a value -- but it's arguable that this is my personal preference. In a way it is. I believe that a function should be fully encapsulated; a total "black box". You give it some input and it gives you back some output. It should not modify anything outside of itself. (Again, just my opinion.)
So assuming you're using this function as part of a larger multi-step process, you should still use it the same way I've described above. The only difference is that you're setting the session variable outside of the function body. Just as previously:
<cfset session.addressData = getAddress("some-CEP-value") />
<cfset redirectTo(controller="assine", action="perfil")>
That looks pretty straightforward. CF doesn't (yet?) have any magical XML-to-Query functions, but that would be pretty cool. If you wanted, you could probably write up an XSL transform to go from XML to WDDX so that you could use the cfwddx tag ... but that's probably putting the cart before the horse.
You need to move your arrayLen() if block into the try block. As it stands, if the cfhttp tag throws an error, the nodes variable will be a string and not an array, thus causing the arrayLen() to throw another error.
Minor nitpick: I wouldn't add a row to the query until inside the arrayLen() block. That way, the calling code can check recordCount to see if the result was a success.
Beyond that ... that's pretty much how it's done.