224
New Feature Notes ADOBE ® COLDFUSION ® 10 Beta Prerelease Prerelease

cf10betafeatures

Embed Size (px)

Citation preview

Page 1: cf10betafeatures

New Feature NotesADOBE® COLDFUSION® 10 Beta

PrereleasePrerelease

Page 2: cf10betafeatures

Last updated 2/17/2012

Copyright© 2012 Adobe Systems Incorporated and its licensors. All rights reserved.

Adobe® ColdFusion® 10 Beta Prerelease

This prerelease version of the document may not contain trademark and copyright notices that will appear in the commercially available version of the

document. This reference is licensed for use under the terms of the Creative Commons Attribution Non-Commercial 3.0 License. This License allows users to

copy, distribute, and transmit the reference for noncommercial purposes only so long as (1) proper attribution to Adobe is given as the owner of the reference;

and (2) any reuse or distribution of the reference contains a notice that use of the guide is governed by these terms. The best way to provide notice is to include

the following link. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/3.0/

Adobe, the Adobe logo, and ColdFusion are either registered trademarks or trademarks of Adobe Systems Incorporated in the United States and/or other

countries. Microsoft is either a registered trademark or a trademark of Microsoft Corporation in the United States and/or other countries. All other trademarks

are the property of their respective owners.

Adobe Systems Incorporated, 345 Park Avenue, San Jose, California 95110, USA.

This product includes software developed by the Apache Software Foundation (http://www.apache.org/).

This product includes software developed by Teodor Danciu (http://jasperreports.sourceforge.net).

This product includes software developed by the OpenSymphony Group (http://www.opensymphony.com/).

This product contains either BSAFE and/or TIPEM software by RSA Security, Inc.

Page 3: cf10betafeatures

iii

Last updated 2/17/2012

Contents

ColdFusion 10 Beta New Feature Notes

Installation instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

What’s new and enhanced . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2

Page 4: cf10betafeatures

1

Last updated 2/17/2012

ColdFusion 10 Beta New Feature Notes

Welcome to the Adobe® ColdFusion® 10 Beta (code-named Zeus) New Feature Notes. This document provides details

of the new and enhanced features.

Note: Though we have attempted to capture all relevant information that you require to get started with ColdFusion 10,

please note that this is Beta documentation and is in work-in-progress state. You might encounter issues with language,

style, formatting, incomplete information, or samples that need improvement. Nevertheless, feel free to inform us on all

content-related issues.

This document has the following sections:

• Installation instructions

• What’s new and enhanced

• Replacement of JRun with Tomcat

• Security enhancements

• Using ColdFusion WebSocket

• Language enhancements

• Using closures

• Enhanced Java integration

• ColdFusion ORM search

• Solr enhancements

• Scheduler enhancements

• Connect to Microsoft Exchange Server 2010

• Lazy loading across client and server

• Web service enhancements

• RESTful Web Services in ColdFusion

• Media Player enhancements

• HTML enhancements

• Client-side charting

• Caching enhancements

• Other enhancements

• ColdFusion Administrator enhancements

Installation instructions

The steps to install ColdFusion 10 are similar to the installation procedures for ColdFusion 9 (except in the case of

installing the multiserver configuration). For details, see the installation guide Installing Adobe ColdFusion 10.

Page 5: cf10betafeatures

2COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

ColdFusion 10 Beta installer does not support multiserver installations. Instead, you have to install a Server

configuration and then you can create multiple instances and clusters using instance manager in the ColdFusion

Administrator. For details, see Replacement of JRun with Tomcat.

Installation considerations/issues

• ColdFusion 10, ColdFusion 9, and ColdFusion 8 can coexist on the same system.

• In the case of ColdFusion cluster setup, any changes to the cluster settings, for example, adding a new member, or

changing member port (in the ColdFusion Administrator) causes web server restart. This may result in page time-out.

Refresh the page to resolve this issue.

• If ColdFusion uninstaller is not able to remove the connector for Apache (for example, in the case of Mac OS X),

do the following to manually remove it:

1 Delete {apache_install_location}/conf/mod_jk.conf.

2 Delete {cfroot}/config/wsconfig/1 folder which has the Apache connector file, mod_jk.so.

3 Remove the following line from {apache_install_location}/conf/httpd.conf file:

Include "{apache_install_location}\conf\mod_jk.conf".

4 Delete the file {apache_install_location}\conf\mod_jk.conf

• From the ColdFusion Administrator, start multiple instances, start cfusion instance first, and then start the other

instances.

• When you run the ColdFusion uninstaller, the logs folder (ColdFusion_Home/cfusion/) is deleted.

• When you install ColdFusion, install the Administrator Component for starting and stopping remote server.

Use the Remote Instance Administrator Component credentials to remotely start/stop the server from applications

such as Server Manager, Instance Manager in ColdFusion Administrator, or ColdFusion Builder.

• J2EE deployment of ColdFusion EAR or WAR on JRun is not supported. The EWS.jar must be present in the

systemclasspath while deploying on a J2EE server.

What’s new and enhanced

Replacement of JRun with Tomcat

Instead of JRun, Tomcat is embedded with a stand-alone ColdFusion 10 installation. Previous versions of ColdFusion

installer allow you to create multi-server installations whereas ColdFusion 10 installer lets you only install stand-alone

installation. After installing ColdFusion in stand-alone mode, you can create multiple instances and clusters, provided

you have an Enterprise or Developer license.

Note: This feature is not available in Standard Edition.

ColdFusion installation directory structure

By default, ColdFusion10 is your installation directory. The following table describes the directory structure:

Page 6: cf10betafeatures

3COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Modifications to the directory structure

The following table shows the directories in ColdFusion 9 and the corresponding ones in ColdFusion 10:

Directory Description

cfusion Contains the following directories:

• bin: Programs for starting, stopping, and viewing information for ColdFusion, and to run Crystal Reports (Windows

only). It also contains the password reset scripts for server administrator and Admin Component for remote server

start and stop.

• cache: Repository for temporary files from ColdFusion.

• cfx: Sample C++ and Java CFX files with their supporting files. You can also store your CFX files in this directory

(although you can put them in any location that is defined in your classpath).

• charting: Files for the ColdFusion graphing and charting engine.

• CustomTags: Repository for your custom tags

• db: The sample Apache Derby databases for all platforms.

• gateway: Files for ColdFusion event gateways.

• jetty: Solr configuration files and files related to remote instance start and stop.

• jintegra: (Applies only to Windows) JIntegra programs, libraries, and other supporting files (for example, to integrate

Java and COM code; manage access to ActiveX controls (OCXs) that are hosted in a graphical user interface (GUI)

container; and register the JVM and type libraries). (Applicable only for Windows.)

• jnbridge: Files for .NET Integration Services.

• lib: JAR, XML, property, and other files that are the foundation of ColdFusion, for functionality such as queries,

charting, mail, security, Solr, and system probes.

• logs: Repository for ColdFusion log files. JRE-specific log files are in the runtime/logs directory. Console outputs are

logged in to start.log instead of cfserver.log.

• Mail: Repository for spooled mail and mail that cannot be delivered.

• META-INF: XML metadata for the ColdFusion Administrator.

• MonitoringServer: Contains crossdomain.xml used for multi-server monitoring.

• registry: (UNIX only) Flat file to store registry settings

• runtime: Programs and supporting files for the ColdFusion runtime. Also, contains the Tomcat libraries. The conf

directory in runtime contains all Tomcat configuration files.

• stubs: web services.

• wwwroot: Default web root directory for the built-in web server. When running on other web servers, this directory

contains the CFIDE and WEB-INF directories; do not remove this directory.

config Contains instances.xml and connector configuration files. Also, contains cluster configuration file, cluster.xml.

jre Java runtime files.

uninstall Files to uninstall ColdFusion.

Page 7: cf10betafeatures

4COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Note: The ColdFusion_install\cfusion\bin directory contains the Jvm.config file.

Information related to connector configuration

Using connector, you can configure ColdFusion to the following web servers: Apache, IIS, and Sun ONE.

Configuring Apache:

Note: To configure Apache connector in UNIX platforms, APXS installation is a prerequisite.

Note: Configuring Apache is not supported on Mac 10.5.

• Creates a folder 1 in cf_install_dir\config\wsconfig that contains all connector-related files.

• Creates a file mod_jk.conf in Apache_root_folder\conf. This file has paths to all files in the

cf_install_dir\config\wsconfig\1 directory.

• Adds an entry in the httpd.conf file of Apache to include mod_jk.conf.

• The following files are significant:

• uriworkermap.properties: Mapped extensions based on which the connector forwards requests to Tomcat.

• mod_jk.conf: Contains paths to all files in the \config\wsconfig\1 directory.

Change the entry JKloglevel info to JKloglevel debug for debugging purposes.

Note: For virtual host configuration, add the following entry in each of the virtual blocks: JkMountFile

"cf_install_dir\config\wsconfig\1\uriworkermap.properties".

Configuring IIS:

• Creates a folder 1 in cf_install_dir\config\wsconfig, that contains all connector-related files.

• Creates a virtual directory Jakarta in cf_install_dir\config\wsconfig (in IIS).

• Adds an entry, tomcat, under the ISAPI FILTERS. This points to cf_install_dir\config\wsconfig\1\

isapi_redirect.dll.

• Adds an entry, tomcat, to cf_install_dir\config\wsconfig\1\isapi_redirect.dll with permission

allowed under ISAPI and CGI Restrictions. It is applicable for global sites in IIS manager.

• Adds the following isapi handlers: cfcHandler, cfmHandler, cfmlHandler, cfrHandler, and cfswfHandler.

• For debugging issues, set the log level to debug, in the isapi_redirect.properties file present in the

cf_install_dir\config\wsconfig\1\ directory.

• To disable webserver buffer, change the is_buffer_enable to false in the

cf_install_dir\config\wsconfig\1\isapi_redirect.properties file. Disable webserver buffer if you want

cfflush to work over an IIS connector. If your application does not use cfflush, set it to true for increase in the

performance.

Configuring Sun ONE:

ColdFusion 9 ColdFusion 10

cfroot cfusion

ColdFusion9\runtime\jre ColdFusion10\jre

ColdFusion9\uninstall ColdFusion10\uninstall

ColdFusion9\runtime\lib\wsconfig ColdFusion10\config\wsconfig

Page 8: cf10betafeatures

5COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Note: On Windows and Linux 64-bit, only 32-bit Sun ONE is available. While using a 64-bit configurator, provide 32-

bit Sun ONE properties.

• Creates a folder 1 in the config\wsconfig folder that contains all connector-related files.

• Adds the following entry in the magnus.conf file of Sun ONE. Change the log level to debug for debugging issues.

Init fn="load-modules" shlib="C:/ColdFusion10/config/wsconfig/2/nsapi_redirect.dll" funcs="jk_init,jk_service" Init fn="jk_init" worker_file="C:/ColdFusion10/config/wsconfig/2/workers.properties" log_level="info" log_file="C:/ColdFusion10/config/wsconfig/2/nsapi.log" shm_file="C:/ColdFusion10/config/wsconfig/2/jk_shm"

• Adds the entries for all extensions in the obj.conf file of Sun ONE. For example,

NameTrans fn="assign-name" from="/*.cfc/*" name="jknsapi" NameTrans fn="assign-name" from="/*.cfc" name="jknsapi" NameTrans fn="assign-name" from="/*.cfml" name="jknsapi" <Object name="jknsapi"> Service fn="jk_service" method="*" worker="server1" </Object>

Note: 64-bit Sun One and iPlanet WebServer are not supported on 64-bit Windows machines.

Using the built-in web server

ColdFusion provides in-built Tomcat webserver that you can use to develop ColdFusion applications.

During the ColdFusion installation, choose a web server. If you select the built-in web server, your web root directory

is located in the cf_install_dir/wwwroot directory. By default, the web server runs on port 8500. It means that to display

a page in your application, append:8500 to the host name or IP address in the URL; for example,

http://localhost:8500/YourApp1/index.cfm. If the page does not appear, ensure that the document is located in the

built-in web server’s web root directory; for example, C:\ColdFusion10\cfusion\wwwroot\YourApp1\index.cfm.

Note: If port 8500 is in use, the installer checks up to 100 ports (starting with 8501) to find a port that is not used.

ColdFusion uses that port and displays a message to indicate the selected port.

If you select an external web server during installation, the built-in web server is deactivated.

Change the port of the built-in web server

1 Back up the server.xml file.

This file is in the cf_install_dir\cfusion\runtime\conf directory.

2 Open the original server.xml file for editing.

3 Search for internal webserver start. Update the port number.

<Connector executor="tomcatThreadPool" port="8500" protocol="org.apache.coyote.http11.Http11NioProtocol" connectionTimeout="20000" redirectPort="8445"/>

4 Save the file and then restart ColdFusion.

Configuring the built-in web server (Tomcat)

While installing, if you have configured ColdFusion on an external web server, do the following to configure

ColdFusion on in-built Tomcat:

1 Open the cf_install_dir\cfusion\runtime\conf\server.xml file.

Page 9: cf10betafeatures

6COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

2 Search for internal webserver start. Uncomment the following connector XML.

<Connector executor="tomcatThreadPool" port="8500" protocol="org.apache.coyote.http11.Http11NioProtocol" connectionTimeout="20000" redirectPort="8445"/>

3 Save the file, and then restart ColdFusion.

Starting, stopping, and restarting ColdFusion

On Windows

❖ At prompt, go to the directory cf_install_dir\cfusion\bin and run the following command: coldfusion.exe -

start -console.

To stop ColdFusion, use the command coldfusion.exe -stop -console. To restart, use the command

coldfusion.exe -restart -console.

Note: As possible in previous versions of ColdFusion, you can also use the cfstart script to start/stop the ColdFusion sever.

Note: The -console argument is optional. If it is not provided, the logs are saved in the

cf_install_dir\cfusion\logs directory.

On UNIX/Linux/Solaris/Mac OSX

❖ At prompt, go to the directory cf_install_dir\cfusion\bin and run the following command: ./coldfusion -start

To stop ColdFusion, use the command ./coldfusion -stop. To restart, use the command ./coldfusion -

restart.

Note: Use the status command to find the status of ColdFusion server.

Editing the JVM settings

To edit the JVM settings, open the cf_install_dir\cfusion\bin\jvm.config file and update the following details:

• java.home: Java home. If not set, ColdFusion verifies the default JRE in the cf_install_dir\jre folder, in the

registry, or in the JAVA_HOME environment variable.

• java.args: Settings for -Xmx, ColdFusion classpath, and so on.

• java.library.path: Settings for library path.

• java.class.path: Additional classpath settings in a comma-separated list.

• application.home: Default is CF_install_dir\cfusion

Creating and editing a new ColdFusion instance

After installing ColdFusion in stand-alone mode, create an instance of ColdFusion using the ColdFusion

Administrator.

1 In the ColdFusion Administrator, go to Enterprise Manager > Instance Manager.

2 Click Add New Instance.

3 Enter the server name and server directory.

4 (Optional) Check Create Windows Service.

5 Click Submit.

In the Instance Manager, start, stop, restart, delete, access website, or access administrator.

Page 10: cf10betafeatures

7COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

6 Click the Edit icon to edit the instance manager.

7 Edit the internal webserver port and load balancing factor.

Load balancing factor represents the load the instance takes up. Load balancing factor is applicable only if the

instance is part of the cluster.

For example, the load balancing factor for the first instance is 1 and that of the second instance is 2. The second

instance receives two times more requests.

8 Click Submit.

Registering a remote instance

Register a new remote instance of ColdFusion using the ColdFusion Administrator.

1 In the ColdFusion Administrator, click Enterprise Manager > Instance Manager > Register Remote Instance.

2 Specify the details such as instance name, remote host, remote port, http port, JVM route, and load balancing factor.

Instance name is a string that is used to identify the instance. Remote port and HTTP port are displayed in the

Instance Manager page. These ports are provided in the server.xml file available in the runtime\conf folder of

the instance. Remote port is the AJP port and the instance port is the connector port.

JVM route is the remote instance name. The JVM route is an attribute that acts as an identifier for a particular

Tomcat worker. JVM route is provided in the server.xml file available in the runtime\conf folder of the instance.

For more information on JVM route, see http://tomcat.apache.org/tomcat-5.5-doc/cluster-howto.html.

Note: A remote instance and a local instance cannot have the same JVM route if they are added in a cluster with sticky

session enabled.

3 If you want remote start and stop functionality over HTTP, enter Admin Component port, Admin Component

user name, and Admin Component password. The default Admin Component port is 8985.

Note: To enable this feature, install admin component on the remote host.

a In the remote host, open the ColdFusion_installtion\cfusion\jetty\etc\jetty.xml.

b Search for the string, org.mortbay.jetty.bio.SocketConnector.

c Update the host with the IP address of the remote host.

d Restart the jetty server.

4 Click Submit.

Adding start and stop functionality to a remote instance over HTTPS

You can start and stop a remote instance over HTTPS or HTTP. To enable this feature, install admin component while

installing ColdFusion. You can install Solr, admin component, or both while installing ColdFusion.

1 Do the following in the remote host.

a In the remote host, generate a private key in a keystore file. Provide the details at prompt.

<CF_installation>\jre\bin\keytool -genkeypair -alias certificatekey -keyalg RSA -validity 7 -keystore keystore.jks

b Export the certificate. You can have a self-signed certificate or a certificate from a Certificate Authority.

<CF_installation>\jre\bin\keytool -export -alias certificatekey -keystore keystore.jks -rfc -file selfsignedcert.cer

c Copy the jks file created in the jetty\etc directory.

Page 11: cf10betafeatures

8COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

d Open the jetty\etc\jetty.xml file.

e Search for the string, To add an HTTPS SSL Listener and add the following entry:

<Call name="addConnector"> <Arg> <New class="org.mortbay.jetty.security.SslSocketConnector">

<Set name="Port">8443</Set> <Set name="maxIdleTime">30000</Set> <Set name="keystore"><SystemProperty name="jetty.home" default="." />/etc/jks-

file.jks</Set> <Set name="password">changeit</Set> <Set name="keyPassword">changeit</Set> <Set name="truststore"><SystemProperty name="jetty.home" default="." />/etc/jks-

file.jks</Set> <Set name="trustPassword">changeit</Set>

</New> </Arg>

</Call>

f Update the keystore name, password, key password, and jks file in the entry.

g Search for the string org.mortbay.jetty.bio.SocketConnector.

h Update the host with the IP address of the remote host.

i Restart the jetty server.

Note: If the remote server is running on Windows Vista, Windows 7, or Windows Server 2008, start the jetty sever

with admin privileges.

2 Do the following in the local host from where you add the remote instance:

a Copy the .cer file created in the remote host to any of the locations.

b Import the certificate.

<CF_installation>\jre\bin\keytool.exe -importcert -keystore "<CF_installation>\jre\lib\security\cacerts" -file selfsignedcert.cer -storepass password

c Register the remote instance using the ColdFusion Administrator. For more information, see Registering a

remote instance.

d In the Register Remote Instance page, enter the admin component port, admin component user name, and

admin component password (user name and password. These details you specified while installing the Remote

Instance Administrator). The default https port is 8443.

e Select the HTTPS check box.

f Click Submit.

Setting up remote start and stop functionality using HTTPS in Server Manager

You can set up start and stop remote instance functionality in Server Manager. To enable this feature, install Remote

Instance Administrator while installing ColdFusion.

1 Do the following in the remote host.

a In the remote host, generate a private key in a keystore file. Provide the details at prompt.

<CF_installation>\jre\bin\keytool -genkeypair -alias certificatekey -keyalg RSA -validity 7 -keystore keystore.jks

Page 12: cf10betafeatures

9COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

b Export the certificate. You can have a self-signed certificate or a certificate from a Certificate Authority.

<CF_installation>\jre\bin\keytool -export -alias certificatekey -keystore keystore.jks -rfc -file selfsignedcert.cer

c Copy the .jks file created in the remote host to the jetty\etc directory.

d Open the jetty\etc\jetty.xml file.

e Search for the string, To add a HTTPS SSL Listener and then add the following entry:

<Call name="addConnector"> <Arg> <New class="org.mortbay.jetty.security.SslSocketConnector">

<Set name="Port">8443</Set> <Set name="maxIdleTime">30000</Set> <Set name="keystore"><SystemProperty name="jetty.home" default="."

/>/etc/server.jks</Set> <Set name="password">changeit</Set> <Set name="keyPassword">changeit</Set> <Set name="truststore"><SystemProperty name="jetty.home" default="."

/>/etc/server.jks</Set> <Set name="trustPassword">changeit</Set>

</New> </Arg>

</Call>

f Update the keystore name, password, key password, and jks file in the entry.

g Search for the string, org.mortbay.jetty.bio.SocketConnector.

h Update the host with the port number of the remote host.

i Restart the jetty server.

Note: If the remote server is running on Windows Vista, Windows 7, or Windows Server 2008, start the jetty sever

with admin privileges.

2 Do the following in the local host from where you add remote instance:

a Copy the .cer file created in the remote host to any of the locations.

b Import the certificate.

<CF_installation>\jre\bin\keytool.exe -importcert -keystore "<CF_installation>\jre\lib\security\cacerts" -file selfsignedcert.cer -storepass password

3 Open wwwroot\CFIDE\ServerManager\ServerManager.air on the local host.

4 Specify the connection details.

5 Click Start/Stop Details.

6 Select HTTPS.

7 Provide the following information:

• App Server Username: User name for the admin component that you specified while installing ColdFusion.

Default value is admin.

• App Server Password: Password for the admin component.

• Port: ColdFusion remote instance’s HTTPS port.

• Server: ColdFusion remote instance name.

Page 13: cf10betafeatures

10COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

• ColdFusion Version: For ColdFusion, the version is 10.

• Admin Server Port: Default https port is 8443. Port of the Jetty server.

• Context Root: Value is AdminServlet.

8 Click Apply.

Setting up remote start and stop functionality using HTTP in Server Manager

You can set up start and stop remote instance functionality in Server Manager. To enable this feature, install Remote

Instance Administrator while installing ColdFusion.

1 Do the following in the remote host:

a In the remote host, open the ColdFusion_installtion\cfusion\jetty\etc\jetty.xml.

b Search for the string, org.mortbay.jetty.bio.SocketConnector.

c Update the host with the IP address of the remote host.

d Start the jetty server. Go to the ColdFusion_installation\cfusion\jetty directory and use jetty.exe.

You can also use the jetty services in the Windows services.

2 Open wwwroot\CFIDE\ServerManager\ServerManager.air on the local host.

3 Specify the connection details.

4 Click Start / Stop Details.

5 Select HTTP.

6 Provide the following information:

• App Server Username: User name for the admin component that you specified while installing ColdFusion.

The default value is admin.

• App Server Password: Password for the admin component.

• Port: ColdFusion remote instance’s HTTP port.

• Server: ColdFusion remote instance name.

• ColdFusion Version: For ColdFusion Zeus, 10.

• Admin Server Port: Default https port is 8985. Port of the Jetty server.

• Context Root: Value is AdminServlet.

7 Click Apply.

Managing clusters

Manage clusters using the ColdFusion Administrator.

1 In the ColdFusion Administrator, click Enterprise Manager > Cluster Manager.

2 Enter a cluster name and then click Add.

3 Click the cluster name and move the servers to the cluster based on the requirement.

4 (If necessary) Edit the multicast port.

Multicast port is used to group the cluster members together. Default value of multicast port is 45564. After you

create a cluster, the port is added in the cf_install_dir\config\cluster.xml file.

For more information on multicast port, see http://tomcat.apache.org/tomcat-7.0-doc/config/cluster-

membership.html

Page 14: cf10betafeatures

11COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

5 Specify if you need sticky session.

Sticky session ensures that after a session is established on an instance, all future requests from the client are

mapped to that instance.

6 Click Submit.

Adding a remote instance to a cluster

To add a remote instance to a cluster, add the cluster block to the remote instance’s server.xml. Then, register the

remote instance and add the instance to the cluster. For more information on configuring clusters on Tomcat, see

http://tomcat.apache.org/tomcat-7.0-doc/cluster-howto.html..

1 Register the remote instance to the local machine.

2 Create a cluster in the local machine.

3 Open the cf_install_dir\instance-name\runtime\conf\server.xml file of the remote instance.

4 Add the following block between the entries </host> and </engine>:

<Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster" channelSendOptions="8">

<Manager notifyListenersOnReplication="true" expireSessionsOnShutdown="false" className="org.apache.catalina.ha.session.DeltaManager">

</Manager> <Channel className="org.apache.catalina.tribes.group.GroupChannel">

<Membership port="45565" dropTime="3000" address="228.0.0.4" className="org.apache.catalina.tribes.membership.McastService" frequency="500">

</Membership> <Receiver port="4003" autoBind="100" address="auto" selectorTimeout="5000"

maxThreads="6" className="org.apache.catalina.tribes.transport.nio.NioReceiver"> </Receiver> <Sender className="org.apache.catalina.tribes.transport.ReplicationTransmitter">

<Transport className="org.apache.catalina.tribes.transport.nio.PooledParallelSender">

</Transport> </Sender> <Interceptor

className="org.apache.catalina.tribes.group.interceptors.TcpFailureDetector"> </Interceptor> <Interceptor

className="org.apache.catalina.tribes.group.interceptors.MessageDispatch15Interceptor"> </Interceptor>

</Channel> <Valve className="org.apache.catalina.ha.tcp.ReplicationValve" filter=""> </Valve> <Valve className="org.apache.catalina.ha.session.JvmRouteBinderValve"> </Valve>

<ClusterListener

className="org.apache.catalina.ha.session.JvmRouteSessionIDBinderListener"> </ClusterListener> <ClusterListener className="org.apache.catalina.ha.session.ClusterSessionListener"> </ClusterListener>

</Cluster>

5 In the entry, update the membership port with the multicast port of the cluster.

Page 15: cf10betafeatures

12COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

6 Using the ColdFusion Administrator of the local host, add the local instance and the remote instance to the cluster.

Note: If you enable sticky session, the JVM route of the remote instance and local instance must not be the same.

7 Restart all the instances.

Configuring other web servers

Use the Web Server Configuration Tool to configure other web servers.

❖ Run cf_install_dir\runtime\bin\wsconfig.exe.

You can also configure web servers using the command-line interface as follows.

Configuring IIS

./wsconfig -ws iis -site <site_no>

or

./wsconfig -ws iis -site <site_name>

Configuring cluster

./wsconfig -ws iis -site <site_no> -cluster <cluster-name>

Configuring Apache

./wsconfig –ws apache –dir <apache_conf_directory>

or

./wsconfig –ws apache –dir <apache_conf_directory> –bin <apache_bin_directory>/httpd –script <apache_bin_directory>/apachectl

Configuring cluster

./wsconfig -ws apache –dir <apache_conf_directory> -cluster <cluster-name>

Configuring SunOne

./wsconfig –ws SunOne –dir <SunOne_conf_directory>

Configuring cluster

./wsconfig -ws SunOne –dir <SunOne_conf_directory> -cluster <cluster-name>

Unconfiguring IIS

./wsconfig -remove -ws iis -site <site_no>

or

./wsconfig -remove iis -site <site_name>

Unconfiguring Apache

./wsconfig -remove –ws apache –dir <apache_conf_directory>

or

./wsconfig -remove –ws apache –dir <apache_conf_directory> –bin <apache_bin directory>/httpd –script <apache_bin_directory>/apachectl

Unconfiguring SunOne

./wsconfig -remove –ws SunOne –dir <SunOne_conf_directory>

Unconfiguring all webservers

Page 16: cf10betafeatures

13COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

./wsconfig -uninstall

Seeing the list of webservers

./wsconfig -list

Configuring Secured Socket Layer (SSL)

SSL allows the browser and the server to communicate over a secured connection. Data that is sent is encrypted at one

side, transmitted, and then decrypted at the other end. For more information about SSL configuration on Tomcat, see

http://tomcat.apache.org/tomcat-7.0-doc/ssl-howto.html.

To configure SSL for ColdFusion using the keytool utility, do the following:

1 Create a certificate file:

a Run the following command:

cf_install_dir\jre\bin\keytool -genkey -alias tomcat -keyalg RSA

b Type the details as per the instruction.

Note: If you do not provide a password, the default password for keystore and key is changeit. If you don’t want to

use the default password, ensure that you provide the same password for the keystore and the key.

Running this command creates a certificate.keystore in the following location:

• Windows: C:\Documents and Settings\user's_directory

• Linux: usr/home

2 Open the cf_install_dir\cfusion\runtime\conf\server.xml file and search for the string Define a SSL

HTTP/1.1.

3 Uncomment the connector details and update the section as follows:

<Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true" maxThreads="150" scheme="https" secure="true" keystoreFile="<certificate_location>\.keystore"

keystorePass="<password>" keyAlias="tomcat" clientAuth="false" sslProtocol="TLS" />

4 Restart ColdFusion.

5 Access ColdFusion using the following URL: https://<ip-address>:8443/CFIDE/administrator

Changing virtual directory and the doc root

Do the following to change the virtual directory and doc root:

1 Open CFInstallation\cfusion\runtime\conf\server.xml.

2 Under host block, search for the string, “To add virtual directory.”

3 Uncomment the entry context path below.

4 To add a virtual directory, add the aliases attribute as shown below:

<Context path="/" docBase="<absolute_path_to_CF_install_directory>\wwwroot" WorkDir="<cf_home>\runtime\conf\Catalina\localhost\tmp" aliases="/path1=<absolute_path_to_directory1>,/path2=<absolute_path_to_directory2>"></Context>

Note: Alias path must include a leading ‘/’.

5 To change the doc root, change the docBase value in the above entry.

For more details on the Context attributes, see http://tomcat.apache.org/tomcat-6.0-doc/config/context.html.

Page 17: cf10betafeatures

14COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Changing the connector port for cfstat

You can use the connector output for logging cfstat metric. The cfconnector port is defined in the

CFInstallation/cfusion/lib/neo-metric.xml file. If you have configured a connector, update the port with the

connector port. The connector port (AJP port) is provided in the

CFInstallation/cfusion/runtime/conf/server.xml.

To update the connector port using the Administrator console:

1 Login ColdFusion Administrator.

2 Click Debugging & Logging > Debug Output.

3 Update the connector port and click Submit Changes.

Enabling Search Engine Safe URLs

Search Engine Safe URL (SES) helps the search engines to index dynamic web pages. SES URLs pass parameters using

slashes instead of default URL pattern. By default, SES is enabled for stand-alone installation of ColdFusion on

Tomcat.

Note: SES is applicable only for stand-alone installation of Tomcat. It does not work if ColdFusion is deployed as a WAR

file on Tomcat.

Changing the log rotation settings

You can change the log rotation settings such as maximum number of backup files and the size of the backup files.

1 Open the ColdFusion_installation_dir\cfusion\lib\neo-logging.xml file.

2 Change the following details:

• maxFileBackup: The number of backup files needed.

• maxFileSize: The size of each backup file in KB.

3 Save the file.

Enabling persistent session

To persist a session after a Tomcat restart, do the following:

1 Open the ColdFusion_installation_dir\cfusionruntime\conf\context.xml file.

2 Uncomment the Manager pathname node.

Note: Flex sessions are not persisted after a Tomcat restart.

Configure Apache virtual host for each ColdFusion instance

Assume that you have two instances: cfusion and server1.

1 Configure Apache webserver for cfusion instance using the wsconfig tool.

This step creates the connector-related files in the cf_root\config\wsconfig\1 folder. It also creates the

mod_jk.conf in the <Apacheroot>\conf folder. The mod_jk.conf file is included in the httpd.conf.

2 Configure Apache virtual hosts.

a In workers.properties of cf-root\config\wsconfig\1, add server1 to workers.list. For example,

worker.list=cfusion,server1.

b Add the following block:

Page 18: cf10betafeatures

15COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

worker.server1.type=ajp13 worker.server1.host=localhost worker.server1.port=8014

Note: The port is the AJP port for server1 and that can be found in server1.server.xml in the

cf_root\server1\runtime\conf\server.xml.

c Copy the content of uriworkermap.properties in cf-root\config\wsconfig\1 to

uriworkermap1.properties. Replace the cfusion with server1.

d Now add the following line in each of the virtual host: For example, VH1 is the ColdFusion instance. It should

have: JkMountFile "cf_root\config\wsconfig\1\uriworkermap.properties" VH2 is the server1

instance. It should have JkMountFile "cf_root\config\wsconfig\1".

New function sessionStartTime

Description

Provides information about the time when the session was created.

Returns

Session creation time

Syntax

SessionStartTime()

History

ColdFusion 10 Beta: Added this function.

Example

<cfset startTime = sessionStartTime() >

Security enhancements

Security enhancements in ColdFusion 10 Beta let you reduce XSS and CSRF attack vulnerability. The enhancements

also help you manage ColdFusion sessions effectively. The release also includes fixes that reduce other vulnerabilities.

XSS attack

Cross-site scripting (XSS) attacks bypass client-side security mechanisms imposed by web browsers. These methods

use Open Web Application Security Project's (OWASP) Enterprise Security API for encoding. An attacker injects

malicious scripts into a web page to access information stored in the browser.

• Only the following characters are allowed as values for the attribute name in the tag cform: alphanumeric

characters, _ (underscore), - (hyphen), : (colon), and . (dot). It prevents stored XSS for the scriptsrc field.

• The following new encoding methods are added to reduce XSS attack vulnerability: encodeForHTML,

encodeForHTMLAttribute, encodeForJavaScript, encodeForCSS, and encodeForURL. Encode the user inputs

depending on the contexts. To decode the input string, added a method: canonicalize

Example: encodeForHTML

This example displays the text that you enter and submit. Enter a script function, say alert(), and execute.

Observe that the script is displayed as a text.

Page 19: cf10betafeatures

16COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

<cfif isDefined("form.submit")> <b> Output:<cfoutput >#encodeForHTML(form.userName)#</cfoutput> </b>

<cfelse> <cfset form.username=""/>

</cfif> <cfform>

<cfinput name="userName" type="text" value="#form.userName#"> <cfinput name="submit" type="submit" value="Submit">

</cfform>

Example: encodeForHTMLAttribute(inputString)

This example displays a text field highlighted in red. Enter a numeric value in the text field and submit. The value

is passed as an HTML attribute and it changes the width of the text field.

<cfif not isDefined ("form.submit")> <cfset form.width = 200 />

</cfif> <cfoutput >

<table width="#encodeForHTMLAttribute(form.width)#" border="1" bgcolor="RED"> <tr>

<td> Enter the value in the below text field.

</td> </tr>

</table> </cfoutput> <cfform>

<cfinput name="width" type="text" value="#form.width#"> <cfinput name="submit" type="submit" value="Submit">

</cfform>

encodeForHTML

Description

Encodes the input string for use in HTML.

Returns

Encoded string

Category

Display and formatting functions

Syntax

encodeForHTML(inputString [,strict])

See also

encodeForHTMLAttribute, encodeForJavaScript, encodeForCSS, encodeForURL, canonicalize

History

ColdFusion 10 Beta: Added this function.

Page 20: cf10betafeatures

17COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Parameters

Example

<cfif isDefined("form.submit")> <b> Output:<cfoutput >#encodeForHTML(form.userName)#</cfoutput> </b>

<cfelse> <cfset form.username=""/>

</cfif> <cfform>

<cfinput name="userName" type="text" value="#form.userName#"> <cfinput name="submit" type="submit" value="Submit">

</cfform>

encodeForHTMLAttribute

Description

Encodes the input string for use in HTML attribute, such as table width or image height.

Returns

Encoded string

Category

Display and formatting functions

Syntax

EncodeForHTMLAttribute(inputString [,strict])

See also

encodeForHTML,encodeForJavaScript, encodeForCSS, encodeForURL, canonicalize

History

ColdFusion 10 Beta: Added this function.

Parameters

Parameter Description

inputString Required. The string to encod.

strict Optional. If set to true, it restricts multiple and mixed encoding.

Parameter Description

inputString Required. The string to encod.

strict Optional. If set to true, it restricts multiple and mixed encoding.

Page 21: cf10betafeatures

18COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Example

<cfif not isDefined ("form.submit")> <cfset form.width = 200 />

</cfif> <cfoutput >

<table width="#encodeForHTMLAttribute(form.width)#" border="1" bgcolor="RED"> <tr>

<td> Enter the value in the below text field.

</td> </tr>

</table> </cfoutput> <cfform>

<cfinput name="width" type="text" value="#form.width#"> <cfinput name="submit" type="submit" value="Submit">

</cfform>

encodeForJavaScript

Description

Encodes the input string for use in JavaScript.

Returns

Encoded string

Category

Display and formatting functions

Syntax

encodeForJavaScript(inputString [,strict])

See also

encodeForHTML,encodeForHTMLAttribute, encodeForCSS, encodeForURL, canonicalize

History

ColdFusion 10 Beta: Added this function.

Parameters

Parameter Description

inputString Required. The string to encod.

strict Optional. If set to true, restricts multiple and mixed encoding.

Page 22: cf10betafeatures

19COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Example

<cfif isDefined ("form.submit")> <!--- If the user submits the form, show him/her a JavaScript alert. --->

<cfoutput > <script type="text/javascript">

alert('Hello #encodeForJavascript(form.userName)# !!!'); // For security purpose, encode the user-generated input, so that it does not

execute malicious codes. </script> </cfoutput>

<cfelse > <cfset form.username = "" />

</cfif> <cfform action="#cgi.SCRIPT_NAME#" method="post" >

<cfinput name="userName" type="text" value="#form.userName#"> <cfinput name="submit" type="submit" value="SayHello!!!">

</cfform>

encodeForCSS

Description

Encodes the input string for use in CSS.

Returns

Encoded string

Category

Display and formatting functions

Syntax

encodeForCSS(inputString [,strict])

See also

encodeForHTML,encodeForHTMLAttribute, canonicalize

History

ColdFusion 10 Beta: Added this function.

Parameters

Parameter Description

inputString Required. The string to encode.

strict Optional. If set to true, restricts multiple and mixed encoding.

Page 23: cf10betafeatures

20COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Example

<cfif not isDefined ("form.bgcolor")> <cfset form.bgcolor = 'red'>

</cfif> <cfoutput> <style>

.myDiv {

background-color : #encodeForCSS(form.bgcolor)#; /* Encode the input to avoid any malicious code execution.*/

} </style> </cfoutput> <hr/> <cfoutput>

<div class="myDiv"> This div element is styled!!!!

</div> </cfoutput> <hr/> <cfform action="#cgi.SCRIPT_NAME#" method="post" >

Background Color : <cfinput name="bgcolor" type="text" value="#form.bgcolor#"> <br/><cfinput name="submit" type="submit" value="Style the div!!!"> </cfform>

encodeForURL

Description

Encodes the input string for use in URLs.

Returns

Encoded string

Category

Display and formatting functions

Syntax

encodeForURL(inputString [,strict])

See also

encodeForHTML,encodeForHTMLAttribute, encodeForJavaScript, canonicalize

History

ColdFusion 10 Beta: Added this function.

Parameters

Parameter Description

inputString Required. The string to encode.

strict Optional. If set to true, it restricts multiple and mixed encoding.

Page 24: cf10betafeatures

21COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Example

<cfif not isDefined ("form.url")> <cfset form.url = "www.adobe.com">

</cfif> <cfform action="#cgi.SCRIPT_NAME#" method="post">

<cfinput name="url" type="text" value="#form.url#"> <cfinput name="submit" type="submit" value="Show link to this URL!!!">

</cfform> <hr /> <cfoutput >

<b>LINK to URL:</b> <a target="_blank" href="http://#encodeForURL(form.url)#">#encodeForURL(form.url)#</a> </cfoutput>

canonicalize

Description

Canonicalize or decode the input string.

Returns

Decoded form of input string.

Category

Display and formatting functions

Syntax

canonicalize(inputString, restrictMultiple, restrictMixed)

History

ColdFusion 10 Beta: Added this function.

See also

encodeForHTML,encodeForHTMLAttribute, encodeForJavaScript, encodeForCSS, encodeForURL

Parameters

Example

<cfoutput>#canonicalize("&lt;",false,false)#</cfoutput><br/> <cfoutput>#canonicalize("%26lt; %26lt; %2526lt%253B %2526lt%253B %2526lt%253B",false,false)#</cfoutput><br/> <cfoutput>#canonicalize("&##X25;3c",false,false)#</cfoutput><br/> <cfoutput>#canonicalize("&##x25;3c",false,false)#</cfoutput><br/>

Parameter Description

inputString Required. The string to be encode.

restrictMultiple Required. . If set to true, multiple encoding is restricted.

restrictMixed Required. If set to true, mixed encoding is restricted.

Page 25: cf10betafeatures

22COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

CSRF attack

Cross-Site Request Forgery (CSRF) forces users to execute unwanted actions on a web application for which they are

authenticated. For example, sending a URL using an email or chat to a privileged user. Clicking the URL link forces

the user to do an action of the attacker's choice.

• Following methods can be used to reduce CSRF vulnerability:

• CSRFGenerateToken: Returns a random token and stores it in the session.

• CSRFVerifyToken: Validates the given token and the key against the same stored in the session.

Example: CSRFGenerateToken

The following example lets you enter value and submit. The page generates a token and calls another ColdFusion page.

<cfset csrfToken=CSRFGenerateToken() /> <cfform method="post" action="sayHello.cfm">

<cfinput name="userName" type="text" > <cfinput name="token" value="#csrfToken#" type="hidden" > <cfinput name="submit" value="Say Hello!!" type="submit" >

</cfform>

The following page, sayHello.cfm, validates the token generated and displays the output of

CSRFverifyToken(token).

<cfset token=form.token> <cfset validate = CSRFverifyToken(token)>

<cfoutput >#validate#</cfoutput>

Note: Enable SessionManagement for protection against CSRF. Disabling session variables in the administrator

console disables CSRF protection.

CSRFGenerateToken

Description

Provides a random token and stores it in the session. You can also provide a specific key to store in the session.

Returns

Token

Category

Display and formatting functions

Syntax

CSRFGenerateToken([key] [,forceNew])

See also

CSRFVerifyToken

History

ColdFusion 10 Beta: Added this function.

Page 26: cf10betafeatures

23COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Parameters

Usage

Use this function to create a random token and store it in the session.

Example

<cfset csrfToken=CSRFGenerateToken() /> <cfform method="post" action="sayHello.cfm">

<cfinput name="userName" type="text" > <cfinput name="token" value="#csrfToken#" type="hidden" > <cfinput name="submit" value="Say Hello!!" type="submit" >

</cfform>

CSRFVerifyToken

Description

Validates the given token against the same stored in the session for a specific key.

Returns

a Boolean value. true is successful.

Category

Display and formatting functions

Syntax

CSRFVerifyToken(token [,key])

See also

CSRFGenerateToken

History

ColdFusion 10 Beta: Added this function.

Parameters

Usage

Use this function to validate the given token against the same stored in the session for a specific key.

Parameter Required\Optional Description

key optional A random token is generated based on the key provided. This key is stored

in the session.

forceNew optional If set to true, a new token is generated every time the method is called. If

false, in case a token exists for the key, the same key is returned.

Parameter Required\Optional Description

token required Token that to be validated against the token stored in the session.

key optional The key against which the token is searched.

Page 27: cf10betafeatures

24COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Example

<cfset token=form.token> <cfset validate = CSRFverifyToken(token)>

<cfoutput >#validate#</cfoutput>

Session improvements

You can manage ColdFusion session cookies effectively.

CF Session cookies (CFID, CFTOKEN, CFAuthorization_<app-name>)

The new features to manage session cookies are:

• The following properties of ColdFusion session cookies can be configured at server level or application level:

• httponly: true by default

• secure: false by default

• domain

• timeout: 30 years by default

You can set the session cookies at the application level by specifying the settings as a struct in the Application.cfm

as shown in the following example:

<cfset cookiest = {httponly='true', timeout=createTimeSpan(0, 0, 0, 10), secure='true',domain=".domain.com"}> <cfset cookieast = {timeout=createTimeSpan(0, 0, 00, 10)}> <cfapplication name="sessionCookies_appcfm_allSetting" sessionmanagement="Yes" sessiontimeout="#createTimeSpan(0,0,03,0)#" scriptprotect="all" sessioncookie=#cookiest# authcookie=#cookieast#>

Note: The application level setting takes precedence over the server level setting.

Use the following new admin APIs to set session cookies at the server level by providing the parameters

getRuntimeProperty and setRuntimeProperty. These methods are available in the

CFIDE\adminapi\runtime.cfc file.

The following example explains how to get the cookie parameters using the getRuntimeProperty() method. Set

the cookie parameters in the similar way using the setRuntimeProperty() method.

GetRuntimeProperty("HttpOnlySessionCookie"); GetRuntimeProperty("SecureSessionCookie"); GetRuntimeProperty("SessionCookieTimeout"); GetRuntimeProperty("SessionCookieDomain");

• The session cookies can be set at the application level by specifying the following in the Application.cfc:

• this.sessioncookie.httponly="true"

• this.sessioncookie.secure="true"

• this.sessioncookie.domain="value"

• this.sessioncookie.timeout="value" (days)

• this.authcookie.timeout= "value" (-1 by default. Cookie is valid until the browser is open.)

Note: You can define the SetDomainCookies property and set session cookies for domain at application and server

level. In this case, the precedence is as follows: application settings, server settings, and the SetDomianCookies

property.

Page 28: cf10betafeatures

25COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Note: The system property, coldfusion.sessioncookie.httponly=true, that was added in ColdFusion 9.01 is

not required in this release and therefore has been removed.

Note: Using CFCookie and CFHeader tags to manipulate ColdFusion cookie and authorization cookie can be

controlled in application or server level configuration. Add the following in application.cfc or application.cfm:

sessioncookie.disableupdate=true and authcookie.disableupdate=true. You can also use the following

methods in the CFIDE\adminapi\runtime.cfc: GetRuntimeProperty("CFInternalCookieDisableUpdate")

and SetRuntimeProperty("CFInternalCookieDisableUpdate", "true/false")To set the tags in the

ColdFusion administrator, go Server Settings > Memory Variables > Session Cookies Settings. Select or deselect

“Disable Updating ColdFusion internal cookies using ColdFusion Tags\Function .”

• The <cflogin> tag stores the password in cache. For longer authenticated sessions, you can enable

diskPeristent by modifying authcache located in the cfhome/lib/auth-ehcache.xml file. The directory

used for persistence should be secured.

New methods

The new methods added for session management are:

• SessionInvalidate

• SessionRotate

SessionInvalidate

Description

Invalidates or cleans up the current session.

Note: The sessionInvalidate() method does not invalidate the underlying J2EE session.

Returns

None

Category

Display and formatting functions

Syntax

sessionInvalidate()

See also

SessionRotate

History

ColdFusion 10 Beta: Added this function.

Parameters

None

Usage

Use this function to invalidate the existing session.

Page 29: cf10betafeatures

26COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Example

Application.cfc

<cfcomponent> <cfset this.sessionManagement = true /> <cfset this.name = "session_app" /> </cfcomponent>

sessionInvalidate.cfm

<cfif isDefined("url.invalidate") > <cfset sessionInvalidate()/>

</cfif> <cfif isDefined("url.name") >

<cfset session.name = url.name /> </cfif> <cfdump var="#session#" label="SESSION"> <cfoutput> <a href="sessionInvalidate.cfm?name=BOB">Set session.name = BOB </a> <br/> <a href="sessionInvalidate.cfm?invalidate=TRUE">Invalidate the session</a> </cfoutput>

SessionRotate

Description

Renews the session when started. For example, you want to generate a new session after a successful login. It prevents

session attacks, because the session before and after a successful authentication is different.

The method,

• Creates a session

• Copies the data from the old session to the new session

• Invalidates the old session

• Invalidates or overwrites the old session cookies

• Creates new session cookies if the old session cookies are invalidated

• Copies and updates client storage data to new session keys

Returns

None

Category

Display and formatting functions

Syntax

SessionRotate()

See also

SessionInvalidate

History

ColdFusion 10 Beta: Added this function.

Page 30: cf10betafeatures

27COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Parameters

None

Usage

Use this function to rotate the session.

Example

Application.cfc

<cfcomponent> <cfset this.sessionManagement = true /> <cfset this.name = "session_app" /> </cfcomponent>

sessionRotate.cfm

<cfif isDefined("url.rotate") > <cfset sessionRotate()/>

</cfif> <cfif isDefined("url.name") >

<cfset session.name = url.name /> </cfif> <cfdump var="#session#" label="SESSION"> <cfoutput> <a href="sessionRotate.cfm?name=BOB">Set session.name = BOB </a> <br/> <a href="sessionRotate.cfm?rotate=TRUE">Rotate the session</a> </cfoutput>

CRLF attack

Carriage Return (ASCII 13, \r) Line Feed (ASCII 10, \n) (CRLF) attacks also referred as HTTP Response Splitting.

Here, an attacker injects CRLF to an http stream. It is commonly done by modifying an HTTP parameter or URL. In

this way, CRLF can be injected into an application and can be included in response. The CRLF interpreted by proxies

and caches create serious security issues.

• Protection is added against CRLF attacks for the tags which create a header, for example, cfheader, cfcontent,

cfmail, cfmailpart, and cfmailparam.

Information disclosure

This feature improves security-related issues on information disclosure.

• Passwords for all services are encrypted in this version.

Change password seed only when the server is running without any load. Otherwise, you face unexpected behavior

of the server.

New HMAC method

Hash-based Message Authentication Code (HMAC) is used to verify the data integrity and authenticity of a message

transmitted. It involves a cryptographic hash function in combination with a secret key. The cryptographic hash

function can be Message Digest 5 (MD5), and Secure Hash Algorithm (SHA), and so on.

Page 31: cf10betafeatures

28COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

HMac

Description

Creates Hash-based Message Authentication Code for the given string based on the algorithm and encoding. Hash-

based Message Authentication Code (HMAC) is used to verify the data integrity and authenticity of a message

transmitted. It involves a cryptographic hash function in combination with a secret key. The cryptographic hash

function can be Message Digest 5 (MD5), Secure Hash Algorithm (SHA), and so on.

Returns

a Boolean value. true if successful.

Category

Display and formatting functions

Syntax

HMac(message, key [,algorithm] [,encoding])

See also

SessionInvalidate, SessionRotate

History

ColdFusion 10 Beta: Added this function.

Parameters

Usage

Use this function to create Hash-based Message Authentication Code for the given string based on the algorithm and

encoding.

Example

<h2>HMAC Test</h2> <cfset x=hmac("Hi There","key1","HMACRIPEMD160")> <cfoutput>#x#</cfoutput>

cfcookie support in CFScript

Cookies can be set as a struct in CFScript. You can set the following parameters:

• expires

• value

• name

Parameter Required\Optional Description

message Required The message to transmit. The message can be a String or a byte array.

key Required The secret key to create HMAC. The key can be a String or a byte array.

algorithm Optional Algorithm used.

encoding Optional Encoding to be used.

Page 32: cf10betafeatures

29COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

• secure

• httponly

• domain

• path

• preservecase

• encodevalue

Example 1

<cfscript > cookie.mytest = {value="Adobe",expires="10",secure="true",domain=".adobe.com",path="/coldfusion"}; </cfscript>

Example 2

<cfscript> cookie_example = structNew(); cookie_example.value = "example"; cookie_example.expires = "10"; cookie_example.secure = "true"; cookie.mycookie = cookie_example;

</cfscript>

Miscellaneous Changes

• The httponly cookies support is available on Tomcat supporting J2EE 1.6.

• A new parameter, numIteration, is added to the hash() method.

This optional parameter specifies the number of times the hash is iterated. The updated hash() method is as

follows:

hash(Object message, String algorithm, String encoding, int no-of-iterations)

The first argument can be an object of String or Byte[] type.

Example

Page 33: cf10betafeatures

30COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

<!--- Do the following if the form is submitted. ---> <cfif IsDefined("Form.UserID")> <!--- query the data base. ---> <cfquery name = "CheckPerson" datasource = "cfdocexamples">

SELECT PasswordHash FROM SecureData WHERE UserID = <cfqueryparam value = "#Form.userID#" cfsqltype = 'CF_SQL_VARCHAR'> </cfquery> <!--- Compare query PasswordHash field and the hashed form password and display the results. ---> <cfoutput>

<cfif Hash(Form.password, "SHA","",4) is not checkperson.passwordHash> User ID #Form.userID# or password is not valid. Try again.

<cfelse> Password is valid for User ID #Form.userID#. </cfif>

</cfoutput> </cfif> <!--- Form for entering ID and password. ---> <form action="#CGI.SCRIPT_NAME#" method="post"> <b>User ID: </b> <input type = "text" name="UserID" ><br> <b>Password: </b> <input type = "text" name="password" ><br><br> <input type = "Submit" value = "Encrypt my String"> </form>

• Strengthened <cflogin> and authorization cookies.

In a clustered environment, enable sticky session. If sticky session is not enabled, do the following:

Note: Different ways of adding distributed cache can be found at the Ehcache website.

• Configure authentication cache for the clustered environment. Do the following for each instance in the cluster:

1 Open CF_instance/lib/auth-ehcache.xml.

2 Search for the string, Mandatory Default Cache configuration and add the following entry:

<!-- distributed caching settings part 1 starts --> <cacheManagerPeerProviderFactory

class="net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory" properties="peerDiscovery=automatic, multicastGroupAddress=230.0.0.1, multicastGroupPort=4446, timeToLive=32"/>

<cacheManagerPeerListenerFactoryclass="net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory"

properties="port=40002, socketTimeoutMillis=3000"/> <!-- distributed caching settings part 1 ends -->

3 In the above entry, update the cacheManagerPeerListenerFactory properties port. It must be unique for

each instance.

4 Search for the string, <cache name="authcache".

5 Add the following entry after clearOnFlush="true">.

clearOnFlush="true"> <cacheEventListenerFactory class="net.sf.ehcache.distribution.RMICacheReplicatorFactory" properties="replicateAsynchronously=false, replicatePuts=true, replicatePutsViaCopy=false, replicateUpdates=true, replicateUpdatesViaCopy=true, replicateRemovals=true" propertySeparator=","/> </cache>

Note: ColdFusion administrator does not support cluster setup.

Page 34: cf10betafeatures

31COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Note: For Remember Me type of functionalities or for keeping authentication cache alive for a long time, change the

authentication cache settings. For example, increase time outs, enable persistent cache, and so on.

Note: Use new cookie configuration for more secured authentication. Depending on the requirement, do the

configuration at the server lever or application level.

• You are logged out from one of the ColdFusion administrators, if:

• From the same host, you log in to the ColdFusion (10) Administrator and the ColdFusion Administrator of an

older version.

• For a user with RDS access, in the ColdFusion Administrator, you can set the data source and secured file path

permissions.

• The default values for the new sandbox are changed to make it more secure.

• In ColdFusion, if the action attribute is not specified in the <cfform> tag, it does not generate the same using the

current URL. If there are issues, add the following entry in the ColdFusion-install-

dir\cfusion\bin\jvm.config file: Dcoldfusion.generateformaction=true

Using ColdFusion WebSocket

What is WebSocket

WebSocket is a protocol for two-way communication with a remote host over TCP protocol exposed through

JavaScript interface in HTML 5 compliant browsers. WebSocket facilitates communication between hosts in both the

directions simultaneously.

How is WebSocket different from conventional communication models

WebSocket is based on HTML 5 server Push Technology. The communication request is initiated by the publisher or

central server following a publish/subscribe model.

This is unlike the request/response model that HTTP relies on, which has drawbacks such as request time-out and

browser refresh.

In the case of WebSocket, a client subscribes to various information channels. If new content is available in the

channel, it is pushed to the clients. This method has the following advantages:

• Simultaneous bi-directional communication

• Lesser browser reloads

• Ease in creating applications that handle real-time data

ColdFusion and WebSocket

ColdFusion 10 implements WebSocket by providing a messaging layer for the WebSocket protocol, which you can

control using CFML and JavaScript.

The messaging layer has features that make WebSocket reliable and scalable. Using WebSocket, you can develop real-

time applications for stock, charting, online gaming, social networking, dashboard for various purposes, and

monitoring.

Browsers and fallback

ColdFusion leverages the browser-supported HTML5 native WebSocket to provide server controlled client-to-client

communication. If a browser currently does not have HTML5 support or the native WebSocket support, ColdFusion

uses Flash player as the fallback option. Fallback to Flash is smooth and automatic.

Page 35: cf10betafeatures

32COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

See also, “Browser support for WebSocket” on page 54.

The following table provides the fallback plan for ColdFusion WebSocket:

WebSocket communication models

ColdFusion WebSocket offers the following two communication models:

• Broadcast: Follows a subscriber/publisher model where hosts include multiple clients and server. Publishing is

possible in either of the following ways:

• From client-side (by way of the server)

• Initiation from the server without client involvement

• Point-to-point: A bi-directional communication between a specific client and server. This model does not involve

any other hosts/multiple clients.

Using WebSocket to broadcast messages

The following procedures let you create a broadcast setup:

Defining a communication channel

Specify the following settings in the Application.cfc to define the communication channel:

component { this.name="testapp"; this.wschannels=[{name = channelName,cfclistener= channel_listener_CFC}]; }

Description

• Specify the channel name.

Note: Though you can use any number of sub-channels, you do not specify them. They are dynamically created.

Scenario What happens

Native WebSocket support available Establishes a WebSocket connection.

Native WebSocket unavailable, but Flash is

installed

Automatically falls back to Flash.

No native WebSocket support or Flash installation Sends a message indicating that the connection is not successful.

To proceed, either move on to a compliant browser or install Flash.

Step Procedure Description

1 Define communication channels in the

Application.cfc

Client can subscribe or publish to a pre-defined set of channels.

To listen to the channel, first register it at the application level.

2 Create WebSocket object using the

cfwebsocket tag in your CFM template

Creates WebSocket connection with all required properties

automatically, and wraps it in a JavaScript object that can invoke

various JavaScript methods.

The tag internally identifies the IP address and port of the server.

3 Implement the business logic using the

JavaScript functions provided by the

WebSocket object

On runtime, you can make use of the supported JavaScript functions

for example, subscribe or publish to achieve your business goals.

Page 36: cf10betafeatures

33COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

• If necessary, specify the ColdFusion channel listener CFC, the component responsible for creating the channel. If

not specified, the default ChannelListener.cfc, available in wwwroot\CFIDE\websocket directory is called.

For further details, see “Using channel listener functions” on page 39.

Creating WebSocket object using cfwebsocket

The new ColdFusion tag cfwebsocket lets you create the WebSocket object in your CFM template. The tag creates a

reference to the WebSocket JavaScript object at the client-side.

Syntax

<cfwebsocket name="websocketName" onMessage="JavaScript function name" onOpen="JavaScript function name" onClose="JavaScript function name" onError="JavaScript function name" useCfAuth=true|false subscribeTo="channel_list">

Attribute

Usage

By specifying the attribute name, for example, mycfwebsocketobject (as in the following example), you create a

JavaScript object.

The JavaScript object can be used to call various Using the WebSocket JavaScript functionswhich you use for the

WebSocket communication.

Attribute Req/Opt Descriptions

name Required The name of the WebSocket object.

This is the reference to the JavaScript objects that are used to call WebSocket JavaScript

functions.

onMessage Required The JavaScript function that is called when the WebSocket receives a message from the server.

The function requires one argument.

onOpen Optional The JavaScript function that is called when the WebSocket establishes a connection.

The function does not require any arguments.

onClose Optional The JavaScript function that is called when the WebSocket closes a connection.

The function does not require any arguments.

onError Optional The JavaScript function that is called if there is an error while performing an action over the

WebSocket connection.

The function requires one argument.

usecfAuth Optional If set to true (default), authentication is not required for WebSocket connection (provided

they have already logged in to the application). This is the default value.

If false, to authenticate, you have to use the javaScript function authenticate.

subscribeTo Optional Comma-separated list of channels/subchannels to subscribe to. You can specify any or all

channels set in the Application.cfc.

Page 37: cf10betafeatures

34COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Example

In the following example,

• The user is automatically subscribed to the channel stocks.

• You have specified the channel name in the Application.cfc.

• Uses the default channel listener (as you have not specified a custom channel listener).

• In the Index.cfm, you specify the channels to which the user can automatically subscribe to (using the attribute

subscribeTo) and also define the message handler.

Application.cfc

component { this.name="websocketsampleapp1"; this.wschannels=[{name="stocks"}]; }

Index.cfm

<script type="text/javascript"> /* mymessangehandler function recieves all messages that comes via WebSocket. This

function requires one argument. */

function mymessagehandler(messageObject) {

//JavaScript messageobject is converted to a string. var message = ColdFusion.JSON.encode(messageObject);

var txt=document.getElementById("myDiv"); txt.innerHTML +=message +"<br>"; } </script> <cfwebsocket name="mycfwebsocketobject" onmessage="mymessagehandler" subscribeto="stocks" > <cfdiv id="myDiv"></cfdiv>

The code creates a JavaScript WebSocket object named mycfwebsocketobject. If the server sends a message, it calls

mymessagehandler function.

Since you have specified subscribeTo in the cfwebsocket tag, the WebSocket object automatically subscribes you to

the channel stocks.

Using the WebSocket JavaScript functions

After you create a JavaScript WebSocket object using the cfwebsocket tag, you can use it to call the following

JavaScript functions:

Page 38: cf10betafeatures

35COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Function Description Syntax Parameters

authenticate

Authenticates the user to a specific

channel.

authenticate(id, password)

For example,

mycfwebsocketobject.authenticate("Ben", "password");

• id: The user-ID against which a

user is authenticated.

• password

subscribe

Lets the client subscribe to a specific

channel.

You can send additional information such

as age of the user (in the form of

custom_header JavaScript object) to

the server. This information can be used

to take a decision on whether to let the

client subscribe or not.

subscribe(channel[, custom_header][, messageHandler])

For example,

mycfwebsocketobject.subscribe(channel);

• channel: Name of the

channel/sub-channel to which the

client wants to subscribe.

• custom_header: Optional.

Passed as key-value pairs. You can

also use ColdFusion keyword

selector and specify a

condition that can be used as a

filter criteria, for example,

mycfwebsocketobject.subscribe(channelname,{age : 25,selector:"symbol eq 'adbe' and value gt 20"}).

• messageHandler: Optional.

Specifies the channel-specific

message handler. If a message

handler is specified, data sent from

the server (to the channel) is

passed to the specific message

handler rather than to tag’s

onMessage attribute (that you

specified while creating the

WebSocket object). For more

details, see “Using channel-

specific message handler” on

page 42

publish Publishes the message to the channel. If

the message is not available use the

function invokeAndPublish.

Message can be passed in any JavaScript

data type (such as array, string, int, or a

key-value pair) as a JavaScript object.

You can send additional information (in

the form of custom_header). The

information can be used to decide if to

allow the client to publish, for example

‘Only platinum members have rights to

publish’.

publish(channel, message [, custom_header])

For example,

mycfwebsocketobject.publish("stocks",msg );

• channel: Name of the

channel/sub-channel to which the

message has to be published.

• message: The message object

that has to be published. Message

is published to clients subscribed

to the specific channel.

• custom_header: Optional.

Passed as key-value pairs. You can

also use ColdFusion keyword

selector and specify a

condition that can be used as a

filter criteria, for example,

mycfwebsocketobject.publish("mychannel", message, {item:phone, selector:"itemcode eq 'HTC HD'"});.

Page 39: cf10betafeatures

36COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Note: When you use these functions, a boolean value indicating the status of the call is returned. But the result of the call

is acknowledged at the message handler side. You can categorize the responses at the message handler using the request

type token as shown in the following example: if (token.reqType =="getSubscriberCount).

Example

The following example illustrates how to use various JavaScript functions.

invokeAndPublish

Invokes a specified method in a CFC file to

generate the message that has to be

published. Used in scnearios where you

have raw data (that needs to be

processed) to create a message.

invokeAndPublish(channel, cfcName, functionName [, argumentsArray] [, custom_header])

For example,

mycfwebsocketobject.invokeAndPublish(ch, "employee", "getEmployeeDetails", ["eid_1"]);

• channel: The name of the

channel/sub-channel to which a

message has to be published.

• cfcName: The CFC that contains

the method that is invoked for the

message. Users can pass the

cfcName as fully qualified path or

path relative to the application

root.

• functionName: The name of the

function in CFC that has to be

invoked for the message.

• argumentsArray: A JavaScript

array of arguments that has to be

passed to invoke the function on

the given CFC.

• custom_header: Optional.

Passed as key-value pairs. You can

also use ColdFusion keyword

selector and specify a

condition that can be used as a

filter criteria.

getSubscriberCount

Provides the number of subscribers for a

specific channel.

getSubscriberCount(channel)

For example,

mycfwebsocketobject.getSubscriberCount("stocks");

• channel: Name of the

channel/sub-channel whose

subscriber count is sought.

getSubscriptions

Provides all channels the client is

subscribed to, as a JavaScript array.

getSubscriptions()

openConnection

Opens a WebSocket connection (if not

already open).

openConnection()

isConnectionOpen

Verifies whether the WebSocket

connection is open.

Returns true if the connection is open.

isConnectionOpen()

CloseConnection

Closes a WebSocket connection.

Returns true on successful completion.

closeConnection()

unsubscribe

Unsubscribes a client from the specified

channel. After the client unsubscribes, the

messages in the channel are not

published to the client.

unsubscribe(channel)

For example,

mycfwebsocketobject.unsubscribe(channel);

• channel: Name of the channel

from which to unsubscribe.

Function Description Syntax Parameters

Page 40: cf10betafeatures

37COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Application.cfc

component { this.name="websocketsampleapp3"; this.wschannels=[{name="stocks"}]; }

Index.cfm

<script> //messagehandler recieves all the messages from websocket function mycbHandler( messageobj) { var message = ColdFusion.JSON.encode(messageobj); var txt=document.getElementById("myDiv"); txt.innerHTML +=message +"<br>"; } //openhandler is invoked when socket connection is function openHandler() { var txt=document.getElementById("myDiv"); txt.innerHTML +="open Handler invoked <br>"; } function subscribeMe() { var channelname = document.getElementById("channelname").value; mywsobj.subscribe(channelname); } function getSubscribers() { var channelname = document.getElementById("channelname").value; mywsobj.getSubscriberCount(channelname); } function unsubscribe_Me() { var channelname = document.getElementById("channelname").value; mywsobj.unsubscribe(channelname); } function publishClient() { var channelname = document.getElementById("channelname").value; var message = document.getElementById("msg").value; mywsobj.publish(channelname,message); } function get_Subscriptions() { mywsobj.getSubscriptions(); } function invokenpublish() { cfcname = document.getElementById("cfcname").value; fnname = document.getElementById("fnname").value; channelname = document.getElementById("channelname").value; mywsobj.invokeAndPublish(channelname, cfcname, fnname); }

Page 41: cf10betafeatures

38COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

function invokefn() { cfcname = document.getElementById("cfcname").value; fnname = document.getElementById("fnname").value; channelname = document.getElementById("channelname").value; mywsobj.invoke(cfcname, fnname); } function opensocket() { var txt=document.getElementById("myDiv"); txt.innerHTML+="opening socket"+"<br >"; x=mywsobj.openConnection(); } function stopsocket() { var txt=document.getElementById("myDiv"); txt.innerHTML+="closing socket"+"<br >"; x=mywsobj.closeConnection(); } function checksocket() { var x=mywsobj.isConnectionOpen(); var txt=document.getElementById("myDiv"); txt.innerHTML+=x+"<br >"; } </script> <form name="f"> <!---Define JS websocket object name and messagehandler and openhandler ---> <cfwebsocket name="mywsobj" onMessage="mycbHandler" onOpen="openHandler"/> <br> Subscribe to: <input id="channelname" name="channelname" type="text" value="stocks" > <input id="stocksSubscribe" type="button" value="stocksSubscribe" onclick="subscribeMe();"> <input id="unsubscribeMe" type="button" value="unsubscribeMe" onclick="unsubscribe_Me();"> <input id="getSubscribersCF" type="button" value="getSubscribersCF" onclick="getSubscribers();"> <input id="getSubscriptions" type="button" value="getSubscriptions" onclick="get_Subscriptions();"> <br> Message :<input id="msg" type="text" > <input id="publishMe" type="button" value="publishMe" onclick="publishClient();"> <br> CFC Name: <input id="cfcname" name="cfcname" type="text" value="invokeandpublish" > Function Name: <input id="fnname" name="fnname" type="text" value="publishall" > <input id="invoke_publish" type="button" value="invoke_publish" onclick="invokenpublish();"> <input id="invoke" type="button" value="invoke" onclick="invokefn();"> <br> <input id="stop" name ="Close" type="button" value ="stop" onclick="stopsocket()" > <input id="open" name ="Open" type="button" value ="open" onclick="opensocket()" > <input id="check" name ="Check" type="button" value="check" onclick="checksocket()" > <br> <div id="myDiv"></div> </form>

invokeandpublish.cfc

Page 42: cf10betafeatures

39COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

component { public function publishall() { return "All Clients"; } }

Scenarios: Subscribing and publishing

If the users subscribe to a parent channel, automatically they subscribe to all subchannels. If users subscribe to a child

channel, they are not subscribed to its parent channel.

The following table elaborates the conditions.

The table shows four clients Client 1, Client 2, Client 3, and Client 4 subscribed to the following channels: Stocks,

Stocks.Finance, Stocks.Banks, and Stocks.Finance.Adobe.

Scenarios: Getting subscriber list

The following table explains the conditions on which you receive the subscriber list when you use the function

getSubscribers.

Assume that there are four clients. Each client is subscribed to only one of the following channels (and no client is

subscribed to the same channel): Stocks, Stocks.Finance, Stocks.Banks, and Stocks.Finance.Adobe.

Using channel listener functions

Channel listener is a set of functions that decide the folow of messages to a channel. When a WebSocket object’s

JavaScript function is called, in turn functions in the channel listener are called. For example, when you call the

subscribe function, it calls the allowSubscribe function from the listener CFC.

A channel listener can be:

• Default channel listener: Used if no channel listener is specified while defining the channel in the Application.cfc.

Client Channel subscribed to Receives

messages when

publishing to

Stocks

Receives messages

when publishing to

Stocks.Finance

Receives

messages when

publishing to

Stocks.Banks

Receives messages

when publishing to

Stocks.

Finance.Adobe

Client 1 Stocks Yes Yes Yes Yes

Client 2 Stocks.Finance No Yes No Yes

Client 3 Stocks.Banks No No Yes No

Client 4 Stocks.Finance.Adobe No No No Yes

Function getSubscribers called with the

channel

Returns the ID of clients subscribed to the following channels

Stocks Stocks

Stocks.Finance Stocks.Finance and Stocks

Stocks.Banks Stocks.Banks and Stocks

Stocks.Finance.Adobe Stocks.Finance.Adobe, Stocks.Finnance, and Stocks

Page 43: cf10betafeatures

40COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

• User-defined channel listener: Used if a channel listener CFC is specified while creating a channel. Update the

methods in the channel listener file to implement a specific business logic.

Specify a custom channel listener to restrict subscription to a channel or right to publish. You can also use custom

channel listener to format messages and decide if the client is eligible to receive message.

Setting up user-defined channel listener

• (You must) Extend the default listener present in webroot/cfide/websocket/ChannelListener as shown in the

following code:

component extends="CFIDE.websocket.ChannelListener"

• A user-defined channel listener CFC must be in the same directory or subdirectory of the application.

• You can only override the functions specified in the default listener CFC to implement the business logic. All

custom functions are ignored.

How the listener functions receive/provide information

The functions in the listener receive or provide information in the following three structs. You can use these three

structs to add custom information.

• clientInfo: Information about the client. The following are the values:

• channelName

• clientId: A unique client ID.

It can be used for setting additional properties, such as roles.

• connectionTime: Connection time as date object.

• subscriberInfo: A struct that contains custom options passed in the subscribe request. Also contains the object

ConnectionInfo as subkey connectionInfo.

• publisherInfo: A struct that contains custom options passed in the publish request. Also contains the object

ConnectionInfo as subkey connectionInfo.

The following table lists the WebSocket JavaScript functions and the corresponding function in the channel listener CFC:

WebSocket object JavaScript

function

Function(s) called in the channel listener CFC

subscribe allowSubscribe

unsubscribe afterUnsubscribe

publish allowPublish

invokeAndPublish allowPublish

getSubscribers None

getSubscriptions None

invoke None

openConnection None

isConnectionOpen None

closeConnection None

Page 44: cf10betafeatures

41COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Channel listener functions

The following table lists the functions in the listener file:

Function Descriptions Syntax Parameters

allowSubscribe

Invoked before subscribing to a

channel/sub-channel.

Used to check if the requested client

can be allowed to subscribe to the

given channel. If returns true,

allows the requested client to

subscribe.

Properties defined in the object

subscriberInfo can be used

decide on authorization.

allowSubscribe(subscriberInfo)

• subscriberInfo: Subscriber

information struct. Contains

information that is passed by the

function subscribe in the

custom_header struct. It has a

connectionInfo object which

can be accessed through

ConnectionInfo key.

allowPublish Called before publishing to a

channel/sub-channel.

Used to check whether the

requested client can be allowed to

publish to the given channel.

Properties defined in the

publisherInfo struct can be used to

take the authorization decision.

If returns true, allows the

requested client to publish.

allowPublish(publisherInfo)

• publisherInfo: Publisher

information struct. Contains the

information that is passed by the

function publish in the

custom_headerstruct. It has a

connectionInfo object which

can be accessed through

ConnectionInfo key.

beforePublish Invoked before publishing the

message on requested

channel/sub-channel. Used to

execute a business logic if required

and to format messages.

beforePublish(message, publisherInfo)

• message: The message that has

to be published to the client. This

can be of type Any.

• publisherInfo: Publisher

information struct.

canSendMessage

Invoked before sending the

message to a subscribed client.

Used to decide whether the

message should be sent to a specific

client. Called for all clients

subscribed to a channel separately.

Properties defined in the object

subscriberInfo and

publisherInfo help you find

client's interest in the message.

canSendMessage(message, subscriberInfo, publisherInfo)

• message: The message that has

to be published to the client. This

can be of type Any.

• subscriberInfo: Subscriber

information struct.

• publisherInfo: Publisher

information struct.

beforeSendMessage

Invoked before sending the

message to a subscribed client. Can

be used to format the message as

per client requirement before

sending. This function is executed

for each client.

beforeSendMessage(message, subscriberInfo)

• message: The message that has

to be published to the client. This

can be of type Any.

• subscriberInfo: Subscriber

information struct.

afterUnsubscribe

Called after you unsubscribe from a

channel/sub-channel. Used to clear

the settings if necessary..

afterUnsubscribe (subscriberInfo)

• subscriberInfo: Subscriber

information struct.

Page 45: cf10betafeatures

42COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Using channel-specific message handler

When you create a WebSocket object, you can define a message handler to manage responses from the server. The

handler can manage messages from all the channels. Additionally, while subscribing to a channel, you can define

channel-specific message handler.

Example

Application.cfc

component

{ this.name = "channelspecifichandlerexample"; this.wschannels = [{name="stocks"}, {name="news"}, {name="products"}];

}

index.cfm

<script type="text/javascript"> function stockhandler(stocksmessageobj){ //write appropriate logic here to handle data coming on stock channel if (stocksmessageobj.data != null) { var message = stocksmessageobj.data; var datadiv = document.getElementById("myDiv"); datadiv.innerHTML += "Stock Handler: " + message + "<br />"; } } function newshandler(newsmessageobj){ //write appropriate logic here to handle data coming on news channel if (newsmessageobj.data != null) { var message = newsmessageobj.data; var datadiv = document.getElementById("myDiv"); datadiv.innerHTML += "News Handler: " + message + "<br />"; } } function productshandler(productsmessageobj){ //write appropriate logic here to handle data coming on products channel if (productsmessageobj.data != null) { var message = productsmessageobj.data; var datadiv = document.getElementById("myDiv"); datadiv.innerHTML += "Product Handler: " + message + "<br />"; } } function subscribeMe(){ var channel = document.getElementById("channeloption").value; switch (channel) { case "stocks": mysock.subscribe("stocks", {}, stockhandler); break; case "news": mysock.subscribe("news", {}, newshandler); break; case "products": mysock.subscribe("products", {}, productshandler); break; } } function mycbHandler(messageobj){

Page 46: cf10betafeatures

43COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

var message = ColdFusion.JSON.encode(messageobj); var datadiv = document.getElementById("myDiv"); datadiv.innerHTML += "Message Handler : " + message + "<br />"; }

</script> <cfwebsocket name="mysock" onmessage="mycbHandler"/> <form>

<select id="channeloption"> <option>

stocks </option> <option>

news </option> <option>

products </option>

</select> <input id="subscribe" name="subscribe" value="Subscribe" type="button" onclick="subscribeMe();">

</form> <div id="myDiv"> </div>

PublishMessage.cfm

<cfscript> if(isdefined("form.publish"))

WsPublish(#form.channel#, #form.message#); </cfscript> <cfform method="post">

<cfselect name="channel"> <option>

stocks </option> <option>

news </option> <option>

products </option>

</cfselect> Message: <input id="message" name="message" type="text"> <cfinput id="publish" name="publish" value="publish" type="submit">

</cfform>

Specifying custom information

The following JavaScript functions subscribe, publish, invokeandpublish and the serverside function WSPublish

let you pass custom information (for example age or status) in the form of key-value pairs.

You can use these custom data in the subscriberInfo in the channel listener.

Example 1: Custom information using subscribe

In the following example,

1 In the subscribe function, specify the age of the client.

Page 47: cf10betafeatures

44COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

2 In the channel listener, specify the age restriction in the allowSubscribe method.

Application.cfc

component { this.name = "customoptionexample"; this.wschannels = [{name="Testchannel", cfclistener="TestListener"}]; }

Index.cfm

<script type = "text/javascript"> function msgHandler(messageobj) { var ouputdiv=document.getElementById("myDiv"); var message = ColdFusion.JSON.encode(messageobj); ouputdiv.innerHTML+=message +"<br >" +"<br>"; } function subscribeMe() { var clientAge = document.getElementById("age").value;

TestSocket.subscribe("Testchannel", {age: clientAge}); }</script> <cfwebsocket name="TestSocket" onMessage="msgHandler"/> <br> Age <input id="age" name="age" type="text"> <br> <input id="stocksSubscribe" type="button" value="Subscribe" onclick="subscribeMe();"> <div id="myDiv"></div>

TestListener.cfc

component extends="CFIDE.websocket.ChannelListener" { public boolean function allowSubscribe(Struct subscriberInfo) { if(structKeyExists(subscriberInfo, "age")) if((subscriberInfo.age gt 18)) { return true; } else { return false; } else return false; } }

Example 2: Custom information using publish

The following example illustrates how you communicate bid value data.

1 In the function publish, specify the bid value as custom information.

2 In the channel listener, specify a condition to validate the bid by comparing it with the current bid value. The

message is broadcasted only if the bid is valid.

Page 48: cf10betafeatures

45COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Application.cfc

component {

this.name = "customoptionexample1"; this.wschannels = [{name="bidchannel", cfclistener="bidListener"}]; boolean function onApplicationStart() {

application.bidvalue = 1; }

}

Index.cfm

<script type="text/javascript"> function msgHandler(messageobj){ if (messageobj.data != null) { var ouputdiv = document.getElementById("myDiv"); var message = messageobj.data; ouputdiv.innerHTML += message + "<br >" + "<br>"; } if (messageobj.code == -1 && messageobj.reqType == "publish") { var ouputdiv = document.getElementById("myDiv"); var message = "Bid amount is less than current bid value"; ouputdiv.innerHTML += message + "<br >" + "<br>"; } } function publishme(){ var bidvalue = document.getElementById("amount").value; var clname = document.getElementById("name").value; var message = "Bid placed by " + clname + " Amount " + bidvalue; TestSocket.publish("bidchannel", message, { value: bidvalue }); }

</script> <cfwebsocket name="TestSocket" onmessage="msgHandler" subscribeto="bidchannel"/><br> Bid Amount: <input id="amount" name="amount" type="text"> Name: <input id="name" type="text"> <input id="publishmessage" type="button" value="Publish" onclick="publishme();"> <div id="myDiv"> </div>

bidListener.cfc

Page 49: cf10betafeatures

46COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

component extends="CFIDE.websocket.ChannelListener"{ public boolean function allowPublish(Struct publisherInfo) { if(structKeyExists(publisherInfo, "value")) if((publisherInfo.value gt application.bidvalue)) { application.bidvalue = publisherInfo.value; return true; } else { return false; } else return false; } }

Using selectors

Selectors provide filtering logic when you subscribe to a channel or publish a message.

While subscribing to a channel, a selector is provided as part of the subscriber information struct. For example, a client

is subscribed to a channel with a selector product eq abc. Only the messages that contain the publisher information

product:abc are published to the subscriber.

Similarly, you can include a selector as part of the publisher information struct while publishing a message. The

messages are published to only the subscribers who satisfy the criteria specified in the selector.

Note: For a custom channel listener CFC, you cannot have the canSendMessage method (for the selector to work).

The following example shows how to subscribe to a channel with a selector:

1 Create a channel selectorchannel in the Application.cfc.

component {

this.name = "websocketApp1"; this.wschannels = [{name="selectorchannel"}];

}

2 Create a CFM that allows the user to subscribe to the channel, with the selector condition ‘value greater than the

specified value’, for example you want to see only the stock values above a particular threshold value.

Page 50: cf10betafeatures

47COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

<script type="text/javascript"> function msgHandler(messageobj)

{ if (messageobj.data != null) { var ouputdiv = document.getElementById("myDiv"); var message = messageobj.data; ouputdiv.innerHTML += message + "<br >" + "<br>"; } } function subscribeMe() { var amt = document.getElementById("amount").value; var selectstring="value gt "+ amt;

TestSocket.subscribe("selectorchannel", {selector : selectstring}); document.getElementById("stocksSubscribe").style.display = 'none'; document.getElementById("l1").style.display = 'none'; document.getElementById("l2").style.display = 'block'; document.getElementById("publisme").style.display = 'block'; } function publishme() { var amt = document.getElementById("amount").value; TestSocket.publish("selectorchannel","Value is " +amt,{value: amt}) } </script> <cfwebsocket name="TestSocket" onMessage="msgHandler"/> <br /> <lablel id="l1">Stock value above which you want to recieve message</lablel> <label id="l2" style="display:none;">Value</label> <input id="amount" name="amount" type="text"> <br> <input id="stocksSubscribe" type="button" value="Subscribe" onclick="subscribeMe();"> <input id="publisme" type="button" value="Publish" onclick="publishme();" style="display:none;"> <div id="myDiv"></div>

Specifying WebSocket authentication details

You can specify the authentication details for WebSocket at the application level. An application method

OnWSAuthenticate has been added to support application level authentication.

1 In the Application.cfc, define the function onWSAuthenticate.

2 Call the JavaScript function authenticate. This function calls the onWSAuthenticate function.

Note: You cannot restrict authentication to a specific channel. If you do not want to authorize the client to any channels,

it can be done using the allowSubscribe function of channel listener.

onWSAuthenticate

Description

Authenticates the user

Syntax

OnWSAuthenticate(username, password, connectionInfo)

Page 51: cf10betafeatures

48COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Parameters

Example

The following example uses the function onWSAuthenticate, validates the user, and associates a user role.

Note: For this example to work, ensure that you implement the user-defined functions.

component {

this.name="websocketsampleapp23"; this.wschannels=[{name="stocks",cfclistener="stocksListener"}]; function onWSAuthenticate(username, password, connectionInfo)

{ //write appropriate logic to fetch user password in funtion checkPassword If(checkPassword(username) eq password) { connectionInfo.authenticated="YES"; //Role is the custom information that you provide

connectionInfo.role= "admin";

return true; } else{ connectionInfo.authenticated="NO"; return false; } writedump("#connectionInfo#","console"); } }

Enabling Single sign-on in WebSocket

If already authenticated to the ColdFusion server, you need not enter the credentials while subscribing to a WebSocket

channel. You need only specify useCFAuth = "true" in the tag cfwebsocket.

Parameter Description

username Name of the user that has to be authenticated.

password Password for the user.

connectionInfo A struct that contains the following keys:

• Authenticated: YES|NO

• ConnectionTime: Connection time stamp.

• clientID: Unique ID of the client.

Custom keys are also supported.

For example, you can specify the user's role, status, or age.

The connectionInfo is shared across all the channels for a given WebSocket

client. Also, modifications are persisted across all the subscriptions for that client.

Page 52: cf10betafeatures

49COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

In the following example, a login page is created using the tag cflogin. After authentication, the client is subscribed

to a channel. That is, the client does not pass the login credentials while subscribing. Here, the function

onWSAuthenticate need not be set up or called using the JavaScript function authenticate.

Example

1 Create a login page using the tag cflogin.

<form name="form1" method="post" > User: <input name="username" type="text" id="username" value="admin"><br> Pass: <input name="password" type="text" id="password"><br> <input type="submit" name="Submit" value="Submit"> </form> <cfif structKeyExists(form,"username")> <cflogout> <cfset r = "user"> <cfif FORM.username is "admin"> <cfset r = "admin"> </cfif>

<cflogin idletimeout="1800"> <cfloginuser name = "#FORM.username#" password ="#FORM.password#" roles = #r#> </cflogin>

<cfoutput>Authorized user: #getAuthUser()#</cfoutput><br> <cfoutput>Authorized role: #GetUserRoles()#</cfoutput><br> <cflocation url="index.cfm"> </cfif>

2 Create the Application.cfc with a channel shares, and listener channelListener.

component { this.name = "myssoexample"; this.wschannels = [ {name = "sso", cfclistener="ChannelListener"}]; }

3 Create a CFM that allows the user to subscribe to a channel and publish the message.

Page 53: cf10betafeatures

50COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

<script> var mycbHandler = function(msg)

{ if(msg.data)

{ var messageObject = msg.data; var txt=document.getElementById("myDiv");

if((messageObject.indexOf("{")!=-1)){ var jsonValue = (new Function( "return( " + messageObject + " );" ))();

if(jsonValue){ txt.innerHTML+="<br>Authenticated : " + jsonValue.authenticated; txt.innerHTML+="<br>UserName : " + jsonValue.username; txt.innerHTML+="<br>Role : " + jsonValue.roles; } } }

} var openHandler = function()

{ mysock.publish("sso","hii");

} </script> <form name="f"> <cfwebsocket name="mysock" onMessage="mycbHandler" subscribeto="sso" onOpen="openHandler" useCFAuth="yes"/> <div id="myDiv"></div> </form>

4 Create a ColdFusion listener file that returns the subscriber information while publishing.

component extends="CFIDE.websocket.ChannelListener" { public any function beforeSendMessage(any message, Struct subscriberInfo) { writedump(var=subscriberInfo.connectionInfo, output="console"); return subscriberInfo.connectionInfo; }

}

Server- side APIs

WebSocket server-side APIs allow a CFC to communicate with a channel or a specific client. For example, when a

message is received from the client, the server sends a specific message.

The following table details the server-side functions:

Function Name Syntax Description

WSgetSubscribers WSgetSubscribers (channel)

Returns an array of struct with clientID and subcriberInfo as the keys.

WSPublish WSPublish(channel, message [, filterCriteria])

Sends messages to a specific channel. Optionally, you can specify a filter

criteria struct.

WSGetAllChannels WSGetAllChannels () Provides all the channels defined in the Application.cfc as an array.

Page 54: cf10betafeatures

51COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Interpreting the Server response

The following is a sample response that you receive from the server:

{"clientid":2077108630,"ns":"coldfusion.websocket.channels","reqType":"welcome","code":0,"type":"response","msg":"ok"} {"clientid":2077108630,"ns":"coldfusion.websocket.channels","reqType":"subscribe","code":0,"type":"response","msg":"ok"}

The table explains the response keys:

The following is a sample subscribeto response sent to the message handler:

{"clientid":2077108664,"ns":"coldfusion.websocket.channels","reqType":"welcome","code":0,"type":"response","msg":"ok"} {"clientid":2077108664,"ns":"coldfusion.websocket.channels","channelsnotsubscribedto":"stocks.a","reqType":"subscribeTo","code":0,"type":"response","msg":"Subscription failed for channel(s) 'stocks.a'.","channelssubscribedto":"stocks"}

In this case, you have the key channelssubscribedto and channelsnotsubscribedto which applies to scenarios

related to the attribute subsscribeTo in the tag cfwebsocket.

Using WebSocket in point-to-point communication

Assume that the client need not send message to multiple clients. That is, the bi-directional communication is only

between one client and server.

So unlike in the broadcast model, you do not need a channel for communication and therefore need not define it in

the Application.cfc.

Do the following to set up a point-to-point communication:

1 Create the WebSocket object using the cfwebsocket tag.

For details, see “Creating WebSocket object using cfwebsocket” on page 33.

Key Description

clientid Unique ID assigned to a client.

ns ColdFusion WebSocket namespace

reqType The type of request represented by the JavaScript functions (for example, publish,

or invokeandpublish).

code See <code section>

type Either response or data.

• Response: Conveys if the request is successful.

• Data: The data that the channel recieves.

msg Applies to responses; ok if successful. On failure, returns the cause of failure.

subscriberCount

An integer that stands for the subscriber count.

channels Applies to getSubscriptions, list of all subscribed channels.

data Message is conveyed through data.

publisherID Client ID of the publisher. If the message is from WSPublish, the ID is 0.

channelname Name of the channel.

Page 55: cf10betafeatures

52COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

2 To send a message to the server, use the JavaScript method invoke.

3 To send additional messages, use the function WSSendMessage.

invoke

Description

Calls a particular function in the CFC. The value returned by the function in CFC is sent back to the client that invokes

the method.

Syntax

invoke(CFCName, functionName [, argumentsArray])

Parameters

Usage

Use the function WSSendMessage to send additional message back to the client inside the function.

To continuously send messages to a client you have to create a thread in the method that you invoke using invoke.

Further, you can keep sending messages inside a thread.

Example

mycfwebsocketobject.invoke("employee","getdept",["eid_2"]);

WSSendMessage

Description

Sends messages to a specific client that invokes the method. This can be included as a part of the function that is called

by the invoke WebSocket JavaScript method.

Returns

Nothing

Syntax

WSSendMessage(message)

Parameters

Parameter Description

cfcName The CFC filename (from where a specific function is called).

functionName The function name in the CFC file.

argumentsArray The function arguments as an array.

Parameters Description

message Required. The message object. This can be of type Any.

Page 56: cf10betafeatures

53COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Example: Point-to-Point communication

The following example shows how to implement a point-to-point communication. In this example, you invoke three

functions defined in mycfc.cfc.

• Method f1 returns a value.

• Method f2 expects an argument and returns a string. Also, client receives an additional message from the method

WSSendMessage used in f2.

• In the method f3, you create a thread that sends messages to the client at particular intervals.

1 Create a CFM page index.cfm.

<script type="text/javascript"> function msgHandler(msgobj){ var txt = document.getElementById("myDiv"); var message = ColdFusion.JSON.encode(msgobj); txt.innerHTML += message + "<br >" + "<br>"; } function invokecfcfn(){ var fname= document.getElementById("fnname").value; if (fname == "f2") { alert("f2 selected"); mysocket.invoke("mycfc", "f2", ["echo"]); } else mysocket.invoke("mycfc", fname); } </script> <cfwebsocket name="mysocket" onmessage="msgHandler"/> <form> <select id="fnname"> <option>f1</option> <option >f2</option> <option>f3</option> </select> <input id="invokefn" name="invokefn" value="Invoke CFC function " type="button" onclick="invokecfcfn();"> <div id="myDiv"> </div> </form>

2 Create a CFC mycfc.cfc that contains the function called from the client page.

Page 57: cf10betafeatures

54COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

<cfcomponent> <cffunction name="f1" > <cfreturn "Message returned from f1"> </cffunction> <cffunction name="f2" returntype="string" > <cfargument name="arg1" type="string" required="true" > <cfset msg= "Message from wsssendmessage of f2 which you called with arg " & arg1> <cfset wssendMessage(msg)> <cfreturn "Message returned from f2"> </cffunction> <cffunction name="f3" > <cfthread action="run" name="t1" > <cfloop index="i" from="1" to="10"> <cfset sleep(20000)> <cfset wssendMessage("Message #i# from wsssendmessage of f3 #now()#")> </cfloop> </cfthread> <cfreturn "Thread initiated in f3"> </cffunction> </cfcomponent>

Error handling in ColdFusion WebSocket

The WebSocket errors are categorized as follows:

Note: If you have defined an Error Handler, it receives the responses -1 and 4001. If not defined, the response goes to

Message Handler.

Using ColdFusion Administrator for WebSocket Configurations

Use the ColdFusion Administrator (Server Settings > WebSocket) to specify the following WebSocket-related details:

• Port that the WebSocket server listens to

• Socket timeout

• Data size of packets sent/received

• If to enable Flash fallback

Browser support for WebSocket

The following table lists the browser support for WebSocket.

Category Description Response code

Channel Error For example, channel not present or client

has already subscribed to the channel

-1

Application Error Runtime errors while invoking CFC 4001

Success On successful completion of request 0

Page 58: cf10betafeatures

55COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Language enhancements

Support for for-in construct (for query)

Similar to looping over array and struct, using for-in construct, you can loop over query object in CFScript.

Example

In this example, query resultset is available in the variable arts and the for-in loop is used to loop over the resultset.

The variable row used in the for-in construct is a struct that contains query columns as keys. You can use

arts.currentrow to reference the current row.

<cfquery name="arts" datasource="cfartgallery"> select * from art

</cfquery> <cfscript>

cols = listToArray(listsort(arts.columnlist, "textnocase")); for(row in arts) {

for(col in cols) writeoutput(arts.currentrow & " ..." & col & ": " & row[col] & "<br>");

writeoutput("<hr>"); }

</cfscript>

Note: You have to prefix queryname to access the query result variables such as recordcount or currentrow (as shown

in the example).

Provide file content in the tag body

For cffile action = "append" and cffile action = "write", you can provide file content in the tag body.

If you provide file content in both the tag body and the output attribute, it results in an error.

Browser WebSocket Support

Internet Explorer 6, 7, 8, and 9 Supported if Flash Player is installed.

Mozilla Firefox 3.x Supported if Flash Player is installed

Mozilla Firefox 6, 7, and 8 Supported

Google Chrome 15.x and above Supported

Safari 5.x Supported

(Android) Default browser Supported

(iPad) Safari Supported

Page 59: cf10betafeatures

56COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Example

<!--- In this case, file content is passed via both - output attribute and inside tag body. Tag body will get preference ---> <cfset filename = expandpath('./myfile.txt')> <cftry>

<cffile action="write" file="#filename#"> some tag body

</cffile> <cfset content = FileRead(filename)> <cfoutput>File Length = #Len(content)#</cfoutput>

<cfcatch type="any"> <cfoutput>

#cfcatch.message# <br>#cfcatch.detail# <br>

</cfoutput> </cfcatch> </cftry>

In this example, the text provided in the body is written to myfile.txt in the current directory.

Now assume that the file does not exist, then a new file myfile.txt is created. If the file exists, it is overwritten.

Similarly, if you use cffile action="append", the tag body content is appended to the contents of the file myfile.txt.

Creating empty files

To create an empty file, you have to provide at least a blank line in the tag body as shown in the following code:

<cffile action="write" file="#filename#"> <!--- Leave a blank line here--->

</cffile>

Callstack for ColdFusion functions

Callstack is a snapshot of all function calls or invocations. For your ColdFusion application, callstack provides the

template name, line number, and if applicable, the function name.

The feature is helpful in scenarios where you want to track the recursive calls that you made.

Example

• a.cfm does an include of b.cfm.

• b.cfm invokes the function callStackGet at line 15.

This results in a callstack that returns a struct that contains the template name, line number, and the function name.

Two callstack functions have been introduced in this release:

callStackGet

Description

Returns an array of structs. Each struct contains template name, line number, and if applicable the function name.

Syntax

callStackGet()

Page 60: cf10betafeatures

57COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Example

In this example, the factorial of a number is computed.

Here,

1 The function callStackGet is called on line 9 in function factorial in the template fact.cfm

2 In turn, it is called from line 14 from the template fact.cfm

3 In turn, it is called from template callfact.cfm (line 2)

4 And so on, for other values of n

callfact.cfm

<cftry> <cfinclude template="fact.cfm">

<cfcatch type="any"> <cfoutput>

#cfcatch.message# <br>#cfcatch.detail# <br>

</cfoutput> </cfcatch> </cftry>

fact.cfm

<cfscript> numeric function factorial(n) {

if(n == 1) {

writedump(callStackGet()); writeoutput("<br>"); return 1;

} else {

writedump(callStackGet()); writeoutput("<br>"); return n * factorial(n - 1);

} } factorial(5);

</cfscript>

callStackDump

Description

Similar to the function callStackGet except that it returns a string representation of the call stack.

Syntax

callStackDump(destination)

Page 61: cf10betafeatures

58COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Parameters

Example

In this example, the factorial of a number is computed. The example is similar to the example for callStackGet except

that the function used here is callStackDump.

callfact.cfm

<cftry> <cfinclude template="fact.cfm">

<cfcatch type="any"> <cfoutput>

#cfcatch.message# <br>#cfcatch.detail# <br>

</cfoutput> </cfcatch> </cftry>

fact.cfm

<cffunction name="factorial" hint="returns the factorial of a number" output="true"> <cfargument name="n" required="yes" type="numeric" hint="The number for which the

factorial is returned"/> <cfif n eq 1>

<Cfset callStackDump()> <cfreturn 1>

<cfelse> <Cfset callStackDump()> <cfreturn n * factorial(n - 1)>

</cfif> </cffunction> <cfoutput> Factorial of 5 - #factorial(5)#</cfoutput>

Getting application metadata

Use the new function getApplicationMetadata to get application metadata.

Recommended Reading

Ray Camden's blog on application metadata

getApplicationMetadata

Description

Returns the application settings that you have specified in the application, either in the Application.cfc or

Application.cfm. For details, see Application Variables section in CFML Reference.

Parameter Description

destination Optional parameter that takes one of the following values:

• console

• browser: This is the default destination.

• file: If you do not provide the complete path to the file, the file is written to the temp directory as

determined by the function getTempDirectory.

Page 62: cf10betafeatures

59COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Note: If you have turned on Enable Global Script Protection in ColdFusion Administrator (Server Settings > Settings),

the value returned is the default scopes protected (form, URL, CGI, or Cookie). If you specify an invalid value, none, or if

Enable Global Script Protection is turned off in ColdFusion Administrator, none is returned.

Note: If you have specified memory limit for VFS in ColdFusion Administrator and if Memory Limit per Application for

In-Memory Virtual File System (Server Settings > Settings) has a value lesser than what you have specified in the

Application.cfc (this.inmemoryfilesystem.size), then the returned value is the one specified in the ColdFusion

Administrator and not the Application.cfc.

Note: If ColdFusion does not find the Application.cfc/Application.cfm ColdFusion searches for the application in the

order in which you have set Application.cfm/Application.cfc look up order (ColdFusion Administrator > Settings > Server

Settings). If no application is found, an empty struct is returned.

Returns

A struct that contains application settings such as name, sessionManagement, or invokeImplicitAccessor.

Category

Other functions

Syntax

getApplicationMetadata()

Example

The example shows how you can access application settings in the CFM using the function

getApplicationMetadata:

Application.cfc

component {

this.name = "myapp"; this.applicationtimeout = createtimespan(0, 0, 0, 10); this.sessiontimeout = createtimespan(0, 0, 0, 10); this.sessionmanagement = true; this.clientmanagement = true; this.datasource = "cfartgallery"; this.ormenabled = true; this.secureJSON = true; this.secureJSONPrefix = "///"; this.setClientCookies = true; this.setDomainCookies = true; this.setClientStorage = "Registry"; this.setLoginStorage = "Cookies"; this.scriptProtect = "all"; this.mappings["mymapping"] = getdirectoryfrompath(cgi.cf_template_path); this.customTagPaths = "path1,path2,path3"; this.invokeImplicitAccessor = true; this.inmemoryfilesystem.enabled = true; this.inmemoryfilesystem.size = 10;

}

AppMetaData.cfm

Page 63: cf10betafeatures

60COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

<cfscript> writedump(getApplicationMetadata());

</cfscript>

Getting disk space details

The disk space functions added in this release return information related to the disk space.

Recommended Reading

Ray Camden's blog on total and free disk space.

getTotalSpace

Description

Returns the total hard disk space or in-memory space available for an application.

Returns

Total space in bytes

Category

System functions

See also

getVFSMetadata

Syntax

getTotalSpace(path)

Parameters

Usage

Application memory is determined by the following settings for RAM:

• In the ColdFusion Administrator, the value specified for Memory Limit per Application for In-Memory Virtual

File System (Server Settings > Settings).

The default value is 20 MB.

• The value specified in the Application.cfc for this.inmemoryfilesystem.size

If you have set values in both the places, the lesser value is considered.

Note: Even if the value specified in Application.cfc is lesser, ensure that Server Settings > Settings > Enable In-Memory

File System is checked in the ColdFusion Administrator.

Parameter Description

path Path to the

• Hard disk drive, for example C: for Windows or / for UNIX. For Windows, you have to explicitly use colon

(:) and not just C. Only the space of the entire hard disk drive is returned. If you mention a directory in the

path, for example, /opt/, it is ignored and only / is considered.

• For in-memory file system, the path is ram:.

Page 64: cf10betafeatures

61COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Example

See the example for getFreeSpace.

getFreeSpace

Description

Gets information about free hard disk space or free in-memory VFS space.

Returns

Returns the free space in bytes.

Syntax

getFreeSpace(path)

Parameters

Usage

See the usage section for getTotalSpace.

Example

In the following example, in-memory file system memory for the application is set to 20 MB in ColdFusion

Administrator. The function returns 20, which means the total space considered is 20 MB. This is because the value

specified in the ColdFusion Administrator (Memory Limit per Application for In-Memory Virtual File System) is

lesser than the value specified in the Application.cfc (20 MB).

Application.cfc

<cfcomponent> <cfset this.name = "vfs_total_space"> <cfset this.inmemoryfilesystem.size = 30>

</cfcomponent>

space.cfm

Parameter Description

path Path to the

• Hard disk drive, for example C: for Windows or / for UNIX. On Windows, you have to explicitly use colon (:) and

not just C. Only the space of the entire hard disk drive is returned. If you mention a directory in the path, for

example, /opt/, it is ignored and only / is considered.

• For in-memory file system, the path is ram:.

Page 65: cf10betafeatures

62COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

<cftry> <cfset totalRAMSpace = getTotalSpace("ram:")> <cfset freeRAMSpace = getFreeSpace("ram:")> <cfset totalDiskSpace = getTotalSpace("c:")> <cfset freeDiskSpace = getFreeSpace("c:")> <cfoutput>

Total Hard Disk Space = #DecimalFormat(totalDiskSpace / (1024 * 1024 * 1024))# GB <br>Free Hard Disk Space = #DecimalFormat(freeDiskSpace / (1024 * 1024 * 1024))# GB <br>Total Application RAM Memory = #DecimalFormat(totalRAMSpace / (1024 * 1024))# MB <br>Free Application RAM Memory = #DecimalFormat(freeRAMSpace / (1024 * 1024))# MB <br>

</cfoutput> <cfcatch type="any">

<cfoutput> #cfcatch.message# <br>#cfcatch.detail# <br>

</cfoutput> </cfcatch> </cftry>

Application-specific In-memory file system

ColdFusion 9 supports in-memory file system only at server level. But the enhancements in this release let you use in-

memory file system specific to applications. This enables application isolation for your virtual file system. That is, the

file created in the in-memory file system by one application is not accessible to another application.

The settings can be specified in the Application.cfc as follows:

Securing your uploads by default (by verifying the MIME type)

When you use the tag cffile for actions upload and uploadAll, the enhancements let you:

• Use filename extension as value for the attribute accept.

• Check for proper MIME type of the file using strict=true by default.

Note: If you use multi-file uploader, there can be instances where the upload fails (for example, when MIME type or

extension check fails) but the status in the uploader shows "Done". In such scenarios, you must trap the errors in the

upload page and send back a serialized struct with MESSAGE and STATUS keys set to the error condition.

Application event method onAbort

Description

Runs when you execute the tag cfabort.

Note: If showError attribute is specified in cfabort, onError method is executed instead of OnAbort.

Variable Description

this.inmemoryfilesystem.enabled

Set the value to true to enable in-memory file system for application.

This is the default setting.

this.inmemoryfilesystem.size Specify the memory limit in MB for the in-memory file system.

You can also specify the value in the ColdFusion Administrator (Server Settings >

Settings > Memory Limit per Application for In-Memory Virtual File System).

The lesser value is considered.

Page 66: cf10betafeatures

63COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Returns

Nothing

Syntax

<cffunction name="onAbort" returnType="boolean"> <cfargument type="string" name="targetPage" required=true/> ... <cfreturn BooleanValue /> </cffunction>

Parameters

Example

Application.cfc

<cfcomponent> <cffunction name="onAbort" access="public" returntype="void" hint="Hanldes Aborted request"> <cfargument type="String" name="targetPage" required=true/> <cfoutput> Target Page: #targetPage#</cfoutput> <!--- do stuff ---> </cffunction> </cfcomponent>

Test.cfm

<cfabort>

New function directoryCopy

Description

Copies the contents of a directory to a destination directory.

Returns

Nothing

Syntax

directoryCopy (source, destination[ , recurse][, filter])

Parameter Description

targetPage The path from the web root to the requested CFML page.

Page 67: cf10betafeatures

64COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Properties

Example

directoryCopy(sourceDirExists,destDirExists,true,"*.cfm")

New action copy for cfdirectory

New action cfdirectory action = "copy" to copy the contents of the directory has been added with filter and

recurse options. Use the attribute destination to specify the directory to which you copy the contents.

Modifications to the tag cffile

The attribute accept takes comma-separated list of any or all extensions, MIME type, or list of MIME types as values.

Specify the extensions with a . prefix. That is, only .txt is supported and not txt, *.txt, or *.*. However, you can

use * as a wildcard to accept all files.

• If you specify filename extension as value, the file is checked, only to ensure if it matches the list of extensions you

specified in comma-separated list. If it matches, the file is uploaded.

• If the value is MIME type or list of MIME types and the attribute strict is set to true, then the first few bytes of

the file are read to determine the MIME type. If MIME type matches with what you have specified, upload occurs,

else results in an error. The default value of strict is false.

• If you specify both filename extensions and MIME types and if strict is set to false, the verification is based

on the order in which you have specified the values. For example, if the first value is .txt, then the .txt file is

uploaded.

If strict is set to true, extensions are ignored.

Example: Using the attribute accept to verify the filename extension

upload.cfm

<cftry> <cfset variables.URL =

"http://#cgi.server_name#:#cgi.server_port##getDirectoryFromPath(cgi.script_name)#_upload.cfm">

<cfhttp method="Post" url="#variables.URL#"> <cfhttpparam type="FILE" name="myfile" file="#expandpath('./sample.txt')#">

</cfhttp> <cfoutput>#cfhttp.filecontent#</cfoutput>

<cfcatch> <cfoutput>

#CFCATCH.message# <br>#CFCATCH.detail# <br>

</cfoutput> </cfcatch> </cftry>

Parameter Description

source Absolute pathname of directory from which you copy content.

destination Path of the destination directory. If not an absolute path, it is relative to the source directory.

recurse By default, false. If true, copies the subdirectories.

filter File extension filter applied, for example, *.cfm.

Page 68: cf10betafeatures

65COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

_upload.cfm

<cfset uploadDirectory = "#GetTempDirectory()#cf_upload"> <!--- create upload directory ---> <cfif not directoryExists(uploadDirectory)>

<cfdirectory action="create" directory="#uploadDirectory#"> </cfif> <cftry>

<cffile action="UPLOAD" destination="#uploadDirectory#" filefield="form.myFile" nameconflict="MAKEUNIQUE" accept=".txt">

<cfcatch> <cfoutput>

#CFCATCH.message# <br>#CFCATCH.detail# <br>

</cfoutput> </cfcatch> </cftry> <!--- read directory ---> <cfdirectory action="LIST" directory="#uploadDirectory#" name="qFileList"> <cfoutput>#qFileList.recordcount#

file(s) uploaded <br>

</cfoutput> <!--- delete all the uploaded files---> <!--- <cfloop query="qFileList"> <cffile action="delete" file="#uploadDirectory#/#Name#"> </cfloop> ---> <!--- delete directory ---> <!--- <cfdirectory action="delete" directory="#uploadDirectory#"> --->

In this example, accept is set to .txt and strict is not specified (and therefore is false by default). So, only files with

.txt extensions are considered for upload.

Even if the file is originally a PDF (sample.pdf) renamed as sample.txt, the file is uploaded (since strict is not set

to true).

If you specify strict=true, then if the file is originally a .txt (and not renamed from some other type) the file is

uploaded only if the correct MIME type is specified. That is, strict=true requires MIME type to be specified in the

accept attribute. So, you should explicitly say accept="text/plain" in _upload.cfm.

Example 2: Using MIME type

Modify the Example 1 by specifying accept="application/pdf" in _upload.cfm as follows:

<cffile action="UPLOAD" destination="#uploadDirectory#" filefield="form.myFile" nameconflict="MAKEUNIQUE" accept="application/pdf" strict=true>

Since strict = true, only files of type PDF are considered for upload.

To use a different file, modify the the following section of upload.cfm:

Page 69: cf10betafeatures

66COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

<cfhttpparam type="FILE" name="myfile" file="#expandpath('./sample.txt')#">

Example 3: Using both extension and MIME type

Modify the Example 1 by specifying the following in _upload.cfm:

<cffile action="UPLOAD" destination="#uploadDirectory#" filefield="form.myFile" nameconflict="MAKEUNIQUE" accept=".txt, application/pdf" strict=true>

Only PDF files are uploaded because strict = true.

If you set strict as false, then both the files are uploaded.

To use a different file, modify the following snippet of upload.cfm:

<cfhttpparam type="FILE" name="myfile" file="#expandpath('./sample.txt')#">

fileGetMimeType

Description

Gets the MIME type for the file path/file object you have specified.

Returns

Returns MIME type.

Syntax

fileGetMimeType(path[, strict])

fileGetMimeType(fileObject[,strict])

Parameters

Example

Assume that you have a file named test.pdf in /folder1 and test.txt in the same folder, and you want to check the MIME

type. Here test.txt is a copy of test.pdf with extension renamed to txt.

Parameter Description

path Full path on disk to the file if strict is set to true.

If you do not specify the full path, the file is assumed to be present in the temp directory, as returned by the function

getTempDirectory.

fileObject Name of the file object.

strict If false, determines the file type by extension. The default value is true.

Page 70: cf10betafeatures

67COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

<cfscript> //Case 1. mime.mimeType1 = FilegetMimeType(expandPath('/folder1/test.pdf')); //Case 2. mime.mimeType2 = FilegetMimeType(expandPath('/folder1/test.pdf'),false); //Case 3. mime.mimeType3 = FilegetMimeType(expandPath('/folder1/test.txt')); //Case 4. mime.mimeType4 = FilegetMimeType(expandPath('/folder1/test.txt'),false); writeDump(mime);

</cfscript>

• Case 1 and Case 2: Returns application/pdf no matter if strict = true or false because the file is originally a

PDF file.

• Case 3: Returns application/pdf since by default strict = true and the file is originally a PDF which is renamed

as TXT.

• Case 4: Returns text/plain since strict = false.

New function ArraySlice

Description

Returns part of an array with only the elements you need.

Returns

Portion of an array based on the offset and length settings.

Syntax

arraySlice(array,offset,[length])

Properties

Example

<cfscript> array = [1, 2, 3, 4, 5, 6, 7, 8]; newArray = arraySlice(array, 2, 3);//returns 2,3,4 newArray = arraySlice(array, 4);//returns 4,5,6, 7, 8 newArray = arraySlice(array, -5, 3);//returns 4,5,6 </cfscript>

New parameter merge supports arrayAppend

The new parameter merge, if set to true appends array elements individually to the source array. If false (default),

the complete array is added as one element at the end, in the source array.

Parameter Description

array Name of the array that you want to slice.

offset Specifies the position from which to slice the array. Negative value indicates that the array is sliced, with

sequence starting from array’s end.

length Element count from offset.

Page 71: cf10betafeatures

68COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Implicit constructor for CFC

You can initialize the CFC properties, when you instantiate the CFC, by passing the values as key-value pair or struct.

For example, assume that you have a CFC employee.cfc with the properties firstName and lastName.

You can use the following syntax to set the first name and last name:

emp=new employee(firstName="Tom", lastName="Nash");

or as an implicit struct as follows:

emp=new Employee({firstName="Tom", lastName="Nash"});

If an init() method is defined for the CFC, either by explicitly defining an init()method or by providing the

method in the component’s initmethod attribute, implicit Constructor is not invoked.

For implicit Constructor support, either specify accessors=true in the cfcomponent or ensure that you have the

setter functions for the properties defined.

If you have setter = false for a specific property or if the property is not defined for the CFC, then the value is not set.

In either case, if there is an onMissingMethod defined for the CFC, it is invoked.

Example 1

In this example, the property firstName is set to the value Tom at the time of CFC instantiation, but the property

lastName is not set because it has setter = false. Also, onMissingMethod is invoked in the case of the property

lastName.

employee.cfm

<cfscript> emp = new employee(firstname="Tom", lastname="Nash"); writeOutput("<u><b>Employee Details</b></u>: " & "<br><br>"); writeOutput("First Name: " & emp.getFirstname() & "<br>");

</cfscript>

employee.cfc

<cfcomponent accessors="TRUE"> <cfproperty name="firstname" type="string" setter="true"/> <cfproperty name="lastname" type="string" setter="false"/> <cfproperty name="age" type="numeric"/> <cffunction name="onMissingMethod">

<cfargument name="missingMethodName"/> <cfargument name="missingMethodArguments"/>

<cfoutput>

onMissingMethod() called for method call - #arguments.missingMethodName# <hr>

</cfoutput> </cffunction>

</cfcomponent>

Example 2

In this example, both employee1.cfc and employee2.cfc have an init()method defined. Therefore, the CFC properties

firstName and lastName are not initialized. But in the employee.cfc, since there is no init() method defined,

property firstName is initialized.

employee1.cfc

Page 72: cf10betafeatures

69COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

<cfcomponent accessors="TRUE"> <cfproperty name="firstname" type="string" setter="true"/> <cfproperty name="lastname" type="string" setter="false"/> <cffunction name="init">

<cfreturn this> </cffunction> <cffunction name="onMissingMethod">

<cfargument name="missingMethodName"/> <cfargument name="missingMethodArguments"/> <cfoutput>

onMissingMethod() called for method call - #arguments.missingMethodName# <hr>

</cfoutput> </cffunction>

</cfcomponent>

employee2.cfc

<cfcomponent accessors="TRUE" initmethod=foo> <cfproperty name="firstname" type="string" setter="true"/> <cfproperty name="lastname" type="string" setter="false"/> <cffunction name="foo">

<cfreturn this> </cffunction> <cffunction name="onMissingMethod">

<cfargument name="missingMethodName"/> <cfargument name="missingMethodArguments"/> <cfoutput>

onMissingMethod() called for method call - #arguments.missingMethodName# <hr>

</cfoutput> </cffunction>

</cfcomponent>

employee.cfm

<cfscript> emp = new employee(firstname="Tom", lastname="Nash"); writeOutput("<u><b>Employee Details</b></u>: " & "<br><br>"); writeOutput("First Name: " & emp.getFirstname() & "<br>"); writeOutput("<hr>"); emp1 = new employee1(firstname="Tom", lastname="Nash"); writeOutput("First Name: " & emp1.getFirstname() & "<br>"); writeOutput("<hr>"); emp2 = new employee2(firstname="Tom", lastname="Nash"); writeOutput("First Name: " & emp2.getFirstname() & "<br>"); writeOutput("<hr>");

</cfscript> <cfoutput>

onMissingMethod() called for method call - #arguments.missingMethodName# <hr>

</cfoutput>

Method chaining for CFC methods

You can chain your CFC methods as follows:

emp=new employee(); emp.setFirstName("Tom").setLastName("Nash").setAge("30");

Page 73: cf10betafeatures

70COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Chaining works only

• If the attribute accessors is set to true

• Until a method is found

• If there are no errors

or

• If the setter functions for the properties are defined

Example

The chain in the example works only until lastName. This is because setter for age is set to false:

<cfcomponent accessors="TRUE"> <cfproperty name="firstname" type="string" setter="true"/> <cfproperty name="lastname" type="string" setter="true"/> <cfproperty name="age" type="numeric" setter="false"/> <cffunction name="init">

<cfreturn this> </cffunction>

</cfcomponent>

CFC Implicit notation

This feature lets you set your CFC property as simple variable assignment, without specifying the setters. That is, you

can set the property by setting the property field rather than by invoking the setter method for the property.

Similarly, the property value can be accessed by referencing the property name, rather than by invoking the getter for

the property.

Example

Application.cfc

component {

this.name = "MyApplication"; this.invokeImplicitAccessor = true;

}

employee.cfm

<cfscript> emp = new emp(); emp.firstname = "Tom"; emp.lastname = "Nash"; emp.age = 30; writeOutput("First Name = " & emp.firstname & "<br>"); writeOutput("last Name = " & emp.emp.lastname & "<br>"); writeOutput("Age = " & emp.age & "<br>");

</cfscript>

employee.cfc

Page 74: cf10betafeatures

71COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

<cfcomponent accessors="TRUE"> <cfproperty name="firstname" type="string" setter="true"/> <cfproperty name="lastname" type="string" setter="false"/> <cfproperty name="age" type="numeric"/> <cffunction name="onMissingMethod">

<cfargument name="missingMethodName"/> <cfargument name="missingMethodArguments"/> <cfoutput>

onMissingMethod() called for method call -#arguments.missingMethodName# <hr>

</cfoutput> </cffunction>

</cfcomponent>

In the example, CFC Implicit notation works only if you set invokeImplicitAccessor in the Application.cfc to true.

Otherwise, the values are posted to the This scope of the component.

New parameter format added to LSParseDateTime function

An optional parameter format that provides the format of the string has been added to the function

LSParseDateTime.

This string is used to parse the given date string to date time object.

In the following example, the format specifies the way in which the given date string has to be read:

<cfoutput>#lsParseDateTime("01/08/2011","en","MM/dd/yyyy")#</cfoutput>

Also, for the function ParseDateTime, the parameter style now supports format (supported by Java) apart from

standard and pop:

<cfset str = "Wed, 01 Sep 2004 13:24:52 GMT"> <cfoutput>#parseDateTime(str, "EEE, d MMM yyyy HH:mm:ss Z")#</cfoutput>

For style description, go to the following URL:

http://docs.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html.

New attribute runOnce added to cfinclude

An optional attribute runOnce with false as the default value has been added to the tag cfinclude. If set to true, the

given template (if already processed) is not processed again for a given request. The CFScript equivalent of this

attribute is runonce, which can be used as follows:

include "<template.cfm>" runonce ="true\false"

Recommended Reading

Ray Camden's blog on cfinclude enhancement

New attribute timeout in cfstoredproc

A new attribute timeout has been added to the tag cfstoredproc, which is the maximum number of seconds that

each action is permitted to execute before returning an error.

The cumulative time may exceed this value. For JDBC statements, ColdFusion sets this attribute. For other drivers, see

the driver documentation.

Page 75: cf10betafeatures

72COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

New attribute maxLength in cfparam

cfparam tag has a new optional attribute maxLength which lets you specify the maximum character length of email,

url, and string.

New functions dateTimeFormat and lsDateTimeFormat

dateTimeFormat

Description

Formats date and time values using date and time formatting conventions.

Returns

A formatted date and time value.

Syntax

dateTimeFormat (date)

dateTimeFormat (date [, mask])

dateTimeFormat (date [, mask, timeZone])

Properties

Parameter Description

date Required. A date/time object, in the range 100 AD–9999 AD.

mask Optional. Mask that has to be used for formatting. The function follows Java date time mask. For details, see

the section Date and Time Patterns at the following URL:

http://docs.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html

timeZone The time-zone information. You can specify in either of the following formats:

• Abbreviation such as GMT or PST

• Full name such as Europe/Dublin

By default, this is the time-zone followed by the system.

Page 76: cf10betafeatures

73COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Example

<cfset todayDateTime = Now()> <body> <h3>DateTimeFormat Example</h3> <p>Today's date and time are <cfoutput>#todayDateTime#</cfoutput>. <p>Using DateTimeFormat, we can display that date and time in different ways: <cfoutput> <ul> <li>#DateTimeFormat(todayDateTime)# <li>#DateTimeFormat(todayDateTime, "yyyy.MM.dd G 'at' HH:mm:ss z")# <li>#DateTimeFormat(todayDateTime, "EEE, MMM d, ''yy")# <li>#DateTimeFormat(todayDateTime, "h:mm a")# <li>#DateTimeFormat(todayDateTime, "hh 'o''clock' a, zzzz")# <li>#DateTimeFormat(todayDateTime, "K:mm a, z")# <li>#DateTimeFormat(todayDateTime, "yyyyy.MMMMM.dd GGG hh:mm aaa")# <li>#DateTimeFormat(todayDateTime, "EEE, d MMM yyyy HH:mm:ss Z")# <li>#DateTimeFormat(todayDateTime, "yyMMddHHmmssZ", "GMT")# </ul> </cfoutput>

LSDateTimeFormat

Description

Formats date and time values using locale-specific date and time formatting conventions.

Returns

A formatted date and time value.

Syntax

LSDateTimeFormat (date , mask)

LSDateTimeFormat (date [, mask, locale])

LSDateTimeFormat (date [, mask, locale, timeZone])

Properties

Parameter Description

date Required. A date/time object, in the range 100 AD–9999 AD.

mask Optional. Mask that has to be used for formatting. The function follows Java date time mask. For details, see

the section Date and Time Patterns at the following URL:

http://docs.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html

timeZone The time-zone information. You can specify in either of the following formats:

• Abbreviation such as GMT or PST

• Full name such as Europe/Dublin

By default, this is the time-zone followed by the system.

locale Locale to use instead of the locale of the page when processing the function.

Page 77: cf10betafeatures

74COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Example

<cfset todayDateTime = Now()> <body> <h3>DateTimeFormat Example</h3> <p>Today's date and time are <cfoutput>#todayDateTime#</cfoutput>. <p>Using DateTimeFormat, we can display that date and time in different ways: <cfoutput> <ul>

<li>#DateTimeFormat(todayDateTime, "yyyy.MM.dd G 'at' HH:mm:ss z")# <li>#DateTimeFormat(todayDateTime, "EEE, MMM d, ''yy")# <li>#DateTimeFormat(todayDateTime, "h:mm a")# <li>#DateTimeFormat(todayDateTime, "hh 'o''clock' a, zzzz")# <li>#DateTimeFormat(todayDateTime, "K:mm a, z")# <li>#DateTimeFormat(todayDateTime, "yyyyy.MMMMM.dd GGG hh:mm aaa")# <li>#DateTimeFormat(todayDateTime, "EEE, d MMM yyyy HH:mm:ss Z")# <li>#DateTimeFormat(todayDateTime, "yyMMddHHmmssZ", "English (UK)", "GMT")# </ul> </cfoutput>

New function reEscape

reEscape

Description

Takes a string and escapes characters that match regular expression control characters.

Returns

String appended with the escape characters

Syntax

reEscape(string)

Properties

Example

<cfoutput> #reescape("*.{}[]exam?ple")# </cfoutput>

The function replaceList takes delimiters

New parameter delimiter added to the function replaceList.

The new syntax can be as follows:

replaceList(string, list1, list2, delimiter)

replaceList(string, list1, list2, delimiter_list1, delimiter_list2)

Parameter Description

string The string in which you have to escape characters that match regular expression characters.

Page 78: cf10betafeatures

75COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

The following two variants are supported:

• A common delimiter for both search and replace

• Different delimiters, one for search and the other for replace

Note: Multichardelimeter is off in both the variants

Examples

In the following example, the delimiter applies to both the lists:

<h3>Replacelist Example One</h3> <cfset stringtoreplace = "The quick brown fox jumped over the lazy dog."> <cfoutput> #ReplaceList(stringtoreplace,"dog:brown:fox:black", "cow:black:ferret:white", ":")# </cfoutput>

In the following example, delimiter is specific to individual lists:

<h3>Replacelist Example Two</h3> <cfset stringtoreplace = "The quick brown fox jumped over the lazy dog."> <cfoutput> #ReplaceList(stringtoreplace,"dog:brown:fox:black", "cow-black-ferret-white", ":" , "-")# </cfoutput>

Modifications to the functions arraySort, listSort, and structSort

Added support for all Java supported locale-specific characters (including support for umlaut characters) in arraySort,

listSort, and structSort. A flag for this support has been added for sorttype = text or sorttype = textnocase.

Implicit struct now supports use of : (colon) separator

As recommended by JSON specifications, implicit stuct now supports specifying key-value pair separated by : (colon),

in addition to using = as shown in the following code:

<cfset s.s1 = {x=1,y=2}> <cfset s.s2 = {x:1,y:2}>

The attribute output is ignored in the interface signature

The output attribute need not be identical to the value in the interface.

Even if you omit the attribute in the interface, you can use it in the implementation. Similarly, you can use the attribute

in the interface and omit it in the implementation.

FUNCTION is now a ColdFusion datatype

For example,

Page 79: cf10betafeatures

76COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

<cfscript> public FUNCTIOn FUNCTION a() { return variables.b; } public FUNCTION b() { return "Hal"; } writeoutput(a()); writedump(a().getMetadata()); writedump(a.getMetadata()); writedump(x.getMetadata()); </cfscript>

Dynamic references supported in query looping

In cfloop, when using query attribute, you can now use dynamic references in addition to string, as shown in the

following code:

<cfloop query = "#getEmployees()#">

New function invoke

invoke

Description

Does either of the following:

• Invokes a component method from within a ColdFusion page or component

• Invokes a web service

Returns

What the invoked method returns.

Syntax

invoke(cfcinstance, methodname [, arguments])

Properties

Example

<cfscript> obj = createObject("component","TestComponent"); invoke(obj,"function1",{a1="ColdFusion"}); </cfscript>

Parameter Description

cfcinstance Required. String or component object; a reference to a component, or component to instantiate.

methodname Required. Name of a method. For a web service, the name of an operation.

arguments Optional. Arguments to pass to the method.

Page 80: cf10betafeatures

77COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

New attribute secure in cfpop

A new attribute secure, if set to true enables SSL for pop requests. The default value is false.

New attribute group in cfloop

An optional attribute group has been added to cfloop. The description is as follows:

Query column to use to group sets of records. Eliminates adjacent duplicate rows when data is sorted. Use if you

retrieved a recordset ordered on one or more query columns.

For example, if a recordset is ordered on "Customer_ID", you can group the output on "Customer_ID."

For-in constructs now support Java arrays

Apart from native ColdFusion arrays, for-in constructs now support Java arrays as shown in the following example:

cfscript> a = CreateObject("java","java.util.Arrays").AsList(ToString("CF,10,Zeus").split(",")); for (var1 in a) { WriteOutput(var1); } </cfscript>

Enhancements to queryAddRow and queryNew functions

The function queryNew now lets you initialize the query data. You can specify a struct, an array of structs, or

arrays with single or multiple dimensions to initialize the query as shown in the following example:

myQuery1 = queryNew("id,name","Integer,Varchar", {id=1,name="One"}); myQuery2 = queryNew("id,name","Integer,Varchar",

[ {id=1,name="One"}, {id=2,name="Two"}, {id=3,name="Three"} ]);

myQuery2 = queryNew("id,name","Integer,Varchar", [ [1,"One"], [2,"Two"], {3,"Three"] ]);

Similarly, in the function queryAddRow you can specify a struct, an array of structs, or arrays with single or

multiple dimensions to add rows to the query as shown in the following example:

queryAddRow(myQuery1, [ {id=2,name="Two"}, {id=3,name="Three"}, {id=4,name="Four"} ]); queryAddRow(myQuery2,{id=4,name="Four"});

queryAddRow(myQuery1, [ [1,"One"], [2,"Two"], {3,"Three"] ]);

Page 81: cf10betafeatures

78COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

New function listRemoveDuplicates

listRemoveDuplicates

Description

Removes duplicate values (if they exist) in a list.

Returns

List sans duplicate values

Syntax

ListRemoveDuplicates(list[, delimiter] [, ignoreCase])

Properties

Example

<cfscript> myList = "one,two,three,four,five,one,five,three" newList = listremoveduplicates(myList); //default delimeter is "," //newList contains "one,two,three,four,five" </cfscript>

<cfscript> myList = "one,two,three,four,five,ONE,TWO,THREE" newList = listremoveduplicates(myList, ",", true);

//newList contains "one,two,three,four,five" </cfscript>

Support for XPath 2.0 and XSLT 2.0 syntax

• XPath 2.0: The function xmlSearch supports XPath 2.0 syntax. Also provided is support for passing variables to

XPath expressions.

A new parameter params has been added to the function xmlSearch. This is an optional parameter which can be

a struct that contains key-value pair (variable name and value) as shown in the following example:

<cfscript> params = structNew(); params["test"] = "food";

</cfscript> <!--- find all nodes with element name as passed by variable test ---> <cfset result = xmlSearch(xmldoc,"/breakfast_menu/*[local-name() eq $test]", params)>

• XSLT 2.0: The function xmlTransform supports XSLT 2.0 syntax.

Parameter Description

list Required. List of objects.

delimiter Optional. Character(s) that separate list elements. The default value is comma. .

ignoreCase Optional. If true, ignores the case of strings in the list. By default the value is set to false.

Page 82: cf10betafeatures

79COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Using closures

A closure is an inner function. The inner function can access the variables in the outer function. You can access the

inner function by accessing the outer function. See the example below.

<cfscript> function helloTranslator(String helloWord)

{ return function(String name)

{ return "#helloWord#, #name#";

}; }

helloInHindi=helloTranslator("Namaste"); helloInFrench=helloTranslator("Bonjour"); writeoutput(helloInHindi("Anna")); //closure is formed. //Prints Namaste, Anna. writeoutput("<br>"); writeoutput(helloInFrench("John")); //Prints Bonjour, John. </cfscript>

In the above example, the outer function returns a closure. Using the helloHindi variable, the outer function is

accessed. It sets the helloWord argument. Using this function pointer, the closure is called. For example,

helloInHindi("Anna"). Observe that even after the execution of outer function, the closure can access the variable

sets by the outer function.

In this case, using closure, two new functions are created. One adds Namaste to the name. And the second one adds

Bonjour to the name. helloInHindi and helloInFrench are closures. They have the same function body; however,

store different environments.

The inner function is available for execution after the outer function is returned. A closure is formed when the inner

function is available for execution.

As seen in the example, even after the outer function is returned, the inner function can access the variables in the outer

function. Closure retains the reference to the environment at the time it is created. For example, the value of a local

variable in the outer function. It makes closure an easy to use and handy feature.

To see more details on closure, see http://jibbering.com/faq/notes/closures.

Closure in ColdFusion

A closure can be of the following categories:

• Defined inline without giving a name. They can be used in the following ways:

• They can be assigned to a variable, array item, struct, and variable scope. It can be returned directly from a

function.

Example

Page 83: cf10betafeatures

80COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

<cfscript> function operation(string operator)

{ return function(numeric x, numeric y) { if(operator eq "add")

{ return x + y; }

else if(operator eq "subtract") { return x - y; }

}; }

myval_addition=operation("add"); myval_substraction=operation("subtract"); writeoutput(myval_addition(10,20)); writeoutput("<br>"); writeoutput(myval_substraction(10,20)); </cfscript>

In the above example, the outer function sets the operator. myval_addition and myval_substraction are two

closures. They process the data based on the condition sets by the outer function.

• Defined inline as a function and tag argument.

Example

<cfscript> function operation(numeric x, numeric y, function logic)

{ var result=logic(x,y); return result;

} add = operation(10,20, function(numeric N1, numeric N2)

{ return N1+N2;

}); subtract = operation(10,20, function(numeric N1, numeric N2)

{ return N1-N2;

}); </cfscript> <cfdump var="#add#"> <cfdump var="#substract#">

In the above example, the function operation has an argument logic, which is a closure. While calling

operation, an inline closure is passed as an argument. This anonymous closure contains the logic to process

the numbers - addition or subtraction. In this case, the logic is dynamic and passed as a closure to the

function.

A closure can be assigned to a variable

You can assign a closure to a variable.

Example

var c2 = function () {..}

Page 84: cf10betafeatures

81COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

A closure can be used as a return type

You can use a closure as a return type.

Note: As a best practice, if the return type is a closure, provide the Function keyword with initial capitalization.

Example

Function function exampleClosure(arg1) {

function exampleReturned(innerArg) {

return innerArg + owner.arg1; } /* return a reference to the inner function defined. */

return exampleReturned; }

Calling closure with key-value pair

You can call a closure by passing a key-value pair as you do for a function call.

Example

var c2 = function(arg1, arg1) {..} c2(arg1=1, arg2=3);

Closure can be assigned to a variable outside function

You can assign a closure to a variable outside the function.

Example

hello = function (arg1) {

writeoutput("Hello " & arg1); }; hello("Mark");

Calling closure with argument collection

Example

var c2 = function(arg1, arg1) {..} argsColl = structNew(); argsColl.arg1= 1; argsColl.arg2= 3; c2(argumentCollection = argsColl);

Closures and functions

A closure retains a copy of variables visible at the time of its creation. The global variables (like ColdFusion specific

scopes) and the local variables (including declaring or outer function's local and arguments scope) are retained at the

time of a closure creation. Functions are static.

The following table details the scope of closure based on the way they are defined:

Page 85: cf10betafeatures

82COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

In closure, following is the order of search for an unscoped variable:

1 Closure's local scope

2 Closure's arguments scope

3 Outer function's local scope if available

4 Owner function's local scope if available

5 ColdFusion built-in scope

Note: A closure cannot call any user-defined function, because the function's context is not retained, though the closure's

context is retained. It gives erroneous results. For example, when a closure is cached, it can be properly called for later use,

while a function cannot.

Closure functions

The following are the closure functions:

ArrayEach

Description

Used to loop over an array.

Returns

Nothing

Category

Closure functions

Syntax

arrayEach(array,function(any currentObj) {});

See also

Other closure functions.

History

ColdFusion 10 Beta: Added this function.

Scenario where closure is

defined

Scope

In a CFC function Closure argument scope, enclosing function local scope and argument scope, this scope, variable

scope, and super scope

In a CFM function Closure argument scope, enclosing function local scope and argument scope, this scope, variable

scope, and super scope

As function argument Closure argument scope, variable scope, and this scope and super scope (if defined in CFC

component).

Page 86: cf10betafeatures

83COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Parameters

ArrayFilter

Description

Used to filter the elements of an array.

Returns

A new array

Category

Closure functions

Syntax

arrayFilter(array,function(arrayElement){return true|false;});

See also

Other closure functions.

History

ColdFusion 10 Beta: Added this function.

Parameters

ArrayFind

Description

Used to find an element in an array.

Returns

Index at which the element was found.

Category

Closure functions

Parameter Description

array Name of the array object.

function Inline function executed for each element in the array.

currentObj Element of the array that is being accessed.

Parameter Description

array Name of the array object.

function Inline function executed for each element in the array. Returns true if the array element has to be included in the

resultant array.

arrayElement Array element being accessed.

Page 87: cf10betafeatures

84COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Syntax

ArrayFind(array,function(currentObj) {return true|false;});

See also

Other closure functions.

History

ColdFusion 10 Beta: Added this function.

Parameters

ArrayFindAll

Description

Used to find an elements in an array.

Returns

Indices in which the elements were found.

Category

Closure functions

Syntax

ArrayFindAll(array,function(currentObj) {return true|false;});

See also

Other closure functions.

History

ColdFusion 10 Beta: Added this function.

Parameters

Parameter Description

array Name of the array object.

function Inline function executed for each element in the array. Returns true if the array element matches the search

criterion.

arrayElement Array element being accessed.

Parameter Description

array Name of the array object.

function Inline function executed for each element in the array. Returns true if the array elements match the search criterion.

arrayElement Array element being accessed.

Page 88: cf10betafeatures

85COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

ArraySort

Description

Sorts the array elements based on the comparison criteria.

Returns

Nothing

Category

Closure functions

Syntax

arraySort(array,function(any obj1, any obj2) {return 1|0|-1;});

See also

Other closure functions.

History

ColdFusion 10 Beta: Added this function.

Parameters

ListFilter

Description

Used to filter the elements in list.

Returns

A new list

Category

Closure functions

Syntax

listFilter(list,function(listElement){return true|false;});

See also

Other closure functions.

History

ColdFusion 10 Beta: Added this function.

Parameter Description

array Name of the array object.

function Returns 1 if the obj1 qualifies to be prior to others in comparison, 0 if objects being compared have equal priority,

and -1 if obj1 qualifies to be of lower priority.

ojb1, obj2 The array elements being compared.

Page 89: cf10betafeatures

86COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Parameters

isClosure

Description

Determines whether a name represents a closure.

Returns

True, if name can be called as a closure; False, otherwise.

Category

Decision functions

Syntax

isClosure(closureName)

See also

Other decision functions.

History

ColdFusion 10 Beta: Added this function.

Parameters

Usage

Use this function to determine whether the name represents a closure.

Example

<cfscript> isClosure(closureName) { // do something } else { // do something }

</cfscript>

Parameter Description

list Name of the list object.

function Inline function executed for each element in the list. Returns true if the list element has to be included in the

resultant list.

listElement LIst element being accessed.

Parameter Description

closureName Name of a closure. Must not be in quotation marks.

Results in an error if not a defined variable or function name.

Page 90: cf10betafeatures

87COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

StructEach

Description

Used to loop over elements in a structure by accessing key-value pairs.

Returns

Nothing

Category

Closure functions

Syntax

structEach(array,function(key, value) {});

See also

Other closure functions.

History

ColdFusion 10 Beta: Added this function.

Parameters

StructFilter

Description

Used to filter the key value pairs in a struct.

Returns

A new struct

Category

Closure functions

Syntax

structFilter(struct,function(key, value){return true|false;});

See also

Other closure functions.

Parameter Description

struct Name of the structure object.

function Inline function executed for each key - value pair in the struct.

key Key in a struct.

value Value in a struct.

Page 91: cf10betafeatures

88COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

History

ColdFusion 10 Beta: Added this function.

Parameters

Modifications to the function isCustomFunction

Though closure is a function object, it is not considered as a custom function.

The function now returns:

• True: If name can be called as a custom function.

• False: If name can be called as a closure.

Usage scenarios

The following scenario explains how you can effectively use ColdFusion closures.

Example - filtering of arrays using closures

The following example filters employees based on location, age, and designation. A single function is used for filtering.

The filtering logic is provided to the function as closures. That’s filtering logic changes dynamically.

Example

1 Create the employee.cfc file that defines the variables.

/** * @name employee * @displayname ColdFusion Closure Example * @output false * @accessors true */ component { property string Name; property numeric Age; property string designation; property string location; property string status; }

2 Create the employee array. This CFC also contains the filterArray() function. A closure, filter, is an

argument of the function. While accessing this function, the filtering logic is passed as a closure.

Parameter Description

struct Name of the struct object.

function Inline function executed for each element in the array. Returns true if the key value pair in the struct has to be

included in the resultant struct.

key Key in a struct.

value Value in a struct.

Page 92: cf10betafeatures

89COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

<!---filter.cfc---> <cfcomponent> <cfscript> //Filter the array based on the logic provided by the closure. function filterArray(Array a, function filter)

{ resultarray = arraynew(1);

for(i=1;i<=ArrayLen(a);i++) {

if(filter(a[i])) ArrayAppend(resultarray,a[i]);

} return resultarray;

} function getEmployee()

{ //Create the employee array.

empArray = Arraynew(1); ArrayAppend(empArray,new employee(Name="Ryan", Age=24, designation="Manager",

location="US")); ArrayAppend(empArray,new employee(Name="Ben", Age=34, designation="Sr Manager",

location="US")); ArrayAppend(empArray,new employee(Name="Den", Age=24, designation="Software Engineer",

location="US")); ArrayAppend(empArray,new employee(Name="Ran", Age=28, designation="Manager",

location="IND")); ArrayAppend(empArray,new employee(Name="Ramesh", Age=31, designation="Software

Engineer", location="IND")); return empArray; }

</cfscript> </cfcomponent>

3 Create the CFM page that accesses the filterArray()function with a closure which provides the filtering logic.

The filterArray()function is used to filter the employee data in three ways: location, age, and designation. Each

time the function is accessed, the filtering logic is changed in the closure.

Page 93: cf10betafeatures

90COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

<!---arrayFilter.cfm---> <cfset filteredArray = arraynew(1)> <cfset componentArray = [3,6,8,2,4,7,9]> <cfscript> obj = CreateObject("component", "filter"); // Filters employees from India filteredArray = obj.filterArray(obj.getEmployee(), function(a)

{ if(a.getLocation()=="IND")

return 1; else

return 0; });

writedump(filteredArray); //Filters employees from india whos age is above thirty filteredArray = obj.filterArray(obj.getEmployee(), closure(a)

{ if((a.getLocation()=="IND") && (a.getAge()>30))

return 1; else

return 0; });

writedump(filteredArray); // Filters employees who are managers filteredArray = obj.filterArray( obj.getEmployee(), function(a)

{ if((a.getdesignation() contains "Manager"))

return 1; else

return 0; });

writedump(filteredArray); </cfscript>

Enhanced Java integration

Integrating Java libraries

ColdFusion 10 Beta lets you load Java libraries from a custom path that you specify. In the previous versions, you use

Java libraries placed in the lib directory of ColdFusion. Those libraries are not application-specific and adding a Java

library or updating an existing library is not easy. You also have to restart ColdFusion.

ColdFusion 10 Beta lets you place the Java libraries for an application in a directory of your choice. You specify the path

of this directory in the Application.cfc. Then, use the libraries in your application by creating a cfobject of Java type.

Specifying custom Java library path in the Application.cfc without dynamic loading

Specify the custom path from where you want to load the Java library in the Application.cfc. of your project.

In this case, if there is an update to the file, restart ColdFusion to load the updated files.

Add the following entry in this file:

THIS.javaSettings = {LoadPaths = [".\java_lib\",".\java\myjar.jar"], loadColdFusionClassPath = true, reloadOnChange = false}

Page 94: cf10betafeatures

91COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Parameters

Specifying the custom Java library path in the Application.cfc with dynamic loading

Specify the custom path from where you want to load the Java library in the Application.cfc of your project.

In this case, if there is an update to the file, you need not restart ColdFusion to load the updated files.

Add the following entry in this file:

THIS.javaSettings = {LoadPaths = [".\java_lib\",".\java\myjar.jar"], loadColdFusionClassPath = true, reloadOnChange= true, watchInterval = 100, watchExtensions = "jar,class,xml"}

Parameters

Using a Java class

Save the Java class files or JARs in the directory that you specified in the Application.cfc. Then, access the methods in

the JARs or class files by creating a cfobject of Java type.

In this example, you create a Java class and access a method in the Java class in the sample application.

1 Create a Java file, Test.java.

public class Test {

public String testJava() { return "Hello Java!!"; }

}

Parameter Description

loadPaths An array of paths to the directories that contain Java classes or JAR files.

You can also provide the path to a JAR or a class. If the paths are not resolved, an error occurs.

loadColdFusionClassPath

Indicates whether to load the classes from the ColdFusion lib directory.

The default value is false.

reloadOnChange

Indicates whether to reload the updated classes and JARs dynamically, without restarting ColdFusion.

The default value is false.

Parameter Description

loadPaths An array of paths to the directories that contain Java classes or JAR files.

You can also provide the path to a JAR or a class. If the paths are not resolved, an error occurs.

loadColdFusionClassPath

Indicates whether to load the classes from the ColdFusion lib directory.

The default value is false.

reloadOnChange

Indicates whether to reload the updated classes and JARs dynamically, without restarting ColdFusion.

The default value is false.

watchInterval

Specifies the time interval in seconds after which to verify any change in the class files or JAR files.

This attribute is applicable only if the reloadOnChange attribute is set to true. The default value is 60

seconds.

watchExtensions

Specifies the extensions of the files to monitor for changes. By default, only .class and .jar files are

monitored.

Page 95: cf10betafeatures

92COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

2 Compile the Java file using a Java compiler.

3 Add the following entry to the Application.cfc of your project:

<cfset THIS.javaSettings = {LoadPaths = ["/myJava/lib"],reloadOnChange=true,watchInterval=30}/>

4 Create the following directory structure in your application folder:

/myJava/lib

5 Copy the Test.class file to the /myJava/lib folder.

6 Create a CFM file with the following content.

<cfobject type="java" class="Test" name="myObj"> <cfset y = myObj.init()>

<cfoutput > #y.testJava()# </cfoutput>

7 Deploy the application and access the CFM file.

Using the CFC Proxy

Using the CFC Proxy, you can access a ColdFusion component from Java classes. To call CFC, ColdFusion class loader

must be the current class loader. For example, the following code creates a CFC Proxy from the file location provided:

CFCProxy(String fully-qualified-path-of-CFC-file)

Similarly, the following code creates a CFC Proxy from the file location provided. It also initializes the This scope of

the CFC with the name value pairs.

CFCProxy(String fully-qualified-path-of-CFC-file name-value-pairs)

ColdFusion 10 Beta introduces a new argument in CFProxy classes, directInvoke.

If this argument is set true, the request does not go through the ColdFusion Filter chain. It results in improved

performance.

The following example creates a Java class that access a ColdFusion component using CFC Proxy.

1 Create the following Java class.

import coldfusion.cfc.CFCProxy; public class CFCInvoker {

public String directInvoke(String cfcPath) {

String myMessage = ""; try

{ CFCProxy myCFC = new CFCProxy(cfcPath, true); Object[] myArgs = { "Hello" }; myMessage = (String)myCFC.invoke("getData", myArgs);

} catch (Throwable e)

{ e.printStackTrace();

} return myMessage;

} }

Page 96: cf10betafeatures

93COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

2 Compile the file and place it in the lib directory of the project folder.

3 Create a ColdFusion component as follows:

<cfcomponent> <cffunction name="getData" returntype="string">

<cfargument name="msg" required="Yes"> <cfreturn msg & "Java" />

</cffunction> </cfcomponent>

4 In the application.cfc, add the following entry:

THIS.javaSettings = {LoadPaths = ["/lib"],reloadOnChange= true,loadColdFusionClassPath=true};

5 Create a CFM file to print the output:

<cfobject action="create" type="java" class="CFCInvoker" name="x"> <cfset cfcPath = "C:\ColdFusion10\cfusion\wwwroot\Project\name.cfc"/> <cfset y = x.directInvoke2(cfcPath)> <cfoutput>#y#</cfoutput>

6 Access the CFM file.

Using the createDynamicProxy function

The function createDynamicProxy creates a dynamic proxy of the ColdFusion component that is passed to a Java

library. Dynamic proxy lets you pass ColdFusion components to Java objects. Java objects can work with the

ColdFusion components seamlessly as if they are native Java objects.

To create a dynamic proxy, provide the name of the ColdFusion component and an array of Java interfaces. The

component is treated as if it implements the specified interfaces.

Create a dynamic proxy as follows:

createDynamicProxy("fullyQualifiedNameOfCFC", ["interfaceName"]);

Specify the following parameters:

• Fully qualified name of the ColdFusion component or a CFC instance.

• An array of Java interfaces for which you want to create the dynamic proxy.

Creating a dynamic proxy

The following example shows how to create a Java interface. Interface defines a method. A ColdFusion component

implements the method as a ColdFusion function. The dynamic proxy of the ColdFusion component calls a Java class

by passing the object of the interface. It then calls the method in ColdFusion as if it is a native Java class.

1 Create a Java interface, MyInterface.

public interface MyInterface {

public String sayHello(); }

2 Compile the Java file and place it in a directory, lib.

3 Create a Java class, InvokeHelloProxy, that calls the ColdFusion object using the instance of the interface.

The constructor, InvokeHelloProxy, creates an object of MyInterface. The invokeHello() method calls the

sayHello() method using the object.

Page 97: cf10betafeatures

94COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

public class InvokeHelloProxy {

private MyInterface myInterface; public InvokeHelloProxy(MyInterface x) {

this.myInterface = x; } public String invokeHello() {

return myInterface.sayHello(); }

}

4 Compile the Java file and place it in a directory, lib.

5 Create a CFC file, HelloWorld.cfc, that implements the method defined in the interface and save it in a directory, cfc.

<cfcomponent> <cffunction name="sayHello" returntype="string">

<cfreturn "Hello World!!!!"> </cffunction>

</cfcomponent>

6 Add the following code in the Application.cfc.

<cfset THIS.javaSettings = {LoadPaths = ["/lib"],reloadOnChange=true,watchInterval=10}/>

7 Add a CFM file that creates a dynamic proxy for HelloWorld as interface, MyInterface. Create an object of

InvokeHelloProxy class and initiate the class.

The code creates a dynamic proxy of MyInterface.

<cfset dynInstnace = createDynamicProxy("cfc.HelloWorld", ["MyInterface"])> <cfset x = createObject("java","InvokeHelloProxy").init(dynInstnace)> <cfset y = x.invokeHello()> <cfoutput>#y#</cfoutput>

Example: using a CFC instance

<cfset instance=new cfc.helloWorld()> <cfset dynInstnace = createDynamicProxy(instance, ["MyInterface"])> <cfset x = createObject("java","InvokeHelloProxy").init(dynInstnace)> <cfset y = x.invokeHello()> <cfoutput>#y#</cfoutput>

8 Deploy the application and access the CFM file.

ColdFusion ORM search

Enhancements in ColdFusion 10 provide indexing and search capabilities for ColdFusion ORM. When you develop

an application that uses ColdFusion ORM, the search feature facilitates full text search. You can load all the persistent

entities that match your search criteria based on a query text.

Full text search is a two-step process that involves indexing the persistent entity and search based on the indexed

information.

Indexing the persistent entity

Indexing stores indexable data of the persistent entity in index files. Search is performed on the indexed data. The

configuration you specify in the component decides the indexable data.

Page 98: cf10betafeatures

95COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Specify the ORM search index directory

You can specify the index directory (the one in which all persistent entities, of an application's indexable data, are

saved) either at the server-level or application-level.

At server level

1 In the ColdFusion Administrator, go to Server Settings > Settings.

2 In the Settings page, specify the directory details in Specify the absolute path to store index files for ORM search.

Note: A directory is created for each application with the application name, in the path you specify.

At application level

Specify the index directory path as absolute or path relative to the current Application.cfc. If you specify the relative

path, then it is resolved with respect to the current folder.

Note: If you do not specify a path, the index files are stored, by default, in cfroot/ormindex.

Search settings at application level

Specify the ColdFusion ORM search settings in the Application.cfc using the properties provided in the following

table:

Example

component {

this.name = "ORM_Search"; this.ormEnabled = "true"; this.ormSettings.datasource = "ORM_Dummy"; this.ormSettings.dbcreate = "dropcreate"; this.ormsettings.searchenabled = "true"; this.ormSettings.search.autoindex = "true"; this.ormSettings.search.indexDir = "C:/ormindex"; this.ormSettings.search.language = "English";

}

Search settings at the component level

Specify the following in the tag cfcomponent. The settings override the values in the Application.cfc.

Property Req./Opt. Default Description

searchenabled Required if using

ORM search

false If yes, ORM search is enabled.

search.autoIndex Optional false If yes, autoindexing is enabled.

search.indexDir Optional If specified, creates a folder by entity name in the file system where

indexes for all entities are saved. The directory you set in the ColdFusion

Administrator is used for this purpose.

This folder has all index information stored.

If not specified, creates the folder in the application root directory.

search.language Optional english Specify the language that is used to index and search.

Page 99: cf10betafeatures

96COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Example

See the example in the section “Search settings at the property level” on page 96

Search settings at the property level

Specify the following in the tag cfproperty. The settings override the values in the Application.cfc and cfcomponent.

Example

Empoyee.cfc

component persistent="true" indexable="true" indexlanguage="English" table="Employee" {

property name="id" fieldtype="id" ormtype="int" generator="native"; property name="firstname" indexable="true" indexstore="yes" indexboost="5.0"; property name="lastname" indexable="true" indextokenize="true" indexfieldname="surname"; property name="description" indexlanguage="Greek"; property name="dept" fieldtype="many-to-one" cfc="dept" indexable="true"

indexfieldname="department" notnull="false"; }

Attribute Req/Opt Default Description

indexable Optional false If true, enables indexing for the component.

indexLanguage Optional english Specify the language that is used to index and search.

The value you set overrides the value defined in the Application.cfc.

autoIndex Optional true If false, auto-indexing of CFC does not occur. That is, indexing occurs

only in offline mode.

Attribute Req/Opt Default Description

indexable Optional false If true, marks the column for indexing.

Except in the case of PK and compositekey (which are indexed if any of

the non-PK property is set to indexed), the default value is false.

indexTokenized Optional true If true, the field text is broken into subkeys for indexing.

Applies only if indexed is set to true.

indexFieldName Optional value of the attribute

nameSpecifies the field name that is used in search query while indexing and

performing search.

indexBoost Optional Used to prioritize the search results. This is a numeric value.

Results from this column appears above others in the query result.

Higher the boost, the more the priority.

indexStore Optional false The values are true, false, and compressed.

• true: Stores the value in the original form, without tokenizing.

• false: Does not store the value.

• compressed: Stores the original value in a compressed form, based

on Lucene implementation.

indexLanguage Optional english Specify the language that is used to index and search.

The value overrides the value defined in cfcomponent and the

Application.cfc.

Page 100: cf10betafeatures

97COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Indexing modes

Using ColdFusion ORM, you can perform indexing either automatically or in offline mode.

Auto-indexing

Indexing is performed every time an entity is added, revised, or deleted from the database.

To enable auto-indexing, set ormsettings.searchenabled to true in the Application.cfc.

Indexing is automatically done whenever an ORM entity is persisted, based on the configuration in CFCs. For details,

see “Specify the ORM search settings” on page 98.

Offline indexing

Indexing is performed manually with the help of ColdFusion functions. In this mode, indexing is performed in

batches.

You may want to perform offline indexing in the following scenarios:

• Index all or some of the pre-existing data in a database.

• Avoid in-request indexing (default behavior) to minimize CPU load, and later perform indexing as batch

operation.

The function ORMIndex lets you perform offline indexing.

ORMIndex

Description

Performs offline indexing.

Syntax

ORMIndex();

ORMIndex("entity_name");

ORMIndex("entityName_list");

ORMIndex (entityObject);

Parameters

Usage

If you use this function without specifying any parameters, all persistent entities of a given application are indexed.

Parameter Description

entityName Name of the entity that has to be indexed.

entityName_list Comma-separated list of entity names for indexing.

entityObject Variable name of a specific entity instance for indexing.

Page 101: cf10betafeatures

98COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Example

EmpObjs = EntityLoad("Employee",{lastname="Bond"}); for(EmpObj in EmpObjs) { ormindex(EmpObj); }

ORMIndexPurge

Description

Clears all indexed data for all entities or specified entities in the current application scope.

Syntax

ORMIndexPurge();

ORMIndexPurge("entityName");

ORMIndexPurge("entityName_list");

Parameters

Usage

If you use this function without specifying entityName, all persistent entities of the application are purged.

Example

ORMIndexPurge();

ORMIndexPurge("Employee");

Search based on indexed information

Search can be performed using the functions provided in ColdFusion. Search can either be a

• Lucene query search

• Full text search where ColdFusion ORM generates the Lucene query

Specify the ORM search settings

You have to specify the ORM search settings at the application level, component level, or property level.

Performing the search

Using the ORM search functions, you can perform search in both online and offline mode in

• An entity

• An indexable field in an entity

• Common fields across entities

• Multiple fields in an entity

Parameter Description

entityName Name of the entity to be loaded.

entityName_list Comma-separated list of entity names for purging.

Page 102: cf10betafeatures

99COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

• Multiple fields in multiple entities

ORMSearch

Description

Searches for given text in specific properties or entities.

Returns

A struct that contains the following:

• An array of structs (with the entity and score being the keys) in the following format:

data -[{entity: entity1, score: entity1_score}, {entity: entity2, score: entity2_score}, ..... ]

• maxTotalRecord (number of possible results)

Syntax

ORMSearch("query_text", "entityName")

ORMSearch("query_text", "entityName", fields)

ORMSearch("query_text", "entityName", fields, optionMap)

Parameters

Usage

When you perform a date search, use the format yyyymmdd as shown in the following example:

objs = ORMSearch("datecheck:[#dateformat(dateadd("d",5,now()),"yyyymmdd")# TO #dateformat(dateadd("d",35,now()),"yyyymmdd")#]","C2",[],{maxresults=2});

If you are performing a time search, use the UTC format.

Parameter Description

query_text The text to be searched for or a complete Lucene query.

In the case of ORMSearch("query_text", "entityName"), only Lucene query is supported.

For details of Lucene query, see http://lucene.apache.org/java/2_3_2/queryparsersyntax.html

entityName Name of the entity to be searched.

fields Fields in which search has to be performed. This can be an array of strings.

If you are performing a Lucene query, you need not specify this field. In other words, if you do not specify this value,

a Lucene query is performed.

Field name is case-sensitive.

optionMap Extra options that can be passed while executing Lucene query.

The options are:

• sort: Sorts based on indexfieldname you specified.

• offSet: Specifies the position from which to retrieve the objects.

• maxResults: Specifies the maximum number of objects to be retrieved.

Page 103: cf10betafeatures

100COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Example 1: ORM search based on Lucene query

ORMSearch("FirstName:ch*","Employee"); ORMSearch("ch*","Employee",["FirstName"]); objs = ORMSearch('FirstName:ch*',"Employee",[],{sort="salary",maxresults=5,offset=2});

Example 2: ORM search on multiple entities

ORMSearch("john*","DeveloperEntity,UserEntity",["firstname"]);

In this example, first name is searched in the DeveloperEntity and UserEntity and a composite array of entities are

returned.

Example 3: ORM search on all subentities based on Lucene query

This example shows how to perform ORM search on all subentities that inherit a super entity. Assume that

USEmployeeEntity and UKEmpoyeeEntity are extending EmployeeEntity. You can search both the subentities

using the following code:

ORMSearch("john*","EmployeeEntity",["FirstName"]);

Example 4: ORM search in relationships

In this example, products and categories have a many-to-one relationship. You can search all products of a specific

category using the following code:

ORMSearch("CategoryID.CategoryName:In*","cproducts",[]);

Note that search in related objects works only for many-to-one relationship and one-to-one relationship.

ORMSearchOffline

Description

Performs search on the indexed properties but returns only the stored fields.

For this function to work, specify indexStore=true on the properties on which you want to perform the search.

Returns

A struct that contains the following:

• An array of structs (with the entity and score being the keys) in the following format:

data -[{entity: entity1, score: entity1_score}, {entity: entity2, score: entity2_score}, ..... ]

• maxTotalRecord (number of possible results)

• fields_to_be_selected as keys.

Syntax

ORMSearchOffline(query_text, entityName, fields_to_be_selected);

ORMSearchOffline(query_text, entityName, fields_to_be_selected, fields);

ORMSearchOffline(query_text, entityName, fields_to_be_selected, fields, optionMap);

Page 104: cf10betafeatures

101COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Parameters

Example 1

ORMSearchOffline('FirstName:"ch*"',"Employee",["id","firstname"]);

Example 2

In the following example, offline search is performed on the property FirstName and first name and last name are

returned as keys in the resultant struct.

ORMSearchOffline("ch*","Employee",["FirstName","LastName"],["FirstName"],{sort="salary",maxresults=5,offset=2});

Example 3

In this example, the resultObj in the query is an array of structs. The individual structs contain all the selected fields

(passed as third parameter).

<cfset resultObj =ORMSearchOffline('Java Rocks', 'Book', [bookId, summary, Author.name, title],[title, short_summary])>

Other enhancements

Logging

Enabling request debugging in ColdFusion Administrator helps logging of HQL queries. To do this,

1 In the ColdFusion Administrator, go to Debugging & Logging > Debug Output Settings.

2 Check the option Enable Request Debugging Output.

Solr enhancements

Enhancements in this release let you

• Use Data Import Handler for database indexing

• Index and search based on dynamic custom fields

• Reload individual collections

• Add languages for search

Parameter Description

query_text The text to be searched for or a complete Lucene query.

For details of Lucene query, see http://lucene.apache.org/java/2_3_2/queryparsersyntax.html.

entityName Name of the entity to be searched.

fieldss_to_be_selected

Fields to be returned as keys in the resultant struct.

fields Fields in which search has to be performed.

optionMap Extra options that can be passed while executing Lucene query. The options can be:

• sort: Sorts based on indexfieldname you specified.

• offSet: Specifies the position from which to retrieve the objects.

• maxResults: Specifies the maximum number of objects to be retrieved.

Page 105: cf10betafeatures

102COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

• Secure your search system using ColdFusion Administrator (Data & Services > Solr Server > Show Advanced

Settings > Use HTTPs connection).

• Autocommit indexed documents

• Boost specific fields or entire document for improved search results.

Modifications to file location and filenames

• For stand-alone installation, all Solr files reside in the jetty folder ColdFusion Zeus\cfusion\jetty (previously

ColdFusion Zeus\cfusion\solr).

• On Windows, the Solr service has been renamed as ColdFusion Zeus Jetty Service (previously ColdFusion Zeus Solr

Service).

• On Windows, the executable file has been renamed as jetty.exe (previously solr.exe)

Using Data Import Handler

In ColdFusion 9, indexing database was a two-step process (of querying database using the tag cfquery and indexing

the query using the tag cfindex). In ColdFusion 10, you need not use cfquery to get data; rather Solr directly

communicates with the database and fetches data using Data Import Handler helping you improve indexing

performance.

You can perform a full or partial indexing depending on your requirement. For example, when you index the database

for the first time, you may do a full indexing. For any updates in the database, you can perform partial indexing to

update your collection.

Indexing using Data Import Handler

The following steps help you configure Data Import Handler for indexing databases:

1 Do the following:

• For full import: Create the following dataconfig.xml to define mapping of database table columns to Solr:

<dataconfig> <datasource driver="org.hsqldb.jdbcDriver" url="jdbc:mysql:/temp/example/ex"

user="user" password="user"/> <document name="products">

<entity name="item" query="select * from item"> <field column="ID" name="id"/> <field column="NAME" name="name"/>

</entity> </document>

</dataconfig>

• For delta import: Create the following dataconfig.xml:

Page 106: cf10betafeatures

103COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

<dataconfig> <dataSource driver="com.mysql.jdbc.Driver" "jdbc:mysql:/temp/example/ex" user="user"

password="password" /> <document name="rrr"> <entity name="item" pk="ID" query="select ID,NAME,PRICE,WEIGHT,last_modified from

item" deltaimportquery="select ID,NAME,PRICE,WEIGHT,last_modified from item where

ID='${dataimporter.delta.id}'" deltaquery="select id from item where last_modified > '${dataimporter.last

index_time}'"> <field column="ID" name="uid"/> <field column="NAME" name="name_t"/> <field column="PRICE" name="price_f"/> <field column="WEIGHT" name="weight_d"/> <entity name="feature" pk="ITEM_ID" query="select description as features from feature where

item_id='${item.ID}'"> <field name="features_t" column="features"/>

</entity> <entity name="item_category" pk="ITEM_ID, CATEGORY_ID" query="select CATEGORY_ID from item_category where ITEM_ID='${item.ID}'">

<entity name="category" pk="ID" query="select description as cat from category where id =

'${item_category.CATEGORY_ID}'"> <field column="cat" n a m e="cat t"/>

</entity> </entity>

</entity> </dataconfig>

For details of the attributes, see Schema for the data config in the section Configuration in data-config.xml at the

URL http://wiki.apache.org/solr/DataImportHandler.

• Ensure that last_modified is the column name of the table that you index and the column has time stamp.

• Unless you have this column mapped, partial import fails.

• The latest timestamp is created in the dataimport.properties available in the collection location.

2 Save the file in the conf directory of the collection that you have created.

3 In the solrconfig.xml (in the conf directory), uncomment the following section.

<!-- <requestHandler name="/dataimport" class="org.apache.solr.handler.dataimport.DataImportHandler"> <lst name="defaults"> <str name="config">data-config.xml</str> </lst> </requestHandler> -->

This enables Data Import Handler.

4 Reload the collection. See “Reload collection” on page 107.

5 Use one of the following cfindex actions: fullImport, deltaImport, status, or abort.

Page 107: cf10betafeatures

104COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Modifications to the tag cfindex

New value for the attribute type

To use Data Import Handler, specify type=dih.

New actions

The following new actions have been added to the tag cfindex to help Solr directly fetch data from the database.

• fullimport:To index full database. For example, when you index the database for the first time.

For example,

<cfindex collection="dih1" type="DIH" action="fullimport" status="st"> <cfsearch collection="dih1" criteria="damaged" name="s" orderby="price_f desc" status="stat">

• deltaimport:For partial indexing. For example, for any updates in the database, instead of a full import, you can

perform delta import to update your collection.

For example,

<cfindex collection="dih1" type="DIH" action="deltaimport" status="st"> <cfsearch collection="dih1" criteria="damaged" name="s" orderby="price_f desc" status="stat">

• status:Provides the status of indexing, such as the total number of documents processed and status such as idle

or running.

For example,

<cfindex collection="bt" type="DIH" action="status" status="s"> <cfoutput>

Rows Indexed : #s.TOTAL_DOCUMENTS_PROCESSED# <br>

</cfoutput> <cfoutput>

Status of Solr Server : #s.status# <br>

</cfoutput>

• abort:Aborts an ongoing indexing task.

<cfindex collection="bt" type="DIH" action="abort" status="s"> <cfoutput>

Status of Solr Server : #s.status# <br>

</cfoutput>

Storing your custom data

In addition to indexing, you can store custom information using custom fields that are dynamically defined.

For example, while indexing a PDF, you can store information such as author and date of publication as shown in the

following example:

Page 108: cf10betafeatures

105COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

<cfindex collection="CodeColl" action="refresh"

type="file" key="C:\learning_resources\wwwroot\vw_files\gettingstarted.pdf" urlpath="http://localhost:8500/vw_files/" language="English" title="Cfindex Reference page" status="info"

blurb_s=information publisher_s=adobe/>

To specify custom fields, use the following syntax:

<cfindex ... datefield_dt=#date1#

column_i=#secondaryColumn# body=#primaryColumn# ....../>

In the code, _i stands for integer custom data whose value is stored and indexed. Any field name that ends with _i is

treated as a Solr integer.

Similarly, _s stands for string custom data.

All the supported data types are listed in the schema.xml:

<dynamicfield name="*_i" type="sint" indexed="true" stored="true"/> <dynamicfield name="*_s" type="string" indexed="true" stored="true"/> <dynamicfield name="*_l" type="slong" indexed="true" stored="true"/> <dynamicfield name="*_t" type="text" indexed="true" stored="true"/> <dynamicfield name="*_b" type="boolean" indexed="true" stored="true"/> <dynamicfield name="*_f" type="sfloat" indexed="true" stored="true"/> <dynamicfield name="*_d" type="sdouble" indexed="true" stored="true"/> <dynamicfield name="*_dt" type="date" indexed="true" stored="true"/> <dynamicfield name="random*" type="random"/>

Note: _dt supports only the date formats supported by ColdFusion.

Example

<cfindex collection="custom1" type="file" action="update" key="#datadir#/text/text1.txt" status="s" date_dt=NOW> <cfsearch collection="custom1" criteria="" name="n" orderby="title">

New attribute orderBy in cfsearch

A new attribute orderBy has been added to cfsearch. It sorts the custom field column rank order. This is an optional

attribute and by default, it sorts in ascending order.

<cfsearch collection="someCollection" criteria="someCriteria" orderby="field1 desc,field2,field3 asc" ....../>

Autocommit indexed documents

Automatically commit the changes to the search server by setting the attribute autoCommit to true in cfindex as

shown in the following example:

Page 109: cf10betafeatures

106COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

<cfindex collection="autocommit_check" action="update" type="file" key="#Expandpath(".")#/_boost1.txt" first_t="fieldboost" second_t="secondfield" fieldboost="first_t:1,second_t:2" docboost="6" autocommit="true">

If false, indexed documents are not committed unless you specifically commit using cfindex action="commit". By

default, the value is set to true.

Improving search result rankings

The following attributes in cfindex help you improve the search result rankings:

• fieldBoost: Boost specific fields while indexing.

fieldBoost enhances the score of the fields and thereby the ranking in the search results. Multiple fields can be

boosted by specifying the values as a comma-separated list.

• docBoost: Boost entire document while indexing.

docBoost enhances the score of the documents and thereby the ranking in the search results.

Variations from ColdFusion 9

• ColdFusion 9 had limited support for custom fields namely custom1, custom2, custom3, and custom4. In

ColdFusion 10, custom fields are dynamic.

• In ColdFusion 9, all custom fields are displayed. In ColdFusion 10, cfdump yields only fields that have data. That

is, if you have specified only custom 1 and custom 2, only those two fields are displayed.

• Consider the following code:

<cfsearch criteria='some_criteria and column_i: [ 10 - 20 ]'...>

Here, some_criteria indicates filtering. For example column_i: [ 10 - 20 ] means search all items whose

values are between 10 and 20. column_i is the custom field provided by user while indexing.

This option was available in ColdFusion 9, but limited to four custom fields. In ColdFusion 10, the options are

unlimited.

• In ColdFusion 10, you can sort the order in which search results have to be returned.

Note: When you search a Solr collection for field type string, the criteria should be within quotes, for example

criteria='string_s:"something missing"'

Solr Search example 1

<cfsearch collection="custom1" criteria="rank_i:[2 TO 4]" name="s1" orderby="value_i" status="s"> <cfdump var="#s1#">

Solr Search example 2: Using wild cards

<!------ Searching with wildcard *---------> <cfsearch collection="custom1" criteria="text1_t:blue*" name="s1" status="s" orderby="cf_i"> <cfoutput>

Searching Text with wildcard * :#s.FOUND# <br>

</cfoutput>

Page 110: cf10betafeatures

107COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Search limitations

Limitations: Searching custom fields of type string

Strings cannot be searched with wild cards except *. Since strings are not tokenized, you cannot search any word in a

string. String can be searched as a whole and not as individual words.

For example, in the case of str_s="All work and no play", you cannot search for play or work in this string. You

have to perform search using full string. However, strings can be sorted in search (using orderby attribute).

Limitations: Searching custom fields of type text

Text type field is tokenized and therefore you can search for any word in the text. You can also search text using wild

cards. The only limitation is that text type cannot be sorted while searching. Since text type is tokenized, Solr treats text

as a set of tokens, and therefore sorting is not possible.

Limitations: Searching custom fields is case-sensitive

Custom fields can be searched only in lowercase. For example, if the name of the custom field is newDate, you must

search for newdate.

Limitations: Using the attribute orderBy

The attribute orderBy must be used with untokenized fields such as stings.

Reload collection

In ColdFusion 9, to reload an individual collection you have to restart Solr, which reloads all the collections. So,

whenever you modify schema.xml, for example while adding language or field type, or when you enable Data Import

Handler, you have to restart Solr so that changes take effect.

In ColdFusion 10, you can limit the reload to a specific collection which helps in significant performance

improvement.

To reload a collection,

1 In the ColdFusion Administrator, go to Data & Services > ColdFusion Collections.

2 For the specific collection, click Reload icon in Solr Collections > Actions.

Support for additional languages

ColdFusion supports search and indexing for 17 languages in addition to English. If your language is not available, you

can add to the list, provided Solr supports indexing and search for that language.

For details of the supported languages, see http://wiki.apache.org/solr/LanguageAnalysis.

If Solr supports the language, you can add it as follows:

1 Add filter class in the schema.xml.

• Add the field type as follows:

Page 111: cf10betafeatures

108COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

<fieldtype name="text_th" class="solr.TextField"> <analyzer class="org.apache.lucene.analysis.th.ThaiAnalyzer"/>

</fieldtype> .... <fieldtype name="text_hi" class="solr.TextField">

<analyzer> <tokenizer class="solr.StandardTokenizerFactory"/> <filter class="solr.IndicNormalizationFilterFactory"/> <filter class="solr.HindiNormalizationFilterFactory"/> <filter class="solr.HindiStemFilterFactory"/>

</analyzer> </fieldtype>

• Add the field name as follows:

<field name="contents_pt" type="text_pt" indexed="true" stored="false" required="false"/> <field name="contents_hi" type="text_hi" indexed="true" stored="false" required="false"/>

2 In the ColdFusion Administrator, go to Data & Services > Solr Server.

3 In the section Configure Indexing languages, specify the following:

• New language: Specify the language, for example Hindi.

• New language suffix: Specify a suffix for the language, for example hi for Hindi.

Security enhancements

Securing Solr

Since Solr cannot be done at a document level or communication level. But you can add security to your Solr search

by ensuring that the application server on which Solr runs is secure. To do this,

1 Secure the application server on which Solr runs; the default is jetty.

2 In the ColdFusion Administrator, go to Data & Services > Solr Server.

3 In Configure Solr server, click Show advanced settings.

4 Check Use HTTPS connection and then specify the Solr Admin HTTPS Port.

Note: Recommended to use when you use DIH.

Support for authentication

In ColdFusion 9, any user can access and add, update, and delete documents for indexing. This release provides basic

authentication in jetty to secure access to collections.

1 Modify the web.xml of jetty server as follows:

Page 112: cf10betafeatures

109COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

<security-constraint> <web-resource-collection>

<web-resource-name> Solr authenticated application

</web-resource-name> <url-pattern>

/core1/ </url-pattern> {*}

</web-resource-collection> <auth-constraint>

<role-name> core1-role

</role-name> </auth-constraint>

</security-constraint> <login-config>

<auth-method> BASIC

</auth-method> <realm-name>

Test Realm </realm-name>

</login-config>

2 Uncomment the following section in jetty.xml:

<set name="UserRealms"> <array type="org.mortbay.jetty.security.UserRealm">

<item> <new>

<set name="name"> Test Realm

</set> <set name="config">

<systemproperty name="jetty.home" default="."/> /etc/realm.properties

</set> </new>

</item> </array>

</set>

3 Add your username and password in /etc/example/realm.properties file as follows:

username:password, core1-role

4 In the ColdFusion Administrator, go to Data & Services > Solr Server > Click Show Advanced Settings in Configure

Solr Server section.

5 Specify the username and password and then click Submit.

Note: If you do not specify the credentials, index operation occurs without authentication.

Scheduler enhancements

Scheduler enhancements let you schedule tasks in a granular, scalable, and organized way. The enhancements include:

• Quartz scheduling service: For details, see http://www.quartz-scheduler.org/.

Page 113: cf10betafeatures

110COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

• Grouping: Arrange tasks in to different groups as shown here:

<cfschedule action=update task=t1 url="www.adobe.com" group="G1"/>

You can club tasks into groups so that later on, you can resume or pause all the tasks in a same group rather than

repeat for individual tasks.

• Application-specific tasks: Apart from scheduling tasks at server level, you can schedule tasks at application level,

visible only to the application, as shown here:

<cfschedule action=update task=t1 url="www.adobe.com" group="G1" mode="application"/>

The default mode is server.

• Event Handling: Attach listeners to scheduled tasks.

For example, you can write a listener CFC that does the following:

• On completion of the task, sends a mail to all stakeholders (onTaskEnd)

• Decide if the task should execute (onTaskStart)

• In the case of exception, refires the task (onError)

• Executes the code provided inside a method instead of invoking the URL (execute)

Page 114: cf10betafeatures

111COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

<cfcomponent implements="cfide.scheduler.ITaskEventHandler"> <cffunction name="beforeExecute" returntype="boolean">

<cfargument name="context" type="struct"/> <cfdump var="In BeforeExecute" output="console"> <cfmail from="[email protected]" subject="Scheduler_Scenario_Testing" to="[email protected]">

The Report is about to be generated. </cfmail> <cfreturn true>

</cffunction> <cffunction name="onMisfire" returntype="void">

<cfargument name="context" type="struct" required="false"/> <cfdump var="In onMisfire for #context.task#" output="console"> <cfmail from="[email protected]" subject="Scheduler_Scenario_Testing" to="[email protected]">

The Report generation task has misfired. </cfmail>

</cffunction> <cffunction name="onTaskEnd" access="public" returntype="void">

<cfargument name="context" type="struct" required="false"/> <cfdump var="In onTaskEnd for #context.task#" output="console">

</cffunction> <cffunction name="onError" returntype="void">

<cfargument name="context" type="struct" required="false"/> <cfdump var="In OnError for #context.task#" output="console">

</cffunction> <cffunction name="execute" returntype="void"> <cffile action="append" file="#Expandpath('.')#/log.txt" output="<br><b>In

Execute</b><br>"> </cffunction> </cfcomponent>

Note: The listener has to extend CFIDE.scheduler.ITaskEventHandler.cfc.

• Chaining: Lets you define dependent tasks. If the parent task is executed, all dependent tasks are also executed.

<cfschedule action=update task=t1 url="www.adobe.com" group="G1" mode="application" onComplete="t2:DEFAULT:application">

In this example, the value of onComplete must be provided in the following format: <task>:<group>:<mode>

Note: You cannot chain an application-specific task after a server-specific task.

• Cluster: You can run scheduler in cluster setups. Currently clustering works only with JDBC job store. Features

include load-balancing and job fail-over. A single application can have both clustered as well as non-clustered

setup. So tasks can go to either of the setups.

The system time of all clustered servers have to be same.

To enable cluster setup, use the ColdFusion Administrator. For details, see “Scheduled tasks” on page 220.

• Cron commands: You can trigger a scheduled task using cron commands. Cron-Expressions are strings made up

of seven subexpressions (Seconds, Minutes, Hours, Day-of-Month, Month, Day-of-Week, and Year (optional

field)), that describe individual details of the schedule.

Sub-expression are separated with white space.

Page 115: cf10betafeatures

112COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

For example, "0 0 12 ? * WED" is a complete cron expression that means every Wednesday at 12:00 pm.

For details, see http://www.quartz-scheduler.org/docs/tutorial/TutorialLesson06.html .

• Prioritize tasks: You can set priorities for the tasks. Assume that you have 50 tasks that have to start at the same

time. But there are only 10 worker threads currently available. Then, the first 10 tasks with the highest priority start

before others. Priority can be any integer value. The default value is 5.

• Exclude dates: You can exclude dates from the scheduling process.

For example, you can set to execute a job from September 1 to December 30, except on December 25.

For exclusion, you can specify a comma-separated list of dates, date, or date range.

For example,

<cfschedule .... exclude="date1 TO date2" .../>

<cfschedule ... exclude="02/02/2011,03/03/2011" .../>

All the dates from date1 to date2 (inclusive) are excluded from scheduling. You can provide an array of date

strings or an array of date objects.

• In case of error: You can specify the action to be taken.

<cfschedule task="job1" onException="REFIRE,PAUSE,INVOKEHANDLER" ....>

That is, if an error occurs while running the job, you can decide if to refire the task, pause the job, or invoke onError

method of the attached eventhandler.

• If task misfires: You can specify the action to be taken.

That is, if to refire, reschedule, or invoke onMisfire method of the attached eventhandler.

<cfschedule task="trigger1" onmisfire="FIRE_NOW ,NOW_EXISTING,NOW_REMAINING,NEXT_EXISTING,NEXT_REMAINING,INVOKEHANDLER..../>

A misfire occurs if a persistent trigger misses the firing time because the scheduler was shut down, or because there

are no available threads in thread pool to execute the job. The threshold value for a task to be considered as misfired

is 60 seconds.

Note: All misfired tasks are logged in scheduler.log available in cf_root\WEB-INF\cfusion\logs\scheduler.log file on

J2EE configurations, or the cf_root\logs\scheduler.log file on server configurations.

• Pause and resume/Pause all and resume all: Pause or resume the tasks of whole group as follows:

<cfschedule group="group1" action="pause" .......>

<cfschedule group="group1" action="resume" .......>

This can be specified at the server-level or application level as follows:

<cfschedule action="pauseall" mode=application/>

<cfschedule action="resumeall" mode=server/>

• List tasks: Lists all scheduled tasks at the server level or application level:

<cfschedule action="list" mode="application" result ="res" />

• Retry: If running a job results in an exception, you can preset to continue re-firing, till retry count is over, as follows:

<cfschedule task="job1" onException="REFIRE" retryCount="3" ....>

• Repeat: Specify the number of times a given schedule has to repeat.

For example, run Job1 at 2 pm today and repeat it 20 times at the interval of 10 minutes.

Page 116: cf10betafeatures

113COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

In this case, you need not specify the end time of the schedule.

<cfschedule task="task1" repeat="20" interval="60" ....>

• Customize quartz: Advanced users can customize Quartz using quartz.properties available in cfusion\lib\quartz.

The current version of Quartz being shipped with ColdFusion is 2.02.

Enhancements to the tag cfschedule

Description

Provides a programmatic interface to the ColdFusion scheduling engine. Can run a CFML page at scheduled intervals,

with the option to write the page output to a static HTML page. This feature enables you to schedule pages that publish

data, such as reports, without waiting while a database transaction is performed to populate the page.

Category

Variable manipulation tags

Syntax

<cfschedule action = "run|update|pause|resume|delete|pauseall|resumeall|list" task = "task name" endDate = "date" endTime = "time" file = "filename" interval = "seconds" operation = "HTTPRequest" password = "password" path = "path to file" port = "port number" proxyPassword = "password" proxyPort = "port number" proxyServer = "host name" proxyUser = "user name" publish = "yes|no" requestTimeOut = "seconds" resolveURL = "yes|no"

isDaily = "yes|no" overwrite = "yes|no"

startDate = "date" startTime = "time" url = "URL" username = "user name">

group="group1" oncomplete="how to handle exception" eventhandler="path_to_event_handler" onException="refire|pause|invokeHandler" cronTime="time" repeat="number" priority="integer" exclude="date|date_range|comma-separated_dates" onMisfire = "" cluster="yes|no mode="server|application" retryCount="number"

Page 117: cf10betafeatures

114COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

OR <cfschedule action = "delete" task = "task name"> OR <cfschedule action = "run" task = "task name"> OR <cfschedule action = "pauseAll" mode = "server|application"> OR <cfschedule action = "resumeAll" mode = "server|application"> OR <cfschedule action = "list" mode = "server|application"

result = "res">

Note: You can specify this tag's attributes in an attributeCollection attribute whose value is a structure. Specify the

structure name in the attributeCollection attribute and use the tag’s attribute names as structure keys.

See also

cfcookie, cfparam, cfregistry, cfsavecontent, cfset

History

ColdFusion 10: Added the actions list, pauseall, and resumeall.

ColdFusion 10: Added the attributes group, onComplete, eventHandler, onException, cronTime, repeat,

priority, exclude, onMisfire, cluster, mode, isDaily, overwrite, and retryCount.

ColdFusion MX 6.1: Changed the way intervals are calculated. The day length now reflects changes between standard

and daylight saving times. The month length is now the calendar month length, not four weeks. The scheduler handles

leap years correctly.

Page 118: cf10betafeatures

115COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Attributes

Attribute Req/Opt Default Description

action Required • delete: Deletes the specified task.

• update: Updates an existing task or creates a task, if one with the name

specified by the task attribute does not exist.

• run: Executes the specified task.

• pause: Pauses the specified task.

• resume: Continues executing the specified task.

• list: Lists all the scheduled tasks.

• pauseAll: Pauses all scheduled tasks for a particular application.

• resumeAll: Resumes all scheduled tasks for a particular application.

task Required Name of the task.

endDate Optional Date when scheduled task ends. The default date format is mm/dd/yy.

endTime Optional Time when scheduled task ends (seconds).

file Required if

publish="Yes"

Name of the file in which to store the published output of the scheduled task.

interval Required if

action="update"

Interval at which task is scheduled:

• number of seconds

• once

• daily

• weekly

• monthly

operation Required if

action="update"

Operation that the scheduler performs. Must be HTTPRequest.

overwrite true If false, results in the creation of new output files every time the task executes.

If true, instead of creating new outputfiles, the existing one is overwritten.

isDaily true By default, (runs the task every day at a specified time interval you specify, for

example between 2pm and 3pm daily. If false, task runs based on your

schedule.

password Optional Password, if URL is protected.

path Required if

publish = "Yes"

Path to the directory in which to put the published file.

port Optional 80 Port to use on the server that is specified by the url parameter. If

resolveURL="yes", retrieved document URLs that specify a port number are

automatically resolved, to preserve links in the retrieved document. A port

value in the url attribute overrides this value.

proxyPassword Opt Password to provide to the proxy server.

proxyPort Optional 80 Port number to use on the proxy server.

Page 119: cf10betafeatures

116COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

proxyServer Optional Host name or IP address of a proxy server.

proxyUser Opt User name to provide to the proxy server.

publish Optional no • yes: saves the result to a file.

• no

requestTimeOut Optional Can be used to extend the default time-out period.

resolveURL Optional no • yes: resolves links in the output page to absolute references.

• no

startDate Required if

action="update"

Date on which to first run the scheduled task. The default date format is

mm/dd/yy.

startTime Required if

action="update"

Time at which to run the scheduled task.

url Required if

action="update"

URL of the page to execute.

username Optional User name, if URL is protected.

group Optional default The group to which the scheduled task belongs.

onComplete Optional invokeHandler The action to be performed after the completion of current task.

eventHandler Optional A CFC file whose pre-defined methods are invoked for various events while

running the task. The CFC must be implementing ITaskEventhandler

The path you specify must be relative to webroot. For example,

schedulerdemo.eventhandler.

onException Optional invokeHandler Specify what to do if a task results in error. The options are:

• refire: Tries to run the task immediately.

• pause: Stops the task from executing further.

• invokeHandler: Invokes onError method of the eventhandler as defined

by the user.

cronTime Optional Specifying task scheduling time in cron job syntax.

repeat Optional -1 The number of times a task has to be repeated.

priority Optional 5 An integer that indicates the priority.

exclude Optional Comma-separated list of dates or date range for exclusion in the schedule

period.

Attribute Req/Opt Default Description

Page 120: cf10betafeatures

117COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Usage

This tag and the ColdFusion Administrator Scheduled task page schedule ColdFusion tasks. Tasks that you add or

change using this tag are visible in the Administrator. You can disable this tag in the Administrator Sandbox/Resource

security page. This tag’s success or failure status is written to the schedule.log file in the cf_root/logs directory

(cf_webapp_root/WEB-INF/cfusion/logs in the multiserver and J2EE configurations).

When you create a task, you specify the URL of the ColdFusion page to execute, the date, time, and frequency of

execution, and whether to publish the task output to an HTML file. If the output is published, you specify the output

file path and file.

If you schedule a job to run monthly on any date in the range 28-31, the scheduler does the following:

• If you schedule a monthly job to run on the last day of a month, the scheduled job will run on the last day of each

month. For example, if you schedule a monthly job to start on January 31, it will run on January 31, February 28 or

29, March 31, April 30, and so on.

• If you schedule a monthly job to run on the 29th or 30th of the month, the job will run on the specified day of each

month for 30 or 31-day months, and the last day of February. For example, if you schedule a monthly job to start

on January 30, the job will run on January 30, February 28 or 29, March 30, April 30, and so on.

If you schedule a job to run once, the starting time is in the past, and the task has not yet run, it runs immediately. If

you schedule a recurring job with a start time in the past, ColdFusion schedules the job to run on the next closest

interval in the future.

The Scheduler configuration file, cf_root\lib\neo-cron.xml contains all scheduled events, as individual entries (except

the clustered tasks).

onMisfire Optional next_remaining for simple

triggers

No misfire by

default for cron

triggers

Specify what the server has to do if a scheduled task misfires.

• NEXT_REMAINING : Trigger is fired for the remaining count starting at next

scheduled trigger time.

• NEXT_EXISTING : Trigger is fired for the existing count starting at next

scheduled trigger time.

• NOW_REMAINING : Trigger is fired for the remaining count starting now.

• NOW_EXISTING : Trigger is fired for the existing count starting now.

cluster Optional no If yes, the task can be executed in cluster setup.

mode Optional server If the task is server-specific or application specific.

retryCount Optional 3 The number of reattempts if the task fails or misfires.

Attribute Req/Opt Default Description

Page 121: cf10betafeatures

118COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Example

<h3>cfschedule Example</h3> <!--- This read-only example schedules a task. To run the example, remove the comments around the code and change the startDate, startTime, url, file, and path attributes to appropriate values. ---> <!--- <cfschedule action = "update" task = "TaskName" operation = "HTTPRequest" url = "http://127.0.0.1/playpen/history.cfm" startDate = "8/17/09" startTime = "12:25 PM" interval = "3600" resolveURL = "Yes" publish = "Yes" file = "sample.html" path = "c:\inetpub\wwwroot\playpen" requestTimeOut = "600"> --->

getSystemFreeMemory

Description

Gets details of free memory.

Returns

Memory, in bytes, that is currently free.

Syntax

getSystemFreeMemory()

getSystemTotalMemory

Description

Gets details of the memory that is available for the operating system, in bytes.

Returns

Memory that is available in bytes.

Syntax

getSystemTotalMemory()

getCPUUsage

Description

Gets the CPU usage with default or custom snapshot interval. The default interval is 1000 milli-seconds.

Syntax

getCPUUsage()

Page 122: cf10betafeatures

119COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

getCPUUsage(long ms)

Parameters

Connect to Microsoft Exchange Server 2010

Support for integration with Microsoft Exchange Server 2010

Adobe ColdFusion can interact with Microsoft Exchange Server 2010 SP1. The enhancements offer support for

Microsoft Exchange Web Services (EWS) which brings in efficacy with the following operations:

• Folder operations such as create, modify, or delete.

• Get rooms and roomlist in the exchange organization.

• Information on user availability, that helps effective scheduling.

• Conversation operations such as find conversation details, copy, move, and the status if the conversation is read.

Note: In ColdFusion 9, the protocol support was limited to WEBDAV.

Note: If you are installing the J2EE configuration of ColdFusion 10, all JARs in the ews folder (residing in cfusion/lib)

have to be present in the system classpath while deploying.

Note: This Beta release does not support form-based authentication to Microsoft Exchange Server 2010.

Setting your Microsoft Exchange Server version

At application level

You can specify the Microsoft Exchange Server version at the application level by providing a value for the variable

exchangeServerVersion as follows:

<cfset this.exchangeserverversion="version">

This corresponds to the attribute with the same name in the tag cfapplication.

In cfapplication

A new attribute exchangeServerVersion has been added to cfapplication.

Syntax

<cfapplication name="app_name" exchangeServerVersion="2010"> ... </cfapplication>

Parameter Description

long ms Time in milli-seconds. This is the time delay between two snapshots.

Page 123: cf10betafeatures

120COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Attribute

Usage

Use this attribute to specify the version of Microsoft Exchange Server that ColdFusion interacts with.

You can also set the version in the Application.cfc

At tag level in any of the cfexchange tags

New attribute serverVersion has been added to the following tags:

• cfexchangeconnection

• cfexchangemail

• cfexchangecalendar

• cfexchangetask

• cfexchangecontact

New attribute folderID added to cfexchangemail

A new attribute folderID supports the following actions: get, move, and set. This is the case-sensitive Exchange

UID value that uniquely identifies the folder.If not specified, folder is used. If either folder or folderID are not

specified, the inbox is used as the default folder to perform the operation.

New actions added to the tag cfexchangecalendar

Added the following three actions:

• getUserAvailability: To effectively schedule meetings and find the availability of users.

• getRoomsList: To find the list of rooms in an organization.

Attribute Required/Optional Default Description

exchangeServerVersion

Optional 2007 Specifies the Microsoft Exchange Server version.

The values are:

• 2003

• 2007

• 2010

If you do not specify the details, 2007 is taken by default.

Attribute Required/Optional Default Description

serverVersion

Optional 2007 Specifies the Microsoft Exchange Server version.

The values are:

• 2003

• 2007

• 2010

If you do not specify the details, 2007 is taken by default.

The value you specify overrides the value that you specify at the

application level.

Page 124: cf10betafeatures

121COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

• getRooms: To find the list of rooms in a room list.

Syntax

getUserAvailability <cfexchangecalendar action = "getUserAvailability" attendees = "attendee_list"

connection = "connection_ID" startDate = "date" endDate = "date" dataRequestType = "freeBusy|suggestions|freeBusyandSuggestions"

name = "name" /> getRoomsList <cfexchangecalendar

action = "getRoomList" name = "name" connection = "connection_ID"/> getRooms <cfexchangecalendar

action = "getRooms" emailAddress = "e-mail_ address" name = "name"

connection = "connection_ID"/>

Attributes

Attribute Action Required/O

ptional

Description

action N/A Optional The action to take. Must be one of the following values:

• getUserAvailability: Gets availability details of users, for scheduling

purposes.

• getRoomsList: Gets various room lists present in the organization.

• getRooms: Gets all the rooms in a room list.

attendees

getUserAvailability

Required Comma-separated list of all attendees.

startDate

getUserAvailability

Required A string that ColdFusion can interpret as a date-time value.

endDate getUserAvailability

Required A string that ColdFusion can interpret as a date-time value.

dataRequestType

getUserAvailability

Required • freeBusy: Returns an array of availability details.

• Suggestions: Returns an array of struct that contains suggestion details.

• freeBusyandSuggestions: Returns both the array of suggestions and an array

of attendeeavailability.

See the sections on suggestion struct and attendeeavailability struct for

details.

Page 125: cf10betafeatures

122COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Suggestions

name getUserAvailability

getRoomsList

getRooms

Required Variable in which the results are displayed.

emailAddress

getRooms Optional Defines the Simple Mail Transfer Protocol (SMTP) address of a mailbox user.

connection

getUserAvailability

getRoomsList

Optional The name of the connection to the Exchange server, as specified in the

cfexchangeconnection tag.

If you omit this attribute, create a temporary connection by specifying

cfexchangeconnection tag connection openaction attributes in the

cfexchangecontact tag.

Struct values Description

date Suggested day for the meeting.

quality The quality of the suggested day, if Excellent, Good, Fair or Poor.

TimeSuggestion

An array of struct that contains the following values:

• MeetingDate: Suggested meeting time.

• Quality: The quality of the time. It can be Excellent, Good, Fair, or Poor.

• array of conflicts: The conflicts at the suggested time. This is a struct that contains the following values:

ConflictType (the type of conflict, which can be individualAttendeeConflict, which is a conflict

with an attendee, GroupConflict which is a conflict with at least one member of a group,

GroupTooBigConflict which is a conflict with at least one member of a group, but the group was too

big for detailed information to be returned, and UnknownAttendeeConflict which is a conflict with an

unresolvable attendee or an attendee that is not a user, group, or contact).

• FreeBusyStatus: Gets the free/busy status of the conflicting attendee. Only meaningful when

ConflictType is equal to IndividualAttendee. The values are Free, Tentative, Busy, OOF (time

slot associated with the appointment appears as Out of Office) or NoData (no free/busy status is associated

with the appointment).

• NoOfMembers: Gets the number of users, resources, and rooms in the conflicting group. Only meaningful

when ConflictType is equal to ConflictType GroupConflict.

• NoOfMembersAvailable: Gets the number of available members (whose status is Free) in the

conflicting group. Only meaningful when ConflictType is equal to ConflictType GroupConflict.

• NoOfMembersWithConflict: Gets the number of members who have a conflict (whose status is Busy,

OOF, or Tentative) in the conflicting group. Only meaningful when ConflictType is equal to

ConflictType GroupConflict.

• NoOfMembersWithNoData: Gets the number of members who do not have published free/busy data in

the conflicting group. Only meaningful when ConflictType is equal to ConflictType GroupConflict.

• isWorkTime: If the suggested meeting happens in the work hours.

Attribute Action Required/O

ptional

Description

Page 126: cf10betafeatures

123COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Values of the struct attendeeavailability

Struct values Description

CalendarEvent A struct that contains the following values:

• startTime: The start date and time of the event.

• endTime: The end date and time of the event.

• freeBusyStatus: The free/busy status associated with the event. It can have following values: Free,

tentative, busy , OOF (Out of Office), or NoData (no free/busy status is associated with the

appointment).

• details: The details of the calendar event; details is null if the user who requests for details does not

have the appropriate rights. details is a struct that contains the following values: location (calendar

location), eventstoreId (store ID of the calendar event), and Subject (can be isException which is

a boolean value that indicates if the calendar event is an exception in a recurring series, isMeeting which

is a boolean value that indicates if the calendar event is a meeting, isPrivate which is a boolean value

that indicates if the calendar event is private, isRecurring which is a boolean value that indicates if the

calendar event is recurring, and isRemainderSet which is a boolean value that indicates if the calendar

event has a reminder set).

Page 127: cf10betafeatures

124COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Example

The following example shows how you can get UserAvailability action:

Application.cfm

mergedFreeBusyStatus

An array of struct that contains status. The status can be

• Free : The time slot associated with the appointment appears as Free.

• Tentative : The time slot associated with the appointment appears as Tentative.

• Busy : The time slot associated with the appointment appears as Busy

• OOF: The time slot associated with the appointment appears as Out of Office.

• NoData: No free/busy status is associated with the appointment.

• result: The result associated with the response. This can be success, warning, or error.

viewType The free/busy view type retrieved for the attendee. It can have the following values:

• None: No view is returned. This value cannot be specified in a call to GetUserAvailability.

• MergedOnly: An aggregated free/busy stream. If the target user in one forest does not have an Availability

service configured, the Availability service of the requestor retrieves the target user’s free/busy information

from the free/busy public folder. Because public folders only stores free/busy information in merged form,

MergedOnly is the only available information.

• FreeBusy: The legacy status information (free, busy, tentative, and OOF). This also includes the

start/end times of the appointments. This view is comprehensive than the legacy free/busy view because

individual meeting start and end times are provided instead of an aggregated free/busy stream.

• FreeBusyMerged: All the properties in FreeBusy with a stream of merged free/busy availability

information.

• Detailed: The legacy status information (free, busy, tentative, andOOF, the start/end times of the

appointments; and various properties of the appointment such as subject, location, and importance). This

requested view returns the maximum amount of information for which the requesting user is privileged. If

merged free/busy information only is available, as with requesting information for users in a Microsoft

Exchange Server 2003 forest, MergedOnly is returned. Otherwise, FreeBusy or Detailed are returned.

• DetailedMerged: Represents all the properties in Detailed with a stream of merged free/busy

availability information. If, only merged free/busy information is available, for example if the mailbox exists

on a computer running Exchange 2003, MergedOnly is returned. Otherwise, FreeBusyMerged or

DetailedMerged is returned.

workingHours A struct that contains the following details:

• startTime: The start date and time of the event.

• endTime: The end date and time of the event.

• daysOfTheWeek: An array of struct. The working days of the attendees. It can have the following values:

Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Weekday, and

WeekEndDayDay.

• Timezone: A struct that contains the following fields: id (ID of the time zone definition) and name (name

of this time zone definition).

Struct values Description

Page 128: cf10betafeatures

125COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

<!--- Setting the present Date ---> <cfset todayDate = #Now()#> <cfset fromDate = #DateFormat(todayDate, "mm/dd/yyyy")# & ' ' & #TimeFormat(todayDate, "HH:MM:SS")#> <!--- Adding one day to present date---> <cfset toDate1 = DateAdd("d", "1", "#fromDate#")> <!--- <cfset toDate = #DateFormat(toDate, "mm/dd/yyyy")#&' '&#TimeFormat(toDate, "HH:MM:SS")#>---> <cfset toDate1 = #DateFormat(toDate1, "mm/dd/yyyy")# & ' ' & #TimeFormat(toDate1, "HH:MM:SS")#> <!---Creating a calendar event ---> <cffunction name="constructCalendarStruct" returntype="struct">

<cfargument name="AllDayEvent" type="string"/> <cfargument name="Duartion" type="string"/> <cfargument name="EndTime" type="string"/> <cfargument name="From" type="string"/> <cfargument name="HasAttachment" type="string"/> <cfargument name="HtmlMessage" type="string"/> <cfargument name="Importance" type="string"/> <cfargument name="IsRecurring" type="string"/> <cfargument name="Location" type="string"/> <cfargument name="Message" type="string"/> <cfargument name="OptionalAttendees" type="string"/> <cfargument name="Organizer" type="string"/> <cfargument name="Reminder" type="string"/> <cfargument name="RequiredAttendees" type="string"/> <cfargument name="Resources" type="string"/> <cfargument name="Sensitivity" type="string"/> <cfargument name="StartTime" type="string"/> <cfargument name="Subject" type="string"/> <cfargument name="UID" type="string"/> <cfscript>

var eventInfo = structNew(); if(isdefined("AllDayEvent") EQ 1)

eventInfo.AllDayEvent = AllDayEvent; if(isdefined("Duration") EQ 1)

eventInfo.Duration = Duration; if(isdefined("EndTime") EQ 1)

eventInfo.EndTime = EndTime; if(isdefined("From") EQ 1)

eventInfo.From = From; if(isdefined("HasAttachment") EQ 1)

eventInfo.HasAttachment = HasAttachment; if(isdefined("HtmlMessage") EQ 1)

eventInfo.HtmlMessage = HtmlMessage; if(isdefined("Importance") EQ 1)

eventInfo.Importance = Importance; if(isdefined("IsRecurring") EQ 1)

eventInfo.IsRecurring = IsRecurring; if(isdefined("Message") EQ 1)

eventInfo.Message = Message; if(isdefined("OptionalAttendees") EQ 1)

eventInfo.OptionalAttendees = OptionalAttendees; if(isdefined("Organizer") EQ 1)

eventInfo.Organizer = Organizer; if(isdefined("Reminder") EQ 1)

eventInfo.Reminder = Reminder; if(isdefined("RequiredAttendees") EQ 1)

Page 129: cf10betafeatures

126COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

eventInfo.RequiredAttendees = RequiredAttendees; if(isdefined("Resources") EQ 1)

eventInfo.Resources = Resources; if(isdefined("Sensitivity") EQ 1)

eventInfo.Sensitivity = Sensitivity; if(isdefined("StartTime") EQ 1)

eventInfo.StartTime = StartTime; if(isdefined("Subject") EQ 1)

eventInfo.Subject = Subject; if(isdefined("UID") EQ 1)

eventInfo.UID = UID; if(isdefined("Location") EQ 1)

eventInfo.Location = Location; </cfscript> <cfreturn eventInfo>

</cffunction> <!--- Function to delete calendar events ---> <cffunction name="deleteAllEvents">

<cfargument name="convariable" type="any"/> <cfexchangecalendar action="get" name="deleteQuery" connection="convariable"> </cfexchangecalendar> <cfloop query="deleteQuery">

<cfexchangecalendar action="delete" connection=convariable uid=#deleteQuery.uid#> </cfloop>

</cffunction>

Availability.cfm

<cfexchangeConnection action="open" username = "user1" password="Password" server="IP_Address" serverversion="2010" connection="conn1"> <cfexchangeConnection action="open" username = "user2" password="Password" server="IP_Address" serverversion="2010" connection="conn2"> <cfset deleteAllEvents(conn1)> <cfset deleteAllEvents(conn2)> <!--- Creating All day event for user1 ---> <cfset eventInfo = constructCalendarStruct(AllDayEvent="yes",Importance="High",Subject="Testplan1",StartTime="#fromDate#")> <cfset eventInfo1 = constructCalendarStruct(AllDayEvent="yes",Importance="High",Subject="Testplan",StartTime="#fromDate#")> <cfexchangeCalendar action="create" connection="conn1"

Page 130: cf10betafeatures

127COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

event="#eventInfo#" result="UID"> <cfscript>sleep(15000);</cfscript> <cfexchangeCalendar action="create" connection="conn2" event="#eventInfo1#" result="UID1"> <cfscript>sleep(15000);</cfscript> <cfexchangeCalendar attendees="[email protected]" action="getuseravailability" connection="conn1" datarequesttype="freebusyandsuggestions" startDate="#fromDate#" endDate="#toDate1#" name="result"> <cfdump var="#result#"> <cfset deleteAllEvents(conn1)> <cfset deleteAllEvents(conn2)>

The following example shows how you can use the actions getRooms and getRoomList.

<cfexchangeConnection action="open" username = "sample" password="Password" server="IP_Address" serverversion="2010" connection="conn1"> <cfexchangecalendar action="getroomlist" name="roomList" connection="conn1"> <cfdump var="#roomList#"> <cfexchangecalendar action="getrooms" emailaddress="[email protected]" name="rooms" connection="conn1"> <cfdump var="#rooms#">

Modifications to the tag cfexchangecalendar

For all the cfexchangecalendar actions, the value of the attribute uid is as follows:

• If exchangeServerVersion is set to 2003 or 2007: The uid indicates the ID of the appointment in the mailbox of

the organizer.

• If exchangeServerVersion is set to 2010: The uid indicates the ID of the received appointment in the mailbox of

the attendee.

In the case of interaction with Microsoft Exchange server 2003 or 2007, whenever an appointment is created, the UID

of the organizer can be used by the attendee for any operation such as responding, deleting, or getting attachments. In

the case of Microsoft Exchange server 2010, the behavior is different. If attendees have to perform appointment-related

actions, they have to first search for the appointment in their mailbox and then use the UID of that appointment.

cfexchangefolder

Description

Lets you perform various actions on the mail folder, such as get folder information, find folders, or create, copy,

modify, move, delete, and empty the contents of a folder.

Page 131: cf10betafeatures

128COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

History

ColdFusion 10: Added this tag.

Category

Communications tags

Syntax

getExtendedlnfo <cfexchangefolder action = "getExtendedlnfo" folderID = "Exchange folder UID"

connection = "connection_ID" name = "query_name"/> OR getExtendedlnfo <cfexchangefolder action = "getExtendedlnfo" folderPath = "Exchange_folder_Path"

connection = "connection_ID" name = "query_name"

pathDelimitter = "delimiter_characters"/> getlnfo <cfexchangefolder action = "getInfo"

connection = "connection_ID" folderID = "Exchange folder UID" name = "query_name"/> OR getlnfo <cfexchangefolder action = "getInfo" folderPath = "Exchange_folder_Name"

connection = "connection_ID" name = "query_name"

pathDelimitter = "delimiter_characters"/> findSubFolders <cfexchangefolder action = "findSubFolders" folderID = "Exchange folder UID"

connection = "connection_ID" name = "query_name"/> create <cfexchangefolder action = "create" folder = "struct" parentFolderID = "folder_UID"

connection = "connection_ID" result = "variable for contact UID"/>

copy <cfexchangefolder action = "copy" destinationFolderID = "Folder_UID" sourceFolderID = "folder_UID">

connection = "connection_ID"

Page 132: cf10betafeatures

129COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

result = "variable for contact UID"/> delete <cfexchangefolder action = "delete" deleteType = "hardDelete|softDelete|moveToDeletedItems" uid = "folder UID">

connection = "connection_ID"/> move <cfexchangefolder action = "move" destinationFolderID = "Folder_UID" sourceFolderID = "folder_UID">

connection = "connection_ID" result = "variable for contact UID"/>

modify <cfexchangefolder action = "modify" uid = "folder UID"

folder = "strut" connection = "connection_ID"/> empty <cfexchangefolder action = "empty" uid = "folder UID" deleteType = "hardDelete|softDelete|moveToDeletedItems">

deleteSubFolder = "true|false" connection = "connection_ID"/>

See also

cfexchangecalendar, cfexchangeconnection, cfexchangefilter, cfexchangemail, cfexchangetask,

Interacting with Microsoft Exchange Servers in the Developing ColdFusion Applications

Page 133: cf10betafeatures

130COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Attributes

Attribute Action Req/Opt Default Description

action N/A Required The action to take.

Must be one of the following values:

• getInfo

• getExtendedlnfo

• findSubFolders

• create

• copy

• delete

• move

• modify

• empty

name getExtendedlnfo

getInfo

findSubFolders

Required The name of the ColdFusion query variable that

contains the returned information about the folder.

folderID getExtendedlnfo

getInfo

findSubFolders

delete

modify

empty

Not required

for

getExtendedInfor and

getInfo, if

folder path is

specified.

UID that is used to identify the folder in which the

actions are performed.

folderPath getExtendedlnfo

getInfo

Not required if

folderID is

specified.

Full path to the folder where the action has to be

performed.

If you do not specify the path delimiter, / is taken

by default.

pathDelimiter getExtendedlnfo

getInfo

Optional / Lets you specify the delimiter that is used to

separate the folders.

parentFolderId

create Required UID that is used to identify the folder in which you

create subfolders.

connection All actions Required The name of the connection to the Exchange server,

as specified in the cfexchangeconnection tag.

If you omit this attribute, create a temporary

connection by specifying

cfexchangeconnection tag connection

openaction attributes in the

cfexchangecontact tag.

result create

copy

move

Required A query variable that contains the result returned

from the exchange server when one of the action is

performed.

Page 134: cf10betafeatures

131COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Result struct values for cfexchangefolder action = "getExtendedlnfo"

For the action getExtendedInfo, the result is a struct that contains the following fields:

destinationFolderID

copy

move

Required A case-sensitive Exchange UID value that uniquely

identifies the destination folder.

sourceFolderID

copy

move

Required The UID that is used to identify the folder from

which you copy or move folders to the destination

folder.

deleteType delete

empty

Optional moveToDeletedItems

• hardDelete: Removes a folder permanently

from the Exchange server.

• softDelete: Moves a folder to the dumpster in

Exchange server, if dumpster is enabled.

• moveToDeletedItems: Moves a folder to the

deleted items folder.

deleteSubFolders

empty Optional False If true, deletes the subfolder.

folder create

modify

Required A struct that contains the required information of

the folder that has to be created or modified, such

as display name and folder class.

Field Description

ChildFolderCount The number of child folders that the parent folder has.

displayName The display name of the folder.

FolderClass The folder class.

FolderPath The folder path.

ManagedFolder Struct that contains the following properties:

• canDelete: Boolean value that indicates if the user can delete objects in the folder.

• canRenameOrMove: Boolean value that indicates if the user can rename or move objects in the

folder.

• mustDisplayComment: Boolean value that indicates if the client application must display the

comment property to the user.

• HasQouta: Boolean value that indicates if the folder has a quota.

• IsManagedFoldersRoot: Boolean value that indicates if the folder is the root of the managed

folder hierarchy.

• ManagedFolderId: The ID of the managed folder.

• comment: The comment that is associated with the folder.

• StorageQuota: The storage quota of the folder.

• FolderSize: The size of the folder.

• HomePage: The home page associated with the folder.

mustDisplayComment Boolean value that indicates if the client application must display the comment property to the user.

Attribute Action Req/Opt Default Description

Page 135: cf10betafeatures

132COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Result struct values for cfexchangefolder action = "getInfo"

For the action getInfo, the result is a struct that contains the following fields:

ParentFolderId The ID of the folder's parent folder.

Permission List of permissions for the folder. This is an array of permission structs with the following values:

• canCreateItems: Boolean value that indicates if the user can create new items.

• canCreateSubFolders: Boolean value that indicates if the user can create subfolders.

• deleteItems: Indicates if/how the user can delete existing items. The values are None (the user

does not have the associated permission), Owned (the user has the associated permission on items

that it owns), and All (the user has the associated permission on all items).

• displayPermissionLevel: The permission level that Outlook displays for this folder permission.

It can have the following values: None, Owner, PublishingEditor, Editor, PublishingAuthor, Freebusytimeandsubjectandlocation, FreebusytimeOnly, Author, NonEditingAuthor, Reveiwer, Contributor, and Custom.

• EditItems: Indicates the items in a folder that the user has permission to edit. Values are none,

owned, or all.

• isFolderContact: Boolean value that indicates if the user is a contact for the folder.

• isFolderOwner: Boolean value that indicates if the user owns the folder.

• isFolderVisible: Boolean value that indicates if the folder is visible to the user.

• PermissionLevel: Represents the combination of permissions that a user has on a folder. The

values are same as that of displayPermissionLevel except

Freebusytimeandsubjectandlocation and FreebusytimeOnly.

• readItems: The read item access permission. The values are as follows: None (user has no read

access on the items in the folder), TimeOnly (user can read the start and end date and time of

appointments; applies only to Calendar folders, TimeAndSubjectAndLocation (user can read the

start and end date and time, subject, and location of appointments; applies only to calendar folders,

and FullDetails (user has access to full details of items).

• UserIDDisplayName: Display name of the user.

• UserIDprimarySMTPAddress: The primary SMTP address of the user.

• userIDSID: SID of the user.

• UserIdstandardUser: Indicates the standard user, if default (the default delegate user, used to

define default delegate permissions and Anonymous (the anonymous delegate user, used to define

delegate permissions for unauthenticated users).

TotalCount Total number of items contained in the folder.

UnreadCount Number of unread items in the folder.

Field Description

ChildFolderCount The number of child folders this folder has

displayName The display name of the folder

folderClass Folder class

UID ID of the folder

Field Description

Page 136: cf10betafeatures

133COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Filter parameters for cfexchangefolder action = "findSubFolders"

For the action findSubFolders, the result is a query that contains details of the subfolders. The values are same as

that of cfexchangefolder action = "getInfo".

Example

The following code shows how you can perform the actions getExtendedInfo, findSubFolders, getInfo, copy,

delete, modify, move, and create.

<cfexchangeconnection action="open" username="folder" password="Password" server="IP_Address" serverversion="2010" connection="conn1"> <cfexchangefolder action="getextendedinfo" connection="conn1" name="result" folderpath="Drafts"> <cfexchangefolder action="getextendedinfo" connection="conn1" name="result3" folderpath="Inbox"> <!--- Checking if the folder is already present.. If it is present then delete it ---> <cfexchangefolder action="findsubfolders" connection="conn1" name="final" uid="#result3.uid#">

<cfexchangefilter name="displayname" value="folder1"> </cfexchangefolder> <cfexchangefolder action="findsubfolders" connection="conn1" name="final1" uid="#result.uid#">

<cfexchangefilter name="displayname" value="folder1"> </cfexchangefolder> <cfif (#final.displayname# EQ "folder1")>

<cfexchangefolder action="delete" connection="conn1" uid="#final.uid#" deletetype="harddelete">

<cfscript> sleep(1000);

</cfscript> <cfelseif (#final1.displayname# EQ "folder1")>

<cfexchangefolder action="delete" connection="conn1" uid="#final1.uid#" deletetype="harddelete">

<cfscript> sleep(1000);

</cfscript> </cfif> <cfset newfolder = structnew()> <cfset newfolder.displayname = "folder1"> <cfset newfolder.folderclass = "IPF.Note"> <cfexchangefolder action="create" connection="conn1" parentfolderid="#result.uid#" folder="#newfolder#" result="result1"> </cfexchangefolder> <!--- Source folder ---> <cfexchangefolder action="findsubfolders" connection="conn1" name="result2" uid="#result.uid#">

<cfexchangefilter name="displayname" value="folder1"> </cfexchangefolder> <!---modifying the folder--->

ParentFolderId The Id of the current folder's parent folder

TotalCount Total number of items contained in the folder

UnreadCount The number of unread items in the folder

Field Description

Page 137: cf10betafeatures

134COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

<cfset modfolder = structnew()> <cfset modfolder.displayname = "exchange"> <cfset modfolder.folderclass = "IPF.Calendar"> <cfexchangefolder action="modify" connection="conn1" uid="#result2.uid#" folder="#modfolder#"> </cfexchangefolder> <cfexchangefolder action="findsubfolders" connection="conn1" name="result5" uid="#result.uid#">

<cfexchangefilter name="displayname" value="exchange"> </cfexchangefolder> <cfdump var="#result5#"> <!--- Destination folder ---> <cfexchangefolder action="getInfo" connection="conn1" name="result3" folderpath="Inbox"> <cfexchangefolder action="copy" connection="conn1" result="copiedfolderid" sourcefolderid="#result2.uid#" destinationfolderid="#result3.uid#"> <cfexchangefolder action="findsubfolders" connection="conn1" name="result2" uid="#result.uid#">

<cfexchangefilter name="displayname" value="exchange"> </cfexchangefolder> <cfdump var="#result2#"> <cfexchangefolder action="findsubfolders" connection="conn1" name="result4" uid="#result3.uid#">

<cfexchangefilter name="displayname" value="exchange"> </cfexchangefolder> <cfdump var="#result4#"> <!---Deleting the folder from source ---> <cfexchangefolder action="delete" connection="conn1" uid="#result2.uid#" deletetype="harddelete"> <cfexchangefolder action="move" connection="conn1" result="movedfolderid" sourcefolderid="#result4.uid#" destinationfolderid="#result.uid#"> <cfexchangefolder action="findsubfolders" connection="conn1" name="result6" uid="#result.uid#">

<cfexchangefilter name="displayname" value="exchange"> </cfexchangefolder> <cfdump var="#result6#"> <cfexchangefolder action="delete" connection="conn1" uid="#result6.uid#" deletetype="harddelete">

cfexchangeconversation

Description

Helps users organize and manage conversations from a Microsoft Exchange account.

The following actions are supported:

• Finds the required conversations in folder/subfolders based on filters.

• Status of the conversation; if read

• Copy, move, or delete conversation

History

ColdFusion 10: Added this tag.

Category

Communications tags

Page 138: cf10betafeatures

135COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Syntax

get <cfexchangeconversation action = "get" connection = "connection_ID" folderID = "Exchange folder UID"

name = "query name" </cfexchangeconversation> setReadState <cfexchangeconversation action = "setReadState" connection = "connection_ID" folderID = "Folder_UID"

UID = "conversation_UID" isRead = true|false

</cfexchangeconversation> copy <cfexchangeconversation action = "copy" connection = "connection_ID" FolderID = "conversation_folder_UID"

UID = "conversation_UID" destinationFolderID = "destination_folder_UID"

</cfexchangeconversation> move <cfexchangeconversation action = "move" connection = "connection_ID" folderID = "conversation_folder_UID"

UID = "conversation_UID" destinationFolderID = "destination_folder_UID"

</cfexchangeconversation> delete <cfexchangeconversation action = "delete" connection = "connection_ID" folderID = "conversation_folder_UID"

UID = "conversation_UID deleteType = hardelete|softdelete|movetodeleteditems

</cfexchangeconversation>

See also

cfexchangecalendar, cfexchangeconnection, cfexchangefilter, cfexchangemail, cfexchangetask,

Interacting with Microsoft Exchange Servers in the Developing ColdFusion Applications

Page 139: cf10betafeatures

136COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Attributes

Filter parameters for cfexchangeconversation action="get"

Attribute Action Req/Opt Default Description

action N/A Required The action to take.

Must be one of the following values:

• get

• setReadState

• copy

• move

• delete

connection All actions Required The name of the connection to the Exchange server,

as specified in the cfexchangeconnectiontag.

If you omit this attribute, create a temporary

connection by specifying

cfexchangeconnectiontag connection open

action attributes in the cfexchangecontacttag.

name get Required The name of the ColdFusion query variable that

contains the returned conversation information.

folderID All actions Required A case-sensitive Exchange UID value that uniquely

identifies the folder.

UID All Required If yes, marks the conversation as read.

isRead setReadState Required Indicates the status of the conversation, if read or not.

destinationFolderID

move copy

Required A case-sensitive Exchange UID value that uniquely

identifies the destination folder.

deleteType delete Required moveToDeletedItems

• hardDelete: Removes a folder permanently from

the store.

• softDelete: Removes a folder to the dumpster, if

dumpster is enabled.

• moveToDeletedItems: Moves a folder to the

deleted items folder.

Parameter Description

maxRows Specify the maximum number of conversations that have to be returned. Default is 100, and if -1 is

specified, all conversations are returned.

catagories A comma-separated list of categories stamped on messages in the conversation (only in the current folder).

flagStaus The flag status for the conversation, calculated by aggregating individual message flag status in the current

folder. It can have the following values:

• NotFlagged

• Flagged

• Complete

Page 140: cf10betafeatures

137COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

GlobalCategories

A comma-separated list that summarizes the categories stamped on messages in the conversation, across

all folders in the mailbox.

GlobalFlagStatus

The flag status for the conversation, calculated by aggregating individual message flag status across all

folders in the mailbox.

It can have the following values.

• NotFlagged

• Flagged

• Complete

GlobalHasAttachments

A value that indicates if at least one message in the conversation, across all folders in the mailbox, has an

attachment.

GlobalImportance

The importance of this conversation, calculated by aggregating individual message’s importance across all

folders in the mailbox. It can have following values:

• Low

• Normal

• High

GlobalItemClasses

A comma-separated list that summarizes the classes of the items in the conversation, across all folders in

the mailbox.

GlobalItemIds A comma-separated list of IDs of the messages in the conversation, across all folders in the mailbox.

GlobalLastDeliveryTime

The delivery time of the message that was last received in the conversation across all folders in the mailbox.

GlobalMessageCount

The total number of messages in the conversation across all folders in the mailbox.

GlobalSize The size of the conversation, calculated by adding the sizes of all messages in the conversation across all

folders in the mailbox.

GlobalUniqueRecipients

A comma-separated list of recipients in the conversation across all folders in the mailbox.

GlobalUniqueSenders

A comma-separated list of senders in the conversation across all folders in the mailbox.

GlobalUniqueUnreadSenders

A comma-separated list of senders whose messages are currently unread in the conversation across all

folders in the mailbox.

GlobalUnreadCount

The total number of unread messages in the conversation across all folders in the mailbox.

HasAttachments Boolean value that indicates if at least one message in the conversation, in the current folder only, has an

attachment.

UId UID of the conversation.

Importance The importance of the conversation, calculated by aggregating individual message’s importance (only in

the current folder).

It can have following values:

• Low

• Normal

• High

Parameter Description

Page 141: cf10betafeatures

138COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Example

The following example shows how you can perform the actions get, setReadState, copy, move, and delete on

conversations:

<cfexchangeconnection action="open" username="conv" password="Password" server="IP_Address" serverversion="2010" connection="conn1"> <!--- Finding information about Inbox ---> <cfexchangefolder action="getextendedinfo" connection="conn1" name="result" folderpath="Inbox"> <cfexchangefolder action="getextendedinfo" connection="conn1" name="result1" folderpath="Drafts"> <cfexchangeconversation action="get" folderid="#result.uid#" name="conversations" connection="conn1">

<cfexchangefilter name="topic" value="testcfexchnage3"> <cfexchangefilter name="categories" value="Yellow Category">

</cfexchangeconversation> <cfdump var="#conversations#"> <cfset myArray = ArrayNew(1)> <cfloop query="conversations">

<cfset temp = ArrayAppend(myArray, "#UID#")> </cfloop> <!--- Copy the conversation to Drafts ---> <cfexchangeconversation action="copy" UID="#myArray[1]#" folderid="#result.uid#" destinationfolderid="#result1.uid#" connection="conn1"> <!--- Getting the detail about the conversation ---> <cfexchangeconversation action="get" folderid="#result1.uid#" name="conversations1" connection="conn1">

<cfexchangefilter name="topic" value="testcfexchnage3"> <cfexchangefilter name="categories" value="Yellow Category">

</cfexchangeconversation>

ItemClasses A comma-separated list of classes of the items in the conversation (only in the current folder).

ItemIds A comma-separated list of IDs of the messages in the conversation (only in the current folder). It is an array

of ItemId objects.

LastDeliveryTime

The delivery time of the message that was last received in the conversation (in the current folder only).

MessageCount The total number of messages in the conversation (in the current folder only).

size The size of the conversation, calculated by adding the sizes of all messages in the conversation (in the

current folder only).

topic The topic of the conversation.

uniqueRecipients

A comma-separated list of message recipients in the conversation (in the current folder only)

uniqueSenders A comma-separated list of senders in the conversation (in the current folder only).

uniqueUnreadSenders

A comma-separated list of senders whose messages are currently unread in the conversation (in the current

folder only).

unreadCount Total number of unread messages in the conversation (in the current folder only).

Parameter Description

Page 142: cf10betafeatures

139COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

<cfdump var="#conversations1#"> <!--- Marking the item as unread ---> <cfexchangeconversation action="setReadState" UID="#conversations1.uid#" folderid="#result1.uid#" isread="false" connection="conn1"> <!--- Deleting the conversations ---> <cfexchangeconversation action="delete" UID="#conversations1.uid#" folderid="#result1.uid#" deletetype="harddelete" connection="conn1"> <!--- Moving the conversations---> <cfexchangeconversation action="move" UID="#myArray[1]#" folderid="#result.uid#" destinationfolderid="#result1.uid#" connection="conn1"> <!--- Getting the detail about the conversation ---> <cfexchangeconversation action="get" folderid="#result1.uid#" name="conversations2" connection="conn1">

<cfexchangefilter name="topic" value="testcfexchnage3"> <cfexchangefilter name="categories" value="Yellow Category">

</cfexchangeconversation> <cfdump var="#conversations2#"> <!---Moving the conversation back to the initial location---> <cfexchangeconversation action="move" UID="#conversations2.uid#" folderid="#result1.uid#" destinationfolderid="#result.uid#" connection="conn1">

Lazy loading across client and server

This release supports need-based loading of related entities for applications that use ColdFusion ORM in the back end

and Flex as the front end. Your application can now fetch the main entity and not return the related entities. Only when

the client application tries to access the related entities, they are loaded.

Example

Maria uses ColdFusion ORM and is building a Flex application. She wants to list all employees and projects that each

employee in her company is part of. Using lazy loading, users in her company can fetch the employee information first

and the number of projects the employee has worked on. And later when the users click on a particular project, the

feature lets them load the project information of a particular employee rather than having all the data loaded initially

when the application is loaded (which was the behavior in ColdFusion 9).

Setting up lazy loading

For lazy loading enhancements to take effect, you need to perform various configurations on both client-side and

server-side.

Server-side configuration

1 In the services-config.xml, go to the section that specifies the channel-definition (for the channel that you use) and

search the following:

*<serialize-array-to-arraycollection>false*

2 Change the value to true.

3 (Optional) If you want to change the name of the method that is invoked while related entities are loaded, modify

the name of the method from loadProxy.

*<proxy-load-method>loadProxy</proxy-load-method>*

4 Add the loadProxy method to your service CFC as shown in the following sample code. The service CFC should be

in the same directory as your ORM components:

service.cfc

Page 143: cf10betafeatures

140COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

component { remote function loadProxy(any proxyKey, any fullyqualifiedname)

{ //writeDump(var="#proxyKey#,,,#fullyqualifiedname#",output="console" ); writedump(var="#proxykey#",output="console"); if(fullyqualifiedname contains "cproducts"){ return EntityLoadByPK("cproducts",proxykey ); }else{ return EntityLoadByPK("ccategories",proxyKey ); } }

}

The loadProxy method gets proxyKey (primary key of the entity instance) and fullyqualifiedname of the entity

as arguments.

The fullyqualifiedname sent by dphibernate is checked and the required object (in this case cproducts or

ccategories) is returned.

5 Set remotingFetch to lazy.

lazy is the new value added to remtoingFetch (in addition to true and false) in the tag cfproprety:

• true: The value of the property is sent to Flash by way of Flash Remoting.

• false: Null is sent to Flash.

• lazy: Proxy object for the related entities is sent with only the primary key value.

Only when any property on the proxy object is accessed, another remoting call reaches the load method defined

on the CFC to which the primary key is passed. The load method returns the object with all the values populated.

Sample configuration

employee.cfc

<cfcomponent persistent="true" table="employees"> <cfproperty name="employeeID" fieldtype="id" generator="native"/> <cfproperty name="personalObj" fieldtype="one-to-one" cfc="cpersonal" cascade="all" remotingfetch="lazy"/> <cfproperty name="lastName"/> <cfproperty name="firstName"/>

</cfcomponent>

personal.cfc

<cfcomponent persistent="true" table="personal" > <cfproperty name="personalID" generator="foreign" params="{property=EmployeeObj}">

<cfproperty name="employeeObj" fieldtype="one-to-one" cfc="employee constrained="true"> <cfproperty name="SSN"> <cfproperty name="fatherName">

</cfcomponent>

service.cfc

Page 144: cf10betafeatures

141COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

component { remote function loadProxy(any proxyKey, any fullyqualifiedname)

{ //writeDump(var="#proxyKey#,,,#fullyqualifiedname#",output="console" ); writedump(var="#proxykey#",output="console"); if(fullyqualifiedname contains "cproducts"){ return EntityLoadByPK("cproducts",proxykey ); }else{ return EntityLoadByPK("ccategories",proxyKey ); } }

}

Client-side configurations

1 Add dpHibernate.swc to your Flex project. The file can be found in the following directory: /CFIDE/scripts/.

2 Use the HibernateRemoteObject instead of the default RemoteObject to make remoting calls.

3 Set HibernateManaged.defaultHibernateService to the Remote Object instance.

The dpHibernate.swc uses this remote object instance to make load calls to the server for lazy loading.

4 Ensure the following:

1 ActionScript class is mapped to the CFC using the attribute alias in the RemoteClass.

For example,

[RemoteClass(alias="orm.employees")]

2 ActionScript class extends from org.dphibernate.core.HibernateBean.

3 Managed metadata is added to the ActionScript class.

4 Perform Flash Remoting to fetch the entities.

The related entities are loaded only when specifically accessed on the client.

Example

Category.as

Page 145: cf10betafeatures

142COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

package model.beans { import mx.collections.ArrayCollection; import org.dphibernate.core.HibernateBean; [RemoteClass(alias="lazyloading.o2m.ccategories")] [Managed] public class Category extends org.dphibernate.core.HibernateBean { public function Category() { } public var categoryID:Number; public var categoryName:String; public var description:String; public var products:ArrayCollection; } } Product.as package model.beans { import mx.collections.ArrayCollection; import org.dphibernate.core.HibernateBean; [RemoteClass(alias="lazyloading.o2m.cproducts")] [Managed] public class Product extends org.dphibernate.core.HibernateBean { public function Product() { } public var productID:Number; public var productName:String; public var categoryID:Category; } } LazyLoading.MXML <?xml version="1.0" encoding="utf-8"?> <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/mx" xmlns:dp="org.dphibernate.rpc.*" applicationComplete="onAppComplete(event)" minWidth="955" minHeight="600" xmlns:dphibernate="http://www.dphibernate.org/2010/mxml"> <fx:Declarations> <!-- Place non-visual elements (e.g., services, value objects) here --> <dp:HibernateRemoteObject destination="ColdFusion" source="newmanual.apollounit.orm.lazyloading.o2m.service" endpoint="http://localhost:8500/flex2gateway/lazyloading" id="BasicService" result="BasicService_resultHandler(event)" fault="BasicService_faultHandler(event)"> </dp:HibernateRemoteObject>

Page 146: cf10betafeatures

143COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

</fx:Declarations> <fx:Script> <![CDATA[ import model.beans.*; import mx.binding.utils.BindingUtils; import mx.collections.ArrayCollection; import mx.rpc.AsyncToken; import mx.rpc.events.FaultEvent; import mx.rpc.events.ResultEvent; import org.dphibernate.rpc.HibernateManaged; [Bindable] public var categories:ArrayCollection; [Bindable] public var ProdsList:ArrayCollection; [Bindable] public var displaytext:String; public var category:Category; public var product:Product; public var employee:Employee; public var employee_self123:Employee_self; protected function BasicService_resultHandler(event:ResultEvent):void { if( event.token.operation == "getCategories"){ categories = event.result as ArrayCollection; var len:Number = categories.length; allintext.text = event.result.length; }else if(event.token.operation == "getProducts"){ ProdsList = event.result as ArrayCollection; } } protected function BasicService_faultHandler(event:FaultEvent):void { allintext.text="There is an error"; } protected function onAppComplete(event:Event):void { HibernateManaged.defaultHibernateService=BasicService; //var token:AsyncToken = BasicService.getCategories(); //token.operation="getCategories"; } protected function load_clickHandler(event:MouseEvent):void { var token:AsyncToken = BasicService.getCategories(); token.operation="getCategories";

Page 147: cf10betafeatures

144COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

} ]]> </fx:Script> <s:TextArea x="10" y="39" id="allintext" text="hello"/> <s:Button x="240" y="10" label="Load Categories" id="load" click="load_clickHandler(event)"/> <mx:DataGrid x="240" y="39" id="CategoryList" dataProvider="{categories}"> <mx:columns> <mx:DataGridColumn headerText="CategoryName" dataField="categoryName"/> <mx:DataGridColumn headerText="CategoryID" dataField="categoryID"/> </mx:columns> </mx:DataGrid> <mx:DataGrid x="239" y="198" id="ProductList" dataProvider="{Category(CategoryList.selectedItem).products}"> <mx:columns> <mx:DataGridColumn headerText="ID" dataField="productID"/> <mx:DataGridColumn headerText="Name" dataField="productName"/> </mx:columns> </mx:DataGrid> </s:Application>

ccategories.cfc

<cfcomponent persistent="true" table="categories"> <cfproperty name="categoryID" fieldtype="id" generator="native"/> <cfproperty name="categoryName"/> <cfproperty name="description"/> <cfproperty name="products" fieldtype="one-to-many" cfc="cproducts" cascade="all" fkcolumn="categoryid" lazy="true" remotingfetch="lazy"/>

</cfcomponent>

cproducts.cfc

<cfcomponent persistent="true" table="products"> <cfproperty name="productID" fieldtype="id" generator="native"/> <cfproperty name="productName"/> <cfproperty name="categoryID" fieldtype="many-to-one" cfc="ccategories" lazy="true" remotingfetch="lazy"/>

</cfcomponent>

Note on using debugger/network monitor in FlashBuilder

When you inspect the results returned by the server in debugging mode, debugger fetches the related entities (and

defies the purpose of lazy loading). This can also occur when you use network monitor.

However, this issue does not occur when you run the application.

Web service enhancements

ColdFusion 10 has Axis 2 web service framework integrated. This enables your web services to use WSDL 2

specifications, SOAP 1.2 protocol, and document literal wrapped style. Also the enhancements resolve many

interoperability issues that you might encounter while working with web services in ColdFusion 9.

The following table shows how the integration helps:

Page 148: cf10betafeatures

145COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Specifying the Axis settings

You can specify the Axis version at server level, application level, or component level.

Server level changes

Modify the following section in the neo-xmlrpc.xml available in the directory CFusion\lib.

<struct type='coldfusion.server.ConfigMap'> <var name='version'>

<string>2</string></var> </struct>

Consumption features Publishing features

Supports WSDL 1.1 and WSDL 2.0 specifications. Supports WSDL 1.1 and WSDL 2.0 specifications.

• To access WSDL2, use the URL as follows:

http://localhost:8500/<path of cfc>?wsdl2.

• To access WSDL1, use the URL as follows:

http://localhost:8500/<path of cfc>?wsdl.

Axis 2 support in ColdFusion lets you consume web services that

publish WSDL in the following styles:

• RPC encoded

• Document Literal

• Document Literal Wrapped

To use Axis 2 for consumption purpose, specify wsversion as 2

in cfinvoke tag. You can also specify the version at the

application level. For details, see “Application level changes” on

page 146. If you have specified wsversion as 1 in cfinvoke,

then Axis 1 is used. Axis 1 services published from ColdFusion are

consumed only by Axis 1. If no value is specified, then If you

publish WSDL in RPC encoded style, ColdFusion uses Axis 1 to

consume the web service whereas, if you publish in either

Document Literal or Document Literal Wrapped, the Axis 2 is used

for consumption.

In ColdFusion 9, only the following WSDL styles were supported:

• RPC Encoded

• Document Literal

The style attribute that you specified in the cfcomponent tag

decided the style used for publishing the WSDL.In ColdFusion

10, integration with Axis 2 lets you publish the WSDL in the new

style Document Literal Wrapped. For publishing WSDL in this

style, specify the style attribute as wrapped in

cfcomponent.Note that you can specify style attribute as

wrapped only if the wsversion specified is 2.

Supports SOAP 1.1 and SOAP 1.2 protocols.

• While accessing the web service using cfinvoke, specify the

serverport as shown in the following code:

<cfset str = structNew()> <cfset str.serviceport = "cfsuite.webservices.axis2.wscf.basic.cfcHttpSoap12Endpoint"> <cfscript> //invoke method ws = createObject("webservice", "http://localhost:8500/cfsuite/webservices/axis2/wscf/basic.cfc?wsdl",str); </cfscript> <cfinvoke webservice="#ws#" method="Echo" returnvariable="foo"> <cfoutput>#foo#</cfoutput>

Here, you have specified SOAP 1.2 endpoint and therefore, SOAP

1.2 protocol is used to send SOAP messages.

Supports SOAP 1.1 and SOAP 1.2.

ColdFusion 9 supports only SOAP 1.1 endpoint. Integration with

Axis 2 in ColdFusion 10 provides support for SOAP 1.1 and SOAP

1.2 protocols.

That is, if you publish a web service with WSVersion set to 2, the

endpoints W3C SOAP 1.2 and W3C SOAP 1.1 are supported

whereas if you specify 1 as the value, only W3C SOAP 1.1 is

supported.

For details on specifying WSVersion, see the configuration

section.

For details on SOAP, see www.w3.org/TR/SOAP/.

Page 149: cf10betafeatures

146COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Application level changes

You can specify the Axis version that you want to use at the application level as follows:

• For publication:<cfset this.wssettings.version.publish="2">.

Note: The version you specify overrides the version specified at server level.

• For consumption: <cfset this.wssettings.version.consume="2">

Setting the attribute style at application level

Set as follows: <cfset this.wssettings.style="rpc/document/wrapped">

Handing ColdFusion's complex datatypes in Web services

Set the includeCFTypesInWSDL attribute at application level as follows:

<cfset this.wssettings.includeCFTypesInWSDL="true">

The default value is true.

If set to true, schemas are generated for complex datatypes and included in the WSDL. At the client-side, stubs are

generated for complex datatypes. User can pass it as the argument.

The following scenarios explain the need of setting the attribute includeCFTypesInWSDL:

<cffunction name="echoObject" access="remote" returnType="any"> <cfargument name="argObj" type="any"> <cfdump var="#argObj#" output="console"> <cfreturn argObj>

</cffunction>

Axis 2 generates WSDL by introspecting CFC’s method signatures. In this function, both argument type and return

type are any. Therefore, the schema generated with WSDL will not contain the schemas for ColdFusion’s complex

datatypes such as struct, query, or xml. If these schemas are not present in the WSDL, then at the client side, there will

not be stub classes for the complex types, making the function useless.

Similarly, in the following function, both argument type and return type are struct. In this case also, the WSDL will

contain schema only for the struct. If you want to pass Document inside struct or Query inside struct, they are not

available as schemas in the WSDL.

<cffunction name="echoComplexStruct" access="remote" returnType="struct"> <cfargument name="argStr" type="struct"> <cfdump var="#argStr#" output="console"> <cfreturn argStr>

</cffunction>

Component level changes

• New attribute wsversion has been added to cfcomponent.

If you specify 2, CFC is deployed using Axis 2 engine. The value you specify overrides the value you specify at

application or server level.

• A new value wrapped can be specified for the attribute style. If you are setting wsversion as 2, the default value

is wrapped and if it is 1, then the default value is rpc.

Note: If you have set style at the application level, in both the cases, instead of the default values, the values at the

application level are used.

The syntax is as follows:

Page 150: cf10betafeatures

147COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

<cfcomponent wsversion = 1|2> style = "rpc|document|wrapped" .... <cffunction ...>

... </cffunction> <cffunction ...> ... </cffunction> </cfcomponent>

Modifications to createObject and cfobject

• New property wsVersion has been added to createObject to specify the Axis version.

• New attribute wsVersion has been added to the tag cfobject to specify the Axis version.

Variations from ColdFusion 9

If the same display name is used in multiple CFCs, in ColdFusion 9, both the CFCs are published. But in ColdFusion

10, if wsVersion is set to 2, in the case of multiple CFCs with same display name, only the first CFC is published.

Attempt to access the second CFC results in an error.

Web services are not automatically registered when you access the service using cfinvoke, cfobject, or

createObject. You have to register the Web service in the ColdFusion Administrator (Data & Services > Web

Services).

Limitations

Note: The following limitations will be addressed in the future releases of ColdFusion 10.

• Unlike in Axis 1, Axis 2 cannot support two CFCs having the same display name.

• The following attributes in the tag cfinvoke are not supported in Axis 2: Serviceaddress, portTypeName.

• If you are publishing JWS files, only Axis 1 is supported.

RESTful Web Services in ColdFusion

ColdFusion 10 lets you create and publish REST (Representational State Transfer) services that can be consumed by

clients over HTTP/HTTPS request.

What is REST

The following URL takes you to the Java Tutorial that provides conceptual information on REST:

http://download.oracle.com/javaee/6/tutorial/doc/gijqy.html

REST and ColdFusion

Note: This section is incomplete. A section that explains how to get started with REST is in the making.

Page 151: cf10betafeatures

148COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

You can create REST services by defining certain attributes in the tags cfcomponent, cffuntion, and cfargument

and publish as REST resources.

• Follows HTTP request-response model:Beyond having HTTP as a medium, the service lets you follow all HTTP

norms. The components published as REST services can be consumed over HTTP/HTTPS request.

The REST services are identified with URI (Uniform Resource Identifier) and can be accessed from a web page as

well as by specifying the URI in the browser’s address bar.

• Supports all HTTP methods : The REST enabled CFCs support the following HTTP methods: GET, POST, PUT,

DELETE, HEAD, and OPTIONS.

• Implicit handling of serialization/deserialization: ColdFusion natively supports JSON and XML

serialization/deserialization. So client applications can consume REST services by issuing HTTP/HTTPS request.

The response can either be serialized to XML or JSON format.

• Publish web service as both REST service and WSDL service: You can create and publish the same ColdFusion

component as a REST service and WSDL service.

Creating the REST web service

• You can create and publish a ColdFusion component or any functions in a component as REST resource.

• To create a CFC as REST web service, specify either of the following in the tag cfcomponent: restPath or rest.

• In cffunction, set the attribute access to remote for the functions that you have to expose as REST resource.

For details, see “Modifications to tags” on page 150.

Example

<cfcomponent rest="true" restpath="restService"> <cffunction name="sayHello" access="remote" returntype="String" httpmethod="GET">

<cfset rest = "Hello World"> <cfreturn rest>

</cffunction> </cfcomponent>

Registering an application with REST service

After you create the CFC you want to REST-enable, specify the folder for registering as web service either using the

function restInitAplication or in the ColdFusion Administrator.

Note: Nested REST applications cannot be registered.

Using ColdFusion Administrator (Data & Services > REST Services)

When you specify a folder, all CFCs in that folder or subfolders for which you have specified rest or restPath are

registered.

1 Browse and select the application path or root folder where ColdFusion would search for CFCs.

2 (Optional) In the Service Mapping section, specify virtual mapping in place of application name.

If the folder has an Application.cfc and an application name, then the service is identified with the application

name. You can override this by specifying the service mapping. In this case, the service is identified with the service

mapping that is provided. If there is no Applicaiton.cfc in the folder, then it is mandatory to specify the Service

mapping.

Page 152: cf10betafeatures

149COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

3 (Optional) Specify an application as default REST service. Only one application can be set as default for a server

instance. You can change the default application at any time. Check Set the default application and then click Add

Service. To remove the service as default, uncheck it.

4 After you specify the details, click Add Service to register.

The Active ColdFusion REST Services section specifies the details of all registered web services.

After you register, all CFCs are published as RESTful services. On subsequent startups, the registered services

automatically get published.

Note: Refresh the application whenever there is a change in REST-related component in the application.

Using the function restInitApplication

restInitApplication

Description

Registers the directory path with the service mapping provided. If no service mapping is provided, the application

name is used. If the rest application is already registered, it is refreshed.

Returns

Nothing

Syntax

RestInitApplication( "dirPath" [, "serviceMapping"] )

Properties

Example

<cfset RestInitApplication("C:/ColdFusion10/cfusion/wwwroot/restexample/", "restexample")>

restDeleteApplication

Description

Unregisters the directory path if it is already registered.

Returns

Nothing

Syntax

RestDeleteApplication("dirPath")

Parameter Description

dirPath Required. Path to the directory to be registered.

serviceMapping

Optional. Alternate string to be used for application name while calling the REST service.

Page 153: cf10betafeatures

150COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Properties

Example

<cfset RestDeleteApplication("C:/ColdFusionZeus/cfusion/wwwroot/restexample/")>

Accessing the web service

• Use the tag cfhttp to access the web service as shown in the following example:

<cfhttp url="http://localhost:8500/rest/RestTest/restService" method="get" port="8500" result="res">

</cfhttp>

• Access using the browser by providing the URL: http://localhost:8500/rest/RestTest/restService

Interpreting the URL

The URL provided in the example can be interpreted as follows:

Providing accept header

The accept header can be provided in the REST URL. The following examples illustrate this:

• For the REST URL http://localhost:8500/rest/RestTest/restService.json, the accept parameter

would be set to application\json.

• For the REST URL http://localhost:8500/rest/RestTest/restService.xml, the accept parameter would

be set to application\xml.

Modifications to tags

cfcomponent

The following new attributes have been added:

Parameter Description

dirPath Required. Path to the directory to be unregistered. If the path is not valid, it results in an error.

URL component Description

http://localhost:8500 Base URL which includes the IP address and port of the ColdFusion server.

If you deploy ColdFusion as a JEE application, the URL will contain a context root, for example,

http://localhost:8500/cfusion.

rest Implies that the request sent is a REST request.

This default value can be renamed by revising the context path in web.xml available in the following

location:

cfusion/wwroot/WEB-INF.

restTest Application name or service mapping that you have used while registering the service in ColdFusion

Administrator. If you do not specify a service mapping in the ColdFusion Administrator, then the

application name is taken from Application.cfc.

restService Rest path you defined in the service. That is, the value of the attribute restPath in the tag

cfcomponent.

Page 154: cf10betafeatures

152COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Attribute Req/Opt Default Description

rest Optional true if

RestPath is

specified

If true, the CFC is REST-enabled.

restPath Optional You can access the REST resource either by providing a REST path or CFC path. So

specify if you want to use a path other than the CFC path. If rest="true" and you do

not specify this attribute, path to the CFC is used.

Path to the CFC should be from the directory registered as a REST service. Also, you

should include the CFC name in the path.

For example, if you have a folder college that is registered as RestTest, and you want

to publish student.cfc which is in a sub-folder department (in the folder college), then

the URL used to access student.cfc is as follows:

http://localhost:8500/rest/RestTest/department/student.

The restPath in this case is department/student.

The path is case-sensitive. Also, it is preferable to avoid special character in the path.

At CFC level, specify the path as follows:

restPath="restService" or restPath="test/restService"

You can specify templates as value of restPath. For example,

restPath="{name}". This means, all URLs in the format <Base URL>/rest/<service_mapping>/<any string without slash> matches the

restPath. For example, http://localhost:8500/rest/service1/abc.

The value in place of template can be accessed using the restargsource value

path. For details, see the attribute details of cfargument.

The attribute can have complex expressions as values. For example,

restpath="customers/{firstname}-{lastname}". This matches URLs such

as "/customers/paul-bensen" but not "/customers/paulbensen".

Also restPath can include regular expressions such as

restpath="/customers/{id : \d+}". Here, id is an integer that can match

"/customers/123111" but not "/customers/asd" or

"/customers/123/122".

If you have two methods with different path attribute values and if the paths are

ambiguous, then there are precedence rules for finding the match. For example,

restpath="/customers/{id : .+}". This expression matches any stream of

characters after /customer. It matches "/customers/123", "/customers/asd",

and "/customers/123/12/asdfa", but not "/customers".

You can also have expressions such as restPath="/customers/{id : .+}/address", the URL "/customers/123/asd/address" is matched with

both URLs. In such scenarios, the precedence rules are used to find the match.

Page 155: cf10betafeatures

153COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

httpMethod optional The HTTP method to use, must be one of the following:

• GET: Requests information from the server. Any data that the server requires to

identify the requested information must be in the URL or in cfhttpparam type="URL" tag.

• POST: Sends information to the server for processing. Requires one or more

cfhttpparam tags. Often used for submitting form-like data.

• PUT: Requests the server to store the message body at the specified URL. Use this

method to send files to the server.

• DELETE: Requests the server to delete the specified URL.

• HEAD: Identical to the GET method, but the server does not send a message body in

the response. Use this method for testing hypertext links for validity and

accessibility, determining the type or modification time of a document, or

determining the type of server. If you have not specified HEAD, by default, GET

method is called. However, message body is not sent in the response.

• OPTIONS: A request for information about the communication options available for

the server or the specified URL. This method enables the ColdFusion application to

determine the options and requirements associated with a URL, or the capabilities

of a server, without requesting any additional activity by the server. If you have not

specified OPTIONS, then ColdFusion sends a response.

Based on the request method, the corresponding function is invoked. For example, if

a GET request is sent to the server, then a function with httpMethod as GET is invoked.

If this value is not specified at the function level, then the value you define here is

used. So all functions for which httpMethod is not specified are assigned this value.

produces optional */* Comma-separated list of acceptable MIME types, for example

produces="text/plain,text/html".

Searches for the Accept header in the HTTP request or extension in the URL (valid

extensions are .xml and .json); if the value is, for example HTML, JSON, or XML,

ColdFusion finds the appropriate method that can handle the request and invoke the

method.

Used to specify the MIME media types or representations a CFC can produce and send

back to the client.

If specified at the component level (and not at the function level) , all the functions in

a CFC can produce the specified MIME types by default.

If no methods in a CFC can produce the MIME type in a client request, the following

error occurs: 406 Not Acceptable.

If no value is specified, */* is taken by default, which means, all MIME types are

produced.

Attribute Req/Opt Default Description

Page 156: cf10betafeatures

154COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

cffunction

The following new attributes have been added:

consumes optional */* Comma-separated list of acceptable MIME types, for example

consumes="text/plain,text/html".

Searches for the Content-Type header in the HTTP request; if the value is, for example

HTML or XML, ColdFusion finds the appropriate method which can handle the request

and invoke the method.

Used to specify which MIME media types of representation a resource can accept or

consume, from the client.

If this attribute is used at the component level (and not at the function level), all the

response methods accept the specified MIME types by default.

If no function in a CFC can consume the MIME type in a client request, the following

error occurs: 415 Unsupported Media Type.

If no value is specified, */* is taken by default, which means, all MIME types are

consumed.

Attribute Req/Opt Default Description

Page 157: cf10betafeatures

155COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Attribute Req/Opt Default Description

restPath Optional Specify to use a sub- resource path for the CFC.

The path is case-sensitive. Also, it is preferable to avoid special characters when you

specify the path. You can include regular expressions in the path.

For details of the expressions that you can specify, see the attribute restPath in

cfcomponent.

httpMethod The HTTP method to use, must be one of the following:

• GET: Requests information from the server. Any data that the server requires to

identify the requested information must be in the URL or in cfhttp type="URL"tag.

• POST: Sends information to the server for processing. Requires one or more

cfhttpparam tags. Often used for submitting form-like data.

• PUT: Requests the server to store the message body at the specified URL. Use this

method to send files to the server.

• DELETE: Requests the server to delete the specified URL.

• HEAD: Identical to the GET method, but the server does not send a message body

in the response. Use this method for testing hypertext links for validity and

accessibility, determining the type or modification time of a document, or

determining the type of server. If you have not specified HEAD, by default, GET

method is called. However, message body is not sent in the response.

• OPTIONS: A request for information about the communication options available

for the server or the specified URL. This method enables the ColdFusion

application to determine the options and requirements associated with a URL, or

the capabilities of a server, without requesting any additional activity by the

server. If you have not specified OPTIONS, then ColdFusion sends a response.

Overrides the value that you specify at component level.

produces Optional */* Comma-separated list of acceptable MIME types.

Used to specify the MIME media type of representation a resource can produce, for

example, produces="text/plain,text/html"

If a resource can produce more than one MIME media type, the function chosen

corresponds to the most acceptable media type as declared by the client.

If no value is specified, */* is taken by default, which means, all MIME types are

consumed.

Overrides the value that you specify at the component level.

consumes Optional */* Comma-separated list of acceptable MIME types, for example

consumes="text/plain,text/html".

Used to specify which MIME media types of representation a resource can accept, or

consume, from the client.

This attribute overrides the same attribute at the component level.

If no value is specified, */* is taken by default, which means, all MIME types are

consumed.

Adobe recommends that you avoid conflict scenarios while specifying the attributes

produces and consumes. For example, avoid situations such as the following: In

function 1, you specify produces as text/xml and consumes as text/* and in

function 2, produces as text/* and consumes as text/xml. Here, both the

functions are valid for the request with accept = text/xml and consumes as

text/xml.

Page 158: cf10betafeatures

156COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

cfargument

The following new attributes have been added:

Attribute Req/Opt Default Description

restArgSource

Optional One of the following:

• path: Extracts parameters from the resource URL. URI path parameters are

extracted from the request URI, and the parameter names correspond to the URI

path template variable names specified in the restPath specified in

cffunction. The default value cannot be used with path param.

• query: Extracts parameters from URL query parameters. Mostly used with HTTP

GET method. When using GET method to send data, the parameters and values are

encoded into the URL. QueryParam is used to extract these values and assign

them to the appropriate variables.

• form: Extracts parameters from a form submission. It is used with HTTP POST

method.

• cookie: Extracts values form a cookie.

• header: Extracts parameters from HTTP header.

• matrix: Extracts parameters from matrix URI. For details, see

http://www.w3.org/DesignIssues/MatrixURIs.html.

If no value is specified, parameters are taken from the body of the request.

Using cfhttp, you can send arguments in either form or body. For form parameter,

the argument is consumed if you specify form as the value for restArgSource and

for body parameter, if you do not specify restArgSource.

While calling the service, if you pass the argument in body, in some scenarios, it is

accepted as form. For example, <cfhttpparam type="body" value="arg=somevalue">. This is because, when you pass the form name-value

pair through cfhttp or the body as "name=value", the body content is same, due

to which REST service is not able to detect what is passed.

In the service, if you expect body argument but while accessing the service through

cfhttp, no argument in the body is passed, you will still receive the body argument

as empty string.

If you use this attribute, but do not specify the type attribute, string is considered by

default as the type.

restArgName Optional The name that can be mapped to the argument name.

While calling functions, arguments are extracted from the incoming request. If

restArgName is provided, it is searched in the restArgSource scope of the

request to populate the argument. If not specified, argument name is searched.

If specified, then argument name has no impact. You can specify correct argument

name so that it corresponds to the appropriate parameter.

If the argument name passed to a REST service is not a valid Java identifier, for

example, the name has hyphen (say arg-name), then you can use this attribute to

map the argument name.

Page 159: cf10betafeatures

157COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Example 1

<cfcomponent restPath="restService"> <cffunction name="useHTTPHeader" access="remote" returnType="string" httpMethod="POST">

<cfargument name="userAgent" type="string" restargsource="header" restargname="User-Agent" required="false" default="CF">

<cfset res="Hello " & userAgent> <cfreturn res>

</cffunction> </cfcomponent>

In this example, the HTTP requests specify User-Agent in the header. Since this is not a valid Java identifier (hyphen

in the variable name), it is specified as a restArgName. The name attribute will contain the value assigned to User-

Agent which is specified as a restArgName. The name attribute is mapped to restArgName.

Example 2

<cfcomponent rest="true" restPath="/hello"> <cffunction name="sayHello" access="remote" returnType="String" httpMethod="GET" restPath="{name}">

<cfargument name="name" type="string" required="yes" restargsource="Path"> <cfset res="Hello " & name> <cfreturn res>

</cffunction>

</cfcomponent>

In this example, if a request comes to URL, for instance baseURL/hello/anyName, anyName is assigned as value to the

argument and you will get the response as Hello anyName.

Note that since a template is used for restPath, anything that follows baseURL/hello/ is accepted unless there is no

further slash. That is, only hello/123 or hello/abc are accepted and not hello/1/1.

Example 3

The following example shows the usage of restArgName.

<cffunction name="sayHelloRestArgname" access="remote" returntype="String" httpmethod="GET" produces="text/plain" restpath="/restArgName">

<cfargument name="field" type="string" restargsource="cookie" required="yes" encoded="false" restargname="firstname-lastname"/> <cfset res = "In rest argname " & field/> <cfreturn res>

</cffunction>

Example 4

In the following example, you specify the attributes produces and consumes. In the second function

BooleanExample, you have not specified restArgSource. So the value is taken from the body of the request whereas

in the first, it is taken from the form.

Test.cfc

Page 160: cf10betafeatures

158COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

<cfcomponent rest="true" restpath="/hello"> <cffunction name="NumericExample" access="remote" returntype="numeric" httpmethod="post"

produces="text/xml" consumes="application/x-www-form-urlencoded"> <cfargument name="AnyNumber" type="numeric" required="yes" restargsource="form"> <cfset res = AnyNumber> <cfreturn res>

</cffunction> <cffunction name="BooleanExample" access="remote" returntype="boolean" httpmethod="put"

produces="text/xml" consumes="text/xml"> <cfargument name="AnyBool" type="boolean" required="yes"> <cfset res = AnyBool> <cfreturn res>

</cffunction> </cfcomponent>

Test.cfm

<cfhttp url="http://localhost:8500/rest/RestTest/hello" method="post" result="res"> <cfhttpparam type="header" name="accept" value="text/xml" > <cfhttpparam type="header" name="content-type" value="application/x-www-form-urlencoded"

> <cfhttpparam type="formfield" name="AnyNumber" value=35>

</cfhttp> <cfdump var="#res#"> <cfhttp url="http://localhost:8500/rest/RestTest/hello123" method="put" result="res">

<cfhttpparam type="header" name="accept" value="text/xml" > <cfhttpparam type="header" name="content-type" value="text/xml" > <cfhttpparam type="body" value=false>

</cfhttp> <cfdump var="#res#">

HTTP Content-type negotiation

The content-type that is returned by a RESTful web service depends on the Accept HTTP header.

Client can set an Accept request header in the following order:

• Comma-separated list of preferred content types.

• (Followed by a semi-colon (;) A floating point number in the range 0 through 1 in the format q=[0-1]. The default

value is 1.

0 is the least value which indicates that the content type is not acceptable whereas 1 is the maximum value with the

highest priority.

If two types are provided the same priority, then the sequential priority is considered.

Examples

In the following example, client can use both XML and JSON format as no value is specified to indicate a priority in

the Accept header:

GET http://adobe.com/stuff Accept: application/xml, application/json

The request in the following example specifies a priority for returning the content-type:

GET http://adobe.com/stuff Accept: text/*;q=0.9, */;q=0.1, audio/mpeg, application/xml;q=0.5

Page 161: cf10betafeatures

159COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

The order of precedence for content type is as follows:

1 audio/mpeg (as no priority is specified)

2 text/* (0.9 is the highest value)

3 application/xml

4 */

In the following example, though you have specified same priority for both text/* and audio/mpeg, text/* gets

precedence because of the sequence.

GET http://adobe.com/stuff Accept: text/*;q=0.9, */;q=0.1, audio/mpeg=0.9, application/xml;q=0.5

Specifying subresources

Functions in a REST service can either be a resource function, subresource function, or subresource locator.

Resource function

The functions for which you have not specified the RestPath at function level but specified httpMethod.In this case,

the resource function is invoked when URL of the CFC is accessed.

Subresource function

The functions for which you have specified both resptPath and httpMethod.

Subresource functions are used to create subresources for the resource created by CFC. If the subresource has

httpMethod attribute in cffunction, the function can directly handle HTTP requests as shown in the following

example.

Example

Employee.cfc

<cfcomponent rest="true" restPath="/hello"> <cffunction name="sayHello" access="remote" returnType="String" httpMethod="GET" restPath="name"> ---------

</cffunction> </cfcomponent>

In this example, httpMethod and restPath are defined. The baseurl/hello/name is a subresource to the URL

baseurl/hello.

Subresource locator

If you have not specified the httpMethod attribute, but have specified restPath, you can dynamically resolve the

component that handles the request. Any returned object is treated as a resource class instance and used to either

handle the request or to further resolve the object that handles the request.

Example

In this example, StudentService.cfc and Student.cfc are the two REST resources. In StudentService.cfc the function

getStudent returns a component. In the function, the object of Student is created and the values name and age are

set. When the object is specified in the return type, the function defined in the object with the requested httpmethod

is invoked.

Page 162: cf10betafeatures

160COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

StudentService.cfc can be invoked directly as it has a restPath specified. Student.cfc can only be invoked through

StudentService.cfc because the function getStudent in StudentService.cfc is acting as the subresource locator and

returns Student.cfc.

StudentService.cfc:

<cfcomponent rest="true" restpath="/studentService"> <cffunction name="addStudent" access="remote" returntype="void" httpmethod="POST">

<cfargument name="name" type="string" required="yes" restargsource="Form"/> <cfargument name="age" type="numeric" required="yes" restargsource="Form"/>

<!--- Adding the student to data base. ---> </cffunction>

<cffunction name="getStudent" access="remote" returntype="student" restpath="{name}-{age}">

<cfargument name="name" type="string" required="yes" restargsource="Path"/> <cfargument name="age" type="string" required="yes" restargsource="Path"/>

<!--- Create a student object and return the object. This object will handle the request now. --->

<cfset var myobj = createObject("component", "student")> <cfset myobj.name = name> <cfset myobj.age = age> <cfreturn myobj>

</cffunction> </cfcomponent>

Student.cfc

<cfcomponent> <cfproperty name="name" type="string"/> <cfproperty name="age" type="numeric"/> <!--- Getting the student detail. ---> <cffunction name="getStudent" access="remote" returntype="String" httpmethod="GET"

produces="text/xml"> <!--- Retrieve the Student from the DB. ---> <!--- get student from db where name and age matches ---> <cfset st.name = "Thomas"> <cfset st.age = "25"> <cfset st.surname = "Paul"> <cfset str = "<student><name>" & st.name & "</name><age>" & st.age & "</age><surname>"

& st.surname & "</surname></student>"> <cfreturn str>

</cffunction> <!--- Updating the student detail. ---> <cffunction name="updateStudent" access="remote" returntype="void" httpmethod="PUT">

<!--- Retrieve the Student from the DB. ---> <!--- Update the student in DB. ---> <cfset st.name = name> <cfset st.age = age>

</cffunction> <!--- Deleting the student. ---> <cffunction name="deleteStudent" access="remote" returntype="String" httpmethod="DELETE">

<!--- Delete the Student from the DB. ---> <!---<cfset st = deleteStudentFromDB(name)>---> <cfreturn "Student deleted">

</cffunction> </cfcomponent>

Page 163: cf10betafeatures

161COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Student.cfm

<!--- adding the student ---> <cfhttp url="http://localhost:8500/rest/RestTest/studentService" method="post" result="res"> <cfhttpparam type="formfield" name="name" value="Thomas" > <cfhttpparam type="formfield" name="age" value="25" > </cfhttp> <cfoutput>Student Added</cfoutput> </br> </br> <!--- fetching the details ---> <cfhttp url="http://localhost:8500/rest/RestTest/studentService/Thomas-25" method="get" result="res"> </cfhttp> <cfoutput>#xmlformat(res.filecontent)#</cfoutput> </br> </br> <!--- updating the student details ---> <cfhttp url="http://localhost:8500/rest/RestTest/studentService/Thomas-25" method="put" result="res"> </cfhttp> <cfoutput>Updated the student</cfoutput> </br> </br> <!--- deleting the student ---> <cfhttp url="http://localhost:8500/rest/RestTest/studentService/Thomas-25" method="delete" result="res"> </cfhttp> <cfoutput>Student Deleted</cfoutput>

HTTP Responses

By default, ColdFusion provides default HTTP success and failure responses to the client as follows:

Success responses

Error responses

Default Response Description

200 OK Sent if the response has body.

204 No Content Sent if the response does not have body.

Default

Response

Description

404 Not found Request URL is not valid.

Page 164: cf10betafeatures

162COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Custom responses

In addition to the default responses available with ColdFusion, you can set custom responses.

For example, assume that you have to provide a success response 201 Created. Such a default response does not exist.

You can only have 200 OK or 204 No Content to send.

In such scenarios, you can create custom responses in either of the following ways:

Send custom success responses using restSetResponse

1 When you define the CFC as REST service, ensure that the returnType is set to void in the cffunction (the

function for which you want to send the custom response).

For example,

<cffunction name="create" httpMethod="POST" produces="application/xml" returnType="void"> <cffunction>

2 Create a struct for the custom response that you want to send in the cffunction as shown in the following

example:

<cfset response=structNew()> <cfset response.status=201> <cfset response.content="<customer id="&id&"><name>"&name&"</name></customer>"> <cfset response.headers=structNew()> <cfset response.headers.location="http://localhost:8500/rest/CustomerService/customers/123">

In this example, you have set 201 as the status of the response, content that you want to send. For example,

customer details and the location where you have created the resource for the POST request.

Note: If you do not specify the status in the custom response, 500 Internal server error is sent as the response

status.

3 Use the function restSetResponse as follows:

restSetResponse( response );

Send custom error response using cfthrow

Assume that you want to send a custom error response. For example, consider the following:

method.service.cfc

406 Not Acceptable

No function in the REST service can produce the MIME type requested by the client.

415

Unsupported

Media Type Error

A resource is unable to consume the MIME type of client request.

405 Method not

allowed

If the client invokes an HTTP method on a valid URI to which the request HTTP method is not bound.

This error does not appear if the client requests for HTTP HEAD and OPTIONS methods.

If a resource method that can service HEAD requests for that particular URI is not available, but there

exists a method that can handle GET, it is invoked and returns the response from that method without

the request body.

If there is no existing method that can handle OPTIONS, a meaningful automatically generated

response is sent along with the Allow header set.

Default

Response

Description

Page 165: cf10betafeatures

163COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

<cffunction name="getCustomer" httpMethod="GET" produces="application/xml" restPath="{id}" return="string">

<cfargument name="id" type="numeric" argtype="PathParam"> <!--- Getting the customer. ---><cffunction>

In this case, you have a customer database and you are doing a GET HTTP request on /customers/123.

But you find that the customer with the specified ID 123 is not available. So you want to send 404 Resource Not

Found response back to the client, which is not possible by default.

In this case, you can use cfthrow to send custom error response as follows:

<cfthrow type="RestError" errorcode="404">

New function restSetResponse

Description

Sets the custom responses.

Syntax

restSetResponse(response)

Parameters

Example

<cffunction name="create" httpMethod="POST" produces="application/xml"> <cfargument name="id" type="numeric" argtype="FormParam">

<cfargument name="name" type="String" argtype="FormParam"> <!--- create the customer. --->

<cfset response=structNew()> <cfset response.status=201> <cfset response.content="<customer id="&id&"><name>"&name&"</name></customer>"> <cfset response.headers=structNew()> <cfset response.headers.location="http://localhost:8500/rest/CustomerService/customers/123"> restSetResponse( response ); <cffunction>

Modifications to Application.cfc

The following enhancements have been made to Application.cfc for REST support:

Parameter Description

response A struct that contains the response details.

Page 166: cf10betafeatures

164COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Extending REST Web services

The following conditions apply when you extend the RESTful CFCs:

• You can define the REST attributes for functions in the base CFC. So all the CFCs that extend from the base CFC

inherits the REST attributes.

In the following example, CustomerResource.cfc extends BaseCustomerResource.cfc:

BaseCustomerResource.cfc

<cfcomponent> <cffunction name="SayPlainHello" access="remote" produces="text/plain"

returntype="string" httpmethod="POST"> <cfreturn "BaseCustomerResource Plain">

</cffunction> <cffunction name="SayXMLHello" access="remote" produces="text/xml,application/xml"

returntype="string" httpmethod="POST"> <cfreturn "BaseCustomerResource XML">

</cffunction> </cfcomponent>

BaseCustomerResource.cfc has all REST attributes applied to functions within the CFC. After you define

BaseCustomerResource.cfc, you can define CustomerService.cfc that extends BaseCustomerResource.cfc as

follows:

Customerservice.cfc

<cfcomponent rest="true" restpath="/customerservice" extends="BaseCustomerResource"> <cffunction name="SayPlainHello" access="remote" returntype="string">

<!--- Implement the method. ---> <cfreturn "CustomerResource Plain">

</cffunction> <cffunction name="SayXMLHello" access="remote" returntype="string">

<!--- Implement the method. ---> <cfreturn "CustomerResource XML">

</cffunction>

</cfcomponent>

BaseCustomerResource.cfm

Variable Description

this.restsettings.cfclocation

To publish the CFCs only in a particular location, provide comma-separated list of directories where the REST

CFCs are located. The directory paths can be absolute or relative.

If not set, all the CFCs from the application root are published.

this.restsettings.skipCFCWithError

When an error occurs, continue publishing, ignoring the CFC that has caused the exception.

If true, the CFC with error is ignored and the rest of the CFCs are published. By default it is false.

If set to false, in case of an error, the application itself is not published. But other registered applications are

published.

If an error occurs during application startup, the error is printed in console.

Each application has separate log files for logging the issues.

Page 167: cf10betafeatures

165COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

<cfhttp url="http://localhost:8500/rest/RestTest/customerservice" method="post" result="res"> <cfhttpparam type="header" name="accept" value="text/plain" > </cfhttp> <cfoutput>#res.filecontent#</cfoutput> </br> </br> <cfhttp url="http://localhost:8500/rest/RestTest/customerservice" method="post" result="res"> <cfhttpparam type="header" name="accept" value="application/xml" > </cfhttp> <cfoutput>#res.filecontent#</cfoutput> </br> </br>

Except the rest and restPath, no other REST attributes are required within CustomerService.cfc.

• When you inherit a RESTful CFC, you can choose to override the attributes used in the CFC that you extend.

For example, the following CFC extends the BaseCustomerResource.CFC, but the function SayPlainHello

overrides the function in Base CFC.

<cfcomponent rest="true" restPath="/customerservice" extends="BaseCustomerResource"> <cffunction name="SayPlainHello" access="remote" produces="text/plain"

returntype="string" httpmethod="PUT"> <cfargument name="username" type="string" argtype="pathparam"> <!--- Implement the method. --->

</cffunction> <cffunction name="SayXMLHello" access="remote" returntype="string">

<cfargument name="username" type="string"> <!--- Implement the method. --->

</cffuntion> </cfcomponent>

Note: Even if you override only one attribute in a function, you have to respecify all REST attributes

• You have to specify the REST attributes (rest/restPath) in the derived CFC to use it as a REST service. Just that

it is defined in the base CFC does not work.

REST services and data interchange formats

REST services in ColdFusion can be represented in XML or JSON formats for transmitting over the web. ColdFusion

takes care of the serialization/deserialization of the ColdFusion data types used in the services to XML or JSON

implicitly.

A function that is REST-enabled can take the following ColdFusion data types as arguments: query, struct, CFC type,

array, array of CFCs, XML, string, numeric, boolean, date, and binary (for XML).

ColdFusion serializes data to pre-defined formats of XML and JSON. Similarly, ColdFusion deserializes the body only

if the body is in the format defined by ColdFusion.

XML serialization for REST services

Serialization specifications

• The Accept header of the request has to be either text/xml or application/xml.

• There has to be a function in the service that can produce the required MIME types.

• The function has to return any of the ColdFusion supported data types.

Page 168: cf10betafeatures

166COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

• Cyclic arrays are not supported. You might see the serialized string published, but not with the expected output as

explained in the following example:

<cfset this.arr1 = arrayNew(1)> <cfset this.arr1[1] = "1"> <cfset this.arr1[2] = this.arr1> <cfset this.arr1[3] = "3">

When an array is assigned to a variable, in this case, <cfset this.arr1[2] = this.arr1>, you assign arr1 as

the item in the second index of arr1. ColdFusion implicitly creates a new array and copies the data from arr1 to

the newly created array. The newly created array is assigned to the second index of arr1. Therefore, both the

instances are different, and therefore cyclic dependency is impacted.

When you serialize, you get the following output:

<array id="1" size="3"> <item index="1" type="string">1</item> <item index="2" type="array"> <array id="2" size="1"> <item index="1" type="string">1</item> </array> </item> <item index="3" type="string">3</item> </array>

As you can observe, the inner array gets truncated after the first element.

Deserialization specifications

• The content of the request has to be in a pre-defined format specified by ColdFusion (see details in the section

Format definition).

• The content type of the request has to be either text/xml or application/xml.

• There has to be a function in the service that can consume the MIME type of the request.

• cfargument cannot have the attributes restArgSource and restArgName specified. That is, you can only send

data in the body of the request.

• cfargument type should be ColdFusion supported data type

• There can only be one argument that does not specify the restArgSource attribute. The whole body of the request

is deserialized to the argument type.

• Cyclic arrays are not supported.

Format definition

Query

• The root element of the XML has to be query.

• Use the attribute ID to handle circular dependency.

• The following are the valid attribute values: string, date, boolean, numeric, document, query, struct, array, and CFC

(if the value is a CFC instance).

Page 169: cf10betafeatures

167COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Example

In the following example, The root query element has two child elements columnnames and rows. columnnames is

the name of the columns in the query. rows can have data in multiple row elements. Here, the order of the column in

the row should match the column defined in the columnames. For each column in the row, a type attribute is

mandatory. The type attribute can have any of the ColdFusion data types as values.

<query id="1"> <columnnames> <column name="columnnameone"/> <column name="columnnametwo"/> </columnnames> <rows> <row> <column type="string">value one</column> <column type="string">value two</column> </row> <row> <column type="number">444.0</column> <column type="string">value four</column> </row> </rows> </query>

Struct

• The root element of the XML should be struct.

• Use the attribute ID to handle circular dependency.

• The struct can have multiple entry child elements. That is, a key-value pair in the Struct instance to be serialized.

entry element requires two mandatory attributes name (name of the entry) and type (the type of the value of the

entry). The type attribute can have one of the ColdFusion data types as values.

Example

<struct id="1"> <entry name="name" type="string">joe</entry> <entry name="age" type="string">30</entry> <entry name="address" type="string">101 some drive, pleasant town, 90010</entry> <entry name="eyecolor" type="string">blue</entry> <entry name="income" type="string">50000</entry> </struct>

CFC Component

• The root element of the XML has to be component.

• ID attribute is used to handle circular dependency.

• The name attribute has to provide the fully qualified name of the CFC from webroot.

• A component element can contain multiple property child elements.

• The property elements are the cfproperty values defined in cfcomponent.

• The name attribute of the property corresponds to the name of the cfproperty defined.

• type attribute specifies the type of the cfproperty.

• If, in the component, any property has a null value, then it does not appear in the serialized format. This applies

also for deserialization.

Page 170: cf10betafeatures

168COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Example

Student.cfc

<component id="1" name="testrest.student"> <property name="name" type="string">paul</property> <property name="age" type="number">444.0</property> <property name="dob" type="date">478377000000</property> </component>

In the following example, testrest.student means the CFC Student.cfc is placed in the testrest directory under

webroot.

Format for array and array of cfcomponent

• The root element has to be array.

• size attribute specifies the length of the array.

• The type attribute is not mandatory for the array element whereas for item element, it is mandatory.

• If the array is a cfcomponent array, then the type attribute of array element should have the fully qualified name

of the CFC.

• The array element contains multiple item child elements. Only the non-null items in the array are serialized.

• The item element has two attributes: index that specifies that index of the item in the array and type.

Example

The following example shows an array containing two struct objects:

<array id="1" size="2"> <item index="0" type="struct"> <struct id="2"> <entry name="name" type="string">joe</entry> <entry name="age" type="string">30</entry> <entry name="address" type="string">101 some drive, pleasant town, 90010</entry> <entry name="eyecolor" type="string">blue</entry> <entry name="income" type="string">50000</entry> </struct> </item> <item index="1" type="struct"> <struct id="3"> <entry name="name" type="string">paul</entry> <entry name="age" type="string">25</entry> <entry name="address" type="string">some other address</entry> <entry name="eyecolor" type="string">black</entry> <entry name="income" type="string">40000</entry> </struct> </item> </array>

Example: Array of CFC Serialization

The following example illustrates serializing array of CFC to XML and JSON formats.

1 Create an array of arrayCFCdefinition.cfc:

<cfcomponent> <cfproperty name="str" type="string"/>

</cfcomponent>

Page 171: cf10betafeatures

169COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

2 arrayCFC.cfc produces the required array as follows:

<cfcomponent restpath="arrayOfCFC"> <cffunction name="func1" access="remote" output="false"

returntype="arrayCFCdefinition[]" httpmethod="get" produces="text/xml">

<cfset arrCFC = arraynew(1)> <cfloop from=1 to=2 index="i">

<cfset obj = createObject("component", "arrayCFCdefinition")> <cfset obj.str = i> <cfset arrayAppend(arrCFC, obj)>

</cfloop> <cfreturn arrCFC>

</cffunction> <cffunction name="func2" access="remote" output="false"

returntype="arrayCFCdefinition[]" httpmethod="get" produces="text/json">

<cfset arrCFC = arraynew(1)> <cfloop from=1 to=2 index="i">

<cfset obj = createObject("component", "arrayCFCdefinition")> <cfset obj.str = i> <cfset arrayAppend(arrCFC, obj)>

</cfloop> <cfreturn arrCFC>

</cffunction> </cfcomponent>

3 Do the following to access the resource:

• For XML:

<cfhttp url="http://127.0.0.1:8500/rest/RestTest/arrayOfCFC" method="get" result="res1"> <cfhttpparam type="header" name="accept" value="text/xml">

</cfhttp>

• For JSON:

<cfhttp url="http://127.0.0.1:8500/rest/RestTest/arrayOfCFC" method="get" result="res2"> <cfhttpparam type="header" name="accept" value="text/json">

</cfhttp>

4 You receive the following serialized output as response:

• For XML:

Page 172: cf10betafeatures

170COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

<array id="1" size="2" type="cfsuite.restservices.restservices.new.ArrayCFCdefinition"> <item index="1" type="COMPONENT">

<component id="2" name="cfsuite.restservices.RESTServices.New.arrayCFCdefinition">

<property name="STR" type="NUMBER"> 1.0

</property> </component>

</item> <item index="2" type="COMPONENT">

<component id="3" name="cfsuite.restservices.RESTServices.New.arrayCFCdefinition">

<property name="STR" type="NUMBER"> 2.0

</property> </component>

</item> </array>

• For JSON:

[{"Str":1},{"Str":2}]

Example: Array of CFC: Deserialization

The following example illustrates deserializing array of CFC from XML format.

Note: Deserializing array of CFC is unsupported for JSON.

1 Create an array of arrayCFCdefinition.cfc:

<cfcomponent> <cfproperty name="str" type="string"/> <cffunction name="check" returntype="any">

<cfreturn this.str> </cffunction>

</cfcomponent>

2 arrayCFC.cfc produces the required array as follows:

<cfcomponent> <cffunction name="func3" access="remote" output="false" returntype="string" httpmethod="put" produces="text/xml" consumes="text/xml">

<cfargument name="arg" type="arrayCFCdefinition[]"/>

<cfif arg[2].check() eq "2"> <cfreturn "true">

<cfelse> <cfreturn "false">

</cfif> </cffunction>

</cfcomponent>

3 Do the following to access the resource for XML:

Page 173: cf10betafeatures

171COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

<cfhttp url="http://127.0.0.1:8500/rest/RestTest/arrayOfCFC" method="put" result="res3"> <cfhttpparam type="header" name="content-type" value="text/xml"> <cfhttpparam type="header" name="accept" value="text/xml"> <cfhttpparam type="body" value="<ARRAY ID=""1"" SIZE=""2""

TYPE=""cfsuite.restservices.restservices.new.ArrayCFCdefinition""><ITEM INDEX=""1"" TYPE=""COMPONENT""><COMPONENT ID=""2"" NAME=""cfsuite.restservices.restservices.new.ArrayCFCdefinition""><PROPERTY NAME=""STR"" TYPE=""NUMBER"">1.0</PROPERTY></COMPONENT></ITEM><ITEM INDEX=""2"" TYPE=""COMPONENT""><COMPONENT ID=""3"" NAME=""cfsuite.restservices.restservices.new.ArrayCFCdefinition""><PROPERTY NAME=""STR"" TYPE=""NUMBER"">2.0</PROPERTY></COMPONENT></ITEM></ARRAY>"> </cfhttp>

4 Refer to the function.

You are verifying the value of the property of arrayCFC definition.cfc for the second index of the array.

string, boolean, numeric, binary, and date

Specify the values directly in the body of the request.

Handling cyclic dependency

In ColdFusion, cyclic dependency is handled using the ID reference. All ColdFusion complex data types have unique

IDs when serialized. If the same object has to be serialized elsewhere, instead of serializing the object again, a reference

is made to the already serialized data using its ID.

In the following example, the main object is a struct. The struct contains an array of objects. The array has two elements

and both the elements are the same instance of a struct.

During serialization, the first element in the array is serialized as it is. The ID of the serialized struct is 2. Instead of

serializing the second element, as that object is already serialized, IDREF attribute is used to refer to the already

serialized struct instance.

<struct id="1"> <entry name="arrayinastruct" type="array"> <array id="2" size="2"> <item index="0" type="struct"> <struct id="3"> <entry name="name" type="string">joe</entry> <entry name="age" type="string">30</entry> <entry name="address" type="string">101 some drive, pleasant town, 90010</entry> <entry name="eyecolor" type="string">blue</entry> <entry name="income" type="string">50000</entry> </struct> </item> <item index="1" type="struct"> <struct idref="3"/> </item> </array> </entry> </struct>

Note: Object reference is taken care of by ColdFusion at the time of deserialization also.

Page 174: cf10betafeatures

172COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

JSON serialization and REST services

Serialization specifications

• The content type of the Accept header of the request has to be text/JSON, application/JSON, or text/plain.

• REST service should have a function that can handle the required MIME types.

• Function has to return any of the ColdFusion supported data types other than binary.

• Cyclic behavior is unsupported. But in the case of arrays, you might see the serialized string published, but not with

expected output as explained in the following example:

<cfset this.arr1 = arrayNew(1)> <cfset this.arr1[1] = "1"> <cfset this.arr1[2] = this.arr1> <cfset this.arr1[3] = "3">

When an array is assigned to a variable (in this case) <cfset this.arr1[2] = this.arr1>, you assign arr1 as

the item in the second index of arr1. ColdFusion implicitly creates a new array and copies the data from arr1 to

the newly created array. The newly created array is assigned to the second index of arr1. Therefore, both the

instances are different, and therefore cyclic dependency is impacted.

When you serialize, you get the following output:

[1,[1],3]

As you can observe, the inner array gets truncated after the first element.

Deserialization specifications

• The content of the request is in a predefined format specified by ColdFusion.

• The content type of the request is text/JSON, application/JSON, or text/plain.

• A function in the service consumes the MIME type of the request.

• cfargument does not have the attributes restargsource and restargname specified.

• cfargument type is ColdFusion supported data type other than binary or CFC definition.

• Only one argument has no restAargSource attribute specified. The whole body of the request is deserialized to

the argument type.

• Cyclic behavior is unsupported. But in the case of cyclic arrays, you might see the deserialized array published, but

not giving expected output.

Format definitions

Format for query

{'COLUMNS':['columnNameOne','columnNameTwo'],'Data':[['value one','value two'],['444.0','value four']]}

Format for struct

{'NAME':'joe','AGE':30,'ADDRESS':'101 Some Drive, Pleasant Town, 90010','EYECOLOR':'blue','INCOME':50000}

Format for component

{'NAME':'Paul','AGE':444.0,'DOB':'July, 27 2011 00:00:00'}

Note: Deserialization is unsupported for components.

Page 175: cf10betafeatures

173COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Format for array

[{'NAME':'joe','AGE':30,'ADDRESS':'101 Some Drive, Pleasant Town, 90010','EYECOLOR':'blue','INCOME':50000},{'NAME':'paul','AGE':25,'ADDRESS':'Some other address','EYECOLOR':'black','INCOME':40000}]

string, boolean, numeric, and date

Specify the values directly in the body of the request.

Media Player enhancements

The enhancements in this release support

• Play back capability for HTML 5 videos

• Fallback to HTML 5 video playback if Flash player is not installed

• Browser independent video controls

• Dynamic streaming of Flash videos

• Advanced skinning for media player

• Play list for Flash videos

• Embedding subtitles in SRT format using HTML track element

• Extending media player using plug-ins built using Open Source Media Framework (OSMF), for example to:

• Play videos in the YouTube server

• Use stage video support by showing advertisements within the videos in linear and non-linear mode

• Adding title to the video

Note: The mediaplayer's behavior is subject to the video capability of your device.

HTML 5 video playback capability

Apart from playing Flash videos, you can play videos in any format supported by HTML 5 compliant browsers.

Specify the source for HTML 5 videos in one of the following ways:

• If you feed only one video source, specify it as shown in the following example:

<cfmediaplayer name="Player" source="myvideo.mp4" width="200" height="200" />

• To feed multiple videos, specify the source as shown in the following example:

<cfmediaplayer name="Player" width=200 height=200> <source src="movie.ogg" type="video/ogg" /> <source src="movie.mp4" type="video/mp4" /> <source src="movie.webm" type="video/webm" /> </cfmediaplayer>

Note: The source tag represents the HTML 5 video source tag. When source tag is specified, you are recommended

to use the attribute type.

• Dynamically set the media player source using the JavaScript function ColdFusion.MediaPlayer.setSource.

For best results with the player, ensure that you specify doctype in your code as follows:

<!DOCTYPE html>

Page 176: cf10betafeatures

174COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Fallback plan for cfmediaplayer

Depending on the playback capability on the browser, cfmediaplayer offers alternate playback plan. cfmediaplayer

supports both Flash to HTML and HTML to Flash fall back.

The fall back feature applies in the following scenarios:

Specifying the playback type

You can set the preference of playback using the attribute type either as Flash or HTML as shown in the following

examples:

• <cfmediaplayer source="myvideo.mp4" type="html"/>

• <cfmediaplayer source="myvideo.mp4" type="flash"/>

Assume that the playback is on Internet Explorer 9 or Google Chrome. By default, the value is set to flash.

cfmediaplayer honors the value you specify only if the browser supports the playback preference. If for example, you

specify type as flash and the browser does not have Flash player installed, it falls back to HTML 5.

Specifying the video poster image, loop playback, and title using the tag cfmediaplayer

• posterImage: Specify this attribute to set a poster image for the video playback.

Takes URL or relative address as value.

• repeat: Set this attribute to true to continue playback from first to last frame after the media player reaches the

end of the video.

The default value is false.

• title: Lets you set title on the media player.

The title appears over the media player on upper-left corner. If title is specified and hideTitle is not specified,

then hideTitle is set to false.

If title is not specified and hideTitle is set to false, then the video filename is displayed as title.

Scenario Fallback

Flash is not installed Falls back to HTML 5 video playback, provided browser is HTML 5 compliant and video

source is supported by the browser.

If not, results in an error and displays the player container.

Browser does not have HTML 5 video

playback capability

Checks for Flash player.

If Flash player is available, plays the content in Flash player (for supported formats). If not,

results in an error and displays the player container.

Flash is not installed and the browser does

not support HTML 5 videos

Results in an error and displays the player container.

Both Flash and HTML playback are

supported and Flash is the default.

From the given video source, media player tries to run the Flash video, if available. Else,

tries to load the HTML 5 video unless you specify html as the value for type attribute in

cfmediaplayer.

Page 177: cf10betafeatures

175COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Example

<!DOCTYPE html> <html> <head> </head> <body> <cfmediaplayer name="player_html" title="End Game" source="/videos/gizmo.ogv" posterImage="/images/music.jpg" repeat="true"> </cfmediaplayer> </body> </html>

Extending the media player capabilities

Note: This feature applies only to Flash videos.

Using FlashVars, you can extend the media player to use capabilities of both OSMF plug-ins and Strobe media player.

As this section describes, you can use plug-ins in the OSMF market. Two popular plug-ins are demonstrated.

The general procedures to extend the media player capability are as follows:

1 Get the FlashVars and SWFs (from the plug-in vendor)

2 In the cfmediaplayer, insert a param tag with the FlashVars.

Playing videos on YouTube server

The following example shows how to play a video hosted on YouTube server using cfmediaplayer:

<!DOCTYPE html > <html> <head> </head> <body> <cfmediaplayer name="player_youtube" source="http://www.youtube.com/watch?v=gv68hDObACk&feature=feedrec_grec_index" type="flash" > <param name="flashvars" value="plugin_YoutubePlugin=/CFIDE/scripts/ajax/resources/cf/assets/YouTubePlugin.swf" /> </cfmediaplayer> </body> </html>

Here, source is the actual YouTube video link. You point to the YouTube plug-in SWF using FlashVars.

Playing linear and non-linear advertisements using stage video

You can extend the mediaplayer to play advertisements using a staged video. The advertisements play within the video

in linear and non-linear mode.

Page 178: cf10betafeatures

176COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Example

<!DOCTYPE html> <html> <head> <script type="text/javascript"> function nonLinear() {

var player = ColdFusion.MediaPlayer.getPlayer('player'); player.displayNonLiniarAd (

"http://gcdn.2mdn.net/MotifFiles/html/1379578/PID_938961_1237818260000_women.flv", { right: 10 * Math.random(), bottom: 10 * Math.random(), scaleMode: "none"});

} </script> </head> <body style="background:#FFFFFF"> <input name = "AdvertisementPlugin" value="Advertisement" type="button" onClick="nonLinear('player')"> <cfmediaplayer name="player" source="/videos/cathy2_HD.mp4" type="flash" > <param name="flashvars" value="plugin_ads=/CFIDE/scripts/ajax/resources/cf/assets/AdvertisementPlugin.swf" /> </cfmediaplayer> </body> </html>

In this example, using FlashVars, you point to the advertisement plug-in. Custom JavaScript function from the plug-

in is used to play video in linear and non-linear mode.

References

• For details on the supported FlashVars, see Chapter 2: Configuring the Player in the documentation available at the

following URL: http://www.osmf.org/downloads/pdf/using_fmp_smp.pdf

• To find more plug-ins that you can use with the mediaplayer, go to the following URL:

http://www.osmf.com/partner.php

• See the section Using Plug-ins in Chapter 4: Advanced Topics for details of how to use the plug-ins inside

cfmediaplayer in the document available at the following URL:

http://www.osmf.org/downloads/pdf/using_fmp_smp.pdf

• For more information on Strobe media playback, see the presentation available at the following URL:

http://www.osmf.com/downloads/pdf/Strobe_Media_Playback_Presentation.pdf

Embedding subtitle files to an HTML 5 video

Note: This option is not currently available for Flash videos.

You can embed subtitles using the HTML 5 track element. track element takes src as subtitle (SRT) file, with

language type and label, and displays it in subtitle options.

This feature works only if the browser supports HTML 5 track element.

Page 179: cf10betafeatures

177COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Example

<cfmediaplyer source="myvideo.ogv"> <track kind="subtitle" src="myvideo_en.srt" label="English" srclang="en" /> <track kind="subtitle" src="myvideo_fr.srt" label="French" srclang="fr" /> </cfmedialayer>

Play list support for Flash videos

Note: This option is not available for HTML 5 videos.

The list of media that you have to play are embedded in play list file M3U format.

You can specify the play list as follows:

<cfmediaplayer source="playlist.m3u" />

Skinning

In ColdFusion 9, you have the option to skin the Flash player using the following styles (using the attribute style):

bgcolor/bgColorTheme, hideborder, titleColorTheme , controlsColorTheme, progressColorTheme, and

progressbgColor.

For HTML 5 playback, you can use these attributes.

Note: In ColdFusion 10, you might not be able to skin the progress bar and control bar using the style attributes. This

is because, the new mediaplayer used in this release currently does not support them.

For Flash player, skin can be controlled using an XML by specifying the path for the skin attribute as follows:

<cfmediaplayer source="myvideo.mp4" skin="./skin/myskin.xml">

Note: Specifying styles using XML applies only to Flash videos.

Reference

Go to the following URL to see a sample skin for mediaplayer:

http://www.rblank.com/2010/10/06/sample-skin-for-strobeflash-media-playback/

New JavaScript functions

ColdFusion.Mediaplayer.getType

Description

Used to get the current playback type, if Flash or HTML player.

Function syntax

ColdFusion.MediaPlayer.getType("name")

See also

ColdFusion.MediaPlayer.resize, ColdFusion.MediaPlayer.setMute,

ColdFusion.MediaPlayer.setSource, ColdFusion.MediaPlayer.setVolume,

ColdFusion.MediaPlayer.startPlay, ColdFusion.MediaPlayer.stopPlay

History

ColdFusion 10: Added this function

Page 180: cf10betafeatures

178COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Parameters

Returns

This function returns the playback type as Flash or HTML 5.

Example

<!DOCTYPE html> <html> <head> <script type="text/javascript"> function getPlayback(player) {

alert(ColdFusion.MediaPlayer.getType("player")); } </script> </head> <body style="background:#"> <input name = "Source" value="Type" type="button" onClick="getPlayback('player')"> <div> <cfmediaplayer fullScreenControl="yes" name="player" width=800 height=500 > <source src="/videos/cathy2_HD.mp4" type="video/mp4" /> <source src="/videos/gizmo.ogv" type="video/ogg" /> </cfmediaplayer> </div> </body> </html>

ColdFusion.Mediaplayer.logError

Description

Lets you show custom error message on the media player, if an error occurs during playback.

Function syntax

ColdFusion.MediaPlayer.logError("Name", "Error")

See also

ColdFusion.Mediaplayer.getTypeColdFusion.MediaPlayer.resize, ColdFusion.MediaPlayer.setMute,

ColdFusion.MediaPlayer.setSource, ColdFusion.MediaPlayer.setVolume,

ColdFusion.MediaPlayer.startPlay, ColdFusion.MediaPlayer.stopPlay

History

ColdFusion 10: Added this function

Parameter Description

name Specifies the value of the name attribute of the cfmediaplayer tag.

Page 181: cf10betafeatures

179COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Parameters

Example

See the example for ColdFusion.Mediaplayer.getType.

ColdFusion.MediaPlayer.getPlayer

Description

Returns the player object that is used to invoke Strobe media player JavaScript API.

Function syntax

ColdFusion.MediaPlayer.getPlayer("Name")

See also

ColdFusion.Mediaplayer.getTypeColdFusion.MediaPlayer.resize, ColdFusion.MediaPlayer.setMute,

ColdFusion.MediaPlayer.setSource, ColdFusion.MediaPlayer.setVolume,

ColdFusion.MediaPlayer.startPlay, ColdFusion.MediaPlayer.stopPlay

History

ColdFusion 10: Added this function

Parameters

Example

See the example for “Dynamic streaming” on page 181.

New attributes in cfmediaplayer

Parameter Description

Name Specifies the value of the name attribute of the cfmediaplayer tag.

Error The custom error message that you want to display.

Parameter Description

Name Specifies the value of the name attribute of the cfmediaplayer tag.

Attribute Default Description

type flash The media player type, if html or flash.

repeat false If true, continues playback from first to last frame after the media player reaches the end of the video.

posterImage

Sets a poster image for the video playback.

Takes URL or relative address as value.

title Sets title on the media player.

The title appears over the media player on upper-left corner. If title is specified and hideTitle is not

specified, then hideTitle is set to false. Also when playback is Flash, the attribute wmode for Flash

player is set to opaque, and ignores the default/user-specified value.

Page 182: cf10betafeatures

180COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Example

<!DOCTYPE html> <html> <head> <script type="text/javascript"> function pausing() {

alert("Pausing"); } function error(errorCode) //For error code details, see Strobe Media Player documentation {

ColdFusion.MediaPlayer.logError("Player_DS","Invalid format"); } </script> </head> <body> <cfmediaplayer name="player_events"

title = "Last Count" onError="error"

onPause="pausing" type="html" source="/videos/cathy2_HD.mp4" > </cfmediaplayer> </body> </html>

The error code details are as follows:

skin Path to the XML in which skinning options are specified. Applies only to Flash

For example,

<cfmediaplayer source="myvideo.mp4" skin="./skin/myskin.xml">

onPause Custom JavaScript function to run when the video is paused.

onError Custom JavaScript function to run when playback results in an error.

Error code Description

1 You interrupted the video playback

2 Due to network issues, the video download failed midway.

3 Play back failed either because the video file is corrupt or your browser does not support some of the features

used by the video.

4 Cannot load the video.

Attribute Default Description

Page 183: cf10betafeatures

181COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Impact on existing attributes in cfmediaplayer

Note on events

For events, ColdFusion provides the EventHandler. But the event is subject to browser discretion. At times, this might

lead to multiple eventHandler calls. For example, on browser 1 event loads when the mediaplayer loads whereas on

browser 2, the event loads on page load.

Player controls

ColdFusion 9 supports the following mediaplayer controls for Flash videos: Play/Pause, Stop, progress bar, Current

and total playback time, volume, and full screen.

While the Stop control is not supported hereafter, enhancements in ColdFusion 10 let you use these controls for

HTML 5 videos also.

In addition, when you use Flash Player, Next and Previous controls are supported. They appear when playing the play

list. Currently, this control is available only for Flash player and appears when source specified is a play list file (M3U).

Dynamic streaming

Note: This feature applies only to Flash player.

At server side

The feature lets dynamic delivery of streaming videos by alternating among various playback streams.

To set up dynamic streaming, point to the dynamic streaming video using the source attribute in cfmediaplayer as

follows:

Attribute Change of behavior

wmode When you set playback type as Flash, value of this attribute is set to opaque, and ignores the default/user-

specified value.

hideTitle The default value has changed from false to true.

fullScreenControl

This attribute is unsupported for HTML playback. Also, you cannot disable full screen for Flash player.

bgcolor In the case of HTML player, this attribute applies only if you are using the attribute wmode set to transparent.

The dependency does not exist if you are using Flash player.

align In ColdFusion 10, lets you use the screen real estate effectively whereas in ColdFusion 9, it was a block element.

Therefore, if you use this attribute, the text-video balance of the page might be affected.

height The default height value now is 275 pixels.

Page 184: cf10betafeatures

182COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <script type="application/javascript"> functi on getStreamData() {

var player = ColdFusion.MediaPlayer.getPlayer("player_ds"); var dynamicStreams=player.getStreamItems(); for (var idx = 0; idx < dynamicStreams.length; idx ++) {

var streamLabel = dynamicStreams[idx]['width'] + "x" + dynamicStreams[idx]['height'] + " @ " + dynamicStreams[idx]['bitrate'] + "kbps";

var element = document.createElement("option"); element.innerHTML = streamLabel; document.getElementById("streams").appendChild(element); if (idx==player.getCurrentDynamicStreamIndex()) {

document.getElementById("streams").selectedIndex = idx; }

} } function selectionChange() {

var index = document.getElementById("streams").selectedIndex; var player = ColdFusion.MediaPlayer.getPlayer("player_ds"); player.setAutoDynamicStreamSwitch(false); player.switchDynamicStreamIndex(index);

} </script> </head> <body> <div align="center"> <br /> <br /> <br /> <button type="button" onclick="getStreamData()" value="Stream Details" name= "Stream Details"> Stream Details</button> <br /> <br /> <select name="streams" id="streams" onchange="selectionChange()"> </select> <br /> </div> <cfmediaplayer name="player_ds" source="URL to the F4M file" width=800 height=500 type="flash" autoplay="true"

align="center" > </cfmediaplayer> </body> </html>

At client side

At the client-side, you have the HD controls which can be used to toggle between different streaming videos available.

Page 185: cf10betafeatures

183COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

HTML enhancements

Displaying geolocation

Displays user location on the map if the attribute showUser is specified in cfmap. This feature works only on HTML

5 compliant browsers.

The following sections describe the changes to the tags cfmap and cfmapitem to display the user location:

cfmap

• A new attribute showUser has been added. The default value is false. If true, on HTML-compliant browsers,

user location is shown on the map.

For browsers that are not HTML 5 compliant, the address falls back to the value you specify for centerAddress.

If no value is specified, it falls back to the value specified for centerLatitude and centerLongitude.

Note: User has to authenticate the site so that it tracks user location. For example, in Google Chrome, you are

prompted to Allow to track your Physical location.

cfmapitem

• A new attribute showUser has been added. The default value is false.

If true, on HTML-compliant browsers, user location is shown on the map.

cfinput

• The attribute type now supports all HTML 5 input types, for example, email, range, or date. For details, see

http://dev.w3.org/html5/spec/Overview.html#the-input-element

• The tag supports new attributes such as max and min.

Client-side charting

ColdFusion 10 supports client-side charting. This is in addition to the existing server-side charting feature (which

continues to serve the way it used to).

Client-side charting supports the following:

• Dynamic and interactive charting: Modify the charts, add styles, and add new series or plots.

• Popular chart formats with appropriate fallback functionality: Use HTML 5, Flash, SVG, or VML charts.

If your browser does not support HTML 5 features relevant to charting, charts are rendered in Flash. Similarly, if

Flash is not supported, charts are rendered in HTML.

• Features identical to server-side charting: Most of the server-side charting features are available with client-side

charting.

• Old and new charts: In addition to the contemporary chart types, offers a new set of charts.

• Needs minimal trips to server: As compared to generating charts at server-level, for every user interaction.

Supported charts

Line Charts Area Charts Bar Charts Scatter Charts

Bubble Charts Horizontal Bar Charts Pie Charts Radar Charts

Bullet Charts Nested Pie Charts Piano Charts Funnel Charts

Gauges Horizontal Bullet

Charts

Cone 3D Line Charts

Page 186: cf10betafeatures

184COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Note: Future releases will support Venn Chart and Stock charts.

How client side charting works

1 Use the cfchart tag and specify html as the value for the attribute format.

By default, the format is flash (which is applicable to server-side charting).

2 Specify the chart details as you specify them for server-side charting in the previous releases.

Modifications to tags

The following section provides details of the new and modified attributes in cfchart.

cfchart

Syntax

Note: Includes old and new attributes.

<!--- This syntax uses a JSON file to specify the chart style. ---> <cfchart style = "JSON filename"> </cfchart> OR <!--- This syntax uses the attributes of the cfchart tag to specify the chart style. ---> <cfchart alpha = "value between 0 and 1"

arrows = "JSON string representation" aspect3D = "JSON string representation" background = "JSON string representation" bevel = "JSON string representation" border = "JSON string representation" backgroundColor = "hexadecimal value|web color"

chartHeight = "integer number of pixels" chartWidth = "integer number of pixels" crosshair = "JSON string representation"

dataBackgroundColor = "hexadecimal value|web color" fill = "JSON string representation"

font = "font name" fontBold = "yes|no" fontItalic = "yes|no" fontSize = "font size" foregroundColor = "hexadecimal value|web color" format = "flash|jpg|png|html" gridlines = "integer number of lines" height = "height in pixels"

ID = "chart identifier" labels = "JSON string representation" legend = "JSON string representation" labelFormat = "number|currency|percent|date"

marker = "JSON string representation" markerSize = "integer number of pixels"

3D Area Charts 3D Pie Charts 3D Horizontal Bar

Charts

Pyramid

Cylinder

Page 187: cf10betafeatures

185COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

name = "string" pieSliceStyle = "solid|sliced"

plot = "JSON string representation" plotarea = "JSON string representation" preview = "JSON string representation" refresh = "JSON string representation" renderer = "canvas|flash|svg|vml" scales = "comma-seperated list of axes"

scaleFrom = "integer minimum value" scaleTo = "integer maximum value" seriesPlacement = "default|cluster| stacked|percent" show3D = "yes|no" showBorder = "yes|no" showLegend = "yes|no" showMarkers = "yes|no" showXGridlines = "yes|no" showYGridlines = "yes|no" sortXAxis = "yes|no" tipBGColor = "hexadecimal value|web color" tipStyle = "MouseDown|MouseOver|none" title = "title of chart"

tooltip = "JSON string representation" url = "onClick destination page"

xAxis = "JSON string representation" xAxis2 = "JSON string representation"

xAxisTitle = "title text" xAxisType = "scale|category"

xAxisValues = "Array of values" xOffset = "number between -1 and 1" yAxis = "JSON string representation"

yAxis2 = "JSON string representation" yAxisTitle = "title text"

yAxisType = "scale|category" yAxisValues = "Array of values"

yOffset = "number between -1 and 1"> zoom = "JSON string representation"

</cfchart>

Note: You can specify this tag’s attributes in an attributeCollection attribute whose value is a structure. Specify the

structure name in the attributeCollection attribute and use the tag’s attribute names as structure keys.

Attribute Req/Opt Default Description

alpha Optional Alpha (transparency) level of the background. Valid values range from 0

(transparent) to 1 (opaque).

arrows Opt Creates an arrow for pointing out data or other chart items.

JSON string representation of array of structs that contain values such as

to, from, size, and label.

aspect3D Opt JSON string representation of struct that defines the angle of 3D aspect.

The valid struct keys are angle and depth.

Page 188: cf10betafeatures

186COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

background Opt A struct of keys related to background such as

• color: Sets the background colors

• color-1: Sets the first background color for the arrow

• color-2: Sets the second background color for the arrow (used with

gradients)

• transparent: Set the transparency of a background image so that

underlying colors or chart can show.

• fit: Defines the width/height to fit area of background.

• repeat: Defines type of image repeat.

• image: Defines the path to the background image.

• position: Defines the position of the background image.

bevel Opt A struct of keys related to bevel such as.

• color: Defines the color of the bevel.

• blur-x: Defines the sharpness/smoothness of the bevel edges in the x-

direction.

• blur-y: Defines the sharpness/smoothness of the bevel edges in the y-

direction.

• angle: Defines the angle of the bevel.

• distance: Distance in # | #px indicating the distance from the object

the bevel should be displayed.

border Opt A struct of keys related to border such as:

• color: Sets the color of the border.

• radius: Defines the radius of rounded corners.

• width: Defines the width of the border.

crosshair Opt A struct of keys related to crosshair such as:

• line-color: Sets the color of the crosshair lines.

• alpha: Defines the alpha transparency level of the line.

• line-style: Defines the line style.

fill Opt A struct of keys related to fill such as:

• angle: Sets the angle at which a linear fill is displayed. A fill angle of

zero displays a vertical gradient from top (background-color-1) to

bottom (background-color-2).

• offset-x: Set x-axis offset for background gradient.

• offset-y: Set y-axis offset for background gradient..

format Req flash Format of the chart to be rendered. The supported formats are html, flash,

jpg, and png.

height Opt Chart height; integer; number of pixels.

Attribute Req/Opt Default Description

Page 189: cf10betafeatures

187COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

The following attributes in the previous release are not supported for client-side charting: format, labelformat,

seriesplacement with percent as the value, sort, xaxis, tipsstlye, url, xAxisTYpe, xoffset, yaxistype, and

yoffset.

cfchartseries

Syntax

Note: Includes old and new attributes.

ID Opt ID of the chart. Used to get the underlying chartobject.

labels Opt An array of structs used to display custom text or images on the chart, for

example author or chart information.

legend Opt A struct used to define the legend attributes, for example, background-

color or margin-top.

plot Opt A struct of keys such as animation, aspect, margin, and marker used

to style the plotting.

plotarea Opt A struct of keys such as position and margin used to style the plotarea.

preview Opt A struct of keys such as visible and margin to control chart preview.

refresh Opt A struct of keys: such as type (feed to full), url, and interval

(In seconds) to create dynamic charts.

renderer Opt canvas if

format is html

Specify the rendering method. Applies only if format is html. The

supported values are canvas, flash, svg, and vml.

scales Opt Comma-separated list of axis against which to plot the chart, for example,

x,y2.

tooltip Opt A struct of keys used to style the tool tip such as background, font, or

border.

xaxis Opt A struct of keys used to style x axis such as format, guide, item, and

label.

xaxis2 Opt A struct of keys used to style second x axis such as format, guide, item,

and label, which is on the top of the chart.

xaxisvalues Opt An array of values to be displayed on x axis.

yaxis Opt A struct of keys used to style y axis such as format, guide, item, and

label.

yaxis2 Opt A struct of keys used to style second y axis such as format, guide, item,

and label, which is on the top of the chart.

yaxisvalues Opt An array of values to be displayed on y axis.

zoom Opt A struct of keys to be applied when you zoom the chart such as alpha,

background, or bevel.

Attribute Req/Opt Default Description

Page 190: cf10betafeatures

188COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

<cfchartseries alpha = "Integer between 0 and 1"

animate = "JSON string representation" aspect = "text" background = "JSON string representation" bevel = "JSON string representation" border = "JSON string representation" color = "text" data = "JSON string representation" hovermarker = "JSON string representation" marker = "JSON string representation" type="type"

itemColumn ="query column" label = "text"

valueColumn="query column" colorlist = "list" dataLabelStyle="style" markerStyle="style" paintStyle="plain|raise|shade|light" query="query name" scales = "comma-seperated list of axes"

shadow = "JSON string representation" seriesColor="hexadecimal value|web color"

seriesLabel="label text"> toolTip = "JSON string representation" zColumn = "query column"

</cfchartseries>

Attributes

Attribute Req/Opt Default Description

alpha Optional Alpha (transparency) level of the background.

Valid values range from 0 (transparent) to 1 (opaque).

animate Opt A struct of keys to define the animation such as effect and speed.

An empty struct results in default animation with appear effect.

aspect Opt Defines the variations of a chart type, for example line, area, and dots

in a radar chart.

background Opt A struct of keys related to background such as

• color: Sets the background colors

• color-1: Sets the first background color for the arrow

• color-2: Sets the second background color for the arrow (used with

gradients)

• transparent: Set the transparency of a background image so that

underlying colors or chart can show.

• fit: Defines the width/height to fit area of background.

• repeat: Defines type of image repeat.

• image: Defines the path to the background image.

• position: Defines the position of the background image.

Page 191: cf10betafeatures

189COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

The following attributes are not supported for Client side charting:

paintStyle and the following values for markerstyle: letterx, mcross, snow, and rcross.

A new attribute zvalue added to cfchartdata: Applicable if chart takes a third dimension in addition to x and y.

bevel Opt A struct of keys related to bevel such as:

• color: Defines the color of the bevel.

• blur-x: Defines the sharpness/smoothness of the bevel edges in the x-

direction.

• blur-y: Defines the sharpness/smoothness of the bevel edges in the y-

direction.

• angle: Defines the angle of the bevel.

• distance: Distance in # | #px indicating the distance from the object

the bevel should be displayed.

border Opt A struct of keys related to border such as:

• color: Sets the color of the border.

• radius: Defines the radius of rounded corners.

• width: Defines the width of the border.

marker Opt A struct of keys used to style the marker such as size, border,

background, and bevel.

color Opt Color of the main element (such as the bars) of a chart.

For a pie chart, this is the color of the first slice.

Hexadecimal value or supported named color; see the name list and

information about six- and eight-digit hexadecimal values in the Usage

section for the cfchart tag.

For a hexadecimal value, use the form"##xxxxxx"or"##xxxxxxxx",

where x = 0-9 or A-F; use two number signs or none.

label Opt Text of the data series label.

hoverMarker Opt A struct of keys used to style the marker on mouse hover such as size,

border, background, and bevel.

data Opt The chart data. This is an array of arrays.

Specify the data as follows:

2,3],[4,5]]or[[3,4,5],[6,7,3]] for charts with z parameter such

as bubble chart, or[[3],[4]] in case of pie charts.

scales Opt Comma-separated list of axis against which to plot the series, for example,

x,y2.

shadow Opt false Used to enable/disable the shadow.

The value can either be yes|no or a struct that takes the key alpha.

tooltip Opt A struct of keys used to style the tool tip such as background, font, or

border.

zcolumn Opt The value of the dimension.

Applicable if the chart takes a third dimension in addition to x and y.

Attribute Req/Opt Default Description

Page 192: cf10betafeatures

190COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Limitations

The following server-side charting features are not available with client-side charting:

• Linking charts to URL

• Writing charts to a variable

Charting examples

Example 1

The following is a basic example of using client side charting.

<cfchart format ="html" type="pie"> <cfchartseries> <cfchartdata item="New car sales" value="50000"> <cfchartdata item="Used car sales" value="25000"> <cfchartdata item="Leasing" value="30000"> <cfchartdata item="Service" value="40000"> </cfchartseries> </cfchart>

Example 2

This example showcases how you can create four different types of charts:

Page 193: cf10betafeatures

191COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

<cfquery name="BasicData" datasource="cfartgallery"> select firstname,sum(price) as totalvalue,max(price) as topprice,count(*) as

artcount,count(*)*50000 as goal from art,artists where artists.artistid=art.artistid group by firstname </cfquery> <div style="float:left;"> <cfchart format="html" type="pie" width=700 height=500 title="Artists and their MarketValue">

<cfchartseries itemcolumn="firstname" valuecolumn="totalvalue" query="BasicData" label="MarketValue"> </cfchart> </div> <div style="float:left;"> <cfchart format="html" type="bubble" width=700 height=500 title="Artists and their MarketValue (with topprice)">

<cfchartseries itemcolumn="firstname" valuecolumn="totalvalue" zcolumn="topprice" query="BasicData" label="MarketValue"> </cfchart> <center><b>Bigger the bubble, higher is the top price</b></center> </div> <div style="clear:both;"></div> <br><br> <div style="float:left;"> <cfchart format="html" type="bullet" itemcolumn="firstname" query="BasicData" width=700 height=500 title="Artists and their MarketValue (with goals at 50k per art)">

<cfchartseries itemcolumn="firstname" valuecolumn="totalvalue" zcolumn="goal" query="BasicData" label="MarketValue"> </cfchart> </div> <div style="float:left;"> <cfchart format="html" type="radar" itemcolumn="firstname" query="BasicData" width=700 height=500 title="Artists and their TopPrice">

<cfchartseries itemcolumn="firstname" valuecolumn="topprice" query="BasicData" label="TopPrice"> </cfchart> </div>

New JavaScript functions

ColdFusion.Chart.getChartHandle

Description

Used to get chart object for various JavaScript operations that you want to perform, for example adding or removing

a series or nodes in charts.

Returns

JavaScript object

Function syntax

ColdFusion.Chart.getChartHandle()

History

ColdFusion 10: Added this function

Page 194: cf10betafeatures

192COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Example

The following example shows how to add a new value to the first series of a chart with chart ID interactivebar:

ColdFusion.Chart.getChartHandle().exec('interactivebar', 'appendseriesvalues', '{"plotindex": 0, "values" : [40]}' );

Example

The following example shows how to add a new value to the register a click event on a chart:

ColdFusion.Chart.getChartHandle().click = function(dataObj){ alert("Chart Clicked - ID: " + data["id"]); }

Caching enhancements

ColdFusion 10 has the following caching enhancements:

Application-specific caching

You can specify caching at server-level or specific to an application.

To set up cache configuration at the application level, specify the application-specific cache settings file (ehcache.xml)

in the Application.cfc as shown in the following examples:

Specify the full path:

this.cache.configfile = "c:/cachesettings/ehcache.xml";

Specify the relative path with respect to the Application.cfc:

this.cache.configfile = "ehcache.xml";

If caching is specified at the application level, all cache functions use the application-specific cache configuration.

Example

Application.cfc

<cfcomponent> <cfscript>

this.name = "appSpecificCacheTest"; this.cache.configfile = "ehcache.xml";

this.applicationTimeout = createtimespan(0,0,0,5);

function onApplicationStart(){ writelog("In onApplicationStart()");

} function onApplicationEnd(){

writelog("In onApplicationEnd()"); }

</cfscript> </cfcomponent>

cache.cfm

Page 195: cf10betafeatures

193COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head>

<title>cfhttp</title> </head> <!--- End of header ---> <body>

<!--- remove object from Application Specific cache ---> <cfif ArrayLen(cacheGetAllIds()) gt 0>

<cfset cacheRemove(ArrayToList(cacheGetAllIds()))> </cfif> <cfset obj1 = structNew()>

<cfset obj1.name = "xyz"> <cfoutput>Starting to write to cache..</cfoutput> <cfset cachePut("obj1",obj1)> <br/> <cfoutput>Done!!</cfoutput> <cfoutput>Trying to fetch cached item...</cfoutput> <cfset obj = cacheGet("obj1")>

<br/> <cfdump var="#obj#">

<cfscript>

sleep(15000); </cfscript> <cfoutput>Trying to fetch cached item after 15 seconds...<br/></cfoutput> <cfset obj = cacheGet("obj1")>

<cfdump var="#obj#"> </body> </html>

ehcache.xml

Page 196: cf10betafeatures

194COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

<?xml version="1.0" encoding="UTF-8"?> <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ehcache.xsd"> <diskStore path="java.io.tmpdir"/> <cacheManagerEventListenerFactory class="" properties=""/> <defaultCache maxElementsInMemory="5" eternal="false" timeToIdleSeconds="30" timeToLiveSeconds="5" overflowToDisk="true" diskSpoolBufferSizeMB="30" maxElementsOnDisk="10" diskPersistent="false" diskExpiryThreadIntervalSeconds="3600" memoryStoreEvictionPolicy="LRU" clearOnFlush="true" /> <cache name="app1cache" maxElementsInMemory="5" eternal="false" timeToIdleSeconds="60"

timeToLiveSeconds="5" overflowToDisk="false" diskSpoolBufferSizeMB="30" maxElementsOnDisk="10" diskPersistent="false" diskExpiryThreadIntervalSeconds="3600" memoryStoreEvictionPolicy="LRU" clearOnFlush="true"/> </ehcache>

Enhanced query caching using Ehcache

Uses Ehcache

All cache queries are cached using Ehcache.

Default and custom query cache regions

All cache queries are stored in the default query region. There are independent default query regions for server-specific

and application-specific cache.

You can specify user-defined query cache region using the attribute cacheRegion in cfquery.

If you do not specify a query cache region, the default cache region is used at application or server level (whichever is

applicable).

Cache ID

You can associate a query with a unique identifier for each cache using the attribute cacheID. The ID you specify can

be quoted while using the cache functions.

Page 197: cf10betafeatures

195COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Within cache, queries are stored as type query like object and template caches.

Example

See the example in the section “New attributes in cfquery” on page 195.

Fallback to internal cache

To fall back to internal cache (and not use Ehcache) to cache queries, do either of the following:

• Server level: Change the following setting:

Check the option Use internal query caching in ColdFusion Administrator.

For details, see “Caching enhancements” on page 221.

• Application level: Specify true for the following setting:

this.cache.useinternalquerycache=true|false. The default value is false.

Specifying query limit

To specify a limit for maximum number of queries in cache, specify the number of queries in the Application.cfc for

the following setting:

this.cache.querysize

Modifications to tags

New attribute in cfcache

A new optional attribute region has been added. It replaces the deprecated attribute key. region is the name that you

assign to a cache region.

New attributes in cfquery

The following new attributes:

Parameter Description

cacheID (Optional) ID to be used to store query result in cache.

This ID can be used to either retrieve or remove query from cache

cacheRegion (Optional) Cache region to be used to cache query result.

If not specified, by default query is cached in the QUERY region.

Page 198: cf10betafeatures

196COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Example: Query caching in user-defined region

<!--- Getting the time when the result was put in the cache ---> <cfset t1 = getTickCount()> <cfset time = createDateTime(2011,9,20,12,10,10)> <cfset timeToLive = createTimespan(0,0,0,60)> <cfset object_id = "ABC"> <cfset cache_region = "customcache"> <!--- Putting the result into the USD Application Cache ---> <cfquery name="q2" cacheid="#object_id#" cacheregion="#cache_region#" datasource="cfartgallery"> select * from art where artid = 2 </cfquery> <br/> <!--- Getting the result from the Cache ---> <cfset a = cacheGet(object_id,cache_region)> <!--- The time during accessing the result ---> <cfset t2 = getTickCount()> <!--- Getting the result from the Cache ---> <cfset a = cacheGet(object_id,cache_region)> <!--- The time during accessing the result ---> <cfset t3 = getTickCount()> <!--- The time difference should be 0 ---> <cfoutput>Time Difference : #t3-t2#</cfoutput> <cfdump var="#cacheGetProperties(cache_region)#"> <!--- Verifying if the result is stored in the correct cache---> <cfoutput>#cacheGetProperties(cache_region).timetoLiveSeconds#</cfoutput><br> <cfscript>sleep(25000);</cfscript> <!--- Accessing the cache if the result is still present even after the TimeToLive ---> <cfset a = cacheGet(object_id,cache_region)> <cfdump var="#a#"> <cfoutput>#cacheIDExists(object_id,cache_region)#</cfoutput>

Page 199: cf10betafeatures

197COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Example: Query caching in default region

<!--- Getting the time when the result was put in the cache ---> <cfset t1 = getTickCount()> <cfset time = createDateTime(2011,9,20,12,10,10)> <cfset timeToLive = createTimespan(0,0,0,60)> <cfset object_id = "TTTQQQ"> <!--- Putting the result into the USD Application Cache ---> <cfquery name="q2" cacheid="#object_id#" cachedwithin="#timeToLive#" datasource="cfartgallery"> select * from art where artid = 2 </cfquery> <br/> <!--- Getting the result from the Cache ---> <cfset a = cacheGet(object_id,"QUERY")> <!--- The time during accessing the result ---> <cfset t2 = getTickCount()> <!--- Getting the result from the Cache ---> <cfset a = cacheGet(object_id,"QUERY")> <!--- The time during accessing the result ---> <cfset t3 = getTickCount()> <!--- The time difference should be 0 ---> <cfoutput>Time Difference : #t3-t2#</cfoutput> <!--- Verifying if the result is stored in the correct cache---> <cfoutput>#cacheGetProperties("QUERY").timetoLiveSeconds#</cfoutput><br> <cfscript>sleep(25000);</cfscript> <!--- Accessing the cache if the result is still present even after the TimeToLive ---> <cfoutput>#cacheIDExists(object_id,"QUERY")#</cfoutput>

New and modified cache functions

The following new functions help you with various cache operations:

cacheIDExists

Description

Used to find if a cached object exists in the cache region. The region can be the default cache region (either at server

or application level) or the custom region you specify.

Returns

True, if the cached object exists in the specified cache region.

Syntax

cacheIDExists(id [, region])

Page 200: cf10betafeatures

198COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Properties

Example: Checks if the cache object is present in the user-defined cache region

<!--- Creating a new object ' <cfset obj1 = structNew()> <cfset obj1.name = "xyz"> <!---Defining the time to live and time to Idle parameters --' <cfset timeToLive=createtimespan(0,0,0,30)> <cfset timeToIdle=createtimespan(0,0,0,30)> <cfoutput>Starting to write to cache..</cfoutput> <cfset cachePut("obj1",obj1,timeToLive,timeToIdle,"customcache")> <br/> <cfoutput>Done!!</cfoutput> <cfoutput>Trying to check if the cached item is present...</cfoutput> <cfoutput>#cacheIDExists("obj1","customcache")#</cfoutput>

Example: Checks if the cache object is present in the default cache region

<cfset obj2 = structNew()> <cfset obj2.name = "xyz"> <cfoutput>Starting to write to cache..</cfoutput> <cfset cachePut("obj2",obj2)> <br/> <cfoutput>Done!!</cfoutput> <cfoutput>Trying to fetch cached item...</cfoutput> <cfset obj = cacheGet("obj2")> <cfoutput>#cacheIDExists("obj2","OBJECT")#</cfoutput>

cacheRegionNew

Description

Creates a custom cache region (if no cache region exists).

Returns

An error if throwOnError parameter is set to true, provided cache region already exists.

Syntax

cacheRegionNew(region,[properties],[throwOnError])

Parameter Description

id (Required) The ID of the cached object.

region (Optional) The cache region where you check for the cached object.

Page 201: cf10betafeatures

199COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Properties

Example

<!--- Defining properties for the struct ---> <cfset defaultCacheProps = StructNew()> <cfset defaultCacheProps.CLEARONFLUSH = "true"> <cfset defaultCacheProps.DISKEXPIRYTHREADINTERVALSECONDS = "3600"> <cfset defaultCacheProps.DISKPERSISTENT = "false"> <cfset defaultCacheProps.DISKSPOOLBUFFERSIZEMB = "30"> <cfset defaultCacheProps.ETERNAL = "false"> <cfset defaultCacheProps.MAXELEMENTSINMEMORY = "5"> <cfset defaultCacheProps.MAXELEMENTSONDISK = "10"> <cfset defaultCacheProps.MEMORYEVICTIONPOLICY = "LRU"> <cfset defaultCacheProps.OBJECTTYPE = "OBJECT"> <cfset defaultCacheProps.OVERFLOWTODISK = "true"> <cfset defaultCacheProps.TIMETOLIVESECONDS = "5"> <cfset defaultCacheProps.TIMETOIDLESECONDS = "30"> <cfset cacheRegionNew("testregion",#defaultCacheProps#,false)> <!--- Defining a struct object ---> <cfset obj1 = structNew()> <cfset obj1.name = "xyz"> <cfset timeToLive = CreateTimeSpan(0,0,5,0)> <cfset timeToIdle = CreateTimeSpan(0,0,10,0)> <!--- Putting Cache in the USD specific cache ---> <cfoutput>Starting to write to cache..</cfoutput> <cfset cachePut("obj1",obj1,timetoLive,timeToIdle,"testregion")> <cfoutput>Trying to fetch cached item...</cfoutput> <cfset obj = cacheGet("obj1","testregion")> <br/> <cfoutput>Done!!<br></cfoutput> <cfoutput>#obj.name#</cfoutput>

cacheRegionRemove

Description

Removes a specified cache region.

Returns

Nothing

Syntax

cacheRegionRemove(region)

Parameter Description

region Name of the new cache region to be created.

properties Optional. Struct that contains the cache region properties.

throwOnError Optional. A Boolean value specifying if to throw an exception if the cache region name you specify already

exists. The default value is true.

Page 202: cf10betafeatures

200COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Properties

Example

See the example for “cacheRegionExists” on page 200.

cacheRemoveAll

Description

Removes all stored objects in a cache region. If no cache region is specified, objects in the default region are removed.

Returns

Nothing

Syntax

cacheRemoveAll(region)

Properties

Example

<!--- clear all object caches ---> <cfif ArrayLen(cacheGetAllIds()) gt 0> <cfset cacheRemove(ArrayToList(cacheGetAllIds()))> </cfif> <!--- create few caches ---> <cfloop from="1" to="10" index="i"> <cfset id = "cache_#i#"> <cfset timeToLive = CreateTimeSpan(0,0,30,0)> <cfset timeToIdle = CreateTimeSpan(0,0,30,0)> <cfset cachePut(id,createQryObj(i),timeToLive,timeToIdle)> </cfloop> <cfoutput>Before cacheRemove() :: Number of objects in the cache: #ArrayLen(cacheGetAllIds())#<br></cfoutput> <!--- clear all objects from the cache ---> <cfset cacheRemoveAll()> <cfoutput>After cacheRemove() :: Number of objects in the cache: #ArrayLen(cacheGetAllIds())#<br><br></cfoutput>

cacheRegionExists

Description

Checks if the cache region exists.

Parameter Description

region Name of the cache region that has to be removed.

Parameter Description

region (Optional) Indicates the cache region from which to remove the stored objects. If no value is specified,

default cache region is considered by default.

Page 203: cf10betafeatures

201COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Returns

True if the cache region exists.

Syntax

cacheRegionExists(region)

Properties

Example

<!--- Checking if the region is present in the Cache ---> <cfif #cacheRegionExists("testregion")# EQ "YES"> <cfset cacheRegionRemove("testregion")> <cfif #cacheRegionExists("testregion")# EQ "NO"> <cfoutput>Region is deleted<br></cfoutput> </cfif> <cfelse> <cfset cacheRegionNew("testregion")> <cfset cacheRegionRemove("testregion")> <cfif #cacheRegionExists("testregion")# EQ "NO"> <cfoutput>Region is deleted<br></cfoutput> </cfif> </cfif>

removeCachedQuery

Description

Removes the query with the details you provide from query cache.

Returns

Nothing

Syntax

removeCachedQuery(SQL, datasource, params)

Properties

Parameter Description

region Name of the cache region.

Parameter Description

SQL The query SQL.

datasource The datasource you ran the query on.

params (Optional) Array of parameter values passed to SQL.

Page 204: cf10betafeatures

202COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Example

<cfset sql = "SELECT * from art where artid = ?"> <cfquery name="q" datasource="cfartgallery" cachedwithin="#CreateTimeSpan(0, 6, 0, 0)#"> SELECT * from art where artid = <cfqueryPARAM value = "1" CFSQLType = 'CF_SQL_INTEGER'> </cfquery> <cfset a = arrayNew(1)> <cfset a[1] = 1> <cfset removeCachedQuery(sql,"cfartgallery", a)>

Enhancements to existing cache functions

• An optional parameter region (the name of the cache region) has been added to the following functions:

• cacheSetProperties

• cacheGetMetadata

• cacheGetProperties

• cacheGetAllIds

Example

<cfset cache_region="customcache"> <!--- clear all object caches for this app---> <cfif ArrayLen(cacheGetAllIds(cache_region)) gt 0> <cfset cacheRemove(ArrayToList(cacheGetAllIds(cache_region)),true,cache_region)> </cfif> <!--- clear all template caches for this app ---> <cfcache action="flush"> <!--- create object cache ---> <cfset cachePut("c1","some_value")> <!--- create template cache ---> <cfcache timespan="#createtimespan(0,0,0,10)#"> [page fragment]<br /> </cfcache> <!--- get application cache properties before cacheSetProperties() ---> <cfset bPropsObject = cacheGetProperties(cache_region)> <cfset bPropsTemplate = cacheGetProperties(cache_region)> <!--- pass an empty struct ---> <cfset cacheSetProperties({},cache_region)> <!--- get application cache properties after cacheSetProperties() ---> <cfset aPropsObject = cacheGetProperties(cache_region)> <cfset aPropsTemplate = cacheGetProperties(cache_region)> <cfdump var="#bPropsObject#"> <cfdump var="#bPropsTemplate#"> <cfdump var="#aPropsObject#"> <cfdump var="#aPropsTemplate#">

• The following parameters have been added to the function CacheRemove:

Page 205: cf10betafeatures

203COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Example with parameter exact set to true

<!--- clear all object caches ---> <cfif ArrayLen(cacheGetAllIds()) gt 0> <cfset cacheRemove(ArrayToList(cacheGetAllIds()))> </cfif> <!--- create few caches ---> <cfloop from="1" to="10" index="i"> <cfset id = "cache_#i#"> <cfset timeToLive = CreateTimeSpan(0,0,30,0)> <cfset timeToIdle = CreateTimeSpan(0,0,30,0)> <cfset cachePut(id,createQryObj(i),timeToLive,timeToIdle)> </cfloop> <cfoutput>Before cacheRemove() :: Number of objects in the cache: #ArrayLen(cacheGetAllIds())#<br></cfoutput> <!--- clear all objects from the cache ---> <cfset cacheRemove("cache_1",true,"object",true)> <cfoutput>(List of cache Ids - #ListSort(ArrayToList(cacheGetAllIds()),"textnocase","ASC")#)</cfoutput><br> <cfoutput>After cacheRemove() :: Number of objects in the cache: #ArrayLen(cacheGetAllIds())#<br><br></cfoutput>

Example with parameter exact set to false

<!--- create few caches ---> <cfloop from="1" to="10" index="i"> <cfset id = "cache_#i#"> <cfset timeToLive = CreateTimeSpan(0,0,30,0)> <cfset timeToIdle = CreateTimeSpan(0,0,30,0)> <cfset cachePut(id,createQryObj(i),timeToLive,timeToIdle)> </cfloop> <cfoutput>Before cacheRemove() :: Number of objects in the cache: #ArrayLen(cacheGetAllIds())#<br></cfoutput> <!--- clear all objects from the cache ---> <cfset cacheRemove("cache",true,"object",false)> <cfoutput>(List of cache Ids - #ListSort(ArrayToList(cacheGetAllIds()),"textnocase","ASC")#)</cfoutput><br> <cfoutput>After cacheRemove() :: Number of objects in the cache: #ArrayLen(cacheGetAllIds())#<br><br></cfoutput>

Cache statistics

• The propsSruct property in cacheSetProperties supports a new field statistics. true indicates that

statistics collection for Ehcache is enabled.

Parameter Description

region (Optional) Name of the cache region from which to remove the cached objects.

exact (Optional) If true, the search narrows down to values that exactly match the IDs (for removal). The

default value is true.

Page 206: cf10betafeatures

204COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

• For cacheGetProperties, in the array of structures, a new field statistics is supported for the structure. true

indicates that statistics collection for Ehcache is enabled.

Other enhancements

Virtual File System: Support for HTTP, FTP, and ZIP

ColdFusion 10 lets you access files over network through FTP or HTTP protocol. Also provided is support for ZIP.

For conventions, see the Apache Commons Documentation.

Examples

For FTP:

<cffile action = "read" file = "ftp://Administrator:Password@Host_Name/ReadmeLater.htm" variable = "varvar"> <cffile action="write" file="ftp://Administrator:Password@Host_Name/ReadmeLater.htm" output="new stuff added">

For ZIP

<cffile action = "read" file="zip:#ExpandPath('./')#/hello.zip!/hello.txt" variable = "varRead1">

CAR, migration, and Code Analyzer

• CAR and migration: CAR files let you archive and deploy website configuration information, files, and

applications. Use this feature to deploy your website applications to another location or to back up your files quickly

and easily. You manage CAR files using the Packaging & Deployment > ColdFusion Archives area of the

ColdFusion Administrator.

You can deploy your website applications from ColdFusion 8, ColdFusion 9, and ColdFusion 10 to ColdFusion 10.

• Migration: You can migrate code from ColdFusion 8 and ColdFusion 9 to ColdFusion 10.

Interoperability with Microsoft Office 2010

ColdFusion 10 supports interoperability with Office 2010 for Microsoft Word 2010 and Microsoft PowerPoint 2010,

subject to OpenOffice restrictions.

ColdFusion image enhancements

• An optional attribute interpolation has been added to cfimage action = "resize" for resampling.

You can specify a specific interpolation algorithm by name (for example, hamming), by image quality (for example,

mediumQuality), or by performance (for example, highestPerformance).

The following are the valid values: highestQuality (default), highQuality, mediumQuality,

highestPerformance, highPerformance, mediumPerformance, nearest, bilinear, bicubic, bessel,

blackman, hamming, hanning, hermite, lanczos, mitchell, and quadratic.

• The attribute name supported for cfimage action = "captcha", now results in the following change of

behavior:

• If destination is specified, image is written to the file (based on the absolute or relative pathname you specify).

Page 207: cf10betafeatures

205COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

• If name is specified, image is written to the image variable.

• If destination or name is not specified, image is written to the browser.

• The function imageDrawText now returns a struct that contains width of the text drawn and the height of the text

drawn.

• Fallback to system font for cfimage action = "captcha":

If the value you specify for fonts is not available, the enhancement facilitates fallback to system fonts instead of

error (which was the behavior in ColdFusion 9).

• New function imageCreateCaptcha.

imageCreateCaptcha

Description

Create a Completely Automated Public Turing test to tell Computers and Humans Apart (CAPTCHA) image, a

distorted text image that is human-readable, but not machine-readable, used in a challenge-response test for

preventing spam.

Returns

Image object

Syntax

imageCreateCaptcha (height, width, text)

imageCreateCaptcha (height, width, text [, difficulty])

imageCreateCaptcha (height, width, text [, difficulty, fonts, fontsize)

Properties

Parameter Description

height Required. Height in pixels of the image.

width Required. Width in pixels of the image.

text Required. Text string displayed in the CAPTCHA image. Use capital letters for better readability. Do not

include spaces because users cannot detect them in the resulting CAPTCHA image.

difficulty Optional. Level of complexity of the CAPTCHA text. Specify one of the following levels of text distortion:

• low

• medium

• high

font Optional. One or more valid fonts to use for the CAPTCHA text. Separate multiple fonts with commas.

ColdFusion supports only the system fonts that the JDK can recognize. For example, TTF fonts in the

Windows directory are supported on Windows.

fontsize Optional. Font size of the text in the CAPTCHA image. The value must be an integer.

Page 208: cf10betafeatures

206COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Example

<h1>ImageCreateCaptcha Method</h1> <cfset funcimg1 = ImageCreateCaptcha(35,400,"loner")> <cfimage action="writetoBrowser" source="#funcimg1#"> <cfset funcimg2 = ImageCreateCaptcha(35,400,"loner","high")> <cfimage action="writetoBrowser" source="#funcimg2#"> <cfset funcimg3 = ImageCreateCaptcha(35,400,"loner","high","serif,sansserif", "24")> <cfimage action="writetoBrowser" source="#funcimg3#">

ImageMakeColorTransparent

Description

Creates an image and sets a transparent color.

Returns

Image object

Syntax

imageColorTransparent (img, color)

History

ColdFusion 10: Added this function

Properties

Example

<cfset myImage=ImageNew("",200,110)> <!--- Set the drawing color to green. ---> <cfset ImageSetDrawingColor(myImage,"green")> <!--- Turn on antialiasing to improve image quality. ---> <cfset ImageSetAntialiasing(myImage,"on")> <!--- Draw a filled green oval on the image. ---> <cfset ImageDrawOval(myImage,5,5,190,100,"yes")> <!--- Display the image in a browser. ---> <cfoutput>PNG image<br></cfoutput> <cfset ImageWrite(myImage,"#expandpath('.')#/png.png")> <cfset myImage = ImageRead("#expandpath('.')#/png.png")> <cfimage source="#myImage#" action="writeToBrowser" > <cfset x =ImageMakeColorTransparent(myImage,"green")> <cfimage source="#x#" action="writeToBrowser" >

Parameter Description

img Required. The ColdFusion image on which this operation is performed.

color Required. The transparent color:

• Hexadecimal value of RGB color. For example, specify the color white as "##FFFFFF" or "FFFFFF".

• String value of color (for example, "black", "red", "green").

• The default value of the transparent color is "black".List of three numbers for (R,G,B) values. Each value

must be in the range 0–255.

Page 209: cf10betafeatures

207COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

ImageMakeTranslucent

Description

Create a new translucent image with given percentage of translucence.

Returns

Image object

Syntax

imageMakeTranslucent (img, percent)

Properties

Example

The following example illustrates three images with the second one translucent than first and the thrid one translucent

than the second.

<cfset myImage=ImageNew("",200,110)> <!--- Set the drawing color to green. ---> <cfset ImageSetDrawingColor(myImage,"green")> <!--- Turn on antialiasing to improve image quality. ---> <cfset ImageSetAntialiasing(myImage,"on")> <!--- Draw a filled green oval on the image. ---> <cfset ImageDrawOval(myImage,5,5,190,100,"yes")> <!--- Display the image in a browser. ---> <cfoutput>PNG image<br></cfoutput> <cfset ImageWrite(myImage,"#expandpath('.')#/png.png")> <cfset myImage = ImageRead("#expandpath('.')#/png.png")> <cfimage source="#myImage#" action="writeToBrowser" > <cfset x =ImageMakeTranslucent(myImage,50)> <cfimage source="#x#" action="writeToBrowser" > <cfset x =ImageMakeTranslucent(myImage,75)> <cfimage source="#x#" action="writeToBrowser" > <cfset x =ImageMakeTranslucent(myImage,100)> <cfimage source="#x#" action="writeToBrowser" > </body></html?

New parameters rule and alpha for the function imageOverlay

Two new parameters are available for the function imageOverlay. You can overlay one image over the other with the

following specifications:

• rule: The following are the supported values: SRC, DST_IN, DST_OUT, DST_OVER, SRC_IN, SRC_OVER, or SRC_OUT.

For details, see Java documentation.

Parameter Description

img Required. Required. The ColdFusion image on which this operation is performed.

percentage Required. The percent of translucence:

• . 0 = opaque

• 100 = transparent

Decimal values are supported.

Page 210: cf10betafeatures

208COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

• alpha: The percentage value of transparency.

Support for HTML 5 multifile input field in fileUploadAll and Form scope

The function fileUploadAll and Form scope now handle form fields with multi-file selection.

Function expandPath resolves files in custom tag directory

Files in the custom tag directory are also resolved. For instance, if there is a file test.txt in the custom tag directory

(C:\Zeus), the function (with \test.txt) returns C:\Zeus\test.txt.

Form fields with same name

Assume that the form fields have same name. In this case, ColdFusion converts the form fields as an array instead of a

list.To do this, in the Application.cfc, specify the following: this.sameformfieldsasarray = "true".The default

value is false.

Enhancements to Amazon S3 integration

Apart from performance improvements while uploading files to Amazon S3, ColdFusion 10 supports multipart upload

where files are split into multiple parts and the parts are uploaded in parallel.

To configure multipart upload support, specify the following settings in the Application.cfc:

this.s3.minsizeformultipart=filesize _in_MB

The size you specify is treated as minimum, above which file upload is performed as multipart upload. This option is

helpful when you have to upload files of huge sizes.

If you forget Administrator password or Administrator component password

1 Go to the folder cfusion\bin.

2 Do the following:

• On Windows: Run passwordreset.bat

• On Mac/Linux: Run passwordrest.sh

3 At prompt, specify the details.

Database enhancements

• Track client information

• Support for new SQL types

• Miscellaneous enhancements that include enhancements to connection validation and exception handling

Tracking client information

To enable auditing on database, while performing a database operation, you can track certain client information, such

as application name or client ID. The supported client information varies from database to database. For example,

Oracle supports client information in a table named $v_session. Other databases store it in local cache or registers.

You can send the client information using the ClientInfo attribute in the following ColdFusion tags: cfquery,

cfupdate, cfinsert, and cfstoredproc. The information sent is set before executing the query.

The following are the values supported by the ClientInfo attribute:

• AccountingInfo

Page 211: cf10betafeatures

209COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

• Action: The action performed by the query.

• ApplicationName: Application name.

• ClientHostName: The host from where the query is executed.

• ClientID: The client ID.

• ClientUser: The user ID.

• ProgramID: The program ID.

• Module: The module name.

Use the cfdbinfo tag to find the supported clientInfo properties.

Example

<cfscript> clientInfo = structNew(); clientInfo.AccountingInfo = "MyAccount_cfquery"; clientInfo.Action = "cfstoredproc_cfquery"; clientInfo.ApplicationName = "testApp_cfquery"; clientInfo.ClientHostName = "Testserver_cfquery"; clientInfo.ClientID = "testID_cfquery"; clientInfo.ClientUser = "cfadmin_cfquery"; clientInfo.ProgramID = 1234; clientInfo.Module = "test_query";

</cfscript> <cfquery name="qName" datasource="#regdatasource#" clientInfo="#clientInfo#"> Select * from employees </cfquery>

Accessing client information metadata

The cfdbinfo tag supports the ClientInfo value for the type attribute. If this value is specified, the metadata

supported for the specified data source is returned.

<CFDBINFO type="clientinfo" datasource="#regdatasource#" name="result"> <cfdump var="#result#">

Accessing client information

When you perform a database operation using the fetchclientinfo attribute, you can access the database-specific

client information. The following ColdFusion tags support the fetchclientinfo attribute: cfquery, cfinsert, and

cfstoredproc. If set to true, the attribute returns a struct with the key-value pair passed by the last query.

Example

<cfquery fetchclientinfo=true result="resultQ" datasource="#regdatasource#"> select * from employees </cfquery>

Passing client information using ColdFusion administrator

Using the ColdFusion administrator’s Data Sources Advanced Settings page, you can set the database-specific

information. If specified, the following information is sent to the database before executing the query.

• Client Hostname: The host name from where the query is executed.

• Client Username: The user name if the user is logged in using the <cflogin> tag.

• Application Name: The application name specified in the application.cfc.

Page 212: cf10betafeatures

210COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

• Prefix: If specified, the value is prefixed with the application name specified in application.cfc.

Note: If the same client info properties are specified in the query tag, it takes the precedence over the server-level settings.

New data type support for CFSQLType

The cfqueryparam and cfprocparam tags support the following SQL types:

• CF_SQL_NCHAR

• CF_SQL_NVARCHAR

• CF_SQL_LONGNVARCHAR

• CF_SQL_NCLOB

• CF_SQL_SQLXML

Miscellaneous enhancements

Following are the miscellaneous enhancements:

Validating connection before executing a query

In the ColdFusion administrator’s Data Sources Advanced Settings page, you can set the option to validate the

connection. If this option is set, ColdFusion validates the database connection before executing a query. Setting this

option can have an impact on the performance of the application.

You can optionally specify a query to validate the connection. If specified, the connection is validated based on it. If

not specified, the default mechanism is used to validate the connection.

Improved exception handling

The <cfcatch> tag’s type=database property is improved for better exception handling.

The #CFCATCH.exceptions# provides details in a list of structs. If multiple exceptions are thrown, it provides multiple

elements. Each element provides information in the following categories: class, messages, and list of causes (if any).

Example

<cftry> <cfquery datasource="badmysql" timeout="2">

Select * from employees </cfquery>

<cfcatch type="database"> <cfdump var="#cfcatch#">

</cfcatch> </cftry>

ColdFusion Administrator enhancements

Server update

Verify if there are any product updates using the ColdFusion Administrator (Server Update > Update). The updates

can include hot fixes and security hot fixes for ColdFusion 10.

Page 213: cf10betafeatures

211COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

The Updates page has the following options:

• Available updates: Click Check for Updates to see if any updates are available for installation.

For a multi-server setup, when you apply the updates from the main instance, you have option to select all local

instances to which you may opt to apply hot fix. By default, update applies only to the main instance.

If you apply the updates from a newly created local instance, the hot fix is applied only to that specific instance. You

have to apply the hot fix to other instances from the main instance or individually from each instance. Before the

update, the main ColdFusion instance automatically stops. But you have to manually stop all other instances (for

which you want to apply the updates).

You can either

• Download: Downloads and places the file in <cf_home>/hf-updates/ for later installation. For details, see

“Download hot fix for later installation” on page 212

• Download and install: Downloads the hot fix and performs a silent installation.

Note: This option does not apply to J2EE installations. Also, in the case of multi-server installations, you have to

select the server on which you want to install the hot fix.

• Installed updates: Lists all updates to ColdFusion 10 that you have installed. For multi-server setup, it shows the

list of updates to the instance to which you have logged in from the ColdFusion Administrator.

Use the option Uninstall to remove the installed hot fix (if needed).

• Settings: Provides options to specify update preferences such as update notifications or if to automatically check

for updates.

If you have set up a local update site, you can also specify URL of that site to get updates.

To do this, populate the updates.xml (see the following sample) and then update the URL in the Administrator

(Server Update > Updates > Settings > Update Site > Site URL). For example, http://IP

Address:Port/updates/updates.xml.

The following is a sample updates.xml:

Page 214: cf10betafeatures

212COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

<?xml version="1.0" encoding="UTF-8"?> <rss version="2.0"> <channel> <title>ColdFusion_Zeus_Update</title> <description>Upload_description</description> <item> <title>Hot_Fix_Name</title> <description>Hotfix_Description</description> <pubDate>Tue, 19 Oct 2011 11:09:11 -0400</pubDate> <cfhf_id>HotFix_ID</cfhf_id> <cfhf_type>Cumulative</cfhf_category> <cfhf_updatelevel>Integer indicating Hotfix Chronology</cfhf_updatelevel> <cfhf_filename>Hotfix_installer_file_name</cfhf_filename> <cfhf_technotelink>Link_to_Technote</cfhf_technotelink> <cfhf_servers> <cfhf_server version="10,0,0"> <cfhf_downloadlink>http://localhost:8500/updates/install060811.jar</cfhf_downloadlink> <cfhf_checksum>20f33dd56597b68c3634be08116bc84a</cfhf_checksum> <cfhf_filename>hotfix_1.jar</cfhf_filename> <cfhf_installinput> <OPTIONAL_![CDATA[ HTML for input fields ]]> </cfhf_installinput> </cfhf_server> </cfhf_servers> </item> </channel> </rsst>

After you specify the settings, click Submit changes for the preferences to take effect.

Download hot fix for later installation

1 Ensure that JRE is in your system path, or directly access Java from the installation directory of ColdFusion.

2 Access the downloaded files from the following location:

<cf_home>/hf-updates/

3 At command prompt, do the following:

Page 215: cf10betafeatures

213COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

For standalone and multiserver installations

Platform Description

On Windows

(Installation possible

in either GUI or Silent

mode)

In GUI mode:

• At command prompt, run the following command: java -jar <jar-file-name>. This launches the hot

fix installer.

• Follow the on screen instructions.

In Silent mode:

• At command prompt, run the following command:java -jar <jar-file-name> -i silent -f

<install_properties_file_path>. Installation occurs silently.

The following is a sample properties file:

INSTALLER_UI=SILENT USER_INSTALL_DIR=<ColdFusion_Home> DOC_ROOT=<ColdFusion_Home>/cfusion/wwwroot #The following applies only to multi server scenarios. INSTANCE_LIST=cfusion,cfusion1

On

Linux/Solaris/UNIX

(Installation possible

in either console or

silent mode)

In Console mode:

• At command prompt, run the following command:java -jar <jar-file-name>. The console appears

with instructions.

• Follow the instructions provided in the console.

In Silent mode:

• At command prompt, run the following command:java -jar <jar-file-name> -i silent -f

<install_properties_file_path>. Installation occurs silently.

The following is a sample properties file:

INSTALLER_UI=SILENT USER_INSTALL_DIR=<ColdFusion_Home> DOC_ROOT=<ColdFusion_Home>/cfusion/wwwroot #The following applies only to multi server scenarios. INSTANCE_LIST=cfusion,cfusion1

On Mac OSX

(Installation possible

in either GUI, Silent,

or Console mode)

In GUI mode:

• At command prompt, run the following command:java -jar <jar-file-name> -i GUI. This launches

the hot fix installer.

• Follow the on screen instructions.

In Console mode:

• At command prompt, run the following command: java -jar <jar-file-name>. The console appears

with instructions.

• Follow the instructions provided in the console.

In Silent mode:

• At command prompt, run the following command:java -jar <jar-file-name> -i silent -f

<install_properties_file_path>. Installation occurs silently.

The following is a sample properties file:

INSTALLER_UI=SILENT USER_INSTALL_DIR=<ColdFusion_Home> DOC_ROOT=<ColdFusion_Home>/cfusion/wwwroot #The following applies only to multi server scenarios. INSTANCE_LIST=cfusion,cfusion1

Page 216: cf10betafeatures

214COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

By default, after applying the hotfix, servers are restarted. If you do not want the servers to restart, additionally, provide

the following command:

• For console and GUI mode: Run the following argument : DDONOT_START_SERVERS_POST_INSTALL=true

• For silent installation: Add the property DONOT_START_SERVERS_POST_INSTALL=true to the properties file.

Page 217: cf10betafeatures

215COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

For J2EE installations

Page 218: cf10betafeatures

217COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Platform Description

On Windows

(Installation possible

in either GUI or Silent

mode)

In GUI mode (for exploded EAR/WAR deployment):

• At command prompt, run the following command:java -jar <jar-file-name>. This launches the hot

fix installer.

• Follow the on screen instructions.

In GUI mode (for unexploded EAR/WAR deployment):

• At command prompt, run the following command:java -jar <jar-file-name> -

DINSTALL_FILES_OUTSIDE_CF=true. This launches the hot fix installer.

• Follow the on screen instructions.

In Silent mode (for exploded EAR/WAR deployment):

• At command prompt, run the following command:java -jar <jar-file-name> -i silent -f

<install_properties_file_path>. Installation occurs silently.

The following is a sample properties file:

INSTALLER_UI=SILENT #For the following, specify the folder that contains META-INF folder which contains application.xml USER_INSTALL_DIR=<ColdFusion_Deployment_Root_Path>

In Silent mode (for unexploded EAR/WAR deployment):

Firstly, install the hotfix files outside your EAR/WAR on your system and then manually update the EAR/WAR.

• At command prompt, run the following command:java -jar <jar-file-name> -i silent -f

<install_properties_file_path>Installation occurs silently.

The following is a sample properties file:

INSTALLER_UI=SILENT USER_INSTALL_DIR=<Any directory on your system> INSTALL_FILES_OUTSIDE_CF=true

Page 219: cf10betafeatures

218COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

On

Linux/Solaris/UNIX

(Installation possible

in either console or

silent mode)

In Console mode (for exploded EAR/WAR deployment):

• At command prompt, run the following command:java -jar <jar-file-name>. The console appears

with instructions.

• Follow the instructions provided in the console.

In Console mode (for unexploded EAR/WAR deployment):

• At command prompt, run the following command: java -jar <jar-file-name> -

DINSTALL_FILES_OUTSIDE_CF=true. The console appears with instructions.

• Follow the instructions provided in the console.

In Silent mode (for exploded EAR/WAR deployment):

• At command prompt, run the following command: java -jar <jar-file-name> -i silent -f

<install_properties_file_path>. Installation occurs silently.

The following is a sample properties file:

INSTALLER_UI=SILENT #For the following, specify the folder that contains META-INF folder which contains application.xml USER_INSTALL_DIR=<ColdFusion_Deployment_Root_Path>

In Silent mode (for unexploded EAR/WAR deployment):

Firstly, you have to install the hotfix files outside your EAR/WAR on your system and then manually update the

EAR/WAR.

• At command prompt, run the following command:java -jar <jar-file-name> -i silent -f

<install_properties_file_path>Installation occurs silently.

The following is a sample properties file:

INSTALLER_UI=SILENT USER_INSTALL_DIR=<Any directory on your system> INSTALL_FILES_OUTSIDE_CF=true

Platform Description

Page 220: cf10betafeatures

219COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Note: When you create a new instance from ColdFusion Administrator, hot fixes applied to the default instance is

automatically applied to the new instance that you create.

Scheduler

Scheduling tasks feature (Server Settings > Scheduled Tasks) has been enhanced in this release. The following sections

provide the details:

On Mac OSX

(Installation possible

in either GUI, Silent,

or Console mode)

In GUI mode (for exploded EAR/WAR deployment):

• At command prompt, run the following command:java -jar <jar-file-name> -i GUIThis launches

the hot fix installer.

• Follow the on screen instructions.

In GUI mode (for unexploded EAR/WAR deployment):

• At command prompt, run the following command:java -jar <jar-file-name> -

DINSTALL_FILES_OUTSIDE_CF=true -i GUI. This launches the hot fix installer.

• Follow the on screen instructions.

In Console mode (for exploded EAR/WAR deployment):

• At command prompt, run the following command:java -jar <jar-file-name>The console appears with

instructions.

• Follow the instructions provided in the console.

In Console mode (for unexploded EAR/WAR deployment):

• At command prompt, run the following command:java -jar <jar-file-name> -

DINSTALL_FILES_OUTSIDE_CF=true. The console appears with instructions.

• Follow the instructions provided in the console.

In Silent mode (for exploded EAR/WAR deployment):

• At command prompt, run the following command:java -jar <jar-file-name> -i silent -f

<install_properties_file_path>. Installation occurs silently.

The following is a sample properties file:

INSTALLER_UI=SILENT #For the following, specify the folder that contains META-INF folder which contains application.xml USER_INSTALL_DIR=<ColdFusion_Deployment_Root_Path>

In Silent mode (for unexploded EAR/WAR deployment):

First, you have to install the hotfix files outside your EAR/WAR on your system and then manually update the

EAR/WAR.

• At command prompt, run the following command:java -jar <jar-file-name> -i silent -f

<install_properties_file_path>Installation occurs silently.

The following is a sample properties file:

INSTALLER_UI=SILENT USER_INSTALL_DIR=<Any directory on your system> INSTALL_FILES_OUTSIDE_CF=true

Platform Description

Page 221: cf10betafeatures

220COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Scheduled tasks

• Application Level Scheduled Tasks: Provides a list of application-specific tasks that you have scheduled, with task

details in tabular format.

The table provides details such as actions, application name, group, task name, duration, interval, last run, next run,

repeat count, and if cluster is enabled.

Note: Application-specific tasks cannot be created using ColdFusion Administrator. But you can pause, resume, or

delete the tasks.

• Server Level Scheduled Tasks: Provides a list of server-specific tasks that you have scheduled, with task details in

tabular format.

The table provides new details such as group, next run, repeat count, if cluster is enabled, and the remaining task

count.

• Enable Cluster Setup: Applies if you have at least one data source configured. Specify the following details:

• Select Data source: All the data sources you have connected to are listed.

• Create Tables for Cluster Setup: Check to create scheduler-specific tables for cluster.

Note: Enable this option only for one node in the cluster. Otherwise, the tables are overridden. If you have created

tables from one node, in other nodes you need to only select and choose the data source. All nodes will point to the

same data source and therefore will be part of the cluster.

• After you specify the details, click Submit.

To disable cluster, select the option Disable Cluster.

Schedule new tasks

The Schedule New Tasks page lets you add or edit task. Click Submit after you specify the following tasks. When the

page loads for the first time, you are provided with only minimum options to create the task. Click Show Additional

tasks to list all settings.

Note: The following table provides details of only the new options in ColdFusion 10.

Filed Description

Group The group to which the scheduled tasks belong. Ensure that the combination of task name and group

are unique.

Crontime Specify task scheduling time in cron job syntax.

Overwrite If not selected, creates new output files every time the task executes.

Select to overwrite the existing output file, instead of creating a new one.

Note that Publish file in schedule tasks can now only have TXT and .log extensions by default. You can

add more extensions in cfusion\lib\neo-cron xml.

Eventhandler A CFC file whose pre-defined methods are invoked for various events while running the task.

The path you specify must be relative to webroot. For example, schedulerdemo.eventhandler.

Exclude Comma-separated list of dates or date range for exclusion in the schedule period.

On Misfire Specify what the server has to do if a scheduled task misfires.

On Exception Specify what to do if a task results in error.

Page 222: cf10betafeatures

221COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Securing search system

You can make Solr an HTTPS secured server as follows:

1 In the ColdFusion Administrator, go to Data & Services > Solr Server.

2 In the Configure Solr Server section, click Show Advanced Settings.

3 Check Use HTTPs connection and specify the Solr Administrator HTTPS port.

Caching enhancements

Use Internal Cache to store queries

An option Use internal cache to store queries has been added to the Caching page (Server Settings > Caching).

When you select this option, at server level, internal cache is used to store cached queries. By default, cached queries

are stored in QUERY region supported by Ehcache.

Clearing query cache

❖ In the Server Settings > Caching section, click Clear Query Cache Now to remove the query cache in the server.

Note: You can also use the function removeCachedQuery.

Clearing folder-specific template cache

In the previous releases, you have the option only to clear the trusted cache, which clears the entire system cache. Now

you can limit the clearing to folder level.

1 Go to Server Settings > Caching > Clear folder-specific template cache.

2 In the Select folder text box, click Browse Server and then select the folder to clear the template cache.

3 Click Clear Template Cache of specific folder.

Web services

Specifying the Axis version

ColdFusion 10 supports Axis 2 web service. To specify the option using ColdFusion Administrator,

1 Go to Data & Services > Web Services.

2 In the web service version section, select either 1 or 2.

Note: You can also specify the settings using the wsconfig attribute in cfcomponent.

On Complete The action to be performed after the completion of current task. Specify the details in the following

format:

Task1:Group1,Task3:Group3

Priority An integer that indicates the priority of the task.

Retry Count The number of reattempts if the task results in an error.

Cluster Enable to execute tasks in cluster setup.

Filed Description

Page 223: cf10betafeatures

222COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Specifying the Proxy server details

You can specify the details of the proxy server required to access the web service URL. This includes the details such

as the proxy server name, port, authentication details of the user, and the time-out for the web service request in

seconds.

Use the section Add/Edit ColdFusion Web Service (Data & Services > Web Services).

Note: In the previous release, you had to set these options using cfinvoke tag.

Registering RESTful web services

For details, see “Registering an application with REST service” on page 148.

RDS can be enabled from ColdFusion Administrator

In the previous releases of ColdFusion, RDS settings you make at the time of installation cannot be revoked. You have

to reinstall ColdFusion to change the settings.

In ColdFusion 10, you can enable/disable RDS using ColdFusion Administrator. That is, you can modify the settings

that you made at the time of installation using ColdFusion Administrator.

RDS Page

The RDS page (Security > RDS) lets you enable/disable RDS service.

Disable dumping of application scope of unnamed applications

The new option in the Server Settings page lets you disable dumping of application scope of unnamed applications.

Accessing the ColdFusion Administrator

If you are using the Developer Edition of ColdFusion, in the previous releases, only two IP addresses are allowed to

access ColdFusion Administrator concurrently. Even if either or both of the IP addresses do not access ColdFusion

Administrator, a third IP address is denied the right.

In this release, access is permitted to any two IP addresses concurrently. For example, Client1 and Client2 already have

access to ColdFusion Administrator. When either Client1 or Client2 does not access ColdFusion Administrator,

Client3 is allowed access.

Restricting access to ColdFusion Administrator

You can restrict access to ColdFusion Administrator.

Note: By default, localhost and all IP addresses can access ColdFusion server.

To add IP addresses that must be allowed access:

1 Go to Security > Allowed IP Addresses > Add/Remove IP Addresses which will have Administrator access.

2 In the IP Address text box, specify the IP addresses.

3 Click Add.

4 Repeat the procedures to add more IP addresses.

Regular expressions are supported. That is, if you specify 10.*.*.*, all IP addresses starting with 10. are allowed

access.

Page 224: cf10betafeatures

223COLDFUSION 10 BETA

ColdFusion 10 Beta New Feature Notes

Last updated 2/17/2012

Logging Administrator actions

By default all major ColdFusion Administrator actions are logged. The log contains details that include current user,

date, time, and action taken.

Note that the logs cover only high-level actions such as the following:

<timestamp>: <Username>: <deleted data source name>

The default log location is cfusion\logs\audit.log.

Changes to the default settings

The following default settings in the previous releases of ColdFusion have been revised in this release:

Session cookie settings

The following settings can be made at the server level using ColdFusion Administrator (Server Settings > Memory

Variables > Session Cookie Settings).

Adobe recommends that you use the new settings.

Area/UI Path Previous value New value

Client variable storage name Server Settings > Client Variables > Select Default

Storage Mechanism for Client Sessions

Registry Cookie

Use UUID for cftoken Server Settings > Settings Unchecked Checked

Enable Global Script Protection Server Settings > Settings Unchecked Checked

Maximum number of simultaneous

Template requests

Server Settings > Request Tuning > Request Limits 10 25

Maximum number of simultaneous CFC

function requests

Server Settings > Request Tuning > Request Limits 10 15

Minimum JVM Heap Size (MB) Server Settings > Java and JVM 256

Maximum size of post data (in MB) Server Settings > Settings > Request Size Limits 100 20

Enable ColdFusion Event Gateway

Services

Event Gateways > Settings Checked Unchecked

Setting Default

HTTPONLY session cookie Checked

Secure Session cookie Unchecked

Session cookie timeout Maximum of 30 years and minimum of two minutes.