Please suggest me what is the correct way to get method arguments in CF web service with SOAP
Below is my sample code for web service method where I didn't used <cfargument> but parsing xml request
<cffunction name="Method1" displayname="method name" description="method description
"access="remote" output="true" returntype="xml">
<cfset isSOAP = isSOAPRequest()>
<cfif isSOAP>
Get the first header as a string.
<cfset reqxml = GetSOAPRequest()>
<cfset reqxml1 = XmlParse(reqxml)>
<cfset responseNodes = xmlSearch(#reqxml1#,"soapenv:Envelope/soapenv:Body") />
<cfset responseNodes = xmlparse(responseNodes[1]) />
<cfif structKeyExists( responseNodes.xmlroot, "AgentID" )>
<CFSET AgentID=trim(responseNodes.xmlroot.AgentID.xmltext)>
<cfelse>
<cfset process = 0 >
<cfset responce['ErrorCode'] = "MG1000">
<cfset responce['ErrorMessage'] = "Agent ID not found in request">
<cfset AnythingToXML = createObject('component', 'AnythingToXML.AnythingToXML').init() />
<cfset myXML = AnythingToXML.toXML(responce,"StatusResponse") />
<cfset result = xmlparse(myXML)>
<cfreturn result>
</cfif>
But I think I should use
<cfargument> in place of parsing xml request.
Please suggest what is the correct way to do it.
Thanks in advance
Your ColdFusion SOAP method can be as simple as:
<cffunction name="yourMethod" access="remote" output="false" returntype="struct">
<cfargument name="testString" type="String" >
<cfset local.out = structNew()>
<cfset local.out.argIn = arguments.testString>
<cfset local.out.additionalValue = "Hello World">
<cfreturn local.out>
</cffunction>
ColdFusion will allow remote function to be accessed via SOAP requests. You don’t need to rely on the SOAP methods like isSOAPRequest() and GetSOAPRequest() unless you’re doing more complex tasks, such as requiring data in the SOAP header. You can view the SOAP wsdl by appending ?wsdl to the name of your component, such as localhost\yourService.cfc?wsdl
You can return any data type that ColdFusion can serialize. In my example I opted to return a structure, which will return a map in SOAP.
Related
I have one .cfc that I use for all communication between client and server code. This cfc page has about 10 different function. Each function has different purpose and I have queries for Select, Insert, Update and Delete. I'm wondering if I should set timeout on the top of the .cfc page inside cfcomponent tag or this should be set inside of the each function or do I even need this? In our current system we have some many error messages like: The request has exceeded the allowable time limit Tag: CFQUERY.
I would like to prevent any similar error messages in my app. Here is example of my cfc page:
<cfcomponent>
<cfset currentDate = DateFormat(Now(),'mm/dd/yyyy')>
<cfset currentTime = TimeFormat(Now(),'hh:mm tt')>
<cfinvoke component="appEntry" method="getRecord" returnvariable="CHKAccess">
<cfinvokeargument name="user" value="userdata"/>
<cfinvokeargument name="app" value="myApp"/>
</cfinvoke>
<cfset adminAccess = false>
<cfset userAccess = false>
<cfif CHKAccess.RecordCount EQ 1>
<cfif CHKAccess.pd_hfmAccess EQ 'A'>
<cfset adminAccess = true>
</cfif>
<cfif CHKAccess.pd_hfmAccess EQ 'U'>
<cfset userAccess = true>
</cfif>
</cfif>
<cffunction name="getData" access="remote" output="true" returnformat="JSON">
<cfargument name="keyVal" type="string" required="true">
<cfset fnResults = structNew()>
<cfif userAccess>
<cfquery name="getRec" datasource="tes">
SELECT some columns
FROM Test
</cfquery>
<cfset fnResults.status = "200">
<cfelse>
<cfset fnResults.status = "400">
<cfset fnResults.message = "Invalid access attempt.">
</cfif>
<cfreturn fnResults>
</cffunction>
<!--- More functions below --->
</cfcomponents>
If anyone have suggestion what would be the best fix please let me know. Thank you.
You should set the requesttimeout in the method that contains that long-running cfquery.
You don't want to "punish" all methods for just one method. If you set it for all, how do you know which one is slow and which one is okay, unless you don't care?
I have a web form which uses the action attribute to call a CFC like this:
<form action="mycfc.cfc?method=registeruser">
The CFC processes the data in the form and then I want it to return a variable telling the user if their form submission has been successful or not.
So within my CFC, I put this:
<cffunction name="registeruser" access="remote" hint="registers a new user" returnformat="JSON">
... PROCESSES FORM HERE THEN...
<cfset Msg = 'Success'>
<cfreturn Msg>
<cflocation url = "/registrationpage.cfm">
</cffunction>
How do I display the Msg variable in the registrationpage.cfm page? My output is set to JSON so I guess I have to DeSerialize but I have no idea how to actually reference/access this output from the method.
My whole answer is for educationnal purposes only and I strongly advise you to use an existing framework rather than reinventing the Wheels. Have a look at Picking a ColdFusion MVC Framework
You can store the value in the session scope. A lot of frameworks does it using a flash memory concept, which is a temporary memory (implemented as a struct) that destroys members when accessed.
Have a look at http://cfwheels.org/docs/1-1/chapter/using-the-flash it's quite straight forward to implement an API that does this.
Client code could look like (depending on your implementation):
<cfset session.flash.set('importantMsg', 'some important msg')>
<cflocation ...>
Then from the other page:
<cfif session.flash.has('importantMsg')>
<!--- The following line should also destroy the 'importantMsg' key --->
#session.flash.get('importantMsg')#
</cfif>
Here's an implementation example (not that the implementation is not thread-safe):
FlashMemory.cfc
<cfcomponent>
<cffunction name="init" returntype="FlashMemory">
<cfset variables.instance = {flash = {}}>
</cffunction>
<cffunction name="set" returntype="void">
<cfargument name="key" type="string" required="true">
<cfargument name="value" type="any" required="true">
<cfset variables.instance.flash[arguments.key] = arguments.value>
</cffunction>
<cffunction name="get" returntype="any">
<cfargument name="key" type="string" required="true">
<cfset var v = variables.instance.flash[arguments.key]>
<cfset structDelete(variables.instance.flash, arguments.key)>
<cfreturn v>
</cffunction>
<cffunction name="has" returntype="boolean">
<cfargument name="key" type="string" required="true">
<cfreturn structKeyExists(variables.instance.flash, arguments.key)>
</cffunction>
</cfcomponent>
onSessionStart
<cfset session.flash = new FlashMemory()>
Also please note that in your case, your remote CFC methods shouldn't return anything. You will use the flash memory to pass data around instead. That means when the method has finished it's work you can simply redirect the client.
You probably shouldn't use remote CFC methods in this particular case:
I have never really used remote CFC methods as stateful web services. The various advantages of remote CFC methods like their ability to spit out data in multiple data-interchange formats (JSON, WDDX...) is lost with your implementation.
You could simply do something like:
registration.cfm
<cfset errors = session.flash.get('registrationErrors')>
<cfif arrayLen(errors)>
<!--- Display errors --->
</cfif>
<form method="post" action="register.cfm">
...
</form>
register.cfm
<cfset registration = new Registration(argumentcollection = form)>
<cfset validator = new RegistrationValidator(registration)>
<cfif validator.validate()>
<cfset application.userService.register(registration)>
<!--- You can also redirect to a page that represents the correct state --->
<cflocation url="registered.cfm" addtoken="no">
<cfelse>
<!--- Store the errors collection in the flash memory --->
<cfset session.flash.set('registrationErrors', validator.errors())>
<!--- Redirect to the page the user came from --->
<cflocation url="#cgi.http_referer#" addtoken="no">
</cfif>
Take the cflocation tag out of your function. It will not execute anyway because it's after the cfreturn tag.
Also, post your form to a .cfm page, not the .cfc. From that .cfm page, do this:
<cfset MyObject = CreateObject(stuff for your cfc goes here)>
<cfset MessageFromFunction = MyObject.registeruser()>
<cfoutput>#MessageFromFunction</cfoutput.
I'm working with ColdFusion 9.0.1 and latest (for current date) stable build of twitter4j library - twitter4j-core-2.2.4. I'm trying to create functionality which allows users to login or register at our site using their twitter accounts.
I was able to create authorization part: user click on the link on our site and system redirects him to twitter page. On this page he able to "Authorise" our application. After that system redirecting him back using callBackURL.
But I have a problem with next step. When I'm trying to setOAuthAccessToken and for that trying to instantiate AccessToken object with follow part of code:
accessToken = createObject( 'java', 'twitter4j.auth.AccessToken' ).init( 'myStoredRequestToken', 'myStoredRequestTokenSecret' );
But I have follow error:
An exception occurred while instantiating a Java object. The class
must not be an interface or an abstract class. Error: ''.
Any ideas?
Update:
The start part of stacktrace:
'coldfusion.runtime.java.JavaObjectInstantiationException: Object instantiation exception. at coldfusion.runtime.java.JavaProxy.CreateObject(JavaProxy.java:171) at coldfusion.runtime.java.JavaProxy.invoke(JavaProxy.java:80) at coldfusion.runtime.CfJspPage._invoke(CfJspPage.java:2360) at cftwitter2ecfc2084917956$funcGETUSERCREDENTIALS.runFunction(C:\inetpub\wwwroot_test\twPlayGrnd_com\twitter.cfc:36) at coldfusion.runtime.UDFMethod.invoke(UDFMethod.java:472) at coldfusion.runtime.UDFMethod$ArgumentCollectionFilter.invoke(UDFMethod.java:368) at coldfusion.filter.FunctionAccessFilter.invoke(FunctionAccessFilter.java:55) at ...
...cut here, not sure this is important...
the last part is
cfapplication2ecfc665259542$funcONREQUEST.runFunction(C:\inetpub\wwwroot_test\twPlayGrnd\application.cfc:55) ... 55 more Caused by: java.lang.IllegalArgumentException: Invalid access token format. at twitter4j.auth.AccessToken.(AccessToken.java:50) ... 60 more'
I saw the message about wrong format, but based on documentation at http://twitter4j.org it should accept two agruments (strings with keys). Am I wrong?
Update 2
*just find that out - I am sorry that I brought you into confusion with my first post and example... of course I used myStoredRequestToken, myStoredRequestTokenSecret, not a consumer key/secret *
*there are relevant parts of code I'm using for this functionality*
application.cfc ("onApplicationStart" function, instantiating components on start of application)
<cffunction name="onApplicationStart" access="public" returntype="boolean" output="false">
...
<cfset application.com.twitterInstance = server.javaloader.create("twitter4j.TwitterFactory").getInstance() />
<cfset application.com.twitter = createObject("component","_com.twitter").init() /> *<!--- cfc component which will be listed below --->*
...
</cffunction>
twitter.cfc (corresponding coldfusion component)
<cfcomponent displayname="twitter" output="false">
<cffunction name="init" access="public" output="false">
<cfreturn this>
</cffunction>
<cffunction name="authorizeTwitter" access="public" output="false">
<cfargument name="callBackURL" type="string" required="false" default="#request.twtCallBackURL#" />
<cfset var requestToken = "" />
<cfset application.com.twitterInstance.setOAuthConsumer(request.twtConsumerKey,request.twtConsumerSecret) />
<cfset requestToken = application.com.twitterInstance.getOAuthRequestToken(arguments.callBackURL) />
<cflock scope="session" type="exclusive" timeout="10">
<cfset session.oAuthRequestToken = requestToken.getToken()>
<cfset session.oAuthRequestTokenSecret = requestToken.getTokenSecret()>
</cflock>
<cflocation url="#vLocal.requestToken.getAuthorizationURL()#" addtoken="No" />
</cffunction>
<cffunction name="getUserCredentials" access="public" output="true">
<cfset var vLocal = {} />
<cfset vLocal.accessToken = "" />
<cfset vLocal.userData = "" />
<cfset vLocal.requestToken = "" />
<cfset vLocal.accessToken = server.javaloader.create("twitter4j.auth.AccessToken").init(session.oAuthRequestToken,session.oAuthRequestTokenSecret)>
<cfset application.com.twitterInstance.setOAuthAccessToken(vLocal.accessToken) />
<cfset vLocal.userData = application.com.twitterInstance.verifyCredentials() />
<cfdump var="#vLocal.userData#" label="User Credentials">
</cffunction>
First function is for first step - requesting twitter for autorization page (where user can autorize or deny application). Call back URL runs the page what calls the second function and I have problem only at this step (line for generation accessToken).
I have the same result if Im using createObject function instead of javaloader.
*So, my main question is still the same - to obtain the users unique Access Token? Please point me, what I'm doing wrong? What is a correct format for unique user's accessToken generation? Should I place oauth_verifier parameter there? if so, how?*
You are passing consumer key/secret instead of access token/secret.
You can generate your access token/secret at dev.twitter.com.
https://dev.twitter.com/apps » create my access token
Best,
Yusuke
I think I figured out what is wrong with the help of the examples 8. Sign in with Twitter and
Adding support for automated tweets with OAuth. Only tested with my own account though ..
Before you redirect to the authorization page, save the whole RequestToken object in a session variable. You will need it to extract the AccessToken. Note: I am storing the TwitterFactory in the application scope - not the instance
<cfset Twitter = application.TwitterFactory.getInstance()>
<cfset Twitter.setOAuthConsumer(application.TwitterConsumerKey, application.TwitterConsumerSecret)>
<cfset Session.RequestToken = Twitter.getOAuthRequestToken( YourCallBackURL )>
On callback, twitter adds a parameter named oauth_verifier to the URL. Use that value and the saved RequestToken to extract the AccessToken.
<cfset AccessToken = Twitter.getOAuthAccessToken(Session.RequestToken, URL.oauth_verifier)>
<cfset session.StoredAccessToken = AccessToken.getToken()>
<cfset session.StoredAccessSecret = AccessToken.getTokenSecret()>
Once you have the AccessToken/Secret you can access user details (update status,...) anywhere.
<cfset Twitter = application.TwitterFactory.getInstance()>
<cfset Twitter.setOAuthConsumer(application.TwitterConsumerKey,application.TwitterConsumerSecret)>
<cfset AccessToken = createObject("java", "twitter4j.auth.AccessToken")>
<cfset OAuthToken = AccessToken.init(session.StoredAccessToken, session.StoredAccessSecret)>
<cfset Twitter.setOAuthAccessToken(OAuthToken)>
<cfset userData = Twitter.verifyCredentials()>
<cfoutput>
id = #userData.getId()#<br>
name = #userData.getName()#<br>
followers = #userData.getFollowersCount()#<br>
friends = #userData.getFriendsCount()#<br>
</cfoutput>
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.
I am creating an API, and within each method I make a call to a logging method for auditing and troubleshooting. Something like:
<cffunction name="isUsernameAvailable">
<cfset logAccess(request.userid,"isUsernameAvailable")>
......
</cffunction>
I'd like to avoid manually repeating the method name. Is there a way to programatically determine it?
I've looked at GetMetaData() but it only returns info about the component (including all the methods) but nothing about which method is currently being called.
So now 3 ways.
If you are using ColdFusion 9.0 or higher there is now a function named GetFunctionCalledName(). It will return what you are looking for.
http://help.adobe.com/en_US/ColdFusion/9.0/CFMLRef/WS7cc222be8a31a47d-6e8b7083122cebfc8f2-8000.html
OR
Use ColdSpring and Aspect Oriented Programming (http://www.coldspringframework.org/coldspring/examples/quickstart/index.cfm?page=aop) to handle this for you.
OR
Use a cfthrow to generate a stack trace that has the information for you:
<cffunction name="determineFunction" output="FALSE" access="public" returntype="string" hint="" >
<cfset var functionName ="" />
<cfset var i = 0 />
<cfset var stackTraceArray = "" />
<cftry>
<cfthrow />
<cfcatch type="any">
<cfset stacktraceArray = ListToArray(Replace(cfcatch.stacktrace, "at ", " | ", "All"), "|") />
<!---Rip the right rows out of the stacktrace --->
<cfloop index ="i" to="1" from="#ArrayLen(stackTraceArray)#" step="-1">
<cfif not findNoCase("runFunction", stackTraceArray[i]) or FindNoCase("determineFunction", stackTraceArray[i])>
<cfset arrayDeleteAt(stackTraceArray, i) />
</cfif>
</cfloop>
<!---Whittle down the string to the func name --->
<cfset functionName =GetToken(stacktraceArray[1], 1, ".") />
<cfset functionName =GetToken(functionName, 2, "$")/>
<cfset functionName =ReplaceNoCase(functionName, "func", "", "once")/>
<cfreturn functionName />
</cfcatch>
</cftry></cffunction>
My recommendation would be use getFunctionCalledName, or if not on CF 9 ColdSpring, as it will probably buy you some other things.
I agree w/ tpryan. ColdSpring makes this very easy. However, here is another alternative. Instead of parsing the stack trace, you can parse the CFC file itself.
<cffunction name="foo" displayname="foo" hint="this is just a test function" access="public" returntype="string">
<cfset var test = getFunctionName(getMetaData().path, getPageContext().getCurrentLineNo()) />
<cfreturn test />
</cffunction>
<cffunction name="getFunctionName" hint="returns the function name based on the line number" access="public" returntype="string">
<cfargument name="filepath" type="string" required="true" />
<cfargument name="linenum" type="any" required="true" />
<cfset var line = "" />
<cfset var functionName = "" />
<cfset var i = 1 />
<!---- loop over CFC by line ---->
<cfloop file="#ARGUMENTS.filepath#" index="line">
<cfif findNoCase('cffunction', line, 1)>
<cfset functionName = line />
</cfif>
<cfif i EQ ARGUMENTS.linenum><cfbreak /></cfif>
<cfset i++ />
</cfloop>
<!---- parse function name ---->
<cfset functionName = REMatchNoCase("(\bname=[""|'])+[a-z]*[""|']", functionName) />
<cfset functionName = REMatchNoCase("[""']+[a-z]*[""']", functionName[1]) />
<cfset functionName = ReReplaceNoCase(functionName[1], "[""']", "", "all") />
<!---- return success ---->
<cfreturn functionName />
</cffunction>
The above is written for ColdFusion 8. CFLOOP added support for looping over files line by line (and doesn't read the entire file into memory). I did a few tests comparing the stack trace method vs. file parsing. Both performed equally well on a small CFC being called directly from a single CFM template. Obviously if you have very large CFCs the parsing method might be a bit slower. On the other hand, if you have a large stack trace (like if you are using any of the popular frameworks) then file parsing may be faster.
-= Viva ColdFusion =-
Well you might try this:
<cffunction name="getFunctionName" returntype="any">
<cfset meta =getMetaData(this)>
<cfreturn meta.functions[numberOfFunction].name>
</cffunction>
I've tried various things, and this is not accurate as the functions seem to be added to the array of functions in reverse alphabetical order. This seems limiting (and not solving the problem). I would imagine some native java code could be invoked, but i'm going to need to look into that.
This and This look like interesting reading on related internal functions.
Re: The other answer on coldspring. I found this in depth article on function metadata with coldspring.
Related question : How to get the name of the component that’s extending mine in ColdFusion?
I thought of another way that could work.
Setup an OnMissingMethod something like this:
<cffunction name="onMissingMethod">
<cfargument name="missingMethodName" type="string">
<cfargument name="missingMethodNameArguments" type="struct">
<cfset var tmpReturn = "">
<cfset var functionToCallName = "Hidden" & Arguments.missingMethodName>
<cfset arguments.missingMethodArguments.calledMethodName = Arguments.missingMethodName>
<cfinvoke method="#functionToCallName#" argumentcollection="#Arguments.missingMethodArguments#" returnvariable="tmpReturn" />
<cfreturn tmpReturn>
</cffunction>
Then name each of the regular methods with a prefix ("Hidden" in this example), and mark them as private. So my initial example would become:
<cffunction name="HiddenisUsernameAvailable" access="private">
<cfset logAccess(request.userid,Arguments.calledMethodName)>
......
</cffunction>
Now all the calls will be intercepted by onMissingMethod, which will add the method name to the arguments that get passed to the real method.
The downsides I see to this are that introspection no longer works properly, and you must be using named arguments to call all your functions. If you are not using named arguments, the args will randomly change order in the missingMethodNameArguments structure.
getFunctionCalledName() gives you the name of the active method.