0% found this document useful (0 votes)
15 views140 pages

C Client Guide

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views140 pages

C Client Guide

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 140

SonicMQ®

C Client Guide
Aurea SonicMQ® C Client Guide 2013
Copyright © 2013 Aurea, Inc. All Rights Reserved. These materials and all Aurea Software, Inc. software products are
copyrighted and all rights are reserved by Aurea, Inc. This document is proprietary and confidential. No part of this
document may be disclosed in any manner to a third party without the prior written consent of Aurea Software, Inc. The
information in these materials is subject to change without notice, and Aurea Software, Inc. assumes no responsibility for
any errors that may appear therein.
Actional®, Actional (and design)®, SOAPscope®, SOAPstation®, Mindreef®, DataXtend®, Savvion®, Savvion (and
design)®, Savvion BusinessManager®, Dynamic Routing Architecture®, Sonic®, Sonic ESB®, Sonic Integration
Workbench®, Sonic Orchestration Server®, SonicMQ®, and SonicXQ® are registered trademarks of Aurea, Inc., in the
U.S. and/or other countries. Actional Agent™, Actional Intermediary™, Actional Management Server™, DataXtend
Semantic Integrator™, Pantero™, Savvion BizLogic™, Savvion BizPulse™, Savvion BizRules™, Savvion BizSolo™,
Savvion BPM Portal™, Savvion BPM Studio™, Savvion BusinessExpert™, Savvion BusinessManager™, Savvion Process
Asset Manager™, ProcessEdge™, Savvion Process Modeler™, Sonic Continuous Availability Architecture™, Sonic
Database Service™, and Sonic Workbench™ are trademarks or service marks of Aurea, Inc., in the U.S. and other countries.
Oracle and Java are registered trademarks of Oracle and/or its affiliates.
All other marks contained herein are for informational purposes only and may be trademarks of their respective owners.

Third Party Acknowledgments: One or more products in the Aurea Sonic 2013 release includes third party components
covered by licenses that require that the following documentation notices be provided:
Aurea Sonic 2013 incorporates Another Tool for Language Recognition v2.7.4. Such technologies are subject to the
following terms and conditions: ANTLR Software License [Link] We reserve no legal rights to
the ANTLR--it is fully in the public domain. An individual or company may do whatever they wish with source code
distributed with ANTLR or the code generated by ANTLR, including the incorporation of ANTLR, or its output, into
commercial software. We encourage users to develop software with ANTLR. However, we do ask that credit is given to us
for developing ANTLR. By "credit", we mean that if you use ANTLR or incorporate any source code into one of your
programs (commercial product, research project, or otherwise) that you acknowledge this fact somewhere in the
documentation, research report, etc... If you like ANTLR and have developed a nice tool with the output, please mention that
you developed it using ANTLR. In addition, we ask that the headers remain intact in our source code. As long as these
guidelines are kept, we expect to continue enhancing this system and expect to make other tools available as they are
completed.
Aurea Sonic 2013 incorporates Apache Ant-Contrib 1.0B3. Such technology is subject to the following terms and
conditions: The Apache Software License, Version 1.1 - Copyright (c) 2001-2003 Ant-Contrib project. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following
conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the
following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions
and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The end-user
documentation included with the redistribution, if any, must include the following acknowledgement: "This product
includes software developed by the Ant-Contrib project ([Link] Alternately, this
acknowledgement may appear in the software itself, if and wherever such third-party acknowledgements normally appear.
4. The name Ant-Contrib must not be used to endorse or promote products derived from this software without prior written
permission. For written permission, please contact ant-contrib-developers@[Link]. 5. Products derived from
this software may not be called "Ant-Contrib" nor may "Ant-Contrib" appear in their names without prior written permission
of the Ant-Contrib project. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE ANT-CONTRIB
PROJECT OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Aurea Sonic2013 incorporates [Link], [Link], [Link],
[Link], [Link] from Sun Microsystems, Inc. These technologies are subject to the
following terms and conditions: Copyright 2000-2002 Sun Microsystems, Inc. All Rights Reserved. Redistribution and use
in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
-Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
-Redistribution in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the distribution. Neither the name of
Sun Microsystems, Inc. or the names of contributors may be used to endorse or promote products derived from this software
without specific prior written permission. This software is provided "AS IS," without a warranty of any kind. ALL
EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY IMPLIED
WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT,
ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES OR
LIABILITIES SUFFERED BY LICENSEE AS A RESULT OF OR RELATING TO USE, MODIFICATION OR
DISTRIBUTION OF THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE
LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE
THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. You acknowledge that Software is not designed,
licensed or intended for use in the design, construction, operation or maintenance of any nuclear facility.
Aurea Sonic 2013 incorporates Colt [Link]* packages v1.0.3 (ca1420-20040626). Such technology is subject to the
following terms and conditions: Packages [Link] , [Link]*, [Link] - Copyright (c) 1999 CERN - European
Organization for Nuclear Research. Permission to use, copy, modify, distribute and sell this software and its documentation
for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both
that copyright notice and this permission notice appear in supporting documentation. CERN makes no representations about
the suitability of this software for any purpose. It is provided "as is" without expressed or implied warranty.
Aurea Sonic 2013 incorporates Crimson v1.1.3. Such technology is subject to the following terms and conditions: The
Apache Software License, Version 1.1. Copyright (c) 1999-2003 The Apache Software Foundation. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following
conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the
following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The end-user
documentation included with the redistribution, if any, must include the following acknowledgment: "This product includes
software developed by the * Apache Software Foundation ([Link] Alternately, this acknowledgment
may appear in the software itself, if and wherever such third-party acknowledgments normally appear. 4. The names
"Xerces" and "Apache Software Foundation" must not be used to endorse or promote products derived from this software
without prior written permission. For written permission, please contact apache@[Link]. 5. Products derived from this
software may not be called "Apache", nor may "Apache" appear in their name, without prior written * permission of the
Apache Software Foundation. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE
SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
====================================================================
This software consists of voluntary contributions made by many individuals on behalf of the Apache Software Foundation
and was originally based on software copyright (c) 1999, International Business Machines, Inc., [Link] For
more information on the Apache Software Foundation, please see <[Link]
Aurea Sonic 2013 incorporates DSTC Xs3P version 1.1 from DSTC Pty Ltd. Aurea will, at Licensee's request, provide
copies of the source code for this third party technology, including modifications, if any, made by Aurea. Aurea may charge
reasonable shipping and handling charges for such distribution. Licensee may also obtain the source code through
[Link] by following the instructions set forth therein. - DSTC Public License. The contents of this
file are subject to the DSTC Public License Version 1.1 (the 'License') (provided herein); you may not use this file except in
compliance with the License. Software distributed under the License is distributed on an 'AS IS' basis, WITHOUT
WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and
limitations under the License. The Original Code is xs3p. The Initial Developer of the Original Code is DSTC. Portions
created by DSTC are Copyright (c) 2001, 2002 DSTC Pty Ltd. All Rights Reserved.
Aurea Sonic 2013 incorporates Jing 20030619 and Trang 20030619. Such technology is subject to the following terms and
conditions: Copyright (c) 2002, 2003 Thai Open Source Software Center Ltd. All rights reserved. Redistribution and use in
source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the distribution. Neither the name of the Thai Open Source
Software Center Ltd nor the names of its contributors may be used to endorse or promote products derived from this software
without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Aurea Sonic 2013 incorporates Model Objects Framework v2.0 from ModelObjects Group. Such technology is subject to
the following terms and conditions: The ModelObjects Group Software License, Version 1.0 - Copyright (c) 2000-2001
ModelObjects Group. All rights reserved. Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above
copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the
above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials
provided with the distribution. 3. The end-user documentation included with the redistribution, if any, must include the
following acknowledgement: "This product includes software developed by the ModelObjects Group
([Link] Alternatively, this acknowledgement may appear in the software itself, if and wherever
such third-party acknowledgements normally appear. 4. The name "ModelObjects" must not be used to endorse or promote
products derived from this software without prior written permission. For written permission, please contact
djacobs@[Link]. 5. Products derived from this software may not be called "ModelObjects", nor may
ModelObjects" appear in thier name, without prior written permission of the ModelObjects Group. THIS SOFTWARE IS
PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE MODEL OBJECTS GROUP OR ITS CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
Aurea Sonic 2013 incorporates Mozilla Rhino v1.5R3. The contents of this file are subject to the Netscape Public License
Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the
License at [Link] and a copy is provided below. Software distributed under the License is distributed
on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific
language governing rights and limitations under the License. The Original Code is Mozilla Communicator client code,
released March 31, 1998. The Initial Developer of the Original Code is Netscape Communications Corporation. Portions
created by Netscape are Copyright (C) 1998-1999 Netscape Communications Corporation. All Rights Reserved. Aurea
will, at Licensee's request, provide copies of the source code for this third party technology, including modifications, if any,
made by Aurea. Aurea may charge reasonable shipping and handling charges for such distribution. Licensee may also obtain
the source code through [Link] by following the instructions set forth therein.
Aurea Sonic 2013 incorporates NET Security Library v1.0. Such technologies are subject to the following terms and
conditions: Copyright (c) 2002-2003, The KPD-Team All rights reserved. [Link] Redistribution and use
in source and binary forms, with or without modification, are permitted provided that the following conditions are met: -
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. -
Neither the name of the KPD-Team, nor the names of its contributors may be used to endorse or promote products derived
from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT
HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE. Copyright (c) 2002-2003, The KPD-Team.
Aurea Sonic 2013 incorporates OpenSAML Java Distribution v1.0.1. Such technology is subject to the following terms and
conditions: The OpenSAML License, Version 1. Copyright (c) 2002 - University Corporation for Advanced Internet
Development, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are
permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided
with the distribution, if any, must include the following acknowledgment: "This product includes software developed by the
University Corporation for Advanced Internet Development [Link] Internet2 Project. Alternately, this
acknowledgement may appear in the software itself, if and wherever such third-party acknowledgments normally appear.
Neither the name of OpenSAML nor the names of its contributors, nor Internet2, nor the University Corporation for
Advanced Internet Development, Inc., nor UCAID may be used to endorse or promote products derived from this software
without specific prior written permission. For written permission, please contact opensaml@[Link]. Products
derived from this software may not be called OpenSAML, Internet2, UCAID, or the University Corporation for Advanced
Internet Development, nor may OpenSAML appear in their name, without prior written permission of the University
Corporation for Advanced Internet Development. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
AND CONTRIBUTORS "AS IS" AND WITH ALL FAULTS. ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT ARE DISCLAIMED AND THE ENTIRE RISK OF
SATISFACTORY QUALITY, PERFORMANCE, ACCURACY, AND EFFORT IS WITH LICENSEE. IN NO EVENT
SHALL THE COPYRIGHT OWNER, CONTRIBUTORS OR THE UNIVERSITY CORPORATION FOR ADVANCED
INTERNET DEVELOPMENT, INC. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Aurea Sonic 2013 incorporates OpenSSL toolkit v0.9.8i. Such technologies are subject to the following terms and
conditions: LICENSE ISSUES ============== The OpenSSL toolkit stays under a dual license, i.e. both the conditions
of the OpenSSL License and the original SSLeay license apply to the toolkit. See below for the actual license texts. Actually
both licenses are BSD-style Open Source licenses. In case of any license issues related to OpenSSL please contact
openssl-core@[Link].
OpenSSL License ---------------
====================================================================
Copyright (c) 1998-2008 The OpenSSL Project. All rights reserved. Redistribution and use in source and binary forms, with
or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided with the distribution.
3. All advertising materials mentioning features or use of this software must display the following acknowledgment: "This
product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit. ([Link]
4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to endorse or promote products derived from
this software without prior written permission. For written permission, please contact openssl-core@[Link].
5. Products derived from this software may not be called "OpenSSL" nor may "OpenSSL" appear in their names without
prior written permission of the OpenSSL Project.
6. Redistributions of any form whatsoever must retain the following acknowledgment: "This product includes software
developed by the OpenSSL Project for use in the OpenSSL Toolkit ([Link] THIS SOFTWARE IS
PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR ITS
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
====================================================================
This product includes cryptographic software written by Eric Young (eay@[Link]). This product includes software
written by Tim Hudson (tjh@[Link]).
Original SSLeay License ----------------------- Copyright (C) 1995-1998 Eric Young (eay@[Link]) All rights
reserved. This package is an SSL implementation written by Eric Young (eay@[Link]). The implementation was
written so as to conform with Netscapes SSL. This library is free for commercial and non-commercial use as long as the
following conditions are aheared to. The following conditions apply to all code found in this distribution, be it the RC4,
RSA, lhash, DES, etc., code; not just the SSL code. The SSL documentation included with this distribution is covered by
the same copyright terms except that the holder is Tim Hudson (tjh@[Link]). Copyright remains Eric Young's, and
as such any Copyright notices in the code are not to be removed. If this package is used in a product, Eric Young should be
given attribution as the author of the parts of the library used. This can be in the form of a textual message at program startup
or in documentation (online or textual) provided with the package. Redistribution and use in source and binary forms, with
or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided with the distribution.
3. All advertising materials mentioning features or use of this software must display the following acknowledgement: "This
product includes cryptographic software written by Eric Young (eay@[Link])" The word 'cryptographic' can be left
out if the rouines from the library being used are not cryptographic related :-).
4. If you include any Windows specific code (or a derivative thereof) from the apps directory (application code) you must
include an acknowledgement: "This product includes software written by Tim Hudson (tjh@[Link])" THIS
SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE. The licence and distribution terms for any publically available version or derivative
of this code cannot be changed. i.e. this code cannot simply be copied and put under another distribution licence [including
the GNU Public Licence.]
Aurea Sonic 2013 incorporates Saxon XSLT and XQuery Processor v8.9.0.4 from Saxonica Limited
([Link] which is available from SourceForge ([Link] Aurea will, at
Licensee's request, provide copies of the source code for this third party technology, including modifications, if any, made
by Aurea. Aurea may charge reasonable shipping and handling charges for such distribution. Licensee may also obtain the
source code through [Link] by following the instructions set forth therein. - Mozilla Public License
Version 1.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the
License at [Link] and it is provided below. Software distributed under the License is distributed on
an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific
language governing rights and limitations under the License. The Original Code of Saxon comprises all those components
which are not explicitly attributed to other parties. The Initial Developer of the Original Code is Michael Kay. Until
February 2001 Michael Kay was an employee of International Computers Limited (now part of Fujitsu Limited), and
original code developed during that time was released under this license by permission from International Computers
Limited. From February 2001 until February 2004 Michael Kay was an employee of Software AG, and code developed
during that time was released under this license by permission from Software AG, acting as a "Contributor". Subsequent
code has been developed by Saxonica Limited, of which Michael Kay is a Director, again acting as a "Contributor". A small
number of modules, or enhancements to modules, have been developed by other individuals (either written specially for
Saxon, or incorporated into Saxon having initially been released as part of another open source product). Such contributions
are acknowledged individually in comments attached to the relevant code modules. All Rights Reserved.
Aurea Sonic 2013 incorporates Xalan Java XSLT Parser v2.4.1 from the Apache Foundation. Such technology is subject to
the following terms and conditions: The Apache Software License, Version 1.1 - Copyright (c) 1999 The Apache Software
Foundation. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are
permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided
with the distribution. 3. The end-user documentation included with the redistribution, if any, must include the following
acknowledgment: "This product includes software developed by the Apache Software Foundation
([Link] Alternately, this acknowledgment may appear in the software itself, if and wherever such
third-party acknowledgments normally appear. 4. The names "Xalan" and "Apache Software Foundation" must not be used
to endorse or promote products derived from this software without prior written permission. For written permission, please
contact apache@[Link]. 5. Products derived from this software may not be called "Apache", nor may "Apache" appear
in their name, without prior written permission of the Apache Software Foundation. THIS SOFTWARE IS PROVIDED
``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
===============================================================
This software consists of voluntary contributions made by many individuals on behalf of the Apache Software Foundation
and was originally based on software copyright (c) 1999, Lotus Development Corporation., [Link] For more
information on the Apache Software Foundation, please see <[Link]
Aurea Sonic 2013 incorporates Xerces v2.6.2 from the Apache Foundation. Such technology is subject to the following
terms and conditions: The Apache Software License, Version 1.1 - Copyright (c) 1999-2004 The Apache Software
Foundation. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are
permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided
with the distribution. 3. The end-user documentation included with the redistribution, if any, must include the following
acknowledgment: "This product includes software developed by the Apache Software Foundation
([Link] Alternately, this acknowledgment may appear in the software itself, if and wherever such
third-party acknowledgments normally appear. 4. The names "Xerces" and "Apache Software Foundation" must not be used
to endorse or promote products derived from this software without prior written permission. For written permission, please
contact apache@[Link]. 5. Products derived from this software may not be called "Apache", nor may "Apache" appear
in their name, without prior written permission of the Apache Software Foundation. THIS SOFTWARE IS PROVIDED
``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
===============================================================
This software consists of voluntary contributions made by many individuals on behalf of the Apache Software Foundation
and was originally based on software copyright (c) 1999, International Business Machines, Inc., [Link] For
more information on the Apache Software Foundation, please see <[Link]
Aurea Sonic 2013 incorporates Progress DataDirect Connect for JDBC v5.1 and Progress DataDirect Connect XE for JDBC
v5.1 which incorporates HyperSQL database v1.8.0.10 from The HSQL Development Group. Such technology is subject
to the following terms and conditions: Copyright (c) 2001-2005, The HSQL Development Group All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following
conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the
following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the
HSQL Development Group nor the names of its contributors may be used to endorse or promote products derived from this
software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, [Link], OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Aurea Sonic 2013 incorporates Woodstox v3.2.8 and 4.1.2 which incorporates Stax2 API v3.1.1. Such technology is subject
to the terms and conditions of the following licenses: Copyright (c) 2004-2010, Woodstox Project
([Link] All rights reserved. Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the
above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce
the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials
provided with the distribution. 3. Neither the name of the Woodstox XML Processor nor the names of its contributors may
be used to endorse or promote products derived from this software without specific prior written permission. THIS
SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Aurea Sonic 2013 incorporates JAXB v2.1.13. Such technology is subject to the following terms and conditions: Jing
Copying Conditions Copyright (c) 2001-2003 Thai Open Source Software Center Ltd. All rights reserved. Redistribution
and use in source and binary forms, with or without modification, are permitted provided that the following conditions are
met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following
disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the
Thai Open Source Software Center Ltd nor the names of its contributors may be used to endorse or promote products derived
from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT
HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
Aurea Sonic 2013 incorporates ASM 3.3.1 from Inria France Telecom. Such technology is subject to the following terms
and conditions: Copyright (c) 2000-2011 INRIA, France Telecom. All rights reserved. Redistribution and use in source
and binary forms, with or without modification, are permitted provided that the following conditions are met: 1.
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright
holders nor the names of its contributors may be used to endorse or promote products derived from this software without
specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
Contents

Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
About This Guide . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Typographical Conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Aurea Sonic Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
SonicMQ Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Other Documentation in the SonicMQ Product Family . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Worldwide Technical Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

1. SonicMQ Messaging Concepts. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13


Messaging Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Direct Application Integration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Broker Distributed Application Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Distributed Components That Are Centrally Managed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
Clustered Brokers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Routing Nodes and the Dynamic Routing Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . 18
Continuous Availability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Fault Tolerant Clients on Replicated Brokers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
How SonicMQ Applications Work . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
Connections and Sessions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
Concurrent Sessions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
Session Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
Transacted Session . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
Nontransacted Session and Acknowledgement Mode . . . . . . . . . . . . . . . . . . . . . . . 23
Producers and Consumers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
Delivery Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
Destinations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
Point-to-point Messaging: There Is Only One Message . . . . . . . . . . . . . . . . . . . . . . . . . . 26
How Point-to-point Communication Works . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
Publish and Subscribe Messaging: Broadcast the Message . . . . . . . . . . . . . . . . . . . . . . 29
How Publish and Subscribe Works . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
Request/Reply . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
Quality of Service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33

Aurea Software, Inc. Confidential 3 Copyright © 2013 Aurea, Inc.


Contents

Disabling Flow Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33


Quality of Protection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34

2. Getting Started with the C Client . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35


Running the Sample Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
Setting Up the SonicMQ Messaging Broker . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
Setting the C Client Environment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
Setting the Variables and Updating the PATH On Windows . . . . . . . . . . . . . . . . . . . 37
Setting the Environment on UNIX or Linux . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
Using Client Console Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
Starting the Sample Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
Modifying and Compiling the Sample Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
Compiling C Applications on Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
Compiling C Applications on Most UNIX and Linux Systems . . . . . . . . . . . . . . . . . . 40
Point-to-point (PTP) Sample Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Talk Sample Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
ReliableTalk Sample Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
SelectorTalk Sample Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
Publish and Subscribe (Pub/Sub) Sample Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
Chat Sample Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
DurableChat Sample Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
HierarchicalChat Sample Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
SelectorChat Sample Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
ReliableChat Sample Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
Extending ReliableChat for Fault Tolerant Connections . . . . . . . . . . . . . . . . . . . . . . 50
Request/Reply Sample Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
Interoperating with Other Language Samples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
Running the Samples with Different Clients . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
Deploying the Sample Applications on Other Machines . . . . . . . . . . . . . . . . . . . . . . . . . . 54

3. Programming with the C Client . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55


Working with the C Client API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
Header Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
Macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
HOBJs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
Handling Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
Using Bytes Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
Callback Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
Releasing Objects and Avoiding Memory Leaks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
Using Message Selectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
Wide Characters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
Characters Used in SonicMQ Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
Using the Nagle Algorithm (TcpNoDelay) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
Broker Setting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
Client Setting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
Connection Factories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
URL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
ConnectID . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
Username and Password . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
ClientID . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
Enabling Message Compression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
Examining the Sample Application Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
Creating Connections and Sessions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68

Aurea Software, Inc. Confidential 4 Copyright © 2013 Aurea, Inc.


Contents

Creating Queues, Senders, and Receivers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69


Starting a Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
Creating a Message . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
Sending a Message . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
Cleaning Up After Sending a Message . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
Receiving a Message Asynchronously . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
Receiving a Message Synchronously . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
Specifying Acknowledgement and Persistence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72

4. High Availability Connections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75


Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
How Fault-Tolerant Connections are Established . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
ConnectionFactory Methods for Fault-Tolerance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
Enabling Fault Tolerant Connections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
Requesting a Fault Tolerant Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
Evaluating the List of Connection URLs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
Client Transaction Buffers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
Specifying Connection Timeouts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
Initial Connect Timeout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
Fault Tolerant Reconnect Timeout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
Connection Methods for Fault-Tolerance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
Verifying Whether a Connection Is Fault Tolerant . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
Handling Connection State Changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
Getting the URL of the Current Broker and Reconnect Brokers . . . . . . . . . . . . . . . . . . . . 84
URL Lists for Reconnecting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
Broker Reconnect URLs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
Standby Broker Reconnect URLs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
Reconnect Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
Load Balancing Considerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
Reliability in Fault-Tolerant Connections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
Reconnect Conflict . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
JMS Connection Reconnect Conflict . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
Durable Subscriber Reconnect Conflict . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
Message Reliability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88

5. Using Login SPI for Sonic Authentication. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91


Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
SimpleLogin SPI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
SimpleLogin Implementation in the SonicMQ C Client Runtime . . . . . . . . . . . . . . . . . . . 92
Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
Sample . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94

6. SSL Connections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
Using SSL on the C Client . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
Certificate Samples and Conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
Authentication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
Settings on a Broker . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
Samples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
Using SSL Authentication with username and password . . . . . . . . . . . . . . . . . . . . . 100
Using SSL Authentication with mutual certificates . . . . . . . . . . . . . . . . . . . . . . . . . . 101

7. Distributed Transactions in C Using the XA Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103


About Distributed Transaction Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
General Properties of a Transaction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104

Aurea Software, Inc. Confidential 5 Copyright © 2013 Aurea, Inc.


Contents

Transaction Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104


Components of Distributed Transactions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
Resource Managers and Transaction Managers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
One Phase Commit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
Two Phase Commit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
Programming with the XA Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
Global Transaction Identifier, Branch Qualifiers, and XIDs . . . . . . . . . . . . . . . . . . . . . . . 108
Using the xa_switch Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
Static Registration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
XA Threads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
Running the SonicMQ C XA Transaction Sample . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
In Doubt Global Transactions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
Distributed Transactions Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
SonicMQ Integrated with an Application Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
SonicMQ Used Directly with a Transaction Manager . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
SonicMQ Performing DTP Without a Transaction Manager . . . . . . . . . . . . . . . . . . . . . . . 115

8. Next Steps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117

A. Comparing the C Client with the Java Client . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119


Message Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
XMLMessage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
ObjectMessage, StreamMessage, and MultipartMessage . . . . . . . . . . . . . . . . . . . . . . . . 120
MapMessage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
Messaging Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
Recoverable File Channels for Large Message Handling . . . . . . . . . . . . . . . . . . . . . . . . 120
Broker-managed Timeouts on Transacted Sessions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
Protocols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
Acknowledge and Forward . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
Duplicate Transaction Detection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
Client Persistence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
Flow Control Administrative Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
Per-message Encryption . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
Global Subscription Propagation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
Pub/Sub Message Selection on the Broker . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
Flow To Disk . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
JMS 1.1 Domain Unification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
Clusterwide Access to Durable Subscriptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
Strict Message Order with Clusterwide Durable Subscriptions . . . . . . . . . . . . . . . . . 124
Sonic Stream API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
Programmatic Limit to Redelivery Attempts from a Queue . . . . . . . . . . . . . . . . . . . . . . . 124
Non-Persistent Replicated Delivery Mode (CAA-FastForward) . . . . . . . . . . . . . . . . . . . . 124
MultiTopic Constructs for Producers and Consumers . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
Socket Connect Timeout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
Custom Destinations for Undelivered Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
Management Framework Capabilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126

Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129

Aurea Software, Inc. Confidential 6 Copyright © 2013 Aurea, Inc.


Preface

About This Guide


SonicMQ is Aurea Software’s standards-based enterprise messaging system. SonicMQ
enables very high service availability, performance, and scalability with its Dynamic
Routing Architecture and advanced clustering technologies. SonicMQ enables loosely
coupled integration that is very resilient and very reliable while securely administered
through extensive authentication, authorization, and encryption support. The SonicMQ
distributed management and deployment infrastructure provides control over complex
configurations, and the metrics that monitor enterprise assets.

Businesses can participate in enterprise messaging from legacy C applications that provide
the performance levels of native C programs to interact with SonicMQ messaging services.

This guide is for developers who are experienced with C. They are not expected to be
familiar with SonicMQ or JMS messaging concepts. This guide provides background
information on SonicMQ messaging concepts to develop messaging clients with the C
Client API. For more in-depth coverage, the guide references the appropriate sections of
the SonicMQ documentation.

This guide contains these chapters and an appendix:

• Chapter 1, SonicMQ Messaging Concepts on page 13 explains basic enterprise


messaging concepts supported by the SonicMQ C Client API.
• Chapter 2, Getting Started with the C Client on page 35 describes how to run and
interpret the sample applications.

Aurea Software, Inc. Confidential 7 Copyright © 2013 Aurea, Inc.


Preface

• Chapter 3, Programming with the C Client on page 55 provides information for


developing an application with the SonicMQ C Client.
• Chapter 4, High Availability Connections on page 75 details the C Client
implementation of fault tolerant client connections.
• Chapter 5, Using Login SPI for Sonic Authentication on page 91 details using the
SonicMQ C++ client Service Provider Interface (SPI) to authenticate JMS client
applications where the broker is using Sonic’s external security implementation.
• Chapter 6, SSL Connections on page 97 describes connections to SonicMQ brokers
through SSL in the SonicMQ C++ client.
• Chapter 7, Distributed Transactions in C Using the XA Interface on page 103
describes the X/Open XA interface included in this product.
• Chapter 8, Next Steps on page 117 provides information about the resources for
learning more about this and other Aurea Sonic products.
• Appendix A, Comparing the C Client with the Java Client on page 119 notes the
differences between this version of the SonicMQ C Client and its corresponding Java
Client.

Typographical Conventions
This section describes the text-formatting conventions used in this guide and a description
of notes, warnings, and important messages. This guide uses the following typographical
conventions:

• Bold typeface in this font indicates keyboard key names (such as Tab or Enter) and
the names of windows, menu commands, buttons, and other Sonic user-interface
elements. For example, “From the File menu, choose Open.”
• Bold typeface in this font emphasizes new terms when they are introduced.
• Monospace typeface indicates text that might appear on a computer screen other than
the names of Sonic user-interface elements, including:
• Code examples and code text that the user must enter
• System output such as responses and error messages
• Filenames, pathnames, and software component names, such as method names
• Bold monospace typeface emphasizes text that would otherwise appear in monospace
typeface to emphasize some computer input or output in context.

• Monospace typeface in italics or Bold monospace typeface in italics


(depending on context) indicates variables or placeholders for values you supply or
that might vary from one case to another.

This manual uses the following syntax notation conventions:

• Brackets ([ ]) in syntax statements indicate parameters that are optional.


• Braces ({ }) indicate that one (and only one) of the enclosed items is required. A
vertical bar (|) separates the alternative selections.
• Ellipses (...) indicate that you can choose one or more of the preceding items.

Aurea Software, Inc. Confidential 8 Copyright © 2013 Aurea, Inc.


Aurea Sonic Documentation

This guide highlights special kinds of information by shading the information area, and
indicating the type of alert in the left margin.

Note: A Note flag indicates information that complements the main text flow. Such
information is especially helpful for understanding the concept or procedure being
discussed.

Important: An Important flag indicates information that must be acted upon within the
given context to successfully complete the procedure or task.

Warning: A Warning flag indicates information that can cause loss of data or other
damage if ignored.

Aurea Sonic Documentation


Sonic installations always have a welcome page that provides links to Sonic
documentation, release notes, communities, and support. See the release’s Product
Update Bulletin book to see what’s new and what’s changed since prior releases.

The Sonic documentation set includes the following books and API references.

SonicMQ Documentation
SonicMQ installations provide the following documentation:

• Aurea Sonic Installation and Upgrade Guide — The essential guide for installing,
upgrading, and updating SonicMQ on distributed systems, using the graphical,
console or silent installers, and scripted responses. Describes on-site tasks such as
defining additional components that use the resources of an installation, defining a
backup broker, creating activation daemons and encrypting local files. Also describes
the use of characters and provides local troubleshooting tips.
• Getting Started with Aurea SonicMQ — Provides an introduction to the scope and
concepts of SonicMQ messaging. Describes the features and benefits of SonicMQ
messaging in terms of its adherence to the JavaSoft JMS specification and its rich
extensions. Provides step by step instructions for sample programs that demonstrate
JMS behaviors and usage scenarios. Concludes with a glossary of terms used
throughout the SonicMQ documentation set.
• Aurea SonicMQ Configuration and Management Guide — Describes the configuration
toolset for objects in a domain. Also shows how to use the JNDI store for administered
objects, how integration with Progerss Actional is implemented, and how to use JSR
160 compliant consoles. Shows how to manage and monitor deployed components
including metrics and notifications.
• Aurea SonicMQ Deployment Guide — Describes how to architect components in
broker clusters, the Sonic Continuous Availability Architecture™ and Dynamic Routing
Architecture®. Shows how to use the protocols and security options that make your

Aurea Software, Inc. Confidential 9 Copyright © 2013 Aurea, Inc.


Preface

deployment a resilient, efficient, controlled structure. Covers all the facets of HTTP
Direct, a Sonic technique that enables SonicMQ brokers to send and receive pure
HTTP messages.
• Aurea SonicMQ Administrative Programming Guide — Shows how to create
applications that perform management, configuration, runtime and authentication
functions.
• Aurea SonicMQ Application Programming Guide— Takes you through the Java
sample applications to describe the design patterns they offer for your applications.
Details each facet of the client functionality: connections, sessions, transactions,
producers and consumers, destinations, messaging models, message types and
message elements. Complete information is included on hierarchical namespaces,
recoverable file channels and distributed transactions.
• Aurea SonicMQ Performance Tuning Guide — Illustrates the buffers and caches that
control message flow and capacities to help you understand how combinations of
parameters can improve both throughput and service levels. Shows how to tune TCP
under Windows and Linux for the Sonic Continuous Availability Architecture™.
• SonicMQ API Reference — Online JavaDoc compilation of the exposed SonicMQ
Java messaging client APIs.
• Management Application API Reference — Online JavaDoc compilation of the
exposed SonicMQ management configuration and runtime APIs.
• Metrics and Notifications API Reference — Online JavaDoc of the exposed SonicMQ
management monitoring APIs.
• Aurea Sonic Event Monitor User’s Guide — Packaged with the SonicMQ installer, this
guide describes the Aurea Sonic logging framework to track, record or redirect metrics
and notifications that monitor and manage applications.

Other Documentation in the SonicMQ Product


Family
The Aurea Sonic download site provides access to additional client and JCA adapter
products and documentation:

• Aurea SonicMQ .NET Client Guide — Packaged with the SonicMQ .NET client
download, this guide takes you through the C# sample applications and describes the
design patterns they offer for your applications. Details each facet of the client
functionality: connections, sessions, transactions, producers and consumers,
destinations, messaging models, message types and message elements. Includes
complete information on hierarchical namespaces and distributed transactions. The
package also includes online API reference for the Sonic .NET client libraries, and
samples for C++ and [Link].
• Aurea SonicMQ C Client Guide — Packaged with the SonicMQ C/C++/COM client
download, this guide presents the C sample applications and shows how to enhance
the samples, focusing on connections, sessions, messages, producers and
consumers in both the point-to-point and publish/subscribe messaging models.
Provides tips and techniques for C programmers and gives detailed information about

Aurea Software, Inc. Confidential 10 Copyright © 2013 Aurea, Inc.


Worldwide Technical Support

using XA resources for distributed transactions. The package also includes online API
reference for the SonicMQ C client.
• Aurea SonicMQ C++ Client Guide — Packaged with the SonicMQ C/C++/COM client
download, this guide presents the C++ sample applications and shows how to
enhance the samples, focusing on connections, sessions, messages, producers and
consumers in both the point-to-point and publish/subscribe messaging models.
Provides tips and techniques for C++ programmers and gives detailed information
about using XA resources for distributed transactions. The package also includes
online API reference for the SonicMQ C++ client.
• Aurea SonicMQ COM Client Guide — Packaged with the SonicMQ C/C++/COM client
download for Windows, this guide presents the COM sample applications under ASP,
and Visual C++. Shows how to enhance the samples, focusing on connections,
sessions, messages, producers and consumers in both the point-to-point and
publish/subscribe messaging models. Provides tips and techniques for COM
programmers. The package also includes online API reference for the SonicMQ COM
client.
• Aurea SonicMQ 2013 Resource Adapter for JCA User’s Guide for Weblogic Aurea
SonicMQ 2013 Resource Adapter for JCA User’s Guide for Weblogic — Packaged
with this JCA adapter in a separate download, this guide describes the Sonic
Resource Adapter for JCA and using it with a WebSphere application server.
• Aurea SonicMQ 2013 Resource Adapter for JCA User’s Guide for Weblogic —
Packaged with this JCA adapter in a separate download, this guide describes the
Sonic Resource Adapter for JCA and using it with a Weblogic application server.
• Aurea SonicMQ 2013 Resource Adapter for JCA User’s Guide for JBoss — Packaged
with this JCA adapter in a separate download, this guide describes the Sonic
Resource Adapter for JCA and using it with a JBoss application server.

Worldwide Technical Support


Aurea Software’s support staff can provide assistance from the resources on their Web site
at [Link]/sonic. There you can access technical support for licensed Aurea Sonic
products to help you resolve technical problems that you encounter when installing or using
Aurea Sonic products

When contacting Technical Support, please provide the following information:

• The release version number and serial number of SonicMQ that you are using. This
information is listed on the license addendum. It is also at the top of the SonicMQ
Broker console window and might appear as follows:

SonicMQ Continuous Availability Edition [Serial Number nnnnnnn]

Release nnn Build Number nnn Protocol nnn

• The release version number and serial number of Sonic ESB that you are using. This
information is listed on the license addendum. It is also near the top of the console
window for a Sonic ESB Container. For example:

Aurea Software, Inc. Confidential 11 Copyright © 2013 Aurea, Inc.


Preface

Sonic ESB Continuous Availability Edition [Serial Number:


nnnnnnn]

Release nnn Build Number nnn

• The platform on which you are running Aurea Sonic products, and any other relevant
environment information.
• The Java Virtual Machine (JVM) your installation uses.
• Your name and, if applicable, your company name.
• E-mail address, telephone, and fax numbers for contacting you.

Aurea Software, Inc. Confidential 12 Copyright © 2013 Aurea, Inc.


1
SonicMQ Messaging Concepts

This chapter introduces Java Message Service (JMS) concepts and explains how these
concepts are implemented by SonicMQ. This chapter includes the following sections:

• Messaging Concepts on page 13 describes the SonicMQ messaging architecture


including its messaging broker topologies and management framework.
• How SonicMQ Applications Work on page 21 describes how asynchronous
messaging and the two messaging model from the client view point

Messaging Concepts
SonicMQ implements standardized messaging concepts, providing an easy-to-use set of
interfaces and administrative tools. The Application Programming Interfaces comply with
the standards in the Sun Java Message Service specification, version 1.02.b.

The following information describes messaging concepts including general topology,


connectivity, alternative messaging behaviors, and the attributes and characteristics that
enable secure, reliable messaging.

Direct Application Integration


As shown in Figure 1, when messaging is not implemented and distributed applications are
integrated, every client application maintains a connection to every other client application.

Aurea Software, Inc. Confidential 13 Copyright © 2013 Aurea, Inc.


Chapter 1: SonicMQ Messaging Concepts

Figure 1: Distributed Application Structure

Client Client
Application Application
A B

Client Client
Application Application
F C

Client Client
Application Application
E D

After applications are linked, they might be secure, fast, and reliable. However, direct
peer-to-peer communication has several limitations:

• Bringing large integrated systems online is often so expensive and time consuming
that systems might become obsolete as soon as they start to amortize their costs.
• Modifying application software with hard-coded communications is tedious and error
prone.

Broker Distributed Application Structure


With the broker architecture, shown in Figure 2, each application is a client, except the
broker—to which each client connects, thereby providing connection services to every
other client.

Figure 2: Broker Structure

Client Client
Application Application
A B

Client Client
Broker
Application Application
F C

Client Client
Application Application
E D

Aurea Software, Inc. Confidential 14 Copyright © 2013 Aurea, Inc.


Distributed Components That Are Centrally Managed

There is a savings in connections since this topology requires only n connections for n
clients, and is more efficient because the broker manages security, logistics and protocols
for connections to clients.

This messaging topology can expand to increase reliability and performance, yet the clients
only have to connect to the appropriate port on their preferred broker system.

The JMS provider implements and manages a JMS application. The JMS provider includes
the JMS Client API and the SonicMQ Client run time accessed from within the client
application, the communications layer between the client and the broker, and the broker
architecture. The broker architecture and services are central to SonicMQ’s messaging
security, efficiency, scalability, and performance. The SonicMQ broker does the following:

• Listens on a port on its host system to provide services to its clients.


• Manages the queued messages, and messages held for durable subscribers.
• Provides support for TCP, HTTP, and Secure Socket Layers (SSL) protocols.

Distributed Components That Are Centrally


Managed
The management infrastructure in SonicMQ is compliant with Java Management
eXtensions (JMX), a standard framework for instrumentation and management of
Java technology-based resources.

A distributed component is managed in the infrastructure in a container—a Java process


that hosts Sonic components in a Java Virtual Machine (JVM).

Container

A container hosts components such as a broker.


The container maintains the cache for its hosted components, providing persistent
configuration information that is used locally by the hosted components.

Broker

Container

Aurea Software, Inc. Confidential 15 Copyright © 2013 Aurea, Inc.


Chapter 1: SonicMQ Messaging Concepts

A Directory Service manages a store of configuration information used by distributed


components.

Broker

Directory Service

JNDI Store

Agent Manager

Container

When a hosted component is a Directory Service, the broker located in the same container
as the Directory Service handles management communications for the Directory Service.
Containers communicate with the Directory Service by connecting to the broker colocated
with the Directory Service. The Directory Service installation includes a local JNDI store, a
file system that enables clients to look up a named connection factories or destinations
defined by administrators.

All the containers that communicate with a given Directory Service are in that Directory
Service’s domain.

Domain

Broker
Domain
Manager

Directory Service

JNDI Store

Agent Manager

Container

The set of components that manage a domain comprise the domain manager.

The broker in the domain manager’s container is an independent broker.

Aurea Software, Inc. Confidential 16 Copyright © 2013 Aurea, Inc.


Distributed Components That Are Centrally Managed

Client applications connect to brokers and are outside the scope of the domain. In this
illustration, one broker performs both management broker and messaging broker functions.

Domain

Client
Applications

Broker
Domain
Manager

Directory Service

JNDI Store

Agent Manager

Container

In production environments, management and messaging functions are separated.


As illustrated in Figure 3, the domain manager is managing another container that hosts a
broker. This dependent broker is focused on client messaging functions. The
management broker communicates with the containers to monitor their states, and update
their configurations. Client applications connect to the management broker to look up
connection and destination administered objects. The Sonic Management Console is
graphical tool that connects to the management broker to facilitate administrative
operations.

Figure 3: Distributed SonicMQ Components, Administration Tool, and Clients


Domain
Administered Object Lookup

Client
Application A
Client
Management Management Messaging
Application
Console Broker Broker Producer to
Destination
Broker
Domain Destination
Manager Consumer from
Broker Destination
Directory 1 Client
Service Application B
JNDI Store

Agent
Manager
Container 1
Container .

Clustered Brokers
As the requirements for performance and availability increase in a deployment, the benefits
of clustering become apparent. Clustered brokers lets you add brokers to handle heavy
message loads or high connection counts by load balancing new connections to brokers in
the cluster.

Aurea Software, Inc. Confidential 17 Copyright © 2013 Aurea, Inc.


Chapter 1: SonicMQ Messaging Concepts

Domain Producer
Application

Broker
Cluster 2
Node A

Broker Consumer
1 Application
Broker
3

Several brokers in the same administrative domain can be configured as members of a


named cluster. Interbroker connections in a cluster make the cluster members a very agile
and mutually supportive team of brokers. When load balanced, connected clients can take
advantage of clusterwide access to topics, queues, and durable subscriptions. A domain
can have many clusters that let you extend your deployment options while still maintaining
a central repository of security and configuration information.

Domain
Node A

Cluster

Node B

Cluster

Routing Nodes and the Dynamic Routing


Architecture
Cluster members express a unique identity as one named routing node. Each cluster and
each unclustered broker—including the domain manager’s broker—is a routing node. The
following illustration shows a domain with four nodes.

Aurea Software, Inc. Confidential 18 Copyright © 2013 Aurea, Inc.


Continuous Availability

Domain

Cluster

Node A
Cluster

Node DM Node B

Broker

Node C

By specifying routing definitions on a local node, client applications can send messages to
a local node in their domain, yet route to a topic or queue on a remote node. This proxy
broker functionality is SonicMQ’s Dynamic Routing Architecture® (DRA). Each business
manages the security for its users and routing while the conduit between businesses is
efficient and accessible for authenticated, authorized [Link] following illustration
shows the concept of an application connecting to a broker in one domain to provide a
routing of a message to a destination on a broker in another domain. A client application
connected to that broker can then receive the message.

OurDomain TheirDomain

OurClient TheirClient
Application Application
Broker
Consumer on Broker Producer to
Q1 OurBroker1 TheirBroker1 OurNode1::Q1
Dynamic Routing Definition
Queue Destination OurNode1
Q1

Node Node
OurNode1 TheirNode1

Continuous Availability
When striving for non-stop availability of enterprise resources, SonicMQ’s Continuous
Availability Architecture™ provides resilience and fault tolerance in several ways:

• Client connections can be fault tolerant. When the broker or the network experiences
a fault, the clients resume when the broker (or its backup) is available. Alternate
network paths reroute to other networks defined on the broker.
• Replicated brokers pairs enable failover to a standby broker when the active broker
fails. Fault tolerant client connections take advantage of this feature.

Aurea Software, Inc. Confidential 19 Copyright © 2013 Aurea, Inc.


Chapter 1: SonicMQ Messaging Concepts

• Management components can have backups that assume the management


component’s functions when the primary management component fails.

All three features, when fully implemented, provide continuous availability.

Fault Tolerant Clients on Replicated Brokers


When connections or systems experience faults, fault tolerant clients on replicated brokers
can each maintain state and data. The brokers failover to backup components that have
been standing by for hot failover.

CLIENTS CONNECTED TO THE ACTIVE BROKER IN A SET OF FAULT TOLERANT REPLICATED BROKERS

ClientClient
Application
Applications Replicated Replicated
R E PL I CA T I O N C O NNE CT I O N ( S )
Fault Broker Broker
Tolerant
ACTIVE STANDBY

Client
Applications

C LIENTS CONNECTED TO F AULT TOLERANT R EPLICATED B ROKERS A FTER THE A CTIVE B ROKER F AILS

ClientClient
Application
Applications Replicated
Fault Broker
Tolerant
STANDALONE
Client
Applications
X

Client applications can specify an interest in a fault tolerant client connection when they
connect to brokers that are licensed for fault tolerance. The client will maintain its
connection and session information even if it experiences a dropped connection, waiting
for the broker to become available again.

While fault tolerant client connections are available on single brokers, replicated brokers
provide a more dramatic case for high availability. When clients are connected to an active
broker, that broker is synchronizing its entire set of client information and data with its
standby broker. In the event that the active broker goes down, the standby broker takes
over as the only broker, and assumes the standalone role. Clients that have fault tolerant
connections maintain their state and connect to the other broker to resume the session
seamlessly.

Note: Additional configuration, management and runtime monitoring in the SonicMQ


JMS Java Client include:

Performance tools — That assess flows and traffic to assist administrators in fine
tuning system performance.

Aurea Software, Inc. Confidential 20 Copyright © 2013 Aurea, Inc.


How SonicMQ Applications Work

Instrumentation — Metrics on messaging activity provide a visual log of


messaging system activity.

Management API — Many administrator functions can, under appropriate


authorization, be coded into management applications.

See Appendix A, Comparing the C Client with the Java Client on page 119 for more
information.

How SonicMQ Applications Work


As you learn about the mechanisms and behaviors of SonicMQ applications, you will also
become knowledgeable about the Java Message Service specification. Several SonicMQ
concepts presented here are extensions of the JMS specification—such as the XML
message type, prefetch, single message acknowledgement, flow control, and load
balancing—that can make better, more efficient implementations.

The rest of this chapter describes you how SonicMQ applications works.

Connections and Sessions


A SonicMQ application starts by accessing a ConnectionFactory to create a connection
that binds the client to the broker. ConnectionFactories are administered objects, objects
with connection configuration parameters that are defined by an administrator.

The connecting application can use the setTCPConnectionTimeout method to set a timeout
for connection attempts that do not succeed.

One or more sessions can be created within a connection. Each session establishes a
context for one thread where messages might be sent or received. Figure 4 shows a client
application where one connection is made through which one session is established. The
client application uses programmatic interfaces to the JMS Client API that are executed
through the SonicMQ client run time on the session.

Aurea Software, Inc. Confidential 21 Copyright © 2013 Aurea, Inc.


Chapter 1: SonicMQ Messaging Concepts

Figure 4: JMS Session on a Connection

Client Application
C
C Client API S
O
E
N
S
N
S
E
Broker
SonicMQ Client I
C
O
Run Time N
T
I
O
N

Note: See Chapter 4, High Availability Connections on page 75 for information about
concepts and techniques for client fault tolerance.

Concurrent Sessions
A client can create multiple sessions within a connection to the broker, each independently
sending and receiving messages. Sessions execute in parallel so that multiple threads are
active concurrently to optimize thread usage for co-dependent activities.

For example, a connection might have two sessions where one is receiving messages
while the other is sending messages, thus removing the possibility of concurrent activities
on a single thread.

A single session can be used for sending and receiving if careful programming ensures that
more than one thread does not have access to a session at one time.

Session Types
Each session is established with a declared intention for acknowledgement of messages.
A session can be either transacted or nontransacted, in which case one of several modes
can be specified for acknowledging messages.

Transacted Session
A SonicMQ session can be specified as transacted. The technology of transaction
processing significantly reduces the effort required to build applications by allowing
applications to combine a group of one or more messages with publisher-to-broker
ACID properties:

• Atomic — Either all the messages are delivered or all are ignored.
• Consistent — Business rules ensure the receiver behaves correctly.
• Isolated — Transacted messages are delivered serially.
• Durable — Messages are persistent.

Aurea Software, Inc. Confidential 22 Copyright © 2013 Aurea, Inc.


How SonicMQ Applications Work

When a transaction commits, its atomic unit of input is acknowledged and its series of
messages is sent. If a transaction rolls back, its produced messages (if any) are destroyed.
The completion of a session’s current transaction automatically begins the next transaction.

A local transaction session is a good example of a session function that can take advantage
of sending and receiving in a single session. When a transacted session commits, all the
sent messages in the session are released on the server destinations and all the received
messages are acknowledged.

Global Transactions
SonicMQ also includes programmatic facilities that enable SonicMQ applications to fully
participate in global transactions—transactions that extend beyond a single session. In
global transactions, a transaction identifier is registered with a transaction manager that
manages the various branches of the transaction as it is constructed and then controls the
orderly preparation and commitment of the completed transaction.

Transaction Timeout
Because transactions buffer messages sent and received, a transaction that is stalled or
interrupted might have messages stuck in transit. Messages received in the transaction
context are neither acknowledged nor available to other consumers. Messages sent are not
accessible to receivers so the messages are invisible.

This situation can be handled by setting a broker limit on the amount of time that a
transaction can take to complete. An overdue transaction is rolled back, freeing queued
messages for other receivers.

Nontransacted Session and Acknowledgement


Mode
When a nontransacted session is created, the client application can set the type of
acknowledgement it expects when messages are delivered:

• Auto — The session automatically acknowledges the client’s receipt of a message


when the session has successfully returned from a call to receive.
• Client — The acknowledgement of a received message automatically acknowledges
the receipt of all messages that have been delivered to a consumer by its session.
A session can recover so that it restarts with its first unacknowledged message.
• Single message — Explicit acknowledgement of one message.
• Dups_OK — The session “lazily” acknowledges the delivery of messages to
consumers, possibly allowing some duplicate messages after a system outage is
experienced. In systems such as market quote streamers, duplicates are an
acceptable trade-off for faster system recovery.

While acknowledgement sets standards for message delivery, there is no reply to the
sender. If a reply to the sender is required, a message attribute is reserved for the request.
The requestor can also append a correlation identifier in the message’s header to ensure
that the reply matches its request.

Aurea Software, Inc. Confidential 23 Copyright © 2013 Aurea, Inc.


Chapter 1: SonicMQ Messaging Concepts

Duplicate Message Detection


While a message can be guaranteed to not be delivered twice, that guarantee is only for a
message within the realm of the JMS provider. If a message producer is concerned that it
might create and produce a message twice, the producer can use a universal identifier as
an audit tracker. The broker will disallow a message that uses an identifier that has already
been processed successfully.

Producers and Consumers


The traffic on a session thread to the broker, as shown in Figure 5, can consist of a
message producer delivering a message to its broker or a broker delivering a message to
an application that will consume it.

Figure 5: Producers and Consumers

C
O
S
N
E
N
S PRODUCER publishes, sends
E
S Messages
C Broker
I
T CONSUMER subscribes, receives
O
I
N
O
N

The producer of the message packages and encrypts the message body, identifies the
service level and protection for the outbound message, and then sends the message to its
destination (a specified location in the broker’s realm).

The consumer of a message binds to a destination to receive a message and then


implements the message’s delivery method:

• Synchronous delivery — The client requests the next message using a receive
method that polls the session, which is the fundamental problem with traditional
system interconnections: the connection could be blocked indefinitely.
• Asynchronous delivery — The client registers a MessageListener. As messages
arrive, SonicMQ calls the listener’s onMessage method. With an asynchronous
connection, if the connection is in any way impaired, messages that are guaranteed
will wait for a connection to be re-established. The producer can determine how long
a message will wait for a consumer to avoid backlogs.

Aurea Software, Inc. Confidential 24 Copyright © 2013 Aurea, Inc.


How SonicMQ Applications Work

Delivery Mode
There are alternative delivery modes for a message:

• When a message is sent to a destination, you can specify that the message will always
be stored in a local log or data store before it is acknowledged as being transferred.
This PERSISTENT delivery mode ensures that a message is safe from normal system
outages and interruptions—whether in its initial transfer to the broker, in durable
subscriptions or queues on the broker, and even in transfers to other brokers and
queues.
• When messages have a NON_PERSISTENT delivery mode, the message throughput is
faster but messages are volatile—they might not be recoverable from an outage.
• Additionally, Pub/Sub offers a DISCARDABLE delivery mode so that high-volume
publishing systems can provide relief to fast subscribers when slow subscribers fall
way behind the incoming message flow.

Destinations
Destinations are the delivery labels in messaging. Rather than the place where the
message is ultimately delivered, a destination is the named staging area for the message.
SonicMQ distinguishes the two JMS messaging models:

• Point-to-point (PTP) — Produces messages to a named queue, placing new


messages at the back of the queue. Prospective consumers of messages addressed
to a queue can either receive the front-most message (thereby removing it from the
queue) or browse through all the messages in the queue, causing no changes. While
several clients can access a queue, a message is received by only one (one-to-one
communication).
• Publish and Subscribe (Pub/Sub) — Produces messages to a topic. Prospective
consumers of messages addressed to a topic simply subscribe to the topic. While a
message can have many subscribers (one-to-many), the producer does not know how
many subscribers, if any, exist for a topic.

These messaging models are very similar in terms of connection and session
management, message structure (types, headers, and properties), delivery mode options,
and delivery methods (blocking or asynchronous).

Forwarding Messages
To assure that a message destined for a remote queue is properly stored, you might use
transaction semantics to refrain from releasing the sender until the message is forwarded
and acknowledged. SonicMQ reduces the overhead of such a single message transaction
with its unique acknowledge-and-forward send method.

Aurea Software, Inc. Confidential 25 Copyright © 2013 Aurea, Inc.


Chapter 1: SonicMQ Messaging Concepts

Point-to-point Messaging: There Is Only One


Message
The Point-to-point (PTP) messaging model ensures the delivery of a unique message to be
received by one and only one consumer. In Figure 6, the message senders send new
messages to QueueOne, a destination on the broker. The broker, unless advised that there
is a request for priority treatment, places new messages at the back of the queue.

Figure 6: Concept of Point-to-point Messaging Queues

Message Senders QueueOne Message Receivers


to QueueOne A known destination on a broker, on QueueOne
where receivers take unique messages.

E
H Synchronous receiver
G about to complete
acknowledgement

F
E
D C
Receiver with
front an exclusive message selector
B
A

A
Prefetch
buffer
Receiver with
PreFetch count of "2"

The messages in this illustration are being removed from the queue by three receivers:

• A synchronous receiver waits for a message—for a specified time or forever—and


then blocks to receive again after processing a message. The queue state indicated
that message E was the front-most message because messages A and B (while still
in the queue) are awaiting acknowledgement from another receiver.
• A receiver browsing with a Message Selector reviews qualified messages on the
queue to determine if any of them are messages that it wants to process. In this
example, the receiver selected and acknowledged messages C and D. Assuming
message F does not meet its criteria, this receiver finds the queue momentarily empty.

By also using a QueueBrowser, this receiver can scan through a queue capturing the
ever-changing queue image as it progresses. The QueueBrowser mechanism can
also let the sender view the queue to see how message traffic is moving.

• A receiver with a PreFetch count of 2 took messages A and B off the queue. Message
B is held aside while message A is processed. When message B enters processing,
the threshold trigger causes the receiver to draw off two more messages. The broker
can keep track of these messages in process and, unless acknowledgement is
received, the messages will be reinstated into the queue.

In the PTP model, each message is a unique item. However, messages can disappear
without being delivered—a message expires when its time to live has passed.

Aurea Software, Inc. Confidential 26 Copyright © 2013 Aurea, Inc.


How SonicMQ Applications Work

In clusters or Dynamic Routing, a message could get stuck in a position where the sender
knows that the broker accepted the message but other brokers, routes, or destinations
could create a state of doubt about final delivery. An application can send messages with
properties that request that as a dead message, it be preserved or at least notify the
administrator that it was never delivered. This concept, a dead message queue (DMQ), can
work in concert with other Quality of Service features to provide guaranteed persistence in
the always-active yet sometimes-disconnected networking environment of modern
computing.

How Point-to-point Communication Works


In the PTP messaging model, a producer is a sender and a consumer is a receiver.
Point-to-point messaging queues are explicitly created by the administrator to allow for
sequential caching of messages for their receiver. While only one receiver consumes the
latest message, several receivers might be receiving from the queue, taking turns
consuming the latest message. A PTP message producer sets headings, properties, and
body content in much the same way as Pub/Sub producers.

In Figure , the PTP session thread has senders producing messages to destinations
maintained by the broker, and receivers consuming messages that the broker forwarded
from queues where the session is waiting to receive messages.

Figure 7: Sending and Receiving on a Queue Connection

S
E C
S O
S
N
Broker
I
O N SENDER sends messages to Queues
N
E
S C Messages Queue
E T RECEIVER receives messages from Queues
S
S
I
I O
O
N
N

The receiver of a queued message, however, notices a significant difference between


Pub/Sub and PTP messaging models. In PTP:

• The first message received is the first message delivered. This first-in-first-out
technique makes the second through nth messages endure until that first message is
consumed. Even when no clients express interest in receiving messages from a
queue, messages wait for a receiver until the message expires. When a message’s
delivery mode is set to PERSISTENT, the message is stored so that even a broker
shutdown does not put it at risk.
• There is only one message consumer for a given message. Many receivers can
balance the load, but only one takes delivery of the message.
• When the message is acknowledged as delivered, it is removed from the queue
permanently. No other receiver sees it and no other receiver consumes it.

Aurea Software, Inc. Confidential 27 Copyright © 2013 Aurea, Inc.


Chapter 1: SonicMQ Messaging Concepts

Authorized users of a Queue Browser can use durable sequential queues to view
messages without consuming them.

In Figure 8, several FIFO queues are shown that might exist on a broker. The queues are
shown to have different depths, illustrating that the stack of messages persists until
receivers take messages off the queue as fast as they are added. The queues also show
a receiver taking a message.

The receiver could be one of many receivers who are standing by to receive the top-most
message. On the middle queue (BQ) in Figure 8, multiple receivers are allowed but only
one receiver gets the message—a queued message gets delivered only once.

Figure 8: Sending Messages to Queues for Receivers

Broker
Queues
Senders
Receivers
S1
R1
AQ
R2
S2
R3
BQ
R4
S3

R5
CQ

Queues are the preferred for load-balancing where many diverse systems can share
processing operations mandated, such as heavy trading activities, credit card charges,
online shopping carts, auctions, reservations, and ticketing.

Producers of queue messages can use Dynamic Routing in queue messaging by using the
routing_node_name::queue_name syntax to send a message to a queue on a remote node.
See Chapter 1, Routing Nodes and the Dynamic Routing Architecture on page 18 for an
illustration of Sonic’s Dynamic Routing Architecture.

Aurea Software, Inc. Confidential 28 Copyright © 2013 Aurea, Inc.


How SonicMQ Applications Work

Publish and Subscribe Messaging: Broadcast


the Message
The Publish and Subscribe (Pub/Sub) messaging model involves a broadcast of
messages—many subscribers receive precisely the same message, as shown in Figure 9.

Figure 9: Concept of Publish and Subscribe Messaging Topics


TopicOne
Message Publisher Message Subscribers
A content node on a broker
to TopicOne where interested parties to TopicOne
subscribe and listen for messages

C
A
B Synchronous subscriber

A
Asynchronous durable subscriber

A
Asynchronous subscriber with
inclusive message selector

Broker

Figure 9 shows three subscribers who have each received message A and are about to
receive message B then message C:

• A synchronous subscriber waits for a message—for a specified time or


forever—and then blocks to receive again after processing a message.
• An asynchronous durable subscriber recorded an interest in receiving messages
from the broker on the selected topic, even when disconnected. Messages are saved
for durable subscribers, although a saved message can expire while waiting for the
durable subscriber to reconnect.
• An asynchronous subscriber has set up a message listener. When a message
arrives, the onMessage method delivers the message to the consumer process. In
Figure 9, this subscriber has a message selector. The subscriber provided a string in
SQL syntax as a parameter when the subscriber was created. If the selection criteria
are not met by message B or C, the application’s consumer does not take delivery of
that message.

In the Pub/Sub model, a topic might have any number of subscribers from none to millions.
There is no statistical feedback to the publisher to indicate demand, but there is also no
burden on the publisher when the number of subscribers increases sharply.

Aurea Software, Inc. Confidential 29 Copyright © 2013 Aurea, Inc.


Chapter 1: SonicMQ Messaging Concepts

How Publish and Subscribe Works


In the Pub/Sub messaging model, a producer is a publisher and a consumer is a
subscriber. A publisher initiates a message by sending an instance of a message type
object that has the appropriate body content as a payload and header and property data
exposed to aid in delivery and tracking. The publisher sets the quality of service—delivery
mode, time-to-live, and priority—as well as whether a reply is requested from the
consumer. The broker returns a message identifier and immediately distributes the
message to all consumers of that topic. If the delivery mode is PERSISTENT, the message is
placed in the broker’s log or message store before starting delivery.

In Figure 10, the Pub/Sub session thread has publishers producing messages to topics
maintained by the broker and subscribers consuming messages that the broker delivered
from topics where the session is subscribed.

Figure 10: Publishing and Subscribing on a Topic Connection

S
E
C
S O
S
Broker
N
I
O N PUBLISHER publishes messages to Topics
N E
S C Messages Topic
E
S
T SUBSCRIBER receives messages from Topics
S I
I O
O
N N

After delivery of the message, the broker checks to see if any of the subscribers to the topic
are durable subscribers—subscribers who expressed a durable interest in the message’s
topic. If, after initial delivery, any durable subscribers did not acknowledge delivery, the
message is retained until the expiration time in anticipation that a durable subscriber will
connect to the broker and accept delivery. The expiration time is calculated from the
time-to-live beyond the time of publication. A message can be set to live forever yet is
discarded as soon as delivery to all current subscribers and all durable subscribers is
complete.

Asynchronous subscribers use a message Event Listener that delivers messages to the
subscriber’s application for interpretation—de-encryption, parsing, and passing to the
message consumer’s methods.

Subscribers can filter the messages they receive by qualifying their subscriptions with
message selectors that evaluate message headers and properties (but not the content)
with expression strings created with a subset of SQL-92 semantics. These filtering tasks
for subscriber messages take place on the broker.

Aurea Software, Inc. Confidential 30 Copyright © 2013 Aurea, Inc.


How SonicMQ Applications Work

SonicMQ extends the JMS standard topic naming mechanism with topic hierarchies (also
referred to as hierarchical name spaces) specified with a dot-delimited name string like
[Link]. The effort is minimal for the publisher, yet there are significant
administrative security advantages to the client subscription. The subscribers to the topic
node can, if granted authority to do so:

• Subscribe to all orders (Orders.#),


• Subscribe to only Euro orders ([Link].#),
• Subscribe to all government messages (#.Gov)

or many other combinations with a few simple template characters. Subscribers to the root
topic (““) get all messages by using (#).

Publishers can do remote publishing by using the routing_node_name::topic_name syntax


to send a message to a topic on a remote [Link] Routing Nodes and the Dynamic
Routing Architecture on page 18 for an illustration of Sonic’s Dynamic Routing Architecture.

Figure 11 describes how publishers send messages to topics and how the messages are
routed to active and durable subscribers:

• Publishers send messages to specific topics.


• The broker keeps track of messages and security for both active and durable
subscribers to topics and topic name spaces.
• As soon as messages are published, they are distributed to the subscribers. Durable
subscribers who were inactive receive unexpired messages when they reconnect.

Figure 11: Publishing Messages to Topics for Subscribers

Broker Durable Subscription Subscribers


Publishers fulfilled
within time-to-live of
message
Topics Subscribers S1

P1 S2

P2 S3

S4
S5

P3

Messages
A SonicMQ message is fully compliant with the JMS specification of a message with all
attributes implemented, plus a few important extensions. The message types are:

• Message — Basic message where no body is required.


• TextMessage — A standard [Link].
• BytesMessage — Stream of uninterpreted bytes.

Aurea Software, Inc. Confidential 31 Copyright © 2013 Aurea, Inc.


Chapter 1: SonicMQ Messaging Concepts

Important: The SonicMQ C Client does not support the other message types specified for
JMS—ObjectMessage, StreamMessage, and MapMessage—or the SonicMQ
extensions, the XMLMessage or the MultipartMessage. While an XMLMessage is
seen as a TextMessage, the message type can be accessed and unaccepted
types can be forwarded without changes. See Chapter A, Message Types on
page 119 for more information.

Structure
A message consists of:

• Header — Contains name-value pairs used by both producers and consumers to


identify and route messages. JMS-standard header fields are JMSCorrelationID,
JMSDestination, JMSDeliveryMode, JMSMessageID, JMSTimestamp, JMSReplyTo,
JMSRedelivered, JMSType, JMSExpiration, and JMSPriority.

• Properties — Message properties can be any of several data types: boolean, byte,
short, int, long, float, double, or String. Custom-defined properties provide
name-value pairs that can be named, typed, populated, sent, and then coerced by the
receiver into other acceptable data types. SonicMQ defines a few properties that are
used to manage undeliverable messages, set per-message encryption, and specify
message types.
• Body — The message body is a set of bytes interpreted as the designated message
type. The message body is actually optional—you can send a message without a body
where the header and property values contain all intended information.

Note: The API provides the method Message_getBodySize(HOBJ msgObj,jint *pret)


that returns the size of a message body in bytes.

Request/Reply
A message producer can specify that it wants more than just acknowledgement from the
broker that the broker received the message. The producer can set a flag indicating that it
would like any consumer of the message to provide an explicit acknowledgement directly
to the producer at a stated destination.

To confirm delivery to its consumer, the message field JMSReplyTo is used as an indicator
that a response is anticipated from the consumer and where that response message should
be sent. The action is, in effect, a reversal of roles where the consumer is asked to produce
the reply message and the original message producer waits at the temporary destination
to consume the return message. While this certifies delivery, in its simplest form, it is
synchronous and therefore a blocking action for the original producer. However, there are
mechanisms that enable asynchronous requests and replies.

Aurea Software, Inc. Confidential 32 Copyright © 2013 Aurea, Inc.


How SonicMQ Applications Work

Quality of Service
Each client application can independently configure the type of message delivery for a
particular destination. Quality of Service is supported by session options and producer
parameters:

• Acknowledgement Mode — The session option determines whether the


acknowledgment of communications between the client and the server are controlled
by the client, the server, or are simply done with reasonable efforts.
• Message Expiration — Messages can be sent with a specific life span to ensure that
clients do not receive out-of-date information. When a message expires, it is dropped
from the queue or from the unfulfilled durable subscriptions.
• Delivery Mode — A persistent message is stored in the broker’s logs and repository
for later delivery to potentially disconnected users. This action provides a higher
quality of service yet produces a corresponding decrease in performance. A persistent
message will survive a system disconnection or unexpected restart. Persistence is
maintained as a message moves across brokers as it is routed.
• Guaranteed Persistence — To make sure that a message will be delivered or exist
on a queue, a message can be flagged for transfer to the system
dead message queue when it expires or gets into an undeliverable situation. On the
DMQ, a message never expires and can only be discarded by explicit action by the
administrator.
• Priority — Messages can be sent with a priority value that encourages the broker to
position that message ahead of other messages in the same queue or topic.
• Redelivery — The broker can make repeated attempts to redeliver messages to each
client that has not acknowledged receipt.

In addition, SonicMQ has features that enable application designers to balance the
workload across several brokers, check the health of a connection, and resume lost
connections.

Disabling Flow Control


Disabling flow control lets applications catch exceptions thrown when messages sent
cause flow problems on the broker. Flow control is an important feature of SonicMQ that
can be turned off on a C Client topic session or queue session.

Quality of Protection
Even when assured of persistence, message integrity can be compromised so that
unauthorized entities can read or change the message. SonicMQ provides features that
enable a message to have an enhanced Quality of Protection (QoP) level:

• Integrity — The contents of the message cannot be altered without the recipient (and
possibly the sender) being informed of the changes.

Aurea Software, Inc. Confidential 33 Copyright © 2013 Aurea, Inc.


Chapter 1: SonicMQ Messaging Concepts

• Privacy — The content of any individual message cannot be viewed by anyone other
than the intended recipient. When you choose Privacy, it includes Integrity as well.

Individual messages can be selectively encrypted by the producer.

Security
SonicMQ provides security options that can be mixed and matched to provide the best
balance of secure message transfer and performance in applications. For example:

• The secure protocol SSL can be used in one connection to a broker while another
connection could use unsecure protocols. Interbroker communication and dynamic
routings can use channel encryption.
• Authentication can use the client side login SPI, external authentication, or built-in
authentication techniques.
• Password-based encryption renders the broker parameter settings readable only by
the broker itself and an authorized administrator.
• User authorization and authentication can be enforced when a connection is
requested.
• Interbroker communication is constrained to authorized routings.
• Access to queues and topics can be read- or write-specific and set to a hierarchy of
destinations. This streamlines security policies for static queues. For dynamically
created hierarchical topics, permissions can be established for topics before they are
created.

Aurea Software, Inc. Confidential 34 Copyright © 2013 Aurea, Inc.


2
Getting Started with the C Client

You can get started with the SonicMQ C Client by installing the client and running the
sample applications. This chapter describes how to set up and run the SonicMQ C sample
applications and explains the messaging concepts the sample applications demonstrate.
You can then use these sample applications to develop your own SonicMQ messaging
applications in C. This chapter includes:

• Running the Sample Applications on page 36 describes how to start the SonicMQ
broker, set up your environment, start the sample applications, and how to compile the
sample applications after you modify them.
• Point-to-point (PTP) Sample Applications on page 41 describes how to run these
sample applications and explains the messaging concepts they illustrate.
• Publish and Subscribe (Pub/Sub) Sample Applications on page 45 describes how to
run these sample applications and explains the messaging concepts they illustrate.
• Interoperating with Other Language Samples on page 53 describes how to explore
various ways to implement a C application.

Note: Platforms and Compilers — Visit the Aurea Sonic web site at [Link]/sonic
for information about supported platforms, processors, and compilers for the C
client.

Downloading and Installing — Register at the Aurea Software web site to qualify
for access to the electronic download location for the C/C++/COM Client
documentation and appropriate platform packages. Expanding the packages on
the corresponding platform installs the software and the documentation.

Release Notes — See the Aurea SonicMQ C/C++/COM Client Release Notes in
the documentation package for information about known issues with the C client.

Aurea Software, Inc. Confidential 35 Copyright © 2013 Aurea, Inc.


Chapter 2: Getting Started with the C Client

Running the Sample Applications


After you install the SonicMQ C Client, you can run the sample applications to better
understand the messaging concepts they demonstrate. The sample applications are
located in the samples directory and are grouped according to the messaging model they
use:

• The Point-to-point sample applications in the QueuePTP folder are examined in


Point-to-point (PTP) Sample Applications on page 41.
• The Publish and Subscribe sample applications in the TopicPubSub folder are
examined in Publish and Subscribe (Pub/Sub) Sample Applications on page 45.

Note: The samples directory also includes the Distributed Transaction sample. This
sample is described in Chapter 7, Running the SonicMQ C XA Transaction Sample
on page 109.

The following sections describe how to run the SonicMQ C Client sample applications:

• Setting Up the SonicMQ Messaging Broker on page 36


• Setting the C Client Environment on page 37
• Using Client Console Windows on page 38
• Starting the Sample Applications on page 38
• Modifying and Compiling the Sample Applications on page 39

Setting Up the SonicMQ Messaging Broker


The C Client makes a connection to an installed and running SonicMQ broker to send and
receive messages. You must access or install a SonicMQ broker on a system in your
network or the Internet to run the sample applications. To install SonicMQ, see your Aurea
Software representative or download an evaluation copy from [Link]/sonic. A
typical broker installation with default parameters installs all the required software and
establishes a TCP listener on port 2506.

After you identify the SonicMQ broker installation you want to use, start the broker
according to the instructions for the product version and platform.

When the broker starts, the console window indicates that it is accepting TCP connections
on a port.

The samples default to localhost:2506—a broker using port 2506 on the same system,
localhost. If you use a different host or port, you must specify the host:port parameter
when you start each sample; for example:

Chat -u Market_Maker -b Eagle:2345

Aurea Software, Inc. Confidential 36 Copyright © 2013 Aurea, Inc.


Running the Sample Applications

Setting the C Client Environment


The following sections describe how to set the client environment on the system where you
plan to run the sample applications.

Setting the Variables and Updating the PATH On


Windows
You must set the path to the libraries. You can do this in one of the following ways:

• As global environment variables.


• Indirectly by putting the libraries in a known path
• Directly by putting the libraries in the same folder as the application
• Locally, by setting the variables in each console session, perhaps from a script

The following sections detail the last option. You put the installation location into a root
variable, create a general script that sets the variable, then use the variable to amend the
PATH statement.

Setting the Root Variable


The installation location of the SonicMQ C Client is typically set on a variable named
SMQROOT. After you have completed your installation, set this variable in the form:

set SMQROOT=cclient_install_dir

Setting the Path to the Libraries


The sample applications require two client .dll files, [Link] and [Link]. These
files must be on the local system and the applications expect their location to be set in the
PATH environment variable.

Using a Setpath Script


To use a Setpath script:

1. In a text editor, create a new file then enter:

set SMQROOT=cclient_install_dir

set PATH=%SMQROOT%\bin\release;%PATH%

2. Save the file as [Link] at an easily accessed location such as, for the C
samples, the root of the directory %SMQROOT%\samples.

3. Open a console window, and then run the script. For example, if you open a console
window to run the Talk sample at samples\C\QueuePTP\Talk, you can run your
setpath script by entering ..\..\..\setpath.

Aurea Software, Inc. Confidential 37 Copyright © 2013 Aurea, Inc.


Chapter 2: Getting Started with the C Client

Setting the Environment on UNIX or Linux


The sample applications require that the [Link] file is on the library path. In a terminal
session, open to the directory where the samples reside and set the environment variables
SMQROOT and LD_LIBRARY_PATH.

For example, in the Bash shell for a Solaris platform:

• export SMQROOT=install_dir/Solaris
• export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$SMQROOT/bin/$BUILDMODE

where BUILDMODE is release (recommended) or debug

Note: The library path referenced as LD_LIBRARY_PATH under Solaris, Linux, and other
UNIX platforms, has variations such as SHLIB_PATH under HP-UX and LIBPATH
under AIX.

Using Client Console Windows


Each application instance should run in its own console window with the current path in the
selected sample directory. Follow these conventions, depending on the platform:

• Windows — The scripts defer to Windows conventions.


• UNIX/Linux— Instead of using .bat files, use the .sh file at the same location.
Substitute forward slash (/) wherever back slash (\) is used as a path delimiter. Any
sourcing is handled in the shell scripts.

Note: Consider all text to be case-sensitive. While there might be some platforms and
names where case is not distinguished, it is good practice to always use case
consistently.

Starting the Sample Applications


The following sections tell you how to start the sample applications on Windows and
UNIX/Linux systems.

To run a SonicMQ C Client application on a Windows system

1. Open a console window to the directory where the application executable will run. For
example:

• On Windows: install_dir\samples\C\QueuePTP\Talk
• On UNIX or Linux: install_dir/samples/C/QueuePTP/Talk

2. Enter the client application executable with its parameters. For example:

Talk -u Sales -qr SampleQ1 -qs SampleQ2

The Talk client application runs in the console window.

Aurea Software, Inc. Confidential 38 Copyright © 2013 Aurea, Inc.


Running the Sample Applications

Modifying and Compiling the Sample


Applications
After exploring the pre-compiled samples, you can modify the sample source files to learn
more about SonicMQ and customize the samples for your own applications. After you
change the source files, you must compile the modified files before you can run them. You
can compile the modified files by running the appropriate mk_c.* file from the command line
in a console window.

The files mk_c.bat (Windows) and mk_c.sh (UNIX/Linux) are included in the samples
directory for compiling and linking your sample applications. The following sections tell you
how to compile the Talk sample on the different platforms:

• Compiling C Applications on Windows on page 39


• Compiling C Applications on Most UNIX and Linux Systems on page 40

Note: Review the make files in a text editor for comments and settings that might be
useful for your platform, operating system, and compiler.

Compiling C Applications on Windows


The following procedure explains how to compile a sample application on a 32-bit Windows
platform using the Microsoft Visual Studio compiler.

To compile a sample C application on Windows:

1. See Setting the Variables and Updating the PATH On Windows on page 37.

2. Set the .dll files ([Link] and [Link]) on the path of the file to be compiled.
This is typically _install_dir\bin\release.

3. Open a console window at the directory level of the sample you want to compile, for
example:

install_dir\Samples\C\QueuePTP\Talk

4. Type the following commands to set the environment variables:

• set BUILDMODE=release and then press ENTER

• set CLIB = “MS_Visual_Studio_install_dir\...\lib” and then press Enter

5. Type the following command to compile the file:

..\..\mk_c Talk and then press ENTER.

The batch file mk_c.bat compiles Talk.c and creates [Link] in the same directory.

Aurea Software, Inc. Confidential 39 Copyright © 2013 Aurea, Inc.


Chapter 2: Getting Started with the C Client

Compiling C Applications on Most UNIX and Linux


Systems
The following procedure tells you how to compile a C application on UNIX or Linux.

To compile a sample application on UNIX or Linux:

1. Open a terminal session on your UNIX or Linux system.

2. Set the following environment variables:

• Set SMQROOT to point to the directory where the C Client libraries reside for your
platform. Using Solaris as an example:

export SMQROOT=install_dir/Solaris

• Set BUILDMODE as follows:

export BUILDMODE=release

• Set LD_LIBRARY_PATH as follows:

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$SMQROOT/bin/$BUILDMODE

using the value you set for the $BUILDMODE variable, release or debug.

Note: The library path—referenced as LD_LIBRARY_PATH under Solaris, Linux, and other
UNIX platforms—has variations such as SHLIB_PATH under HP-UX and LIBPATH
under AIX.

Another method for setting these environment variables is to create a shell script file
containing these exported properties, then source this file to set the properties.

3. Edit the mk_c.sh file to set the following switches correctly in the command line:

• Set the include switch to point to the appropriate include directory:

-I$SMQROOT/include

• Set the library switch to point to the directory containing the [Link] file:

-L$SMQROOT/bin/$BUILDMODE

• The branch statement in mk_c.sh that determines the OS type and invokes the
appropriate compiler.

4. Change the current directory to the directory where the sample source file is, for
example: $SMQROOT/samples/C/QueuePTP/Talk

5. Type the command ../../mk_c.sh Talk and then press Enter.

The shell file mk_c.sh runs, creating the C executable file [Link] in the Talk
directory.

Aurea Software, Inc. Confidential 40 Copyright © 2013 Aurea, Inc.


Point-to-point (PTP) Sample Applications

Point-to-point (PTP) Sample Applications


The Point-to-point (PTP) sample applications demonstrate various messaging concepts
common to both messaging models and some that are unique to PTP messaging.

The PTP sample applications send and receive to specific queues:

• Text you enter is sent on one queue


• Text is received on another queue

There are three PTP sample applications in the folder install_dir\samples\C\QueuePTP

• Talk — Demonstrates basic sending and receiving with PTP messaging


• ReliableTalk — Additionally demonstrates CLIENT_ACKNOWLEDGE on sessions,
PERSISTENT message delivery, an ExceptionListener for connection failure, and
setPingInterval

• SelectorTalk — Shows how clients can define SQL qualifiers that message receivers
can apply to filter messages received.

Important: The PTP sample applications require the sample queues in the broker
database named SampleQ1, SampleQ2, SampleQ3, and SampleQ4. If they are not
present, see the Aurea SonicMQ Configuration and Management Guide to set
up these queues.

Aurea Software, Inc. Confidential 41 Copyright © 2013 Aurea, Inc.


Chapter 2: Getting Started with the C Client

Talk Sample Application


The Talk sample application demonstrates basic PTP messaging. When you type a text
message in one console window, the message is displayed in the other (receiver) window
as it is sent to the specified queue. Any active Talk sample applications are waiting to
receive messages on that queue, taking turns as the sole receiver of the message at the
front of the queue.

This sample application usage is:

Talk -b hostname:port -u username -p password -qs sendqueue -qr recvqueue -ec


compress

where:

-b hostname:port Points to your message broker Default: localhost:2506


-u username Must be unique (checked when using a secure broker)
-p password Password for user (checked when using a secure broker)
-qs sendqueue Name of queue where messages are sent
-qr recvqueue Name of queue from which messages will be received

You can also add the following optional switches to the commandline:

-ec true Enable compression


(See “Enabling Message Compression” on page 67.)
-l Register the default loginSPI. (Only applies when security
is configured to use external authentication).
-ca cadir SSL: Name of the CA directory
-cc cltcert SSL: Client certificate
-pk privkey SSL: Private key for client certificate

To run the Talk sample application:

1. Open two console windows at the directory level of the Talk sample, for example:

install_dir\samples\C\QueuePTP\Talk

2. Start an instance of the application under unique user names in each console window,
specifying a queue for sending and receiving:

Talk -u SALES -qr SampleQ1 -qs SampleQ2

Talk -u MARKETING -qr SampleQ2 -qs SampleQ1

3. In one console window, type text and then press Enter to send the message.

Observe the message in the other console window preceded by the sending user’s
name.

4. Stop a session by entering an empty line of text in its console window.

You can use the Talk sample to demonstrate multiple receivers to the same sender.
Repeat the preceding steps, this time opening three console windows and specifying two
receivers to SampleQ2, in addition to the sender to SampleQ1:

Talk -u Sender -qr SampleQ1 -qs SampleQ2


Talk -u Receiver1 -qr SampleQ2 -qs SampleQ1
Talk -u Receiver2 -qr SampleQ2 -qs SampleQ1

Aurea Software, Inc. Confidential 42 Copyright © 2013 Aurea, Inc.


Point-to-point (PTP) Sample Applications

Now send a series of messages from the Sender and observe how they appear on one or
the other of the Receiver windows.

ReliableTalk Sample Application


The ReliableTalk sample application demonstrates basic PTP messaging and includes
CLIENT_ACKNOWLEDGE and PERSISTENT message delivery. By setting the message delivery
mode to PERSISTENT, the message is logged before the producer is acknowledged and is
guaranteed to be retained in the final broker’s message store until it is either acknowledged
as delivered or expires.

This sample application also demonstrates how to deal with recovery after loss of
connection. It specifies an ExceptionListener for connection failure and
setPingInterval, to monitor the heartbeat of the broker by pinging the broker at a preset
interval, letting the thread sleep for a while but initiating reconnection if the broker does not
respond.

This sample application sends and receive messages on specified queues. If a receiver’s
connection is lost, the receiver attempts to reconnect and continue receiving messages
waiting on the queue.

The ReliableTalk sample application usage is:


ReliableTalk -b hostname:port -u username -p password -qr recvqueue -qs
sendqueue

-b hostname:port Points to your message broker


Default: localhost:2506
-u usernameMust be unique (checked when using a secure broker)
-p password Password for user (checked when using a secure broker)
-qr recvqueue Specify queue for receiving messages
-qs sendqueue Specify queue where message will be sent
-ttl millis Specify message time to live in milliseconds
Default: 180000 (30 minutes)

To run the ReliableTalk sample application:

1. Open two console windows at the directory level of the ReliableTalk sample
application, for example:

install_dir\samples\C\QueuePTP\ReliableTalk

2. Start an instance of the application under unique user names in each console window,
specifying a queue for sending and receiving:

ReliableTalk -u ACCOUNTING -qr SampleQ1 -qs SampleQ2

ReliableTalk -u LEGAL -qr SampleQ2 -qs SampleQ1

3. Type a text message and press Enter to send the message.

Observe the messages that appear under the different user names as you enter
messages in each console window.

4. Stop a session by entering an empty line of text in its console window.

5. Keep sending messages in other sessions.

Aurea Software, Inc. Confidential 43 Copyright © 2013 Aurea, Inc.


Chapter 2: Getting Started with the C Client

6. Restart the session that was stopped.

Observe that the missed messages are still available if the restart is within ten
minutes.

7. Stop the broker and restart it.

Observe the clients trying to reconnect.

For information about setPingInterval, see the “SonicMQ Connections” chapter in the
Aurea SonicMQ Application Programming Guide.

For information about PERSISTENT message delivery, see Chapter 1, Delivery Mode on
page 25.

SelectorTalk Sample Application


Selection criteria lets a message receiver filter the messages on a queue to choose
attributes of acceptable messages. The SQL-92 syntax performs tests on the message in
the receive queue.

In the SelectorTalk application, the application starts by declaring a selector


String-value that will be attached to the message as PROPERTY_NAME=‘String_value’.
They send and receive to alternate queues so that they pass each other messages. The
receive method has a selector string parameter (-s). In PTP domains, all messages on a
queue are filtered on the broker and only the qualified messages are delivered to the
consumer.

The sample application usage is:

SelectorTalk -b hostname:port -u username -p password


-s selection -qr recvqueue -qs sendqueue

-b hostname:port Points to your message broker


The default value is localhost:2506
-u usernameMust be unique (checked when using a secure broker)
-p password Password for user (checked when using a secure broker)
-s selection Required. The value for the property that is filtered
-qr recvqueue Specify queue for receiving messages
-qs sendqueue Specify queue for sending messages

To run the SelectorTalk sample application:

1. Open a console window to the QueuePTP\SelectorTalk folder, then enter:


SelectorTalk -u AAA -s North -qr SampleQ1 -qs SampleQ2

2. Open another console window to the QueuePTP\SelectorTalk folder, then enter:


SelectorTalk -u BBB -s South -qr SampleQ2 -qs SampleQ1

3. In the AAA window, type any text and then press Enter. The message is enqueued but
there is no receiver. The BBB selector string does not see any enqueued messages
except those that evaluate to South.

4. Stop the BBB session by pressing Ctrl+C.

Aurea Software, Inc. Confidential 44 Copyright © 2013 Aurea, Inc.


Publish and Subscribe (Pub/Sub) Sample Applications

5. In that console window start a new session, changing the selector string:
SelectorTalk -u BBB -s North -qr SampleQ2 -qs SampleQ1

The session starts and the message that was enqueued is immediately received.

6. In the AAA window, again type any text and then press Enter. The message is
enqueued and the BBB selector string qualifies the message for delivery.

Publish and Subscribe (Pub/Sub) Sample


Applications
The Pub/Sub sample applications demonstrate how messages are produced and
consumed through topics. There are six Publish and Subscribe sample applications in the
folder install_dir\samples\C\TopicPubSub

• Chat — Demonstrates basic Pub/Sub messaging


• DurableChat — Demonstrates basic Pub/Sub messaging with persistent messages
and durable subscriptions
• HierarchicalChat —Demonstrates basic Pub/Sub messaging using specified topic
nodes
• SelectorChat — Shows how clients can define the SQL qualifiers that message
subscribers can apply to filter messages received
• ReliableChat — Demonstrates basic Pub/Sub messaging with durable subscriptions,
persistent messages, and using an ExceptionListener for connection failure and
setPingInterval

• RequestReply — Demonstrates basic Pub/Sub messaging with synchronous


Request/reply

Chat Sample Application


The Chat sample application demonstrates basic Pub/Sub messaging. This sample
application publishes and subscribes to a specified topic. A message entered in one
session is published and then received by all subscribers.

This sample application usage is:

Chat -b hostname:port -u username -p password

-b hostname:port Points to your message broker


Default: localhost:2506
-u username Must be unique (checked when using a secure broker)
-p password Password for user (checked when using a secure broker)

To run the Chat sample application:

1. Open three console windows at the directory level of the Chat sample, for example:

install_dir\samples\C\TopicPubSub\Chat

Aurea Software, Inc. Confidential 45 Copyright © 2013 Aurea, Inc.


Chapter 2: Getting Started with the C Client

2. Start an instance of the application under unique user names in each console window,
for example:

chat -b localhost:2506 -u SALES

chat -b localhost:2506 -u MARKETING

chat -b localhost:2506 -u LEGAL

3. In each window, enter text and then press Enter to publish the message.

Observe that the messages appear under the assigned user names as you enter
messages in each console window.

4. Stop a session by entering an empty line of text in its console window.

DurableChat Sample Application


The DurableChat sample application demonstrates a basic application using Pub/Sub
messaging as well as persistent messages and durable subscriptions, which are
permanent records in the broker’s database. This sample application publishes and
subscribes to a specified topic. The text you enter is published to the topic with the user
name. The message persists for thirty minutes if the subscriber is not available. If the
subscriber reconnects within that time, the message is delivered.

When messages are published, they are delivered to all active subscribers. Some
subscribers register an enduring interest in receiving messages that were sent while they
are inactive. These durable subscriptions are permanent records in the broker database.

Whenever a subscriber connects to the topic again, all undelivered messages to that topic
that have not expired are delivered immediately. When sessions are running, DurableChat
messages look similar to Chat, but if one of the sessions is interrupted, messages are
retained for it by the broker.

This sample application usage is:

DurableChat -b hostname:port -u username -p password

-b hostname:port Points to your message broker


Default:localhost:2506
-u username Must be unique (checked when using a secure broker)
-p password Password for user (checked when using a secure broker)
-ttl millis Specify message time to live in milliseconds
Default: 1800000 (30 minutes)
-t topic Specify the topic name
Default: [Link].c

To run the DurableChat sample application

1. Open at least three console windows at the directory level of the DurableChat sample,
for example:

install_dir\samples\C\TopicPubSub\DurableChat

2. Start an instance of the application under unique user names in each console window:

Aurea Software, Inc. Confidential 46 Copyright © 2013 Aurea, Inc.


Publish and Subscribe (Pub/Sub) Sample Applications

DurableChat -b localhost:2506 -u ACCOUNTING

DurableChat -b localhost:2506 -u LEGAL

DurableChat -b localhost:2506 -u MARKETING

3. In each window, type text and press Enter to publish the message.

Observe that the messages appear under the assigned user names as you enter
messages in each console window.

4. Stop a session by entering an empty line of text in its console window.

5. Keep sending messages in other sessions.

6. Restart the subscriber session that was stopped.

Observe that the missed messages are still available if the restart is within thirty
minutes.

For information on durable subscriptions, see Chapter 1, Publish and Subscribe


Messaging: Broadcast the Message on page 29. For more details, see the “Publish and
Subscribe Messaging” chapter in the Aurea SonicMQ Application Programming Guide.

HierarchicalChat Sample Application


The HierarchicalChat sample application demonstrates basic Pub/Sub messaging with
hierarchical topics. This sample application publishes and subscribes to specified topic
nodes. Text you enter is published and then received by all subscribers to the topic node.

The HierarchicalChat sample application usage is:

HierarchicalChat -b hostname:port -u username -p password


-t publishertopic -s subscribertopic

-b hostname:portPoints to your message broker Default: localhost:2506


-u usernameMust be unique (checked when using a secure broker)
-p passwordPassword for user (checked when using a secure broker)
-t publisherTopic Name of topic to which to publish. Default: [Link]
-s subscriberTopicName of topic to which to subscribe Default: [Link]

To run the HierarchicalChat sample application:

1. Open two console windows at the directory level of the HierarchicalChat sample, for
example:

install_dir\samples\C\TopicPubSub\HierarchicalChat

2. Start an instance of the application under unique user names in each console window:

HierarchicalChat -u SALES -t sales -s sales.*

HierarchicalChat -u USA -t [Link] -s [Link]

3. Type text messages in both the USA and SALES console windows and press Enter to
publish the message.

Aurea Software, Inc. Confidential 47 Copyright © 2013 Aurea, Inc.


Chapter 2: Getting Started with the C Client

Observe that messages published from the SALES console window to the sales topic
are not seen in the USA console window as it is listening for messages on the
[Link] topic.

Observe that messages published to the [Link] topic are received by the SALES
user listening to sales.*.

4. Stop a session by entering an empty line of text in its console window.

SelectorChat Sample Application


The SelectorChat sample application shows how subscribers to a topic or hierarchy of
topics can delimit the messages that are received. Setting a selector string—an SQL
statement—to test the properties of messages available for delivery, the broker can ignore
messages that do not meet the specified criteria.

The application starts by declaring a String-value selection to attach to the message as


PROPERTY_NAME=‘String_value’. The publisher and the subscriber use the same topic so
that they both can see each other’s messages. All messages published to a topic are
filtered for a C Client on the broker and only the qualified messages are delivered to the C
consumer.

The sample application usage is:

SelectorChat -b hostname:port -u username -p password -s selection

-b hostname:port Points to your message broker


The default value is localhost:2506
-u usernameMust be unique (checked when using a secure broker)
-p password Password for user (checked when using a secure broker)
-s selection Required. The value for the property that is filtered

To start SelectorChat sessions:

1. Open a console window to the TopicPubSub\SelectorChat folder, then enter:


SelectorChat -u Closer -s Sales

2. Open another console window to the TopicPubSub\SelectorChat folder, then enter:


SelectorChat -u Presenter -s Marketing

To SelectorChat:

1. In the Closer window, type any text and then press Enter. The text is only displayed
in that window. The Presenter selector string excludes the Sales message.

2. In the Presenter window, type any text and then press Enter. The text is only
displayed in that window. The Closer selector string excludes the Marketing
message.

3. Stop the Closer session by pressing Ctrl+C.

4. In that console window start a new session, changing the selector string:
SelectorChat -u Closer -s Marketing

Type text in either window and then press Enter. The text is displayed in both windows. The
selector string matches and the message displays.

Aurea Software, Inc. Confidential 48 Copyright © 2013 Aurea, Inc.


Publish and Subscribe (Pub/Sub) Sample Applications

ReliableChat Sample Application


The ReliableChat sample application demonstrates basic Pub/Sub messaging, durable
subscriptions, and persistent messages. This sample application also demonstrates how
to deal with recovery after the loss of a connection. It specifies an ExceptionListener for
connection failure and setPingInterval to monitor the heartbeat of the broker by pinging
the broker at a preset interval, letting the thread sleep for a while but initiating reconnection
if the broker does not respond.

ReliableChat publishes and subscribes to a specified topic. Text you enter is published to
the topic with the user name. The message persists for thirty minutes if the subscriber is
not available. If the subscriber reconnects within that time, the message is delivered.

After you run the basic sample, the syntax is extended to demonstrate how fault tolerant
clients behave in the Sonic Continuous Availability Architecture. See Chapter 2, Extending
ReliableChat for Fault Tolerant Connections on page 50 for details.

The sample application usage is:

ReliableChat -b hostname:port -u username -p password

-b hostname:port Points to your message broker


Default: localhost:2506
-u username Must be unique (checked when using a secure broker)
-p password Password for user (checked when using a secure broker)
-ttl millis Specify message time to live in milliseconds
Default: 1800000 (30 minutes)
-t topic Specify the topic name
Default: [Link].c

To run the ReliableChat sample application:

1. Open at least three console windows at the directory level of the ReliableChat
sample, for example:

install_dir\samples\C\TopicPubSub\ReliableChat

2. Start an instance of the application under unique user names in each console window:

ReliableChat -b localhost:2506 -u ACCOUNTING

ReliableChat -b localhost:2506 -u LEGAL

ReliableChat -b localhost:2506 -u MARKETING

3. In each window, enter text and press Enter to publish a message. Observe that
messages appear under the assigned user names as you enter messages in all
console windows.

4. Stop a session by entering an empty line of text in its console window.

5. Keep sending messages in the other sessions.

6. Restart the subscriber session that was stopped.

Observe that the missed messages are still available if the restart is within thirty
minutes.

Aurea Software, Inc. Confidential 49 Copyright © 2013 Aurea, Inc.


Chapter 2: Getting Started with the C Client

7. Stop the broker and restart it.

Observe the clients trying to reconnect.

Extending ReliableChat for Fault Tolerant


Connections
Reliability becomes virtually certain when you use SonicMQ’s Continuous Availability
Architecture (CAA). When you set up SonicMQ brokers that are licensed for Continuous
Availability, a pair of brokers can provide client fault tolerance (resumption of interrupted
sessions or a network path in a redundant structure) as well as added service that provides
the client with the current standby broker’s URL so that, in the event of a failure, the client
can resume its session on the backup broker.

See Chapter 4, Overview on page 76 for more information about fault tolerant connections
and references to the SonicMQ documentation on the fault tolerant architecture.

To run the ReliableChat sample application for fault tolerant connections:

1. Determine that the broker is licensed to support continuous availability. Create a


backup broker and replication between the primary and backup broker. For this
sample, the replicated brokers are assumed to be at the URLs tcp://host_B1P:2101
(Primary) and tcp://host_B1B:2102 (Backup).

2. Note the host port of each of the replicating brokers. Assume that the primary broker
is the active broker.

3. Open two console windows at:

install_dir\samples\C\TopicPubSub\ReliableChat

4. Start an instance of the application under unique user names in each console window:

a. In the first console window, enter:

ReliableChat -b tcp://host_B1P:2101 -u BOSTON

The connection succeeds.

b. In the other console window, enter:

ReliableChat -b tcp://host_B1P:2101,tcp://host_B1B:2102 -u PARIS -c


true

where the -c true option is sample’s parameter to setFaultTolerant(boolean) on


the connection.

5. Enter messages in the BOSTON and PARIS consoles. The messages are received by
both subscribers.

6. Stop the broker on host_B1P.

The broker fails over to its standby, the broker on host_B1B listening on port 2102. That
broker will standalone until the other broker resumes.

7. Restart broker’s container on host_B1P.

Aurea Software, Inc. Confidential 50 Copyright © 2013 Aurea, Inc.


Publish and Subscribe (Pub/Sub) Sample Applications

When the primary broker comes back on line, it will be the standby broker for the
active broker, the one listening on port 2102 of host_B1B.

8. Enter messages in the BOSTON and PARIS consoles.

The BOSTON console cannot resume. It does not have a fault tolerant connection and it
does not even know the host port of the active broker. Unless the connection list is
changed to include both brokers, BOSTON must wait until the active broker fails so that
the broker accepting connections will again be listening on port 2101 of host_B1P.

The PARIS console resumes receiving messages as if nothing unusual happened in


the broker architecture. The client remembers its state and where the other broker is
located. The now-active broker started accepting connections and waited for PARIS to
connect and resume. Because the sample set the delivery mode of messages to
PERSISTENT, the optimal recovery of messages is available.

9. In the BOSTON console, enter:

ReliableChat -b tcp://host_B1P:2101,tcp://host_B1B:2102 -u BOSTON

The connection list is evaluated. The first connection URL is dedicated to its standby
role so it is not accepting connections. The next connection URL succeeds in
connecting to host_B1B:2102.

10. Publish messages in each console window.

11. Stop the broker on host_B1B.

The BOSTON console cannot resume. It does not have a fault tolerant connection. It
reconnects to host_B1P as a new connection.

The PARIS console continues its connection with only a pause.

Request/Reply Sample Applications


The Request/Reply sample applications demonstrate basic Pub/Sub messaging with
synchronous Request/Reply. There are two RequestReply sample application programs,
replier.c and requestor.c.

A replier is set up to consume a text message, convert it to all uppercase or all lowercase
characters, and then publish it to the topic where the requestor waits for a reply.

Replier Program
A replier will consume a text message, fold the case, and then publish it to the topic where
the requestor waits for reply. When replier.c runs, it waits for messages to the
[Link] topic. When that message occurs, a response based on the
request is sent back to the requestor specified in the JMSReplyTo header. A replier waits for
the request and replies with a message.

The replier.c sample application usage is:

Replier -b hostname:port -u username -p password -m mode

-b hostname:port Points to your message broker

Aurea Software, Inc. Confidential 51 Copyright © 2013 Aurea, Inc.


Chapter 2: Getting Started with the C Client

Default: localhost:2506
-u username Must be unique (checked when using a secure broker
Default: SampleReplier
-p password Password for user (checked when using a secure broker)
Default: password
-m mode Replier mode (uppercase, or lowercase)
Default: uppercase

Requestor Program
When requestor.c runs, it reads input and sends the text as a message to the
[Link] topic. This sample application replies with a simple text manipulation
of the request. The text is either changed to all uppercase or all lowercase. The
requestor.c sample application usage is:

Requestor -b hostname:port -u username -p password

-b hostname:port Points to your message broker


Default: localhost:2506
-u username Must be unique (checked when using a secure broker)
Default: SampleRequestor
-p password Password for user (checked when using a secure broker)
Default: password

To run the RequestReply sample application:

Note: You must run the replier first; otherwise the synchronous request times
out.

1. Open two console windows at the directory level of the RequestReply sample, for
example:

install_dir\samples\C\TopicPubSub\RequestReply

2. Start a replier in one console window:

Replier -u SampleReplier

3. Start a requestor in the other console window:

Requestor -u SampleRequestor

4. Type a text message in lowercase in the requestor window and press Enter.

The replier responds, returning the message in all uppercase characters.

5. Start other requestors with different user names and observe that replies are not
broadcast to all users, for example:

Requestor -u SampleRequestorToo

6. Stop the Replier session by entering an empty line of text in its console window.

7. Start another Replier instance, this time using the lowercase reply mode:

Replier -u toLower -m lowercase

Aurea Software, Inc. Confidential 52 Copyright © 2013 Aurea, Inc.


Interoperating with Other Language Samples

8. Observe that all Replier instances are receiving all the messages (as they should)
and that the Requestor only receives one response.

For more about Request/Reply messaging, see Chapter 1, Request/Reply on page 32.
For more detailed information, see the “Message Producers and Consumers” chapter in the
Aurea SonicMQ Application Programming Guide.

Interoperating with Other Language Samples


After you successfully run the sample applications, you can try other clients to explore
various ways to implement a C application.

Running the Samples with Different Clients


You can run a C Client application in one console window and a non-C application in
another console window to demonstrate how your C Client can communicate with other
types of SonicMQ clients. The following steps tell you how to run both the C++ and C Talk
samples:

To run the C++ and C Talk samples:

1. Open a console window at the directory level of the C++ Talk sample, for example:

install_dir\samples\CPP\QueuePTP\Talk

2. Open a console window at the directory level of the C Talk sample, for example:

install_dir\samples\C\QueuePTP\Talk

3. Start an instance of the Talk application under unique user names in each console
window, specifying a queue for sending and receiving:

Talk -b localhost:2506 -u CPP_Client -qr SampleQ1 -qs SampleQ2

Talk -b localhost:2506 -u C_Client -qr SampleQ2 -qs SampleQ1

4. In the C++ client application console window, type text and then press Enter to send
the message.

You should see the message in C Client console window preceded by the user’s
name.

5. In the C Client application console window, type text and then press Enter to send the
message.

You should see the message in C++ client console window preceded by the user’s
name.

6. Stop a session by entering an empty line of text in its console window.

Aurea Software, Inc. Confidential 53 Copyright © 2013 Aurea, Inc.


Chapter 2: Getting Started with the C Client

Deploying the Sample Applications on Other


Machines
On Windows, you can deploy your compiled applications to other clients by copying the
.dll files and the executable application file to a client machine. If you put the .dll files
and executable file in the same location, you can run the application without changing any
path or environment variables on that system. You can try this deployment with the Talk
sample by placing your [Link] and .dll files in one folder and copying them onto a
different machine.

On UNIX or Linux, put the [Link] file in the client path (LD_LIBRARY_PATH on most
UNIX/Linux platforms) and copy the executable application file to the client machine. Then,
open console windows and run the samples as before.

Aurea Software, Inc. Confidential 54 Copyright © 2013 Aurea, Inc.


3
Programming with the C Client

This chapter examines the sample code provided with the SonicMQ C Client, and explains
how you can implement the features in the samples in your own applications. The chapter
also discusses some additional programming topics and explains how to interface with the
C API. The chapter includes:

• Working with the C Client API on page 55 explains the syntax and implementation of
the C Client API.
• Examining the Sample Application Code on page 68 explains how to establish
connections and sessions for messaging and illustrates these steps with code
excerpts from the SonicMQ C Client samples.

Working with the C Client API


All of the interfaces and methods in the SonicMQ JMS API are suites of functions in the C
Client API. For most functions, the first part of the function's name reflects the related
SonicMQ Java API class. Generally, the first argument in most C function calls is the C
object, similar to a Java object reference. The basic Java utility classes are reproduced in
C.

The SonicMQ C Client actively uses threads—Win32 threads on Windows and pthreads on
UNIX/Linux. Your application code must be multi-threaded when it interacts with SonicMQ.

The following sections provide information and advice for working with the C Client API.

Aurea Software, Inc. Confidential 55 Copyright © 2013 Aurea, Inc.


Chapter 3: Programming with the C Client

Header Files
The header file, smqc.h, contains all of the C Client API declarations. Your C Client
application must include smqc.h in each source file that uses the client interface:

#include <smqc.h>

and link to an import library module on Windows or a shared library on UNIX/Linux. At


run-time, the client code is loaded as:

• A dynamic library on Windows


• A shared library on UNIX/Linux

Macros
The header file, smqc.h, uses macros to represent C inheritance. These macros are a
convenience, but if you learn the API, you can program without them.

For example, if you look at the TextMessage section of smqc.h, it contains many #define
macros, including:

#define TextMessage_getIntProperty(textMsg, name, pret)


Message_getIntProperty(textMsg, name, pret)

Here, TextMessage_getIntProperty is a convenience for working with a TextMessage


object. However, Message_getIntProperty is the library entry point that is called.

HOBJs
The C Client interface uses an HOBJ to represent every object. (An HOBJ is a handle to an
opaque object.) You pass an HOBJ into other methods, using C entry points that operate on
that type of object.

To obtain an HOBJ, call a factory method, as in this excerpt from the Talk.c sample
application:

Obtaining an HOBJ
/* Create string objects to work with. */
if ((String_create2(broker, &brokerObj) != 0) ||
(String_create2((char *)"", &connectIdObj) != 0) ||
(String_create2(username, &usernameObj) != 0) ||
(String_create2(password, &passwordObj) != 0) ||
(String_create2(sQueueName, &sQueueNameObj) != 0) ||
(String_create2(rQueueName, &rQueueNameObj) != 0))
{
fprintf(stderr, "Error creating String object(s)\n");
handleJMSException();
goto exit_cleanly;
}

Here, String_create2 is the factory that takes a char* as a parameter and returns an HOBJ
representing a string and a status code.

Aurea Software, Inc. Confidential 56 Copyright © 2013 Aurea, Inc.


Working with the C Client API

Since there are many string factories, they are distinguished by numeric designations; for
example, here 2 is appended to String_create.

From the HOBJ, you can query its type with Message_getType, as in this excerpt from the
Talk.c sample application:

Querying an HOBJ Type


}
else
{
int msgType;
if (Message_getType(aMessage, &msgType) != 0) {
fprintf(stderr, "Error getting message type\n");
handleJMSException();
}
else {
fprintf(stderr, "Unsupported message type received: %d\n", msgType);
}
}

You can also use Message_type( ) to check whether a message is the type you require,
for example, a text message. Use Message_instanceof( )and pass it the message HOBJ
that was sent. Then use another parameter for the result, TRUE or FALSE, as in this excerpt
from the Talk.c sample application:

Checking an HOBJ Type


/* Cast the message as a TextMessage if possible. */
if (Message_instanceof(aMessage, TextMessage_type(), &isTextMessage) != 0)
{
fprintf(stderr, "Error testing type of message\n");
handleJMSException();
}
else if (isTextMessage)
{
char *string;
HOBJ text;

text = NULL;
}

Bytes Message
For a BytesMessage, use an HOBJ that points to a jbyteArray to create an array then use
jbyteArrayRef when reading and sending the message.

Handling Strings
The C Client API works almost exclusively with HOBJs to represent string objects, rather
than with arrays of characters. This reflects the platform-independent implementation in
C++ of the C Client library. The exceptions are the string factory API that take char* or
wchar_t* as parameters and the AString_*, WString_*, and UTF8String_* APIs that
return char* and wchar_t* respectively.

Aurea Software, Inc. Confidential 57 Copyright © 2013 Aurea, Inc.


Chapter 3: Programming with the C Client

This approach requires an extra step to get text into or out of the system. Therefore, the
String_* API contains many of the typical string operations. If you are examining or altering
a string HOBJ to submit it back to the C Client, you might consider operating directly on the
HOBJ, rather than extracting the character array.

This excerpt from the Talk.c sample application obtains the message text as an HOBJ and
then calls a helper function, copyOutString( ), to extract a char* for output to the console:

Obtaining Message Text as an HOBJ


/* This handler reads a single string from the
message and prints it to the standard output. */

if (TextMessage_getText(aMessage, &text) != 0)
{
fprintf(stderr, "Error retrieving text from TextMessage\n");
handleJMSException();
} else if ((string = copyOutString(text)) == NULL) {
fprintf(stderr, "Error copying text from TextMessage\n");
handleJMSException();
}
else {
fprintf(stdout, "%s\n", string);
free(string);
}

if (text)
{
String_release(text, &retval);
text = NULL;
}
else {
int msgType;
if (Message_getType(aMessage, &msgType) != 0) {
fprintf(stderr, "Error getting message type\n");
handleJMSException();
}
else {
fprintf(stderr, "Unsupported message type received: %d\n", msgType);
}
}

Using Bytes Messages


For a BytesMessage, use jbyteArray_create to create an array (rather than trying to use
the new operator) then use jbyteArray when reading and sending the message. The
following code segments show patterns for sending and receiving a BytesMessage.

Sending a BytesMessage
Data is moved to a jbyteArray to a BytesMessage for sending:

Myfunc ()
{
typedef MyStruct;
MyStruct foo;
HOBJ byteValues;
jbyte *ptr;

Aurea Software, Inc. Confidential 58 Copyright © 2013 Aurea, Inc.


Working with the C Client API

/* Do something with foo */

/* Load foo into a jbyte array */


jbyteArray_create (sizeof (MyStruct), &byteValues);

/* get a pointer to the bytes in the jbyte array */


jbyteArray_getArray(byteValues, &ptr);

/* Copy from foo to the jbyte array */


memcpy ((void *)&foo, (void *)ptr, sizeof (MyStruct));

/* Create a bytes message */


Session_createBytesMessage(mySession, &msg );

/* Load the jbyte array into the bytes message */


BytesMessage_writeBytes(msg, byteValues);
}

Receiving a BytesMessage
On receipt of a BytesMessage, data moves from the BytesMessage to a jbyteArray:

void onMessage(HOBJ aMessage)


{
MyStruct gotFoo;
HOBJ byteValues;
jint msgSize = 0;
jbyte *ptr;

/* Create an empty jbyte array */


jbyteArray_create (sizeof (MyStruct), &byteValues);

/* Get the message body size */


BytesMessage_getBodySize(aMessage, &msgSize );

/* Get the bytes from the message */


BytesMessage_readBytes(aMessage, byteValues, msgSize );

/* get a pointer to the bytes in the jbyte array */


jbyteArray_getArray(byteValues, &ptr);

/* Copy from the jbyte array to foo */


memcpy ((void *)&gotFoo, (void *)ptr, sizeof (MyStruct));
}

Callback Functions
In the C Client, asynchronous messages and exceptions are specified as callback function
pointers. The application must keep track of the listener contexts if there is more than one,
as the callback functions receive only a single message or exception HOBJ.

Here is an example from the Talk.c sample application:

if (QueueReceiver_setMessageListener(receiver, onMessage) != 0)
{
fprintf(stderr, "Error setting message listener\n");

Aurea Software, Inc. Confidential 59 Copyright © 2013 Aurea, Inc.


Chapter 3: Programming with the C Client

handleJMSException();
goto exit_cleanly;
}

Releasing Objects and Avoiding Memory


Leaks
When you finish with an HOBJ, you must explicitly call a release method and give it an object
reference as in this excerpt from the Talk.c sample application:

Releasing Objects
/* Clean up. Order doesn't matter. */
if (msg)
Message_release(msg, &retval);

/* SonicMQ allocated this one, so "release" it. */


if (textObj)
String_release(textObj, &retval);

/* Application allocated this one, so "free" it. */


if (text)
free(text);

If you do not release the HOBJs, remaining references will cause memory leaks. Note that
all *_release API are mapped to Object_release so that Object_release can be called to
release any HOBJ.

Also, be sure to close and destroy connections or they will cause memory leaks. The
correct sequence is to close the producer (publisher or sender), then the session, and then
the connection.

Every _release() function decrements its argument object’s ref count, and objects are
destroyed when their ref counts reach 0. When you are done with an HOBJ, release it—if
the Sonic Client runtime needs a reference to that object, it will keep that reference and
your _release will not destroy the object. If the runtime needs to copy the contents of the
object into some other representation, it will do it and will not keep a reference to the original
object so that your _release() will destroy the object (provided that it was the last reference
to it.)

In summary, release HOBJs when your code does not need them anymore and trust the
runtime to do the right thing. (In much the same way that the Win32 API exposes kernel
objects via handles to them and operations on those handles.)

The following C code example sets and then releases string properties.

Example of releasing objects


/*
@Copyright 2010 Aurea Software Corporation and/or its affiliates or
subsidiaries.
All rights reserved.
*/
long ref_count_after_release = 0;
char* property_name = (char*)"string_property_name";
char* property_value = (char*)"string_property_value";

Aurea Software, Inc. Confidential 60 Copyright © 2013 Aurea, Inc.


Working with the C Client API

HOBJ property_name_obj = 0;
HOBJ property_value_obj = 0;
HOBJ message_obj = 0;

if (String_create2(property_name, &property_name_obj) != SMQ_SUCCESS) {


// Handle the error.
//
return;
}
if (String_create2(property_value, &property_value_obj) != SMQ_SUCCESS) {
// Handle the error.
//
String_release(property_name_obj, &ref_count_after_release);
return;
}
if (Message_create(&message_obj) != SMQ_SUCCESS) {
// Handle the error.
//
String_release(property_name_obj, &ref_count_after_release);
String_release(property_value_obj, &ref_count_after_release);
return;
}
if (Message_setStringProperty(message_obj, property_name_obj,
property_value_obj) != SMQ_SUCCESS) {
// Handle the error.
//
String_release(property_name_obj, &ref_count_after_release);
String_release(property_value_obj, &ref_count_after_release);
Message_release(message_obj, &ref_count_after_release);
return;
}
// At this point our string property has been set and we do not
// need the name and value Strings anymore, so release them.
//
String_release(property_name_obj, &ref_count_after_release);
String_release(property_value_obj, &ref_count_after_release);

To try it, copy the text in Example of releasing objects on page 60, and then build it.

Exceptions
Exceptions cannot be thrown or caught in C, but they are in the C Client API because of
the exception listener, a way for an application to watch for dropped connections. If an HOBJ
is sent to your exception listener callback you can pass it back into the exception entry
points, for example, Exception_getMessage, to extract the message for further processing.
The application must release the HOBJ when it finishes with it.

SonicMQ exceptions result in C function return values that are nonzero. Using the
SMQ_getLastError() function interrogates the last error returned by a C API call, and
SMQ_getLastErrorText( ) retrieves the associated error text.

Here is a typical example from the Talk.c sample application:

Retrieving Exceptions
/**
* See if there was an error during the last API call.

Aurea Software, Inc. Confidential 61 Copyright © 2013 Aurea, Inc.


Chapter 3: Programming with the C Client

* Displays error message, if any.


* Returns 0 if there was no error, 1 if there was.
*/
int handleJMSException()
{
jint lastError;
if ((lastError = SMQ_getLastError()) != SMQ_SUCCESS) {
HOBJ errmsgObj;
char *errmsg;

if ((errmsgObj = SMQ_getLastErrorText()) != NULL) {


long retval;
if ((errmsg = copyOutString(errmsgObj)) != NULL) {
fprintf(stderr, errmsg);
fprintf(stderr, "\n");
free(errmsg);
}
String_release(errmsgObj, &retval);
}
return 1;
}
return 0;
}

The library only keeps track of one exception per thread at a time. The next exception
causes the previous one to be destroyed if not queried by the application.

For example, if a client attempts to read a message in write-only mode, a


MessageNotReadableException is thrown. If a client attempts to write a message in
read-only mode, a MessageNotWriteableException is thrown.

The error codes returned by SMQ_getLastError correspond to the enumerators for


exception classes in the classtypes.h file.

Using Message Selectors


Message selectors for SonicMQ C Clients are passed to the broker where the tests are
applied. Message filtering does not take place on the client. In the sample
cclient_install_dir\samples\QueuePTP\SelectorTalk\SelectorTalk.c, the sample
presets the property it will test:

char PROPERTY_NAME[] = "Department";

and defines a variable that the user will enter as a command line parameter:

char *selection;

When the user inputs a value for -s selection, these values are assembled after user input
as selectorString:

char selectorString [256];


sprintf (selectorString, "%s = \'%s\'", PROPERTY_NAME, selection);
String_create2(selectorString, &selectorStringObj);

The message consumer session is defined for a rQueue and qualified by


selectorStringObj by using the function:

Aurea Software, Inc. Confidential 62 Copyright © 2013 Aurea, Inc.


Working with the C Client API

QueueSession_createReceiver2(recvSession, rQueue, selectorStringObj,


&receiver)

The selection test in this basic example is the property name to be tested for equivalence
to the given value. As described in the sample, the selectorString is Department, SALES
which formats into the SQL statement:

“Department=’SALES’”

The only messages in the receiver queue that will be delivered to the receiver are those
that have the property Department set to the value SALES.

Wide Characters
If your application uses Unicode characters, as either UCS-2 or UTF-8, use the most
appropriate alternate string factory methods and extraction classes.

• For UCS-2 (that is, fixed-width 2-byte characters, as on Windows NT):


• Create strings with String_create8(wchar_t*, HOBJ*).
• Extract a string under UCS-2 with the String_toWide() method
• For UTF-8:
• Create strings that specify the encoding along with the string data, such as
String_create9(str, "UTF-8", &obj).

• Extract a string under UTF-8, use String_toUTF8().

Further manipulation of Unicode character data is outside the scope of the SonicMQ C
Client. The International Components for Unicode (ICU) is a C library that supports Unicode
on a wide variety of platforms. The ICU software is available under public license from IBM
at [Link]

Characters Used in SonicMQ Names


The following table lists characters that are allowed in SonicMQ identifier names.

Table 1: Characters for Names

Name Allowed Characters and Special Use

ClientID All alphanumeric characters, ASCII punctuation and symbols are allowed
except period (.), asterisk (*), pound (#), slash (/), and dollar sign ($).

ConnectID All alphanumeric characters, ASCII punctuation and symbols are allowed
except period (.), asterisk (*), pound (#), slash (/). and dollar sign ($).

Durable All alphanumeric characters, ASCII punctuation and symbols are allowed
Subscription except period (.), dollar sign ($), slash (/), and backslash (\). Note that asterisk
(*) and pound sign (#) have wildcard meaning.

Aurea Software, Inc. Confidential 63 Copyright © 2013 Aurea, Inc.


Chapter 3: Programming with the C Client

Table 1: Characters for Names

Name Allowed Characters and Special Use

Queue All alphanumeric characters, ASCII punctuation and symbols are allowed
except backslash (\), slash (/), and dollar sign ($).
Note that:
Asterisk (*) and pound sign (#) have wildcard meaning when specifying
ranges of queue names in subscription names and ACLs.
Adjacent colons (::) are reserved for delimiting sections of global routing
names.

Routing Node All alphanumeric characters, ASCII punctuation and symbols are allowed
except asterisk (*), pound (#), dollar sign ($), slash (/), backslash (\), double
colon (::), and double quote (").

Topic All alphanumeric characters, ASCII punctuation and symbols are allowed
except slash (/), backslash (\) and single brackets ([ or ])
Note that:
Asterisk (*) and pound sign (#) have wildcard meaning.
Colon (:) is reserved for a remote topic name.
Adjacent colons (::) are reserved for delimiting sections of global routing
names.
Double brackets ([[ ]] )enclose a shared subscription identifier.
Names that begin with a dollar sign ($) or the character string “SonicMQ” are
reserved for system use.

User, All alphanumeric characters, ASCII punctuation and symbols are allowed
Routing User except asterisk (*), pound (#), dollar sign ($), slash (/), and backslash (\).

Using the Nagle Algorithm (TcpNoDelay)


The Nagle algorithm, TcpNoDelay, allows buffering of small data before sending the data as
a fully constructed IP packet. The Nagle algorithm addresses the network congestion issue
of sending many small JMS messages by sending fewer large packets of data, each
containing many small messages.

In SonicMQ, the Nagle algorithm is disabled by default. A Sonic C Client and the Sonic
broker can each set the TcpNoDelay option.

Broker Setting
The broker tunes the TcpNoDelay setting in its broker properties panel on the Tuning tab.
Setting the value to true disables the Nagle algorithm and minimizes small message
latency. A value of false enables the Nagle algorithm.

Aurea Software, Inc. Confidential 64 Copyright © 2013 Aurea, Inc.


Connection Factories

Client Setting
While the Java-based clients have the option of setting a virtual machine parameter or
using a Management API method to set the Nagle algorithm, neither of these techniques is
available in the C Client.

You can set the Nagle algorithm in SonicMQ C Client applications by using setter methods
as follows:

• int QueueConnectionFactory_setTcpNoDelay(HOBJ thisObj, jboolean


noDelay);
• int TopicConnectionFactory_setTcpNoDelay(HOBJ thisObj, jboolean
noDelay);

where

• true disables the Nagle algorithm and minimizes small message latency.

• false enables the Nagle algorithm.

Similarly getter methods let you test the current setting:

• int QueueConnectionFactory_getTcpNoDelay(HOBJ thisObj, jboolean


*pret);
• int TopicConnectionFactory_getTcpNoDelay(HOBJ thisObj, jboolean
*pret);

Connection Factories
To establish a connection with the SonicMQ broker, a client uses a ConnectionFactory
object. Model-specific factories are required for the Pub/Sub and PTP message models in
the SonicMQ C Client.

These connection factories are:

• QueueConnectionFactory
• TopicConnectionFactory

Note: In this chapter, references that are appropriate to either connection factory are
presented in the form: [Queue|Topic]ConnectionFactory.

Note: SonicMQ Java clients can use unified domain syntax as well as messaging model
specific syntax. QueueConnectionFactory and TopicConnectionFactory can be
used as well as the common ConnectionFactory. Java clients also require
distributed transactions to use the XAConnectionFactory, a model that is not
required in the C Client.

Aurea Software, Inc. Confidential 65 Copyright © 2013 Aurea, Inc.


Chapter 3: Programming with the C Client

Minimize subscriber The connection factories support functionality to minimize subscriber traffic. When enabled,
traffic
the subscriber will attempt to flow control the broker immediately after the very first
message is received. The subscriber could receive more messages put on the wire by the
broker before it receives the flow control message. The sending will resume when the
subscriber's buffer becomes empty.

int TopicConnectionFactory_setMinimizeSubscriberTraffic
(HOBJ thisObj, jboolean minimizeTraffic);

where:

• thisObj is the TopicConnectionFactory object to operate against.


• minimizeTraffic when set to true will minimize the subscriber traffic.

Connection Factory SonicMQ connection factory objects encapsulate the information needed to connect and
information
configure the SonicMQ JMS client connection, including:

• Host, port, and protocol information


• User, password, and other identity information
• Load balancing, fault-tolerance, and similar connection or session behavioral settings

The most essential connection factory settings are discussed in the following sections.

Important: Some characters are not allowed in SonicMQ names. In the context of
Connection Factory settings, generally period (.), asterisk (*), pound (#),
slash (/), and dollar sign ($) are not allowed. See Appendix A of the Aurea
Sonic Installation and Upgrade Guide for more information on using
characters in SonicMQ names.

URL
The Uniform Resource Locator (URL) identifies the host port and protocol for the
connection. The URL is in the form:

[protocol://]hostname[:port]

where:

• protocol is the broker’s communication protocol (default value: tcp).

• hostname is a networked SonicMQ broker machine.

• port is the port on the host where the broker is listening. The broker’s default
port value is 2506.

ConnectID
The ConnectID determines whether the broker allows multiple connections to be
established using a single username/ConnectID combination. You control the broker’s
behavior by calling the [Queue|Topic]ConnectionFactory_setConnectID method and
either providing a value (allow only one connection), or null (allow unlimited connections.)

Aurea Software, Inc. Confidential 66 Copyright © 2013 Aurea, Inc.


Connection Factories

Username and Password


The username and password define a principal’s identity maintained by the SonicMQ
broker’s authentication domain to authenticate a user with the SonicMQ broker and the
broker’s authorization policy to establish permissions and access rights.

When the broker is not security-enabled, these parameters are optional, and a named user
is simply a text label.

ClientID
The ClientID is a unique identifier to avoid conflicts for durable subscriptions when many
clients might be using the same username and the same subscription name.

The value of the ClientID is set in either of two ways:

• In the client application, immediately after creating a connection, call the


Connection_setClientID method.

• Call the [Queue|Topic]ConnectionFactory_setClientID method in the client


application.

Enabling Message Compression


Some throughput problems are caused by large messages and low bandwidth networks.
Applications that produce and consume messages of significant size over these slow
networks might improve overall performance by compressing messages.

The setEnableCompression methods declared in smqc.h in the


QueueConnectionFactory and in the TopicConnectionFactory cause messages
produced in the scope of the connection factory to be compressed so that:

• MessageProducers compress every message before sending it, and the broker
decompresses every message it receives on these connections.
• MessageConsumers decompress every message when received because the broker
compressed every message it delivered to the consumer on these connections.

When a SonicMQ client application enables message compression, the client negotiates
with the broker to which it is connecting to agree on the compression characteristics and
error checking. The actual compression and decompression functions are implicit when the
option is enabled.

Message compression has time and space requirements on both the client and the broker.
An administrator needs to determine which connections can offset the compression
overheads with the savings in message transfer time, and how many connections that
enable compression can be supported by the broker’s resources.

The following syntax enables message compression on a connection factory:

int SMQ_API QueueConnectionFactory_setEnableCompression


(HOBJ thisObj, jboolean enabled);

Aurea Software, Inc. Confidential 67 Copyright © 2013 Aurea, Inc.


Chapter 3: Programming with the C Client

int SMQ_API TopicConnectionFactory_setEnableCompression


(HOBJ thisObj, jboolean enabled);

where enabled as true enables message compression.

Corresponding get methods are provided:

int SMQ_API QueueConnectionFactory_getEnableCompression


(HOBJ thisObj, jboolean *pret);

int SMQ_API TopicConnectionFactory_getEnableCompression


(HOBJ thisObj, jboolean *pret);

The “Talk Sample Application” on page 53 provides an option to enable compression at the
sample’s commandline to make it easy to explore this feature.

This option can be set on Connection Factories that are defined as Administered Objects.
See the Aurea SonicMQ Configuration and Management Guide for information.

Examining the Sample Application Code


The sample applications demonstrate most of the functionality available from SonicMQ
using the C Client API. You can use these sample applications as the basis for building your
own applications.

The following sections use excerpts from various sample applications. For more
information on the sample applications, see Chapter 2, Getting Started with the C Client on
page 35.

Creating Connections and Sessions


The recommended way to create a connection is to call a method on a connection factory.
Using connection factories allows you to set properties for load balancing and failover and
the connection will then inherit the properties of the connection factory. (See the SonicMQ
documentation set for detailed information about connection factories, load balancing, and
connection balancing.)

The sample applications do not implement connection factories. Instead, they create
connections and sessions directly, as in the following excerpt from the Talk.c sample
application:

Creating Connections and Sessions Directly


/* Create a connection and sessions. */
if (QueueConnection_create(brokerObj, connectIdObj, usernameObj,
passwordObj, &connection) != 0)
{
fprintf(stderr, "Error creating QueueConnection\n");
handleJMSException();
goto exit_cleanly;
}

if (QueueConnection_createQueueSession(connection, 0,
Session_AUTO_ACKNOWLEDGE, &sendSession) != 0)

Aurea Software, Inc. Confidential 68 Copyright © 2013 Aurea, Inc.


Examining the Sample Application Code

{
fprintf(stderr, "Error creating QueueSession\n");
handleJMSException();
goto exit_cleanly;
}

if (QueueConnection_createQueueSession(connection, 0,
Session_AUTO_ACKNOWLEDGE, &recvSession) != 0)
{
fprintf(stderr, "Error creating QueueSession\n");
handleJMSException();
goto exit_cleanly;
}

Creating Queues, Senders, and Receivers


The following excerpt from the Talk.c sample application illustrates how to create queues
(for sending or receiving messages), senders, receivers, and how to register a message
listener callback:

Creating Queues, Senders, and Receivers


/* Create queues, sender and receiver to 'talk' queues */
if (sQueueNameObj != NULL) {
if (QueueSession_createQueue(sendSession, sQueueNameObj, &sQueue) != 0) {
fprintf(stderr, "Error creating sending queue\n");
handleJMSException();
goto exit_cleanly;
}

if (QueueSession_createSender(sendSession, sQueue, &sender) != 0) {


fprintf(stderr, "Error creating QueueSender\n");
handleJMSException();
goto exit_cleanly;
}
}

if (rQueueNameObj != NULL) {
if (QueueSession_createQueue(sendSession, rQueueNameObj, &rQueue) != 0) {
fprintf(stderr, "Error creating receiving queue\n");
handleJMSException();
goto exit_cleanly;
}

if (QueueSession_createReceiver(recvSession, rQueue, &receiver) != 0) {


fprintf(stderr, "Error creating QueueReceiver\n");
handleJMSException();
goto exit_cleanly;
}

if (QueueReceiver_setMessageListener(receiver, onMessage) != 0) {
fprintf(stderr, "Error setting message listener\n");
handleJMSException();
goto exit_cleanly;
}
}

Aurea Software, Inc. Confidential 69 Copyright © 2013 Aurea, Inc.


Chapter 3: Programming with the C Client

Starting a Connection
The following excerpt from the Talk.c sample application starts a connection:

Starting a Connection
/* Now that 'receive' setup is complete, start the Connection */
if (QueueConnection_start(connection) != 0) {
fprintf(stderr, "Error starting connection\n");
handleJMSException();
goto exit_cleanly;
}

Creating a Message
The following excerpt from the Talk.c sample application creates a message:

Creating a Message
/* Create a message from the string. */
else if (QueueSession_createTextMessage2(sendSession, textObj, &msg) != 0)
{
fprintf(stderr, "Error creating TextMessage\n");
handleJMSException();
}

Sending a Message
The following excerpt from the Talk.c sample application sends a persistent message and
specifies holding messages for 30 minutes (1,800,000 milliseconds):

Sending a Message
/* Send the message. Queues usually are used for PERSISTENT messages.
* Hold messages for 30 minutes (1,800,000 milliseconds).*/
else if (QueueSender_send2(sender, msg, DeliveryMode_PERSISTENT,
Message_DEFAULT_PRIORITY, MESSAGE_LIFESPAN) != 0)
{
fprintf(stderr, "Error sending message\n");
handleJMSException();
}

Cleaning Up After Sending a Message


The following excerpt from the Talk.c sample application cleans up after sending a
message:

Cleaning Up After Sending a Message


/* Clean up. Order doesn't matter. */
if (msg)
Message_release(msg, &retval);
/* SonicMQ allocated this one, so "release" it. */
if (textObj)
String_release(textObj, &retval);

Aurea Software, Inc. Confidential 70 Copyright © 2013 Aurea, Inc.


Examining the Sample Application Code

/* Application allocated this one, so "free" it. */


if (text)
free(text);
}
else {
fprintf(stderr, "Couldn't get memory for string\n");
}
}
}
exit_cleanly:

Receiving a Message Asynchronously


The following excerpt from the Talk.c sample application receives a message
asynchronously and casts the message as a TextMessage:

Receiving a Message Asynchronously


/* Handle the message*/
void onMessage(HOBJ aMessage)
{
long retval;
int isTextMessage;

/* Cast the message as a TextMessage if possible. */


if (Message_instanceof(aMessage, TextMessage_type(), &isTextMessage) != 0) {
fprintf(stderr, "Error testing type of message\n");
handleJMSException();
}
else if (isTextMessage) {

char *string;
HOBJ text;

text = NULL;

/* This handler reads a single string from the


message and prints it to the standard output. */
if (TextMessage_getText(aMessage, &text) != 0) {
fprintf(stderr, "Error retrieving text from TextMessage\n");
handleJMSException();
} else if ((string = copyOutString(text)) == NULL) {
fprintf(stderr, "Error copying text from TextMessage\n");
handleJMSException();
}
else {
fprintf(stdout, "%s\n", string);
free(string);
}

if (text) {
String_release(text, &retval);
text = NULL;
}
}
else {
int msgType;
if (Message_getType(aMessage, &msgType) != 0) {
fprintf(stderr, "Error getting message type\n");

Aurea Software, Inc. Confidential 71 Copyright © 2013 Aurea, Inc.


Chapter 3: Programming with the C Client

handleJMSException();
}
else {
fprintf(stderr, "Unsupported message type received: %d\n", msgType);
}
}

/* Release the message the system sent to us. */


Message_release(aMessage, &retval);
}

Receiving a Message Synchronously


The following excerpt from the requestor.c file in the RequestReply sample application
receives a message synchronously and casts the message as a TextMessage:

Receiving a Message Synchronously


/* Set up the request/reply helper */
else if (TopicRequestor_init(session, topic) != 0) {
fprintf(stderr, "Error initializing TopicRequestor\n");
}

/* Send the request, wait for the reply */


else if (TopicRequestor_request(msg, REQUESTREPLY_TIMEOUT, &response) !=
0) {
fprintf(stderr, "Error in TopicRequestor_request\n");
}

/* Cast the response to a TextMessage */


else if (Object_instanceof(response, TextMessage_type(), &isTextMessage)
!= 0) {
fprintf(stderr, "Error casting response to TextMessage\n");
handleJMSException();
}

else if (TextMessage_getText(response, &responseTextObj) != 0) {


fprintf(stderr, "Error getting Text from TextMessage\n");
handleJMSException();
}
else if ((responseText = copyOutString(responseTextObj)) == NULL) {
fprintf(stderr, "Error copying text from response\n");
handleJMSException();
}
else {
fprintf(stdout, "%s\n", responseText);
/*free32(responseText);*/
}

Specifying Acknowledgement and Persistence


The following excerpt from the ReliableTalk.c sample application shows how to specify
CLIENT_ACKNOWLEDGE on sessions, persistent message delivery, an ExceptionListener
for connection failure, and setPingInterval. (For more information, see Chapter 2,
ReliableTalk Sample Application on page 43). This excerpt creates a connection and
sessions:

Aurea Software, Inc. Confidential 72 Copyright © 2013 Aurea, Inc.


Examining the Sample Application Code

Specifying Acknowledgement and Persistence


/* Create a connection and sessions. */
if (QueueConnection_create(brokerObj, connectIdObj, usernameObj,
passwordObj, &connection) != 0)
{
fprintf(stderr, "Error creating QueueConnection\n");
handleJMSException();
goto exit_cleanly;
}

if (QueueConnection_setClientID(connection, clientIDObj) != 0)
{
fprintf(stderr, "Error setting client ID\n");
handleJMSException();goto exit_cleanly;
}

if (QueueConnection_setPingInterval(connection, 30) != 0)
{
fprintf(stderr, "Error setting ping interval\n");
handleJMSException();
goto exit_cleanly;
}

if (QueueConnection_createQueueSession(connection, 0,
Session_CLIENT_ACKNOWLEDGE, &sendSession) != 0)
{
fprintf(stderr, "Error creating QueueSession\n");
handleJMSException();
goto exit_cleanly;
}

if (QueueConnection_createQueueSession(connection, 0,
Session_CLIENT_ACKNOWLEDGE, &receiveSession) != 0)
{
fprintf(stderr, "Error creating QueueSession\n");
handleJMSException();
goto exit_cleanly;
}

if (rQueueNameObj != NULL) {

if (QueueSession_createQueue(receiveSession, rQueueNameObj, &rQueue) != 0)


{
fprintf(stderr, "Error creating receive queue\n");
handleJMSException();
goto exit_cleanly;
}
if (QueueSession_createReceiver(receiveSession, rQueue, &receiver) != 0)
{
fprintf(stderr, "Error creating QueueReceiver\n");
handleJMSException();
goto exit_cleanly;
}

if (QueueReceiver_setMessageListener(receiver, onMessage) != 0)
{
fprintf(stderr, "Error setting message listener\n");
handleJMSException();
goto exit_cleanly;
}

Aurea Software, Inc. Confidential 73 Copyright © 2013 Aurea, Inc.


Chapter 3: Programming with the C Client

}
if (sQueueNameObj != NULL) {

if (QueueSession_createQueue(sendSession, sQueueNameObj, &sQueue) != 0)


{
fprintf(stderr, "Error creating send queue\n");
handleJMSException();
goto exit_cleanly;
}

if (QueueSession_createSender(sendSession, sQueue, &sender) != 0)


{
fprintf(stderr, "Error creating QueueSender\n");
handleJMSException();
goto exit_cleanly;
}
}
if (QueueConnection_setExceptionListener(connection, onException) != 0)
{
fprintf(stderr, "Error setting exception listener\n");
handleJMSException();
goto exit_cleanly;
}

fprintf(stdout, "...Setup complete\n");

Aurea Software, Inc. Confidential 74 Copyright © 2013 Aurea, Inc.


4
High Availability Connections

This chapter explains the programming concepts and actions required to establish and
maintain high availability in SonicMQ connections through Aurea Sonic’s fault tolerance
mechanisms. This chapter contains the following sections:

• Overview on page 76 describes the concepts and advantages of choosing high


availability for client connections.
• How Fault-Tolerant Connections are Established on page 77 shows the basic
requirements for requesting fault tolerant connections and providing a connection list.
• ConnectionFactory Methods for Fault-Tolerance on page 77 describes the connection
factory methods related to fault tolerance connections.
• Connection Methods for Fault-Tolerance on page 82 describes the connection
methods related to fault tolerance connections.
• Reconnect Errors on page 86 describes the error code when reconnection cannot
succeed.
• Load Balancing Considerations on page 86 describes the current URLs that can be
retrieved.
• Reliability in Fault-Tolerant Connections on page 86 discusses reliability of
connections.
• Reconnect Conflict on page 87 details the conflicts that can arise in JMS connections
and in durable subscribers during connection recovery.
• Message Reliability on page 88 provides a table that assesses the expected message
reliability under various delivery modes, subscription models, and producer/consumer
connections whether or not fault tolerant.

Aurea Software, Inc. Confidential 75 Copyright © 2013 Aurea, Inc.


Chapter 4: High Availability Connections

Overview
Aurea Software’s Sonic Continuous Availability Architecture provides mechanisms for fault
tolerant management, replicated brokers, and fault tolerant client connections. A
fault-tolerant connection is designed to be resilient when it detects problems with the broker
or network. A standard connection, in contrast, is immediately dropped when the broker or
network fails. Because the standard connection is immediately dropped, your client
application has to explicitly deal with the situation, possibly trying to create a new
connection and resolve any in-doubt messages.

A fault-tolerant connection, unlike a standard connection, is kept alive when the broker or
network fails. It automatically performs several tasks when a problem occurs. For example,
it automatically attempts to reconnect when it encounters a problem with a connection. If it
successfully reconnects, it immediately executes several state and synchronization
protocol exchanges, allowing it to resynchronize client and broker state and resolve
in-doubt messages. When the connection successfully resynchronizes client and broker
state, the connection is said to be resumed, and your client application can continue its
operations without any directly visible disruption.

A fault-tolerant connection can respond to broker or network failure in a variety of ways.


How it responds depends on how you deploy SonicMQ and the nature of the failure.
There are several possibilities:

• If the network experiences a transient failure, the fault-tolerant connection can


repeatedly try to recover the connection until the network returns to normal.
• If your client system has redundant network pathways to the broker, when one path
fails, the fault-tolerant connection uses the other pathway to resume the connection.
• If your client application is connected to a standalone broker, when the broker fails,
the fault-tolerant connection tries to reconnect to the broker, until the broker is
recovered and restarted.
• If your client application is connected to a broker that is actively replicating to its
standby broker, when the active broker fails, the fault-tolerant connection can resume
on the standby broker when it fails over to the active role.

Fault-tolerant connections provide continuous operation across failures for JMS operations
that expect high availability:

• Production of PERSISTENT messages to both topics and queues.


• Consumption of messages from queues and durable subscriptions.
• Production and consumption of messages in a transacted session, integrity of the
transaction demarcation operations Session_commit and Session_rollback,
including duplicate transaction detection.
• Client requests that manage temporary queues.

For more information about fault tolerant deployments and continuous availability, see the
Aurea SonicMQ Deployment Guide. For more information about configuring fault tolerant
brokers, see the Aurea SonicMQ Configuration and Management Guide.

Aurea Software, Inc. Confidential 76 Copyright © 2013 Aurea, Inc.


How Fault-Tolerant Connections are Established

How Fault-Tolerant Connections are Established


To establish a fault-tolerant connection, two statements are required by the application:

• Request that the connection be fault tolerant which will establish a contract between
the broker and the client to perform fault tolerant operations—provided that the broker
is licensed to provide continuous availability. The methods for this are:

QueueConnectionFactory_setFaultTolerant(HOBJ connObj,true)

TopicConnectionFactory_setFaultTolerant(HOBJ connObj,true)

where true requests a fault tolerant connection.

• Supply a connection list with the primary and backup broker connection URLs:

QueueConnectionFactory_setConnectionURLs(HOBJ connObj,HOBJ
brokerList)

TopicConnectionFactory_setConnectionURLs(HOBJ connObj,HOBJ
brokerList)

where brokerList is a comma-delimited list of broker URLs.

ConnectionFactory Methods for Fault-Tolerance


There are several ConnectionFactory methods related to fault tolerant connections:

• Using the FaultTolerant option described in Enabling Fault Tolerant Connections on


page 77
• Using ConnectionURLs, as inEvaluating the List of Connection URLs on page 78
• Using ClientTransactionBufferSize, as in Client Transaction Buffers on page 79
• Using InitialConnectTimeout and FaultTolerantReconnectTimeout, described in
Specifying Connection Timeouts on page 80

Enabling Fault Tolerant Connections


By default, a ConnectionFactory creates standard connections, not fault-tolerant
ones.
To create a fault-tolerant connection, you must explicitly:
• Request a fault tolerant connection on the broker.
• Evaluate the list of connection URLs.
The use of other methods discussed in this section are optional.

Requesting a Fault Tolerant Connection


Call one of the setFaultTolerant methods before you create the connection:

Aurea Software, Inc. Confidential 77 Copyright © 2013 Aurea, Inc.


Chapter 4: High Availability Connections

• QueueConnectionFactory_setFaultTolerant(HOBJ connObj,jboolean
faultTolerant)
• TopicConnectionFactory_setFaultTolerant(HOBJ connObj,jboolean
faultTolerant)

When faultTolerant is true, the ConnectionFactory attempts to create fault tolerant


connections; when false, the ConnectionFactory creates standard connections.

You cannot create a fault-tolerant connection unless the broker is licensed to support fault
tolerance. A broker that is not licensed to support fault tolerance will effectively ignore the
ConnectionFactory setting.

To get the ConnectionFactory’s current fault-tolerance setting for new connections, call
one of the following methods:

• QueueConnectionFactory_getFaultTolerant(HOBJ connObj,jboolean
*pfaultTolerant)
• TopicConnectionFactory_getFaultTolerant(HOBJ connObj,jboolean
*pfaultTolerant)

Once connections are created, you can determine if the connection established a contract
as fault tolerant by calling the appropriate Connection_isFaultTolerant method.

Evaluating the List of Connection URLs


The client runtime works through the connection URL list, a list that intends to include
several broker URLs. When your client application wants to use fault-tolerant connections
against a replicated broker pair, the programming model requires you to specify the URLs
for your primary and backup brokers in the ConnectionFactory URL list. Before the client
application initially connects, it does not know which broker (primary or backup) is active. If
you omit the active broker from the list, the client cannot connect.

The client runtime works through the list one URL at a time, and connects to the first
available broker on the list. The client runtime works through the list in sequential order,
either:

• Starting from a random entry in the list (to get this behavior, call the appropriate
ConnectionFactory_setSequential method).

The following code excerpt demonstrates setting setSequential to false to make the
client runtime randomly choose a broker from a list:

[Link](false);

//Two sets of primary and backup brokers in list.

HOBJ URLsObj
Connection_setConnectionURLs(URLsObj,“tcp://B1P:2101,tcp://B1B:210
2,tcp://B2P:2201,tcp://B2B:2202”);

• Starting from the beginning of the list (the default behavior).

The following code excerpt demonstrates setting setSequential to true to make the
client runtime choose a broker by starting at the beginning of the list:

Aurea Software, Inc. Confidential 78 Copyright © 2013 Aurea, Inc.


ConnectionFactory Methods for Fault-Tolerance

Connection_setSequential(true);

//Two sets of primary and backup brokers, listed by primary and


backup brokers.
HOBJ URLsObj
Connection_setConnectionURLs(URLsObj,“tcp://B1P:2101,tcp://B1B:210
2,tcp://B2P:2201,tcp://B2B:2202”);

• The following code excerpt demonstrates that if you change the list sequence, you can
specify that the primary brokers are attempted before their respective backup brokers.
This approach is appropriate, for example, if the backup brokers are on slower
machines than the primary brokers.

Connection_setSequential(true);

//Two sets of primary and backup brokers in list, primary


brokers listed first.
Connection_setConnectionURLs(URLSObj,“tcp://B1P:2101,tcp://B2P:220
1,tcp://B1B:2102,tcp://B2B:2202”);

When the client runtime successfully establishes a fault tolerant connection with a broker,
the broker sends a list of URLs to the client runtime to be used for reconnection. When
replicating, the broker also sends a list of standby broker URLs for of reconnection.

After a connection is established, you can see the values in these lists by calling the
following methods on the connection:

• Connection_getBrokerReconnectURLs(HOBJ connObj, HOBJ *pret))


• Connection_getStandbyBrokerReconnectURLs(HOBJ connObj, HOBJ
*pret)

Client Transaction Buffers


When a fault-tolerant connection fails in the middle of a transaction, the client runtime
attempts to resume the connection with the broker. If the broker is down, the client runtime
attempts to connect to a standby broker, provided the broker was using broker replication.
If the client runtime can resume the connection with either broker, it confirms that its
transaction state is synchronized with the broker’s transaction state.

The broker, for performance reasons, buffers transacted messages in memory, instead of
saving each message individually as it is received. Consequently, the client runtime also
buffers the unsaved messages, so that if the broker goes down and loses the buffered
messages, they can be automatically resent by the client runtime.

The broker Tuning parameter, Transactions: Buffer Size, specifies the size of the broker’s
buffer on a per-transaction basis. In general, performance improves as the buffer size is
increased. However, the improved performance has two costs: the client runtime uses
more memory, and it takes longer to resend the unsaved messages if the broker fails.

The client application can override the transaction buffer size by calling the
setClientTransactionBufferSize method:

Aurea Software, Inc. Confidential 79 Copyright © 2013 Aurea, Inc.


Chapter 4: High Availability Connections

• QueueConnectionFactory_setClientTransactionBufferSize(HOBJ
connObj,jlong size)
• TopicConnectionFactory_setClientTransactionBufferSize(HOBJ
connObj,jlong size)

Valid values for size are as follows:

• Zero (0) (the default value) — Indicates the broker Transaction Buffer Size is applied.
The client runtime must be able to buffer up to the broker Transactions Buffer Size
parameter per transaction.
• Positive Long integer — Specifies the size, in bytes, that the client runtime buffers
per transaction. If the buffer size is reached, JMS client sending threads block until
further messages are saved by the broker. The broker applies a buffer size that is the
lesser of the client-specified value and the broker’s Transactions: Buffer Size.

The client runtime must allocate sufficient memory to buffer messages for each active
transaction. For local transactions, each JMS Session can have at most one
transaction active. For global transactions, every active XA transaction branch is
considered an active transaction.

The broker flushes transacted messages to disk when the transacted messages exceed a
calculated amount: the lesser of the broker’s Transactions: Buffer Size parameter or the
fault-tolerant client’s transaction buffer size.

To get the client’s buffer size, call the getClientTransactionBufferSize method:

• QueueConnectionFactory_getClientTransactionBufferSize(HOBJ
connObj,jlong *psize)
• TopicConnectionFactory_getClientTransactionBufferSize(HOBJ
connObj,jlong *psize)

Specifying Connection Timeouts


When a client application tries to establish an initial connection or resume a fault-tolerant
connection, it might not succeed immediately. The client can continue to try until it
succeeds, or it can specify a time interval (timeout) beyond which it stops trying.

The client application can specify two timeouts related to fault tolerant connections:

• Initial connect timeout — How long the client runtime tries to establish an initial
connection to the broker.
• Fault tolerant reconnect timeout — How long the client runtime tries to resume a
fault tolerant connection after a problem is detected.

Initial Connect Timeout


When the client runtime tries to establish an initial connection, it sequentially tries the URLs
listed in the ConnectionFactory. You can set this list programmatically with the
setConnectionURLs method (see How Fault-Tolerant Connections are Established on
page 77).

Aurea Software, Inc. Confidential 80 Copyright © 2013 Aurea, Inc.


ConnectionFactory Methods for Fault-Tolerance

The client runtime continues to try to establish a connection until either a connection is
successful or the initial connect timeout is exceeded. If the client runtime is trying to connect
to a URL when a timeout occurs, it does not stop immediately. It must complete its current
attempt (and fail) before returning a failure to the client application. However, it can return
a failure before trying all URLs in the list.

To set the initial connect timeout, call the appropriate setInitialConnectTimeoutmethod:

• QueueConnectionFactory_setInitialConnectTimeout(HOBJ
connObj,jint seconds)
• TopicConnectionFactory_setInitialConnectTimeout(HOBJ
connObj,jint seconds)

Where the value of seconds can be:

• Positive integer — Specifies a timeout; the client runtime abandons further


connection attempts after it times out. The default timeout is 30 seconds.
• Zero (0) — Specifies no timeout; the client runtime tries indefinitely.
• Negative one (-1) — Specifies that each URL is tried one time only; the client runtime
tries each URL sequentially one at a time until a successful connection is made or until
all URLs have been tried. This sequence is the same as the connection sequence
used for standard connections.

If a connection cannot be established within the time, a connection exception is thrown. You
can get the existing initial connect timeout value by calling the appropriate method:

• int QueueConnectionFactory_getInitialConnectTimeout(HOBJ
connObj,jint *pseconds)
• int TopicConnectionFactory_getInitialConnectTimeout(HOBJ
connObj,jint *pseconds)

Fault Tolerant Reconnect Timeout


When a problem is detected with a fault tolerant connection, the client runtime tries to
resume the connection. If it can connect to the same broker, it will; otherwise, it will try to
reconnect to a standby broker (if you are using broker replication).

You can adjust the timeout or whether the attempts will ever timeout by setting either:

• QueueConnectionFactory_setFaultTolerantReconnectTimeout(HOBJ
connObj,jint seconds)
• TopicConnectionFactory_setFaultTolerantReconnectTimeout(HOBJ
connObj,jint seconds)

Where the value of seconds can be:

• A positive integer — Specifies a timeout; the client runtime will abandon further
reconnection attempts if the timeout is exceeded. The default timeout is 60 seconds.
• Zero (0) — Specifies no timeout: the client runtime will try to reconnect indefinitely.

Aurea Software, Inc. Confidential 81 Copyright © 2013 Aurea, Inc.


Chapter 4: High Availability Connections

If the client fails to reconnect in the allocated time, the client is completely disconnected by
the broker. A fault-tolerant client runtime that attempts to reconnect after the broker has
discarded state will encounter a connection failure. When the client runtime fails to resume
a connection, the client runtime drops the connection and returns a connection dropped
exception to the client application’s ExceptionListener.

Note: The client’s ability to reconnect is also influenced by an advanced broker


administrative parameter
CONNECTION_TUNING_PARAMETERS.CLIENT_RECONNECT_TIMEOUT. The default
timeout is 10 minutes. By setting this parameter, the administrator can limit the
overall length of time the broker maintains state for any fault-tolerant connection
that fails and cannot reconnect. The maximum length of time that a broker
maintains state is the lesser of the client-specified fault tolerant reconnect timeout
and the CLIENT_RECONNECT_TIMEOUT setting.

You can get the existing FT reconnect timeout value by calling the appropriate method:

int QueueConnectionFactory_getFaultTolerantReconnectTimeout(HOBJ
connObj,jint *pseconds)
int TopicConnectionFactory_getFaultTolerantReconnectTimeout(HOBJ
connObj,jint *pseconds)

Connection Methods for Fault-Tolerance


There are several Connection methods related to fault tolerant connections:

• Setting and getting FaultTolerant described in Verifying Whether a Connection Is


Fault Tolerant on page 82
• Setting and getting ConnectionState and ConnectionStateListener, described
inHandling Connection State Changes on page 83
• Setting and getting BrokerURL, BrokerReconnectURLs, and
StandbyBrokerReconnectURLs, described in Getting the URL of the Current Broker
and Reconnect Brokers on page 84

Verifying Whether a Connection Is Fault


Tolerant
You can confirm if a connection you requested as fault tolerant is in fact fault tolerant. If the
broker is not licensed to enable fault tolerant connections a standard connection is
established. While the ConnectionFactory_getFaultTolerant methods might indicate that
the application is requesting an FT connection, this connection method verifies whether an
FT connection is active.

• int Connection_isFaultTolerant(HOBJ connObj,jboolean


*pfaultTolerant)
• int QueueConnection_isFaultTolerant(HOBJ connObj,jboolean
*pfaultTolerant)
• int TopicConnection_(HOBJ connObj,jboolean *pfaultTolerant)

Aurea Software, Inc. Confidential 82 Copyright © 2013 Aurea, Inc.


Connection Methods for Fault-Tolerance

Handling Connection State Changes


If a fault-tolerant connection fails for some reason, the client runtime reacts differently than
it does for a standard connection. When a standard connection fails, the client runtime
immediately drops the connection and raises an exception. How the exception is returned
to the client application depends on what the application was doing when the exceptional
condition was raised. If the client application was in the middle of a synchronous call, the
exception is thrown by the invoked method. If the exception occurred asynchronously, the
client runtime passes an exception to the connection’s ExceptionListener.

When a fault tolerant connection encounters a problem and cannot communicate with the
broker, the client runtime does not immediately drop the connection. Instead, it tries to
resume the connection. While it is trying to resume the connection, it defers passing any
exceptions to the client application. If it fails in its attempt to reconnect, it then passes the
exceptions to the client application as it would for a standard connection.

A client application can obtain the connection’s current state by calling a


getConnectionState method:

• int Connection_getConnectionState(HOBJ connObj, jint *pret)


• int QueueConnection_getConnectionState(HOBJ connObj, jint
*pret)
• int TopicConnection_getConnectionState(HOBJ connObj, jint
*pret)

If a standard connection calls the Connection_getConnectionState method, it will never


get a RECONNECTING state.

When a fault tolerant connection is working normally, the connection state is ACTIVE. If a
problem occurs with the connection, the client runtime changes the state to RECONNECTING
and attempts to resume the connection. If the attempt is successful, the client runtime
changes the state back to ACTIVE; if all attempts to reconnect fail, the client runtime
changes the state to FAILED. Finally, if an ExceptionListener is registered, the client
runtime calls its onException method.

While the client runtime is trying to resume a fault-tolerant connection, the client application
appears to block. However, the client application can stay informed about the state of the
connection by implementing a ConnectionStateChangeListener and registering it with the
appropriate Connection.

• Connection_setConnectionStateChangeListener
(HOBJ connObj, pfnCConnectionStateChangeListener listener, HOBJ
hobjUser)
• QueueConnection_setConnectionStateChangeListener
(HOBJ connObj, pfnCConnectionStateChangeListener listener, HOBJ
hobjUser)
• TopicConnection_setConnectionStateChangeListener
(HOBJ connObj, pfnCConnectionStateChangeListener listener, HOBJ
hobjUser)

Aurea Software, Inc. Confidential 83 Copyright © 2013 Aurea, Inc.


Chapter 4: High Availability Connections

You can get information about a connection state change listener by calling one of the
following methods:

• int Connection_getConnectionStateChangeListener
(HOBJ connObj, pfnCCSCL* p_pfncListener)
• int QueueConnection_getConnectionStateChangeListener
(HOBJ connObj, pfnCCSCL* p_pfncListener)
• int TopicConnection_getConnectionStateChangeListener
(HOBJ connObj, pfnCCSCL* p_pfncListener)
• int Connection_getConnectionStateChangeListenerHobjUser
(HOBJ connObj, HOBJ* hobjUser)

When you implement a ConnectionStateChangeListener, you must not perform any JMS
operations related to the connection, except for the informational Connection_ methods
getConnectionState, getBrokerURL, getBrokerReconnectURLs, and
getStandbyBrokerReconnectURLs.

Getting the URL of the Current Broker and


Reconnect Brokers
If you are using client URL lists or broker load-balancing, a client connection (fault-tolerant
or standard) can be made to one of a number of brokers. Further, with broker
load-balancing, it is typical that the URL provided by a load-balancing broker is not
configured by the client. With fault-tolerance enabled, the connection can reconnect to a
different URL or to a different broker than it initially connected to.

In all these cases, a client application can determine which broker it is currently connected
to by calling the appropriate Connection_getBrokerURL method:

• int Connection_getBrokerURL(HOBJ connObj, HOBJ* pBrokerURL)


• int QueueConnection_getBrokerURL(HOBJ connObj, HOBJ*
pBrokerURL)
• int TopicConnection_getBrokerURL(HOBJ connObj, HOBJ*
pBrokerURL)

The method returns the URL of the currently connected broker. If the current connection
state is RECONNECTING, this method returns the URL of the last broker connected when the
connection state was ACTIVE. This method may be called after the connection is closed.

URL Lists for Reconnecting


When a client initially establishes a fault-tolerant connection to a broker, the broker passes
two URL lists to the client runtime. The first list contains all of the URLs that are tried to
resume a connection to the connected broker; the second list contains all of the URLs that
are tried to resume a connection to its standby broker.

A client application can access the first list by calling the getBrokerReconnectURLs
method. The signatures of these methods are as follows:

Aurea Software, Inc. Confidential 84 Copyright © 2013 Aurea, Inc.


Connection Methods for Fault-Tolerance

• Connection_getBrokerReconnectURLs(HOBJ connObj, HOBJ *pret)


• QueueConnection_getBrokerReconnectURLs(HOBJ connObj, HOBJ
*pret)
• TopicConnection_getBrokerReconnectURLs(HOBJ connObj, HOBJ
*pret)

A client application can access the second list by calling the


getStandbyBrokerReconnectURLs method. The signatures of these methods are as
follows:

• Connection_getStandbyBrokerReconnectURLs(HOBJ connObj, HOBJ


*pret)
• QueueConnection_getStandbyBrokerReconnectURLs(HOBJ connObj,
HOBJ *pret)
• TopicConnection_getStandbyBrokerReconnectURLs(HOBJ connObj,
HOBJ *pret)

These methods are used for purely informational purposes, such as for writing to an audit
log; the reconnect logic is automatically performed by the client runtime. These methods
can both be called after the fault-tolerant connection is closed

Broker Reconnect URLs


These are URLs the client runtime can use to try and reconnect to the current broker, in the
event of connection failure (transient or other). The broker reconnect URLs allows multiple
acceptors on redundant network interfaces to be configured and included in client
reconnect logic.

The broker reconnect URLs are derived from the configuration by the following rules:

• If the active broker has a default routing URL configured, return the currently
connected URL.
• If the active broker has one or more URLs with same acceptor name as the currently
connected URL, return the URLs with same acceptor name, and include the currently
connected URL (getBrokerURL).
• Otherwise return the currently connected URL (getBrokerURL).

If getBrokerReconnectURLs is called against a fault-tolerant connection that is


RECONNECTING, the method returns the broker reconnect URLs when the connection state
was last ACTIVE.

Standby Broker Reconnect URLs


These are URLs the client runtime can use to connect to a standby broker (a broker that is
paired for fault-tolerance with the current broker) if it cannot successfully resume its
connection with the current broker. The list of standby broker reconnect URLs is derived
from the configuration by the following rules. These rules are consistent with how broker
load-balanced connections are selected:

Aurea Software, Inc. Confidential 85 Copyright © 2013 Aurea, Inc.


Chapter 4: High Availability Connections

• If the broker is standalone, return null.


• If the standby broker has a default routing URL configured, return the standby broker
default routing URL.
• If the standby broker has one or more URLs with same acceptor name as the primary
broker URL, return the standby broker URLs with same acceptor name.
• Otherwise return null. The final case is regarded as a configuration error. Replicated
brokers must be configured with corresponding acceptor names.

If getStandbyBrokerReconnectURLs is called against a fault tolerant connection that is


RECONNECTING, the method returns the standby broker reconnect URLs of the last broker
connected when the connection state was ACTIVE.

Reconnect Errors
A fault-tolerant connection might fail to reconnect for a variety of reasons. When a failure
occurs, the ERR_CONNECTION_DROPPED error code is included in the exception returned to the
Connection’s ExceptionListener. A linked exception provides more information about the
specific cause of the failure.

Load Balancing Considerations


When a client is connecting to a replicated broker, both the primary and backup URLs
should be specified in the ConnectionFactory’s URL list. This applies if the replicated
broker is also a load-balancing broker. If a fault-tolerant client is redirected to a broker that
is replicated, the client is automatically capable of reconnecting to that broker’s list of
reconnect URLs and standby reconnect URLs.

To get:

• The URL of the broker that the client connects to as a result of load balancing, call
getBrokerURL on the connection object.

• The reconnect URLs of the broker that the client connects to as a result of load
balancing, call getBrokerReconnectURLs on the connection object.
• The URLs of the backup broker for the broker that the client connects to as a result of
load balancing, call getStandbyBrokerReconnectURLs on the connection object.

Reliability in Fault-Tolerant Connections


This section describes the reliability of various JMS and SonicMQ-specific operations in the
event of a client reconnect after a general failure or a broker failure.

The general term failure means either a broker failure or a transient network failure. Some
of the behaviors after or failure are:

• Production and consumption of persistent messages to temporary queues for


fault-tolerant clients are highly reliable across failures.

Aurea Software, Inc. Confidential 86 Copyright © 2013 Aurea, Inc.


Reconnect Conflict

• Production and consumption of persistent messages to temporary topics are


unreliable across failures. For fault tolerant request-reply, applications should use a
durable subscriber to handle replies.

The phrase broker failure means one of the following—a broker crashed, recovered fully,
and restarted successfully; or a replicated broker crashed and failed over to its backup
broker. Some of the behaviors after broker failure are:

• Transaction timeouts (a Sonic-specific feature) are restarted after a broker failure.


• QueueBrowsers are unreliable if a fault tolerant connection detects failover; all
QueueBrowsers are immediately closed. The current browse cursor throws a
NoSuchElementException exception with text indicating that the browse terminated
due to failover. Any attempt to call a QueueBrowser method after failover will result in
an IllegalStateException. Explanatory text is provided in the exception and the
error code BROWSER_CLOSED_DURING_RECONNECT.
• Access to read-exclusive queues (a Sonic-specific feature) might be lost during broker
failure. It is possible for a fault tolerant connection with a QueueReceiver open on a
read-exclusive queue to fail to reconnect after broker failure. This happens if another
client opens a receiver to the same queue before the fault-tolerant client reconnects.
In this case, normal JMS connection failure occurs. This problem cannot occur when
the client connection recovers from transient network failure.

When a message is sent from a client to an active broker, the client maintains a copy of the
message until two acknowledgements are received. The first acknowledgement is from the
active broker, the second acknowldegement is from the standby broker through the active
broker. If the active broker fails before the second acknowledgement is returned,
then—when the client reconnects to the standby as it assumes the active state—it
negotiates its state: what was the last message received, what was the last
acknowledgement received by the client. When the now-active broker has synchronized
with the client, any missed messages are resent from the client cache. If the active broker
fails prior to replication, then—when the client negotiates its state at reconnection—missing
messages are resent from the client cache. Messages are removed from the client cache
after both acknowledgements are received.

Reconnect Conflict
Connect conflicts are possible during client connection recovery. Conflicts can happen at
the JMS connection level and at the durable subscriber level.

Aurea Software, Inc. Confidential 87 Copyright © 2013 Aurea, Inc.


Chapter 4: High Availability Connections

JMS Connection Reconnect Conflict


To uniquely identify connections, set the username and connectID values in the
ConnectionFactory. If connectID is null (default) a unique connect identifier is allocated
by the broker. Therefore, by specifying a null connectID, the username is permitted to
establish any number of connections. If a non-null connectID is specified, only one
connection with the particular username and connectID combination is permitted. A client
using a non-null connectID might be connected when failover occurs. Before reconnecting,
another client can attempt to connect using the same connectID and username identifiers.
A normal (non-recovery) connection is received for this client. From the broker’s
perspective, this also happens if the original client application does not disconnect
gracefully, and then attempts to create a new connection. For this reason, it is undesirable
for the broker to reject new connections while maintaining state for a fault tolerant
connection that has failed and is pending reconnection. Therefore if a fault tolerant
connection has failed and is pending reconnect in the broker and a new connection
(non-recovery) is received with the same connectID and username, the new connection is
accepted and the previous connection state is discarded. This means that a client using
fixed connect identifiers to gain exclusive access can lose such access to a different client
during the pending-reconnection state.

Durable Subscriber Reconnect Conflict


To uniquely identify durable subscriptions, set the username and clientID values in the
ConnectionFactory in conjunction with the subscription name parameter provided to
TopicSession createDurableSubscriber signatures. A client may create a fault-tolerant
connection, session and a durable subscriber. If the connection fails, the connection enters
pending-reconnect state in the broker. During pending-reconnect state, no connection is
permitted to create (gain access to) the durable subscriber unless the underlying
connectID is identical to that of the connection in postponed disconnect state.

Message Reliability
The following table describes the message reliability levels for clients that reconnect to the
broker or its backup after a failure. The reconnect is automatic for fault tolerant connections,
application driven for standard connections. The table assumes that clients that reconnect
on standard connections do not resend in-doubt messages on reconnecting.

Note: The only way to guarantee exactly-once delivery is with a fault-tolerant


MessageProducer sending messages under PERSISTENT delivery mode and a
fault-tolerant MessageConsumer.

Aurea Software, Inc. Confidential 88 Copyright © 2013 Aurea, Inc.


Message Reliability

Message Producer Message Consumer

Connection Delivery Mode Standard Connection Fault Tolerant Connection


Type
Topic (but not Topic (Durable Topic (but not Topic (Durable
a Durable Subscription) a Durable Subscription)
Subscription) or Queue Subscription) or Queue

Standard DISCARDABL At most once1 At most once1 At most once1 At most once1
Connection E

PERSISTENT At most once2 At least once1, At most once1 Exactly once1


2

NON_PERSIS At most once1 At most once1 At most once1 At most once1


TENT

Fault-Tolerant DISCARDABL At most once At most once At most once At most once
Connection E

PERSISTENT At most once3 At least once2 At most once Exactly once

NON_PERSIS At most once At most once At most once At most once


TENT
1In
the case of a standard connection failure, if the last message sent was in doubt, your application logic might
retry the publication, after creating a new connection, session, and MessageProducer. This causes the
generation of a duplicate message if the broker had received the original message. According to JMS this is
not a redelivery since the message was delivered from a new session. This ambiguity is resolved for
fault-tolerant message producers: PERSISTENT messages are exactly-once; DISCARDABLE and
NON_PERSISTENT messages are dropped in a failure.
2
In the case of a standard connection failure, the acknowledgement for the last message might be lost. In this case
the broker redelivers the message with JMS_REDELIVERY set to true in accordance with the JMS
Specification.
3If a message consumer client reconnects using a standard connection at the same time as a fault-tolerant
publisher is reconnecting, it is possible that the publisher will resend a message that had been delivered to the
previously connected client. According to JMS this is not a redelivery since the message was delivered to a
new session.

Aurea Software, Inc. Confidential 89 Copyright © 2013 Aurea, Inc.


Chapter 4: High Availability Connections

Aurea Software, Inc. Confidential 90 Copyright © 2013 Aurea, Inc.


5
Using Login SPI for Sonic
Authentication

Chapter 5, Using Login SPI for Sonic Authentication on page 91 describes using the
SonicMQ C client Service Provider Interface (SPI) which is used on the client side to
authenticate JMS client applications inwhich the broker uses Sonic’s external security
implementation, Pluggable Authentication and Security Service (PASS). Implementation of
this interface requires implementing the Authentication SPI and the Management SPI on
the broker side.

The Authentication SPI is used to authenticate JMS clients connecting to a broker via the
delegation mode, and to perform callback operations on the broker. The Management SPI
is used by the Sonic Directory Service to replicate users and credentials on the Sonic
Directory Service. This information is used in the Sonic Management Console to provide a
graphical read-only representation of users and groups in an external domain.

See the Aurea SonicMQ Administrative Programming Guide for information about the
Authentication SPI and the Management SPI as well as the Login SPI for Java clients. This
chapter contains the following sections:

• Overview on page 92 provides an introduction on implementing security features for


your applications.
• SimpleLogin SPI on page 92 describes the various methods available in the
SimpleLogin SPI for authentication.

Aurea Software, Inc. Confidential 91 Copyright © 2013 Aurea, Inc.


Chapter 5: Using Login SPI for Sonic Authentication

Overview
You can implement an external security store for an authentication domain, in addition to
the local security store that is implemented by default for all authentication domains:

• Local security store — Users are stored in the Sonic Directory Service.

• External security store — Users are stored externally and accessed in the domain by
the Authentication SPI and the Management SPI. Passwords are stored in an external
security store in an unknown format. You must implement the Login SPI to perform
password transformations when using an external security store.

The SonicMQ C client includes sample code in its QueuePTP/Talk.c sample which you can
examine to understand how to implement these security features in your applications. This
chapter includes some code excerpts from the C client sample to illustrate how to
implement the PASS SPIs.

See the MQ2013_install_root\samples\AdvancedSecurity\[Link] file for


information about the Authentication, Management, and Java-client Login samples which
demonstrate advanced security features using the PASS SPIs.

For information about the PASS features in SonicMQ, see the chapter “Security
Considerations in System Design” in the Aurea SonicMQ Deployment Guide.

See the chapter “Configuring Security” in the Aurea SonicMQ Configuration and
Management Guide for information about using the SMC to configure these security
features in SonicMQ.

SimpleLogin SPI
The SimpleLogin SPI provides access to the ILogin interfaces. When you implement the
SimpleLogin SPI, users can be authenticated with external authentication service before a
JMS connection is created.

SimpleLogin Implementation in the SonicMQ C


Client Runtime
The Login SPI is used internally by the SonicMQ C client runtime. When a JMS connection
is requested from a connection factory, the following sequence of events occurs:

1. The application uses SimpleLoginCMap_init, an implementation that populates the


LoginSPICMap structure so that the internal runtime can call appropriate functionality
during client authentication. This initializes the LoginSPI and then calls setLoginSPI
to register the initialized structure.

2. The SonicMQ runtime calls the method getLoginSPI( ), which returns an ILogin
instance to be used for further authentication processing.

3. Upon successful instantiation of the class, the SonicMQ runtime passes the user
name and the password to the underlying SPI implementation using its CMap.

Aurea Software, Inc. Confidential 92 Copyright © 2013 Aurea, Inc.


SimpleLogin SPI

4. The SonicMQ runtime calls the method login( ) on the underlying SPI
implementation.

5. If the login( ) method returns without an exception, the login to external security
store or schema is assumed validated and the user is considered authenticated.

6. Upon successful return from the login( ) method, the SonicMQ runtime calls the
getTransformedUsername and getTransformedPassword functions to retrieve the user
credentials.

7. The retrieved user name, password, and transformed password are used to establish
a connection with the Sonic broker.

Important: The implementation is not thread safe, and requires synchronization


protection at the application layer when used in a multi-threaded context.

Important: Also, the default LoginSPI implementation is a primitive implementation and


results in user credentials transferred over the wire in obfuscated, but
unencrypted, form.
SSL authentication with certificates is the preferred technique. See Chapter 6,
SSL Connections on page 97 for more information about SSL in the C client.

Methods
SimpleLogin methods:

• Initialize the Login SPI callback methods in the structure:

void SimpleLoginCMap_init(ILoginSPICMap*)

• Callback methods:

void SimpleLoginCMap_setUsername(struct _loginSPIMap *, HOBJ);

HOBJ SimpleLoginCMap_getUsername(struct _loginSPIMap *);

void SimpleLoginCMap_setPassword(struct _loginSPIMap *, HOBJ);

HOBJ SimpleLoginCMap_getPassword(struct _loginSPIMap *);

void SimpleLoginCMap_setTransformedUsername(struct
_loginSPIMap *, HOBJ);

HOBJ SimpleLoginCMap_getTransformedUsername(struct
_loginSPIMap *);

void SimpleLoginCMap_setTransformedPassword(struct
_loginSPIMap *, HOBJ);

HOBJ SimpleLoginCMap_getTransformedPassword(struct
_loginSPIMap *);

Related APIs:

int QueueConnectionFactory_setLoginSPI(HOBJ, ILoginSPICMap*)

Aurea Software, Inc. Confidential 93 Copyright © 2013 Aurea, Inc.


Chapter 5: Using Login SPI for Sonic Authentication

int TopicConnectionFactory_setLoginSPI(HOBJ, ILoginSPICMap*)

Sample
The following code provides excerpts from the Talk sample application that create a queue
connection to a SonicMQ broker, invoking the Login SPI implementation in the C client. The
sample assumes that the broker side has been set up for external authentication.

1. Adds login to the initialization list:

...

void Talk:talker(

char *broker,

char *username,

char *password,

char *qReceiver,

char *qSender,

jint timeout,

int login);

2. Calls login to create its CMap:

ILoginSPICMap login_cmap;

3. Populates the CMap and then passes it on to the ConnectionFactory:

/* external authentication */

if (login)

SimpleLoginCMap_init(&login_cmap);

if (QueueConnectionFactory_setLoginSPI(connectionFactory,
&login_cmap)!= SMQ_SUCCESS) {

fprintf(stderr, "Error installing LoginSPI\n");

handleJMSException();

goto exit_cleanly;

4. Adds to the usage that a switch lets you choose to use the Login SPI:

fprintf(stderr, " -l Register the default loginSPI. (Optional


and only applies\n");

Aurea Software, Inc. Confidential 94 Copyright © 2013 Aurea, Inc.


SimpleLogin SPI

fprintf(stderr, " to brokers configured with external


authentication).\n");

5. Extends the commandline to add the login switch entry:

/* Start the JMS client for the "talk". */

Init();

talker(broker, username, password, qReceiver, qSender, timeout,


login);

Aurea Software, Inc. Confidential 95 Copyright © 2013 Aurea, Inc.


Chapter 5: Using Login SPI for Sonic Authentication

Aurea Software, Inc. Confidential 96 Copyright © 2013 Aurea, Inc.


6
SSL Connections

SonicMQ supports encryption at the connection level through SSL. This chapter describes
the programming concepts and actions required to establish and maintain connections with
SonicMQ brokers through SSL in the SonicMQ C client.

See the Aurea SonicMQ Deployment Guide for more information about SSL. This chapter
includes the following section:

• Using SSL on the C Client on page 97 provides information on how to use SSL
certificates on the C client.

Using SSL on the C Client


Transport layer security between a client application and a broker involves a set of libraries
and files on the client and the broker that enable SSL connectivity. SonicMQ C clients use
the OpenSSL library included in the client package. You set runtime properties to identify
the certificates and the cipher suites preferred for the encryption of the communication
channel. The default cipher suite is RC4-SHA:RC4-MD5.

Note: The OpenSSL inclusions in the SonicMQ C client explicitly omit patented
algorithms, such as IDEA, MDC2, and RC5.

These properties can be established in any one of the following ways:

• Command line — Pass the SSL properties at the command line when starting the
application.
• Programmatically — Set the SSL properties in your application.

Aurea Software, Inc. Confidential 97 Copyright © 2013 Aurea, Inc.


Chapter 6: SSL Connections

For optimal security, consider using LoginSPI in conjunction with SSL so that the
obfuscated credentials are encrypted at the connection level. See Chapter 5, Using Login
SPI for Sonic Authentication on page 91 for more information.

Certificate Samples and Conversions


Certificates used by OpenSSL in the SonicMQ C client are in the PEM format. Sample
certificates are provided in the cclient_install_dir/samples/certs directory.

You can convert certificates used in a Java client to the PEM format for use by the C client.

To convert certificates used in a Java client to the PEM format

1. Open a command prompt and go to the client installation’s certs directory.

2. In the Java client’s MQ2013/certs directory, copy the files:

• CA/[Link]
• client.p7c
• clientKey.pkcs8

3. Paste the copied files into the cclient_install_dir/samples/certs directory:

• [Link] (into the CA subdirectory)


• client.p7c
• clientKey.pkcs8

4. Enter the following commands to perform the conversions:

openssl x509 -inform DER -in CA/[Link] -out


CA/[Link]

c_rehash CA

openssl pkcs7 -print_certs -inform DER -in client.p7c -out


[Link]

openssl pkcs8 -inform DER -in clientKey.pkcs8 -out [Link]

5. Type the password when prompted. The password for the sample private key in the
certs folder is password. The password is stored in the PEM file that is created.

Note: The openssl commands refer to the OpenSSL utility built and packaged with the
Sonic C client. You can use the public OpenSSL utilities if you prefer to use them.

Authentication
Authentication is the process of presenting an identity to the broker and then providing a
password or certificate that certifies the user’s credentials.

Two methods are provided in the C client API to set SSL properties

Aurea Software, Inc. Confidential 98 Copyright © 2013 Aurea, Inc.


Using SSL on the C Client

• QueueConnectionFactory_setSSLProperties (connectionFactory,
ca, cc, pk, cs);
• TopicConnectionFactory_setSSLProperties (connectionFactory, ca, cc, pk,
cs);

wherein:

• -ca is the name of the CA directory


• -cc is the name of the client certificate
• -pk is the name of the client private key
• -cs is the cipher suite. RC4-SHA:RC4-MD5 is the default cipher suite.

Settings on a Broker
In the configuration of SSL acceptors on a broker, each acceptor’s SSL tab lets you choose
to enable client authentication, as shown in the following image:

• When enabled, the broker mandates that the client present its certificate, referred to
as mutual authentication. Thus, the server presents its certificate in the handshake
and expects the client to present the client certicate to complete the handshake. The
client must specify CA CERT DIR, CERTIFICATE CHAIN, and PRIVATE KEY properties.
• When not enabled, only the broker presents its certificate in the handshake, referred
to as server-only authentication. The client must specify a CA CERT DIR property.

Samples
The following procedures show how to run a C client application with SSL:

• Using SSL Authentication with username and password on page 100


• Using SSL Authentication with mutual certificates on page 101

Aurea Software, Inc. Confidential 99 Copyright © 2013 Aurea, Inc.


Chapter 6: SSL Connections

Using SSL Authentication with username and


password
Assumptions:

• The broker where connection will be attempted has an acceptor setup for SSL on port
3000 that has chosen to not enable client authentication.

• The broker is running.


• Two users have been created in the broker’s authentication domain:
• aUser with the password aPwd

• bUser with the password bPwd

• The C client Talk sample will be used since it is preset to accept the properties and
use the SSL connection factories.

Note: See the Aurea SonicMQ Configuration and Management Guide for information on
defining acceptors and users.

The Talk sample application usage for SSL with username/password authentication is:

Talk -b ssl://host:port -u user -p pwd \


-qs sendq -qr recvq -ca CA_dir -cc cert -pk key

-b host:port Points to a message broker’s SSL acceptor


-u user Must be unique (checked when using a secure broker)
-p pwd Password for user (checked when using a secure broker)
-qs sendq Name of queue where messages are sent
-qr recvq Name of queue from which messages will be received
-ca CA_dir Name of the CA directory
-cc cert Name of the client certificate
-pk key PEM Name of the client private key

To run the SonicMQ C Talk sample application for SSL with username/password
authentication:

1. Open two command prompts and go to the directory of the the Talk sample in each
one, for example:

install_dir\samples\C\QueuePTP\Talk

2. Start an instance of the application using unique user names in each command
prompt, specifying a queue for sending and receiving:

./Talk -b ssl://localhost:3000 -u aUser -p aPwd -qr SampleQ1 -qs


SampleQ2 \
-ca CA/ -cc [Link] -pk [Link]

./Talk -b ssl://localhost:3000 -u bUser -p bPwd -qr SampleQ2 -qs


SampleQ1 \
-ca CA/ -cc [Link] -pk [Link]

3. In one command prompt, type a test message and then press Enter to send it.

4. Observe the message in the other commandprompt preceded by the sender’s name.

Aurea Software, Inc. Confidential 100 Copyright © 2013 Aurea, Inc.


Using SSL on the C Client

5. Stop a session by pressing Enter.

Using SSL Authentication with mutual certificates


SonicMQ always uses server authentication when using SSL. To have mutual
authentication, you must enable Client Authentication on the broker’s acceptor. The
following procedure explains how to run an application with SSL with client authentication
via mutual certificates.

Assumptions:

• The broker where connection will be attempted has an acceptor setup for SSL on port
4000 that has chosen to enable client authentication.

• The broker is running.


• The C client Talk sample will be used as it is preset to accept the properties and use
the SSL connection factories.

Note: See the Aurea SonicMQ Configuration and Management Guide for information on
defining acceptors and users.

The Talk sample application usage for SSL with mutual authentication is:

Talk -b ssl://host:port -u user -p pwd \


-qs sendq -qr recvq -ca CA_dir -cc cert -pk key

-b host:port Points to a message broker’s SSL acceptor


-u user Must be unique (checked when using a secure broker)
-p pwd Password for user (checked when using a secure broker)
-qs sendq Name of queue where messages are sent
-qr recvq Name of queue from which messages will be received
-ca CA_dir Name of the CA directory
-cc cert Name of the client certificate
-pk key PEMName of the client private key

To run the SonicMQ C Talk sample application with client authentication via mutual
certificates:

1. Open two command prompts and go to the directory of the the Talk sample in each
one, for example:

install_dir\samples\C\QueuePTP\Talk

2. Start an instance of the application using unique user names in each command
prompt, specifying a queue for sending and receiving:

./Talk -b ssl://localhost:3000 -u aUser -p aPwd -qr SampleQ1 -qs


SampleQ2 \
-ca CA/ -cc [Link] -pk [Link]

./Talk -b ssl://localhost:3000 -u bUser -p bPwd -qr SampleQ2 -qs


SampleQ1 \
-ca CA/ -cc [Link] -pk [Link]

3. In one command prompt, type a test message and then press Enter to send it.

Aurea Software, Inc. Confidential 101 Copyright © 2013 Aurea, Inc.


Chapter 6: SSL Connections

The connection is authenticated by exchange of certificates between client and


broker.

4. Stop a session by pressing Enter.

Aurea Software, Inc. Confidential 102 Copyright © 2013 Aurea, Inc.


7
Distributed Transactions in C Using
the XA Interface

This chapter introduces distributed transaction support in the SonicMQ C Client.


This chapter includes the following sections:

• About Distributed Transaction Processing on page 103 describes the general


concepts of distributed transactions.
• Programming with the XA Interface on page 108 describes the specifics of the
distributed transaction support in SonicMQ C Client through the XA interface.
• Running the SonicMQ C XA Transaction Sample on page 109 steps through the
distributed transaction sample provided in the SonicMQ C Client package.
• In Doubt Global Transactions on page 112 shows how transaction administrators can
handle in doubt global transactions.
• Distributed Transactions Models on page 113 describes the three models of
distributed transactions under the SonicMQ C Client.

About Distributed Transaction Processing


Distributed transaction processing (DTP) allows a set of messages from heterogeneous
sessions to form a composite transaction. An example of a distributed transaction is a
transfer of funds between bank accounts. Withdrawal from one account and deposit into
another account comprise one balanced transaction. Every effort must be taken to assure
that the transaction—even though it might involve two different banks can—and likely
will—complete successfully. If it cannot succeed, no part of it can be recorded.

Aurea Software, Inc. Confidential 103 Copyright © 2013 Aurea, Inc.


Chapter 7: Distributed Transactions in C Using the XA Interface

General Properties of a Transaction


A distributed transaction is characterized by the same properties as a simple transaction
—a series of messages sent and/or received on one session thread. As detailed for a
Transacted Session on page 22, the properties of a transaction are that it is atomic,
consistent, isolated, and durable.

Transaction Types
A single SonicMQ application can contain both local and global transactions.

• Local Transaction — Involves a single resource manager. In SonicMQ, a transaction


performed in a session with the transacted parameter set to true is a local transaction.
• Global Transaction — Involves dispersed resources in the transaction. It is often
referred to as a distributed transaction. A distributed transaction system typically relies
on an external transaction manager to coordinate the participants in a transaction.

Components of Distributed Transactions


Distributed transactions have as many as five components that contribute to the distributed
transaction processing system by implementing different sets of transaction APIs and
functionalities:

• Transaction manager (TM) — Provides the services and management functions


required to support transaction demarcation, transactional resource management,
synchronization, and transaction context propagation.
• Application server (or TP monitor) — Provides the infrastructure that supports the
application run-time environment including transaction state management.
• Resource manager (RM) — Manages data or some other kind of resource through a
resource adapter. SonicMQ is a resource manager, implementing a transaction
resource interface—the XA91 specification defined in the Open Group’s X/Open CAE
Specification Distributed Transaction Processing: The XA Specification—that the
transaction manager uses to communicate transaction association, transaction
completion, and recovery work.
• Transactional application — In an application server environment relies on the
application server to provide transaction management support through transaction
attribute settings. In addition, other standalone Java Client programs can control their
transaction boundaries using a high-level interface provided by the application server
or the transaction manager.
• Communication resource manager (CRM) — Supports transaction context
propagation and access to the transaction service for incoming and outgoing requests.

From the transaction manager’s perspective, the actual implementation of the transaction
services does not need to be exposed. Only high-level interfaces must be defined to allow
transaction demarcation, resource enlistment, synchronization, and recovery process to be
driven by the users of the transaction services.

Aurea Software, Inc. Confidential 104 Copyright © 2013 Aurea, Inc.


About Distributed Transaction Processing

Resource Managers and Transaction


Managers
A SonicMQ C application has access to all the required components for distributed
transactions. A SonicMQ C application uses the interfaces defined in xa.h to provide
complete suite of functionality for applications in distributed transactions.

A SonicMQ application initiates a transaction by communicating with the transaction


manager (TM). The resource manager (RM) uses the XA protocol to connect to the TM, as
shown in Figure 1.

Figure 1: Resource Manager Connected to a Transaction Manager

Resource Transaction
XA
Manager Manager

As RMs on diverse threads participate in the distributed transaction, it is crucial that the TM
establish and maintain the state of the transaction as it evolves. A transaction context
logically envelopes all the operations performed on transactional resources during the
transaction.

An application server can bring additional resources into the transaction, referred to as
resource enlistment. In Figure 2, another RM is participating in an XA connection to the
same TM as the owner.

Figure 2: Enlistment of a Second RM to a Distributed Transaction

Transaction
Manager
XA XA

Resource Resource
Manager Manager

The transaction context and resource enlistment can extend to other transaction managers,
as shown in Figure 3.

Aurea Software, Inc. Confidential 105 Copyright © 2013 Aurea, Inc.


Chapter 7: Distributed Transactions in C Using the XA Interface

Figure 3: Distributed Transaction with Multiple Transaction Managers

Resource Resource
RM 21 RM 22
Manager 11 Manager 12

XA XA
Transaction
TM 2
Manager 1

TM 3

RM 31 RM 32

Messages sent in the transaction context are not permanently recorded. Messages
received in the transaction context are not acknowledged until the owner ends the
transaction demarcation and passes control to its TM. This TM can coordinate with the
other involved TMs and RMs to prepare and commit the global transaction.

The transaction owner explicitly ends the global transaction. If the transaction involves a
single transaction manager, telling the TM to commit or rollback the transaction handles the
transaction state on all the participating branches.

A global transaction that involves multiple resource managers requires a two-phase commit
to request that the participants prepare for completion., when all are prepared, request that
the participants perform the commitment. It a failure occurs during the commitment
process, the state of the global transaction can be indoubt.

One Phase Commit


The transaction manager does not prepare the participating resource managers for a
one-phase commit. Instead the TM immediately issues the command to commit. In
Figure 5, both resource managers, when commanded to commit, do so without error.
Nevertheless, the risk of error in a one-phase commit is considerably higher because some
resources might be unable to commit after other resources have already done so.

Aurea Software, Inc. Confidential 106 Copyright © 2013 Aurea, Inc.


About Distributed Transaction Processing

Figure 4: One-phase Commit That Completed Successfully

Phase 1: Commit
Resource
Manager
Released

Commit Transaction
Application
Manager
Phase 1: Commit

Resource
Manager
Released

Two Phase Commit


When the transaction manager prepares the transaction, each participating resource
manager is polled to see if commitment is likely to succeed.

In Figure 5, both resource managers, when commanded to prepare their contribution to the
transaction, responded positively. The global commit by the owner’s transaction manager
commits each branch of the global transaction.

Figure 5: Two-phase Commit That Completed Successfully

Phase 1: Prepare
Ready !
Resource
Phase 2: Commit Manager
Released

Commit Transaction
Application
Manager
Phase 1: Prepare
Ready !
Resource
Phase 2: Commit Manager
Released

In Figure 6, one of the resource managers indicates that its portion of the global transaction
cannot complete. As a result, a global rollback is issued for each branch of the transaction.

Aurea Software, Inc. Confidential 107 Copyright © 2013 Aurea, Inc.


Chapter 7: Distributed Transactions in C Using the XA Interface

Figure 6: Two-phase Commit That Cannot Complete Successfully

Phase 1: Prepare
Ready !
Resource
Phase 2: Rollback Manager
Discarded

Commit Transaction
Application
Manager
Phase 1: Prepare
Not Acceptable
Resource
Phase 2: Rollback Manager
Discarded

Programming with the XA Interface


The X/Open XA Interface is the 1991standard maintained by the Open Group for
coordinating changes to multiple resources (such as databases) while ensuring the
integrity of the changes. Software products referred to as transaction processing monitors
typically use the XA interface.

Global Transaction Identifier, Branch


Qualifiers, and XIDs
The SonicMQ C Client creates global transaction identifiers (gtrid) that are then
associated with resource managers participating in the transaction. Each participant is a
branch of the transaction identified with a branch qualifier (bqual). The XID for a branch is
gtrid + bqual. For example, if gtrid is 12 and bqual is 34 then XID is 1234.

Using the xa_switch Structure


The SonicMQ C Client provides a global instance of xa_switch, a switch structure whose
function pointers are categorized in the following table.

Category Functions Details

Functions to connect to xa_open_entry(char*,int,long) The string passed to


and disconnect from the xa_close_entry(char*,int,long) xa_open() typically contains
XA resource manager connection information, such
as a database name,
username, and password.

Functions to start and end xa_start_entry(XID*,int,long)


associations between xa_end_entry(XID*,int,long)
connections and a
transactions

Aurea Software, Inc. Confidential 108 Copyright © 2013 Aurea, Inc.


Running the SonicMQ C XA Transaction Sample

Category Functions Details

Transaction completion xa_prepare_entry(XID*,int,long) These correspond to the


functions xa_commit_entry(XID*,int,long) CosTransactions::
xa_rollback_entry(XID*,int,long) Resource operations.
xa_forget_entry(XID*,int,long)

Recovery function xa_recover_entry(XID*,int,long)

To use an XA connection in a distributed transaction, you must create an association


between the connection and the distributed transaction:

• xa_start() creates such an association

• xa_end(TMSUSPEND) suspends the association without releasing the connection

• xa_start(TMRESUME) resumes a suspended association

• xa_end(TMSUCCESS) terminates an association with success

• xa_end(TMFAIL) terminates an association and marks the transaction rollback-only.

Static Registration
The SonicMQ C Client resource manager uses static registration to register its participation
in each global transaction. Static registration means the transaction manager must, for
each transaction, issue the xa_start_entry, xa_end_entry, and xa_prepare_entry series
of calls to all the defined resource managers.

XA Threads
In addition to supporting the X/Open XA protocol, SonicMQ C XA transaction applications
must adhere to rules for every XA thread — each thread in which XA transactions will be
used. An XA thread:

• Must call the xa_open_entry function before creating a connection.


• Must call the xa_end_entry function before closing its connection. If this is not done,
a subsequent call to xa_end_entry fails.
• Can have only one connection per rmid, but an application can have multiple XA
threads, each connected to the same rmid with identical or different usernames.
• Can only receive messages synchronously within a transaction—call the receive()
method instead of setting a MessageListener.

Running the SonicMQ C XA Transaction Sample


This sample shows how to handle XA transactions with the SonicMQ C Client and assumes
that you are familiar with the X/Open XA protocol.

The complete enunciation of the sample command line and its parameters is:

Aurea Software, Inc. Confidential 109 Copyright © 2013 Aurea, Inc.


Chapter 7: Distributed Transactions in C Using the XA Interface

XASample -b hostname:port -u username -p password -tp pTopicName -ts sTopicName

where:

-b hostname:port identifies the message broker port. It defaults to


localhost:2506.
-u username is an authentic user. It defaults to Administrator.
-p password is the user’s password. It defaults to Administrator
-tp pTopicName is the name of the topic where messages are to be published.
-ts sTopicName is the name of the topic to which to subscribe to receive
messages.

If you have a typical local broker installation, you can let the broker and security parameters
accept their defaults. You typically specify the pTopicName and sTopicName each in
separate console windows, although they can both run concurrently. The command line
then might appear as one of the following:

XASample -tp [Link]


XASample -ts [Link]
XASample -ts [Link] -ts [Link]

When acting as a producer in the sample, the user can enter:

• A known producer command, which is then attempted


• Other text which is then packaged in the payload of the message
• No text, which indicates the end of the producer loop

When acting as a consumer in the sample, the user can enter:

• A known consumer command, which is then attempted


• The command to receive a message
• No text, which indicates the end of the consumer loop

When you specify both the -tp and -ts parameters, the sample acts first as a producer,
then acts as a consumer.

To run the XASample application:

1. Open two console windows at the directory level of the XASample executable, typically
located adjacent to its source file.

2. In one window, enter: XASample -tp [Link]


This is the Producer window.

3. In the other window, enter: XASample -ts [Link]


This is the Consumer window.

Aurea Software, Inc. Confidential 110 Copyright © 2013 Aurea, Inc.


Running the SonicMQ C XA Transaction Sample

Table 1 shows the sequence of entries in the Producer and Consumer windows.
Table 1: XASample’s Prescribed Transaction Entries

Producer Consumer

Enter Comment Enter Comment

START Start a new global


transaction.
message1 Publish a message with the
body message1 to [Link]
message2 Publish a message with the
body message2 to [Link]
message3 Publish a message with the
body message3 to [Link]
START Start a new global
transaction.
GET Attempt to receive a
message. This fails: there is
no message.
END End the current global
transaction in success.
PREPARE Prepare to commit the
current global transaction.
GET Attempt to receive a
message. This fails: there is
no message
COMMIT Commit the global
transaction.
Receives the first message
GET then displays its content,
message1.

Receives the next message


GET then displays its content,
message2.

Receives the third message


GET then displays its content,
message3.

End the current global


END
transaction in success.
ROLLBA Rollback the current global
CK transaction.
Receives and displays the
GET
first message again.
GET Receives and displays the
second message again.

Aurea Software, Inc. Confidential 111 Copyright © 2013 Aurea, Inc.


Chapter 7: Distributed Transactions in C Using the XA Interface

Table 1: XASample’s Prescribed Transaction Entries

Producer Consumer

Enter Comment Enter Comment

GET Receives and displays the


third message again.
no text End the Producer dialog
no text End the Consumer dialog

When you finish, close the console windows.

In Doubt Global Transactions


If a global transaction succeeds in phase one of the two-phase commit, the physical
connections can fail so that part of the global transaction is recorded and part of it is
indeterminate. The commitment might execute yet fail before notifying the TM, as illustrated
in Figure 7.

Figure 7: In-Doubt Transaction During Two-Phase Commit

Phase 1: Prepare
Ready !
Resource
Phase 2: Commit Manager
Released

Commit Transaction
Application
Manager
Phase 1: Prepare
Ready !
Resource
Phase 2: Commit Manager
X

In this case, one branch of the global transaction committed while another branch did not.

SonicMQ Can Complete In-doubt Transaction Branches


SonicMQ provides administrative capabilities to members of the TxnAdministrator group
to review and manipulate the uncommitted branches. For more information, see the
information for transaction administrators and resolution of indoubt transaction branches in
the Aurea SonicMQ Configuration and Management Guide.

Access Control Group for Transaction Administrators


SonicMQ administrators can use the Sonic Management Console to assign users to a
special user group, TxnAdministrators, to view and handle indoubt transactions. See the
Aurea SonicMQ Configuration and Management Guide for more information.

Aurea Software, Inc. Confidential 112 Copyright © 2013 Aurea, Inc.


Distributed Transactions Models

Transaction Recovery
If the transaction owner becomes unable to continue, a transaction manager can invoke a
recovery method to a resource manager to determine the identity (xidnnn) and status of
transaction branches.

Distributed Transactions Models


Distributed transactions can:

• Allow SonicMQ to participate in transactions controlled by an application server that


involves other resources such as a database
• Allow SonicMQ to participate in a distributed transaction
• Allow one SonicMQ transaction be composed of PTP and Pub/Sub messages

SonicMQ Integrated with an Application Server


When a SonicMQ client is integrated with an XA-compliant application server, as shown in
Figure 8, the application server has a transaction manager. The TM begins, ends,
prepares, and commits the transaction work.

Inside SonicMQ, the TM is communicating with the SonicMQ server to let clients coordinate
with the broker. This is transparent to the application server.

The application might choose to use a container-managed transaction which means that
everything is managed by the application server.

Aurea Software, Inc. Confidential 113 Copyright © 2013 Aurea, Inc.


Chapter 7: Distributed Transactions in C Using the XA Interface

Figure 8: SonicMQ Integrated with an Application Server

Application Client

Application Server

Transaction Manager

SonicMQ Client
SonicMQ
Resource
xa_switch
Manager Broker

SonicMQ Used Directly with a Transaction


Manager
As shown in Figure 9, when standing alone, a JMS application can use the JMS XA SPI to
get an XA connection and an XA session that will get an XA resource reference for the
transaction manager.

Aurea Software, Inc. Confidential 114 Copyright © 2013 Aurea, Inc.


Distributed Transactions Models

Figure 9: SonicMQ Directly Accessing a Transaction Manager

JMS Application

Transaction Manager

SonicMQ Client
SonicMQ
JMS XA SPI XA Resource Broker

SonicMQ Performing DTP Without a


Transaction Manager
Because the XA interface and the protocols are public, application developers can do all
the work handled by the transaction manager directly in their code. Figure 10 illustrates a
simple example where the application directly calls the xa_switch structure and references
the XA resource. The developer is responsible for the preparation and commit (or rollback)
of the transaction.

Figure 10: SonicMQ Performing DTP Without a Transaction Manager

JMS Application

SonicMQ Client
SonicMQ
Resource
xa_switch
Manager Broker

This model constrains the application from the benefits of distributed transaction branches.
However, for cases where two sessions, one PTP and one Pub/Sub, must coordinate in a
transaction, this model might be appropriate.

Aurea Software, Inc. Confidential 115 Copyright © 2013 Aurea, Inc.


Chapter 7: Distributed Transactions in C Using the XA Interface

Aurea Software, Inc. Confidential 116 Copyright © 2013 Aurea, Inc.


8
Next Steps

To learn more about Aurea SonicMQ and its C/C++/COM Clients, access:

• Online Books and API Documentation — You can learn about the
programming, deployment, and management of SonicMQ from its documentation
set. The SonicMQ documentation link, sonic_welcome.htm, provides links to
SonicMQ PDF books, release notes, and SonicMQ API online reference.

The SonicMQ C Client sample applications parallel the SonicMQ sample applications,
which are described in detail in Getting Started with Aurea SonicMQ and the “Examining
the SonicMQ Samples” chapter in the Aurea SonicMQ Application Programming Guide.
See Aurea Sonic Documentation on page 9 for descriptions of the SonicMQ books.

• Aurea Software Web Site — The latest SonicMQ information and downloads
are accessible by registering at [Link]/sonic.

• Technical and Pre-sales Support — Aurea Software’s professional sales and


support staff are ready to help you complete your testing, purchase, and
implementation of the SonicMQ C Client. See the Web site, email, and telephone
contact information for Worldwide Technical Support on page 11.

Aurea Software, Inc. Confidential 117 Copyright © 2013 Aurea, Inc.


Chapter 8: Next Steps

Aurea Software, Inc. Confidential 118 Copyright © 2013 Aurea, Inc.


A
Comparing the C Client with the
Java Client

This appendix distinguishes which SonicMQ client features are available in the Java Clients
and that are not yet available in the SonicMQ C Client.

The appendix includes these sections:

• Message Types on page 119


• Messaging Features on page 120
• Management Framework Capabilities on page 126

Message Types
The JMS Java Client supports all JMS specified message types and also provides an
XMLMessage type and a MultipartMessage type. The SonicMQ C Client supports the JMS
message types TextMessage, BytesMessage, and the bodyless Message. Other types can
be handled indirectly with limitations.

XMLMessage
While not supported, XMLMessages are an extension of the TextMessage.

• Inbound, an XMLMessage is considered a TextMessage by the C Client. You can


thereafter read the initial lines of its payload to discover that it is XML. You can forward
an incoming XMLMessage to another destination and preserve its message type.

Aurea Software, Inc. Confidential 119 Copyright © 2013 Aurea, Inc.


Chapter A: Comparing the C Client with the Java Client

• Outbound, you can package XML into a TextMessage and then produce the message
to a destination where it can be picked up by an application that repackages it as an
XMLMessage. A good technique is to set the message’s header field JMSType or a
custom property that indicates that the content is XML.

ObjectMessage, StreamMessage, and


MultipartMessage
The C Client cannot accept an ObjectMessage, StreamMessage, or MultipartMessage. You
can forward messages of these types back to destinations where other clients (such as
Java Clients) can handle them. Forwarding lets you complete the chain of
acknowledgements and preserve the unacceptable message’s type and payload.

MapMessage
A MapMessage is a set of strongly typed name-value pairs. You cannot access an incoming
MapMessage from the C Client. Outbound, you can either:

• Set properties for each name-value pair, and then send the message as a bodyless
Message.

• Use a BytesMessage and provide a decoding template at the start of the message that
indicates the template length and then delineates each name and value length that
can be read from the balance of the message.

Messaging Features
Some features of the SonicMQ Java Client have not been ported to other clients. If any of
these features suits your architectural needs, contact your Aurea Software representative
to learn about the feature’s scheduled implementation in the SonicMQ C Client.

Recoverable File Channels for Large Message


Handling
A recoverable file channel is a unidirectional stream of information from a JMS Java Client
to a JMS Java Client, a peer-to-peer type of transfer, similar to FTP. State and recovery
information is stored on both the sending and receiving clients and is separate from state
and recovery information stored on brokers. Typically reserved for messages where a
partial send requires less effort to recover from than a resend, messages from ten
megabyte to multi-gigabyte messages are moved through a queue.

For more information about recoverable file channels, see Chapter 11 of the Aurea
SonicMQ Application Programming Guide.

Aurea Software, Inc. Confidential 120 Copyright © 2013 Aurea, Inc.


Messaging Features

Broker-managed Timeouts on Transacted


Sessions
A SonicMQ broker can use a broker configuration property to indicate that it will not tolerate
transacted messages that have been in process more than the specified number of
minutes. If the time is exceeded, the transaction is forced to roll back and the transacted
session is then closed. This property is the transaction Idle Timeout property, configured
by tuning broker properties through the Sonic Management Console. There is a client side
to the functionality that has been implemented in Java but not for the C Clients.

For more information about transacted timeouts, see Chapter 5 of the Aurea SonicMQ
Application Programming Guide.

Protocols
The TCP and SSL protocols are supported for SonicMQ C Clients.

Acknowledge and Forward


The best way to route messages to a remote queue is to build a transaction for a message
where the message is not acknowledged to the broker queue from which it was received
until it is securely enqueued in its target destination. SonicMQ Java Clients have a method
that offers the increased reliability of acknowledge-and-forward without the overhead of a
transacted session. The body and property of the message are not changed by this
method.

A message move requires that a JMS client have the ability to both acknowledge receipt of
a message and forward onto a new queue in a single, atomic action that couples the send
method and the receipt acknowledge method. The session is required to use
SINGLE_MESSAGE_ACKNOWLEDGE, which is the SonicMQ non-transacted extension of the
CLIENT_ACKNOWLEDGE session parameter applies to the current message only.

For more information about acknowledge and forward, see Chapter 8 of the Aurea
SonicMQ Application Programming Guide.

Duplicate Transaction Detection


SonicMQ extends the JMS concept of a transacted session to allow a commit to take an
optional index parameter and possibly a lifespan parameter. The indexed commit operation
is supported on SonicMQ Java Client transacted queue sessions and topic sessions.

For more information on duplicate detection, see Chapter 10 of the Aurea SonicMQ
Application Programming Guide.

Aurea Software, Inc. Confidential 121 Copyright © 2013 Aurea, Inc.


Chapter A: Comparing the C Client with the Java Client

Client Persistence
Where a network failure during a JMS send normally causes a message being sent to be
effectively lost unless the user application takes additional precautions, client persistence
enables client-based logging of messages sent until the broker connection is
re-established. This feature enhances delivery guarantees and provides disconnected
operation on Java Clients.

For more information about client persistence on the Java Client,


see Chapter 4 of the Aurea SonicMQ Application Programming Guide.

Flow Control Administrative Events


SonicMQ JMS Java Client connection factory methods allow a client to set a monitor
interval that can either disable flow control monitoring for all sessions on a connection or
send flow control pause notifications after the session is blocked for one full monitoring
interval.

For more information about flow control events on the Java Client,
see Chapter 5 of the Aurea SonicMQ Application Programming Guide.

Per-message Encryption
When a Java Client application wants to ensure that it sends messages to a
security-enabled broker after encrypting them and establishing integrity tests, the
application can set the property JMS_SonicMQ_perMessageEncryption.

For more information about per-message encryption on the Java Client,


see Chapter 6 of the Aurea SonicMQ Application Programming Guide.

Global Subscription Propagation


SonicMQ brokers can administratively connect the topic spaces of two nodes so that
messages published to a topic on one node are delivered to subscribers on the other node
without using a special destination format. This technique is called global subscriptions.
While programmers do not have to be aware that they are receiving from topics that cross
routing nodes, client software is required to manage the flow control and
acknowledgements appropriate to these special subscriptions.

For more information about broker-based global subscription rules, see Chapter 9 of the
Aurea SonicMQ Application Programming Guide.

Aurea Software, Inc. Confidential 122 Copyright © 2013 Aurea, Inc.


Messaging Features

Pub/Sub Message Selection on the Broker


Connections where message selectors are used can receive a large number of messages
from the broker and select only a few messages for processing. This condition can be
relieved for Java clients by using the method setSelectorAtBroker(true) on the factory.
A similar method is not available to C Clients in this release. However, the default behavior
on C Clients is to perform the selection tasks at the broker. Therefore, the alternative of
setting selectors to perform on the client is the feature not available on C Clients.

For more information about message selectors, see Chapter 7 of the Aurea SonicMQ
Application Programming Guide.

Flow To Disk
SonicMQ brokers can choose to let messages be offloaded to the database used by the
SonicMQ broker when published messages cannot be delivered immediately to a
connected yet slow subscriber. This broker functionality and the effects of flow control are
common to all SonicMQ clients. However, the SonicMQ Java client can choose to override
the broker setting to turn Flow To Disk on or off, an option that is not available to the
SonicMQ C Client.

For more information about flow to disk, see Chapter 5 of the Aurea SonicMQ Application
Programming Guide.

JMS 1.1 Domain Unification


The JMS 1.1 specification states “Prior to version 1.1 of the JMS specification, only the
client interfaces that were tailored to each domain (PTP and Pub/Sub) were available.
These interfaces continue to be supported to provide backward compatibility for those who
have already implemented JMS clients using them. The preferred approach for
implementing clients is to use the domain-independent interfaces. These interfaces,
referred to as the common interfaces, are parents of the domain-specific interfaces.”

These common interfaces have been implemented in the SonicMQ Java client and are not
available in the SonicMQ C Client.

Clusterwide Access to Durable Subscriptions


Messages in a durable subscription can be accessed from any broker in a cluster. A
message that is published on one broker can be received by a client application that
created a durable subscriber on any other broker in the cluster. When a message is
published for a disconnected durable subscriber, or a message is published while there is
no active subscriber for the durable subscription on any broker in the cluster, that message
is stored in the message store on the publishing broker. When the client application
connects to any broker in the cluster and recreates the durable subscriber for the
subscription, the messages stored earlier for that subscription are forwarded to the client
application.

Aurea Software, Inc. Confidential 123 Copyright © 2013 Aurea, Inc.


Chapter A: Comparing the C Client with the Java Client

Strict Message Order with Clusterwide Durable


Subscriptions
When a client is publishing messages and the broker to which it is connected becomes
unavailable, the client can reconnect to any other broker in the cluster and continue
publishing messages. However, some of the messages published by the first session might
be stored in the failed broker, and when that broker is restarted they can be delivered out
of order. With a single broker configuration, message ordering to durable subscribers is
always guaranteed. In a clustered environment, SonicMQ supports optional strict message
ordering to durable subscribers.

SonicMQ Java clients provide methods to set durable message order on the connection
factory or the session that are not supported on Sonic C Clients.

For more information about clusterwide access to durable subscriptions and strict message
order with clusterwide durable subscriptions, see Chapter 9 of the Aurea SonicMQ
Application Programming Guide.

Sonic Stream API


This API enables a stream publisher application to send a stream of bytes of indeterminate
length as segments through a JMS broker topic to many stream subscribers. See the
“SonicStream API” chapter in the Aurea SonicMQ Application Programming Guide. This
feature is not supported by the Aurea SonicMQ C client.

Programmatic Limit to Redelivery Attempts


from a Queue
Applications can exit a loop where a message causes application failure and rollback, only
to repeat the failure when the same “poison message” is redelivered. The feature enables
programmatic setting of a maximum redelivery count that causes unacknowledged
messages that exceed the redelivery limit to be discarded. See the “SonicMQ Client
Sessions” chapter in the Aurea SonicMQ Application Programming Guide. This feature is
not supported by the Aurea SonicMQ C client.

Non-Persistent Replicated Delivery Mode


(CAA-FastForward)
SonicMQ provides a delivery mode (NON_PERSISTENT_REPLICATED) that protects
non-persistent messages from broker failures by replicating the messages to a standby
broker. This feature is called CAA-Fast Forward (CAA-FF). CAA-FF combines the
performance of non-persistent messaging with the reliability of Sonic's Continuous
Availability Architecture to provide an unparalleled message throughput and latency for
reliable delivery. See the “SonicMQ Connections” chapter in the Aurea SonicMQ
Application Programming Guide. This feature is not supported by the Aurea SonicMQ C
client.

Aurea Software, Inc. Confidential 124 Copyright © 2013 Aurea, Inc.


Messaging Features

MultiTopic Constructs for Producers and


Consumers
Application code or administered destination objects that define a list of topics as a
MultiTopic enable publishers to accelerate the publishing operation to many topics
concurrently, even to a specified Dynamic Routing node. A new sample, MultiTopicChat,
is included. See the “Publish and Subscribe Messaging” and “Examining the SonicMQ JMS
Samples” chapters in the Aurea SonicMQ Application Programming Guide. This feature is
not supported by the Aurea SonicMQ C client.

Socket Connect Timeout


When using a JVM that supports socket connect timeout, you can set a timeout to be used
when establishing a socket connection to a broker. See the “Introduction to Configuration”
chapter in the Aurea SonicMQ Configuration and Management Guide.

This feature is also included as a parameter of the JMS Administered Objects Connection
Factory. See the “SonicMQ Connections” chapter in the Aurea SonicMQ Application
Programming Guide.

This feature is not supported by the Aurea SonicMQ C client.

Custom Destinations for Undelivered


Messages
While every SonicMQ broker provides a Dead Message Queue (DMQ), you can now
override the default destination for preserving undelivered messages programmatically by
defining an undelivered destination. When delivery of the message to the user-specified
DMQ destination fails, the message is placed in the default DMQ of the appropriate broker.

To override the Dead Message Queue, set the message property as follows:

char PROPERTY_NAME_SMQ_DEST_UND[] = "JMS_SonicMQ_destinationUndelivered";


char PROPERTY_NAME_SMQ_DEST_QNAME[] = "$Q.SampleQ4";

char PROPERTY_NAME_SMQ_PRES_UND[] = "JMS_SonicMQ_preserveUndelivered";


char PROPERTY_NAME_SMQ_NOTIFY_UND[] = "JMS_SonicMQ_notifyUndelivered";

HOBJ propNameDestUndelivered;
HOBJ propNameDeadQName;

HOBJ propNamePreserveUndelivered;
HOBJ propNameNotifyUndelivered;

/* Create a property string object. */


if (String_create2(PROPERTY_NAME_SMQ_DEST_UND, &propNameDestUndelivered)
!= 0) {
fprintf(stderr, "Error creating property String object\n");
handleJMSException();
}
/* Create a property string object. */

Aurea Software, Inc. Confidential 125 Copyright © 2013 Aurea, Inc.


Chapter A: Comparing the C Client with the Java Client

if (String_create2(PROPERTY_NAME_SMQ_DEST_QNAME, &propNameDeadQName) != 0)
{
fprintf(stderr, "Error creating property String object\n");
handleJMSException();
}
/* Create a property string object. */
if (String_create2(PROPERTY_NAME_SMQ_PRES_UND,
&propNamePreserveUndelivered) != 0) {
fprintf(stderr, "Error creating property String object\n");
handleJMSException();
}
/* Create a property string object. */
if (String_create2(PROPERTY_NAME_SMQ_NOTIFY_UND,
&propNameNotifyUndelivered) != 0) {
fprintf(stderr, "Error creating property String object\n");
handleJMSException();
}
/* Setthe message property for the selector. */
if (TextMessage_setStringProperty(msg, propNameDestUndelivered,
propNameDeadQName) != 0) {
fprintf(stderr, "Error creating TextMessage\n");
handleJMSException();
}
if (TextMessage_setBooleanProperty(msg, propNamePreserveUndelivered,
jtrue) != 0) {
fprintf(stderr, "Error setting PRESERVE_UNDELIVERED property\n");
handleJMSException();
}
if (TextMessage_setBooleanProperty(msg, propNameNotifyUndelivered, jtrue)
!= 0) {
fprintf(stderr, "Error setting PRESERVE_UNDELIVERED property\n");
handleJMSException();
}

If a message is undelivered, it is placed in the destination queue specified in the above


code (in this case SampleQ4).

For more information, see the “Guaranteeing Messages” chapter in the Aurea SonicMQ
Application Programming Guide and the “Configuring Queues” chapter in the Aurea
SonicMQ Configuration and Management Guide.

Management Framework Capabilities


SonicMQ provides the Sonic Management Environment and supporting APIs for Java
Clients.

• Management Console — The Sonic Management Console is a Java-based GUI tool


that provides configurations and runtime management of SonicMQ deployments.
There is no non-Java management console.
• Management Application API — The APIs that enable management functions
programmatically are based on Java Management Extensions (JMX) and are
reserved for SonicMQ Java Clients.
• Metrics and Monitoring API — The APIs that provide metrics and notifications
functions programmatically are based on Java Management Extensions (JMX) and
are reserved for SonicMQ Java Clients.

Aurea Software, Inc. Confidential 126 Copyright © 2013 Aurea, Inc.


Management Framework Capabilities

For more information about the management and metrics APIs, see the appendices
of the Aurea SonicMQ Administrative Programming Guide.

For more information about the management framework, see the Aurea SonicMQ
Configuration and Management Guide.

Aurea Software, Inc. Confidential 127 Copyright © 2013 Aurea, Inc.


Chapter A: Comparing the C Client with the Java Client

Aurea Software, Inc. Confidential 128 Copyright © 2013 Aurea, Inc.


Index
A client acknowledgement 23

CLIENT_ACKNOWLEDGE 72
acknowledge and forward 25
clients
acknowledgement 23
identifier 67
automatic 23
client 23 commit
Dups_OK 23 definition 23
lazy 23 in a global transaction 106, 107
single message 23
concurrency 22
administered objects
ConnectionFactories 65 ConnectionFactories
definition 65
asynchronous 24
connections 21
authentication fault-tolerant 76
SSL identifier 66
client certificates 101
username and password 100 connections, creating 68
automatic acknowledgement 23 consumers 24

Continuous Availability
B client connection 76

browser 28 creating, connections 68

BytesMessage type 31 creating, send queue 69

creating, sessions 68
C
callback functions 59 D
characters, restricted 63 dead message queue 27, 33

Chat sample application 45 delivery mode 25, 30

cleaning up, after sending message 70 destinations 25


temporary 32

Aurea Software, Inc. Confidential 129 Copyright © 2013 Aurea, Inc.


Index

discardable 25 transaction state 106, 107

duplicate message detection 24 integrity 33

durable subscribers
definition 30 J
durable subscription JMS
sample application 46 provider 15
DurableChat sample application 46

Dynamic Routing Architecture 19 L


lazy acknowledgement 23
E life span of a message 30
enlistment of resources 105 listeners 24
exception_getmessage 61 local security store 92
exceptions 61 Login SPI 92
expiration
definition 30 M
effect on quality of service 33
external security store 92 message selectors 26

message servers
F topology 14
message types 31
fault tolerant client 76
Message_gettype 57
fault-tolerant connections 76
Message_instanceof 57
Figure 1
Distributed Application Structure 14 messages
body 32
forwarding 25 header fields 32
properties 32
H
N
header files 56
non-persistent 25
hierarchical name spaces
definition 31
HierarchicalChat sample application 47, 48 P
HOBJs 56 persistent 25
delivery mode 30
HOBJs,releasing 60 message 33
hostname 66 persistent message delivery 72

point-to-point 25
I
Point-to-Point sample applications 41
identifier
port 66
client 67
connection 66 prefetch 26
indoubt privacy 34

Aurea Software, Inc. Confidential 130 Copyright © 2013 Aurea, Inc.


Index

producers 24 SMQ_getLastError 61

properties 32 SMQ_getLastErrorText 61

protocols 66 smqc.h 56

publish and subscribe 25 SonicMQ naming restrictions 63

Publish and Subscribe sample applications SPIs


45, 46 Login 92

publishers 30 SSL 97

starting, connection 70
Q store and forward 25
quality of protection 33 strings 57
quality of service 32 subscribers 30
queues support, technical 11
browser 28
definition 25 synchronous 24

R T
receivers 27 Talk sample application 42
release method 60 technical support 11
ReliableChat sample application 49 temporary destination 32
ReliableTalk sample application 43 TextMessage type 31
request and reply 23, 32 topic hierarchies 31
RequestReply sample application 51 topics 25
resource transacted sessions
enlistment 105 definition 22
rollback transaction
definition 23 context 105
transaction manager 104
S
transactions
security store global 23
external 92 local 23
internal 92 timeout 23

selectors 26, 29 two-phase commit 106, 107

senders 27
U
sending, message 70
URL 66
sessions 21
username 67
sessions, creating 68

Aurea Software, Inc. Confidential 131 Copyright © 2013 Aurea, Inc.


Index

Aurea Software, Inc. Confidential 132 Copyright © 2013 Aurea, Inc.

You might also like