From abada90e3f84dc703b8ddc9efcbed8a946fadead Mon Sep 17 00:00:00 2001 From: Bernard Normier Date: Thu, 1 Feb 2007 17:09:49 +0000 Subject: Expanded tabs into spaces --- cpp/RPMTools.py | 620 +- cpp/allTests.py | 56 +- cpp/config/IceGridAdmin.py | 28 +- cpp/config/TestUtil.py | 178 +- cpp/config/convertssl.py | 184 +- cpp/config/findSliceFiles.py | 14 +- cpp/config/makeprops.py | 372 +- cpp/config/upgradeicegrid.py | 6 +- cpp/config/upgradeicestorm.py | 4 +- cpp/demo/Database/Oracle/occi/Client.cpp | 606 +- cpp/demo/Database/Oracle/occi/DeptFactoryI.cpp | 72 +- cpp/demo/Database/Oracle/occi/DeptFactoryI.h | 8 +- cpp/demo/Database/Oracle/occi/DeptI.cpp | 92 +- cpp/demo/Database/Oracle/occi/EmpI.cpp | 120 +- .../Database/Oracle/occi/OCCIServantLocator.cpp | 54 +- cpp/demo/Database/Oracle/occi/Server.cpp | 48 +- cpp/demo/Database/Oracle/occi/Util.cpp | 66 +- cpp/demo/Database/Oracle/occi/Util.h | 4 +- cpp/demo/Database/Oracle/proc/Client.cpp | 606 +- cpp/demo/Database/Oracle/proc/CurrentSqlContext.pc | 82 +- cpp/demo/Database/Oracle/proc/DeptFactoryI.pc | 28 +- cpp/demo/Database/Oracle/proc/DeptI.pc | 52 +- cpp/demo/Database/Oracle/proc/EmpI.pc | 34 +- cpp/demo/Database/Oracle/proc/Server.pc | 14 +- cpp/demo/Database/Oracle/proc/Util.pc | 4 +- cpp/demo/Freeze/backup/Client.cpp | 78 +- cpp/demo/Freeze/bench/Client.cpp | 794 +-- cpp/demo/Freeze/library/Client.cpp | 6 +- cpp/demo/Freeze/library/Collocated.cpp | 10 +- cpp/demo/Freeze/library/Library.ice | 16 +- cpp/demo/Freeze/library/LibraryI.cpp | 132 +- cpp/demo/Freeze/library/LibraryI.h | 4 +- cpp/demo/Freeze/library/Parser.cpp | 440 +- cpp/demo/Freeze/library/RunParser.cpp | 176 +- cpp/demo/Freeze/library/Server.cpp | 4 +- cpp/demo/Freeze/phonebook/Client.cpp | 6 +- cpp/demo/Freeze/phonebook/Collocated.cpp | 10 +- cpp/demo/Freeze/phonebook/Parser.cpp | 396 +- cpp/demo/Freeze/phonebook/PhoneBookI.cpp | 34 +- cpp/demo/Freeze/phonebook/RunParser.cpp | 176 +- cpp/demo/Freeze/phonebook/Server.cpp | 4 +- cpp/demo/Glacier2/callback/CallbackI.cpp | 22 +- cpp/demo/Glacier2/callback/Client.cpp | 246 +- cpp/demo/Glacier2/callback/SessionI.cpp | 2 +- cpp/demo/Glacier2/chat/ChatSessionI.cpp | 40 +- cpp/demo/Glacier2/chat/Client.cpp | 310 +- cpp/demo/Glacier2/chat/Server.cpp | 16 +- cpp/demo/Ice/MFC/client/HelloClient.cpp | 6 +- cpp/demo/Ice/MFC/client/stdafx.h | 24 +- cpp/demo/Ice/MFC/server/HelloServer.cpp | 6 +- cpp/demo/Ice/MFC/server/LogI.cpp | 4 +- cpp/demo/Ice/MFC/server/stdafx.h | 24 +- cpp/demo/Ice/async/Client.cpp | 84 +- cpp/demo/Ice/async/WorkQueue.cpp | 60 +- cpp/demo/Ice/async/WorkQueue.h | 2 +- cpp/demo/Ice/bidir/CallbackI.cpp | 58 +- cpp/demo/Ice/bidir/CallbackI.h | 18 +- cpp/demo/Ice/bidir/Client.cpp | 6 +- cpp/demo/Ice/bidir/Server.cpp | 6 +- cpp/demo/Ice/callback/CallbackSenderI.cpp | 8 +- cpp/demo/Ice/callback/Client.cpp | 198 +- cpp/demo/Ice/converter/Client.cpp | 106 +- cpp/demo/Ice/converter/StringConverterI.cpp | 76 +- cpp/demo/Ice/hello/Client.cpp | 292 +- cpp/demo/Ice/invoke/Client.cpp | 6 +- cpp/demo/Ice/latency/Client.cpp | 6 +- cpp/demo/Ice/minimal/Client.cpp | 44 +- cpp/demo/Ice/minimal/Server.cpp | 32 +- cpp/demo/Ice/nested/Client.cpp | 46 +- cpp/demo/Ice/nested/NestedI.cpp | 2 +- cpp/demo/Ice/session/Client.cpp | 248 +- cpp/demo/Ice/session/ReapThread.cpp | 62 +- cpp/demo/Ice/session/ReapThread.h | 8 +- cpp/demo/Ice/session/SessionI.cpp | 34 +- cpp/demo/Ice/throughput/Client.cpp | 628 +- cpp/demo/Ice/throughput/ThroughputI.cpp | 10 +- cpp/demo/Ice/value/Client.cpp | 108 +- cpp/demo/Ice/value/ObjectFactory.cpp | 4 +- cpp/demo/IceBox/hello/Client.cpp | 190 +- cpp/demo/IceBox/hello/HelloServiceI.h | 4 +- cpp/demo/IceGrid/allocate/Client.cpp | 194 +- cpp/demo/IceGrid/replication/Client.cpp | 10 +- cpp/demo/IceGrid/sessionActivation/Client.cpp | 170 +- cpp/demo/IceGrid/simple/Client.cpp | 86 +- cpp/demo/IcePatch2/MFC/PatchClientDlg.cpp | 196 +- cpp/demo/IcePatch2/MFC/stdafx.h | 24 +- cpp/demo/IceStorm/clock/Publisher.cpp | 58 +- cpp/demo/IceStorm/clock/Subscriber.cpp | 84 +- cpp/demo/IceStorm/counter/Client.cpp | 78 +- cpp/demo/IceStorm/counter/CounterI.cpp | 2 +- cpp/demo/IceStorm/counter/Server.cpp | 28 +- cpp/demo/IceStorm/replicated/Publisher.cpp | 2 +- cpp/demo/IceStorm/replicated/Subscriber.cpp | 40 +- cpp/demo/IceUtil/workqueue/WorkQueue.cpp | 96 +- cpp/demo/book/evictor/EvictorBase.cpp | 50 +- cpp/demo/book/evictor/EvictorBase.h | 10 +- cpp/demo/book/printer/Client.cpp | 34 +- cpp/demo/book/printer/Printer.ice | 2 +- cpp/demo/book/printer/Server.cpp | 38 +- cpp/demo/book/simple_filesystem/Client.cpp | 64 +- cpp/demo/book/simple_filesystem/Filesystem.ice | 10 +- cpp/demo/book/simple_filesystem/FilesystemI.cpp | 10 +- cpp/demo/book/simple_filesystem/FilesystemI.h | 30 +- cpp/demo/book/simple_filesystem/Server.cpp | 80 +- cpp/fixCopyright.py | 4 +- cpp/fixVersion.py | 122 +- cpp/iceemakedist.py | 54 +- cpp/include/Freeze/Initialize.h | 28 +- cpp/include/Freeze/Map.h | 776 +-- cpp/include/Ice/BasicStream.h | 166 +- cpp/include/Ice/Buffer.h | 224 +- cpp/include/Ice/FactoryTable.h | 2 +- cpp/include/Ice/GCShared.h | 4 +- cpp/include/Ice/Handle.h | 186 +- cpp/include/Ice/IncomingAsync.h | 2 +- cpp/include/Ice/Initialize.h | 14 +- cpp/include/Ice/Object.h | 2 +- cpp/include/Ice/Outgoing.h | 10 +- cpp/include/Ice/OutgoingAsync.h | 4 +- cpp/include/Ice/Proxy.h | 156 +- cpp/include/Ice/ProxyHandle.h | 190 +- cpp/include/Ice/StringConverter.h | 8 +- cpp/include/IcePatch2/Util.h | 144 +- cpp/include/IceStorm/Service.h | 10 +- cpp/include/IceUtil/AbstractMutex.h | 18 +- cpp/include/IceUtil/Cache.h | 298 +- cpp/include/IceUtil/Cond.h | 40 +- cpp/include/IceUtil/DisableWarnings.h | 4 +- cpp/include/IceUtil/Functional.h | 32 +- cpp/include/IceUtil/Handle.h | 184 +- cpp/include/IceUtil/InputUtil.h | 4 +- cpp/include/IceUtil/Lock.h | 58 +- cpp/include/IceUtil/Monitor.h | 100 +- cpp/include/IceUtil/Mutex.h | 74 +- cpp/include/IceUtil/Options.h | 6 +- cpp/include/IceUtil/OutputUtil.h | 4 +- cpp/include/IceUtil/RWRecMutex.h | 158 +- cpp/include/IceUtil/RecMutex.h | 6 +- cpp/include/IceUtil/ScopedArray.h | 24 +- cpp/include/IceUtil/Shared.h | 112 +- cpp/include/IceUtil/StaticMutex.h | 78 +- cpp/include/IceUtil/Thread.h | 4 +- cpp/include/IceUtil/Time.h | 88 +- cpp/include/IceUtil/Unicode.h | 14 +- cpp/include/Slice/CPlusPlusUtil.h | 10 +- cpp/include/Slice/CsUtil.h | 2 +- cpp/include/Slice/JavaUtil.h | 14 +- cpp/include/Slice/Parser.h | 60 +- cpp/include/Slice/VbUtil.h | 2 +- cpp/install/common/components.py | 602 +- cpp/install/common/makewindist.py | 892 +-- cpp/install/rpm/makeSRPMs.py | 18 +- cpp/makebindist.py | 704 +-- cpp/makedist.py | 6 +- cpp/slice/Glacier2/Router.ice | 6 +- cpp/slice/Glacier2/Session.ice | 4 +- cpp/slice/Ice/Locator.ice | 10 +- cpp/slice/IceGrid/Admin.ice | 94 +- cpp/slice/IceGrid/FileParser.ice | 2 +- cpp/slice/IceGrid/Registry.ice | 8 +- cpp/slice/IceGrid/Session.ice | 6 +- cpp/slice/IceGrid/UserAccountMapper.ice | 2 +- cpp/slice/IcePatch2/FileServer.ice | 4 +- cpp/slice/IceStorm/IceStorm.ice | 2 +- cpp/src/Freeze/ConnectionI.cpp | 36 +- cpp/src/Freeze/ConnectionI.h | 6 +- cpp/src/Freeze/EvictorI.cpp | 2280 ++++---- cpp/src/Freeze/EvictorI.h | 16 +- cpp/src/Freeze/EvictorIteratorI.cpp | 274 +- cpp/src/Freeze/IndexI.cpp | 402 +- cpp/src/Freeze/MapI.cpp | 1552 ++--- cpp/src/Freeze/MapI.h | 30 +- cpp/src/Freeze/ObjectStore.cpp | 362 +- cpp/src/Freeze/ObjectStore.h | 2 +- cpp/src/Freeze/SharedDb.cpp | 402 +- cpp/src/Freeze/SharedDb.h | 34 +- cpp/src/Freeze/SharedDbEnv.cpp | 374 +- cpp/src/Freeze/TransactionHolder.cpp | 50 +- cpp/src/Freeze/TransactionI.cpp | 160 +- cpp/src/Freeze/TransactionI.h | 2 +- cpp/src/Freeze/Util.cpp | 72 +- cpp/src/Freeze/Util.h | 4 +- cpp/src/FreezeScript/Data.cpp | 44 +- cpp/src/FreezeScript/DumpDB.cpp | 268 +- cpp/src/FreezeScript/DumpDescriptors.cpp | 24 +- cpp/src/FreezeScript/DumpDescriptors.h | 2 +- cpp/src/FreezeScript/Functions.cpp | 4 +- cpp/src/FreezeScript/Functions.h | 2 +- cpp/src/FreezeScript/TransformAnalyzer.cpp | 20 +- cpp/src/FreezeScript/TransformAnalyzer.h | 4 +- cpp/src/FreezeScript/Transformer.cpp | 82 +- cpp/src/FreezeScript/Transformer.h | 6 +- cpp/src/FreezeScript/Util.cpp | 42 +- cpp/src/FreezeScript/transformdb.cpp | 738 +-- cpp/src/Glacier2/Blobject.cpp | 510 +- cpp/src/Glacier2/Blobject.h | 2 +- cpp/src/Glacier2/ClientBlobject.cpp | 138 +- cpp/src/Glacier2/ClientBlobject.h | 2 +- cpp/src/Glacier2/CryptPermissionsVerifierI.cpp | 4 +- cpp/src/Glacier2/FilterI.h | 76 +- cpp/src/Glacier2/FilterManager.cpp | 350 +- cpp/src/Glacier2/FilterManager.h | 12 +- cpp/src/Glacier2/Glacier2Router.cpp | 342 +- cpp/src/Glacier2/ProxyVerifier.cpp | 1010 ++-- cpp/src/Glacier2/RequestQueue.cpp | 402 +- cpp/src/Glacier2/RequestQueue.h | 2 +- cpp/src/Glacier2/RouterI.cpp | 104 +- cpp/src/Glacier2/RouterI.h | 2 +- cpp/src/Glacier2/RoutingTable.cpp | 126 +- cpp/src/Glacier2/RoutingTable.h | 4 +- cpp/src/Glacier2/ServerBlobject.cpp | 4 +- cpp/src/Glacier2/ServerBlobject.h | 2 +- cpp/src/Glacier2/SessionRouterI.cpp | 1028 ++-- cpp/src/Glacier2/SessionRouterI.h | 18 +- cpp/src/Ice/Application.cpp | 624 +- cpp/src/Ice/BasicStream.cpp | 1148 ++-- cpp/src/Ice/Buffer.cpp | 20 +- cpp/src/Ice/CommunicatorI.cpp | 146 +- cpp/src/Ice/ConnectionFactory.cpp | 1436 ++--- cpp/src/Ice/ConnectionFactory.h | 18 +- cpp/src/Ice/ConnectionI.cpp | 3424 +++++------ cpp/src/Ice/ConnectionI.h | 36 +- cpp/src/Ice/ConnectionMonitor.cpp | 104 +- cpp/src/Ice/DLLMain.cpp | 2 +- cpp/src/Ice/DefaultsAndOverrides.cpp | 22 +- cpp/src/Ice/Direct.cpp | 110 +- cpp/src/Ice/DynamicLibrary.cpp | 32 +- cpp/src/Ice/EndpointFactoryManager.cpp | 4 +- cpp/src/Ice/EventLoggerI.cpp | 2 +- cpp/src/Ice/Exception.cpp | 78 +- cpp/src/Ice/FactoryTableDef.cpp | 106 +- cpp/src/Ice/GC.cpp | 302 +- cpp/src/Ice/IdentityUtil.cpp | 4 +- cpp/src/Ice/ImplicitContextI.cpp | 308 +- cpp/src/Ice/Incoming.cpp | 610 +- cpp/src/Ice/IncomingAsync.cpp | 120 +- cpp/src/Ice/Initialize.cpp | 74 +- cpp/src/Ice/Instance.cpp | 684 +-- cpp/src/Ice/Instance.h | 8 +- cpp/src/Ice/LocatorInfo.cpp | 436 +- cpp/src/Ice/LoggerI.cpp | 6 +- cpp/src/Ice/LoggerUtil.cpp | 8 +- cpp/src/Ice/Network.cpp | 1164 ++-- cpp/src/Ice/Object.cpp | 110 +- cpp/src/Ice/ObjectAdapterFactory.cpp | 146 +- cpp/src/Ice/ObjectAdapterI.cpp | 994 ++-- cpp/src/Ice/ObjectAdapterI.h | 6 +- cpp/src/Ice/ObjectFactoryManager.cpp | 102 +- cpp/src/Ice/Outgoing.cpp | 714 +-- cpp/src/Ice/OutgoingAsync.cpp | 596 +- cpp/src/Ice/PluginManagerI.cpp | 198 +- cpp/src/Ice/PropertiesI.cpp | 142 +- cpp/src/Ice/Protocol.cpp | 2 +- cpp/src/Ice/Proxy.cpp | 974 +-- cpp/src/Ice/ProxyFactory.cpp | 190 +- cpp/src/Ice/Reference.cpp | 904 +-- cpp/src/Ice/Reference.h | 30 +- cpp/src/Ice/ReferenceFactory.cpp | 656 +-- cpp/src/Ice/ReferenceFactory.h | 10 +- cpp/src/Ice/RouterInfo.cpp | 164 +- cpp/src/Ice/ServantManager.cpp | 198 +- cpp/src/Ice/Service.cpp | 366 +- cpp/src/Ice/SharedContext.h | 4 +- cpp/src/Ice/SliceChecksums.cpp | 8 +- cpp/src/Ice/StringConverter.cpp | 66 +- cpp/src/Ice/TcpAcceptor.cpp | 40 +- cpp/src/Ice/TcpConnector.cpp | 8 +- cpp/src/Ice/TcpEndpointI.cpp | 352 +- cpp/src/Ice/TcpTransceiver.cpp | 452 +- cpp/src/Ice/ThreadPool.cpp | 1192 ++-- cpp/src/Ice/ThreadPool.h | 8 +- cpp/src/Ice/TraceUtil.cpp | 514 +- cpp/src/Ice/UdpEndpointI.cpp | 602 +- cpp/src/Ice/UdpTransceiver.cpp | 460 +- cpp/src/Ice/UnknownEndpointI.cpp | 16 +- cpp/src/IceBox/Admin.cpp | 130 +- cpp/src/IceBox/Service.cpp | 6 +- cpp/src/IceBox/ServiceManagerI.cpp | 620 +- cpp/src/IceBox/ServiceManagerI.h | 8 +- cpp/src/IceGrid/Activator.cpp | 1182 ++-- cpp/src/IceGrid/Activator.h | 12 +- cpp/src/IceGrid/AdapterCache.cpp | 274 +- cpp/src/IceGrid/AdapterCache.h | 2 +- cpp/src/IceGrid/AdminI.cpp | 362 +- cpp/src/IceGrid/AdminI.h | 4 +- cpp/src/IceGrid/AdminSessionI.cpp | 266 +- cpp/src/IceGrid/AdminSessionI.h | 8 +- cpp/src/IceGrid/Allocatable.cpp | 476 +- cpp/src/IceGrid/Allocatable.h | 8 +- cpp/src/IceGrid/AllocatableObjectCache.cpp | 224 +- cpp/src/IceGrid/AllocatableObjectCache.h | 24 +- cpp/src/IceGrid/Cache.h | 114 +- cpp/src/IceGrid/Client.cpp | 644 +- cpp/src/IceGrid/Database.cpp | 1358 ++--- cpp/src/IceGrid/Database.h | 4 +- cpp/src/IceGrid/DescriptorBuilder.cpp | 216 +- cpp/src/IceGrid/DescriptorBuilder.h | 4 +- cpp/src/IceGrid/DescriptorHelper.cpp | 2678 ++++----- cpp/src/IceGrid/DescriptorHelper.h | 18 +- cpp/src/IceGrid/DescriptorParser.cpp | 1220 ++-- cpp/src/IceGrid/DescriptorParser.h | 8 +- cpp/src/IceGrid/FileCache.cpp | 170 +- cpp/src/IceGrid/FileParserI.cpp | 6 +- cpp/src/IceGrid/FileUserAccountMapperI.cpp | 82 +- cpp/src/IceGrid/IceGridNode.cpp | 518 +- cpp/src/IceGrid/IceGridRegistry.cpp | 74 +- cpp/src/IceGrid/Internal.ice | 40 +- cpp/src/IceGrid/InternalRegistryI.cpp | 62 +- cpp/src/IceGrid/InternalRegistryI.h | 6 +- cpp/src/IceGrid/LocatorI.cpp | 414 +- cpp/src/IceGrid/LocatorI.h | 42 +- cpp/src/IceGrid/LocatorRegistryI.cpp | 370 +- cpp/src/IceGrid/LocatorRegistryI.h | 10 +- cpp/src/IceGrid/NodeCache.cpp | 824 +-- cpp/src/IceGrid/NodeI.cpp | 1066 ++-- cpp/src/IceGrid/NodeI.h | 20 +- cpp/src/IceGrid/NodeSessionI.cpp | 208 +- cpp/src/IceGrid/NodeSessionI.h | 4 +- cpp/src/IceGrid/NodeSessionManager.cpp | 458 +- cpp/src/IceGrid/NodeSessionManager.h | 50 +- cpp/src/IceGrid/ObjectCache.cpp | 36 +- cpp/src/IceGrid/ObjectCache.h | 14 +- cpp/src/IceGrid/Parser.cpp | 1744 +++--- cpp/src/IceGrid/PlatformInfo.cpp | 158 +- cpp/src/IceGrid/QueryI.cpp | 40 +- cpp/src/IceGrid/QueryI.h | 2 +- cpp/src/IceGrid/ReapThread.cpp | 146 +- cpp/src/IceGrid/ReapThread.h | 48 +- cpp/src/IceGrid/RegistryI.cpp | 942 +-- cpp/src/IceGrid/RegistryI.h | 8 +- cpp/src/IceGrid/ReplicaCache.cpp | 194 +- cpp/src/IceGrid/ReplicaSessionI.cpp | 134 +- cpp/src/IceGrid/ReplicaSessionI.h | 4 +- cpp/src/IceGrid/ReplicaSessionManager.cpp | 698 +-- cpp/src/IceGrid/ReplicaSessionManager.h | 40 +- cpp/src/IceGrid/ServerAdapterI.cpp | 140 +- cpp/src/IceGrid/ServerCache.cpp | 1000 ++-- cpp/src/IceGrid/ServerI.cpp | 2484 ++++---- cpp/src/IceGrid/ServerI.h | 32 +- cpp/src/IceGrid/SessionI.cpp | 168 +- cpp/src/IceGrid/SessionI.h | 6 +- cpp/src/IceGrid/SessionManager.h | 352 +- cpp/src/IceGrid/SessionServantLocatorI.cpp | 4 +- cpp/src/IceGrid/SessionServantLocatorI.h | 6 +- cpp/src/IceGrid/Topics.cpp | 530 +- cpp/src/IceGrid/Util.cpp | 72 +- cpp/src/IceGrid/Util.h | 26 +- cpp/src/IceGrid/WaitQueue.cpp | 160 +- cpp/src/IceGrid/WellKnownObjectsManager.cpp | 6 +- cpp/src/IcePatch2/Calc.cpp | 308 +- cpp/src/IcePatch2/Client.cpp | 264 +- cpp/src/IcePatch2/ClientUtil.cpp | 1144 ++-- cpp/src/IcePatch2/FileServerI.cpp | 58 +- cpp/src/IcePatch2/FileServerI.h | 2 +- cpp/src/IcePatch2/OS.cpp | 4 +- cpp/src/IcePatch2/Server.cpp | 116 +- cpp/src/IcePatch2/Util.cpp | 1518 ++--- cpp/src/IceSSL/AcceptorI.cpp | 58 +- cpp/src/IceSSL/Certificate.cpp | 236 +- cpp/src/IceSSL/ConnectorI.cpp | 206 +- cpp/src/IceSSL/EndpointI.cpp | 328 +- cpp/src/IceSSL/Instance.cpp | 1156 ++-- cpp/src/IceSSL/PluginI.cpp | 186 +- cpp/src/IceSSL/RFC2253.cpp | 444 +- cpp/src/IceSSL/TrustManager.cpp | 174 +- cpp/src/IceSSL/Util.cpp | 288 +- cpp/src/IceStorm/Admin.cpp | 310 +- cpp/src/IceStorm/BatchFlusher.cpp | 110 +- cpp/src/IceStorm/Instance.cpp | 20 +- cpp/src/IceStorm/Parser.cpp | 550 +- cpp/src/IceStorm/Parser.h | 4 +- cpp/src/IceStorm/Service.cpp | 60 +- cpp/src/IceStorm/Subscriber.cpp | 504 +- cpp/src/IceStorm/Subscriber.h | 14 +- cpp/src/IceStorm/SubscriberPool.cpp | 422 +- cpp/src/IceStorm/TopicI.cpp | 484 +- cpp/src/IceStorm/TopicI.h | 2 +- cpp/src/IceStorm/TopicManagerI.cpp | 52 +- cpp/src/IceStorm/TopicManagerI.h | 6 +- cpp/src/IceUtil/Cond.cpp | 96 +- cpp/src/IceUtil/ConvertUTF.cpp | 478 +- cpp/src/IceUtil/ConvertUTF.h | 34 +- cpp/src/IceUtil/CountDownLatch.cpp | 70 +- cpp/src/IceUtil/CtrlCHandler.cpp | 120 +- cpp/src/IceUtil/Exception.cpp | 4 +- cpp/src/IceUtil/InputUtil.cpp | 130 +- cpp/src/IceUtil/MD5I.cpp | 128 +- cpp/src/IceUtil/MD5I.h | 16 +- cpp/src/IceUtil/Options.cpp | 1210 ++-- cpp/src/IceUtil/OutputUtil.cpp | 146 +- cpp/src/IceUtil/RWRecMutex.cpp | 318 +- cpp/src/IceUtil/Random.cpp | 126 +- cpp/src/IceUtil/RecMutex.cpp | 116 +- cpp/src/IceUtil/StaticMutex.cpp | 40 +- cpp/src/IceUtil/StringUtil.cpp | 358 +- cpp/src/IceUtil/Thread.cpp | 132 +- cpp/src/IceUtil/ThreadException.cpp | 46 +- cpp/src/IceUtil/Time.cpp | 2 +- cpp/src/IceUtil/UUID.cpp | 26 +- cpp/src/IceUtil/Unicode.cpp | 116 +- cpp/src/Slice/CPlusPlusUtil.cpp | 1428 ++--- cpp/src/Slice/CsUtil.cpp | 1260 ++-- cpp/src/Slice/DotNetNames.cpp | 130 +- cpp/src/Slice/JavaUtil.cpp | 1844 +++--- cpp/src/Slice/Parser.cpp | 3934 ++++++------- cpp/src/Slice/Preprocessor.cpp | 226 +- cpp/src/Slice/PythonUtil.cpp | 468 +- cpp/src/Slice/RubyUtil.cpp | 1778 +++--- cpp/src/Slice/VbUtil.cpp | 1298 ++-- cpp/src/ca/ImportKey.java | 184 +- cpp/src/icecpp/cccp.c | 6174 ++++++++++---------- cpp/src/icecpp/gansidecl.h | 12 +- cpp/src/icecpp/pcp.h | 14 +- cpp/src/icecpp/prefix.c | 30 +- cpp/src/slice2cpp/Gen.cpp | 4634 +++++++-------- cpp/src/slice2cpp/Gen.h | 348 +- cpp/src/slice2cpp/Main.cpp | 152 +- cpp/src/slice2cppe/Gen.cpp | 2388 ++++---- cpp/src/slice2cppe/Gen.h | 204 +- cpp/src/slice2cppe/Main.cpp | 150 +- cpp/src/slice2cs/Gen.cpp | 4664 +++++++-------- cpp/src/slice2cs/Gen.h | 144 +- cpp/src/slice2cs/Main.cpp | 170 +- cpp/src/slice2docbook/Gen.cpp | 1678 +++--- cpp/src/slice2docbook/Main.cpp | 120 +- cpp/src/slice2freeze/Main.cpp | 2142 +++---- cpp/src/slice2freezej/Main.cpp | 1436 ++--- cpp/src/slice2html/Gen.cpp | 2186 +++---- cpp/src/slice2html/Gen.h | 4 +- cpp/src/slice2html/Main.cpp | 164 +- cpp/src/slice2java/Gen.cpp | 3536 +++++------ cpp/src/slice2java/Gen.h | 12 +- cpp/src/slice2java/Main.cpp | 204 +- cpp/src/slice2javae/Gen.cpp | 1432 ++--- cpp/src/slice2javae/Gen.h | 2 +- cpp/src/slice2javae/Main.cpp | 162 +- cpp/src/slice2py/Main.cpp | 182 +- cpp/src/slice2rb/Main.cpp | 152 +- cpp/src/slice2vb/Gen.cpp | 5302 ++++++++--------- cpp/src/slice2vb/Gen.h | 140 +- cpp/src/slice2vb/Main.cpp | 170 +- cpp/test/Freeze/complex/Client.cpp | 126 +- cpp/test/Freeze/complex/NodeI.h | 48 +- cpp/test/Freeze/complex/Parser.cpp | 14 +- cpp/test/Freeze/dbmap/Client.cpp | 596 +- cpp/test/Freeze/evictor/Client.cpp | 896 +-- cpp/test/Freeze/evictor/Test.ice | 2 +- cpp/test/Freeze/evictor/TestI.cpp | 42 +- cpp/test/Freeze/evictor/TestI.h | 2 +- cpp/test/Freeze/oldevictor/Client.cpp | 896 +-- cpp/test/Freeze/oldevictor/Test.ice | 2 +- cpp/test/Freeze/oldevictor/TestI.cpp | 42 +- cpp/test/Freeze/oldevictor/TestI.h | 2 +- cpp/test/FreezeScript/dbmap/run.py | 4 +- cpp/test/FreezeScript/evictor/makedb.cpp | 2 +- cpp/test/Glacier2/attack/Client.cpp | 92 +- cpp/test/Glacier2/attack/Server.cpp | 6 +- cpp/test/Glacier2/dynamicFiltering/Client.cpp | 136 +- cpp/test/Glacier2/dynamicFiltering/Server.cpp | 32 +- cpp/test/Glacier2/dynamicFiltering/SessionI.cpp | 2 +- .../Glacier2/dynamicFiltering/TestControllerI.cpp | 194 +- .../Glacier2/dynamicFiltering/TestControllerI.h | 24 +- cpp/test/Glacier2/dynamicFiltering/run.py | 6 +- cpp/test/Glacier2/router/Callback.ice | 4 +- cpp/test/Glacier2/router/CallbackI.cpp | 122 +- cpp/test/Glacier2/router/CallbackI.h | 22 +- cpp/test/Glacier2/router/Client.cpp | 1252 ++-- cpp/test/Glacier2/sessionControl/Client.cpp | 22 +- cpp/test/Glacier2/sessionControl/SessionI.cpp | 10 +- cpp/test/Glacier2/sessionControl/run.py | 4 +- cpp/test/Glacier2/ssl/Client.cpp | 34 +- cpp/test/Glacier2/ssl/Server.cpp | 90 +- cpp/test/Glacier2/ssl/run.py | 4 +- cpp/test/Glacier2/staticFiltering/Client.cpp | 180 +- cpp/test/Glacier2/staticFiltering/Server.cpp | 38 +- cpp/test/Glacier2/staticFiltering/run.py | 248 +- cpp/test/Ice/adapterDeactivation/AllTests.cpp | 38 +- .../Ice/adapterDeactivation/ServantLocatorI.cpp | 2 +- cpp/test/Ice/adapterDeactivation/TestI.cpp | 2 +- cpp/test/Ice/binding/AllTests.cpp | 1108 ++-- cpp/test/Ice/binding/Client.cpp | 26 +- cpp/test/Ice/binding/Server.cpp | 26 +- cpp/test/Ice/binding/TestI.cpp | 4 +- cpp/test/Ice/binding/TestI.h | 2 +- cpp/test/Ice/checksum/client/Client.cpp | 26 +- cpp/test/Ice/checksum/server/Server.cpp | 26 +- cpp/test/Ice/custom/AllTests.cpp | 1530 ++--- cpp/test/Ice/custom/Client.cpp | 4 +- cpp/test/Ice/custom/Collocated.cpp | 10 +- cpp/test/Ice/custom/MyByteSeq.cpp | 6 +- cpp/test/Ice/custom/Server.cpp | 10 +- cpp/test/Ice/custom/ServerAMD.cpp | 12 +- cpp/test/Ice/custom/StringConverterI.cpp | 4 +- cpp/test/Ice/custom/StringConverterI.h | 4 +- cpp/test/Ice/custom/Test.ice | 10 +- cpp/test/Ice/custom/TestAMD.ice | 10 +- cpp/test/Ice/custom/TestAMDI.cpp | 130 +- cpp/test/Ice/custom/TestAMDI.h | 128 +- cpp/test/Ice/custom/TestI.cpp | 98 +- cpp/test/Ice/custom/TestI.h | 96 +- cpp/test/Ice/custom/WstringAMDI.cpp | 24 +- cpp/test/Ice/custom/WstringAMDI.h | 24 +- cpp/test/Ice/custom/WstringI.cpp | 20 +- cpp/test/Ice/custom/WstringI.h | 20 +- cpp/test/Ice/exceptions/AllTests.cpp | 1346 ++--- cpp/test/Ice/exceptions/Client.cpp | 26 +- cpp/test/Ice/exceptions/Collocated.cpp | 26 +- cpp/test/Ice/exceptions/Server.cpp | 26 +- cpp/test/Ice/exceptions/ServerAMD.cpp | 26 +- cpp/test/Ice/exceptions/Test.ice | 2 +- cpp/test/Ice/exceptions/TestAMD.ice | 2 +- cpp/test/Ice/exceptions/TestAMDI.cpp | 46 +- cpp/test/Ice/exceptions/TestAMDI.h | 34 +- cpp/test/Ice/exceptions/TestI.cpp | 12 +- cpp/test/Ice/facets/AllTests.cpp | 12 +- cpp/test/Ice/facets/Client.cpp | 26 +- cpp/test/Ice/facets/Collocated.cpp | 26 +- cpp/test/Ice/facets/Server.cpp | 26 +- cpp/test/Ice/faultTolerance/AllTests.cpp | 328 +- cpp/test/Ice/faultTolerance/Client.cpp | 66 +- cpp/test/Ice/faultTolerance/Server.cpp | 72 +- cpp/test/Ice/gc/Client.cpp | 634 +- cpp/test/Ice/gc/Test.ice | 54 +- cpp/test/Ice/hold/AllTests.cpp | 2 +- cpp/test/Ice/hold/Client.cpp | 26 +- cpp/test/Ice/hold/Server.cpp | 26 +- cpp/test/Ice/hold/TestI.cpp | 6 +- cpp/test/Ice/inheritance/Client.cpp | 26 +- cpp/test/Ice/inheritance/Collocated.cpp | 26 +- cpp/test/Ice/inheritance/Server.cpp | 26 +- cpp/test/Ice/inheritance/TestI.h | 2 +- cpp/test/Ice/location/AllTests.cpp | 120 +- cpp/test/Ice/location/Client.cpp | 30 +- cpp/test/Ice/location/Server.cpp | 34 +- cpp/test/Ice/location/ServerLocator.cpp | 14 +- cpp/test/Ice/location/ServerLocator.h | 12 +- cpp/test/Ice/location/TestI.cpp | 20 +- cpp/test/Ice/location/TestI.h | 2 +- cpp/test/Ice/objects/AllTests.cpp | 52 +- cpp/test/Ice/objects/Client.cpp | 56 +- cpp/test/Ice/objects/Collocated.cpp | 26 +- cpp/test/Ice/objects/Server.cpp | 26 +- cpp/test/Ice/objects/TestI.cpp | 2 +- cpp/test/Ice/operations/AllTests.cpp | 44 +- cpp/test/Ice/operations/BatchOneways.cpp | 36 +- cpp/test/Ice/operations/Client.cpp | 68 +- cpp/test/Ice/operations/Collocated.cpp | 30 +- cpp/test/Ice/operations/Server.cpp | 32 +- cpp/test/Ice/operations/ServerAMD.cpp | 32 +- cpp/test/Ice/operations/Test.ice | 44 +- cpp/test/Ice/operations/TestAMD.ice | 44 +- cpp/test/Ice/operations/TestAMDI.cpp | 168 +- cpp/test/Ice/operations/TestAMDI.h | 110 +- cpp/test/Ice/operations/TestI.cpp | 168 +- cpp/test/Ice/operations/TestI.h | 152 +- cpp/test/Ice/operations/Twoways.cpp | 1252 ++-- cpp/test/Ice/operations/TwowaysAMI.cpp | 1474 ++--- cpp/test/Ice/retry/AllTests.cpp | 46 +- cpp/test/Ice/retry/Client.cpp | 44 +- cpp/test/Ice/retry/Server.cpp | 26 +- cpp/test/Ice/retry/TestI.cpp | 2 +- cpp/test/Ice/servantLocator/AllTests.cpp | 94 +- cpp/test/Ice/servantLocator/Collocated.cpp | 12 +- cpp/test/Ice/servantLocator/ServantLocatorI.cpp | 26 +- cpp/test/Ice/servantLocator/Server.cpp | 12 +- cpp/test/Ice/servantLocator/ServerAMD.cpp | 12 +- cpp/test/Ice/slicing/exceptions/AllTests.cpp | 914 +-- cpp/test/Ice/slicing/exceptions/Client.cpp | 26 +- cpp/test/Ice/slicing/exceptions/Server.cpp | 26 +- cpp/test/Ice/slicing/exceptions/ServerAMD.cpp | 26 +- cpp/test/Ice/slicing/exceptions/TestAMDI.cpp | 8 +- cpp/test/Ice/slicing/exceptions/TestAMDI.h | 32 +- cpp/test/Ice/slicing/objects/AllTests.cpp | 2418 ++++---- cpp/test/Ice/slicing/objects/Client.cpp | 26 +- cpp/test/Ice/slicing/objects/Server.cpp | 26 +- cpp/test/Ice/slicing/objects/ServerAMD.cpp | 26 +- cpp/test/Ice/slicing/objects/Test.ice | 4 +- cpp/test/Ice/slicing/objects/TestAMD.ice | 4 +- cpp/test/Ice/slicing/objects/TestAMDI.cpp | 34 +- cpp/test/Ice/slicing/objects/TestAMDI.h | 16 +- cpp/test/Ice/slicing/objects/TestI.cpp | 30 +- cpp/test/Ice/stream/Client.cpp | 4 +- cpp/test/Ice/timeout/AllTests.cpp | 462 +- cpp/test/Ice/timeout/Client.cpp | 52 +- cpp/test/Ice/timeout/Server.cpp | 38 +- cpp/test/Ice/timeout/TestI.cpp | 6 +- cpp/test/IceGrid/activation/AllTests.cpp | 844 +-- cpp/test/IceGrid/activation/Client.cpp | 26 +- cpp/test/IceGrid/activation/Server.cpp | 8 +- cpp/test/IceGrid/allocation/AllTests.cpp | 1868 +++--- cpp/test/IceGrid/allocation/Client.cpp | 30 +- .../IceGrid/allocation/PermissionsVerifier.cpp | 12 +- cpp/test/IceGrid/deployer/AllTests.cpp | 88 +- cpp/test/IceGrid/deployer/Client.cpp | 64 +- cpp/test/IceGrid/deployer/Service.cpp | 16 +- cpp/test/IceGrid/distribution/AllTests.cpp | 142 +- cpp/test/IceGrid/distribution/Client.cpp | 30 +- cpp/test/IceGrid/distribution/TestI.cpp | 4 +- cpp/test/IceGrid/distribution/run.py | 2 +- cpp/test/IceGrid/replicaGroup/AllTests.cpp | 798 +-- cpp/test/IceGrid/replicaGroup/Client.cpp | 26 +- cpp/test/IceGrid/replicaGroup/Service.cpp | 8 +- cpp/test/IceGrid/replication/AllTests.cpp | 1730 +++--- cpp/test/IceGrid/replication/Client.cpp | 28 +- cpp/test/IceGrid/session/AllTests.cpp | 3072 +++++----- cpp/test/IceGrid/session/Client.cpp | 34 +- cpp/test/IceGrid/session/PermissionsVerifier.cpp | 26 +- cpp/test/IceGrid/session/Server.cpp | 22 +- cpp/test/IceGrid/simple/AllTests.cpp | 42 +- cpp/test/IceGrid/simple/Client.cpp | 44 +- cpp/test/IceGrid/simple/Server.cpp | 2 +- cpp/test/IceGrid/simple/run.py | 2 +- cpp/test/IceGrid/update/AllTests.cpp | 2152 +++---- cpp/test/IceGrid/update/Client.cpp | 30 +- cpp/test/IceGrid/update/run.py | 2 +- cpp/test/IceSSL/configuration/AllTests.cpp | 2446 ++++---- cpp/test/IceSSL/configuration/Client.cpp | 30 +- cpp/test/IceSSL/configuration/Server.cpp | 26 +- cpp/test/IceSSL/configuration/TestI.cpp | 28 +- cpp/test/IceStorm/federation/Publisher.cpp | 70 +- cpp/test/IceStorm/federation/Subscriber.cpp | 110 +- cpp/test/IceStorm/federation/run.py | 4 +- cpp/test/IceStorm/federation2/Publisher.cpp | 44 +- cpp/test/IceStorm/federation2/Subscriber.cpp | 102 +- cpp/test/IceStorm/federation2/run.py | 92 +- cpp/test/IceStorm/single/Publisher.cpp | 46 +- cpp/test/IceStorm/single/Subscriber.cpp | 238 +- cpp/test/IceStorm/stress/Publisher.cpp | 70 +- cpp/test/IceStorm/stress/Subscriber.cpp | 306 +- cpp/test/IceStorm/stress/run.py | 90 +- cpp/test/IceUtil/ctrlCHandler/Client.cpp | 14 +- cpp/test/IceUtil/inputUtil/Client.cpp | 16 +- cpp/test/IceUtil/thread/AliveTest.cpp | 36 +- cpp/test/IceUtil/thread/Client.cpp | 14 +- cpp/test/IceUtil/thread/CountDownLatchTest.cpp | 72 +- cpp/test/IceUtil/thread/CreateTest.cpp | 24 +- cpp/test/IceUtil/thread/MonitorMutexTest.cpp | 102 +- cpp/test/IceUtil/thread/MonitorRecMutexTest.cpp | 94 +- cpp/test/IceUtil/thread/MutexTest.cpp | 172 +- cpp/test/IceUtil/thread/RWRecMutexTest.cpp | 954 +-- cpp/test/IceUtil/thread/RecMutexTest.cpp | 68 +- cpp/test/IceUtil/thread/StartTest.cpp | 16 +- cpp/test/IceUtil/thread/StaticMutexTest.cpp | 148 +- cpp/test/IceUtil/thread/TestBase.cpp | 6 +- cpp/test/IceUtil/unicode/Client.cpp | 214 +- cpp/test/IceUtil/uuid/Client.cpp | 122 +- cpp/test/Slice/errorDetection/CaseInsensitive.ice | 4 +- cpp/test/Slice/errorDetection/ChangedMeaning.ice | 56 +- cpp/test/Slice/errorDetection/ConstDef.ice | 60 +- .../Slice/errorDetection/DerivedRedefinition.ice | 16 +- cpp/test/Slice/errorDetection/IdentAsKeyword.ice | 14 +- .../Slice/errorDetection/IllegalDictionary.ice | 40 +- cpp/test/Slice/errorDetection/IllegalLocal.ice | 38 +- cpp/test/Slice/errorDetection/IllegalMI.ice | 44 +- cpp/test/Slice/errorDetection/Reserved.ice | 2 +- cpp/test/Slice/errorDetection/SelfContainment.ice | 4 +- cpp/test/Slice/errorDetection/StructMembers.ice | 26 +- cpp/test/Slice/errorDetection/run.py | 4 +- 658 files changed, 86389 insertions(+), 86389 deletions(-) (limited to 'cpp') diff --git a/cpp/RPMTools.py b/cpp/RPMTools.py index 06eb1c1ff98..698390914d0 100644 --- a/cpp/RPMTools.py +++ b/cpp/RPMTools.py @@ -44,51 +44,51 @@ class Package: self.group = group self.description = description self.filelist = filelist - self.other = other - self.prepTextGen = [] - self.buildTextGen = [] - self.installTextGen = [] + self.other = other + self.prepTextGen = [] + self.buildTextGen = [] + self.installTextGen = [] def writeHdr(self, ofile, version, release, installDir, targetHost): - ofile.write('%define _unpackaged_files_terminate_build 0\n') - ofile.write('\n%define core_arches %{ix86} x86_64\n') - ofile.write('Summary: ' + self.summary + '\n') - ofile.write('Name: ' + self.name + '\n') - ofile.write('Version: ' + version + '\n') - ofile.write('Release: ' + release + '\n') - if len(self.requires) != 0: + ofile.write('%define _unpackaged_files_terminate_build 0\n') + ofile.write('\n%define core_arches %{ix86} x86_64\n') + ofile.write('Summary: ' + self.summary + '\n') + ofile.write('Name: ' + self.name + '\n') + ofile.write('Version: ' + version + '\n') + ofile.write('Release: ' + release + '\n') + if len(self.requires) != 0: if self.requires.find('%version%'): self.requires = self.requires.replace('%version%', version) - ofile.write('Requires: ' + self.requires + '\n') - ofile.write('License: GPL\n') - ofile.write('Group:' + self.group + '\n') - ofile.write('Vendor: ZeroC, Inc\n') - ofile.write('URL: http://www.zeroc.com/\n') - - # - # major.minor is part of the URL, this needs to be parameterized. - # + ofile.write('Requires: ' + self.requires + '\n') + ofile.write('License: GPL\n') + ofile.write('Group:' + self.group + '\n') + ofile.write('Vendor: ZeroC, Inc\n') + ofile.write('URL: http://www.zeroc.com/\n') + + # + # major.minor is part of the URL, this needs to be parameterized. + # minorVer = version[0:3] - ofile.write('Source0: http://www.zeroc.com/download/Ice/' + minorVer + '/Ice-%{version}.tar.gz\n') - ofile.write('Source1: http://www.zeroc.com/download/Ice/' + minorVer + '/IceJ-%{version}-java2.tar.gz\n') - ofile.write('Source2: http://www.zeroc.com/download/Ice/' + minorVer + '/IcePy-%{version}.tar.gz\n') - ofile.write('Source3: http://www.zeroc.com/download/Ice/' + minorVer + '/IceCS-%{version}.tar.gz\n') - ofile.write('Source4: http://www.zeroc.com/download/Ice/' + minorVer + '/IceJ-%{version}-java5.tar.gz\n') - ofile.write('Source5: http://www.zeroc.com/download/Ice/' + minorVer + '/IcePHP-%{version}.tar.gz\n') + ofile.write('Source0: http://www.zeroc.com/download/Ice/' + minorVer + '/Ice-%{version}.tar.gz\n') + ofile.write('Source1: http://www.zeroc.com/download/Ice/' + minorVer + '/IceJ-%{version}-java2.tar.gz\n') + ofile.write('Source2: http://www.zeroc.com/download/Ice/' + minorVer + '/IcePy-%{version}.tar.gz\n') + ofile.write('Source3: http://www.zeroc.com/download/Ice/' + minorVer + '/IceCS-%{version}.tar.gz\n') + ofile.write('Source4: http://www.zeroc.com/download/Ice/' + minorVer + '/IceJ-%{version}-java5.tar.gz\n') + ofile.write('Source5: http://www.zeroc.com/download/Ice/' + minorVer + '/IcePHP-%{version}.tar.gz\n') ofile.write('Source6: http://www.zeroc.com/download/Ice/' + minorVer + '/THIRD_PARTY_LICENSE\n') - ofile.write('Source7: http://www.zeroc.com/download/Ice/' + minorVer + '/ice.ini\n') - ofile.write('Source8: http://www.zeroc.com/download/Ice/' + minorVer + '/README.Linux-RPM\n') + ofile.write('Source7: http://www.zeroc.com/download/Ice/' + minorVer + '/ice.ini\n') + ofile.write('Source8: http://www.zeroc.com/download/Ice/' + minorVer + '/README.Linux-RPM\n') ofile.write('Source9: http://www.zeroc.com/download/Ice/' + minorVer + '/SOURCES\n') - if targetHost != "suse": - ofile.write('Source10: http://www.zeroc.com/download/Ice/' + minorVer + '/IceRuby-%{version}.tar.gz\n') - - ofile.write('\n') - if len(installDir) != 0: - ofile.write('BuildRoot: ' + installDir + '\n') - else: - ofile.write('BuildRoot: /var/tmp/Ice-' + version + '-' + release + '-buildroot\n') + if targetHost != "suse": + ofile.write('Source10: http://www.zeroc.com/download/Ice/' + minorVer + '/IceRuby-%{version}.tar.gz\n') + + ofile.write('\n') + if len(installDir) != 0: + ofile.write('BuildRoot: ' + installDir + '\n') + else: + ofile.write('BuildRoot: /var/tmp/Ice-' + version + '-' + release + '-buildroot\n') ofile.write('\n') - ofile.write(''' + ofile.write(''' %ifarch x86_64 %define icelibdir lib64 %else @@ -99,109 +99,109 @@ class Package: ''') ofile.write('BuildRequires: mono-core >= 1.2.2\n') - ofile.write('\n%endif\n') + ofile.write('\n%endif\n') - buildRequiresList = ['python >= 2.3.4', 'python-devel >= 2.3.4', - 'expat >= 0.5.0', 'libstdc++ >= 3.2', 'gcc >= 3.2', 'gcc-c++ >= 3.2', 'tar', - 'binutils >= 2.10', 'openssl >= 0.9.7a', 'openssl-devel >= 0.9.7a', 'ncurses >= 5.4'] + buildRequiresList = ['python >= 2.3.4', 'python-devel >= 2.3.4', + 'expat >= 0.5.0', 'libstdc++ >= 3.2', 'gcc >= 3.2', 'gcc-c++ >= 3.2', 'tar', + 'binutils >= 2.10', 'openssl >= 0.9.7a', 'openssl-devel >= 0.9.7a', 'ncurses >= 5.4'] - if targetHost == "suse": - buildRequiresList.extend(['bzip >= 1.0.2', 'php5 >= 5.1.2', 'php5-devel >= 5.1.2']) - else: - buildRequiresList.extend(['bzip2-devel >= 1.0.2', 'bzip2-libs >= 1.0.2', 'db45 >= 4.5.20', - 'expat-devel >= 0.5.0', 'php >= 5.1.4', 'php-devel >= 5.1.4']) + if targetHost == "suse": + buildRequiresList.extend(['bzip >= 1.0.2', 'php5 >= 5.1.2', 'php5-devel >= 5.1.2']) + else: + buildRequiresList.extend(['bzip2-devel >= 1.0.2', 'bzip2-libs >= 1.0.2', 'db45 >= 4.5.20', + 'expat-devel >= 0.5.0', 'php >= 5.1.4', 'php-devel >= 5.1.4']) - for f in buildRequiresList: + for f in buildRequiresList: ofile.write('BuildRequires: ' + f + '\n') - ofile.write('\n') - - ofile.write('Provides: %s-%%{_arch}\n' % self.name) - ofile.write('%description\n') - ofile.write(self.description) - ofile.write('\n') - ofile.write('%prep\n') - for g in self.prepTextGen: - g(ofile, version, targetHost) - ofile.write('\n') - ofile.write('%build\n') - for g in self.buildTextGen: - g(ofile, version, targetHost) - ofile.write('\n') - ofile.write('%install\n') - for g in self.installTextGen: - g(ofile, version, targetHost) - ofile.write('\n') - ofile.write('%clean\n') - ofile.write('\n') - ofile.write('%changelog\n') - ofile.write('* Fri Dec 6 2006 ZeroC Staff\n') - ofile.write('- See source distributions or the ZeroC website for more information\n') - ofile.write(' about the changes in this release\n') - ofile.write('\n') + ofile.write('\n') + + ofile.write('Provides: %s-%%{_arch}\n' % self.name) + ofile.write('%description\n') + ofile.write(self.description) + ofile.write('\n') + ofile.write('%prep\n') + for g in self.prepTextGen: + g(ofile, version, targetHost) + ofile.write('\n') + ofile.write('%build\n') + for g in self.buildTextGen: + g(ofile, version, targetHost) + ofile.write('\n') + ofile.write('%install\n') + for g in self.installTextGen: + g(ofile, version, targetHost) + ofile.write('\n') + ofile.write('%clean\n') + ofile.write('\n') + ofile.write('%changelog\n') + ofile.write('* Fri Dec 6 2006 ZeroC Staff\n') + ofile.write('- See source distributions or the ZeroC website for more information\n') + ofile.write(' about the changes in this release\n') + ofile.write('\n') def writeFileList(self, ofile, version, intVersion, installDir): ofile.write('%defattr(644, root, root, 755)\n\n') for perm, f in self.filelist: prefix = '' - - # - # Select an RPM spec file attribute depending on the type of - # file or directory we've specified. - # + + # + # Select an RPM spec file attribute depending on the type of + # file or directory we've specified. + # if perm == 'exe' or perm == 'lib': prefix = '%attr(755, root, root) ' - elif perm == 'cfg': - prefix = '%config' - elif perm == 'xdir': - prefix = '%dir ' + elif perm == 'cfg': + prefix = '%config' + elif perm == 'xdir': + prefix = '%dir ' if f.find('%version%'): f = f.replace('%version%', version) if perm == 'lib' and f.endswith('.VERSION'): - fname = os.path.splitext(f)[0] + fname = os.path.splitext(f)[0] ofile.write(prefix + '/usr/' + fname + '.' + version + '\n') ofile.write(prefix + '/usr/' + fname + '.' + str(intVersion) + '\n') - elif perm == 'cfg': - ofile.write(f + '\n') - else: - ofile.write(prefix + '/usr/' + f + '\n') + elif perm == 'cfg': + ofile.write(f + '\n') + else: + ofile.write(prefix + '/usr/' + f + '\n') ofile.write('\n') def writePostInstall(self, ofile, version, intVersion, installDir): - pass + pass def writePostUninstall(self, ofile, version, intVersion, installDir): - pass + pass def writeFilesImpl(self, ofile, version, intVersion, installDir): ofile.write('%files\n') self.writeFileList(ofile, version, intVersion, installDir) - ofile.write('\n') + ofile.write('\n') - ofile.write('%post\n') - self.writePostInstall(ofile, version, intVersion, installDir) + ofile.write('%post\n') + self.writePostInstall(ofile, version, intVersion, installDir) - ofile.write('%postun\n') - self.writePostUninstall(ofile, version, intVersion, installDir) - ofile.write('\n') + ofile.write('%postun\n') + self.writePostUninstall(ofile, version, intVersion, installDir) + ofile.write('\n') def writeFiles(self, ofile, version, intVersion, installDir): - ofile.write('\n%ifarch %{core_arches}\n') - self.writeFilesImpl(ofile, version, intVersion, installDir) - ofile.write('\n%else\n') - ofile.write('%files\n') - ofile.write('\n%endif\n') + ofile.write('\n%ifarch %{core_arches}\n') + self.writeFilesImpl(ofile, version, intVersion, installDir) + ofile.write('\n%else\n') + ofile.write('%files\n') + ofile.write('\n%endif\n') def addPrepGenerator(self, gen): - self.prepTextGen.append(gen) + self.prepTextGen.append(gen) def addBuildGenerator(self, gen): - self.buildTextGen.append(gen) + self.buildTextGen.append(gen) def addInstallGenerator(self, gen): - self.installTextGen.append(gen) + self.installTextGen.append(gen) # # Represents subpackages in an RPM spec file. @@ -211,67 +211,67 @@ class Subpackage(Package): def writeFilesImpl(self, ofile, version, intVersion, installDir): ofile.write('%%files %s\n' % self.name) self.writeFileList(ofile, version, intVersion, installDir) - ofile.write('\n') + ofile.write('\n') - ofile.write('%%post %s\n' % self.name) - self.writePostInstall(ofile, version, intVersion, installDir) + ofile.write('%%post %s\n' % self.name) + self.writePostInstall(ofile, version, intVersion, installDir) - ofile.write('%%postun %s\n' % self.name) - self.writePostUninstall(ofile, version, intVersion, installDir) - ofile.write('\n') + ofile.write('%%postun %s\n' % self.name) + self.writePostUninstall(ofile, version, intVersion, installDir) + ofile.write('\n') def writeFiles(self, ofile, version, intVersion, installDir): - ofile.write('\n%ifarch %{core_arches}\n') - self.writeFilesImpl(ofile, version, intVersion, installDir) - ofile.write('\n%endif\n') + ofile.write('\n%ifarch %{core_arches}\n') + self.writeFilesImpl(ofile, version, intVersion, installDir) + ofile.write('\n%endif\n') def writeSubpackageHeader(self, ofile, version, release, installDir): ofile.write('%package ' + self.name + '\n') ofile.write('Summary: ' + self.summary + '\n') ofile.write('Group: ' + self.group + '\n') - if len(self.requires) != 0: + if len(self.requires) != 0: if self.requires.find('%version%'): self.requires = self.requires.replace('%version%', version) - ofile.write('Requires: ' + self.requires + '\n') - if len(self.other) != 0: - ofile.write(self.other + '\n') + ofile.write('Requires: ' + self.requires + '\n') + if len(self.other) != 0: + ofile.write(self.other + '\n') ofile.write('%description ' + self.name + '\n') ofile.write(self.description) def writeHdr(self, ofile, version, release, installDir, targetHost): - ofile.write('\n%ifarch %{core_arches}\n') - self.writeSubpackageHeader(ofile, version, release, installDir) - ofile.write('\n%endif\n') + ofile.write('\n%ifarch %{core_arches}\n') + self.writeSubpackageHeader(ofile, version, release, installDir) + ofile.write('\n%endif\n') class NoarchSubpackage(Subpackage): def writeHdr(self, ofile, version, release, installDir, targetHost): - ofile.write('\n%ifarch noarch\n') - self.writeSubpackageHeader(ofile, version, release, installDir) - ofile.write('\n%endif\n') + ofile.write('\n%ifarch noarch\n') + self.writeSubpackageHeader(ofile, version, release, installDir) + ofile.write('\n%endif\n') def writeFiles(self, ofile, version, intVersion, installDir): - ofile.write('\n%ifarch noarch\n') - self.writeFilesImpl(ofile, version, intVersion, installDir) - ofile.write('\n%endif\n') + ofile.write('\n%ifarch noarch\n') + self.writeFilesImpl(ofile, version, intVersion, installDir) + ofile.write('\n%endif\n') class DotNetPackage(Subpackage): def writePostInstall(self, ofile, version, intVersion, installDir): - ofile.write('\n%ifnarch noarch\n') - ofile.write(''' + ofile.write('\n%ifnarch noarch\n') + ofile.write(''' pklibdir="%{icelibdir}" for f in icecs glacier2cs iceboxcs icegridcs icepatch2cs icestormcs; do sed -i.bak -e "s/^mono_root.*$/mono_root = \/usr/" /usr/$pklibdir/pkgconfig/$f.pc ; done - ''') - ofile.write('\n%endif\n') + ''') + ofile.write('\n%endif\n') class DotNetPackage(Subpackage): def writePostInstall(self, ofile, version, intVersion, installDir): - ofile.write('\n%ifnarch noarch\n') - ofile.write(''' + ofile.write('\n%ifnarch noarch\n') + ofile.write(''' pklibdir="lib" %ifarch x86_64 @@ -282,37 +282,37 @@ for f in icecs glacier2cs iceboxcs icegridcs icepatch2cs icestormcs; do sed -i.bak -e "s/^mono_root.*$/mono_root = \/usr/" /usr/$pklibdir/pkgconfig/$f.pc ; done - ''') - ofile.write('\n%endif\n') + ''') + ofile.write('\n%endif\n') # # NOTE: File transforms should be listed before directory transforms. # transforms = [ ('file', 'ice.ini', 'etc/php.d/ice.ini'), - ('dir', 'lib', 'usr/lib'), - ('dir', '%{icelibdir}', 'usr/%{icelibdir}'), - ('file', 'usr/%{icelibdir}/IcePHP.so', 'usr/%{icelibdir}/php/modules/IcePHP.so'), - ('file', 'usr/lib/Ice.jar', 'usr/lib/Ice-%version%/Ice.jar' ), - ('dir', 'usr/lib/java2', 'usr/lib/Ice-%version%/java2' ), - ('file', 'usr/lib/IceGridGUI.jar', 'usr/lib/Ice-%version%/IceGridGUI.jar' ), - ('file', 'bin/icecs.dll', 'usr/lib/mono/gac/icecs/%version%.0__1f998c50fec78381/icecs.dll'), - ('file', 'bin/glacier2cs.dll', - 'usr/lib/mono/gac/glacier2cs/%version%.0__1f998c50fec78381/glacier2cs.dll'), - ('file', 'bin/iceboxcs.dll', - 'usr/lib/mono/gac/iceboxcs/%version%.0__1f998c50fec78381/iceboxcs.dll'), - ('file', 'bin/icegridcs.dll', - 'usr/lib/mono/gac/icegridcs/%version%.0__1f998c50fec78381/icegridcs.dll'), - ('file', 'bin/icepatch2cs.dll', - 'usr/lib/mono/gac/icepatch2cs/%version%.0__1f998c50fec78381/icepatch2cs.dll'), - ('file', 'bin/icestormcs.dll', - 'usr/lib/mono/gac/icestormcs/%version%.0__1f998c50fec78381/icestormcs.dll'), - ('dir', 'ant', 'usr/lib/Ice-%version%/ant'), - ('dir', 'config', 'usr/share/Ice-%version%'), - ('dir', 'slice', 'usr/share/slice'), - ('dir', 'bin', 'usr/bin'), - ('dir', 'include', 'usr/include'), - ('dir', 'python', 'usr/%{icelibdir}/Ice-%version%/python'), - ('dir', 'ruby', 'usr/%{icelibdir}/Ice-%version%/ruby'), + ('dir', 'lib', 'usr/lib'), + ('dir', '%{icelibdir}', 'usr/%{icelibdir}'), + ('file', 'usr/%{icelibdir}/IcePHP.so', 'usr/%{icelibdir}/php/modules/IcePHP.so'), + ('file', 'usr/lib/Ice.jar', 'usr/lib/Ice-%version%/Ice.jar' ), + ('dir', 'usr/lib/java2', 'usr/lib/Ice-%version%/java2' ), + ('file', 'usr/lib/IceGridGUI.jar', 'usr/lib/Ice-%version%/IceGridGUI.jar' ), + ('file', 'bin/icecs.dll', 'usr/lib/mono/gac/icecs/%version%.0__1f998c50fec78381/icecs.dll'), + ('file', 'bin/glacier2cs.dll', + 'usr/lib/mono/gac/glacier2cs/%version%.0__1f998c50fec78381/glacier2cs.dll'), + ('file', 'bin/iceboxcs.dll', + 'usr/lib/mono/gac/iceboxcs/%version%.0__1f998c50fec78381/iceboxcs.dll'), + ('file', 'bin/icegridcs.dll', + 'usr/lib/mono/gac/icegridcs/%version%.0__1f998c50fec78381/icegridcs.dll'), + ('file', 'bin/icepatch2cs.dll', + 'usr/lib/mono/gac/icepatch2cs/%version%.0__1f998c50fec78381/icepatch2cs.dll'), + ('file', 'bin/icestormcs.dll', + 'usr/lib/mono/gac/icestormcs/%version%.0__1f998c50fec78381/icestormcs.dll'), + ('dir', 'ant', 'usr/lib/Ice-%version%/ant'), + ('dir', 'config', 'usr/share/Ice-%version%'), + ('dir', 'slice', 'usr/share/slice'), + ('dir', 'bin', 'usr/bin'), + ('dir', 'include', 'usr/include'), + ('dir', 'python', 'usr/%{icelibdir}/Ice-%version%/python'), + ('dir', 'ruby', 'usr/%{icelibdir}/Ice-%version%/ruby'), ('dir', 'doc', 'usr/share/doc/Ice-%version%/doc'), ('file', 'README', 'usr/share/doc/Ice-%version%/README'), ('file', 'ICE_LICENSE', 'usr/share/doc/Ice-%version%/ICE_LICENSE'), @@ -324,10 +324,10 @@ transforms = [ ('file', 'ice.ini', 'etc/php.d/ice.ini'), fileLists = [ Package('ice', '', - 'The Ice base runtime and services', + 'The Ice base runtime and services', 'System Environment/Libraries', - iceDescription, - 'Provides: ice-%{_arch}', + iceDescription, + 'Provides: ice-%{_arch}', [('xdir', 'share/doc/Ice-%version%'), ('doc', 'share/doc/Ice-%version%/ICE_LICENSE'), ('doc', 'share/doc/Ice-%version%/LICENSE'), @@ -363,121 +363,121 @@ fileLists = [ ('lib', '%{icelibdir}/libSlice.so.VERSION'), ('lib', '%{icelibdir}/libIceGrid.so.VERSION'), ('xdir', 'lib/Ice-%version%'), - ('file', 'lib/Ice-%version%/IceGridGUI.jar'), + ('file', 'lib/Ice-%version%/IceGridGUI.jar'), ('dir', 'share/slice'), ('dir', 'share/doc/Ice-%version%/doc'), - ('xdir', 'share/Ice-%version%'), - ('file', 'share/Ice-%version%/templates.xml'), - ('exe', 'share/Ice-%version%/convertssl.py'), + ('xdir', 'share/Ice-%version%'), + ('file', 'share/Ice-%version%/templates.xml'), + ('exe', 'share/Ice-%version%/convertssl.py'), ('exe', 'share/Ice-%version%/upgradeicegrid.py'), ('file', 'share/Ice-%version%/icegrid-slice.3.1.ice.gz')]), Subpackage('c++-devel', 'ice = %version%', 'Tools for developing Ice applications in C++', 'Development/Tools', - iceDescription, - 'Requires: ice-%{_arch}', + iceDescription, + 'Requires: ice-%{_arch}', [('exe', 'bin/slice2cpp'), ('exe', 'bin/slice2freeze'), ('dir', 'include'), - ('lib', '%{icelibdir}/libFreeze.so'), - ('lib', '%{icelibdir}/libGlacier2.so'), - ('lib', '%{icelibdir}/libIceBox.so'), - ('lib', '%{icelibdir}/libIceGrid.so'), - ('lib', '%{icelibdir}/libIcePatch2.so'), - ('lib', '%{icelibdir}/libIce.so'), - ('lib', '%{icelibdir}/libIceSSL.so'), - ('lib', '%{icelibdir}/libIceStormService.so'), - ('lib', '%{icelibdir}/libIceStorm.so'), - ('lib', '%{icelibdir}/libIceUtil.so'), - ('lib', '%{icelibdir}/libIceXML.so'), - ('lib', '%{icelibdir}/libSlice.so') - ]), + ('lib', '%{icelibdir}/libFreeze.so'), + ('lib', '%{icelibdir}/libGlacier2.so'), + ('lib', '%{icelibdir}/libIceBox.so'), + ('lib', '%{icelibdir}/libIceGrid.so'), + ('lib', '%{icelibdir}/libIcePatch2.so'), + ('lib', '%{icelibdir}/libIce.so'), + ('lib', '%{icelibdir}/libIceSSL.so'), + ('lib', '%{icelibdir}/libIceStormService.so'), + ('lib', '%{icelibdir}/libIceStorm.so'), + ('lib', '%{icelibdir}/libIceUtil.so'), + ('lib', '%{icelibdir}/libIceXML.so'), + ('lib', '%{icelibdir}/libSlice.so') + ]), DotNetPackage('csharp-devel', - 'ice-dotnet = %version%', - 'Tools for developing Ice applications in C#', - 'Development/Tools', - iceDescription, - 'Requires: ice-%{_arch}', - [('exe', 'bin/slice2cs'), - ('xdir', 'share/doc/Ice-%version%'), - ('file', '%{icelibdir}/pkgconfig/icecs.pc'), - ('file', '%{icelibdir}/pkgconfig/glacier2cs.pc'), - ('file', '%{icelibdir}/pkgconfig/iceboxcs.pc'), - ('file', '%{icelibdir}/pkgconfig/icegridcs.pc'), - ('file', '%{icelibdir}/pkgconfig/icepatch2cs.pc'), - ('file', '%{icelibdir}/pkgconfig/icestormcs.pc')]), + 'ice-dotnet = %version%', + 'Tools for developing Ice applications in C#', + 'Development/Tools', + iceDescription, + 'Requires: ice-%{_arch}', + [('exe', 'bin/slice2cs'), + ('xdir', 'share/doc/Ice-%version%'), + ('file', '%{icelibdir}/pkgconfig/icecs.pc'), + ('file', '%{icelibdir}/pkgconfig/glacier2cs.pc'), + ('file', '%{icelibdir}/pkgconfig/iceboxcs.pc'), + ('file', '%{icelibdir}/pkgconfig/icegridcs.pc'), + ('file', '%{icelibdir}/pkgconfig/icepatch2cs.pc'), + ('file', '%{icelibdir}/pkgconfig/icestormcs.pc')]), Subpackage('java-devel', 'ice-java = %version%', 'Tools for developing Ice applications in Java', 'Development/Tools', - iceDescription, - 'Requires: ice-%{_arch}', + iceDescription, + 'Requires: ice-%{_arch}', [('exe', 'bin/slice2java'), ('exe', 'bin/slice2freezej'), - ('xdir', 'lib/Ice-%version%'), - ('dir', 'lib/Ice-%version%/ant'), ]), + ('xdir', 'lib/Ice-%version%'), + ('dir', 'lib/Ice-%version%/ant'), ]), Subpackage('python', 'ice = %version%, python >= 2.3.4', 'The Ice runtime for Python applications', 'System Environment/Libraries', - iceDescription, - 'Requires: ice-%{_arch}', + iceDescription, + 'Requires: ice-%{_arch}', [('dir', '%{icelibdir}/Ice-%version%/python')]), Subpackage('python-devel', 'ice-python = %version%', 'Tools for developing Ice applications in Python', 'Development/Tools', - iceDescription, - 'Requires: ice-%{_arch}', + iceDescription, + 'Requires: ice-%{_arch}', [('exe', 'bin/slice2py')]), Subpackage('ruby', 'ice = %version%, ruby >= 1.8.1', 'The Ice runtime for Ruby applications', 'System Environment/Libraries', - iceDescription, - 'Requires: ice-%{_arch}', + iceDescription, + 'Requires: ice-%{_arch}', [('dir', '%{icelibdir}/Ice-%version%/ruby')]), Subpackage('ruby-devel', 'ice-ruby = %version%', 'Tools for developing Ice applications in Python', 'Development/Tools', - iceDescription, - 'Requires: ice-%{_arch}', + iceDescription, + 'Requires: ice-%{_arch}', [('exe', 'bin/slice2rb')]), Subpackage('php', - 'ice = %version%, php >= 5.1.2', - 'The Ice runtime for PHP applications', - 'System Environment/Libraries', - iceDescription, - 'Requires: ice-%{_arch}', - [('lib', '%{icelibdir}/php/modules'), ('cfg', '/etc/php.d/ice.ini')] - ), + 'ice = %version%, php >= 5.1.2', + 'The Ice runtime for PHP applications', + 'System Environment/Libraries', + iceDescription, + 'Requires: ice-%{_arch}', + [('lib', '%{icelibdir}/php/modules'), ('cfg', '/etc/php.d/ice.ini')] + ), NoarchSubpackage('java', - 'ice = %version%, db45-java >= 4.5.20', - 'The Ice runtime for Java', - 'System Environment/Libraries', - iceDescription, - '', - [ ('xdir', 'lib/Ice-%version%'), - ('file', 'lib/Ice-%version%/Ice.jar'), + 'ice = %version%, db45-java >= 4.5.20', + 'The Ice runtime for Java', + 'System Environment/Libraries', + iceDescription, + '', + [ ('xdir', 'lib/Ice-%version%'), + ('file', 'lib/Ice-%version%/Ice.jar'), ('xdir', 'lib/Ice-%version%/java2'), - ('file', 'lib/Ice-%version%/java2/Ice.jar') - ]), + ('file', 'lib/Ice-%version%/java2/Ice.jar') + ]), NoarchSubpackage('dotnet', 'ice = %version%, mono-core >= 1.2.2', - 'The Ice runtime for C# applications', - 'System Environment/Libraries', - iceDescription, - '', - [('dll', 'lib/mono/gac/glacier2cs/%version%.0__1f998c50fec78381/glacier2cs.dll'), - ('dll', 'lib/mono/gac/icecs/%version%.0__1f998c50fec78381/icecs.dll'), - ('dll', 'lib/mono/gac/iceboxcs/%version%.0__1f998c50fec78381/iceboxcs.dll'), - ('dll', 'lib/mono/gac/icegridcs/%version%.0__1f998c50fec78381/icegridcs.dll'), - ('dll', 'lib/mono/gac/icepatch2cs/%version%.0__1f998c50fec78381/icepatch2cs.dll'), - ('dll', 'lib/mono/gac/icestormcs/%version%.0__1f998c50fec78381/icestormcs.dll'), - ('exe', 'bin/iceboxnet.exe'), - ('exe', 'bin/iceboxadminnet.exe')]) + 'The Ice runtime for C# applications', + 'System Environment/Libraries', + iceDescription, + '', + [('dll', 'lib/mono/gac/glacier2cs/%version%.0__1f998c50fec78381/glacier2cs.dll'), + ('dll', 'lib/mono/gac/icecs/%version%.0__1f998c50fec78381/icecs.dll'), + ('dll', 'lib/mono/gac/iceboxcs/%version%.0__1f998c50fec78381/iceboxcs.dll'), + ('dll', 'lib/mono/gac/icegridcs/%version%.0__1f998c50fec78381/icegridcs.dll'), + ('dll', 'lib/mono/gac/icepatch2cs/%version%.0__1f998c50fec78381/icepatch2cs.dll'), + ('dll', 'lib/mono/gac/icestormcs/%version%.0__1f998c50fec78381/icestormcs.dll'), + ('exe', 'bin/iceboxnet.exe'), + ('exe', 'bin/iceboxadminnet.exe')]) ] ############################################################################ @@ -494,51 +494,51 @@ def _transformDirectories(transforms, version, installDir): cwd = os.getcwd() os.chdir(installDir) for type, source, dest in transforms: - dest = dest.replace('%version%', version) - source = source.replace('%version%', version) + dest = dest.replace('%version%', version) + source = source.replace('%version%', version) - libdir = 'lib' # Key on architecture. - dest = dest.replace('%{icelibdir}', libdir) - source = source.replace('%{icelibdir}', libdir) + libdir = 'lib' # Key on architecture. + dest = dest.replace('%{icelibdir}', libdir) + source = source.replace('%{icelibdir}', libdir) sourcedir = source destdir = dest - if os.path.exists('./tmp'): - shutil.rmtree('./tmp') - - try: - if not os.path.isdir(sourcedir): - if os.path.exists(source): - os.renames(source, dest) - else: - # - # This is a special problem. What this implies is that - # we are trying to move the contents of a directory into - # a subdirectory of itself. The regular shutil.move() - # won't cut it. - # - if os.path.isdir(sourcedir) and sourcedir.split("/")[0] == destdir.split("/")[0]: - os.renames(sourcedir, "./tmp/" + sourcedir) - os.renames("./tmp/" + sourcedir, destdir) - else: - print 'Renaming ' + source + ' to ' + dest - if os.path.exists(source): - os.renames(source, dest) - - except OSError: - print "Exception occurred while trying to transform " + source + " to " + dest - raise + if os.path.exists('./tmp'): + shutil.rmtree('./tmp') + + try: + if not os.path.isdir(sourcedir): + if os.path.exists(source): + os.renames(source, dest) + else: + # + # This is a special problem. What this implies is that + # we are trying to move the contents of a directory into + # a subdirectory of itself. The regular shutil.move() + # won't cut it. + # + if os.path.isdir(sourcedir) and sourcedir.split("/")[0] == destdir.split("/")[0]: + os.renames(sourcedir, "./tmp/" + sourcedir) + os.renames("./tmp/" + sourcedir, destdir) + else: + print 'Renaming ' + source + ' to ' + dest + if os.path.exists(source): + os.renames(source, dest) + + except OSError: + print "Exception occurred while trying to transform " + source + " to " + dest + raise os.chdir(cwd) def createArchSpecFile(ofile, installDir, version, soVersion, targetHost): for v in fileLists: - v.writeHdr(ofile, version, "1", installDir, targetHost) - ofile.write("\n\n\n") + v.writeHdr(ofile, version, "1", installDir, targetHost) + ofile.write("\n\n\n") for v in fileLists: - v.writeFiles(ofile, version, soVersion, installDir) - ofile.write("\n") + v.writeFiles(ofile, version, soVersion, installDir) + ofile.write("\n") def createFullSpecFile(ofile, installDir, version, soVersion, targetHost): fullFileList = fileLists @@ -548,21 +548,21 @@ def createFullSpecFile(ofile, installDir, version, soVersion, targetHost): fullFileList[0].addInstallGenerator(writeTransformCommands) for v in fullFileList: - # - # Skip ruby on SuSE - # - if targetHost == "suse" and v.name.startswith("ruby"): - continue - v.writeHdr(ofile, version, "1", '', targetHost) - ofile.write("\n\n\n") + # + # Skip ruby on SuSE + # + if targetHost == "suse" and v.name.startswith("ruby"): + continue + v.writeHdr(ofile, version, "1", '', targetHost) + ofile.write("\n\n\n") for v in fullFileList: - # - # Skip ruby on SuSE - # - if targetHost == "suse" and v.name.startswith("ruby"): - continue - v.writeFiles(ofile, version, soVersion, '') - ofile.write("\n") + # + # Skip ruby on SuSE + # + if targetHost == "suse" and v.name.startswith("ruby"): + continue + v.writeFiles(ofile, version, soVersion, '') + ofile.write("\n") def writeUnpackingCommands(ofile, version, targetHost): ofile.write('%setup -n Ice-%{version} -q -T -D -b 0\n') @@ -585,7 +585,7 @@ cd $RPM_BUILD_DIR cp $RPM_SOURCE_DIR/ice.ini $RPM_BUILD_DIR/IcePHP-%{version} """) if targetHost != "suse": - ofile.write(""" + ofile.write(""" %setup -q -n IceRuby-%{version} -T -D -b 10 sed -i -e 's/^prefix.*$/prefix = $\(RPM_BUILD_ROOT\)/' $RPM_BUILD_DIR/IceRuby-%{version}/config/Make.rules @@ -622,10 +622,10 @@ cd $RPM_BUILD_DIR/IcePHP-%{version} gmake OPTIMIZE=yes ICE_HOME=$RPM_BUILD_DIR/Ice-%{version} RPM_BUILD_ROOT=$RPM_BUILD_ROOT embedded_runpath_prefix="" """) if targetHost != "suse": - ofile.write(""" + ofile.write(""" cd $RPM_BUILD_DIR/IceRuby-%{version} gmake OPTIMIZE=yes ICE_HOME=$RPM_BUILD_DIR/Ice-%{version} RPM_BUILD_ROOT=$RPM_BUILD_ROOT embedded_runpath_prefix="" - """) + """) def writeInstallCommands(ofile, version, targetHost): ofile.write(""" @@ -677,10 +677,10 @@ done """) if targetHost != "suse": - ofile.write(""" + ofile.write(""" cd $RPM_BUILD_DIR/IceRuby-%{version} gmake OPTIMIZE=yes ICE_HOME=$RPM_BUILD_DIR/Ice-%{version} RPM_BUILD_ROOT=$RPM_BUILD_ROOT embedded_runpath_prefix="" install - """) + """) def writeTransformCommands(ofile, version, targetHost): # @@ -693,31 +693,31 @@ def writeTransformCommands(ofile, version, targetHost): ofile.write('# Linux system.\n') ofile.write('#\n\n') for type, source, dest in transforms: - dest = dest.replace('%version%', version) - source = source.replace('%version%', version) - if type == 'file': - ofile.write('# Rule 1\n') - ofile.write('mkdir -p $RPM_BUILD_ROOT/' + os.path.dirname(dest) + '\n') - ofile.write('mv $RPM_BUILD_ROOT/' + source + ' $RPM_BUILD_ROOT/' + dest + '\n') - elif type == 'dir': - if os.path.dirname(dest) <> '' and source.split('/')[0] == dest.split('/')[0]: - ofile.write('# Rule 2\n') - ofile.write('mkdir -p $RPM_BUILD_ROOT/arraftmp\n') - ofile.write('mkdir -p $RPM_BUILD_ROOT/arraftmp/%s\n' % os.path.dirname(source)) - ofile.write('mv $RPM_BUILD_ROOT/' + source + ' $RPM_BUILD_ROOT/arraftmp/' + source + '\n') - ofile.write('mkdir -p $RPM_BUILD_ROOT/' + os.path.dirname(dest) + '\n') - ofile.write('mv $RPM_BUILD_ROOT/arraftmp/' + source + ' $RPM_BUILD_ROOT/' + dest + '\n') - ofile.write('rm -rf $RPM_BUILD_ROOT/arraftmp\n') - elif os.path.dirname(dest) <> '': - ofile.write('# Rule 3\n') - ofile.write('if test -d $RPM_BUILD_ROOT/' + source + '\n') - ofile.write('then\n') - ofile.write(' mkdir -p $RPM_BUILD_ROOT/' + os.path.dirname(dest) + '\n') - ofile.write(' mv $RPM_BUILD_ROOT/' + source + ' $RPM_BUILD_ROOT/' + dest + '\n') - ofile.write('fi\n') - else: - ofile.write('# Rule 4\n') - ofile.write('mv $RPM_BUILD_ROOT/usr/' + source + ' $RPM_BUILD_ROOT/usr/' + dest + '\n') - + dest = dest.replace('%version%', version) + source = source.replace('%version%', version) + if type == 'file': + ofile.write('# Rule 1\n') + ofile.write('mkdir -p $RPM_BUILD_ROOT/' + os.path.dirname(dest) + '\n') + ofile.write('mv $RPM_BUILD_ROOT/' + source + ' $RPM_BUILD_ROOT/' + dest + '\n') + elif type == 'dir': + if os.path.dirname(dest) <> '' and source.split('/')[0] == dest.split('/')[0]: + ofile.write('# Rule 2\n') + ofile.write('mkdir -p $RPM_BUILD_ROOT/arraftmp\n') + ofile.write('mkdir -p $RPM_BUILD_ROOT/arraftmp/%s\n' % os.path.dirname(source)) + ofile.write('mv $RPM_BUILD_ROOT/' + source + ' $RPM_BUILD_ROOT/arraftmp/' + source + '\n') + ofile.write('mkdir -p $RPM_BUILD_ROOT/' + os.path.dirname(dest) + '\n') + ofile.write('mv $RPM_BUILD_ROOT/arraftmp/' + source + ' $RPM_BUILD_ROOT/' + dest + '\n') + ofile.write('rm -rf $RPM_BUILD_ROOT/arraftmp\n') + elif os.path.dirname(dest) <> '': + ofile.write('# Rule 3\n') + ofile.write('if test -d $RPM_BUILD_ROOT/' + source + '\n') + ofile.write('then\n') + ofile.write(' mkdir -p $RPM_BUILD_ROOT/' + os.path.dirname(dest) + '\n') + ofile.write(' mv $RPM_BUILD_ROOT/' + source + ' $RPM_BUILD_ROOT/' + dest + '\n') + ofile.write('fi\n') + else: + ofile.write('# Rule 4\n') + ofile.write('mv $RPM_BUILD_ROOT/usr/' + source + ' $RPM_BUILD_ROOT/usr/' + dest + '\n') + if __name__ == "main": print 'Ice RPM Tools module' diff --git a/cpp/allTests.py b/cpp/allTests.py index 60f469568bd..0e7997bd70a 100755 --- a/cpp/allTests.py +++ b/cpp/allTests.py @@ -51,25 +51,25 @@ def runTests(args, tests, num = 0): # for i in tests: - i = os.path.normpath(i) - dir = os.path.join(toplevel, "test", i) + i = os.path.normpath(i) + dir = os.path.join(toplevel, "test", i) - print - if(num > 0): - print "[" + str(num) + "]", - print "*** running tests in " + dir, - print + print + if(num > 0): + print "[" + str(num) + "]", + print "*** running tests in " + dir, + print if isWin9x(): - status = os.system("python " + os.path.join(dir, "run.py " + args)) + status = os.system("python " + os.path.join(dir, "run.py " + args)) else: status = os.system(os.path.join(dir, "run.py " + args)) - if status: - if(num > 0): - print "[" + str(num) + "]", - print "test in " + dir + " failed with exit status", status, - sys.exit(status) + if status: + if(num > 0): + print "[" + str(num) + "]", + print "test in " + dir + " failed with exit status", status, + sys.exit(status) # # List of all basic tests. @@ -142,7 +142,7 @@ def usage(): try: opts, args = getopt.getopt(sys.argv[1:], "lr:R:", \ - ["debug", "protocol=", "compress", "host=", "threadPerConnection", "disablePool"]) + ["debug", "protocol=", "compress", "host=", "threadPerConnection", "disablePool"]) except getopt.GetoptError: usage() @@ -155,26 +155,26 @@ for o, a in opts: if o == "-l": loop = 1 if o == "-r" or o == '-R': - import re - regexp = re.compile(a) - if o == '-r': - def rematch(x): return regexp.search(x) - else: - def rematch(x): return not regexp.search(x) - tests = filter(rematch, tests) + import re + regexp = re.compile(a) + if o == '-r': + def rematch(x): return regexp.search(x) + else: + def rematch(x): return not regexp.search(x) + tests = filter(rematch, tests) if o == "--protocol": - if a not in ( "ssl", "tcp"): - usage() - args += " " + o + " " + a + if a not in ( "ssl", "tcp"): + usage() + args += " " + o + " " + a if o == "--host" : - args += " " + o + " " + a + args += " " + o + " " + a if o in ( "--debug", "--compress", "--threadPerConnection", "--disablePool" ): - args += " " + o + args += " " + o if loop: num = 1 while 1: - runTests(args, tests, num) - num += 1 + runTests(args, tests, num) + num += 1 else: runTests(args, tests) diff --git a/cpp/config/IceGridAdmin.py b/cpp/config/IceGridAdmin.py index 1095cca520b..05076c45d5a 100644 --- a/cpp/config/IceGridAdmin.py +++ b/cpp/config/IceGridAdmin.py @@ -36,7 +36,7 @@ nodeOptions = r' --Ice.Warn.Connections=0' + \ r' --IceGrid.Node.Trace.Server=0' + \ r' --Ice.OA.IceGrid.Node.ThreadPool.SizeWarn=0' + \ r' --IceGrid.Node.PrintServersReady=node' + \ - r' --Ice.NullHandleAbort' + \ + r' --Ice.NullHandleAbort' + \ r' --Ice.ThreadPool.Server.Size=0' + \ r' --Ice.ServerIdleTime=0'; @@ -83,10 +83,10 @@ def startIceGridRegistry(testdir, dynamicRegistration = False): i = 0 while i < (nreplicas + 1): - if i == 0: + if i == 0: name = "registry" - else: - name = "replica-" + str(i) + else: + name = "replica-" + str(i) dataDir = os.path.join(testdir, "db", name) if not os.path.exists(dataDir): @@ -101,10 +101,10 @@ def startIceGridRegistry(testdir, dynamicRegistration = False): r' --IceGrid.Registry.Data=' + dataDir if i > 0: - cmd += r' --IceGrid.Registry.ReplicaName=' + name + ' ' + getDefaultLocatorProperty() + cmd += r' --IceGrid.Registry.ReplicaName=' + name + ' ' + getDefaultLocatorProperty() if TestUtil.debug: - print "(" + cmd + ")", + print "(" + cmd + ")", pipe = os.popen(cmd + " 2>&1") TestUtil.getServerPid(pipe) @@ -137,7 +137,7 @@ def startIceGridNode(testdir): cleanDbDir(dataDir) overrideOptions = '"' + TestUtil.clientServerOptions.replace("--", "") + \ - ' Ice.ServerIdleTime=0 Ice.PrintProcessId=0 Ice.PrintAdapterReady=0"' + ' Ice.ServerIdleTime=0 Ice.PrintProcessId=0 Ice.PrintAdapterReady=0"' print "starting icegrid node...", command = iceGrid + TestUtil.clientServerOptions + ' --nowarn ' + nodeOptions + \ @@ -164,7 +164,7 @@ def iceGridAdmin(cmd, ignoreFailure = False): user = r"admin1" if cmd == "registry shutdown": - user = r"shutdown" + user = r"shutdown" command = iceGridAdmin + TestUtil.clientOptions + ' ' + getDefaultLocatorProperty() + \ r" --IceGridAdmin.Username=" + user + " --IceGridAdmin.Password=test1 " + \ r' -e "' + cmd + '"' @@ -303,11 +303,11 @@ def cleanDbDir(path): fullpath = os.path.join(path, filename); if os.path.isdir(fullpath): cleanDbDir(fullpath) - try: - os.rmdir(fullpath) - except OSError: - # This might fail if the directory is empty (because it itself is - # a CVS directory). - pass + try: + os.rmdir(fullpath) + except OSError: + # This might fail if the directory is empty (because it itself is + # a CVS directory). + pass else: os.remove(fullpath) diff --git a/cpp/config/TestUtil.py b/cpp/config/TestUtil.py index 4196c013721..3fbbfbc0060 100644 --- a/cpp/config/TestUtil.py +++ b/cpp/config/TestUtil.py @@ -61,17 +61,17 @@ except getopt.GetoptError: for o, a in opts: if o == "--debug": - debug = 1 + debug = 1 if o == "--protocol": - if a not in ( "tcp", "ssl"): - usage() - protocol = a + if a not in ( "tcp", "ssl"): + usage() + protocol = a if o == "--compress": - compress = 1 + compress = 1 if o == "--threadPerConnection": - threadPerConnection = 1 + threadPerConnection = 1 if o == "--host": - host = a + host = a def getIceVersion(): @@ -148,16 +148,16 @@ def isDarwin(): def closePipe(pipe): try: - status = pipe.close() + status = pipe.close() except IOError, ex: - # TODO: There's a waitpid problem on CentOS, so we have to ignore ECHILD. - if ex.errno == errno.ECHILD: - status = 0 + # TODO: There's a waitpid problem on CentOS, so we have to ignore ECHILD. + if ex.errno == errno.ECHILD: + status = 0 # This happens with the test/IceGrid/simple test on AIX elif ex.errno == 0: status = 0 - else: - raise + else: + raise return status class ReaderThread(Thread): @@ -171,20 +171,20 @@ class ReaderThread(Thread): while 1: line = self.pipe.readline() if not line: break - # Suppress "adapter ready" messages. Under windows the eol isn't \n. - if not line.endswith(" ready\n") and not line.endswith(" ready\r\n"): - print line, + # Suppress "adapter ready" messages. Under windows the eol isn't \n. + if not line.endswith(" ready\n") and not line.endswith(" ready\r\n"): + print line, except IOError: pass - #print "TERMINATED: " + str(self.pipe) - self.status = closePipe(self.pipe) + #print "TERMINATED: " + str(self.pipe) + self.status = closePipe(self.pipe) def getPipe(self): - return self.pipe + return self.pipe def getStatus(self): - return self.status + return self.status serverPids = [] serverThreads = [] @@ -194,8 +194,8 @@ def joinServers(): global serverThreads global allServerThreads for t in serverThreads: - t.join() - allServerThreads.append(t) + t.join() + allServerThreads.append(t) serverThreads = [] # This joins with all servers and if any of them failed then @@ -204,9 +204,9 @@ def serverStatus(): global allServerThreads joinServers() for t in allServerThreads: - status = t.getStatus() - if status: - return status + status = t.getStatus() + if status: + return status return 0 # This joins with a specific server (the one started with the given pipe) @@ -215,13 +215,13 @@ def serverStatus(): def specificServerStatus(pipe, timeout = None): global serverThreads for t in serverThreads: - if t.getPipe() == pipe: - serverThreads.remove(t) - t.join(timeout) - if t.isAlive(): - raise "server with pipe " + str(pipe) + " did not exit within the timeout period." - status = t.getStatus() - return status + if t.getPipe() == pipe: + serverThreads.remove(t) + t.join(timeout) + if t.isAlive(): + raise "server with pipe " + str(pipe) + " did not exit within the timeout period." + status = t.getStatus() + return status raise "can't find server with pipe: " + str(pipe) def killServers(): @@ -259,32 +259,32 @@ def getServerPid(pipe): global serverThreads while 1: - output = pipe.readline().strip() - if not output: - print "failed!" - killServers() - sys.exit(1) - if output.startswith("warning: "): - continue - break + output = pipe.readline().strip() + if not output: + print "failed!" + killServers() + sys.exit(1) + if output.startswith("warning: "): + continue + break try: - serverPids.append(int(output)) + serverPids.append(int(output)) except ValueError: - print "Output is not a PID: " + output - raise + print "Output is not a PID: " + output + raise def ignorePid(pipe): while 1: - output = pipe.readline().strip() - if not output: - print "failed!" - killServers() - sys.exit(1) - if output.startswith("warning: "): - continue - break + output = pipe.readline().strip() + if not output: + print "failed!" + killServers() + sys.exit(1) + if output.startswith("warning: "): + continue + break def getAdapterReady(pipe, createThread = True, count = 1): global serverThreads @@ -300,9 +300,9 @@ def getAdapterReady(pipe, createThread = True, count = 1): # Start a thread for this server. if createThread: - serverThread = ReaderThread(pipe) - serverThread.start() - serverThreads.append(serverThread) + serverThread = ReaderThread(pipe) + serverThread.start() + serverThreads.append(serverThread) def getIceBox(testdir): @@ -312,23 +312,23 @@ def getIceBox(testdir): iceBox = "" if isWin32(): - # - # Read the build.txt file from the test directory to figure out - # how the IceBox service was built ("debug" vs. "release") and - # decide which icebox executable to use. - # - build = open(os.path.join(testdir, "build.txt"), "r") - type = build.read().strip() - if type == "debug": - iceBox = os.path.join(toplevel, "bin", "iceboxd.exe") + # + # Read the build.txt file from the test directory to figure out + # how the IceBox service was built ("debug" vs. "release") and + # decide which icebox executable to use. + # + build = open(os.path.join(testdir, "build.txt"), "r") + type = build.read().strip() + if type == "debug": + iceBox = os.path.join(toplevel, "bin", "iceboxd.exe") elif type == "release": iceBox = os.path.join(toplevel, "bin", "icebox.exe") else: - iceBox = os.path.join(toplevel, "bin", "icebox") + iceBox = os.path.join(toplevel, "bin", "icebox") if iceBox == "" or not os.path.exists(iceBox): - print "couldn't find icebox executable to run the test" - sys.exit(0) + print "couldn't find icebox executable to run the test" + sys.exit(0) return iceBox; @@ -345,9 +345,9 @@ def waitServiceReady(pipe, token, createThread = True): # Start a thread for this server. if createThread: - serverThread = ReaderThread(pipe) - serverThread.start() - serverThreads.append(serverThread) + serverThread = ReaderThread(pipe) + serverThread.start() + serverThreads.append(serverThread) def printOutputFromPipe(pipe): @@ -359,15 +359,15 @@ def printOutputFromPipe(pipe): def addLdPath(path): if isWin32(): - if isCygwin(): - os.environ["PATH"] = path + ":" + os.getenv("PATH", "") - else: - os.environ["PATH"] = path + ";" + os.getenv("PATH", "") + if isCygwin(): + os.environ["PATH"] = path + ":" + os.getenv("PATH", "") + else: + os.environ["PATH"] = path + ";" + os.getenv("PATH", "") elif isAIX(): - os.environ["LIBPATH"] = path + ":" + os.getenv("LIBPATH", "") + os.environ["LIBPATH"] = path + ":" + os.getenv("LIBPATH", "") else: - os.environ["LD_LIBRARY_PATH"] = path + ":" + os.getenv("LD_LIBRARY_PATH", "") - os.environ["LD_LIBRARY_PATH_64"] = path + ":" + os.getenv("LD_LIBRARY_PATH_64", "") + os.environ["LD_LIBRARY_PATH"] = path + ":" + os.getenv("LD_LIBRARY_PATH", "") + os.environ["LD_LIBRARY_PATH_64"] = path + ":" + os.getenv("LD_LIBRARY_PATH_64", "") for toplevel in [".", "..", "../..", "../../..", "../../../.."]: toplevel = os.path.normpath(toplevel) @@ -378,9 +378,9 @@ else: if isWin32(): if isCygwin(): - os.environ["PATH"] = os.path.join(toplevel, "bin") + ":" + os.getenv("PATH", "") + os.environ["PATH"] = os.path.join(toplevel, "bin") + ":" + os.getenv("PATH", "") else: - os.environ["PATH"] = os.path.join(toplevel, "bin") + ";" + os.getenv("PATH", "") + os.environ["PATH"] = os.path.join(toplevel, "bin") + ";" + os.getenv("PATH", "") elif isHpUx(): os.environ["SHLIB_PATH"] = os.path.join(toplevel, "lib") + ":" + os.getenv("SHLIB_PATH", "") elif isDarwin(): @@ -393,7 +393,7 @@ else: os.environ["LD_LIBRARY_PATH_64"] = os.path.join(toplevel, "lib") + ":" + os.getenv("LD_LIBRARY_PATH_64", "") if protocol == "ssl": - plugin = " --Ice.Plugin.IceSSL=IceSSL:createIceSSL" + plugin = " --Ice.Plugin.IceSSL=IceSSL:createIceSSL" clientProtocol = plugin + " --Ice.Default.Protocol=ssl" + \ " --IceSSL.DefaultDir=" + os.path.join(toplevel, "certs") + \ " --IceSSL.CertFile=c_rsa1024_pub.pem" + \ @@ -430,7 +430,7 @@ if threadPerConnection: commonServerOptions += " --Ice.ThreadPerConnection" else: commonServerOptions += " --Ice.ThreadPool.Server.Size=1 --Ice.ThreadPool.Server.SizeMax=3" + \ - " --Ice.ThreadPool.Server.SizeWarn=0" + " --Ice.ThreadPool.Server.SizeWarn=0" clientOptions = clientProtocol + defaultHost + commonClientOptions serverOptions = serverProtocol + defaultHost + commonServerOptions @@ -447,7 +447,7 @@ def clientServerTestWithOptionsAndNames(name, additionalServerOptions, additiona print "starting " + serverName + "...", serverCmd = server + serverOptions + additionalServerOptions if debug: - print "(" + serverCmd + ")", + print "(" + serverCmd + ")", serverPipe = os.popen(serverCmd + " 2>&1") getServerPid(serverPipe) getAdapterReady(serverPipe) @@ -456,7 +456,7 @@ def clientServerTestWithOptionsAndNames(name, additionalServerOptions, additiona print "starting " + clientName + "...", clientCmd = client + clientOptions + additionalClientOptions if debug: - print "(" + clientCmd + ")", + print "(" + clientCmd + ")", clientPipe = os.popen(clientCmd + " 2>&1") print "ok" @@ -464,7 +464,7 @@ def clientServerTestWithOptionsAndNames(name, additionalServerOptions, additiona clientStatus = closePipe(clientPipe) if clientStatus: - killServers() + killServers() joinServers() @@ -488,7 +488,7 @@ def mixedClientServerTestWithOptions(name, additionalServerOptions, additionalCl print "starting server...", serverCmd = server + clientServerOptions + additionalServerOptions if debug: - print "(" + serverCmd + ")", + print "(" + serverCmd + ")", serverPipe = os.popen(serverCmd + " 2>&1") getServerPid(serverPipe) getAdapterReady(serverPipe) @@ -497,7 +497,7 @@ def mixedClientServerTestWithOptions(name, additionalServerOptions, additionalCl print "starting client...", clientCmd = client + clientServerOptions + additionalClientOptions if debug: - print "(" + clientCmd + ")", + print "(" + clientCmd + ")", clientPipe = os.popen(clientCmd + " 2>&1") ignorePid(clientPipe) getAdapterReady(clientPipe, False) @@ -508,10 +508,10 @@ def mixedClientServerTestWithOptions(name, additionalServerOptions, additionalCl clientStatus = closePipe(clientPipe) if clientStatus: - killServers() + killServers() if clientStatus or serverStatus(): - sys.exit(1) + sys.exit(1) def mixedClientServerTest(name): @@ -525,7 +525,7 @@ def collocatedTestWithOptions(name, additionalOptions): print "starting collocated...", command = collocated + collocatedOptions + additionalOptions if debug: - print "(" + command + ")", + print "(" + command + ")", collocatedPipe = os.popen(command + " 2>&1") print "ok" @@ -534,7 +534,7 @@ def collocatedTestWithOptions(name, additionalOptions): collocatedStatus = closePipe(collocatedPipe) if collocatedStatus: - sys.exit(1) + sys.exit(1) def collocatedTest(name): diff --git a/cpp/config/convertssl.py b/cpp/config/convertssl.py index 348023bb26f..8950ccd1685 100755 --- a/cpp/config/convertssl.py +++ b/cpp/config/convertssl.py @@ -52,8 +52,8 @@ else: def findChild(parent, name): for i in parent.childNodes: - if i.localName == name: - return i + if i.localName == name: + return i return None def printConfig(node, name, comment=""): @@ -62,98 +62,98 @@ def printConfig(node, name, comment=""): result = result + "#\n# NOTE: You may need to define IceSSL.DefaultDir\n" general = findChild(node, "general") if general: - if general.attributes.has_key("version"): - version = general.attributes["version"].nodeValue - if version == "SSLv3": - result = result + prefix + "Protocols=SSLv3\n" - elif version == "TLSv1": - result = result + prefix + "Protocols=TLSv1\n" - elif version != "SSLv23": - print "unknown value `" + version + "' for version attribute" - sys.exit(1) - - if general.attributes.has_key("cipherlist"): - result = result + prefix + "Ciphers=" + general.attributes["cipherlist"].nodeValue + "\n" - - if general.attributes.has_key("verifymode"): - verifymode = general.attributes["verifymode"].nodeValue - if verifymode == "none": - result = result + prefix + "VerifyPeer=0\n" - elif verifymode == "peer": - result = result + prefix + "VerifyPeer=1\n" - elif verifymode.find("fail") != -1: - result = result + prefix + "VerifyPeer=2\n" - elif verifymode.find("client_once") != -1: - result = result + prefix + "VerifyPeer=2\n" - else: - print "unknown value `" + verifymode + "' for verifymode attribute" - sys.exit(1) - - if general.attributes.has_key("verifydepth"): - result = result + prefix + "VerifyDepthMax=" + general.attributes["verifydepth"].nodeValue + "\n" - - if general.attributes.has_key("randombytes"): - result = result + "# NOTE: You may need to use IceSSL.EntropyDaemon\n" - result = result + prefix + "Random=" + general.attributes["randombytes"].nodeValue + "\n" + if general.attributes.has_key("version"): + version = general.attributes["version"].nodeValue + if version == "SSLv3": + result = result + prefix + "Protocols=SSLv3\n" + elif version == "TLSv1": + result = result + prefix + "Protocols=TLSv1\n" + elif version != "SSLv23": + print "unknown value `" + version + "' for version attribute" + sys.exit(1) + + if general.attributes.has_key("cipherlist"): + result = result + prefix + "Ciphers=" + general.attributes["cipherlist"].nodeValue + "\n" + + if general.attributes.has_key("verifymode"): + verifymode = general.attributes["verifymode"].nodeValue + if verifymode == "none": + result = result + prefix + "VerifyPeer=0\n" + elif verifymode == "peer": + result = result + prefix + "VerifyPeer=1\n" + elif verifymode.find("fail") != -1: + result = result + prefix + "VerifyPeer=2\n" + elif verifymode.find("client_once") != -1: + result = result + prefix + "VerifyPeer=2\n" + else: + print "unknown value `" + verifymode + "' for verifymode attribute" + sys.exit(1) + + if general.attributes.has_key("verifydepth"): + result = result + prefix + "VerifyDepthMax=" + general.attributes["verifydepth"].nodeValue + "\n" + + if general.attributes.has_key("randombytes"): + result = result + "# NOTE: You may need to use IceSSL.EntropyDaemon\n" + result = result + prefix + "Random=" + general.attributes["randombytes"].nodeValue + "\n" ca = findChild(node, "certauthority") if ca: - if ca.attributes.has_key("file"): - result = result + prefix + "CertAuthFile=" + ca.attributes["file"].nodeValue + "\n" - if ca.attributes.has_key("path"): - result = result + prefix + "CertAuthDir=" + ca.attributes["path"].nodeValue + "\n" + if ca.attributes.has_key("file"): + result = result + prefix + "CertAuthFile=" + ca.attributes["file"].nodeValue + "\n" + if ca.attributes.has_key("path"): + result = result + prefix + "CertAuthDir=" + ca.attributes["path"].nodeValue + "\n" basecerts = findChild(node, "basecerts") if basecerts: - certFile = "" - keyFile = "" - rsacert = findChild(basecerts, "rsacert") - if rsacert: - pub = findChild(rsacert, "public") - if pub.attributes.has_key("encoding"): - if pub.attributes["encoding"].nodeValue != "PEM": - result = result + "# NOTE: Only PEM encoding is supported for certificates!\n" - if pub.attributes.has_key("filename"): - certFile = pub.attributes["filename"].nodeValue - priv = findChild(rsacert, "private") - if priv.attributes.has_key("encoding"): - if priv.attributes["encoding"].nodeValue != "PEM": - result = result + "# NOTE: Only PEM encoding is supported for private keys!\n" - if priv.attributes.has_key("filename"): - keyFile = priv.attributes["filename"].nodeValue - dsacert = findChild(basecerts, "dsacert") - if dsacert: - pub = findChild(dsacert, "public") - if pub.attributes.has_key("encoding"): - if pub.attributes["encoding"].nodeValue != "PEM": - result = result + "# NOTE: Only PEM encoding is supported for certificates!\n" - if pub.attributes.has_key("filename"): - if len(certFile) > 0: - certFile = certFile + sep + pub.attributes["filename"].nodeValue - else: - certFile = pub.attributes["filename"].nodeValue - priv = findChild(rsacert, "private") - if priv.attributes.has_key("encoding"): - if priv.attributes["encoding"].nodeValue != "PEM": - result = result + "# NOTE: Only PEM encoding is supported for private keys!\n" - if priv.attributes.has_key("filename"): - if len(keyFile) > 0: - keyFile = keyFile + sep + priv.attributes["filename"].nodeValue - else: - keyFile = priv.attributes["filename"].nodeValue - if len(certFile) > 0: - result = result + prefix + "CertFile=" + certFile + "\n" - if len(keyFile) > 0: - result = result + prefix + "KeyFile=" + keyFile + "\n" - - for child in basecerts.childNodes: - if child.localName == "dhparams": - keysize = child.attributes["keysize"].nodeValue - if child.attributes.has_key("encoding"): - if child.attributes["encoding"].nodeValue != "PEM": - result = result + "# NOTE: Only PEM encoding is supported for DH parameters!\n" - filename = child.attributes["filename"].nodeValue - result = result + prefix + "DH." + keysize + "=" + filename + "\n" + certFile = "" + keyFile = "" + rsacert = findChild(basecerts, "rsacert") + if rsacert: + pub = findChild(rsacert, "public") + if pub.attributes.has_key("encoding"): + if pub.attributes["encoding"].nodeValue != "PEM": + result = result + "# NOTE: Only PEM encoding is supported for certificates!\n" + if pub.attributes.has_key("filename"): + certFile = pub.attributes["filename"].nodeValue + priv = findChild(rsacert, "private") + if priv.attributes.has_key("encoding"): + if priv.attributes["encoding"].nodeValue != "PEM": + result = result + "# NOTE: Only PEM encoding is supported for private keys!\n" + if priv.attributes.has_key("filename"): + keyFile = priv.attributes["filename"].nodeValue + dsacert = findChild(basecerts, "dsacert") + if dsacert: + pub = findChild(dsacert, "public") + if pub.attributes.has_key("encoding"): + if pub.attributes["encoding"].nodeValue != "PEM": + result = result + "# NOTE: Only PEM encoding is supported for certificates!\n" + if pub.attributes.has_key("filename"): + if len(certFile) > 0: + certFile = certFile + sep + pub.attributes["filename"].nodeValue + else: + certFile = pub.attributes["filename"].nodeValue + priv = findChild(rsacert, "private") + if priv.attributes.has_key("encoding"): + if priv.attributes["encoding"].nodeValue != "PEM": + result = result + "# NOTE: Only PEM encoding is supported for private keys!\n" + if priv.attributes.has_key("filename"): + if len(keyFile) > 0: + keyFile = keyFile + sep + priv.attributes["filename"].nodeValue + else: + keyFile = priv.attributes["filename"].nodeValue + if len(certFile) > 0: + result = result + prefix + "CertFile=" + certFile + "\n" + if len(keyFile) > 0: + result = result + prefix + "KeyFile=" + keyFile + "\n" + + for child in basecerts.childNodes: + if child.localName == "dhparams": + keysize = child.attributes["keysize"].nodeValue + if child.attributes.has_key("encoding"): + if child.attributes["encoding"].nodeValue != "PEM": + result = result + "# NOTE: Only PEM encoding is supported for DH parameters!\n" + filename = child.attributes["filename"].nodeValue + result = result + prefix + "DH." + keysize + "=" + filename + "\n" return result @@ -171,10 +171,10 @@ for x in sys.argv[1:]: usage() sys.exit(1) else: - if xmlfile: - usage() - sys.exit(1) - xmlfile = x + if xmlfile: + usage() + sys.exit(1) + xmlfile = x if not xmlfile: usage() diff --git a/cpp/config/findSliceFiles.py b/cpp/config/findSliceFiles.py index 5b3b283a4e6..cffe292cb59 100644 --- a/cpp/config/findSliceFiles.py +++ b/cpp/config/findSliceFiles.py @@ -32,13 +32,13 @@ print >> out, "SLICEFILES =", first = True for root, dirs, files in os.walk(sys.argv[1]): for name in files: - if not name.startswith(".") and name.endswith(".ice"): - if not first: - print >> out, "\\" - print >> out, " ", - else: - first = False - print >> out, os.path.join(root, name), + if not name.startswith(".") and name.endswith(".ice"): + if not first: + print >> out, "\\" + print >> out, " ", + else: + first = False + print >> out, os.path.join(root, name), print >> out, "\n" sys.exit(0) diff --git a/cpp/config/makeprops.py b/cpp/config/makeprops.py index 3c448a025ba..aec33ea0a39 100644 --- a/cpp/config/makeprops.py +++ b/cpp/config/makeprops.py @@ -33,12 +33,12 @@ def progError(msg): def removeOutputFiles(): global outputFiles for entry in outputFiles: - try: - if os.path.exists(entry[0]): - os.remove(entry[0]) - except EnvironmentError, ex: - progError("warning: could not unlink `" + entry[0] + "': " + ex.strerror + \ - " -- generated file contains errors"); + try: + if os.path.exists(entry[0]): + os.remove(entry[0]) + except EnvironmentError, ex: + progError("warning: could not unlink `" + entry[0] + "': " + ex.strerror + \ + " -- generated file contains errors"); def handler(signum, frame): removeOutputFiles() @@ -48,11 +48,11 @@ def openOutputFile(filename): global outputFiles try: outfile = file(filename, 'w') - outputFiles.append([filename, outfile]) + outputFiles.append([filename, outfile]) except IOError, ex: progError("cannot open `" + filename + "' for writing: " + ex.strerror) - removeOutputFiles() - sys.exit(1) + removeOutputFiles() + sys.exit(1) def writePreamble(lang): global progname @@ -61,117 +61,117 @@ def writePreamble(lang): global classname for entry in outputFiles: - file = entry[1] - file.write("// **********************************************************************\n") - file.write("//\n") - file.write("// Copyright (c) 2003-2006 ZeroC, Inc. All rights reserved.\n") - file.write("//\n") - file.write("// This copy of Ice is licensed to you under the terms described in the\n") - file.write("// ICE_LICENSE file included in this distribution.\n") - file.write("//\n") - file.write("// **********************************************************************\n") - file.write("\n") - file.write("// Generated by " + progname + " from file `" + infile + "', " + time.ctime() + "\n") - file.write("\n") - file.write("// IMPORTANT: Do not edit this file -- any edits made here will be lost!\n"); - if lang == "cpp": - continue - if lang == "java": - file.write("\n"); - file.write("package IceInternal;\n") - file.write("\n") - file.write("public final class " + classname + '\n'); - file.write("{\n") - continue - if lang == "cs": - file.write("\n"); - file.write("namespace IceInternal\n") - file.write("{\n") - file.write(" public sealed class " + classname + '\n') - file.write(" {\n"); - continue - progError("Internal error: impossible language: `" + lang + "'") - sys.exit(1) + file = entry[1] + file.write("// **********************************************************************\n") + file.write("//\n") + file.write("// Copyright (c) 2003-2006 ZeroC, Inc. All rights reserved.\n") + file.write("//\n") + file.write("// This copy of Ice is licensed to you under the terms described in the\n") + file.write("// ICE_LICENSE file included in this distribution.\n") + file.write("//\n") + file.write("// **********************************************************************\n") + file.write("\n") + file.write("// Generated by " + progname + " from file `" + infile + "', " + time.ctime() + "\n") + file.write("\n") + file.write("// IMPORTANT: Do not edit this file -- any edits made here will be lost!\n"); + if lang == "cpp": + continue + if lang == "java": + file.write("\n"); + file.write("package IceInternal;\n") + file.write("\n") + file.write("public final class " + classname + '\n'); + file.write("{\n") + continue + if lang == "cs": + file.write("\n"); + file.write("namespace IceInternal\n") + file.write("{\n") + file.write(" public sealed class " + classname + '\n') + file.write(" {\n"); + continue + progError("Internal error: impossible language: `" + lang + "'") + sys.exit(1) if lang == "cpp": header = outputFiles[1][1] - header.write("\n"); - header.write("#ifndef ICE_INTERNAL_" + classname + "_H\n"); - header.write("#define ICE_INTERNAL_" + classname + "_H\n"); - header.write("\n") - header.write("#include ") - header.write("\n") - header.write("namespace IceInternal\n") - header.write("{\n") - header.write("\n") - header.write("class " + classname + '\n') - header.write("{\n") - header.write("public:\n") - header.write("\n") - file = outputFiles[0][1] - file.write("\n"); - file.write("#include \n") + header.write("\n"); + header.write("#ifndef ICE_INTERNAL_" + classname + "_H\n"); + header.write("#define ICE_INTERNAL_" + classname + "_H\n"); + header.write("\n") + header.write("#include ") + header.write("\n") + header.write("namespace IceInternal\n") + header.write("{\n") + header.write("\n") + header.write("class " + classname + '\n') + header.write("{\n") + header.write("public:\n") + header.write("\n") + file = outputFiles[0][1] + file.write("\n"); + file.write("#include \n") def writePostamble(lang, labels, commandLineLabels): file = outputFiles[0][1] if lang == "cpp": header = outputFiles[1][1] - header.write("\n") + header.write("\n") - header.write(" static const char* const* validProps[];\n") - file.write("\n"); + header.write(" static const char* const* validProps[];\n") + file.write("\n"); file.write("const char* const* IceInternal::" + classname + "::validProps[] =\n") - file.write("{\n") - for label, line in labels.iteritems(): - file.write(" " + label + "Props,\n") - file.write(" 0\n"); - file.write("};\n") - - header.write(" static const char* clPropNames[];\n") - file.write("\n"); + file.write("{\n") + for label, line in labels.iteritems(): + file.write(" " + label + "Props,\n") + file.write(" 0\n"); + file.write("};\n") + + header.write(" static const char* clPropNames[];\n") + file.write("\n"); file.write("const char* IceInternal::" + classname + "::clPropNames[] =\n") - file.write("{\n") - for label in commandLineLabels: - file.write(" \"" + label + "\",\n") - file.write(" 0\n"); - file.write("};\n") - - header.write("};\n") - header.write("\n") - header.write("}\n") - header.write("\n") - header.write("#endif\n"); - return + file.write("{\n") + for label in commandLineLabels: + file.write(" \"" + label + "\",\n") + file.write(" 0\n"); + file.write("};\n") + + header.write("};\n") + header.write("\n") + header.write("}\n") + header.write("\n") + header.write("#endif\n"); + return if lang == "java": file.write(" public static final String[] validProps[] =\n") - file.write(" {\n") - for label, line in labels.iteritems(): - file.write(" " + label + "Props,\n") - file.write(" null\n") - file.write(" };\n\n"); + file.write(" {\n") + for label, line in labels.iteritems(): + file.write(" " + label + "Props,\n") + file.write(" null\n") + file.write(" };\n\n"); file.write(" public static final String clPropNames[] =\n") - file.write(" {\n") - for label in commandLineLabels: - file.write(" \"" + label + "\",\n") - file.write(" null\n") - file.write(" };\n"); + file.write(" {\n") + for label in commandLineLabels: + file.write(" \"" + label + "\",\n") + file.write(" null\n") + file.write(" };\n"); file.write("}\n"); return if lang == "cs": file.write(" public static string[][] validProps =\n") - file.write(" {\n") - for label, line in labels.iteritems(): - file.write(" " + label + "Props,\n") - file.write(" null\n") - file.write(" };\n\n"); + file.write(" {\n") + for label, line in labels.iteritems(): + file.write(" " + label + "Props,\n") + file.write(" null\n") + file.write(" };\n\n"); file.write(" public static string[] clPropNames =\n") - file.write(" {\n") - for label in commandLineLabels: - file.write(" \"" + label + "\",\n") - file.write(" null\n") - file.write(" };\n"); + file.write(" {\n") + for label in commandLineLabels: + file.write(" \"" + label + "\",\n") + file.write(" null\n") + file.write(" };\n"); file.write(" }\n"); file.write("}\n"); return @@ -179,21 +179,21 @@ def writePostamble(lang, labels, commandLineLabels): def startSection(lang, label): if lang == "cpp": header = outputFiles[1][1] - header.write(" static const char* " + label + "Props[];\n") + header.write(" static const char* " + label + "Props[];\n") file = outputFiles[0][1] if lang == "cpp": - file.write("\n"); + file.write("\n"); file.write("const char* IceInternal::" + classname + "::" + label + "Props[] =\n") file.write("{\n"); - return + return if lang == "java": file.write(" public static final String " + label + "Props[] =\n"); - file.write(" {\n") - return + file.write(" {\n") + return if lang == "cs": file.write(" public static string[] " + label + "Props =\n"); - file.write(" {\n") + file.write(" {\n") return def endSection(lang): @@ -201,32 +201,32 @@ def endSection(lang): if lang == "cpp": file.write(" 0\n"); file.write("};\n"); - return + return if lang == "java": - file.write(" null\n"); - file.write(" };\n"); + file.write(" null\n"); + file.write(" };\n"); file.write("\n") - return + return if lang == "cs": - file.write(" null\n"); - file.write(" };\n"); + file.write(" null\n"); + file.write(" };\n"); file.write("\n") - return + return wildcard = re.compile(".*.*") def writeEntry(lang, label, entry): file = outputFiles[0][1] if lang == "cpp": - file.write(" \"" + label + '.' + string.replace(entry, "", "*") + "\",\n") + file.write(" \"" + label + '.' + string.replace(entry, "", "*") + "\",\n") elif lang == "java": - pattern = string.replace(entry, ".", "\\\\.") - pattern = string.replace(pattern, "", "[^\\\\s]+") - file.write(" " + "\"^" + label + "\\\\." + pattern + "$\",\n") + pattern = string.replace(entry, ".", "\\\\.") + pattern = string.replace(pattern, "", "[^\\\\s]+") + file.write(" " + "\"^" + label + "\\\\." + pattern + "$\",\n") elif lang == "cs": - pattern = string.replace(entry, ".", "\\.") - pattern = string.replace(pattern, "", "[^\\s]+") - file.write(" " + "@\"^" + label + "\\." + pattern + "$\",\n") + pattern = string.replace(entry, ".", "\\.") + pattern = string.replace(pattern, "", "[^\\s]+") + file.write(" " + "@\"^" + label + "\\." + pattern + "$\",\n") def processFile(lang): @@ -235,17 +235,17 @@ def processFile(lang): # global infile try: - f = file(infile, 'r') + f = file(infile, 'r') except IOError, ex: - progError("cannot open `" + infile + "': " + ex.strerror) - sys.exit(1) + progError("cannot open `" + infile + "': " + ex.strerror) + sys.exit(1) # # Set up regular expressions for empty and comment lines, section headings, and entry lines. # - ignore = re.compile("^\s*(?:#.*)?$") # Empty line or comment line + ignore = re.compile("^\s*(?:#.*)?$") # Empty line or comment line section = re.compile("^\s*([a-zA-Z_]\w*)\s*:\s*([a-zA-Z]\w*)?\s*$") # Section heading - entry = re.compile("^\s*([^ \t\n\r\f\v#]+)(?:\s*#.*)?$") # Any non-whitespace character sequence, except for # + entry = re.compile("^\s*([^ \t\n\r\f\v#]+)(?:\s*#.*)?$") # Any non-whitespace character sequence, except for # # # Install signal handler so we can remove the output files if we are interrupted. @@ -261,14 +261,14 @@ def processFile(lang): classname, ext = os.path.splitext(os.path.basename(infile)) openOutputFile(classname + '.' + lang) if(lang == "cpp"): - openOutputFile(classname + ".h") + openOutputFile(classname + ".h") - labels = {} # Records the line number on which each label is defined + labels = {} # Records the line number on which each label is defined commandLineLabels = [] # The set of labels which are command line processing is enabled - atSectionStart = 0 # True for the line on which a label is defined - seenSection = 0 # Set to true (and the remains as true) once the first label is defined - numEntries = 0 # Number of entries within a section - errors = 0 # Number of syntax errors in the input file + atSectionStart = 0 # True for the line on which a label is defined + seenSection = 0 # Set to true (and the remains as true) once the first label is defined + numEntries = 0 # Number of entries within a section + errors = 0 # Number of syntax errors in the input file # # Write preamble. @@ -281,57 +281,57 @@ def processFile(lang): global lineNum lines = f.readlines() for l in lines: - lineNum += 1 - - # - # Ignore empty lines and comments. - # - if ignore.match(l) != None: - continue - - # - # Start of section. - # - labelMatch = section.match(l) - if labelMatch != None: - if atSectionStart: - fileError("section `" + label + "' must have at least one entry") - label = labelMatch.group(1) - try: - badLine = labels[label] - fileError("duplicate section heading: `" + label + "': previously defined on line " + badLine) - except KeyError: - pass - if label == "validProps": - fileError("`validProps' is reserved and cannot be used as a section heading") + lineNum += 1 + + # + # Ignore empty lines and comments. + # + if ignore.match(l) != None: + continue + + # + # Start of section. + # + labelMatch = section.match(l) + if labelMatch != None: + if atSectionStart: + fileError("section `" + label + "' must have at least one entry") + label = labelMatch.group(1) + try: + badLine = labels[label] + fileError("duplicate section heading: `" + label + "': previously defined on line " + badLine) + except KeyError: + pass + if label == "validProps": + fileError("`validProps' is reserved and cannot be used as a section heading") if labelMatch.group(2) != "false": commandLineLabels.append(label) - labels[label] = lineNum - if seenSection: - endSection(lang) - numEntries = 0 - startSection(lang, label) - seenSection = 1 - atSectionStart = 1 - continue - - entryMatch = entry.match(l) - if entryMatch != None: - writeEntry(lang, label, entryMatch.group(1)) - atSectionStart = 0 - numEntries += 1 - continue - - fileError("syntax error") + labels[label] = lineNum + if seenSection: + endSection(lang) + numEntries = 0 + startSection(lang, label) + seenSection = 1 + atSectionStart = 1 + continue + + entryMatch = entry.match(l) + if entryMatch != None: + writeEntry(lang, label, entryMatch.group(1)) + atSectionStart = 0 + numEntries += 1 + continue + + fileError("syntax error") if len(labels) == 0: - fileError("input must define at least one section"); + fileError("input must define at least one section"); # # End the final section. # if numEntries == 0: - fileError("section `" + label + "' must have at least one entry") + fileError("section `" + label + "' must have at least one entry") endSection(lang) # @@ -347,8 +347,8 @@ def processFile(lang): # Remove the output files if anything went wrong, so we don't leave partically written files behind. # if errors != 0: - removeOutputFiles() - sys.exit(1) + removeOutputFiles() + sys.exit(1) outputFiles = [] # @@ -364,12 +364,12 @@ if len(sys.argv) == 1: # Find where the root of the tree is. # for toplevel in [".", "..", "../..", "../../..", "../../../.."]: - toplevel = os.path.normpath(toplevel) - if os.path.exists(os.path.join(toplevel, "config", "makeprops.py")): - break + toplevel = os.path.normpath(toplevel) + if os.path.exists(os.path.join(toplevel, "config", "makeprops.py")): + break else: - progError("cannot find top-level directory") - sys.exit(1) + progError("cannot find top-level directory") + sys.exit(1) infile = os.path.join(toplevel, "config", "PropertyNames.def") lang = "all" @@ -377,17 +377,17 @@ if len(sys.argv) == 1: else: option = sys.argv[1] if option == "--cpp": - lang = "cpp" + lang = "cpp" elif option == "--java": - lang = "java" + lang = "java" elif option == "--cs": - lang = "cs" + lang = "cs" elif option == "-h" or option == "--help" or option == "-?": - usage() - sys.exit(0) + usage() + sys.exit(0) else: - usage() - sys.exit(1) + usage() + sys.exit(1) infile = sys.argv[2] if lang == "all": diff --git a/cpp/config/upgradeicegrid.py b/cpp/config/upgradeicegrid.py index 143b0535680..4fcaeb53c9a 100755 --- a/cpp/config/upgradeicegrid.py +++ b/cpp/config/upgradeicegrid.py @@ -51,7 +51,7 @@ def printOutputFromPipe(pipe): if not line: break if line.find("warning") == -1: - os.write(1, line) + os.write(1, line) def error(message): print "error: " + message @@ -92,7 +92,7 @@ for x in sys.argv[1:]: usage() sys.exit(0) elif x == "-o": - iceVersion = "3.1" + iceVersion = "3.1" elif x.startswith("-"): print sys.argv[0] + ": unknown option `" + x + "'" print @@ -138,7 +138,7 @@ desc = \ '' + \ ' ' + \ ' ' + \ -' ' + \ +' ' + \ ' ' + \ ' ' + \ ' ' + \ diff --git a/cpp/config/upgradeicestorm.py b/cpp/config/upgradeicestorm.py index 84a7152b763..56ee149626a 100755 --- a/cpp/config/upgradeicestorm.py +++ b/cpp/config/upgradeicestorm.py @@ -44,7 +44,7 @@ def printOutputFromPipe(pipe): if not line: break if line.find("warning") == -1: - os.write(1, line) + os.write(1, line) def error(message): print "error: " + message @@ -66,7 +66,7 @@ def transformdb(db, desc, oldSlice, newSlice): os.close(temp) transformdb = os.path.join(bindir, "transformdb") + " -i --old " + oldSliceFile + " --new " + newSliceFile + \ - " -f " + descFile + " " + olddbenv + " " + db + " " + newdbenv + " 2>&1" + " -f " + descFile + " " + olddbenv + " " + db + " " + newdbenv + " 2>&1" pipe = os.popen(transformdb) printOutputFromPipe(pipe) diff --git a/cpp/demo/Database/Oracle/occi/Client.cpp b/cpp/demo/Database/Oracle/occi/Client.cpp index 2260decdd0b..569fdf620fc 100644 --- a/cpp/demo/Database/Oracle/occi/Client.cpp +++ b/cpp/demo/Database/Oracle/occi/Client.cpp @@ -63,32 +63,32 @@ HRClient::HRClient() : _currentMenu(rootMenu) { _commonCommands = - "dept : set department as the current department\n" - "emp : set employee as the current employee\n" - "exit or quit: exit client\n" - "help: print this list of commands\n" - "root: go back to the root menu\n"; + "dept : set department as the current department\n" + "emp : set employee as the current employee\n" + "exit or quit: exit client\n" + "help: print this list of commands\n" + "root: go back to the root menu\n"; _rootCommands = - "create: create a new department\n" - "find : find the department(s) with the given name\n" - "list: list all departments\n"; + "create: create a new department\n" + "find : find the department(s) with the given name\n" + "list: list all departments\n"; - + _deptCommands = - "create: create a new employee in this department\n" - "find : find employee(s) named in this department\n" - "list: list all employees in this department\n" - "ping: ping this department\n" - "remove: remove this department\n" - "show: describe this department\n" - "update : update this department\n"; + "create: create a new employee in this department\n" + "find : find employee(s) named in this department\n" + "list: list all employees in this department\n" + "ping: ping this department\n" + "remove: remove this department\n" + "show: describe this department\n" + "update : update this department\n"; _empCommands = - "ping: ping this employee\n" - "remove: remove this employee\n" - "show: describe this employee\n" - "update : update this employee\n"; + "ping: ping this employee\n" + "remove: remove this employee\n" + "show: describe this employee\n" + "update : update this employee\n"; } void @@ -96,13 +96,13 @@ HRClient::checkEof(const string& command) const { if(!cin.eof()) { - string extra; - getline(cin, extra); - if(extra.size() > 0) - { - cout << "Warning: ignoring extra args '" << extra - << "' for '" << command << "'" << endl; - } + string extra; + getline(cin, extra); + if(extra.size() > 0) + { + cout << "Warning: ignoring extra args '" << extra + << "' for '" << command << "'" << endl; + } } } @@ -111,10 +111,10 @@ HRClient::checkCin(const string& command) const { if(!cin) { - cout << "Error: failed to read arguments for '" << command << "'" << endl; - cin.clear(); - cin.ignore(numeric_limits::max(), '\n'); - return false; + cout << "Error: failed to read arguments for '" << command << "'" << endl; + cin.clear(); + cin.ignore(numeric_limits::max(), '\n'); + return false; } checkEof(command); return true; @@ -124,7 +124,7 @@ void HRClient::invalidCommand(const string& command) const { cout << "Invalid command '" << command << "'. " - "Type 'help' for help." << endl; + "Type 'help' for help." << endl; cin.ignore(numeric_limits::max(), '\n'); } @@ -136,21 +136,21 @@ HRClient::help() const switch(_currentMenu) { - case rootMenu: - { - cout << _rootCommands; - break; - } - case deptMenu: - { - cout << _deptCommands; - break; - } - case empMenu: - { - cout << _empCommands; - break; - } + case rootMenu: + { + cout << _rootCommands; + break; + } + case deptMenu: + { + cout << _deptCommands; + break; + } + case empMenu: + { + cout << _empCommands; + break; + } } cout << "--- Common to all menus ---\n"; cout << _commonCommands << endl; @@ -163,8 +163,8 @@ HRClient::run(int argc, char* argv[]) _factory = DeptFactoryPrx::checkedCast(base); if(_factory == 0) { - cerr << argv[0] << ": invalid proxy" << endl; - return EXIT_FAILURE; + cerr << argv[0] << ": invalid proxy" << endl; + return EXIT_FAILURE; } Ice::EndpointSeq endpoints = _factory->ice_getEndpoints(); @@ -178,102 +178,102 @@ HRClient::run(int argc, char* argv[]) do { - cout << "==> "; - cin >> command; - - if(!cin) - { - break; - } - - try - { - - // - // Common commands - // - if(command == "dept") - { - int deptno; - cin >> deptno; - if(checkCin(command)) - { - _currentDept = DeptPrx::uncheckedCast(_factory->findDeptByNo(deptno)); - if(_currentDept != 0) - { - _currentMenu = deptMenu; - } - else - { - cout << "There is no department with deptno " << deptno << endl; - } - } - } - else if(command == "emp") - { - int empno; - cin >> empno; - if(checkCin(command)) - { - _currentEmp = EmpPrx::uncheckedCast(_factory->findEmpByNo(empno)); - if(_currentEmp != 0) - { - _currentMenu = empMenu; - } - else - { - cout << "There is no employee with empno " << empno << endl; - } - } - } - else if(command == "exit" || command == "quit") - { - checkEof(command); - break; - } - else if(command == "help") - { - checkEof(command); - help(); - } - else if(command == "root") - { - checkEof(command); - _currentMenu = rootMenu; - } - else if(_currentMenu == rootMenu) - { - doRootMenu(command); - } - else if(_currentMenu == deptMenu) - { - doDeptMenu(command); - } - else if(_currentMenu == empMenu) - { - doEmpMenu(command); - } - else - { - assert(0); - } - } - catch(const SqlException& e) - { - cout << "Caught a SqlException: " << e.reason << endl; - } - catch(const IceUtil::Exception& e) - { - cout << "Caught an Ice exception: " << e << endl; - } - catch(const std::exception& e) - { - cout << "Caught a std::exception: " << e.what() << endl; - } - catch(...) - { - cout << "Caught an unknown exception" << endl; - } + cout << "==> "; + cin >> command; + + if(!cin) + { + break; + } + + try + { + + // + // Common commands + // + if(command == "dept") + { + int deptno; + cin >> deptno; + if(checkCin(command)) + { + _currentDept = DeptPrx::uncheckedCast(_factory->findDeptByNo(deptno)); + if(_currentDept != 0) + { + _currentMenu = deptMenu; + } + else + { + cout << "There is no department with deptno " << deptno << endl; + } + } + } + else if(command == "emp") + { + int empno; + cin >> empno; + if(checkCin(command)) + { + _currentEmp = EmpPrx::uncheckedCast(_factory->findEmpByNo(empno)); + if(_currentEmp != 0) + { + _currentMenu = empMenu; + } + else + { + cout << "There is no employee with empno " << empno << endl; + } + } + } + else if(command == "exit" || command == "quit") + { + checkEof(command); + break; + } + else if(command == "help") + { + checkEof(command); + help(); + } + else if(command == "root") + { + checkEof(command); + _currentMenu = rootMenu; + } + else if(_currentMenu == rootMenu) + { + doRootMenu(command); + } + else if(_currentMenu == deptMenu) + { + doDeptMenu(command); + } + else if(_currentMenu == empMenu) + { + doEmpMenu(command); + } + else + { + assert(0); + } + } + catch(const SqlException& e) + { + cout << "Caught a SqlException: " << e.reason << endl; + } + catch(const IceUtil::Exception& e) + { + cout << "Caught an Ice exception: " << e << endl; + } + catch(const std::exception& e) + { + cout << "Caught a std::exception: " << e.what() << endl; + } + catch(...) + { + cout << "Caught an unknown exception" << endl; + } } while(cin.good()); @@ -285,38 +285,38 @@ HRClient::doRootMenu(const string& command) const { if(command == "create") { - checkEof(command); - cout << "Please enter: deptno dname loc ==> "; - int deptno; - DeptDesc desc; - cin >> deptno >> desc.dname >> desc.loc; - - desc.dname = unquote(desc.dname); - desc.loc = unquote(desc.loc); - - if(checkCin("create parameters")) - { - _factory->createDept(deptno, desc); - cout << "Created new department number " << deptno << endl; - } + checkEof(command); + cout << "Please enter: deptno dname loc ==> "; + int deptno; + DeptDesc desc; + cin >> deptno >> desc.dname >> desc.loc; + + desc.dname = unquote(desc.dname); + desc.loc = unquote(desc.loc); + + if(checkCin("create parameters")) + { + _factory->createDept(deptno, desc); + cout << "Created new department number " << deptno << endl; + } } else if(command == "find") { - string name; - cin >> name; - if(checkCin(command)) - { - printDepts(_factory->findByName(name)); - } + string name; + cin >> name; + if(checkCin(command)) + { + printDepts(_factory->findByName(name)); + } } else if(command == "list") { - checkEof(command); - printDepts(_factory->findAll()); + checkEof(command); + printDepts(_factory->findAll()); } else { - invalidCommand(command); + invalidCommand(command); } } @@ -325,84 +325,84 @@ HRClient::doDeptMenu(const string& command) const { if(command == "create") { - checkEof(command); - cout << "Please enter: empno ename job mgr(empno) hiredate sal comm ==> "; - int empno; - int mgrEmpno; - EmpDesc desc; - cin >> empno >> desc.ename >> desc.job >> mgrEmpno >> desc.hiredate >> desc.sal >> desc.comm; - - desc.ename = unquote(desc.ename); - desc.job = unquote(desc.job); - - if(mgrEmpno != 0) - { - desc.mgr = _factory->findEmpByNo(mgrEmpno); - if(desc.mgr == 0) - { - cout << "Manager #" << mgrEmpno << " does not exist: clearing manager" << endl; - } - } - desc.hiredate = unquote(desc.hiredate); - desc.sal = unquote(desc.sal); - desc.comm = unquote(desc.comm); - - desc.edept = _currentDept; - - if(checkCin("create parameters")) - { - _currentDept->createEmp(empno, desc); - cout << "Created new employee number " << empno << endl; - } + checkEof(command); + cout << "Please enter: empno ename job mgr(empno) hiredate sal comm ==> "; + int empno; + int mgrEmpno; + EmpDesc desc; + cin >> empno >> desc.ename >> desc.job >> mgrEmpno >> desc.hiredate >> desc.sal >> desc.comm; + + desc.ename = unquote(desc.ename); + desc.job = unquote(desc.job); + + if(mgrEmpno != 0) + { + desc.mgr = _factory->findEmpByNo(mgrEmpno); + if(desc.mgr == 0) + { + cout << "Manager #" << mgrEmpno << " does not exist: clearing manager" << endl; + } + } + desc.hiredate = unquote(desc.hiredate); + desc.sal = unquote(desc.sal); + desc.comm = unquote(desc.comm); + + desc.edept = _currentDept; + + if(checkCin("create parameters")) + { + _currentDept->createEmp(empno, desc); + cout << "Created new employee number " << empno << endl; + } } else if(command == "find") { - string name; - cin >> name; - if(checkCin(command)) - { - printEmps(_currentDept->findByName(name)); - } + string name; + cin >> name; + if(checkCin(command)) + { + printEmps(_currentDept->findByName(name)); + } } else if(command == "list") { - checkEof(command); - printEmps(_currentDept->findAll()); + checkEof(command); + printEmps(_currentDept->findAll()); } else if(command == "ping") { - checkEof(command); - _currentDept->ice_ping(); - cout << "ice_ping: success!" << endl; + checkEof(command); + _currentDept->ice_ping(); + cout << "ice_ping: success!" << endl; } else if(command == "remove") { - checkEof(command); - _currentDept->remove(); + checkEof(command); + _currentDept->remove(); } else if(command == "show") { - checkEof(command); - DeptDesc desc = _currentDept->getDesc(); - cout << "deptno: " << desc.deptno << endl; - cout << "dname: " << quote(desc.dname) << endl; - cout << "loc: " << quote(desc.loc) << endl; + checkEof(command); + DeptDesc desc = _currentDept->getDesc(); + cout << "deptno: " << desc.deptno << endl; + cout << "dname: " << quote(desc.dname) << endl; + cout << "loc: " << quote(desc.loc) << endl; } else if(command == "update") { - string field; - string newValue; - cin >> field >> newValue; - newValue = unquote(newValue); - - if(checkCin("update " + field)) - { - _currentDept->updateField(field, newValue); - } + string field; + string newValue; + cin >> field >> newValue; + newValue = unquote(newValue); + + if(checkCin("update " + field)) + { + _currentDept->updateField(field, newValue); + } } else { - invalidCommand(command); + invalidCommand(command); } } @@ -411,80 +411,80 @@ HRClient::doEmpMenu(const string& command) const { if(command == "ping") { - checkEof(command); - _currentEmp->ice_ping(); - cout << "ice_ping: success!" << endl; + checkEof(command); + _currentEmp->ice_ping(); + cout << "ice_ping: success!" << endl; } else if(command == "remove") { - checkEof(command); - _currentEmp->remove(); + checkEof(command); + _currentEmp->remove(); } else if(command == "show") { - checkEof(command); - EmpDesc desc = _currentEmp->getDesc(); - cout << "empno: " << desc.empno << endl; - cout << "ename: " << quote(desc.ename) << endl; - cout << "job: " << quote(desc.job) << endl; - cout << "mgr: "; - if(desc.mgr == 0) - { - cout << "" << endl; - } - else - { - cout << desc.mgr->getDesc().empno << endl; - } - cout << "hiredate: " << quote(desc.hiredate) << endl; - cout << "sal: " << quote(desc.sal) << endl; - cout << "comm: " << quote(desc.comm) << endl; - cout << "dept: "; - if(desc.edept == 0) - { - cout << "" << endl; - } - else - { - cout << desc.edept->getDesc().deptno << endl; - } + checkEof(command); + EmpDesc desc = _currentEmp->getDesc(); + cout << "empno: " << desc.empno << endl; + cout << "ename: " << quote(desc.ename) << endl; + cout << "job: " << quote(desc.job) << endl; + cout << "mgr: "; + if(desc.mgr == 0) + { + cout << "" << endl; + } + else + { + cout << desc.mgr->getDesc().empno << endl; + } + cout << "hiredate: " << quote(desc.hiredate) << endl; + cout << "sal: " << quote(desc.sal) << endl; + cout << "comm: " << quote(desc.comm) << endl; + cout << "dept: "; + if(desc.edept == 0) + { + cout << "" << endl; + } + else + { + cout << desc.edept->getDesc().deptno << endl; + } } else if(command == "update") { - string field; - cin >> field; - if(field == "mgr") - { - int mgr; - cin >> mgr; - if(checkCin("update mgr")) - { - _currentEmp->updateMgr(mgr); - } - } - else if(field == "dept") - { - int deptno; - cin >> deptno; - if(checkCin("update dept")) - { - _currentEmp->updateDept(deptno); - } - } - else - { - string newValue; - cin >> newValue; - newValue = unquote(newValue); - if(checkCin("update " + field)) - { - _currentEmp->updateField(field, newValue); - } - } + string field; + cin >> field; + if(field == "mgr") + { + int mgr; + cin >> mgr; + if(checkCin("update mgr")) + { + _currentEmp->updateMgr(mgr); + } + } + else if(field == "dept") + { + int deptno; + cin >> deptno; + if(checkCin("update dept")) + { + _currentEmp->updateDept(deptno); + } + } + else + { + string newValue; + cin >> newValue; + newValue = unquote(newValue); + if(checkCin("update " + field)) + { + _currentEmp->updateField(field, newValue); + } + } } else { - invalidCommand(command); + invalidCommand(command); } } @@ -494,15 +494,15 @@ HRClient::printDepts(const DeptPrxSeq& depts) const cout << "Deptno\t Dname\t Loc" << endl; if(depts.size() == 0) { - cout << "" << endl; + cout << "" << endl; } else { - for(DeptPrxSeq::const_iterator p = depts.begin(); p != depts.end(); ++p) - { - HR::DeptDesc desc = (*p)->getDesc(); - cout << desc.deptno << "\t " << desc.dname << "\t " << desc.loc << endl; - } + for(DeptPrxSeq::const_iterator p = depts.begin(); p != depts.end(); ++p) + { + HR::DeptDesc desc = (*p)->getDesc(); + cout << desc.deptno << "\t " << desc.dname << "\t " << desc.loc << endl; + } } } @@ -512,15 +512,15 @@ HRClient::printEmps(const EmpPrxSeq& emps) const cout << "Empno\t Ename" << endl; if(emps.size() == 0) { - cout << "" << endl; + cout << "" << endl; } else { - for(EmpPrxSeq::const_iterator p = emps.begin(); p != emps.end(); ++p) - { - HR::EmpDesc desc = (*p)->getDesc(); - cout << desc.empno << "\t " << desc.ename << endl; - } + for(EmpPrxSeq::const_iterator p = emps.begin(); p != emps.end(); ++p) + { + HR::EmpDesc desc = (*p)->getDesc(); + cout << desc.empno << "\t " << desc.ename << endl; + } } } @@ -530,11 +530,11 @@ HRClient::quote(const string& str) { if(str == "") { - return "''"; + return "''"; } else { - return str; + return str; } } @@ -544,10 +544,10 @@ HRClient::unquote(const string& str) { if(str == "''") { - return ""; + return ""; } else { - return str; + return str; } } diff --git a/cpp/demo/Database/Oracle/occi/DeptFactoryI.cpp b/cpp/demo/Database/Oracle/occi/DeptFactoryI.cpp index 03a9d7538b7..336d4dc6a1b 100644 --- a/cpp/demo/Database/Oracle/occi/DeptFactoryI.cpp +++ b/cpp/demo/Database/Oracle/occi/DeptFactoryI.cpp @@ -23,7 +23,7 @@ using namespace std; using namespace oracle::occi; DeptFactoryI::DeptFactoryI(Environment* env, StatelessConnectionPool* pool, - const string& category) : + const string& category) : _env(env), _pool(pool), _category(category) @@ -58,18 +58,18 @@ DeptFactoryI::findAll(const Ice::Current& current) ConnectionHolderPtr conh = new ConnectionHolder(_pool); { - StatementHolder stmth(conh); + StatementHolder stmth(conh); - auto_ptr rs(stmth.statement()->executeQuery("SELECT REF(d) FROM DEPT_VIEW d")); - - while(rs->next() != ResultSet::END_OF_FETCH) - { - Ice::Identity deptId; - deptId.category = _category; - deptId.name = encodeRef(rs->getRef(1), _env); - - result.push_back(HR::DeptPrx::uncheckedCast(current.adapter->createProxy(deptId))); - } + auto_ptr rs(stmth.statement()->executeQuery("SELECT REF(d) FROM DEPT_VIEW d")); + + while(rs->next() != ResultSet::END_OF_FETCH) + { + Ice::Identity deptId; + deptId.category = _category; + deptId.name = encodeRef(rs->getRef(1), _env); + + result.push_back(HR::DeptPrx::uncheckedCast(current.adapter->createProxy(deptId))); + } } conh->commit(); return result; @@ -82,20 +82,20 @@ DeptFactoryI::findByName(const string& name, const Ice::Current& current) HR::DeptPrxSeq result; ConnectionHolderPtr conh = new ConnectionHolder(_pool); { - StatementHolder stmth(conh); - stmth.statement()->setSQL("SELECT REF(d) FROM DEPT_VIEW d WHERE DNAME = :1"); - stmth.statement()->setString(1, name); - - auto_ptr rs(stmth.statement()->executeQuery()); - - while(rs->next() != ResultSet::END_OF_FETCH) - { - Ice::Identity deptId; - deptId.category = _category; - deptId.name = encodeRef(rs->getRef(1), _env); - - result.push_back(HR::DeptPrx::uncheckedCast(current.adapter->createProxy(deptId))); - } + StatementHolder stmth(conh); + stmth.statement()->setSQL("SELECT REF(d) FROM DEPT_VIEW d WHERE DNAME = :1"); + stmth.statement()->setString(1, name); + + auto_ptr rs(stmth.statement()->executeQuery()); + + while(rs->next() != ResultSet::END_OF_FETCH) + { + Ice::Identity deptId; + deptId.category = _category; + deptId.name = encodeRef(rs->getRef(1), _env); + + result.push_back(HR::DeptPrx::uncheckedCast(current.adapter->createProxy(deptId))); + } } conh->commit(); return result; @@ -111,10 +111,10 @@ DeptFactoryI::findDeptByNo(int deptno, const Ice::Current& current) if(!ref.isNull()) { - Ice::Identity deptId; - deptId.category = _category; - deptId.name = encodeRef(ref, _env); - result = HR::DeptPrx::uncheckedCast(current.adapter->createProxy(deptId)); + Ice::Identity deptId; + deptId.category = _category; + deptId.name = encodeRef(ref, _env); + result = HR::DeptPrx::uncheckedCast(current.adapter->createProxy(deptId)); } conh->commit(); return result; @@ -129,10 +129,10 @@ DeptFactoryI::findEmpByNo(int empno, const Ice::Current& current) if(!ref.isNull()) { - Ice::Identity empId; - empId.category = _category; - empId.name = encodeRef(ref, _env); - result = HR::EmpPrx::uncheckedCast(current.adapter->createProxy(empId)); + Ice::Identity empId; + empId.category = _category; + empId.name = encodeRef(ref, _env); + result = HR::EmpPrx::uncheckedCast(current.adapter->createProxy(empId)); } conh->commit(); return result; @@ -148,7 +148,7 @@ DeptFactoryI::findDeptRefByNo(int deptno, Connection* con) const if(rs->next() == ResultSet::END_OF_FETCH) { - return Ref(); + return Ref(); } return rs->getRef(1); } @@ -163,7 +163,7 @@ DeptFactoryI::findEmpRefByNo(int empno, Connection* con) const if(rs->next() == ResultSet::END_OF_FETCH) { - return Ref(); + return Ref(); } return rs->getRef(1); } diff --git a/cpp/demo/Database/Oracle/occi/DeptFactoryI.h b/cpp/demo/Database/Oracle/occi/DeptFactoryI.h index 13cf0402fc6..96ff67d28cc 100644 --- a/cpp/demo/Database/Oracle/occi/DeptFactoryI.h +++ b/cpp/demo/Database/Oracle/occi/DeptFactoryI.h @@ -19,7 +19,7 @@ class DeptFactoryI : public HR::DeptFactory public: DeptFactoryI(oracle::occi::Environment* env, oracle::occi::StatelessConnectionPool*, - const std::string&); + const std::string&); virtual HR::DeptPrx createDept(int, const HR::DeptDesc&, const Ice::Current&); @@ -34,17 +34,17 @@ public: oracle::occi::Environment* getEnv() const { - return _env; + return _env; } oracle::occi::StatelessConnectionPool* getConnectionPool() const { - return _pool; + return _pool; } const std::string& getCategory() const { - return _category; + return _category; } private: diff --git a/cpp/demo/Database/Oracle/occi/DeptI.cpp b/cpp/demo/Database/Oracle/occi/DeptI.cpp index 0703cfb9fac..d74f7ccf7cc 100644 --- a/cpp/demo/Database/Oracle/occi/DeptI.cpp +++ b/cpp/demo/Database/Oracle/occi/DeptI.cpp @@ -34,36 +34,36 @@ DeptI::createEmp(int empno, const HR::EmpDesc& desc, const Ice::Current& current // Inserted into the OCCI cache // EMP_T* emp = new(_conh->connection(), "EMP_VIEW")EMP_T; - + emp->setEmpno(empno); emp->setEname(desc.ename); emp->setJob(desc.job); if(desc.mgr != 0) { - Ref mgrRef = decodeRef(desc.mgr->ice_getIdentity().name, env, _conh->connection()); - - emp->setMgrref(mgrRef); + Ref mgrRef = decodeRef(desc.mgr->ice_getIdentity().name, env, _conh->connection()); + + emp->setMgrref(mgrRef); } if(desc.hiredate != "") { - Date hiredate(env); - hiredate.fromText(desc.hiredate); - emp->setHiredate(hiredate); + Date hiredate(env); + hiredate.fromText(desc.hiredate); + emp->setHiredate(hiredate); } if(desc.sal != "") { - Number sal(0); - sal.fromText(env, desc.sal, "99999.99"); - emp->setSal(sal); + Number sal(0); + sal.fromText(env, desc.sal, "99999.99"); + emp->setSal(sal); } if(desc.comm != "") { - Number comm(0); - comm.fromText(env, desc.comm, "0.999"); - emp->setComm(comm); + Number comm(0); + comm.fromText(env, desc.comm, "0.999"); + emp->setComm(comm); } emp->setDeptref(_ref); @@ -93,18 +93,18 @@ void DeptI::updateField(const string& field, const string& newValue, const Ice::Current& current) { Ref deptRef = decodeRef(current.id.name, _factory->getEnv(), _conh->connection()); - + if(field == "dname") { - deptRef->setDname(newValue); + deptRef->setDname(newValue); } else if(field == "loc") { - deptRef->setLoc(newValue); + deptRef->setLoc(newValue); } else { - throw HR::SqlException("There is no field " + field + " in object DEPT_T"); + throw HR::SqlException("There is no field " + field + " in object DEPT_T"); } deptRef->markModified(); _conh->commit(); @@ -123,21 +123,21 @@ DeptI::findAll(const Ice::Current& current) { HR::EmpPrxSeq result; { - Ref deptRef = decodeRef(current.id.name, _factory->getEnv(), _conh->connection()); + Ref deptRef = decodeRef(current.id.name, _factory->getEnv(), _conh->connection()); - StatementHolder stmth(_conh); - stmth.statement()->setSQL("SELECT REF(e) FROM EMP_VIEW e WHERE DEPTREF = :1"); - stmth.statement()->setRef(1, deptRef); - auto_ptr rs(stmth.statement()->executeQuery()); - - while(rs->next() != ResultSet::END_OF_FETCH) - { - Ice::Identity empId; - empId.category = _factory->getCategory(); - empId.name = encodeRef(rs->getRef(1), _factory->getEnv()); - - result.push_back(HR::EmpPrx::uncheckedCast(current.adapter->createProxy(empId))); - } + StatementHolder stmth(_conh); + stmth.statement()->setSQL("SELECT REF(e) FROM EMP_VIEW e WHERE DEPTREF = :1"); + stmth.statement()->setRef(1, deptRef); + auto_ptr rs(stmth.statement()->executeQuery()); + + while(rs->next() != ResultSet::END_OF_FETCH) + { + Ice::Identity empId; + empId.category = _factory->getCategory(); + empId.name = encodeRef(rs->getRef(1), _factory->getEnv()); + + result.push_back(HR::EmpPrx::uncheckedCast(current.adapter->createProxy(empId))); + } } _conh->commit(); return result; @@ -148,22 +148,22 @@ DeptI::findByName(const string& name, const Ice::Current& current) { HR::EmpPrxSeq result; { - Ref deptRef = decodeRef(current.id.name, _factory->getEnv(), _conh->connection()); + Ref deptRef = decodeRef(current.id.name, _factory->getEnv(), _conh->connection()); - StatementHolder stmth(_conh); - stmth.statement()->setSQL("SELECT REF(e) FROM EMP_VIEW e WHERE DEPTREF = :1 AND ENAME = :2"); - stmth.statement()->setRef(1, deptRef); - stmth.statement()->setString(2, name); - auto_ptr rs(stmth.statement()->executeQuery()); - - while(rs->next() != ResultSet::END_OF_FETCH) - { - Ice::Identity empId; - empId.category = _factory->getCategory(); - empId.name = encodeRef(rs->getRef(1), _factory->getEnv()); - - result.push_back(HR::EmpPrx::uncheckedCast(current.adapter->createProxy(empId))); - } + StatementHolder stmth(_conh); + stmth.statement()->setSQL("SELECT REF(e) FROM EMP_VIEW e WHERE DEPTREF = :1 AND ENAME = :2"); + stmth.statement()->setRef(1, deptRef); + stmth.statement()->setString(2, name); + auto_ptr rs(stmth.statement()->executeQuery()); + + while(rs->next() != ResultSet::END_OF_FETCH) + { + Ice::Identity empId; + empId.category = _factory->getCategory(); + empId.name = encodeRef(rs->getRef(1), _factory->getEnv()); + + result.push_back(HR::EmpPrx::uncheckedCast(current.adapter->createProxy(empId))); + } } _conh->commit(); return result; diff --git a/cpp/demo/Database/Oracle/occi/EmpI.cpp b/cpp/demo/Database/Oracle/occi/EmpI.cpp index d591542cafe..7ae0bd39461 100644 --- a/cpp/demo/Database/Oracle/occi/EmpI.cpp +++ b/cpp/demo/Database/Oracle/occi/EmpI.cpp @@ -32,31 +32,31 @@ EmpI::getDesc(const Ice::Current& current) Ref mgrRef = empRef->getMgrref(); if(!mgrRef.isNull()) { - Ice::Identity mgrId; - mgrId.name = encodeRef(mgrRef, env); - mgrId.category = _factory->getCategory(); - result.mgr = HR::EmpPrx::uncheckedCast(current.adapter->createProxy(mgrId)); + Ice::Identity mgrId; + mgrId.name = encodeRef(mgrRef, env); + mgrId.category = _factory->getCategory(); + result.mgr = HR::EmpPrx::uncheckedCast(current.adapter->createProxy(mgrId)); } result.hiredate = empRef->getHiredate().toText(); if(!empRef->getSal().isNull()) { - result.sal = empRef->getSal().toText(env, "99999.99"); + result.sal = empRef->getSal().toText(env, "99999.99"); } if(!empRef->getComm().isNull()) { - result.comm = empRef->getComm().toText(env, "0.999"); + result.comm = empRef->getComm().toText(env, "0.999"); } Ref deptRef = empRef->getDeptref(); if(!deptRef.isNull()) { - Ice::Identity deptId; - deptId.name = encodeRef(deptRef, env); - deptId.category = _factory->getCategory(); - result.edept = HR::DeptPrx::uncheckedCast(current.adapter->createProxy(deptId)); + Ice::Identity deptId; + deptId.name = encodeRef(deptRef, env); + deptId.category = _factory->getCategory(); + result.edept = HR::DeptPrx::uncheckedCast(current.adapter->createProxy(deptId)); } _conh->commit(); return result; @@ -69,55 +69,55 @@ EmpI::updateField(const string& field, const string& newValue, const Ice::Curren if(field == "ename") { - empRef->setEname(newValue); + empRef->setEname(newValue); } else if(field == "job") { - empRef->setJob(newValue); + empRef->setJob(newValue); } else if(field == "hiredate") { - if(newValue == "") - { - empRef->setHiredate(Date()); - } - else - { - Date hiredate(_factory->getEnv()); - hiredate.fromText(newValue); - empRef->setHiredate(hiredate); - } + if(newValue == "") + { + empRef->setHiredate(Date()); + } + else + { + Date hiredate(_factory->getEnv()); + hiredate.fromText(newValue); + empRef->setHiredate(hiredate); + } } else if(field == "sal") { - if(newValue == "") - { - empRef->setSal(Number()); - } - else - { - Number sal(0); - sal.fromText(_factory->getEnv(), newValue, "99999.99"); - empRef->setSal(sal); - } + if(newValue == "") + { + empRef->setSal(Number()); + } + else + { + Number sal(0); + sal.fromText(_factory->getEnv(), newValue, "99999.99"); + empRef->setSal(sal); + } } else if(field == "comm") { - if(newValue == "") - { - empRef->setComm(Number()); - } - else - { - Number comm(0); - comm.fromText(_factory->getEnv(), newValue, "0.999"); - empRef->setComm(comm); - } + if(newValue == "") + { + empRef->setComm(Number()); + } + else + { + Number comm(0); + comm.fromText(_factory->getEnv(), newValue, "0.999"); + empRef->setComm(comm); + } } else { - throw HR::SqlException("There is no field " + field + " in type EMP_T"); - } + throw HR::SqlException("There is no field " + field + " in type EMP_T"); + } empRef->markModified(); _conh->commit(); } @@ -129,17 +129,17 @@ EmpI::updateMgr(int newMgr, const Ice::Current& current) if(newMgr == 0) { - empRef->setMgrref(Ref()); + empRef->setMgrref(Ref()); } else { - Ref mgrRef = _factory->findEmpRefByNo(newMgr, _conh->connection()); - - if(mgrRef.isNull()) - { - throw HR::SqlException("There is no employee with this empno"); - } - empRef->setMgrref(mgrRef); + Ref mgrRef = _factory->findEmpRefByNo(newMgr, _conh->connection()); + + if(mgrRef.isNull()) + { + throw HR::SqlException("There is no employee with this empno"); + } + empRef->setMgrref(mgrRef); } empRef->markModified(); _conh->commit(); @@ -152,17 +152,17 @@ EmpI::updateDept(int newDept, const Ice::Current& current) if(newDept == 0) { - empRef->setDeptref(Ref()); + empRef->setDeptref(Ref()); } else { - Ref deptRef = _factory->findDeptRefByNo(newDept, _conh->connection()); - - if(deptRef.isNull()) - { - throw HR::SqlException("There is no department with this deptno"); - } - empRef->setDeptref(deptRef); + Ref deptRef = _factory->findDeptRefByNo(newDept, _conh->connection()); + + if(deptRef.isNull()) + { + throw HR::SqlException("There is no department with this deptno"); + } + empRef->setDeptref(deptRef); } empRef->markModified(); _conh->commit(); diff --git a/cpp/demo/Database/Oracle/occi/OCCIServantLocator.cpp b/cpp/demo/Database/Oracle/occi/OCCIServantLocator.cpp index 4236c9dc542..6d8b0ba8449 100755 --- a/cpp/demo/Database/Oracle/occi/OCCIServantLocator.cpp +++ b/cpp/demo/Database/Oracle/occi/OCCIServantLocator.cpp @@ -30,37 +30,37 @@ OCCIServantLocator::locate(const Ice::Current& current, Ice::LocalObjectPtr& coo try { - // - // Extract SQL type from target object - // - string sqlType = Ref(ref)->getSQLTypeName(); + // + // Extract SQL type from target object + // + string sqlType = Ref(ref)->getSQLTypeName(); - // - // Create and return the servant, used only for this one operation - // - if(sqlType.find("EMP_T") != string::npos) - { - return new EmpI(ref, con, _factory); - } - else if(sqlType.find("DEPT_T") != string::npos) - { - return new DeptI(ref, con, _factory); - } - else - { - return 0; - } + // + // Create and return the servant, used only for this one operation + // + if(sqlType.find("EMP_T") != string::npos) + { + return new EmpI(ref, con, _factory); + } + else if(sqlType.find("DEPT_T") != string::npos) + { + return new DeptI(ref, con, _factory); + } + else + { + return 0; + } } catch(const SQLException& sqle) { - if(sqle.getErrorCode() == 21700) - { - return 0; - } - else - { - throw; - } + if(sqle.getErrorCode() == 21700) + { + return 0; + } + else + { + throw; + } } } diff --git a/cpp/demo/Database/Oracle/occi/Server.cpp b/cpp/demo/Database/Oracle/occi/Server.cpp index aff2f171ea3..8df9dceb43f 100644 --- a/cpp/demo/Database/Oracle/occi/Server.cpp +++ b/cpp/demo/Database/Oracle/occi/Server.cpp @@ -47,42 +47,42 @@ HRServer::run(int argc, char* argv[]) try { - env = Environment::createEnvironment(Environment::Mode(Environment::THREADED_MUTEXED | Environment::OBJECT)); - DbTypesMap(env); - - pool = env->createStatelessConnectionPool(username, password, connectString, 5, 2, 1, - StatelessConnectionPool::HOMOGENEOUS); + env = Environment::createEnvironment(Environment::Mode(Environment::THREADED_MUTEXED | Environment::OBJECT)); + DbTypesMap(env); + + pool = env->createStatelessConnectionPool(username, password, connectString, 5, 2, 1, + StatelessConnectionPool::HOMOGENEOUS); - Ice::ObjectAdapterPtr adapter = communicator()->createObjectAdapter("HR"); - - DeptFactoryIPtr factory = new DeptFactoryI(env, pool, category); - adapter->addServantLocator(new OCCIServantLocator(factory), category); + Ice::ObjectAdapterPtr adapter = communicator()->createObjectAdapter("HR"); + + DeptFactoryIPtr factory = new DeptFactoryI(env, pool, category); + adapter->addServantLocator(new OCCIServantLocator(factory), category); - adapter->add(factory, communicator()->stringToIdentity("DeptFactory")); - - adapter->activate(); - communicator()->waitForShutdown(); + adapter->add(factory, communicator()->stringToIdentity("DeptFactory")); + + adapter->activate(); + communicator()->waitForShutdown(); } catch(...) { - if(pool != 0) - { - env->terminateStatelessConnectionPool(pool); - } - if(env != 0) - { - Environment::terminateEnvironment(env); - } - throw; + if(pool != 0) + { + env->terminateStatelessConnectionPool(pool); + } + if(env != 0) + { + Environment::terminateEnvironment(env); + } + throw; } if(pool != 0) { - env->terminateStatelessConnectionPool(pool); + env->terminateStatelessConnectionPool(pool); } if(env != 0) { - Environment::terminateEnvironment(env); + Environment::terminateEnvironment(env); } return EXIT_SUCCESS; } diff --git a/cpp/demo/Database/Oracle/occi/Util.cpp b/cpp/demo/Database/Oracle/occi/Util.cpp index 44c6dda8912..7b6a109e494 100644 --- a/cpp/demo/Database/Oracle/occi/Util.cpp +++ b/cpp/demo/Database/Oracle/occi/Util.cpp @@ -28,11 +28,11 @@ ConnectionHolder::commit() _txDone = true; try { - _con->commit(); + _con->commit(); } catch(const SQLException& e) { - throw HR::SqlException(e.what()); + throw HR::SqlException(e.what()); } } @@ -42,11 +42,11 @@ ConnectionHolder::rollback() _txDone = true; try { - _con->rollback(); + _con->rollback(); } catch(const SQLException& e) { - throw HR::SqlException(e.what()); + throw HR::SqlException(e.what()); } } @@ -54,19 +54,19 @@ ConnectionHolder::~ConnectionHolder() { if(!_txDone) { - _txDone = true; - try - { - _con->rollback(); - } - catch(const std::exception&) - { - } + _txDone = true; + try + { + _con->rollback(); + } + catch(const std::exception&) + { + } } try { - _pool->releaseConnection(_con); + _pool->releaseConnection(_con); } catch(const std::exception&) { @@ -104,15 +104,15 @@ encodeRef(const RefAny& ref, Environment* env) if(status == OCI_SUCCESS) { - result.assign(reinterpret_cast(buffer), length); + result.assign(reinterpret_cast(buffer), length); } else { - cerr << "encodeRef failed: "; - sb4 errcode = 0; - OraText buf[512]; - OCIErrorGet(error, 1, 0, &errcode, buf, 512, OCI_HTYPE_ERROR); - cerr << reinterpret_cast(buf) << endl; + cerr << "encodeRef failed: "; + sb4 errcode = 0; + OraText buf[512]; + OCIErrorGet(error, 1, 0, &errcode, buf, 512, OCI_HTYPE_ERROR); + cerr << reinterpret_cast(buf) << endl; } OCIHandleFree(error, OCI_HTYPE_ERROR); @@ -128,26 +128,26 @@ decodeRef(const string& str, Environment* env, Connection* con) OCIHandleAlloc(env->getOCIEnvironment(), reinterpret_cast(&error), OCI_HTYPE_ERROR, 0, 0); sword status = OCIRefFromHex(env->getOCIEnvironment(), error, - con->getOCIServiceContext(), - reinterpret_cast(str.c_str()), str.length(), - &ref); + con->getOCIServiceContext(), + reinterpret_cast(str.c_str()), str.length(), + &ref); if(status == OCI_SUCCESS) - { - OCIHandleFree(error, OCI_HTYPE_ERROR); - return RefAny(con, ref); + { + OCIHandleFree(error, OCI_HTYPE_ERROR); + return RefAny(con, ref); } else { - cerr << "decodeRef failed: "; - sb4 errcode = 0; - OraText buf[512]; - OCIErrorGet(error, 1, 0, &errcode, buf, 512, OCI_HTYPE_ERROR); - cerr << reinterpret_cast(buf) << endl; - - OCIHandleFree(error, OCI_HTYPE_ERROR); - throw Ice::ObjectNotExistException(__FILE__, __LINE__); + cerr << "decodeRef failed: "; + sb4 errcode = 0; + OraText buf[512]; + OCIErrorGet(error, 1, 0, &errcode, buf, 512, OCI_HTYPE_ERROR); + cerr << reinterpret_cast(buf) << endl; + + OCIHandleFree(error, OCI_HTYPE_ERROR); + throw Ice::ObjectNotExistException(__FILE__, __LINE__); } } diff --git a/cpp/demo/Database/Oracle/occi/Util.h b/cpp/demo/Database/Oracle/occi/Util.h index dbe44d6b9c3..2655b2281ec 100644 --- a/cpp/demo/Database/Oracle/occi/Util.h +++ b/cpp/demo/Database/Oracle/occi/Util.h @@ -25,7 +25,7 @@ public: oracle::occi::Connection* connection() const { - return _con; + return _con; } void commit(); @@ -55,7 +55,7 @@ public: oracle::occi::Statement* statement() const { - return _stmt; + return _stmt; } private: diff --git a/cpp/demo/Database/Oracle/proc/Client.cpp b/cpp/demo/Database/Oracle/proc/Client.cpp index 2260decdd0b..569fdf620fc 100644 --- a/cpp/demo/Database/Oracle/proc/Client.cpp +++ b/cpp/demo/Database/Oracle/proc/Client.cpp @@ -63,32 +63,32 @@ HRClient::HRClient() : _currentMenu(rootMenu) { _commonCommands = - "dept : set department as the current department\n" - "emp : set employee as the current employee\n" - "exit or quit: exit client\n" - "help: print this list of commands\n" - "root: go back to the root menu\n"; + "dept : set department as the current department\n" + "emp : set employee as the current employee\n" + "exit or quit: exit client\n" + "help: print this list of commands\n" + "root: go back to the root menu\n"; _rootCommands = - "create: create a new department\n" - "find : find the department(s) with the given name\n" - "list: list all departments\n"; + "create: create a new department\n" + "find : find the department(s) with the given name\n" + "list: list all departments\n"; - + _deptCommands = - "create: create a new employee in this department\n" - "find : find employee(s) named in this department\n" - "list: list all employees in this department\n" - "ping: ping this department\n" - "remove: remove this department\n" - "show: describe this department\n" - "update : update this department\n"; + "create: create a new employee in this department\n" + "find : find employee(s) named in this department\n" + "list: list all employees in this department\n" + "ping: ping this department\n" + "remove: remove this department\n" + "show: describe this department\n" + "update : update this department\n"; _empCommands = - "ping: ping this employee\n" - "remove: remove this employee\n" - "show: describe this employee\n" - "update : update this employee\n"; + "ping: ping this employee\n" + "remove: remove this employee\n" + "show: describe this employee\n" + "update : update this employee\n"; } void @@ -96,13 +96,13 @@ HRClient::checkEof(const string& command) const { if(!cin.eof()) { - string extra; - getline(cin, extra); - if(extra.size() > 0) - { - cout << "Warning: ignoring extra args '" << extra - << "' for '" << command << "'" << endl; - } + string extra; + getline(cin, extra); + if(extra.size() > 0) + { + cout << "Warning: ignoring extra args '" << extra + << "' for '" << command << "'" << endl; + } } } @@ -111,10 +111,10 @@ HRClient::checkCin(const string& command) const { if(!cin) { - cout << "Error: failed to read arguments for '" << command << "'" << endl; - cin.clear(); - cin.ignore(numeric_limits::max(), '\n'); - return false; + cout << "Error: failed to read arguments for '" << command << "'" << endl; + cin.clear(); + cin.ignore(numeric_limits::max(), '\n'); + return false; } checkEof(command); return true; @@ -124,7 +124,7 @@ void HRClient::invalidCommand(const string& command) const { cout << "Invalid command '" << command << "'. " - "Type 'help' for help." << endl; + "Type 'help' for help." << endl; cin.ignore(numeric_limits::max(), '\n'); } @@ -136,21 +136,21 @@ HRClient::help() const switch(_currentMenu) { - case rootMenu: - { - cout << _rootCommands; - break; - } - case deptMenu: - { - cout << _deptCommands; - break; - } - case empMenu: - { - cout << _empCommands; - break; - } + case rootMenu: + { + cout << _rootCommands; + break; + } + case deptMenu: + { + cout << _deptCommands; + break; + } + case empMenu: + { + cout << _empCommands; + break; + } } cout << "--- Common to all menus ---\n"; cout << _commonCommands << endl; @@ -163,8 +163,8 @@ HRClient::run(int argc, char* argv[]) _factory = DeptFactoryPrx::checkedCast(base); if(_factory == 0) { - cerr << argv[0] << ": invalid proxy" << endl; - return EXIT_FAILURE; + cerr << argv[0] << ": invalid proxy" << endl; + return EXIT_FAILURE; } Ice::EndpointSeq endpoints = _factory->ice_getEndpoints(); @@ -178,102 +178,102 @@ HRClient::run(int argc, char* argv[]) do { - cout << "==> "; - cin >> command; - - if(!cin) - { - break; - } - - try - { - - // - // Common commands - // - if(command == "dept") - { - int deptno; - cin >> deptno; - if(checkCin(command)) - { - _currentDept = DeptPrx::uncheckedCast(_factory->findDeptByNo(deptno)); - if(_currentDept != 0) - { - _currentMenu = deptMenu; - } - else - { - cout << "There is no department with deptno " << deptno << endl; - } - } - } - else if(command == "emp") - { - int empno; - cin >> empno; - if(checkCin(command)) - { - _currentEmp = EmpPrx::uncheckedCast(_factory->findEmpByNo(empno)); - if(_currentEmp != 0) - { - _currentMenu = empMenu; - } - else - { - cout << "There is no employee with empno " << empno << endl; - } - } - } - else if(command == "exit" || command == "quit") - { - checkEof(command); - break; - } - else if(command == "help") - { - checkEof(command); - help(); - } - else if(command == "root") - { - checkEof(command); - _currentMenu = rootMenu; - } - else if(_currentMenu == rootMenu) - { - doRootMenu(command); - } - else if(_currentMenu == deptMenu) - { - doDeptMenu(command); - } - else if(_currentMenu == empMenu) - { - doEmpMenu(command); - } - else - { - assert(0); - } - } - catch(const SqlException& e) - { - cout << "Caught a SqlException: " << e.reason << endl; - } - catch(const IceUtil::Exception& e) - { - cout << "Caught an Ice exception: " << e << endl; - } - catch(const std::exception& e) - { - cout << "Caught a std::exception: " << e.what() << endl; - } - catch(...) - { - cout << "Caught an unknown exception" << endl; - } + cout << "==> "; + cin >> command; + + if(!cin) + { + break; + } + + try + { + + // + // Common commands + // + if(command == "dept") + { + int deptno; + cin >> deptno; + if(checkCin(command)) + { + _currentDept = DeptPrx::uncheckedCast(_factory->findDeptByNo(deptno)); + if(_currentDept != 0) + { + _currentMenu = deptMenu; + } + else + { + cout << "There is no department with deptno " << deptno << endl; + } + } + } + else if(command == "emp") + { + int empno; + cin >> empno; + if(checkCin(command)) + { + _currentEmp = EmpPrx::uncheckedCast(_factory->findEmpByNo(empno)); + if(_currentEmp != 0) + { + _currentMenu = empMenu; + } + else + { + cout << "There is no employee with empno " << empno << endl; + } + } + } + else if(command == "exit" || command == "quit") + { + checkEof(command); + break; + } + else if(command == "help") + { + checkEof(command); + help(); + } + else if(command == "root") + { + checkEof(command); + _currentMenu = rootMenu; + } + else if(_currentMenu == rootMenu) + { + doRootMenu(command); + } + else if(_currentMenu == deptMenu) + { + doDeptMenu(command); + } + else if(_currentMenu == empMenu) + { + doEmpMenu(command); + } + else + { + assert(0); + } + } + catch(const SqlException& e) + { + cout << "Caught a SqlException: " << e.reason << endl; + } + catch(const IceUtil::Exception& e) + { + cout << "Caught an Ice exception: " << e << endl; + } + catch(const std::exception& e) + { + cout << "Caught a std::exception: " << e.what() << endl; + } + catch(...) + { + cout << "Caught an unknown exception" << endl; + } } while(cin.good()); @@ -285,38 +285,38 @@ HRClient::doRootMenu(const string& command) const { if(command == "create") { - checkEof(command); - cout << "Please enter: deptno dname loc ==> "; - int deptno; - DeptDesc desc; - cin >> deptno >> desc.dname >> desc.loc; - - desc.dname = unquote(desc.dname); - desc.loc = unquote(desc.loc); - - if(checkCin("create parameters")) - { - _factory->createDept(deptno, desc); - cout << "Created new department number " << deptno << endl; - } + checkEof(command); + cout << "Please enter: deptno dname loc ==> "; + int deptno; + DeptDesc desc; + cin >> deptno >> desc.dname >> desc.loc; + + desc.dname = unquote(desc.dname); + desc.loc = unquote(desc.loc); + + if(checkCin("create parameters")) + { + _factory->createDept(deptno, desc); + cout << "Created new department number " << deptno << endl; + } } else if(command == "find") { - string name; - cin >> name; - if(checkCin(command)) - { - printDepts(_factory->findByName(name)); - } + string name; + cin >> name; + if(checkCin(command)) + { + printDepts(_factory->findByName(name)); + } } else if(command == "list") { - checkEof(command); - printDepts(_factory->findAll()); + checkEof(command); + printDepts(_factory->findAll()); } else { - invalidCommand(command); + invalidCommand(command); } } @@ -325,84 +325,84 @@ HRClient::doDeptMenu(const string& command) const { if(command == "create") { - checkEof(command); - cout << "Please enter: empno ename job mgr(empno) hiredate sal comm ==> "; - int empno; - int mgrEmpno; - EmpDesc desc; - cin >> empno >> desc.ename >> desc.job >> mgrEmpno >> desc.hiredate >> desc.sal >> desc.comm; - - desc.ename = unquote(desc.ename); - desc.job = unquote(desc.job); - - if(mgrEmpno != 0) - { - desc.mgr = _factory->findEmpByNo(mgrEmpno); - if(desc.mgr == 0) - { - cout << "Manager #" << mgrEmpno << " does not exist: clearing manager" << endl; - } - } - desc.hiredate = unquote(desc.hiredate); - desc.sal = unquote(desc.sal); - desc.comm = unquote(desc.comm); - - desc.edept = _currentDept; - - if(checkCin("create parameters")) - { - _currentDept->createEmp(empno, desc); - cout << "Created new employee number " << empno << endl; - } + checkEof(command); + cout << "Please enter: empno ename job mgr(empno) hiredate sal comm ==> "; + int empno; + int mgrEmpno; + EmpDesc desc; + cin >> empno >> desc.ename >> desc.job >> mgrEmpno >> desc.hiredate >> desc.sal >> desc.comm; + + desc.ename = unquote(desc.ename); + desc.job = unquote(desc.job); + + if(mgrEmpno != 0) + { + desc.mgr = _factory->findEmpByNo(mgrEmpno); + if(desc.mgr == 0) + { + cout << "Manager #" << mgrEmpno << " does not exist: clearing manager" << endl; + } + } + desc.hiredate = unquote(desc.hiredate); + desc.sal = unquote(desc.sal); + desc.comm = unquote(desc.comm); + + desc.edept = _currentDept; + + if(checkCin("create parameters")) + { + _currentDept->createEmp(empno, desc); + cout << "Created new employee number " << empno << endl; + } } else if(command == "find") { - string name; - cin >> name; - if(checkCin(command)) - { - printEmps(_currentDept->findByName(name)); - } + string name; + cin >> name; + if(checkCin(command)) + { + printEmps(_currentDept->findByName(name)); + } } else if(command == "list") { - checkEof(command); - printEmps(_currentDept->findAll()); + checkEof(command); + printEmps(_currentDept->findAll()); } else if(command == "ping") { - checkEof(command); - _currentDept->ice_ping(); - cout << "ice_ping: success!" << endl; + checkEof(command); + _currentDept->ice_ping(); + cout << "ice_ping: success!" << endl; } else if(command == "remove") { - checkEof(command); - _currentDept->remove(); + checkEof(command); + _currentDept->remove(); } else if(command == "show") { - checkEof(command); - DeptDesc desc = _currentDept->getDesc(); - cout << "deptno: " << desc.deptno << endl; - cout << "dname: " << quote(desc.dname) << endl; - cout << "loc: " << quote(desc.loc) << endl; + checkEof(command); + DeptDesc desc = _currentDept->getDesc(); + cout << "deptno: " << desc.deptno << endl; + cout << "dname: " << quote(desc.dname) << endl; + cout << "loc: " << quote(desc.loc) << endl; } else if(command == "update") { - string field; - string newValue; - cin >> field >> newValue; - newValue = unquote(newValue); - - if(checkCin("update " + field)) - { - _currentDept->updateField(field, newValue); - } + string field; + string newValue; + cin >> field >> newValue; + newValue = unquote(newValue); + + if(checkCin("update " + field)) + { + _currentDept->updateField(field, newValue); + } } else { - invalidCommand(command); + invalidCommand(command); } } @@ -411,80 +411,80 @@ HRClient::doEmpMenu(const string& command) const { if(command == "ping") { - checkEof(command); - _currentEmp->ice_ping(); - cout << "ice_ping: success!" << endl; + checkEof(command); + _currentEmp->ice_ping(); + cout << "ice_ping: success!" << endl; } else if(command == "remove") { - checkEof(command); - _currentEmp->remove(); + checkEof(command); + _currentEmp->remove(); } else if(command == "show") { - checkEof(command); - EmpDesc desc = _currentEmp->getDesc(); - cout << "empno: " << desc.empno << endl; - cout << "ename: " << quote(desc.ename) << endl; - cout << "job: " << quote(desc.job) << endl; - cout << "mgr: "; - if(desc.mgr == 0) - { - cout << "" << endl; - } - else - { - cout << desc.mgr->getDesc().empno << endl; - } - cout << "hiredate: " << quote(desc.hiredate) << endl; - cout << "sal: " << quote(desc.sal) << endl; - cout << "comm: " << quote(desc.comm) << endl; - cout << "dept: "; - if(desc.edept == 0) - { - cout << "" << endl; - } - else - { - cout << desc.edept->getDesc().deptno << endl; - } + checkEof(command); + EmpDesc desc = _currentEmp->getDesc(); + cout << "empno: " << desc.empno << endl; + cout << "ename: " << quote(desc.ename) << endl; + cout << "job: " << quote(desc.job) << endl; + cout << "mgr: "; + if(desc.mgr == 0) + { + cout << "" << endl; + } + else + { + cout << desc.mgr->getDesc().empno << endl; + } + cout << "hiredate: " << quote(desc.hiredate) << endl; + cout << "sal: " << quote(desc.sal) << endl; + cout << "comm: " << quote(desc.comm) << endl; + cout << "dept: "; + if(desc.edept == 0) + { + cout << "" << endl; + } + else + { + cout << desc.edept->getDesc().deptno << endl; + } } else if(command == "update") { - string field; - cin >> field; - if(field == "mgr") - { - int mgr; - cin >> mgr; - if(checkCin("update mgr")) - { - _currentEmp->updateMgr(mgr); - } - } - else if(field == "dept") - { - int deptno; - cin >> deptno; - if(checkCin("update dept")) - { - _currentEmp->updateDept(deptno); - } - } - else - { - string newValue; - cin >> newValue; - newValue = unquote(newValue); - if(checkCin("update " + field)) - { - _currentEmp->updateField(field, newValue); - } - } + string field; + cin >> field; + if(field == "mgr") + { + int mgr; + cin >> mgr; + if(checkCin("update mgr")) + { + _currentEmp->updateMgr(mgr); + } + } + else if(field == "dept") + { + int deptno; + cin >> deptno; + if(checkCin("update dept")) + { + _currentEmp->updateDept(deptno); + } + } + else + { + string newValue; + cin >> newValue; + newValue = unquote(newValue); + if(checkCin("update " + field)) + { + _currentEmp->updateField(field, newValue); + } + } } else { - invalidCommand(command); + invalidCommand(command); } } @@ -494,15 +494,15 @@ HRClient::printDepts(const DeptPrxSeq& depts) const cout << "Deptno\t Dname\t Loc" << endl; if(depts.size() == 0) { - cout << "" << endl; + cout << "" << endl; } else { - for(DeptPrxSeq::const_iterator p = depts.begin(); p != depts.end(); ++p) - { - HR::DeptDesc desc = (*p)->getDesc(); - cout << desc.deptno << "\t " << desc.dname << "\t " << desc.loc << endl; - } + for(DeptPrxSeq::const_iterator p = depts.begin(); p != depts.end(); ++p) + { + HR::DeptDesc desc = (*p)->getDesc(); + cout << desc.deptno << "\t " << desc.dname << "\t " << desc.loc << endl; + } } } @@ -512,15 +512,15 @@ HRClient::printEmps(const EmpPrxSeq& emps) const cout << "Empno\t Ename" << endl; if(emps.size() == 0) { - cout << "" << endl; + cout << "" << endl; } else { - for(EmpPrxSeq::const_iterator p = emps.begin(); p != emps.end(); ++p) - { - HR::EmpDesc desc = (*p)->getDesc(); - cout << desc.empno << "\t " << desc.ename << endl; - } + for(EmpPrxSeq::const_iterator p = emps.begin(); p != emps.end(); ++p) + { + HR::EmpDesc desc = (*p)->getDesc(); + cout << desc.empno << "\t " << desc.ename << endl; + } } } @@ -530,11 +530,11 @@ HRClient::quote(const string& str) { if(str == "") { - return "''"; + return "''"; } else { - return str; + return str; } } @@ -544,10 +544,10 @@ HRClient::unquote(const string& str) { if(str == "''") { - return ""; + return ""; } else { - return str; + return str; } } diff --git a/cpp/demo/Database/Oracle/proc/CurrentSqlContext.pc b/cpp/demo/Database/Oracle/proc/CurrentSqlContext.pc index 862196b8718..35e27fc3749 100644 --- a/cpp/demo/Database/Oracle/proc/CurrentSqlContext.pc +++ b/cpp/demo/Database/Oracle/proc/CurrentSqlContext.pc @@ -38,7 +38,7 @@ class Notification : public Ice::ThreadNotification public: Notification(size_t index) : - _index(index) + _index(index) { } @@ -48,35 +48,35 @@ public: virtual void stop() { - if(_current != 0 && _index < _current->size()) - { + if(_current != 0 && _index < _current->size()) + { #ifdef TRACE - cerr << "Disconnecting from Oracle in thread " << IceUtil::ThreadControl().id() << endl; + cerr << "Disconnecting from Oracle in thread " << IceUtil::ThreadControl().id() << endl; #endif - EXEC SQL BEGIN DECLARE SECTION; - sql_context ctx = (*_current)[_index]; - EXEC SQL END DECLARE SECTION; - - if(ctx != 0) - { - (*_current)[_index] = 0; - EXEC SQL CONTEXT USE :ctx; - - sqlca sqlca; - EXEC SQL ROLLBACK RELEASE; - EXEC SQL CONTEXT FREE :ctx; - } - - if(find_if(_current->begin(), _current->end(), bind2nd(not_equal_to(), static_cast(0))) - == _current->end()) - { + EXEC SQL BEGIN DECLARE SECTION; + sql_context ctx = (*_current)[_index]; + EXEC SQL END DECLARE SECTION; + + if(ctx != 0) + { + (*_current)[_index] = 0; + EXEC SQL CONTEXT USE :ctx; + + sqlca sqlca; + EXEC SQL ROLLBACK RELEASE; + EXEC SQL CONTEXT FREE :ctx; + } + + if(find_if(_current->begin(), _current->end(), bind2nd(not_equal_to(), static_cast(0))) + == _current->end()) + { #ifdef TRACE - cerr << "Deleting _current in thread " << IceUtil::ThreadControl().id() << endl; + cerr << "Deleting _current in thread " << IceUtil::ThreadControl().id() << endl; #endif - delete _current; - _current = 0; - } - } + delete _current; + _current = 0; + } + } } private: @@ -90,8 +90,8 @@ CurrentSqlContext::CurrentSqlContext(const string& connectInfo) : _connectInfo(connectInfo) { { - IceUtil::StaticMutex::Lock lock(IceUtil::globalMutex); - _index = _currentIndex++; + IceUtil::StaticMutex::Lock lock(IceUtil::globalMutex); + _index = _currentIndex++; } _hook = new Notification(_index); } @@ -106,11 +106,11 @@ CurrentSqlContext::operator sql_context() const { if(_current == 0) { - _current = new std::vector(_index + 1); + _current = new std::vector(_index + 1); } if(_index >= _current->size()) { - _current->resize(_index + 1); + _current->resize(_index + 1); } EXEC SQL BEGIN DECLARE SECTION; @@ -123,18 +123,18 @@ CurrentSqlContext::operator sql_context() const if(ctx == 0) { #ifdef TRACE - cerr << "Connecting to Oracle in thread " << IceUtil::ThreadControl().id() << endl; + cerr << "Connecting to Oracle in thread " << IceUtil::ThreadControl().id() << endl; #endif - // - // Allocate and connect - // - sqlca sqlca; - - EXEC SQL CONTEXT ALLOCATE :ctx; - EXEC SQL CONTEXT USE :ctx; - EXEC SQL CONNECT :connectInfo; - - (*_current)[_index] = ctx; + // + // Allocate and connect + // + sqlca sqlca; + + EXEC SQL CONTEXT ALLOCATE :ctx; + EXEC SQL CONTEXT USE :ctx; + EXEC SQL CONNECT :connectInfo; + + (*_current)[_index] = ctx; } return ctx; diff --git a/cpp/demo/Database/Oracle/proc/DeptFactoryI.pc b/cpp/demo/Database/Oracle/proc/DeptFactoryI.pc index 1d72b58d0db..e6bcdd56145 100644 --- a/cpp/demo/Database/Oracle/proc/DeptFactoryI.pc +++ b/cpp/demo/Database/Oracle/proc/DeptFactoryI.pc @@ -62,13 +62,13 @@ DeptFactoryI::findAll(const Ice::Current& current) for(;;) { - EXEC SQL FETCH depCursor1 INTO :deptno; + EXEC SQL FETCH depCursor1 INTO :deptno; - Ice::Identity deptId; - deptId.category = _deptCategory; - deptId.name = encodeName(deptno); + Ice::Identity deptId; + deptId.category = _deptCategory; + deptId.name = encodeName(deptno); - result.push_back(HR::DeptPrx::uncheckedCast(current.adapter->createProxy(deptId))); + result.push_back(HR::DeptPrx::uncheckedCast(current.adapter->createProxy(deptId))); } EXEC SQL CLOSE depCursor1; @@ -94,13 +94,13 @@ DeptFactoryI::findByName(const string& name, const Ice::Current& current) for(;;) { - EXEC SQL FETCH depCursor2 INTO :deptno; + EXEC SQL FETCH depCursor2 INTO :deptno; - Ice::Identity deptId; - deptId.category = _deptCategory; - deptId.name = encodeName(deptno); + Ice::Identity deptId; + deptId.category = _deptCategory; + deptId.name = encodeName(deptno); - result.push_back(HR::DeptPrx::uncheckedCast(current.adapter->createProxy(deptId))); + result.push_back(HR::DeptPrx::uncheckedCast(current.adapter->createProxy(deptId))); } EXEC SQL CLOSE depCursor2; @@ -121,11 +121,11 @@ DeptFactoryI::findDeptByNo(int deptno, const Ice::Current& current) // try { - prx->ice_ping(); + prx->ice_ping(); } catch(const Ice::ObjectNotExistException&) { - return 0; + return 0; } return HR::DeptPrx::uncheckedCast(prx); @@ -144,11 +144,11 @@ DeptFactoryI::findEmpByNo(int empno, const Ice::Current& current) // try { - prx->ice_ping(); + prx->ice_ping(); } catch(const Ice::ObjectNotExistException&) { - return 0; + return 0; } return HR::EmpPrx::uncheckedCast(prx); diff --git a/cpp/demo/Database/Oracle/proc/DeptI.pc b/cpp/demo/Database/Oracle/proc/DeptI.pc index 7a9d2c63f1c..203ab110a5a 100644 --- a/cpp/demo/Database/Oracle/proc/DeptI.pc +++ b/cpp/demo/Database/Oracle/proc/DeptI.pc @@ -38,7 +38,7 @@ DeptI::ice_ping(const Ice::Current& current) const if(count == 0) { - throw Ice::ObjectNotExistException(__FILE__, __LINE__); + throw Ice::ObjectNotExistException(__FILE__, __LINE__); } } @@ -64,19 +64,19 @@ DeptI::createEmp(int key, const HR::EmpDesc& desc, const Ice::Current& current) if(desc.mgr == 0) { - // - // mgr is NULL - // - mgrInd = -1; + // + // mgr is NULL + // + mgrInd = -1; } else { - mgr = decodeName(desc.mgr->ice_getIdentity().name); + mgr = decodeName(desc.mgr->ice_getIdentity().name); } EXEC SQL CONTEXT USE :ctx; EXEC SQL INSERT INTO EMP(empno, ename, job, mgr, hiredate, sal, comm, deptno) - VALUES(:empno, :ename, :job, :mgr:mgrInd, :hiredate, :sal, :comm, :deptno); + VALUES(:empno, :ename, :job, :mgr:mgrInd, :hiredate, :sal, :comm, :deptno); EXEC SQL COMMIT; Ice::Identity empId; @@ -107,10 +107,10 @@ DeptI::getDesc(const Ice::Current& current) if(dnameInd >= 0) { - // - // Should log a warning if > 0! - // - result.dname = dname; + // + // Should log a warning if > 0! + // + result.dname = dname; } // // else null @@ -118,10 +118,10 @@ DeptI::getDesc(const Ice::Current& current) if(locInd >= 0) { - // - // Should log a warning if > 0! - // - result.loc = loc; + // + // Should log a warning if > 0! + // + result.loc = loc; } // // else null @@ -134,7 +134,7 @@ void DeptI::updateField(const string& field, const string& newValue, const Ice::Current& current) { const string updateDeptStr = - "UPDATE DEPT SET " + field + " = '" + newValue + "' WHERE DEPTNO = " + current.id.name; + "UPDATE DEPT SET " + field + " = '" + newValue + "' WHERE DEPTNO = " + current.id.name; sqlca sqlca; EXEC SQL BEGIN DECLARE SECTION; @@ -185,13 +185,13 @@ DeptI::findAll(const Ice::Current& current) for(;;) { - EXEC SQL FETCH empCursor1 INTO :empno; + EXEC SQL FETCH empCursor1 INTO :empno; - Ice::Identity empId; - empId.category = _empCategory; - empId.name = encodeName(empno); + Ice::Identity empId; + empId.category = _empCategory; + empId.name = encodeName(empno); - result.push_back(HR::EmpPrx::uncheckedCast(current.adapter->createProxy(empId))); + result.push_back(HR::EmpPrx::uncheckedCast(current.adapter->createProxy(empId))); } EXEC SQL CLOSE empCursor1; @@ -218,13 +218,13 @@ DeptI::findByName(const string& name, const Ice::Current& current) for(;;) { - EXEC SQL FETCH empCursor2 INTO :empno; + EXEC SQL FETCH empCursor2 INTO :empno; - Ice::Identity empId; - empId.category = _empCategory; - empId.name = encodeName(empno); + Ice::Identity empId; + empId.category = _empCategory; + empId.name = encodeName(empno); - result.push_back(HR::EmpPrx::uncheckedCast(current.adapter->createProxy(empId))); + result.push_back(HR::EmpPrx::uncheckedCast(current.adapter->createProxy(empId))); } EXEC SQL CLOSE empCursor2; diff --git a/cpp/demo/Database/Oracle/proc/EmpI.pc b/cpp/demo/Database/Oracle/proc/EmpI.pc index e74887a939d..5506d0d0d84 100644 --- a/cpp/demo/Database/Oracle/proc/EmpI.pc +++ b/cpp/demo/Database/Oracle/proc/EmpI.pc @@ -17,7 +17,7 @@ EXEC SQL WHENEVER NOT FOUND DO handleNotFound(current, ctx); using namespace std; EmpI::EmpI(const CurrentSqlContext& currentCtx, - const string& empCategory, const string& deptCategory) : + const string& empCategory, const string& deptCategory) : _currentCtx(currentCtx), _empCategory(empCategory), _deptCategory(deptCategory) @@ -40,7 +40,7 @@ EmpI::ice_ping(const Ice::Current& current) const if(count == 0) { - throw Ice::ObjectNotExistException(__FILE__, __LINE__); + throw Ice::ObjectNotExistException(__FILE__, __LINE__); } } @@ -69,7 +69,7 @@ EmpI::getDesc(const Ice::Current& current) EXEC SQL CONTEXT USE :ctx; EXEC SQL SELECT ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO - INTO :ename:enameInd, :job:jobInd, :mgr:mgrInd, :hiredate:hiredateInd, :sal:salInd, :comm:commInd, + INTO :ename:enameInd, :job:jobInd, :mgr:mgrInd, :hiredate:hiredateInd, :sal:salInd, :comm:commInd, :deptno:deptnoInd FROM EMP WHERE EMPNO = :empno; EXEC SQL COMMIT; @@ -79,37 +79,37 @@ EmpI::getDesc(const Ice::Current& current) if(enameInd >= 0) { - result.ename = ename; + result.ename = ename; } if(jobInd >= 0) { - result.job = job; + result.job = job; } if(mgrInd >= 0) { - Ice::Identity mgrId; - mgrId.name = encodeName(mgr); - mgrId.category = _empCategory; - result.mgr = HR::EmpPrx::uncheckedCast(current.adapter->createProxy(mgrId)); + Ice::Identity mgrId; + mgrId.name = encodeName(mgr); + mgrId.category = _empCategory; + result.mgr = HR::EmpPrx::uncheckedCast(current.adapter->createProxy(mgrId)); } if(hiredateInd >= 0) { - result.hiredate = hiredate; + result.hiredate = hiredate; } if(salInd >= 0) { - result.sal = sal; + result.sal = sal; } if(commInd >= 0) { - result.comm = comm; + result.comm = comm; } if(deptnoInd >= 0) { - Ice::Identity deptId; - deptId.name = encodeName(deptno); - deptId.category = _deptCategory; - result.edept = HR::DeptPrx::uncheckedCast(current.adapter->createProxy(deptId)); + Ice::Identity deptId; + deptId.name = encodeName(deptno); + deptId.category = _deptCategory; + result.edept = HR::DeptPrx::uncheckedCast(current.adapter->createProxy(deptId)); } return result; } @@ -118,7 +118,7 @@ void EmpI::updateField(const string& field, const string& newValue, const Ice::Current& current) { const string updateEmpStr = - "UPDATE EMP SET " + field + " = '" + newValue + "' WHERE EMPNO = " + current.id.name; + "UPDATE EMP SET " + field + " = '" + newValue + "' WHERE EMPNO = " + current.id.name; sqlca sqlca; EXEC SQL BEGIN DECLARE SECTION; diff --git a/cpp/demo/Database/Oracle/proc/Server.pc b/cpp/demo/Database/Oracle/proc/Server.pc index a0a0d80e083..bc325649259 100644 --- a/cpp/demo/Database/Oracle/proc/Server.pc +++ b/cpp/demo/Database/Oracle/proc/Server.pc @@ -34,18 +34,18 @@ class DefaultServantLocator : public Ice::ServantLocator public: DefaultServantLocator(const Ice::ObjectPtr& servant) : - _servant(servant) + _servant(servant) { } virtual Ice::ObjectPtr locate(const Ice::Current&, Ice::LocalObjectPtr&) { - return _servant; + return _servant; } virtual void finished(const Ice::Current& curr, - const Ice::ObjectPtr& servant, - const Ice::LocalObjectPtr& cookie) + const Ice::ObjectPtr& servant, + const Ice::LocalObjectPtr& cookie) { } @@ -70,7 +70,7 @@ main(int argc, char* argv[]) initData.properties->load("config.server"); const string connectInfo = initData.properties - ->getPropertyWithDefault("Oracle.ConnectInfo", "scott/tiger"); + ->getPropertyWithDefault("Oracle.ConnectInfo", "scott/tiger"); CurrentSqlContext currentCtx(connectInfo); initData.threadHook = currentCtx.getHook(); @@ -92,12 +92,12 @@ HRServer::run(int argc, char* argv[]) const string deptCategory = "Dept"; adapter->addServantLocator(new DefaultServantLocator(new EmpI(_currentCtx, empCategory, deptCategory)), - empCategory); + empCategory); adapter->addServantLocator(new DefaultServantLocator(new DeptI(_currentCtx, empCategory)), deptCategory); adapter->add(new DeptFactoryI(_currentCtx, deptCategory, empCategory), - communicator()->stringToIdentity("DeptFactory")); + communicator()->stringToIdentity("DeptFactory")); adapter->activate(); communicator()->waitForShutdown(); diff --git a/cpp/demo/Database/Oracle/proc/Util.pc b/cpp/demo/Database/Oracle/proc/Util.pc index 9e96d81d88a..6a3ab69c03d 100644 --- a/cpp/demo/Database/Oracle/proc/Util.pc +++ b/cpp/demo/Database/Oracle/proc/Util.pc @@ -57,8 +57,8 @@ decodeName(const string& name) is >> result; if(!is || !is.eof()) { - cerr << "Unable to decode " << name << endl; - throw Ice::ObjectNotExistException(__FILE__, __LINE__); + cerr << "Unable to decode " << name << endl; + throw Ice::ObjectNotExistException(__FILE__, __LINE__); } return result; } diff --git a/cpp/demo/Freeze/backup/Client.cpp b/cpp/demo/Freeze/backup/Client.cpp index 89008fa26b2..4630a15858f 100644 --- a/cpp/demo/Freeze/backup/Client.cpp +++ b/cpp/demo/Freeze/backup/Client.cpp @@ -38,51 +38,51 @@ main(int argc, char* argv[]) const int size = 10000; if(m.size() == 0) - { - cout << "********* Creating new map ***********" << endl; - Freeze::TransactionHolder txHolder(connection); - - IceUtil::Time time = IceUtil::Time::now(); - IceUtil::Int64 ms = time.toMilliSeconds(); - - for(int i = 0; i < size; ++i) - { - m.insert(IntLongMap::value_type(i, ms)); - } - txHolder.commit(); + { + cout << "********* Creating new map ***********" << endl; + Freeze::TransactionHolder txHolder(connection); + + IceUtil::Time time = IceUtil::Time::now(); + IceUtil::Int64 ms = time.toMilliSeconds(); + + for(int i = 0; i < size; ++i) + { + m.insert(IntLongMap::value_type(i, ms)); + } + txHolder.commit(); } cout << "Updating map" << endl; for(;;) { - int count = 0; - - Freeze::TransactionHolder txHolder(connection); - IceUtil::Time time = IceUtil::Time::now(); - IceUtil::Int64 ms = time.toMilliSeconds(); - - IntLongMap::iterator p = m.begin(); - IceUtil::Int64 oldMs = p->second; - do - { - if(p->second != oldMs) - { - cerr << "old time (ms) == " << oldMs << endl; - cerr << "current current (ms) == " << p->second << endl; - } - - test(p->second == oldMs); - p.set(ms); - count++; - } while(++p != m.end()); - - cout << "Read " << IceUtil::Time::milliSeconds(oldMs).toDateTime() << " in all records;" - << " updating with " << time.toDateTime() << " ... " << flush; - - txHolder.commit(); - cout << "done" << endl; - test(count == size); + int count = 0; + + Freeze::TransactionHolder txHolder(connection); + IceUtil::Time time = IceUtil::Time::now(); + IceUtil::Int64 ms = time.toMilliSeconds(); + + IntLongMap::iterator p = m.begin(); + IceUtil::Int64 oldMs = p->second; + do + { + if(p->second != oldMs) + { + cerr << "old time (ms) == " << oldMs << endl; + cerr << "current current (ms) == " << p->second << endl; + } + + test(p->second == oldMs); + p.set(ms); + count++; + } while(++p != m.end()); + + cout << "Read " << IceUtil::Time::milliSeconds(oldMs).toDateTime() << " in all records;" + << " updating with " << time.toDateTime() << " ... " << flush; + + txHolder.commit(); + cout << "done" << endl; + test(count == size); } connection->close(); diff --git a/cpp/demo/Freeze/bench/Client.cpp b/cpp/demo/Freeze/bench/Client.cpp index 07b95e14f38..67f71de2a2e 100644 --- a/cpp/demo/Freeze/bench/Client.cpp +++ b/cpp/demo/Freeze/bench/Client.cpp @@ -36,20 +36,20 @@ public: void start() { - _stopped = false; - _start = IceUtil::Time::now(); + _stopped = false; + _start = IceUtil::Time::now(); } IceUtil::Time stop() { - if(!_stopped) - { - _stopped = true; - _stop = IceUtil::Time::now(); - } + if(!_stopped) + { + _stopped = true; + _stop = IceUtil::Time::now(); + } - return _stop - _start; + return _stop - _start; } private: @@ -75,23 +75,23 @@ class RandomGenerator : public Generator public: RandomGenerator(int seed, int max) : - _max(max) + _max(max) { - srand(seed); + srand(seed); } virtual int next() { - return rand() % _max; + return rand() % _max; } virtual string toString() { - ostringstream os; - os << "random(" << _max << ")"; - return os.str(); + ostringstream os; + os << "random(" << _max << ")"; + return os.str(); } private: @@ -104,30 +104,30 @@ class SequentialGenerator : public Generator public: SequentialGenerator(int min, int max) : - _min(min), - _max(max), - _current(0) + _min(min), + _max(max), + _current(0) { } virtual int next() { - int n = _current; - ++_current; - if(_current > _max) - { - _current = _min; - } - return n; + int n = _current; + ++_current; + if(_current > _max) + { + _current = _min; + } + return n; } virtual string toString() { - ostringstream os; - os << ((_max - _min)+1); - return os.str(); + ostringstream os; + os << ((_max - _min)+1); + return os.str(); } private: @@ -157,68 +157,68 @@ private: void IntIntMapIndexTest(IndexedIntIntMap&); template void IntIntMapTest(const string& mapName, T* = 0) { - T m(_connection, mapName); - // - // Populate the database. - // - int i; - _watch.start(); - { - Freeze::TransactionHolder txHolder(_connection); - for(i = 0; i < _repetitions; ++i) - { + T m(_connection, mapName); + // + // Populate the database. + // + int i; + _watch.start(); + { + Freeze::TransactionHolder txHolder(_connection); + for(i = 0; i < _repetitions; ++i) + { #if defined(__BCPLUSPLUS__) || (defined(_MSC_VER) && (_MSC_VER < 1310)) - m.put(T::value_type(i, i)); + m.put(T::value_type(i, i)); #else - m.put(typename T::value_type(i, i)); + m.put(typename T::value_type(i, i)); #endif - } - txHolder.commit(); - } - IceUtil::Time total = _watch.stop(); - IceUtil::Time perRecord = total / _repetitions; - - cout << "\ttime for " << _repetitions << " writes: " << total * 1000 << "ms" << endl; - cout << "\ttime per write: " << perRecord * 1000 << "ms" << endl; - - // - // Read each record. - // - _watch.start(); - for(i = 0; i < _repetitions; ++i) - { - typename T::iterator p = m.find(i); - test(p != m.end()); - test(p->second == i); - } - total = _watch.stop(); - perRecord = total / _repetitions; - - cout << "\ttime for " << _repetitions << " reads: " << total * 1000 << "ms" << endl; - cout << "\ttime per read: " << perRecord * 1000 << "ms" << endl; - - // - // Optional index sub-test - // - IntIntMapIndexTest(m); - - // - // Remove each record. - // - _watch.start(); - { - Freeze::TransactionHolder txHolder(_connection); - for(i = 0; i < _repetitions; ++i) - { - m.erase(i); - } - txHolder.commit(); - } - total = _watch.stop(); - perRecord = total / _repetitions; - - cout << "\ttime for " << _repetitions << " removes: " << total * 1000 << "ms" << endl; - cout << "\ttime per remove: " << perRecord * 1000 << "ms" << endl; + } + txHolder.commit(); + } + IceUtil::Time total = _watch.stop(); + IceUtil::Time perRecord = total / _repetitions; + + cout << "\ttime for " << _repetitions << " writes: " << total * 1000 << "ms" << endl; + cout << "\ttime per write: " << perRecord * 1000 << "ms" << endl; + + // + // Read each record. + // + _watch.start(); + for(i = 0; i < _repetitions; ++i) + { + typename T::iterator p = m.find(i); + test(p != m.end()); + test(p->second == i); + } + total = _watch.stop(); + perRecord = total / _repetitions; + + cout << "\ttime for " << _repetitions << " reads: " << total * 1000 << "ms" << endl; + cout << "\ttime per read: " << perRecord * 1000 << "ms" << endl; + + // + // Optional index sub-test + // + IntIntMapIndexTest(m); + + // + // Remove each record. + // + _watch.start(); + { + Freeze::TransactionHolder txHolder(_connection); + for(i = 0; i < _repetitions; ++i) + { + m.erase(i); + } + txHolder.commit(); + } + total = _watch.stop(); + perRecord = total / _repetitions; + + cout << "\ttime for " << _repetitions << " removes: " << total * 1000 << "ms" << endl; + cout << "\ttime per remove: " << perRecord * 1000 << "ms" << endl; } @@ -227,22 +227,22 @@ private: void generatedReadWithIndex(IndexedIntIntMap&, int, const GeneratorPtr&); template void generatedRead(T& m, int reads , const GeneratorPtr& gen) { - _watch.start(); - for(int i = 0; i < reads; ++i) - { - int key = gen->next(); - typename T::iterator p = m.find(key); - test(p != m.end()); - test(p->second == key); - } - IceUtil::Time total = _watch.stop(); - IceUtil::Time perRecord = total / reads; - - cout << "\ttime for " << reads << " reads of " << gen->toString() << " records: " << total * 1000 << "ms" - << endl; - cout << "\ttime per read: " << perRecord * 1000 << "ms" << endl; - - generatedReadWithIndex(m, reads, gen); + _watch.start(); + for(int i = 0; i < reads; ++i) + { + int key = gen->next(); + typename T::iterator p = m.find(key); + test(p != m.end()); + test(p->second == key); + } + IceUtil::Time total = _watch.stop(); + IceUtil::Time perRecord = total / reads; + + cout << "\ttime for " << reads << " reads of " << gen->toString() << " records: " << total * 1000 << "ms" + << endl; + cout << "\ttime per read: " << perRecord * 1000 << "ms" << endl; + + generatedReadWithIndex(m, reads, gen); } @@ -251,81 +251,81 @@ private: void Struct1Struct2MapIndexTest(IndexedStruct1Struct2Map&); template void Struct1Struct2MapTest(const string& mapName, T* = 0) { - T m(_connection, mapName); - - // - // Populate the database. - // - Struct1 s1; - Struct2 s2; - int i; - _watch.start(); - { - Freeze::TransactionHolder txHolder(_connection); - for(i = 0; i < _repetitions; ++i) - { - s1.l = i; - ostringstream os; - os << i; - s2.s = os.str(); - s2.s1 = s1; + T m(_connection, mapName); + + // + // Populate the database. + // + Struct1 s1; + Struct2 s2; + int i; + _watch.start(); + { + Freeze::TransactionHolder txHolder(_connection); + for(i = 0; i < _repetitions; ++i) + { + s1.l = i; + ostringstream os; + os << i; + s2.s = os.str(); + s2.s1 = s1; #if defined(__BCPLUSPLUS__) || (defined(_MSC_VER) && (_MSC_VER < 1310)) - m.put(T::value_type(s1, s2)); + m.put(T::value_type(s1, s2)); #else - m.put(typename T::value_type(s1, s2)); + m.put(typename T::value_type(s1, s2)); #endif - } - txHolder.commit(); - } - IceUtil::Time total = _watch.stop(); - IceUtil::Time perRecord = total / _repetitions; - - cout << "\ttime for " << _repetitions << " writes: " << total * 1000 << "ms" << endl; - cout << "\ttime per write: " << perRecord * 1000 << "ms" << endl; - - // - // Read each record. - // - _watch.start(); - for(i = 0; i < _repetitions; ++i) - { - s1.l = i; - typename T::iterator p = m.find(s1); - test(p != m.end()); - ostringstream os; - os << i; - test(p->second.s == os.str()); - } - total = _watch.stop(); - perRecord = total / _repetitions; - - cout << "\ttime for " << _repetitions << " reads: " << total * 1000 << "ms" << endl; - cout << "\ttime per read: " << perRecord * 1000 << "ms" << endl; - - // - // Optional index test - // - Struct1Struct2MapIndexTest(m); - - // - // Remove each record. - // - _watch.start(); - { - Freeze::TransactionHolder txHolder(_connection); - for(i = 0; i < _repetitions; ++i) - { - s1.l = i; - m.erase(s1); - } - txHolder.commit(); - } - total = _watch.stop(); - perRecord = total / _repetitions; - - cout << "\ttime for " << _repetitions << " removes: " << total * 1000 << "ms" << endl; - cout << "\ttime per remove: " << perRecord * 1000 << "ms" << endl; + } + txHolder.commit(); + } + IceUtil::Time total = _watch.stop(); + IceUtil::Time perRecord = total / _repetitions; + + cout << "\ttime for " << _repetitions << " writes: " << total * 1000 << "ms" << endl; + cout << "\ttime per write: " << perRecord * 1000 << "ms" << endl; + + // + // Read each record. + // + _watch.start(); + for(i = 0; i < _repetitions; ++i) + { + s1.l = i; + typename T::iterator p = m.find(s1); + test(p != m.end()); + ostringstream os; + os << i; + test(p->second.s == os.str()); + } + total = _watch.stop(); + perRecord = total / _repetitions; + + cout << "\ttime for " << _repetitions << " reads: " << total * 1000 << "ms" << endl; + cout << "\ttime per read: " << perRecord * 1000 << "ms" << endl; + + // + // Optional index test + // + Struct1Struct2MapIndexTest(m); + + // + // Remove each record. + // + _watch.start(); + { + Freeze::TransactionHolder txHolder(_connection); + for(i = 0; i < _repetitions; ++i) + { + s1.l = i; + m.erase(s1); + } + txHolder.commit(); + } + total = _watch.stop(); + perRecord = total / _repetitions; + + cout << "\ttime for " << _repetitions << " removes: " << total * 1000 << "ms" << endl; + cout << "\ttime per remove: " << perRecord * 1000 << "ms" << endl; } @@ -334,80 +334,80 @@ private: void Struct1Class1MapIndexTest(IndexedStruct1Class1Map&); template void Struct1Class1MapTest(const string& mapName, T* = 0) { - T m(_connection, mapName); - - // - // Populate the database. - // - Struct1 s1; - Class1Ptr c1 = new Class1(); - int i; - _watch.start(); - { - Freeze::TransactionHolder txHolder(_connection); - for(i = 0; i < _repetitions; ++i) - { - s1.l = i; - ostringstream os; - os << i; - c1->s = os.str(); + T m(_connection, mapName); + + // + // Populate the database. + // + Struct1 s1; + Class1Ptr c1 = new Class1(); + int i; + _watch.start(); + { + Freeze::TransactionHolder txHolder(_connection); + for(i = 0; i < _repetitions; ++i) + { + s1.l = i; + ostringstream os; + os << i; + c1->s = os.str(); #if defined(__BCPLUSPLUS__) || (defined(_MSC_VER) && (_MSC_VER < 1310)) - m.put(T::value_type(s1, c1)); + m.put(T::value_type(s1, c1)); #else - m.put(typename T::value_type(s1, c1)); + m.put(typename T::value_type(s1, c1)); #endif - } - txHolder.commit(); - } - IceUtil::Time total = _watch.stop(); - IceUtil::Time perRecord = total / _repetitions; - - cout << "\ttime for " << _repetitions << " writes: " << total * 1000 << "ms" << endl; - cout << "\ttime per write: " << perRecord * 1000 << "ms" << endl; - - // - // Read each record. - // - _watch.start(); - for(i = 0; i < _repetitions; ++i) - { - s1.l = i; - typename T::iterator p = m.find(s1); - test(p != m.end()); - ostringstream os; - os << i; - test(p->second->s == os.str()); - } - total = _watch.stop(); - perRecord = total / _repetitions; - - cout << "\ttime for " << _repetitions << " reads: " << total * 1000 << "ms" << endl; - cout << "\ttime per read: " << perRecord * 1000 << "ms" << endl; - - // - // Optional index test - // - - Struct1Class1MapIndexTest(m); - - // - // Remove each record. - // - _watch.start(); - { - Freeze::TransactionHolder txHolder(_connection); - for(i = 0; i < _repetitions; ++i) - { - s1.l = i; - m.erase(s1); - } - txHolder.commit(); - } - total = _watch.stop(); - perRecord = total / _repetitions; - - cout << "\ttime for " << _repetitions << " removes: " << total * 1000 << "ms" << endl; - cout << "\ttime per remove: " << perRecord * 1000 << "ms" << endl; + } + txHolder.commit(); + } + IceUtil::Time total = _watch.stop(); + IceUtil::Time perRecord = total / _repetitions; + + cout << "\ttime for " << _repetitions << " writes: " << total * 1000 << "ms" << endl; + cout << "\ttime per write: " << perRecord * 1000 << "ms" << endl; + + // + // Read each record. + // + _watch.start(); + for(i = 0; i < _repetitions; ++i) + { + s1.l = i; + typename T::iterator p = m.find(s1); + test(p != m.end()); + ostringstream os; + os << i; + test(p->second->s == os.str()); + } + total = _watch.stop(); + perRecord = total / _repetitions; + + cout << "\ttime for " << _repetitions << " reads: " << total * 1000 << "ms" << endl; + cout << "\ttime per read: " << perRecord * 1000 << "ms" << endl; + + // + // Optional index test + // + + Struct1Class1MapIndexTest(m); + + // + // Remove each record. + // + _watch.start(); + { + Freeze::TransactionHolder txHolder(_connection); + for(i = 0; i < _repetitions; ++i) + { + s1.l = i; + m.erase(s1); + } + txHolder.commit(); + } + total = _watch.stop(); + perRecord = total / _repetitions; + + cout << "\ttime for " << _repetitions << " removes: " << total * 1000 << "ms" << endl; + cout << "\ttime per remove: " << perRecord * 1000 << "ms" << endl; } void IntIntMapReadIndexTest(IntIntMap&) @@ -415,62 +415,62 @@ private: void IntIntMapReadIndexTest(IndexedIntIntMap&); template void IntIntMapReadTest(const string& mapName, T* = 0) { - T m(_connection, mapName); - - // - // Populate the database. - // - int i; - _watch.start(); - { - Freeze::TransactionHolder txHolder(_connection); - for(i = 0; i < _repetitions; ++i) - { + T m(_connection, mapName); + + // + // Populate the database. + // + int i; + _watch.start(); + { + Freeze::TransactionHolder txHolder(_connection); + for(i = 0; i < _repetitions; ++i) + { #if defined(__BCPLUSPLUS__) || (defined(_MSC_VER) && (_MSC_VER < 1310)) - m.put(T::value_type(i, i)); + m.put(T::value_type(i, i)); #else - m.put(typename T::value_type(i, i)); + m.put(typename T::value_type(i, i)); #endif - } - txHolder.commit(); - } - IceUtil::Time total = _watch.stop(); - IceUtil::Time perRecord = total / _repetitions; - - cout << "\ttime for " << _repetitions << " writes: " << total * 1000 << "ms" << endl; - cout << "\ttime per write: " << perRecord * 1000 << "ms" << endl; - - // - // Do some read tests. - // - generatedRead(m, _repetitions, new SequentialGenerator(1000, 1000)); - generatedRead(m, _repetitions, new SequentialGenerator(2000, 2009)); - generatedRead(m, _repetitions, new SequentialGenerator(3000, 3099)); - generatedRead(m, _repetitions, new SequentialGenerator(4000, 4999)); - - // - // Do a random read test. - // - generatedRead(m, _repetitions, new RandomGenerator(0, 10000)); - - // - // Remove each record. - // - /* - * For this test I don't want to remove the records because I - * want to examine the cache stats for the database. - * - _watch.start(); - for(i = 0; i < _repetitions; ++i) - { - m.erase(i); - } - total = _watch.stop(); - perRecord = total / _repetitions; - - cout << "\ttime for " << _repetitions << " removes: " << total * 1000 << "ms" << endl; - cout << "\ttime per remove: " << perRecord * 1000 << "ms" << endl; - */ + } + txHolder.commit(); + } + IceUtil::Time total = _watch.stop(); + IceUtil::Time perRecord = total / _repetitions; + + cout << "\ttime for " << _repetitions << " writes: " << total * 1000 << "ms" << endl; + cout << "\ttime per write: " << perRecord * 1000 << "ms" << endl; + + // + // Do some read tests. + // + generatedRead(m, _repetitions, new SequentialGenerator(1000, 1000)); + generatedRead(m, _repetitions, new SequentialGenerator(2000, 2009)); + generatedRead(m, _repetitions, new SequentialGenerator(3000, 3099)); + generatedRead(m, _repetitions, new SequentialGenerator(4000, 4999)); + + // + // Do a random read test. + // + generatedRead(m, _repetitions, new RandomGenerator(0, 10000)); + + // + // Remove each record. + // + /* + * For this test I don't want to remove the records because I + * want to examine the cache stats for the database. + * + _watch.start(); + for(i = 0; i < _repetitions; ++i) + { + m.erase(i); + } + total = _watch.stop(); + perRecord = total / _repetitions; + + cout << "\ttime for " << _repetitions << " removes: " << total * 1000 << "ms" << endl; + cout << "\ttime per remove: " << perRecord * 1000 << "ms" << endl; + */ } @@ -497,15 +497,15 @@ TestApp::IntIntMapIndexTest(IndexedIntIntMap& m) _watch.start(); for(int i = 0; i < _repetitions; ++i) { - IndexedIntIntMap::iterator p = m.findByValue(i); - test(p != m.end()); - test(p->second == i); + IndexedIntIntMap::iterator p = m.findByValue(i); + test(p != m.end()); + test(p->second == i); } IceUtil::Time total = _watch.stop(); IceUtil::Time perRecord = total / _repetitions; cout << "\ttime for " << _repetitions << " reverse (indexed) reads: " << total * 1000 << "ms" - << endl; + << endl; cout << "\ttime per reverse read: " << perRecord * 1000 << "ms" << endl; } @@ -515,16 +515,16 @@ TestApp::generatedReadWithIndex(IndexedIntIntMap& m, int reads, const GeneratorP _watch.start(); for(int i = 0; i < reads; ++i) { - int value = gen->next(); - IndexedIntIntMap::iterator p = m.findByValue(value); - test(p != m.end()); - test(p->second == value); + int value = gen->next(); + IndexedIntIntMap::iterator p = m.findByValue(value); + test(p != m.end()); + test(p->second == value); } IceUtil::Time total = _watch.stop(); IceUtil::Time perRecord = total / reads; cout << "\ttime for " << reads << " reverse (indexed) reads of " << gen->toString() << " records: " - << total * 1000 << "ms" << endl; + << total * 1000 << "ms" << endl; cout << "\ttime per reverse read: " << perRecord * 1000 << "ms" << endl; } @@ -536,23 +536,23 @@ TestApp::Struct1Struct2MapIndexTest(IndexedStruct1Struct2Map& m) _watch.start(); for(i = 0; i < _repetitions; ++i) { - ostringstream os; - os << i; + ostringstream os; + os << i; - IndexedStruct1Struct2Map::iterator p = m.findByS(os.str()); - test(p != m.end()); - test(p->first.l == i); - test(p->second.s1.l == i); + IndexedStruct1Struct2Map::iterator p = m.findByS(os.str()); + test(p != m.end()); + test(p->first.l == i); + test(p->second.s1.l == i); } for(i = 0; i < _repetitions; ++i) { - Struct1 s1; - s1.l = i; - IndexedStruct1Struct2Map::iterator p = m.findByS1(s1); - test(p != m.end()); - test(p->first.l == i); - test(p->second.s1.l == i); + Struct1 s1; + s1.l = i; + IndexedStruct1Struct2Map::iterator p = m.findByS1(s1); + test(p != m.end()); + test(p->first.l == i); + test(p->second.s1.l == i); } IceUtil::Time total = _watch.stop(); @@ -571,12 +571,12 @@ TestApp::Struct1Class1MapIndexTest(IndexedStruct1Class1Map& m) _watch.start(); for(int i = 0; i < _repetitions; ++i) { - ostringstream os; - os << i; + ostringstream os; + os << i; - IndexedStruct1Class1Map::iterator p = m.findByS(os.str()); - test(p != m.end()); - test(p->first.l == i); + IndexedStruct1Class1Map::iterator p = m.findByS(os.str()); + test(p != m.end()); + test(p->first.l == i); } IceUtil::Time total = _watch.stop(); IceUtil::Time perRecord = total / _repetitions; @@ -603,25 +603,25 @@ TestApp::Struct1ObjectMapTest() int i; _watch.start(); { - Freeze::TransactionHolder txHolder(_connection); - for(i = 0; i < _repetitions; ++i) - { - s1.l = i; - Ice::ObjectPtr o; - if((i % 2) == 0) - { - o = c2; - } - else - { - o = c1; - } - ostringstream os; - os << i; - c1->s = os.str(); - m.put(Struct1ObjectMap::value_type(s1, o)); - } - txHolder.commit(); + Freeze::TransactionHolder txHolder(_connection); + for(i = 0; i < _repetitions; ++i) + { + s1.l = i; + Ice::ObjectPtr o; + if((i % 2) == 0) + { + o = c2; + } + else + { + o = c1; + } + ostringstream os; + os << i; + c1->s = os.str(); + m.put(Struct1ObjectMap::value_type(s1, o)); + } + txHolder.commit(); } IceUtil::Time total = _watch.stop(); IceUtil::Time perRecord = total / _repetitions; @@ -635,27 +635,27 @@ TestApp::Struct1ObjectMapTest() _watch.start(); for(i = 0; i < _repetitions; ++i) { - s1.l = i; - Struct1ObjectMap::iterator p = m.find(s1); - test(p != m.end()); - Ice::ObjectPtr o = p->second; - Class1Ptr nc1; - if((i % 2) == 0) - { - Class2Ptr nc2 = Class2Ptr::dynamicCast(o); - test(nc2); - - test(nc2->rec == nc2); - nc1 = Class1Ptr::dynamicCast(nc2->obj); - } - else - { - nc1 = Class1Ptr::dynamicCast(o); - } - test(nc1); - ostringstream os; - os << i; - test(nc1->s == os.str()); + s1.l = i; + Struct1ObjectMap::iterator p = m.find(s1); + test(p != m.end()); + Ice::ObjectPtr o = p->second; + Class1Ptr nc1; + if((i % 2) == 0) + { + Class2Ptr nc2 = Class2Ptr::dynamicCast(o); + test(nc2); + + test(nc2->rec == nc2); + nc1 = Class1Ptr::dynamicCast(nc2->obj); + } + else + { + nc1 = Class1Ptr::dynamicCast(o); + } + test(nc1); + ostringstream os; + os << i; + test(nc1->s == os.str()); } total = _watch.stop(); perRecord = total / _repetitions; @@ -668,13 +668,13 @@ TestApp::Struct1ObjectMapTest() // _watch.start(); { - Freeze::TransactionHolder txHolder(_connection); - for(i = 0; i < _repetitions; ++i) - { - s1.l = i; - m.erase(s1); - } - txHolder.commit(); + Freeze::TransactionHolder txHolder(_connection); + for(i = 0; i < _repetitions; ++i) + { + s1.l = i; + m.erase(s1); + } + txHolder.commit(); } total = _watch.stop(); perRecord = total / _repetitions; @@ -690,15 +690,15 @@ public: Ice::ObjectPtr create(const string& type) { - if(type == "::Class1") - { - return new Class1(); - } - else if(type == "::Class2") - { - return new Class2(); - } - return 0; + if(type == "::Class1") + { + return new Class1(); + } + else if(type == "::Class2") + { + return new Class2(); + } + return 0; } void @@ -709,8 +709,8 @@ public: void install(const Ice::CommunicatorPtr& communicator) { - communicator->addObjectFactory(this, "::Class1"); - communicator->addObjectFactory(this, "::Class2"); + communicator->addObjectFactory(this, "::Class1"); + communicator->addObjectFactory(this, "::Class2"); } }; typedef IceUtil::Handle MyFactoryPtr; @@ -729,8 +729,8 @@ TestApp::run(int argc, char* argv[]) cout << "IntIntMap" << endl; #if defined(_MSC_VER) && (_MSC_VER < 1310) { - IntIntMap* dummy = 0; - IntIntMapTest("IntIntMap", dummy); + IntIntMap* dummy = 0; + IntIntMapTest("IntIntMap", dummy); } #else IntIntMapTest("IntIntMap"); @@ -739,8 +739,8 @@ TestApp::run(int argc, char* argv[]) cout << "IntIntMap with index" << endl; #if defined(_MSC_VER) && (_MSC_VER < 1310) { - IndexedIntIntMap* dummy = 0; - IntIntMapTest("IndexedIntIntMap", dummy); + IndexedIntIntMap* dummy = 0; + IntIntMapTest("IndexedIntIntMap", dummy); } #else IntIntMapTest("IndexedIntIntMap"); @@ -749,8 +749,8 @@ TestApp::run(int argc, char* argv[]) cout <<"Struct1Struct2Map" << endl; #if defined(_MSC_VER) && (_MSC_VER < 1310) { - Struct1Struct2Map* dummy = 0; - Struct1Struct2MapTest("Struct1Struct2Map", dummy); + Struct1Struct2Map* dummy = 0; + Struct1Struct2MapTest("Struct1Struct2Map", dummy); } #else Struct1Struct2MapTest("Struct1Struct2Map"); @@ -759,8 +759,8 @@ TestApp::run(int argc, char* argv[]) cout <<"Struct1Struct2Map with index" << endl; #if defined(_MSC_VER) && (_MSC_VER < 1310) { - IndexedStruct1Struct2Map* dummy = 0; - Struct1Struct2MapTest("IndexedStruct1Struct2Map", dummy); + IndexedStruct1Struct2Map* dummy = 0; + Struct1Struct2MapTest("IndexedStruct1Struct2Map", dummy); } #else Struct1Struct2MapTest("IndexedStruct1Struct2Map"); @@ -769,8 +769,8 @@ TestApp::run(int argc, char* argv[]) cout <<"Struct1Class1Map" << endl; #if defined(_MSC_VER) && (_MSC_VER < 1310) { - Struct1Class1Map* dummy = 0; - Struct1Class1MapTest("Struct1Class1Map", dummy); + Struct1Class1Map* dummy = 0; + Struct1Class1MapTest("Struct1Class1Map", dummy); } #else Struct1Class1MapTest("Struct1Class1Map"); @@ -779,8 +779,8 @@ TestApp::run(int argc, char* argv[]) cout <<"Struct1Class1Map with index" << endl; #if defined(_MSC_VER) && (_MSC_VER < 1310) { - IndexedStruct1Class1Map* dummy = 0; - Struct1Class1MapTest("IndexedStruct1Class1Map", dummy); + IndexedStruct1Class1Map* dummy = 0; + Struct1Class1MapTest("IndexedStruct1Class1Map", dummy); } #else Struct1Class1MapTest("IndexedStruct1Class1Map"); @@ -795,8 +795,8 @@ TestApp::run(int argc, char* argv[]) cout <<"IntIntMap (read test)" << endl; #if defined(_MSC_VER) && (_MSC_VER < 1310) { - IntIntMap* dummy = 0; - IntIntMapReadTest("IntIntMap", dummy); + IntIntMap* dummy = 0; + IntIntMapReadTest("IntIntMap", dummy); } #else IntIntMapReadTest("IntIntMap"); @@ -805,8 +805,8 @@ TestApp::run(int argc, char* argv[]) cout <<"IntIntMap with index(read test)" << endl; #if defined(_MSC_VER) && (_MSC_VER < 1310) { - IndexedIntIntMap* dummy = 0; - IntIntMapReadTest("IndexedIntIntMap", dummy); + IndexedIntIntMap* dummy = 0; + IntIntMapReadTest("IndexedIntIntMap", dummy); } #else IntIntMapReadTest("IndexedIntIntMap"); diff --git a/cpp/demo/Freeze/library/Client.cpp b/cpp/demo/Freeze/library/Client.cpp index 2cd23ba1bf8..4c13a512683 100644 --- a/cpp/demo/Freeze/library/Client.cpp +++ b/cpp/demo/Freeze/library/Client.cpp @@ -43,15 +43,15 @@ LibraryClient::interruptCallback(int) { try { - communicator()->destroy(); + communicator()->destroy(); } catch(const IceUtil::Exception& ex) { - cerr << appName() << ": " << ex << endl; + cerr << appName() << ": " << ex << endl; } catch(...) { - cerr << appName() << ": unknown exception" << endl; + cerr << appName() << ": unknown exception" << endl; } exit(EXIT_SUCCESS); } diff --git a/cpp/demo/Freeze/library/Collocated.cpp b/cpp/demo/Freeze/library/Collocated.cpp index 5c7ed0261d3..a3457c081dc 100644 --- a/cpp/demo/Freeze/library/Collocated.cpp +++ b/cpp/demo/Freeze/library/Collocated.cpp @@ -19,7 +19,7 @@ class LibraryCollocated : public Ice::Application public: LibraryCollocated(const string& envName) : - _envName(envName) + _envName(envName) { } @@ -61,7 +61,7 @@ LibraryCollocated::run(int argc, char* argv[]) Ice::Int evictorSize = properties->getPropertyAsInt("Library.EvictorSize"); if(evictorSize > 0) { - evictor->setSize(evictorSize); + evictor->setSize(evictorSize); } // @@ -96,15 +96,15 @@ LibraryCollocated::interruptCallback(int) { try { - communicator()->destroy(); + communicator()->destroy(); } catch(const IceUtil::Exception& ex) { - cerr << appName() << ": " << ex << endl; + cerr << appName() << ": " << ex << endl; } catch(...) { - cerr << appName() << ": unknown exception" << endl; + cerr << appName() << ": unknown exception" << endl; } exit(EXIT_SUCCESS); } diff --git a/cpp/demo/Freeze/library/Library.ice b/cpp/demo/Freeze/library/Library.ice index 7111b0f1eac..87663189286 100644 --- a/cpp/demo/Freeze/library/Library.ice +++ b/cpp/demo/Freeze/library/Library.ice @@ -92,7 +92,7 @@ class Book * **/ ["freeze:write"] void destroy() - throws DatabaseException; + throws DatabaseException; /** * @@ -105,7 +105,7 @@ class Book * **/ ["freeze:write"] void rentBook(string name) - throws BookRentedException; + throws BookRentedException; /** * @@ -118,7 +118,7 @@ class Book * **/ ["cpp:const"] idempotent string getRenterName() - throws BookNotRentedException; + throws BookNotRentedException; /** * @@ -129,7 +129,7 @@ class Book * **/ ["freeze:write"] void returnBook() - throws BookNotRentedException; + throws BookNotRentedException; /** * @@ -177,7 +177,7 @@ interface Library * **/ Book* createBook(BookDescription description) - throws DatabaseException, BookExistsException; + throws DatabaseException, BookExistsException; /** * @@ -192,7 +192,7 @@ interface Library * **/ ["cpp:const"] idempotent Book* findByIsbn(string isbn) - throws DatabaseException; + throws DatabaseException; /** * @@ -207,7 +207,7 @@ interface Library * **/ ["cpp:const"] idempotent BookPrxSeq findByAuthors(string authors) - throws DatabaseException; + throws DatabaseException; /** * @@ -220,7 +220,7 @@ interface Library * **/ idempotent void setEvictorSize(int size) - throws DatabaseException; + throws DatabaseException; /** * diff --git a/cpp/demo/Freeze/library/LibraryI.cpp b/cpp/demo/Freeze/library/LibraryI.cpp index 450420c6f55..8a950d3b95c 100644 --- a/cpp/demo/Freeze/library/LibraryI.cpp +++ b/cpp/demo/Freeze/library/LibraryI.cpp @@ -24,19 +24,19 @@ BookI::destroy(const Ice::Current&) IceUtil::Mutex::Lock lock(*this); if(_destroyed) { - throw Ice::ObjectNotExistException(__FILE__, __LINE__); + throw Ice::ObjectNotExistException(__FILE__, __LINE__); } _destroyed = true; try { - _library->remove(description); + _library->remove(description); } catch(const Freeze::DatabaseException& ex) { - DatabaseException e; - e.message = ex.message; - throw e; + DatabaseException e; + e.message = ex.message; + throw e; } } @@ -68,7 +68,7 @@ BookI::getRenterName(const Ice::Current&) const if(rentalCustomerName.empty()) { - throw BookNotRentedException(); + throw BookNotRentedException(); } return rentalCustomerName; } @@ -85,7 +85,7 @@ BookI::rentBook(const string& name, const Ice::Current&) if(!rentalCustomerName.empty()) { - throw BookRentedException(); + throw BookRentedException(); } rentalCustomerName = name; } @@ -102,7 +102,7 @@ BookI::returnBook(const Ice::Current&) if(rentalCustomerName.empty()) { - throw BookNotRentedException(); + throw BookNotRentedException(); } rentalCustomerName.clear();; } @@ -128,14 +128,14 @@ class IsbnToBook public: IsbnToBook(const Ice::ObjectAdapterPtr& adapter) : - _adapter(adapter) + _adapter(adapter) { } BookPrx operator()(const string& isbn) { - return BookPrx::uncheckedCast(_adapter->createProxy(createBookIdentity(isbn))); + return BookPrx::uncheckedCast(_adapter->createProxy(createBookIdentity(isbn))); } private: @@ -144,8 +144,8 @@ private: }; LibraryI::LibraryI(const Ice::CommunicatorPtr& communicator, - const string& envName, const string& dbName, - const Freeze::EvictorPtr& evictor) : + const string& envName, const string& dbName, + const Freeze::EvictorPtr& evictor) : _evictor(evictor), _connection(Freeze::createConnection(communicator, envName)), _authors(_connection, dbName) @@ -163,25 +163,25 @@ LibraryI::createBook(const Demo::BookDescription& description, const Ice::Curren // BookPrx book; { - book = IsbnToBook(c.adapter)(description.isbn); + book = IsbnToBook(c.adapter)(description.isbn); } #else BookPrx book = IsbnToBook(c.adapter)(description.isbn); #endif try { - book->ice_ping(); + book->ice_ping(); - // - // The book already exists. - // - throw BookExistsException(); + // + // The book already exists. + // + throw BookExistsException(); } catch(const Ice::ObjectNotExistException&) { - // - // Book doesn't exist, ignore the exception. - // + // + // Book doesn't exist, ignore the exception. + // } BookPtr bookI = new BookI(this); @@ -205,7 +205,7 @@ LibraryI::createBook(const Demo::BookDescription& description, const Ice::Curren StringIsbnSeqDict::iterator p = _authors.find(description.authors); if(p != _authors.end()) { - isbnSeq = p->second; + isbnSeq = p->second; } isbnSeq.push_back(description.isbn); @@ -224,16 +224,16 @@ LibraryI::findByIsbn(const string& isbn, const Ice::Current& c) const try { - BookPrx book = IsbnToBook(c.adapter)(isbn); - book->ice_ping(); - return book; + BookPrx book = IsbnToBook(c.adapter)(isbn); + book->ice_ping(); + return book; } catch(const Ice::ObjectNotExistException&) { - // - // Book doesn't exist, return a null proxy. - // - return 0; + // + // Book doesn't exist, return a null proxy. + // + return 0; } } @@ -252,8 +252,8 @@ LibraryI::findByAuthors(const string& authors, const Ice::Current& c) const if(p != _authors.end()) { - books.reserve(p->second.size()); - transform(p->second.begin(), p->second.end(), back_inserter(books), IsbnToBook(c.adapter)); + books.reserve(p->second.size()); + transform(p->second.begin(), p->second.end(), back_inserter(books), IsbnToBook(c.adapter)); } return books; @@ -286,43 +286,43 @@ LibraryI::remove(const BookDescription& description) try { - StringIsbnSeqDict::iterator p = _authors.find(description.authors); - - assert(p != _authors.end()); - - // - // Remove the isbn number from the sequence. - // - Ice::StringSeq isbnSeq = p->second; - isbnSeq.erase(remove_if(isbnSeq.begin(), isbnSeq.end(), bind2nd(equal_to(), description.isbn)), - isbnSeq.end()); - - if(isbnSeq.empty()) - { - // - // If there are no further associated isbn numbers then remove - // the record. - // - _authors.erase(p); - } - else - { - // - // Otherwise, write back the new record. - // - p.set(isbnSeq); - } - - // - // This can throw EvictorDeactivatedException (which indicates - // an internal error). The exception is currently ignored. - // - _evictor->remove(createBookIdentity(description.isbn)); + StringIsbnSeqDict::iterator p = _authors.find(description.authors); + + assert(p != _authors.end()); + + // + // Remove the isbn number from the sequence. + // + Ice::StringSeq isbnSeq = p->second; + isbnSeq.erase(remove_if(isbnSeq.begin(), isbnSeq.end(), bind2nd(equal_to(), description.isbn)), + isbnSeq.end()); + + if(isbnSeq.empty()) + { + // + // If there are no further associated isbn numbers then remove + // the record. + // + _authors.erase(p); + } + else + { + // + // Otherwise, write back the new record. + // + p.set(isbnSeq); + } + + // + // This can throw EvictorDeactivatedException (which indicates + // an internal error). The exception is currently ignored. + // + _evictor->remove(createBookIdentity(description.isbn)); } catch(const Freeze::DatabaseException& ex) { - DatabaseException e; - e.message = ex.message; - throw e; + DatabaseException e; + e.message = ex.message; + throw e; } } diff --git a/cpp/demo/Freeze/library/LibraryI.h b/cpp/demo/Freeze/library/LibraryI.h index 6733f6e3f35..aba7775842d 100644 --- a/cpp/demo/Freeze/library/LibraryI.h +++ b/cpp/demo/Freeze/library/LibraryI.h @@ -21,8 +21,8 @@ class LibraryI : public Demo::Library, public IceUtil::Mutex public: LibraryI(const Ice::CommunicatorPtr& communicator, - const std::string& envName, const std::string& dbName, - const Freeze::EvictorPtr& evictor); + const std::string& envName, const std::string& dbName, + const Freeze::EvictorPtr& evictor); virtual Demo::BookPrx createBook(const Demo::BookDescription&, const Ice::Current&); virtual Demo::BookPrx findByIsbn(const std::string&, const Ice::Current&) const; diff --git a/cpp/demo/Freeze/library/Parser.cpp b/cpp/demo/Freeze/library/Parser.cpp index eeb8046327d..c884b42fd6e 100644 --- a/cpp/demo/Freeze/library/Parser.cpp +++ b/cpp/demo/Freeze/library/Parser.cpp @@ -51,37 +51,37 @@ Parser::addBook(const list& _args) { if(_args.size() != 3) { - error("`add' requires at exactly three arguments (type `help' for more info)"); - return; + error("`add' requires at exactly three arguments (type `help' for more info)"); + return; } try { - list args = _args; + list args = _args; - BookDescription desc; - desc.isbn = args.front(); - args.pop_front(); - desc.title = args.front(); - args.pop_front(); - desc.authors = args.front(); + BookDescription desc; + desc.isbn = args.front(); + args.pop_front(); + desc.title = args.front(); + args.pop_front(); + desc.authors = args.front(); - BookPrx book = _library->createBook(desc); - cout << "added new book with isbn " << desc.isbn << endl; + BookPrx book = _library->createBook(desc); + cout << "added new book with isbn " << desc.isbn << endl; } catch(const DatabaseException& ex) { - error(ex.message); + error(ex.message); } catch(const BookExistsException&) { - error("the book already exists."); + error("the book already exists."); } catch(const Ice::Exception& ex) { - ostringstream s; - s << ex; - error(s.str()); + ostringstream s; + s << ex; + error(s.str()); } } @@ -90,36 +90,36 @@ Parser::findIsbn(const list& args) { if(args.size() != 1) { - error("`isbn' requires exactly one argument (type `help' for more info)"); - return; + error("`isbn' requires exactly one argument (type `help' for more info)"); + return; } try { - _foundBooks.clear(); - _current = _foundBooks.begin(); - - BookPrx book = _library->findByIsbn(args.front()); - if(!book) - { - cout << "no book with that ISBN number exists." << endl; - } - else - { - _foundBooks.push_back(book); - _current = _foundBooks.begin(); - printCurrent(); - } + _foundBooks.clear(); + _current = _foundBooks.begin(); + + BookPrx book = _library->findByIsbn(args.front()); + if(!book) + { + cout << "no book with that ISBN number exists." << endl; + } + else + { + _foundBooks.push_back(book); + _current = _foundBooks.begin(); + printCurrent(); + } } catch(const DatabaseException& ex) { - error(ex.message); + error(ex.message); } catch(const Ice::Exception& ex) { - ostringstream s; - s << ex; - error(s.str()); + ostringstream s; + s << ex; + error(s.str()); } } @@ -128,26 +128,26 @@ Parser::findAuthors(const list& args) { if(args.size() != 1) { - error("`authors' requires exactly one argument (type `help' for more info)"); - return; + error("`authors' requires exactly one argument (type `help' for more info)"); + return; } try { - _foundBooks = _library->findByAuthors(args.front()); - _current = _foundBooks.begin(); - cout << "number of books found: " << _foundBooks.size() << endl; - printCurrent(); + _foundBooks = _library->findByAuthors(args.front()); + _current = _foundBooks.begin(); + cout << "number of books found: " << _foundBooks.size() << endl; + printCurrent(); } catch(const DatabaseException& ex) { - error(ex.message); + error(ex.message); } catch(const Ice::Exception& ex) { - ostringstream s; - s << ex; - error(s.str()); + ostringstream s; + s << ex; + error(s.str()); } } @@ -156,7 +156,7 @@ Parser::nextFoundBook() { if(_current != _foundBooks.end()) { - ++_current; + ++_current; } printCurrent(); } @@ -166,31 +166,31 @@ Parser::printCurrent() { try { - if(_current != _foundBooks.end()) - { - BookDescription desc = (*_current)->getBookDescription(); - string renter; - try - { - renter = (*_current)->getRenterName(); - } - catch(const BookNotRentedException&) - { - } - - cout << "current book is:" << endl; - cout << "isbn: " << desc.isbn << endl; - cout << "title: " << desc.title << endl; - cout << "authors: " << desc.authors << endl; - if(!renter.empty()) - { - cout << "rented: " << renter << endl; - } - } - else - { - cout << "no current book" << endl; - } + if(_current != _foundBooks.end()) + { + BookDescription desc = (*_current)->getBookDescription(); + string renter; + try + { + renter = (*_current)->getRenterName(); + } + catch(const BookNotRentedException&) + { + } + + cout << "current book is:" << endl; + cout << "isbn: " << desc.isbn << endl; + cout << "title: " << desc.title << endl; + cout << "authors: " << desc.authors << endl; + if(!renter.empty()) + { + cout << "rented: " << renter << endl; + } + } + else + { + cout << "no current book" << endl; + } } catch(const Ice::ObjectNotExistException&) { @@ -198,9 +198,9 @@ Parser::printCurrent() } catch(const Ice::Exception& ex) { - ostringstream s; - s << ex; - error(s.str()); + ostringstream s; + s << ex; + error(s.str()); } } @@ -209,25 +209,25 @@ Parser::rentCurrent(const list& args) { if(args.size() != 1) { - error("`rent' requires exactly one argument (type `help' for more info)"); - return; + error("`rent' requires exactly one argument (type `help' for more info)"); + return; } try { - if(_current != _foundBooks.end()) - { - (*_current)->rentBook(args.front()); - cout << "the book is now rented by `" << args.front() << "'" << endl; - } - else - { - cout << "no current book" << endl; - } + if(_current != _foundBooks.end()) + { + (*_current)->rentBook(args.front()); + cout << "the book is now rented by `" << args.front() << "'" << endl; + } + else + { + cout << "no current book" << endl; + } } catch(const BookRentedException&) { - cout << "the book has already been rented." << endl; + cout << "the book has already been rented." << endl; } catch(const Ice::ObjectNotExistException&) { @@ -235,13 +235,13 @@ Parser::rentCurrent(const list& args) } catch(const DatabaseException& ex) { - error(ex.message); + error(ex.message); } catch(const Ice::Exception& ex) { - ostringstream s; - s << ex; - error(s.str()); + ostringstream s; + s << ex; + error(s.str()); } } @@ -250,19 +250,19 @@ Parser::returnCurrent() { try { - if(_current != _foundBooks.end()) - { - (*_current)->returnBook(); - cout << "the book has been returned." << endl; - } - else - { - cout << "no current book" << endl; - } + if(_current != _foundBooks.end()) + { + (*_current)->returnBook(); + cout << "the book has been returned." << endl; + } + else + { + cout << "no current book" << endl; + } } catch(const BookNotRentedException&) { - cout << "the book is not currently rented." << endl; + cout << "the book is not currently rented." << endl; } catch(const Ice::ObjectNotExistException&) { @@ -270,13 +270,13 @@ Parser::returnCurrent() } catch(const DatabaseException& ex) { - error(ex.message); + error(ex.message); } catch(const Ice::Exception& ex) { - ostringstream s; - s << ex; - error(s.str()); + ostringstream s; + s << ex; + error(s.str()); } } @@ -285,15 +285,15 @@ Parser::removeCurrent() { try { - if(_current != _foundBooks.end()) - { - (*_current)->destroy(); - cout << "removed current book" << endl; - } - else - { - cout << "no current book" << endl; - } + if(_current != _foundBooks.end()) + { + (*_current)->destroy(); + cout << "removed current book" << endl; + } + else + { + cout << "no current book" << endl; + } } catch(const Ice::ObjectNotExistException&) { @@ -301,13 +301,13 @@ Parser::removeCurrent() } catch(const DatabaseException& ex) { - error(ex.message); + error(ex.message); } catch(const Ice::Exception& ex) { - ostringstream s; - s << ex; - error(s.str()); + ostringstream s; + s << ex; + error(s.str()); } } @@ -316,23 +316,23 @@ Parser::setEvictorSize(const list& args) { if(args.size() != 1) { - error("`size' requires exactly one argument (type `help' for more info)"); - return; + error("`size' requires exactly one argument (type `help' for more info)"); + return; } try { - _library->setEvictorSize(atoi(args.front().c_str())); + _library->setEvictorSize(atoi(args.front().c_str())); } catch(const DatabaseException& ex) { - error(ex.message); + error(ex.message); } catch(const Ice::Exception& ex) { - ostringstream s; - s << ex; - error(s.str()); + ostringstream s; + s << ex; + error(s.str()); } } @@ -341,13 +341,13 @@ Parser::shutdown() { try { - _library->shutdown(); + _library->shutdown(); } catch(const Ice::Exception& ex) { - ostringstream s; - s << ex; - error(s.str()); + ostringstream s; + s << ex; + error(s.str()); } } @@ -356,105 +356,105 @@ Parser::getInput(char* buf, int& result, int maxSize) { if(!_commands.empty()) { - if(_commands == ";") - { - result = 0; - } - else - { + if(_commands == ";") + { + result = 0; + } + else + { #if defined(_MSC_VER) && !defined(_STLP_MSVC) - // COMPILERBUG: Stupid Visual C++ defines min and max as macros - result = _MIN(maxSize, static_cast(_commands.length())); + // COMPILERBUG: Stupid Visual C++ defines min and max as macros + result = _MIN(maxSize, static_cast(_commands.length())); #else - result = min(maxSize, static_cast(_commands.length())); + result = min(maxSize, static_cast(_commands.length())); #endif - strncpy(buf, _commands.c_str(), result); - _commands.erase(0, result); - if(_commands.empty()) - { - _commands = ";"; - } - } + strncpy(buf, _commands.c_str(), result); + _commands.erase(0, result); + if(_commands.empty()) + { + _commands = ";"; + } + } } else if(isatty(fileno(yyin))) { #ifdef HAVE_READLINE const char* prompt = parser->getPrompt(); - char* line = readline(const_cast(prompt)); - if(!line) - { - result = 0; - } - else - { - if(*line) - { - add_history(line); - } - - result = strlen(line) + 1; - if(result > maxSize) - { - free(line); - error("input line too long"); - result = 0; - } - else - { - strcpy(buf, line); - strcat(buf, "\n"); - free(line); - } - } + char* line = readline(const_cast(prompt)); + if(!line) + { + result = 0; + } + else + { + if(*line) + { + add_history(line); + } + + result = strlen(line) + 1; + if(result > maxSize) + { + free(line); + error("input line too long"); + result = 0; + } + else + { + strcpy(buf, line); + strcat(buf, "\n"); + free(line); + } + } #else - cout << parser->getPrompt() << flush; - - string line; - while(true) - { - char c = static_cast(getc(yyin)); - if(c == EOF) - { - if(line.size()) - { - line += '\n'; - } - break; - } - - line += c; - - if(c == '\n') - { - break; - } - } - - result = static_cast(line.length()); - if(result > maxSize) - { - error("input line too long"); - buf[0] = EOF; - result = 1; - } - else - { - strcpy(buf, line.c_str()); - } + cout << parser->getPrompt() << flush; + + string line; + while(true) + { + char c = static_cast(getc(yyin)); + if(c == EOF) + { + if(line.size()) + { + line += '\n'; + } + break; + } + + line += c; + + if(c == '\n') + { + break; + } + } + + result = static_cast(line.length()); + if(result > maxSize) + { + error("input line too long"); + buf[0] = EOF; + result = 1; + } + else + { + strcpy(buf, line.c_str()); + } #endif } else { - if(((result = static_cast(fread(buf, 1, maxSize, yyin))) == 0) && ferror(yyin)) - { - error("input in flex scanner failed"); - buf[0] = EOF; - result = 1; - } + if(((result = static_cast(fread(buf, 1, maxSize, yyin))) == 0) && ferror(yyin)) + { + error("input in flex scanner failed"); + buf[0] = EOF; + result = 1; + } } } @@ -477,12 +477,12 @@ Parser::getPrompt() if(_continue) { - _continue = false; - return "(cont) "; + _continue = false; + return "(cont) "; } else { - return ">>> "; + return ">>> "; } } @@ -491,11 +491,11 @@ Parser::error(const char* s) { if(_commands.empty() && !isatty(fileno(yyin))) { - cerr << _currentFile << ':' << _currentLine << ": " << s << endl; + cerr << _currentFile << ':' << _currentLine << ": " << s << endl; } else { - cerr << "error: " << s << endl; + cerr << "error: " << s << endl; } _errors++; } @@ -511,11 +511,11 @@ Parser::warning(const char* s) { if(_commands.empty() && !isatty(fileno(yyin))) { - cerr << _currentFile << ':' << _currentLine << ": warning: " << s << endl; + cerr << _currentFile << ':' << _currentLine << ": warning: " << s << endl; } else { - cerr << "warning: " << s << endl; + cerr << "warning: " << s << endl; } } @@ -550,7 +550,7 @@ Parser::parse(FILE* file, bool debug) int status = yyparse(); if(_errors) { - status = EXIT_FAILURE; + status = EXIT_FAILURE; } parser = 0; @@ -582,7 +582,7 @@ Parser::parse(const string& commands, bool debug) int status = yyparse(); if(_errors) { - status = EXIT_FAILURE; + status = EXIT_FAILURE; } parser = 0; diff --git a/cpp/demo/Freeze/library/RunParser.cpp b/cpp/demo/Freeze/library/RunParser.cpp index 87500d3a6f3..f1a79c08d5f 100644 --- a/cpp/demo/Freeze/library/RunParser.cpp +++ b/cpp/demo/Freeze/library/RunParser.cpp @@ -17,13 +17,13 @@ void usage(const char* appName) { cerr << "Usage: " << appName << " [options] [file...]\n"; - cerr << - "Options:\n" - "-h, --help Show this message.\n" - "-v, --version Display the Ice version.\n" - "-e COMMANDS Execute COMMANDS.\n" - "-d, --debug Print debug messages.\n" - ; + cerr << + "Options:\n" + "-h, --help Show this message.\n" + "-v, --version Display the Ice version.\n" + "-e COMMANDS Execute COMMANDS.\n" + "-d, --debug Print debug messages.\n" + ; } int @@ -35,67 +35,67 @@ runParser(int argc, char* argv[], const Ice::CommunicatorPtr& communicator) int idx = 1; while(idx < argc) { - if(strcmp(argv[idx], "-h") == 0 || strcmp(argv[idx], "--help") == 0) - { - usage(argv[0]); - return EXIT_SUCCESS; - } - else if(strcmp(argv[idx], "-v") == 0 || strcmp(argv[idx], "--version") == 0) - { - cout << ICE_STRING_VERSION << endl; - return EXIT_SUCCESS; - } - else if(strcmp(argv[idx], "-e") == 0) - { - if(idx + 1 >= argc) + if(strcmp(argv[idx], "-h") == 0 || strcmp(argv[idx], "--help") == 0) + { + usage(argv[0]); + return EXIT_SUCCESS; + } + else if(strcmp(argv[idx], "-v") == 0 || strcmp(argv[idx], "--version") == 0) + { + cout << ICE_STRING_VERSION << endl; + return EXIT_SUCCESS; + } + else if(strcmp(argv[idx], "-e") == 0) + { + if(idx + 1 >= argc) { - cerr << argv[0] << ": argument expected for`" << argv[idx] << "'" << endl; - usage(argv[0]); - return EXIT_FAILURE; + cerr << argv[0] << ": argument expected for`" << argv[idx] << "'" << endl; + usage(argv[0]); + return EXIT_FAILURE; } - - commands += argv[idx + 1]; - commands += ';'; + + commands += argv[idx + 1]; + commands += ';'; - for(int i = idx ; i + 2 < argc ; ++i) - { - argv[i] = argv[i + 2]; - } - argc -= 2; - } - else if(strcmp(argv[idx], "-d") == 0 || strcmp(argv[idx], "--debug") == 0) - { - debug = true; - for(int i = idx ; i + 1 < argc ; ++i) - { - argv[i] = argv[i + 1]; - } - --argc; - } - else if(argv[idx][0] == '-') - { - cerr << argv[0] << ": unknown option `" << argv[idx] << "'" << endl; - usage(argv[0]); - return EXIT_FAILURE; - } - else - { - ++idx; - } + for(int i = idx ; i + 2 < argc ; ++i) + { + argv[i] = argv[i + 2]; + } + argc -= 2; + } + else if(strcmp(argv[idx], "-d") == 0 || strcmp(argv[idx], "--debug") == 0) + { + debug = true; + for(int i = idx ; i + 1 < argc ; ++i) + { + argv[i] = argv[i + 1]; + } + --argc; + } + else if(argv[idx][0] == '-') + { + cerr << argv[0] << ": unknown option `" << argv[idx] << "'" << endl; + usage(argv[0]); + return EXIT_FAILURE; + } + else + { + ++idx; + } } if(argc >= 2 && !commands.empty()) { - cerr << argv[0] << ": `-e' option cannot be used if input files are given" << endl; - usage(argv[0]); - return EXIT_FAILURE; + cerr << argv[0] << ": `-e' option cannot be used if input files are given" << endl; + usage(argv[0]); + return EXIT_FAILURE; } LibraryPrx phoneBook = LibraryPrx::checkedCast(communicator->propertyToProxy("Library.Proxy")); if(!phoneBook) { - cerr << argv[0] << ": invalid proxy" << endl; - return EXIT_FAILURE; + cerr << argv[0] << ": invalid proxy" << endl; + return EXIT_FAILURE; } ParserPtr p = Parser::createParser(phoneBook); @@ -103,43 +103,43 @@ runParser(int argc, char* argv[], const Ice::CommunicatorPtr& communicator) if(argc < 2) // No files given { - if(!commands.empty()) // Commands were given - { - int parseStatus = p->parse(commands, debug); - if(parseStatus == EXIT_FAILURE) - { - status = EXIT_FAILURE; - } - } - else // No commands, let's use standard input - { - int parseStatus = p->parse(stdin, debug); - if(parseStatus == EXIT_FAILURE) - { - status = EXIT_FAILURE; - } - } + if(!commands.empty()) // Commands were given + { + int parseStatus = p->parse(commands, debug); + if(parseStatus == EXIT_FAILURE) + { + status = EXIT_FAILURE; + } + } + else // No commands, let's use standard input + { + int parseStatus = p->parse(stdin, debug); + if(parseStatus == EXIT_FAILURE) + { + status = EXIT_FAILURE; + } + } } else // Process files given on the command line { - for(idx = 1 ; idx < argc ; ++idx) - { - FILE* file = fopen(argv[idx], "r"); - if(file == NULL) - { - cerr << argv[0] << ": can't open file `" << argv[idx] << "': " << strerror(errno) << endl; - return EXIT_FAILURE; - } - - int parseStatus = p->parse(file, debug); + for(idx = 1 ; idx < argc ; ++idx) + { + FILE* file = fopen(argv[idx], "r"); + if(file == NULL) + { + cerr << argv[0] << ": can't open file `" << argv[idx] << "': " << strerror(errno) << endl; + return EXIT_FAILURE; + } + + int parseStatus = p->parse(file, debug); - fclose(file); + fclose(file); - if(parseStatus == EXIT_FAILURE) - { - status = EXIT_FAILURE; - } - } + if(parseStatus == EXIT_FAILURE) + { + status = EXIT_FAILURE; + } + } } return status; diff --git a/cpp/demo/Freeze/library/Server.cpp b/cpp/demo/Freeze/library/Server.cpp index a819e74ee1b..fda90db0811 100644 --- a/cpp/demo/Freeze/library/Server.cpp +++ b/cpp/demo/Freeze/library/Server.cpp @@ -18,7 +18,7 @@ class LibraryServer : public Ice::Application public: LibraryServer(const string& envName) : - _envName(envName) + _envName(envName) { } @@ -53,7 +53,7 @@ LibraryServer::run(int argc, char* argv[]) Ice::Int evictorSize = properties->getPropertyAsInt("Library.EvictorSize"); if(evictorSize > 0) { - evictor->setSize(evictorSize); + evictor->setSize(evictorSize); } // diff --git a/cpp/demo/Freeze/phonebook/Client.cpp b/cpp/demo/Freeze/phonebook/Client.cpp index 5f7c3c032a2..d027ae411a0 100644 --- a/cpp/demo/Freeze/phonebook/Client.cpp +++ b/cpp/demo/Freeze/phonebook/Client.cpp @@ -43,15 +43,15 @@ PhoneBookClient::interruptCallback(int) { try { - communicator()->destroy(); + communicator()->destroy(); } catch(const IceUtil::Exception& ex) { - cerr << appName() << ": " << ex << endl; + cerr << appName() << ": " << ex << endl; } catch(...) { - cerr << appName() << ": unknown exception" << endl; + cerr << appName() << ": unknown exception" << endl; } exit(EXIT_SUCCESS); } diff --git a/cpp/demo/Freeze/phonebook/Collocated.cpp b/cpp/demo/Freeze/phonebook/Collocated.cpp index 6b1efc3c75f..692f33e425e 100644 --- a/cpp/demo/Freeze/phonebook/Collocated.cpp +++ b/cpp/demo/Freeze/phonebook/Collocated.cpp @@ -19,7 +19,7 @@ class PhoneBookCollocated : public Ice::Application public: PhoneBookCollocated(const string& envName) : - _envName(envName) + _envName(envName) { } @@ -82,7 +82,7 @@ PhoneBookCollocated::run(int argc, char* argv[]) Ice::Int evictorSize = properties->getPropertyAsInt("PhoneBook.EvictorSize"); if(evictorSize > 0) { - evictor->setSize(evictorSize); + evictor->setSize(evictorSize); } // @@ -113,15 +113,15 @@ PhoneBookCollocated::interruptCallback(int) { try { - communicator()->destroy(); + communicator()->destroy(); } catch(const IceUtil::Exception& ex) { - cerr << appName() << ": " << ex << endl; + cerr << appName() << ": " << ex << endl; } catch(...) { - cerr << appName() << ": unknown exception" << endl; + cerr << appName() << ": unknown exception" << endl; } exit(EXIT_SUCCESS); } diff --git a/cpp/demo/Freeze/phonebook/Parser.cpp b/cpp/demo/Freeze/phonebook/Parser.cpp index a09f663ceec..a93bab7648d 100644 --- a/cpp/demo/Freeze/phonebook/Parser.cpp +++ b/cpp/demo/Freeze/phonebook/Parser.cpp @@ -52,28 +52,28 @@ Parser::addContacts(const list& args) { if(args.empty()) { - error("`add' requires at least one argument (type `help' for more info)"); - return; + error("`add' requires at least one argument (type `help' for more info)"); + return; } try { - for(list::const_iterator p = args.begin(); p != args.end(); ++p) - { - ContactPrx contact = _phoneBook->createContact(); - contact->setName(*p); - cout << "added new contact for `" << *p << "'" << endl; - } + for(list::const_iterator p = args.begin(); p != args.end(); ++p) + { + ContactPrx contact = _phoneBook->createContact(); + contact->setName(*p); + cout << "added new contact for `" << *p << "'" << endl; + } } catch(const DatabaseException& ex) { - error(ex.message); + error(ex.message); } catch(const Ice::Exception& ex) { - ostringstream s; - s << ex; - error(s.str()); + ostringstream s; + s << ex; + error(s.str()); } } @@ -82,26 +82,26 @@ Parser::findContacts(const list& args) { if(args.size() != 1) { - error("`find' requires exactly one argument (type `help' for more info)"); - return; + error("`find' requires exactly one argument (type `help' for more info)"); + return; } try { - _foundContacts = _phoneBook->findContacts(args.front()); - _current = _foundContacts.begin(); - cout << "number of contacts found: " << _foundContacts.size() << endl; - printCurrent(); + _foundContacts = _phoneBook->findContacts(args.front()); + _current = _foundContacts.begin(); + cout << "number of contacts found: " << _foundContacts.size() << endl; + printCurrent(); } catch(const DatabaseException& ex) { - error(ex.message); + error(ex.message); } catch(const Ice::Exception& ex) { - ostringstream s; - s << ex; - error(s.str()); + ostringstream s; + s << ex; + error(s.str()); } } @@ -110,7 +110,7 @@ Parser::nextFoundContact() { if(_current != _foundContacts.end()) { - ++_current; + ++_current; } printCurrent(); } @@ -120,17 +120,17 @@ Parser::printCurrent() { try { - if(_current != _foundContacts.end()) - { - cout << "current contact is:" << endl; - cout << "name: " << (*_current)->getName() << endl; - cout << "address: " << (*_current)->getAddress() << endl; - cout << "phone: " << (*_current)->getPhone() << endl; - } - else - { - cout << "no current contact" << endl; - } + if(_current != _foundContacts.end()) + { + cout << "current contact is:" << endl; + cout << "name: " << (*_current)->getName() << endl; + cout << "address: " << (*_current)->getAddress() << endl; + cout << "phone: " << (*_current)->getPhone() << endl; + } + else + { + cout << "no current contact" << endl; + } } catch(const Ice::ObjectNotExistException&) { @@ -138,13 +138,13 @@ Parser::printCurrent() } catch(const DatabaseException& ex) { - error(ex.message); + error(ex.message); } catch(const Ice::Exception& ex) { - ostringstream s; - s << ex; - error(s.str()); + ostringstream s; + s << ex; + error(s.str()); } } @@ -153,21 +153,21 @@ Parser::setCurrentName(const list& args) { if(args.size() != 1) { - error("`name' requires exactly one argument (type `help' for more info)"); - return; + error("`name' requires exactly one argument (type `help' for more info)"); + return; } try { - if(_current != _foundContacts.end()) - { - (*_current)->setName(args.front()); - cout << "changed name to `" << args.front() << "'" << endl; - } - else - { - cout << "no current contact" << endl; - } + if(_current != _foundContacts.end()) + { + (*_current)->setName(args.front()); + cout << "changed name to `" << args.front() << "'" << endl; + } + else + { + cout << "no current contact" << endl; + } } catch(const Ice::ObjectNotExistException&) { @@ -175,13 +175,13 @@ Parser::setCurrentName(const list& args) } catch(const DatabaseException& ex) { - error(ex.message); + error(ex.message); } catch(const Ice::Exception& ex) { - ostringstream s; - s << ex; - error(s.str()); + ostringstream s; + s << ex; + error(s.str()); } } @@ -190,21 +190,21 @@ Parser::setCurrentAddress(const list& args) { if(args.size() != 1) { - error("`address' requires exactly one argument (type `help' for more info)"); - return; + error("`address' requires exactly one argument (type `help' for more info)"); + return; } try { - if(_current != _foundContacts.end()) - { - (*_current)->setAddress(args.front()); - cout << "changed address to `" << args.front() << "'" << endl; - } - else - { - cout << "no current contact" << endl; - } + if(_current != _foundContacts.end()) + { + (*_current)->setAddress(args.front()); + cout << "changed address to `" << args.front() << "'" << endl; + } + else + { + cout << "no current contact" << endl; + } } catch(const Ice::ObjectNotExistException&) { @@ -212,13 +212,13 @@ Parser::setCurrentAddress(const list& args) } catch(const DatabaseException& ex) { - error(ex.message); + error(ex.message); } catch(const Ice::Exception& ex) { - ostringstream s; - s << ex; - error(s.str()); + ostringstream s; + s << ex; + error(s.str()); } } @@ -227,21 +227,21 @@ Parser::setCurrentPhone(const list& args) { if(args.size() != 1) { - error("`phone' requires exactly one argument (type `help' for more info)"); - return; + error("`phone' requires exactly one argument (type `help' for more info)"); + return; } try { - if(_current != _foundContacts.end()) - { - (*_current)->setPhone(args.front()); - cout << "changed phone number to `" << args.front() << "'" << endl; - } - else - { - cout << "no current contact" << endl; - } + if(_current != _foundContacts.end()) + { + (*_current)->setPhone(args.front()); + cout << "changed phone number to `" << args.front() << "'" << endl; + } + else + { + cout << "no current contact" << endl; + } } catch(const Ice::ObjectNotExistException&) { @@ -249,13 +249,13 @@ Parser::setCurrentPhone(const list& args) } catch(const DatabaseException& ex) { - error(ex.message); + error(ex.message); } catch(const Ice::Exception& ex) { - ostringstream s; - s << ex; - error(s.str()); + ostringstream s; + s << ex; + error(s.str()); } } @@ -264,15 +264,15 @@ Parser::removeCurrent() { try { - if(_current != _foundContacts.end()) - { - (*_current)->destroy(); - cout << "removed current contact" << endl; - } - else - { - cout << "no current contact" << endl; - } + if(_current != _foundContacts.end()) + { + (*_current)->destroy(); + cout << "removed current contact" << endl; + } + else + { + cout << "no current contact" << endl; + } } catch(const Ice::ObjectNotExistException&) { @@ -280,13 +280,13 @@ Parser::removeCurrent() } catch(const DatabaseException& ex) { - error(ex.message); + error(ex.message); } catch(const Ice::Exception& ex) { - ostringstream s; - s << ex; - error(s.str()); + ostringstream s; + s << ex; + error(s.str()); } } @@ -295,23 +295,23 @@ Parser::setEvictorSize(const list& args) { if(args.size() != 1) { - error("`size' requires exactly one argument (type `help' for more info)"); - return; + error("`size' requires exactly one argument (type `help' for more info)"); + return; } try { - _phoneBook->setEvictorSize(atoi(args.front().c_str())); + _phoneBook->setEvictorSize(atoi(args.front().c_str())); } catch(const DatabaseException& ex) { - error(ex.message); + error(ex.message); } catch(const Ice::Exception& ex) { - ostringstream s; - s << ex; - error(s.str()); + ostringstream s; + s << ex; + error(s.str()); } } @@ -320,13 +320,13 @@ Parser::shutdown() { try { - _phoneBook->shutdown(); + _phoneBook->shutdown(); } catch(const Ice::Exception& ex) { - ostringstream s; - s << ex; - error(s.str()); + ostringstream s; + s << ex; + error(s.str()); } } @@ -335,105 +335,105 @@ Parser::getInput(char* buf, int& result, int maxSize) { if(!_commands.empty()) { - if(_commands == ";") - { - result = 0; - } - else - { + if(_commands == ";") + { + result = 0; + } + else + { #if defined(_MSC_VER) && !defined(_STLP_MSVC) - // COMPILERBUG: Stupid Visual C++ defines min and max as macros - result = _MIN(maxSize, static_cast(_commands.length())); + // COMPILERBUG: Stupid Visual C++ defines min and max as macros + result = _MIN(maxSize, static_cast(_commands.length())); #else - result = min(maxSize, static_cast(_commands.length())); + result = min(maxSize, static_cast(_commands.length())); #endif - strncpy(buf, _commands.c_str(), result); - _commands.erase(0, result); - if(_commands.empty()) - { - _commands = ";"; - } - } + strncpy(buf, _commands.c_str(), result); + _commands.erase(0, result); + if(_commands.empty()) + { + _commands = ";"; + } + } } else if(isatty(fileno(yyin))) { #ifdef HAVE_READLINE const char* prompt = parser->getPrompt(); - char* line = readline(const_cast(prompt)); - if(!line) - { - result = 0; - } - else - { - if(*line) - { - add_history(line); - } - - result = strlen(line) + 1; - if(result > maxSize) - { - free(line); - error("input line too long"); - result = 0; - } - else - { - strcpy(buf, line); - strcat(buf, "\n"); - free(line); - } - } + char* line = readline(const_cast(prompt)); + if(!line) + { + result = 0; + } + else + { + if(*line) + { + add_history(line); + } + + result = strlen(line) + 1; + if(result > maxSize) + { + free(line); + error("input line too long"); + result = 0; + } + else + { + strcpy(buf, line); + strcat(buf, "\n"); + free(line); + } + } #else - cout << parser->getPrompt() << flush; - - string line; - while(true) - { - char c = static_cast(getc(yyin)); - if(c == EOF) - { - if(line.size()) - { - line += '\n'; - } - break; - } - - line += c; - - if(c == '\n') - { - break; - } - } - - result = static_cast(line.length()); - if(result > maxSize) - { - error("input line too long"); - buf[0] = EOF; - result = 1; - } - else - { - strcpy(buf, line.c_str()); - } + cout << parser->getPrompt() << flush; + + string line; + while(true) + { + char c = static_cast(getc(yyin)); + if(c == EOF) + { + if(line.size()) + { + line += '\n'; + } + break; + } + + line += c; + + if(c == '\n') + { + break; + } + } + + result = static_cast(line.length()); + if(result > maxSize) + { + error("input line too long"); + buf[0] = EOF; + result = 1; + } + else + { + strcpy(buf, line.c_str()); + } #endif } else { - if(((result = static_cast(fread(buf, 1, maxSize, yyin))) == 0) && ferror(yyin)) - { - error("input in flex scanner failed"); - buf[0] = EOF; - result = 1; - } + if(((result = static_cast(fread(buf, 1, maxSize, yyin))) == 0) && ferror(yyin)) + { + error("input in flex scanner failed"); + buf[0] = EOF; + result = 1; + } } } @@ -456,12 +456,12 @@ Parser::getPrompt() if(_continue) { - _continue = false; - return "(cont) "; + _continue = false; + return "(cont) "; } else { - return ">>> "; + return ">>> "; } } @@ -470,11 +470,11 @@ Parser::error(const char* s) { if(_commands.empty() && !isatty(fileno(yyin))) { - cerr << _currentFile << ':' << _currentLine << ": " << s << endl; + cerr << _currentFile << ':' << _currentLine << ": " << s << endl; } else { - cerr << "error: " << s << endl; + cerr << "error: " << s << endl; } _errors++; } @@ -490,11 +490,11 @@ Parser::warning(const char* s) { if(_commands.empty() && !isatty(fileno(yyin))) { - cerr << _currentFile << ':' << _currentLine << ": warning: " << s << endl; + cerr << _currentFile << ':' << _currentLine << ": warning: " << s << endl; } else { - cerr << "warning: " << s << endl; + cerr << "warning: " << s << endl; } } @@ -529,7 +529,7 @@ Parser::parse(FILE* file, bool debug) int status = yyparse(); if(_errors) { - status = EXIT_FAILURE; + status = EXIT_FAILURE; } parser = 0; @@ -561,7 +561,7 @@ Parser::parse(const string& commands, bool debug) int status = yyparse(); if(_errors) { - status = EXIT_FAILURE; + status = EXIT_FAILURE; } parser = 0; diff --git a/cpp/demo/Freeze/phonebook/PhoneBookI.cpp b/cpp/demo/Freeze/phonebook/PhoneBookI.cpp index b58fa5adedb..208eac42620 100644 --- a/cpp/demo/Freeze/phonebook/PhoneBookI.cpp +++ b/cpp/demo/Freeze/phonebook/PhoneBookI.cpp @@ -65,18 +65,18 @@ ContactI::destroy(const Ice::Current& c) { try { - _factory->getEvictor()->remove(c.id); + _factory->getEvictor()->remove(c.id); } catch(const Freeze::DatabaseException& ex) { - DatabaseException e; - e.message = ex.message; - throw e; + DatabaseException e; + e.message = ex.message; + throw e; } } PhoneBookI::PhoneBookI(const Freeze::EvictorPtr& evictor, const ContactFactoryPtr& contactFactory, - const NameIndexPtr& index) : + const NameIndexPtr& index) : _evictor(evictor), _contactFactory(contactFactory), _index(index) @@ -88,13 +88,13 @@ class IdentityToContact public: IdentityToContact(const Ice::ObjectAdapterPtr& adapter) : - _adapter(adapter) + _adapter(adapter) { } - ContactPrx operator()(const Ice::Identity& ident) + ContactPrx operator()(const Ice::Identity& ident) { - return ContactPrx::uncheckedCast(_adapter->createProxy(ident)); + return ContactPrx::uncheckedCast(_adapter->createProxy(ident)); } private: @@ -136,19 +136,19 @@ PhoneBookI::findContacts(const string& name, const Ice::Current& c) const { try { - vector identities = _index->find(name); - - Contacts contacts; - contacts.reserve(identities.size()); - transform(identities.begin(), identities.end(), back_inserter(contacts), IdentityToContact(c.adapter)); + vector identities = _index->find(name); + + Contacts contacts; + contacts.reserve(identities.size()); + transform(identities.begin(), identities.end(), back_inserter(contacts), IdentityToContact(c.adapter)); - return contacts; + return contacts; } catch(const Freeze::DatabaseException& ex) { - DatabaseException e; - e.message = ex.message; - throw e; + DatabaseException e; + e.message = ex.message; + throw e; } } diff --git a/cpp/demo/Freeze/phonebook/RunParser.cpp b/cpp/demo/Freeze/phonebook/RunParser.cpp index eac469e60e1..6fce1244c50 100644 --- a/cpp/demo/Freeze/phonebook/RunParser.cpp +++ b/cpp/demo/Freeze/phonebook/RunParser.cpp @@ -17,13 +17,13 @@ void usage(const char* appName) { cerr << "Usage: " << appName << " [options] [file...]\n"; - cerr << - "Options:\n" - "-h, --help Show this message.\n" - "-v, --version Display the Ice version.\n" - "-e COMMANDS Execute COMMANDS.\n" - "-d, --debug Print debug messages.\n" - ; + cerr << + "Options:\n" + "-h, --help Show this message.\n" + "-v, --version Display the Ice version.\n" + "-e COMMANDS Execute COMMANDS.\n" + "-d, --debug Print debug messages.\n" + ; } int @@ -35,67 +35,67 @@ runParser(int argc, char* argv[], const Ice::CommunicatorPtr& communicator) int idx = 1; while(idx < argc) { - if(strcmp(argv[idx], "-h") == 0 || strcmp(argv[idx], "--help") == 0) - { - usage(argv[0]); - return EXIT_SUCCESS; - } - else if(strcmp(argv[idx], "-v") == 0 || strcmp(argv[idx], "--version") == 0) - { - cout << ICE_STRING_VERSION << endl; - return EXIT_SUCCESS; - } - else if(strcmp(argv[idx], "-e") == 0) - { - if(idx + 1 >= argc) + if(strcmp(argv[idx], "-h") == 0 || strcmp(argv[idx], "--help") == 0) + { + usage(argv[0]); + return EXIT_SUCCESS; + } + else if(strcmp(argv[idx], "-v") == 0 || strcmp(argv[idx], "--version") == 0) + { + cout << ICE_STRING_VERSION << endl; + return EXIT_SUCCESS; + } + else if(strcmp(argv[idx], "-e") == 0) + { + if(idx + 1 >= argc) { - cerr << argv[0] << ": argument expected for`" << argv[idx] << "'" << endl; - usage(argv[0]); - return EXIT_FAILURE; + cerr << argv[0] << ": argument expected for`" << argv[idx] << "'" << endl; + usage(argv[0]); + return EXIT_FAILURE; } - - commands += argv[idx + 1]; - commands += ';'; + + commands += argv[idx + 1]; + commands += ';'; - for(int i = idx ; i + 2 < argc ; ++i) - { - argv[i] = argv[i + 2]; - } - argc -= 2; - } - else if(strcmp(argv[idx], "-d") == 0 || strcmp(argv[idx], "--debug") == 0) - { - debug = true; - for(int i = idx ; i + 1 < argc ; ++i) - { - argv[i] = argv[i + 1]; - } - --argc; - } - else if(argv[idx][0] == '-') - { - cerr << argv[0] << ": unknown option `" << argv[idx] << "'" << endl; - usage(argv[0]); - return EXIT_FAILURE; - } - else - { - ++idx; - } + for(int i = idx ; i + 2 < argc ; ++i) + { + argv[i] = argv[i + 2]; + } + argc -= 2; + } + else if(strcmp(argv[idx], "-d") == 0 || strcmp(argv[idx], "--debug") == 0) + { + debug = true; + for(int i = idx ; i + 1 < argc ; ++i) + { + argv[i] = argv[i + 1]; + } + --argc; + } + else if(argv[idx][0] == '-') + { + cerr << argv[0] << ": unknown option `" << argv[idx] << "'" << endl; + usage(argv[0]); + return EXIT_FAILURE; + } + else + { + ++idx; + } } if(argc >= 2 && !commands.empty()) { - cerr << argv[0] << ": `-e' option cannot be used if input files are given" << endl; - usage(argv[0]); - return EXIT_FAILURE; + cerr << argv[0] << ": `-e' option cannot be used if input files are given" << endl; + usage(argv[0]); + return EXIT_FAILURE; } PhoneBookPrx phoneBook = PhoneBookPrx::checkedCast(communicator->propertyToProxy("PhoneBook.Proxy")); if(!phoneBook) { - cerr << argv[0] << ": invalid proxy" << endl; - return EXIT_FAILURE; + cerr << argv[0] << ": invalid proxy" << endl; + return EXIT_FAILURE; } ParserPtr p = Parser::createParser(phoneBook); @@ -103,43 +103,43 @@ runParser(int argc, char* argv[], const Ice::CommunicatorPtr& communicator) if(argc < 2) // No files given { - if(!commands.empty()) // Commands were given - { - int parseStatus = p->parse(commands, debug); - if(parseStatus == EXIT_FAILURE) - { - status = EXIT_FAILURE; - } - } - else // No commands, let's use standard input - { - int parseStatus = p->parse(stdin, debug); - if(parseStatus == EXIT_FAILURE) - { - status = EXIT_FAILURE; - } - } + if(!commands.empty()) // Commands were given + { + int parseStatus = p->parse(commands, debug); + if(parseStatus == EXIT_FAILURE) + { + status = EXIT_FAILURE; + } + } + else // No commands, let's use standard input + { + int parseStatus = p->parse(stdin, debug); + if(parseStatus == EXIT_FAILURE) + { + status = EXIT_FAILURE; + } + } } else // Process files given on the command line { - for(idx = 1 ; idx < argc ; ++idx) - { - FILE* file = fopen(argv[idx], "r"); - if(file == NULL) - { - cerr << argv[0] << ": can't open file `" << argv[idx] << "': " << strerror(errno) << endl; - return EXIT_FAILURE; - } - - int parseStatus = p->parse(file, debug); + for(idx = 1 ; idx < argc ; ++idx) + { + FILE* file = fopen(argv[idx], "r"); + if(file == NULL) + { + cerr << argv[0] << ": can't open file `" << argv[idx] << "': " << strerror(errno) << endl; + return EXIT_FAILURE; + } + + int parseStatus = p->parse(file, debug); - fclose(file); + fclose(file); - if(parseStatus == EXIT_FAILURE) - { - status = EXIT_FAILURE; - } - } + if(parseStatus == EXIT_FAILURE) + { + status = EXIT_FAILURE; + } + } } return status; diff --git a/cpp/demo/Freeze/phonebook/Server.cpp b/cpp/demo/Freeze/phonebook/Server.cpp index e21d25b485d..13f49990880 100644 --- a/cpp/demo/Freeze/phonebook/Server.cpp +++ b/cpp/demo/Freeze/phonebook/Server.cpp @@ -20,7 +20,7 @@ class PhoneBookServer : public Ice::Application public: PhoneBookServer(const string& envName) : - _envName(envName) + _envName(envName) { } @@ -74,7 +74,7 @@ PhoneBookServer::run(int argc, char* argv[]) Ice::Int evictorSize = properties->getPropertyAsInt("PhoneBook.EvictorSize"); if(evictorSize > 0) { - evictor->setSize(evictorSize); + evictor->setSize(evictorSize); } // diff --git a/cpp/demo/Glacier2/callback/CallbackI.cpp b/cpp/demo/Glacier2/callback/CallbackI.cpp index fb9ff794970..24389d5541a 100644 --- a/cpp/demo/Glacier2/callback/CallbackI.cpp +++ b/cpp/demo/Glacier2/callback/CallbackI.cpp @@ -18,14 +18,14 @@ CallbackReceiverI::callback(const Ice::Current&) { #ifdef __xlC__ - // - // The xlC compiler synchronizes cin and cout; to see the messages - // while accepting input through cin, we have to print the messages - // with printf - // + // + // The xlC compiler synchronizes cin and cout; to see the messages + // while accepting input through cin, we have to print the messages + // with printf + // - printf("received callback\n"); - fflush(0); + printf("received callback\n"); + fflush(0); #else cout << "received callback" << endl; #endif @@ -37,11 +37,11 @@ CallbackI::initiateCallback(const CallbackReceiverPrx& proxy, const Ice::Current cout << "initiating callback to: " << current.adapter->getCommunicator()->proxyToString(proxy) << endl; try { - proxy->callback(current.ctx); + proxy->callback(current.ctx); } catch(const Ice::Exception& ex) { - cout << ex << endl; + cout << ex << endl; } } @@ -51,10 +51,10 @@ CallbackI::shutdown(const Ice::Current& c) cout << "shutting down..." << endl; try { - c.adapter->getCommunicator()->shutdown(); + c.adapter->getCommunicator()->shutdown(); } catch(const Ice::Exception& ex) { - cout << ex << endl; + cout << ex << endl; } } diff --git a/cpp/demo/Glacier2/callback/Client.cpp b/cpp/demo/Glacier2/callback/Client.cpp index 063ea984470..c8623250faf 100644 --- a/cpp/demo/Glacier2/callback/Client.cpp +++ b/cpp/demo/Glacier2/callback/Client.cpp @@ -33,16 +33,16 @@ void menu() { cout << - "usage:\n" - "t: invoke callback as twoway\n" - "o: invoke callback as oneway\n" - "O: invoke callback as batch oneway\n" - "f: flush all batch requests\n" - "v: set/reset override context field\n" - "F: set/reset fake category\n" - "s: shutdown server\n" - "x: exit\n" - "?: help\n"; + "usage:\n" + "t: invoke callback as twoway\n" + "o: invoke callback as oneway\n" + "O: invoke callback as batch oneway\n" + "f: flush all batch requests\n" + "v: set/reset override context field\n" + "F: set/reset fake category\n" + "s: shutdown server\n" + "x: exit\n" + "?: help\n"; } int @@ -57,38 +57,38 @@ CallbackClient::run(int argc, char* argv[]) Ice::RouterPrx defaultRouter = communicator()->getDefaultRouter(); if(!defaultRouter) { - cerr << argv[0] << ": no default router set" << endl; - return EXIT_FAILURE; + cerr << argv[0] << ": no default router set" << endl; + return EXIT_FAILURE; } Glacier2::RouterPrx router = Glacier2::RouterPrx::checkedCast(defaultRouter); if(!router) { - cerr << argv[0] << ": configured router is not a Glacier2 router" << endl; - return EXIT_FAILURE; + cerr << argv[0] << ": configured router is not a Glacier2 router" << endl; + return EXIT_FAILURE; } while(true) { - cout << "This demo accepts any user-id / password combination.\n"; + cout << "This demo accepts any user-id / password combination.\n"; - string id; - cout << "user id: " << flush; - cin >> id; + string id; + cout << "user id: " << flush; + cin >> id; - string pw; - cout << "password: " << flush; - cin >> pw; + string pw; + cout << "password: " << flush; + cin >> pw; - try - { - router->createSession(id, pw); - break; - } - catch(const Glacier2::PermissionDeniedException& ex) - { - cout << "permission denied:\n" << ex.reason << endl; - } + try + { + router->createSession(id, pw); + break; + } + catch(const Glacier2::PermissionDeniedException& ex) + { + cout << "permission denied:\n" << ex.reason << endl; + } } Ice::Identity callbackReceiverIdent; @@ -119,97 +119,97 @@ CallbackClient::run(int argc, char* argv[]) char c; do { - try - { - cout << "==> "; - cin >> c; - if(c == 't') - { - Ice::Context context; - context["_fwd"] = "t"; - if(!override.empty()) - { - context["_ovrd"] = override; - } - twoway->initiateCallback(twowayR, context); - } - else if(c == 'o') - { - Ice::Context context; - context["_fwd"] = "o"; - if(!override.empty()) - { - context["_ovrd"] = override; - } - oneway->initiateCallback(onewayR, context); - } - else if(c == 'O') - { - Ice::Context context; - context["_fwd"] = "O"; - if(!override.empty()) - { - context["_ovrd"] = override; - } - batchOneway->initiateCallback(onewayR, context); - } - else if(c == 'f') - { - communicator()->flushBatchRequests(); - } - else if(c == 'v') - { - if(override.empty()) + try + { + cout << "==> "; + cin >> c; + if(c == 't') + { + Ice::Context context; + context["_fwd"] = "t"; + if(!override.empty()) { - override = "some_value"; - cout << "override context field is now `" << override << "'" << endl; - } - else - { - override.clear(); - cout << "override context field is empty" << endl; - } - } - else if(c == 'F') - { - fake = !fake; - - if(fake) - { - twowayR = CallbackReceiverPrx::uncheckedCast(twowayR->ice_identity(callbackReceiverFakeIdent)); - onewayR = CallbackReceiverPrx::uncheckedCast(onewayR->ice_identity(callbackReceiverFakeIdent)); - } - else - { - twowayR = CallbackReceiverPrx::uncheckedCast(twowayR->ice_identity(callbackReceiverIdent)); - onewayR = CallbackReceiverPrx::uncheckedCast(onewayR->ice_identity(callbackReceiverIdent)); - } - - cout << "callback receiver identity: " << communicator()->identityToString(twowayR->ice_getIdentity()) - << endl; - } - else if(c == 's') - { - twoway->shutdown(); - } - else if(c == 'x') - { - // Nothing to do - } - else if(c == '?') - { - menu(); - } - else - { - cout << "unknown command `" << c << "'" << endl; - menu(); - } - } - catch(const Ice::Exception& ex) - { - cerr << ex << endl; - } + context["_ovrd"] = override; + } + twoway->initiateCallback(twowayR, context); + } + else if(c == 'o') + { + Ice::Context context; + context["_fwd"] = "o"; + if(!override.empty()) + { + context["_ovrd"] = override; + } + oneway->initiateCallback(onewayR, context); + } + else if(c == 'O') + { + Ice::Context context; + context["_fwd"] = "O"; + if(!override.empty()) + { + context["_ovrd"] = override; + } + batchOneway->initiateCallback(onewayR, context); + } + else if(c == 'f') + { + communicator()->flushBatchRequests(); + } + else if(c == 'v') + { + if(override.empty()) + { + override = "some_value"; + cout << "override context field is now `" << override << "'" << endl; + } + else + { + override.clear(); + cout << "override context field is empty" << endl; + } + } + else if(c == 'F') + { + fake = !fake; + + if(fake) + { + twowayR = CallbackReceiverPrx::uncheckedCast(twowayR->ice_identity(callbackReceiverFakeIdent)); + onewayR = CallbackReceiverPrx::uncheckedCast(onewayR->ice_identity(callbackReceiverFakeIdent)); + } + else + { + twowayR = CallbackReceiverPrx::uncheckedCast(twowayR->ice_identity(callbackReceiverIdent)); + onewayR = CallbackReceiverPrx::uncheckedCast(onewayR->ice_identity(callbackReceiverIdent)); + } + + cout << "callback receiver identity: " << communicator()->identityToString(twowayR->ice_getIdentity()) + << endl; + } + else if(c == 's') + { + twoway->shutdown(); + } + else if(c == 'x') + { + // Nothing to do + } + else if(c == '?') + { + menu(); + } + else + { + cout << "unknown command `" << c << "'" << endl; + menu(); + } + } + catch(const Ice::Exception& ex) + { + cerr << ex << endl; + } } while(cin.good() && c != 'x'); @@ -221,15 +221,15 @@ CallbackClient::interruptCallback(int) { try { - communicator()->destroy(); + communicator()->destroy(); } catch(const IceUtil::Exception& ex) { - cerr << appName() << ": " << ex << endl; + cerr << appName() << ": " << ex << endl; } catch(...) { - cerr << appName() << ": unknown exception" << endl; + cerr << appName() << ": unknown exception" << endl; } exit(EXIT_SUCCESS); } diff --git a/cpp/demo/Glacier2/callback/SessionI.cpp b/cpp/demo/Glacier2/callback/SessionI.cpp index 7169270aac9..8bd4a13e769 100644 --- a/cpp/demo/Glacier2/callback/SessionI.cpp +++ b/cpp/demo/Glacier2/callback/SessionI.cpp @@ -14,7 +14,7 @@ using namespace std; bool DummyPermissionsVerifierI::checkPermissions(const string& userId, const string& password, string&, - const Ice::Current&) const + const Ice::Current&) const { cout << "verified user `" << userId << "' with password `" << password << "'" << endl; return true; diff --git a/cpp/demo/Glacier2/chat/ChatSessionI.cpp b/cpp/demo/Glacier2/chat/ChatSessionI.cpp index 33cfe63ad35..21e5c3c5e7e 100755 --- a/cpp/demo/Glacier2/chat/ChatSessionI.cpp +++ b/cpp/demo/Glacier2/chat/ChatSessionI.cpp @@ -44,7 +44,7 @@ ChatRoom::instance() IceUtil::StaticMutex::Lock sync(_instanceMutex); if(!_instance) { - _instance = new ChatRoom; + _instance = new ChatRoom; } return _instance; @@ -64,10 +64,10 @@ ChatRoom::leave(const ChatCallbackPrx& callback) list::iterator p; for(p = _members.begin(); p != _members.end(); ++p) { - if(Ice::proxyIdentityEqual(callback, *p)) - { - break; - } + if(Ice::proxyIdentityEqual(callback, *p)) + { + break; + } } assert(p != _members.end()); @@ -80,13 +80,13 @@ ChatRoom::message(const string& data) const Lock sync(*this); for(list::const_iterator p = _members.begin(); p != _members.end(); ++p) { - try - { - (*p)->message(data); - } - catch(const Ice::LocalException&) - { - } + try + { + (*p)->message(data); + } + catch(const Ice::LocalException&) + { + } } } @@ -101,10 +101,10 @@ ChatSessionI::setCallback(const ChatCallbackPrx& callback, const Ice::Current& c Lock sync(*this); if(!_callback) { - _callback = callback; - ChatRoomPtr chatRoom = ChatRoom::instance(); - chatRoom->message(_userId + " has entered the chat room."); - chatRoom->enter(callback); + _callback = callback; + ChatRoomPtr chatRoom = ChatRoom::instance(); + chatRoom->message(_userId + " has entered the chat room."); + chatRoom->enter(callback); } } @@ -120,10 +120,10 @@ ChatSessionI::destroy(const Ice::Current& current) Lock sync(*this); if(_callback) { - ChatRoomPtr chatRoom = ChatRoom::instance(); - chatRoom->leave(_callback); - _callback = 0; - chatRoom->message(_userId + " has left the chat room."); + ChatRoomPtr chatRoom = ChatRoom::instance(); + chatRoom->leave(_callback); + _callback = 0; + chatRoom->message(_userId + " has left the chat room."); } current.adapter->remove(current.id); } diff --git a/cpp/demo/Glacier2/chat/Client.cpp b/cpp/demo/Glacier2/chat/Client.cpp index 4aadf845f5c..d6c9c46da19 100755 --- a/cpp/demo/Glacier2/chat/Client.cpp +++ b/cpp/demo/Glacier2/chat/Client.cpp @@ -73,16 +73,16 @@ public: { #ifdef __xlC__ - // - // The xlC compiler synchronizes cin and cout; to see the messages - // while accepting input through cin, we have to print the messages - // with printf - // - - printf("%s\n", data.c_str()); - fflush(0); + // + // The xlC compiler synchronizes cin and cout; to see the messages + // while accepting input through cin, we have to print the messages + // with printf + // + + printf("%s\n", data.c_str()); + fflush(0); #else - cout << data << endl; + cout << data << endl; #endif } }; @@ -94,128 +94,128 @@ public: virtual int run(int argc, char* argv[]) { - // - // Since this is an interactive demo we want the custom interrupt - // callback to be called when the process is interrupted. - // - callbackOnInterrupt(); - - { - IceUtil::Mutex::Lock sync(_mutex); - Ice::RouterPrx defaultRouter = communicator()->getDefaultRouter(); - if(!defaultRouter) - { - cerr << argv[0] << ": no default router set" << endl; - return EXIT_FAILURE; - } - - _router = Glacier2::RouterPrx::checkedCast(defaultRouter); - if(!_router) - { - cerr << argv[0] << ": configured router is not a Glacier2 router" << endl; - return EXIT_FAILURE; - } - } - - ChatSessionPrx session; - while(true) - { - cout << "This demo accepts any user-id / password combination.\n"; - - string id; - cout << "user id: " << flush; - getline(cin, id); - id = trim(id); - - string pw; - cout << "password: " << flush; - getline(cin, pw); - pw = trim(pw); - - try - { - session = ChatSessionPrx::uncheckedCast(_router->createSession(id, pw)); - break; - } - catch(const Glacier2::PermissionDeniedException& ex) - { - cout << "permission denied:\n" << ex.reason << endl; - } - } - - { - IceUtil::Mutex::Lock sync(_mutex); - _ping = new SessionPingThread(session, (long)_router->getSessionTimeout() / 2); - _ping->start(); - } - - Ice::Identity callbackReceiverIdent; - callbackReceiverIdent.name = "callbackReceiver"; - callbackReceiverIdent.category = _router->getCategoryForClient(); - - Ice::ObjectAdapterPtr adapter = communicator()->createObjectAdapter("Chat.Client"); - ChatCallbackPrx callback = ChatCallbackPrx::uncheckedCast( - adapter->add(new ChatCallbackI, callbackReceiverIdent)); - adapter->activate(); - - session->setCallback(callback); - - menu(); - - try - { - do - { - string s; - cout << "==> "; - getline(cin, s); - s = trim(s); - if(!s.empty()) - { - if(s[0] == '/') - { - if(s == "/quit") - { - break; - } - menu(); - } - else - { - session->say(s); - } - } - } - while(cin.good()); - - cleanup(); - } - catch(const Ice::Exception& ex) - { - cerr << ex << endl; - cleanup(); - - return EXIT_FAILURE; - } - return EXIT_SUCCESS; + // + // Since this is an interactive demo we want the custom interrupt + // callback to be called when the process is interrupted. + // + callbackOnInterrupt(); + + { + IceUtil::Mutex::Lock sync(_mutex); + Ice::RouterPrx defaultRouter = communicator()->getDefaultRouter(); + if(!defaultRouter) + { + cerr << argv[0] << ": no default router set" << endl; + return EXIT_FAILURE; + } + + _router = Glacier2::RouterPrx::checkedCast(defaultRouter); + if(!_router) + { + cerr << argv[0] << ": configured router is not a Glacier2 router" << endl; + return EXIT_FAILURE; + } + } + + ChatSessionPrx session; + while(true) + { + cout << "This demo accepts any user-id / password combination.\n"; + + string id; + cout << "user id: " << flush; + getline(cin, id); + id = trim(id); + + string pw; + cout << "password: " << flush; + getline(cin, pw); + pw = trim(pw); + + try + { + session = ChatSessionPrx::uncheckedCast(_router->createSession(id, pw)); + break; + } + catch(const Glacier2::PermissionDeniedException& ex) + { + cout << "permission denied:\n" << ex.reason << endl; + } + } + + { + IceUtil::Mutex::Lock sync(_mutex); + _ping = new SessionPingThread(session, (long)_router->getSessionTimeout() / 2); + _ping->start(); + } + + Ice::Identity callbackReceiverIdent; + callbackReceiverIdent.name = "callbackReceiver"; + callbackReceiverIdent.category = _router->getCategoryForClient(); + + Ice::ObjectAdapterPtr adapter = communicator()->createObjectAdapter("Chat.Client"); + ChatCallbackPrx callback = ChatCallbackPrx::uncheckedCast( + adapter->add(new ChatCallbackI, callbackReceiverIdent)); + adapter->activate(); + + session->setCallback(callback); + + menu(); + + try + { + do + { + string s; + cout << "==> "; + getline(cin, s); + s = trim(s); + if(!s.empty()) + { + if(s[0] == '/') + { + if(s == "/quit") + { + break; + } + menu(); + } + else + { + session->say(s); + } + } + } + while(cin.good()); + + cleanup(); + } + catch(const Ice::Exception& ex) + { + cerr << ex << endl; + cleanup(); + + return EXIT_FAILURE; + } + return EXIT_SUCCESS; } virtual void interruptCallback(int) { - try - { - communicator()->destroy(); - } - catch(const IceUtil::Exception& ex) - { - cerr << appName() << ": " << ex << endl; - } - catch(...) - { - cerr << appName() << ": unknown exception" << endl; - } - exit(EXIT_SUCCESS); + try + { + communicator()->destroy(); + } + catch(const IceUtil::Exception& ex) + { + cerr << appName() << ": " << ex << endl; + } + catch(...) + { + cerr << appName() << ": unknown exception" << endl; + } + exit(EXIT_SUCCESS); } private: @@ -223,45 +223,45 @@ private: void cleanup() { - IceUtil::Mutex::Lock sync(_mutex); - if(_router) - { - try - { - _router->destroySession(); - } - catch(const Ice::ConnectionLostException&) - { - // - // Expected: the router closed the connection. - // - } - _router = 0; - } - if(_ping) - { - _ping->destroy(); - _ping->getThreadControl().join(); - _ping = 0; - } + IceUtil::Mutex::Lock sync(_mutex); + if(_router) + { + try + { + _router->destroySession(); + } + catch(const Ice::ConnectionLostException&) + { + // + // Expected: the router closed the connection. + // + } + _router = 0; + } + if(_ping) + { + _ping->destroy(); + _ping->getThreadControl().join(); + _ping = 0; + } } void menu() { - cout << "enter /quit to exit." << endl; + cout << "enter /quit to exit." << endl; } string trim(const string& s) { - static const string delims = "\t\r\n "; - string::size_type last = s.find_last_not_of(delims); - if(last != string::npos) - { - return s.substr(s.find_first_not_of(delims), last+1); - } - return s; + static const string delims = "\t\r\n "; + string::size_type last = s.find_last_not_of(delims); + if(last != string::npos) + { + return s.substr(s.find_first_not_of(delims), last+1); + } + return s; } IceUtil::Mutex _mutex; diff --git a/cpp/demo/Glacier2/chat/Server.cpp b/cpp/demo/Glacier2/chat/Server.cpp index e2a26e34c21..53c811a3b64 100755 --- a/cpp/demo/Glacier2/chat/Server.cpp +++ b/cpp/demo/Glacier2/chat/Server.cpp @@ -21,7 +21,7 @@ public: virtual Glacier2::SessionPrx create(const string& userId, const Glacier2::SessionControlPrx&, const Ice::Current& current) { - return Glacier2::SessionPrx::uncheckedCast(current.adapter->addWithUUID(new ChatSessionI(userId))); + return Glacier2::SessionPrx::uncheckedCast(current.adapter->addWithUUID(new ChatSessionI(userId))); } }; @@ -32,13 +32,13 @@ public: virtual int run(int, char*[]) { - Ice::ObjectAdapterPtr adapter = communicator()->createObjectAdapter("ChatServer"); - - adapter->add(new ChatSessionManagerI, communicator()->stringToIdentity("ChatSessionManager")); - adapter->activate(); - communicator()->waitForShutdown(); - - return EXIT_SUCCESS; + Ice::ObjectAdapterPtr adapter = communicator()->createObjectAdapter("ChatServer"); + + adapter->add(new ChatSessionManagerI, communicator()->stringToIdentity("ChatSessionManager")); + adapter->activate(); + communicator()->waitForShutdown(); + + return EXIT_SUCCESS; } }; diff --git a/cpp/demo/Ice/MFC/client/HelloClient.cpp b/cpp/demo/Ice/MFC/client/HelloClient.cpp index 73d4a30e6f5..cc97e071f20 100644 --- a/cpp/demo/Ice/MFC/client/HelloClient.cpp +++ b/cpp/demo/Ice/MFC/client/HelloClient.cpp @@ -48,9 +48,9 @@ CHelloClientApp::InitInstance() try { int argc = 0; - Ice::InitializationData initData; - initData.properties = Ice::createProperties(); - initData.properties->load("config"); + Ice::InitializationData initData; + initData.properties = Ice::createProperties(); + initData.properties->load("config"); communicator = Ice::initialize(argc, 0, initData); } catch(const IceUtil::Exception& ex) diff --git a/cpp/demo/Ice/MFC/client/stdafx.h b/cpp/demo/Ice/MFC/client/stdafx.h index 81d5a220522..6ad764438f9 100644 --- a/cpp/demo/Ice/MFC/client/stdafx.h +++ b/cpp/demo/Ice/MFC/client/stdafx.h @@ -22,30 +22,30 @@ #endif #ifndef VC_EXTRALEAN -#define VC_EXTRALEAN // Exclude rarely-used stuff from Windows headers +#define VC_EXTRALEAN // Exclude rarely-used stuff from Windows headers #endif // Modify the following defines if you have to target a platform prior to the ones specified below. // Refer to MSDN for the latest info on corresponding values for different platforms. -#ifndef WINVER // Allow use of features specific to Windows 95 and Windows NT 4 or later. -#define WINVER 0x0400 // Change this to the appropriate value to target Windows 98 and Windows 2000 or later. +#ifndef WINVER // Allow use of features specific to Windows 95 and Windows NT 4 or later. +#define WINVER 0x0400 // Change this to the appropriate value to target Windows 98 and Windows 2000 or later. #endif -#ifndef _WIN32_WINNT // Allow use of features specific to Windows NT 4 or later. -#define _WIN32_WINNT 0x0400 // Change this to the appropriate value to target Windows 98 and Windows 2000 or later. -#endif +#ifndef _WIN32_WINNT // Allow use of features specific to Windows NT 4 or later. +#define _WIN32_WINNT 0x0400 // Change this to the appropriate value to target Windows 98 and Windows 2000 or later. +#endif #if 0 -#ifndef _WIN32_WINDOWS // Allow use of features specific to Windows 98 or later. +#ifndef _WIN32_WINDOWS // Allow use of features specific to Windows 98 or later. #define _WIN32_WINDOWS 0x0410 // Change this to the appropriate value to target Windows Me or later. #endif -#ifndef _WIN32_IE // Allow use of features specific to IE 4.0 or later. -#define _WIN32_IE 0x0400 // Change this to the appropriate value to target IE 5.0 or later. +#ifndef _WIN32_IE // Allow use of features specific to IE 4.0 or later. +#define _WIN32_IE 0x0400 // Change this to the appropriate value to target IE 5.0 or later. #endif #endif -#define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS // some CString constructors will be explicit +#define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS // some CString constructors will be explicit // turns off MFC's hiding of some common and often safely ignored warning messages #define _AFX_ALL_WARNINGS @@ -53,9 +53,9 @@ #include // MFC core and standard components #include // MFC extensions -#include // MFC support for Internet Explorer 4 Common Controls +#include // MFC support for Internet Explorer 4 Common Controls #ifndef _AFX_NO_AFXCMN_SUPPORT -#include // MFC support for Windows Common Controls +#include // MFC support for Windows Common Controls #endif // _AFX_NO_AFXCMN_SUPPORT #include diff --git a/cpp/demo/Ice/MFC/server/HelloServer.cpp b/cpp/demo/Ice/MFC/server/HelloServer.cpp index 064b6e4e0cf..6d60db6f561 100644 --- a/cpp/demo/Ice/MFC/server/HelloServer.cpp +++ b/cpp/demo/Ice/MFC/server/HelloServer.cpp @@ -51,11 +51,11 @@ BOOL CHelloServerApp::InitInstance() try { int argc = 0; - Ice::InitializationData initData; + Ice::InitializationData initData; initData.properties = Ice::createProperties(); - initData.properties->load("config"); + initData.properties->load("config"); log = new LogI; - initData.logger = log; + initData.logger = log; communicator = Ice::initialize(argc, 0, initData); adapter = communicator->createObjectAdapter("Hello"); } diff --git a/cpp/demo/Ice/MFC/server/LogI.cpp b/cpp/demo/Ice/MFC/server/LogI.cpp index a8c18c4e2f5..2e153f952f7 100644 --- a/cpp/demo/Ice/MFC/server/LogI.cpp +++ b/cpp/demo/Ice/MFC/server/LogI.cpp @@ -66,7 +66,7 @@ LogI::message(const string& msg) string line = msg + "\r\n"; if(_hwnd) { - post(line); + post(line); } else { @@ -80,7 +80,7 @@ LogI::setHandle(HWND hwnd) _hwnd = hwnd; if(_hwnd != 0 && !_buffer.empty()) { - post(_buffer); + post(_buffer); _buffer.clear(); } } diff --git a/cpp/demo/Ice/MFC/server/stdafx.h b/cpp/demo/Ice/MFC/server/stdafx.h index 81d5a220522..6ad764438f9 100644 --- a/cpp/demo/Ice/MFC/server/stdafx.h +++ b/cpp/demo/Ice/MFC/server/stdafx.h @@ -22,30 +22,30 @@ #endif #ifndef VC_EXTRALEAN -#define VC_EXTRALEAN // Exclude rarely-used stuff from Windows headers +#define VC_EXTRALEAN // Exclude rarely-used stuff from Windows headers #endif // Modify the following defines if you have to target a platform prior to the ones specified below. // Refer to MSDN for the latest info on corresponding values for different platforms. -#ifndef WINVER // Allow use of features specific to Windows 95 and Windows NT 4 or later. -#define WINVER 0x0400 // Change this to the appropriate value to target Windows 98 and Windows 2000 or later. +#ifndef WINVER // Allow use of features specific to Windows 95 and Windows NT 4 or later. +#define WINVER 0x0400 // Change this to the appropriate value to target Windows 98 and Windows 2000 or later. #endif -#ifndef _WIN32_WINNT // Allow use of features specific to Windows NT 4 or later. -#define _WIN32_WINNT 0x0400 // Change this to the appropriate value to target Windows 98 and Windows 2000 or later. -#endif +#ifndef _WIN32_WINNT // Allow use of features specific to Windows NT 4 or later. +#define _WIN32_WINNT 0x0400 // Change this to the appropriate value to target Windows 98 and Windows 2000 or later. +#endif #if 0 -#ifndef _WIN32_WINDOWS // Allow use of features specific to Windows 98 or later. +#ifndef _WIN32_WINDOWS // Allow use of features specific to Windows 98 or later. #define _WIN32_WINDOWS 0x0410 // Change this to the appropriate value to target Windows Me or later. #endif -#ifndef _WIN32_IE // Allow use of features specific to IE 4.0 or later. -#define _WIN32_IE 0x0400 // Change this to the appropriate value to target IE 5.0 or later. +#ifndef _WIN32_IE // Allow use of features specific to IE 4.0 or later. +#define _WIN32_IE 0x0400 // Change this to the appropriate value to target IE 5.0 or later. #endif #endif -#define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS // some CString constructors will be explicit +#define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS // some CString constructors will be explicit // turns off MFC's hiding of some common and often safely ignored warning messages #define _AFX_ALL_WARNINGS @@ -53,9 +53,9 @@ #include // MFC core and standard components #include // MFC extensions -#include // MFC support for Internet Explorer 4 Common Controls +#include // MFC support for Internet Explorer 4 Common Controls #ifndef _AFX_NO_AFXCMN_SUPPORT -#include // MFC support for Windows Common Controls +#include // MFC support for Windows Common Controls #endif // _AFX_NO_AFXCMN_SUPPORT #include diff --git a/cpp/demo/Ice/async/Client.cpp b/cpp/demo/Ice/async/Client.cpp index cb3e7e862c0..e164fb18cc3 100644 --- a/cpp/demo/Ice/async/Client.cpp +++ b/cpp/demo/Ice/async/Client.cpp @@ -54,8 +54,8 @@ AsyncClient::run(int argc, char* argv[]) HelloPrx hello = HelloPrx::checkedCast(communicator()->propertyToProxy("Hello.Proxy")); if(!hello) { - cerr << argv[0] << ": invalid proxy" << endl; - return EXIT_FAILURE; + cerr << argv[0] << ": invalid proxy" << endl; + return EXIT_FAILURE; } menu(); @@ -63,40 +63,40 @@ AsyncClient::run(int argc, char* argv[]) char c; do { - try - { - cout << "==> "; - cin >> c; - if(c == 'i') - { - hello->sayHello(0); - } - else if(c == 'd') - { - hello->sayHello_async(new AMI_Hello_sayHelloI, 5000); - } - else if(c == 's') - { - hello->shutdown(); - } - else if(c == 'x') - { - // Nothing to do - } - else if(c == '?') - { - menu(); - } - else - { - cout << "unknown command `" << c << "'" << endl; - menu(); - } - } - catch(const Ice::Exception& ex) - { - cerr << ex << endl; - } + try + { + cout << "==> "; + cin >> c; + if(c == 'i') + { + hello->sayHello(0); + } + else if(c == 'd') + { + hello->sayHello_async(new AMI_Hello_sayHelloI, 5000); + } + else if(c == 's') + { + hello->shutdown(); + } + else if(c == 'x') + { + // Nothing to do + } + else if(c == '?') + { + menu(); + } + else + { + cout << "unknown command `" << c << "'" << endl; + menu(); + } + } + catch(const Ice::Exception& ex) + { + cerr << ex << endl; + } } while(cin.good() && c != 'x'); @@ -125,10 +125,10 @@ void AsyncClient::menu() { cout << - "usage:\n" - "i: send immediate greeting\n" - "d: send delayed greeting\n" - "s: shutdown server\n" - "x: exit\n" - "?: help\n"; + "usage:\n" + "i: send immediate greeting\n" + "d: send delayed greeting\n" + "s: shutdown server\n" + "x: exit\n" + "?: help\n"; } diff --git a/cpp/demo/Ice/async/WorkQueue.cpp b/cpp/demo/Ice/async/WorkQueue.cpp index 0493b8087ab..fc506938210 100644 --- a/cpp/demo/Ice/async/WorkQueue.cpp +++ b/cpp/demo/Ice/async/WorkQueue.cpp @@ -25,34 +25,34 @@ WorkQueue::run() while(!_done) { if(_callbacks.size() == 0) - { - _monitor.wait(); - } + { + _monitor.wait(); + } - if(_callbacks.size() != 0) - { - // - // Get next work item. - // - CallbackEntry entry = _callbacks.front(); + if(_callbacks.size() != 0) + { + // + // Get next work item. + // + CallbackEntry entry = _callbacks.front(); - // - // Wait for the amount of time indicated in delay to - // emulate a process that takes a significant period of - // time to complete. - // - _monitor.timedWait(IceUtil::Time::milliSeconds(entry.delay)); + // + // Wait for the amount of time indicated in delay to + // emulate a process that takes a significant period of + // time to complete. + // + _monitor.timedWait(IceUtil::Time::milliSeconds(entry.delay)); - if(!_done) - { - // - // Print greeting and send response. - // - _callbacks.pop_front(); - cout << "Belated Hello World!" << endl; - entry.cb->ice_response(); - } - } + if(!_done) + { + // + // Print greeting and send response. + // + _callbacks.pop_front(); + cout << "Belated Hello World!" << endl; + entry.cb->ice_response(); + } + } } // @@ -79,17 +79,17 @@ WorkQueue::add(const Demo::AMD_Hello_sayHelloPtr& cb, int delay) entry.cb = cb; entry.delay = delay; - if(_callbacks.size() == 0) - { + if(_callbacks.size() == 0) + { _monitor.notify(); - } + } _callbacks.push_back(entry); } else { // - // Destroyed, throw exception. - // + // Destroyed, throw exception. + // cb->ice_exception(Demo::RequestCanceledException()); } } diff --git a/cpp/demo/Ice/async/WorkQueue.h b/cpp/demo/Ice/async/WorkQueue.h index 9147b2f615d..47c3ebf04da 100644 --- a/cpp/demo/Ice/async/WorkQueue.h +++ b/cpp/demo/Ice/async/WorkQueue.h @@ -33,7 +33,7 @@ private: struct CallbackEntry { Demo::AMD_Hello_sayHelloPtr cb; - int delay; + int delay; }; IceUtil::Monitor _monitor; diff --git a/cpp/demo/Ice/bidir/CallbackI.cpp b/cpp/demo/Ice/bidir/CallbackI.cpp index 05c6e288d82..d24888c0dd3 100644 --- a/cpp/demo/Ice/bidir/CallbackI.cpp +++ b/cpp/demo/Ice/bidir/CallbackI.cpp @@ -28,15 +28,15 @@ CallbackSenderI::destroy() IceUtil::ThreadPtr callbackSenderThread; { - IceUtil::Monitor::Lock lock(*this); - - cout << "destroying callback sender" << endl; - _destroy = true; - - notify(); + IceUtil::Monitor::Lock lock(*this); + + cout << "destroying callback sender" << endl; + _destroy = true; + + notify(); - callbackSenderThread = _callbackSenderThread; - _callbackSenderThread = 0; // Resolve cyclic dependency. + callbackSenderThread = _callbackSenderThread; + _callbackSenderThread = 0; // Resolve cyclic dependency. } callbackSenderThread->getThreadControl().join(); @@ -66,27 +66,27 @@ CallbackSenderI::run() while(!_destroy) { - timedWait(IceUtil::Time::seconds(2)); + timedWait(IceUtil::Time::seconds(2)); - if(!_destroy && !_clients.empty()) - { - ++_num; - - set::iterator p = _clients.begin(); - while(p != _clients.end()) - { - try - { - (*p)->callback(_num); - ++p; - } - catch(const Exception& ex) - { - cerr << "removing client `" << _communicator->identityToString((*p)->ice_getIdentity()) << "':\n" - << ex << endl; - _clients.erase(p++); - } - } - } + if(!_destroy && !_clients.empty()) + { + ++_num; + + set::iterator p = _clients.begin(); + while(p != _clients.end()) + { + try + { + (*p)->callback(_num); + ++p; + } + catch(const Exception& ex) + { + cerr << "removing client `" << _communicator->identityToString((*p)->ice_getIdentity()) << "':\n" + << ex << endl; + _clients.erase(p++); + } + } + } } } diff --git a/cpp/demo/Ice/bidir/CallbackI.h b/cpp/demo/Ice/bidir/CallbackI.h index 2af7a28bce7..e99789bfa31 100644 --- a/cpp/demo/Ice/bidir/CallbackI.h +++ b/cpp/demo/Ice/bidir/CallbackI.h @@ -48,19 +48,19 @@ private: { public: - CallbackSenderThread(const CallbackSenderIPtr& callbackSender) : - _callbackSender(callbackSender) - { - } + CallbackSenderThread(const CallbackSenderIPtr& callbackSender) : + _callbackSender(callbackSender) + { + } - virtual void run() - { - _callbackSender->run(); - } + virtual void run() + { + _callbackSender->run(); + } private: - const CallbackSenderIPtr _callbackSender; + const CallbackSenderIPtr _callbackSender; }; IceUtil::ThreadPtr _callbackSenderThread; diff --git a/cpp/demo/Ice/bidir/Client.cpp b/cpp/demo/Ice/bidir/Client.cpp index a7e8198ab45..9dbd44ab388 100644 --- a/cpp/demo/Ice/bidir/Client.cpp +++ b/cpp/demo/Ice/bidir/Client.cpp @@ -21,7 +21,7 @@ public: virtual void callback(Ice::Int num, const Ice::Current&) { - cout << "received callback #" << num << endl; + cout << "received callback #" << num << endl; } }; @@ -46,8 +46,8 @@ CallbackClient::run(int argc, char* argv[]) CallbackSenderPrx::checkedCast(communicator()->propertyToProxy("Callback.Client.CallbackServer")); if(!server) { - cerr << appName() << ": invalid proxy" << endl; - return EXIT_FAILURE; + cerr << appName() << ": invalid proxy" << endl; + return EXIT_FAILURE; } Ice::ObjectAdapterPtr adapter = communicator()->createObjectAdapter(""); diff --git a/cpp/demo/Ice/bidir/Server.cpp b/cpp/demo/Ice/bidir/Server.cpp index a311635864c..170d12ad77d 100644 --- a/cpp/demo/Ice/bidir/Server.cpp +++ b/cpp/demo/Ice/bidir/Server.cpp @@ -38,12 +38,12 @@ CallbackServer::run(int argc, char* argv[]) sender->start(); try { - communicator()->waitForShutdown(); + communicator()->waitForShutdown(); } catch(...) { - sender->destroy(); - throw; + sender->destroy(); + throw; } sender->destroy(); diff --git a/cpp/demo/Ice/callback/CallbackSenderI.cpp b/cpp/demo/Ice/callback/CallbackSenderI.cpp index 302dbecdba4..f50c47e7a32 100644 --- a/cpp/demo/Ice/callback/CallbackSenderI.cpp +++ b/cpp/demo/Ice/callback/CallbackSenderI.cpp @@ -20,11 +20,11 @@ CallbackSenderI::initiateCallback(const CallbackReceiverPrx& proxy, const Curren cout << "initiating callback" << endl; try { - proxy->callback(current.ctx); + proxy->callback(current.ctx); } catch(const Exception& ex) { - cout << ex << endl; + cout << ex << endl; } } @@ -34,10 +34,10 @@ CallbackSenderI::shutdown(const Current& c) cout << "shutting down..." << endl; try { - c.adapter->getCommunicator()->shutdown(); + c.adapter->getCommunicator()->shutdown(); } catch(const Exception& ex) { - cout << ex << endl; + cout << ex << endl; } } diff --git a/cpp/demo/Ice/callback/Client.cpp b/cpp/demo/Ice/callback/Client.cpp index 83959a1e5fe..a68bed47b99 100644 --- a/cpp/demo/Ice/callback/Client.cpp +++ b/cpp/demo/Ice/callback/Client.cpp @@ -20,15 +20,15 @@ public: virtual void callback(const Ice::Current&) { #ifdef __xlC__ - // - // The xlC compiler synchronizes cin and cout; to see the messages - // while accepting input through cin, we have to print the messages - // with printf - // - printf("received callback\n"); - fflush(0); + // + // The xlC compiler synchronizes cin and cout; to see the messages + // while accepting input through cin, we have to print the messages + // with printf + // + printf("received callback\n"); + fflush(0); #else - cout << "received callback" << endl; + cout << "received callback" << endl; #endif } }; @@ -62,12 +62,12 @@ CallbackClient::run(int argc, char* argv[]) callbackOnInterrupt(); CallbackSenderPrx twoway = CallbackSenderPrx::checkedCast( - communicator()->propertyToProxy("Callback.Client.CallbackServer")-> - ice_twoway()->ice_timeout(-1)->ice_secure(false)); + communicator()->propertyToProxy("Callback.Client.CallbackServer")-> + ice_twoway()->ice_timeout(-1)->ice_secure(false)); if(!twoway) { - cerr << appName() << ": invalid proxy" << endl; - return EXIT_FAILURE; + cerr << appName() << ": invalid proxy" << endl; + return EXIT_FAILURE; } CallbackSenderPrx oneway = CallbackSenderPrx::uncheckedCast(twoway->ice_oneway()); CallbackSenderPrx batchOneway = CallbackSenderPrx::uncheckedCast(twoway->ice_batchOneway()); @@ -79,7 +79,7 @@ CallbackClient::run(int argc, char* argv[]) adapter->activate(); CallbackReceiverPrx twowayR = CallbackReceiverPrx::uncheckedCast( - adapter->createProxy(communicator()->stringToIdentity("callbackReceiver"))); + adapter->createProxy(communicator()->stringToIdentity("callbackReceiver"))); CallbackReceiverPrx onewayR = CallbackReceiverPrx::uncheckedCast(twowayR->ice_oneway()); CallbackReceiverPrx datagramR = CallbackReceiverPrx::uncheckedCast(twowayR->ice_datagram()); @@ -91,24 +91,24 @@ CallbackClient::run(int argc, char* argv[]) char c; do { - try - { - cout << "==> "; - cin >> c; - if(c == 't') - { - twoway->initiateCallback(twowayR); - } - else if(c == 'o') - { - oneway->initiateCallback(onewayR); - } - else if(c == 'O') - { - batchOneway->initiateCallback(onewayR); - } - else if(c == 'd') - { + try + { + cout << "==> "; + cin >> c; + if(c == 't') + { + twoway->initiateCallback(twowayR); + } + else if(c == 'o') + { + oneway->initiateCallback(onewayR); + } + else if(c == 'O') + { + batchOneway->initiateCallback(onewayR); + } + else if(c == 'd') + { if(secure) { cout << "secure datagrams are not supported" << endl; @@ -117,9 +117,9 @@ CallbackClient::run(int argc, char* argv[]) { datagram->initiateCallback(datagramR); } - } - else if(c == 'D') - { + } + else if(c == 'D') + { if(secure) { cout << "secure datagrams are not supported" << endl; @@ -128,57 +128,57 @@ CallbackClient::run(int argc, char* argv[]) { batchDatagram->initiateCallback(datagramR); } - } - else if(c == 'f') - { - communicator()->flushBatchRequests(); - } - else if(c == 'S') - { - secure = !secure; - secureStr = secure ? "s" : ""; - - twoway = CallbackSenderPrx::uncheckedCast(twoway->ice_secure(secure)); - oneway = CallbackSenderPrx::uncheckedCast(oneway->ice_secure(secure)); - batchOneway = CallbackSenderPrx::uncheckedCast(batchOneway->ice_secure(secure)); - datagram = CallbackSenderPrx::uncheckedCast(datagram->ice_secure(secure)); - batchDatagram = CallbackSenderPrx::uncheckedCast(batchDatagram->ice_secure(secure)); - - twowayR = CallbackReceiverPrx::uncheckedCast(twowayR->ice_secure(secure)); - onewayR = CallbackReceiverPrx::uncheckedCast(onewayR->ice_secure(secure)); - datagramR = CallbackReceiverPrx::uncheckedCast(datagramR->ice_secure(secure)); - - if(secure) - { - cout << "secure mode is now on" << endl; - } - else - { - cout << "secure mode is now off" << endl; - } - } - else if(c == 's') - { - twoway->shutdown(); - } - else if(c == 'x') - { - // Nothing to do - } - else if(c == '?') - { - menu(); - } - else - { - cout << "unknown command `" << c << "'" << endl; - menu(); - } - } - catch(const Ice::Exception& ex) - { - cerr << ex << endl; - } + } + else if(c == 'f') + { + communicator()->flushBatchRequests(); + } + else if(c == 'S') + { + secure = !secure; + secureStr = secure ? "s" : ""; + + twoway = CallbackSenderPrx::uncheckedCast(twoway->ice_secure(secure)); + oneway = CallbackSenderPrx::uncheckedCast(oneway->ice_secure(secure)); + batchOneway = CallbackSenderPrx::uncheckedCast(batchOneway->ice_secure(secure)); + datagram = CallbackSenderPrx::uncheckedCast(datagram->ice_secure(secure)); + batchDatagram = CallbackSenderPrx::uncheckedCast(batchDatagram->ice_secure(secure)); + + twowayR = CallbackReceiverPrx::uncheckedCast(twowayR->ice_secure(secure)); + onewayR = CallbackReceiverPrx::uncheckedCast(onewayR->ice_secure(secure)); + datagramR = CallbackReceiverPrx::uncheckedCast(datagramR->ice_secure(secure)); + + if(secure) + { + cout << "secure mode is now on" << endl; + } + else + { + cout << "secure mode is now off" << endl; + } + } + else if(c == 's') + { + twoway->shutdown(); + } + else if(c == 'x') + { + // Nothing to do + } + else if(c == '?') + { + menu(); + } + else + { + cout << "unknown command `" << c << "'" << endl; + menu(); + } + } + catch(const Ice::Exception& ex) + { + cerr << ex << endl; + } } while(cin.good() && c != 'x'); @@ -190,15 +190,15 @@ CallbackClient::interruptCallback(int) { try { - communicator()->destroy(); + communicator()->destroy(); } catch(const IceUtil::Exception& ex) { - cerr << appName() << ": " << ex << endl; + cerr << appName() << ": " << ex << endl; } catch(...) { - cerr << appName() << ": unknown exception" << endl; + cerr << appName() << ": unknown exception" << endl; } exit(EXIT_SUCCESS); } @@ -207,15 +207,15 @@ void CallbackClient::menu() { cout << - "usage:\n" - "t: send callback as twoway\n" - "o: send callback as oneway\n" - "O: send callback as batch oneway\n" - "d: send callback as datagram\n" - "D: send callback as batch datagram\n" - "f: flush all batch requests\n" - "S: switch secure mode on/off\n" - "s: shutdown server\n" - "x: exit\n" - "?: help\n"; + "usage:\n" + "t: send callback as twoway\n" + "o: send callback as oneway\n" + "O: send callback as batch oneway\n" + "d: send callback as datagram\n" + "D: send callback as batch datagram\n" + "f: flush all batch requests\n" + "S: switch secure mode on/off\n" + "s: shutdown server\n" + "x: exit\n" + "?: help\n"; } diff --git a/cpp/demo/Ice/converter/Client.cpp b/cpp/demo/Ice/converter/Client.cpp index 123ad49dc52..3db03370c4f 100644 --- a/cpp/demo/Ice/converter/Client.cpp +++ b/cpp/demo/Ice/converter/Client.cpp @@ -19,12 +19,12 @@ void menu() { cout << - "usage:\n" - "t: send greeting with conversion\n" - "u: send greeting without conversion\n" - "s: shutdown server\n" - "x: exit\n" - "?: help\n"; + "usage:\n" + "t: send greeting with conversion\n" + "u: send greeting without conversion\n" + "s: shutdown server\n" + "x: exit\n" + "?: help\n"; } int @@ -34,15 +34,15 @@ run(int argc, char* argv[], const Ice::CommunicatorPtr& communicator1, const Ice EchoPrx echo1 = EchoPrx::checkedCast(communicator1->propertyToProxy(proxyProperty)); if(!echo1) { - cerr << argv[0] << ": invalid proxy" << endl; - return EXIT_FAILURE; + cerr << argv[0] << ": invalid proxy" << endl; + return EXIT_FAILURE; } EchoPrx echo2 = EchoPrx::checkedCast(communicator2->propertyToProxy(proxyProperty)); if(!echo2) { - cerr << argv[0] << ": invalid proxy" << endl; - return EXIT_FAILURE; + cerr << argv[0] << ": invalid proxy" << endl; + return EXIT_FAILURE; } menu(); @@ -52,42 +52,42 @@ run(int argc, char* argv[], const Ice::CommunicatorPtr& communicator1, const Ice char c; do { - try - { - cout << "==> "; - cin >> c; - if(c == 't') - { - string ret = echo1->echoString(greeting); - cout << "Received (LATIN-1): \"" << IceUtil::escapeString(ret, "") << '\"' << endl; - } - else if(c == 'u') - { - string ret = echo2->echoString(greeting); - cout << "Received (LATIN-1): \"" << IceUtil::escapeString(ret, "") << '\"' << endl; - } - else if(c == 's') - { - echo1->shutdown(); - } - else if(c == 'x') - { - // Nothing to do - } - else if(c == '?') - { - menu(); - } - else - { - cout << "unknown command `" << c << "'" << endl; - menu(); - } - } - catch(const Ice::Exception& ex) - { - cerr << ex << endl; - } + try + { + cout << "==> "; + cin >> c; + if(c == 't') + { + string ret = echo1->echoString(greeting); + cout << "Received (LATIN-1): \"" << IceUtil::escapeString(ret, "") << '\"' << endl; + } + else if(c == 'u') + { + string ret = echo2->echoString(greeting); + cout << "Received (LATIN-1): \"" << IceUtil::escapeString(ret, "") << '\"' << endl; + } + else if(c == 's') + { + echo1->shutdown(); + } + else if(c == 'x') + { + // Nothing to do + } + else if(c == '?') + { + menu(); + } + else + { + cout << "unknown command `" << c << "'" << endl; + menu(); + } + } + catch(const Ice::Exception& ex) + { + cerr << ex << endl; + } } while(cin.good() && c != 'x'); @@ -104,18 +104,18 @@ main(int argc, char* argv[]) try { // - // Create two communicators, one with string converter configured - // and one without. - // + // Create two communicators, one with string converter configured + // and one without. + // Ice::InitializationData initData; initData.stringConverter = new StringConverterI(); - initData.properties = Ice::createProperties(initData.stringConverter); - initData.properties->load("config.client"); + initData.properties = Ice::createProperties(initData.stringConverter); + initData.properties->load("config.client"); communicator1 = Ice::initialize(argc, argv, initData); Ice::InitializationData initData2; - initData2.properties = Ice::createProperties(); - initData2.properties->load("config.client"); + initData2.properties = Ice::createProperties(); + initData2.properties->load("config.client"); communicator2 = Ice::initialize(argc, argv, initData2); status = run(argc, argv, communicator1, communicator2); diff --git a/cpp/demo/Ice/converter/StringConverterI.cpp b/cpp/demo/Ice/converter/StringConverterI.cpp index 0f6a7f3bd64..0da9ee6cdbb 100644 --- a/cpp/demo/Ice/converter/StringConverterI.cpp +++ b/cpp/demo/Ice/converter/StringConverterI.cpp @@ -34,32 +34,32 @@ Demo::StringConverterI::toUTF8(const char* sourceStart, const char* sourceEnd, I { unsigned char byte = sourceStart[i]; if(byte <= 0x7F) - { - if(outputBytesLeft == 0) - { - targetStart = buffer.getMoreBytes(chunkSize, targetStart + chunkSize); - offset = 0; - } + { + if(outputBytesLeft == 0) + { + targetStart = buffer.getMoreBytes(chunkSize, targetStart + chunkSize); + offset = 0; + } - targetStart[offset] = byte; + targetStart[offset] = byte; - ++offset; - --outputBytesLeft; - } - else - { - if(outputBytesLeft <= 1) - { - targetStart = buffer.getMoreBytes(chunkSize, targetStart + chunkSize - outputBytesLeft); - offset = 0; - } + ++offset; + --outputBytesLeft; + } + else + { + if(outputBytesLeft <= 1) + { + targetStart = buffer.getMoreBytes(chunkSize, targetStart + chunkSize - outputBytesLeft); + offset = 0; + } - targetStart[offset] = 0xC0 | ((byte & 0xC0) >> 6); - targetStart[offset + 1] = 0x80 | (byte & 0x3F); + targetStart[offset] = 0xC0 | ((byte & 0xC0) >> 6); + targetStart[offset + 1] = 0x80 | (byte & 0x3F); - offset += 2; - outputBytesLeft -= 2; - } + offset += 2; + outputBytesLeft -= 2; + } } return targetStart + offset; @@ -67,7 +67,7 @@ Demo::StringConverterI::toUTF8(const char* sourceStart, const char* sourceEnd, I void Demo::StringConverterI::fromUTF8(const Ice::Byte* sourceStart, const Ice::Byte* sourceEnd, - string& target) const + string& target) const { size_t inSize = static_cast(sourceEnd - sourceStart); target.resize(inSize); @@ -77,21 +77,21 @@ Demo::StringConverterI::fromUTF8(const Ice::Byte* sourceStart, const Ice::Byte* while(i < inSize) { if((sourceStart[i] & 0xC0) == 0xC0) - { - if(i + 1 >= inSize) - { - throw Ice::StringConversionException(__FILE__, __LINE__, "UTF-8 string source exhausted"); - } - target[targetIndex] = (sourceStart[i] & 0x03) << 6; - target[targetIndex] = target[targetIndex] | (sourceStart[i + 1] & 0x3F); - i += 2; - } - else - { - target[targetIndex] = sourceStart[i]; - ++i; - } - ++targetIndex; + { + if(i + 1 >= inSize) + { + throw Ice::StringConversionException(__FILE__, __LINE__, "UTF-8 string source exhausted"); + } + target[targetIndex] = (sourceStart[i] & 0x03) << 6; + target[targetIndex] = target[targetIndex] | (sourceStart[i + 1] & 0x3F); + i += 2; + } + else + { + target[targetIndex] = sourceStart[i]; + ++i; + } + ++targetIndex; } target.resize(targetIndex); diff --git a/cpp/demo/Ice/hello/Client.cpp b/cpp/demo/Ice/hello/Client.cpp index 801a8ebc337..50269cca8af 100644 --- a/cpp/demo/Ice/hello/Client.cpp +++ b/cpp/demo/Ice/hello/Client.cpp @@ -42,11 +42,11 @@ HelloClient::run(int argc, char* argv[]) callbackOnInterrupt(); HelloPrx twoway = HelloPrx::checkedCast( - communicator()->propertyToProxy("Hello.Proxy")->ice_twoway()->ice_timeout(-1)->ice_secure(false)); + communicator()->propertyToProxy("Hello.Proxy")->ice_twoway()->ice_timeout(-1)->ice_secure(false)); if(!twoway) { - cerr << argv[0] << ": invalid proxy" << endl; - return EXIT_FAILURE; + cerr << argv[0] << ": invalid proxy" << endl; + return EXIT_FAILURE; } HelloPrx oneway = HelloPrx::uncheckedCast(twoway->ice_oneway()); HelloPrx batchOneway = HelloPrx::uncheckedCast(twoway->ice_batchOneway()); @@ -62,133 +62,133 @@ HelloClient::run(int argc, char* argv[]) char c; do { - try - { - cout << "==> "; - cin >> c; - if(c == 't') - { - twoway->sayHello(delay); - } - else if(c == 'o') - { - oneway->sayHello(delay); - } - else if(c == 'O') - { - batchOneway->sayHello(delay); - } - else if(c == 'd') - { - if(secure) - { - cout << "secure datagrams are not supported" << endl; - } - else - { - datagram->sayHello(delay); - } - } - else if(c == 'D') - { - if(secure) - { - cout << "secure datagrams are not supported" << endl; - } - else - { - batchDatagram->sayHello(delay); - } - } - else if(c == 'f') - { - communicator()->flushBatchRequests(); - } - else if(c == 'T') - { - if(timeout == -1) - { - timeout = 2000; - } - else - { - timeout = -1; - } - - twoway = HelloPrx::uncheckedCast(twoway->ice_timeout(timeout)); - oneway = HelloPrx::uncheckedCast(oneway->ice_timeout(timeout)); - batchOneway = HelloPrx::uncheckedCast(batchOneway->ice_timeout(timeout)); - - if(timeout == -1) - { - cout << "timeout is now switched off" << endl; - } - else - { - cout << "timeout is now set to 2000ms" << endl; - } - } - else if(c == 'P') - { - if(delay == 0) - { - delay = 2500; - } - else - { - delay = 0; - } - - if(delay == 0) - { - cout << "server delay is now disabled" << endl; - } - else - { - cout << "server delay is now set to 2500ms" << endl; - } - } - else if(c == 'S') - { - secure = !secure; - - twoway = HelloPrx::uncheckedCast(twoway->ice_secure(secure)); - oneway = HelloPrx::uncheckedCast(oneway->ice_secure(secure)); - batchOneway = HelloPrx::uncheckedCast(batchOneway->ice_secure(secure)); - datagram = HelloPrx::uncheckedCast(datagram->ice_secure(secure)); - batchDatagram = HelloPrx::uncheckedCast(batchDatagram->ice_secure(secure)); - - if(secure) - { - cout << "secure mode is now on" << endl; - } - else - { - cout << "secure mode is now off" << endl; - } - } - else if(c == 's') - { - twoway->shutdown(); - } - else if(c == 'x') - { - // Nothing to do - } - else if(c == '?') - { - menu(); - } - else - { - cout << "unknown command `" << c << "'" << endl; - menu(); - } - } - catch(const Ice::Exception& ex) - { - cerr << ex << endl; - } + try + { + cout << "==> "; + cin >> c; + if(c == 't') + { + twoway->sayHello(delay); + } + else if(c == 'o') + { + oneway->sayHello(delay); + } + else if(c == 'O') + { + batchOneway->sayHello(delay); + } + else if(c == 'd') + { + if(secure) + { + cout << "secure datagrams are not supported" << endl; + } + else + { + datagram->sayHello(delay); + } + } + else if(c == 'D') + { + if(secure) + { + cout << "secure datagrams are not supported" << endl; + } + else + { + batchDatagram->sayHello(delay); + } + } + else if(c == 'f') + { + communicator()->flushBatchRequests(); + } + else if(c == 'T') + { + if(timeout == -1) + { + timeout = 2000; + } + else + { + timeout = -1; + } + + twoway = HelloPrx::uncheckedCast(twoway->ice_timeout(timeout)); + oneway = HelloPrx::uncheckedCast(oneway->ice_timeout(timeout)); + batchOneway = HelloPrx::uncheckedCast(batchOneway->ice_timeout(timeout)); + + if(timeout == -1) + { + cout << "timeout is now switched off" << endl; + } + else + { + cout << "timeout is now set to 2000ms" << endl; + } + } + else if(c == 'P') + { + if(delay == 0) + { + delay = 2500; + } + else + { + delay = 0; + } + + if(delay == 0) + { + cout << "server delay is now disabled" << endl; + } + else + { + cout << "server delay is now set to 2500ms" << endl; + } + } + else if(c == 'S') + { + secure = !secure; + + twoway = HelloPrx::uncheckedCast(twoway->ice_secure(secure)); + oneway = HelloPrx::uncheckedCast(oneway->ice_secure(secure)); + batchOneway = HelloPrx::uncheckedCast(batchOneway->ice_secure(secure)); + datagram = HelloPrx::uncheckedCast(datagram->ice_secure(secure)); + batchDatagram = HelloPrx::uncheckedCast(batchDatagram->ice_secure(secure)); + + if(secure) + { + cout << "secure mode is now on" << endl; + } + else + { + cout << "secure mode is now off" << endl; + } + } + else if(c == 's') + { + twoway->shutdown(); + } + else if(c == 'x') + { + // Nothing to do + } + else if(c == '?') + { + menu(); + } + else + { + cout << "unknown command `" << c << "'" << endl; + menu(); + } + } + catch(const Ice::Exception& ex) + { + cerr << ex << endl; + } } while(cin.good() && c != 'x'); @@ -200,15 +200,15 @@ HelloClient::interruptCallback(int) { try { - communicator()->destroy(); + communicator()->destroy(); } catch(const IceUtil::Exception& ex) { - cerr << appName() << ": " << ex << endl; + cerr << appName() << ": " << ex << endl; } catch(...) { - cerr << appName() << ": unknown exception" << endl; + cerr << appName() << ": unknown exception" << endl; } exit(EXIT_SUCCESS); } @@ -217,17 +217,17 @@ void HelloClient::menu() { cout << - "usage:\n" - "t: send greeting as twoway\n" - "o: send greeting as oneway\n" - "O: send greeting as batch oneway\n" - "d: send greeting as datagram\n" - "D: send greeting as batch datagram\n" - "f: flush all batch requests\n" - "T: set a timeout\n" - "P: set server delay\n" - "S: switch secure mode on/off\n" - "s: shutdown server\n" - "x: exit\n" - "?: help\n"; + "usage:\n" + "t: send greeting as twoway\n" + "o: send greeting as oneway\n" + "O: send greeting as batch oneway\n" + "d: send greeting as datagram\n" + "D: send greeting as batch datagram\n" + "f: flush all batch requests\n" + "T: set a timeout\n" + "P: set server delay\n" + "S: switch secure mode on/off\n" + "s: shutdown server\n" + "x: exit\n" + "?: help\n"; } diff --git a/cpp/demo/Ice/invoke/Client.cpp b/cpp/demo/Ice/invoke/Client.cpp index 3c0bb5bf8c6..e36fb965f31 100644 --- a/cpp/demo/Ice/invoke/Client.cpp +++ b/cpp/demo/Ice/invoke/Client.cpp @@ -304,15 +304,15 @@ InvokeClient::interruptCallback(int) { try { - communicator()->destroy(); + communicator()->destroy(); } catch(const IceUtil::Exception& ex) { - cerr << appName() << ": " << ex << endl; + cerr << appName() << ": " << ex << endl; } catch(...) { - cerr << appName() << ": unknown exception" << endl; + cerr << appName() << ": unknown exception" << endl; } exit(EXIT_SUCCESS); } diff --git a/cpp/demo/Ice/latency/Client.cpp b/cpp/demo/Ice/latency/Client.cpp index 27347c49dd0..5f59ff10b17 100644 --- a/cpp/demo/Ice/latency/Client.cpp +++ b/cpp/demo/Ice/latency/Client.cpp @@ -34,8 +34,8 @@ LatencyClient::run(int argc, char* argv[]) PingPrx ping = PingPrx::checkedCast(base); if(!ping) { - cerr << argv[0] << ": invalid proxy" << endl; - return EXIT_FAILURE; + cerr << argv[0] << ": invalid proxy" << endl; + return EXIT_FAILURE; } // Initial ping to setup the connection. @@ -47,7 +47,7 @@ LatencyClient::run(int argc, char* argv[]) cout << "pinging server " << repetitions << " times (this may take a while)" << endl; for(int i = 0; i < repetitions; ++i) { - ping->ice_ping(); + ping->ice_ping(); } tm = IceUtil::Time::now() - tm; diff --git a/cpp/demo/Ice/minimal/Client.cpp b/cpp/demo/Ice/minimal/Client.cpp index 7009383bef6..583379642ef 100644 --- a/cpp/demo/Ice/minimal/Client.cpp +++ b/cpp/demo/Ice/minimal/Client.cpp @@ -21,35 +21,35 @@ main(int argc, char* argv[]) try { - communicator = Ice::initialize(argc, argv); - HelloPrx hello = HelloPrx::checkedCast(communicator->stringToProxy("hello:tcp -p 10000")); - if(!hello) - { - cerr << argv[0] << ": invalid proxy" << endl; - status = EXIT_FAILURE; - } - else - { - hello->sayHello(); - } + communicator = Ice::initialize(argc, argv); + HelloPrx hello = HelloPrx::checkedCast(communicator->stringToProxy("hello:tcp -p 10000")); + if(!hello) + { + cerr << argv[0] << ": invalid proxy" << endl; + status = EXIT_FAILURE; + } + else + { + hello->sayHello(); + } } catch(const Ice::Exception& ex) { - cerr << ex << endl; - status = EXIT_FAILURE; + cerr << ex << endl; + status = EXIT_FAILURE; } if(communicator) { - try - { - communicator->destroy(); - } - catch(const Ice::Exception& ex) - { - cerr << ex << endl; - status = EXIT_FAILURE; - } + try + { + communicator->destroy(); + } + catch(const Ice::Exception& ex) + { + cerr << ex << endl; + status = EXIT_FAILURE; + } } return status; diff --git a/cpp/demo/Ice/minimal/Server.cpp b/cpp/demo/Ice/minimal/Server.cpp index dc243ba9e49..6b2e4874689 100644 --- a/cpp/demo/Ice/minimal/Server.cpp +++ b/cpp/demo/Ice/minimal/Server.cpp @@ -20,29 +20,29 @@ main(int argc, char* argv[]) try { - communicator = Ice::initialize(argc, argv); - Ice::ObjectAdapterPtr adapter = communicator->createObjectAdapterWithEndpoints("Hello", "tcp -p 10000"); - adapter->add(new HelloI, communicator->stringToIdentity("hello")); - adapter->activate(); - communicator->waitForShutdown(); + communicator = Ice::initialize(argc, argv); + Ice::ObjectAdapterPtr adapter = communicator->createObjectAdapterWithEndpoints("Hello", "tcp -p 10000"); + adapter->add(new HelloI, communicator->stringToIdentity("hello")); + adapter->activate(); + communicator->waitForShutdown(); } catch(const Ice::Exception& ex) { - cerr << ex << endl; - status = EXIT_FAILURE; + cerr << ex << endl; + status = EXIT_FAILURE; } if(communicator) { - try - { - communicator->destroy(); - } - catch(const Ice::Exception& ex) - { - cerr << ex << endl; - status = EXIT_FAILURE; - } + try + { + communicator->destroy(); + } + catch(const Ice::Exception& ex) + { + cerr << ex << endl; + status = EXIT_FAILURE; + } } return status; diff --git a/cpp/demo/Ice/nested/Client.cpp b/cpp/demo/Ice/nested/Client.cpp index 12235c1d0ea..30c6edc42f2 100644 --- a/cpp/demo/Ice/nested/Client.cpp +++ b/cpp/demo/Ice/nested/Client.cpp @@ -41,8 +41,8 @@ NestedClient::run(int argc, char* argv[]) NestedPrx nested = NestedPrx::checkedCast(communicator()->propertyToProxy("Nested.Client.NestedServer")); if(!nested) { - cerr << appName() << ": invalid proxy" << endl; - return EXIT_FAILURE; + cerr << appName() << ": invalid proxy" << endl; + return EXIT_FAILURE; } Ice::ObjectAdapterPtr adapter = communicator()->createObjectAdapter("Nested.Client"); @@ -51,28 +51,28 @@ NestedClient::run(int argc, char* argv[]) adapter->activate(); cout << "Note: The maximum nesting level is sz * 2, with sz being\n" - << "the maximum number of threads in the server thread pool. if\n" - << "you specify a value higher than that, the application will\n" - << "block or timeout.\n" - << endl; + << "the maximum number of threads in the server thread pool. if\n" + << "you specify a value higher than that, the application will\n" + << "block or timeout.\n" + << endl; string s; do { - try - { - cout << "enter nesting level or 'x' for exit: "; - cin >> s; - int level = atoi(s.c_str()); - if(level > 0) - { - nested->nestedCall(level, self); - } - } - catch(const Ice::Exception& ex) - { - cerr << ex << endl; - } + try + { + cout << "enter nesting level or 'x' for exit: "; + cin >> s; + int level = atoi(s.c_str()); + if(level > 0) + { + nested->nestedCall(level, self); + } + } + catch(const Ice::Exception& ex) + { + cerr << ex << endl; + } } while(cin.good() && s != "x"); @@ -89,15 +89,15 @@ NestedClient::interruptCallback(int) * try { - communicator()->destroy(); + communicator()->destroy(); } catch(const IceUtil::Exception& ex) { - cerr << appName() << ": " << ex << endl; + cerr << appName() << ": " << ex << endl; } catch(...) { - cerr << appName() << ": unknown exception" << endl; + cerr << appName() << ": unknown exception" << endl; } */ exit(EXIT_SUCCESS); diff --git a/cpp/demo/Ice/nested/NestedI.cpp b/cpp/demo/Ice/nested/NestedI.cpp index 133e34b896a..bb129b6dcdf 100644 --- a/cpp/demo/Ice/nested/NestedI.cpp +++ b/cpp/demo/Ice/nested/NestedI.cpp @@ -25,6 +25,6 @@ NestedI::nestedCall(Int level, const NestedPrx& proxy, const Ice::Current& curre cout << level << endl; if(--level > 0) { - proxy->nestedCall(level, _self, current.ctx); + proxy->nestedCall(level, _self, current.ctx); } } diff --git a/cpp/demo/Ice/session/Client.cpp b/cpp/demo/Ice/session/Client.cpp index 28a0393a1bd..89b05b09c1d 100755 --- a/cpp/demo/Ice/session/Client.cpp +++ b/cpp/demo/Ice/session/Client.cpp @@ -19,42 +19,42 @@ class SessionRefreshThread : public IceUtil::Thread, public IceUtil::Monitorrefresh(); - } - catch(const Ice::Exception& ex) - { - Ice::Warning warn(_logger); - warn << "SessionRefreshThread: " << ex; - _terminated = true; - } - } - } + Lock sync(*this); + while(!_terminated) + { + timedWait(_timeout); + if(!_terminated) + { + try + { + _session->refresh(); + } + catch(const Ice::Exception& ex) + { + Ice::Warning warn(_logger); + warn << "SessionRefreshThread: " << ex; + _terminated = true; + } + } + } } void terminate() { - Lock sync(*this); - _terminated = true; - notify(); + Lock sync(*this); + _terminated = true; + notify(); } private: @@ -109,24 +109,24 @@ SessionClient::run(int argc, char* argv[]) cin >> name; if(!cin.good()) { - return EXIT_FAILURE; + return EXIT_FAILURE; } Ice::ObjectPrx base = communicator()->propertyToProxy("SessionFactory.Proxy"); SessionFactoryPrx factory = SessionFactoryPrx::checkedCast(base); if(!factory) { - cerr << argv[0] << ": invalid proxy" << endl; - return EXIT_FAILURE; + cerr << argv[0] << ": invalid proxy" << endl; + return EXIT_FAILURE; } { - IceUtil::Mutex::Lock sync(_mutex); - _session = factory->create(name); - - _refresh = new SessionRefreshThread( - communicator()->getLogger(), IceUtil::Time::seconds(5), _session); - _refresh->start(); + IceUtil::Mutex::Lock sync(_mutex); + _session = factory->create(name); + + _refresh = new SessionRefreshThread( + communicator()->getLogger(), IceUtil::Time::seconds(5), _session); + _refresh->start(); } vector hellos; @@ -135,85 +135,85 @@ SessionClient::run(int argc, char* argv[]) try { - bool destroy = true; - bool shutdown = false; - while(true) - { - cout << "==> "; - char c; - cin >> c; - if(!cin.good()) - { - break; - } - if(isdigit(c)) - { - string s; - s += c; - vector::size_type index = atoi(s.c_str()); - if(index < hellos.size()) - { - hellos[index]->sayHello(); - } - else - { - cout << "Index is too high. " << hellos.size() << " hello objects exist so far.\n" - << "Use `c' to create a new hello object." << endl; - } - } - else if(c == 'c') - { - hellos.push_back(_session->createHello()); - cout << "Created hello object " << hellos.size() - 1 << endl; - } - else if(c == 's') - { - destroy = false; - shutdown = true; - break; - } - else if(c == 'x') - { - break; - } - else if(c == 't') - { - destroy = false; - break; - } - else if(c == '?') - { - menu(); - } - else - { - cout << "Unknown command `" << c << "'." << endl; - menu(); - } - } + bool destroy = true; + bool shutdown = false; + while(true) + { + cout << "==> "; + char c; + cin >> c; + if(!cin.good()) + { + break; + } + if(isdigit(c)) + { + string s; + s += c; + vector::size_type index = atoi(s.c_str()); + if(index < hellos.size()) + { + hellos[index]->sayHello(); + } + else + { + cout << "Index is too high. " << hellos.size() << " hello objects exist so far.\n" + << "Use `c' to create a new hello object." << endl; + } + } + else if(c == 'c') + { + hellos.push_back(_session->createHello()); + cout << "Created hello object " << hellos.size() - 1 << endl; + } + else if(c == 's') + { + destroy = false; + shutdown = true; + break; + } + else if(c == 'x') + { + break; + } + else if(c == 't') + { + destroy = false; + break; + } + else if(c == '?') + { + menu(); + } + else + { + cout << "Unknown command `" << c << "'." << endl; + menu(); + } + } - // - // The refresher thread must be terminated before destroy is - // called, otherwise it might get ObjectNotExistException. refresh - // is set to 0 so that if session->destroy() raises an exception - // the thread will not be re-terminated and re-joined. - // - cleanup(destroy); - if(shutdown) - { - factory->shutdown(); - } + // + // The refresher thread must be terminated before destroy is + // called, otherwise it might get ObjectNotExistException. refresh + // is set to 0 so that if session->destroy() raises an exception + // the thread will not be re-terminated and re-joined. + // + cleanup(destroy); + if(shutdown) + { + factory->shutdown(); + } } catch(...) { - try - { - cleanup(true); - } - catch(...) - { - } - throw; + try + { + cleanup(true); + } + catch(...) + { + } + throw; } return EXIT_SUCCESS; @@ -232,15 +232,15 @@ SessionClient::interruptCallback(int) try { - communicator()->destroy(); + communicator()->destroy(); } catch(const IceUtil::Exception& ex) { - cerr << appName() << ": " << ex << endl; + cerr << appName() << ": " << ex << endl; } catch(...) { - cerr << appName() << ": unknown exception" << endl; + cerr << appName() << ": unknown exception" << endl; } exit(EXIT_SUCCESS); } @@ -251,15 +251,15 @@ SessionClient::cleanup(bool destroy) IceUtil::Mutex::Lock sync(_mutex); if(_refresh) { - _refresh->terminate(); - _refresh->getThreadControl().join(); - _refresh = 0; + _refresh->terminate(); + _refresh->getThreadControl().join(); + _refresh = 0; } if(destroy && _session) { - _session->destroy(); - _session = 0; + _session->destroy(); + _session = 0; } } @@ -267,11 +267,11 @@ void SessionClient::menu() { cout << - "usage:\n" - "c: create a new per-client hello object\n" - "0-9: send a greeting to a hello object\n" - "s: shutdown the server and exit\n" - "x: exit\n" - "t: exit without destroying the session\n" - "?: help\n"; + "usage:\n" + "c: create a new per-client hello object\n" + "0-9: send a greeting to a hello object\n" + "s: shutdown the server and exit\n" + "x: exit\n" + "t: exit without destroying the session\n" + "?: help\n"; } diff --git a/cpp/demo/Ice/session/ReapThread.cpp b/cpp/demo/Ice/session/ReapThread.cpp index 26d25ff506a..7257bd0994c 100755 --- a/cpp/demo/Ice/session/ReapThread.cpp +++ b/cpp/demo/Ice/session/ReapThread.cpp @@ -25,38 +25,38 @@ ReapThread::run() while(!_terminated) { - timedWait(_timeout); + timedWait(_timeout); - if(!_terminated) - { - list::iterator p = _sessions.begin(); - while(p != _sessions.end()) - { - try - { - // - // Session destruction may take time in a - // real-world example. Therefore the current time - // is computed for each iteration. - // - if((IceUtil::Time::now() - p->session->timestamp()) > _timeout) - { - string name = p->proxy->getName(); - p->proxy->destroy(); - cout << "The session " << name << " has timed out." << endl; - p = _sessions.erase(p); - } - else - { - ++p; - } - } - catch(const Ice::ObjectNotExistException&) - { - p = _sessions.erase(p); - } - } - } + if(!_terminated) + { + list::iterator p = _sessions.begin(); + while(p != _sessions.end()) + { + try + { + // + // Session destruction may take time in a + // real-world example. Therefore the current time + // is computed for each iteration. + // + if((IceUtil::Time::now() - p->session->timestamp()) > _timeout) + { + string name = p->proxy->getName(); + p->proxy->destroy(); + cout << "The session " << name << " has timed out." << endl; + p = _sessions.erase(p); + } + else + { + ++p; + } + } + catch(const Ice::ObjectNotExistException&) + { + p = _sessions.erase(p); + } + } + } } } diff --git a/cpp/demo/Ice/session/ReapThread.h b/cpp/demo/Ice/session/ReapThread.h index b7fc1434cf0..f96cf25036a 100755 --- a/cpp/demo/Ice/session/ReapThread.h +++ b/cpp/demo/Ice/session/ReapThread.h @@ -30,10 +30,10 @@ private: bool _terminated; struct SessionProxyPair { - SessionProxyPair(const Demo::SessionPrx& p, const SessionIPtr& s) : - proxy(p), session(s) { } - const Demo::SessionPrx proxy; - const SessionIPtr session; + SessionProxyPair(const Demo::SessionPrx& p, const SessionIPtr& s) : + proxy(p), session(s) { } + const Demo::SessionPrx proxy; + const SessionIPtr session; }; std::list _sessions; }; diff --git a/cpp/demo/Ice/session/SessionI.cpp b/cpp/demo/Ice/session/SessionI.cpp index d458b4117e4..a0e70e24168 100755 --- a/cpp/demo/Ice/session/SessionI.cpp +++ b/cpp/demo/Ice/session/SessionI.cpp @@ -17,21 +17,21 @@ class HelloI : public Hello public: HelloI(const string& name, int id) : - _name(name), - _id(id) + _name(name), + _id(id) { } virtual ~HelloI() { - cout << "Hello object #" << _id << " for session `" << _name << "' destroyed" << endl; + cout << "Hello object #" << _id << " for session `" << _name << "' destroyed" << endl; } void sayHello(const Ice::Current&) const { - cout << "Hello object #" << _id << " for session `" << _name << "' says:\n" - << "Hello " << _name << "!" << endl; + cout << "Hello object #" << _id << " for session `" << _name << "' says:\n" + << "Hello " << _name << "!" << endl; } private: @@ -55,7 +55,7 @@ SessionI::createHello(const Ice::Current& c) Lock sync(*this); if(_destroy) { - throw Ice::ObjectNotExistException(__FILE__, __LINE__); + throw Ice::ObjectNotExistException(__FILE__, __LINE__); } HelloPrx hello = HelloPrx::uncheckedCast(c.adapter->addWithUUID(new HelloI(_name, _nextId++))); @@ -69,7 +69,7 @@ SessionI::refresh(const Ice::Current& c) Lock sync(*this); if(_destroy) { - throw Ice::ObjectNotExistException(__FILE__, __LINE__); + throw Ice::ObjectNotExistException(__FILE__, __LINE__); } _timestamp = IceUtil::Time::now(); @@ -81,7 +81,7 @@ SessionI::getName(const Ice::Current&) const Lock sync(*this); if(_destroy) { - throw Ice::ObjectNotExistException(__FILE__, __LINE__); + throw Ice::ObjectNotExistException(__FILE__, __LINE__); } return _name; @@ -93,7 +93,7 @@ SessionI::destroy(const Ice::Current& c) Lock sync(*this); if(_destroy) { - throw Ice::ObjectNotExistException(__FILE__, __LINE__); + throw Ice::ObjectNotExistException(__FILE__, __LINE__); } _destroy = true; @@ -101,16 +101,16 @@ SessionI::destroy(const Ice::Current& c) cout << "The session " << _name << " is now destroyed." << endl; try { - c.adapter->remove(c.id); - for(list::const_iterator p = _objs.begin(); p != _objs.end(); ++p) - { - c.adapter->remove((*p)->ice_getIdentity()); - } + c.adapter->remove(c.id); + for(list::const_iterator p = _objs.begin(); p != _objs.end(); ++p) + { + c.adapter->remove((*p)->ice_getIdentity()); + } } catch(const Ice::ObjectAdapterDeactivatedException&) { - // This method is called on shutdown of the server, in which - // case this exception is expected. + // This method is called on shutdown of the server, in which + // case this exception is expected. } _objs.clear(); @@ -122,7 +122,7 @@ SessionI::timestamp() const Lock sync(*this); if(_destroy) { - throw Ice::ObjectNotExistException(__FILE__, __LINE__); + throw Ice::ObjectNotExistException(__FILE__, __LINE__); } return _timestamp; } diff --git a/cpp/demo/Ice/throughput/Client.cpp b/cpp/demo/Ice/throughput/Client.cpp index d019e951a19..112eb317177 100644 --- a/cpp/demo/Ice/throughput/Client.cpp +++ b/cpp/demo/Ice/throughput/Client.cpp @@ -47,8 +47,8 @@ ThroughputClient::run(int argc, char* argv[]) ThroughputPrx throughput = ThroughputPrx::checkedCast(base); if(!throughput) { - cerr << argv[0] << ": invalid proxy" << endl; - return EXIT_FAILURE; + cerr << argv[0] << ": invalid proxy" << endl; + return EXIT_FAILURE; } ThroughputPrx throughputOneway = ThroughputPrx::uncheckedCast(throughput->ice_oneway()); @@ -64,7 +64,7 @@ ThroughputClient::run(int argc, char* argv[]) for(i = 0; i < StringDoubleSeqSize; ++i) { structSeq[i].s = "hello"; - structSeq[i].d = 3.14; + structSeq[i].d = 3.14; } FixedSeq fixedSeq(FixedSeqSize); @@ -88,296 +88,296 @@ ThroughputClient::run(int argc, char* argv[]) char c; do { - try - { - cout << "==> "; - cin >> c; - - IceUtil::Time tm = IceUtil::Time::now(); - const int repetitions = 1000; - - if(c == '1' || c == '2' || c == '3' || c == '4') - { - currentType = c; - switch(c) - { - case '1': - { - cout << "using byte sequences" << endl; - seqSize = ByteSeqSize; - break; - } - - case '2': - { - cout << "using string sequences" << endl; - seqSize = StringSeqSize; - break; - } - - case '3': - { - cout << "using variable-length struct sequences" << endl; - seqSize = StringDoubleSeqSize; - break; - } - - case '4': - { - cout << "using fixed-length struct sequences" << endl; - seqSize = FixedSeqSize; - break; - } - } - } - else if(c == 't' || c == 'o' || c == 'r' || c == 'e') - { - switch(c) - { - case 't': - case 'o': - { - cout << "sending"; - break; - } - - case 'r': - { - cout << "receiving"; - break; - } - - case 'e': - { - cout << "sending and receiving"; - break; - } - } - - cout << ' ' << repetitions; - switch(currentType) - { - case '1': - { - cout << " byte"; - break; - } - - case '2': - { - cout << " string"; - break; - } - - case '3': - { - cout << " variable-length struct"; - break; - } - - case '4': - { - cout << " fixed-length struct"; - break; - } - } - cout << " sequences of size " << seqSize; - - - if(c == 'o') - { - cout << " as oneway"; - } - - cout << "..." << endl; - - for(int i = 0; i < repetitions; ++i) - { - switch(currentType) - { - case '1': - { - switch(c) - { - case 't': - { - throughput->sendByteSeq(byteArr); - break; - } - - case 'o': - { - throughputOneway->sendByteSeq(byteArr); - break; - } - - case 'r': - { - throughput->recvByteSeq(); - break; - } - - case 'e': - { - throughput->echoByteSeq(byteSeq); - break; - } - } - break; - } - - case '2': - { - switch(c) - { - case 't': - { - throughput->sendStringSeq(stringSeq); - break; - } - - case 'o': - { - throughputOneway->sendStringSeq(stringSeq); - break; - } - - case 'r': - { - throughput->recvStringSeq(); - break; - } - - case 'e': - { - throughput->echoStringSeq(stringSeq); - break; - } - } - break; - } - - case '3': - { - switch(c) - { - case 't': - { - throughput->sendStructSeq(structSeq); - break; - } - - case 'o': - { - throughputOneway->sendStructSeq(structSeq); - break; - } - - case 'r': - { - throughput->recvStructSeq(); - break; - } - - case 'e': - { - throughput->echoStructSeq(structSeq); - break; - } - } - break; - } - - case '4': - { - switch(c) - { - case 't': - { - throughput->sendFixedSeq(fixedSeq); - break; - } - - case 'o': - { - throughputOneway->sendFixedSeq(fixedSeq); - break; - } - - case 'r': - { - throughput->recvFixedSeq(); - break; - } - - case 'e': - { - throughput->echoFixedSeq(fixedSeq); - break; - } - } - break; - } - } - } - - tm = IceUtil::Time::now() - tm; - cout << "time for " << repetitions << " sequences: " << tm * 1000 << "ms" << endl; - cout << "time per sequence: " << tm * 1000 / repetitions << "ms" << endl; - int wireSize = 0; - switch(currentType) - { - case '1': - { - wireSize = 1; - break; - } - case '2': - { - wireSize = static_cast(stringSeq[0].size()); - break; - } - case '3': - { - wireSize = static_cast(structSeq[0].s.size()); - wireSize += 8; // Size of double on the wire. - break; - } - case '4': - { - wireSize = 16; // Size of two ints and a double on the wire. - break; - } - } - double mbit = repetitions * seqSize * wireSize * 8.0 / tm.toMicroSeconds(); - if(c == 'e') - { - mbit *= 2; - } - cout << "throughput: " << setprecision(5) << mbit << "Mbps" << endl; - } - else if(c == 's') - { - throughput->shutdown(); - } - else if(c == 'x') - { - // Nothing to do - } - else if(c == '?') - { - menu(); - } - else - { - cout << "unknown command `" << c << "'" << endl; - menu(); - } - } - catch(const Ice::Exception& ex) - { - cerr << ex << endl; - } + try + { + cout << "==> "; + cin >> c; + + IceUtil::Time tm = IceUtil::Time::now(); + const int repetitions = 1000; + + if(c == '1' || c == '2' || c == '3' || c == '4') + { + currentType = c; + switch(c) + { + case '1': + { + cout << "using byte sequences" << endl; + seqSize = ByteSeqSize; + break; + } + + case '2': + { + cout << "using string sequences" << endl; + seqSize = StringSeqSize; + break; + } + + case '3': + { + cout << "using variable-length struct sequences" << endl; + seqSize = StringDoubleSeqSize; + break; + } + + case '4': + { + cout << "using fixed-length struct sequences" << endl; + seqSize = FixedSeqSize; + break; + } + } + } + else if(c == 't' || c == 'o' || c == 'r' || c == 'e') + { + switch(c) + { + case 't': + case 'o': + { + cout << "sending"; + break; + } + + case 'r': + { + cout << "receiving"; + break; + } + + case 'e': + { + cout << "sending and receiving"; + break; + } + } + + cout << ' ' << repetitions; + switch(currentType) + { + case '1': + { + cout << " byte"; + break; + } + + case '2': + { + cout << " string"; + break; + } + + case '3': + { + cout << " variable-length struct"; + break; + } + + case '4': + { + cout << " fixed-length struct"; + break; + } + } + cout << " sequences of size " << seqSize; + + + if(c == 'o') + { + cout << " as oneway"; + } + + cout << "..." << endl; + + for(int i = 0; i < repetitions; ++i) + { + switch(currentType) + { + case '1': + { + switch(c) + { + case 't': + { + throughput->sendByteSeq(byteArr); + break; + } + + case 'o': + { + throughputOneway->sendByteSeq(byteArr); + break; + } + + case 'r': + { + throughput->recvByteSeq(); + break; + } + + case 'e': + { + throughput->echoByteSeq(byteSeq); + break; + } + } + break; + } + + case '2': + { + switch(c) + { + case 't': + { + throughput->sendStringSeq(stringSeq); + break; + } + + case 'o': + { + throughputOneway->sendStringSeq(stringSeq); + break; + } + + case 'r': + { + throughput->recvStringSeq(); + break; + } + + case 'e': + { + throughput->echoStringSeq(stringSeq); + break; + } + } + break; + } + + case '3': + { + switch(c) + { + case 't': + { + throughput->sendStructSeq(structSeq); + break; + } + + case 'o': + { + throughputOneway->sendStructSeq(structSeq); + break; + } + + case 'r': + { + throughput->recvStructSeq(); + break; + } + + case 'e': + { + throughput->echoStructSeq(structSeq); + break; + } + } + break; + } + + case '4': + { + switch(c) + { + case 't': + { + throughput->sendFixedSeq(fixedSeq); + break; + } + + case 'o': + { + throughputOneway->sendFixedSeq(fixedSeq); + break; + } + + case 'r': + { + throughput->recvFixedSeq(); + break; + } + + case 'e': + { + throughput->echoFixedSeq(fixedSeq); + break; + } + } + break; + } + } + } + + tm = IceUtil::Time::now() - tm; + cout << "time for " << repetitions << " sequences: " << tm * 1000 << "ms" << endl; + cout << "time per sequence: " << tm * 1000 / repetitions << "ms" << endl; + int wireSize = 0; + switch(currentType) + { + case '1': + { + wireSize = 1; + break; + } + case '2': + { + wireSize = static_cast(stringSeq[0].size()); + break; + } + case '3': + { + wireSize = static_cast(structSeq[0].s.size()); + wireSize += 8; // Size of double on the wire. + break; + } + case '4': + { + wireSize = 16; // Size of two ints and a double on the wire. + break; + } + } + double mbit = repetitions * seqSize * wireSize * 8.0 / tm.toMicroSeconds(); + if(c == 'e') + { + mbit *= 2; + } + cout << "throughput: " << setprecision(5) << mbit << "Mbps" << endl; + } + else if(c == 's') + { + throughput->shutdown(); + } + else if(c == 'x') + { + // Nothing to do + } + else if(c == '?') + { + menu(); + } + else + { + cout << "unknown command `" << c << "'" << endl; + menu(); + } + } + catch(const Ice::Exception& ex) + { + cerr << ex << endl; + } } while(cin.good() && c != 'x'); @@ -389,15 +389,15 @@ ThroughputClient::interruptCallback(int) { try { - communicator()->destroy(); + communicator()->destroy(); } catch(const IceUtil::Exception& ex) { - cerr << appName() << ": " << ex << endl; + cerr << appName() << ": " << ex << endl; } catch(...) { - cerr << appName() << ": unknown exception" << endl; + cerr << appName() << ": unknown exception" << endl; } exit(EXIT_SUCCESS); } @@ -406,22 +406,22 @@ void ThroughputClient::menu() { cout << - "usage:\n" - "\n" - "toggle type of data to send:\n" - "1: sequence of bytes (default)\n" - "2: sequence of strings (\"hello\")\n" - "3: sequence of structs with a string (\"hello\") and a double\n" - "4: sequence of structs with two ints and a double\n" - "\n" - "select test to run:\n" - "t: Send sequence as twoway\n" - "o: Send sequence as oneway\n" - "r: Receive sequence\n" - "e: Echo (send and receive) sequence\n" - "\n" - "other commands:\n" - "s: shutdown server\n" - "x: exit\n" - "?: help\n"; + "usage:\n" + "\n" + "toggle type of data to send:\n" + "1: sequence of bytes (default)\n" + "2: sequence of strings (\"hello\")\n" + "3: sequence of structs with a string (\"hello\") and a double\n" + "4: sequence of structs with two ints and a double\n" + "\n" + "select test to run:\n" + "t: Send sequence as twoway\n" + "o: Send sequence as oneway\n" + "r: Receive sequence\n" + "e: Echo (send and receive) sequence\n" + "\n" + "other commands:\n" + "s: shutdown server\n" + "x: exit\n" + "?: help\n"; } diff --git a/cpp/demo/Ice/throughput/ThroughputI.cpp b/cpp/demo/Ice/throughput/ThroughputI.cpp index 68114a2b7bf..beb61966b0b 100644 --- a/cpp/demo/Ice/throughput/ThroughputI.cpp +++ b/cpp/demo/Ice/throughput/ThroughputI.cpp @@ -20,14 +20,14 @@ ThroughputI::ThroughputI() : int i; for(i = 0; i < Demo::StringDoubleSeqSize; ++i) { - _structSeq[i].s = "hello"; - _structSeq[i].d = 3.14; + _structSeq[i].s = "hello"; + _structSeq[i].d = 3.14; } for(i = 0; i < Demo::FixedSeqSize; ++i) { - _fixedSeq[i].i = 0; - _fixedSeq[i].j = 0; - _fixedSeq[i].d = 0; + _fixedSeq[i].i = 0; + _fixedSeq[i].j = 0; + _fixedSeq[i].d = 0; } } diff --git a/cpp/demo/Ice/value/Client.cpp b/cpp/demo/Ice/value/Client.cpp index b072355b87f..e37a48aa349 100644 --- a/cpp/demo/Ice/value/Client.cpp +++ b/cpp/demo/Ice/value/Client.cpp @@ -42,47 +42,47 @@ ValueClient::run(int argc, char* argv[]) InitialPrx initial = InitialPrx::checkedCast(base); if(!initial) { - cerr << argv[0] << ": invalid object reference" << endl; - return EXIT_FAILURE; + cerr << argv[0] << ": invalid object reference" << endl; + return EXIT_FAILURE; } char c[2]; cout << '\n' - << "Let's first transfer a simple object, for a class without\n" - << "operations, and print its contents. No factory is required\n" - << "for this.\n" - << "[press enter]\n"; + << "Let's first transfer a simple object, for a class without\n" + << "operations, and print its contents. No factory is required\n" + << "for this.\n" + << "[press enter]\n"; cin.getline(c, 2); SimplePtr simple = initial->getSimple(); cout << "==> " << simple->message << endl; cout << '\n' - << "Yes, this worked. Now let's try to transfer an object for a class\n" - << "with operations as type ::Demo::Printer, without installing a factory first.\n" - << "This should give us a `no factory' exception.\n" - << "[press enter]\n"; + << "Yes, this worked. Now let's try to transfer an object for a class\n" + << "with operations as type ::Demo::Printer, without installing a factory first.\n" + << "This should give us a `no factory' exception.\n" + << "[press enter]\n"; cin.getline(c, 2); PrinterPtr printer; PrinterPrx printerProxy; try { - initial->getPrinter(printer, printerProxy); - cerr << argv[0] << "Did not get the expected NoObjectFactoryException!" << endl; - exit(EXIT_FAILURE); + initial->getPrinter(printer, printerProxy); + cerr << argv[0] << "Did not get the expected NoObjectFactoryException!" << endl; + exit(EXIT_FAILURE); } catch(const Ice::NoObjectFactoryException& ex) { - cout << "==> " << ex << endl; + cout << "==> " << ex << endl; } cout << '\n' - << "Yep, that's what we expected. Now let's try again, but with\n" - << "installing an appropriate factory first. If successful, we print\n" - << "the object's content.\n" - << "[press enter]\n"; + << "Yep, that's what we expected. Now let's try again, but with\n" + << "installing an appropriate factory first. If successful, we print\n" + << "the object's content.\n" + << "[press enter]\n"; cin.getline(c, 2); Ice::ObjectFactoryPtr factory = new ObjectFactory; @@ -92,28 +92,28 @@ ValueClient::run(int argc, char* argv[]) cout << "==> " << printer->message << endl; cout << '\n' - << "Cool, it worked! Let's try calling the printBackwards() method\n" - << "on the object we just received locally.\n" - << "[press enter]\n"; + << "Cool, it worked! Let's try calling the printBackwards() method\n" + << "on the object we just received locally.\n" + << "[press enter]\n"; cin.getline(c, 2); cout << "==> "; printer->printBackwards(); cout << '\n' - << "Now we call the same method, but on the remote object. Watch the\n" - << "server's output.\n" - << "[press enter]\n"; + << "Now we call the same method, but on the remote object. Watch the\n" + << "server's output.\n" + << "[press enter]\n"; cin.getline(c, 2); printerProxy->printBackwards(); cout << '\n' - << "Next, we transfer a derived object from the server as a base\n" - << "object. Since we haven't yet installed a factory for the derived\n" - << "class, the derived class (::Demo::DerivedPrinter) is sliced\n" - << "to its base class (::Demo::Printer).\n" - << "[press enter]\n"; + << "Next, we transfer a derived object from the server as a base\n" + << "object. Since we haven't yet installed a factory for the derived\n" + << "class, the derived class (::Demo::DerivedPrinter) is sliced\n" + << "to its base class (::Demo::Printer).\n" + << "[press enter]\n"; cin.getline(c, 2); PrinterPtr derivedAsBase; @@ -122,10 +122,10 @@ ValueClient::run(int argc, char* argv[]) assert(derivedAsBase->ice_id() == "::Demo::Printer"); cout << '\n' - << "Now we install a factory for the derived class, and try again.\n" - << "Because we receive the derived object as a base object, we\n" - << "we need to do a dynamic_cast<> to get from the base to the derived object.\n" - << "[press enter]\n"; + << "Now we install a factory for the derived class, and try again.\n" + << "Because we receive the derived object as a base object, we\n" + << "we need to do a dynamic_cast<> to get from the base to the derived object.\n" + << "[press enter]\n"; cin.getline(c, 2); communicator()->addObjectFactory(factory, "::Demo::DerivedPrinter"); @@ -137,10 +137,10 @@ ValueClient::run(int argc, char* argv[]) cout << "==> The type ID of the received object is \"" << derived->ice_id() << "\"" << endl; cout << '\n' - << "Let's print the message contained in the derived object, and\n" - << "call the operation printUppercase() on the derived object\n" - << "locally.\n" - << "[press enter]\n"; + << "Let's print the message contained in the derived object, and\n" + << "call the operation printUppercase() on the derived object\n" + << "locally.\n" + << "[press enter]\n"; cin.getline(c, 2); cout << "==> " << derived->derivedMessage << endl; @@ -148,26 +148,26 @@ ValueClient::run(int argc, char* argv[]) derived->printUppercase(); cout << '\n' - << "Finally, we try the same again, but instead of returning the\n" - << "derived object, we throw an exception containing the derived\n" - << "object.\n" - << "[press enter]\n"; + << "Finally, we try the same again, but instead of returning the\n" + << "derived object, we throw an exception containing the derived\n" + << "object.\n" + << "[press enter]\n"; cin.getline(c, 2); try { - initial->throwDerivedPrinter(); - cerr << argv[0] << ": Did not get the expected DerivedPrinterException!" << endl; - exit(EXIT_FAILURE); + initial->throwDerivedPrinter(); + cerr << argv[0] << ": Did not get the expected DerivedPrinterException!" << endl; + exit(EXIT_FAILURE); } catch(const DerivedPrinterException& ex) { - derived = ex.derived; - if(!derived) - { - cerr << argv[0] << "Unexpected null pointer for `derived'" << endl; - exit(EXIT_FAILURE); - } + derived = ex.derived; + if(!derived) + { + cerr << argv[0] << "Unexpected null pointer for `derived'" << endl; + exit(EXIT_FAILURE); + } } cout << "==> " << derived->derivedMessage << endl; @@ -175,7 +175,7 @@ ValueClient::run(int argc, char* argv[]) derived->printUppercase(); cout << '\n' - << "That's it for this demo. Have fun with Ice!\n"; + << "That's it for this demo. Have fun with Ice!\n"; initial->shutdown(); @@ -187,15 +187,15 @@ ValueClient::interruptCallback(int) { try { - communicator()->destroy(); + communicator()->destroy(); } catch(const IceUtil::Exception& ex) { - cerr << appName() << ": " << ex << endl; + cerr << appName() << ": " << ex << endl; } catch(...) { - cerr << appName() << ": unknown exception" << endl; + cerr << appName() << ": unknown exception" << endl; } exit(EXIT_SUCCESS); } diff --git a/cpp/demo/Ice/value/ObjectFactory.cpp b/cpp/demo/Ice/value/ObjectFactory.cpp index 2156f97448f..8c1ae1a5868 100644 --- a/cpp/demo/Ice/value/ObjectFactory.cpp +++ b/cpp/demo/Ice/value/ObjectFactory.cpp @@ -18,12 +18,12 @@ ObjectFactory::create(const string& type) { if(type == "::Demo::Printer") { - return new PrinterI; + return new PrinterI; } if(type == "::Demo::DerivedPrinter") { - return new DerivedPrinterI; + return new DerivedPrinterI; } assert(false); diff --git a/cpp/demo/IceBox/hello/Client.cpp b/cpp/demo/IceBox/hello/Client.cpp index 279fd041c47..70fc21e6389 100644 --- a/cpp/demo/IceBox/hello/Client.cpp +++ b/cpp/demo/IceBox/hello/Client.cpp @@ -36,16 +36,16 @@ void HelloClient::menu() { cout << - "usage:\n" - "t: send greeting as twoway\n" - "o: send greeting as oneway\n" - "O: send greeting as batch oneway\n" - "d: send greeting as datagram\n" - "D: send greeting as batch datagram\n" - "f: flush all batch requests\n" - "S: switch secure mode on/off\n" - "x: exit\n" - "?: help\n"; + "usage:\n" + "t: send greeting as twoway\n" + "o: send greeting as oneway\n" + "O: send greeting as batch oneway\n" + "d: send greeting as datagram\n" + "D: send greeting as batch datagram\n" + "f: flush all batch requests\n" + "S: switch secure mode on/off\n" + "x: exit\n" + "?: help\n"; } int @@ -58,11 +58,11 @@ HelloClient::run(int argc, char* argv[]) callbackOnInterrupt(); HelloPrx twoway = HelloPrx::checkedCast( - communicator()->propertyToProxy("Hello.Proxy")->ice_twoway()->ice_timeout(-1)->ice_secure(false)); + communicator()->propertyToProxy("Hello.Proxy")->ice_twoway()->ice_timeout(-1)->ice_secure(false)); if(!twoway) { - cerr << argv[0] << ": invalid proxy" << endl; - return EXIT_FAILURE; + cerr << argv[0] << ": invalid proxy" << endl; + return EXIT_FAILURE; } HelloPrx oneway = HelloPrx::uncheckedCast(twoway->ice_oneway()); HelloPrx batchOneway = HelloPrx::uncheckedCast(twoway->ice_batchOneway()); @@ -76,85 +76,85 @@ HelloClient::run(int argc, char* argv[]) char c; do { - try - { - cout << "==> "; - cin >> c; - if(c == 't') - { - twoway->sayHello(); - } - else if(c == 'o') - { - oneway->sayHello(); - } - else if(c == 'O') - { - batchOneway->sayHello(); - } - else if(c == 'd') - { - if(secure) - { - cout << "secure datagrams are not supported" << endl; - } - else - { - datagram->sayHello(); - } - } - else if(c == 'D') - { - if(secure) - { - cout << "secure datagrams are not supported" << endl; - } - else - { - batchDatagram->sayHello(); - } - } - else if(c == 'f') - { - communicator()->flushBatchRequests(); - } - else if(c == 'S') - { - secure = !secure; - - twoway = HelloPrx::uncheckedCast(twoway->ice_secure(secure)); - oneway = HelloPrx::uncheckedCast(oneway->ice_secure(secure)); - batchOneway = HelloPrx::uncheckedCast(batchOneway->ice_secure(secure)); - datagram = HelloPrx::uncheckedCast(datagram->ice_secure(secure)); - batchDatagram = HelloPrx::uncheckedCast(batchDatagram->ice_secure(secure)); - - if(secure) - { - cout << "secure mode is now on" << endl; - } - else - { - cout << "secure mode is now off" << endl; - } - } - else if(c == 'x') - { - // Nothing to do - } - else if(c == '?') - { - menu(); - } - else - { - cout << "unknown command `" << c << "'" << endl; - menu(); - } - } - catch(const Ice::Exception& ex) - { - cerr << ex << endl; - } + try + { + cout << "==> "; + cin >> c; + if(c == 't') + { + twoway->sayHello(); + } + else if(c == 'o') + { + oneway->sayHello(); + } + else if(c == 'O') + { + batchOneway->sayHello(); + } + else if(c == 'd') + { + if(secure) + { + cout << "secure datagrams are not supported" << endl; + } + else + { + datagram->sayHello(); + } + } + else if(c == 'D') + { + if(secure) + { + cout << "secure datagrams are not supported" << endl; + } + else + { + batchDatagram->sayHello(); + } + } + else if(c == 'f') + { + communicator()->flushBatchRequests(); + } + else if(c == 'S') + { + secure = !secure; + + twoway = HelloPrx::uncheckedCast(twoway->ice_secure(secure)); + oneway = HelloPrx::uncheckedCast(oneway->ice_secure(secure)); + batchOneway = HelloPrx::uncheckedCast(batchOneway->ice_secure(secure)); + datagram = HelloPrx::uncheckedCast(datagram->ice_secure(secure)); + batchDatagram = HelloPrx::uncheckedCast(batchDatagram->ice_secure(secure)); + + if(secure) + { + cout << "secure mode is now on" << endl; + } + else + { + cout << "secure mode is now off" << endl; + } + } + else if(c == 'x') + { + // Nothing to do + } + else if(c == '?') + { + menu(); + } + else + { + cout << "unknown command `" << c << "'" << endl; + menu(); + } + } + catch(const Ice::Exception& ex) + { + cerr << ex << endl; + } } while(cin.good() && c != 'x'); @@ -166,15 +166,15 @@ HelloClient::interruptCallback(int) { try { - communicator()->destroy(); + communicator()->destroy(); } catch(const IceUtil::Exception& ex) { - cerr << appName() << ": " << ex << endl; + cerr << appName() << ": " << ex << endl; } catch(...) { - cerr << appName() << ": unknown exception" << endl; + cerr << appName() << ": unknown exception" << endl; } exit(EXIT_SUCCESS); } diff --git a/cpp/demo/IceBox/hello/HelloServiceI.h b/cpp/demo/IceBox/hello/HelloServiceI.h index 15e95fe4b43..50aaaa24584 100644 --- a/cpp/demo/IceBox/hello/HelloServiceI.h +++ b/cpp/demo/IceBox/hello/HelloServiceI.h @@ -24,8 +24,8 @@ public: virtual ~HelloServiceI(); virtual void start(const ::std::string&, - const ::Ice::CommunicatorPtr&, - const ::Ice::StringSeq&); + const ::Ice::CommunicatorPtr&, + const ::Ice::StringSeq&); virtual void stop(); diff --git a/cpp/demo/IceGrid/allocate/Client.cpp b/cpp/demo/IceGrid/allocate/Client.cpp index 16774c94252..7dce0c6a6ae 100644 --- a/cpp/demo/IceGrid/allocate/Client.cpp +++ b/cpp/demo/IceGrid/allocate/Client.cpp @@ -20,7 +20,7 @@ class SessionKeepAliveThread : public IceUtil::Thread, public IceUtil::MonitorkeepAlive(); } catch(const Ice::Exception&) { - break; + break; } } } @@ -102,7 +102,7 @@ HelloClient::run(int argc, char* argv[]) callbackOnInterrupt(); IceGrid::RegistryPrx registry = IceGrid::RegistryPrx::checkedCast( - communicator()->stringToProxy("DemoIceGrid/Registry")); + communicator()->stringToProxy("DemoIceGrid/Registry")); if(!registry) { cerr << argv[0] << ": could not contact registry" << endl; @@ -111,101 +111,101 @@ HelloClient::run(int argc, char* argv[]) while(true) { - cout << "This demo accepts any user-id / password combination.\n"; + cout << "This demo accepts any user-id / password combination.\n"; - string id; - cout << "user id: " << flush; - getline(cin, id); - id = trim(id); + string id; + cout << "user id: " << flush; + getline(cin, id); + id = trim(id); - string password; - cout << "password: " << flush; - getline(cin, password); - password = trim(password); + string password; + cout << "password: " << flush; + getline(cin, password); + password = trim(password); - try - { - IceUtil::Mutex::Lock sync(_mutex); - _session = registry->createSession(id, password); - break; - } - catch(const IceGrid::PermissionDeniedException& ex) - { - cout << "permission denied:\n" << ex.reason << endl; - } + try + { + IceUtil::Mutex::Lock sync(_mutex); + _session = registry->createSession(id, password); + break; + } + catch(const IceGrid::PermissionDeniedException& ex) + { + cout << "permission denied:\n" << ex.reason << endl; + } } { - IceUtil::Mutex::Lock sync(_mutex); - _keepAlive = new SessionKeepAliveThread(_session, registry->getSessionTimeout() / 2); - _keepAlive->start(); + IceUtil::Mutex::Lock sync(_mutex); + _keepAlive = new SessionKeepAliveThread(_session, registry->getSessionTimeout() / 2); + _keepAlive->start(); } try { - // - // First try to retrieve object by identity, which will work - // if the application-single.xml descriptor is used. Otherwise - // we retrieve object by type, which will succeed if the - // application-multiple.xml descriptor is used. - // - HelloPrx hello; - try - { - hello = HelloPrx::checkedCast(_session->allocateObjectById(communicator()->stringToIdentity("hello"))); - } - catch(const IceGrid::ObjectNotRegisteredException&) - { - hello = HelloPrx::checkedCast(_session->allocateObjectByType("::Demo::Hello")); - } - - menu(); - - char c; - do - { - try - { - cout << "==> "; - cin >> c; - if(c == 't') - { - hello->sayHello(); - } - else if(c == 's') - { - hello->shutdown(); - } - else if(c == 'x') - { - // Nothing to do - } - else if(c == '?') - { - menu(); - } - else - { - cout << "unknown command `" << c << "'" << endl; - menu(); - } - } - catch(const Ice::Exception& ex) - { - cerr << ex << endl; - } - } - while(cin.good() && c != 'x'); + // + // First try to retrieve object by identity, which will work + // if the application-single.xml descriptor is used. Otherwise + // we retrieve object by type, which will succeed if the + // application-multiple.xml descriptor is used. + // + HelloPrx hello; + try + { + hello = HelloPrx::checkedCast(_session->allocateObjectById(communicator()->stringToIdentity("hello"))); + } + catch(const IceGrid::ObjectNotRegisteredException&) + { + hello = HelloPrx::checkedCast(_session->allocateObjectByType("::Demo::Hello")); + } + + menu(); + + char c; + do + { + try + { + cout << "==> "; + cin >> c; + if(c == 't') + { + hello->sayHello(); + } + else if(c == 's') + { + hello->shutdown(); + } + else if(c == 'x') + { + // Nothing to do + } + else if(c == '?') + { + menu(); + } + else + { + cout << "unknown command `" << c << "'" << endl; + menu(); + } + } + catch(const Ice::Exception& ex) + { + cerr << ex << endl; + } + } + while(cin.good() && c != 'x'); } catch(const IceGrid::AllocationException& ex) { - cerr << argv[0] << ": could not allocate object: " << ex.reason << endl; - status = EXIT_FAILURE; + cerr << argv[0] << ": could not allocate object: " << ex.reason << endl; + status = EXIT_FAILURE; } catch(...) { - cerr << "unexpected exception" << endl; - status = EXIT_FAILURE; + cerr << "unexpected exception" << endl; + status = EXIT_FAILURE; } cleanup(); @@ -219,15 +219,15 @@ HelloClient::interruptCallback(int) try { - communicator()->destroy(); + communicator()->destroy(); } catch(const IceUtil::Exception& ex) { - cerr << appName() << ": " << ex << endl; + cerr << appName() << ": " << ex << endl; } catch(...) { - cerr << appName() << ": unknown exception" << endl; + cerr << appName() << ": unknown exception" << endl; } exit(EXIT_SUCCESS); } @@ -243,14 +243,14 @@ HelloClient::cleanup() // if(_keepAlive) { - _keepAlive->destroy(); - _keepAlive->getThreadControl().join(); - _keepAlive = 0; + _keepAlive->destroy(); + _keepAlive->getThreadControl().join(); + _keepAlive = 0; } if(_session) { - _session->destroy(); - _session = 0; + _session->destroy(); + _session = 0; } } @@ -258,11 +258,11 @@ void HelloClient::menu() { cout << - "usage:\n" - "t: send greeting\n" - "s: shutdown server\n" - "x: exit\n" - "?: help\n"; + "usage:\n" + "t: send greeting\n" + "s: shutdown server\n" + "x: exit\n" + "?: help\n"; } string diff --git a/cpp/demo/IceGrid/replication/Client.cpp b/cpp/demo/IceGrid/replication/Client.cpp index 1fc5d816c5d..baabc33bef7 100644 --- a/cpp/demo/IceGrid/replication/Client.cpp +++ b/cpp/demo/IceGrid/replication/Client.cpp @@ -58,8 +58,8 @@ HelloClient::run(int argc, char* argv[]) HelloPrx hello = HelloPrx::checkedCast(obj); if(!hello) { - cerr << argv[0] << ": couldn't find a `::Demo::Hello' object." << endl; - return EXIT_FAILURE; + cerr << argv[0] << ": couldn't find a `::Demo::Hello' object." << endl; + return EXIT_FAILURE; } string s; @@ -92,15 +92,15 @@ HelloClient::interruptCallback(int) { try { - communicator()->destroy(); + communicator()->destroy(); } catch(const IceUtil::Exception& ex) { - cerr << appName() << ": " << ex << endl; + cerr << appName() << ": " << ex << endl; } catch(...) { - cerr << appName() << ": unknown exception" << endl; + cerr << appName() << ": unknown exception" << endl; } exit(EXIT_SUCCESS); } diff --git a/cpp/demo/IceGrid/sessionActivation/Client.cpp b/cpp/demo/IceGrid/sessionActivation/Client.cpp index f01015892c8..8a120aef9ba 100644 --- a/cpp/demo/IceGrid/sessionActivation/Client.cpp +++ b/cpp/demo/IceGrid/sessionActivation/Client.cpp @@ -20,7 +20,7 @@ class SessionKeepAliveThread : public IceUtil::Thread, public IceUtil::MonitorkeepAlive(); } catch(const Ice::Exception&) { - break; + break; } } } @@ -102,7 +102,7 @@ HelloClient::run(int argc, char* argv[]) callbackOnInterrupt(); IceGrid::RegistryPrx registry = - IceGrid::RegistryPrx::checkedCast(communicator()->stringToProxy("DemoIceGrid/Registry")); + IceGrid::RegistryPrx::checkedCast(communicator()->stringToProxy("DemoIceGrid/Registry")); if(!registry) { cerr << argv[0] << ": could not contact registry" << endl; @@ -111,93 +111,93 @@ HelloClient::run(int argc, char* argv[]) while(true) { - cout << "This demo accepts any user-id / password combination.\n"; - - string id; - cout << "user id: " << flush; - getline(cin, id); - id = trim(id); - - string password; - cout << "password: " << flush; - getline(cin, password); - password = trim(password); - - try - { - IceUtil::Mutex::Lock sync(_mutex); - _session = registry->createSession(id, password); - break; - } - catch(const IceGrid::PermissionDeniedException& ex) - { - cout << "permission denied:\n" << ex.reason << endl; - } + cout << "This demo accepts any user-id / password combination.\n"; + + string id; + cout << "user id: " << flush; + getline(cin, id); + id = trim(id); + + string password; + cout << "password: " << flush; + getline(cin, password); + password = trim(password); + + try + { + IceUtil::Mutex::Lock sync(_mutex); + _session = registry->createSession(id, password); + break; + } + catch(const IceGrid::PermissionDeniedException& ex) + { + cout << "permission denied:\n" << ex.reason << endl; + } } { - IceUtil::Mutex::Lock sync(_mutex); - _keepAlive = new SessionKeepAliveThread(_session, registry->getSessionTimeout() / 2); - _keepAlive->start(); + IceUtil::Mutex::Lock sync(_mutex); + _keepAlive = new SessionKeepAliveThread(_session, registry->getSessionTimeout() / 2); + _keepAlive->start(); } try { - HelloPrx hello = HelloPrx::checkedCast(_session->allocateObjectById(communicator()->stringToIdentity("hello"))); - - menu(); - - char c; - do - { - try - { - cout << "==> "; - cin >> c; - if(c == 't') - { - hello->sayHello(); - } - else if(c == 'x') - { - // Nothing to do - } - else if(c == '?') - { - menu(); - } - else - { - cout << "unknown command `" << c << "'" << endl; - menu(); - } - } - catch(const Ice::Exception& ex) - { - cerr << ex << endl; - } - } - while(cin.good() && c != 'x'); + HelloPrx hello = HelloPrx::checkedCast(_session->allocateObjectById(communicator()->stringToIdentity("hello"))); + + menu(); + + char c; + do + { + try + { + cout << "==> "; + cin >> c; + if(c == 't') + { + hello->sayHello(); + } + else if(c == 'x') + { + // Nothing to do + } + else if(c == '?') + { + menu(); + } + else + { + cout << "unknown command `" << c << "'" << endl; + menu(); + } + } + catch(const Ice::Exception& ex) + { + cerr << ex << endl; + } + } + while(cin.good() && c != 'x'); } catch(const IceGrid::AllocationException& ex) { - cerr << argv[0] << ": could not allocate object: " << ex.reason << endl; - status = EXIT_FAILURE; + cerr << argv[0] << ": could not allocate object: " << ex.reason << endl; + status = EXIT_FAILURE; } catch(const IceGrid::ObjectNotRegisteredException&) { - cerr << argv[0] << ": object not registered with registry" << endl; - status = EXIT_FAILURE; + cerr << argv[0] << ": object not registered with registry" << endl; + status = EXIT_FAILURE; } catch(const Ice::Exception& ex) { - cerr << ex << endl; - status = EXIT_FAILURE; + cerr << ex << endl; + status = EXIT_FAILURE; } catch(...) { - cerr << "unexpected exception" << endl; - status = EXIT_FAILURE; + cerr << "unexpected exception" << endl; + status = EXIT_FAILURE; } cleanup(); @@ -212,15 +212,15 @@ HelloClient::interruptCallback(int) try { - communicator()->destroy(); + communicator()->destroy(); } catch(const IceUtil::Exception& ex) { - cerr << appName() << ": " << ex << endl; + cerr << appName() << ": " << ex << endl; } catch(...) { - cerr << appName() << ": unknown exception" << endl; + cerr << appName() << ": unknown exception" << endl; } exit(EXIT_SUCCESS); } @@ -236,14 +236,14 @@ HelloClient::cleanup() // if(_keepAlive) { - _keepAlive->destroy(); - _keepAlive->getThreadControl().join(); - _keepAlive = 0; + _keepAlive->destroy(); + _keepAlive->getThreadControl().join(); + _keepAlive = 0; } if(_session) { - _session->destroy(); - _session = 0; + _session->destroy(); + _session = 0; } } @@ -251,10 +251,10 @@ void HelloClient::menu() { cout << - "usage:\n" - "t: send greeting\n" - "x: exit\n" - "?: help\n"; + "usage:\n" + "t: send greeting\n" + "x: exit\n" + "?: help\n"; } string diff --git a/cpp/demo/IceGrid/simple/Client.cpp b/cpp/demo/IceGrid/simple/Client.cpp index 8f8d24029f8..5528bdad6b7 100644 --- a/cpp/demo/IceGrid/simple/Client.cpp +++ b/cpp/demo/IceGrid/simple/Client.cpp @@ -37,11 +37,11 @@ void HelloClient::menu() { cout << - "usage:\n" - "t: send greeting\n" - "s: shutdown server\n" - "x: exit\n" - "?: help\n"; + "usage:\n" + "t: send greeting\n" + "s: shutdown server\n" + "x: exit\n" + "?: help\n"; } int @@ -61,17 +61,17 @@ HelloClient::run(int argc, char* argv[]) HelloPrx hello; try { - hello = HelloPrx::checkedCast(communicator()->stringToProxy("hello")); + hello = HelloPrx::checkedCast(communicator()->stringToProxy("hello")); } catch(const Ice::NotRegisteredException&) { - IceGrid::QueryPrx query = IceGrid::QueryPrx::checkedCast(communicator()->stringToProxy("DemoIceGrid/Query")); - hello = HelloPrx::checkedCast(query->findObjectByType("::Demo::Hello")); + IceGrid::QueryPrx query = IceGrid::QueryPrx::checkedCast(communicator()->stringToProxy("DemoIceGrid/Query")); + hello = HelloPrx::checkedCast(query->findObjectByType("::Demo::Hello")); } if(!hello) { - cerr << argv[0] << ": couldn't find a `::Demo::Hello' object." << endl; - return EXIT_FAILURE; + cerr << argv[0] << ": couldn't find a `::Demo::Hello' object." << endl; + return EXIT_FAILURE; } menu(); @@ -79,36 +79,36 @@ HelloClient::run(int argc, char* argv[]) char c; do { - try - { - cout << "==> "; - cin >> c; - if(c == 't') - { - hello->sayHello(); - } - else if(c == 's') - { - hello->shutdown(); - } - else if(c == 'x') - { - // Nothing to do - } - else if(c == '?') - { - menu(); - } - else - { - cout << "unknown command `" << c << "'" << endl; - menu(); - } - } - catch(const Ice::Exception& ex) - { - cerr << ex << endl; - } + try + { + cout << "==> "; + cin >> c; + if(c == 't') + { + hello->sayHello(); + } + else if(c == 's') + { + hello->shutdown(); + } + else if(c == 'x') + { + // Nothing to do + } + else if(c == '?') + { + menu(); + } + else + { + cout << "unknown command `" << c << "'" << endl; + menu(); + } + } + catch(const Ice::Exception& ex) + { + cerr << ex << endl; + } } while(cin.good() && c != 'x'); @@ -120,15 +120,15 @@ HelloClient::interruptCallback(int) { try { - communicator()->destroy(); + communicator()->destroy(); } catch(const IceUtil::Exception& ex) { - cerr << appName() << ": " << ex << endl; + cerr << appName() << ": " << ex << endl; } catch(...) { - cerr << appName() << ": unknown exception" << endl; + cerr << appName() << ": unknown exception" << endl; } exit(EXIT_SUCCESS); } diff --git a/cpp/demo/IcePatch2/MFC/PatchClientDlg.cpp b/cpp/demo/IcePatch2/MFC/PatchClientDlg.cpp index 5aaca0ee731..5f8d6f61acf 100755 --- a/cpp/demo/IcePatch2/MFC/PatchClientDlg.cpp +++ b/cpp/demo/IcePatch2/MFC/PatchClientDlg.cpp @@ -25,77 +25,77 @@ class DialogPatcherFeedback : public IcePatch2::PatcherFeedback public: DialogPatcherFeedback(CPatchDlg* dialog) : - _dialog(dialog), + _dialog(dialog), _filesPatched(0) { - assert(_dialog); + assert(_dialog); } virtual bool noFileSummary(const string& reason) { - return IDYES == AfxMessageBox(L"Cannot load file summary. Perform a thorough patch?", MB_YESNO|MB_ICONSTOP); + return IDYES == AfxMessageBox(L"Cannot load file summary. Perform a thorough patch?", MB_YESNO|MB_ICONSTOP); } virtual bool checksumStart() { - return _dialog->checksumStart(); + return _dialog->checksumStart(); } virtual bool checksumProgress(const string& path) { - return _dialog->checksumProgress(path); + return _dialog->checksumProgress(path); } virtual bool checksumEnd() { - return _dialog->checksumEnd(); + return _dialog->checksumEnd(); } virtual bool fileListStart() { - return _dialog->fileListStart(); + return _dialog->fileListStart(); } virtual bool fileListProgress(Ice::Int percent) { - return _dialog->fileListProgress(percent); + return _dialog->fileListProgress(percent); } virtual bool fileListEnd() { - return _dialog->fileListEnd(); + return _dialog->fileListEnd(); } virtual bool patchStart(const string& path, Ice::Long size, Ice::Long totalProgress, Ice::Long totalSize) { - return _dialog->patchStart(path, size, totalProgress, totalSize); + return _dialog->patchStart(path, size, totalProgress, totalSize); } virtual bool patchProgress(Ice::Long progress, Ice::Long size, Ice::Long totalProgress, Ice::Long totalSize) { - return _dialog->patchProgress(progress, size, totalProgress, totalSize); + return _dialog->patchProgress(progress, size, totalProgress, totalSize); } virtual bool patchEnd() { - ++_filesPatched; - return _dialog->patchEnd(); + ++_filesPatched; + return _dialog->patchEnd(); } virtual int filesPatched() const { - return _filesPatched; + return _filesPatched; } private: @@ -181,10 +181,10 @@ CPatchDlg::patchStart(const string& path, Ice::Long size, Ice::Long totalProgres { if(!_isPatch) { - _startTime = IceUtil::Time::now(); - _status->SetWindowText(CString(L" Patching...")); - _speed->SetWindowText(CString(L" 0.0 KB/s")); - _isPatch = true; + _startTime = IceUtil::Time::now(); + _status->SetWindowText(CString(L" Patching...")); + _speed->SetWindowText(CString(L" 0.0 KB/s")); + _isPatch = true; } CString file; @@ -200,15 +200,15 @@ CPatchDlg::patchProgress(Ice::Long, Ice::Long, Ice::Long totalProgress, Ice::Lon IceUtil::Time elapsed = IceUtil::Time::now() - _startTime; if(elapsed.toSeconds() > 0) { - CString speed; - speed.Format(L" %s/s", convertSize(totalProgress / elapsed.toSeconds())); - _speed->SetWindowText(speed); + CString speed; + speed.Format(L" %s/s", convertSize(totalProgress / elapsed.toSeconds())); + _speed->SetWindowText(speed); } int pcnt = 100; if(totalSize > 0) { - pcnt = static_cast(totalProgress * 100 / totalSize); + pcnt = static_cast(totalProgress * 100 / totalSize); } CString percent; percent.Format(L"%d%%", pcnt); @@ -339,18 +339,18 @@ CPatchDlg::OnSelectDir() LPITEMIDLIST pidl = SHBrowseForFolder(&info); if(pidl != 0) { - // + // // Get the name of the selected folder. - // + // TCHAR path[MAX_PATH]; if(SHGetPathFromIDList(pidl, path)) { - _path->SetWindowText(path); + _path->SetWindowText(path); } - // + // // Free up memory used. - // + // IMalloc * imalloc = 0; if(SUCCEEDED(SHGetMalloc(&imalloc))) { @@ -365,61 +365,61 @@ CPatchDlg::OnStartPatch() { try { - Ice::PropertiesPtr properties = _communicator->getProperties(); - - // - // Set the patch directory. - // - CString path; - _path->GetWindowText(path); - if(path.IsEmpty()) - { - AfxMessageBox(CString(L"Please select a patch directory."), MB_OK|MB_ICONEXCLAMATION); - return; - } - properties->setProperty("IcePatch2.Directory", IceUtil::wstringToString(wstring(path))); - - // - // Set the thorough patch flag. - // - string thorough = _thorough->GetCheck() == BST_CHECKED ? "1" : "0"; - properties->setProperty("IcePatch2.Thorough", thorough); - - // - // Set the remove orphan flag. - // - string remove = _remove->GetCheck() == BST_CHECKED ? "1" : "0"; - properties->setProperty("IcePatch2.Remove", remove); + Ice::PropertiesPtr properties = _communicator->getProperties(); + + // + // Set the patch directory. + // + CString path; + _path->GetWindowText(path); + if(path.IsEmpty()) + { + AfxMessageBox(CString(L"Please select a patch directory."), MB_OK|MB_ICONEXCLAMATION); + return; + } + properties->setProperty("IcePatch2.Directory", IceUtil::wstringToString(wstring(path))); + + // + // Set the thorough patch flag. + // + string thorough = _thorough->GetCheck() == BST_CHECKED ? "1" : "0"; + properties->setProperty("IcePatch2.Thorough", thorough); + + // + // Set the remove orphan flag. + // + string remove = _remove->GetCheck() == BST_CHECKED ? "1" : "0"; + properties->setProperty("IcePatch2.Remove", remove); DialogPatcherFeedbackPtr feedback = new DialogPatcherFeedback(this); - IcePatch2::PatcherPtr patcher = new IcePatch2::Patcher(_communicator, feedback); - - // - // Disable a few controls during the patch process. - // - _path->EnableWindow(false); - _select->EnableWindow(false); - _thorough->EnableWindow(false); - _remove->EnableWindow(false); - _start->EnableWindow(false); - - // - // Patch - // - bool aborted = !patcher->prepare(); - if(!aborted) - { - aborted = !patcher->patch(""); - } - if(!aborted) - { - patcher->finish(); - } - - // - // Reset and indicate the completion status. - // - reset(aborted ? L" Aborted" : L" Completed"); + IcePatch2::PatcherPtr patcher = new IcePatch2::Patcher(_communicator, feedback); + + // + // Disable a few controls during the patch process. + // + _path->EnableWindow(false); + _select->EnableWindow(false); + _thorough->EnableWindow(false); + _remove->EnableWindow(false); + _start->EnableWindow(false); + + // + // Patch + // + bool aborted = !patcher->prepare(); + if(!aborted) + { + aborted = !patcher->patch(""); + } + if(!aborted) + { + patcher->finish(); + } + + // + // Reset and indicate the completion status. + // + reset(aborted ? L" Aborted" : L" Completed"); } catch(const IceUtil::Exception& ex) { @@ -500,24 +500,24 @@ CPatchDlg::convertSize(Ice::Long size) const } else { - final = start / megabyte; - if(final >= 1) - { - units = L"MB"; - } - else - { - final = start / kilobyte; - if(final >= 1) - { - units = L"KB"; - } - else - { - final = start; - units = L"B"; - } - } + final = start / megabyte; + if(final >= 1) + { + units = L"MB"; + } + else + { + final = start / kilobyte; + if(final >= 1) + { + units = L"KB"; + } + else + { + final = start; + units = L"B"; + } + } } CString convert; diff --git a/cpp/demo/IcePatch2/MFC/stdafx.h b/cpp/demo/IcePatch2/MFC/stdafx.h index ea41685f994..b9072540cc6 100755 --- a/cpp/demo/IcePatch2/MFC/stdafx.h +++ b/cpp/demo/IcePatch2/MFC/stdafx.h @@ -21,30 +21,30 @@ #endif #ifndef VC_EXTRALEAN -#define VC_EXTRALEAN // Exclude rarely-used stuff from Windows headers +#define VC_EXTRALEAN // Exclude rarely-used stuff from Windows headers #endif // Modify the following defines if you have to target a platform prior to the ones specified below. // Refer to MSDN for the latest info on corresponding values for different platforms. -#ifndef WINVER // Allow use of features specific to Windows 95 and Windows NT 4 or later. -#define WINVER 0x0400 // Change this to the appropriate value to target Windows 98 and Windows 2000 or later. +#ifndef WINVER // Allow use of features specific to Windows 95 and Windows NT 4 or later. +#define WINVER 0x0400 // Change this to the appropriate value to target Windows 98 and Windows 2000 or later. #endif -#ifndef _WIN32_WINNT // Allow use of features specific to Windows NT 4 or later. -#define _WIN32_WINNT 0x0400 // Change this to the appropriate value to target Windows 98 and Windows 2000 or later. -#endif +#ifndef _WIN32_WINNT // Allow use of features specific to Windows NT 4 or later. +#define _WIN32_WINNT 0x0400 // Change this to the appropriate value to target Windows 98 and Windows 2000 or later. +#endif #if 0 -#ifndef _WIN32_WINDOWS // Allow use of features specific to Windows 98 or later. +#ifndef _WIN32_WINDOWS // Allow use of features specific to Windows 98 or later. #define _WIN32_WINDOWS 0x0410 // Change this to the appropriate value to target Windows Me or later. #endif -#ifndef _WIN32_IE // Allow use of features specific to IE 4.0 or later. -#define _WIN32_IE 0x0400 // Change this to the appropriate value to target IE 5.0 or later. +#ifndef _WIN32_IE // Allow use of features specific to IE 4.0 or later. +#define _WIN32_IE 0x0400 // Change this to the appropriate value to target IE 5.0 or later. #endif #endif -#define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS // some CString constructors will be explicit +#define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS // some CString constructors will be explicit // turns off MFC's hiding of some common and often safely ignored warning messages #define _AFX_ALL_WARNINGS @@ -52,9 +52,9 @@ #include // MFC core and standard components #include // MFC extensions -#include // MFC support for Internet Explorer 4 Common Controls +#include // MFC support for Internet Explorer 4 Common Controls #ifndef _AFX_NO_AFXCMN_SUPPORT -#include // MFC support for Windows Common Controls +#include // MFC support for Windows Common Controls #endif // _AFX_NO_AFXCMN_SUPPORT #include diff --git a/cpp/demo/IceStorm/clock/Publisher.cpp b/cpp/demo/IceStorm/clock/Publisher.cpp index c779a97e0c7..166a2c8c3fa 100644 --- a/cpp/demo/IceStorm/clock/Publisher.cpp +++ b/cpp/demo/IceStorm/clock/Publisher.cpp @@ -52,22 +52,22 @@ Publisher::run(int argc, char* argv[]) } catch(const IceUtil::BadOptException& e) { - cerr << argv[0] << ": " << e.reason << endl; - return EXIT_FAILURE; + cerr << argv[0] << ": " << e.reason << endl; + return EXIT_FAILURE; } IceStorm::TopicManagerPrx manager = IceStorm::TopicManagerPrx::checkedCast( - communicator()->propertyToProxy("IceStorm.TopicManager.Proxy")); + communicator()->propertyToProxy("IceStorm.TopicManager.Proxy")); if(!manager) { - cerr << appName() << ": invalid proxy" << endl; - return EXIT_FAILURE; + cerr << appName() << ": invalid proxy" << endl; + return EXIT_FAILURE; } string topicName = "time"; if(!remaining.empty()) { - topicName = remaining.front(); + topicName = remaining.front(); } // @@ -76,19 +76,19 @@ Publisher::run(int argc, char* argv[]) IceStorm::TopicPrx topic; try { - topic = manager->retrieve(topicName); + topic = manager->retrieve(topicName); } catch(const IceStorm::NoSuchTopic&) { - try - { - topic = manager->create(topicName); - } - catch(const IceStorm::TopicExists&) - { - cerr << appName() << ": temporary failure. try again." << endl; - return EXIT_FAILURE; - } + try + { + topic = manager->create(topicName); + } + catch(const IceStorm::TopicExists&) + { + cerr << appName() << ": temporary failure. try again." << endl; + return EXIT_FAILURE; + } } // @@ -99,38 +99,38 @@ Publisher::run(int argc, char* argv[]) int optsSet = 0; if(opts.isSet("datagram")) { - publisher = publisher->ice_datagram(); - ++optsSet; + publisher = publisher->ice_datagram(); + ++optsSet; } else if(opts.isSet("twoway")) { - // Do nothing. - ++optsSet; + // Do nothing. + ++optsSet; } else if(opts.isSet("oneway") || optsSet == 0) { - publisher = publisher->ice_oneway(); - ++optsSet; + publisher = publisher->ice_oneway(); + ++optsSet; } if(optsSet != 1) { - usage(appName()); - return EXIT_FAILURE; + usage(appName()); + return EXIT_FAILURE; } ClockPrx clock = ClockPrx::uncheckedCast(publisher); cout << "publishing tick events. Press ^C to terminate the application." << endl; try { - while(true) - { - clock->tick(IceUtil::Time::now().toDateTime()); + while(true) + { + clock->tick(IceUtil::Time::now().toDateTime()); IceUtil::ThreadControl::sleep(IceUtil::Time::seconds(1)); - } + } } catch(const Ice::CommunicatorDestroyedException&) { - // Ignore + // Ignore } return EXIT_SUCCESS; diff --git a/cpp/demo/IceStorm/clock/Subscriber.cpp b/cpp/demo/IceStorm/clock/Subscriber.cpp index f6082fef192..abc593c8b0b 100644 --- a/cpp/demo/IceStorm/clock/Subscriber.cpp +++ b/cpp/demo/IceStorm/clock/Subscriber.cpp @@ -25,7 +25,7 @@ public: virtual void tick(const string& time, const Ice::Current&) { - cout << time << endl; + cout << time << endl; } }; @@ -66,41 +66,41 @@ Subscriber::run(int argc, char* argv[]) } catch(const IceUtil::BadOptException& e) { - cerr << argv[0] << ": " << e.reason << endl; - usage(appName()); - return EXIT_FAILURE; + cerr << argv[0] << ": " << e.reason << endl; + usage(appName()); + return EXIT_FAILURE; } IceStorm::TopicManagerPrx manager = IceStorm::TopicManagerPrx::checkedCast( - communicator()->propertyToProxy("IceStorm.TopicManager.Proxy")); + communicator()->propertyToProxy("IceStorm.TopicManager.Proxy")); if(!manager) { - cerr << appName() << ": invalid proxy" << endl; - return EXIT_FAILURE; + cerr << appName() << ": invalid proxy" << endl; + return EXIT_FAILURE; } string topicName = "time"; if(!remaining.empty()) { - topicName = remaining.front(); + topicName = remaining.front(); } IceStorm::TopicPrx topic; try { - topic = manager->retrieve(topicName); + topic = manager->retrieve(topicName); } catch(const IceStorm::NoSuchTopic&) { - try - { - topic = manager->create(topicName); - } - catch(const IceStorm::TopicExists&) - { - cerr << appName() << ": temporary failure. try again." << endl; - return EXIT_FAILURE; - } + try + { + topic = manager->create(topicName); + } + catch(const IceStorm::TopicExists&) + { + cerr << appName() << ": temporary failure. try again." << endl; + return EXIT_FAILURE; + } } Ice::ObjectAdapterPtr adapter = communicator()->createObjectAdapter("Clock.Subscriber"); @@ -116,47 +116,47 @@ Subscriber::run(int argc, char* argv[]) int optsSet = 0; if(opts.isSet("datagram")) { - subscriber = subscriber->ice_datagram(); - ++optsSet; + subscriber = subscriber->ice_datagram(); + ++optsSet; } if(opts.isSet("twoway")) { - // Do nothing to the subscriber proxy. Its already twoway. - ++optsSet; + // Do nothing to the subscriber proxy. Its already twoway. + ++optsSet; } if(opts.isSet("ordered")) { - qos["reliability"] = "ordered"; - // Do nothing to the subscriber proxy. Its already twoway. - ++optsSet; + qos["reliability"] = "ordered"; + // Do nothing to the subscriber proxy. Its already twoway. + ++optsSet; } if(opts.isSet("oneway") || optsSet == 0) { - subscriber = subscriber->ice_oneway(); - ++optsSet; + subscriber = subscriber->ice_oneway(); + ++optsSet; } if(optsSet != 1) { - usage(appName()); - return EXIT_FAILURE; + usage(appName()); + return EXIT_FAILURE; } if(opts.isSet("batch")) { - if(opts.isSet("twoway") || opts.isSet("ordered")) - { - cerr << appName() << ": batch can only be set with oneway or datagram" << endl; - return EXIT_FAILURE; - } - if(opts.isSet("datagram")) - { - subscriber = subscriber->ice_batchDatagram(); - } - else - { - subscriber = subscriber->ice_batchOneway(); - } + if(opts.isSet("twoway") || opts.isSet("ordered")) + { + cerr << appName() << ": batch can only be set with oneway or datagram" << endl; + return EXIT_FAILURE; + } + if(opts.isSet("datagram")) + { + subscriber = subscriber->ice_batchDatagram(); + } + else + { + subscriber = subscriber->ice_batchOneway(); + } } topic->subscribeAndGetPublisher(qos, subscriber); diff --git a/cpp/demo/IceStorm/counter/Client.cpp b/cpp/demo/IceStorm/counter/Client.cpp index 82fa66270c0..863b90f9bcd 100644 --- a/cpp/demo/IceStorm/counter/Client.cpp +++ b/cpp/demo/IceStorm/counter/Client.cpp @@ -40,15 +40,15 @@ Client::run(int argc, char* argv[]) string proxy = properties->getProperty(proxyProperty); if(proxy.empty()) { - cerr << appName() << ": property `" << proxyProperty << "' not set" << endl; - return EXIT_FAILURE; + cerr << appName() << ": property `" << proxyProperty << "' not set" << endl; + return EXIT_FAILURE; } CounterPrx counter = CounterPrx::uncheckedCast(communicator()->stringToProxy(proxy)); if(!counter) { - cerr << appName() << ": invalid proxy" << endl; - return EXIT_FAILURE; + cerr << appName() << ": invalid proxy" << endl; + return EXIT_FAILURE; } MTPrinterPtr printer = new MTPrinter(); @@ -65,36 +65,36 @@ Client::run(int argc, char* argv[]) char c; do { - try - { - printer->print("==> "); - cin >> c; - if(c == 'i') - { - counter->inc(1); - } - else if(c == 'd') - { - counter->inc(-1); - } - else if(c == 'x') - { - // Nothing to do - } - else if(c == '?') - { - menu(printer); - } - else - { - cout << "unknown command `" << c << "'" << endl; - menu(printer); - } - } - catch(const Ice::Exception& ex) - { - cerr << ex << endl; - } + try + { + printer->print("==> "); + cin >> c; + if(c == 'i') + { + counter->inc(1); + } + else if(c == 'd') + { + counter->inc(-1); + } + else if(c == 'x') + { + // Nothing to do + } + else if(c == '?') + { + menu(printer); + } + else + { + cout << "unknown command `" << c << "'" << endl; + menu(printer); + } + } + catch(const Ice::Exception& ex) + { + cerr << ex << endl; + } } while(cin.good() && c != 'x'); @@ -107,9 +107,9 @@ void Client::menu(const MTPrinterPtr& printer) { printer->print( - "usage:\n" - "i: increment the counter\n" - "d: decrement the counter\n" - "x: exit\n" - "?: help\n"); + "usage:\n" + "i: increment the counter\n" + "d: decrement the counter\n" + "x: exit\n" + "?: help\n"); } diff --git a/cpp/demo/IceStorm/counter/CounterI.cpp b/cpp/demo/IceStorm/counter/CounterI.cpp index 9391cec441f..ff9fad3d1f2 100644 --- a/cpp/demo/IceStorm/counter/CounterI.cpp +++ b/cpp/demo/IceStorm/counter/CounterI.cpp @@ -32,7 +32,7 @@ CounterI::subscribe(const CounterObserverPrx& observer, const Ice::Current&) // the given subscriber. // CounterObserverPrx o = CounterObserverPrx::uncheckedCast( - _topic->subscribeAndGetPublisher(IceStorm::QoS(), observer)); + _topic->subscribeAndGetPublisher(IceStorm::QoS(), observer)); o->init(_value); } diff --git a/cpp/demo/IceStorm/counter/Server.cpp b/cpp/demo/IceStorm/counter/Server.cpp index 33bbcb4c8aa..838b7d11efa 100644 --- a/cpp/demo/IceStorm/counter/Server.cpp +++ b/cpp/demo/IceStorm/counter/Server.cpp @@ -40,33 +40,33 @@ Server::run(int argc, char* argv[]) string proxy = properties->getProperty(proxyProperty); if(proxy.empty()) { - cerr << appName() << ": property `" << proxyProperty << "' not set" << endl; - return EXIT_FAILURE; + cerr << appName() << ": property `" << proxyProperty << "' not set" << endl; + return EXIT_FAILURE; } IceStorm::TopicManagerPrx manager = IceStorm::TopicManagerPrx::checkedCast(communicator()->stringToProxy(proxy)); if(!manager) { - cerr << appName() << ": invalid proxy" << endl; - return EXIT_FAILURE; + cerr << appName() << ": invalid proxy" << endl; + return EXIT_FAILURE; } IceStorm::TopicPrx topic; try { - topic = manager->retrieve("counter"); + topic = manager->retrieve("counter"); } catch(const IceStorm::NoSuchTopic&) { - try - { - topic = manager->create("counter"); - } - catch(const IceStorm::TopicExists&) - { - cerr << appName() << ": topic exists, please try again." << endl; - return EXIT_FAILURE; - } + try + { + topic = manager->create("counter"); + } + catch(const IceStorm::TopicExists&) + { + cerr << appName() << ": topic exists, please try again." << endl; + return EXIT_FAILURE; + } } // diff --git a/cpp/demo/IceStorm/replicated/Publisher.cpp b/cpp/demo/IceStorm/replicated/Publisher.cpp index c1d1d1ec52b..cf432841e02 100644 --- a/cpp/demo/IceStorm/replicated/Publisher.cpp +++ b/cpp/demo/IceStorm/replicated/Publisher.cpp @@ -54,7 +54,7 @@ Publisher::run(int argc, char* argv[]) catch(const IceStorm::NoSuchTopic&) { cerr << appName() << ": topics not created yet, run subscriber." << endl; - return EXIT_FAILURE; + return EXIT_FAILURE; } // diff --git a/cpp/demo/IceStorm/replicated/Subscriber.cpp b/cpp/demo/IceStorm/replicated/Subscriber.cpp index 8755650cf9f..a6fbc11e35d 100644 --- a/cpp/demo/IceStorm/replicated/Subscriber.cpp +++ b/cpp/demo/IceStorm/replicated/Subscriber.cpp @@ -72,34 +72,34 @@ Subscriber::run(int argc, char* argv[]) Ice::ObjectProxySeq::const_iterator p; for(p = managers.begin(); p != managers.end(); ++p) { - // - // Add a Servant for the Ice Object. - // - IceStorm::TopicManagerPrx manager = IceStorm::TopicManagerPrx::checkedCast(*p); + // + // Add a Servant for the Ice Object. + // + IceStorm::TopicManagerPrx manager = IceStorm::TopicManagerPrx::checkedCast(*p); - try - { + try + { topic = manager->retrieve(topicName); - } - catch(const IceStorm::NoSuchTopic&) - { - try - { - topic = manager->create(topicName); - } - catch(const IceStorm::TopicExists&) - { - cerr << appName() << ": temporary failure. try again." << endl; - return EXIT_FAILURE; - } - } + } + catch(const IceStorm::NoSuchTopic&) + { + try + { + topic = manager->create(topicName); + } + catch(const IceStorm::TopicExists&) + { + cerr << appName() << ": temporary failure. try again." << endl; + return EXIT_FAILURE; + } + } } Ice::ObjectProxySeq topics = query->findAllReplicas(topic); for(p = topics.begin(); p != topics.end(); ++p) { topic = IceStorm::TopicPrx::uncheckedCast(*p); - topic->subscribeAndGetPublisher(IceStorm::QoS(), clock); + topic->subscribeAndGetPublisher(IceStorm::QoS(), clock); } adapter->activate(); diff --git a/cpp/demo/IceUtil/workqueue/WorkQueue.cpp b/cpp/demo/IceUtil/workqueue/WorkQueue.cpp index 2b7c081e1da..3e006040fae 100644 --- a/cpp/demo/IceUtil/workqueue/WorkQueue.cpp +++ b/cpp/demo/IceUtil/workqueue/WorkQueue.cpp @@ -36,28 +36,28 @@ public: virtual void run() { - while(1) - { - string item = nextItem(); - if(item == "destroy") - { - break; - } - - mtprint("work item: " + item + "\n"); - IceUtil::ThreadControl::sleep(IceUtil::Time::seconds(1)); - } + while(1) + { + string item = nextItem(); + if(item == "destroy") + { + break; + } + + mtprint("work item: " + item + "\n"); + IceUtil::ThreadControl::sleep(IceUtil::Time::seconds(1)); + } } void add(const string& item) { - IceUtil::Monitor::Lock lock(_monitor); - if(_queue.empty()) - { - _monitor.notify(); - } - _queue.push_back(item); + IceUtil::Monitor::Lock lock(_monitor); + if(_queue.empty()) + { + _monitor.notify(); + } + _queue.push_back(item); } private: @@ -65,15 +65,15 @@ private: string nextItem() { - IceUtil::Monitor::Lock lock(_monitor); - while(_queue.empty()) - { - _monitor.wait(); - } - - string item = _queue.front(); - _queue.pop_front(); - return item; + IceUtil::Monitor::Lock lock(_monitor); + while(_queue.empty()) + { + _monitor.wait(); + } + + string item = _queue.front(); + _queue.pop_front(); + return item; } @@ -88,31 +88,31 @@ main() { try { - WorkQueuePtr h = new WorkQueue(); - IceUtil::ThreadControl control = h->start(); - mtprint("Pushing work items"); - mtprint("."); - h->add("item1"); - mtprint("."); - h->add("item2"); - mtprint("."); - h->add("item3"); - mtprint("."); - h->add("item4"); - mtprint("."); - h->add("item5"); - mtprint("."); - h->add("destroy"); - mtprint("ok\n"); - mtprint("Waiting for WorkQueue to terminate\n"); - control.join(); + WorkQueuePtr h = new WorkQueue(); + IceUtil::ThreadControl control = h->start(); + mtprint("Pushing work items"); + mtprint("."); + h->add("item1"); + mtprint("."); + h->add("item2"); + mtprint("."); + h->add("item3"); + mtprint("."); + h->add("item4"); + mtprint("."); + h->add("item5"); + mtprint("."); + h->add("destroy"); + mtprint("ok\n"); + mtprint("Waiting for WorkQueue to terminate\n"); + control.join(); } catch(const IceUtil::Exception& ex) { - ostringstream os; - os << ex << "\n"; - mtprint(os.str()); - return EXIT_FAILURE; + ostringstream os; + os << ex << "\n"; + mtprint(os.str()); + return EXIT_FAILURE; } return EXIT_SUCCESS; diff --git a/cpp/demo/book/evictor/EvictorBase.cpp b/cpp/demo/book/evictor/EvictorBase.cpp index 49edb2a3366..fbea9580212 100644 --- a/cpp/demo/book/evictor/EvictorBase.cpp +++ b/cpp/demo/book/evictor/EvictorBase.cpp @@ -28,26 +28,26 @@ EvictorBase::locate(const Ice::Current& c, Ice::LocalObjectPtr& cookie) bool newEntry = i == _map.end(); if(!newEntry) { - // - // Got an entry already, dequeue the entry from its current position. - // - ec->entry = i->second; - _queue.erase(ec->entry->pos); + // + // Got an entry already, dequeue the entry from its current position. + // + ec->entry = i->second; + _queue.erase(ec->entry->pos); } else { - // - // We do not have an entry. Ask the derived class to - // instantiate a servant and add a new entry to the map. - // - ec->entry = new EvictorEntry; - ec->entry->servant = add(c, ec->entry->userCookie); // Down-call - if(!ec->entry->servant) - { - return 0; - } - ec->entry->useCount = 0; - i = _map.insert(std::make_pair(c.id, ec->entry)).first; + // + // We do not have an entry. Ask the derived class to + // instantiate a servant and add a new entry to the map. + // + ec->entry = new EvictorEntry; + ec->entry->servant = add(c, ec->entry->userCookie); // Down-call + if(!ec->entry->servant) + { + return 0; + } + ec->entry->useCount = 0; + i = _map.insert(std::make_pair(c.id, ec->entry)).first; } // @@ -93,13 +93,13 @@ EvictorBase::evictServants() // for(int i = static_cast(_map.size() - _size); i > 0; --i) { - EvictorQueue::reverse_iterator p = _queue.rbegin(); - if((*p)->second->useCount == 0) - { - evict((*p)->second->servant, (*p)->second->userCookie); // Down-call - EvictorMap::iterator pos = *p; - _queue.erase((*p)->second->pos); - _map.erase(pos); - } + EvictorQueue::reverse_iterator p = _queue.rbegin(); + if((*p)->second->useCount == 0) + { + evict((*p)->second->servant, (*p)->second->userCookie); // Down-call + EvictorMap::iterator pos = *p; + _queue.erase((*p)->second->pos); + _map.erase(pos); + } } } diff --git a/cpp/demo/book/evictor/EvictorBase.h b/cpp/demo/book/evictor/EvictorBase.h index 3677bffe4b6..030f3318394 100644 --- a/cpp/demo/book/evictor/EvictorBase.h +++ b/cpp/demo/book/evictor/EvictorBase.h @@ -30,15 +30,15 @@ private: struct EvictorEntry : public Ice::LocalObject { - Ice::ObjectPtr servant; - Ice::LocalObjectPtr userCookie; - EvictorQueue::iterator pos; - int useCount; + Ice::ObjectPtr servant; + Ice::LocalObjectPtr userCookie; + EvictorQueue::iterator pos; + int useCount; }; struct EvictorCookie : public Ice::LocalObject { - EvictorEntryPtr entry; + EvictorEntryPtr entry; }; typedef IceUtil::Handle EvictorCookiePtr; diff --git a/cpp/demo/book/printer/Client.cpp b/cpp/demo/book/printer/Client.cpp index 71f6bb711b2..4928da9a903 100755 --- a/cpp/demo/book/printer/Client.cpp +++ b/cpp/demo/book/printer/Client.cpp @@ -19,28 +19,28 @@ main(int argc, char * argv[]) int status = 0; Ice::CommunicatorPtr ic; try { - ic = Ice::initialize(argc, argv); - Ice::ObjectPrx base = ic->stringToProxy( - "SimplePrinter:default -p 10000"); - PrinterPrx printer = PrinterPrx::checkedCast(base); - if (!printer) - throw "Invalid proxy"; + ic = Ice::initialize(argc, argv); + Ice::ObjectPrx base = ic->stringToProxy( + "SimplePrinter:default -p 10000"); + PrinterPrx printer = PrinterPrx::checkedCast(base); + if (!printer) + throw "Invalid proxy"; - printer->printString("Hello World!"); + printer->printString("Hello World!"); } catch (const Ice::Exception & ex) { - cerr << ex << endl; - status = 1; + cerr << ex << endl; + status = 1; } catch (const char * msg) { - cerr << msg << endl; - status = 1; + cerr << msg << endl; + status = 1; } if (ic) { - try { - ic->destroy(); - } catch (const Ice::Exception & ex) { - cerr << ex << endl; - status = 1; - } + try { + ic->destroy(); + } catch (const Ice::Exception & ex) { + cerr << ex << endl; + status = 1; + } } return status; } diff --git a/cpp/demo/book/printer/Printer.ice b/cpp/demo/book/printer/Printer.ice index 20e46cdf549..01a4d213aa0 100755 --- a/cpp/demo/book/printer/Printer.ice +++ b/cpp/demo/book/printer/Printer.ice @@ -15,7 +15,7 @@ module Demo interface Printer { - void printString(string s); + void printString(string s); }; }; diff --git a/cpp/demo/book/printer/Server.cpp b/cpp/demo/book/printer/Server.cpp index 2c9d22d4beb..1e619d76b16 100755 --- a/cpp/demo/book/printer/Server.cpp +++ b/cpp/demo/book/printer/Server.cpp @@ -16,7 +16,7 @@ using namespace Demo; class PrinterI : public Printer { public: virtual void printString(const string & s, - const Ice::Current &); + const Ice::Current &); }; void @@ -32,29 +32,29 @@ main(int argc, char* argv[]) int status = 0; Ice::CommunicatorPtr ic; try { - ic = Ice::initialize(argc, argv); - Ice::ObjectAdapterPtr adapter - = ic->createObjectAdapterWithEndpoints( - "SimplePrinterAdapter", "default -p 10000"); - Ice::ObjectPtr object = new PrinterI; - adapter->add(object, - ic->stringToIdentity("SimplePrinter")); - adapter->activate(); - ic->waitForShutdown(); + ic = Ice::initialize(argc, argv); + Ice::ObjectAdapterPtr adapter + = ic->createObjectAdapterWithEndpoints( + "SimplePrinterAdapter", "default -p 10000"); + Ice::ObjectPtr object = new PrinterI; + adapter->add(object, + ic->stringToIdentity("SimplePrinter")); + adapter->activate(); + ic->waitForShutdown(); } catch (const Ice::Exception & e) { - cerr << e << endl; - status = 1; + cerr << e << endl; + status = 1; } catch (const char * msg) { - cerr << msg << endl; - status = 1; + cerr << msg << endl; + status = 1; } if (ic) { try { - ic->destroy(); - } catch (const Ice::Exception & e) { - cerr << e << endl; - status = 1; - } + ic->destroy(); + } catch (const Ice::Exception & e) { + cerr << e << endl; + status = 1; + } } return status; } diff --git a/cpp/demo/book/simple_filesystem/Client.cpp b/cpp/demo/book/simple_filesystem/Client.cpp index 870b879e0d9..00cbc8a425e 100755 --- a/cpp/demo/book/simple_filesystem/Client.cpp +++ b/cpp/demo/book/simple_filesystem/Client.cpp @@ -27,16 +27,16 @@ listRecursive(const DirectoryPrx & dir, int depth = 0) NodeSeq contents = dir->list(); for (NodeSeq::const_iterator i = contents.begin(); i != contents.end(); ++i) { - DirectoryPrx dir = DirectoryPrx::checkedCast(*i); - FilePrx file = FilePrx::uncheckedCast(*i); - cout << indent << (*i)->name() << (dir ? " (directory):" : " (file):") << endl; - if (dir) { - listRecursive(dir, depth); - } else { - Lines text = file->read(); - for (Lines::const_iterator j = text.begin(); j != text.end(); ++j) - cout << indent << "\t" << *j << endl; - } + DirectoryPrx dir = DirectoryPrx::checkedCast(*i); + FilePrx file = FilePrx::uncheckedCast(*i); + cout << indent << (*i)->name() << (dir ? " (directory):" : " (file):") << endl; + if (dir) { + listRecursive(dir, depth); + } else { + Lines text = file->read(); + for (Lines::const_iterator j = text.begin(); j != text.end(); ++j) + cout << indent << "\t" << *j << endl; + } } } @@ -46,38 +46,38 @@ main(int argc, char * argv[]) int status = 0; Ice::CommunicatorPtr ic; try { - // Create a communicator - // - ic = Ice::initialize(argc, argv); + // Create a communicator + // + ic = Ice::initialize(argc, argv); - // Create a proxy for the root directory - // - Ice::ObjectPrx base = ic->stringToProxy("RootDir:default -p 10000"); - if (!base) - throw "Could not create proxy"; + // Create a proxy for the root directory + // + Ice::ObjectPrx base = ic->stringToProxy("RootDir:default -p 10000"); + if (!base) + throw "Could not create proxy"; - // Down-cast the proxy to a Directory proxy - // - DirectoryPrx rootDir = DirectoryPrx::checkedCast(base); - if (!rootDir) - throw "Invalid proxy"; + // Down-cast the proxy to a Directory proxy + // + DirectoryPrx rootDir = DirectoryPrx::checkedCast(base); + if (!rootDir) + throw "Invalid proxy"; - // Recursively list the contents of the root directory - // - cout << "Contents of root directory:" << endl; - listRecursive(rootDir); + // Recursively list the contents of the root directory + // + cout << "Contents of root directory:" << endl; + listRecursive(rootDir); } catch (const Ice::Exception & ex) { - cerr << ex << endl; - status = 1; + cerr << ex << endl; + status = 1; } catch (const char * msg) { - cerr << msg << endl; - status = 1; + cerr << msg << endl; + status = 1; } // Clean up // if (ic) - ic->destroy(); + ic->destroy(); return status; } diff --git a/cpp/demo/book/simple_filesystem/Filesystem.ice b/cpp/demo/book/simple_filesystem/Filesystem.ice index 8592c68381e..de701e15cee 100755 --- a/cpp/demo/book/simple_filesystem/Filesystem.ice +++ b/cpp/demo/book/simple_filesystem/Filesystem.ice @@ -9,23 +9,23 @@ module Filesystem { exception GenericError { - string reason; + string reason; }; interface Node { - ["cpp:const"] idempotent string name(); + ["cpp:const"] idempotent string name(); }; sequence Lines; interface File extends Node { - ["cpp:const"] idempotent Lines read(); - idempotent void write(Lines text) throws GenericError; + ["cpp:const"] idempotent Lines read(); + idempotent void write(Lines text) throws GenericError; }; sequence NodeSeq; interface Directory extends Node { - ["cpp:const"] idempotent NodeSeq list(); + ["cpp:const"] idempotent NodeSeq list(); }; }; diff --git a/cpp/demo/book/simple_filesystem/FilesystemI.cpp b/cpp/demo/book/simple_filesystem/FilesystemI.cpp index 8560075d36c..7367e89e3e8 100755 --- a/cpp/demo/book/simple_filesystem/FilesystemI.cpp +++ b/cpp/demo/book/simple_filesystem/FilesystemI.cpp @@ -12,7 +12,7 @@ using namespace std; -Ice::ObjectAdapterPtr Filesystem::NodeI::_adapter; // static member +Ice::ObjectAdapterPtr Filesystem::NodeI::_adapter; // static member // Slice Node::name() operation @@ -39,15 +39,15 @@ Filesystem::NodeI::NodeI(const Ice::CommunicatorPtr & ic, const string & name, c // Ice::Identity myID; if (parent) - myID = ic->stringToIdentity(IceUtil::generateUUID()); + myID = ic->stringToIdentity(IceUtil::generateUUID()); else - myID = ic->stringToIdentity("RootDir"); + myID = ic->stringToIdentity("RootDir"); // Create a proxy for the new node and add it as a child to the parent // NodePrx thisNode = NodePrx::uncheckedCast(_adapter->createProxy(myID)); if (parent) - parent->addChild(thisNode); + parent->addChild(thisNode); // Activate the servant // @@ -66,7 +66,7 @@ Filesystem::FileI::read(const Ice::Current &) const void Filesystem::FileI::write(const Filesystem::Lines & text, - const Ice::Current &) + const Ice::Current &) { _lines = text; } diff --git a/cpp/demo/book/simple_filesystem/FilesystemI.h b/cpp/demo/book/simple_filesystem/FilesystemI.h index fde910b3ac0..c627ce35116 100755 --- a/cpp/demo/book/simple_filesystem/FilesystemI.h +++ b/cpp/demo/book/simple_filesystem/FilesystemI.h @@ -19,33 +19,33 @@ namespace Filesystem { class NodeI : virtual public Node { public: - virtual std::string name(const Ice::Current &) const; - NodeI(const Ice::CommunicatorPtr &, const std::string &, const DirectoryIPtr & parent); - static Ice::ObjectAdapterPtr _adapter; + virtual std::string name(const Ice::Current &) const; + NodeI(const Ice::CommunicatorPtr &, const std::string &, const DirectoryIPtr & parent); + static Ice::ObjectAdapterPtr _adapter; private: - const std::string _name; - DirectoryIPtr _parent; + const std::string _name; + DirectoryIPtr _parent; }; class FileI : virtual public File, - virtual public NodeI { + virtual public NodeI { public: - virtual Lines read(const Ice::Current &) const; - virtual void write(const Lines &, - const Ice::Current &); - FileI(const Ice::CommunicatorPtr &, const std::string &, const DirectoryIPtr &); + virtual Lines read(const Ice::Current &) const; + virtual void write(const Lines &, + const Ice::Current &); + FileI(const Ice::CommunicatorPtr &, const std::string &, const DirectoryIPtr &); private: - Lines _lines; + Lines _lines; }; class DirectoryI : virtual public Directory, - virtual public NodeI { + virtual public NodeI { public: - virtual NodeSeq list(const Ice::Current &) const; + virtual NodeSeq list(const Ice::Current &) const; DirectoryI(const Ice::CommunicatorPtr &, const std::string &, const DirectoryIPtr &); - void addChild(NodePrx child); + void addChild(NodePrx child); private: - NodeSeq _contents; + NodeSeq _contents; }; } diff --git a/cpp/demo/book/simple_filesystem/Server.cpp b/cpp/demo/book/simple_filesystem/Server.cpp index 84cd4fadbdd..59aa1f61e83 100755 --- a/cpp/demo/book/simple_filesystem/Server.cpp +++ b/cpp/demo/book/simple_filesystem/Server.cpp @@ -17,57 +17,57 @@ class FilesystemApp : virtual public Ice::Application { public: virtual int run(int, char * []) { // Terminate cleanly on receipt of a signal - // - shutdownOnInterrupt(); + // + shutdownOnInterrupt(); - // Create an object adapter (stored in the NodeI::_adapter - // static member) - // - NodeI::_adapter = - communicator()->createObjectAdapterWithEndpoints( - "SimpleFilesystem", "default -p 10000"); + // Create an object adapter (stored in the NodeI::_adapter + // static member) + // + NodeI::_adapter = + communicator()->createObjectAdapterWithEndpoints( + "SimpleFilesystem", "default -p 10000"); - // Create the root directory (with name "/" and no parent) - // - DirectoryIPtr root = new DirectoryI(communicator(), "/", 0); + // Create the root directory (with name "/" and no parent) + // + DirectoryIPtr root = new DirectoryI(communicator(), "/", 0); - // Create a file called "README" in the root directory - // - FilePtr file = new FileI(communicator(), "README", root); - Lines text; - text.push_back("This file system contains a collection of poetry."); - file->write(text); + // Create a file called "README" in the root directory + // + FilePtr file = new FileI(communicator(), "README", root); + Lines text; + text.push_back("This file system contains a collection of poetry."); + file->write(text); - // Create a directory called "Coleridge" in the root directory - // - DirectoryIPtr coleridge = new DirectoryI(communicator(), "Coleridge", root); + // Create a directory called "Coleridge" in the root directory + // + DirectoryIPtr coleridge = new DirectoryI(communicator(), "Coleridge", root); - // Create a file called "Kubla_Khan" in the Coleridge directory - // - file = new FileI(communicator(), "Kubla_Khan", coleridge); - text.erase(text.begin(), text.end()); - text.push_back("In Xanadu did Kubla Khan"); - text.push_back("A stately pleasure-dome decree:"); - text.push_back("Where Alph, the sacred river, ran"); - text.push_back("Through caverns measureless to man"); - text.push_back("Down to a sunless sea."); - file->write(text); + // Create a file called "Kubla_Khan" in the Coleridge directory + // + file = new FileI(communicator(), "Kubla_Khan", coleridge); + text.erase(text.begin(), text.end()); + text.push_back("In Xanadu did Kubla Khan"); + text.push_back("A stately pleasure-dome decree:"); + text.push_back("Where Alph, the sacred river, ran"); + text.push_back("Through caverns measureless to man"); + text.push_back("Down to a sunless sea."); + file->write(text); - // All objects are created, allow client requests now - // - NodeI::_adapter->activate(); + // All objects are created, allow client requests now + // + NodeI::_adapter->activate(); - // Wait until we are done - // - communicator()->waitForShutdown(); + // Wait until we are done + // + communicator()->waitForShutdown(); if (interrupted()) { cerr << appName() - << ": received signal, shutting down" << endl; - } + << ": received signal, shutting down" << endl; + } - NodeI::_adapter = 0; + NodeI::_adapter = 0; - return 0; + return 0; }; }; diff --git a/cpp/fixCopyright.py b/cpp/fixCopyright.py index 5edbbdf7c0a..4feb798c8a4 100755 --- a/cpp/fixCopyright.py +++ b/cpp/fixCopyright.py @@ -123,7 +123,7 @@ def replaceCopyright(file, commentMark, commentBegin, commentEnd, newCopyrightLi # Hack to keep the .err files # if fnmatch.fnmatch(file, "*test/Slice/errorDetection/*.ice") > 0: - newFile.write("\n") + newFile.write("\n") newFile.writelines(newLines) newFile.close() @@ -215,7 +215,7 @@ for x in sys.argv[1:]: sys.exit(0) elif x == "-e": patchIceE = True - path = "../icee" + path = "../icee" elif x.startswith("-"): print sys.argv[0] + ": unknown option `" + x + "'" print diff --git a/cpp/fixVersion.py b/cpp/fixVersion.py index 4c7db0352f1..3e5577ad118 100755 --- a/cpp/fixVersion.py +++ b/cpp/fixVersion.py @@ -164,13 +164,13 @@ def fileMatchAllAndReplace(filename, matchAndReplaceExps): # updated = False for line in oldFile.readlines(): - for (regexp, replace) in regexps: - match = regexp.search(line) - if match != None: - oldLine = line - line = oldLine.replace(match.group(1), replace) - updated = True - newFile.write(line) + for (regexp, replace) in regexps: + match = regexp.search(line) + if match != None: + oldLine = line + line = oldLine.replace(match.group(1), replace) + updated = True + newFile.write(line) newFile.close() oldFile.close() @@ -196,7 +196,7 @@ except getopt.GetoptError: for o, a in opts: if o in ("-h", "--help"): usage() - sys.exit(0) + sys.exit(0) if o in ("-e"): patchIceE = True if len(args) != 1: @@ -217,87 +217,87 @@ if not patchIceE: # ice_home = findSourceTree("ice", os.path.join("include", "IceUtil", "Config.h")) if ice_home: - fileMatchAndReplace(os.path.join(ice_home, "include", "IceUtil", "Config.h"), - [("ICE_STRING_VERSION \"" + vpatMatch + "\"", version), \ + fileMatchAndReplace(os.path.join(ice_home, "include", "IceUtil", "Config.h"), + [("ICE_STRING_VERSION \"" + vpatMatch + "\"", version), \ ("ICE_INT_VERSION ([0-9]*)", intVersion(version))]) - fileMatchAndReplace(os.path.join(ice_home, "config", "Make.rules"), - [("VERSION_MAJOR[\t\s]*= ([0-9]*)", majorVersion(version)), + fileMatchAndReplace(os.path.join(ice_home, "config", "Make.rules"), + [("VERSION_MAJOR[\t\s]*= ([0-9]*)", majorVersion(version)), ("VERSION_MINOR[\t\s]*= ([0-9]*)", minorVersion(version)), ("VERSION[\t\s]*= " + vpatMatch, version), ("SOVERSION[\t\s]*= ([0-9]+b?)", soVersion(version))]) - fileMatchAndReplace(os.path.join(ice_home, "config", "Make.rules.mak"), - [("VERSION[\t\s]*= " + vpatMatch, version), - ("SOVERSION[\t\s]*= ([0-9]+b?)", soVersion(version))]) + fileMatchAndReplace(os.path.join(ice_home, "config", "Make.rules.mak"), + [("VERSION[\t\s]*= " + vpatMatch, version), + ("SOVERSION[\t\s]*= ([0-9]+b?)", soVersion(version))]) - fileMatchAndReplace(os.path.join(ice_home, "src", "ca", "iceca"), - [("Ice-" + vpatMatch, version)]) + fileMatchAndReplace(os.path.join(ice_home, "src", "ca", "iceca"), + [("Ice-" + vpatMatch, version)]) - fileMatchAndReplace(os.path.join(ice_home, "demo", "IceStorm", "clock", "config.icebox"), - [("IceStormService,([0-9]+b?)", soVersion(version))]) + fileMatchAndReplace(os.path.join(ice_home, "demo", "IceStorm", "clock", "config.icebox"), + [("IceStormService,([0-9]+b?)", soVersion(version))]) - fileMatchAndReplace(os.path.join(ice_home, "demo", "IceStorm", "counter", "config.icebox"), - [("IceStormService,([0-9]+b?)", soVersion(version))]) + fileMatchAndReplace(os.path.join(ice_home, "demo", "IceStorm", "counter", "config.icebox"), + [("IceStormService,([0-9]+b?)", soVersion(version))]) fileMatchAndReplace(os.path.join(ice_home, "config", "templates.xml"), - [("IceStormService,([0-9]+b?)", soVersion(version))]) + [("IceStormService,([0-9]+b?)", soVersion(version))]) # # Fix version in IceJ sources # icej_home = findSourceTree("icej", os.path.join("src", "IceUtil", "Version.java")) if icej_home: - fileMatchAndReplace(os.path.join(icej_home, "src", "IceUtil", "Version.java"), - [("ICE_STRING_VERSION = \"" + vpatMatch +"\"", version), \ - ("ICE_INT_VERSION = ([0-9]*)", intVersion(version))]) + fileMatchAndReplace(os.path.join(icej_home, "src", "IceUtil", "Version.java"), + [("ICE_STRING_VERSION = \"" + vpatMatch +"\"", version), \ + ("ICE_INT_VERSION = ([0-9]*)", intVersion(version))]) - fileMatchAndReplace(os.path.join(icej_home, "demo", "IceStorm", "clock", "config.icebox"), - [("IceStormService,([0-9]+b?)", soVersion(version))]) + fileMatchAndReplace(os.path.join(icej_home, "demo", "IceStorm", "clock", "config.icebox"), + [("IceStormService,([0-9]+b?)", soVersion(version))]) # # Fix version in IceCS sources # icecs_home = findSourceTree("icecs", os.path.join("src", "Ice", "AssemblyInfo.cs")) if icecs_home: - for f in find(icecs_home, "AssemblyInfo.cs"): - if f.find("generate") < 0 and f.find("ConsoleApplication") < 0: - fileMatchAndReplace(f, [("AssemblyVersion\(\"" + vpatMatch + "\"", + for f in find(icecs_home, "AssemblyInfo.cs"): + if f.find("generate") < 0 and f.find("ConsoleApplication") < 0: + fileMatchAndReplace(f, [("AssemblyVersion\(\"" + vpatMatch + "\"", majorVersion(version) + "." + minorVersion(version) + "." + patchVersion(version))]) - fileMatchAndReplace(os.path.join(icecs_home, "config", "Make.rules.cs"), - [("VERSION[\t\s]*= " + vpatMatch, version)]) + fileMatchAndReplace(os.path.join(icecs_home, "config", "Make.rules.cs"), + [("VERSION[\t\s]*= " + vpatMatch, version)]) - fileMatchAndReplace(os.path.join(icecs_home, "config", "Make.rules.mak"), - [("VERSION[\t\s]*= " + vpatMatch, version)]) + fileMatchAndReplace(os.path.join(icecs_home, "config", "Make.rules.mak"), + [("VERSION[\t\s]*= " + vpatMatch, version)]) - fileMatchAndReplace(os.path.join(icecs_home, "config", "makeconfig.py"), - [("version=*\"([0-9]*\.[0-9]*\.[0-9]*).0\"", + fileMatchAndReplace(os.path.join(icecs_home, "config", "makeconfig.py"), + [("version=*\"([0-9]*\.[0-9]*\.[0-9]*).0\"", majorVersion(version) + "." + minorVersion(version) + "." + patchVersion(version))]) - cmd = "chmod 770 " + os.path.join(icecs_home, "config", "makeconfig.py") - os.system(cmd) + cmd = "chmod 770 " + os.path.join(icecs_home, "config", "makeconfig.py") + os.system(cmd) - fileMatchAndReplace(os.path.join(icecs_home, "demo", "IceStorm", "clock", "config.icebox"), - [("IceStormService,([0-9]+b?)", soVersion(version))]) + fileMatchAndReplace(os.path.join(icecs_home, "demo", "IceStorm", "clock", "config.icebox"), + [("IceStormService,([0-9]+b?)", soVersion(version))]) - for f in find(icecs_home, "*.pc"): - fileMatchAndReplace(f, [("[\t\s]*version[\t\s]*=[\t\s]*" + vpatMatch, version)]) + for f in find(icecs_home, "*.pc"): + fileMatchAndReplace(f, [("[\t\s]*version[\t\s]*=[\t\s]*" + vpatMatch, version)]) # # Fix version in IceVB sources # icevb_home = findSourceTree("icevb", os.path.join("generate", "Generate.vb")) if icevb_home: - fileMatchAndReplace(os.path.join(icevb_home, "config", "Make.rules.mak"), - [("VERSION[\t\s]*= " + vpatMatch, version)]) + fileMatchAndReplace(os.path.join(icevb_home, "config", "Make.rules.mak"), + [("VERSION[\t\s]*= " + vpatMatch, version)]) - fileMatchAndReplace(os.path.join(icevb_home, "config", "makeconfig.py"), - [("codeBase version=\"" + vpatMatch + "\.0\"", - majorVersion(version) + "." + minorVersion(version) + "." + patchVersion(version))]) + fileMatchAndReplace(os.path.join(icevb_home, "config", "makeconfig.py"), + [("codeBase version=\"" + vpatMatch + "\.0\"", + majorVersion(version) + "." + minorVersion(version) + "." + patchVersion(version))]) - fileMatchAndReplace(os.path.join(icevb_home, "demo", "IceStorm", "clock", "config.icebox"), - [("IceStormService,([0-9]+b?)", soVersion(version))]) + fileMatchAndReplace(os.path.join(icevb_home, "demo", "IceStorm", "clock", "config.icebox"), + [("IceStormService,([0-9]+b?)", soVersion(version))]) # # Fix version in IcePHP @@ -310,39 +310,39 @@ if not patchIceE: ("VERSION[\t\s]*= " + vpatMatch, version), ("SOVERSION[\t\s]*= ([0-9]+b?)", soVersion(version))]) - fileMatchAndReplace(os.path.join(icephp_home, "config", "Make.rules.mak"), - [("VERSION[\t\s]*= " + vpatMatch, version), - ("SOVERSION[\t\s]*= ([0-9]+b?)", soVersion(version))]) + fileMatchAndReplace(os.path.join(icephp_home, "config", "Make.rules.mak"), + [("VERSION[\t\s]*= " + vpatMatch, version), + ("SOVERSION[\t\s]*= ([0-9]+b?)", soVersion(version))]) print "Please update icephp/src/IcePHP/Profile.cpp: too difficult to parse!" - + # # Fix version in IcePy # icepy_home = findSourceTree("icepy", os.path.join("modules", "IcePy", "Config.h")) if icepy_home: fileMatchAndReplace(os.path.join(icepy_home, "config", "Make.rules"), - [("VERSION_MAJOR[\t\s]*= ([0-9]*)", majorVersion(version)), + [("VERSION_MAJOR[\t\s]*= ([0-9]*)", majorVersion(version)), ("VERSION_MINOR[\t\s]*= ([0-9]*)", minorVersion(version)), ("VERSION[\t\s]*= " + vpatMatch, version), ("SOVERSION[\t\s]*= ([0-9]+b?)", soVersion(version))]) fileMatchAndReplace(os.path.join(icepy_home, "config", "Make.rules.mak"), - [("VERSION[\t\s]*= " + vpatMatch, version), - ("SOVERSION[\t\s]*= ([0-9]+b?)", soVersion(version))]) + [("VERSION[\t\s]*= " + vpatMatch, version), + ("SOVERSION[\t\s]*= ([0-9]+b?)", soVersion(version))]) # # Fix version in IceRuby # icerb_home = findSourceTree("icerb", os.path.join("src", "IceRuby", "Config.h")) if icerb_home: - fileMatchAndReplace(os.path.join(icerb_home, "config", "Make.rules"), - [("VERSION[\t\s]*= " + vpatMatch, version), - ("SOVERSION[\t\s]*= ([0-9]+b?)", soVersion(version))]) + fileMatchAndReplace(os.path.join(icerb_home, "config", "Make.rules"), + [("VERSION[\t\s]*= " + vpatMatch, version), + ("SOVERSION[\t\s]*= ([0-9]+b?)", soVersion(version))]) fileMatchAndReplace(os.path.join(icerb_home, "config", "Make.rules.mak"), - [("VERSION[\t\s]*= " + vpatMatch, version), - ("SOVERSION[\t\s]*= ([0-9]+b?)", soVersion(version))]) + [("VERSION[\t\s]*= " + vpatMatch, version), + ("SOVERSION[\t\s]*= ([0-9]+b?)", soVersion(version))]) print "Running 'make config' in IceCS" os.chdir(icecs_home) diff --git a/cpp/iceemakedist.py b/cpp/iceemakedist.py index 86ee099c13b..ae528b029da 100755 --- a/cpp/iceemakedist.py +++ b/cpp/iceemakedist.py @@ -226,24 +226,24 @@ if verbose: else: quiet = "-Q" os.system("cvs " + quiet + " -d cvs.zeroc.com:/home/cvsroot export -l " + tag + " " + - "ice " + - "ice/bin " + - "ice/config " + - "ice/include " + - "ice/include/IceUtil " + - "ice/include/Slice " + - "ice/install " + - "ice/install/icee " + - "ice/lib " + - "ice/src " + - "ice/src/icecpp " + - "ice/src/IceUtil " + - "ice/src/Slice " + - "ice/src/Slice/dummyinclude " + - "ice/src/slice2cppe " + - "ice/src/slice2javae " + - "icee/include/IceE/Config.h " - ) + "ice " + + "ice/bin " + + "ice/config " + + "ice/include " + + "ice/include/IceUtil " + + "ice/include/Slice " + + "ice/install " + + "ice/install/icee " + + "ice/lib " + + "ice/src " + + "ice/src/icecpp " + + "ice/src/IceUtil " + + "ice/src/Slice " + + "ice/src/Slice/dummyinclude " + + "ice/src/slice2cppe " + + "ice/src/slice2javae " + + "icee/include/IceE/Config.h " + ) # # Copy Ice-E specific install files. @@ -372,11 +372,11 @@ lines = makeRules.readlines() makeRules.close() for i in range(len(lines)): if lines[i].find("#STATICLIBS") == 0: - lines[i] = lines[i].replace("#STATICLIBS", "STATICLIBS") + lines[i] = lines[i].replace("#STATICLIBS", "STATICLIBS") if lines[i].find("#OPTIMIZE") == 0: - lines[i] = lines[i].replace("#OPTIMIZE", "OPTIMIZE") + lines[i] = lines[i].replace("#OPTIMIZE", "OPTIMIZE") if lines[i].find("prefix") == 0: - lines[i] = lines[i].replace("Ice-$(VERSION)", "IceE-" + version) + lines[i] = lines[i].replace("Ice-$(VERSION)", "IceE-" + version) makeRules = open(makeRulesName, "w") makeRules.writelines(lines) makeRules.close() @@ -390,9 +390,9 @@ lines = makeFile.readlines() makeFile.close() for i in range(len(lines)): if lines[i].find("SUBDIRS") == 0: - lines[i] = "SUBDIRS = src\n" + lines[i] = "SUBDIRS = src\n" if lines[i].find("INSTALL_SUBDIRS") == 0: - lines[i] = "INSTALL_SUBDIRS = $(install_bindir) $(install_libdir)\n" + lines[i] = "INSTALL_SUBDIRS = $(install_bindir) $(install_libdir)\n" makeFile = open(makeFileName, "w") makeFile.writelines(lines) makeFile.close() @@ -401,14 +401,14 @@ makeFile.close() # Disable install targets for libIceUtil, libSlice. # for makeFileName in [os.path.join("ice", "src", "IceUtil", "Makefile"), \ - os.path.join("ice", "src", "Slice", "Makefile")]: + os.path.join("ice", "src", "Slice", "Makefile")]: makeFile = open(makeFileName, "r") lines = makeFile.readlines() makeFile.close() for i in range(len(lines)): - if lines[i].find("install::") == 0: - lines[i + 1] = "#" + lines[i + 1] - break + if lines[i].find("install::") == 0: + lines[i + 1] = "#" + lines[i + 1] + break makeFile = open(makeFileName, "w") makeFile.writelines(lines) makeFile.close() diff --git a/cpp/include/Freeze/Initialize.h b/cpp/include/Freeze/Initialize.h index de656d2be30..87684264415 100644 --- a/cpp/include/Freeze/Initialize.h +++ b/cpp/include/Freeze/Initialize.h @@ -26,27 +26,27 @@ namespace Freeze { FREEZE_API EvictorPtr createEvictor(const Ice::ObjectAdapterPtr& adapter, - const std::string& envName, - const std::string& filename, - const ServantInitializerPtr& initializer = 0, - const std::vector& indices = std::vector(), - bool createDb = true); + const std::string& envName, + const std::string& filename, + const ServantInitializerPtr& initializer = 0, + const std::vector& indices = std::vector(), + bool createDb = true); FREEZE_API EvictorPtr createEvictor(const Ice::ObjectAdapterPtr& adapter, - const std::string& envName, - DbEnv& dbEnv, - const std::string& filename, - const ServantInitializerPtr& initializer = 0, - const std::vector& indices = std::vector(), - bool createDb = true); + const std::string& envName, + DbEnv& dbEnv, + const std::string& filename, + const ServantInitializerPtr& initializer = 0, + const std::vector& indices = std::vector(), + bool createDb = true); FREEZE_API ConnectionPtr createConnection(const Ice::CommunicatorPtr& communicator, - const std::string& envName); + const std::string& envName); FREEZE_API ConnectionPtr createConnection(const Ice::CommunicatorPtr& communicator, - const std::string& envName, - DbEnv& dbEnv); + const std::string& envName, + DbEnv& dbEnv); FREEZE_API const std::string& catalogName(); diff --git a/cpp/include/Freeze/Map.h b/cpp/include/Freeze/Map.h index 2f26699caec..1c7e61c2add 100644 --- a/cpp/include/Freeze/Map.h +++ b/cpp/include/Freeze/Map.h @@ -89,12 +89,12 @@ public: static MapHelper* create(const Freeze::ConnectionPtr& connection, - const std::string& dbName, - const std::string& key, - const std::string& value, - const KeyCompareBasePtr&, - const std::vector&, - bool createDb); + const std::string& dbName, + const std::string& key, + const std::string& value, + const KeyCompareBasePtr&, + const std::vector&, + bool createDb); virtual ~MapHelper() = 0; @@ -167,10 +167,10 @@ public: // Forward declaration // template + typename KeyCodec, typename ValueCodec, typename Compare> class Map; template + typename KeyCodec, typename ValueCodec, typename Compare> class ConstIterator; // @@ -193,7 +193,7 @@ struct IteratorBase // necessary. // template + typename KeyCodec, typename ValueCodec, typename Compare> class Iterator : public IteratorBase { public: @@ -207,16 +207,16 @@ public: typedef value_type& reference; Iterator(MapHelper& mapHelper, const Ice::CommunicatorPtr& communicator) : - _helper(IteratorHelper::create(mapHelper, false)), - _communicator(communicator), - _refValid(false) + _helper(IteratorHelper::create(mapHelper, false)), + _communicator(communicator), + _refValid(false) { } Iterator(IteratorHelper* helper, const Ice::CommunicatorPtr& communicator) : - _helper(helper), - _communicator(communicator), - _refValid(false) + _helper(helper), + _communicator(communicator), + _refValid(false) { } @@ -226,32 +226,32 @@ public: } Iterator(const Iterator& rhs) : - _communicator(rhs._communicator), + _communicator(rhs._communicator), _refValid(false) { - if(rhs._helper.get() != 0) - { - _helper.reset(rhs._helper->clone()); - } + if(rhs._helper.get() != 0) + { + _helper.reset(rhs._helper->clone()); + } } Iterator& operator=(const Iterator& rhs) { - if(this != &rhs) - { - if(rhs._helper.get() != 0) - { - _helper.reset(rhs._helper->clone()); - } - else - { - _helper.reset(); - } - _communicator = rhs._communicator; - _refValid = false; - } + if(this != &rhs) + { + if(rhs._helper.get() != 0) + { + _helper.reset(rhs._helper->clone()); + } + else + { + _helper.reset(); + } + _communicator = rhs._communicator; + _refValid = false; + } - return *this; + return *this; } ~Iterator() @@ -260,40 +260,40 @@ public: bool operator==(const Iterator& rhs) const { - if(_helper.get() == rhs._helper.get()) - { - return true; - } - - if(_helper.get() != 0 && rhs._helper.get() != 0) - { - const Key* lhsKey = _helper->get(); - const Key* rhsKey = rhs._helper->get(); - - if(lhsKey != 0 && rhsKey != 0) - { - return *lhsKey == *rhsKey; - } - } - return false; + if(_helper.get() == rhs._helper.get()) + { + return true; + } + + if(_helper.get() != 0 && rhs._helper.get() != 0) + { + const Key* lhsKey = _helper->get(); + const Key* rhsKey = rhs._helper->get(); + + if(lhsKey != 0 && rhsKey != 0) + { + return *lhsKey == *rhsKey; + } + } + return false; } bool operator!=(const Iterator& rhs) const { - return !(*this == rhs); + return !(*this == rhs); } Iterator& operator++() { - incr(); - return *this; + incr(); + return *this; } Iterator operator++(int) { - Iterator tmp = *this; - incr(); - return tmp; + Iterator tmp = *this; + incr(); + return tmp; } // @@ -321,7 +321,7 @@ public: _refValid = true; } - return _ref; + return _ref; } value_type* operator->() { return &(operator*()); } @@ -331,11 +331,11 @@ public: // void set(const mapped_type& value) { - assert(_helper.get()); + assert(_helper.get()); - Value v; - ValueCodec::write(value, v, _communicator); - _helper->set(v); + Value v; + ValueCodec::write(value, v, _communicator); + _helper->set(v); _refValid = false; } @@ -343,36 +343,36 @@ private: void incr() { - assert(_helper.get() != 0); - if(!_helper->next()) - { - // - // The iterator has been moved past the end, and is now - // invalid. - // - _helper.reset(); - } + assert(_helper.get() != 0); + if(!_helper->next()) + { + // + // The iterator has been moved past the end, and is now + // invalid. + // + _helper.reset(); + } _refValid = false; } void getCurrentValue(key_type& key, mapped_type& value) const { - assert(_helper.get() != 0); + assert(_helper.get() != 0); - const Key* k = 0; - const Value* v = 0; - _helper->get(k, v); - assert(k != 0); - assert(v != 0); + const Key* k = 0; + const Value* v = 0; + _helper->get(k, v); + assert(k != 0); + assert(v != 0); - KeyCodec::read(key, *k, _communicator); - ValueCodec::read(value, *v, _communicator); + KeyCodec::read(key, *k, _communicator); + ValueCodec::read(value, *v, _communicator); } friend class ConstIterator; + KeyCodec, ValueCodec, Compare>; friend class Map; + KeyCodec, ValueCodec, Compare>; std::auto_ptr _helper; Ice::CommunicatorPtr _communicator; @@ -395,7 +395,7 @@ private: // See Iterator comments for design notes // template + typename KeyCodec, typename ValueCodec, typename Compare> class ConstIterator : public IteratorBase { public: @@ -409,16 +409,16 @@ public: typedef value_type& reference; ConstIterator(MapHelper& mapHelper, const Ice::CommunicatorPtr& communicator) : - _helper(IteratorHelper::create(mapHelper, true)), - _communicator(_communicator), - _refValid(false) + _helper(IteratorHelper::create(mapHelper, true)), + _communicator(_communicator), + _refValid(false) { } ConstIterator(IteratorHelper* helper, const Ice::CommunicatorPtr& communicator) : - _helper(helper), - _communicator(communicator), - _refValid(false) + _helper(helper), + _communicator(communicator), + _refValid(false) { } @@ -428,13 +428,13 @@ public: } ConstIterator(const ConstIterator& rhs) : - _communicator(rhs._communicator), + _communicator(rhs._communicator), _refValid(false) { - if(rhs._helper.get() != 0) - { - _helper.reset(rhs._helper->clone()); - } + if(rhs._helper.get() != 0) + { + _helper.reset(rhs._helper->clone()); + } } // @@ -442,53 +442,53 @@ public: // vice versa) - same for operator=. // ConstIterator(const Iterator& rhs) : + KeyCodec, ValueCodec, Compare>& rhs) : _refValid(false) { - if(rhs._helper.get() != 0) - { - _helper.reset(rhs._helper->clone()); - } - _communicator = rhs._communicator; + if(rhs._helper.get() != 0) + { + _helper.reset(rhs._helper->clone()); + } + _communicator = rhs._communicator; } ConstIterator& operator=(const ConstIterator& rhs) { - if(this != &rhs) - { - if(rhs._helper.get() != 0) - { - _helper.reset(rhs._helper->clone()); - } - else - { - _helper.reset(); - } - _communicator = rhs._communicator; - _refValid = false; - } + if(this != &rhs) + { + if(rhs._helper.get() != 0) + { + _helper.reset(rhs._helper->clone()); + } + else + { + _helper.reset(); + } + _communicator = rhs._communicator; + _refValid = false; + } - return *this; + return *this; } // // Create const_iterator from iterator. // ConstIterator& operator=(const Iterator& rhs) - { - if(rhs._helper.get() != 0) - { - _helper.reset(rhs._helper->clone()); - } - else - { - _helper.reset(); - } - _communicator = rhs._communicator; + KeyCodec, ValueCodec, Compare>& rhs) + { + if(rhs._helper.get() != 0) + { + _helper.reset(rhs._helper->clone()); + } + else + { + _helper.reset(); + } + _communicator = rhs._communicator; _refValid = false; - return *this; + return *this; } ~ConstIterator() @@ -497,40 +497,40 @@ public: bool operator==(const ConstIterator& rhs) { - if(_helper.get() == rhs._helper.get()) - { - return true; - } - - if(_helper.get() != 0 && rhs._helper.get() != 0) - { - const Key* lhsKey = _helper->get(); - const Key* rhsKey = rhs._helper->get(); - - if(lhsKey != 0 && rhsKey != 0) - { - return *lhsKey == *rhsKey; - } - } - return false; + if(_helper.get() == rhs._helper.get()) + { + return true; + } + + if(_helper.get() != 0 && rhs._helper.get() != 0) + { + const Key* lhsKey = _helper->get(); + const Key* rhsKey = rhs._helper->get(); + + if(lhsKey != 0 && rhsKey != 0) + { + return *lhsKey == *rhsKey; + } + } + return false; } bool operator!=(const ConstIterator& rhs) { - return !(*this == rhs); + return !(*this == rhs); } ConstIterator& operator++() { - incr(); - return *this; + incr(); + return *this; } ConstIterator operator++(int) { - ConstIterator tmp = *this; - incr(); - return tmp; + ConstIterator tmp = *this; + incr(); + return tmp; } // @@ -558,7 +558,7 @@ public: _refValid = true; } - return _ref; + return _ref; } pointer operator->() const { return &(operator*()); } @@ -567,34 +567,34 @@ private: void incr() { - assert(_helper.get() != 0); - if(!_helper->next()) - { - // - // The iterator has been moved past the end, and is now - // invalid. - // - _helper.reset(); - } + assert(_helper.get() != 0); + if(!_helper->next()) + { + // + // The iterator has been moved past the end, and is now + // invalid. + // + _helper.reset(); + } _refValid = false; } void getCurrentValue(key_type& key, mapped_type& value) const { - assert(_helper.get() != 0); + assert(_helper.get() != 0); - const Key* k = 0; - const Value* v = 0; - _helper->get(k, v); - assert(k != 0); - assert(v != 0); + const Key* k = 0; + const Value* v = 0; + _helper->get(k, v); + assert(k != 0); + assert(v != 0); - KeyCodec::read(key, *k, _communicator); - ValueCodec::read(value, *v, _communicator); + KeyCodec::read(key, *k, _communicator); + ValueCodec::read(value, *v, _communicator); } friend class Map; + KeyCodec, ValueCodec, Compare>; std::auto_ptr _helper; Ice::CommunicatorPtr _communicator; @@ -622,7 +622,7 @@ struct IceEncodingCompare { bool operator()(...) { - return false; + return false; } }; @@ -648,35 +648,35 @@ class KeyCompare : public KeyCompareBase { public: KeyCompare(const Compare& compare, - const Ice::CommunicatorPtr& communicator) : + const Ice::CommunicatorPtr& communicator) : #if defined(_MSC_VER) && (_MSC_VER <= 1300) - KeyCompareBase(enableKeyCompare(compare)), + KeyCompareBase(enableKeyCompare(compare)), #else - KeyCompareBase(true), + KeyCompareBase(true), #endif - _compare(compare), - _communicator(communicator) + _compare(compare), + _communicator(communicator) {} virtual int compare(const Key& dbKey1, const Key& dbKey2) { - key_type key1; - KeyCodec::read(key1, dbKey1, _communicator); - key_type key2; - KeyCodec::read(key2, dbKey2, _communicator); - - if(_compare(key1, key2)) - { - return -1; - } - else if(_compare(key2, key1)) - { - return 1; - } - else - { - return 0; - } + key_type key1; + KeyCodec::read(key1, dbKey1, _communicator); + key_type key2; + KeyCodec::read(key2, dbKey2, _communicator); + + if(_compare(key1, key2)) + { + return -1; + } + else if(_compare(key2, key1)) + { + return 1; + } + else + { + return 0; + } } private: Compare _compare; @@ -693,13 +693,13 @@ class KeyCompare : public KeyCompareBase { public: KeyCompare(const IceEncodingCompare&, const Ice::CommunicatorPtr&): - KeyCompareBase(false) + KeyCompareBase(false) {} virtual int compare(const Key& dbKey1, const Key& dbKey2) { - assert(0); - return 0; + assert(0); + return 0; } }; #endif @@ -714,33 +714,33 @@ class MapIndex : public MapIndexBase public: virtual int compare(const Key& dbKey1, const Key& dbKey2) { - key_type key1; - KeyCodec::read(key1, dbKey1, _communicator); - key_type key2; - KeyCodec::read(key2, dbKey2, _communicator); - - if(_compare(key1, key2)) - { - return -1; - } - else if(_compare(key2, key1)) - { - return 1; - } - else - { - return 0; - } + key_type key1; + KeyCodec::read(key1, dbKey1, _communicator); + key_type key2; + KeyCodec::read(key2, dbKey2, _communicator); + + if(_compare(key1, key2)) + { + return -1; + } + else if(_compare(key2, key1)) + { + return 1; + } + else + { + return 0; + } } protected: MapIndex(const std::string& name, const Compare& compare) : #if defined(_MSC_VER) && (_MSC_VER <= 1300) - MapIndexBase(name, enableKeyCompare(compare)), + MapIndexBase(name, enableKeyCompare(compare)), #else - MapIndexBase(name, true), + MapIndexBase(name, true), #endif - _compare(compare) + _compare(compare) {} private: @@ -758,13 +758,13 @@ class MapIndex : public MapIndexBase public: virtual int compare(const Key& dbKey1, const Key& dbKey2) { - assert(0); - return 0; + assert(0); + return 0; } protected: MapIndex(const std::string& name, const IceEncodingCompare&): - MapIndexBase(name, false) + MapIndexBase(name, false) {} }; #endif @@ -777,8 +777,8 @@ protected: // TODO: implement bidirectional iterators. // template + typename KeyCodec, typename ValueCodec, + typename Compare = IceEncodingCompare> class Map { public: @@ -786,9 +786,9 @@ public: typedef std::pair value_type; typedef Iterator iterator; + KeyCodec, ValueCodec, Compare> iterator; typedef ConstIterator const_iterator; + KeyCodec, ValueCodec, Compare> const_iterator; // // No definition for reference, const_reference, pointer or @@ -807,41 +807,41 @@ public: // Constructors // Map(const Freeze::ConnectionPtr& connection, - const std::string& dbName, - bool createDb = true, - const Compare& compare = Compare()) : - _communicator(connection->getCommunicator()) - { - KeyCompareBasePtr keyCompare = - new KeyCompare(compare, _communicator); - std::vector indices; + const std::string& dbName, + bool createDb = true, + const Compare& compare = Compare()) : + _communicator(connection->getCommunicator()) + { + KeyCompareBasePtr keyCompare = + new KeyCompare(compare, _communicator); + std::vector indices; - _helper.reset(MapHelper::create(connection, dbName, - KeyCodec::typeId(), ValueCodec::typeId(), - keyCompare, indices, createDb)); + _helper.reset(MapHelper::create(connection, dbName, + KeyCodec::typeId(), ValueCodec::typeId(), + keyCompare, indices, createDb)); } template Map(const Freeze::ConnectionPtr& connection, - const std::string& dbName, - bool createDb, - _InputIterator first, _InputIterator last, - const Compare& compare = Compare()) : - _communicator(connection->getCommunicator()) + const std::string& dbName, + bool createDb, + _InputIterator first, _InputIterator last, + const Compare& compare = Compare()) : + _communicator(connection->getCommunicator()) { - KeyCompareBasePtr keyCompare = - new KeyCompare(compare, _communicator); + KeyCompareBasePtr keyCompare = + new KeyCompare(compare, _communicator); - std::vector indices; + std::vector indices; - _helper.reset(MapHelper::create(connection, dbName, - KeyCodec::typeId(), ValueCodec::typeId(), - keyCompare, indices, createDb)); - while(first != last) - { - put(*first); - ++first; - } + _helper.reset(MapHelper::create(connection, dbName, + KeyCodec::typeId(), ValueCodec::typeId(), + keyCompare, indices, createDb)); + while(first != last) + { + put(*first); + ++first; + } } ~Map() @@ -850,94 +850,94 @@ public: bool operator==(const Map& rhs) const { - // - // This does a memberwise equality for the entire contents of - // the database. While slow this is always correct. Database - // equality is not necessarily correct in the context of a - // transaction. - // - if(count() != rhs.count()) - { - return false; - } - - for(const_iterator p = rhs.begin() ; p != rhs.end() ; ++p) - { - const_iterator q = rhs.find(p->first); - if(q == rhs.end()) - { - return false; - } - if(p->second != q->second) - { - return false; - } - } - return true; + // + // This does a memberwise equality for the entire contents of + // the database. While slow this is always correct. Database + // equality is not necessarily correct in the context of a + // transaction. + // + if(count() != rhs.count()) + { + return false; + } + + for(const_iterator p = rhs.begin() ; p != rhs.end() ; ++p) + { + const_iterator q = rhs.find(p->first); + if(q == rhs.end()) + { + return false; + } + if(p->second != q->second) + { + return false; + } + } + return true; } bool operator!=(const Map& rhs) const { - return !(*this == rhs); + return !(*this == rhs); } void swap(Map& rhs) { - MapHelper* tmp = _helper.release(); - _helper.reset(rhs._helper.release()); - rhs._helper.reset(tmp); - - Ice::CommunicatorPtr tmpCom = _communicator; - _communicator = rhs._communicator; - rhs._communicator = tmpCom; + MapHelper* tmp = _helper.release(); + _helper.reset(rhs._helper.release()); + rhs._helper.reset(tmp); + + Ice::CommunicatorPtr tmpCom = _communicator; + _communicator = rhs._communicator; + rhs._communicator = tmpCom; } iterator begin() { - try - { - return iterator(IteratorHelper::create(*_helper.get(), false), _communicator); - } - catch(const NotFoundException&) - { - return iterator(); - } + try + { + return iterator(IteratorHelper::create(*_helper.get(), false), _communicator); + } + catch(const NotFoundException&) + { + return iterator(); + } } const_iterator begin() const { - try - { - return const_iterator(IteratorHelper::create(*_helper.get(), true), _communicator); - } - catch(const NotFoundException&) - { - return const_iterator(); - } + try + { + return const_iterator(IteratorHelper::create(*_helper.get(), true), _communicator); + } + catch(const NotFoundException&) + { + return const_iterator(); + } } iterator end() { - return iterator(); + return iterator(); } const_iterator end() const { - return const_iterator(); + return const_iterator(); } bool empty() const { - return size() == 0; + return size() == 0; } size_type size() const { - return _helper->size(); + return _helper->size(); } size_type max_size() const { - return 0xffffffff; // TODO: is this the max? + return 0xffffffff; // TODO: is this the max? } // @@ -962,106 +962,106 @@ public: iterator insert(iterator /*position*/, const value_type& key) { - // - // position is ignored. - // - Key k; - KeyCodec::write(key.first, k, _communicator); - - iterator r = iterator(_helper->find(k, false), _communicator); + // + // position is ignored. + // + Key k; + KeyCodec::write(key.first, k, _communicator); + + iterator r = iterator(_helper->find(k, false), _communicator); - if(r == end()) - { - Value v; - ValueCodec::write(key.second, v, _communicator); - - _helper->put(k, v); - r = iterator(_helper->find(k, false), _communicator); - } + if(r == end()) + { + Value v; + ValueCodec::write(key.second, v, _communicator); + + _helper->put(k, v); + r = iterator(_helper->find(k, false), _communicator); + } - return r; + return r; } std::pair insert(const value_type& key) { - Key k; - KeyCodec::write(key.first, k, _communicator); + Key k; + KeyCodec::write(key.first, k, _communicator); - iterator r = iterator(_helper->find(k, false), _communicator); - bool inserted = false; + iterator r = iterator(_helper->find(k, false), _communicator); + bool inserted = false; - if(r == end()) - { - Value v; - ValueCodec::write(key.second, v, _communicator); - - _helper->put(k, v); - inserted = true; - r = iterator(_helper->find(k, false), _communicator); - } + if(r == end()) + { + Value v; + ValueCodec::write(key.second, v, _communicator); + + _helper->put(k, v); + inserted = true; + r = iterator(_helper->find(k, false), _communicator); + } - return std::pair(r, inserted); + return std::pair(r, inserted); } template void insert(InputIterator first, InputIterator last) { - while(first != last) - { - insert(*first); - ++first; - } + while(first != last) + { + insert(*first); + ++first; + } } void put(const value_type& key) { - // - // insert or replace - // - Key k; - Value v; - KeyCodec::write(key.first, k, _communicator); - ValueCodec::write(key.second, v, _communicator); + // + // insert or replace + // + Key k; + Value v; + KeyCodec::write(key.first, k, _communicator); + ValueCodec::write(key.second, v, _communicator); - _helper->put(k, v); + _helper->put(k, v); } template void put(InputIterator first, InputIterator last) { - while(first != last) - { - put(*first); - ++first; - } + while(first != last) + { + put(*first); + ++first; + } } void erase(iterator position) { - assert(position._helper.get() != 0); - position._helper->erase(); + assert(position._helper.get() != 0); + position._helper->erase(); } size_type erase(const key_type& key) { - Key k; - KeyCodec::write(key, k, _communicator); + Key k; + KeyCodec::write(key, k, _communicator); - return _helper->erase(k); + return _helper->erase(k); } void erase(iterator first, iterator last) { - while(first != last) - { - first._helper->erase(); - ++first; - } + while(first != last) + { + first._helper->erase(); + ++first; + } } void clear() { - _helper->clear(); + _helper->clear(); } @@ -1070,87 +1070,87 @@ public: // void destroy() { - _helper->destroy(); + _helper->destroy(); } iterator find(const key_type& key) { - Key k; - KeyCodec::write(key, k, _communicator); + Key k; + KeyCodec::write(key, k, _communicator); - return iterator(_helper->find(k, false), _communicator); + return iterator(_helper->find(k, false), _communicator); } const_iterator find(const key_type& key) const { - Key k; - KeyCodec::write(key, k, _communicator); + Key k; + KeyCodec::write(key, k, _communicator); - return const_iterator(_helper->find(k, true), _communicator); + return const_iterator(_helper->find(k, true), _communicator); } size_type count(const key_type& key) const { - Key k; - KeyCodec::write(key, k, _communicator); - - return _helper->count(k); + Key k; + KeyCodec::write(key, k, _communicator); + + return _helper->count(k); } iterator lower_bound(const key_type& key) { - Key k; - KeyCodec::write(key, k, _communicator); + Key k; + KeyCodec::write(key, k, _communicator); - return iterator(_helper->lowerBound(k, false), _communicator); + return iterator(_helper->lowerBound(k, false), _communicator); } const_iterator lower_bound(const key_type& key) const { - Key k; - KeyCodec::write(key, k, _communicator); + Key k; + KeyCodec::write(key, k, _communicator); - return iterator(_helper->lowerBound(k, true), _communicator); + return iterator(_helper->lowerBound(k, true), _communicator); } iterator upper_bound(const key_type& key) { - Key k; - KeyCodec::write(key, k, _communicator); + Key k; + KeyCodec::write(key, k, _communicator); - return iterator(_helper->upperBound(k, false), _communicator); + return iterator(_helper->upperBound(k, false), _communicator); } const_iterator upper_bound(const key_type& key) const { - Key k; - KeyCodec::write(key, k, _communicator); + Key k; + KeyCodec::write(key, k, _communicator); - return iterator(_helper->upperBound(k, true), _communicator); + return iterator(_helper->upperBound(k, true), _communicator); } std::pair equal_range(const key_type& key) { - return std::make_pair(lower_bound(key), upper_bound(key)); + return std::make_pair(lower_bound(key), upper_bound(key)); } std::pair equal_range(const key_type& key) const { - return std::make_pair(lower_bound(key), upper_bound(key)); + return std::make_pair(lower_bound(key), upper_bound(key)); } const Ice::CommunicatorPtr& communicator() const { - return _communicator(); + return _communicator(); } protected: Map(const Ice::CommunicatorPtr& communicator) : - _communicator(communicator) + _communicator(communicator) { } @@ -1170,19 +1170,19 @@ namespace std // TODO: update. template + class KeyCodec, class ValueCodec, class Compare> inline pair* value_type(const Freeze::Iterator&) + KeyCodec, ValueCodec, Compare>&) { return (pair*)0; } template + class KeyCodec, class ValueCodec, class Compare> inline pair* value_type(const Freeze::ConstIterator&) + KeyCodec, ValueCodec, Compare>&) { return (pair*)0; } diff --git a/cpp/include/Ice/BasicStream.h b/cpp/include/Ice/BasicStream.h index 671c46f49d6..7cab7da51ef 100644 --- a/cpp/include/Ice/BasicStream.h +++ b/cpp/include/Ice/BasicStream.h @@ -38,14 +38,14 @@ public: public: StreamUTF8BufferI(BasicStream& stream) : - _stream(stream) - { - } + _stream(stream) + { + } Ice::Byte* getMoreBytes(size_t howMany, Ice::Byte* firstUnused) { - assert(howMany > 0); + assert(howMany > 0); if(firstUnused != 0) { @@ -71,7 +71,7 @@ public: private: - BasicStream& _stream; + BasicStream& _stream; }; typedef void (*PatchFunc)(void*, Ice::ObjectPtr&); @@ -102,14 +102,14 @@ public: void resize(Container::size_type sz) { // - // Check memory limit if stream is not unlimited. - // - if(!_unlimited && sz > _messageSizeMax) - { - throwMemoryLimitException(__FILE__, __LINE__); - } - - b.resize(sz); + // Check memory limit if stream is not unlimited. + // + if(!_unlimited && sz > _messageSizeMax) + { + throwMemoryLimitException(__FILE__, __LINE__); + } + + b.resize(sz); } void startSeq(int, int); @@ -142,8 +142,8 @@ public: void checkFixedSeq(int, int); // For sequences of fixed-size types. void endElement() { - assert(_seqDataStack); - --_seqDataStack->numElements; + assert(_seqDataStack); + --_seqDataStack->numElements; } void endSeq(int); @@ -364,32 +364,32 @@ public: void write(Ice::Byte v) { - b.push_back(v); + b.push_back(v); } void write(const Ice::Byte*, const Ice::Byte*); void read(Ice::Byte& v) { - if(i >= b.end()) - { - throwUnmarshalOutOfBoundsException(__FILE__, __LINE__); - } - v = *i++; + if(i >= b.end()) + { + throwUnmarshalOutOfBoundsException(__FILE__, __LINE__); + } + v = *i++; } void read(std::pair&); void write(bool v) { - b.push_back(static_cast(v)); + b.push_back(static_cast(v)); } void write(const std::vector&); void write(const bool*, const bool*); void read(bool& v) { - if(i >= b.end()) - { - throwUnmarshalOutOfBoundsException(__FILE__, __LINE__); - } - v = *i++; + if(i >= b.end()) + { + throwUnmarshalOutOfBoundsException(__FILE__, __LINE__); + } + v = *i++; } void read(std::vector&); bool* read(std::pair&); @@ -479,11 +479,11 @@ public: { Ice::Int sz = static_cast(v.size()); if(convert && sz > 0 && _stringConverter != 0) - { - writeConverted(v); - } - else - { + { + writeConverted(v); + } + else + { writeSize(sz); if(sz > 0) { @@ -491,7 +491,7 @@ public: resize(pos + sz); memcpy(&b[pos], v.data(), sz); } - } + } } void write(const std::string*, const std::string*, bool = true); void read(std::string& v, bool convert = true) @@ -505,14 +505,14 @@ public: { throwUnmarshalOutOfBoundsException(__FILE__, __LINE__); } - if(convert && _stringConverter != 0) - { - _stringConverter->fromUTF8(i, i + sz, v); - } - else - { + if(convert && _stringConverter != 0) + { + _stringConverter->fromUTF8(i, i + sz, v); + } + else + { std::string(reinterpret_cast(&*i), reinterpret_cast(&*i) + sz).swap(v); - } + } i += sz; } else @@ -535,7 +535,7 @@ public: throwUnmarshalOutOfBoundsException(__FILE__, __LINE__); } - _wstringConverter->fromUTF8(i, i + sz, v); + _wstringConverter->fromUTF8(i, i + sz, v); i += sz; } else @@ -561,8 +561,8 @@ public: struct PatchEntry { - PatchFunc patchFunc; - void* patchAddr; + PatchFunc patchFunc; + void* patchAddr; }; typedef std::vector PatchList; @@ -598,20 +598,20 @@ private: { public: - ReadEncaps() : patchMap(0), unmarshaledMap(0), typeIdMap(0), typeIdIndex(0), previous(0) - { - // Inlined for performance reasons. - } - ~ReadEncaps() - { - // Inlined for performance reasons. + ReadEncaps() : patchMap(0), unmarshaledMap(0), typeIdMap(0), typeIdIndex(0), previous(0) + { + // Inlined for performance reasons. + } + ~ReadEncaps() + { + // Inlined for performance reasons. delete patchMap; delete unmarshaledMap; delete typeIdMap; - } - void reset() + } + void reset() { - // Inlined for performance reasons. + // Inlined for performance reasons. delete patchMap; delete unmarshaledMap; delete typeIdMap; @@ -622,40 +622,40 @@ private: typeIdIndex = 0; previous = 0; } - void swap(ReadEncaps&); + void swap(ReadEncaps&); - Container::size_type start; - Ice::Int sz; + Container::size_type start; + Ice::Int sz; - Ice::Byte encodingMajor; - Ice::Byte encodingMinor; + Ice::Byte encodingMajor; + Ice::Byte encodingMinor; - PatchMap* patchMap; - IndexToPtrMap* unmarshaledMap; - TypeIdReadMap* typeIdMap; - Ice::Int typeIdIndex; + PatchMap* patchMap; + IndexToPtrMap* unmarshaledMap; + TypeIdReadMap* typeIdMap; + Ice::Int typeIdIndex; - ReadEncaps* previous; + ReadEncaps* previous; }; class ICE_API WriteEncaps : private ::IceUtil::noncopyable { public: - WriteEncaps() : writeIndex(0), toBeMarshaledMap(0), marshaledMap(0), typeIdMap(0), typeIdIndex(0), previous(0) - { - // Inlined for performance reasons. - } - ~WriteEncaps() + WriteEncaps() : writeIndex(0), toBeMarshaledMap(0), marshaledMap(0), typeIdMap(0), typeIdIndex(0), previous(0) + { + // Inlined for performance reasons. + } + ~WriteEncaps() { - // Inlined for performance reasons. + // Inlined for performance reasons. delete toBeMarshaledMap; delete marshaledMap; delete typeIdMap; } - void reset() + void reset() { - // Inlined for performance reasons. + // Inlined for performance reasons. delete toBeMarshaledMap; delete marshaledMap; delete typeIdMap; @@ -667,17 +667,17 @@ private: typeIdIndex = 0; previous = 0; } - void swap(WriteEncaps&); + void swap(WriteEncaps&); - Container::size_type start; + Container::size_type start; - Ice::Int writeIndex; - PtrToIndexMap* toBeMarshaledMap; - PtrToIndexMap* marshaledMap; - TypeIdWriteMap* typeIdMap; - Ice::Int typeIdIndex; + Ice::Int writeIndex; + PtrToIndexMap* toBeMarshaledMap; + PtrToIndexMap* marshaledMap; + TypeIdWriteMap* typeIdMap; + Ice::Int typeIdIndex; - WriteEncaps* previous; + WriteEncaps* previous; }; ReadEncaps* _currentReadEncaps; @@ -705,10 +705,10 @@ private: struct SeqData { - SeqData(int, int); - int numElements; - int minSize; - SeqData* previous; + SeqData(int, int); + int numElements; + int minSize; + SeqData* previous; }; SeqData* _seqDataStack; diff --git a/cpp/include/Ice/Buffer.h b/cpp/include/Ice/Buffer.h index a15b9184b53..b780d84d2fa 100644 --- a/cpp/include/Ice/Buffer.h +++ b/cpp/include/Ice/Buffer.h @@ -28,122 +28,122 @@ public: { public: - // - // Standard vector-like operations. - // - - typedef Ice::Byte value_type; - typedef Ice::Byte* iterator; - typedef const Ice::Byte* const_iterator; - typedef Ice::Byte& reference; - typedef const Ice::Byte& const_reference; - typedef Ice::Byte* pointer; - typedef ptrdiff_t difference_type; - typedef size_t size_type; - - Container(size_type maxCapacity); - - ~Container(); - - iterator begin() - { - return _buf; - } - - const_iterator begin() const - { - return _buf; - } - - iterator end() - { - return _buf + _size; - } - - const_iterator end() const - { - return _buf + _size; - } - - size_type size() const - { - return _size; - } - - bool empty() const - { - return !_size; - } - - void swap(Container&); - - void clear(); - - void resize(size_type n) // Inlined for performance reasons. + // + // Standard vector-like operations. + // + + typedef Ice::Byte value_type; + typedef Ice::Byte* iterator; + typedef const Ice::Byte* const_iterator; + typedef Ice::Byte& reference; + typedef const Ice::Byte& const_reference; + typedef Ice::Byte* pointer; + typedef ptrdiff_t difference_type; + typedef size_t size_type; + + Container(size_type maxCapacity); + + ~Container(); + + iterator begin() + { + return _buf; + } + + const_iterator begin() const + { + return _buf; + } + + iterator end() + { + return _buf + _size; + } + + const_iterator end() const + { + return _buf + _size; + } + + size_type size() const + { + return _size; + } + + bool empty() const + { + return !_size; + } + + void swap(Container&); + + void clear(); + + void resize(size_type n) // Inlined for performance reasons. + { + if(n == 0) + { + clear(); + } + else if(n > _capacity) + { + reserve(n); + } + _size = n; + } + + void reset() + { + if(_size > 0 && _size * 2 < _capacity) + { + // + // If the current buffer size is smaller than the + // buffer capacity, we shrink the buffer memory to the + // current size. This is to avoid holding on too much + // memory if it's not needed anymore. + // + if(++_shrinkCounter > 2) + { + reserve(_size); + _shrinkCounter = 0; + } + } + else + { + _shrinkCounter = 0; + } + _size = 0; + } + + void push_back(value_type v) + { + resize(_size + 1); + _buf[_size - 1] = v; + } + + reference operator[](size_type n) + { + assert(n < _size); + return _buf[n]; + } + + const_reference operator[](size_type n) const { - if(n == 0) - { - clear(); - } - else if(n > _capacity) - { - reserve(n); - } - _size = n; - } - - void reset() - { - if(_size > 0 && _size * 2 < _capacity) - { - // - // If the current buffer size is smaller than the - // buffer capacity, we shrink the buffer memory to the - // current size. This is to avoid holding on too much - // memory if it's not needed anymore. - // - if(++_shrinkCounter > 2) - { - reserve(_size); - _shrinkCounter = 0; - } - } - else - { - _shrinkCounter = 0; - } - _size = 0; - } - - void push_back(value_type v) - { - resize(_size + 1); - _buf[_size - 1] = v; - } - - reference operator[](size_type n) - { - assert(n < _size); - return _buf[n]; - } - - const_reference operator[](size_type n) const - { - assert(n < _size); - return _buf[n]; - } - + assert(n < _size); + return _buf[n]; + } + private: - Container(const Container&); - void operator=(const Container&); - void reserve(size_type); + Container(const Container&); + void operator=(const Container&); + void reserve(size_type); - pointer _buf; - size_type _size; - size_type _capacity; - size_type _maxCapacity; - int _shrinkCounter; + pointer _buf; + size_type _size; + size_type _capacity; + size_type _maxCapacity; + int _shrinkCounter; }; Container b; diff --git a/cpp/include/Ice/FactoryTable.h b/cpp/include/Ice/FactoryTable.h index 81e15a485c0..8a534ab252d 100644 --- a/cpp/include/Ice/FactoryTable.h +++ b/cpp/include/Ice/FactoryTable.h @@ -23,7 +23,7 @@ public: ~FactoryTable(); }; -static FactoryTable factoryTableInitializer; // Dummy variable to force initialization of factoryTable +static FactoryTable factoryTableInitializer; // Dummy variable to force initialization of factoryTable extern ICE_API FactoryTableDef* factoryTable; diff --git a/cpp/include/Ice/GCShared.h b/cpp/include/Ice/GCShared.h index 2812a1b4702..df5dd94262e 100755 --- a/cpp/include/Ice/GCShared.h +++ b/cpp/include/Ice/GCShared.h @@ -44,12 +44,12 @@ public: int __getRefUnsafe() const { - return _ref; + return _ref; } void __decRefUnsafe() { - --_ref; + --_ref; } protected: diff --git a/cpp/include/Ice/Handle.h b/cpp/include/Ice/Handle.h index 0fc6212cb93..c224ceace4e 100644 --- a/cpp/include/Ice/Handle.h +++ b/cpp/include/Ice/Handle.h @@ -44,143 +44,143 @@ public: Handle(T* p = 0) { - this->_ptr = p; + this->_ptr = p; - if(this->_ptr) - { - incRef(this->_ptr); - } + if(this->_ptr) + { + incRef(this->_ptr); + } } template Handle(const Handle& r) { - this->_ptr = r._ptr; + this->_ptr = r._ptr; - if(this->_ptr) - { - incRef(this->_ptr); - } + if(this->_ptr) + { + incRef(this->_ptr); + } } template Handle(const ::IceUtil::Handle& r) { - this->_ptr = r._ptr; + this->_ptr = r._ptr; - if(this->_ptr) - { - incRef(this->_ptr); - } + if(this->_ptr) + { + incRef(this->_ptr); + } } Handle(const Handle& r) { - this->_ptr = r._ptr; + this->_ptr = r._ptr; - if(this->_ptr) - { - incRef(this->_ptr); - } + if(this->_ptr) + { + incRef(this->_ptr); + } } ~Handle() { - if(this->_ptr) - { - decRef(this->_ptr); - } + if(this->_ptr) + { + decRef(this->_ptr); + } } Handle& operator=(T* p) { - if(this->_ptr != p) - { - if(p) - { - incRef(p); - } - - T* ptr = this->_ptr; - this->_ptr = p; - - if(ptr) - { - decRef(ptr); - } - } - return *this; + if(this->_ptr != p) + { + if(p) + { + incRef(p); + } + + T* ptr = this->_ptr; + this->_ptr = p; + + if(ptr) + { + decRef(ptr); + } + } + return *this; } template Handle& operator=(const Handle& r) { - if(this->_ptr != r._ptr) - { - if(r._ptr) - { - incRef(r._ptr); - } - - T* ptr = this->_ptr; - this->_ptr = r._ptr; - - if(ptr) - { - decRef(ptr); - } - } - return *this; + if(this->_ptr != r._ptr) + { + if(r._ptr) + { + incRef(r._ptr); + } + + T* ptr = this->_ptr; + this->_ptr = r._ptr; + + if(ptr) + { + decRef(ptr); + } + } + return *this; } template Handle& operator=(const ::IceUtil::Handle& r) { - if(this->_ptr != r._ptr) - { - if(r._ptr) - { - incRef(r._ptr); - } - - T* ptr = this->_ptr; - this->_ptr = r._ptr; - - if(ptr) - { - decRef(ptr); - } - } - return *this; + if(this->_ptr != r._ptr) + { + if(r._ptr) + { + incRef(r._ptr); + } + + T* ptr = this->_ptr; + this->_ptr = r._ptr; + + if(ptr) + { + decRef(ptr); + } + } + return *this; } Handle& operator=(const Handle& r) { - if(this->_ptr != r._ptr) - { - if(r._ptr) - { - incRef(r._ptr); - } - - T* ptr = this->_ptr; - this->_ptr = r._ptr; - - if(ptr) - { - decRef(ptr); - } - } - return *this; + if(this->_ptr != r._ptr) + { + if(r._ptr) + { + incRef(r._ptr); + } + + T* ptr = this->_ptr; + this->_ptr = r._ptr; + + if(ptr) + { + decRef(ptr); + } + } + return *this; } template static Handle dynamicCast(const ::IceUtil::HandleBase& r) { #ifdef __BCPLUSPLUS__ - return Handle(dynamic_cast(r._ptr)); + return Handle(dynamic_cast(r._ptr)); #else - return Handle(dynamic_cast(r._ptr)); + return Handle(dynamic_cast(r._ptr)); #endif } @@ -188,15 +188,15 @@ public: static Handle dynamicCast(Y* p) { #ifdef __BCPLUSPLUS__ - return Handle(dynamic_cast(p)); + return Handle(dynamic_cast(p)); #else - return Handle(dynamic_cast(p)); + return Handle(dynamic_cast(p)); #endif } void __clearHandleUnsafe() { - this->_ptr = 0; + this->_ptr = 0; } }; diff --git a/cpp/include/Ice/IncomingAsync.h b/cpp/include/Ice/IncomingAsync.h index dc6af5ed78a..e7c5ba20ece 100644 --- a/cpp/include/Ice/IncomingAsync.h +++ b/cpp/include/Ice/IncomingAsync.h @@ -99,7 +99,7 @@ public: }; class ICE_API AMD_Array_Object_ice_invoke : public ::Ice::AMD_Array_Object_ice_invoke, - public IceInternal::IncomingAsync + public IceInternal::IncomingAsync { public: diff --git a/cpp/include/Ice/Initialize.h b/cpp/include/Ice/Initialize.h index 78cd1dbd104..77c8df84026 100644 --- a/cpp/include/Ice/Initialize.h +++ b/cpp/include/Ice/Initialize.h @@ -65,22 +65,22 @@ struct InitializationData }; ICE_API CommunicatorPtr initialize(int&, char*[], const InitializationData& = InitializationData(), - Int = ICE_INT_VERSION); + Int = ICE_INT_VERSION); ICE_API CommunicatorPtr initialize(Ice::StringSeq&, const InitializationData& = InitializationData(), - Int = ICE_INT_VERSION); + Int = ICE_INT_VERSION); ICE_API CommunicatorPtr initialize(const InitializationData& = InitializationData(), - Int = ICE_INT_VERSION); + Int = ICE_INT_VERSION); ICE_API ICE_DEPRECATED_API CommunicatorPtr initializeWithProperties(int&, char*[], const PropertiesPtr&, - Int = ICE_INT_VERSION); + Int = ICE_INT_VERSION); ICE_API ICE_DEPRECATED_API CommunicatorPtr initializeWithLogger(int&, char*[], const Ice::LoggerPtr&, - Int = ICE_INT_VERSION); + Int = ICE_INT_VERSION); ICE_API ICE_DEPRECATED_API CommunicatorPtr initializeWithPropertiesAndLogger(int&, char*[], const PropertiesPtr&, - const Ice::LoggerPtr&, - Int = ICE_INT_VERSION); + const Ice::LoggerPtr&, + Int = ICE_INT_VERSION); ICE_API InputStreamPtr createInputStream(const CommunicatorPtr&, const ::std::vector< Byte >&); ICE_API OutputStreamPtr createOutputStream(const CommunicatorPtr&); diff --git a/cpp/include/Ice/Object.h b/cpp/include/Ice/Object.h index e740d25a69d..2fe85ed8508 100644 --- a/cpp/include/Ice/Object.h +++ b/cpp/include/Ice/Object.h @@ -133,7 +133,7 @@ public: // Returns true if ok, false if user exception. virtual void ice_invoke_async(const AMD_Array_Object_ice_invokePtr&, const std::pair&, - const Current&) = 0; + const Current&) = 0; virtual IceInternal::DispatchStatus __dispatch(IceInternal::Incoming&, const Current&); }; diff --git a/cpp/include/Ice/Outgoing.h b/cpp/include/Ice/Outgoing.h index 30e8f0c4d43..2ce534c3466 100644 --- a/cpp/include/Ice/Outgoing.h +++ b/cpp/include/Ice/Outgoing.h @@ -85,11 +85,11 @@ private: enum { - StateUnsent, - StateInProgress, - StateOK, - StateUserException, - StateLocalException + StateUnsent, + StateInProgress, + StateOK, + StateUserException, + StateLocalException } _state; BasicStream _is; diff --git a/cpp/include/Ice/OutgoingAsync.h b/cpp/include/Ice/OutgoingAsync.h index 768846e619c..21a3796b156 100644 --- a/cpp/include/Ice/OutgoingAsync.h +++ b/cpp/include/Ice/OutgoingAsync.h @@ -77,7 +77,7 @@ public: virtual void ice_exception(const Ice::Exception&) = 0; void __invoke(const Ice::ObjectPrx&, const std::string& operation, OperationMode, - const std::vector&, const Context*); + const std::vector&, const Context*); protected: @@ -92,7 +92,7 @@ public: virtual void ice_exception(const Ice::Exception&) = 0; void __invoke(const Ice::ObjectPrx&, const std::string& operation, OperationMode, - const std::pair&, const Context*); + const std::pair&, const Context*); protected: diff --git a/cpp/include/Ice/Proxy.h b/cpp/include/Ice/Proxy.h index 3c7d1b3912a..9a70a3a65c0 100644 --- a/cpp/include/Ice/Proxy.h +++ b/cpp/include/Ice/Proxy.h @@ -93,82 +93,82 @@ public: bool ice_isA(const ::std::string& typeId) { - return ice_isA(typeId, 0); + return ice_isA(typeId, 0); } bool ice_isA(const ::std::string& typeId, const ::Ice::Context& context) { - return ice_isA(typeId, &context); + return ice_isA(typeId, &context); } void ice_ping() { - ice_ping(0); + ice_ping(0); } void ice_ping(const ::Ice::Context& context) { - ice_ping(&context); + ice_ping(&context); } ::std::vector< ::std::string> ice_ids() { - return ice_ids(0); + return ice_ids(0); } ::std::vector< ::std::string> ice_ids(const ::Ice::Context& context) { - return ice_ids(&context); + return ice_ids(&context); } ::std::string ice_id() { - return ice_id(0); + return ice_id(0); } ::std::string ice_id(const ::Ice::Context& context) { - return ice_id(&context); + return ice_id(&context); } // Returns true if ok, false if user exception. bool ice_invoke(const ::std::string& operation, - ::Ice::OperationMode mode, - const ::std::vector< ::Ice::Byte>& inParams, - ::std::vector< ::Ice::Byte>& outParams) + ::Ice::OperationMode mode, + const ::std::vector< ::Ice::Byte>& inParams, + ::std::vector< ::Ice::Byte>& outParams) { - const ::Ice::Context* context = 0; - return ice_invoke(operation, mode, inParams, outParams, context); + const ::Ice::Context* context = 0; + return ice_invoke(operation, mode, inParams, outParams, context); } bool ice_invoke(const ::std::string& operation, - ::Ice::OperationMode mode, - const ::std::vector< ::Ice::Byte>& inParams, - ::std::vector< ::Ice::Byte>& outParams, - const ::Ice::Context& context) + ::Ice::OperationMode mode, + const ::std::vector< ::Ice::Byte>& inParams, + ::std::vector< ::Ice::Byte>& outParams, + const ::Ice::Context& context) { - return ice_invoke(operation, mode, inParams, outParams, &context); + return ice_invoke(operation, mode, inParams, outParams, &context); } bool ice_invoke(const ::std::string& operation, - ::Ice::OperationMode mode, - const ::std::pair& inParams, - ::std::vector< ::Ice::Byte>& outParams) + ::Ice::OperationMode mode, + const ::std::pair& inParams, + ::std::vector< ::Ice::Byte>& outParams) { - const ::Ice::Context* context = 0; - return ice_invoke(operation, mode, inParams, outParams, context); + const ::Ice::Context* context = 0; + return ice_invoke(operation, mode, inParams, outParams, context); } bool ice_invoke(const ::std::string& operation, - ::Ice::OperationMode mode, - const ::std::pair& inParams, - ::std::vector< ::Ice::Byte>& outParams, - const ::Ice::Context& context) + ::Ice::OperationMode mode, + const ::std::pair& inParams, + ::std::vector< ::Ice::Byte>& outParams, + const ::Ice::Context& context) { - return ice_invoke(operation, mode, inParams, outParams, &context); + return ice_invoke(operation, mode, inParams, outParams, &context); } void ice_invoke_async(const ::Ice::AMI_Object_ice_invokePtr&, const ::std::string&, ::Ice::OperationMode, - const ::std::vector< ::Ice::Byte>&); + const ::std::vector< ::Ice::Byte>&); void ice_invoke_async(const ::Ice::AMI_Object_ice_invokePtr&, const ::std::string&, ::Ice::OperationMode, - const ::std::vector< ::Ice::Byte>&, const ::Ice::Context&); + const ::std::vector< ::Ice::Byte>&, const ::Ice::Context&); void ice_invoke_async(const ::Ice::AMI_Array_Object_ice_invokePtr&, const ::std::string&, ::Ice::OperationMode, - const ::std::pair&); + const ::std::pair&); void ice_invoke_async(const ::Ice::AMI_Array_Object_ice_invokePtr&, const ::std::string&, ::Ice::OperationMode, - const ::std::pair&, const ::Ice::Context&); + const ::std::pair&, const ::Ice::Context&); ::Ice::Identity ice_getIdentity() const; ICE_DEPRECATED_API ::Ice::ObjectPrx ice_newIdentity(const ::Ice::Identity&) const; @@ -241,11 +241,11 @@ public: ::IceInternal::ReferencePtr __reference() const; void __copyFrom(const ::Ice::ObjectPrx&); void __handleException(const ::IceInternal::Handle< ::IceDelegate::Ice::Object>&, - const ::Ice::LocalException&, int&); + const ::Ice::LocalException&, int&); void __handleExceptionWrapper(const ::IceInternal::Handle< ::IceDelegate::Ice::Object>&, - const ::IceInternal::LocalExceptionWrapper&); + const ::IceInternal::LocalExceptionWrapper&); void __handleExceptionWrapperRelaxed(const ::IceInternal::Handle< ::IceDelegate::Ice::Object>&, - const ::IceInternal::LocalExceptionWrapper&, int&); + const ::IceInternal::LocalExceptionWrapper&, int&); void __checkTwowayOnly(const char*) const; void __checkTwowayOnly(const ::std::string&) const; @@ -265,15 +265,15 @@ private: bool ice_invoke(const ::std::string&, - ::Ice::OperationMode, - const ::std::vector< ::Ice::Byte>&, - ::std::vector< ::Ice::Byte>&, - const ::Ice::Context*); + ::Ice::OperationMode, + const ::std::vector< ::Ice::Byte>&, + ::std::vector< ::Ice::Byte>&, + const ::Ice::Context*); bool ice_invoke(const ::std::string&, - ::Ice::OperationMode, - const ::std::pair&, - ::std::vector< ::Ice::Byte>&, - const ::Ice::Context*); + ::Ice::OperationMode, + const ::std::pair&, + ::std::vector< ::Ice::Byte>&, + const ::Ice::Context*); void setup(const ::IceInternal::ReferencePtr&); friend class ::IceInternal::ProxyFactory; @@ -298,8 +298,8 @@ public: virtual ::std::vector< ::std::string> ice_ids(const ::Ice::Context*) = 0; virtual ::std::string ice_id(const ::Ice::Context*) = 0; virtual bool ice_invoke(const ::std::string&, ::Ice::OperationMode, - const ::std::pair&, - ::std::vector< ::Ice::Byte>&, const ::Ice::Context*) = 0; + const ::std::pair&, + ::std::vector< ::Ice::Byte>&, const ::Ice::Context*) = 0; virtual ::Ice::ConnectionIPtr __getConnection(bool&) const = 0; }; @@ -320,8 +320,8 @@ public: virtual ::std::vector< ::std::string> ice_ids(const ::Ice::Context*); virtual ::std::string ice_id(const ::Ice::Context*); virtual bool ice_invoke(const ::std::string&, ::Ice::OperationMode, - const ::std::pair&, - ::std::vector< ::Ice::Byte>&, const ::Ice::Context*); + const ::std::pair&, + ::std::vector< ::Ice::Byte>&, const ::Ice::Context*); virtual ::Ice::ConnectionIPtr __getConnection(bool&) const; @@ -353,8 +353,8 @@ public: virtual ::std::vector< ::std::string> ice_ids(const ::Ice::Context*); virtual ::std::string ice_id(const ::Ice::Context*); virtual bool ice_invoke(const ::std::string&, ::Ice::OperationMode, - const ::std::pair&, - ::std::vector< ::Ice::Byte>&, const ::Ice::Context*); + const ::std::pair&, + ::std::vector< ::Ice::Byte>&, const ::Ice::Context*); virtual ::Ice::ConnectionIPtr __getConnection(bool&) const; @@ -388,7 +388,7 @@ struct ProxyIdentityLess : std::binary_function { bool operator()(const ObjectPrx& lhs, const ObjectPrx& rhs) const { - return proxyIdentityLess(lhs, rhs); + return proxyIdentityLess(lhs, rhs); } }; @@ -396,7 +396,7 @@ struct ProxyIdentityEqual : std::binary_function { bool operator()(const ObjectPrx& lhs, const ObjectPrx& rhs) const { - return proxyIdentityEqual(lhs, rhs); + return proxyIdentityEqual(lhs, rhs); } }; @@ -404,7 +404,7 @@ struct ProxyIdentityAndFacetLess : std::binary_function(b.get()); - if(!d && (context == 0 ? - b->ice_isA(T::ice_staticId()) : - b->ice_isA(T::ice_staticId(), *context))) - { - d = new T; - d->__copyFrom(b); - } + typedef typename P::element_type T; + + d = dynamic_cast(b.get()); + if(!d && (context == 0 ? + b->ice_isA(T::ice_staticId()) : + b->ice_isA(T::ice_staticId(), *context))) + { + d = new T; + d->__copyFrom(b); + } } return d; } @@ -450,14 +450,14 @@ uncheckedCastImpl(const ::Ice::ObjectPrx& b) P d = 0; if(b) { - typedef typename P::element_type T; - - d = dynamic_cast(b.get()); - if(!d) - { - d = new T; - d->__copyFrom(b); - } + typedef typename P::element_type T; + + d = dynamic_cast(b.get()); + if(!d) + { + d = new T; + d->__copyFrom(b); + } } return d; } @@ -489,7 +489,7 @@ uncheckedCastImpl< ::Ice::ObjectPrx>(const ::Ice::ObjectPrx& b, const std::strin ::Ice::ObjectPrx d = 0; if(b) { - d = b->ice_facet(f); + d = b->ice_facet(f); } return d; } @@ -504,8 +504,8 @@ checkedCastImpl(const ::Ice::ObjectPrx& b, const std::string& f, const ::Ice::Co if(bb) { - d = new T; - d->__copyFrom(bb); + d = new T; + d->__copyFrom(bb); } return d; } @@ -516,11 +516,11 @@ uncheckedCastImpl(const ::Ice::ObjectPrx& b, const std::string& f) P d = 0; if(b) { - typedef typename P::element_type T; + typedef typename P::element_type T; - ::Ice::ObjectPrx bb = b->ice_facet(f); - d = new T; - d->__copyFrom(bb); + ::Ice::ObjectPrx bb = b->ice_facet(f); + d = new T; + d->__copyFrom(bb); } return d; } diff --git a/cpp/include/Ice/ProxyHandle.h b/cpp/include/Ice/ProxyHandle.h index 6c06e30647b..7229b428bdc 100644 --- a/cpp/include/Ice/ProxyHandle.h +++ b/cpp/include/Ice/ProxyHandle.h @@ -110,171 +110,171 @@ public: ProxyHandle(T* p = 0) { - this->_ptr = p; + this->_ptr = p; - if(this->_ptr) - { - incRef(this->_ptr); - } + if(this->_ptr) + { + incRef(this->_ptr); + } } template ProxyHandle(const ProxyHandle& r) { - this->_ptr = r._ptr; + this->_ptr = r._ptr; - if(this->_ptr) - { - incRef(this->_ptr); - } + if(this->_ptr) + { + incRef(this->_ptr); + } } template ProxyHandle(const ::IceUtil::Handle& r) { - this->_ptr = r._ptr; + this->_ptr = r._ptr; - if(this->_ptr) - { - incRef(this->_ptr); - } + if(this->_ptr) + { + incRef(this->_ptr); + } } ProxyHandle(const ProxyHandle& r) { - this->_ptr = r._ptr; + this->_ptr = r._ptr; - if(this->_ptr) - { - incRef(this->_ptr); - } + if(this->_ptr) + { + incRef(this->_ptr); + } } ~ProxyHandle() { - if(this->_ptr) - { - decRef(this->_ptr); - } + if(this->_ptr) + { + decRef(this->_ptr); + } } ProxyHandle& operator=(T* p) { - if(this->_ptr != p) - { - if(p) - { - incRef(p); - } - - if(this->_ptr) - { - decRef(this->_ptr); - } - - this->_ptr = p; - } - return *this; + if(this->_ptr != p) + { + if(p) + { + incRef(p); + } + + if(this->_ptr) + { + decRef(this->_ptr); + } + + this->_ptr = p; + } + return *this; } template ProxyHandle& operator=(const ProxyHandle& r) { - if(this->_ptr != r._ptr) - { - if(r._ptr) - { - incRef(r._ptr); - } - - if(this->_ptr) - { - decRef(this->_ptr); - } - - this->_ptr = r._ptr; - } - return *this; + if(this->_ptr != r._ptr) + { + if(r._ptr) + { + incRef(r._ptr); + } + + if(this->_ptr) + { + decRef(this->_ptr); + } + + this->_ptr = r._ptr; + } + return *this; } template ProxyHandle& operator=(const ::IceUtil::Handle& r) { - if(this->_ptr != r._ptr) - { - if(r._ptr) - { - incRef(r._ptr); - } - - if(this->_ptr) - { - decRef(this->_ptr); - } - - this->_ptr = r._ptr; - } - return *this; + if(this->_ptr != r._ptr) + { + if(r._ptr) + { + incRef(r._ptr); + } + + if(this->_ptr) + { + decRef(this->_ptr); + } + + this->_ptr = r._ptr; + } + return *this; } ProxyHandle& operator=(const ProxyHandle& r) { - if(this->_ptr != r._ptr) - { - if(r._ptr) - { - incRef(r._ptr); - } - - if(this->_ptr) - { - decRef(this->_ptr); - } - - this->_ptr = r._ptr; - } - return *this; + if(this->_ptr != r._ptr) + { + if(r._ptr) + { + incRef(r._ptr); + } + + if(this->_ptr) + { + decRef(this->_ptr); + } + + this->_ptr = r._ptr; + } + return *this; } template static ProxyHandle checkedCast(const ProxyHandle& r) { - Y* tag = 0; - Ice::Context* ctx = 0; - return ::IceInternal::checkedCastHelper(r, tag, ctx); + Y* tag = 0; + Ice::Context* ctx = 0; + return ::IceInternal::checkedCastHelper(r, tag, ctx); } template static ProxyHandle checkedCast(const ProxyHandle& r, const std::string& f) { - Ice::Context* ctx = 0; - return ::IceInternal::checkedCastImpl(r, f, ctx); + Ice::Context* ctx = 0; + return ::IceInternal::checkedCastImpl(r, f, ctx); } template static ProxyHandle checkedCast(const ProxyHandle& r, const ::Ice::Context& ctx) { - Y* tag = 0; - return ::IceInternal::checkedCastHelper(r, tag, &ctx); + Y* tag = 0; + return ::IceInternal::checkedCastHelper(r, tag, &ctx); } template static ProxyHandle checkedCast(const ProxyHandle& r, const std::string& f, const ::Ice::Context& ctx) { - return ::IceInternal::checkedCastImpl(r, f, &ctx); + return ::IceInternal::checkedCastImpl(r, f, &ctx); } template static ProxyHandle uncheckedCast(const ProxyHandle& r) { - Y* tag = 0; - return::IceInternal::uncheckedCastHelper(r, tag); + Y* tag = 0; + return::IceInternal::uncheckedCastHelper(r, tag); } template static ProxyHandle uncheckedCast(const ProxyHandle& r, const std::string& f) { - return ::IceInternal::uncheckedCastImpl(r, f); + return ::IceInternal::uncheckedCastImpl(r, f); } }; diff --git a/cpp/include/Ice/StringConverter.h b/cpp/include/Ice/StringConverter.h index 634b328c1e3..d2aa1dffa7a 100755 --- a/cpp/include/Ice/StringConverter.h +++ b/cpp/include/Ice/StringConverter.h @@ -47,13 +47,13 @@ public: // past the last byte returned by getMoreBytes). // virtual Byte* toUTF8(const charT* sourceStart, const charT* sourceEnd, - UTF8Buffer&) const = 0; + UTF8Buffer&) const = 0; // // Unmarshals a UTF-8 sequence into a basic_string // virtual void fromUTF8(const Byte* sourceStart, const Byte* sourceEnd, - std::basic_string& target) const = 0; + std::basic_string& target) const = 0; }; typedef BasicStringConverter StringConverter; @@ -71,10 +71,10 @@ class ICE_API UnicodeWstringConverter : public WstringConverter public: virtual Byte* toUTF8(const wchar_t* sourceStart, const wchar_t* sourceEnd, - UTF8Buffer&) const; + UTF8Buffer&) const; virtual void fromUTF8(const Byte* sourceStart, const Byte* sourceEnd, - std::wstring& target) const; + std::wstring& target) const; }; } #endif diff --git a/cpp/include/IcePatch2/Util.h b/cpp/include/IcePatch2/Util.h index 4467e911d21..fb7a1836277 100644 --- a/cpp/include/IcePatch2/Util.h +++ b/cpp/include/IcePatch2/Util.h @@ -56,30 +56,30 @@ struct FileInfoEqual: public std::binary_function= 0) and directory (size == -1). We do - // not take the actual size into account, as it might be set - // to 0 if no compressed file is available. - // - Ice::Int lsz = lhs.size > 0 ? 0 : lhs.size; - Ice::Int rsz = rhs.size > 0 ? 0 : rhs.size; - if(lsz != rsz) - { - return false; - } - - if(lhs.executable != rhs.executable) - { - return false; - } - - return lhs.checksum == rhs.checksum; + if(lhs.path != rhs.path) + { + return false; + } + + // + // For the size portion of the comparison, we only distinquish + // between file (size >= 0) and directory (size == -1). We do + // not take the actual size into account, as it might be set + // to 0 if no compressed file is available. + // + Ice::Int lsz = lhs.size > 0 ? 0 : lhs.size; + Ice::Int rsz = rhs.size > 0 ? 0 : rhs.size; + if(lsz != rsz) + { + return false; + } + + if(lhs.executable != rhs.executable) + { + return false; + } + + return lhs.checksum == rhs.checksum; } }; @@ -88,48 +88,48 @@ struct FileInfoWithoutFlagsLess: public std::binary_function= 0) and directory (size == -1). We do - // not take the actual size into account, as it might be set - // to 0 if no compressed file is available. - // - Ice::Int lsz = lhs.size > 0 ? 0 : lhs.size; - Ice::Int rsz = rhs.size > 0 ? 0 : rhs.size; - if(lsz < rsz) - { - return -1; - } - else if(rsz < lsz) - { - return 1; - } - - if(lhs.checksum < rhs.checksum) - { - return -1; - } - else if(rhs.checksum < lhs.checksum) - { - return 1; - } - - return 0; + if(lhs.path < rhs.path) + { + return -1; + } + else if(rhs.path < lhs.path) + { + return 1; + } + + // + // For the size portion of the comparison, we only distinquish + // between file (size >= 0) and directory (size == -1). We do + // not take the actual size into account, as it might be set + // to 0 if no compressed file is available. + // + Ice::Int lsz = lhs.size > 0 ? 0 : lhs.size; + Ice::Int rsz = rhs.size > 0 ? 0 : rhs.size; + if(lsz < rsz) + { + return -1; + } + else if(rsz < lsz) + { + return 1; + } + + if(lhs.checksum < rhs.checksum) + { + return -1; + } + else if(rhs.checksum < lhs.checksum) + { + return 1; + } + + return 0; } }; @@ -138,17 +138,17 @@ struct FileInfoLess : public FileInfoWithoutFlagsLess bool operator()(const FileInfo& lhs, const FileInfo& rhs) { - int rc = compareWithoutFlags(lhs, rhs); - if(rc < 0) - { - return true; - } - else if(rc > 0) - { - return false; - } - - return lhs.executable < rhs.executable; + int rc = compareWithoutFlags(lhs, rhs); + if(rc < 0) + { + return true; + } + else if(rc > 0) + { + return false; + } + + return lhs.executable < rhs.executable; } }; diff --git a/cpp/include/IceStorm/Service.h b/cpp/include/IceStorm/Service.h index 55083fc5faa..ed64dcc45bc 100644 --- a/cpp/include/IceStorm/Service.h +++ b/cpp/include/IceStorm/Service.h @@ -32,11 +32,11 @@ class ICE_STORM_API Service : public ::IceBox::Service public: static ServicePtr create(const Ice::CommunicatorPtr&, - const Ice::ObjectAdapterPtr&, - const Ice::ObjectAdapterPtr&, - const std::string&, - const Ice::Identity&, - const std::string&); + const Ice::ObjectAdapterPtr&, + const Ice::ObjectAdapterPtr&, + const std::string&, + const Ice::Identity&, + const std::string&); virtual void start(const std::string&, const Ice::CommunicatorPtr&, const Ice::StringSeq&) = 0; diff --git a/cpp/include/IceUtil/AbstractMutex.h b/cpp/include/IceUtil/AbstractMutex.h index b2756a71821..1e8b2e0ed3b 100644 --- a/cpp/include/IceUtil/AbstractMutex.h +++ b/cpp/include/IceUtil/AbstractMutex.h @@ -43,17 +43,17 @@ public: virtual void lock() const { - T::lock(); + T::lock(); } virtual void unlock() const { - T::unlock(); + T::unlock(); } virtual bool tryLock() const { - return T::tryLock(); + return T::tryLock(); } virtual ~AbstractMutexI() @@ -72,17 +72,17 @@ public: virtual void lock() const { - T::readLock(); + T::readLock(); } virtual void unlock() const { - T::unlock(); + T::unlock(); } virtual bool tryLock() const { - return T::tryReadLock(); + return T::tryReadLock(); } virtual ~AbstractMutexReadI() @@ -101,17 +101,17 @@ public: virtual void lock() const { - T::writeLock(); + T::writeLock(); } virtual void unlock() const { - T::unlock(); + T::unlock(); } virtual bool tryLock() const { - return T::tryWriteLock(); + return T::tryWriteLock(); } virtual ~AbstractMutexWriteI() diff --git a/cpp/include/IceUtil/Cache.h b/cpp/include/IceUtil/Cache.h index f03afafdbd6..a4d1532a969 100644 --- a/cpp/include/IceUtil/Cache.h +++ b/cpp/include/IceUtil/Cache.h @@ -35,24 +35,24 @@ public: struct Latch : public CountDownLatch { - Latch() : - CountDownLatch(1), - useCount(0) - { - } - int useCount; + Latch() : + CountDownLatch(1), + useCount(0) + { + } + int useCount; }; struct CacheValue { - CacheValue(const Handle& o) : - obj(o), - latch(0) - { - } - - Handle obj; - Latch* latch; + CacheValue(const Handle& o) : + obj(o), + latch(0) + { + } + + Handle obj; + Latch* latch; }; typedef typename std::map::iterator Position; @@ -101,11 +101,11 @@ Cache::getIfPinned(const Key& key) const typename CacheMap::const_iterator p = _map.find(key); if(p != _map.end()) { - return (*p).second.obj; + return (*p).second.obj; } else { - return 0; + return 0; } } @@ -156,7 +156,7 @@ Cache::pin(const Key& key, const Handle& obj) if(ir.second) { - pinned(obj, ir.first); + pinned(obj, ir.first); } return ir.second; } @@ -181,145 +181,145 @@ Cache::pinImpl(const Key& key, const Handle& newObj) for(;;) { - { - Mutex::Lock sync(_mutex); - - // - // Clean up latch from previous loop - // - if(latch != 0) - { - if(--latch->useCount == 0) - { - delete latch; - } - latch = 0; - } + { + Mutex::Lock sync(_mutex); + + // + // Clean up latch from previous loop + // + if(latch != 0) + { + if(--latch->useCount == 0) + { + delete latch; + } + latch = 0; + } #if defined(_MSC_VER) && (_MSC_VER < 1300) - std::pair ir = + std::pair ir = #else - std::pair ir = -#endif - + std::pair ir = +#endif + #if defined(_MSC_VER) || defined(__BCPLUSPLUS__) - _map.insert(CacheMap::value_type(key, CacheValue(0))); + _map.insert(CacheMap::value_type(key, CacheValue(0))); #else - _map.insert(typename CacheMap::value_type(key, CacheValue(0))); + _map.insert(typename CacheMap::value_type(key, CacheValue(0))); #endif - if(ir.second == false) - { - CacheValue& val = ir.first->second; - if(val.obj != 0) - { - return val.obj; - } - - // - // Otherwise wait - // - if(val.latch == 0) - { - // - // The first queued thread creates the latch - // - val.latch = new Latch; - } - latch = val.latch; - latch->useCount++; - } - - p = ir.first; - } - - if(latch != 0) - { - latch->await(); - - // - // p could be stale now, e.g. some other thread pinned and unpinned the - // object while we were waiting. - // So start over. - // - continue; - } - else - { - Handle obj; - try - { - obj = load(key); - } - catch(...) - { - { - Mutex::Lock sync(_mutex); - latch = p->second.latch; - p->second.latch = 0; - _map.erase(p); - } - if(latch != 0) - { - assert(latch->getCount() == 1); - latch->countDown(); - } - throw; - } - - { - Mutex::Lock sync(_mutex); - - latch = p->second.latch; - p->second.latch = 0; - - try - { - if(obj != 0) - { - p->second.obj = obj; - pinned(obj, p); - } - else - { - if(newObj == 0) - { - // - // pin() did not find the object - // - - // - // The waiting threads will have to call load() to see by themselves. - // - _map.erase(p); - } - else - { - // - // putIfAbsent() inserts key/newObj - // - p->second.obj = newObj; - pinned(newObj, p); - } - } - } - catch(...) - { - if(latch != 0) - { - assert(latch->getCount() == 1); - latch->countDown(); - } - throw; - } - } - if(latch != 0) - { - assert(latch->getCount() == 1); - latch->countDown(); - } - return obj; - } + if(ir.second == false) + { + CacheValue& val = ir.first->second; + if(val.obj != 0) + { + return val.obj; + } + + // + // Otherwise wait + // + if(val.latch == 0) + { + // + // The first queued thread creates the latch + // + val.latch = new Latch; + } + latch = val.latch; + latch->useCount++; + } + + p = ir.first; + } + + if(latch != 0) + { + latch->await(); + + // + // p could be stale now, e.g. some other thread pinned and unpinned the + // object while we were waiting. + // So start over. + // + continue; + } + else + { + Handle obj; + try + { + obj = load(key); + } + catch(...) + { + { + Mutex::Lock sync(_mutex); + latch = p->second.latch; + p->second.latch = 0; + _map.erase(p); + } + if(latch != 0) + { + assert(latch->getCount() == 1); + latch->countDown(); + } + throw; + } + + { + Mutex::Lock sync(_mutex); + + latch = p->second.latch; + p->second.latch = 0; + + try + { + if(obj != 0) + { + p->second.obj = obj; + pinned(obj, p); + } + else + { + if(newObj == 0) + { + // + // pin() did not find the object + // + + // + // The waiting threads will have to call load() to see by themselves. + // + _map.erase(p); + } + else + { + // + // putIfAbsent() inserts key/newObj + // + p->second.obj = newObj; + pinned(newObj, p); + } + } + } + catch(...) + { + if(latch != 0) + { + assert(latch->getCount() == 1); + latch->countDown(); + } + throw; + } + } + if(latch != 0) + { + assert(latch->getCount() == 1); + latch->countDown(); + } + return obj; + } } } diff --git a/cpp/include/IceUtil/Cond.h b/cpp/include/IceUtil/Cond.h index 2aedc67952c..ae47c4f6456 100644 --- a/cpp/include/IceUtil/Cond.h +++ b/cpp/include/IceUtil/Cond.h @@ -88,11 +88,11 @@ public: template inline void wait(const Lock& lock) const { - if(!lock.acquired()) - { - throw ThreadLockedException(__FILE__, __LINE__); - } - waitImpl(lock._mutex); + if(!lock.acquired()) + { + throw ThreadLockedException(__FILE__, __LINE__); + } + waitImpl(lock._mutex); } // @@ -105,11 +105,11 @@ public: template inline bool timedWait(const Lock& lock, const Time& timeout) const { - if(!lock.acquired()) - { - throw ThreadLockedException(__FILE__, __LINE__); - } - return timedWaitImpl(lock._mutex, timeout); + if(!lock.acquired()) + { + throw ThreadLockedException(__FILE__, __LINE__); + } + return timedWaitImpl(lock._mutex, timeout); } private: @@ -205,7 +205,7 @@ Cond::waitImpl(const M& mutex) const if(rc != 0) { - throw ThreadSyscallException(__FILE__, __LINE__, rc); + throw ThreadSyscallException(__FILE__, __LINE__, rc); } } @@ -226,15 +226,15 @@ Cond::timedWaitImpl(const M& mutex, const Time& timeout) const if(rc != 0) { - // - // pthread_cond_timedwait returns ETIMEOUT in the event of a - // timeout. - // - if(rc != ETIMEDOUT) - { - throw ThreadSyscallException(__FILE__, __LINE__, rc); - } - return false; + // + // pthread_cond_timedwait returns ETIMEOUT in the event of a + // timeout. + // + if(rc != ETIMEDOUT) + { + throw ThreadSyscallException(__FILE__, __LINE__, rc); + } + return false; } return true; } diff --git a/cpp/include/IceUtil/DisableWarnings.h b/cpp/include/IceUtil/DisableWarnings.h index 1803a0bdc19..ff68c2e0e4b 100644 --- a/cpp/include/IceUtil/DisableWarnings.h +++ b/cpp/include/IceUtil/DisableWarnings.h @@ -21,11 +21,11 @@ // #if defined(_MSC_VER) && _MSC_VER >= 1400 -# define _CRT_SECURE_NO_DEPRECATE 1 // C4996 '' was declared deprecated/ +# define _CRT_SECURE_NO_DEPRECATE 1 // C4996 '' was declared deprecated/ #endif #if defined(_MSC_VER) && _MSC_VER >= 1300 -# pragma warning( 4 : 4996 ) // C4996 'std::' was declared deprecated +# pragma warning( 4 : 4996 ) // C4996 'std::' was declared deprecated #endif #endif diff --git a/cpp/include/IceUtil/Functional.h b/cpp/include/IceUtil/Functional.h index c0a7bf25623..29effa43b9a 100644 --- a/cpp/include/IceUtil/Functional.h +++ b/cpp/include/IceUtil/Functional.h @@ -32,7 +32,7 @@ public: explicit MemFun(MemberFN p) : _mfn(p) { } R operator()(H handle) const { - return (handle.get() ->* _mfn)(); + return (handle.get() ->* _mfn)(); } }; @@ -47,7 +47,7 @@ public: explicit MemFun1(MemberFN p) : _mfn(p) { } R operator()(H handle, A arg) const { - return (handle.get() ->* _mfn)(arg); + return (handle.get() ->* _mfn)(arg); } }; @@ -62,7 +62,7 @@ public: explicit VoidMemFun(MemberFN p) : _mfn(p) { } void operator()(H handle) const { - (handle.get() ->* _mfn)(); + (handle.get() ->* _mfn)(); } }; @@ -77,7 +77,7 @@ public: explicit VoidMemFun1(MemberFN p) : _mfn(p) { } void operator()(H handle, A arg) const { - (handle.get() ->* _mfn)(arg); + (handle.get() ->* _mfn)(arg); } }; @@ -92,7 +92,7 @@ public: explicit SecondMemFun(MemberFN p) : _mfn(p) { } R operator()(std::pair pair) const { - return (pair.second.get() ->* _mfn)(); + return (pair.second.get() ->* _mfn)(); } }; @@ -107,7 +107,7 @@ public: explicit SecondMemFun1(MemberFN p) : _mfn(p) { } R operator()(std::pair pair, A arg) const { - return (pair.second.get() ->* _mfn)(arg); + return (pair.second.get() ->* _mfn)(arg); } }; @@ -122,7 +122,7 @@ public: explicit SecondVoidMemFun(MemberFN p) : _mfn(p) { } void operator()(std::pair pair) const { - (pair.second.get() ->* _mfn)(); + (pair.second.get() ->* _mfn)(); } }; @@ -137,7 +137,7 @@ public: explicit SecondVoidMemFun1(MemberFN p) : _mfn(p) { } void operator()(std::pair pair, A arg) const { - (pair.second.get() ->* _mfn)(arg); + (pair.second.get() ->* _mfn)(arg); } }; @@ -152,7 +152,7 @@ public: explicit ConstMemFun(MemberFN p) : _mfn(p) { } R operator()(H handle) const { - return (handle.get() ->* _mfn)(); + return (handle.get() ->* _mfn)(); } }; @@ -167,7 +167,7 @@ public: explicit ConstMemFun1(MemberFN p) : _mfn(p) { } R operator()(H handle, A arg) const { - return (handle.get() ->* _mfn)(arg); + return (handle.get() ->* _mfn)(arg); } }; @@ -182,7 +182,7 @@ public: explicit ConstVoidMemFun(MemberFN p) : _mfn(p) { } void operator()(H handle) const { - (handle.get() ->* _mfn)(); + (handle.get() ->* _mfn)(); } }; @@ -197,7 +197,7 @@ public: explicit ConstVoidMemFun1(MemberFN p) : _mfn(p) { } void operator()(H handle, A arg) const { - (handle.get() ->* _mfn)(arg); + (handle.get() ->* _mfn)(arg); } }; @@ -212,7 +212,7 @@ public: explicit SecondConstMemFun(MemberFN p) : _mfn(p) { } R operator()(std::pair pair) const { - return (pair.second.get() ->* _mfn)(); + return (pair.second.get() ->* _mfn)(); } }; @@ -227,7 +227,7 @@ public: explicit SecondConstMemFun1(MemberFN p) : _mfn(p) { } R operator()(std::pair pair, A arg) const { - return (pair.second.get() ->* _mfn)(arg); + return (pair.second.get() ->* _mfn)(arg); } }; @@ -242,7 +242,7 @@ public: explicit SecondConstVoidMemFun(MemberFN p) : _mfn(p) { } void operator()(std::pair pair) const { - (pair.second.get() ->* _mfn)(); + (pair.second.get() ->* _mfn)(); } }; @@ -257,7 +257,7 @@ public: explicit SecondConstVoidMemFun1(MemberFN p) : _mfn(p) { } void operator()(std::pair pair, A arg) const { - (pair.second.get() ->* _mfn)(arg); + (pair.second.get() ->* _mfn)(arg); } }; diff --git a/cpp/include/IceUtil/Handle.h b/cpp/include/IceUtil/Handle.h index c20616ec21f..0f48e2ee71b 100644 --- a/cpp/include/IceUtil/Handle.h +++ b/cpp/include/IceUtil/Handle.h @@ -29,13 +29,13 @@ public: T* get() const { - return _ptr; + return _ptr; } T* operator->() const { - if(!_ptr) - { + if(!_ptr) + { // // We don't throw directly NullHandleException here to // keep the code size of this method to a minimun (the @@ -43,16 +43,16 @@ public: // than just a function call). This maximises the chances // of inlining by compiler optimization. // - throwNullHandleException(__FILE__, __LINE__); - } + throwNullHandleException(__FILE__, __LINE__); + } - return _ptr; + return _ptr; } T& operator*() const { - if(!_ptr) - { + if(!_ptr) + { // // We don't throw directly NullHandleException here to // keep the code size of this method to a minimun (the @@ -60,20 +60,20 @@ public: // than just a function call). This maximises the chances // of inlining by compiler optimization. // - throwNullHandleException(__FILE__, __LINE__); - } + throwNullHandleException(__FILE__, __LINE__); + } - return *_ptr; + return *_ptr; } operator bool() const { - return _ptr ? true : false; + return _ptr ? true : false; } void swap(HandleBase& other) { - std::swap(_ptr, other._ptr); + std::swap(_ptr, other._ptr); } T* _ptr; @@ -96,12 +96,12 @@ inline bool operator==(const HandleBase& lhs, const HandleBase& rhs) U* r = rhs.get(); if(l && r) { - return *l == *r; + return *l == *r; } else { - return !l && !r; - } + return !l && !r; + } } template @@ -111,12 +111,12 @@ inline bool operator!=(const HandleBase& lhs, const HandleBase& rhs) U* r = rhs.get(); if(l && r) { - return *l != *r; + return *l != *r; } else { - return l || r; - } + return l || r; + } } template @@ -126,11 +126,11 @@ inline bool operator<(const HandleBase& lhs, const HandleBase& rhs) U* r = rhs.get(); if(l && r) { - return *l < *r; + return *l < *r; } else { - return !l && r; + return !l && r; } } @@ -141,111 +141,111 @@ public: Handle(T* p = 0) { - this->_ptr = p; + this->_ptr = p; - if(this->_ptr) - { - this->_ptr->__incRef(); - } + if(this->_ptr) + { + this->_ptr->__incRef(); + } } template Handle(const Handle& r) { - this->_ptr = r._ptr; + this->_ptr = r._ptr; - if(this->_ptr) - { - this->_ptr->__incRef(); - } + if(this->_ptr) + { + this->_ptr->__incRef(); + } } Handle(const Handle& r) { - this->_ptr = r._ptr; + this->_ptr = r._ptr; - if(this->_ptr) - { - this->_ptr->__incRef(); - } + if(this->_ptr) + { + this->_ptr->__incRef(); + } } ~Handle() { - if(this->_ptr) - { - this->_ptr->__decRef(); - } + if(this->_ptr) + { + this->_ptr->__decRef(); + } } Handle& operator=(T* p) { - if(this->_ptr != p) - { - if(p) - { - p->__incRef(); - } - - T* ptr = this->_ptr; - this->_ptr = p; - - if(ptr) - { - ptr->__decRef(); - } - } - return *this; + if(this->_ptr != p) + { + if(p) + { + p->__incRef(); + } + + T* ptr = this->_ptr; + this->_ptr = p; + + if(ptr) + { + ptr->__decRef(); + } + } + return *this; } template Handle& operator=(const Handle& r) { - if(this->_ptr != r._ptr) - { - if(r._ptr) - { - r._ptr->__incRef(); - } - - T* ptr = this->_ptr; - this->_ptr = r._ptr; - - if(ptr) - { - ptr->__decRef(); - } - } - return *this; + if(this->_ptr != r._ptr) + { + if(r._ptr) + { + r._ptr->__incRef(); + } + + T* ptr = this->_ptr; + this->_ptr = r._ptr; + + if(ptr) + { + ptr->__decRef(); + } + } + return *this; } Handle& operator=(const Handle& r) { - if(this->_ptr != r._ptr) - { - if(r._ptr) - { - r._ptr->__incRef(); - } - - T* ptr = this->_ptr; - this->_ptr = r._ptr; - - if(ptr) - { - ptr->__decRef(); - } - } - return *this; + if(this->_ptr != r._ptr) + { + if(r._ptr) + { + r._ptr->__incRef(); + } + + T* ptr = this->_ptr; + this->_ptr = r._ptr; + + if(ptr) + { + ptr->__decRef(); + } + } + return *this; } template static Handle dynamicCast(const HandleBase& r) { #ifdef __BCPLUSPLUS__ - return Handle(dynamic_cast(r._ptr)); + return Handle(dynamic_cast(r._ptr)); #else - return Handle(dynamic_cast(r._ptr)); + return Handle(dynamic_cast(r._ptr)); #endif } @@ -253,9 +253,9 @@ public: static Handle dynamicCast(Y* p) { #ifdef __BCPLUSPLUS__ - return Handle(dynamic_cast(p)); + return Handle(dynamic_cast(p)); #else - return Handle(dynamic_cast(p)); + return Handle(dynamic_cast(p)); #endif } }; diff --git a/cpp/include/IceUtil/InputUtil.h b/cpp/include/IceUtil/InputUtil.h index 89ce9990373..480147bffdd 100644 --- a/cpp/include/IceUtil/InputUtil.h +++ b/cpp/include/IceUtil/InputUtil.h @@ -37,8 +37,8 @@ ICE_UTIL_API Int64 strToInt64(const char*, char**, int); // // - return value == true indicates a successful conversion and result contains the converted value // - return value == false indicates an unsuccessful conversion: -// - result == 0 indicates that no digits were available for conversion -// - result == "Int64 Min" or result == "Int64 Max" indicate underflow or overflow. +// - result == 0 indicates that no digits were available for conversion +// - result == "Int64 Min" or result == "Int64 Max" indicate underflow or overflow. // ICE_UTIL_API bool stringToInt64(const std::string&, Int64&); diff --git a/cpp/include/IceUtil/Lock.h b/cpp/include/IceUtil/Lock.h index 9aaf24bcf56..5fdfbddcdd8 100644 --- a/cpp/include/IceUtil/Lock.h +++ b/cpp/include/IceUtil/Lock.h @@ -44,63 +44,63 @@ class LockT public: LockT(const T& mutex) : - _mutex(mutex) + _mutex(mutex) { - _mutex.lock(); - _acquired = true; + _mutex.lock(); + _acquired = true; } ~LockT() { - if (_acquired) - { - _mutex.unlock(); - } + if (_acquired) + { + _mutex.unlock(); + } } void acquire() const { - if (_acquired) - { - throw ThreadLockedException(__FILE__, __LINE__); - } - _mutex.lock(); - _acquired = true; + if (_acquired) + { + throw ThreadLockedException(__FILE__, __LINE__); + } + _mutex.lock(); + _acquired = true; } bool tryAcquire() const { - if (_acquired) - { - throw ThreadLockedException(__FILE__, __LINE__); - } - _acquired = _mutex.tryLock(); - return _acquired; + if (_acquired) + { + throw ThreadLockedException(__FILE__, __LINE__); + } + _acquired = _mutex.tryLock(); + return _acquired; } void release() const { - if (!_acquired) - { - throw ThreadLockedException(__FILE__, __LINE__); - } - _mutex.unlock(); - _acquired = false; + if (!_acquired) + { + throw ThreadLockedException(__FILE__, __LINE__); + } + _mutex.unlock(); + _acquired = false; } bool acquired() const { - return _acquired; + return _acquired; } protected: // TryLockT's contructor LockT(const T& mutex, bool) : - _mutex(mutex) + _mutex(mutex) { - _acquired = _mutex.tryLock(); + _acquired = _mutex.tryLock(); } private: @@ -126,7 +126,7 @@ class TryLockT : public LockT public: TryLockT(const T& mutex) : - LockT(mutex, true) + LockT(mutex, true) {} }; diff --git a/cpp/include/IceUtil/Monitor.h b/cpp/include/IceUtil/Monitor.h index 2e9fd0e456f..e64830e0979 100644 --- a/cpp/include/IceUtil/Monitor.h +++ b/cpp/include/IceUtil/Monitor.h @@ -89,11 +89,11 @@ IceUtil::Monitor::lock() const _mutex.lock(); if(_mutex.willUnlock()) { - // - // On the first mutex acquisition reset the number pending - // notifications. - // - _nnotify = 0; + // + // On the first mutex acquisition reset the number pending + // notifications. + // + _nnotify = 0; } } @@ -102,10 +102,10 @@ IceUtil::Monitor::unlock() const { if(_mutex.willUnlock()) { - // - // Perform any pending notifications. - // - notifyImpl(_nnotify); + // + // Perform any pending notifications. + // + notifyImpl(_nnotify); } _mutex.unlock(); @@ -113,10 +113,10 @@ IceUtil::Monitor::unlock() const int nnotify = _nnotify; if(_mutex.unlock()) { - // - // Perform any pending notifications. - // - notifyImpl(nnotify); + // + // Perform any pending notifications. + // + notifyImpl(nnotify); } */ } @@ -127,11 +127,11 @@ IceUtil::Monitor::tryLock() const bool result = _mutex.tryLock(); if(result && _mutex.willUnlock()) { - // - // On the first mutex acquisition reset the number pending - // notifications. - // - _nnotify = 0; + // + // On the first mutex acquisition reset the number pending + // notifications. + // + _nnotify = 0; } return result; } @@ -149,15 +149,15 @@ IceUtil::Monitor::wait() const // try { - _cond.waitImpl(_mutex); - // - // Reset the nnotify count once wait() returns. - // + _cond.waitImpl(_mutex); + // + // Reset the nnotify count once wait() returns. + // } catch(...) { - _nnotify = 0; - throw; + _nnotify = 0; + throw; } _nnotify = 0; @@ -177,16 +177,16 @@ IceUtil::Monitor::timedWait(const Time& timeout) const // try { - rc = _cond.timedWaitImpl(_mutex, timeout); + rc = _cond.timedWaitImpl(_mutex, timeout); - // - // Reset the nnotify count once wait() returns. - // + // + // Reset the nnotify count once wait() returns. + // } catch(...) { - _nnotify = 0; - throw; + _nnotify = 0; + throw; } _nnotify = 0; @@ -202,7 +202,7 @@ IceUtil::Monitor::notify() // if(_nnotify != -1) { - ++_nnotify; + ++_nnotify; } } @@ -224,25 +224,25 @@ IceUtil::Monitor::notifyImpl(int nnotify) const // if(nnotify != 0) { - // - // -1 means notifyAll. - // - if(nnotify == -1) - { - _cond.broadcast(); - return; - } - else - { - // - // Otherwise notify n times. - // - while(nnotify > 0) - { - _cond.signal(); - --nnotify; - } - } + // + // -1 means notifyAll. + // + if(nnotify == -1) + { + _cond.broadcast(); + return; + } + else + { + // + // Otherwise notify n times. + // + while(nnotify > 0) + { + _cond.signal(); + --nnotify; + } + } } } diff --git a/cpp/include/IceUtil/Mutex.h b/cpp/include/IceUtil/Mutex.h index da2c36b9bca..ca08324d28b 100644 --- a/cpp/include/IceUtil/Mutex.h +++ b/cpp/include/IceUtil/Mutex.h @@ -87,7 +87,7 @@ private: #else struct LockState { - pthread_mutex_t* mutex; + pthread_mutex_t* mutex; }; #endif @@ -140,12 +140,12 @@ Mutex::tryLock() const { if(!TryEnterCriticalSection(&_mutex)) { - return false; + return false; } if(_mutex.RecursionCount > 1) { - LeaveCriticalSection(&_mutex); - throw ThreadLockedException(__FILE__, __LINE__); + LeaveCriticalSection(&_mutex); + throw ThreadLockedException(__FILE__, __LINE__); } return true; } @@ -178,7 +178,7 @@ Mutex::Mutex() : _mutex = CreateMutex(0, false, 0); if(_mutex == 0) { - throw ThreadSyscallException(__FILE__, __LINE__, GetLastError()); + throw ThreadSyscallException(__FILE__, __LINE__, GetLastError()); } } @@ -188,7 +188,7 @@ Mutex::~Mutex() BOOL rc = CloseHandle(_mutex); if(rc == 0) { - throw ThreadSyscallException(__FILE__, __LINE__, GetLastError()); + throw ThreadSyscallException(__FILE__, __LINE__, GetLastError()); } } @@ -198,14 +198,14 @@ Mutex::lock() const DWORD rc = WaitForSingleObject(_mutex, INFINITE); if(rc != WAIT_OBJECT_0) { - if(rc == WAIT_FAILED) - { - throw ThreadSyscallException(__FILE__, __LINE__, GetLastError()); - } - else - { - throw ThreadSyscallException(__FILE__, __LINE__, 0); - } + if(rc == WAIT_FAILED) + { + throw ThreadSyscallException(__FILE__, __LINE__, GetLastError()); + } + else + { + throw ThreadSyscallException(__FILE__, __LINE__, 0); + } } _recursionCount++; } @@ -216,18 +216,18 @@ Mutex::tryLock() const DWORD rc = WaitForSingleObject(_mutex, 0); if(rc != WAIT_OBJECT_0) { - return false; + return false; } else if(_recursionCount == 1) { - _recursionCount++; - unlock(); - throw ThreadLockedException(__FILE__, __LINE__); + _recursionCount++; + unlock(); + throw ThreadLockedException(__FILE__, __LINE__); } else { - _recursionCount++; - return true; + _recursionCount++; + return true; } } @@ -238,7 +238,7 @@ Mutex::unlock() const BOOL rc = ReleaseMutex(_mutex); if(rc == 0) { - throw ThreadSyscallException(__FILE__, __LINE__, GetLastError()); + throw ThreadSyscallException(__FILE__, __LINE__, GetLastError()); } } @@ -287,7 +287,7 @@ Mutex::Mutex() if(rc != 0) { - throw ThreadSyscallException(__FILE__, __LINE__, rc); + throw ThreadSyscallException(__FILE__, __LINE__, rc); } } @@ -306,13 +306,13 @@ Mutex::lock() const if(rc != 0) { if(rc == EDEADLK) - { - throw ThreadLockedException(__FILE__, __LINE__); - } - else - { - throw ThreadSyscallException(__FILE__, __LINE__, rc); - } + { + throw ThreadLockedException(__FILE__, __LINE__); + } + else + { + throw ThreadSyscallException(__FILE__, __LINE__, rc); + } } } @@ -323,13 +323,13 @@ Mutex::tryLock() const if(rc != 0 && rc != EBUSY) { if(rc == EDEADLK) - { - throw ThreadLockedException(__FILE__, __LINE__); - } - else - { - throw ThreadSyscallException(__FILE__, __LINE__, rc); - } + { + throw ThreadLockedException(__FILE__, __LINE__); + } + else + { + throw ThreadSyscallException(__FILE__, __LINE__, rc); + } } return (rc == 0); } @@ -340,7 +340,7 @@ Mutex::unlock() const int rc = pthread_mutex_unlock(&_mutex); if(rc != 0) { - throw ThreadSyscallException(__FILE__, __LINE__, rc); + throw ThreadSyscallException(__FILE__, __LINE__, rc); } } diff --git a/cpp/include/IceUtil/Options.h b/cpp/include/IceUtil/Options.h index f7af12c47a5..ef14133eb7e 100755 --- a/cpp/include/IceUtil/Options.h +++ b/cpp/include/IceUtil/Options.h @@ -87,10 +87,10 @@ private: struct OptionDetails : public IceUtil::Shared { - LengthType length; - ArgType arg; + LengthType length; + ArgType arg; RepeatType repeat; - bool hasDefault; + bool hasDefault; }; typedef IceUtil::Handle ODPtr; diff --git a/cpp/include/IceUtil/OutputUtil.h b/cpp/include/IceUtil/OutputUtil.h index c6b6c021f89..ec86158f1d1 100644 --- a/cpp/include/IceUtil/OutputUtil.h +++ b/cpp/include/IceUtil/OutputUtil.h @@ -127,7 +127,7 @@ operator<<(Output& out, const std::vector& val) { for(typename std::vector::const_iterator p = val.begin(); p != val.end(); ++p) { - out << *p; + out << *p; } return out; } @@ -145,7 +145,7 @@ operator<<(Output& out, std::vector& val) { for(typename std::vector::const_iterator p = val.begin(); p != val.end(); ++p) { - out << *p; + out << *p; } return out; } diff --git a/cpp/include/IceUtil/RWRecMutex.h b/cpp/include/IceUtil/RWRecMutex.h index bdcefeb676d..396aae37cf3 100644 --- a/cpp/include/IceUtil/RWRecMutex.h +++ b/cpp/include/IceUtil/RWRecMutex.h @@ -37,83 +37,83 @@ class RLockT public: RLockT(const T& mutex) : - _mutex(mutex) + _mutex(mutex) { - _mutex.readLock(); - _acquired = true; + _mutex.readLock(); + _acquired = true; } ~RLockT() { - if (_acquired) - { - _mutex.unlock(); - } + if (_acquired) + { + _mutex.unlock(); + } } void acquire() const { - if (_acquired) - { - throw ThreadLockedException(__FILE__, __LINE__); - } - _mutex.readLock(); - _acquired = true; + if (_acquired) + { + throw ThreadLockedException(__FILE__, __LINE__); + } + _mutex.readLock(); + _acquired = true; } bool tryAcquire() const { - if (_acquired) - { - throw ThreadLockedException(__FILE__, __LINE__); - } - _acquired = _mutex.tryReadLock(); - return _acquired; + if (_acquired) + { + throw ThreadLockedException(__FILE__, __LINE__); + } + _acquired = _mutex.tryReadLock(); + return _acquired; } bool timedAcquire(const Time& timeout) const { - if (_acquired) - { - throw ThreadLockedException(__FILE__, __LINE__); - } - _acquired = _mutex.timedReadLock(timeout); - return _acquired; + if (_acquired) + { + throw ThreadLockedException(__FILE__, __LINE__); + } + _acquired = _mutex.timedReadLock(timeout); + return _acquired; } void release() const { - if (!_acquired) - { - throw ThreadLockedException(__FILE__, __LINE__); - } - _mutex.unlock(); - _acquired = false; + if (!_acquired) + { + throw ThreadLockedException(__FILE__, __LINE__); + } + _mutex.unlock(); + _acquired = false; } bool acquired() const { - return _acquired; + return _acquired; } void upgrade() const { - _mutex.upgrade(); + _mutex.upgrade(); } bool timedUpgrade(const Time& timeout) const { - return _mutex.timedUpgrade(timeout); + return _mutex.timedUpgrade(timeout); } void downgrade() const { - _mutex.downgrade(); + _mutex.downgrade(); } protected: @@ -121,16 +121,16 @@ protected: // TryRLockT's constructors RLockT(const T& mutex, bool) : - _mutex(mutex) + _mutex(mutex) { - _acquired = _mutex.tryReadLock(); + _acquired = _mutex.tryReadLock(); } RLockT(const T& mutex, const Time& timeout) : - _mutex(mutex) + _mutex(mutex) { - _acquired = _mutex.timedReadLock(timeout); + _acquired = _mutex.timedReadLock(timeout); } @@ -151,12 +151,12 @@ class TryRLockT : public RLockT public: TryRLockT(const T& mutex) : - RLockT(mutex, true) + RLockT(mutex, true) { } TryRLockT(const T& mutex, const Time& timeout) : - RLockT(mutex, timeout) + RLockT(mutex, timeout) { } }; @@ -167,63 +167,63 @@ class WLockT public: WLockT(const T& mutex) : - _mutex(mutex) + _mutex(mutex) { - _mutex.writeLock(); - _acquired = true; + _mutex.writeLock(); + _acquired = true; } ~WLockT() { - if (_acquired) - { - _mutex.unlock(); - } + if (_acquired) + { + _mutex.unlock(); + } } void acquire() const { - if (_acquired) - { - throw ThreadLockedException(__FILE__, __LINE__); - } - _mutex.writeLock(); - _acquired = true; + if (_acquired) + { + throw ThreadLockedException(__FILE__, __LINE__); + } + _mutex.writeLock(); + _acquired = true; } bool tryAcquire() const { - if (_acquired) - { - throw ThreadLockedException(__FILE__, __LINE__); - } - _acquired = _mutex.tryWriteLock(); - return _acquired; + if (_acquired) + { + throw ThreadLockedException(__FILE__, __LINE__); + } + _acquired = _mutex.tryWriteLock(); + return _acquired; } bool timedAcquire(const Time& timeout) const { - if (_acquired) - { - throw ThreadLockedException(__FILE__, __LINE__); - } - _acquired = _mutex.timedWriteLock(timeout); - return _acquired; + if (_acquired) + { + throw ThreadLockedException(__FILE__, __LINE__); + } + _acquired = _mutex.timedWriteLock(timeout); + return _acquired; } void release() const { - if (!_acquired) - { - throw ThreadLockedException(__FILE__, __LINE__); - } - _mutex.unlock(); - _acquired = false; + if (!_acquired) + { + throw ThreadLockedException(__FILE__, __LINE__); + } + _mutex.unlock(); + _acquired = false; } bool acquired() const { - return _acquired; + return _acquired; } protected: @@ -231,15 +231,15 @@ protected: // TryWLockT's constructor WLockT(const T& mutex, bool) : - _mutex(mutex) + _mutex(mutex) { - _acquired = _mutex.tryWriteLock(); + _acquired = _mutex.tryWriteLock(); } WLockT(const T& mutex, const Time& timeout) : - _mutex(mutex) + _mutex(mutex) { - _acquired = _mutex.timedWriteLock(timeout); + _acquired = _mutex.timedWriteLock(timeout); } private: @@ -259,12 +259,12 @@ class TryWLockT : public WLockT public: TryWLockT(const T& mutex) : - WLockT(mutex, true) + WLockT(mutex, true) { } TryWLockT(const T& mutex, const Time& timeout) : - WLockT(mutex, timeout) + WLockT(mutex, timeout) { } }; diff --git a/cpp/include/IceUtil/RecMutex.h b/cpp/include/IceUtil/RecMutex.h index 898123834c4..5c89feb21b2 100644 --- a/cpp/include/IceUtil/RecMutex.h +++ b/cpp/include/IceUtil/RecMutex.h @@ -78,13 +78,13 @@ private: #ifdef _WIN32 struct LockState { - int count; + int count; }; #else struct LockState { - pthread_mutex_t* mutex; - int count; + pthread_mutex_t* mutex; + int count; }; #endif diff --git a/cpp/include/IceUtil/ScopedArray.h b/cpp/include/IceUtil/ScopedArray.h index edc033f0c8c..52be7c0ae12 100644 --- a/cpp/include/IceUtil/ScopedArray.h +++ b/cpp/include/IceUtil/ScopedArray.h @@ -28,25 +28,25 @@ public: ~ScopedArray() { if(_ptr != 0) - { - delete[] _ptr; - } + { + delete[] _ptr; + } } void reset(T* ptr = 0) { - assert(ptr == 0 || ptr != _ptr); + assert(ptr == 0 || ptr != _ptr); if(_ptr != 0) - { - delete[] _ptr; - } - _ptr = ptr; + { + delete[] _ptr; + } + _ptr = ptr; } T& operator[](size_t i) const { - assert(_ptr != 0); - assert(i >= 0); + assert(_ptr != 0); + assert(i >= 0); return _ptr[i]; } @@ -58,8 +58,8 @@ public: void swap(ScopedArray& a) { T* tmp = a._ptr; - a._ptr = _ptr; - _ptr = tmp; + a._ptr = _ptr; + _ptr = tmp; } private: diff --git a/cpp/include/IceUtil/Shared.h b/cpp/include/IceUtil/Shared.h index 8abb33f0c34..c80b6b35c5b 100644 --- a/cpp/include/IceUtil/Shared.h +++ b/cpp/include/IceUtil/Shared.h @@ -62,9 +62,9 @@ inline void ice_atomic_set(ice_atomic_t* v, int i) inline void ice_atomic_inc(ice_atomic_t *v) { __asm__ __volatile__( - "lock ; incl %0" - :"=m" (v->counter) - :"m" (v->counter)); + "lock ; incl %0" + :"=m" (v->counter) + :"m" (v->counter)); } /** @@ -81,9 +81,9 @@ inline int ice_atomic_dec_and_test(ice_atomic_t *v) { unsigned char c; __asm__ __volatile__( - "lock ; decl %0; sete %1" - :"=m" (v->counter), "=qm" (c) - :"m" (v->counter) : "memory"); + "lock ; decl %0; sete %1" + :"=m" (v->counter), "=qm" (c) + :"m" (v->counter) : "memory"); return c != 0; } @@ -98,10 +98,10 @@ inline int ice_atomic_exchange_add(int i, ice_atomic_t* v) { int tmp = i; __asm__ __volatile__( - "lock ; xadd %0,(%2)" - :"+r"(tmp), "=m"(v->counter) - :"r"(v), "m"(v->counter) - : "memory"); + "lock ; xadd %0,(%2)" + :"+r"(tmp), "=m"(v->counter) + :"r"(v), "m"(v->counter) + : "memory"); return tmp + i; } @@ -148,31 +148,31 @@ public: void __incRef() { - assert(_ref >= 0); - ++_ref; + assert(_ref >= 0); + ++_ref; } void __decRef() { - assert(_ref > 0); - if(--_ref == 0) - { - if(!_noDelete) - { - _noDelete = true; - delete this; - } - } + assert(_ref > 0); + if(--_ref == 0) + { + if(!_noDelete) + { + _noDelete = true; + delete this; + } + } } int __getRef() const { - return _ref; + return _ref; } void __setNoDelete(bool b) { - _noDelete = b; + _noDelete = b; } private: @@ -200,49 +200,49 @@ public: void __incRef() { #if defined(_WIN32) - assert(InterlockedExchangeAdd(&_ref, 0) >= 0); - InterlockedIncrement(&_ref); + assert(InterlockedExchangeAdd(&_ref, 0) >= 0); + InterlockedIncrement(&_ref); #elif defined(ICE_HAS_ATOMIC_FUNCTIONS) - assert(ice_atomic_exchange_add(0, &_ref) >= 0); - ice_atomic_inc(&_ref); + assert(ice_atomic_exchange_add(0, &_ref) >= 0); + ice_atomic_inc(&_ref); #else - _mutex.lock(); - assert(_ref >= 0); - ++_ref; - _mutex.unlock(); + _mutex.lock(); + assert(_ref >= 0); + ++_ref; + _mutex.unlock(); #endif } void __decRef() { #if defined(_WIN32) - assert(InterlockedExchangeAdd(&_ref, 0) > 0); - if(InterlockedDecrement(&_ref) == 0 && !_noDelete) - { - _noDelete = true; - delete this; - } + assert(InterlockedExchangeAdd(&_ref, 0) > 0); + if(InterlockedDecrement(&_ref) == 0 && !_noDelete) + { + _noDelete = true; + delete this; + } #elif defined(ICE_HAS_ATOMIC_FUNCTIONS) - assert(ice_atomic_exchange_add(0, &_ref) > 0); - if(ice_atomic_dec_and_test(&_ref) && !_noDelete) - { - _noDelete = true; - delete this; - } + assert(ice_atomic_exchange_add(0, &_ref) > 0); + if(ice_atomic_dec_and_test(&_ref) && !_noDelete) + { + _noDelete = true; + delete this; + } #else - _mutex.lock(); - bool doDelete = false; - assert(_ref > 0); - if(--_ref == 0) - { - doDelete = !_noDelete; - _noDelete = true; - } - _mutex.unlock(); - if(doDelete) - { - delete this; - } + _mutex.lock(); + bool doDelete = false; + assert(_ref > 0); + if(--_ref == 0) + { + doDelete = !_noDelete; + _noDelete = true; + } + _mutex.unlock(); + if(doDelete) + { + delete this; + } #endif } diff --git a/cpp/include/IceUtil/StaticMutex.h b/cpp/include/IceUtil/StaticMutex.h index bf67e79635e..4bf6ccf2fad 100644 --- a/cpp/include/IceUtil/StaticMutex.h +++ b/cpp/include/IceUtil/StaticMutex.h @@ -95,7 +95,7 @@ private: #else struct LockState { - pthread_mutex_t* mutex; + pthread_mutex_t* mutex; }; #endif @@ -149,7 +149,7 @@ StaticMutex::lock() const { if(!initialized()) { - initialize(); + initialize(); } EnterCriticalSection(_mutex); assert(_mutex->RecursionCount == 1); @@ -160,16 +160,16 @@ StaticMutex::tryLock() const { if(!initialized()) { - initialize(); + initialize(); } if(!TryEnterCriticalSection(_mutex)) { - return false; + return false; } if(_mutex->RecursionCount > 1) { - LeaveCriticalSection(_mutex); - throw ThreadLockedException(__FILE__, __LINE__); + LeaveCriticalSection(_mutex); + throw ThreadLockedException(__FILE__, __LINE__); } return true; } @@ -195,7 +195,7 @@ StaticMutex::lock(LockState&) const { if(!initialized()) { - initialize(); + initialize(); } EnterCriticalSection(_mutex); } @@ -207,20 +207,20 @@ StaticMutex::lock() const { if(!initialized()) { - initialize(); + initialize(); } DWORD rc = WaitForSingleObject(_mutex, INFINITE); if(rc != WAIT_OBJECT_0) { - if(rc == WAIT_FAILED) - { - throw ThreadSyscallException(__FILE__, __LINE__, GetLastError()); - } - else - { - throw ThreadSyscallException(__FILE__, __LINE__, 0); - } + if(rc == WAIT_FAILED) + { + throw ThreadSyscallException(__FILE__, __LINE__, GetLastError()); + } + else + { + throw ThreadSyscallException(__FILE__, __LINE__, 0); + } } _recursionCount++; assert(_recursionCount == 1); @@ -231,24 +231,24 @@ StaticMutex::tryLock() const { if(!initialized()) { - initialize(); + initialize(); } DWORD rc = WaitForSingleObject(_mutex, 0); if(rc != WAIT_OBJECT_0) { - return false; + return false; } else if(_recursionCount == 1) { - _recursionCount++; - unlock(); - throw ThreadLockedException(__FILE__, __LINE__); + _recursionCount++; + unlock(); + throw ThreadLockedException(__FILE__, __LINE__); } else { - _recursionCount++; - return true; + _recursionCount++; + return true; } } @@ -259,7 +259,7 @@ StaticMutex::unlock() const BOOL rc = ReleaseMutex(_mutex); if(rc == 0) { - throw ThreadSyscallException(__FILE__, __LINE__, GetLastError()); + throw ThreadSyscallException(__FILE__, __LINE__, GetLastError()); } } @@ -286,13 +286,13 @@ StaticMutex::lock() const if(rc != 0) { if(rc == EDEADLK) - { - throw ThreadLockedException(__FILE__, __LINE__); - } - else - { - throw ThreadSyscallException(__FILE__, __LINE__, rc); - } + { + throw ThreadLockedException(__FILE__, __LINE__); + } + else + { + throw ThreadSyscallException(__FILE__, __LINE__, rc); + } } } @@ -303,13 +303,13 @@ StaticMutex::tryLock() const if(rc != 0 && rc != EBUSY) { if(rc == EDEADLK) - { - throw ThreadLockedException(__FILE__, __LINE__); - } - else - { - throw ThreadSyscallException(__FILE__, __LINE__, rc); - } + { + throw ThreadLockedException(__FILE__, __LINE__); + } + else + { + throw ThreadSyscallException(__FILE__, __LINE__, rc); + } } return (rc == 0); } @@ -320,7 +320,7 @@ StaticMutex::unlock() const int rc = pthread_mutex_unlock(&_mutex); if(rc != 0) { - throw ThreadSyscallException(__FILE__, __LINE__, rc); + throw ThreadSyscallException(__FILE__, __LINE__, rc); } } diff --git a/cpp/include/IceUtil/Thread.h b/cpp/include/IceUtil/Thread.h index ce70f933336..f46182b2476 100644 --- a/cpp/include/IceUtil/Thread.h +++ b/cpp/include/IceUtil/Thread.h @@ -140,8 +140,8 @@ protected: #endif private: - Thread(const Thread&); // Copying is forbidden - void operator=(const Thread&); // Assignment is forbidden + Thread(const Thread&); // Copying is forbidden + void operator=(const Thread&); // Assignment is forbidden }; typedef Handle ThreadPtr; diff --git a/cpp/include/IceUtil/Time.h b/cpp/include/IceUtil/Time.h index 857c9a680d0..b2b5981776a 100644 --- a/cpp/include/IceUtil/Time.h +++ b/cpp/include/IceUtil/Time.h @@ -51,142 +51,142 @@ public: Time operator-() const { - return Time(-_usec); + return Time(-_usec); } Time operator-(const Time& rhs) const { - return Time(_usec - rhs._usec); + return Time(_usec - rhs._usec); } Time operator+(const Time& rhs) const { - return Time(_usec + rhs._usec); + return Time(_usec + rhs._usec); } Time& operator+=(const Time& rhs) { - _usec += rhs._usec; - return *this; + _usec += rhs._usec; + return *this; } Time& operator-=(const Time& rhs) { - _usec -= rhs._usec; - return *this; + _usec -= rhs._usec; + return *this; } bool operator<(const Time& rhs) const { - return _usec < rhs._usec; + return _usec < rhs._usec; } bool operator<=(const Time& rhs) const { - return _usec <= rhs._usec; + return _usec <= rhs._usec; } bool operator>(const Time& rhs) const { - return _usec > rhs._usec; + return _usec > rhs._usec; } bool operator>=(const Time& rhs) const { - return _usec >= rhs._usec; + return _usec >= rhs._usec; } bool operator==(const Time& rhs) const { - return _usec == rhs._usec; + return _usec == rhs._usec; } bool operator!=(const Time& rhs) const { - return _usec != rhs._usec; + return _usec != rhs._usec; } double operator/(const Time& rhs) const { - return (double)_usec / (double)rhs._usec; + return (double)_usec / (double)rhs._usec; } Time& operator*=(int rhs) { - _usec *= rhs; - return *this; + _usec *= rhs; + return *this; } Time operator*(int rhs) const { - Time t; - t._usec = _usec * rhs; - return t; + Time t; + t._usec = _usec * rhs; + return t; } Time& operator/=(int rhs) { - _usec /= rhs; - return *this; + _usec /= rhs; + return *this; } Time operator/(int rhs) const { - Time t; - t._usec = _usec / rhs; - return t; + Time t; + t._usec = _usec / rhs; + return t; } Time& operator*=(Int64 rhs) { - _usec *= rhs; - return *this; + _usec *= rhs; + return *this; } Time operator*(Int64 rhs) const { - Time t; - t._usec = _usec * rhs; - return t; + Time t; + t._usec = _usec * rhs; + return t; } Time& operator/=(Int64 rhs) { - _usec /= rhs; - return *this; + _usec /= rhs; + return *this; } Time operator/(Int64 rhs) const { - Time t; - t._usec = _usec / rhs; - return t; + Time t; + t._usec = _usec / rhs; + return t; } Time& operator*=(double rhs) { - _usec = static_cast(static_cast(_usec) * rhs); - return *this; + _usec = static_cast(static_cast(_usec) * rhs); + return *this; } Time operator*(double rhs) const { - Time t; - t._usec = static_cast(static_cast(_usec) * rhs); - return t; + Time t; + t._usec = static_cast(static_cast(_usec) * rhs); + return t; } Time& operator/=(double rhs) { - _usec = static_cast(static_cast(_usec) / rhs); - return *this; + _usec = static_cast(static_cast(_usec) / rhs); + return *this; } Time operator/(double rhs) const { - Time t; - t._usec = static_cast(static_cast(_usec) / rhs); - return t; + Time t; + t._usec = static_cast(static_cast(_usec) / rhs); + return t; } private: diff --git a/cpp/include/IceUtil/Unicode.h b/cpp/include/IceUtil/Unicode.h index caebf5b2a5d..03c95a3fa56 100644 --- a/cpp/include/IceUtil/Unicode.h +++ b/cpp/include/IceUtil/Unicode.h @@ -97,10 +97,10 @@ ICE_UTIL_API std::wstring stringToWstring(const std::string&); enum ConversionResult { - conversionOK, /* conversion successful */ - sourceExhausted, /* partial character in source, but hit end */ - targetExhausted, /* insuff. room in target for conversion */ - sourceIllegal /* source sequence is illegal/malformed */ + conversionOK, /* conversion successful */ + sourceExhausted, /* partial character in source, but hit end */ + targetExhausted, /* insuff. room in target for conversion */ + sourceIllegal /* source sequence is illegal/malformed */ }; @@ -117,15 +117,15 @@ isLegalUTF8Sequence(const Byte* source, const Byte* end); ICE_UTIL_API ConversionResult convertUTFWstringToUTF8(const wchar_t*& sourceStart, const wchar_t* sourceEnd, - Byte*& targetStart, Byte* targetEnd, ConversionFlags flags); + Byte*& targetStart, Byte* targetEnd, ConversionFlags flags); ICE_UTIL_API ConversionResult convertUTF8ToUTFWstring(const Byte*& sourceStart, const Byte* sourceEnd, - wchar_t*& targetStart, wchar_t* targetEnd, ConversionFlags flags); + wchar_t*& targetStart, wchar_t* targetEnd, ConversionFlags flags); ICE_UTIL_API ConversionResult convertUTF8ToUTFWstring(const Byte*& sourceStart, const Byte* sourceEnd, - std::wstring& target, ConversionFlags flags); + std::wstring& target, ConversionFlags flags); diff --git a/cpp/include/Slice/CPlusPlusUtil.h b/cpp/include/Slice/CPlusPlusUtil.h index ae4af4cae89..7fb3f900a4c 100644 --- a/cpp/include/Slice/CPlusPlusUtil.h +++ b/cpp/include/Slice/CPlusPlusUtil.h @@ -36,14 +36,14 @@ SLICE_API std::string operationModeToString(Operation::Mode); SLICE_API std::string fixKwd(const std::string&); SLICE_API void writeMarshalUnmarshalCode(::IceUtil::Output&, const TypePtr&, const std::string&, bool, - const std::string& = "", bool = true, const StringList& = StringList(), - bool = false); + const std::string& = "", bool = true, const StringList& = StringList(), + bool = false); SLICE_API void writeMarshalCode(::IceUtil::Output&, const ParamDeclList&, const TypePtr&, - const StringList&, bool = false); + const StringList&, bool = false); SLICE_API void writeUnmarshalCode(::IceUtil::Output&, const ParamDeclList&, const TypePtr&, - const StringList&, bool = false); + const StringList&, bool = false); SLICE_API void writeAllocateCode(::IceUtil::Output&, const ParamDeclList&, const TypePtr&, - const StringList&, bool = false, bool = false); + const StringList&, bool = false, bool = false); SLICE_API void writeStreamMarshalUnmarshalCode(::IceUtil::Output&, const TypePtr&, const std::string&, bool, const std::string& = "", bool = false, const StringList& = StringList()); SLICE_API std::string findMetaData(const StringList&, bool); diff --git a/cpp/include/Slice/CsUtil.h b/cpp/include/Slice/CsUtil.h index 90a53540d51..28c8b577c87 100644 --- a/cpp/include/Slice/CsUtil.h +++ b/cpp/include/Slice/CsUtil.h @@ -74,7 +74,7 @@ private: void validate(const ContainedPtr&); StringSet _history; - bool _globalMetaDataDone; + bool _globalMetaDataDone; }; }; diff --git a/cpp/include/Slice/JavaUtil.h b/cpp/include/Slice/JavaUtil.h index decc474943b..75bc163a1f1 100644 --- a/cpp/include/Slice/JavaUtil.h +++ b/cpp/include/Slice/JavaUtil.h @@ -115,14 +115,14 @@ protected: // to typeToString. // std::string typeToObjectString(const TypePtr&, TypeMode, const std::string& = std::string(), - const StringList& = StringList(), bool = true) const; + const StringList& = StringList(), bool = true) const; // // Generate code to marshal or unmarshal a type. // void writeMarshalUnmarshalCode(::IceUtil::Output&, const std::string&, const TypePtr&, const std::string&, bool, int&, bool = false, const StringList& = StringList(), - const std::string& patchParams = ""); + const std::string& patchParams = ""); // // Generate code to marshal or unmarshal a dictionary type. @@ -143,7 +143,7 @@ protected: // void writeStreamMarshalUnmarshalCode(::IceUtil::Output&, const std::string&, const TypePtr&, const std::string&, bool, int&, bool = false, const StringList& = StringList(), - const std::string& patchParams = ""); + const std::string& patchParams = ""); // // Generate code to marshal or unmarshal a dictionary type using the public stream API. @@ -179,9 +179,9 @@ protected: // the default mapping was used. // bool getDictionaryTypes(const DictionaryPtr&, const std::string&, const StringList&, - std::string&, std::string&) const; + std::string&, std::string&) const; bool getSequenceTypes(const SequencePtr&, const std::string&, const StringList&, - std::string&, std::string&) const; + std::string&, std::string&) const; virtual JavaOutput* createOutput(); @@ -212,8 +212,8 @@ private: private: StringList getMetaData(const ContainedPtr&); - void validateType(const SyntaxTreeBasePtr&, const StringList&, const std::string&, const std::string&); - void validateGetSet(const SyntaxTreeBasePtr&, const StringList&, const std::string&, const std::string&); + void validateType(const SyntaxTreeBasePtr&, const StringList&, const std::string&, const std::string&); + void validateGetSet(const SyntaxTreeBasePtr&, const StringList&, const std::string&, const std::string&); StringSet _history; }; diff --git a/cpp/include/Slice/Parser.h b/cpp/include/Slice/Parser.h index d13965b46ad..d903cae03b0 100644 --- a/cpp/include/Slice/Parser.h +++ b/cpp/include/Slice/Parser.h @@ -283,17 +283,17 @@ public: enum Kind { - KindByte, - KindBool, - KindShort, - KindInt, - KindLong, - KindFloat, - KindDouble, - KindString, - KindObject, - KindObjectProxy, - KindLocalObject + KindByte, + KindBool, + KindShort, + KindInt, + KindLong, + KindFloat, + KindDouble, + KindString, + KindObject, + KindObjectProxy, + KindLocalObject }; virtual bool isLocal() const; @@ -343,18 +343,18 @@ public: enum ContainedType { - ContainedTypeSequence, - ContainedTypeDictionary, - ContainedTypeEnum, - ContainedTypeEnumerator, - ContainedTypeModule, - ContainedTypeClass, - ContainedTypeException, - ContainedTypeStruct, - ContainedTypeOperation, - ContainedTypeParamDecl, - ContainedTypeDataMember, - ContainedTypeConstant + ContainedTypeSequence, + ContainedTypeDictionary, + ContainedTypeEnum, + ContainedTypeEnumerator, + ContainedTypeModule, + ContainedTypeClass, + ContainedTypeException, + ContainedTypeStruct, + ContainedTypeOperation, + ContainedTypeParamDecl, + ContainedTypeDataMember, + ContainedTypeConstant }; virtual ContainedType containedType() const = 0; @@ -396,11 +396,11 @@ public: StructPtr createStruct(const std::string&, bool); SequencePtr createSequence(const std::string&, const TypePtr&, const StringList&, bool); DictionaryPtr createDictionary(const std::string&, const TypePtr&, const StringList&, const TypePtr&, - const StringList&, bool); + const StringList&, bool); EnumPtr createEnum(const std::string&, bool); EnumeratorPtr createEnumerator(const std::string&); ConstPtr createConst(const std::string, const TypePtr&, const StringList&, const SyntaxTreeBasePtr&, - const std::string&); + const std::string&); TypeList lookupType(const std::string&, bool = true); TypeList lookupTypeNoBuiltin(const std::string&, bool = true); ContainedList lookupContained(const std::string&, bool = true); @@ -543,9 +543,9 @@ public: // enum Mode { - Normal, - Nonmutating, - Idempotent + Normal, + Nonmutating, + Idempotent }; TypePtr returnType() const; @@ -762,7 +762,7 @@ public: protected: Dictionary(const ContainerPtr&, const std::string&, const TypePtr&, const StringList&, const TypePtr&, - const StringList&, bool); + const StringList&, bool); friend class Container; TypePtr _keyType; @@ -839,7 +839,7 @@ public: static bool isLegalType(const std::string&, const TypePtr&, const UnitPtr&); static bool typesAreCompatible(const std::string&, const TypePtr&, - const SyntaxTreeBasePtr&, const std::string&, const UnitPtr&); + const SyntaxTreeBasePtr&, const std::string&, const UnitPtr&); static bool isInRange(const std::string&, const TypePtr&, const std::string&, const UnitPtr&); protected: diff --git a/cpp/include/Slice/VbUtil.h b/cpp/include/Slice/VbUtil.h index 704caf8c743..62939d78b23 100644 --- a/cpp/include/Slice/VbUtil.h +++ b/cpp/include/Slice/VbUtil.h @@ -72,7 +72,7 @@ private: void validate(const ContainedPtr&); StringSet _history; - bool _globalMetaDataDone; + bool _globalMetaDataDone; }; }; diff --git a/cpp/install/common/components.py b/cpp/install/common/components.py index 7f2561ce008..63bd8dbaa10 100755 --- a/cpp/install/common/components.py +++ b/cpp/install/common/components.py @@ -9,350 +9,350 @@ def listFileLists(): cfg = ConfigParser.SafeConfigParser() cfg.read("./components/components.ini") for f in cfg.sections(): - try: - if cfg.getint(f, "active") == 1: - for item, value in cfg.items(f): - if item.startswith("filelist"): - print value - except ConfigParser.NoOptionError: - continue + try: + if cfg.getint(f, "active") == 1: + for item, value in cfg.items(f): + if item.startswith("filelist"): + print value + except ConfigParser.NoOptionError: + continue class StageFileError: """Thrown when there is a problem with the stage configuration file.""" def __init__(self, msg = None): - self.msg = msg + self.msg = msg def __str__(self): - return repr(self.msg) + return repr(self.msg) class ComponentDefError: """Indicates a component definition file has an error that provides proper interpretation""" def __init__(self, msg = None): - self.msg = msg + self.msg = msg def __str__(self): - return repr(self.msg) + return repr(self.msg) class FileSpecError(ComponentDefError): """Indicates a filespec component definition file has a syntactical error""" def __init__(self, msg = None): - ComponentDefError.__init__(self, msg) + ComponentDefError.__init__(self, msg) def recursiveListing(path): """Provides a recursive directory listing based in path""" result = [] files = os.listdir(path) for x in files: - fullpath = os.path.join(path, x); - if os.path.isdir(fullpath) and not os.path.islink(fullpath): - result.extend(recursiveListing(fullpath)) - else: - result.append(fullpath) + fullpath = os.path.join(path, x); + if os.path.isdir(fullpath) and not os.path.islink(fullpath): + result.extend(recursiveListing(fullpath)) + else: + result.append(fullpath) return result class FileSpecWorker: def __init__(self, source, dest): - self.source = source - self.dest = dest - self.include = [] - self.exclude = [] - self.explicit = [] - + self.source = source + self.dest = dest + self.include = [] + self.exclude = [] + self.explicit = [] + def add(self, filename): - parts = filename.split("=") - if len(parts) < 2: - # - # This line doesn"t have a separator and so assume its an - # explicit listing - # - self.explicit.append(filename) - return - - if parts[0].startswith("include"): - self.include.append(parts[1].strip()) - elif parts[0].startswith("exclude"): - self.exclude.append(parts[1].strip()) - elif parts[0].startswith("expect"): - pass - else: - raise FileSpecError("Line \'%s\' does not match filespec schema." % filename) + parts = filename.split("=") + if len(parts) < 2: + # + # This line doesn"t have a separator and so assume its an + # explicit listing + # + self.explicit.append(filename) + return + + if parts[0].startswith("include"): + self.include.append(parts[1].strip()) + elif parts[0].startswith("exclude"): + self.exclude.append(parts[1].strip()) + elif parts[0].startswith("expect"): + pass + else: + raise FileSpecError("Line \'%s\' does not match filespec schema." % filename) def execute(self, defaults, fake = False): - """Copy all of the specified files.""" - recursiveIncludes = [] - recursiveExcludes = [] - - midmatchIncludes = [] - midmatchExcludes = [] - - localIncludes = [] - localExcludes = [] - - for f in self.include: - if f.startswith("**/"): - if f.endswith("/**"): - midmatchIncludes.append(".*%s.*" %f[3:len(f) -3].replace('/', '.')) - else: - recursiveIncludes.append(f[3:]) - else: - if f.endswith("/**"): - midmatchIncludes.append("%s.*" %f[0:len(f) -3].replace('/', '.')) - else: - localIncludes.append(f) - - for f in self.exclude: - if f.startswith("**/"): - if f.endswith("/**"): - midmatchExcludes.append(".*%s.*" % f[3:len(f) -3].replace('/', '.')) - else: - recursiveExcludes.append(f[3:]) - else: - if f.endswith("/**"): - midmatchExcludes.append("%s.*" %f[0:len(f) -3].replace('/', '.')) - else: - localExcludes.append(f) - - logging.debug('localIncludes: ' + str(localIncludes)) - logging.debug('localExcludes: ' + str(localExcludes)) - logging.debug('recursiveIncludes: ' + str(recursiveIncludes)) - logging.debug('recursiveExcludes: ' + str(recursiveExcludes)) - logging.debug('midmatchIncludes: ' + str(midmatchIncludes)) - logging.debug('midmatchExcludes: ' + str(midmatchExcludes)) - - fullListing = [] - result = [] - files = os.listdir(self.source) - - for f in files: - fullpath = os.path.join(self.source, f); - if os.path.isdir(fullpath) and not os.path.islink(fullpath): - fullListing.extend(recursiveListing(fullpath)) - continue - - for p in localIncludes + recursiveIncludes: - if fnmatch.fnmatch(f, p): - found = False - for x in localExcludes + recursiveExcludes: - if fnmatch.fnmatch(f, x): - found = True - break - if not found: result.append(f) - - inmatches = [] - for p in recursiveIncludes: - inmatches.extend(fnmatch.filter(fullListing, p)) - - inSet = set(inmatches) - - for p in midmatchIncludes: - r = re.compile(p) - inmatches = [] - for f in fullListing(f): - rel = f[len(self.source):].strip('\\/') - if not r.match(rel) == None: - inmatches.append(f) - inSet = inSet.union(set(inmatches)) - - outmatches = [] - for x in recursiveExcludes: - outmatches.extend(fnmatch.filter(fullListing, x)) - - outSet = set(outmatches) - - for x in midmatchExcludes: - r = re.compile(x) - outmatches = [] - for f in fullListing: - rel = f[len(self.source):].strip('\\/') - if not r.match(rel) == None: - outmatches.append(f) - outSet = outSet.union(set(outmatches)) - - - # - # Using sets is the "easiest" way to do this. If Python"s set - # implementation is/gets buggy then this needs to be written - # "longhand". - # - diff = inSet - outSet - result.extend(list(diff)) - - for i in range(0, len(result)): - if result[i].startswith(self.source): - result[i] = result[i][len(self.source):].strip('\\/') - - result.sort() - result.extend(self.explicit) - - if fake: - for f in result: - print "Copying %s from %s to %s" % (f, self.source, self.dest) - return - - if logging.getLogger().getEffectiveLevel() == logging.DEBUG: - logging.debug("Files to be copied:") - for f in result: - logging.debug(f) - - # - # Scan filename to see if matches one of our designated - # 'convert to dos file format' name patterns. (These are - # regex patterns, not patterns for filename globbing). - # - textFiles = [".*README.*", ".*Makefile.mak", ".*LICENSE.*"] + """Copy all of the specified files.""" + recursiveIncludes = [] + recursiveExcludes = [] + + midmatchIncludes = [] + midmatchExcludes = [] + + localIncludes = [] + localExcludes = [] + + for f in self.include: + if f.startswith("**/"): + if f.endswith("/**"): + midmatchIncludes.append(".*%s.*" %f[3:len(f) -3].replace('/', '.')) + else: + recursiveIncludes.append(f[3:]) + else: + if f.endswith("/**"): + midmatchIncludes.append("%s.*" %f[0:len(f) -3].replace('/', '.')) + else: + localIncludes.append(f) + + for f in self.exclude: + if f.startswith("**/"): + if f.endswith("/**"): + midmatchExcludes.append(".*%s.*" % f[3:len(f) -3].replace('/', '.')) + else: + recursiveExcludes.append(f[3:]) + else: + if f.endswith("/**"): + midmatchExcludes.append("%s.*" %f[0:len(f) -3].replace('/', '.')) + else: + localExcludes.append(f) + + logging.debug('localIncludes: ' + str(localIncludes)) + logging.debug('localExcludes: ' + str(localExcludes)) + logging.debug('recursiveIncludes: ' + str(recursiveIncludes)) + logging.debug('recursiveExcludes: ' + str(recursiveExcludes)) + logging.debug('midmatchIncludes: ' + str(midmatchIncludes)) + logging.debug('midmatchExcludes: ' + str(midmatchExcludes)) + + fullListing = [] + result = [] + files = os.listdir(self.source) + + for f in files: + fullpath = os.path.join(self.source, f); + if os.path.isdir(fullpath) and not os.path.islink(fullpath): + fullListing.extend(recursiveListing(fullpath)) + continue + + for p in localIncludes + recursiveIncludes: + if fnmatch.fnmatch(f, p): + found = False + for x in localExcludes + recursiveExcludes: + if fnmatch.fnmatch(f, x): + found = True + break + if not found: result.append(f) + + inmatches = [] + for p in recursiveIncludes: + inmatches.extend(fnmatch.filter(fullListing, p)) + + inSet = set(inmatches) + + for p in midmatchIncludes: + r = re.compile(p) + inmatches = [] + for f in fullListing(f): + rel = f[len(self.source):].strip('\\/') + if not r.match(rel) == None: + inmatches.append(f) + inSet = inSet.union(set(inmatches)) + + outmatches = [] + for x in recursiveExcludes: + outmatches.extend(fnmatch.filter(fullListing, x)) + + outSet = set(outmatches) + + for x in midmatchExcludes: + r = re.compile(x) + outmatches = [] + for f in fullListing: + rel = f[len(self.source):].strip('\\/') + if not r.match(rel) == None: + outmatches.append(f) + outSet = outSet.union(set(outmatches)) + + + # + # Using sets is the "easiest" way to do this. If Python"s set + # implementation is/gets buggy then this needs to be written + # "longhand". + # + diff = inSet - outSet + result.extend(list(diff)) + + for i in range(0, len(result)): + if result[i].startswith(self.source): + result[i] = result[i][len(self.source):].strip('\\/') + + result.sort() + result.extend(self.explicit) + + if fake: + for f in result: + print "Copying %s from %s to %s" % (f, self.source, self.dest) + return + + if logging.getLogger().getEffectiveLevel() == logging.DEBUG: + logging.debug("Files to be copied:") + for f in result: + logging.debug(f) + + # + # Scan filename to see if matches one of our designated + # 'convert to dos file format' name patterns. (These are + # regex patterns, not patterns for filename globbing). + # + textFiles = [".*README.*", ".*Makefile.mak", ".*LICENSE.*"] textFileScanner = None - expression = "" - for p in textFiles: - if expression != "": - expression = expression + "|" - expression = expression + p - textFileScanner = re.compile(expression) - - for f in result: - # - # an f, prefix means flatten. - # - flatten = False - current = f - - if f.startswith('f,'): - flatten = True - current = current[2:] - current = current % defaults - - targetDirectory = self.dest - targetFile = os.path.basename(current) - if not flatten: - targetDirectory = os.path.join(self.dest, os.path.dirname(current)) - - if not os.path.exists(targetDirectory): - os.makedirs(targetDirectory) - - s = os.path.join(self.source, current) - d = os.path.join(targetDirectory, targetFile) - try: - if os.path.isdir(s): - os.mkdir(d) - else: - shutil.copy2(s, d) - isTextFile = (textFileScanner.search(d) != None) - if isTextFile: - # So how do I do the conversion. - tmp = open(d + ".bak", "w") - tmp.write(open(d, "rU").read()) - tmp.close() - shutil.copy2(d + ".bak", d) - os.remove(d + ".bak") - - - except IOError, e: - logging.info('Copying %s to %s failed: %s' % (s, d, str(e))) - raise + expression = "" + for p in textFiles: + if expression != "": + expression = expression + "|" + expression = expression + p + textFileScanner = re.compile(expression) + + for f in result: + # + # an f, prefix means flatten. + # + flatten = False + current = f + + if f.startswith('f,'): + flatten = True + current = current[2:] + current = current % defaults + + targetDirectory = self.dest + targetFile = os.path.basename(current) + if not flatten: + targetDirectory = os.path.join(self.dest, os.path.dirname(current)) + + if not os.path.exists(targetDirectory): + os.makedirs(targetDirectory) + + s = os.path.join(self.source, current) + d = os.path.join(targetDirectory, targetFile) + try: + if os.path.isdir(s): + os.mkdir(d) + else: + shutil.copy2(s, d) + isTextFile = (textFileScanner.search(d) != None) + if isTextFile: + # So how do I do the conversion. + tmp = open(d + ".bak", "w") + tmp.write(open(d, "rU").read()) + tmp.close() + shutil.copy2(d + ".bak", d) + os.remove(d + ".bak") + + + except IOError, e: + logging.info('Copying %s to %s failed: %s' % (s, d, str(e))) + raise def stage(filename, componentdir, stageDirectory, group, defaults): cfg = ConfigParser.SafeConfigParser() cfg.read(filename) if not cfg.has_section(group): - raise StageFileError("Section %s is missing from component list file." % group) + raise StageFileError("Section %s is missing from component list file." % group) sections = [] for entry in cfg.options(group): - section = cfg.get(group, entry) - if not cfg.has_section(section): - raise StageFileError("Section %s is missing from component list file." % section) - sections.append((entry, section)) + section = cfg.get(group, entry) + if not cfg.has_section(section): + raise StageFileError("Section %s is missing from component list file." % section) + sections.append((entry, section)) for stageLoc, section in sections: - try: - currentBase = stageDirectory - for f in stageLoc.split('-'): - currentBase = os.path.join(currentBase, f) - - if not os.path.exists(currentBase): - os.makedirs(currentBase) - - elementCount = cfg.getint(section, "elements") - if elementCount < 0: - raise StageFileError("Section %s elements field is negative value" % section) - - for i in range(1, elementCount + 1): - try: - if cfg.has_option(section, "targets"): - target = cfg.get(section, "targets", False, defaults).strip() - - if "~" + defaults["target"] in target: - continue - elif not defaults["target"] in target: - continue - - source = cfg.get(section, "source%d" % i, False, defaults) - filelist = cfg.get(section, "filelist%d" % i, False, defaults) - dest = cfg.get(section, "dest%d" % i, False, defaults) - # - # Most configurations won"t have file templates. These are usually only used so that file lists can - # be reused but need to be slightly modified for each use case. - # - template = None - mapping = None - if cfg.has_option(section, "filetemplate%d" % i): - # - # We need to get the raw value! - # - template = cfg.get(section, "filetemplate%d" %i, True) - mapping = defaults - - filename = os.path.join(componentdir, filelist) - if not (os.path.exists(filename) and os.path.isfile(filename)): - raise StageFileError("Component file %s does not exist or is not a file" % filename) - - componentFile = file(filename, "r") - try: - worker = FileSpecWorker(source, os.path.join(currentBase, dest)) - for line in componentFile: - current = line.strip() - if line.startswith('#'): - continue - - if len(current) == 0: - continue - if not template == None: - mapping['name'] = current - try: - computedName = template % mapping - except: - print "Mapping exception occurred with " + template + " and " + current - raise - - logging.log(logging.DEBUG, 'Adding templatized name %s' % computedName) - worker.add(computedName) - else: - try: - worker.add(current % defaults) - except Exception, e: - print str(e) + ": occured while adding %s to worker in element %d in %s" % \ - (current, i, section) - - if worker == None: - msg = "Component file %s is empty." % filename - logging.warning(msg) - else: - # - # XXX- fake is set to true while we are - # debugging. - # - worker.execute(defaults, False) - - finally: - componentFile.close() - - except ConfigParser.NoOptionError: - raise StageFileError("Section %s has invalid value for element %d" % (section, i)) - - except ConfigParser.NoOptionError: - raise StageFileError("Section %s has invalid or missing elements field" % section) + try: + currentBase = stageDirectory + for f in stageLoc.split('-'): + currentBase = os.path.join(currentBase, f) + + if not os.path.exists(currentBase): + os.makedirs(currentBase) + + elementCount = cfg.getint(section, "elements") + if elementCount < 0: + raise StageFileError("Section %s elements field is negative value" % section) + + for i in range(1, elementCount + 1): + try: + if cfg.has_option(section, "targets"): + target = cfg.get(section, "targets", False, defaults).strip() + + if "~" + defaults["target"] in target: + continue + elif not defaults["target"] in target: + continue + + source = cfg.get(section, "source%d" % i, False, defaults) + filelist = cfg.get(section, "filelist%d" % i, False, defaults) + dest = cfg.get(section, "dest%d" % i, False, defaults) + # + # Most configurations won"t have file templates. These are usually only used so that file lists can + # be reused but need to be slightly modified for each use case. + # + template = None + mapping = None + if cfg.has_option(section, "filetemplate%d" % i): + # + # We need to get the raw value! + # + template = cfg.get(section, "filetemplate%d" %i, True) + mapping = defaults + + filename = os.path.join(componentdir, filelist) + if not (os.path.exists(filename) and os.path.isfile(filename)): + raise StageFileError("Component file %s does not exist or is not a file" % filename) + + componentFile = file(filename, "r") + try: + worker = FileSpecWorker(source, os.path.join(currentBase, dest)) + for line in componentFile: + current = line.strip() + if line.startswith('#'): + continue + + if len(current) == 0: + continue + if not template == None: + mapping['name'] = current + try: + computedName = template % mapping + except: + print "Mapping exception occurred with " + template + " and " + current + raise + + logging.log(logging.DEBUG, 'Adding templatized name %s' % computedName) + worker.add(computedName) + else: + try: + worker.add(current % defaults) + except Exception, e: + print str(e) + ": occured while adding %s to worker in element %d in %s" % \ + (current, i, section) + + if worker == None: + msg = "Component file %s is empty." % filename + logging.warning(msg) + else: + # + # XXX- fake is set to true while we are + # debugging. + # + worker.execute(defaults, False) + + finally: + componentFile.close() + + except ConfigParser.NoOptionError: + raise StageFileError("Section %s has invalid value for element %d" % (section, i)) + + except ConfigParser.NoOptionError: + raise StageFileError("Section %s has invalid or missing elements field" % section) if __name__ == "__main__": print 'components' diff --git a/cpp/install/common/makewindist.py b/cpp/install/common/makewindist.py index c37757baa7d..b711d68d45d 100755 --- a/cpp/install/common/makewindist.py +++ b/cpp/install/common/makewindist.py @@ -23,21 +23,21 @@ ExpatVer = '2.0.0' DBVer = '4.5.20' DistPrefixes = ["Ice-%s", "IceJ-%s-java2", "IceJ-%s-java5", "IceCS-%s", "IcePy-%s", "IcePHP-%s", "IceVB-%s", - "IceRuby-%s"] + "IceRuby-%s"] class DistEnvironmentError: def __init__(self, msg = None): - self.msg = msg + self.msg = msg def __str__(self): - return repr(self.msg) + return repr(self.msg) class ExtProgramError: def __init__(self, msg): - self.msg = msg + self.msg = msg def __str__(self): - return repr(self.msg) + return repr(self.msg) def prependEnvPath(name, path): """Prepend a path to an existing environment variable.""" @@ -47,17 +47,17 @@ def prependEnvPath(name, path): def prependEnvPathList(name, list): """Prepend a list of paths to an existing environment variable.""" for path in list: - prependEnvPath(name, path) + prependEnvPath(name, path) def runprog(command, haltOnError = True): logging.debug('Running external command: %s' % command) result = os.system(command) if not result == 0: - msg = 'Command %s failed with error code %d' % (command, result) - if haltOnError: - raise ExtProgramError('Command %s failed with error code %d' % (command, result)) - else: - logging.error(msg) + msg = 'Command %s failed with error code %d' % (command, result) + if haltOnError: + raise ExtProgramError('Command %s failed with error code %d' % (command, result)) + else: + logging.error(msg) def usage(): """Print usage/help information""" @@ -68,57 +68,57 @@ def usage(): print " --skip-build Do not build any sources." print " --clean Clean compiled or staged files." print " --skip-installer Do not build any installers or merge modules." - print "-i, --info Log information messages" - print "-d, --debug Log debug messages" - print "-l, --logfile Specify the destination log file" + print "-i, --info Log information messages" + print "-d, --debug Log debug messages" + print "-l, --logfile Specify the destination log file" def environmentCheck(target): """Warning: uses global environment.""" required = ["SOURCES", "BUILD_DIR", "DB_HOME", "BZIP2_HOME", "EXPAT_HOME", "OPENSSL_HOME"] if target == "vc60": - required.append("STLPORT_HOME") + required.append("STLPORT_HOME") elif target == "vc80": - required.extend(["PHP_BIN_HOME", "PHP_SRC_HOME", "PYTHON_HOME"]) + required.extend(["PHP_BIN_HOME", "PHP_SRC_HOME", "PYTHON_HOME"]) fail = False for f in required: - if not os.environ.has_key(f): - logging.error("Environment variable %s is missing" % f) - fail = True - continue + if not os.environ.has_key(f): + logging.error("Environment variable %s is missing" % f) + fail = True + continue - if not os.path.isdir(os.environ[f]): - logging.error("Value %s for env var %s is not a valid directory." % (os.environ[f], f)) - fail = True - continue + if not os.path.isdir(os.environ[f]): + logging.error("Value %s for env var %s is not a valid directory." % (os.environ[f], f)) + fail = True + continue if fail: - logging.error("Invalid environment. Please consult error log and repair environment/command line settings.") - sys.exit(2) + logging.error("Invalid environment. Please consult error log and repair environment/command line settings.") + sys.exit(2) def maxVersion(a, b): """Compares to version strings. The version strings should be trimmed of leading and trailing whitespace.""" if a == b: - return a + return a avalues = a.split('.') bvalues = b.split('.') diff = len(avalues) - len(bvalues) if not diff == 0: - if diff < 0: - for f in range(0, abs(diff)): - avalues.append('0') - else: - for f in range(0, abs(diff)): - bvalues.append('0') + if diff < 0: + for f in range(0, abs(diff)): + avalues.append('0') + else: + for f in range(0, abs(diff)): + bvalues.append('0') for i in range(0, len(avalues)): - if int(avalues[i]) > int(bvalues[i]): - return a - elif int(avalues[i]) < int(bvalues[i]): - return b + if int(avalues[i]) > int(bvalues[i]): + return a + elif int(avalues[i]) < int(bvalues[i]): + return b return a @@ -127,10 +127,10 @@ def testMaxVersion(): cases = [ ("1.0", "1.0.0", "1.0"), ("0.0", "0.1", "0.1"), ("2.1.0", "2.0.1", "2.1.0"), ("2.1", "2.0.1", "2.1"), ("2.1.9", "2.1.12", "2.1.12")] for a, b, expected in cases: - result = maxVersion(a, b) - if not expected == result: - print "Expected %s from %s and %s, got %s" % (expected, a, b, result) - assert(False) + result = maxVersion(a, b) + if not expected == result: + print "Expected %s from %s and %s, got %s" % (expected, a, b, result) + assert(False) print "testMaxVersion() succeeded" def checkSources(sourceDir): @@ -138,29 +138,29 @@ def checkSources(sourceDir): icezip = glob.glob(os.path.join(sourceDir, "Ice-*.zip")) if len(icezip) == 0: - msg = "Source directory %s does not contain a zip archive for any version of Ice for C++" % sourceDir - logging.error(msg) - raise DistEnvironmentError(msg) + msg = "Source directory %s does not contain a zip archive for any version of Ice for C++" % sourceDir + logging.error(msg) + raise DistEnvironmentError(msg) keyVersion = '0.0.0' exp = re.compile("Ice-([0-9.]*).*.zip") current = None for d in icezip: - m = exp.match(os.path.split(d)[1]) - if m == None: - print icezip - current = m.group(1) - keyVersion = maxVersion(keyVersion, current) + m = exp.match(os.path.split(d)[1]) + if m == None: + print icezip + current = m.group(1) + keyVersion = maxVersion(keyVersion, current) print keyVersion prefixes = list(DistPrefixes) prefixes.remove("Ice-%s") for prefix in prefixes: - pkg = prefix % keyVersion + ".zip" - if not os.path.exists(os.path.join(sourceDir, pkg)): - msg = "Source directory %s does not contain archive for %s." % (sourceDir, pkg) - logging.error(msg) - raise DistEnvironmentError(msg) + pkg = prefix % keyVersion + ".zip" + if not os.path.exists(os.path.join(sourceDir, pkg)): + msg = "Source directory %s does not contain archive for %s." % (sourceDir, pkg) + logging.error(msg) + raise DistEnvironmentError(msg) return keyVersion @@ -168,14 +168,14 @@ def setMakefileOption(filename, optionName, value): optre = re.compile("^\#?\s*?%s\s*?=.*" % optionName) optionString = "no" if value: - optionString = "yes" + optionString = "yes" f = fileinput.input(filename, True) for line in f: - l = line.rstrip('\n') - if optre.search(l): + l = line.rstrip('\n') + if optre.search(l): print "%s = %s" % (optionName, optionString) - else: - print l + else: + print l f.close() def setOptimize(filename, optimizeOn): @@ -192,35 +192,35 @@ def buildIceDists(stageDir, sourcesDir, sourcesVersion, installVersion): # building Ice for C++. # path = [ - os.path.join(stageDir, "berkeley", "dev", "bin"), - os.path.join(stageDir, "berkeley", "runtime", "bin"), - os.path.join(stageDir, "berkeley", "java", "bin"), - os.path.join(stageDir, "expat", "runtime", "bin"), - os.path.join(stageDir, "openssl", "runtime", "bin") + os.path.join(stageDir, "berkeley", "dev", "bin"), + os.path.join(stageDir, "berkeley", "runtime", "bin"), + os.path.join(stageDir, "berkeley", "java", "bin"), + os.path.join(stageDir, "expat", "runtime", "bin"), + os.path.join(stageDir, "openssl", "runtime", "bin") ] if installVersion == "vc60": - path.append(os.path.join(stageDir, "stlport", "dev", "bin")) - path.append(os.path.join(stageDir, "stlport", "runtime", "bin")) + path.append(os.path.join(stageDir, "stlport", "dev", "bin")) + path.append(os.path.join(stageDir, "stlport", "runtime", "bin")) prependEnvPathList('PATH', path) lib = [ - os.path.join(stageDir, "berkeley", "dev", "lib"), - os.path.join(stageDir, "bzip2", "dev", "lib"), - os.path.join(stageDir, "expat", "dev", "lib"), - os.path.join(stageDir, "openssl", "dev", "lib"), + os.path.join(stageDir, "berkeley", "dev", "lib"), + os.path.join(stageDir, "bzip2", "dev", "lib"), + os.path.join(stageDir, "expat", "dev", "lib"), + os.path.join(stageDir, "openssl", "dev", "lib"), ] if installVersion == "vc60": - lib.append(os.path.join(stageDir, "stlport", "dev", "lib")) + lib.append(os.path.join(stageDir, "stlport", "dev", "lib")) prependEnvPathList('LIB', lib) include = [ - os.path.join(stageDir, "berkeley", "dev", "include"), - os.path.join(stageDir, "bzip2", "dev", "include"), - os.path.join(stageDir, "expat", "dev", "include"), - os.path.join(stageDir, "openssl", "dev", "include"), + os.path.join(stageDir, "berkeley", "dev", "include"), + os.path.join(stageDir, "bzip2", "dev", "include"), + os.path.join(stageDir, "expat", "dev", "include"), + os.path.join(stageDir, "openssl", "dev", "include"), ] if installVersion == "vc60": - include.append(os.path.join(stageDir, "stlport", "dev", "include", "stlport")) + include.append(os.path.join(stageDir, "stlport", "dev", "include", "stlport")) prependEnvPathList('INCLUDE', include) # @@ -244,60 +244,60 @@ def buildIceDists(stageDir, sourcesDir, sourcesVersion, installVersion): runprog("nmake /f Makefile.mak") if installVersion in ["vc80"]: - # - # Ice for C# - # - os.chdir(os.path.join(sourcesDir, "debug", "IceCS-" + sourcesVersion)) - print "Building in " + os.getcwd() + "..." + # + # Ice for C# + # + os.chdir(os.path.join(sourcesDir, "debug", "IceCS-" + sourcesVersion)) + print "Building in " + os.getcwd() + "..." setOptimize(os.path.join(os.getcwd(), "config", "Make.rules.mak"), False) setDebug(os.path.join(os.getcwd(), "config", "Make.rules.mak"), True) - runprog("nmake /f Makefile.mak") + runprog("nmake /f Makefile.mak") - # - # Ice for Visual Basic - # - os.chdir(os.path.join(sourcesDir, "debug", "IceVB-" + sourcesVersion)) - print "Building in " + os.getcwd() + "..." + # + # Ice for Visual Basic + # + os.chdir(os.path.join(sourcesDir, "debug", "IceVB-" + sourcesVersion)) + print "Building in " + os.getcwd() + "..." setOptimize(os.path.join(os.getcwd(), "config", "Make.rules.mak"), False) - f = fileinput.input(os.path.join(os.getcwd(), "config", "Make.rules.mak"), True) - for l in f: - i = l.find("icecs") - if i <> -1: - print l.rstrip('\n').replace("icecs", "IceCS-%s" % sourcesVersion) - else: - print l.rstrip('\n') - - f.close() - - runprog("nmake /f Makefile.mak") - - # - # Ice for C# - # - os.chdir(os.path.join(sourcesDir, "release", "IceCS-" + sourcesVersion)) - print "Building in " + os.getcwd() + "..." + f = fileinput.input(os.path.join(os.getcwd(), "config", "Make.rules.mak"), True) + for l in f: + i = l.find("icecs") + if i <> -1: + print l.rstrip('\n').replace("icecs", "IceCS-%s" % sourcesVersion) + else: + print l.rstrip('\n') + + f.close() + + runprog("nmake /f Makefile.mak") + + # + # Ice for C# + # + os.chdir(os.path.join(sourcesDir, "release", "IceCS-" + sourcesVersion)) + print "Building in " + os.getcwd() + "..." setOptimize(os.path.join(os.getcwd(), "config", "Make.rules.mak"), True) setDebug(os.path.join(os.getcwd(), "config", "Make.rules.mak"), False) - runprog("nmake /f Makefile.mak") + runprog("nmake /f Makefile.mak") - # - # Ice for Visual Basic - # - os.chdir(os.path.join(sourcesDir, "release", "IceVB-" + sourcesVersion)) - print "Building in " + os.getcwd() + "..." + # + # Ice for Visual Basic + # + os.chdir(os.path.join(sourcesDir, "release", "IceVB-" + sourcesVersion)) + print "Building in " + os.getcwd() + "..." setOptimize(os.path.join(os.getcwd(), "config", "Make.rules.mak"), True) - f = fileinput.input(os.path.join(os.getcwd(), "config", "Make.rules.mak"), True) - for l in f: - i = l.find("icecs") - if i <> -1: - print l.rstrip('\n').replace("icecs", "IceCS-%s" % sourcesVersion) - else: - print l.rstrip('\n') + f = fileinput.input(os.path.join(os.getcwd(), "config", "Make.rules.mak"), True) + for l in f: + i = l.find("icecs") + if i <> -1: + print l.rstrip('\n').replace("icecs", "IceCS-%s" % sourcesVersion) + else: + print l.rstrip('\n') - f.close() + f.close() - runprog("nmake /f Makefile.mak") + runprog("nmake /f Makefile.mak") # @@ -318,61 +318,61 @@ def buildIceDists(stageDir, sourcesDir, sourcesVersion, installVersion): runprog("nmake /f Makefile.mak") if installVersion == "vc71": - # - # Ice for Python - # - pythonHome = os.environ['PYTHON_HOME'] - prependEnvPath('LIB', os.path.join(pythonHome, "libs")) - prependEnvPath('INCLUDE', os.path.join(pythonHome, "include")) - - os.chdir(os.path.join(sourcesDir, "release", "IcePy-" + sourcesVersion)) - print "Building in " + os.getcwd() + "..." + # + # Ice for Python + # + pythonHome = os.environ['PYTHON_HOME'] + prependEnvPath('LIB', os.path.join(pythonHome, "libs")) + prependEnvPath('INCLUDE', os.path.join(pythonHome, "include")) + + os.chdir(os.path.join(sourcesDir, "release", "IcePy-" + sourcesVersion)) + print "Building in " + os.getcwd() + "..." setOptimize(os.path.join(os.getcwd(), "config", "Make.rules.mak"), True) - runprog("nmake /f Makefile.mak") + runprog("nmake /f Makefile.mak") if installVersion == "vc60": - # - # Ice for C++ - # - os.chdir(os.path.join(sourcesDir, "release", "Ice-" + sourcesVersion)) + # + # Ice for C++ + # + os.chdir(os.path.join(sourcesDir, "release", "Ice-" + sourcesVersion)) setOptimize(os.path.join(os.getcwd(), "config", "Make.rules.mak"), True) - print "Building in " + os.getcwd() + "..." - runprog("nmake /f Makefile.mak") - # - # Ice for PHP - # - phpBinHome = os.environ['PHP_BIN_HOME'] - phpLib = [ - os.path.join(phpBinHome, "lib"), - os.path.join(phpBinHome, "dev") - ] - prependEnvPathList('LIB', phpLib) - - phpSrcHome = os.environ['PHP_SRC_HOME'] - phpInc = [ - phpSrcHome, - os.path.join(phpSrcHome, "main"), - os.path.join(phpSrcHome, "Zend"), - os.path.join(phpSrcHome, "TSRM") - ] - prependEnvPathList('INCLUDE', phpInc) - - os.chdir(os.path.join(sourcesDir, "release", "IcePHP-" + sourcesVersion)) - print "Building in " + os.getcwd() + "..." + print "Building in " + os.getcwd() + "..." + runprog("nmake /f Makefile.mak") + # + # Ice for PHP + # + phpBinHome = os.environ['PHP_BIN_HOME'] + phpLib = [ + os.path.join(phpBinHome, "lib"), + os.path.join(phpBinHome, "dev") + ] + prependEnvPathList('LIB', phpLib) + + phpSrcHome = os.environ['PHP_SRC_HOME'] + phpInc = [ + phpSrcHome, + os.path.join(phpSrcHome, "main"), + os.path.join(phpSrcHome, "Zend"), + os.path.join(phpSrcHome, "TSRM") + ] + prependEnvPathList('INCLUDE', phpInc) + + os.chdir(os.path.join(sourcesDir, "release", "IcePHP-" + sourcesVersion)) + print "Building in " + os.getcwd() + "..." setOptimize(os.path.join(os.getcwd(), "config", "Make.rules.mak"), True) - runprog("nmake /f Makefile.mak") - os.chdir(os.path.join(sourcesDir, "release", "IceRuby-%s" % sourcesVersion)) - setOptimize(os.path.join(os.getcwd(), "config", "Make.rules.mak"), True) - print "Building in " + os.getcwd() + "..." - runprog("nmake /f Makefile.mak") + runprog("nmake /f Makefile.mak") + os.chdir(os.path.join(sourcesDir, "release", "IceRuby-%s" % sourcesVersion)) + setOptimize(os.path.join(os.getcwd(), "config", "Make.rules.mak"), True) + print "Building in " + os.getcwd() + "..." + runprog("nmake /f Makefile.mak") def list2english(l): if len(l) == 1: - return l[0] + return l[0] elif len(l) == 2: - return l[0] + " and " + list2english(l[1:]) + return l[0] + " and " + list2english(l[1:]) else: - return l[0] + ", " + list2english(l[1:]) + return l[0] + ", " + list2english(l[1:]) def convertLicensesToRTF(toolDir, installTarget): openssl = (os.path.join(os.environ["OPENSSL_HOME"], "LICENSE"), "OpenSSL", "OPENSSL_LICENSE.rtf") @@ -392,15 +392,15 @@ def convertLicensesToRTF(toolDir, installTarget): collection = core jgoodies =[(os.path.join(os.environ["JGOODIES_FORMS"], "license.txt"), "JGoodies Forms", - "JGOODIES_FORMS_LICENSE.rtf"), - (os.path.join(os.environ["JGOODIES_LOOKS"], "license.txt"), "JGoodies Looks", - "JGOODIES_LOOKS_LICENSE.rtf")] + "JGOODIES_FORMS_LICENSE.rtf"), + (os.path.join(os.environ["JGOODIES_LOOKS"], "license.txt"), "JGoodies Looks", + "JGOODIES_LOOKS_LICENSE.rtf")] if installTarget == "vc60": - collection.append((os.path.join(os.environ["STLPORT_HOME"], "doc", "license.html"), - "STLport", "STLPORT_LICENSE.rtf")) - collection.extend(jgoodies) + collection.append((os.path.join(os.environ["STLPORT_HOME"], "doc", "license.html"), + "STLport", "STLPORT_LICENSE.rtf")) + collection.extend(jgoodies) elif installTarget in ["vc71", "vc80", "vc80_x64"]: - collection.extend(jgoodies) + collection.extend(jgoodies) third_party_sources_file_hdr = """Source Code ----------- @@ -408,12 +408,12 @@ def convertLicensesToRTF(toolDir, installTarget): """ if not os.path.exists(os.path.join(toolDir, "docs")): - os.mkdir(os.path.join(toolDir, "docs")) + os.mkdir(os.path.join(toolDir, "docs")) if not os.path.exists(os.path.join(toolDir, "docs", installTarget)): - os.mkdir(os.path.join(toolDir, "docs", installTarget)) + os.mkdir(os.path.join(toolDir, "docs", installTarget)) names = [] for e in collection: - names.append(e[1]) + names.append(e[1]) text = "The source distributions of " + list2english(names) text = text + " used to build this distribution can be downloaded at no cost from http://www.zeroc.com/download.html." @@ -432,41 +432,41 @@ def convertLicensesToRTF(toolDir, installTarget): # SOURCES is used by the third party installer. # shutil.copy(os.path.join(toolDir, "docs", installTarget, "THIRD_PARTY_SOURCES"), - os.path.join(toolDir, "docs", installTarget, "SOURCES")) + os.path.join(toolDir, "docs", installTarget, "SOURCES")) licensefile = file(os.path.join(toolDir, "docs", installTarget, "LICENSE"), "w") for f in collection: - contents = None - if f[0].endswith(".html"): - # - # Here's me wishing the Python standard library had a class - # for converting HTML to plain text. In the meantime, we'll - # have to leverage 'links' in cygwin. - # - pipe_stdin, pipe_stdout = os.popen2("cygpath %s" % f[0]) - lines = pipe_stdout.readlines() - pipe_stdin.close() - pipe_stdout.close() - cygname = lines[0].strip() - pipe_stdin, pipe_stdout = os.popen2("links -dump %s" % cygname) - lines = pipe_stdout.readlines() - contents = lines[2:] - else: - contents = file(f[0]).readlines() - hdr = section_header % f[1] - - licensefile.write(hdr) - licensefile.write(line_string[:len(hdr)] + "\n\n") - licensefile.writelines(contents) - licensefile.write("\n\n") - rtffile = file(os.path.join(toolDir, "docs", installTarget, os.path.basename(f[2])), "w") - rtffile.writelines(rtfhdr) - rtffile.write(hdr + "\\par") - rtffile.write(line_string[:len(hdr)] + "\\par\n") - for l in contents: - rtffile.write(l.rstrip("\n") + "\\par\n") - rtffile.writelines(rtfftr) - rtffile.close() + contents = None + if f[0].endswith(".html"): + # + # Here's me wishing the Python standard library had a class + # for converting HTML to plain text. In the meantime, we'll + # have to leverage 'links' in cygwin. + # + pipe_stdin, pipe_stdout = os.popen2("cygpath %s" % f[0]) + lines = pipe_stdout.readlines() + pipe_stdin.close() + pipe_stdout.close() + cygname = lines[0].strip() + pipe_stdin, pipe_stdout = os.popen2("links -dump %s" % cygname) + lines = pipe_stdout.readlines() + contents = lines[2:] + else: + contents = file(f[0]).readlines() + hdr = section_header % f[1] + + licensefile.write(hdr) + licensefile.write(line_string[:len(hdr)] + "\n\n") + licensefile.writelines(contents) + licensefile.write("\n\n") + rtffile = file(os.path.join(toolDir, "docs", installTarget, os.path.basename(f[2])), "w") + rtffile.writelines(rtfhdr) + rtffile.write(hdr + "\\par") + rtffile.write(line_string[:len(hdr)] + "\\par\n") + for l in contents: + rtffile.write(l.rstrip("\n") + "\\par\n") + rtffile.writelines(rtfftr) + rtffile.close() # # Technically, the JGoodies stuff isn't part of the Ice 6.0.0 target @@ -474,58 +474,58 @@ def convertLicensesToRTF(toolDir, installTarget): # IceJ builders. # if installTarget == "vc60": - for f in jgoodies: - contents = file(f[0]).readlines() - hdr = section_header % f[1] - rtffile = file(os.path.join(toolDir, "docs", installTarget, os.path.basename(f[2])), "w") - rtffile.writelines(rtfhdr) - rtffile.write(hdr + "\\par") - rtffile.write(line_string[:len(hdr)] + "\\par\n") - for l in contents: - rtffile.write(l.rstrip("\n") + "\\par\n") - rtffile.writelines(rtfftr) - rtffile.close() + for f in jgoodies: + contents = file(f[0]).readlines() + hdr = section_header % f[1] + rtffile = file(os.path.join(toolDir, "docs", installTarget, os.path.basename(f[2])), "w") + rtffile.writelines(rtfhdr) + rtffile.write(hdr + "\\par") + rtffile.write(line_string[:len(hdr)] + "\\par\n") + for l in contents: + rtffile.write(l.rstrip("\n") + "\\par\n") + rtffile.writelines(rtfftr) + rtffile.close() licensefile.close() shutil.copyfile(os.path.join(toolDir, "docs", installTarget, "LICENSE"), \ - os.path.join(toolDir, "docs", installTarget, "THIRD_PARTY_LICENSE")) + os.path.join(toolDir, "docs", installTarget, "THIRD_PARTY_LICENSE")) lines = file(os.path.join(toolDir, "docs", installTarget, "LICENSE")).readlines() rtflicense = file(os.path.join(toolDir, "docs", installTarget, "LICENSE.rtf"), "w") rtflicense.writelines(rtfhdr) for l in lines: - rtflicense.write(l.rstrip("\n") + "\\par\n") + rtflicense.write(l.rstrip("\n") + "\\par\n") rtflicense.writelines(rtfftr) rtflicense.close() def buildMergeModules(startDir, stageDir, sourcesVersion, installVersion): """Build third party merge modules.""" modules = [ - ("BerkeleyDBDevKit", "BERKELEYDB_DEV_KIT"), - ("BerkeleyDBRuntime", "BERKELEYDB_RUNTIME"), - ("BZip2DevKit", "BZIP2_DEV_KIT"), - ("BZip2Runtime", "BZIP2_RUNTIME"), - ("ExpatDevKit", "EXPAT_DEV_KIT"), - ("ExpatRuntime", "EXPAT_RUNTIME"), - ("OpenSSLDevKit", "OPENSSL_DEV_KIT"), - ("OpenSSLRuntime", "OPENSSL_RUNTIME"), - ("JGoodies", "JGOODIES_RUNTIME"), - ("BerkeleyDBJava", "BERKELEYDB_JAVA") + ("BerkeleyDBDevKit", "BERKELEYDB_DEV_KIT"), + ("BerkeleyDBRuntime", "BERKELEYDB_RUNTIME"), + ("BZip2DevKit", "BZIP2_DEV_KIT"), + ("BZip2Runtime", "BZIP2_RUNTIME"), + ("ExpatDevKit", "EXPAT_DEV_KIT"), + ("ExpatRuntime", "EXPAT_RUNTIME"), + ("OpenSSLDevKit", "OPENSSL_DEV_KIT"), + ("OpenSSLRuntime", "OPENSSL_RUNTIME"), + ("JGoodies", "JGOODIES_RUNTIME"), + ("BerkeleyDBJava", "BERKELEYDB_JAVA") ] if installVersion == "vc60": - extras = [ ("STLPortDevKit", "STLPORT_DEV_KIT"), ("STLPortRuntime", "STLPORT_RUNTIME") ] - modules.extend(extras) + extras = [ ("STLPortDevKit", "STLPORT_DEV_KIT"), ("STLPortRuntime", "STLPORT_RUNTIME") ] + modules.extend(extras) # # Build modules. # os.chdir(startDir) for project, release in modules: - # - # The -w -x flags indicate that the build should stop on any - # warning or error. This is preferable since it catches staging - # errors and forces us to keep our projects clean. - # - runprog(os.environ['INSTALLSHIELD_HOME'] + "\IsCmdBld -x -w -c COMP -a ZEROC -p " + project + ".ism -r " + release) + # + # The -w -x flags indicate that the build should stop on any + # warning or error. This is preferable since it catches staging + # errors and forces us to keep our projects clean. + # + runprog(os.environ['INSTALLSHIELD_HOME'] + "\IsCmdBld -x -w -c COMP -a ZEROC -p " + project + ".ism -r " + release) # # Archive modules in the stage directory root. @@ -539,38 +539,38 @@ def buildMergeModules(startDir, stageDir, sourcesVersion, installVersion): zipPath = "ThirdPartyMergeModules-" + sourcesVersion + "-" + installVersion.upper() + ".zip" zip = zipfile.ZipFile(os.path.join(stageDir, zipPath), 'w') for project, release in modules: - msm = project + "." + installVersion.upper() + ".msm" - msmPath = os.path.join(os.getcwd(), project, "ZEROC", release, "DiskImages/DISK1", msm) - zip.write(msmPath, os.path.basename(msmPath)) + msm = project + "." + installVersion.upper() + ".msm" + msmPath = os.path.join(os.getcwd(), project, "ZEROC", release, "DiskImages/DISK1", msm) + zip.write(msmPath, os.path.basename(msmPath)) zip.close() def buildInstallers(startDir, stageDir, sourcesVersion, installVersion, installers): if installVersion == "vc80_x64": - installVersion = "VC80-x64" + installVersion = "VC80-x64" else: - installVersion = installVersion.upper() + installVersion = installVersion.upper() # # Build and copy to the stage directory root. # os.chdir(startDir) for project, release in installers: - runprog(os.environ['INSTALLSHIELD_HOME'] + "\ISCmdBld -x -w -c COMP -a ZEROC -p " + project + ".ism -r " + release) - msi = project + "-" + sourcesVersion + "-" + installVersion + ".msi" - msiPath = os.path.join(os.getcwd(), project, "ZEROC", release, "DiskImages/DISK1", msi) - shutil.copy(msiPath, stageDir) + runprog(os.environ['INSTALLSHIELD_HOME'] + "\ISCmdBld -x -w -c COMP -a ZEROC -p " + project + ".ism -r " + release) + msi = project + "-" + sourcesVersion + "-" + installVersion + ".msi" + msiPath = os.path.join(os.getcwd(), project, "ZEROC", release, "DiskImages/DISK1", msi) + shutil.copy(msiPath, stageDir) def environToString(tbl): '''Convert an environment hashtable to the typical k=v format''' ofile = cStringIO.StringIO() result = '' try: - for k, v in tbl.iteritems(): - ofile.write('%s=%s\n' % (k, v)) - result = ofile.getvalue() - finally: - ofile.close() + for k, v in tbl.iteritems(): + ofile.write('%s=%s\n' % (k, v)) + result = ofile.getvalue() + finally: + ofile.close() return result def main(): @@ -590,207 +590,207 @@ def main(): os.environ['INSTALL_TOOLS'] = installDir try: - # - # Process args. - # - try: - optionList, args = getopt.getopt( - sys.argv[1:], "dhil:", [ "help", "clean", "skip-build", "skip-installer", "info", "debug", - "logfile", "vc60", "vc71", "vc80", "vc80_x64", "sslhome=", "expathome=", "dbhome=", "stlporthome=", - "bzip2home=", "thirdparty="]) - except getopt.GetoptError: - usage() - sys.exit(2) - - # - # Set a few defaults. - # - clean = False - build = True - installer = True - debugLevel = logging.NOTSET - logFile = None - target = None - - for o, a in optionList: - if o in ("-h", "--help"): - usage() - sys.exit() - elif o == "--clean": - clean = True - elif o == "--skip-build": - build = False - elif o == "--skip-installer": - installer = False - elif o in ('-l', '--logfile'): - logFile = a - elif o in ('-d', '--debug'): - debugLevel = logging.DEBUG - elif o in ('-', '--info'): - debugLevel = logging.INFO - elif o == '--vc60': - target = 'vc60' - elif o == '--vc71': - target = 'vc71' - elif o == '--vc80': - target = 'vc80' - elif o == '--vc80_x64': - target = 'vc80_x64' - elif o == '--sources': - os.environ['SOURCES'] = a - elif o == '--buildDir': - os.environ['BUILD_DIR'] = a - elif o == '--sslhome': - os.environ['OPENSSL_HOME'] = a - elif o == '--expathome': - os.environ['EXPAT_HOME'] = a - elif o == '--dbhome': - os.environ['DB_HOME'] = a - elif o == '--stlporthome': - os.environ['STLPORT_HOME'] = a - elif o == '--bzip2home': - os.environ['BZIP2_HOME'] = a - elif o == '--thirdparty': - os.environ['OPENSSL_HOME'] = os.path.join(a, 'openssl-%s' % OpenSSLVer) - os.environ['BZIP2_HOME'] = os.path.join(a, 'bzip2-%s' % Bzip2Ver) - os.environ['EXPAT_HOME'] = os.path.join(a, 'expat-%s' % ExpatVer) - os.environ['DB_HOME'] = os.path.join(a, 'db-%s' % DBVer) - os.environ['STLPORT_HOME'] = os.path.join(a, 'STLPort-%s' % STLPortVer) - - if debugLevel != logging.NOTSET: - if a != None: - logging.basicConfig(level = debugLevel, format='%(asctime)s %(levelname)s %(message)s', filename = a) - else: - logging.basicConfig(level = debugLevel, format='%(asctime)s %(levelname)s %(message)s') - - if target == None: - print 'The development target must be specified' - sys.exit(2) - - os.environ['target'] = target - - # - # Where all the files will be staged so that the install projects - # can find them. - # - targetDir = os.path.join(installDir, target) - stageDir = os.path.join(targetDir, "install") - - logging.info("Install Tool: " + installDir) - logging.info("Target Directory: " + targetDir) - logging.info("Stage Directory: " + stageDir) - - if clean: - print('You have indicated you want to ''clean'' files, starting from scratch.') - confirm = '' - while not confirm in ['y', 'n']: - confirm = raw_input('Are you sure? [y/N]') - if confirm == '': - confirm = 'n' - if confirm == 'n': - sys.exit() - else: - logging.info('Deleting intermediate files and rebuilding from scratch!') - - logging.info('Starting windows installer creation.') - - environmentCheck(target) - - buildDir = os.environ['BUILD_DIR'] - - logging.debug(environToString(os.environ)) - - sourcesVersion = checkSources(os.environ['SOURCES']) - - defaults = os.environ - defaults['dbver'] = '45' - defaults['version'] = sourcesVersion - defaults['dllversion'] = sourcesVersion.replace('.', '')[:2] - - if target == "vc80_x64": - defaults['OutDir'] = "x64/" - else: - defaults['OutDir'] = '' - - if os.path.exists(stageDir): - try: - shutil.rmtree(stageDir) - except IOError: - print """ + # + # Process args. + # + try: + optionList, args = getopt.getopt( + sys.argv[1:], "dhil:", [ "help", "clean", "skip-build", "skip-installer", "info", "debug", + "logfile", "vc60", "vc71", "vc80", "vc80_x64", "sslhome=", "expathome=", "dbhome=", "stlporthome=", + "bzip2home=", "thirdparty="]) + except getopt.GetoptError: + usage() + sys.exit(2) + + # + # Set a few defaults. + # + clean = False + build = True + installer = True + debugLevel = logging.NOTSET + logFile = None + target = None + + for o, a in optionList: + if o in ("-h", "--help"): + usage() + sys.exit() + elif o == "--clean": + clean = True + elif o == "--skip-build": + build = False + elif o == "--skip-installer": + installer = False + elif o in ('-l', '--logfile'): + logFile = a + elif o in ('-d', '--debug'): + debugLevel = logging.DEBUG + elif o in ('-', '--info'): + debugLevel = logging.INFO + elif o == '--vc60': + target = 'vc60' + elif o == '--vc71': + target = 'vc71' + elif o == '--vc80': + target = 'vc80' + elif o == '--vc80_x64': + target = 'vc80_x64' + elif o == '--sources': + os.environ['SOURCES'] = a + elif o == '--buildDir': + os.environ['BUILD_DIR'] = a + elif o == '--sslhome': + os.environ['OPENSSL_HOME'] = a + elif o == '--expathome': + os.environ['EXPAT_HOME'] = a + elif o == '--dbhome': + os.environ['DB_HOME'] = a + elif o == '--stlporthome': + os.environ['STLPORT_HOME'] = a + elif o == '--bzip2home': + os.environ['BZIP2_HOME'] = a + elif o == '--thirdparty': + os.environ['OPENSSL_HOME'] = os.path.join(a, 'openssl-%s' % OpenSSLVer) + os.environ['BZIP2_HOME'] = os.path.join(a, 'bzip2-%s' % Bzip2Ver) + os.environ['EXPAT_HOME'] = os.path.join(a, 'expat-%s' % ExpatVer) + os.environ['DB_HOME'] = os.path.join(a, 'db-%s' % DBVer) + os.environ['STLPORT_HOME'] = os.path.join(a, 'STLPort-%s' % STLPortVer) + + if debugLevel != logging.NOTSET: + if a != None: + logging.basicConfig(level = debugLevel, format='%(asctime)s %(levelname)s %(message)s', filename = a) + else: + logging.basicConfig(level = debugLevel, format='%(asctime)s %(levelname)s %(message)s') + + if target == None: + print 'The development target must be specified' + sys.exit(2) + + os.environ['target'] = target + + # + # Where all the files will be staged so that the install projects + # can find them. + # + targetDir = os.path.join(installDir, target) + stageDir = os.path.join(targetDir, "install") + + logging.info("Install Tool: " + installDir) + logging.info("Target Directory: " + targetDir) + logging.info("Stage Directory: " + stageDir) + + if clean: + print('You have indicated you want to ''clean'' files, starting from scratch.') + confirm = '' + while not confirm in ['y', 'n']: + confirm = raw_input('Are you sure? [y/N]') + if confirm == '': + confirm = 'n' + if confirm == 'n': + sys.exit() + else: + logging.info('Deleting intermediate files and rebuilding from scratch!') + + logging.info('Starting windows installer creation.') + + environmentCheck(target) + + buildDir = os.environ['BUILD_DIR'] + + logging.debug(environToString(os.environ)) + + sourcesVersion = checkSources(os.environ['SOURCES']) + + defaults = os.environ + defaults['dbver'] = '45' + defaults['version'] = sourcesVersion + defaults['dllversion'] = sourcesVersion.replace('.', '')[:2] + + if target == "vc80_x64": + defaults['OutDir'] = "x64/" + else: + defaults['OutDir'] = '' + + if os.path.exists(stageDir): + try: + shutil.rmtree(stageDir) + except IOError: + print """ If you are getting a permission error here, try running 'attrib -r /s' on both the stage directory and the source location for the third party libraries.""" - raise - os.mkdir(stageDir) - - # - # Gather and generate license files. - # - convertLicensesToRTF(os.path.dirname(__file__), target) - - # - # The third party packages need to be staged before building the - # distributions. This ordering is important because it adds an - # additional check that the third party packages that are - # included in the installer are suitable for use with Ice. - # - components.stage(os.path.join(os.path.dirname(components.__file__), "components", "components.ini"), - os.path.join(os.path.dirname(components.__file__), "components"), stageDir, "packages", defaults) - - # - # Build the merge module projects. - # - if installer: - buildMergeModules(targetDir, stageDir, sourcesVersion, target) - buildInstallers(targetDir, stageDir, sourcesVersion, target, [("ThirdParty", "THIRD_PARTY_MSI")]) - - # - # Screw clean rules, run the ultimate clean! - # - if clean: - shutil.rmtree(buildDir) - - if not os.path.exists(buildDir): - os.mkdir(buildDir) - if not os.path.exists(os.path.join(buildDir, "debug")): - os.mkdir(os.path.join(buildDir, "debug")) - if not os.path.exists(os.path.join(buildDir, "release")): - os.mkdir(os.path.join(buildDir, "release")) - - for z in DistPrefixes: + raise + os.mkdir(stageDir) + + # + # Gather and generate license files. + # + convertLicensesToRTF(os.path.dirname(__file__), target) + + # + # The third party packages need to be staged before building the + # distributions. This ordering is important because it adds an + # additional check that the third party packages that are + # included in the installer are suitable for use with Ice. + # + components.stage(os.path.join(os.path.dirname(components.__file__), "components", "components.ini"), + os.path.join(os.path.dirname(components.__file__), "components"), stageDir, "packages", defaults) + + # + # Build the merge module projects. + # + if installer: + buildMergeModules(targetDir, stageDir, sourcesVersion, target) + buildInstallers(targetDir, stageDir, sourcesVersion, target, [("ThirdParty", "THIRD_PARTY_MSI")]) + + # + # Screw clean rules, run the ultimate clean! + # + if clean: + shutil.rmtree(buildDir) + + if not os.path.exists(buildDir): + os.mkdir(buildDir) + if not os.path.exists(os.path.join(buildDir, "debug")): + os.mkdir(os.path.join(buildDir, "debug")) + if not os.path.exists(os.path.join(buildDir, "release")): + os.mkdir(os.path.join(buildDir, "release")) + + for z in DistPrefixes: + # + # TODO: See if this can be replaced by ZipFile and native + # Python code somehow. # - # TODO: See if this can be replaced by ZipFile and native - # Python code somehow. - # - filename = os.path.join(os.environ['SOURCES'], z % sourcesVersion + ".zip") - if not os.path.exists(os.path.join(buildDir, "debug", z % sourcesVersion)): - runprog("unzip -o -q %s -d %s" % (filename, os.path.join(buildDir, "debug"))) - if not os.path.exists(os.path.join(buildDir, "release", z % sourcesVersion)): - runprog("unzip -o -q %s -d %s" % (filename, os.path.join(buildDir, "release"))) - - # - # Build the Ice distributions. - # - if build: - buildIceDists(stageDir, buildDir, sourcesVersion, target) - - # - # Stage Ice! - # - components.stage(os.path.join(os.path.dirname(components.__file__), "components", "components.ini"), - os.path.join(os.path.dirname(components.__file__), "components"), stageDir, "ice", defaults) - - # - # Build the installer projects. - # - if installer: - buildInstallers(targetDir, stageDir, sourcesVersion, target, [("Ice", "ICE_MSI")]) + filename = os.path.join(os.environ['SOURCES'], z % sourcesVersion + ".zip") + if not os.path.exists(os.path.join(buildDir, "debug", z % sourcesVersion)): + runprog("unzip -o -q %s -d %s" % (filename, os.path.join(buildDir, "debug"))) + if not os.path.exists(os.path.join(buildDir, "release", z % sourcesVersion)): + runprog("unzip -o -q %s -d %s" % (filename, os.path.join(buildDir, "release"))) + + # + # Build the Ice distributions. + # + if build: + buildIceDists(stageDir, buildDir, sourcesVersion, target) + + # + # Stage Ice! + # + components.stage(os.path.join(os.path.dirname(components.__file__), "components", "components.ini"), + os.path.join(os.path.dirname(components.__file__), "components"), stageDir, "ice", defaults) + + # + # Build the installer projects. + # + if installer: + buildInstallers(targetDir, stageDir, sourcesVersion, target, [("Ice", "ICE_MSI")]) finally: - # - # Return the user to where they started. - # - os.chdir(startDir) + # + # Return the user to where they started. + # + os.chdir(startDir) if __name__ == "__main__": main() diff --git a/cpp/install/rpm/makeSRPMs.py b/cpp/install/rpm/makeSRPMs.py index a252696be3b..3e8531647f1 100755 --- a/cpp/install/rpm/makeSRPMs.py +++ b/cpp/install/rpm/makeSRPMs.py @@ -28,19 +28,19 @@ def main(): sourceLocation = None try: - optionList, args = getopt.getopt(sys.argv[1:], "hs:t:", ["sources=", "target-host=", "help"]) + optionList, args = getopt.getopt(sys.argv[1:], "hs:t:", ["sources=", "target-host=", "help"]) except getopt.GetoptError: - usage() - sys.exit(2) + usage() + sys.exit(2) for o, a in optionList: - if o in ["-h", "--help"]: - pass - if o in ["-s", "--sources"]: - pass - if o in ["-t", "--target-host"]: - pass + if o in ["-h", "--help"]: + pass + if o in ["-s", "--sources"]: + pass + if o in ["-t", "--target-host"]: + pass f = open("./test.spec", "w+b") RPMTools.createFullSpecFile(f, "", "3.2.0", 32, "suse") diff --git a/cpp/makebindist.py b/cpp/makebindist.py index e7f2a5dd303..6fbe3cd77aa 100755 --- a/cpp/makebindist.py +++ b/cpp/makebindist.py @@ -46,27 +46,27 @@ def initDirectory(d): class ExtProgramError: def __init__(self, error = None): - self.msg = error - + self.msg = error + def __str__(self): - return repr(self.msg) + return repr(self.msg) def runprog(commandstring, haltOnError = True): #commandtuple = commandstring.split() #result = os.spawnvpe(os.P_WAIT, commandtuple[0], commandtuple, os.environ) result = os.system(commandstring) if result != 0: - msg = 'Command %s returned error code %d' % (commandstring, result) - if haltOnError: - raise ExtProgramError(msg) + msg = 'Command %s returned error code %d' % (commandstring, result) + if haltOnError: + raise ExtProgramError(msg) def copyfiles(srcDir, destDir): '''Copy the contents of one directory to another (non-recursive)''' for f in os.listdir(srcDir): - src = os.path.join(srcDir, f) - dest = os.path.join(destDir, f) - if not os.path.isdir(src) and not os.path.islink(src): - shutil.copy(src, dest) + src = os.path.join(srcDir, f) + dest = os.path.join(destDir, f) + if not os.path.isdir(src) and not os.path.islink(src): + shutil.copy(src, dest) def getIceVersion(file): """Extract the ICE version string from a file.""" @@ -91,10 +91,10 @@ def getPlatform(): if sys.platform.startswith('win') or sys.platform.startswith('cygwin'): return 'win32' elif sys.platform.startswith('linux'): - if readcommand('uname -p') == 'x86_64': - return 'linux64' - else: - return 'linux' + if readcommand('uname -p') == 'x86_64': + return 'linux64' + else: + return 'linux' elif sys.platform.startswith('sunos'): return 'solaris' elif sys.platform.startswith('hp'): @@ -131,8 +131,8 @@ def getVersion(cvsTag, buildDir): runprog('cvs -d cvs.zeroc.com:/home/cvsroot export -r ' + cvsTag + ' ice/include/IceUtil/Config.h') result = [ getIceVersion('ice/include/IceUtil/Config.h'), \ - getIceSoVersion('ice/include/IceUtil/Config.h'), \ - getIceMMVersion('ice/include/IceUtil/Config.h') ] + getIceSoVersion('ice/include/IceUtil/Config.h'), \ + getIceMMVersion('ice/include/IceUtil/Config.h') ] os.remove('ice/include/IceUtil/Config.h') os.removedirs('ice/include/IceUtil') @@ -142,28 +142,28 @@ def getVersion(cvsTag, buildDir): def fixVersion(filename, version, mmVersion): f = fileinput.input(filename, True) for line in f: - l = line.rstrip('\n') - l = l.replace('@ver@', version) - l = l.replace('@mmver@', mmVersion) - print l + l = line.rstrip('\n') + l = l.replace('@ver@', version) + l = l.replace('@mmver@', mmVersion) + print l f.close() def getInstallFiles(cvsTag, buildDir, version, mmVersion): """Gets the install sources for this revision""" cwd = os.getcwd() try: - os.chdir(buildDir) - runprog('rm -rf ' + buildDir + '/ice/install') - runprog('cvs -d cvs.zeroc.com:/home/cvsroot export -r ' + cvsTag + ' ice/install/unix') - runprog('cvs -d cvs.zeroc.com:/home/cvsroot export -r ' + cvsTag + ' ice/install/common') - runprog('cvs -d cvs.zeroc.com:/home/cvsroot export -r ' + cvsTag + ' ice/install/rpm') - runprog('cvs -d cvs.zeroc.com:/home/cvsroot export -r ' + cvsTag + ' ice/install/thirdparty') - snapshot = os.walk('./ice/install/unix') - for dirInfo in snapshot: - for f in dirInfo[2]: - fixVersion(os.path.join(dirInfo[0], f), version, mmVersion) + os.chdir(buildDir) + runprog('rm -rf ' + buildDir + '/ice/install') + runprog('cvs -d cvs.zeroc.com:/home/cvsroot export -r ' + cvsTag + ' ice/install/unix') + runprog('cvs -d cvs.zeroc.com:/home/cvsroot export -r ' + cvsTag + ' ice/install/common') + runprog('cvs -d cvs.zeroc.com:/home/cvsroot export -r ' + cvsTag + ' ice/install/rpm') + runprog('cvs -d cvs.zeroc.com:/home/cvsroot export -r ' + cvsTag + ' ice/install/thirdparty') + snapshot = os.walk('./ice/install/unix') + for dirInfo in snapshot: + for f in dirInfo[2]: + fixVersion(os.path.join(dirInfo[0], f), version, mmVersion) finally: - os.chdir(cwd) + os.chdir(cwd) return buildDir + '/ice/install' def getInstallFilesFromLocalDirectory(cvsTag, buildDir, version, mmVersion): @@ -172,20 +172,20 @@ def getInstallFilesFromLocalDirectory(cvsTag, buildDir, version, mmVersion): continue working!''' cwd = os.getcwd() try: - os.chdir(buildDir) - target = os.path.join(buildDir, 'ice', 'install') - if os.path.exists(target): - shutil.rmtree(target) - iceloc = os.path.abspath(os.path.join(os.environ['ICE_HOME'],'install')) - os.makedirs(target) - for f in ['unix', 'common', 'rpm', 'thirdparty']: - shutil.copytree(os.path.join(iceloc, f), os.path.join(target, f)) - snapshot = os.walk('./ice/install/unix') - for dirInfo in snapshot: - for f in dirInfo[2]: - fixVersion(os.path.join(dirInfo[0], f), version, mmVersion) + os.chdir(buildDir) + target = os.path.join(buildDir, 'ice', 'install') + if os.path.exists(target): + shutil.rmtree(target) + iceloc = os.path.abspath(os.path.join(os.environ['ICE_HOME'],'install')) + os.makedirs(target) + for f in ['unix', 'common', 'rpm', 'thirdparty']: + shutil.copytree(os.path.join(iceloc, f), os.path.join(target, f)) + snapshot = os.walk('./ice/install/unix') + for dirInfo in snapshot: + for f in dirInfo[2]: + fixVersion(os.path.join(dirInfo[0], f), version, mmVersion) finally: - os.chdir(cwd) + os.chdir(cwd) return buildDir + '/ice/install' def readcommand(cmd): @@ -204,7 +204,7 @@ def collectSourceDistributions(tag, sourceDir, cvsdir, distro): cwd = os.getcwd() os.chdir(cwd + "/../" + cvsdir) if len(tag) > 0: - print 'Making disribution ' + cvsdir + ' with tag ' + tag + print 'Making disribution ' + cvsdir + ' with tag ' + tag # # The sources collected by the makebindist.py script are *NOT* @@ -214,7 +214,7 @@ def collectSourceDistributions(tag, sourceDir, cvsdir, distro): runprog("./makedist.py " + tag) else: runprog("./makedist.py -d " + tag) - + shutil.copy("dist/" + distro + ".tar.gz", sourceDir) os.chdir(cwd) @@ -226,12 +226,12 @@ def editMakeRulesCS(filename, version): reIceLocation = re.compile('^[a-z]*dir.*=\s*\$\(top_srcdir\)') makefile = fileinput.input(filename, True) for line in makefile: - if reIceLocation.search(line) <> None: - print line.rstrip('\n').replace('top_srcdir', 'ICE_DIR', 10) - elif line.startswith('prefix'): - print 'prefix = $(ICE_DIR)' - else: - print line.rstrip('\n') + if reIceLocation.search(line) <> None: + print line.rstrip('\n').replace('top_srcdir', 'ICE_DIR', 10) + elif line.startswith('prefix'): + print 'prefix = $(ICE_DIR)' + else: + print line.rstrip('\n') makefile.close() def editMakeRules(filename, version): @@ -245,66 +245,66 @@ def editMakeRules(filename, version): makefile = fileinput.input(filename, True) for line in makefile: - if line.startswith('slicedir'): - print """ + if line.startswith('slicedir'): + print """ ifeq ($(ICE_DIR),/usr) slicedir = $(ICE_DIR)/share/slice else slicedir = $(ICE_DIR)/slice endif """ - elif line.startswith('embedded_runpath_prefix'): - state = 'untilblank' - print """ + elif line.startswith('embedded_runpath_prefix'): + state = 'untilblank' + print """ ifneq ($(ICE_DIR),/usr) embedded_runpath_prefix ?= /opt/Ice-$(VERSION_MAJOR).$(VERSION_MINOR) endif """ - elif line.startswith('embedded_runpath_prefix'): - # - # embedded_runpath_prefix is moved down to after the version - # information is set. - # - pass - elif reIceLocation.search(line) <> None: - output = line.rstrip('\n').replace('top_srcdir', 'ICE_DIR', 10) - if line.startswith('libdir'): - print 'ifeq ($(LP64),yes)' - print ' ' + output + '$(lp64suffix)' - print 'else' - print ' ' + output - print 'endif' - elif line.startswith('bindir'): - print output - # - # NOTE!!! Magic occurs... - # It simplifies building the demos for the user if - # we try to detect whether the executables are 64 - # bit and, if so, set LP64=yes automagically. - # - print '' - print '#' - print '# If LP64 is unset, sample an Ice executable to see if it is 64 bit' - print '# and set automatically. This avoids having to set LP64 if there is' - print '# Ice installation in a well-known location.' - print '#' - print 'ifeq ($(LP64),)' - print ' ifneq ($(shell file $(bindir)/slice2cpp | grep 64-bit),)' - print ' LP64=yes' - print ' endif' - print 'endif' - print '' - else: - print output - - elif line.startswith('install_'): - # - # Do nothing. - # - pass - elif line.startswith('SOVERSION'): - print line.rstrip('\n') - print """ + elif line.startswith('embedded_runpath_prefix'): + # + # embedded_runpath_prefix is moved down to after the version + # information is set. + # + pass + elif reIceLocation.search(line) <> None: + output = line.rstrip('\n').replace('top_srcdir', 'ICE_DIR', 10) + if line.startswith('libdir'): + print 'ifeq ($(LP64),yes)' + print ' ' + output + '$(lp64suffix)' + print 'else' + print ' ' + output + print 'endif' + elif line.startswith('bindir'): + print output + # + # NOTE!!! Magic occurs... + # It simplifies building the demos for the user if + # we try to detect whether the executables are 64 + # bit and, if so, set LP64=yes automagically. + # + print '' + print '#' + print '# If LP64 is unset, sample an Ice executable to see if it is 64 bit' + print '# and set automatically. This avoids having to set LP64 if there is' + print '# Ice installation in a well-known location.' + print '#' + print 'ifeq ($(LP64),)' + print ' ifneq ($(shell file $(bindir)/slice2cpp | grep 64-bit),)' + print ' LP64=yes' + print ' endif' + print 'endif' + print '' + else: + print output + + elif line.startswith('install_'): + # + # Do nothing. + # + pass + elif line.startswith('SOVERSION'): + print line.rstrip('\n') + print """ # # Checks for ICE_HOME environment variable. If it isn't present, @@ -314,17 +314,17 @@ endif ifeq ($(ICE_HOME),) ICE_DIR = /usr ifneq ($(shell test -f $(ICE_DIR)/bin/icestormadmin && echo 0),0) - NEXTDIR = /opt/Ice-$(VERSION_MAJOR).$(VERSION_MINOR) - ifneq ($(shell test -f $(NEXTDIR)/bin/icestormadmin && echo 0),0) + NEXTDIR = /opt/Ice-$(VERSION_MAJOR).$(VERSION_MINOR) + ifneq ($(shell test -f $(NEXTDIR)/bin/icestormadmin && echo 0),0) $(error Unable to locate Ice distribution, please set ICE_HOME!) - else - ICE_DIR = $(NEXTDIR) - endif + else + ICE_DIR = $(NEXTDIR) + endif else - NEXTDIR = /opt/Ice-$(VERSION_MAJOR).$(VERSION_MINOR) - ifeq ($(shell test -f $(NEXTDIR)/bin/icestormadmin && echo 0),0) + NEXTDIR = /opt/Ice-$(VERSION_MAJOR).$(VERSION_MINOR) + ifeq ($(shell test -f $(NEXTDIR)/bin/icestormadmin && echo 0),0) $(warning Ice distribution found in /usr and $(NEXTDIR)! Installation in "/usr" will be used by default. Use ICE_HOME to specify alternate Ice installation.) - endif + endif endif else ICE_DIR = $(ICE_HOME) @@ -340,15 +340,15 @@ endif prefix = $(ICE_DIR) """ - elif line.startswith('prefix'): - # - # Delete the prefix line. It will be set later on after - # SOVERSION. - # - print "# 'prefix' is automatically defined later on in this file using default" - print "# locations or ICE_HOME" - else: - print line.rstrip('\n') + elif line.startswith('prefix'): + # + # Delete the prefix line. It will be set later on after + # SOVERSION. + # + print "# 'prefix' is automatically defined later on in this file using default" + print "# locations or ICE_HOME" + else: + print line.rstrip('\n') # # Dependency files are all going to be bogus since they contain relative @@ -373,30 +373,30 @@ def editMakeRulesMak(filename, version): makefile = fileinput.input(filename, True) for line in makefile: - if state == 'done': - if reIceLocation.search(line) <> None: - output = line.rstrip('\n').replace('top_srcdir', 'ICE_DIR', 10) - print output - elif line.startswith('install_'): - # - # Do nothing. - # - pass - elif line.startswith('THIRDPARTY_HOME'): - # - # Do nothing. - # - pass - else: - print line.rstrip('\n') - elif state == 'header': - # - # Reading header. - # - print line.rstrip('\n') - if line.strip() == "": - state = 'untilprefix' - print """ + if state == 'done': + if reIceLocation.search(line) <> None: + output = line.rstrip('\n').replace('top_srcdir', 'ICE_DIR', 10) + print output + elif line.startswith('install_'): + # + # Do nothing. + # + pass + elif line.startswith('THIRDPARTY_HOME'): + # + # Do nothing. + # + pass + else: + print line.rstrip('\n') + elif state == 'header': + # + # Reading header. + # + print line.rstrip('\n') + if line.strip() == "": + state = 'untilprefix' + print """ # # Checks for ICE_HOME environment variable. # @@ -417,9 +417,9 @@ ICE_DIR = $(ICE_HOME) prefix = $(ICE_DIR) """ - elif state == 'untilprefix': - if line.startswith('prefix'): - state = 'done' + elif state == 'untilprefix': + if line.startswith('prefix'): + state = 'done' # # Dependency files are all going to be bogus since they contain relative # paths to Ice headers. We need to adjust this. @@ -435,16 +435,16 @@ def updateIceVersion(filename, version): print 'Updating ice version in ' + filename + ' to ' + version f = fileinput.input(filename, True) for line in f: - print line.rstrip('\n').replace('ICE_VERSION', version) + print line.rstrip('\n').replace('ICE_VERSION', version) f.close() def obliterate(files): for f in files: - if os.path.exists(f): - if os.path.isdir(f): - shutil.rmtree(f) - else: - os.remove(f) + if os.path.exists(f): + if os.path.isdir(f): + shutil.rmtree(f) + else: + os.remove(f) def extractDemos(sources, buildDir, version, distro, demoDir): """Pulls the demo directory out of a distribution and massages its @@ -460,42 +460,42 @@ def extractDemos(sources, buildDir, version, distro, demoDir): # toExtract = "%s/demo " % distro if demoDir == '': - toExtract = toExtract + " %s/ICE_LICENSE" % distro + toExtract = toExtract + " %s/ICE_LICENSE" % distro if not demoDir == 'php': - toExtract = toExtract + " %s/certs %s/config" % (distro, distro) - + toExtract = toExtract + " %s/certs %s/config" % (distro, distro) + runprog("gzip -dc " + os.path.join(sources, distro) + ".tar.gz | tar xf - " + toExtract, False) - + shutil.move(os.path.join(distro, "demo"), os.path.join(buildDir, "Ice-" + version + "-demos", "demo" + demoDir)) if os.path.exists(os.path.join(buildDir, "demotree", distro, "ICE_LICENSE")): - shutil.move(os.path.join(buildDir, "demotree", distro, "ICE_LICENSE"), \ - os.path.join(buildDir, "Ice-%s-demos" % version, "ICE_LICENSE")) + shutil.move(os.path.join(buildDir, "demotree", distro, "ICE_LICENSE"), \ + os.path.join(buildDir, "Ice-%s-demos" % version, "ICE_LICENSE")) # # 'System' copying of files here because its just easier! We don't # need any configuration out of the Python tree. # if not os.path.exists(buildDir + "/Ice-" + version + "-demos/certs"): - os.mkdir(buildDir + "/Ice-" + version + "-demos/certs") - + os.mkdir(buildDir + "/Ice-" + version + "-demos/certs") + if not os.path.exists(buildDir + "/Ice-" + version + "-demos/config"): - os.mkdir(buildDir + "/Ice-" + version + "-demos/config") + os.mkdir(buildDir + "/Ice-" + version + "-demos/config") if os.path.exists('%s/certs' % distro): - runprog("cp -pR " + distro + "/certs " + buildDir + "/Ice-" + version + "-demos") + runprog("cp -pR " + distro + "/certs " + buildDir + "/Ice-" + version + "-demos") srcConfigDir = '%s/%s/config' % (os.getcwd(), distro) destConfigDir = '%s/Ice-%s-demos/config' % (buildDir, version) if not demoDir in ['py', 'vb'] and os.path.exists(srcConfigDir): - for f in os.listdir(srcConfigDir): - src = os.path.join(srcConfigDir, f) - dest = os.path.join(destConfigDir, f) - if not os.path.isdir(src) and not os.path.islink(src): - shutil.copy(src, dest) + for f in os.listdir(srcConfigDir): + src = os.path.join(srcConfigDir, f) + dest = os.path.join(destConfigDir, f) + if not os.path.isdir(src) and not os.path.islink(src): + shutil.copy(src, dest) if demoDir == 'j': - updateIceVersion(os.path.join(destConfigDir, 'common.xml'), version) + updateIceVersion(os.path.join(destConfigDir, 'common.xml'), version) # # Collect files to remove from the demo distribution. @@ -504,24 +504,24 @@ def extractDemos(sources, buildDir, version, distro, demoDir): basepath = os.path.join(buildDir, 'Ice-' + version + '-demos', 'certs') for f in ['openssl', 'makecerts']: - fullpath = os.path.join(basepath, f) + fullpath = os.path.join(basepath, f) if os.path.exists(fullpath): - remove.append(fullpath) + remove.append(fullpath) if len(demoDir) == 0: - basepath = os.path.join(buildDir, 'Ice-' + version + '-demos', 'demo') - for f in ['IcePatch2', os.path.join('Ice', 'MFC')]: - fullpath = os.path.join(basepath, f) + basepath = os.path.join(buildDir, 'Ice-' + version + '-demos', 'demo') + for f in ['IcePatch2', os.path.join('Ice', 'MFC')]: + fullpath = os.path.join(basepath, f) if os.path.exists(fullpath): - remove.append(fullpath) + remove.append(fullpath) basepath = os.path.join(buildDir, 'Ice-' + version + '-demos', 'config') if distro.startswith('Ice-'): - editMakeRules(os.path.join(basepath, 'Make.rules'), version) - editMakeRulesMak(os.path.join(basepath, 'Make.rules.mak'), version) + editMakeRules(os.path.join(basepath, 'Make.rules'), version) + editMakeRulesMak(os.path.join(basepath, 'Make.rules.mak'), version) elif distro.startswith('IceCS-'): - editMakeRulesCS(os.path.join(basepath, 'Make.rules.cs'), version) + editMakeRulesCS(os.path.join(basepath, 'Make.rules.cs'), version) # # Remove collected files. @@ -535,8 +535,8 @@ def archiveDemoTree(buildDir, version, installFiles): cwd = os.getcwd() os.chdir(os.path.join(buildDir, 'Ice-%s-demos' % version)) filesToRemove = ['certs/makecerts.py', 'certs/ImportKey.java', 'certs/ImportKey.class', 'certs/seed.dat', - 'config/convertssl.py', 'config/upgradeicegrid.py', 'config/icegrid-slice.3.1.ice.gz', 'config/PropertyNames.def', 'config/makeprops.py', - 'config/TestUtil.py', 'config/IceGridAdmin.py', 'config/ice_ca.cnf', 'config/icegridgui.pro'] + 'config/convertssl.py', 'config/upgradeicegrid.py', 'config/icegrid-slice.3.1.ice.gz', 'config/PropertyNames.def', 'config/makeprops.py', + 'config/TestUtil.py', 'config/IceGridAdmin.py', 'config/ice_ca.cnf', 'config/icegridgui.pro'] obliterate(filesToRemove) os.chdir(buildDir) @@ -571,9 +571,9 @@ def makeInstall(sources, buildDir, installDir, distro, clean, version, mmVersion shutil.rmtree(distro, True) if not os.path.exists(distro): - filename = sources + '/' + distro + '.tar' + filename = sources + '/' + distro + '.tar' runprog('gzip -d %s.gz' % filename) - runprog('tar xf %s' % filename) + runprog('tar xf %s' % filename) runprog('gzip -9 %s' % filename) os.chdir(distro) @@ -585,18 +585,18 @@ def makeInstall(sources, buildDir, installDir, distro, clean, version, mmVersion if distro.startswith('IceJ'): initDirectory(installDir) initDirectory(os.path.join(installDir, 'lib')) - shutil.copy(buildDir + '/' + distro + '/lib/Ice.jar', installDir + '/lib') - shutil.copy(buildDir + '/' + distro + '/lib/IceGridGUI.jar', installDir + '/lib') - # - # We really just want to copy the files, not move them. - # Shelling out to a copy is easier (and more likely to always - # work) than shutil.copytree(). - # - runprog('cp -pR ' + buildDir + '/' + distro + '/ant ' + installDir) - runprog('find ' + installDir + '/ant -name "*.java" | xargs rm') - destDir = os.path.join(installDir, 'config') - if not os.path.exists(destDir): - os.mkdir(destDir) + shutil.copy(buildDir + '/' + distro + '/lib/Ice.jar', installDir + '/lib') + shutil.copy(buildDir + '/' + distro + '/lib/IceGridGUI.jar', installDir + '/lib') + # + # We really just want to copy the files, not move them. + # Shelling out to a copy is easier (and more likely to always + # work) than shutil.copytree(). + # + runprog('cp -pR ' + buildDir + '/' + distro + '/ant ' + installDir) + runprog('find ' + installDir + '/ant -name "*.java" | xargs rm') + destDir = os.path.join(installDir, 'config') + if not os.path.exists(destDir): + os.mkdir(destDir) shutil.copy(os.path.join('config', 'build.properties'), destDir) os.chdir(cwd) return @@ -610,32 +610,32 @@ def makeInstall(sources, buildDir, installDir, distro, clean, version, mmVersion if pyHome == None or pyHome == '': logging.info('PYTHON_HOME is not set, figuring it out and trying that') pyHome = sys.exec_prefix - os.environ['PYTHON_HOME'] = pyHome + os.environ['PYTHON_HOME'] = pyHome # # XXX- Optimizations need to be turned on for the release. # try: - runprog('gmake NOGAC=yes OPTIMIZE=yes prefix=%s embedded_runpath_prefix=/opt/Ice-%s install' % (installDir, mmVersion)) + runprog('gmake NOGAC=yes OPTIMIZE=yes prefix=%s embedded_runpath_prefix=/opt/Ice-%s install' % (installDir, mmVersion)) except ExtProgramError: - print "gmake failed for makeInstall(%s, %s, %s, %s, %s, %s, %s)" % (sources, buildDir, installDir, distro, str(clean), version, mmVersion) - raise + print "gmake failed for makeInstall(%s, %s, %s, %s, %s, %s, %s)" % (sources, buildDir, installDir, distro, str(clean), version, mmVersion) + raise runprog('rm -rf /opt/Ice-%s' % (mmVersion), False) if distro.startswith('IceCS'): - assemblies = ["glacier2cs", "iceboxcs", "icecs", "icegridcs", "icepatch2cs", "icestormcs"] + assemblies = ["glacier2cs", "iceboxcs", "icecs", "icegridcs", "icepatch2cs", "icestormcs"] - # - # We are relying on pkgconfig to deal with some mono library - # configuration, so we need to copy these files into place. - # - if not os.path.exists("%s/lib/pkgconfig" % installDir): - os.makedirs("%s/lib/pkgconfig" % installDir) + # + # We are relying on pkgconfig to deal with some mono library + # configuration, so we need to copy these files into place. + # + if not os.path.exists("%s/lib/pkgconfig" % installDir): + os.makedirs("%s/lib/pkgconfig" % installDir) - for a in assemblies: - shutil.copy("bin/%s.dll" % a, "%s/bin/%s.dll" % (installDir, a)) - shutil.copy("lib/pkgconfig/%s.pc" % a, "%s/lib/pkgconfig" % installDir) + for a in assemblies: + shutil.copy("bin/%s.dll" % a, "%s/bin/%s.dll" % (installDir, a)) + shutil.copy("lib/pkgconfig/%s.pc" % a, "%s/lib/pkgconfig" % installDir) os.chdir(cwd) @@ -653,11 +653,11 @@ def shlibExtensions(versionString, versionInt): def getPlatformLibExtension(): platform = getPlatform() if platform == 'hpux': - return '.sl' + return '.sl' elif platform == 'macosx': - return '.dylib' + return '.dylib' else: - return '.so' + return '.so' def getDBfiles(dbLocation): cwd = os.getcwd() @@ -672,18 +672,18 @@ def getDBfiles(dbLocation): findCmd = '' if getPlatform() == 'solaris': - findCmd = 'find lib -name "*' + getPlatformLibExtension() + '" -type f -maxdepth 1' + findCmd = 'find lib -name "*' + getPlatformLibExtension() + '" -type f -maxdepth 1' elif getPlatform() == 'macosx': - findCmd = 'find lib \( -name "*' + getPlatformLibExtension() + '" -or -name "*jnilib" \) -type f ' + findCmd = 'find lib \( -name "*' + getPlatformLibExtension() + '" -or -name "*jnilib" \) -type f ' else: - findCmd = 'find lib -name "*' + getPlatformLibExtension() + '" -type f' + findCmd = 'find lib -name "*' + getPlatformLibExtension() + '" -type f' pipe_stdin, pipe_stdout = os.popen2(findCmd) lines = pipe_stdout.readlines() pipe_stdin.close() pipe_stdout.close() fileList.extend(lines) if getPlatform() == 'aix': - fileList.append('lib/libdb_cxx.so') + fileList.append('lib/libdb_cxx.so') os.chdir(cwd) return fileList @@ -695,9 +695,9 @@ def copyExpatFiles(expatLocation, version): fileList = [] findCmd = '' if getPlatform() == 'solaris': - findCmd = 'find lib -name "*' + getPlatformLibExtension() + '" -type f -maxdepth 1' + findCmd = 'find lib -name "*' + getPlatformLibExtension() + '" -type f -maxdepth 1' else: - findCmd = 'find lib -name "*' + getPlatformLibExtension() + '" -type f' + findCmd = 'find lib -name "*' + getPlatformLibExtension() + '" -type f' pipe_stdin, pipe_stdout = os.popen2(findCmd) lines = pipe_stdout.readlines() pipe_stdin.close() @@ -707,9 +707,9 @@ def copyExpatFiles(expatLocation, version): linkList = [] findCmd = '' if getPlatform() == 'solaris': - findCmd = 'find lib -name "*' + getPlatformLibExtension() + '" -type l -maxdepth 1' + findCmd = 'find lib -name "*' + getPlatformLibExtension() + '" -type l -maxdepth 1' else: - findCmd = 'find lib -name "*' + getPlatformLibExtension() + '" -type l' + findCmd = 'find lib -name "*' + getPlatformLibExtension() + '" -type l' pipe_stdin, pipe_stdout = os.popen2(findCmd) lines = pipe_stdout.readlines() pipe_stdin.close() @@ -717,14 +717,14 @@ def copyExpatFiles(expatLocation, version): fileList.extend(lines) for i in lines: - if i != 'libexpat.' + getPlatformLibExtension(): - linkList.append(i) + if i != 'libexpat.' + getPlatformLibExtension(): + linkList.append(i) os.chdir(cwd) if not os.path.exists('Ice-' + version + '/' + fileList[0].strip()): - shutil.copy(expatLocation + '/' + fileList[0].strip(), 'Ice-' + version + '/' + fileList[0].strip()) - os.symlink(os.path.basename(fileList[0].strip()), 'Ice-' + version + '/' + linkList[0].strip()) + shutil.copy(expatLocation + '/' + fileList[0].strip(), 'Ice-' + version + '/' + fileList[0].strip()) + os.symlink(os.path.basename(fileList[0].strip()), 'Ice-' + version + '/' + linkList[0].strip()) def usage(): """Print usage/help information""" @@ -742,7 +742,7 @@ def usage(): print ' If this is omitted makebindist will traverse' print ' ../icej ../icepy ../icecs, etc and make the' print ' distributions for you.' - print ' (Note: makedist.py seems to only work on Linux.' + print ' (Note: makedist.py seems to only work on Linux.' print ' To use makebindist.py on other UNIX platforms,' print ' you must copy pre-made source distributions onto' print ' the host and use this option to reference their' @@ -753,7 +753,7 @@ def usage(): print ' applicable (some bits will still be cleaned.' print '--nobuild Run through the process but don\'t build' print ' anything new.' - print '--usecvs Use contents of existing CVS directories' + print '--usecvs Use contents of existing CVS directories' print ' to create binary package.' print print 'The following options set the locations for third party libraries' @@ -777,7 +777,7 @@ def usage(): print ' (default=/opt/db).' print '--sslhome=[path] Specify location of OpenSSL' print ' (default=/opt/openssl).' - print '--expathome=[path] Specify location of expat libraries ' + print '--expathome=[path] Specify location of expat libraries ' print ' (default=/opt/expat).' print '--readlinehome=[path] Specify readline library and location ' print ' (defaults to /opt/readline if set).' @@ -808,8 +808,8 @@ def main(): optionList, args = getopt.getopt(sys.argv[1:], 'hvt:', [ 'build-dir=', 'install-dir=', 'install-root=', 'sources=', 'verbose', 'tag=', 'noclean', 'nobuild', - 'stlporthome=', 'bzip2home=', 'dbhome=', 'sslhome=', - 'expathome=', 'readlinehome=', 'usecvs', 'offline', 'debug']) + 'stlporthome=', 'bzip2home=', 'dbhome=', 'sslhome=', + 'expathome=', 'readlinehome=', 'usecvs', 'offline', 'debug']) except getopt.GetoptError: usage() @@ -835,51 +835,51 @@ def main(): clean = False elif o == '--nobuild': build = False - elif o == '--stlporthome': - buildEnvironment['STLPORT_HOME'] = a - elif o == '--bzip2home': - buildEnvironment['BZIP2_HOME'] = a - elif o == '--dbhome': - buildEnvironment['DB_HOME'] = a - elif o == '--sslhome': - buildEnvironment['OPENSSL_HOME'] = a - elif o == '--expathome': - buildEnvironment['EXPAT_HOME'] = a - elif o == '--readlinehome': - buildEnvironment['READLINE_HOME'] = a - elif o == '--offline': - offline = True - elif o == '--usecvs': - cvsMode = True + elif o == '--stlporthome': + buildEnvironment['STLPORT_HOME'] = a + elif o == '--bzip2home': + buildEnvironment['BZIP2_HOME'] = a + elif o == '--dbhome': + buildEnvironment['DB_HOME'] = a + elif o == '--sslhome': + buildEnvironment['OPENSSL_HOME'] = a + elif o == '--expathome': + buildEnvironment['EXPAT_HOME'] = a + elif o == '--readlinehome': + buildEnvironment['READLINE_HOME'] = a + elif o == '--offline': + offline = True + elif o == '--usecvs': + cvsMode = True if verbose: - logging.getLogger().setLevel(logging.DEBUG) + logging.getLogger().setLevel(logging.DEBUG) if offline and sources == None: - logging.error("You must specify a location for the sources if running in offline mode") - sys.exit(1) + logging.error("You must specify a location for the sources if running in offline mode") + sys.exit(1) # # Configure environment. # if getPlatform() == 'aix': - dylibEnvironmentVar = 'LIBPATH' + dylibEnvironmentVar = 'LIBPATH' elif getPlatform() == 'hpux': - dylibEnvironmentVar = 'SHLIB_PATH' + dylibEnvironmentVar = 'SHLIB_PATH' else: - dylibEnvironmentVar = 'LD_LIBRARY_PATH' + dylibEnvironmentVar = 'LD_LIBRARY_PATH' for k, v in buildEnvironment.iteritems(): - os.environ[k] = v - if os.environ.has_key(dylibEnvironmentVar): - os.environ[dylibEnvironmentVar] = v + '/lib:' + os.environ[dylibEnvironmentVar] + os.environ[k] = v + if os.environ.has_key(dylibEnvironmentVar): + os.environ[dylibEnvironmentVar] = v + '/lib:' + os.environ[dylibEnvironmentVar] if buildDir == None: print 'No build directory specified, defaulting to $HOME/tmp/icebuild' buildDir = os.environ.get('HOME') + '/tmp/icebuild' if cvsMode: - print 'Using CVS mode' + print 'Using CVS mode' if installDir == None: print 'No install directory specified, default to $HOME/tmp/iceinstall' @@ -899,9 +899,9 @@ def main(): # the build sources. # if cvsMode: - directories = [] + directories = [] else: - directories = [buildDir, buildDir + '/sources', buildDir + '/demotree'] + directories = [buildDir, buildDir + '/sources', buildDir + '/demotree'] directories.append(installDir) @@ -913,18 +913,18 @@ def main(): # installFiles = None if cvsMode: - version = getIceVersion('include/IceUtil/Config.h') - soVersion = getIceSoVersion('include/IceUtil/Config.h') + version = getIceVersion('include/IceUtil/Config.h') + soVersion = getIceSoVersion('include/IceUtil/Config.h') mmVersion = getIceMMVersion('include/IceUtil/Config.h') - installFiles = 'install' + installFiles = 'install' elif offline: - version = getIceVersion('include/IceUtil/Config.h') - soVersion = getIceSoVersion('include/IceUtil/Config.h') - mmVersion = getIceMMVersion('include/IceUtil/Config.h') - installFiles = getInstallFilesFromLocalDirectory(cvsTag, buildDir, version, mmVersion) + version = getIceVersion('include/IceUtil/Config.h') + soVersion = getIceSoVersion('include/IceUtil/Config.h') + mmVersion = getIceMMVersion('include/IceUtil/Config.h') + installFiles = getInstallFilesFromLocalDirectory(cvsTag, buildDir, version, mmVersion) else: - version, soVersion, mmVersion = getVersion(cvsTag, buildDir) - installFiles = getInstallFiles(cvsTag, buildDir, version, mmVersion) + version, soVersion, mmVersion = getVersion(cvsTag, buildDir) + installFiles = getInstallFiles(cvsTag, buildDir, version, mmVersion) if verbose: print 'Building binary distributions for Ice-' + version + ' on ' + getPlatform() @@ -934,20 +934,20 @@ def main(): if not cvsMode: - # - # These last build directories will have to wait until we've got - # the version number for the distribution. - # - shutil.rmtree(buildDir + '/Ice-' + version + '-demos', True) - initDirectory(buildDir + '/Ice-' + version + '-demos/config') + # + # These last build directories will have to wait until we've got + # the version number for the distribution. + # + shutil.rmtree(buildDir + '/Ice-' + version + '-demos', True) + initDirectory(buildDir + '/Ice-' + version + '-demos/config') if build and not cvsMode: collectSources = False if sources == None: - if not getPlatform().startswith("linux"): - print "makedist.py is not supported on non-Linux platforms. Create the source" - print "distributions on a Linux box, copy them to a location on this host and" - print "specify their location with the --sources argument" + if not getPlatform().startswith("linux"): + print "makedist.py is not supported on non-Linux platforms. Create the source" + print "distributions on a Linux box, copy them to a location on this host and" + print "specify their location with the --sources argument" sources = buildDir + '/sources' collectSources = clean @@ -955,15 +955,15 @@ def main(): # Ice must be first or building the other source distributions will fail. # sourceTarBalls = [ ('ice', 'Ice-%s' % version, ''), - ('icephp','IcePHP-%s' % version, 'php'), + ('icephp','IcePHP-%s' % version, 'php'), ('icej','IceJ-%s-java2' % version, 'j'), - ('icerb', 'IceRuby-%s' % version, 'rb')] + ('icerb', 'IceRuby-%s' % version, 'rb')] - if not getPlatform() in ['aix', 'solaris', 'hpux']: - sourceTarBalls.append(('icepy','IcePy-' + version, 'py')) + if not getPlatform() in ['aix', 'solaris', 'hpux']: + sourceTarBalls.append(('icepy','IcePy-' + version, 'py')) - if getPlatform().startswith("linux"): - sourceTarBalls.append(('icecs','IceCS-' + version, 'cs')) + if getPlatform().startswith("linux"): + sourceTarBalls.append(('icecs','IceCS-' + version, 'cs')) os.environ['ICE_HOME'] = installDir + '/Ice-' + version currentLibraryPath = None @@ -978,63 +978,63 @@ def main(): os.environ[dylibEnvironmentVar] = installDir + '/Ice-' + version + '/lib64:' + installDir + '/Ice-' + version + '/lib:' + currentLibraryPath os.environ['PATH'] = installDir + '/Ice-' + version + '/bin:' + os.environ['PATH'] - # - # Collect all of the distributions first. This prevents having - # to go through costly builds before finding out that one of the - # distributions doesn't build. - # - if collectSources: - toCollect = list(sourceTarBalls) - toCollect.append(('icevb', 'IceVB-' + version, 'vb')) - for cvs, tarball, demoDir in toCollect: + # + # Collect all of the distributions first. This prevents having + # to go through costly builds before finding out that one of the + # distributions doesn't build. + # + if collectSources: + toCollect = list(sourceTarBalls) + toCollect.append(('icevb', 'IceVB-' + version, 'vb')) + for cvs, tarball, demoDir in toCollect: collectSourceDistributions(cvsTag, sources, cvs, tarball) - print ''' + print ''' >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< >> << >> Sources have been collected! << >> << >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<''' - # - # Package up demo distribution. - # - toCollect = list(sourceTarBalls) - for cvs, tarball, demoDir in toCollect: - extractDemos(sources, buildDir, version, tarball, demoDir) - shutil.copy("%s/unix/README.DEMOS" % installFiles, "%s/Ice-%s-demos/README.DEMOS" % (buildDir, version)) - archiveDemoTree(buildDir, version, installFiles) - shutil.move("%s/Ice-%s-demos.tar.gz" % (buildDir, version), "%s/Ice-%s-demos.tar.gz" % (installDir, version)) + # + # Package up demo distribution. + # + toCollect = list(sourceTarBalls) + for cvs, tarball, demoDir in toCollect: + extractDemos(sources, buildDir, version, tarball, demoDir) + shutil.copy("%s/unix/README.DEMOS" % installFiles, "%s/Ice-%s-demos/README.DEMOS" % (buildDir, version)) + archiveDemoTree(buildDir, version, installFiles) + shutil.move("%s/Ice-%s-demos.tar.gz" % (buildDir, version), "%s/Ice-%s-demos.tar.gz" % (installDir, version)) shutil.move("%s/Ice-%s-demos.zip" % (buildDir, version), "%s/Ice-%s-demos.zip" % (installDir, version)) - # - # Everything should be set for building stuff up now. - # + # + # Everything should be set for building stuff up now. + # for cvs, tarball, demoDir in sourceTarBalls: - makeInstall(sources, buildDir, "%s/Ice-%s" % (installDir, version), tarball, clean, version, mmVersion) - - # - # XXX- put java5 Ice.jar in place! - # - prevDir = os.getcwd() - os.chdir("%s/Ice-%s/lib" % (installDir, version)) - os.mkdir("java5") - os.chdir("java5") - os.system("gzip -dc %s/IceJ-%s-java5.tar.gz | tar xf - IceJ-%s-java5/lib/Ice.jar" % (sources, version, version)) - shutil.move("IceJ-%s-java5/lib/Ice.jar" % version, "Ice.jar") - shutil.rmtree("IceJ-%s-java5" % version) - os.chdir(prevDir) + makeInstall(sources, buildDir, "%s/Ice-%s" % (installDir, version), tarball, clean, version, mmVersion) + + # + # XXX- put java5 Ice.jar in place! + # + prevDir = os.getcwd() + os.chdir("%s/Ice-%s/lib" % (installDir, version)) + os.mkdir("java5") + os.chdir("java5") + os.system("gzip -dc %s/IceJ-%s-java5.tar.gz | tar xf - IceJ-%s-java5/lib/Ice.jar" % (sources, version, version)) + shutil.move("IceJ-%s-java5/lib/Ice.jar" % version, "Ice.jar") + shutil.rmtree("IceJ-%s-java5" % version) + os.chdir(prevDir) elif cvsMode: - collectSources = False + collectSources = False - # - # TODO: Sanity check to make sure that the script is being run - # from a location that it expects. - # - cvsDirs = [ 'ice', 'icej', 'icephp' ] - if getPlatform() == 'linux': - cvsDirs.append('icecs', 'icepy', 'icerb') + # + # TODO: Sanity check to make sure that the script is being run + # from a location that it expects. + # + cvsDirs = [ 'ice', 'icej', 'icephp' ] + if getPlatform() == 'linux': + cvsDirs.append('icecs', 'icepy', 'icerb') os.environ['ICE_HOME'] = os.getcwd() currentLibraryPath = None @@ -1046,18 +1046,18 @@ def main(): os.environ[dylibEnvironmentVar] = installDir + '/Ice-' + version + '/lib:' + currentLibraryPath os.environ['PATH'] = installDir + '/Ice-' + version + '/bin:' + os.environ['PATH'] - for d in cvsDirs: - currentDir = os.getcwd() - os.chdir('../' + d) - print 'Going to directory ' + d - if d == 'icej': - shutil.copy('lib/Ice.jar', installDir +'/Ice-' + version + '/lib') - shutil.copy('lib/IceGridGUI.jar', installDir +'/Ice-' + version + '/lib') - runprog('cp -pR ant ' + installDir + '/Ice-' + version) - runprog('find ' + installDir + '/Ice-' + version + ' -name "*.java" | xargs rm') - else: - runprog('gmake prefix=' + installDir + '/Ice-' + version + ' install') - os.chdir(currentDir) + for d in cvsDirs: + currentDir = os.getcwd() + os.chdir('../' + d) + print 'Going to directory ' + d + if d == 'icej': + shutil.copy('lib/Ice.jar', installDir +'/Ice-' + version + '/lib') + shutil.copy('lib/IceGridGUI.jar', installDir +'/Ice-' + version + '/lib') + runprog('cp -pR ant ' + installDir + '/Ice-' + version) + runprog('find ' + installDir + '/Ice-' + version + ' -name "*.java" | xargs rm') + else: + runprog('gmake prefix=' + installDir + '/Ice-' + version + ' install') + os.chdir(currentDir) # # Sources should have already been built and installed. We @@ -1069,34 +1069,34 @@ def main(): os.chdir(installDir) if not getPlatform().startswith('linux'): - # - # Get third party libraries. - # - dbLocation = os.environ['DB_HOME'] - dbFiles = getDBfiles(dbLocation) - for f in dbFiles: + # + # Get third party libraries. + # + dbLocation = os.environ['DB_HOME'] + dbFiles = getDBfiles(dbLocation) + for f in dbFiles: if not os.path.exists('Ice-' + version + '/' + f.strip()): shutil.copy(dbLocation + '/' + f.strip(), 'Ice-' + version + '/' + f.strip()) if getPlatform() == 'macosx': - copyExpatFiles(os.environ['EXPAT_HOME'], version) + copyExpatFiles(os.environ['EXPAT_HOME'], version) if getPlatform() == 'hpux': - ssl = os.environ['OPENSSL_HOME'] - shutil.copy('%s/bin/openssl' % ssl, 'Ice-%s/bin' % version) -# runprog('cp -R ' + ssl + '/include Ice-' + version) - runprog('cp ' + ssl + '/lib/lib*.sl.* Ice-' + version + '/lib') - runprog('rm -rf Ice-' + version + '/lib/libfips*') + ssl = os.environ['OPENSSL_HOME'] + shutil.copy('%s/bin/openssl' % ssl, 'Ice-%s/bin' % version) +# runprog('cp -R ' + ssl + '/include Ice-' + version) + runprog('cp ' + ssl + '/lib/lib*.sl.* Ice-' + version + '/lib') + runprog('rm -rf Ice-' + version + '/lib/libfips*') runprog('rm -rf Ice-' + version + '/lib/engines') - runprog('rm -rf Ice-' + version + '/lib/pkgconfig') - runprog('rm -f Ice-' + version + '/lib/*.a') + runprog('rm -rf Ice-' + version + '/lib/pkgconfig') + runprog('rm -f Ice-' + version + '/lib/*.a') uname = readcommand('uname') platformSpecificFiles = [ 'README', 'SOURCES', 'THIRD_PARTY_LICENSE' ] for psf in platformSpecificFiles: - cf = os.path.join(installFiles, 'unix', psf + '.' + uname) - if os.path.exists(cf): - shutil.copy(cf, os.path.join('Ice-' + version, psf)) + cf = os.path.join(installFiles, 'unix', psf + '.' + uname) + if os.path.exists(cf): + shutil.copy(cf, os.path.join('Ice-' + version, psf)) # # Remove build files from binary distribution. diff --git a/cpp/makedist.py b/cpp/makedist.py index 32993c47217..b0e635c2780 100755 --- a/cpp/makedist.py +++ b/cpp/makedist.py @@ -185,9 +185,9 @@ def fixVersion(files, version, mmversion): os.rename(file, origfile) oldFile = open(origfile, "r") newFile = open(file, "w") - line = oldFile.read(); - line = re.sub("@ver@", version, line) - line = re.sub("@mmver@", mmversion, line) + line = oldFile.read(); + line = re.sub("@ver@", version, line) + line = re.sub("@mmver@", mmversion, line) newFile.write(line) newFile.close() oldFile.close() diff --git a/cpp/slice/Glacier2/Router.ice b/cpp/slice/Glacier2/Router.ice index 05a5e87b8c5..dc94a93a216 100644 --- a/cpp/slice/Glacier2/Router.ice +++ b/cpp/slice/Glacier2/Router.ice @@ -108,7 +108,7 @@ interface Router extends Ice::Router * **/ Session* createSession(string userId, string password) - throws PermissionDeniedException, CannotCreateSessionException; + throws PermissionDeniedException, CannotCreateSessionException; /** * @@ -140,7 +140,7 @@ interface Router extends Ice::Router * **/ Session* createSessionFromSecureConnection() - throws PermissionDeniedException, CannotCreateSessionException; + throws PermissionDeniedException, CannotCreateSessionException; /** * @@ -151,7 +151,7 @@ interface Router extends Ice::Router * **/ void destroySession() - throws SessionNotExistException; + throws SessionNotExistException; /** * diff --git a/cpp/slice/Glacier2/Session.ice b/cpp/slice/Glacier2/Session.ice index f32bb1103a4..d8c725a99e4 100644 --- a/cpp/slice/Glacier2/Session.ice +++ b/cpp/slice/Glacier2/Session.ice @@ -229,7 +229,7 @@ interface SessionManager * **/ Session* create(string userId, SessionControl* control) - throws CannotCreateSessionException; + throws CannotCreateSessionException; }; /** @@ -261,7 +261,7 @@ interface SSLSessionManager * **/ Session* create(SSLInfo info, SessionControl* control) - throws CannotCreateSessionException; + throws CannotCreateSessionException; }; }; diff --git a/cpp/slice/Ice/Locator.ice b/cpp/slice/Ice/Locator.ice index b5f786b272d..7c724c55d8d 100644 --- a/cpp/slice/Ice/Locator.ice +++ b/cpp/slice/Ice/Locator.ice @@ -92,7 +92,7 @@ interface Locator * **/ ["amd", "nonmutating", "cpp:const"] idempotent Object* findObjectById(Ice::Identity id) - throws ObjectNotFoundException; + throws ObjectNotFoundException; /** * @@ -108,7 +108,7 @@ interface Locator * **/ ["amd", "nonmutating", "cpp:const"] idempotent Object* findAdapterById(string id) - throws AdapterNotFoundException; + throws AdapterNotFoundException; /** * @@ -153,7 +153,7 @@ interface LocatorRegistry * **/ ["amd", "ami"] idempotent void setAdapterDirectProxy(string id, Object* proxy) - throws AdapterNotFoundException, AdapterAlreadyActiveException; + throws AdapterNotFoundException, AdapterAlreadyActiveException; /** * @@ -181,7 +181,7 @@ interface LocatorRegistry * **/ ["amd", "ami"] idempotent void setReplicatedAdapterDirectProxy(string adapterId, string replicaGroupId, Object* p) - throws AdapterNotFoundException, AdapterAlreadyActiveException, InvalidReplicaGroupIdException; + throws AdapterNotFoundException, AdapterAlreadyActiveException, InvalidReplicaGroupIdException; /** * @@ -196,7 +196,7 @@ interface LocatorRegistry * **/ ["amd"] idempotent void setServerProcessProxy(string id, Process* proxy) - throws ServerNotFoundException; + throws ServerNotFoundException; }; }; diff --git a/cpp/slice/IceGrid/Admin.ice b/cpp/slice/IceGrid/Admin.ice index 126af90baf0..f682430d39a 100644 --- a/cpp/slice/IceGrid/Admin.ice +++ b/cpp/slice/IceGrid/Admin.ice @@ -397,7 +397,7 @@ interface Admin * **/ ["ami"] void addApplication(ApplicationDescriptor descriptor) - throws AccessDeniedException, DeploymentException; + throws AccessDeniedException, DeploymentException; /** * @@ -419,7 +419,7 @@ interface Admin * **/ ["ami"] void syncApplication(ApplicationDescriptor descriptor) - throws AccessDeniedException, DeploymentException, ApplicationNotExistException; + throws AccessDeniedException, DeploymentException, ApplicationNotExistException; /** * @@ -440,7 +440,7 @@ interface Admin * **/ ["ami"] void updateApplication(ApplicationUpdateDescriptor descriptor) - throws AccessDeniedException, DeploymentException, ApplicationNotExistException; + throws AccessDeniedException, DeploymentException, ApplicationNotExistException; /** * @@ -457,7 +457,7 @@ interface Admin * **/ ["ami"] void removeApplication(string name) - throws AccessDeniedException, DeploymentException, ApplicationNotExistException; + throws AccessDeniedException, DeploymentException, ApplicationNotExistException; /** * @@ -483,7 +483,7 @@ interface Admin * **/ void instantiateServer(string application, string node, ServerInstanceDescriptor desc) - throws AccessDeniedException, ApplicationNotExistException, DeploymentException; + throws AccessDeniedException, ApplicationNotExistException, DeploymentException; /** * @@ -501,7 +501,7 @@ interface Admin * **/ ["ami", "amd"] void patchApplication(string name, bool shutdown) - throws ApplicationNotExistException, PatchException; + throws ApplicationNotExistException, PatchException; /** * @@ -516,7 +516,7 @@ interface Admin * **/ ["nonmutating", "cpp:const"] idempotent ApplicationInfo getApplicationInfo(string name) - throws ApplicationNotExistException; + throws ApplicationNotExistException; /** * @@ -527,7 +527,7 @@ interface Admin * **/ ["nonmutating", "cpp:const"] idempotent ApplicationDescriptor getDefaultApplicationDescriptor() - throws DeploymentException; + throws DeploymentException; /** * @@ -550,7 +550,7 @@ interface Admin * **/ ["nonmutating", "cpp:const"] idempotent ServerInfo getServerInfo(string id) - throws ServerNotExistException; + throws ServerNotExistException; /** * @@ -570,7 +570,7 @@ interface Admin * **/ ["nonmutating", "cpp:const"] idempotent ServerState getServerState(string id) - throws ServerNotExistException, NodeUnreachableException, DeploymentException; + throws ServerNotExistException, NodeUnreachableException, DeploymentException; /** * @@ -591,7 +591,7 @@ interface Admin * **/ ["nonmutating", "cpp:const"] idempotent int getServerPid(string id) - throws ServerNotExistException, NodeUnreachableException, DeploymentException; + throws ServerNotExistException, NodeUnreachableException, DeploymentException; /** * @@ -614,7 +614,7 @@ interface Admin * **/ ["ami"] idempotent void enableServer(string id, bool enabled) - throws ServerNotExistException, NodeUnreachableException, DeploymentException; + throws ServerNotExistException, NodeUnreachableException, DeploymentException; /** * @@ -633,7 +633,7 @@ interface Admin * **/ ["nonmutating", "cpp:const"] idempotent bool isServerEnabled(string id) - throws ServerNotExistException, NodeUnreachableException, DeploymentException; + throws ServerNotExistException, NodeUnreachableException, DeploymentException; /** * @@ -658,7 +658,7 @@ interface Admin * **/ ["ami"] void startServer(string id) - throws ServerNotExistException, ServerStartException, NodeUnreachableException, DeploymentException; + throws ServerNotExistException, ServerStartException, NodeUnreachableException, DeploymentException; /** * @@ -680,7 +680,7 @@ interface Admin * **/ ["ami"] void stopServer(string id) - throws ServerNotExistException, ServerStopException, NodeUnreachableException, DeploymentException; + throws ServerNotExistException, ServerStopException, NodeUnreachableException, DeploymentException; /** * @@ -704,7 +704,7 @@ interface Admin * **/ ["ami", "amd"] void patchServer(string id, bool shutdown) - throws ServerNotExistException, NodeUnreachableException, DeploymentException, PatchException; + throws ServerNotExistException, NodeUnreachableException, DeploymentException, PatchException; /** * @@ -728,7 +728,7 @@ interface Admin * **/ ["ami"] void sendSignal(string id, string signal) - throws ServerNotExistException, NodeUnreachableException, DeploymentException, BadSignalException; + throws ServerNotExistException, NodeUnreachableException, DeploymentException, BadSignalException; /** * @@ -751,7 +751,7 @@ interface Admin * **/ ["ami"] void writeMessage(string id, string message, int fd) - throws ServerNotExistException, NodeUnreachableException, DeploymentException; + throws ServerNotExistException, NodeUnreachableException, DeploymentException; /** * @@ -780,7 +780,7 @@ interface Admin * **/ ["nonmutating", "cpp:const"] idempotent AdapterInfoSeq getAdapterInfo(string id) - throws AdapterNotExistException; + throws AdapterNotExistException; /** * @@ -791,7 +791,7 @@ interface Admin * **/ ["ami"] void removeAdapter(string adapterId) - throws AdapterNotExistException, DeploymentException; + throws AdapterNotExistException, DeploymentException; /** * @@ -819,7 +819,7 @@ interface Admin * **/ ["ami"] void addObject(Object* obj) - throws ObjectExistsException, DeploymentException; + throws ObjectExistsException, DeploymentException; /** * @@ -839,7 +839,7 @@ interface Admin * **/ void updateObject(Object* obj) - throws ObjectNotRegisteredException, DeploymentException; + throws ObjectNotRegisteredException, DeploymentException; /** * @@ -855,7 +855,7 @@ interface Admin * **/ ["ami"] void addObjectWithType(Object* obj, string type) - throws ObjectExistsException, DeploymentException; + throws ObjectExistsException, DeploymentException; /** * @@ -876,7 +876,7 @@ interface Admin * **/ ["ami"] void removeObject(Ice::Identity id) - throws ObjectNotRegisteredException, DeploymentException; + throws ObjectNotRegisteredException, DeploymentException; /** * @@ -891,7 +891,7 @@ interface Admin * **/ ["nonmutating", "cpp:const"] idempotent ObjectInfo getObjectInfo(Ice::Identity id) - throws ObjectNotRegisteredException; + throws ObjectNotRegisteredException; /** * @@ -932,7 +932,7 @@ interface Admin * **/ ["nonmutating", "cpp:const"] idempotent bool pingNode(string name) - throws NodeNotExistException; + throws NodeNotExistException; /** * @@ -949,7 +949,7 @@ interface Admin * **/ ["ami", "nonmutating", "cpp:const"] idempotent LoadInfo getNodeLoad(string name) - throws NodeNotExistException, NodeUnreachableException; + throws NodeNotExistException, NodeUnreachableException; /** * @@ -966,7 +966,7 @@ interface Admin * **/ ["nonmutating", "cpp:const"] idempotent NodeInfo getNodeInfo(string name) - throws NodeNotExistException, NodeUnreachableException; + throws NodeNotExistException, NodeUnreachableException; /** * @@ -981,7 +981,7 @@ interface Admin * **/ ["ami"] void shutdownNode(string name) - throws NodeNotExistException, NodeUnreachableException; + throws NodeNotExistException, NodeUnreachableException; /** * @@ -998,7 +998,7 @@ interface Admin * **/ ["nonmutating", "cpp:const"] idempotent string getNodeHostname(string name) - throws NodeNotExistException, NodeUnreachableException; + throws NodeNotExistException, NodeUnreachableException; /** * @@ -1021,7 +1021,7 @@ interface Admin * **/ ["cpp:const"] idempotent bool pingRegistry(string name) - throws RegistryNotExistException; + throws RegistryNotExistException; /** * @@ -1038,7 +1038,7 @@ interface Admin * **/ ["cpp:const"] idempotent RegistryInfo getRegistryInfo(string name) - throws RegistryNotExistException, RegistryUnreachableException; + throws RegistryNotExistException, RegistryUnreachableException; /** * @@ -1053,7 +1053,7 @@ interface Admin * **/ ["ami"] idempotent void shutdownRegistry(string name) - throws RegistryNotExistException, RegistryUnreachableException; + throws RegistryNotExistException, RegistryUnreachableException; /** * @@ -1109,7 +1109,7 @@ interface FileIterator * **/ bool read(int size, out Ice::StringSeq lines) - throws FileNotAvailableException; + throws FileNotAvailableException; /** * @@ -1179,8 +1179,8 @@ interface AdminSession extends Glacier2::Session * **/ idempotent void setObservers(RegistryObserver* registryObs, NodeObserver* nodeObs, ApplicationObserver* appObs, - AdapterObserver* adptObs, ObjectObserver* objObs) - throws ObserverAlreadyRegisteredException; + AdapterObserver* adptObs, ObjectObserver* objObs) + throws ObserverAlreadyRegisteredException; /** * @@ -1205,8 +1205,8 @@ interface AdminSession extends Glacier2::Session * **/ idempotent void setObserversByIdentity(Ice::Identity registryObs, Ice::Identity nodeObs, Ice::Identity appObs, - Ice::Identity adptObs, Ice::Identity objObs) - throws ObserverAlreadyRegisteredException; + Ice::Identity adptObs, Ice::Identity objObs) + throws ObserverAlreadyRegisteredException; /** * @@ -1220,7 +1220,7 @@ interface AdminSession extends Glacier2::Session * **/ int startUpdate() - throws AccessDeniedException; + throws AccessDeniedException; /** * @@ -1231,7 +1231,7 @@ interface AdminSession extends Glacier2::Session * **/ void finishUpdate() - throws AccessDeniedException; + throws AccessDeniedException; /** * @@ -1273,7 +1273,7 @@ interface AdminSession extends Glacier2::Session * **/ FileIterator* openServerLog(string id, string path, int count) - throws FileNotAvailableException, ServerNotExistException, NodeUnreachableException, DeploymentException; + throws FileNotAvailableException, ServerNotExistException, NodeUnreachableException, DeploymentException; /** * @@ -1302,7 +1302,7 @@ interface AdminSession extends Glacier2::Session * **/ FileIterator* openServerStdErr(string id, int count) - throws FileNotAvailableException, ServerNotExistException, NodeUnreachableException, DeploymentException; + throws FileNotAvailableException, ServerNotExistException, NodeUnreachableException, DeploymentException; /** * @@ -1331,7 +1331,7 @@ interface AdminSession extends Glacier2::Session * **/ FileIterator* openServerStdOut(string id, int count) - throws FileNotAvailableException, ServerNotExistException, NodeUnreachableException, DeploymentException; + throws FileNotAvailableException, ServerNotExistException, NodeUnreachableException, DeploymentException; /** * @@ -1356,7 +1356,7 @@ interface AdminSession extends Glacier2::Session * **/ FileIterator* openNodeStdErr(string name, int count) - throws FileNotAvailableException, NodeNotExistException, NodeUnreachableException; + throws FileNotAvailableException, NodeNotExistException, NodeUnreachableException; /** * @@ -1381,7 +1381,7 @@ interface AdminSession extends Glacier2::Session * **/ FileIterator* openNodeStdOut(string name, int count) - throws FileNotAvailableException, NodeNotExistException, NodeUnreachableException; + throws FileNotAvailableException, NodeNotExistException, NodeUnreachableException; /** * @@ -1407,7 +1407,7 @@ interface AdminSession extends Glacier2::Session * **/ FileIterator* openRegistryStdErr(string name, int count) - throws FileNotAvailableException, RegistryNotExistException, RegistryUnreachableException; + throws FileNotAvailableException, RegistryNotExistException, RegistryUnreachableException; /** * @@ -1433,7 +1433,7 @@ interface AdminSession extends Glacier2::Session * **/ FileIterator * openRegistryStdOut(string name, int count) - throws FileNotAvailableException, RegistryNotExistException, RegistryUnreachableException; + throws FileNotAvailableException, RegistryNotExistException, RegistryUnreachableException; }; }; diff --git a/cpp/slice/IceGrid/FileParser.ice b/cpp/slice/IceGrid/FileParser.ice index 82c21166952..b7c87ac5be3 100755 --- a/cpp/slice/IceGrid/FileParser.ice +++ b/cpp/slice/IceGrid/FileParser.ice @@ -52,7 +52,7 @@ interface FileParser **/ idempotent ApplicationDescriptor parse(string xmlFile, Admin* adminProxy) - throws ParseException; + throws ParseException; }; }; diff --git a/cpp/slice/IceGrid/Registry.ice b/cpp/slice/IceGrid/Registry.ice index 4e33a8dbb1a..3fbb6d9ef5c 100644 --- a/cpp/slice/IceGrid/Registry.ice +++ b/cpp/slice/IceGrid/Registry.ice @@ -47,7 +47,7 @@ interface Registry * **/ Session* createSession(string userId, string password) - throws PermissionDeniedException; + throws PermissionDeniedException; /** * @@ -68,7 +68,7 @@ interface Registry * **/ AdminSession* createAdminSession(string userId, string password) - throws PermissionDeniedException; + throws PermissionDeniedException; /** * @@ -89,7 +89,7 @@ interface Registry * **/ Session* createSessionFromSecureConnection() - throws PermissionDeniedException; + throws PermissionDeniedException; /** * @@ -106,7 +106,7 @@ interface Registry * **/ AdminSession* createAdminSessionFromSecureConnection() - throws PermissionDeniedException; + throws PermissionDeniedException; /** * diff --git a/cpp/slice/IceGrid/Session.ice b/cpp/slice/IceGrid/Session.ice index bd840cc674f..66e364cc1d8 100644 --- a/cpp/slice/IceGrid/Session.ice +++ b/cpp/slice/IceGrid/Session.ice @@ -60,7 +60,7 @@ interface Session extends Glacier2::Session * **/ ["ami", "amd"] Object* allocateObjectById(Ice::Identity id) - throws ObjectNotRegisteredException, AllocationException; + throws ObjectNotRegisteredException, AllocationException; /** * @@ -81,7 +81,7 @@ interface Session extends Glacier2::Session * **/ ["ami", "amd"] Object* allocateObjectByType(string type) - throws AllocationException; + throws AllocationException; /** * @@ -101,7 +101,7 @@ interface Session extends Glacier2::Session * **/ void releaseObject(Ice::Identity id) - throws ObjectNotRegisteredException, AllocationException; + throws ObjectNotRegisteredException, AllocationException; /** * diff --git a/cpp/slice/IceGrid/UserAccountMapper.ice b/cpp/slice/IceGrid/UserAccountMapper.ice index 049b9e96c8c..01492f78772 100644 --- a/cpp/slice/IceGrid/UserAccountMapper.ice +++ b/cpp/slice/IceGrid/UserAccountMapper.ice @@ -49,7 +49,7 @@ interface UserAccountMapper * **/ string getUserAccount(string user) - throws UserAccountNotFoundException; + throws UserAccountNotFoundException; }; }; diff --git a/cpp/slice/IcePatch2/FileServer.ice b/cpp/slice/IcePatch2/FileServer.ice index 099f7c2948c..de1c74b3ca2 100644 --- a/cpp/slice/IcePatch2/FileServer.ice +++ b/cpp/slice/IcePatch2/FileServer.ice @@ -76,7 +76,7 @@ interface FileServer * **/ ["ami", "nonmutating", "cpp:const"] idempotent FileInfoSeq getFileInfoSeq(int partition) - throws PartitionOutOfRangeException; + throws PartitionOutOfRangeException; /** * @@ -120,7 +120,7 @@ interface FileServer **/ ["ami", "amd", "nonmutating", "cpp:const", "cpp:array"] idempotent Ice::ByteSeq getFileCompressed(string path, int pos, int num) - throws FileAccessException; + throws FileAccessException; }; /** diff --git a/cpp/slice/IceStorm/IceStorm.ice b/cpp/slice/IceStorm/IceStorm.ice index f9a543f770a..f816b6d58ec 100644 --- a/cpp/slice/IceStorm/IceStorm.ice +++ b/cpp/slice/IceStorm/IceStorm.ice @@ -207,7 +207,7 @@ interface Topic * **/ Object* subscribeAndGetPublisher(QoS theQoS, Object* subscriber) - throws AlreadySubscribed, BadQoS; + throws AlreadySubscribed, BadQoS; /** * diff --git a/cpp/src/Freeze/ConnectionI.cpp b/cpp/src/Freeze/ConnectionI.cpp index 8b823a613ad..3f93a4eebaa 100644 --- a/cpp/src/Freeze/ConnectionI.cpp +++ b/cpp/src/Freeze/ConnectionI.cpp @@ -21,7 +21,7 @@ Freeze::ConnectionI::beginTransaction() { if(_transaction != 0) { - throw TransactionAlreadyInProgressException(__FILE__, __LINE__); + throw TransactionAlreadyInProgressException(__FILE__, __LINE__); } closeAllIterators(); _transaction = new TransactionI(this); @@ -39,21 +39,21 @@ Freeze::ConnectionI::close() { if(_transaction != 0) { - try - { - _transaction->rollback(); - } - catch(const DatabaseException&) - { - // - // Ignored - // - } + try + { + _transaction->rollback(); + } + catch(const DatabaseException&) + { + // + // Ignored + // + } } while(!_mapList.empty()) { - (*_mapList.begin())->close(); + (*_mapList.begin())->close(); } _dbEnv = 0; @@ -79,7 +79,7 @@ Freeze::ConnectionI::~ConnectionI() } Freeze::ConnectionI::ConnectionI(const CommunicatorPtr& communicator, - const string& envName, DbEnv* dbEnv) : + const string& envName, DbEnv* dbEnv) : _communicator(communicator), _dbEnv(SharedDbEnv::get(communicator, envName, dbEnv)), _envName(envName), @@ -93,9 +93,9 @@ void Freeze::ConnectionI::closeAllIterators() { for(list::iterator p = _mapList.begin(); p != _mapList.end(); - ++p) + ++p) { - (*p)->closeAllIterators(); + (*p)->closeAllIterators(); } } @@ -113,7 +113,7 @@ Freeze::ConnectionI::unregisterMap(MapHelperI* m) Freeze::ConnectionPtr Freeze::createConnection(const CommunicatorPtr& communicator, - const string& envName) + const string& envName) { return new ConnectionI(communicator, envName, 0); @@ -121,8 +121,8 @@ Freeze::createConnection(const CommunicatorPtr& communicator, Freeze::ConnectionPtr Freeze::createConnection(const CommunicatorPtr& communicator, - const string& envName, - DbEnv& dbEnv) + const string& envName, + DbEnv& dbEnv) { return new ConnectionI(communicator, envName, &dbEnv); } diff --git a/cpp/src/Freeze/ConnectionI.h b/cpp/src/Freeze/ConnectionI.h index 7ee5a59390e..987077b1adf 100644 --- a/cpp/src/Freeze/ConnectionI.h +++ b/cpp/src/Freeze/ConnectionI.h @@ -43,7 +43,7 @@ public: virtual ~ConnectionI(); ConnectionI(const Ice::CommunicatorPtr& communicator, - const std::string& envName, DbEnv*); + const std::string& envName, DbEnv*); void closeAllIterators(); @@ -101,11 +101,11 @@ ConnectionI::dbTxn() const { if(_transaction == 0) { - return 0; + return 0; } else { - return _transaction->dbTxn(); + return _transaction->dbTxn(); } } diff --git a/cpp/src/Freeze/EvictorI.cpp b/cpp/src/Freeze/EvictorI.cpp index 75e1722c004..a3bffc1a2bc 100644 --- a/cpp/src/Freeze/EvictorI.cpp +++ b/cpp/src/Freeze/EvictorI.cpp @@ -36,23 +36,23 @@ string Freeze::EvictorI::indexPrefix = "$index:"; Freeze::EvictorPtr Freeze::createEvictor(const ObjectAdapterPtr& adapter, - const string& envName, - const string& filename, - const ServantInitializerPtr& initializer, - const vector& indices, - bool createDb) + const string& envName, + const string& filename, + const ServantInitializerPtr& initializer, + const vector& indices, + bool createDb) { return new EvictorI(adapter, envName, 0, filename, initializer, indices, createDb); } Freeze::EvictorPtr Freeze::createEvictor(const ObjectAdapterPtr& adapter, - const string& envName, - DbEnv& dbEnv, - const string& filename, - const ServantInitializerPtr& initializer, - const vector& indices, - bool createDb) + const string& envName, + DbEnv& dbEnv, + const string& filename, + const ServantInitializerPtr& initializer, + const vector& indices, + bool createDb) { return new EvictorI(adapter, envName, &dbEnv, filename, initializer, indices, createDb); } @@ -78,11 +78,11 @@ handleFatalError(const Freeze::EvictorPtr& evictor, const Ice::CommunicatorPtr& IceUtil::StaticMutex::Lock lock(fatalErrorCallbackMutex); if(fatalErrorCallback != 0) { - fatalErrorCallback(evictor, communicator); + fatalErrorCallback(evictor, communicator); } else { - ::abort(); + ::abort(); } } @@ -112,7 +112,7 @@ Freeze::DeactivateController::Guard::Guard(DeactivateController& controller) : Lock sync(controller); if(controller._deactivated || _controller._deactivating) { - throw EvictorDeactivatedException(__FILE__, __LINE__); + throw EvictorDeactivatedException(__FILE__, __LINE__); } controller._guardCount++; } @@ -123,11 +123,11 @@ Freeze::DeactivateController::Guard::~Guard() _controller._guardCount--; if(_controller._deactivating && _controller._guardCount == 0) { - // - // Notify all the threads -- although we only want to - // reach the thread doing the deactivation. - // - _controller.notifyAll(); + // + // Notify all the threads -- although we only want to + // reach the thread doing the deactivation. + // + _controller.notifyAll(); } } @@ -153,40 +153,40 @@ Freeze::DeactivateController::deactivate() if(_deactivated) { - return false; + return false; } if(_deactivating) { - // - // Wait for deactivated - // - while(!_deactivated) - { - wait(); - } - return false; + // + // Wait for deactivated + // + while(!_deactivated) + { + wait(); + } + return false; } else { - _deactivating = true; - while(_guardCount > 0) - { - if(_evictor->trace() >= 1) - { - Trace out(_evictor->communicator()->getLogger(), "Freeze.Evictor"); - out << "*** Waiting for " << _guardCount << " threads to complete before starting deactivation."; - } - - wait(); - } - - if(_evictor->trace() >= 1) - { - Trace out(_evictor->communicator()->getLogger(), "Freeze.Evictor"); - out << "Starting deactivation."; - } - return true; + _deactivating = true; + while(_guardCount > 0) + { + if(_evictor->trace() >= 1) + { + Trace out(_evictor->communicator()->getLogger(), "Freeze.Evictor"); + out << "*** Waiting for " << _guardCount << " threads to complete before starting deactivation."; + } + + wait(); + } + + if(_evictor->trace() >= 1) + { + Trace out(_evictor->communicator()->getLogger(), "Freeze.Evictor"); + out << "Starting deactivation."; + } + return true; } } @@ -195,8 +195,8 @@ Freeze::DeactivateController::deactivationComplete() { if(_evictor->trace() >= 1) { - Trace out(_evictor->communicator()->getLogger(), "Freeze.Evictor"); - out << "Deactivation complete."; + Trace out(_evictor->communicator()->getLogger(), "Freeze.Evictor"); + out << "Deactivation complete."; } Lock sync(*this); @@ -225,20 +225,20 @@ Freeze::WatchDogThread::run() while(!_done) { - if(_active) - { - if(timedWait(_timeout) == false && _active && !_done) - { - Error out(_evictor.communicator()->getLogger()); - out << "Fatal error: streaming watch dog thread timed out."; - out.flush(); - handleFatalError(&_evictor, _evictor.communicator()); - } - } - else - { - wait(); - } + if(_active) + { + if(timedWait(_timeout) == false && _active && !_done) + { + Error out(_evictor.communicator()->getLogger()); + out << "Fatal error: streaming watch dog thread timed out."; + out.flush(); + handleFatalError(&_evictor, _evictor.communicator()); + } + } + else + { + wait(); + } } } @@ -270,12 +270,12 @@ Freeze::WatchDogThread::terminate() // Freeze::EvictorI::EvictorI(const ObjectAdapterPtr& adapter, - const string& envName, - DbEnv* dbEnv, - const string& filename, - const ServantInitializerPtr& initializer, - const vector& indices, - bool createDb) : + const string& envName, + DbEnv* dbEnv, + const string& filename, + const ServantInitializerPtr& initializer, + const vector& indices, + bool createDb) : _evictorSize(10), _currentEvictorSize(0), @@ -304,10 +304,10 @@ Freeze::EvictorI::EvictorI(const ObjectAdapterPtr& adapter, // _saveSizeTrigger = _communicator->getProperties()-> - getPropertyAsIntWithDefault(propertyPrefix + ".SaveSizeTrigger", 10); + getPropertyAsIntWithDefault(propertyPrefix + ".SaveSizeTrigger", 10); Int savePeriod = _communicator->getProperties()-> - getPropertyAsIntWithDefault(propertyPrefix + ".SavePeriod", 60 * 1000); + getPropertyAsIntWithDefault(propertyPrefix + ".SavePeriod", 60 * 1000); _savePeriod = IceUtil::Time::milliSeconds(savePeriod); @@ -315,17 +315,17 @@ Freeze::EvictorI::EvictorI(const ObjectAdapterPtr& adapter, // By default, we save at most 10 * SaveSizeTrigger objects per transaction // _maxTxSize = _communicator->getProperties()-> - getPropertyAsIntWithDefault(propertyPrefix + ".MaxTxSize", 10 * _saveSizeTrigger); + getPropertyAsIntWithDefault(propertyPrefix + ".MaxTxSize", 10 * _saveSizeTrigger); if(_maxTxSize <= 0) { - _maxTxSize = 100; - } + _maxTxSize = 100; + } bool populateEmptyIndices = - (_communicator->getProperties()-> - getPropertyAsIntWithDefault(propertyPrefix + ".PopulateEmptyIndices", 0) != 0); - + (_communicator->getProperties()-> + getPropertyAsIntWithDefault(propertyPrefix + ".PopulateEmptyIndices", 0) != 0); + // // Instantiate all Dbs in 2 steps: // (1) iterate over the indices and create ObjectStore with indices @@ -342,57 +342,57 @@ Freeze::EvictorI::EvictorI(const ObjectAdapterPtr& adapter, for(vector::const_iterator i = indices.begin(); i != indices.end(); ++i) { - string facet = (*i)->facet(); + string facet = (*i)->facet(); - StoreMap::iterator q = _storeMap.find(facet); - if(q == _storeMap.end()) - { - // - // New db - // + StoreMap::iterator q = _storeMap.find(facet); + if(q == _storeMap.end()) + { + // + // New db + // - vector storeIndices; + vector storeIndices; - for(vector::const_iterator r = i; r != indices.end(); ++r) - { - if((*r)->facet() == facet) - { - storeIndices.push_back(*r); - } - } - ObjectStore* store = new ObjectStore(facet, _createDb, this, storeIndices, populateEmptyIndices); - _storeMap.insert(StoreMap::value_type(facet, store)); - } + for(vector::const_iterator r = i; r != indices.end(); ++r) + { + if((*r)->facet() == facet) + { + storeIndices.push_back(*r); + } + } + ObjectStore* store = new ObjectStore(facet, _createDb, this, storeIndices, populateEmptyIndices); + _storeMap.insert(StoreMap::value_type(facet, store)); + } } for(vector::iterator p = dbs.begin(); p != dbs.end(); ++p) { - string facet = *p; - if(facet == defaultDb) - { - facet = ""; - } - - pair ir = - _storeMap.insert(StoreMap::value_type(facet, 0)); - - if(ir.second) - { - ir.first->second = new ObjectStore(facet, _createDb, this); - } + string facet = *p; + if(facet == defaultDb) + { + facet = ""; + } + + pair ir = + _storeMap.insert(StoreMap::value_type(facet, 0)); + + if(ir.second) + { + ir.first->second = new ObjectStore(facet, _createDb, this); + } } // // By default, no stream timeout // long streamTimeout = _communicator->getProperties()-> - getPropertyAsIntWithDefault(propertyPrefix+ ".StreamTimeout", 0) * 1000; + getPropertyAsIntWithDefault(propertyPrefix+ ".StreamTimeout", 0) * 1000; if(streamTimeout > 0) { - _watchDogThread = new WatchDogThread(streamTimeout, *this); - _watchDogThread->start(); + _watchDogThread = new WatchDogThread(streamTimeout, *this); + _watchDogThread->start(); } // @@ -405,13 +405,13 @@ Freeze::EvictorI::~EvictorI() { if(!_deactivateController.deactivated()) { - Warning out(_communicator->getLogger()); - out << "evictor has not been deactivated"; + Warning out(_communicator->getLogger()); + out << "evictor has not been deactivated"; - // - // Need to deactivate to save objects and join saving thread - // - deactivate(""); + // + // Need to deactivate to save objects and join saving thread + // + deactivate(""); } // @@ -419,7 +419,7 @@ Freeze::EvictorI::~EvictorI() // for(StoreMap::iterator p = _storeMap.begin(); p != _storeMap.end(); ++p) { - delete (*p).second; + delete (*p).second; } } @@ -435,7 +435,7 @@ Freeze::EvictorI::setSize(Int evictorSize) // if(evictorSize < 0) { - return; + return; } // @@ -473,35 +473,35 @@ Freeze::EvictorI::addFacet(const ObjectPtr& servant, const Identity& ident, cons for(;;) { - { - Lock sync(*this); - - StoreMap::iterator p = _storeMap.find(facet); - if(p == _storeMap.end()) - { - if(store != 0) - { - _storeMap.insert(StoreMap::value_type(facet, store)); - } - } - else - { - delete store; - store = (*p).second; - assert(store != 0); - } - } - - if(store == 0) - { - assert(facet != ""); - store = new ObjectStore(facet, _createDb, this); - // loop - } - else - { - break; // for(;;) - } + { + Lock sync(*this); + + StoreMap::iterator p = _storeMap.find(facet); + if(p == _storeMap.end()) + { + if(store != 0) + { + _storeMap.insert(StoreMap::value_type(facet, store)); + } + } + else + { + delete store; + store = (*p).second; + assert(store != 0); + } + } + + if(store == 0) + { + assert(facet != ""); + store = new ObjectStore(facet, _createDb, this); + // loop + } + else + { + break; // for(;;) + } } assert(store != 0); @@ -509,103 +509,103 @@ Freeze::EvictorI::addFacet(const ObjectPtr& servant, const Identity& ident, cons for(;;) { - // - // Create a new entry - // - - EvictorElementPtr element = new EvictorElement(*store); - element->status = EvictorElement::dead; - EvictorElementPtr oldElt = store->putIfAbsent(ident, element); + // + // Create a new entry + // + + EvictorElementPtr element = new EvictorElement(*store); + element->status = EvictorElement::dead; + EvictorElementPtr oldElt = store->putIfAbsent(ident, element); - if(oldElt != 0) - { - element = oldElt; - } - - { - Lock sync(*this); - - if(element->stale) - { - // - // Try again - // - continue; - } - fixEvictPosition(element); - - IceUtil::Mutex::Lock lock(element->mutex); - - switch(element->status) - { - case EvictorElement::clean: - case EvictorElement::created: - case EvictorElement::modified: - { - alreadyThere = true; - break; - } - case EvictorElement::destroyed: - { - element->status = EvictorElement::modified; - element->rec.servant = servant; - - // - // No need to push it on the modified queue, as a destroyed object - // is either already on the queue or about to be saved. When saved, - // it becomes dead. - // - break; - } - case EvictorElement::dead: - { - element->status = EvictorElement::created; - ObjectRecord& rec = element->rec; - - rec.servant = servant; - rec.stats.creationTime = IceUtil::Time::now().toMilliSeconds(); - rec.stats.lastSaveTime = 0; - rec.stats.avgSaveTime = 0; - - addToModifiedQueue(element); - break; - } - default: - { - assert(0); - break; - } - } - } - break; // for(;;) + if(oldElt != 0) + { + element = oldElt; + } + + { + Lock sync(*this); + + if(element->stale) + { + // + // Try again + // + continue; + } + fixEvictPosition(element); + + IceUtil::Mutex::Lock lock(element->mutex); + + switch(element->status) + { + case EvictorElement::clean: + case EvictorElement::created: + case EvictorElement::modified: + { + alreadyThere = true; + break; + } + case EvictorElement::destroyed: + { + element->status = EvictorElement::modified; + element->rec.servant = servant; + + // + // No need to push it on the modified queue, as a destroyed object + // is either already on the queue or about to be saved. When saved, + // it becomes dead. + // + break; + } + case EvictorElement::dead: + { + element->status = EvictorElement::created; + ObjectRecord& rec = element->rec; + + rec.servant = servant; + rec.stats.creationTime = IceUtil::Time::now().toMilliSeconds(); + rec.stats.lastSaveTime = 0; + rec.stats.avgSaveTime = 0; + + addToModifiedQueue(element); + break; + } + default: + { + assert(0); + break; + } + } + } + break; // for(;;) } if(alreadyThere) { - AlreadyRegisteredException ex(__FILE__, __LINE__); - ex.kindOfObject = "servant"; - ex.id = _communicator->identityToString(ident); - if(!facet.empty()) - { - ex.id += " -f " + IceUtil::escapeString(facet, ""); - } - throw ex; + AlreadyRegisteredException ex(__FILE__, __LINE__); + ex.kindOfObject = "servant"; + ex.id = _communicator->identityToString(ident); + if(!facet.empty()) + { + ex.id += " -f " + IceUtil::escapeString(facet, ""); + } + throw ex; } if(_trace >= 1) { - Trace out(_communicator->getLogger(), "Freeze.Evictor"); - out << "added object \"" << _communicator->identityToString(ident) << "\""; - if(!facet.empty()) - { - out << " with facet \"" << facet << "\""; - } + Trace out(_communicator->getLogger(), "Freeze.Evictor"); + out << "added object \"" << _communicator->identityToString(ident) << "\""; + if(!facet.empty()) + { + out << " with facet \"" << facet << "\""; + } } ObjectPrx obj = _adapter->createProxy(ident); if(!facet.empty()) { - obj = obj->ice_facet(facet); + obj = obj->ice_facet(facet); } return obj; } @@ -627,108 +627,108 @@ Freeze::EvictorI::removeFacet(const Identity& ident, const string& facet) if(store != 0) { - for(;;) - { - // - // Retrieve object - // - - EvictorElementPtr element = store->pin(ident); - if(element != 0) - { - Lock sync(*this); - if(element->stale) - { - // - // Try again - // - continue; - } - - fixEvictPosition(element); - { - IceUtil::Mutex::Lock lock(element->mutex); - - switch(element->status) - { - case EvictorElement::clean: - { - servant = element->rec.servant; - element->status = EvictorElement::destroyed; - element->rec.servant = 0; - addToModifiedQueue(element); - break; - } - case EvictorElement::created: - { - servant = element->rec.servant; - element->status = EvictorElement::dead; - element->rec.servant = 0; - break; - } - case EvictorElement::modified: - { - servant = element->rec.servant; - element->status = EvictorElement::destroyed; - element->rec.servant = 0; - // - // Not necessary to push it on the modified queue, as a modified - // element is either on the queue already or about to be saved - // (at which point it becomes clean) - // - break; - } - case EvictorElement::destroyed: - case EvictorElement::dead: - { - break; - } - default: - { - assert(0); - break; - } - } - } - if(element->keepCount > 0) - { - assert(servant != 0); - - element->keepCount = 0; - // - // Add to front of evictor queue - // - // Note that save evicts dead objects - // - _evictorList.push_front(element); - _currentEvictorSize++; - element->evictPosition = _evictorList.begin(); - } - } - break; // for(;;) - } + for(;;) + { + // + // Retrieve object + // + + EvictorElementPtr element = store->pin(ident); + if(element != 0) + { + Lock sync(*this); + if(element->stale) + { + // + // Try again + // + continue; + } + + fixEvictPosition(element); + { + IceUtil::Mutex::Lock lock(element->mutex); + + switch(element->status) + { + case EvictorElement::clean: + { + servant = element->rec.servant; + element->status = EvictorElement::destroyed; + element->rec.servant = 0; + addToModifiedQueue(element); + break; + } + case EvictorElement::created: + { + servant = element->rec.servant; + element->status = EvictorElement::dead; + element->rec.servant = 0; + break; + } + case EvictorElement::modified: + { + servant = element->rec.servant; + element->status = EvictorElement::destroyed; + element->rec.servant = 0; + // + // Not necessary to push it on the modified queue, as a modified + // element is either on the queue already or about to be saved + // (at which point it becomes clean) + // + break; + } + case EvictorElement::destroyed: + case EvictorElement::dead: + { + break; + } + default: + { + assert(0); + break; + } + } + } + if(element->keepCount > 0) + { + assert(servant != 0); + + element->keepCount = 0; + // + // Add to front of evictor queue + // + // Note that save evicts dead objects + // + _evictorList.push_front(element); + _currentEvictorSize++; + element->evictPosition = _evictorList.begin(); + } + } + break; // for(;;) + } } if(servant == 0) { - NotRegisteredException ex(__FILE__, __LINE__); - ex.kindOfObject = "servant"; - ex.id = _communicator->identityToString(ident); - if(!facet.empty()) - { - ex.id += " -f " + IceUtil::escapeString(facet, ""); - } - throw ex; + NotRegisteredException ex(__FILE__, __LINE__); + ex.kindOfObject = "servant"; + ex.id = _communicator->identityToString(ident); + if(!facet.empty()) + { + ex.id += " -f " + IceUtil::escapeString(facet, ""); + } + throw ex; } if(_trace >= 1) { - Trace out(_communicator->getLogger(), "Freeze.Evictor"); - out << "removed object \"" << _communicator->identityToString(ident) << "\""; - if(!facet.empty()) - { - out << " with facet \"" << facet << "\""; - } + Trace out(_communicator->getLogger(), "Freeze.Evictor"); + out << "removed object \"" << _communicator->identityToString(ident) << "\""; + if(!facet.empty()) + { + out << " with facet \"" << facet << "\""; + } } return servant; } @@ -750,77 +750,77 @@ Freeze::EvictorI::keepFacet(const Identity& ident, const string& facet) ObjectStore* store = findStore(facet); if(store == 0) { - notThere = true; + notThere = true; } else { - for(;;) - { - EvictorElementPtr element = store->pin(ident); - if(element == 0) - { - notThere = true; - break; - } - - Lock sync(*this); - - if(element->stale) - { - // - // try again - // - continue; - } - - - { - IceUtil::Mutex::Lock lockElement(element->mutex); - if(element->status == EvictorElement::destroyed || element->status == EvictorElement::dead) - { - notThere = true; - break; - } - } - - // - // Found! - // - - if(element->keepCount == 0) - { - if(element->usageCount < 0) - { - // - // New object - // - element->usageCount = 0; - } - else - { - _evictorList.erase(element->evictPosition); - _currentEvictorSize--; - } - element->keepCount = 1; - } - else - { - element->keepCount++; - } - break; - } + for(;;) + { + EvictorElementPtr element = store->pin(ident); + if(element == 0) + { + notThere = true; + break; + } + + Lock sync(*this); + + if(element->stale) + { + // + // try again + // + continue; + } + + + { + IceUtil::Mutex::Lock lockElement(element->mutex); + if(element->status == EvictorElement::destroyed || element->status == EvictorElement::dead) + { + notThere = true; + break; + } + } + + // + // Found! + // + + if(element->keepCount == 0) + { + if(element->usageCount < 0) + { + // + // New object + // + element->usageCount = 0; + } + else + { + _evictorList.erase(element->evictPosition); + _currentEvictorSize--; + } + element->keepCount = 1; + } + else + { + element->keepCount++; + } + break; + } } if(notThere) { - NotRegisteredException ex(__FILE__, __LINE__); - ex.kindOfObject = "servant"; - ex.id = _communicator->identityToString(ident); - if(!facet.empty()) - { - ex.id += " -f " + IceUtil::escapeString(facet, ""); - } - throw ex; + NotRegisteredException ex(__FILE__, __LINE__); + ex.kindOfObject = "servant"; + ex.id = _communicator->identityToString(ident); + if(!facet.empty()) + { + ex.id += " -f " + IceUtil::escapeString(facet, ""); + } + throw ex; } } @@ -837,38 +837,38 @@ Freeze::EvictorI::releaseFacet(const Identity& ident, const string& facet) DeactivateController::Guard deactivateGuard(_deactivateController); { - Lock sync(*this); - - StoreMap::iterator p = _storeMap.find(facet); - if(p != _storeMap.end()) - { - ObjectStore* store = (*p).second; - - EvictorElementPtr element = store->getIfPinned(ident); - if(element != 0) - { - assert(!element->stale); - if(element->keepCount > 0) - { - if(--element->keepCount == 0) - { - // - // Add to front of evictor queue - // - // Note that the element cannot be destroyed or dead since - // its keepCount was > 0. - // - _evictorList.push_front(element); - _currentEvictorSize++; - element->evictPosition = _evictorList.begin(); - } - // - // Success - // - return; - } - } - } + Lock sync(*this); + + StoreMap::iterator p = _storeMap.find(facet); + if(p != _storeMap.end()) + { + ObjectStore* store = (*p).second; + + EvictorElementPtr element = store->getIfPinned(ident); + if(element != 0) + { + assert(!element->stale); + if(element->keepCount > 0) + { + if(--element->keepCount == 0) + { + // + // Add to front of evictor queue + // + // Note that the element cannot be destroyed or dead since + // its keepCount was > 0. + // + _evictorList.push_front(element); + _currentEvictorSize++; + element->evictPosition = _evictorList.begin(); + } + // + // Success + // + return; + } + } + } } NotRegisteredException ex(__FILE__, __LINE__); @@ -876,7 +876,7 @@ Freeze::EvictorI::releaseFacet(const Identity& ident, const string& facet) ex.id = _communicator->identityToString(ident); if(!facet.empty()) { - ex.id += " -f " + IceUtil::escapeString(facet, ""); + ex.id += " -f " + IceUtil::escapeString(facet, ""); } throw ex; } @@ -888,14 +888,14 @@ Freeze::EvictorI::getIterator(const string& facet, Int batchSize) ObjectStore* store = 0; { - Lock sync(*this); - - StoreMap::iterator p = _storeMap.find(facet); - if(p != _storeMap.end()) - { - store = (*p).second; - saveNowNoSync(); - } + Lock sync(*this); + + StoreMap::iterator p = _storeMap.find(facet); + if(p != _storeMap.end()) + { + store = (*p).second; + saveNowNoSync(); + } } return new EvictorIteratorI(store, batchSize); } @@ -924,25 +924,25 @@ Freeze::EvictorI::hasFacetImpl(const Identity& ident, const string& facet) ObjectStore* store = 0; { - Lock sync(*this); + Lock sync(*this); - StoreMap::iterator p = _storeMap.find(facet); - if(p == _storeMap.end()) - { - return false; - } - - store = (*p).second; - - EvictorElementPtr element = store->getIfPinned(ident); - if(element != 0) - { - assert(!element->stale); - - IceUtil::Mutex::Lock lock(element->mutex); - return element->status != EvictorElement::dead && - element->status != EvictorElement::destroyed; - } + StoreMap::iterator p = _storeMap.find(facet); + if(p == _storeMap.end()) + { + return false; + } + + store = (*p).second; + + EvictorElementPtr element = store->getIfPinned(ident); + if(element != 0) + { + assert(!element->stale); + + IceUtil::Mutex::Lock lock(element->mutex); + return element->status != EvictorElement::dead && + element->status != EvictorElement::destroyed; + } } return store->dbHasObject(ident); } @@ -960,45 +960,45 @@ Freeze::EvictorI::hasAnotherFacet(const Identity& ident, const string& facet) // StoreMap storeMapCopy; { - Lock sync(*this); - storeMapCopy = _storeMap; - } - + Lock sync(*this); + storeMapCopy = _storeMap; + } + for(StoreMap::iterator p = storeMapCopy.begin(); p != storeMapCopy.end(); ++p) { - // - // Do not check again the given facet - // - if((*p).first != facet) - { - ObjectStore* store = (*p).second; - - bool inCache = false; - { - Lock sync(*this); - - EvictorElementPtr element = store->getIfPinned(ident); - if(element != 0) - { - inCache = true; - assert(!element->stale); - - IceUtil::Mutex::Lock lock(element->mutex); - if(element->status != EvictorElement::dead && - element->status != EvictorElement::destroyed) - { - return true; - } - } - } - if(!inCache) - { - if(store->dbHasObject(ident)) - { - return true; - } - } - } + // + // Do not check again the given facet + // + if((*p).first != facet) + { + ObjectStore* store = (*p).second; + + bool inCache = false; + { + Lock sync(*this); + + EvictorElementPtr element = store->getIfPinned(ident); + if(element != 0) + { + inCache = true; + assert(!element->stale); + + IceUtil::Mutex::Lock lock(element->mutex); + if(element->status != EvictorElement::dead && + element->status != EvictorElement::destroyed) + { + return true; + } + } + } + if(!inCache) + { + if(store->dbHasObject(ident)) + { + return true; + } + } + } } return false; } @@ -1018,48 +1018,48 @@ Freeze::EvictorI::locate(const Current& current, LocalObjectPtr& cookie) // if(current.operation == "ice_ping") { - if(hasFacetImpl(current.id, current.facet)) - { - if(_trace >= 3) - { - Trace out(_communicator->getLogger(), "Freeze.Evictor"); - out << "ice_ping found \"" << _communicator->identityToString(current.id) - << "\" with facet \"" << current.facet + "\""; - } - - cookie = 0; - return _pingObject; - } - else if(hasAnotherFacet(current.id, current.facet)) - { - if(_trace >= 3) - { - Trace out(_communicator->getLogger(), "Freeze.Evictor"); - out << "ice_ping raises FacetNotExistException for \"" << _communicator->identityToString(current.id) - << "\" with facet \"" << current.facet + "\""; - } - throw FacetNotExistException(__FILE__, __LINE__); - } - else - { - if(_trace >= 3) - { - Trace out(_communicator->getLogger(), "Freeze.Evictor"); - out << "ice_ping will raise ObjectNotExistException for \"" - << _communicator->identityToString(current.id) << "\" with facet \"" << current.facet + "\""; - } - return 0; - } + if(hasFacetImpl(current.id, current.facet)) + { + if(_trace >= 3) + { + Trace out(_communicator->getLogger(), "Freeze.Evictor"); + out << "ice_ping found \"" << _communicator->identityToString(current.id) + << "\" with facet \"" << current.facet + "\""; + } + + cookie = 0; + return _pingObject; + } + else if(hasAnotherFacet(current.id, current.facet)) + { + if(_trace >= 3) + { + Trace out(_communicator->getLogger(), "Freeze.Evictor"); + out << "ice_ping raises FacetNotExistException for \"" << _communicator->identityToString(current.id) + << "\" with facet \"" << current.facet + "\""; + } + throw FacetNotExistException(__FILE__, __LINE__); + } + else + { + if(_trace >= 3) + { + Trace out(_communicator->getLogger(), "Freeze.Evictor"); + out << "ice_ping will raise ObjectNotExistException for \"" + << _communicator->identityToString(current.id) << "\" with facet \"" << current.facet + "\""; + } + return 0; + } } ObjectPtr result = locateImpl(current, cookie); if(result == 0) { - if(hasAnotherFacet(current.id, current.facet)) - { - throw FacetNotExistException(__FILE__, __LINE__); - } + if(hasAnotherFacet(current.id, current.facet)) + { + throw FacetNotExistException(__FILE__, __LINE__); + } } return result; } @@ -1074,65 +1074,65 @@ Freeze::EvictorI::locateImpl(const Current& current, LocalObjectPtr& cookie) if(store == 0) { if(_trace >= 2) - { - Trace out(_communicator->getLogger(), "Freeze.Evictor"); - out << "locate could not find a database for facet \"" << current.facet << "\""; - } - return 0; + { + Trace out(_communicator->getLogger(), "Freeze.Evictor"); + out << "locate could not find a database for facet \"" << current.facet << "\""; + } + return 0; } for(;;) { - EvictorElementPtr element = store->pin(current.id); - if(element == 0) - { + EvictorElementPtr element = store->pin(current.id); + if(element == 0) + { if(_trace >= 2) - { - Trace out(_communicator->getLogger(), "Freeze.Evictor"); - out << "locate could not find \"" << _communicator->identityToString(current.id) << "\" in database \"" - << current.facet << "\""; - } - return 0; - } - - Lock sync(*this); - - if(element->stale) - { - // - // try again - // - continue; - } - - - IceUtil::Mutex::Lock lockElement(element->mutex); - if(element->status == EvictorElement::destroyed || element->status == EvictorElement::dead) - { + { + Trace out(_communicator->getLogger(), "Freeze.Evictor"); + out << "locate could not find \"" << _communicator->identityToString(current.id) << "\" in database \"" + << current.facet << "\""; + } + return 0; + } + + Lock sync(*this); + + if(element->stale) + { + // + // try again + // + continue; + } + + + IceUtil::Mutex::Lock lockElement(element->mutex); + if(element->status == EvictorElement::destroyed || element->status == EvictorElement::dead) + { if(_trace >= 2) - { - Trace out(_communicator->getLogger(), "Freeze.Evictor"); - out << "locate found \"" << _communicator->identityToString(current.id) - << "\" in the cache for database \"" << current.facet << "\" but it was dead or destroyed"; - } - return 0; - } - - // - // It's a good one! - // + { + Trace out(_communicator->getLogger(), "Freeze.Evictor"); + out << "locate found \"" << _communicator->identityToString(current.id) + << "\" in the cache for database \"" << current.facet << "\" but it was dead or destroyed"; + } + return 0; + } + + // + // It's a good one! + // if(_trace >= 2) - { - Trace out(_communicator->getLogger(), "Freeze.Evictor"); - out << "locate found \"" << _communicator->identityToString(current.id) << "\" in database \"" - << current.facet << "\""; - } - - fixEvictPosition(element); - element->usageCount++; - cookie = element; - assert(element->rec.servant != 0); - return element->rec.servant; + { + Trace out(_communicator->getLogger(), "Freeze.Evictor"); + out << "locate found \"" << _communicator->identityToString(current.id) << "\" in database \"" + << current.facet << "\""; + } + + fixEvictPosition(element); + element->usageCount++; + cookie = element; + assert(element->rec.servant != 0); + return element->rec.servant; } } @@ -1148,51 +1148,51 @@ Freeze::EvictorI::finished(const Current& current, const ObjectPtr& servant, con if(cookie != 0) { - EvictorElementPtr element = EvictorElementPtr::dynamicCast(cookie); - assert(element); + EvictorElementPtr element = EvictorElementPtr::dynamicCast(cookie); + assert(element); - bool enqueue = false; - - if((_useNonmutating && current.mode != Nonmutating) || - (servant->ice_operationAttributes(current.operation) & 0x1) != 0) - { - IceUtil::Mutex::Lock lock(element->mutex); - - if(element->status == EvictorElement::clean) - { - // - // Assume this operation updated the object - // - element->status = EvictorElement::modified; - enqueue = true; - } - } - - Lock sync(*this); - - // - // Only elements with a usageCount == 0 can become stale and we own - // one count! - // - assert(!element->stale); - assert(element->usageCount >= 1); - - // - // Decrease the usage count of the evictor queue element. - // - element->usageCount--; - - if(enqueue) - { - addToModifiedQueue(element); - } - else if(element->usageCount == 0 && element->keepCount == 0) - { - // - // Evict as many elements as necessary. - // - evict(); - } + bool enqueue = false; + + if((_useNonmutating && current.mode != Nonmutating) || + (servant->ice_operationAttributes(current.operation) & 0x1) != 0) + { + IceUtil::Mutex::Lock lock(element->mutex); + + if(element->status == EvictorElement::clean) + { + // + // Assume this operation updated the object + // + element->status = EvictorElement::modified; + enqueue = true; + } + } + + Lock sync(*this); + + // + // Only elements with a usageCount == 0 can become stale and we own + // one count! + // + assert(!element->stale); + assert(element->usageCount >= 1); + + // + // Decrease the usage count of the evictor queue element. + // + element->usageCount--; + + if(enqueue) + { + addToModifiedQueue(element); + } + else if(element->usageCount == 0 && element->keepCount == 0) + { + // + // Evict as many elements as necessary. + // + evict(); + } } } @@ -1201,44 +1201,44 @@ Freeze::EvictorI::deactivate(const string&) { if(_deactivateController.deactivate()) { - try - { - Lock sync(*this); - - saveNowNoSync(); - - // - // Set the evictor size to zero, meaning that we will evict - // everything possible. - // - _evictorSize = 0; - evict(); - - _savingThreadDone = true; - notifyAll(); - sync.release(); - getThreadControl().join(); - - if(_watchDogThread != 0) - { - _watchDogThread->terminate(); - _watchDogThread->getThreadControl().join(); - } - - for(StoreMap::iterator p = _storeMap.begin(); p != _storeMap.end(); ++p) - { - (*p).second->close(); - } - - _dbEnv = 0; - _initializer = 0; - } - catch(...) - { - _deactivateController.deactivationComplete(); - throw; - } - _deactivateController.deactivationComplete(); + try + { + Lock sync(*this); + + saveNowNoSync(); + + // + // Set the evictor size to zero, meaning that we will evict + // everything possible. + // + _evictorSize = 0; + evict(); + + _savingThreadDone = true; + notifyAll(); + sync.release(); + getThreadControl().join(); + + if(_watchDogThread != 0) + { + _watchDogThread->terminate(); + _watchDogThread->getThreadControl().join(); + } + + for(StoreMap::iterator p = _storeMap.begin(); p != _storeMap.end(); ++p) + { + (*p).second->close(); + } + + _dbEnv = 0; + _initializer = 0; + } + catch(...) + { + _deactivateController.deactivationComplete(); + throw; + } + _deactivateController.deactivationComplete(); } } @@ -1248,7 +1248,7 @@ Freeze::EvictorI::initialize(const Identity& ident, const string& facet, const O { if(_initializer != 0) { - _initializer->initialize(_adapter, ident, facet, servant); + _initializer->initialize(_adapter, ident, facet, servant); } } @@ -1258,387 +1258,387 @@ Freeze::EvictorI::run() { try { - for(;;) - { - deque allObjects; - deque deadObjects; - - size_t saveNowThreadsSize = 0; - - { - Lock sync(*this); - - while(!_savingThreadDone && - (_saveNowThreads.size() == 0) && - (_saveSizeTrigger < 0 || static_cast(_modifiedQueue.size()) < _saveSizeTrigger)) - { - if(_savePeriod == IceUtil::Time::milliSeconds(0)) - { - wait(); - } - else if(timedWait(_savePeriod) == false) - { - // - // Timeout, so let's save - // - break; // while - } - } - - saveNowThreadsSize = _saveNowThreads.size(); - - if(_savingThreadDone) - { - assert(_modifiedQueue.size() == 0); - assert(saveNowThreadsSize == 0); - break; // for(;;) - } - - // - // Check first if there is something to do! - // - if(_modifiedQueue.size() == 0) - { - if(saveNowThreadsSize > 0) - { - _saveNowThreads.clear(); - notifyAll(); - } - continue; // for(;;) - } - - _modifiedQueue.swap(allObjects); - } - - const size_t size = allObjects.size(); - - deque streamedObjectQueue; - - Long streamStart = IceUtil::Time::now().toMilliSeconds(); - - // - // Stream each element - // - for(size_t i = 0; i < size; i++) - { - EvictorElementPtr& element = allObjects[i]; - - bool tryAgain; - do - { - tryAgain = false; - ObjectPtr servant = 0; - - // - // These elements can't be stale as only elements with - // usageCount == 0 can become stale, and the modifiedQueue - // (us now) owns one count. - // - - IceUtil::Mutex::Lock lockElement(element->mutex); - Byte status = element->status; - - switch(status) - { - case EvictorElement::created: - case EvictorElement::modified: - { - servant = element->rec.servant; - break; - } - case EvictorElement::destroyed: - { - size_t index = streamedObjectQueue.size(); - streamedObjectQueue.resize(index + 1); - StreamedObject& obj = streamedObjectQueue[index]; - stream(element, streamStart, obj); - - element->status = EvictorElement::dead; - deadObjects.push_back(element); - - break; - } - case EvictorElement::dead: - { - deadObjects.push_back(element); - break; - } - default: - { - // - // Nothing to do (could be a duplicate) - // - break; - } - } - if(servant == 0) - { - lockElement.release(); - } - else - { - IceUtil::AbstractMutex* mutex = dynamic_cast(servant.get()); - if(mutex != 0) - { - // - // Lock servant and then element so that user can safely lock - // servant and call various Evictor operations - // - - IceUtil::AbstractMutex::TryLock lockServant(*mutex); - if(!lockServant.acquired()) - { - lockElement.release(); - - if(_watchDogThread != 0) - { - _watchDogThread->activate(); - } - lockServant.acquire(); - if(_watchDogThread != 0) - { - _watchDogThread->deactivate(); - } - - lockElement.acquire(); - status = element->status; - } + for(;;) + { + deque allObjects; + deque deadObjects; + + size_t saveNowThreadsSize = 0; + + { + Lock sync(*this); + + while(!_savingThreadDone && + (_saveNowThreads.size() == 0) && + (_saveSizeTrigger < 0 || static_cast(_modifiedQueue.size()) < _saveSizeTrigger)) + { + if(_savePeriod == IceUtil::Time::milliSeconds(0)) + { + wait(); + } + else if(timedWait(_savePeriod) == false) + { + // + // Timeout, so let's save + // + break; // while + } + } + + saveNowThreadsSize = _saveNowThreads.size(); + + if(_savingThreadDone) + { + assert(_modifiedQueue.size() == 0); + assert(saveNowThreadsSize == 0); + break; // for(;;) + } + + // + // Check first if there is something to do! + // + if(_modifiedQueue.size() == 0) + { + if(saveNowThreadsSize > 0) + { + _saveNowThreads.clear(); + notifyAll(); + } + continue; // for(;;) + } + + _modifiedQueue.swap(allObjects); + } + + const size_t size = allObjects.size(); + + deque streamedObjectQueue; + + Long streamStart = IceUtil::Time::now().toMilliSeconds(); + + // + // Stream each element + // + for(size_t i = 0; i < size; i++) + { + EvictorElementPtr& element = allObjects[i]; + + bool tryAgain; + do + { + tryAgain = false; + ObjectPtr servant = 0; + + // + // These elements can't be stale as only elements with + // usageCount == 0 can become stale, and the modifiedQueue + // (us now) owns one count. + // + + IceUtil::Mutex::Lock lockElement(element->mutex); + Byte status = element->status; + + switch(status) + { + case EvictorElement::created: + case EvictorElement::modified: + { + servant = element->rec.servant; + break; + } + case EvictorElement::destroyed: + { + size_t index = streamedObjectQueue.size(); + streamedObjectQueue.resize(index + 1); + StreamedObject& obj = streamedObjectQueue[index]; + stream(element, streamStart, obj); + + element->status = EvictorElement::dead; + deadObjects.push_back(element); + + break; + } + case EvictorElement::dead: + { + deadObjects.push_back(element); + break; + } + default: + { + // + // Nothing to do (could be a duplicate) + // + break; + } + } + if(servant == 0) + { + lockElement.release(); + } + else + { + IceUtil::AbstractMutex* mutex = dynamic_cast(servant.get()); + if(mutex != 0) + { + // + // Lock servant and then element so that user can safely lock + // servant and call various Evictor operations + // + + IceUtil::AbstractMutex::TryLock lockServant(*mutex); + if(!lockServant.acquired()) + { + lockElement.release(); + + if(_watchDogThread != 0) + { + _watchDogThread->activate(); + } + lockServant.acquire(); + if(_watchDogThread != 0) + { + _watchDogThread->deactivate(); + } + + lockElement.acquire(); + status = element->status; + } - switch(status) - { - case EvictorElement::created: - case EvictorElement::modified: - { - if(servant == element->rec.servant) - { - size_t index = streamedObjectQueue.size(); - streamedObjectQueue.resize(index + 1); - StreamedObject& obj = streamedObjectQueue[index]; - stream(element, streamStart, obj); - - element->status = EvictorElement::clean; - } - else - { - tryAgain = true; - } - break; - } - case EvictorElement::destroyed: - { - lockServant.release(); - - size_t index = streamedObjectQueue.size(); - streamedObjectQueue.resize(index + 1); - StreamedObject& obj = streamedObjectQueue[index]; - stream(element, streamStart, obj); - - element->status = EvictorElement::dead; - deadObjects.push_back(element); - break; - } - case EvictorElement::dead: - { - deadObjects.push_back(element); - break; - } - default: - { - // - // Nothing to do (could be a duplicate) - // - break; - } - } - } - else - { - DatabaseException ex(__FILE__, __LINE__); - ex.message = string(typeid(*element->rec.servant).name()) - + " does not implement IceUtil::AbstractMutex"; - throw ex; - } - } - } while(tryAgain); - } - - if(_trace >= 1) - { - Long now = IceUtil::Time::now().toMilliSeconds(); - Trace out(_communicator->getLogger(), "Freeze.Evictor"); - out << "streamed " << streamedObjectQueue.size() << " objects in " - << static_cast(now - streamStart) << " ms"; - } - - // - // Now let's save all these streamed objects to disk using a transaction - // - - // - // Each time we get a deadlock, we reduce the number of objects to save - // per transaction - // - size_t txSize = streamedObjectQueue.size(); - if(txSize > static_cast(_maxTxSize)) - { - txSize = static_cast(_maxTxSize); - } - bool tryAgain; - - do - { - tryAgain = false; - - while(streamedObjectQueue.size() > 0) - { - if(txSize > streamedObjectQueue.size()) - { - txSize = streamedObjectQueue.size(); - } - - Long saveStart = IceUtil::Time::now().toMilliSeconds(); - try - { - DbTxn* tx = 0; - _dbEnv->getEnv()->txn_begin(0, &tx, 0); - - long txnId = 0; - if(_txTrace >= 1) - { - txnId = (tx->id() & 0x7FFFFFFF) + 0x80000000L; - Trace out(_communicator->getLogger(), "Freeze.Evictor"); - out << "started transaction " << hex << txnId << dec << " in saving thread"; - } - - try - { - for(size_t i = 0; i < txSize; i++) - { - StreamedObject& obj = streamedObjectQueue[i]; - obj.store->save(obj.key, obj.value, obj.status, tx); - } - } - catch(...) - { - tx->abort(); - if(_txTrace >= 1) - { - Trace out(_communicator->getLogger(), "Freeze.Evictor"); - out << "rolled back transaction " << hex << txnId << dec; - } - throw; - } - tx->commit(0); - - if(_txTrace >= 1) - { - Trace out(_communicator->getLogger(), "Freeze.Evictor"); - out << "committed transaction " << hex << txnId << dec; - } - - streamedObjectQueue.erase - (streamedObjectQueue.begin(), - streamedObjectQueue.begin() + txSize); - - if(_trace >= 1) - { - Long now = IceUtil::Time::now().toMilliSeconds(); - Trace out(_communicator->getLogger(), "Freeze.Evictor"); - out << "saved " << txSize << " objects in " - << static_cast(now - saveStart) << " ms"; - } - } - catch(const DbDeadlockException&) - { - if(_deadlockWarning) - { - Warning out(_communicator->getLogger()); - out << "Deadlock in Freeze::EvictorI::run while writing into Db \"" + _filename - + "\"; retrying ..."; - } - - tryAgain = true; - txSize = (txSize + 1)/2; - } - catch(const DbException& dx) - { - DatabaseException ex(__FILE__, __LINE__); - ex.message = dx.what(); - throw ex; - } - } - } - while(tryAgain); - - { - Lock sync(*this); - - // - // Release usage count - // - for(deque::iterator p = allObjects.begin(); - p != allObjects.end(); p++) - { - EvictorElementPtr& element = *p; - element->usageCount--; - } - allObjects.clear(); - - for(deque::iterator q = deadObjects.begin(); - q != deadObjects.end(); q++) - { - EvictorElementPtr& element = *q; - if(!element->stale) - { - // - // Can be stale when there are duplicate elements on the - // deadObjecst queue - // - - if(!element->stale && element->usageCount == 0 && element->keepCount == 0) - { - // - // Get rid of unused dead elements - // - IceUtil::Mutex::Lock lockElement(element->mutex); - if(element->status == EvictorElement::dead) - { - evict(element); - } - } - } - } - deadObjects.clear(); - evict(); - - if(saveNowThreadsSize > 0) - { - _saveNowThreads.erase(_saveNowThreads.begin(), _saveNowThreads.begin() + saveNowThreadsSize); - notifyAll(); - } - } - } + switch(status) + { + case EvictorElement::created: + case EvictorElement::modified: + { + if(servant == element->rec.servant) + { + size_t index = streamedObjectQueue.size(); + streamedObjectQueue.resize(index + 1); + StreamedObject& obj = streamedObjectQueue[index]; + stream(element, streamStart, obj); + + element->status = EvictorElement::clean; + } + else + { + tryAgain = true; + } + break; + } + case EvictorElement::destroyed: + { + lockServant.release(); + + size_t index = streamedObjectQueue.size(); + streamedObjectQueue.resize(index + 1); + StreamedObject& obj = streamedObjectQueue[index]; + stream(element, streamStart, obj); + + element->status = EvictorElement::dead; + deadObjects.push_back(element); + break; + } + case EvictorElement::dead: + { + deadObjects.push_back(element); + break; + } + default: + { + // + // Nothing to do (could be a duplicate) + // + break; + } + } + } + else + { + DatabaseException ex(__FILE__, __LINE__); + ex.message = string(typeid(*element->rec.servant).name()) + + " does not implement IceUtil::AbstractMutex"; + throw ex; + } + } + } while(tryAgain); + } + + if(_trace >= 1) + { + Long now = IceUtil::Time::now().toMilliSeconds(); + Trace out(_communicator->getLogger(), "Freeze.Evictor"); + out << "streamed " << streamedObjectQueue.size() << " objects in " + << static_cast(now - streamStart) << " ms"; + } + + // + // Now let's save all these streamed objects to disk using a transaction + // + + // + // Each time we get a deadlock, we reduce the number of objects to save + // per transaction + // + size_t txSize = streamedObjectQueue.size(); + if(txSize > static_cast(_maxTxSize)) + { + txSize = static_cast(_maxTxSize); + } + bool tryAgain; + + do + { + tryAgain = false; + + while(streamedObjectQueue.size() > 0) + { + if(txSize > streamedObjectQueue.size()) + { + txSize = streamedObjectQueue.size(); + } + + Long saveStart = IceUtil::Time::now().toMilliSeconds(); + try + { + DbTxn* tx = 0; + _dbEnv->getEnv()->txn_begin(0, &tx, 0); + + long txnId = 0; + if(_txTrace >= 1) + { + txnId = (tx->id() & 0x7FFFFFFF) + 0x80000000L; + Trace out(_communicator->getLogger(), "Freeze.Evictor"); + out << "started transaction " << hex << txnId << dec << " in saving thread"; + } + + try + { + for(size_t i = 0; i < txSize; i++) + { + StreamedObject& obj = streamedObjectQueue[i]; + obj.store->save(obj.key, obj.value, obj.status, tx); + } + } + catch(...) + { + tx->abort(); + if(_txTrace >= 1) + { + Trace out(_communicator->getLogger(), "Freeze.Evictor"); + out << "rolled back transaction " << hex << txnId << dec; + } + throw; + } + tx->commit(0); + + if(_txTrace >= 1) + { + Trace out(_communicator->getLogger(), "Freeze.Evictor"); + out << "committed transaction " << hex << txnId << dec; + } + + streamedObjectQueue.erase + (streamedObjectQueue.begin(), + streamedObjectQueue.begin() + txSize); + + if(_trace >= 1) + { + Long now = IceUtil::Time::now().toMilliSeconds(); + Trace out(_communicator->getLogger(), "Freeze.Evictor"); + out << "saved " << txSize << " objects in " + << static_cast(now - saveStart) << " ms"; + } + } + catch(const DbDeadlockException&) + { + if(_deadlockWarning) + { + Warning out(_communicator->getLogger()); + out << "Deadlock in Freeze::EvictorI::run while writing into Db \"" + _filename + + "\"; retrying ..."; + } + + tryAgain = true; + txSize = (txSize + 1)/2; + } + catch(const DbException& dx) + { + DatabaseException ex(__FILE__, __LINE__); + ex.message = dx.what(); + throw ex; + } + } + } + while(tryAgain); + + { + Lock sync(*this); + + // + // Release usage count + // + for(deque::iterator p = allObjects.begin(); + p != allObjects.end(); p++) + { + EvictorElementPtr& element = *p; + element->usageCount--; + } + allObjects.clear(); + + for(deque::iterator q = deadObjects.begin(); + q != deadObjects.end(); q++) + { + EvictorElementPtr& element = *q; + if(!element->stale) + { + // + // Can be stale when there are duplicate elements on the + // deadObjecst queue + // + + if(!element->stale && element->usageCount == 0 && element->keepCount == 0) + { + // + // Get rid of unused dead elements + // + IceUtil::Mutex::Lock lockElement(element->mutex); + if(element->status == EvictorElement::dead) + { + evict(element); + } + } + } + } + deadObjects.clear(); + evict(); + + if(saveNowThreadsSize > 0) + { + _saveNowThreads.erase(_saveNowThreads.begin(), _saveNowThreads.begin() + saveNowThreadsSize); + notifyAll(); + } + } + } } catch(const IceUtil::Exception& ex) { - Error out(_communicator->getLogger()); - out << "Saving thread killed by exception: " << ex; - out.flush(); - handleFatalError(this, _communicator); + Error out(_communicator->getLogger()); + out << "Saving thread killed by exception: " << ex; + out.flush(); + handleFatalError(this, _communicator); } catch(const std::exception& ex) { - Error out(_communicator->getLogger()); - out << "Saving thread killed by std::exception: " << ex.what(); - out.flush(); - handleFatalError(this, _communicator); + Error out(_communicator->getLogger()); + out << "Saving thread killed by std::exception: " << ex.what(); + out.flush(); + handleFatalError(this, _communicator); } catch(...) { - Error out(_communicator->getLogger()); - out << "Saving thread killed by unknown exception"; - out.flush(); - handleFatalError(this, _communicator); + Error out(_communicator->getLogger()); + out << "Saving thread killed by unknown exception"; + out.flush(); + handleFatalError(this, _communicator); } } @@ -1665,7 +1665,7 @@ Freeze::EvictorI::saveNowNoSync() notifyAll(); do { - wait(); + wait(); } while(find(_saveNowThreads.begin(), _saveNowThreads.end(), myself) != _saveNowThreads.end()); } @@ -1683,50 +1683,50 @@ Freeze::EvictorI::evict() while(_currentEvictorSize > _evictorSize) { - // - // Get the last unused element from the evictor queue. - // - while(p != _evictorList.rend()) - { - if((*p)->usageCount == 0) - { - break; // Fine, servant is not in use (and not in the modifiedQueue) - } - ++p; - } - if(p == _evictorList.rend()) - { - // - // All servants are active, can't evict any further. - // - break; - } - - EvictorElementPtr& element = *p; - assert(!element->stale); - assert(element->keepCount == 0); - - if(_trace >= 2 || (_trace >= 1 && _evictorList.size() % 50 == 0)) - { - string facet = element->store.facet(); - - Trace out(_communicator->getLogger(), "Freeze.Evictor"); - out << "evicting \"" << _communicator->identityToString(element->cachePosition->first) << "\" "; - if(facet != "") - { - out << "-f \"" << facet << "\" "; - } - out << "from the queue\n" - << "number of elements in the queue: " << _currentEvictorSize; - } - - // - // Remove last unused element from the evictor queue. - // - element->stale = true; - element->store.unpin(element->cachePosition); - p = list::reverse_iterator(_evictorList.erase(element->evictPosition)); - _currentEvictorSize--; + // + // Get the last unused element from the evictor queue. + // + while(p != _evictorList.rend()) + { + if((*p)->usageCount == 0) + { + break; // Fine, servant is not in use (and not in the modifiedQueue) + } + ++p; + } + if(p == _evictorList.rend()) + { + // + // All servants are active, can't evict any further. + // + break; + } + + EvictorElementPtr& element = *p; + assert(!element->stale); + assert(element->keepCount == 0); + + if(_trace >= 2 || (_trace >= 1 && _evictorList.size() % 50 == 0)) + { + string facet = element->store.facet(); + + Trace out(_communicator->getLogger(), "Freeze.Evictor"); + out << "evicting \"" << _communicator->identityToString(element->cachePosition->first) << "\" "; + if(facet != "") + { + out << "-f \"" << facet << "\" "; + } + out << "from the queue\n" + << "number of elements in the queue: " << _currentEvictorSize; + } + + // + // Remove last unused element from the evictor queue. + // + element->stale = true; + element->store.unpin(element->cachePosition); + p = list::reverse_iterator(_evictorList.erase(element->evictPosition)); + _currentEvictorSize--; } } @@ -1737,20 +1737,20 @@ Freeze::EvictorI::fixEvictPosition(const EvictorElementPtr& element) if(element->keepCount == 0) { - if(element->usageCount < 0) - { - // - // New object - // - element->usageCount = 0; - _currentEvictorSize++; - } - else - { - _evictorList.erase(element->evictPosition); - } - _evictorList.push_front(element); - element->evictPosition = _evictorList.begin(); + if(element->usageCount < 0) + { + // + // New object + // + element->usageCount = 0; + _currentEvictorSize++; + } + else + { + _evictorList.erase(element->evictPosition); + } + _evictorList.push_front(element); + element->evictPosition = _evictorList.begin(); } } @@ -1775,7 +1775,7 @@ Freeze::EvictorI::addToModifiedQueue(const EvictorElementPtr& element) if(_saveSizeTrigger >= 0 && static_cast(_modifiedQueue.size()) >= _saveSizeTrigger) { - notifyAll(); + notifyAll(); } } @@ -1793,22 +1793,22 @@ Freeze::EvictorI::stream(const EvictorElementPtr& element, Long streamStart, Str if(element->status != EvictorElement::destroyed) { - // - // Update stats first - // - Statistics& stats = element->rec.stats; - Long diff = streamStart - (stats.creationTime + stats.lastSaveTime); - if(stats.lastSaveTime == 0) - { - stats.lastSaveTime = diff; - stats.avgSaveTime = diff; - } - else - { - stats.lastSaveTime = streamStart - stats.creationTime; - stats.avgSaveTime = static_cast(stats.avgSaveTime * 0.95 + diff * 0.05); - } - ObjectStore::marshal(element->rec, obj.value, _communicator); + // + // Update stats first + // + Statistics& stats = element->rec.stats; + Long diff = streamStart - (stats.creationTime + stats.lastSaveTime); + if(stats.lastSaveTime == 0) + { + stats.lastSaveTime = diff; + stats.avgSaveTime = diff; + } + else + { + stats.lastSaveTime = streamStart - stats.creationTime; + stats.avgSaveTime = static_cast(stats.avgSaveTime * 0.95 + diff * 0.05); + } + ObjectStore::marshal(element->rec, obj.value, _communicator); } } @@ -1820,11 +1820,11 @@ Freeze::EvictorI::findStore(const string& facet) const StoreMap::const_iterator p = _storeMap.find(facet); if(p == _storeMap.end()) { - return 0; + return 0; } else { - return (*p).second; + return (*p).second; } } @@ -1836,45 +1836,45 @@ Freeze::EvictorI::allDbs() const try { - Db db(_dbEnv->getEnv(), 0); - db.open(0, _filename.c_str(), 0, DB_UNKNOWN, DB_RDONLY, 0); - - Dbc* dbc = 0; - db.cursor(0, &dbc, 0); - - Dbt dbKey; - dbKey.set_flags(DB_DBT_MALLOC); - - Dbt dbValue; - dbValue.set_flags(DB_DBT_USERMEM | DB_DBT_PARTIAL); - - bool more = true; - while(more) - { - more = (dbc->get(&dbKey, &dbValue, DB_NEXT) == 0); - if(more) - { - string dbName(static_cast(dbKey.get_data()), dbKey.get_size()); - - if(dbName.find(indexPrefix) != 0) - { - result.push_back(dbName); - } - free(dbKey.get_data()); - } - } - - dbc->close(); - db.close(0); + Db db(_dbEnv->getEnv(), 0); + db.open(0, _filename.c_str(), 0, DB_UNKNOWN, DB_RDONLY, 0); + + Dbc* dbc = 0; + db.cursor(0, &dbc, 0); + + Dbt dbKey; + dbKey.set_flags(DB_DBT_MALLOC); + + Dbt dbValue; + dbValue.set_flags(DB_DBT_USERMEM | DB_DBT_PARTIAL); + + bool more = true; + while(more) + { + more = (dbc->get(&dbKey, &dbValue, DB_NEXT) == 0); + if(more) + { + string dbName(static_cast(dbKey.get_data()), dbKey.get_size()); + + if(dbName.find(indexPrefix) != 0) + { + result.push_back(dbName); + } + free(dbKey.get_data()); + } + } + + dbc->close(); + db.close(0); } catch(const DbException& dx) { - if(dx.get_errno() != ENOENT) - { - DatabaseException ex(__FILE__, __LINE__); - ex.message = dx.what(); - throw ex; - } + if(dx.get_errno() != ENOENT) + { + DatabaseException ex(__FILE__, __LINE__); + ex.message = dx.what(); + throw ex; + } } return result; diff --git a/cpp/src/Freeze/EvictorI.h b/cpp/src/Freeze/EvictorI.h index 6c85a3092df..187294cb8c6 100644 --- a/cpp/src/Freeze/EvictorI.h +++ b/cpp/src/Freeze/EvictorI.h @@ -43,11 +43,11 @@ public: class Guard { public: - Guard(DeactivateController&); - ~Guard(); + Guard(DeactivateController&); + ~Guard(); private: - DeactivateController& _controller; + DeactivateController& _controller; }; DeactivateController(EvictorI*); @@ -112,7 +112,7 @@ class EvictorI : public Evictor, public IceUtil::Monitor, publi public: EvictorI(const Ice::ObjectAdapterPtr&, const std::string&, DbEnv*, const std::string&, - const ServantInitializerPtr&, const std::vector&, bool); + const ServantInitializerPtr&, const std::vector&, bool); virtual ~EvictorI(); @@ -165,10 +165,10 @@ public: struct StreamedObject { - Key key; - Value value; - Ice::Byte status; - ObjectStore* store; + Key key; + Value value; + Ice::Byte status; + ObjectStore* store; }; diff --git a/cpp/src/Freeze/EvictorIteratorI.cpp b/cpp/src/Freeze/EvictorIteratorI.cpp index d2a1ecef2f5..68feab953aa 100644 --- a/cpp/src/Freeze/EvictorIteratorI.cpp +++ b/cpp/src/Freeze/EvictorIteratorI.cpp @@ -33,12 +33,12 @@ Freeze::EvictorIteratorI::hasNext() { if(_batchIterator != _batch.end()) { - return true; + return true; } else { - _batchIterator = nextBatch(); - return (_batchIterator != _batch.end()); + _batchIterator = nextBatch(); + return (_batchIterator != _batch.end()); } } @@ -47,11 +47,11 @@ Freeze::EvictorIteratorI::next() { if(hasNext()) { - return *_batchIterator++; + return *_batchIterator++; } else { - throw Freeze::NoSuchElementException(__FILE__, __LINE__); + throw Freeze::NoSuchElementException(__FILE__, __LINE__); } } @@ -60,13 +60,13 @@ vector::const_iterator Freeze::EvictorIteratorI::nextBatch() { DeactivateController::Guard - deactivateGuard(_store->evictor()->deactivateController()); + deactivateGuard(_store->evictor()->deactivateController()); _batch.clear(); if(!_more) { - return _batch.end(); + return _batch.end(); } vector evictorElements; @@ -78,145 +78,145 @@ Freeze::EvictorIteratorI::nextBatch() try { - for(;;) - { - _batch.clear(); - evictorElements.clear(); - - Dbt dbKey; - initializeOutDbt(_key, dbKey); - - Dbt dbValue; - dbValue.set_flags(DB_DBT_USERMEM | DB_DBT_PARTIAL); - - Dbc* dbc = 0; - try - { - // - // Move to the first record - // - u_int32_t flags = DB_NEXT; - - if(_initialized) - { - // - // _key represents the next element not yet returned - // if it has been deleted, we want the one after - // - flags = DB_SET_RANGE; - - // - // Will be used as input as well - // - dbKey.set_size(static_cast(firstKey.size())); - } - - _store->db()->cursor(0, &dbc, 0); - - bool done = false; - do - { - for(;;) - { - try - { - // - // It is critical to set key size to key capacity before the - // get, as a resize that increases the size inserts 0 - // - _key.resize(_key.capacity()); - - _more = (dbc->get(&dbKey, &dbValue, flags) == 0); - if(_more) - { - _key.resize(dbKey.get_size()); - _initialized = true; - - flags = DB_NEXT; - - Ice::Identity ident; - ObjectStore::unmarshal(ident, _key, communicator); - if(_batch.size() < _batchSize) - { - _batch.push_back(ident); - } - else - { - // - // Keep the last element in _key - // - done = true; - } - } - break; - } - catch(const DbDeadlockException&) - { - throw; - } - catch(const DbException& dx) - { - handleDbException(dx, _key, dbKey, __FILE__, __LINE__); - } - } - } - while(!done && _more); - - Dbc* toClose = dbc; - dbc = 0; - toClose->close(); - break; // for (;;) - } - catch(const DbDeadlockException&) - { - if(dbc != 0) - { - try - { - dbc->close(); - } - catch(const DbDeadlockException&) - { - // - // Ignored - // - } - } - _key = firstKey; - // - // Retry - // - } - catch(...) - { - if(dbc != 0) - { - try - { - dbc->close(); - } - catch(const DbDeadlockException&) - { - // - // Ignored - // - } - } - throw; - } - } + for(;;) + { + _batch.clear(); + evictorElements.clear(); + + Dbt dbKey; + initializeOutDbt(_key, dbKey); + + Dbt dbValue; + dbValue.set_flags(DB_DBT_USERMEM | DB_DBT_PARTIAL); + + Dbc* dbc = 0; + try + { + // + // Move to the first record + // + u_int32_t flags = DB_NEXT; + + if(_initialized) + { + // + // _key represents the next element not yet returned + // if it has been deleted, we want the one after + // + flags = DB_SET_RANGE; + + // + // Will be used as input as well + // + dbKey.set_size(static_cast(firstKey.size())); + } + + _store->db()->cursor(0, &dbc, 0); + + bool done = false; + do + { + for(;;) + { + try + { + // + // It is critical to set key size to key capacity before the + // get, as a resize that increases the size inserts 0 + // + _key.resize(_key.capacity()); + + _more = (dbc->get(&dbKey, &dbValue, flags) == 0); + if(_more) + { + _key.resize(dbKey.get_size()); + _initialized = true; + + flags = DB_NEXT; + + Ice::Identity ident; + ObjectStore::unmarshal(ident, _key, communicator); + if(_batch.size() < _batchSize) + { + _batch.push_back(ident); + } + else + { + // + // Keep the last element in _key + // + done = true; + } + } + break; + } + catch(const DbDeadlockException&) + { + throw; + } + catch(const DbException& dx) + { + handleDbException(dx, _key, dbKey, __FILE__, __LINE__); + } + } + } + while(!done && _more); + + Dbc* toClose = dbc; + dbc = 0; + toClose->close(); + break; // for (;;) + } + catch(const DbDeadlockException&) + { + if(dbc != 0) + { + try + { + dbc->close(); + } + catch(const DbDeadlockException&) + { + // + // Ignored + // + } + } + _key = firstKey; + // + // Retry + // + } + catch(...) + { + if(dbc != 0) + { + try + { + dbc->close(); + } + catch(const DbDeadlockException&) + { + // + // Ignored + // + } + } + throw; + } + } } catch(const DbException& dx) { - handleDbException(dx, __FILE__, __LINE__); + handleDbException(dx, __FILE__, __LINE__); } if(_batch.size() == 0) { - return _batch.end(); + return _batch.end(); } else { - return _batch.begin(); + return _batch.begin(); } } diff --git a/cpp/src/Freeze/IndexI.cpp b/cpp/src/Freeze/IndexI.cpp index 5058fb23ece..ca9c21e095a 100644 --- a/cpp/src/Freeze/IndexI.cpp +++ b/cpp/src/Freeze/IndexI.cpp @@ -37,7 +37,7 @@ vector Freeze::IndexI::untypedFindFirst(const Key& bytes, Int firstN) const { DeactivateController::Guard - deactivateGuard(_store->evictor()->deactivateController()); + deactivateGuard(_store->evictor()->deactivateController()); Dbt dbKey; initializeInDbt(bytes, dbKey); @@ -63,111 +63,111 @@ Freeze::IndexI::untypedFindFirst(const Key& bytes, Int firstN) const try { - for(;;) - { - Dbc* dbc = 0; - identities.clear(); - - try - { - // - // Move to the first record - // - _db->cursor(0, &dbc, 0); - u_int32_t flags = DB_SET; - - bool found; - - do - { - for(;;) - { - try - { - // - // It is critical to set key size to key capacity before the - // get, as a resize that increases the size inserts 0 - // - pkey.resize(pkey.capacity()); - - found = (dbc->pget(&dbKey, &pdbKey, &dbValue, flags) == 0); - if(found) - { - pkey.resize(pdbKey.get_size()); - - Ice::Identity ident; - ObjectStore::unmarshal(ident, pkey, communicator); - identities.push_back(ident); - flags = DB_NEXT_DUP; - } - break; // for(;;) - } - catch(const DbDeadlockException&) - { - throw; - } - catch(const DbException& dx) - { - handleDbException(dx, pkey, pdbKey, __FILE__, __LINE__); - } - } - } - while((firstN <= 0 || identities.size() < static_cast(firstN)) && found); - - Dbc* toClose = dbc; - dbc = 0; - toClose->close(); - break; // for (;;) - } - catch(const DbDeadlockException&) - { - if(dbc != 0) - { - try - { - dbc->close(); - } - catch(const DbDeadlockException&) - { - // - // Ignored - // - } - } - - if(_store->evictor()->deadlockWarning()) - { - Warning out(_store->communicator()->getLogger()); - out << "Deadlock in Freeze::IndexI::untypedFindFirst while searching \"" - << _store->evictor()->filename() + "/" + _dbName << "\"; retrying ..."; - } - - // - // Retry - // - } - catch(...) - { - if(dbc != 0) - { - try - { - dbc->close(); - } - catch(const DbDeadlockException&) - { - // - // Ignored - // - } - } - throw; - } - } + for(;;) + { + Dbc* dbc = 0; + identities.clear(); + + try + { + // + // Move to the first record + // + _db->cursor(0, &dbc, 0); + u_int32_t flags = DB_SET; + + bool found; + + do + { + for(;;) + { + try + { + // + // It is critical to set key size to key capacity before the + // get, as a resize that increases the size inserts 0 + // + pkey.resize(pkey.capacity()); + + found = (dbc->pget(&dbKey, &pdbKey, &dbValue, flags) == 0); + if(found) + { + pkey.resize(pdbKey.get_size()); + + Ice::Identity ident; + ObjectStore::unmarshal(ident, pkey, communicator); + identities.push_back(ident); + flags = DB_NEXT_DUP; + } + break; // for(;;) + } + catch(const DbDeadlockException&) + { + throw; + } + catch(const DbException& dx) + { + handleDbException(dx, pkey, pdbKey, __FILE__, __LINE__); + } + } + } + while((firstN <= 0 || identities.size() < static_cast(firstN)) && found); + + Dbc* toClose = dbc; + dbc = 0; + toClose->close(); + break; // for (;;) + } + catch(const DbDeadlockException&) + { + if(dbc != 0) + { + try + { + dbc->close(); + } + catch(const DbDeadlockException&) + { + // + // Ignored + // + } + } + + if(_store->evictor()->deadlockWarning()) + { + Warning out(_store->communicator()->getLogger()); + out << "Deadlock in Freeze::IndexI::untypedFindFirst while searching \"" + << _store->evictor()->filename() + "/" + _dbName << "\"; retrying ..."; + } + + // + // Retry + // + } + catch(...) + { + if(dbc != 0) + { + try + { + dbc->close(); + } + catch(const DbDeadlockException&) + { + // + // Ignored + // + } + } + throw; + } + } } catch(const DbException& dx) { - handleDbException(dx, __FILE__, __LINE__); + handleDbException(dx, __FILE__, __LINE__); } return identities; @@ -183,7 +183,7 @@ Int Freeze::IndexI::untypedCount(const Key& bytes) const { DeactivateController::Guard - deactivateGuard(_store->evictor()->deactivateController()); + deactivateGuard(_store->evictor()->deactivateController()); Dbt dbKey; initializeInDbt(bytes, dbKey); @@ -203,81 +203,81 @@ Freeze::IndexI::untypedCount(const Key& bytes) const try { - for(;;) - { - Dbc* dbc = 0; - - try - { - // - // Move to the first record - // - _db->cursor(0, &dbc, 0); - bool found = (dbc->get(&dbKey, &dbValue, DB_SET) == 0); - - if(found) - { - db_recno_t count = 0; - dbc->count(&count, 0); - result = static_cast(count); - } - - Dbc* toClose = dbc; - dbc = 0; - toClose->close(); - break; // for (;;) - } - catch(const DbDeadlockException&) - { - if(dbc != 0) - { - try - { - dbc->close(); - } - catch(const DbDeadlockException&) - { - // - // Ignored - // - } - } - - if(_store->evictor()->deadlockWarning()) - { - Warning out(_store->communicator()->getLogger()); - out << "Deadlock in Freeze::IndexI::untypedCount while searching \"" - << _store->evictor()->filename() + "/" + _dbName << "\"; retrying ..."; - } - - // - // Retry - // - } - catch(...) - { - if(dbc != 0) - { - try - { - dbc->close(); - } - catch(const DbDeadlockException&) - { - // - // Ignored - // - } - } - throw; - } - } + for(;;) + { + Dbc* dbc = 0; + + try + { + // + // Move to the first record + // + _db->cursor(0, &dbc, 0); + bool found = (dbc->get(&dbKey, &dbValue, DB_SET) == 0); + + if(found) + { + db_recno_t count = 0; + dbc->count(&count, 0); + result = static_cast(count); + } + + Dbc* toClose = dbc; + dbc = 0; + toClose->close(); + break; // for (;;) + } + catch(const DbDeadlockException&) + { + if(dbc != 0) + { + try + { + dbc->close(); + } + catch(const DbDeadlockException&) + { + // + // Ignored + // + } + } + + if(_store->evictor()->deadlockWarning()) + { + Warning out(_store->communicator()->getLogger()); + out << "Deadlock in Freeze::IndexI::untypedCount while searching \"" + << _store->evictor()->filename() + "/" + _dbName << "\"; retrying ..."; + } + + // + // Retry + // + } + catch(...) + { + if(dbc != 0) + { + try + { + dbc->close(); + } + catch(const DbDeadlockException&) + { + // + // Ignored + // + } + } + throw; + } + } } catch(const DbException& dx) { - DatabaseException ex(__FILE__, __LINE__); - ex.message = dx.what(); - throw ex; + DatabaseException ex(__FILE__, __LINE__); + ex.message = dx.what(); + throw ex; } return result; @@ -285,7 +285,7 @@ Freeze::IndexI::untypedCount(const Key& bytes) const void Freeze::IndexI::associate(ObjectStore* store, DbTxn* txn, - bool createDb, bool populateIndex) + bool createDb, bool populateIndex) { assert(txn != 0); _store = store; @@ -298,7 +298,7 @@ Freeze::IndexI::associate(ObjectStore* store, DbTxn* txn, u_int32_t flags = 0; if(createDb) { - flags = DB_CREATE; + flags = DB_CREATE; } _dbName = EvictorI::indexPrefix + store->dbName() + "." + _index.name(); @@ -308,14 +308,14 @@ Freeze::IndexI::associate(ObjectStore* store, DbTxn* txn, flags = 0; if(populateIndex) { - flags = DB_CREATE; + flags = DB_CREATE; } store->db()->associate(txn, _db.get(), callback, flags); } int Freeze::IndexI::secondaryKeyCreate(Db* secondary, const Dbt* dbKey, - const Dbt* dbValue, Dbt* result) + const Dbt* dbValue, Dbt* result) { Ice::CommunicatorPtr communicator = _store->communicator(); @@ -327,19 +327,19 @@ Freeze::IndexI::secondaryKeyCreate(Db* secondary, const Dbt* dbKey, Key bytes; if(_index.marshalKey(rec.servant, bytes)) { - result->set_flags(DB_DBT_APPMALLOC); - void* data = malloc(bytes.size()); - memcpy(data, &bytes[0], bytes.size()); - result->set_data(data); - result->set_size(static_cast(bytes.size())); - return 0; + result->set_flags(DB_DBT_APPMALLOC); + void* data = malloc(bytes.size()); + memcpy(data, &bytes[0], bytes.size()); + result->set_data(data); + result->set_size(static_cast(bytes.size())); + return 0; } else { - // - // Don't want to index this one - // - return DB_DONOTINDEX; + // + // Don't want to index this one + // + return DB_DONOTINDEX; } } @@ -348,16 +348,16 @@ Freeze::IndexI::close() { if(_db.get() != 0) { - try - { - _db->close(0); - } - catch(const DbException& dx) - { - DatabaseException ex(__FILE__, __LINE__); - ex.message = dx.what(); - throw ex; - } - _db.reset(0); + try + { + _db->close(0); + } + catch(const DbException& dx) + { + DatabaseException ex(__FILE__, __LINE__); + ex.message = dx.what(); + throw ex; + } + _db.reset(0); } } diff --git a/cpp/src/Freeze/MapI.cpp b/cpp/src/Freeze/MapI.cpp index a3e756725d2..37c894dad0c 100644 --- a/cpp/src/Freeze/MapI.cpp +++ b/cpp/src/Freeze/MapI.cpp @@ -86,12 +86,12 @@ Freeze::KeyCompareBase::compareEnabled() const Freeze::MapHelper* Freeze::MapHelper::create(const Freeze::ConnectionPtr& connection, - const string& dbName, - const string& key, - const string& value, - const Freeze::KeyCompareBasePtr& keyCompare, - const std::vector& indices, - bool createDb) + const string& dbName, + const string& key, + const string& value, + const Freeze::KeyCompareBasePtr& keyCompare, + const std::vector& indices, + bool createDb) { Freeze::ConnectionIPtr connectionI = Freeze::ConnectionIPtr::dynamicCast(connection.get()); return new MapHelperI(connectionI, dbName, key, value, keyCompare, indices, createDb); @@ -112,14 +112,14 @@ Freeze::IteratorHelper::create(const MapHelper& m, bool readOnly) const MapHelperI& actualMap = dynamic_cast(m); auto_ptr r(new IteratorHelperI(actualMap, readOnly, - 0, false)); + 0, false)); if(r->next()) { - return r.release(); + return r.release(); } else { - return 0; + return 0; } } @@ -134,8 +134,8 @@ Freeze::IteratorHelper::~IteratorHelper() // Freeze::IteratorHelperI::IteratorHelperI(const MapHelperI& m, bool readOnly, - const MapIndexBasePtr& index, - bool onlyDups) : + const MapIndexBasePtr& index, + bool onlyDups) : _map(m), _dbc(0), _indexed(index != 0), @@ -144,41 +144,41 @@ Freeze::IteratorHelperI::IteratorHelperI(const MapHelperI& m, bool readOnly, { if(_map._trace >= 2) { - Trace out(_map._connection->communicator()->getLogger(), "Freeze.Map"); - out << "opening iterator on Db \"" << _map._dbName << "\""; - if(index != 0) - { - out << " with index \"" << index->name() << "\""; - } + Trace out(_map._connection->communicator()->getLogger(), "Freeze.Map"); + out << "opening iterator on Db \"" << _map._dbName << "\""; + if(index != 0) + { + out << " with index \"" << index->name() << "\""; + } } DbTxn* txn = _map._connection->dbTxn(); if(txn == 0 && !readOnly) { - // - // Need to start a transaction - // - _tx = new Tx(_map); - txn = _tx->getTxn(); + // + // Need to start a transaction + // + _tx = new Tx(_map); + txn = _tx->getTxn(); } try { - if(index != 0) - { - index->_impl->db()->cursor(txn, &_dbc, 0); - } - else - { - _map._db->cursor(txn, &_dbc, 0); - } + if(index != 0) + { + index->_impl->db()->cursor(txn, &_dbc, 0); + } + else + { + _map._db->cursor(txn, &_dbc, 0); + } } catch(const ::DbException& dx) { - DatabaseException ex(__FILE__, __LINE__); - ex.message = dx.what(); - throw ex; + DatabaseException ex(__FILE__, __LINE__); + ex.message = dx.what(); + throw ex; } _map._iteratorList.push_back(this); @@ -194,19 +194,19 @@ Freeze::IteratorHelperI::IteratorHelperI(const IteratorHelperI& it) : { if(_map._trace >= 2) { - Trace out(_map._connection->communicator()->getLogger(), "Freeze.Map"); - out << "duplicating iterator on Db \"" << _map._dbName << "\""; + Trace out(_map._connection->communicator()->getLogger(), "Freeze.Map"); + out << "duplicating iterator on Db \"" << _map._dbName << "\""; } try { - it._dbc->dup(&_dbc, DB_POSITION); + it._dbc->dup(&_dbc, DB_POSITION); } catch(const ::DbException& dx) { - DatabaseException ex(__FILE__, __LINE__); - ex.message = dx.what(); - throw ex; + DatabaseException ex(__FILE__, __LINE__); + ex.message = dx.what(); + throw ex; } _tx = it._tx; @@ -241,31 +241,31 @@ Freeze::IteratorHelperI::find(const Key& key) const { try { - if(_dbc->get(&dbKey, &dbValue, DB_SET) == 0) - { - return true; - } - else - { - return false; - } + if(_dbc->get(&dbKey, &dbValue, DB_SET) == 0) + { + return true; + } + else + { + return false; + } } catch(const ::DbDeadlockException& dx) { - if(_tx != 0) - { - _tx->dead(); - } - - DeadlockException ex(__FILE__, __LINE__); - ex.message = dx.what(); - throw ex; + if(_tx != 0) + { + _tx->dead(); + } + + DeadlockException ex(__FILE__, __LINE__); + ex.message = dx.what(); + throw ex; } catch(const ::DbException& dx) { - DatabaseException ex(__FILE__, __LINE__); - ex.message = dx.what(); - throw ex; + DatabaseException ex(__FILE__, __LINE__); + ex.message = dx.what(); + throw ex; } } } @@ -289,42 +289,42 @@ Freeze::IteratorHelperI::lowerBound(const Key& key) const for(;;) { - try - { - int err = _dbc->get(&dbKey, &dbValue, DB_SET_RANGE); - if(err == 0) - { - _key.resize(dbKey.get_size()); - return true; - } - else if(err == DB_NOTFOUND) - { - return false; - } - else - { - // - // Bug in Freeze - // - assert(0); - throw DatabaseException(__FILE__, __LINE__); - } - } - catch(const ::DbDeadlockException& dx) - { - if(_tx != 0) - { - _tx->dead(); - } - - DeadlockException ex(__FILE__, __LINE__); - ex.message = dx.what(); - throw ex; - } - catch(const ::DbException& dx) - { - handleDbException(dx, _key, dbKey, __FILE__, __LINE__); - } + try + { + int err = _dbc->get(&dbKey, &dbValue, DB_SET_RANGE); + if(err == 0) + { + _key.resize(dbKey.get_size()); + return true; + } + else if(err == DB_NOTFOUND) + { + return false; + } + else + { + // + // Bug in Freeze + // + assert(0); + throw DatabaseException(__FILE__, __LINE__); + } + } + catch(const ::DbDeadlockException& dx) + { + if(_tx != 0) + { + _tx->dead(); + } + + DeadlockException ex(__FILE__, __LINE__); + ex.message = dx.what(); + throw ex; + } + catch(const ::DbException& dx) + { + handleDbException(dx, _key, dbKey, __FILE__, __LINE__); + } } } @@ -333,18 +333,18 @@ Freeze::IteratorHelperI::upperBound(const Key& key) const { if(lowerBound(key)) { - if(_key == key) - { - return next(true); - } - else - { - return true; - } + if(_key == key) + { + return next(true); + } + else + { + return true; + } } else { - return false; + return false; } } @@ -364,7 +364,7 @@ Freeze::IteratorHelperI::get(const Key*& key, const Value*& value) const size_t keySize = _key.capacity(); if(keySize < 1024) { - keySize = 1024; + keySize = 1024; } _key.resize(keySize); @@ -374,7 +374,7 @@ Freeze::IteratorHelperI::get(const Key*& key, const Value*& value) const size_t valueSize = _value.capacity(); if(valueSize < 1024) { - valueSize = 1024; + valueSize = 1024; } _value.resize(valueSize); Dbt dbValue; @@ -382,60 +382,60 @@ Freeze::IteratorHelperI::get(const Key*& key, const Value*& value) const for(;;) { - try - { - int err; - - if(_indexed) - { - // - // Not interested in getting the index's key - // - Dbt iKey; - iKey.set_flags(DB_DBT_USERMEM | DB_DBT_PARTIAL); - - err = _dbc->pget(&iKey, &dbKey, &dbValue, DB_CURRENT); - } - else - { - err = _dbc->get(&dbKey, &dbValue, DB_CURRENT); - } - - if(err == 0) - { - _key.resize(dbKey.get_size()); - _value.resize(dbValue.get_size()); - break; // for(;;) - } - else if(err == DB_KEYEMPTY) - { - throw InvalidPositionException(__FILE__, __LINE__); - } - else - { - // - // Bug in Freeze - // - assert(0); - throw DatabaseException(__FILE__, __LINE__); - } - } - catch(const ::DbDeadlockException& dx) - { - if(_tx != 0) - { - _tx->dead(); - } - - DeadlockException ex(__FILE__, __LINE__); - ex.message = dx.what(); - throw ex; - } - catch(const ::DbException& dx) - { - handleDbException(dx, _key, dbKey, _value, dbValue, - __FILE__, __LINE__); - } + try + { + int err; + + if(_indexed) + { + // + // Not interested in getting the index's key + // + Dbt iKey; + iKey.set_flags(DB_DBT_USERMEM | DB_DBT_PARTIAL); + + err = _dbc->pget(&iKey, &dbKey, &dbValue, DB_CURRENT); + } + else + { + err = _dbc->get(&dbKey, &dbValue, DB_CURRENT); + } + + if(err == 0) + { + _key.resize(dbKey.get_size()); + _value.resize(dbValue.get_size()); + break; // for(;;) + } + else if(err == DB_KEYEMPTY) + { + throw InvalidPositionException(__FILE__, __LINE__); + } + else + { + // + // Bug in Freeze + // + assert(0); + throw DatabaseException(__FILE__, __LINE__); + } + } + catch(const ::DbDeadlockException& dx) + { + if(_tx != 0) + { + _tx->dead(); + } + + DeadlockException ex(__FILE__, __LINE__); + ex.message = dx.what(); + throw ex; + } + catch(const ::DbException& dx) + { + handleDbException(dx, _key, dbKey, _value, dbValue, + __FILE__, __LINE__); + } } } @@ -445,7 +445,7 @@ Freeze::IteratorHelperI::get() const size_t keySize = _key.capacity(); if(keySize < 1024) { - keySize = 1024; + keySize = 1024; } _key.resize(keySize); @@ -460,57 +460,57 @@ Freeze::IteratorHelperI::get() const for(;;) { - try - { - int err; - if(_indexed) - { - // - // Not interested in getting the index's key - // - Dbt iKey; - iKey.set_flags(DB_DBT_USERMEM | DB_DBT_PARTIAL); - - err = _dbc->pget(&iKey, &dbKey, &dbValue, DB_CURRENT); - } - else - { - err = _dbc->get(&dbKey, &dbValue, DB_CURRENT); - } - - if(err == 0) - { - _key.resize(dbKey.get_size()); - return &_key; - } - else if(err == DB_KEYEMPTY) - { - throw InvalidPositionException(__FILE__, __LINE__); - } - else - { - // - // Bug in Freeze - // - assert(0); - throw DatabaseException(__FILE__, __LINE__); - } - } - catch(const ::DbDeadlockException& dx) - { - if(_tx != 0) - { - _tx->dead(); - } - - DeadlockException ex(__FILE__, __LINE__); - ex.message = dx.what(); - throw ex; - } - catch(const ::DbException& dx) - { - handleDbException(dx, _key, dbKey, __FILE__, __LINE__); - } + try + { + int err; + if(_indexed) + { + // + // Not interested in getting the index's key + // + Dbt iKey; + iKey.set_flags(DB_DBT_USERMEM | DB_DBT_PARTIAL); + + err = _dbc->pget(&iKey, &dbKey, &dbValue, DB_CURRENT); + } + else + { + err = _dbc->get(&dbKey, &dbValue, DB_CURRENT); + } + + if(err == 0) + { + _key.resize(dbKey.get_size()); + return &_key; + } + else if(err == DB_KEYEMPTY) + { + throw InvalidPositionException(__FILE__, __LINE__); + } + else + { + // + // Bug in Freeze + // + assert(0); + throw DatabaseException(__FILE__, __LINE__); + } + } + catch(const ::DbDeadlockException& dx) + { + if(_tx != 0) + { + _tx->dead(); + } + + DeadlockException ex(__FILE__, __LINE__); + ex.message = dx.what(); + throw ex; + } + catch(const ::DbException& dx) + { + handleDbException(dx, _key, dbKey, __FILE__, __LINE__); + } } } @@ -519,9 +519,9 @@ Freeze::IteratorHelperI::set(const Value& value) { if(_indexed) { - DatabaseException ex(__FILE__, __LINE__); - ex.message = "Cannot set an iterator retrieved through an index"; - throw ex; + DatabaseException ex(__FILE__, __LINE__); + ex.message = "Cannot set an iterator retrieved through an index"; + throw ex; } // @@ -535,31 +535,31 @@ Freeze::IteratorHelperI::set(const Value& value) if(_tx != 0) { - _map.closeAllIteratorsExcept(_tx); + _map.closeAllIteratorsExcept(_tx); } try { - int err; - err = _dbc->put(&dbKey, &dbValue, DB_CURRENT); - assert(err == 0); + int err; + err = _dbc->put(&dbKey, &dbValue, DB_CURRENT); + assert(err == 0); } catch(const ::DbDeadlockException& dx) { - if(_tx != 0) - { - _tx->dead(); - } + if(_tx != 0) + { + _tx->dead(); + } - DeadlockException ex(__FILE__, __LINE__); - ex.message = dx.what(); - throw ex; + DeadlockException ex(__FILE__, __LINE__); + ex.message = dx.what(); + throw ex; } catch(const ::DbException& dx) { - DatabaseException ex(__FILE__, __LINE__); - ex.message = dx.what(); - throw ex; + DatabaseException ex(__FILE__, __LINE__); + ex.message = dx.what(); + throw ex; } } @@ -568,34 +568,34 @@ Freeze::IteratorHelperI::erase() { if(_tx != 0) { - _map.closeAllIteratorsExcept(_tx); + _map.closeAllIteratorsExcept(_tx); } try { - int err = _dbc->del(0); - if(err == DB_KEYEMPTY) - { - throw InvalidPositionException(__FILE__, __LINE__); - } - assert(err == 0); + int err = _dbc->del(0); + if(err == DB_KEYEMPTY) + { + throw InvalidPositionException(__FILE__, __LINE__); + } + assert(err == 0); } catch(const ::DbDeadlockException& dx) { - if(_tx != 0) - { - _tx->dead(); - } + if(_tx != 0) + { + _tx->dead(); + } - DeadlockException ex(__FILE__, __LINE__); - ex.message = dx.what(); - throw ex; + DeadlockException ex(__FILE__, __LINE__); + ex.message = dx.what(); + throw ex; } catch(const ::DbException& dx) { - DatabaseException ex(__FILE__, __LINE__); - ex.message = dx.what(); - throw ex; + DatabaseException ex(__FILE__, __LINE__); + ex.message = dx.what(); + throw ex; } } @@ -619,40 +619,40 @@ Freeze::IteratorHelperI::next(bool skipDups) const int flags = DB_NEXT; if(skipDups) { - flags = DB_NEXT_NODUP; + flags = DB_NEXT_NODUP; } else if(_indexed && _onlyDups) { - flags = DB_NEXT_DUP; + flags = DB_NEXT_DUP; } try { - if(_dbc->get(&dbKey, &dbValue, flags) == 0) - { - return true; - } - else - { - return false; - } + if(_dbc->get(&dbKey, &dbValue, flags) == 0) + { + return true; + } + else + { + return false; + } } catch(const ::DbDeadlockException& dx) { - if(_tx != 0) - { - _tx->dead(); - } + if(_tx != 0) + { + _tx->dead(); + } - DeadlockException ex(__FILE__, __LINE__); - ex.message = dx.what(); - throw ex; + DeadlockException ex(__FILE__, __LINE__); + ex.message = dx.what(); + throw ex; } catch(const ::DbException& dx) { - DatabaseException ex(__FILE__, __LINE__); - ex.message = dx.what(); - throw ex; + DatabaseException ex(__FILE__, __LINE__); + ex.message = dx.what(); + throw ex; } } @@ -661,35 +661,35 @@ Freeze::IteratorHelperI::close() { if(_dbc != 0) { - if(_map._trace >= 2) - { - Trace out(_map._connection->communicator()->getLogger(), "Freeze.Map"); - out << "closing iterator on Db \"" << _map._dbName << "\""; - } - - try - { - _dbc->close(); - } - catch(const ::DbDeadlockException& dx) - { - bool raiseException = (_tx == 0); - cleanup(); - if(raiseException) - { - DeadlockException ex(__FILE__, __LINE__); - ex.message = dx.what(); - throw ex; - } - } - catch(const ::DbException& dx) - { - cleanup(); - DatabaseException ex(__FILE__, __LINE__); - ex.message = dx.what(); - throw ex; - } - cleanup(); + if(_map._trace >= 2) + { + Trace out(_map._connection->communicator()->getLogger(), "Freeze.Map"); + out << "closing iterator on Db \"" << _map._dbName << "\""; + } + + try + { + _dbc->close(); + } + catch(const ::DbDeadlockException& dx) + { + bool raiseException = (_tx == 0); + cleanup(); + if(raiseException) + { + DeadlockException ex(__FILE__, __LINE__); + ex.message = dx.what(); + throw ex; + } + } + catch(const ::DbException& dx) + { + cleanup(); + DatabaseException ex(__FILE__, __LINE__); + ex.message = dx.what(); + throw ex; + } + cleanup(); } } @@ -713,68 +713,68 @@ Freeze::IteratorHelperI::Tx::Tx(const MapHelperI& m) : { if(_map._trace >= 2) { - Trace out(_map._connection->communicator()->getLogger(), "Freeze.Map"); - out << "starting transaction for Db \"" << _map._dbName << "\""; + Trace out(_map._connection->communicator()->getLogger(), "Freeze.Map"); + out << "starting transaction for Db \"" << _map._dbName << "\""; } try { - _map._connection->dbEnv()->getEnv()->txn_begin(0, &_txn, 0); + _map._connection->dbEnv()->getEnv()->txn_begin(0, &_txn, 0); } catch(const ::DbException& dx) { - DatabaseException ex(__FILE__, __LINE__); - ex.message = dx.what(); - throw ex; + DatabaseException ex(__FILE__, __LINE__); + ex.message = dx.what(); + throw ex; } } - + Freeze::IteratorHelperI::Tx::~Tx() { if(_dead) { - if(_map._trace >= 2) - { - Trace out(_map._connection->communicator()->getLogger(), ""); - out << "aborting transaction for Db \"" << _map._dbName << "\""; - } - - try - { - _txn->abort(); - } - catch(...) - { - // - // Ignore exceptions to avoid crash during stack unwinding - // - } + if(_map._trace >= 2) + { + Trace out(_map._connection->communicator()->getLogger(), ""); + out << "aborting transaction for Db \"" << _map._dbName << "\""; + } + + try + { + _txn->abort(); + } + catch(...) + { + // + // Ignore exceptions to avoid crash during stack unwinding + // + } } else { - if(_map._trace >= 2) - { - Trace out(_map._connection->communicator()->getLogger(), "Freeze.Map"); - out << "committing transaction for Db \"" << _map._dbName.c_str() << "\""; - } - - try - { - _txn->commit(0); - } - catch(const ::DbDeadlockException& dx) - { - DeadlockException ex(__FILE__, __LINE__); - ex.message = dx.what(); - throw ex; - } - catch(const ::DbException& dx) - { - DatabaseException ex(__FILE__, __LINE__); - ex.message = dx.what(); - throw ex; - } + if(_map._trace >= 2) + { + Trace out(_map._connection->communicator()->getLogger(), "Freeze.Map"); + out << "committing transaction for Db \"" << _map._dbName.c_str() << "\""; + } + + try + { + _txn->commit(0); + } + catch(const ::DbDeadlockException& dx) + { + DeadlockException ex(__FILE__, __LINE__); + ex.message = dx.what(); + throw ex; + } + catch(const ::DbException& dx) + { + DatabaseException ex(__FILE__, __LINE__); + ex.message = dx.what(); + throw ex; + } } } @@ -792,31 +792,31 @@ Freeze::IteratorHelperI::Tx::dead() Freeze::MapHelperI::MapHelperI(const ConnectionIPtr& connection, - const string& dbName, - const string& key, - const string& value, - const KeyCompareBasePtr& keyCompare, - const vector& indices, - bool createDb) : + const string& dbName, + const string& key, + const string& value, + const KeyCompareBasePtr& keyCompare, + const vector& indices, + bool createDb) : _connection(connection), _db(SharedDb::get(connection, dbName, key, value, keyCompare, indices, createDb)), _dbName(dbName), _trace(connection->trace()) { for(vector::const_iterator p = indices.begin(); - p != indices.end(); ++p) + p != indices.end(); ++p) { - const MapIndexBasePtr& indexBase = *p; - assert(indexBase->_impl != 0); - assert(indexBase->_communicator == _connection->communicator()); - assert(indexBase->_map == 0); - + const MapIndexBasePtr& indexBase = *p; + assert(indexBase->_impl != 0); + assert(indexBase->_communicator == _connection->communicator()); + assert(indexBase->_map == 0); + #ifndef NDEBUG - bool inserted = + bool inserted = #endif - _indices.insert(IndexMap::value_type(indexBase->name(), indexBase)).second; - assert(inserted); - indexBase->_map = this; + _indices.insert(IndexMap::value_type(indexBase->name(), indexBase)).second; + assert(inserted); + indexBase->_map = this; } _connection->registerMap(this); @@ -832,38 +832,38 @@ Freeze::MapHelperI::find(const Key& k, bool readOnly) const { for(;;) { - try - { - auto_ptr r(new IteratorHelperI(*this, readOnly, 0, false)); - if(r->find(k)) - { - return r.release(); - } - else - { - return 0; - } - } - catch(const DeadlockException&) - { - if(_connection->dbTxn() != 0) - { - throw; - } - else - { - if(_connection->deadlockWarning()) - { - Warning out(_connection->communicator()->getLogger()); - out << "Deadlock in Freeze::MapHelperI::find on Map \"" - << _dbName << "\"; retrying ..."; - } - - // - // Ignored, try again - // - } - } + try + { + auto_ptr r(new IteratorHelperI(*this, readOnly, 0, false)); + if(r->find(k)) + { + return r.release(); + } + else + { + return 0; + } + } + catch(const DeadlockException&) + { + if(_connection->dbTxn() != 0) + { + throw; + } + else + { + if(_connection->deadlockWarning()) + { + Warning out(_connection->communicator()->getLogger()); + out << "Deadlock in Freeze::MapHelperI::find on Map \"" + << _dbName << "\"; retrying ..."; + } + + // + // Ignored, try again + // + } + } } } @@ -872,38 +872,38 @@ Freeze::MapHelperI::lowerBound(const Key& k, bool readOnly) const { for(;;) { - try - { - auto_ptr r(new IteratorHelperI(*this, readOnly, 0, false)); - if(r->lowerBound(k)) - { - return r.release(); - } - else - { - return 0; - } - } - catch(const DeadlockException&) - { - if(_connection->dbTxn() != 0) - { - throw; - } - else - { - if(_connection->deadlockWarning()) - { - Warning out(_connection->communicator()->getLogger()); - out << "Deadlock in Freeze::MapHelperI::lowerBound on Map \"" - << _dbName << "\"; retrying ..."; - } - - // - // Ignored, try again - // - } - } + try + { + auto_ptr r(new IteratorHelperI(*this, readOnly, 0, false)); + if(r->lowerBound(k)) + { + return r.release(); + } + else + { + return 0; + } + } + catch(const DeadlockException&) + { + if(_connection->dbTxn() != 0) + { + throw; + } + else + { + if(_connection->deadlockWarning()) + { + Warning out(_connection->communicator()->getLogger()); + out << "Deadlock in Freeze::MapHelperI::lowerBound on Map \"" + << _dbName << "\"; retrying ..."; + } + + // + // Ignored, try again + // + } + } } } @@ -912,38 +912,38 @@ Freeze::MapHelperI::upperBound(const Key& k, bool readOnly) const { for(;;) { - try - { - auto_ptr r(new IteratorHelperI(*this, readOnly, 0, false)); - if(r->upperBound(k)) - { - return r.release(); - } - else - { - return 0; - } - } - catch(const DeadlockException&) - { - if(_connection->dbTxn() != 0) - { - throw; - } - else - { - if(_connection->deadlockWarning()) - { - Warning out(_connection->communicator()->getLogger()); - out << "Deadlock in Freeze::MapHelperI::upperBound on Map \"" - << _dbName << "\"; retrying ..."; - } - - // - // Ignored, try again - // - } - } + try + { + auto_ptr r(new IteratorHelperI(*this, readOnly, 0, false)); + if(r->upperBound(k)) + { + return r.release(); + } + else + { + return 0; + } + } + catch(const DeadlockException&) + { + if(_connection->dbTxn() != 0) + { + throw; + } + else + { + if(_connection->deadlockWarning()) + { + Warning out(_connection->communicator()->getLogger()); + out << "Deadlock in Freeze::MapHelperI::upperBound on Map \"" + << _dbName << "\"; retrying ..."; + } + + // + // Ignored, try again + // + } + } } } @@ -958,56 +958,56 @@ Freeze::MapHelperI::put(const Key& key, const Value& value) DbTxn* txn = _connection->dbTxn(); if(txn == 0) { - closeAllIterators(); + closeAllIterators(); } for(;;) { - try - { - int err = _db->put(txn, &dbKey, &dbValue, - txn != 0 ? 0 : DB_AUTO_COMMIT); - - if(err == 0) - { - break; - } - else - { - // - // Bug in Freeze - // - throw DatabaseException(__FILE__, __LINE__); - } - } - catch(const ::DbDeadlockException& dx) - { - if(txn != 0) - { - DeadlockException ex(__FILE__, __LINE__); - ex.message = dx.what(); - throw ex; - } - else - { - if(_connection->deadlockWarning()) - { - Warning out(_connection->communicator()->getLogger()); - out << "Deadlock in Freeze::MapHelperI::put on Map \"" - << _dbName << "\"; retrying ..."; - } - - // - // Ignored, try again - // - } - } - catch(const ::DbException& dx) - { - DatabaseException ex(__FILE__, __LINE__); - ex.message = dx.what(); - throw ex; - } + try + { + int err = _db->put(txn, &dbKey, &dbValue, + txn != 0 ? 0 : DB_AUTO_COMMIT); + + if(err == 0) + { + break; + } + else + { + // + // Bug in Freeze + // + throw DatabaseException(__FILE__, __LINE__); + } + } + catch(const ::DbDeadlockException& dx) + { + if(txn != 0) + { + DeadlockException ex(__FILE__, __LINE__); + ex.message = dx.what(); + throw ex; + } + else + { + if(_connection->deadlockWarning()) + { + Warning out(_connection->communicator()->getLogger()); + out << "Deadlock in Freeze::MapHelperI::put on Map \"" + << _dbName << "\"; retrying ..."; + } + + // + // Ignored, try again + // + } + } + catch(const ::DbException& dx) + { + DatabaseException ex(__FILE__, __LINE__); + ex.message = dx.what(); + throw ex; + } } } @@ -1020,57 +1020,57 @@ Freeze::MapHelperI::erase(const Key& key) DbTxn* txn = _connection->dbTxn(); if(txn == 0) { - closeAllIterators(); + closeAllIterators(); } for(;;) { - try - { - int err = _db->del(txn, &dbKey, txn != 0 ? 0 : DB_AUTO_COMMIT); - - if(err == 0) - { - return true; - } - else if(err == DB_NOTFOUND) - { - return false; - } - else - { - assert(0); - throw DatabaseException(__FILE__, __LINE__); - } - } - catch(const ::DbDeadlockException& dx) - { - if(txn != 0) - { - DeadlockException ex(__FILE__, __LINE__); - ex.message = dx.what(); - throw ex; - } - else - { - if(_connection->deadlockWarning()) - { - Warning out(_connection->communicator()->getLogger()); - out << "Deadlock in Freeze::MapHelperI::erase on Map \"" - << _dbName << "\"; retrying ..."; - } - - // - // Ignored, try again - // - } - } - catch(const ::DbException& dx) - { - DatabaseException ex(__FILE__, __LINE__); - ex.message = dx.what(); - throw ex; - } + try + { + int err = _db->del(txn, &dbKey, txn != 0 ? 0 : DB_AUTO_COMMIT); + + if(err == 0) + { + return true; + } + else if(err == DB_NOTFOUND) + { + return false; + } + else + { + assert(0); + throw DatabaseException(__FILE__, __LINE__); + } + } + catch(const ::DbDeadlockException& dx) + { + if(txn != 0) + { + DeadlockException ex(__FILE__, __LINE__); + ex.message = dx.what(); + throw ex; + } + else + { + if(_connection->deadlockWarning()) + { + Warning out(_connection->communicator()->getLogger()); + out << "Deadlock in Freeze::MapHelperI::erase on Map \"" + << _dbName << "\"; retrying ..."; + } + + // + // Ignored, try again + // + } + } + catch(const ::DbException& dx) + { + DatabaseException ex(__FILE__, __LINE__); + ex.message = dx.what(); + throw ex; + } } } @@ -1088,52 +1088,52 @@ Freeze::MapHelperI::count(const Key& key) const for(;;) { - try - { - int err = _db->get(_connection->dbTxn(), &dbKey, &dbValue, 0); - - if(err == 0) - { - return 1; - } - else if(err == DB_NOTFOUND) - { - return 0; - } - else - { - assert(0); - throw DatabaseException(__FILE__, __LINE__); - } - } - catch(const ::DbDeadlockException& dx) - { - if(_connection->dbTxn() != 0) - { - DeadlockException ex(__FILE__, __LINE__); - ex.message = dx.what(); - throw ex; - } - else - { - if(_connection->deadlockWarning()) - { - Warning out(_connection->communicator()->getLogger()); - out << "Deadlock in Freeze::MapHelperI::count on Map \"" - << _dbName << "\"; retrying ..."; - } - - // - // Ignored, try again - // - } - } - catch(const ::DbException& dx) - { - DatabaseException ex(__FILE__, __LINE__); - ex.message = dx.what(); - throw ex; - } + try + { + int err = _db->get(_connection->dbTxn(), &dbKey, &dbValue, 0); + + if(err == 0) + { + return 1; + } + else if(err == DB_NOTFOUND) + { + return 0; + } + else + { + assert(0); + throw DatabaseException(__FILE__, __LINE__); + } + } + catch(const ::DbDeadlockException& dx) + { + if(_connection->dbTxn() != 0) + { + DeadlockException ex(__FILE__, __LINE__); + ex.message = dx.what(); + throw ex; + } + else + { + if(_connection->deadlockWarning()) + { + Warning out(_connection->communicator()->getLogger()); + out << "Deadlock in Freeze::MapHelperI::count on Map \"" + << _dbName << "\"; retrying ..."; + } + + // + // Ignored, try again + // + } + } + catch(const ::DbException& dx) + { + DatabaseException ex(__FILE__, __LINE__); + ex.message = dx.what(); + throw ex; + } } } @@ -1143,47 +1143,47 @@ Freeze::MapHelperI::clear() DbTxn* txn = _connection->dbTxn(); if(txn == 0) { - closeAllIterators(); + closeAllIterators(); } for(;;) { - try - { - u_int32_t count; - int err; - err = _db->truncate(txn, &count, txn != 0 ? 0 : DB_AUTO_COMMIT); - assert(err == 0); - break; - } - catch(const ::DbDeadlockException& dx) - { - if(txn != 0) - { - DeadlockException ex(__FILE__, __LINE__); - ex.message = dx.what(); - throw ex; - } - else - { - if(_connection->deadlockWarning()) - { - Warning out(_connection->communicator()->getLogger()); - out << "Deadlock in Freeze::MapHelperI::clear on Map \"" - << _dbName << "\"; retrying ..."; - } - - // - // Ignored, try again - // - } - } - catch(const ::DbException& dx) - { - DatabaseException ex(__FILE__, __LINE__); - ex.message = dx.what(); - throw ex; - } + try + { + u_int32_t count; + int err; + err = _db->truncate(txn, &count, txn != 0 ? 0 : DB_AUTO_COMMIT); + assert(err == 0); + break; + } + catch(const ::DbDeadlockException& dx) + { + if(txn != 0) + { + DeadlockException ex(__FILE__, __LINE__); + ex.message = dx.what(); + throw ex; + } + else + { + if(_connection->deadlockWarning()) + { + Warning out(_connection->communicator()->getLogger()); + out << "Deadlock in Freeze::MapHelperI::clear on Map \"" + << _dbName << "\"; retrying ..."; + } + + // + // Ignored, try again + // + } + } + catch(const ::DbException& dx) + { + DatabaseException ex(__FILE__, __LINE__); + ex.message = dx.what(); + throw ex; + } } } @@ -1192,71 +1192,71 @@ Freeze::MapHelperI::destroy() { if(_dbName == catalogName()) { - DatabaseException ex(__FILE__, __LINE__); - ex.message = "You cannot destroy the " + catalogName() + " database"; - throw ex; + DatabaseException ex(__FILE__, __LINE__); + ex.message = "You cannot destroy the " + catalogName() + " database"; + throw ex; } TransactionPtr tx = _connection->currentTransaction(); bool ownTx = (tx == 0); if(ownTx) - { - tx = _connection->beginTransaction(); + { + tx = _connection->beginTransaction(); } DbTxn* txn = _connection->dbTxn(); try { - close(); + close(); - Catalog catalog(_connection, catalogName()); - catalog.erase(_dbName); - _connection->dbEnv()->getEnv()->dbremove(txn, _dbName.c_str(), 0, 0); + Catalog catalog(_connection, catalogName()); + catalog.erase(_dbName); + _connection->dbEnv()->getEnv()->dbremove(txn, _dbName.c_str(), 0, 0); - if(ownTx) - { - tx->commit(); - } + if(ownTx) + { + tx->commit(); + } } catch(const ::DbException& dx) { - if(ownTx) - { - tx = _connection->currentTransaction(); - if(tx != 0) - { - try - { - tx->rollback(); - } - catch(...) - { - } - } - } - - DatabaseException ex(__FILE__, __LINE__); - ex.message = dx.what(); - throw ex; + if(ownTx) + { + tx = _connection->currentTransaction(); + if(tx != 0) + { + try + { + tx->rollback(); + } + catch(...) + { + } + } + } + + DatabaseException ex(__FILE__, __LINE__); + ex.message = dx.what(); + throw ex; } catch(...) { - if(ownTx) - { - tx = _connection->currentTransaction(); - if(tx != 0) - { - try - { - tx->rollback(); - } - catch(...) - { - } - } - } - throw; + if(ownTx) + { + tx = _connection->currentTransaction(); + if(tx != 0) + { + try + { + tx->rollback(); + } + catch(...) + { + } + } + } + throw; } } @@ -1282,9 +1282,9 @@ Freeze::MapHelperI::size() const } catch(const ::DbException& dx) { - DatabaseException ex(__FILE__, __LINE__); - ex.message = dx.what(); - throw ex; + DatabaseException ex(__FILE__, __LINE__); + ex.message = dx.what(); + throw ex; } size_t num = s->bt_ndata; @@ -1298,7 +1298,7 @@ Freeze::MapHelperI::closeAllIterators() { while(!_iteratorList.empty()) { - (*_iteratorList.begin())->close(); + (*_iteratorList.begin())->close(); } } @@ -1308,9 +1308,9 @@ Freeze::MapHelperI::index(const string& name) const IndexMap::const_iterator p = _indices.find(name); if(p == _indices.end()) { - DatabaseException ex(__FILE__, __LINE__); - ex.message = "Cannot find index \"" + name + "\""; - throw ex; + DatabaseException ex(__FILE__, __LINE__); + ex.message = "Cannot find index \"" + name + "\""; + throw ex; } return p->second; } @@ -1320,16 +1320,16 @@ Freeze::MapHelperI::close() { if(_db != 0) { - _connection->unregisterMap(this); + _connection->unregisterMap(this); } _db = 0; for(IndexMap::iterator p = _indices.begin(); p != _indices.end(); ++p) { - MapIndexBasePtr& indexBase = p->second; + MapIndexBasePtr& indexBase = p->second; - indexBase->_impl = 0; - indexBase->_map = 0; + indexBase->_impl = 0; + indexBase->_map = 0; } _indices.clear(); } @@ -1343,15 +1343,15 @@ Freeze::MapHelperI::closeAllIteratorsExcept(const IteratorHelperI::TxPtr& tx) co while(q != _iteratorList.end()) { - if((*q)->tx().get() == tx.get()) - { - ++q; - } - else - { - (*q)->close(); - q = _iteratorList.begin(); - } + if((*q)->tx().get() == tx.get()) + { + ++q; + } + else + { + (*q)->close(); + q = _iteratorList.begin(); + } } } @@ -1385,7 +1385,7 @@ callback(Db* secondary, const Dbt* key, const Dbt* value, Dbt* result) Freeze::MapIndexI::MapIndexI(const ConnectionIPtr& connection, SharedDb& db, - DbTxn* txn, bool createDb, const MapIndexBasePtr& index) : + DbTxn* txn, bool createDb, const MapIndexBasePtr& index) : _index(index) { assert(txn != 0); @@ -1397,7 +1397,7 @@ Freeze::MapIndexI::MapIndexI(const ConnectionIPtr& connection, SharedDb& db, u_int32_t flags = 0; if(createDb) { - flags = DB_CREATE; + flags = DB_CREATE; } _dbName = db.dbName() + "." + _index->name(); @@ -1406,7 +1406,7 @@ Freeze::MapIndexI::MapIndexI(const ConnectionIPtr& connection, SharedDb& db, if(index->compareEnabled()) { - _db->set_bt_compare(&customIndexCompare); + _db->set_bt_compare(&customIndexCompare); } _db->open(txn, _dbName.c_str(), 0, DB_BTREE, flags, FREEZE_DB_MODE); @@ -1429,17 +1429,17 @@ Freeze::MapIndexI::~MapIndexI() IteratorHelper* Freeze::MapIndexI::untypedFind(const Key& k, bool ro, const MapHelperI& m, - bool onlyDups) const + bool onlyDups) const { auto_ptr r(new IteratorHelperI(m, ro, _index, onlyDups)); if(r->find(k)) { - return r.release(); + return r.release(); } else { - return 0; + return 0; } } @@ -1450,11 +1450,11 @@ Freeze::MapIndexI::untypedLowerBound(const Key& k, bool ro, const MapHelperI& m) if(r->lowerBound(k)) { - return r.release(); + return r.release(); } else { - return 0; + return 0; } } @@ -1465,11 +1465,11 @@ Freeze::MapIndexI::untypedUpperBound(const Key& k, bool ro, const MapHelperI& m) if(r->upperBound(k)) { - return r.release(); + return r.release(); } else { - return 0; + return 0; } } @@ -1493,81 +1493,81 @@ Freeze::MapIndexI::untypedCount(const Key& k, const ConnectionIPtr& connection) try { - for(;;) - { - Dbc* dbc = 0; - - try - { - // - // Move to the first record - // - _db->cursor(0, &dbc, 0); - bool found = (dbc->get(&dbKey, &dbValue, DB_SET) == 0); - - if(found) - { - db_recno_t count = 0; - dbc->count(&count, 0); - result = static_cast(count); - } - - Dbc* toClose = dbc; - dbc = 0; - toClose->close(); - break; // for (;;) - } - catch(const DbDeadlockException&) - { - if(dbc != 0) - { - try - { - dbc->close(); - } - catch(const DbDeadlockException&) - { - // - // Ignored - // - } - } - - if(connection->deadlockWarning()) - { - Warning out(connection->communicator()->getLogger()); - out << "Deadlock in Freeze::MapIndexI::untypedCount while searching \"" - << _dbName << "\"; retrying ..."; - } - - // - // Retry - // - } - catch(...) - { - if(dbc != 0) - { - try - { - dbc->close(); - } - catch(const DbDeadlockException&) - { - // - // Ignored - // - } - } - throw; - } - } + for(;;) + { + Dbc* dbc = 0; + + try + { + // + // Move to the first record + // + _db->cursor(0, &dbc, 0); + bool found = (dbc->get(&dbKey, &dbValue, DB_SET) == 0); + + if(found) + { + db_recno_t count = 0; + dbc->count(&count, 0); + result = static_cast(count); + } + + Dbc* toClose = dbc; + dbc = 0; + toClose->close(); + break; // for (;;) + } + catch(const DbDeadlockException&) + { + if(dbc != 0) + { + try + { + dbc->close(); + } + catch(const DbDeadlockException&) + { + // + // Ignored + // + } + } + + if(connection->deadlockWarning()) + { + Warning out(connection->communicator()->getLogger()); + out << "Deadlock in Freeze::MapIndexI::untypedCount while searching \"" + << _dbName << "\"; retrying ..."; + } + + // + // Retry + // + } + catch(...) + { + if(dbc != 0) + { + try + { + dbc->close(); + } + catch(const DbDeadlockException&) + { + // + // Ignored + // + } + } + throw; + } + } } catch(const DbException& dx) { - DatabaseException ex(__FILE__, __LINE__); - ex.message = dx.what(); - throw ex; + DatabaseException ex(__FILE__, __LINE__); + ex.message = dx.what(); + throw ex; } return result; @@ -1575,7 +1575,7 @@ Freeze::MapIndexI::untypedCount(const Key& k, const ConnectionIPtr& connection) int Freeze::MapIndexI::secondaryKeyCreate(Db* secondary, const Dbt* dbKey, - const Dbt* dbValue, Dbt* result) + const Dbt* dbValue, Dbt* result) { Byte* first = static_cast(dbValue->get_data()); Value value(first, first + dbValue->get_size()); diff --git a/cpp/src/Freeze/MapI.h b/cpp/src/Freeze/MapI.h index fa2e3524b3e..3623beae33d 100644 --- a/cpp/src/Freeze/MapI.h +++ b/cpp/src/Freeze/MapI.h @@ -24,7 +24,7 @@ class IteratorHelperI : public IteratorHelper public: IteratorHelperI(const MapHelperI& m, bool readOnly, - const MapIndexBasePtr& index, bool onlyDups); + const MapIndexBasePtr& index, bool onlyDups); IteratorHelperI(const IteratorHelperI&); virtual @@ -66,20 +66,20 @@ public: { public: - Tx(const MapHelperI&); - ~Tx(); + Tx(const MapHelperI&); + ~Tx(); - void dead(); + void dead(); - DbTxn* getTxn() - { - return _txn; - } + DbTxn* getTxn() + { + return _txn; + } private: - const MapHelperI& _map; - DbTxn* _txn; - bool _dead; + const MapHelperI& _map; + DbTxn* _txn; + bool _dead; }; typedef IceUtil::Handle TxPtr; @@ -108,9 +108,9 @@ class MapHelperI : public MapHelper public: MapHelperI(const ConnectionIPtr&, const std::string&, - const std::string&, const std::string&, - const KeyCompareBasePtr&, - const std::vector&, bool); + const std::string&, const std::string&, + const KeyCompareBasePtr&, + const std::vector&, bool); virtual ~MapHelperI(); @@ -152,7 +152,7 @@ public: const ConnectionIPtr& connection() const { - return _connection; + return _connection; } diff --git a/cpp/src/Freeze/ObjectStore.cpp b/cpp/src/Freeze/ObjectStore.cpp index 6f120752afb..24ab9ba484f 100644 --- a/cpp/src/Freeze/ObjectStore.cpp +++ b/cpp/src/Freeze/ObjectStore.cpp @@ -20,9 +20,9 @@ using namespace Freeze; Freeze::ObjectStore::ObjectStore(const string& facet, - bool createDb, EvictorI* evictor, - const vector& indices, - bool populateEmptyIndices) : + bool createDb, EvictorI* evictor, + const vector& indices, + bool populateEmptyIndices) : _facet(facet), _evictor(evictor), _indices(indices), @@ -30,11 +30,11 @@ Freeze::ObjectStore::ObjectStore(const string& facet, { if(facet == "") { - _dbName = EvictorI::defaultDb; + _dbName = EvictorI::defaultDb; } else { - _dbName = facet; + _dbName = facet; } ConnectionPtr catalogConnection = createConnection(_communicator, evictor->dbEnv()->getEnvName()); @@ -43,85 +43,85 @@ Freeze::ObjectStore::ObjectStore(const string& facet, Catalog::iterator p = catalog.find(evictor->filename()); if(p != catalog.end()) { - if(p->second.evictor == false) - { - DatabaseException ex(__FILE__, __LINE__); - ex.message = evictor->filename() + " is an evictor database"; - throw ex; - } + if(p->second.evictor == false) + { + DatabaseException ex(__FILE__, __LINE__); + ex.message = evictor->filename() + " is an evictor database"; + throw ex; + } } DbEnv* dbEnv = evictor->dbEnv()->getEnv(); try { - _db.reset(new Db(dbEnv, 0)); - - TransactionPtr tx = catalogConnection->beginTransaction(); - DbTxn* txn = getTxn(tx); - - u_int32_t flags = DB_THREAD; - if(createDb) - { - flags |= DB_CREATE; - } - _db->open(txn, evictor->filename().c_str(), _dbName.c_str(), DB_BTREE, flags, FREEZE_DB_MODE); - - for(size_t i = 0; i < _indices.size(); ++i) - { - _indices[i]->_impl->associate(this, txn, createDb, populateEmptyIndices); - } - - if(p == catalog.end()) - { - CatalogData catalogData; - catalogData.evictor = true; - catalog.put(Catalog::value_type(evictor->filename(), catalogData)); - } - - tx->commit(); + _db.reset(new Db(dbEnv, 0)); + + TransactionPtr tx = catalogConnection->beginTransaction(); + DbTxn* txn = getTxn(tx); + + u_int32_t flags = DB_THREAD; + if(createDb) + { + flags |= DB_CREATE; + } + _db->open(txn, evictor->filename().c_str(), _dbName.c_str(), DB_BTREE, flags, FREEZE_DB_MODE); + + for(size_t i = 0; i < _indices.size(); ++i) + { + _indices[i]->_impl->associate(this, txn, createDb, populateEmptyIndices); + } + + if(p == catalog.end()) + { + CatalogData catalogData; + catalogData.evictor = true; + catalog.put(Catalog::value_type(evictor->filename(), catalogData)); + } + + tx->commit(); } catch(const DbException& dx) { - TransactionPtr tx = catalogConnection->currentTransaction(); - if(tx != 0) - { - try - { - tx->rollback(); - } - catch(...) - { - } - } - - if(dx.get_errno() == ENOENT) - { - NotFoundException ex(__FILE__, __LINE__); - ex.message = dx.what(); - throw ex; - } - else - { - DatabaseException ex(__FILE__, __LINE__); - ex.message = dx.what(); - throw ex; - } + TransactionPtr tx = catalogConnection->currentTransaction(); + if(tx != 0) + { + try + { + tx->rollback(); + } + catch(...) + { + } + } + + if(dx.get_errno() == ENOENT) + { + NotFoundException ex(__FILE__, __LINE__); + ex.message = dx.what(); + throw ex; + } + else + { + DatabaseException ex(__FILE__, __LINE__); + ex.message = dx.what(); + throw ex; + } } catch(...) { - TransactionPtr tx = catalogConnection->currentTransaction(); - if(tx != 0) - { - try - { - tx->rollback(); - } - catch(...) - { - } - } - throw; + TransactionPtr tx = catalogConnection->currentTransaction(); + if(tx != 0) + { + try + { + tx->rollback(); + } + catch(...) + { + } + } + throw; } } @@ -129,7 +129,7 @@ Freeze::ObjectStore::~ObjectStore() { if(_db.get() != 0) { - close(); + close(); } } @@ -138,19 +138,19 @@ Freeze::ObjectStore::close() { try { - _db->close(0); - - for(size_t i = 0; i < _indices.size(); ++i) - { - _indices[i]->_impl->close(); - } - _indices.clear(); + _db->close(0); + + for(size_t i = 0; i < _indices.size(); ++i) + { + _indices[i]->_impl->close(); + } + _indices.clear(); } catch(const DbException& dx) { - DatabaseException ex(__FILE__, __LINE__); - ex.message = dx.what(); - throw ex; + DatabaseException ex(__FILE__, __LINE__); + ex.message = dx.what(); + throw ex; } _db.reset(); } @@ -171,43 +171,43 @@ Freeze::ObjectStore::dbHasObject(const Identity& ident) const for(;;) { - try - { - int err = _db->get(0, &dbKey, &dbValue, 0); - - if(err == 0) - { - return true; - } - else if(err == DB_NOTFOUND) - { - return false; - } - else - { - assert(0); - throw DatabaseException(__FILE__, __LINE__); - } - } - catch(const DbDeadlockException&) - { - if(_evictor->deadlockWarning()) - { - Warning out(_communicator->getLogger()); - out << "Deadlock in Freeze::ObjectStore::dbHasObject while searching \"" - << _evictor->filename() + "/" + _dbName << "\"; retrying ..."; - } - - // - // Ignored, try again - // - } - catch(const DbException& dx) - { - DatabaseException ex(__FILE__, __LINE__); - ex.message = dx.what(); - throw ex; - } + try + { + int err = _db->get(0, &dbKey, &dbValue, 0); + + if(err == 0) + { + return true; + } + else if(err == DB_NOTFOUND) + { + return false; + } + else + { + assert(0); + throw DatabaseException(__FILE__, __LINE__); + } + } + catch(const DbDeadlockException&) + { + if(_evictor->deadlockWarning()) + { + Warning out(_communicator->getLogger()); + out << "Deadlock in Freeze::ObjectStore::dbHasObject while searching \"" + << _evictor->filename() + "/" + _dbName << "\"; retrying ..."; + } + + // + // Ignored, try again + // + } + catch(const DbException& dx) + { + DatabaseException ex(__FILE__, __LINE__); + ex.message = dx.what(); + throw ex; + } } } @@ -217,37 +217,37 @@ Freeze::ObjectStore::save(Key& key, Value& value, Byte status, DbTxn* tx) { switch(status) { - case EvictorElement::created: - case EvictorElement::modified: - { - Dbt dbKey; - Dbt dbValue; - initializeInDbt(key, dbKey); - initializeInDbt(value, dbValue); - u_int32_t flags = (status == EvictorElement::created) ? DB_NOOVERWRITE : 0; - int err = _db->put(tx, &dbKey, &dbValue, flags); - if(err != 0) - { - throw DatabaseException(__FILE__, __LINE__); - } - break; - } - - case EvictorElement::destroyed: - { - Dbt dbKey; - initializeInDbt(key, dbKey); - int err = _db->del(tx, &dbKey, 0); - if(err != 0) - { - throw DatabaseException(__FILE__, __LINE__); - } - break; - } - default: - { - assert(0); - } + case EvictorElement::created: + case EvictorElement::modified: + { + Dbt dbKey; + Dbt dbValue; + initializeInDbt(key, dbKey); + initializeInDbt(value, dbValue); + u_int32_t flags = (status == EvictorElement::created) ? DB_NOOVERWRITE : 0; + int err = _db->put(tx, &dbKey, &dbValue, flags); + if(err != 0) + { + throw DatabaseException(__FILE__, __LINE__); + } + break; + } + + case EvictorElement::destroyed: + { + Dbt dbKey; + initializeInDbt(key, dbKey); + int err = _db->del(tx, &dbKey, 0); + if(err != 0) + { + throw DatabaseException(__FILE__, __LINE__); + } + break; + } + default: + { + assert(0); + } } } @@ -322,36 +322,36 @@ Freeze::ObjectStore::load(const Identity& ident) for(;;) { - try - { - int rs = _db->get(0, &dbKey, &dbValue, 0); - if(rs == DB_NOTFOUND) - { - return 0; - } - else if(rs != 0) - { - assert(0); - throw DatabaseException(__FILE__, __LINE__); - } - break; // for(;;) - } - catch(const DbDeadlockException&) - { - if(_evictor->deadlockWarning()) - { - Warning out(_communicator->getLogger()); - out << "Deadlock in Freeze::ObjectStore::load while searching \"" - << _evictor->filename() + "/" + _dbName << "\"; retrying ..."; - } - // - // Ignored, try again - // - } - catch(const DbException& dx) - { - handleDbException(dx, value, dbValue, __FILE__, __LINE__); - } + try + { + int rs = _db->get(0, &dbKey, &dbValue, 0); + if(rs == DB_NOTFOUND) + { + return 0; + } + else if(rs != 0) + { + assert(0); + throw DatabaseException(__FILE__, __LINE__); + } + break; // for(;;) + } + catch(const DbDeadlockException&) + { + if(_evictor->deadlockWarning()) + { + Warning out(_communicator->getLogger()); + out << "Deadlock in Freeze::ObjectStore::load while searching \"" + << _evictor->filename() + "/" + _dbName << "\"; retrying ..."; + } + // + // Ignored, try again + // + } + catch(const DbException& dx) + { + handleDbException(dx, value, dbValue, __FILE__, __LINE__); + } } EvictorElementPtr result = new EvictorElement(*this); diff --git a/cpp/src/Freeze/ObjectStore.h b/cpp/src/Freeze/ObjectStore.h index 274a82331f7..94db579a64d 100644 --- a/cpp/src/Freeze/ObjectStore.h +++ b/cpp/src/Freeze/ObjectStore.h @@ -36,7 +36,7 @@ class ObjectStore : public Cache public: ObjectStore(const std::string&, bool, EvictorI*, - const std::vector& = std::vector(), bool = false); + const std::vector& = std::vector(), bool = false); virtual ~ObjectStore(); diff --git a/cpp/src/Freeze/SharedDb.cpp b/cpp/src/Freeze/SharedDb.cpp index 86205fa91b4..0c208c26eb1 100644 --- a/cpp/src/Freeze/SharedDb.cpp +++ b/cpp/src/Freeze/SharedDb.cpp @@ -31,15 +31,15 @@ checkTypes(const SharedDb& sharedDb, const string& key, const string& value) { if(key != sharedDb.key()) { - DatabaseException ex(__FILE__, __LINE__); - ex.message = sharedDb.dbName() + "'s key type is " + sharedDb.key() + ", not " + key; - throw ex; + DatabaseException ex(__FILE__, __LINE__); + ex.message = sharedDb.dbName() + "'s key type is " + sharedDb.key() + ", not " + key; + throw ex; } if(value != sharedDb.value()) { - DatabaseException ex(__FILE__, __LINE__); - ex.message = sharedDb.dbName() + "'s value type is " + sharedDb.value() + ", not " + value; - throw ex; + DatabaseException ex(__FILE__, __LINE__); + ex.message = sharedDb.dbName() + "'s value type is " + sharedDb.value() + ", not " + value; + throw ex; } } } @@ -68,29 +68,29 @@ Freeze::catalogName() SharedDbPtr Freeze::SharedDb::get(const ConnectionIPtr& connection, - const string& dbName, - const string& key, - const string& value, - const KeyCompareBasePtr& keyCompare, - const vector& indices, - bool createDb) + const string& dbName, + const string& key, + const string& value, + const KeyCompareBasePtr& keyCompare, + const vector& indices, + bool createDb) { if(dbName == _catalogName) { - // - // We don't want to lock the _mapMutex to retrieve the catalog - // - - SharedDbPtr result = connection->dbEnv()->getCatalog(); - checkTypes(*result, key, value); - return result; + // + // We don't want to lock the _mapMutex to retrieve the catalog + // + + SharedDbPtr result = connection->dbEnv()->getCatalog(); + checkTypes(*result, key, value); + return result; } StaticMutex::Lock lock(_mapMutex); if(sharedDbMap == 0) { - sharedDbMap = new SharedDbMap; + sharedDbMap = new SharedDbMap; } MapKey mapKey; @@ -99,20 +99,20 @@ Freeze::SharedDb::get(const ConnectionIPtr& connection, mapKey.dbName = dbName; { - SharedDbMap::iterator p = sharedDbMap->find(mapKey); - if(p != sharedDbMap->end()) - { - checkTypes(*(p->second), key, value); - p->second->connectIndices(indices); - return p->second; - } + SharedDbMap::iterator p = sharedDbMap->find(mapKey); + if(p != sharedDbMap->end()) + { + checkTypes(*(p->second), key, value); + p->second->connectIndices(indices); + return p->second; + } } // // MapKey not found, let's create and open a new Db // auto_ptr result(new SharedDb(mapKey, key, value, connection, - keyCompare, indices, createDb)); + keyCompare, indices, createDb)); // // Insert it into the map @@ -131,7 +131,7 @@ Freeze::SharedDb::openCatalog(SharedDbEnv& dbEnv) if(sharedDbMap == 0) { - sharedDbMap = new SharedDbMap; + sharedDbMap = new SharedDbMap; } MapKey mapKey; @@ -145,17 +145,17 @@ Freeze::SharedDb::openCatalog(SharedDbEnv& dbEnv) // Insert it into the map // pair insertResult - = sharedDbMap->insert(SharedDbMap::value_type(mapKey, result.get())); + = sharedDbMap->insert(SharedDbMap::value_type(mapKey, result.get())); if(!insertResult.second) { - // - // That's very wrong: the catalog is associated with another env - // - assert(0); - DatabaseException ex(__FILE__, __LINE__); - ex.message = "Catalog already opened"; - throw ex; + // + // That's very wrong: the catalog is associated with another env + // + assert(0); + DatabaseException ex(__FILE__, __LINE__); + ex.message = "Catalog already opened"; + throw ex; } return result.release(); @@ -166,8 +166,8 @@ Freeze::SharedDb::~SharedDb() { if(_trace >= 1) { - Trace out(_mapKey.communicator->getLogger(), "Freeze.Map"); - out << "closing Db \"" << _mapKey.dbName << "\""; + Trace out(_mapKey.communicator->getLogger(), "Freeze.Map"); + out << "closing Db \"" << _mapKey.dbName << "\""; } cleanup(false); @@ -177,8 +177,8 @@ void Freeze::SharedDb::__incRef() { if(_trace >= 2) { - Trace out(_mapKey.communicator->getLogger(), "Freeze.Map"); - out << "incremeting reference count for Db \"" << _mapKey.dbName << "\""; + Trace out(_mapKey.communicator->getLogger(), "Freeze.Map"); + out << "incremeting reference count for Db \"" << _mapKey.dbName << "\""; } IceUtil::StaticMutex::Lock lock(_refCountMutex); @@ -189,57 +189,57 @@ void Freeze::SharedDb::__decRef() { if(_trace >= 2) { - Trace out(_mapKey.communicator->getLogger(), "Freeze.Map"); - out << "removing reference count for Db \"" << _mapKey.dbName << "\""; + Trace out(_mapKey.communicator->getLogger(), "Freeze.Map"); + out << "removing reference count for Db \"" << _mapKey.dbName << "\""; } IceUtil::StaticMutex::Lock lock(_refCountMutex); if(--_refCount == 0) { IceUtil::StaticMutex::TryLock mapLock(_mapMutex); - if(!mapLock.acquired()) - { - // - // Reacquire mutex in proper order and check again - // - lock.release(); - mapLock.acquire(); - lock.acquire(); - if(_refCount > 0) - { - return; - } - } - - // - // Remove from map - // - size_t one; - one = sharedDbMap->erase(_mapKey); - assert(one == 1); - - if(sharedDbMap->size() == 0) - { - delete sharedDbMap; - sharedDbMap = 0; - } - - // - // Keep lock to prevent somebody else to re-open this Db - // before it's closed. - // - delete this; + if(!mapLock.acquired()) + { + // + // Reacquire mutex in proper order and check again + // + lock.release(); + mapLock.acquire(); + lock.acquire(); + if(_refCount > 0) + { + return; + } + } + + // + // Remove from map + // + size_t one; + one = sharedDbMap->erase(_mapKey); + assert(one == 1); + + if(sharedDbMap->size() == 0) + { + delete sharedDbMap; + sharedDbMap = 0; + } + + // + // Keep lock to prevent somebody else to re-open this Db + // before it's closed. + // + delete this; } } Freeze::SharedDb::SharedDb(const MapKey& mapKey, - const string& key, - const string& value, - const ConnectionIPtr& connection, - const KeyCompareBasePtr& keyCompare, - const vector& indices, - bool createDb) : + const string& key, + const string& value, + const ConnectionIPtr& connection, + const KeyCompareBasePtr& keyCompare, + const vector& indices, + bool createDb) : Db(connection->dbEnv()->getEnv(), 0), _mapKey(mapKey), _refCount(0), @@ -248,128 +248,128 @@ Freeze::SharedDb::SharedDb(const MapKey& mapKey, { if(_trace >= 1) { - Trace out(_mapKey.communicator->getLogger(), "Freeze.Map"); - out << "opening Db \"" << _mapKey.dbName << "\""; + Trace out(_mapKey.communicator->getLogger(), "Freeze.Map"); + out << "opening Db \"" << _mapKey.dbName << "\""; } ConnectionPtr catalogConnection = - createConnection(_mapKey.communicator, connection->dbEnv()->getEnvName()); + createConnection(_mapKey.communicator, connection->dbEnv()->getEnvName()); Catalog catalog(catalogConnection, _catalogName); Catalog::iterator ci = catalog.find(_mapKey.dbName); if(ci != catalog.end()) { - if(ci->second.evictor) - { - DatabaseException ex(__FILE__, __LINE__); - ex.message = _mapKey.dbName + " is an evictor database"; - throw ex; - } - - _key = ci->second.key; - _value = ci->second.value; - checkTypes(*this, key, value); + if(ci->second.evictor) + { + DatabaseException ex(__FILE__, __LINE__); + ex.message = _mapKey.dbName + " is an evictor database"; + throw ex; + } + + _key = ci->second.key; + _value = ci->second.value; + checkTypes(*this, key, value); } else { - _key = key; - _value = value; + _key = key; + _value = value; } set_app_private(this); if(_keyCompare->compareEnabled()) { - set_bt_compare(&customCompare); + set_bt_compare(&customCompare); } try { - TransactionPtr tx = catalogConnection->beginTransaction(); - DbTxn* txn = getTxn(tx); - - u_int32_t flags = DB_THREAD; - if(createDb) - { - flags |= DB_CREATE; - } - open(txn, _mapKey.dbName.c_str(), 0, DB_BTREE, flags, FREEZE_DB_MODE); - - for(vector::const_iterator p = indices.begin(); - p != indices.end(); ++p) - { - const MapIndexBasePtr& indexBase = *p; - assert(indexBase->_impl == 0); - assert(indexBase->_communicator == 0); - indexBase->_communicator = connection->communicator(); - - auto_ptr indexI(new MapIndexI(connection, *this, txn, createDb, indexBase)); - + TransactionPtr tx = catalogConnection->beginTransaction(); + DbTxn* txn = getTxn(tx); + + u_int32_t flags = DB_THREAD; + if(createDb) + { + flags |= DB_CREATE; + } + open(txn, _mapKey.dbName.c_str(), 0, DB_BTREE, flags, FREEZE_DB_MODE); + + for(vector::const_iterator p = indices.begin(); + p != indices.end(); ++p) + { + const MapIndexBasePtr& indexBase = *p; + assert(indexBase->_impl == 0); + assert(indexBase->_communicator == 0); + indexBase->_communicator = connection->communicator(); + + auto_ptr indexI(new MapIndexI(connection, *this, txn, createDb, indexBase)); + #ifndef NDEBUG - bool inserted = + bool inserted = #endif - _indices.insert(IndexMap::value_type(indexBase->name(), indexI.get())).second; - assert(inserted); - - indexBase->_impl = indexI.release(); - } - - if(ci == catalog.end()) - { - CatalogData catalogData; - catalogData.evictor = false; - catalogData.key = key; - catalogData.value = value; - catalog.put(Catalog::value_type(_mapKey.dbName, catalogData)); - } - - tx->commit(); + _indices.insert(IndexMap::value_type(indexBase->name(), indexI.get())).second; + assert(inserted); + + indexBase->_impl = indexI.release(); + } + + if(ci == catalog.end()) + { + CatalogData catalogData; + catalogData.evictor = false; + catalogData.key = key; + catalogData.value = value; + catalog.put(Catalog::value_type(_mapKey.dbName, catalogData)); + } + + tx->commit(); } catch(const ::DbException& dx) { - TransactionPtr tx = catalogConnection->currentTransaction(); - if(tx != 0) - { - try - { - tx->rollback(); - } - catch(...) - { - } - } - - cleanup(true); - - if(dx.get_errno() == ENOENT) - { - NotFoundException ex(__FILE__, __LINE__); - ex.message = dx.what(); - throw ex; - } - else - { - DatabaseException ex(__FILE__, __LINE__); - ex.message = dx.what(); - throw ex; - } + TransactionPtr tx = catalogConnection->currentTransaction(); + if(tx != 0) + { + try + { + tx->rollback(); + } + catch(...) + { + } + } + + cleanup(true); + + if(dx.get_errno() == ENOENT) + { + NotFoundException ex(__FILE__, __LINE__); + ex.message = dx.what(); + throw ex; + } + else + { + DatabaseException ex(__FILE__, __LINE__); + ex.message = dx.what(); + throw ex; + } } catch(...) { - TransactionPtr tx = catalogConnection->currentTransaction(); - if(tx != 0) - { - try - { - tx->rollback(); - } - catch(...) - { - } - } - - cleanup(true); - throw; + TransactionPtr tx = catalogConnection->currentTransaction(); + if(tx != 0) + { + try + { + tx->rollback(); + } + catch(...) + { + } + } + + cleanup(true); + throw; } } @@ -385,20 +385,20 @@ Freeze::SharedDb::SharedDb(const MapKey& mapKey, DbEnv* env) : if(_trace >= 1) { - Trace out(_mapKey.communicator->getLogger(), "Freeze.Db"); - out << "opening Db \"" << _mapKey.dbName << "\""; + Trace out(_mapKey.communicator->getLogger(), "Freeze.Db"); + out << "opening Db \"" << _mapKey.dbName << "\""; } try { - u_int32_t flags = DB_THREAD | DB_CREATE | DB_AUTO_COMMIT; - open(0, _mapKey.dbName.c_str(), 0, DB_BTREE, flags, FREEZE_DB_MODE); + u_int32_t flags = DB_THREAD | DB_CREATE | DB_AUTO_COMMIT; + open(0, _mapKey.dbName.c_str(), 0, DB_BTREE, flags, FREEZE_DB_MODE); } catch(const ::DbException& dx) { - DatabaseException ex(__FILE__, __LINE__); - ex.message = dx.what(); - throw ex; + DatabaseException ex(__FILE__, __LINE__); + ex.message = dx.what(); + throw ex; } } @@ -406,15 +406,15 @@ void Freeze::SharedDb::connectIndices(const vector& indices) const { for(vector::const_iterator p = indices.begin(); - p != indices.end(); ++p) + p != indices.end(); ++p) { - const MapIndexBasePtr& indexBase = *p; - assert(indexBase->_impl == 0); + const MapIndexBasePtr& indexBase = *p; + assert(indexBase->_impl == 0); - IndexMap::const_iterator q = _indices.find(indexBase->name()); - assert(q != _indices.end()); - indexBase->_impl = q->second; - indexBase->_communicator = _mapKey.communicator; + IndexMap::const_iterator q = _indices.find(indexBase->name()); + assert(q != _indices.end()); + indexBase->_impl = q->second; + indexBase->_communicator = _mapKey.communicator; } } @@ -423,21 +423,21 @@ Freeze::SharedDb::cleanup(bool noThrow) { try { - for(IndexMap::iterator p = _indices.begin(); p != _indices.end(); ++p) - { - delete p->second; - } - _indices.clear(); - - close(0); + for(IndexMap::iterator p = _indices.begin(); p != _indices.end(); ++p) + { + delete p->second; + } + _indices.clear(); + + close(0); } catch(const ::DbException& dx) { - if(!noThrow) - { - DatabaseException ex(__FILE__, __LINE__); - ex.message = dx.what(); - throw ex; - } + if(!noThrow) + { + DatabaseException ex(__FILE__, __LINE__); + ex.message = dx.what(); + throw ex; + } } } diff --git a/cpp/src/Freeze/SharedDb.h b/cpp/src/Freeze/SharedDb.h index a6ce6672c44..3576f51fa23 100644 --- a/cpp/src/Freeze/SharedDb.h +++ b/cpp/src/Freeze/SharedDb.h @@ -30,7 +30,7 @@ class MapIndexI public: MapIndexI(const ConnectionIPtr&, SharedDb&, - DbTxn*, bool, const MapIndexBasePtr&); + DbTxn*, bool, const MapIndexBasePtr&); ~MapIndexI(); @@ -45,17 +45,17 @@ public: const std::string name() const { - return _index->name(); + return _index->name(); } Db* db() const { - return _db.get(); + return _db.get(); } const MapIndexBasePtr& getKeyCompare() const { - return _index; + return _index; } private: @@ -73,9 +73,9 @@ public: using Db::get; static SharedDbPtr get(const ConnectionIPtr&, const std::string&, - const std::string&, const std::string&, - const KeyCompareBasePtr&, - const std::vector&, bool); + const std::string&, const std::string&, + const KeyCompareBasePtr&, + const std::vector&, bool); static SharedDbPtr openCatalog(SharedDbEnv&); @@ -101,7 +101,7 @@ public: virtual int get(DbTxn *txnid, Dbt *key, Dbt *data, u_int32_t flags) { - return ::Db::get(txnid, key, data, flags); + return ::Db::get(txnid, key, data, flags); } #endif @@ -111,19 +111,19 @@ private: struct MapKey { - std::string envName; - Ice::CommunicatorPtr communicator; - std::string dbName; + std::string envName; + Ice::CommunicatorPtr communicator; + std::string dbName; - inline bool - operator<(const MapKey& rhs) const; + inline bool + operator<(const MapKey& rhs) const; }; typedef std::map SharedDbMap; SharedDb(const MapKey&, const std::string&, const std::string&, - const ConnectionIPtr&, const KeyCompareBasePtr&, - const std::vector&, bool); + const ConnectionIPtr&, const KeyCompareBasePtr&, + const std::vector&, bool); SharedDb(const MapKey&, DbEnv*); @@ -170,8 +170,8 @@ inline bool SharedDb::MapKey::operator<(const MapKey& rhs) const { return (communicator < rhs.communicator) || - ((communicator == rhs.communicator) && (dbName < rhs.dbName)) || - ((communicator == rhs.communicator) && (dbName == rhs.dbName) && (envName < rhs.envName)); + ((communicator == rhs.communicator) && (dbName < rhs.dbName)) || + ((communicator == rhs.communicator) && (dbName == rhs.dbName) && (envName < rhs.envName)); } } diff --git a/cpp/src/Freeze/SharedDbEnv.cpp b/cpp/src/Freeze/SharedDbEnv.cpp index ea1dc64a054..3c03af446d2 100644 --- a/cpp/src/Freeze/SharedDbEnv.cpp +++ b/cpp/src/Freeze/SharedDbEnv.cpp @@ -59,7 +59,7 @@ inline bool operator<(const MapKey& lhs, const MapKey& rhs) { return (lhs.communicator < rhs.communicator) || - ((lhs.communicator == rhs.communicator) && (lhs.envName < rhs.envName)); + ((lhs.communicator == rhs.communicator) && (lhs.envName < rhs.envName)); } #if DB_VERSION_MAJOR != 4 @@ -92,13 +92,13 @@ SharedDbEnvMap* sharedDbEnvMap; Freeze::SharedDbEnvPtr Freeze::SharedDbEnv::get(const CommunicatorPtr& communicator, - const string& envName, DbEnv* env) + const string& envName, DbEnv* env) { StaticMutex::Lock lock(_mapMutex); if(sharedDbEnvMap == 0) { - sharedDbEnvMap = new SharedDbEnvMap; + sharedDbEnvMap = new SharedDbEnvMap; } MapKey key; @@ -106,11 +106,11 @@ Freeze::SharedDbEnv::get(const CommunicatorPtr& communicator, key.communicator = communicator; { - SharedDbEnvMap::iterator p = sharedDbEnvMap->find(key); - if(p != sharedDbEnvMap->end()) - { - return p->second; - } + SharedDbEnvMap::iterator p = sharedDbEnvMap->find(key); + if(p != sharedDbEnvMap->end()) + { + return p->second; + } } // @@ -132,8 +132,8 @@ Freeze::SharedDbEnv::~SharedDbEnv() { if(_trace >= 1) { - Trace out(_communicator->getLogger(), "Freeze.DbEnv"); - out << "closing database environment \"" << _envName << "\""; + Trace out(_communicator->getLogger(), "Freeze.DbEnv"); + out << "closing database environment \"" << _envName << "\""; } // @@ -146,22 +146,22 @@ Freeze::SharedDbEnv::~SharedDbEnv() // if(_thread != 0) { - _thread->terminate(); - _thread = 0; + _thread->terminate(); + _thread = 0; } if(_envHolder.get() != 0) { - try - { - _envHolder->close(0); - } - catch(const ::DbException& dx) - { - DatabaseException ex(__FILE__, __LINE__); - ex.message = dx.what(); - throw ex; - } + try + { + _envHolder->close(0); + } + catch(const ::DbException& dx) + { + DatabaseException ex(__FILE__, __LINE__); + ex.message = dx.what(); + throw ex; + } } } @@ -177,47 +177,47 @@ void Freeze::SharedDbEnv::__decRef() if(--_refCount == 0) { IceUtil::StaticMutex::TryLock mapLock(_mapMutex); - if(!mapLock.acquired()) - { - // - // Reacquire mutex in proper order and check again - // - lock.release(); - mapLock.acquire(); - lock.acquire(); - if(_refCount > 0) - { - return; - } - } - - // - // Remove from map - // + if(!mapLock.acquired()) + { + // + // Reacquire mutex in proper order and check again + // + lock.release(); + mapLock.acquire(); + lock.acquire(); + if(_refCount > 0) + { + return; + } + } + + // + // Remove from map + // MapKey key; key.envName = _envName; key.communicator = _communicator; - size_t one; - one = sharedDbEnvMap->erase(key); - assert(one == 1); - - if(sharedDbEnvMap->size() == 0) - { - delete sharedDbEnvMap; - sharedDbEnvMap = 0; - } - - // - // Keep lock to prevent somebody else to re-open this DbEnv - // before it's closed. - // - delete this; + size_t one; + one = sharedDbEnvMap->erase(key); + assert(one == 1); + + if(sharedDbEnvMap->size() == 0) + { + delete sharedDbEnvMap; + sharedDbEnvMap = 0; + } + + // + // Keep lock to prevent somebody else to re-open this DbEnv + // before it's closed. + // + delete this; } } Freeze::SharedDbEnv::SharedDbEnv(const std::string& envName, - const Ice::CommunicatorPtr& communicator, DbEnv* env) : + const Ice::CommunicatorPtr& communicator, DbEnv* env) : _env(env), _envName(envName), _communicator(communicator), @@ -229,113 +229,113 @@ Freeze::SharedDbEnv::SharedDbEnv(const std::string& envName, if(_env == 0) { - _envHolder.reset(new DbEnv(0)); - _env = _envHolder.get(); + _envHolder.reset(new DbEnv(0)); + _env = _envHolder.get(); - if(_trace >= 1) - { - Trace out(_communicator->getLogger(), "Freeze.DbEnv"); - out << "opening database environment \"" << envName << "\""; - } + if(_trace >= 1) + { + Trace out(_communicator->getLogger(), "Freeze.DbEnv"); + out << "opening database environment \"" << envName << "\""; + } - string propertyPrefix = string("Freeze.DbEnv.") + envName; - - try - { - _env->set_errpfx(reinterpret_cast(this)); + string propertyPrefix = string("Freeze.DbEnv.") + envName; + + try + { + _env->set_errpfx(reinterpret_cast(this)); - _env->set_errcall(dbErrCallback); + _env->set_errcall(dbErrCallback); #ifdef _WIN32 - // - // Berkeley DB may use a different C++ runtime - // - _env->set_alloc(::malloc, ::realloc, ::free); + // + // Berkeley DB may use a different C++ runtime + // + _env->set_alloc(::malloc, ::realloc, ::free); #endif - - // - // Deadlock detection - // - _env->set_lk_detect(DB_LOCK_YOUNGEST); - - u_int32_t flags = DB_INIT_LOCK | DB_INIT_LOG | DB_INIT_MPOOL | DB_INIT_TXN; - - if(properties->getPropertyAsInt(propertyPrefix + ".DbRecoverFatal") != 0) - { - flags |= DB_RECOVER_FATAL | DB_CREATE; - } - else - { - flags |= DB_RECOVER | DB_CREATE; - } - - if(properties->getPropertyAsIntWithDefault(propertyPrefix + ".DbPrivate", 1) != 0) - { - flags |= DB_PRIVATE; - } - - /* - - // - // Does not seem to work reliably in 4.1.25 - // - - time_t timeStamp = properties->getPropertyAsIntWithDefault(propertyPrefix + ".TxTimestamp", 0); - - if(timeStamp != 0) - { - try - { - set_tx_timestamp(&timeStamp); - } - catch(const ::DbException& dx) - { - DatabaseException ex(__FILE__, __LINE__); - ex.message = dx.what(); - throw ex; - } - } - */ - - // - // Maybe we can deprecate this property since it can be set in the DB_CONFIG file - // - bool autoDelete = (properties->getPropertyAsIntWithDefault( - propertyPrefix + ".OldLogsAutoDelete", 1) != 0); - - if(autoDelete) - { - _env->set_flags(DB_LOG_AUTOREMOVE, 1); - } - - // - // Threading - // - flags |= DB_THREAD; - - string dbHome = properties->getPropertyWithDefault( - propertyPrefix + ".DbHome", envName); - - _env->open(dbHome.c_str(), flags, FREEZE_DB_MODE); - } - catch(const ::DbException& dx) - { - DatabaseException ex(__FILE__, __LINE__); - ex.message = dx.what(); - throw ex; - } - - // - // Default checkpoint period is every 120 seconds - // - Int checkpointPeriod = properties->getPropertyAsIntWithDefault( - propertyPrefix + ".CheckpointPeriod", 120); - Int kbyte = properties->getPropertyAsIntWithDefault(propertyPrefix + ".PeriodicCheckpointMinSize", 0); - - if(checkpointPeriod > 0) - { - _thread = new CheckpointThread(*this, Time::seconds(checkpointPeriod), kbyte, _trace); - } + + // + // Deadlock detection + // + _env->set_lk_detect(DB_LOCK_YOUNGEST); + + u_int32_t flags = DB_INIT_LOCK | DB_INIT_LOG | DB_INIT_MPOOL | DB_INIT_TXN; + + if(properties->getPropertyAsInt(propertyPrefix + ".DbRecoverFatal") != 0) + { + flags |= DB_RECOVER_FATAL | DB_CREATE; + } + else + { + flags |= DB_RECOVER | DB_CREATE; + } + + if(properties->getPropertyAsIntWithDefault(propertyPrefix + ".DbPrivate", 1) != 0) + { + flags |= DB_PRIVATE; + } + + /* + + // + // Does not seem to work reliably in 4.1.25 + // + + time_t timeStamp = properties->getPropertyAsIntWithDefault(propertyPrefix + ".TxTimestamp", 0); + + if(timeStamp != 0) + { + try + { + set_tx_timestamp(&timeStamp); + } + catch(const ::DbException& dx) + { + DatabaseException ex(__FILE__, __LINE__); + ex.message = dx.what(); + throw ex; + } + } + */ + + // + // Maybe we can deprecate this property since it can be set in the DB_CONFIG file + // + bool autoDelete = (properties->getPropertyAsIntWithDefault( + propertyPrefix + ".OldLogsAutoDelete", 1) != 0); + + if(autoDelete) + { + _env->set_flags(DB_LOG_AUTOREMOVE, 1); + } + + // + // Threading + // + flags |= DB_THREAD; + + string dbHome = properties->getPropertyWithDefault( + propertyPrefix + ".DbHome", envName); + + _env->open(dbHome.c_str(), flags, FREEZE_DB_MODE); + } + catch(const ::DbException& dx) + { + DatabaseException ex(__FILE__, __LINE__); + ex.message = dx.what(); + throw ex; + } + + // + // Default checkpoint period is every 120 seconds + // + Int checkpointPeriod = properties->getPropertyAsIntWithDefault( + propertyPrefix + ".CheckpointPeriod", 120); + Int kbyte = properties->getPropertyAsIntWithDefault(propertyPrefix + ".PeriodicCheckpointMinSize", 0); + + if(checkpointPeriod > 0) + { + _thread = new CheckpointThread(*this, Time::seconds(checkpointPeriod), kbyte, _trace); + } } // @@ -361,9 +361,9 @@ void Freeze::CheckpointThread::terminate() { { - Lock sync(*this); - _done = true; - notify(); + Lock sync(*this); + _done = true; + notify(); } getThreadControl().join(); @@ -375,33 +375,33 @@ Freeze::CheckpointThread::run() { for(;;) { - { - Lock sync(*this); - while(!_done && timedWait(_checkpointPeriod)) - { - // - // Loop - // - } - if(_done) - { - return; - } - } - - try - { - if(_trace >= 2) - { - Trace out(_dbEnv.getCommunicator()->getLogger(), "Freeze.DbEnv"); - out << "checkpointing environment \"" << _dbEnv.getEnvName() << "\""; - } - _dbEnv.getEnv()->txn_checkpoint(_kbyte, 0, 0); - } - catch(const DbException& dx) - { - Warning out(_dbEnv.getCommunicator()->getLogger()); - out << "checkpoint on DbEnv \"" << _dbEnv.getEnvName() << "\" raised DbException: " << dx.what(); - } + { + Lock sync(*this); + while(!_done && timedWait(_checkpointPeriod)) + { + // + // Loop + // + } + if(_done) + { + return; + } + } + + try + { + if(_trace >= 2) + { + Trace out(_dbEnv.getCommunicator()->getLogger(), "Freeze.DbEnv"); + out << "checkpointing environment \"" << _dbEnv.getEnvName() << "\""; + } + _dbEnv.getEnv()->txn_checkpoint(_kbyte, 0, 0); + } + catch(const DbException& dx) + { + Warning out(_dbEnv.getCommunicator()->getLogger()); + out << "checkpoint on DbEnv \"" << _dbEnv.getEnvName() << "\" raised DbException: " << dx.what(); + } } } diff --git a/cpp/src/Freeze/TransactionHolder.cpp b/cpp/src/Freeze/TransactionHolder.cpp index e10c402d10e..04d87729abb 100644 --- a/cpp/src/Freeze/TransactionHolder.cpp +++ b/cpp/src/Freeze/TransactionHolder.cpp @@ -16,7 +16,7 @@ Freeze::TransactionHolder::TransactionHolder(const ConnectionPtr& connection) { if(connection->currentTransaction() == 0) { - _transaction = connection->beginTransaction(); + _transaction = connection->beginTransaction(); } } @@ -24,13 +24,13 @@ Freeze::TransactionHolder::~TransactionHolder() { try { - rollback(); + rollback(); } catch(...) { - // - // Ignored to avoid crash during stack unwinding - // + // + // Ignored to avoid crash during stack unwinding + // } } @@ -39,16 +39,16 @@ Freeze::TransactionHolder::commit() { if(_transaction != 0) { - try - { - _transaction->commit(); - _transaction = 0; - } - catch(...) - { - _transaction = 0; - throw; - } + try + { + _transaction->commit(); + _transaction = 0; + } + catch(...) + { + _transaction = 0; + throw; + } } } @@ -57,15 +57,15 @@ Freeze::TransactionHolder::rollback() { if(_transaction != 0) { - try - { - _transaction->rollback(); - _transaction = 0; - } - catch(...) - { - _transaction = 0; - throw; - } + try + { + _transaction->rollback(); + _transaction = 0; + } + catch(...) + { + _transaction = 0; + throw; + } } } diff --git a/cpp/src/Freeze/TransactionI.cpp b/cpp/src/Freeze/TransactionI.cpp index ae8c4c7e2e4..c9920c7bfc0 100644 --- a/cpp/src/Freeze/TransactionI.cpp +++ b/cpp/src/Freeze/TransactionI.cpp @@ -30,46 +30,46 @@ Freeze::TransactionI::commit() long txnId = 0; try { - _connection->closeAllIterators(); + _connection->closeAllIterators(); - if(_txTrace >= 1) - { - txnId = (_txn->id() & 0x7FFFFFFF) + 0x80000000L; - } + if(_txTrace >= 1) + { + txnId = (_txn->id() & 0x7FFFFFFF) + 0x80000000L; + } - _txn->commit(0); + _txn->commit(0); - if(_txTrace >= 1) - { - Trace out(_connection->communicator()->getLogger(), "Freeze.Map"); - out << "committed transaction " << hex << txnId << dec; - } + if(_txTrace >= 1) + { + Trace out(_connection->communicator()->getLogger(), "Freeze.Map"); + out << "committed transaction " << hex << txnId << dec; + } } catch(const ::DbDeadlockException& dx) { - if(_txTrace >= 1) - { - Trace out(_connection->communicator()->getLogger(), "Freeze.Map"); - out << "failed to commit transaction " << hex << txnId << dec << ": " << dx.what(); - } - - cleanup(); - DeadlockException ex(__FILE__, __LINE__); - ex.message = dx.what(); - throw ex; + if(_txTrace >= 1) + { + Trace out(_connection->communicator()->getLogger(), "Freeze.Map"); + out << "failed to commit transaction " << hex << txnId << dec << ": " << dx.what(); + } + + cleanup(); + DeadlockException ex(__FILE__, __LINE__); + ex.message = dx.what(); + throw ex; } catch(const ::DbException& dx) { - if(_txTrace >= 1) - { - Trace out(_connection->communicator()->getLogger(), "Freeze.Map"); - out << "failed to commit transaction " << hex << txnId << dec << ": " << dx.what(); - } - - cleanup(); - DatabaseException ex(__FILE__, __LINE__); - ex.message = dx.what(); - throw ex; + if(_txTrace >= 1) + { + Trace out(_connection->communicator()->getLogger(), "Freeze.Map"); + out << "failed to commit transaction " << hex << txnId << dec << ": " << dx.what(); + } + + cleanup(); + DatabaseException ex(__FILE__, __LINE__); + ex.message = dx.what(); + throw ex; } cleanup(); } @@ -82,46 +82,46 @@ Freeze::TransactionI::rollback() long txnId = 0; try { - _connection->closeAllIterators(); + _connection->closeAllIterators(); - if(_txTrace >= 1) - { - txnId = (_txn->id() & 0x7FFFFFFF) + 0x80000000L; - } + if(_txTrace >= 1) + { + txnId = (_txn->id() & 0x7FFFFFFF) + 0x80000000L; + } - _txn->abort(); + _txn->abort(); - if(_txTrace >= 1) - { - Trace out(_connection->communicator()->getLogger(), "Freeze.Map"); - out << "rolled back transaction " << hex << txnId << dec; - } + if(_txTrace >= 1) + { + Trace out(_connection->communicator()->getLogger(), "Freeze.Map"); + out << "rolled back transaction " << hex << txnId << dec; + } } catch(const ::DbDeadlockException& dx) { - if(_txTrace >= 1) - { - Trace out(_connection->communicator()->getLogger(), "Freeze.Map"); - out << "failed to rollback transaction " << hex << txnId << dec << ": " << dx.what(); - } - - cleanup(); - DeadlockException ex(__FILE__, __LINE__); - ex.message = dx.what(); - throw ex; + if(_txTrace >= 1) + { + Trace out(_connection->communicator()->getLogger(), "Freeze.Map"); + out << "failed to rollback transaction " << hex << txnId << dec << ": " << dx.what(); + } + + cleanup(); + DeadlockException ex(__FILE__, __LINE__); + ex.message = dx.what(); + throw ex; } catch(const ::DbException& dx) { - if(_txTrace >= 1) - { - Trace out(_connection->communicator()->getLogger(), "Freeze.Map"); - out << "failed to rollback transaction " << hex << txnId << dec << ": " << dx.what(); - } - - cleanup(); - DatabaseException ex(__FILE__, __LINE__); - ex.message = dx.what(); - throw ex; + if(_txTrace >= 1) + { + Trace out(_connection->communicator()->getLogger(), "Freeze.Map"); + out << "failed to rollback transaction " << hex << txnId << dec << ": " << dx.what(); + } + + cleanup(); + DatabaseException ex(__FILE__, __LINE__); + ex.message = dx.what(); + throw ex; } cleanup(); } @@ -133,26 +133,26 @@ Freeze::TransactionI::TransactionI(ConnectionI* connection) : { try { - _connection->dbEnv()->getEnv()->txn_begin(0, &_txn, 0); - - if(_txTrace >= 1) - { - long txnId = (_txn->id() & 0x7FFFFFFF) + 0x80000000L; - Trace out(_connection->communicator()->getLogger(), "Freeze.Map"); - out << "started transaction " << hex << txnId << dec; - } + _connection->dbEnv()->getEnv()->txn_begin(0, &_txn, 0); + + if(_txTrace >= 1) + { + long txnId = (_txn->id() & 0x7FFFFFFF) + 0x80000000L; + Trace out(_connection->communicator()->getLogger(), "Freeze.Map"); + out << "started transaction " << hex << txnId << dec; + } } catch(const ::DbException& dx) { - if(_txTrace >= 1) - { - Trace out(_connection->communicator()->getLogger(), "Freeze.Map"); - out << "failed to start transaction: " << dx.what(); - } - - DatabaseException ex(__FILE__, __LINE__); - ex.message = dx.what(); - throw ex; + if(_txTrace >= 1) + { + Trace out(_connection->communicator()->getLogger(), "Freeze.Map"); + out << "failed to start transaction: " << dx.what(); + } + + DatabaseException ex(__FILE__, __LINE__); + ex.message = dx.what(); + throw ex; } } @@ -160,7 +160,7 @@ Freeze::TransactionI::~TransactionI() { if(_txn != 0) { - rollback(); + rollback(); } } diff --git a/cpp/src/Freeze/TransactionI.h b/cpp/src/Freeze/TransactionI.h index 275f8b429f4..72cfc852d16 100644 --- a/cpp/src/Freeze/TransactionI.h +++ b/cpp/src/Freeze/TransactionI.h @@ -36,7 +36,7 @@ public: DbTxn* dbTxn() const { - return _txn; + return _txn; } private: diff --git a/cpp/src/Freeze/Util.cpp b/cpp/src/Freeze/Util.cpp index c29f3845f9e..20782bfeca4 100644 --- a/cpp/src/Freeze/Util.cpp +++ b/cpp/src/Freeze/Util.cpp @@ -16,75 +16,75 @@ using namespace std; void Freeze::handleDbException(const DbException& dx, - const char* file, int line) + const char* file, int line) { throw DatabaseException(file, line, dx.what()); } void Freeze::handleDbException(const DbException& dx, - Key& key, Dbt& dbKey, - const char* file, int line) + Key& key, Dbt& dbKey, + const char* file, int line) { bool bufferSmallException = #if (DB_VERSION_MAJOR == 4) && (DB_VERSION_MINOR == 2) - (dx.get_errno() == ENOMEM); + (dx.get_errno() == ENOMEM); #else (dx.get_errno() == DB_BUFFER_SMALL || dx.get_errno() == ENOMEM); -#endif - +#endif + if(bufferSmallException && (dbKey.get_size() > dbKey.get_ulen())) { - // - // Keep the old key size in case it's used as input - // - size_t oldKeySize = key.size(); + // + // Keep the old key size in case it's used as input + // + size_t oldKeySize = key.size(); - key.resize(dbKey.get_size()); - initializeOutDbt(key, dbKey); - dbKey.set_size(static_cast(oldKeySize)); + key.resize(dbKey.get_size()); + initializeOutDbt(key, dbKey); + dbKey.set_size(static_cast(oldKeySize)); } else { - handleDbException(dx, file, line); + handleDbException(dx, file, line); } } void Freeze::handleDbException(const DbException& dx, - Key& key, Dbt& dbKey, - Value& value, Dbt& dbValue, - const char* file, int line) + Key& key, Dbt& dbKey, + Value& value, Dbt& dbValue, + const char* file, int line) { bool bufferSmallException = #if (DB_VERSION_MAJOR == 4) && (DB_VERSION_MINOR == 2) - (dx.get_errno() == ENOMEM); + (dx.get_errno() == ENOMEM); #else (dx.get_errno() == DB_BUFFER_SMALL || dx.get_errno() == ENOMEM); -#endif +#endif - bool resized = false; + bool resized = false; if(bufferSmallException) { - if(dbKey.get_size() > dbKey.get_ulen()) - { - size_t oldKeySize = key.size(); - key.resize(dbKey.get_size()); - initializeOutDbt(key, dbKey); - dbKey.set_size(static_cast(oldKeySize)); - resized = true; - } - - if(dbValue.get_size() > dbValue.get_ulen()) - { - value.resize(dbValue.get_size()); - initializeOutDbt(value, dbValue); - resized = true; - } + if(dbKey.get_size() > dbKey.get_ulen()) + { + size_t oldKeySize = key.size(); + key.resize(dbKey.get_size()); + initializeOutDbt(key, dbKey); + dbKey.set_size(static_cast(oldKeySize)); + resized = true; + } + + if(dbValue.get_size() > dbValue.get_ulen()) + { + value.resize(dbValue.get_size()); + initializeOutDbt(value, dbValue); + resized = true; + } } if(!resized) { - handleDbException(dx, file, line); + handleDbException(dx, file, line); } } diff --git a/cpp/src/Freeze/Util.h b/cpp/src/Freeze/Util.h index b41815f2c94..52582471517 100644 --- a/cpp/src/Freeze/Util.h +++ b/cpp/src/Freeze/Util.h @@ -61,11 +61,11 @@ handleDbException(const DbException&, const char*, int); void handleDbException(const DbException&, Key&, Dbt&, - const char*, int); + const char*, int); void handleDbException(const DbException&, Key&, Dbt&, Value&, Dbt&, - const char*, int); + const char*, int); } diff --git a/cpp/src/FreezeScript/Data.cpp b/cpp/src/FreezeScript/Data.cpp index 3c4050f03ee..cc51a8a2d0e 100644 --- a/cpp/src/FreezeScript/Data.cpp +++ b/cpp/src/FreezeScript/Data.cpp @@ -2494,28 +2494,28 @@ FreezeScript::ObjectFactory::create(const string& id) if(_factory) { - if(id == Ice::Object::ice_staticId()) - { - result = new ObjectReader(_factory, _unit->builtin(Slice::Builtin::KindObject)); - } - else - { - Slice::TypeList l = _unit->lookupTypeNoBuiltin(id); - if(!l.empty()) - { - Slice::ClassDeclPtr decl = Slice::ClassDeclPtr::dynamicCast(l.front()); - if(!decl) - { - _factory->getErrorReporter()->error("Slice definition for `" + id + "' is not a class"); - } - Slice::ClassDefPtr def = decl->definition(); - if(!def) - { - _factory->getErrorReporter()->error("no class definition for `" + id + "'"); - } - result = new ObjectReader(_factory, decl); - } - } + if(id == Ice::Object::ice_staticId()) + { + result = new ObjectReader(_factory, _unit->builtin(Slice::Builtin::KindObject)); + } + else + { + Slice::TypeList l = _unit->lookupTypeNoBuiltin(id); + if(!l.empty()) + { + Slice::ClassDeclPtr decl = Slice::ClassDeclPtr::dynamicCast(l.front()); + if(!decl) + { + _factory->getErrorReporter()->error("Slice definition for `" + id + "' is not a class"); + } + Slice::ClassDefPtr def = decl->definition(); + if(!def) + { + _factory->getErrorReporter()->error("no class definition for `" + id + "'"); + } + result = new ObjectReader(_factory, decl); + } + } } return result; diff --git a/cpp/src/FreezeScript/DumpDB.cpp b/cpp/src/FreezeScript/DumpDB.cpp index de79afd89a3..dc08bfcbda9 100644 --- a/cpp/src/FreezeScript/DumpDB.cpp +++ b/cpp/src/FreezeScript/DumpDB.cpp @@ -54,7 +54,7 @@ class DescriptorHandler : public IceXML::Handler public: DescriptorHandler(const DataFactoryPtr&, const Slice::UnitPtr&, const ErrorReporterPtr&, - const FreezeScript::ObjectFactoryPtr&); + const FreezeScript::ObjectFactoryPtr&); virtual void startElement(const std::string&, const IceXML::Attributes&, int, int); virtual void endElement(const std::string&, int, int); @@ -108,13 +108,13 @@ printCatalogData(const string& dbName, const Freeze::CatalogData& data) cout << dbName << ": "; if(data.evictor) { - cout << "Evictor database" << endl; + cout << "Evictor database" << endl; } else { - cout << "Map database" << endl; - cout << " key type = " << data.key << endl; - cout << " value type = " << data.value << endl; + cout << "Map database" << endl; + cout << " key type = " << data.key << endl; + cout << " value type = " << data.value << endl; } } @@ -159,98 +159,98 @@ run(int argc, char** argv, const Ice::CommunicatorPtr& communicator) } catch(const IceUtil::BadOptException& e) { - cerr << argv[0] << ": " << e.reason << endl; - usage(argv[0]); - return EXIT_FAILURE; + cerr << argv[0] << ": " << e.reason << endl; + usage(argv[0]); + return EXIT_FAILURE; } if(opts.isSet("h")) { - usage(argv[0]); - return EXIT_SUCCESS; + usage(argv[0]); + return EXIT_SUCCESS; } if(opts.isSet("version")) { - cout << ICE_STRING_VERSION << endl; - return EXIT_SUCCESS; + cout << ICE_STRING_VERSION << endl; + return EXIT_SUCCESS; } if(opts.isSet("c")) { - if(args.empty()) - { - cerr << argv[0] << ": no database environment specified." << endl; - usage(argv[0]); - return EXIT_FAILURE; - } - else if(args.size() > 2) - { - usage(argv[0]); - return EXIT_FAILURE; - } - try - { - FreezeScript::CatalogDataMap catalog = FreezeScript::readCatalog(communicator, args[0]); - if(args.size() == 1) - { - if(catalog.empty()) - { - cout << "Catalog is empty." << endl; - } - else - { - cout << "Catalog contents:" << endl; - for(FreezeScript::CatalogDataMap::const_iterator p = catalog.begin(); p != catalog.end(); ++p) - { - cout << endl; - printCatalogData(p->first, p->second); - } - } - } - else - { - FreezeScript::CatalogDataMap::const_iterator p = catalog.find(args[1]); - if(p == catalog.end()) - { - cerr << argv[0] << ": database `" << args[1] << "' not found in environment `" << args[0] << "'." - << endl; - return EXIT_FAILURE; - } - else - { - printCatalogData(p->first, p->second); - } - } - return EXIT_SUCCESS; - } - catch(const FreezeScript::FailureException& ex) - { - cerr << argv[0] << ": " << ex.reason() << endl; - return EXIT_FAILURE; - } + if(args.empty()) + { + cerr << argv[0] << ": no database environment specified." << endl; + usage(argv[0]); + return EXIT_FAILURE; + } + else if(args.size() > 2) + { + usage(argv[0]); + return EXIT_FAILURE; + } + try + { + FreezeScript::CatalogDataMap catalog = FreezeScript::readCatalog(communicator, args[0]); + if(args.size() == 1) + { + if(catalog.empty()) + { + cout << "Catalog is empty." << endl; + } + else + { + cout << "Catalog contents:" << endl; + for(FreezeScript::CatalogDataMap::const_iterator p = catalog.begin(); p != catalog.end(); ++p) + { + cout << endl; + printCatalogData(p->first, p->second); + } + } + } + else + { + FreezeScript::CatalogDataMap::const_iterator p = catalog.find(args[1]); + if(p == catalog.end()) + { + cerr << argv[0] << ": database `" << args[1] << "' not found in environment `" << args[0] << "'." + << endl; + return EXIT_FAILURE; + } + else + { + printCatalogData(p->first, p->second); + } + } + return EXIT_SUCCESS; + } + catch(const FreezeScript::FailureException& ex) + { + cerr << argv[0] << ": " << ex.reason() << endl; + return EXIT_FAILURE; + } } if(opts.isSet("D")) { - vector optargs = opts.argVec("D"); - for(vector::const_iterator i = optargs.begin(); i != optargs.end(); ++i) - { - cppArgs += " -D" + *i; - } + vector optargs = opts.argVec("D"); + for(vector::const_iterator i = optargs.begin(); i != optargs.end(); ++i) + { + cppArgs += " -D" + *i; + } } if(opts.isSet("U")) { - vector optargs = opts.argVec("U"); - for(vector::const_iterator i = optargs.begin(); i != optargs.end(); ++i) - { - cppArgs += " -U" + *i; - } + vector optargs = opts.argVec("U"); + for(vector::const_iterator i = optargs.begin(); i != optargs.end(); ++i) + { + cppArgs += " -U" + *i; + } } if(opts.isSet("I")) { - vector optargs = opts.argVec("I"); - for(vector::const_iterator i = optargs.begin(); i != optargs.end(); ++i) - { - cppArgs += " -I" + *i; - } + vector optargs = opts.argVec("I"); + for(vector::const_iterator i = optargs.begin(); i != optargs.end(); ++i) + { + cppArgs += " -I" + *i; + } } debug = opts.isSet("debug"); @@ -258,32 +258,32 @@ run(int argc, char** argv, const Ice::CommunicatorPtr& communicator) if(opts.isSet("o")) { - outputFile = opts.optArg("o"); + outputFile = opts.optArg("o"); } if(opts.isSet("f")) { - inputFile = opts.optArg("f"); + inputFile = opts.optArg("f"); } if(opts.isSet("load")) { vector optArgs = opts.argVec("load"); - for(vector::const_iterator i = optArgs.begin(); i != optArgs.end(); ++i) - { - slice.push_back(*i); - } + for(vector::const_iterator i = optArgs.begin(); i != optArgs.end(); ++i) + { + slice.push_back(*i); + } } evictor = opts.isSet("e"); if(opts.isSet("key")) { - keyTypeName = opts.optArg("key"); + keyTypeName = opts.optArg("key"); } if(opts.isSet("value")) { - valueTypeName = opts.optArg("value"); + valueTypeName = opts.optArg("value"); } if(opts.isSet("select")) { - selectExpr = opts.optArg("select"); + selectExpr = opts.optArg("select"); } caseSensitive = opts.isSet("case-sensitive"); @@ -328,55 +328,55 @@ run(int argc, char** argv, const Ice::CommunicatorPtr& communicator) string descriptors; if(inputFile.empty()) { - const string evictorKeyTypeName = "::Ice::Identity"; - const string evictorValueTypeName = "::Freeze::ObjectRecord"; - - if((!keyTypeName.empty() && valueTypeName.empty()) || (keyTypeName.empty() && !valueTypeName.empty())) - { - cerr << argv[0] << ": a key type and a value type must be specified" << endl; - usage(argv[0]); - return EXIT_FAILURE; - } - else if(!evictor && keyTypeName.empty() && valueTypeName.empty()) - { - try - { - FreezeScript::CatalogDataMap catalog = FreezeScript::readCatalog(communicator, dbEnvName); - FreezeScript::CatalogDataMap::iterator p = catalog.find(dbName); - if(p == catalog.end()) - { - cerr << argv[0] << ": database `" << dbName << "' not found in catalog." << endl; - cerr << "Current catalog databases:" << endl; - for(p = catalog.begin(); p != catalog.end(); ++p) - { - cerr << " " << p->first << endl; - } - return EXIT_FAILURE; - } - else - { - if(p->second.evictor) - { - evictor = true; - } - else - { - keyTypeName = p->second.key; - valueTypeName = p->second.value; - } - } - } - catch(const FreezeScript::FailureException& ex) - { - cerr << argv[0] << ": " << ex.reason() << endl; - return EXIT_FAILURE; - } - } + const string evictorKeyTypeName = "::Ice::Identity"; + const string evictorValueTypeName = "::Freeze::ObjectRecord"; + + if((!keyTypeName.empty() && valueTypeName.empty()) || (keyTypeName.empty() && !valueTypeName.empty())) + { + cerr << argv[0] << ": a key type and a value type must be specified" << endl; + usage(argv[0]); + return EXIT_FAILURE; + } + else if(!evictor && keyTypeName.empty() && valueTypeName.empty()) + { + try + { + FreezeScript::CatalogDataMap catalog = FreezeScript::readCatalog(communicator, dbEnvName); + FreezeScript::CatalogDataMap::iterator p = catalog.find(dbName); + if(p == catalog.end()) + { + cerr << argv[0] << ": database `" << dbName << "' not found in catalog." << endl; + cerr << "Current catalog databases:" << endl; + for(p = catalog.begin(); p != catalog.end(); ++p) + { + cerr << " " << p->first << endl; + } + return EXIT_FAILURE; + } + else + { + if(p->second.evictor) + { + evictor = true; + } + else + { + keyTypeName = p->second.key; + valueTypeName = p->second.value; + } + } + } + catch(const FreezeScript::FailureException& ex) + { + cerr << argv[0] << ": " << ex.reason() << endl; + return EXIT_FAILURE; + } + } if(evictor) { - keyTypeName = evictorKeyTypeName; - valueTypeName = evictorValueTypeName; + keyTypeName = evictorKeyTypeName; + valueTypeName = evictorValueTypeName; } Slice::TypePtr keyType, valueType; @@ -744,7 +744,7 @@ FreezeScript::SliceVisitor::visitEnum(const Slice::EnumPtr& v) // FreezeScript::DescriptorHandler::DescriptorHandler(const DataFactoryPtr& factory, const Slice::UnitPtr& unit, const ErrorReporterPtr& errorReporter, - const FreezeScript::ObjectFactoryPtr& objectFactory) : + const FreezeScript::ObjectFactoryPtr& objectFactory) : _factory(factory), _unit(unit), _errorReporter(errorReporter), _objectFactory(objectFactory) { } diff --git a/cpp/src/FreezeScript/DumpDescriptors.cpp b/cpp/src/FreezeScript/DumpDescriptors.cpp index fb947a16e47..8b2a15300cc 100644 --- a/cpp/src/FreezeScript/DumpDescriptors.cpp +++ b/cpp/src/FreezeScript/DumpDescriptors.cpp @@ -1239,7 +1239,7 @@ FreezeScript::RecordDescriptor::RecordDescriptor(const DescriptorPtr& parent, in const ErrorReporterPtr& errorReporter, const IceXML::Attributes& attributes, const Slice::UnitPtr& unit, - const FreezeScript::ObjectFactoryPtr& objectFactory) : + const FreezeScript::ObjectFactoryPtr& objectFactory) : Descriptor(parent, line, factory, errorReporter), ExecutableContainerDescriptor(parent, line, factory, errorReporter, attributes, "record"), _unit(unit), @@ -1322,7 +1322,7 @@ FreezeScript::RecordDescriptor::execute(const SymbolTablePtr& sym, ExecuteInfo* { dbc->close(); } - _objectFactory->deactivate(); + _objectFactory->deactivate(); throw; } @@ -1870,16 +1870,16 @@ FreezeScript::DumpVisitor::visitObject(const ObjectRefPtr& data) ObjectDataPtr value = data->getValue(); if(value) { - set::iterator p = _objectHistory.find(value.get()); - if(p == _objectHistory.end()) - { - _objectHistory.insert(value.get()); - DataMemberMap& members = value->getMembers(); - for(DataMemberMap::iterator q = members.begin(); q != members.end(); ++q) - { - q->second->visit(*this); - } - } + set::iterator p = _objectHistory.find(value.get()); + if(p == _objectHistory.end()) + { + _objectHistory.insert(value.get()); + DataMemberMap& members = value->getMembers(); + for(DataMemberMap::iterator q = members.begin(); q != members.end(); ++q) + { + q->second->visit(*this); + } + } } } } diff --git a/cpp/src/FreezeScript/DumpDescriptors.h b/cpp/src/FreezeScript/DumpDescriptors.h index 4f8daf65b9c..f915c08ba1f 100644 --- a/cpp/src/FreezeScript/DumpDescriptors.h +++ b/cpp/src/FreezeScript/DumpDescriptors.h @@ -247,7 +247,7 @@ public: RecordDescriptor(const DescriptorPtr&, int, const DataFactoryPtr&, const ErrorReporterPtr&, const IceXML::Attributes&, const Slice::UnitPtr&, - const FreezeScript::ObjectFactoryPtr&); + const FreezeScript::ObjectFactoryPtr&); virtual void execute(const SymbolTablePtr&, ExecuteInfo*); diff --git a/cpp/src/FreezeScript/Functions.cpp b/cpp/src/FreezeScript/Functions.cpp index b96f237b3d0..4f38c91f935 100644 --- a/cpp/src/FreezeScript/Functions.cpp +++ b/cpp/src/FreezeScript/Functions.cpp @@ -15,8 +15,8 @@ using namespace std; bool FreezeScript::invokeGlobalFunction(const Ice::CommunicatorPtr& communicator, const string& name, const DataList& args, - DataPtr& result, const DataFactoryPtr& factory, - const ErrorReporterPtr& errorReporter) + DataPtr& result, const DataFactoryPtr& factory, + const ErrorReporterPtr& errorReporter) { // // Global function. diff --git a/cpp/src/FreezeScript/Functions.h b/cpp/src/FreezeScript/Functions.h index b0a4b5eb441..0b5fff2b21b 100644 --- a/cpp/src/FreezeScript/Functions.h +++ b/cpp/src/FreezeScript/Functions.h @@ -16,7 +16,7 @@ namespace FreezeScript { bool invokeGlobalFunction(const Ice::CommunicatorPtr&, const std::string&, const DataList&, DataPtr&, - const DataFactoryPtr&, const ErrorReporterPtr&); + const DataFactoryPtr&, const ErrorReporterPtr&); bool invokeMemberFunction(const std::string&, const DataPtr&, const DataList&, DataPtr&, const DataFactoryPtr&, const ErrorReporterPtr&); diff --git a/cpp/src/FreezeScript/TransformAnalyzer.cpp b/cpp/src/FreezeScript/TransformAnalyzer.cpp index fc9f6be8b66..4095b87007c 100644 --- a/cpp/src/FreezeScript/TransformAnalyzer.cpp +++ b/cpp/src/FreezeScript/TransformAnalyzer.cpp @@ -90,46 +90,46 @@ FreezeScript::AnalyzeTransformVisitor::AnalyzeTransformVisitor(XMLOutput& out, c void FreezeScript::AnalyzeTransformVisitor::addDatabase(const string& name, const TypePtr& oldKey, const TypePtr& newKey, - const TypePtr& oldValue, const TypePtr& newValue) + const TypePtr& oldValue, const TypePtr& newValue) { _out << "\n"; _out << se("database"); if(!name.empty()) { - _out << attr("name", name); + _out << attr("name", name); } string oldKeyName = oldKey ? typeToString(oldKey) : string("UNKNOWN"); string newKeyName = newKey ? typeToString(newKey) : string("UNKNOWN"); if(oldKeyName == newKeyName) { - _out << attr("key", oldKeyName); + _out << attr("key", oldKeyName); } else { - _out << attr("key", oldKeyName + "," + newKeyName); + _out << attr("key", oldKeyName + "," + newKeyName); } string oldValueName = oldValue ? typeToString(oldValue) : string("UNKNOWN"); string newValueName = newValue ? typeToString(newValue) : string("UNKNOWN"); if(oldValueName == newValueName) { - _out << attr("value", oldValueName); + _out << attr("value", oldValueName); } else { - _out << attr("value", oldValueName + "," + newValueName); + _out << attr("value", oldValueName + "," + newValueName); } _out << se("record"); if(oldKey && newKey) { - compareTypes("database key", oldKey, newKey); + compareTypes("database key", oldKey, newKey); } if(oldValue && newValue) { - compareTypes("database value", oldValue, newValue); + compareTypes("database value", oldValue, newValue); } _out << ee; @@ -1130,7 +1130,7 @@ FreezeScript::AnalyzeInitVisitor::typeChange(const TypePtr& t, const string& sco FreezeScript::TransformAnalyzer::TransformAnalyzer(const UnitPtr& oldUnit, const UnitPtr& newUnit, bool ignoreTypeChanges, ostream& os, vector& missingTypes, - vector& errors) : + vector& errors) : _old(oldUnit), _new(newUnit), _out(os), _visitor(new AnalyzeTransformVisitor(_out, newUnit, ignoreTypeChanges, missingTypes, errors)) { @@ -1144,7 +1144,7 @@ FreezeScript::TransformAnalyzer::~TransformAnalyzer() void FreezeScript::TransformAnalyzer::addDatabase(const string& name, const TypePtr& oldKey, const TypePtr& newKey, - const TypePtr& oldValue, const TypePtr& newValue) + const TypePtr& oldValue, const TypePtr& newValue) { _visitor->addDatabase(name, oldKey, newKey, oldValue, newValue); } diff --git a/cpp/src/FreezeScript/TransformAnalyzer.h b/cpp/src/FreezeScript/TransformAnalyzer.h index 9af9c06126a..73539de5d67 100644 --- a/cpp/src/FreezeScript/TransformAnalyzer.h +++ b/cpp/src/FreezeScript/TransformAnalyzer.h @@ -24,11 +24,11 @@ class TransformAnalyzer public: TransformAnalyzer(const Slice::UnitPtr&, const Slice::UnitPtr&, bool, std::ostream&, std::vector&, - std::vector&); + std::vector&); ~TransformAnalyzer(); void addDatabase(const std::string&, const Slice::TypePtr&, const Slice::TypePtr&, const Slice::TypePtr&, - const Slice::TypePtr&); + const Slice::TypePtr&); void finish(); private: diff --git a/cpp/src/FreezeScript/Transformer.cpp b/cpp/src/FreezeScript/Transformer.cpp index 5b6926c75cd..148d3867f68 100644 --- a/cpp/src/FreezeScript/Transformer.cpp +++ b/cpp/src/FreezeScript/Transformer.cpp @@ -1911,7 +1911,7 @@ FreezeScript::RecordDescriptor::execute(const SymbolTablePtr& sym) Ice::ByteSeq outKeyBytes, outValueBytes; transformRecord(inKeyBytes, inValueBytes, outKeyBytes, outValueBytes); Dbt dbNewKey(&outKeyBytes[0], static_cast(outKeyBytes.size())), - dbNewValue(&outValueBytes[0], static_cast(outValueBytes.size())); + dbNewValue(&outValueBytes[0], static_cast(outValueBytes.size())); if(_info->newDb->put(_info->newDbTxn, &dbNewKey, &dbNewValue, DB_NOOVERWRITE) == DB_KEYEXIST) { _info->errorReporter->error("duplicate key encountered"); @@ -1941,7 +1941,7 @@ FreezeScript::RecordDescriptor::execute(const SymbolTablePtr& sym) { dbc->close(); } - _info->objectFactory->deactivate(); + _info->objectFactory->deactivate(); throw; } @@ -2051,7 +2051,7 @@ FreezeScript::DatabaseDescriptor::DatabaseDescriptor(const DescriptorPtr& parent p = attributes.find("name"); if(p != attributes.end()) { - _name = p->second; + _name = p->second; } p = attributes.find("key"); @@ -2077,13 +2077,13 @@ FreezeScript::DatabaseDescriptor::DatabaseDescriptor(const DescriptorPtr& parent } if(pos == string::npos) { - _oldKeyName = keyTypes; - _newKeyName = keyTypes; + _oldKeyName = keyTypes; + _newKeyName = keyTypes; } else { - _oldKeyName = keyTypes.substr(0, pos); - _newKeyName = keyTypes.substr(pos + 1); + _oldKeyName = keyTypes.substr(0, pos); + _newKeyName = keyTypes.substr(pos + 1); } pos = valueTypes.find(','); @@ -2093,13 +2093,13 @@ FreezeScript::DatabaseDescriptor::DatabaseDescriptor(const DescriptorPtr& parent } if(pos == string::npos) { - _oldValueName = valueTypes; - _newValueName = valueTypes; + _oldValueName = valueTypes; + _newValueName = valueTypes; } else { - _oldValueName = valueTypes.substr(0, pos); - _newValueName = valueTypes.substr(pos + 1); + _oldValueName = valueTypes.substr(0, pos); + _newValueName = valueTypes.substr(pos + 1); } } @@ -2136,12 +2136,12 @@ FreezeScript::DatabaseDescriptor::execute(const SymbolTablePtr& st) if(_info->connection != 0) { - Freeze::Catalog catalog(_info->connection, Freeze::catalogName()); - Freeze::CatalogData catalogData; - catalogData.evictor = false; - catalogData.key = _info->newKeyType->typeId(); - catalogData.value = _info->newValueType->typeId(); - catalog.put(Freeze::Catalog::value_type(_info->newDbName, catalogData)); + Freeze::Catalog catalog(_info->connection, Freeze::catalogName()); + Freeze::CatalogData catalogData; + catalogData.evictor = false; + catalogData.key = _info->newKeyType->typeId(); + catalogData.value = _info->newValueType->typeId(); + catalog.put(Freeze::Catalog::value_type(_info->newDbName, catalogData)); } // @@ -2182,24 +2182,24 @@ FreezeScript::TransformDBDescriptor::addChild(const DescriptorPtr& child) if(db) { - string name = db->name(); - map::iterator p = _databases.find(name); - if(p != _databases.end()) - { - if(name.empty()) - { - _info->errorReporter->error("duplicate element"); - } - else - { - _info->errorReporter->error(string("duplicate element for ") + name); - } - } - else - { - _databases[name] = db; - _children.push_back(db); - } + string name = db->name(); + map::iterator p = _databases.find(name); + if(p != _databases.end()) + { + if(name.empty()) + { + _info->errorReporter->error("duplicate element"); + } + else + { + _info->errorReporter->error(string("duplicate element for ") + name); + } + } + else + { + _databases[name] = db; + _children.push_back(db); + } } else if(transform) { @@ -2243,7 +2243,7 @@ FreezeScript::TransformDBDescriptor::validate() if(_databases.empty()) { - _info->errorReporter->error("no element defined"); + _info->errorReporter->error("no element defined"); } for(vector::iterator p = _children.begin(); p != _children.end(); ++p) @@ -2258,12 +2258,12 @@ FreezeScript::TransformDBDescriptor::execute(const SymbolTablePtr& sym) map::iterator p = _databases.find(_info->newDbName); if(p == _databases.end()) { - p = _databases.find(""); + p = _databases.find(""); } if(p == _databases.end()) { - _info->errorReporter->error("no element found for `" + _info->newDbName + "'"); + _info->errorReporter->error("no element found for `" + _info->newDbName + "'"); } p->second->execute(sym); @@ -3000,11 +3000,11 @@ FreezeScript::assignOrTransform(const DataPtr& dest, const DataPtr& src, bool co void FreezeScript::transformDatabase(const Ice::CommunicatorPtr& communicator, - const FreezeScript::ObjectFactoryPtr& objectFactory, + const FreezeScript::ObjectFactoryPtr& objectFactory, const Slice::UnitPtr& oldUnit, const Slice::UnitPtr& newUnit, Db* oldDb, Db* newDb, DbTxn* newDbTxn, const Freeze::ConnectionPtr& connection, - const string& newDbName, const string& facetName, bool purgeObjects, ostream& errors, - bool suppress, istream& is) + const string& newDbName, const string& facetName, bool purgeObjects, ostream& errors, + bool suppress, istream& is) { TransformInfoIPtr info = new TransformInfoI; diff --git a/cpp/src/FreezeScript/Transformer.h b/cpp/src/FreezeScript/Transformer.h index 3afc6b507f8..5f856507d78 100644 --- a/cpp/src/FreezeScript/Transformer.h +++ b/cpp/src/FreezeScript/Transformer.h @@ -23,10 +23,10 @@ namespace FreezeScript void transformDatabase(const Ice::CommunicatorPtr&, - const FreezeScript::ObjectFactoryPtr& objectFactory, - const Slice::UnitPtr&, const Slice::UnitPtr&, + const FreezeScript::ObjectFactoryPtr& objectFactory, + const Slice::UnitPtr&, const Slice::UnitPtr&, Db*, Db*, DbTxn*, const Freeze::ConnectionPtr&, const std::string&, const std::string&, bool, - std::ostream&, bool, std::istream&); + std::ostream&, bool, std::istream&); } // End of namespace FreezeScript diff --git a/cpp/src/FreezeScript/Util.cpp b/cpp/src/FreezeScript/Util.cpp index 49585d72520..b8f5c17cfc8 100644 --- a/cpp/src/FreezeScript/Util.cpp +++ b/cpp/src/FreezeScript/Util.cpp @@ -218,36 +218,36 @@ FreezeScript::readCatalog(const Ice::CommunicatorPtr& communicator, const string try { #ifdef _WIN32 - // - // Berkeley DB may use a different C++ runtime. - // - dbEnv.set_alloc(::malloc, ::realloc, ::free); + // + // Berkeley DB may use a different C++ runtime. + // + dbEnv.set_alloc(::malloc, ::realloc, ::free); #endif - // - // Open the database environment. - // - { - u_int32_t flags = DB_INIT_LOG | DB_INIT_MPOOL | DB_INIT_TXN | DB_CREATE | DB_THREAD | DB_RECOVER; - dbEnv.open(dbEnvName.c_str(), flags, mode); - } + // + // Open the database environment. + // + { + u_int32_t flags = DB_INIT_LOG | DB_INIT_MPOOL | DB_INIT_TXN | DB_CREATE | DB_THREAD | DB_RECOVER; + dbEnv.open(dbEnvName.c_str(), flags, mode); + } - Freeze::ConnectionPtr connection = Freeze::createConnection(communicator, dbEnvName, dbEnv); - Freeze::Catalog catalog(connection, Freeze::catalogName()); - for(Freeze::Catalog::const_iterator p = catalog.begin(); p != catalog.end(); ++p) - { - result.insert(make_pair(p->first, p->second)); - } + Freeze::ConnectionPtr connection = Freeze::createConnection(communicator, dbEnvName, dbEnv); + Freeze::Catalog catalog(connection, Freeze::catalogName()); + for(Freeze::Catalog::const_iterator p = catalog.begin(); p != catalog.end(); ++p) + { + result.insert(make_pair(p->first, p->second)); + } } catch(const DbException& ex) { - dbEnv.close(0); - throw FailureException(__FILE__, __LINE__, string("database error: ") + ex.what()); + dbEnv.close(0); + throw FailureException(__FILE__, __LINE__, string("database error: ") + ex.what()); } catch(...) { - dbEnv.close(0); - throw FailureException(__FILE__, __LINE__, "unknown exception"); + dbEnv.close(0); + throw FailureException(__FILE__, __LINE__, "unknown exception"); } dbEnv.close(0); diff --git a/cpp/src/FreezeScript/transformdb.cpp b/cpp/src/FreezeScript/transformdb.cpp index 8f17b6e8d37..b3a5a6adec4 100644 --- a/cpp/src/FreezeScript/transformdb.cpp +++ b/cpp/src/FreezeScript/transformdb.cpp @@ -96,21 +96,21 @@ findType(const Slice::UnitPtr& u, const string& type) string t; if(type == "::Ice::Object") { - t = "Object"; + t = "Object"; } else if(type == "::Ice::Object*") { - t = "Object*"; + t = "Object*"; } else { - t = type; + t = type; } l = u->lookupType(t, false); if(l.empty()) { - return 0; + return 0; } return l.front(); @@ -118,97 +118,97 @@ findType(const Slice::UnitPtr& u, const string& type) static void transformDb(bool evictor, const Ice::CommunicatorPtr& communicator, - const FreezeScript::ObjectFactoryPtr& objectFactory, - DbEnv& dbEnv, DbEnv& dbEnvNew, const string& dbName, - const Freeze::ConnectionPtr& connectionNew, vector& dbs, - const Slice::UnitPtr& oldUnit, const Slice::UnitPtr& newUnit, - DbTxn* txnNew, bool purgeObjects, bool suppress, string descriptors) + const FreezeScript::ObjectFactoryPtr& objectFactory, + DbEnv& dbEnv, DbEnv& dbEnvNew, const string& dbName, + const Freeze::ConnectionPtr& connectionNew, vector& dbs, + const Slice::UnitPtr& oldUnit, const Slice::UnitPtr& newUnit, + DbTxn* txnNew, bool purgeObjects, bool suppress, string descriptors) { if(evictor) { - // - // The evictor database file contains multiple databases. We must first - // determine the names of those databases, ignoring any whose names - // begin with "$index:". Each database represents a separate facet, with - // the facet name used as the database name. The database named "$default" - // represents the main object. - // - vector dbNames; - { - Db db(&dbEnv, 0); - db.open(0, dbName.c_str(), 0, DB_UNKNOWN, DB_RDONLY, 0); - Dbt dbKey, dbValue; - dbKey.set_flags(DB_DBT_MALLOC); - dbValue.set_flags(DB_DBT_USERMEM | DB_DBT_PARTIAL); - - Dbc* dbc = 0; - db.cursor(0, &dbc, 0); - - while(dbc->get(&dbKey, &dbValue, DB_NEXT) == 0) - { - string s(static_cast(dbKey.get_data()), dbKey.get_size()); - if(s.find("$index:") != 0) - { - dbNames.push_back(s); - } - free(dbKey.get_data()); - } - - dbc->close(); - db.close(0); - } - - // - // Transform each database. We must delay closing the new databases - // until after the transaction is committed or aborted. - // - for(vector::iterator p = dbNames.begin(); p != dbNames.end(); ++p) - { - string name = p->c_str(); - - Db db(&dbEnv, 0); - db.open(0, dbName.c_str(), name.c_str(), DB_BTREE, DB_RDONLY, FREEZE_SCRIPT_DB_MODE); - - Db* dbNew = new Db(&dbEnvNew, 0); - dbs.push_back(dbNew); - dbNew->open(txnNew, dbName.c_str(), name.c_str(), DB_BTREE, DB_CREATE | DB_EXCL, FREEZE_SCRIPT_DB_MODE); - - // - // Execute the transformation descriptors. - // - istringstream istr(descriptors); - string facet = (name == "$default" ? string("") : name); - FreezeScript::transformDatabase(communicator, objectFactory, oldUnit, newUnit, &db, dbNew, txnNew, 0, - dbName, facet, purgeObjects, cerr, suppress, istr); - - db.close(0); - } - - Freeze::Catalog catalogNew(connectionNew, Freeze::catalogName()); - Freeze::CatalogData catalogData; - catalogData.evictor = true; - catalogNew.put(Freeze::Catalog::value_type(dbName, catalogData)); + // + // The evictor database file contains multiple databases. We must first + // determine the names of those databases, ignoring any whose names + // begin with "$index:". Each database represents a separate facet, with + // the facet name used as the database name. The database named "$default" + // represents the main object. + // + vector dbNames; + { + Db db(&dbEnv, 0); + db.open(0, dbName.c_str(), 0, DB_UNKNOWN, DB_RDONLY, 0); + Dbt dbKey, dbValue; + dbKey.set_flags(DB_DBT_MALLOC); + dbValue.set_flags(DB_DBT_USERMEM | DB_DBT_PARTIAL); + + Dbc* dbc = 0; + db.cursor(0, &dbc, 0); + + while(dbc->get(&dbKey, &dbValue, DB_NEXT) == 0) + { + string s(static_cast(dbKey.get_data()), dbKey.get_size()); + if(s.find("$index:") != 0) + { + dbNames.push_back(s); + } + free(dbKey.get_data()); + } + + dbc->close(); + db.close(0); + } + + // + // Transform each database. We must delay closing the new databases + // until after the transaction is committed or aborted. + // + for(vector::iterator p = dbNames.begin(); p != dbNames.end(); ++p) + { + string name = p->c_str(); + + Db db(&dbEnv, 0); + db.open(0, dbName.c_str(), name.c_str(), DB_BTREE, DB_RDONLY, FREEZE_SCRIPT_DB_MODE); + + Db* dbNew = new Db(&dbEnvNew, 0); + dbs.push_back(dbNew); + dbNew->open(txnNew, dbName.c_str(), name.c_str(), DB_BTREE, DB_CREATE | DB_EXCL, FREEZE_SCRIPT_DB_MODE); + + // + // Execute the transformation descriptors. + // + istringstream istr(descriptors); + string facet = (name == "$default" ? string("") : name); + FreezeScript::transformDatabase(communicator, objectFactory, oldUnit, newUnit, &db, dbNew, txnNew, 0, + dbName, facet, purgeObjects, cerr, suppress, istr); + + db.close(0); + } + + Freeze::Catalog catalogNew(connectionNew, Freeze::catalogName()); + Freeze::CatalogData catalogData; + catalogData.evictor = true; + catalogNew.put(Freeze::Catalog::value_type(dbName, catalogData)); } else { - // - // Transform a map database. - // - Db db(&dbEnv, 0); - db.open(0, dbName.c_str(), 0, DB_BTREE, DB_RDONLY, FREEZE_SCRIPT_DB_MODE); - - Db* dbNew = new Db(&dbEnvNew, 0); - dbs.push_back(dbNew); - dbNew->open(txnNew, dbName.c_str(), 0, DB_BTREE, DB_CREATE | DB_EXCL, FREEZE_SCRIPT_DB_MODE); - - // - // Execute the transformation descriptors. - // - istringstream istr(descriptors); - FreezeScript::transformDatabase(communicator, objectFactory, oldUnit, newUnit, &db, dbNew, txnNew, - connectionNew, dbName, "", purgeObjects, cerr, suppress, istr); - - db.close(0); + // + // Transform a map database. + // + Db db(&dbEnv, 0); + db.open(0, dbName.c_str(), 0, DB_BTREE, DB_RDONLY, FREEZE_SCRIPT_DB_MODE); + + Db* dbNew = new Db(&dbEnvNew, 0); + dbs.push_back(dbNew); + dbNew->open(txnNew, dbName.c_str(), 0, DB_BTREE, DB_CREATE | DB_EXCL, FREEZE_SCRIPT_DB_MODE); + + // + // Execute the transformation descriptors. + // + istringstream istr(descriptors); + FreezeScript::transformDatabase(communicator, objectFactory, oldUnit, newUnit, &db, dbNew, txnNew, + connectionNew, dbName, "", purgeObjects, cerr, suppress, istr); + + db.close(0); } } @@ -263,44 +263,44 @@ run(int argc, char** argv, const Ice::CommunicatorPtr& communicator) } catch(const IceUtil::BadOptException& e) { - cerr << argv[0] << ": " << e.reason << endl; - usage(argv[0]); - return EXIT_FAILURE; + cerr << argv[0] << ": " << e.reason << endl; + usage(argv[0]); + return EXIT_FAILURE; } if(opts.isSet("help")) { - usage(argv[0]); - return EXIT_SUCCESS; + usage(argv[0]); + return EXIT_SUCCESS; } if(opts.isSet("version")) { - cout << ICE_STRING_VERSION << endl; - return EXIT_SUCCESS; + cout << ICE_STRING_VERSION << endl; + return EXIT_SUCCESS; } if(opts.isSet("D")) { - vector optargs = opts.argVec("D"); - for(vector::const_iterator i = optargs.begin(); i != optargs.end(); ++i) - { - oldCppArgs += " -D" + *i; - newCppArgs += " -D" + *i; - } + vector optargs = opts.argVec("D"); + for(vector::const_iterator i = optargs.begin(); i != optargs.end(); ++i) + { + oldCppArgs += " -D" + *i; + newCppArgs += " -D" + *i; + } } if(opts.isSet("U")) { - vector optargs = opts.argVec("U"); - for(vector::const_iterator i = optargs.begin(); i != optargs.end(); ++i) - { - oldCppArgs += " -U" + *i; - newCppArgs += " -U" + *i; - } + vector optargs = opts.argVec("U"); + for(vector::const_iterator i = optargs.begin(); i != optargs.end(); ++i) + { + oldCppArgs += " -U" + *i; + newCppArgs += " -U" + *i; + } } debug = opts.isSet("debug"); if(opts.isSet("o")) { - outputFile = opts.optArg("o"); + outputFile = opts.optArg("o"); } ignoreTypeChanges = opts.isSet("i"); purgeObjects = opts.isSet("p"); @@ -308,102 +308,102 @@ run(int argc, char** argv, const Ice::CommunicatorPtr& communicator) suppress = opts.isSet("w"); if(opts.isSet("f")) { - inputFile = opts.optArg("f"); + inputFile = opts.optArg("f"); } if(opts.isSet("include-old")) { - vector optargs = opts.argVec("include-old"); - for(vector::const_iterator i = optargs.begin(); i != optargs.end(); ++i) - { - oldCppArgs += " -I" + *i; - } + vector optargs = opts.argVec("include-old"); + for(vector::const_iterator i = optargs.begin(); i != optargs.end(); ++i) + { + oldCppArgs += " -I" + *i; + } } if(opts.isSet("include-new")) { - vector optargs = opts.argVec("include-new"); - for(vector::const_iterator i = optargs.begin(); i != optargs.end(); ++i) - { - newCppArgs += " -I" + *i; - } + vector optargs = opts.argVec("include-new"); + for(vector::const_iterator i = optargs.begin(); i != optargs.end(); ++i) + { + newCppArgs += " -I" + *i; + } } if(opts.isSet("old")) { - vector optargs = opts.argVec("old"); - for(vector::const_iterator i = optargs.begin(); i != optargs.end(); ++i) - { - oldSlice.push_back(*i); - } + vector optargs = opts.argVec("old"); + for(vector::const_iterator i = optargs.begin(); i != optargs.end(); ++i) + { + oldSlice.push_back(*i); + } } if(opts.isSet("new")) { - vector optargs = opts.argVec("new"); - for(vector::const_iterator i = optargs.begin(); i != optargs.end(); ++i) - { - newSlice.push_back(*i); - } + vector optargs = opts.argVec("new"); + for(vector::const_iterator i = optargs.begin(); i != optargs.end(); ++i) + { + newSlice.push_back(*i); + } } evictor = opts.isSet("e"); if(opts.isSet("key")) { - keyTypeNames = opts.optArg("key"); + keyTypeNames = opts.optArg("key"); } if(opts.isSet("value")) { - valueTypeNames = opts.optArg("value"); + valueTypeNames = opts.optArg("value"); } caseSensitive = opts.isSet("case-sensitive"); if(outputFile.empty()) { - if(args.size() == 2) - { - allDb = true; - } - else if(args.size() != 3) - { - usage(argv[0]); - return EXIT_FAILURE; - } + if(args.size() == 2) + { + allDb = true; + } + else if(args.size() != 3) + { + usage(argv[0]); + return EXIT_FAILURE; + } } else { - if(args.size() == 1) - { - allDb = true; - } - else if(args.size() != 0) - { - usage(argv[0]); - return EXIT_FAILURE; - } + if(args.size() == 1) + { + allDb = true; + } + else if(args.size() != 0) + { + usage(argv[0]); + return EXIT_FAILURE; + } } if(allDb && (!keyTypeNames.empty() || !valueTypeNames.empty())) { - usage(argv[0]); - return EXIT_FAILURE; + usage(argv[0]); + return EXIT_FAILURE; } if(inputFile.empty() && !allDb && !evictor && (keyTypeNames.empty() || valueTypeNames.empty())) { - usage(argv[0]); - return EXIT_FAILURE; + usage(argv[0]); + return EXIT_FAILURE; } if(args.size() > 0) { - dbEnvName = args[0]; + dbEnvName = args[0]; } if(args.size() > 1) { - if(allDb) - { - dbEnvNameNew = args[1]; - } - else - { - dbName = args[1]; - } + if(allDb) + { + dbEnvNameNew = args[1]; + } + else + { + dbName = args[1]; + } } if(args.size() > 2) { @@ -436,20 +436,20 @@ run(int argc, char** argv, const Ice::CommunicatorPtr& communicator) FreezeScript::CatalogDataMap catalog; if(allDb) { - try - { - catalog = FreezeScript::readCatalog(communicator, dbEnvName); - } - catch(const FreezeScript::FailureException& ex) - { - cerr << argv[0] << ": " << ex.reason() << endl; - return EXIT_FAILURE; - } - if(catalog.empty()) - { - cerr << argv[0] << ": no databases in environment `" << dbEnvName << "'" << endl; - return EXIT_FAILURE; - } + try + { + catalog = FreezeScript::readCatalog(communicator, dbEnvName); + } + catch(const FreezeScript::FailureException& ex) + { + cerr << argv[0] << ": " << ex.reason() << endl; + return EXIT_FAILURE; + } + if(catalog.empty()) + { + cerr << argv[0] << ": no databases in environment `" << dbEnvName << "'" << endl; + return EXIT_FAILURE; + } } // @@ -463,166 +463,166 @@ run(int argc, char** argv, const Ice::CommunicatorPtr& communicator) vector missingTypes; vector analyzeErrors; - FreezeScript::TransformAnalyzer analyzer(oldUnit, newUnit, ignoreTypeChanges, out, missingTypes, analyzeErrors); - - const string evictorKeyName = "::Ice::Identity"; - const string evictorValueName = "::Freeze::ObjectRecord"; - - if(allDb) - { - // - // Add a element for each database in the catalog. - // - for(FreezeScript::CatalogDataMap::iterator p = catalog.begin(); p != catalog.end(); ++p) - { - string keyName, valueName; - - if(p->second.evictor) - { - keyName = evictorKeyName; - valueName = evictorValueName; - } - else - { - keyName = p->second.key; - valueName = p->second.value; - } - - // - // Look up the key and value types in the old and new Slice definitions. - // - Slice::TypePtr oldKeyType = findType(oldUnit, keyName); - if(!oldKeyType) - { - cerr << argv[0] << ": type `" << keyName << "' from database `" << p->first - << "' not found in old Slice definitions" << endl; - } - Slice::TypePtr newKeyType = findType(newUnit, keyName); - if(!newKeyType) - { - cerr << argv[0] << ": type `" << keyName << "' from database `" << p->first - << "' not found in new Slice definitions" << endl; - } - Slice::TypePtr oldValueType = findType(oldUnit, valueName); - if(!oldValueType) - { - cerr << argv[0] << ": type `" << valueName << "' from database `" << p->first - << "' not found in old Slice definitions" << endl; - } - Slice::TypePtr newValueType = findType(newUnit, valueName); - if(!newValueType) - { - cerr << argv[0] << ": type `" << valueName << "' from database `" << p->first - << "' not found in new Slice definitions" << endl; - } - - // - // If we are generating an output file, we do not consider a missing type to be - // an error. Since the type information comes from the catalog of the old - // environment, it's possible that the key or value types are not present in - // the new Slice definitions. Rather than abort at this point, we simply emit - // a partially-defined element that must be edited by the user. - // - // If we are not generating an output file, we have to stop now. - // - if(outputFile.empty() && (!oldKeyType || !newKeyType || !oldValueType || !newValueType)) - { - return EXIT_FAILURE; - } - - analyzer.addDatabase(p->first, oldKeyType, newKeyType, oldValueType, newValueType); - } - } - else - { - string oldKeyName, newKeyName, oldValueName, newValueName; - - if(evictor) - { - oldKeyName = newKeyName = evictorKeyName; - oldValueName = newValueName = evictorValueName; - } - else - { - string::size_type pos; - - if(keyTypeNames.empty() || valueTypeNames.empty()) - { - usage(argv[0]); - return EXIT_FAILURE; - } - - pos = keyTypeNames.find(','); - if(pos == 0 || pos == keyTypeNames.size()) - { - usage(argv[0]); - return EXIT_FAILURE; - } - if(pos == string::npos) - { - oldKeyName = keyTypeNames; - newKeyName = keyTypeNames; - } - else - { - oldKeyName = keyTypeNames.substr(0, pos); - newKeyName = keyTypeNames.substr(pos + 1); - } - - pos = valueTypeNames.find(','); - if(pos == 0 || pos == valueTypeNames.size()) - { - usage(argv[0]); - return EXIT_FAILURE; - } - if(pos == string::npos) - { - oldValueName = valueTypeNames; - newValueName = valueTypeNames; - } - else - { - oldValueName = valueTypeNames.substr(0, pos); - newValueName = valueTypeNames.substr(pos + 1); - } - } - - // - // Look up the key and value types in the old and new Slice definitions. - // - Slice::TypePtr oldKeyType = findType(oldUnit, oldKeyName); - if(!oldKeyType) - { - cerr << argv[0] << ": type `" << oldKeyName << "' not found in old Slice definitions" << endl; - } - Slice::TypePtr newKeyType = findType(newUnit, newKeyName); - if(!newKeyType) - { - cerr << argv[0] << ": type `" << newKeyName << "' not found in new Slice definitions" << endl; - } - Slice::TypePtr oldValueType = findType(oldUnit, oldValueName); - if(!oldValueType) - { - cerr << argv[0] << ": type `" << oldValueName << "' not found in old Slice definitions" << endl; - } - Slice::TypePtr newValueType = findType(newUnit, newValueName); - if(!newValueType) - { - cerr << argv[0] << ": type `" << newValueName << "' not found in new Slice definitions" << endl; - } - - // - // Stop now if any of the types could not be found. - // - if(!oldKeyType || !newKeyType || !oldValueType || !newValueType) - { - return EXIT_FAILURE; - } - - analyzer.addDatabase("", oldKeyType, newKeyType, oldValueType, newValueType); - } - - analyzer.finish(); + FreezeScript::TransformAnalyzer analyzer(oldUnit, newUnit, ignoreTypeChanges, out, missingTypes, analyzeErrors); + + const string evictorKeyName = "::Ice::Identity"; + const string evictorValueName = "::Freeze::ObjectRecord"; + + if(allDb) + { + // + // Add a element for each database in the catalog. + // + for(FreezeScript::CatalogDataMap::iterator p = catalog.begin(); p != catalog.end(); ++p) + { + string keyName, valueName; + + if(p->second.evictor) + { + keyName = evictorKeyName; + valueName = evictorValueName; + } + else + { + keyName = p->second.key; + valueName = p->second.value; + } + + // + // Look up the key and value types in the old and new Slice definitions. + // + Slice::TypePtr oldKeyType = findType(oldUnit, keyName); + if(!oldKeyType) + { + cerr << argv[0] << ": type `" << keyName << "' from database `" << p->first + << "' not found in old Slice definitions" << endl; + } + Slice::TypePtr newKeyType = findType(newUnit, keyName); + if(!newKeyType) + { + cerr << argv[0] << ": type `" << keyName << "' from database `" << p->first + << "' not found in new Slice definitions" << endl; + } + Slice::TypePtr oldValueType = findType(oldUnit, valueName); + if(!oldValueType) + { + cerr << argv[0] << ": type `" << valueName << "' from database `" << p->first + << "' not found in old Slice definitions" << endl; + } + Slice::TypePtr newValueType = findType(newUnit, valueName); + if(!newValueType) + { + cerr << argv[0] << ": type `" << valueName << "' from database `" << p->first + << "' not found in new Slice definitions" << endl; + } + + // + // If we are generating an output file, we do not consider a missing type to be + // an error. Since the type information comes from the catalog of the old + // environment, it's possible that the key or value types are not present in + // the new Slice definitions. Rather than abort at this point, we simply emit + // a partially-defined element that must be edited by the user. + // + // If we are not generating an output file, we have to stop now. + // + if(outputFile.empty() && (!oldKeyType || !newKeyType || !oldValueType || !newValueType)) + { + return EXIT_FAILURE; + } + + analyzer.addDatabase(p->first, oldKeyType, newKeyType, oldValueType, newValueType); + } + } + else + { + string oldKeyName, newKeyName, oldValueName, newValueName; + + if(evictor) + { + oldKeyName = newKeyName = evictorKeyName; + oldValueName = newValueName = evictorValueName; + } + else + { + string::size_type pos; + + if(keyTypeNames.empty() || valueTypeNames.empty()) + { + usage(argv[0]); + return EXIT_FAILURE; + } + + pos = keyTypeNames.find(','); + if(pos == 0 || pos == keyTypeNames.size()) + { + usage(argv[0]); + return EXIT_FAILURE; + } + if(pos == string::npos) + { + oldKeyName = keyTypeNames; + newKeyName = keyTypeNames; + } + else + { + oldKeyName = keyTypeNames.substr(0, pos); + newKeyName = keyTypeNames.substr(pos + 1); + } + + pos = valueTypeNames.find(','); + if(pos == 0 || pos == valueTypeNames.size()) + { + usage(argv[0]); + return EXIT_FAILURE; + } + if(pos == string::npos) + { + oldValueName = valueTypeNames; + newValueName = valueTypeNames; + } + else + { + oldValueName = valueTypeNames.substr(0, pos); + newValueName = valueTypeNames.substr(pos + 1); + } + } + + // + // Look up the key and value types in the old and new Slice definitions. + // + Slice::TypePtr oldKeyType = findType(oldUnit, oldKeyName); + if(!oldKeyType) + { + cerr << argv[0] << ": type `" << oldKeyName << "' not found in old Slice definitions" << endl; + } + Slice::TypePtr newKeyType = findType(newUnit, newKeyName); + if(!newKeyType) + { + cerr << argv[0] << ": type `" << newKeyName << "' not found in new Slice definitions" << endl; + } + Slice::TypePtr oldValueType = findType(oldUnit, oldValueName); + if(!oldValueType) + { + cerr << argv[0] << ": type `" << oldValueName << "' not found in old Slice definitions" << endl; + } + Slice::TypePtr newValueType = findType(newUnit, newValueName); + if(!newValueType) + { + cerr << argv[0] << ": type `" << newValueName << "' not found in new Slice definitions" << endl; + } + + // + // Stop now if any of the types could not be found. + // + if(!oldKeyType || !newKeyType || !oldValueType || !newValueType) + { + return EXIT_FAILURE; + } + + analyzer.addDatabase("", oldKeyType, newKeyType, oldValueType, newValueType); + } + + analyzer.finish(); if(!analyzeErrors.empty()) { @@ -717,7 +717,7 @@ run(int argc, char** argv, const Ice::CommunicatorPtr& communicator) // Open the old database environment. Use DB_RECOVER_FATAL if -c is specified. // No transaction is created for the old environment. // - // DB_THREAD is for compatibility with Freeze (the catalog) + // DB_THREAD is for compatibility with Freeze (the catalog) { u_int32_t flags = DB_INIT_LOG | DB_INIT_MPOOL | DB_INIT_TXN | DB_CREATE | DB_THREAD; if(catastrophicRecover) @@ -734,42 +734,42 @@ run(int argc, char** argv, const Ice::CommunicatorPtr& communicator) // // Open the new database environment and start a transaction. // - // - // DB_THREAD is for compatibility with Freeze (the catalog) - // + // + // DB_THREAD is for compatibility with Freeze (the catalog) + // { u_int32_t flags = DB_INIT_LOG | DB_INIT_MPOOL | DB_INIT_TXN | DB_RECOVER | DB_CREATE - | DB_THREAD; + | DB_THREAD; dbEnvNew.open(dbEnvNameNew.c_str(), flags, FREEZE_SCRIPT_DB_MODE); } - // - // TODO: handle properly DbHome config (currently it will break if it's set for the new env) - // - - // - // Open the catalog of the new environment, and start a transaction. - // - Freeze::ConnectionPtr connectionNew = Freeze::createConnection(communicator, dbEnvNameNew, dbEnvNew); - txNew = connectionNew->beginTransaction(); - DbTxn* txnNew = Freeze::getTxn(txNew); - - if(allDb) - { - // - // Transform all databases in the old catalog. - // - for(FreezeScript::CatalogDataMap::iterator p = catalog.begin(); p != catalog.end(); ++p) - { - transformDb(p->second.evictor, communicator, objectFactory, dbEnv, dbEnvNew, p->first, connectionNew, - dbs, oldUnit, newUnit, txnNew, purgeObjects, suppress, descriptors); - } - } - else - { - transformDb(evictor, communicator, objectFactory, dbEnv, dbEnvNew, dbName, connectionNew, dbs, - oldUnit, newUnit, txnNew, purgeObjects, suppress, descriptors); - } + // + // TODO: handle properly DbHome config (currently it will break if it's set for the new env) + // + + // + // Open the catalog of the new environment, and start a transaction. + // + Freeze::ConnectionPtr connectionNew = Freeze::createConnection(communicator, dbEnvNameNew, dbEnvNew); + txNew = connectionNew->beginTransaction(); + DbTxn* txnNew = Freeze::getTxn(txNew); + + if(allDb) + { + // + // Transform all databases in the old catalog. + // + for(FreezeScript::CatalogDataMap::iterator p = catalog.begin(); p != catalog.end(); ++p) + { + transformDb(p->second.evictor, communicator, objectFactory, dbEnv, dbEnvNew, p->first, connectionNew, + dbs, oldUnit, newUnit, txnNew, purgeObjects, suppress, descriptors); + } + } + else + { + transformDb(evictor, communicator, objectFactory, dbEnv, dbEnvNew, dbName, connectionNew, dbs, + oldUnit, newUnit, txnNew, purgeObjects, suppress, descriptors); + } } catch(const DbException& ex) { diff --git a/cpp/src/Glacier2/Blobject.cpp b/cpp/src/Glacier2/Blobject.cpp index fb4f49d8772..bc5995fb547 100644 --- a/cpp/src/Glacier2/Blobject.cpp +++ b/cpp/src/Glacier2/Blobject.cpp @@ -32,57 +32,57 @@ Glacier2::Blobject::Blobject(const CommunicatorPtr& communicator, bool reverse, _logger(_communicator->getLogger()), _reverse(reverse), _forwardContext(_reverse ? - _properties->getPropertyAsInt(serverForwardContext) > 0 : - _properties->getPropertyAsInt(clientForwardContext) > 0), + _properties->getPropertyAsInt(serverForwardContext) > 0 : + _properties->getPropertyAsInt(clientForwardContext) > 0), _buffered(_reverse ? - _properties->getPropertyAsIntWithDefault(serverBuffered, 1) > 0 : - _properties->getPropertyAsIntWithDefault(clientBuffered, 1) > 0), + _properties->getPropertyAsIntWithDefault(serverBuffered, 1) > 0 : + _properties->getPropertyAsIntWithDefault(clientBuffered, 1) > 0), _alwaysBatch(_reverse ? - _properties->getPropertyAsInt(serverAlwaysBatch) > 0 : - _properties->getPropertyAsInt(clientAlwaysBatch) > 0), + _properties->getPropertyAsInt(serverAlwaysBatch) > 0 : + _properties->getPropertyAsInt(clientAlwaysBatch) > 0), _requestTraceLevel(_reverse ? - _properties->getPropertyAsInt(serverTraceRequest) : - _properties->getPropertyAsInt(clientTraceRequest)), + _properties->getPropertyAsInt(serverTraceRequest) : + _properties->getPropertyAsInt(clientTraceRequest)), _overrideTraceLevel(reverse ? - _properties->getPropertyAsInt(serverTraceOverride) : - _properties->getPropertyAsInt(clientTraceOverride)), + _properties->getPropertyAsInt(serverTraceOverride) : + _properties->getPropertyAsInt(clientTraceOverride)), _sslContext(sslContext) { if(_buffered) { - try - { - IceUtil::Time sleepTime = _reverse ? - IceUtil::Time::milliSeconds(_properties->getPropertyAsInt(serverSleepTime)) : - IceUtil::Time::milliSeconds(_properties->getPropertyAsInt(clientSleepTime)); + try + { + IceUtil::Time sleepTime = _reverse ? + IceUtil::Time::milliSeconds(_properties->getPropertyAsInt(serverSleepTime)) : + IceUtil::Time::milliSeconds(_properties->getPropertyAsInt(clientSleepTime)); - const_cast(_requestQueue) = new RequestQueue(sleepTime); - - Int threadStackSize = _properties->getPropertyAsInt("Ice.ThreadPerConnection.StackSize"); - - _requestQueue->start(static_cast(threadStackSize)); + const_cast(_requestQueue) = new RequestQueue(sleepTime); + + Int threadStackSize = _properties->getPropertyAsInt("Ice.ThreadPerConnection.StackSize"); + + _requestQueue->start(static_cast(threadStackSize)); - // - // See the comment in Glacier2::RequestQueue::destroy() - // for why we detach the thread. - // - _requestQueue->getThreadControl().detach(); - } - catch(const IceUtil::Exception& ex) - { - { - Error out(_logger); - out << "cannot create thread for request queue:\n" << ex; - } + // + // See the comment in Glacier2::RequestQueue::destroy() + // for why we detach the thread. + // + _requestQueue->getThreadControl().detach(); + } + catch(const IceUtil::Exception& ex) + { + { + Error out(_logger); + out << "cannot create thread for request queue:\n" << ex; + } - if(_requestQueue) - { - _requestQueue->destroy(); - } - - throw; - } + if(_requestQueue) + { + _requestQueue->destroy(); + } + + throw; + } } } @@ -98,14 +98,14 @@ Glacier2::Blobject::destroy() void Glacier2::Blobject::invoke(ObjectPrx& proxy, const AMD_Array_Object_ice_invokePtr& amdCB, - const std::pair& inParams, const Current& current) + const std::pair& inParams, const Current& current) { // // Set the correct facet on the proxy. // if(!current.facet.empty()) { - proxy = proxy->ice_facet(current.facet); + proxy = proxy->ice_facet(current.facet); } // @@ -115,13 +115,13 @@ Glacier2::Blobject::invoke(ObjectPrx& proxy, const AMD_Array_Object_ice_invokePt if(current.requestId == 0) { if(_alwaysBatch && _buffered) - { - proxy = proxy->ice_batchOneway(); - } - else - { + { + proxy = proxy->ice_batchOneway(); + } + else + { proxy = proxy->ice_oneway(); - } + } } else if(current.requestId > 0) { @@ -134,229 +134,229 @@ Glacier2::Blobject::invoke(ObjectPrx& proxy, const AMD_Array_Object_ice_invokePt Context::const_iterator p = current.ctx.find("_fwd"); if(p != current.ctx.end()) { - for(unsigned int i = 0; i < p->second.length(); ++i) - { - char option = p->second[i]; - switch(option) - { - case 't': - { - proxy = proxy->ice_twoway(); - break; - } - - case 'o': - { - if(_alwaysBatch && _buffered) - { - proxy = proxy->ice_batchOneway(); - } - else - { - proxy = proxy->ice_oneway(); - } - break; - } - - case 'd': - { - if(_alwaysBatch && _buffered) - { - proxy = proxy->ice_batchDatagram(); - } - else - { - proxy = proxy->ice_datagram(); - } - break; - } - - case 'O': - { - if(_buffered) - { - proxy = proxy->ice_batchOneway(); - } - else - { - proxy = proxy->ice_oneway(); - } - break; - } - - case 'D': - { - if(_buffered) - { - proxy = proxy->ice_batchDatagram(); - } - else - { - proxy = proxy->ice_datagram(); - } - break; - } - - case 's': - { - proxy = proxy->ice_secure(true); - break; - } - - case 'z': - { - proxy = proxy->ice_compress(true); - break; - } - - default: - { - Warning out(_logger); - out << "unknown forward option `" << option << "'"; - break; - } - } - } + for(unsigned int i = 0; i < p->second.length(); ++i) + { + char option = p->second[i]; + switch(option) + { + case 't': + { + proxy = proxy->ice_twoway(); + break; + } + + case 'o': + { + if(_alwaysBatch && _buffered) + { + proxy = proxy->ice_batchOneway(); + } + else + { + proxy = proxy->ice_oneway(); + } + break; + } + + case 'd': + { + if(_alwaysBatch && _buffered) + { + proxy = proxy->ice_batchDatagram(); + } + else + { + proxy = proxy->ice_datagram(); + } + break; + } + + case 'O': + { + if(_buffered) + { + proxy = proxy->ice_batchOneway(); + } + else + { + proxy = proxy->ice_oneway(); + } + break; + } + + case 'D': + { + if(_buffered) + { + proxy = proxy->ice_batchDatagram(); + } + else + { + proxy = proxy->ice_datagram(); + } + break; + } + + case 's': + { + proxy = proxy->ice_secure(true); + break; + } + + case 'z': + { + proxy = proxy->ice_compress(true); + break; + } + + default: + { + Warning out(_logger); + out << "unknown forward option `" << option << "'"; + break; + } + } + } } if(_requestTraceLevel >= 1) { - Trace out(_logger, "Glacier2"); - if(_reverse) - { - out << "reverse "; - } - out << "routing"; - if(_buffered) - { - out << " (buffered)"; - } - else - { - out << " (not buffered)"; - } - if(_reverse) - { - out << "\nidentity = " << _communicator->identityToString(proxy->ice_getIdentity()); - } - else - { - out << "\nproxy = " << _communicator->proxyToString(proxy); - } - out << "\noperation = " << current.operation; - out << "\ncontext = "; - Context::const_iterator q = current.ctx.begin(); - while(q != current.ctx.end()) - { - out << q->first << '/' << q->second; - if(++q != current.ctx.end()) - { - out << ", "; - } - } + Trace out(_logger, "Glacier2"); + if(_reverse) + { + out << "reverse "; + } + out << "routing"; + if(_buffered) + { + out << " (buffered)"; + } + else + { + out << " (not buffered)"; + } + if(_reverse) + { + out << "\nidentity = " << _communicator->identityToString(proxy->ice_getIdentity()); + } + else + { + out << "\nproxy = " << _communicator->proxyToString(proxy); + } + out << "\noperation = " << current.operation; + out << "\ncontext = "; + Context::const_iterator q = current.ctx.begin(); + while(q != current.ctx.end()) + { + out << q->first << '/' << q->second; + if(++q != current.ctx.end()) + { + out << ", "; + } + } } if(_buffered) { - // - // If we are in buffered mode, we create a new request and add - // it to the request queue. If the request is twoway, we use - // AMI. - // + // + // If we are in buffered mode, we create a new request and add + // it to the request queue. If the request is twoway, we use + // AMI. + // - bool override; - try - { - override = - _requestQueue->addRequest(new Request(proxy, inParams, current, _forwardContext, _sslContext, amdCB)); - } - catch(const ObjectNotExistException& ex) - { - amdCB->ice_exception(ex); - return; - } + bool override; + try + { + override = + _requestQueue->addRequest(new Request(proxy, inParams, current, _forwardContext, _sslContext, amdCB)); + } + catch(const ObjectNotExistException& ex) + { + amdCB->ice_exception(ex); + return; + } - if(override && _overrideTraceLevel >= 1) - { - Trace out(_logger, "Glacier2"); - if(_reverse) - { - out << "reverse "; - } - out << "routing override"; - if(_reverse) - { - out << "\nidentity = " << _communicator->identityToString(proxy->ice_getIdentity()); - } - else - { - out << "\nproxy = " << _communicator->proxyToString(proxy); - } - out << "\noperation = " << current.operation; - out << "\ncontext = "; - Context::const_iterator q = current.ctx.begin(); - while(q != current.ctx.end()) - { - out << q->first << '/' << q->second; - if(++q != current.ctx.end()) - { - out << ", "; - } - } - } + if(override && _overrideTraceLevel >= 1) + { + Trace out(_logger, "Glacier2"); + if(_reverse) + { + out << "reverse "; + } + out << "routing override"; + if(_reverse) + { + out << "\nidentity = " << _communicator->identityToString(proxy->ice_getIdentity()); + } + else + { + out << "\nproxy = " << _communicator->proxyToString(proxy); + } + out << "\noperation = " << current.operation; + out << "\ncontext = "; + Context::const_iterator q = current.ctx.begin(); + while(q != current.ctx.end()) + { + out << q->first << '/' << q->second; + if(++q != current.ctx.end()) + { + out << ", "; + } + } + } } else { - // - // If we are in not in buffered mode, we send the request - // directly. - // + // + // If we are in not in buffered mode, we send the request + // directly. + // - bool ok; - ByteSeq outParams; + bool ok; + ByteSeq outParams; - try - { - if(_forwardContext) - { - if(_sslContext.size() > 0) - { - Ice::Context ctx = current.ctx; - ctx.insert(_sslContext.begin(), _sslContext.end()); - ok = proxy->ice_invoke(current.operation, current.mode, inParams, outParams, ctx); - } - else - { - ok = proxy->ice_invoke(current.operation, current.mode, inParams, outParams, current.ctx); - } - } - else - { - if(_sslContext.size() > 0) - { - ok = proxy->ice_invoke(current.operation, current.mode, inParams, outParams, _sslContext); - } - else - { - ok = proxy->ice_invoke(current.operation, current.mode, inParams, outParams); - } - } + try + { + if(_forwardContext) + { + if(_sslContext.size() > 0) + { + Ice::Context ctx = current.ctx; + ctx.insert(_sslContext.begin(), _sslContext.end()); + ok = proxy->ice_invoke(current.operation, current.mode, inParams, outParams, ctx); + } + else + { + ok = proxy->ice_invoke(current.operation, current.mode, inParams, outParams, current.ctx); + } + } + else + { + if(_sslContext.size() > 0) + { + ok = proxy->ice_invoke(current.operation, current.mode, inParams, outParams, _sslContext); + } + else + { + ok = proxy->ice_invoke(current.operation, current.mode, inParams, outParams); + } + } - pair outPair; - if(outParams.size() == 0) - { - outPair.first = outPair.second = 0; - } - else - { - outPair.first = &outParams[0]; - outPair.second = outPair.first + outParams.size(); - } - amdCB->ice_response(ok, outPair); - } - catch(const LocalException& ex) - { - amdCB->ice_exception(ex); - } + pair outPair; + if(outParams.size() == 0) + { + outPair.first = outPair.second = 0; + } + else + { + outPair.first = &outParams[0]; + outPair.second = outPair.first + outParams.size(); + } + amdCB->ice_response(ok, outPair); + } + catch(const LocalException& ex) + { + amdCB->ice_exception(ex); + } } } diff --git a/cpp/src/Glacier2/Blobject.h b/cpp/src/Glacier2/Blobject.h index c9ffd39469d..afda9383a7e 100644 --- a/cpp/src/Glacier2/Blobject.h +++ b/cpp/src/Glacier2/Blobject.h @@ -28,7 +28,7 @@ public: protected: void invoke(Ice::ObjectPrx&, const Ice::AMD_Array_Object_ice_invokePtr&, - const std::pair&, const Ice::Current&); + const std::pair&, const Ice::Current&); const Ice::CommunicatorPtr _communicator; const Ice::PropertiesPtr _properties; diff --git a/cpp/src/Glacier2/ClientBlobject.cpp b/cpp/src/Glacier2/ClientBlobject.cpp index fde2b1669d0..a1e32dca027 100644 --- a/cpp/src/Glacier2/ClientBlobject.cpp +++ b/cpp/src/Glacier2/ClientBlobject.cpp @@ -17,9 +17,9 @@ using namespace Ice; using namespace Glacier2; Glacier2::ClientBlobject::ClientBlobject(const CommunicatorPtr& communicator, - const FilterManagerPtr& filters, - const Ice::Context& sslContext): - + const FilterManagerPtr& filters, + const Ice::Context& sslContext): + Glacier2::Blobject(communicator, false, sslContext), _routingTable(new RoutingTable(communicator)), _filters(filters), @@ -33,8 +33,8 @@ Glacier2::ClientBlobject::~ClientBlobject() void Glacier2::ClientBlobject::ice_invoke_async(const Ice::AMD_Array_Object_ice_invokePtr& amdCB, - const std::pair& inParams, - const Current& current) + const std::pair& inParams, + const Current& current) { bool matched = false; bool hasFilters = false; @@ -42,89 +42,89 @@ Glacier2::ClientBlobject::ice_invoke_async(const Ice::AMD_Array_Object_ice_invok if(!_filters->categories()->empty()) { - hasFilters = true; - if(_filters->categories()->match(current.id.category)) - { - matched = true; - } - else if(_rejectTraceLevel >= 1) - { - if(rejectedFilters.size() != 0) - { - rejectedFilters += ", "; - - } - rejectedFilters += "category filter"; - } + hasFilters = true; + if(_filters->categories()->match(current.id.category)) + { + matched = true; + } + else if(_rejectTraceLevel >= 1) + { + if(rejectedFilters.size() != 0) + { + rejectedFilters += ", "; + + } + rejectedFilters += "category filter"; + } } if(!_filters->identities()->empty()) { - hasFilters = true; - if(_filters->identities()->match(current.id)) - { - matched = true; - } - else if(_rejectTraceLevel >= 1) - { - if(rejectedFilters.size() != 0) - { - rejectedFilters += ", "; - - } - rejectedFilters += "identity filter"; - } + hasFilters = true; + if(_filters->identities()->match(current.id)) + { + matched = true; + } + else if(_rejectTraceLevel >= 1) + { + if(rejectedFilters.size() != 0) + { + rejectedFilters += ", "; + + } + rejectedFilters += "identity filter"; + } } ObjectPrx proxy = _routingTable->get(current.id); if(!proxy) { - ObjectNotExistException ex(__FILE__, __LINE__); - - // - // We use a special operation name indicate to the client that - // the proxy for the Ice object has not been found in our - // routing table. This can happen if the proxy was evicted - // from the routing table. - // - ex.id = current.id; - ex.facet = current.facet; - ex.operation = "ice_add_proxy"; - throw ex; + ObjectNotExistException ex(__FILE__, __LINE__); + + // + // We use a special operation name indicate to the client that + // the proxy for the Ice object has not been found in our + // routing table. This can happen if the proxy was evicted + // from the routing table. + // + ex.id = current.id; + ex.facet = current.facet; + ex.operation = "ice_add_proxy"; + throw ex; } string adapterId = proxy->ice_getAdapterId(); if(!adapterId.empty() && !_filters->adapterIds()->empty()) { - hasFilters = true; - if(_filters->adapterIds()->match(adapterId)) - { - matched = true; - } - else if(_rejectTraceLevel >= 1) - { - if(rejectedFilters.size() != 0) - { - rejectedFilters += ", "; - - } - rejectedFilters += "adapter id filter"; - } + hasFilters = true; + if(_filters->adapterIds()->match(adapterId)) + { + matched = true; + } + else if(_rejectTraceLevel >= 1) + { + if(rejectedFilters.size() != 0) + { + rejectedFilters += ", "; + + } + rejectedFilters += "adapter id filter"; + } } if(hasFilters && !matched) { - if(_rejectTraceLevel >= 1) - { - Trace out(_logger, "Glacier2"); - out << "rejecting request: " << rejectedFilters << "\n"; - out << "identity: " << _communicator->identityToString(current.id); - } - - ObjectNotExistException ex(__FILE__, __LINE__); - ex.id = current.id; - throw ex; + if(_rejectTraceLevel >= 1) + { + Trace out(_logger, "Glacier2"); + out << "rejecting request: " << rejectedFilters << "\n"; + out << "identity: " << _communicator->identityToString(current.id); + } + + ObjectNotExistException ex(__FILE__, __LINE__); + ex.id = current.id; + throw ex; } invoke(proxy, amdCB, inParams, current); } diff --git a/cpp/src/Glacier2/ClientBlobject.h b/cpp/src/Glacier2/ClientBlobject.h index 835a2da22e0..5385a0f2c0b 100644 --- a/cpp/src/Glacier2/ClientBlobject.h +++ b/cpp/src/Glacier2/ClientBlobject.h @@ -35,7 +35,7 @@ public: virtual ~ClientBlobject(); virtual void ice_invoke_async(const Ice::AMD_Array_Object_ice_invokePtr&, - const std::pair&, const Ice::Current&); + const std::pair&, const Ice::Current&); Ice::ObjectProxySeq add(const Ice::ObjectProxySeq&, const Ice::Current&); // Returns evicted proxies. diff --git a/cpp/src/Glacier2/CryptPermissionsVerifierI.cpp b/cpp/src/Glacier2/CryptPermissionsVerifierI.cpp index 7d6736df860..66a77599e0d 100755 --- a/cpp/src/Glacier2/CryptPermissionsVerifierI.cpp +++ b/cpp/src/Glacier2/CryptPermissionsVerifierI.cpp @@ -29,12 +29,12 @@ Glacier2::CryptPermissionsVerifierI::checkPermissions( if(p == _passwords.end()) { - return false; + return false; } if(p->second.size() != 13) // Crypt passwords are 13 characters long. { - return false; + return false; } char buff[14]; diff --git a/cpp/src/Glacier2/FilterI.h b/cpp/src/Glacier2/FilterI.h index b7e6ab996b1..a213f3c08a2 100755 --- a/cpp/src/Glacier2/FilterI.h +++ b/cpp/src/Glacier2/FilterI.h @@ -47,24 +47,24 @@ public: bool match(const T& candidate) const { - IceUtil::Monitor::Lock lock(*this); - // - // Empty vectors mean no filtering, so all matches will succeed. - // - if(_items.size() == 0) - { - return true; - } - - return binary_search(_items.begin(), _items.end(), candidate); + IceUtil::Monitor::Lock lock(*this); + // + // Empty vectors mean no filtering, so all matches will succeed. + // + if(_items.size() == 0) + { + return true; + } + + return binary_search(_items.begin(), _items.end(), candidate); } bool empty() const { - return _items.size() == 0; + return _items.size() == 0; } - + private: std::vector _items; @@ -128,36 +128,36 @@ FilterT::remove(const std::vector& deletions, const Ice::Current&) while(r != toRemove.end()) { - iterator i = mark; - while(i != _items.end() && r != toRemove.end()) - { - if(*r == *i) - { - // - // We want this list to be in LIFO order because we are - // going to erase things from the tail forward. - // - deleteList.push_front(i); - ++i; - ++r; - mark = i; - } - else - { - ++i; - } - } - - if(r == toRemove.end()) - { - break; - } - ++r; + iterator i = mark; + while(i != _items.end() && r != toRemove.end()) + { + if(*r == *i) + { + // + // We want this list to be in LIFO order because we are + // going to erase things from the tail forward. + // + deleteList.push_front(i); + ++i; + ++r; + mark = i; + } + else + { + ++i; + } + } + + if(r == toRemove.end()) + { + break; + } + ++r; } for(literator i = deleteList.begin(); i != deleteList.end(); ++i) { - _items.erase(*i); + _items.erase(*i); } } diff --git a/cpp/src/Glacier2/FilterManager.cpp b/cpp/src/Glacier2/FilterManager.cpp index 13c2a44e674..99bc204ed9e 100755 --- a/cpp/src/Glacier2/FilterManager.cpp +++ b/cpp/src/Glacier2/FilterManager.cpp @@ -32,61 +32,61 @@ stringToSeq(const string& str, vector& seq) string::size_type end = 0; while(current != string::npos) { - switch(str[current]) - { - case '"': - case '\'': - { - char quote = str[current]; - end = current+1; - while(true) - { - end = str.find(quote, end); + switch(str[current]) + { + case '"': + case '\'': + { + char quote = str[current]; + end = current+1; + while(true) + { + end = str.find(quote, end); - if(end == string::npos) - { - // - // TODO: should this be an unmatched quote error? - // - seq.push_back(str.substr(current)); - break; - } + if(end == string::npos) + { + // + // TODO: should this be an unmatched quote error? + // + seq.push_back(str.substr(current)); + break; + } - bool markString = true; - for(string::size_type r = end -1 ; r > current && str[r] == '\\' ; --r) - { - markString = !markString; - } - // - // We don't want the quote so we skip that. - // - if(markString) - { - ++current; - seq.push_back(str.substr(current, end-current)); - break; - } - else - { - ++end; - } - } - if(end != string::npos) - { - ++end; - } - break; - } + bool markString = true; + for(string::size_type r = end -1 ; r > current && str[r] == '\\' ; --r) + { + markString = !markString; + } + // + // We don't want the quote so we skip that. + // + if(markString) + { + ++current; + seq.push_back(str.substr(current, end-current)); + break; + } + else + { + ++end; + } + } + if(end != string::npos) + { + ++end; + } + break; + } - default: - { - end = str.find_first_of(ws, current); - string::size_type len = (end == string::npos) ? string::npos : end - current; - seq.push_back(str.substr(current, len)); - break; - } - } - current = str.find_first_not_of(ws, end); + default: + { + end = str.find_first_of(ws, current); + string::size_type len = (end == string::npos) ? string::npos : end - current; + seq.push_back(str.substr(current, len)); + break; + } + } + current = str.find_first_not_of(ws, end); } } @@ -102,61 +102,61 @@ stringToSeq(const CommunicatorPtr& comm, const string& str, vector& se string::size_type end = 0; while(current != string::npos) { - switch(str[current]) - { - case '"': - case '\'': - { - char quote = str[current]; - end = current+1; - while(true) - { - end = str.find(quote, end); + switch(str[current]) + { + case '"': + case '\'': + { + char quote = str[current]; + end = current+1; + while(true) + { + end = str.find(quote, end); - if(end == string::npos) - { - // - // TODO: should this be an unmatched quote error? - // - seq.push_back(comm->stringToIdentity(str.substr(current))); - break; - } + if(end == string::npos) + { + // + // TODO: should this be an unmatched quote error? + // + seq.push_back(comm->stringToIdentity(str.substr(current))); + break; + } - bool markString = true; - for(string::size_type r = end -1 ; r > current && str[r] == '\\' ; --r) - { - markString = !markString; - } - // - // We don't want the quote so we skip that. - // - if(markString) - { - ++current; - seq.push_back(comm->stringToIdentity(str.substr(current, end-current))); - break; - } - else - { - ++end; - } - } - if(end != string::npos) - { - ++end; - } - break; - } + bool markString = true; + for(string::size_type r = end -1 ; r > current && str[r] == '\\' ; --r) + { + markString = !markString; + } + // + // We don't want the quote so we skip that. + // + if(markString) + { + ++current; + seq.push_back(comm->stringToIdentity(str.substr(current, end-current))); + break; + } + else + { + ++end; + } + } + if(end != string::npos) + { + ++end; + } + break; + } - default: - { - end = str.find_first_of(ws, current); - string::size_type len = (end == string::npos) ? string::npos : end - current; - seq.push_back(comm->stringToIdentity(str.substr(current, len))); - break; - } - } - current = str.find_first_not_of(ws, end); + default: + { + end = str.find_first_of(ws, current); + string::size_type len = (end == string::npos) ? string::npos : end - current; + seq.push_back(comm->stringToIdentity(str.substr(current, len))); + break; + } + } + current = str.find_first_not_of(ws, end); } } @@ -170,42 +170,42 @@ Glacier2::FilterManager::destroy() { if(_adapter) { - try - { - if(_categoriesPrx) - { - _adapter->remove(_categoriesPrx->ice_getIdentity()); - } - } - catch(const Exception&) - { - } - try - { - if(_adapterIdsPrx) - { - _adapter->remove(_adapterIdsPrx->ice_getIdentity()); - } - } - catch(const Exception&) - { - } - try - { - if(_identitiesPrx) - { - _adapter->remove(_identitiesPrx->ice_getIdentity()); - } - } - catch(const Exception&) - { - } + try + { + if(_categoriesPrx) + { + _adapter->remove(_categoriesPrx->ice_getIdentity()); + } + } + catch(const Exception&) + { + } + try + { + if(_adapterIdsPrx) + { + _adapter->remove(_adapterIdsPrx->ice_getIdentity()); + } + } + catch(const Exception&) + { + } + try + { + if(_identitiesPrx) + { + _adapter->remove(_identitiesPrx->ice_getIdentity()); + } + } + catch(const Exception&) + { + } } } Glacier2::FilterManager::FilterManager(const ObjectAdapterPtr& adapter, const Glacier2::StringSetIPtr& categories, - const Glacier2::StringSetIPtr& adapters, - const Glacier2::IdentitySetIPtr& identities) : + const Glacier2::StringSetIPtr& adapters, + const Glacier2::IdentitySetIPtr& identities) : _categories(categories), _adapters(adapters), _identities(identities), @@ -213,23 +213,23 @@ Glacier2::FilterManager::FilterManager(const ObjectAdapterPtr& adapter, const Gl { try { - if(_adapter) - { - _categoriesPrx = Glacier2::StringSetPrx::uncheckedCast(_adapter->addWithUUID(_categories)); - _adapterIdsPrx = Glacier2::StringSetPrx::uncheckedCast(_adapter->addWithUUID(_adapters)); - _identitiesPrx = Glacier2::IdentitySetPrx::uncheckedCast(_adapter->addWithUUID(_identities)); - } + if(_adapter) + { + _categoriesPrx = Glacier2::StringSetPrx::uncheckedCast(_adapter->addWithUUID(_categories)); + _adapterIdsPrx = Glacier2::StringSetPrx::uncheckedCast(_adapter->addWithUUID(_adapters)); + _identitiesPrx = Glacier2::IdentitySetPrx::uncheckedCast(_adapter->addWithUUID(_identities)); + } } catch(...) { - destroy(); - throw; + destroy(); + throw; } } Glacier2::FilterManager* Glacier2::FilterManager::create(const CommunicatorPtr& communicator, const ObjectAdapterPtr& adapter, const string& userId, - const bool allowAddUser) + const bool allowAddUser) { PropertiesPtr props = communicator->getProperties(); // @@ -239,12 +239,12 @@ Glacier2::FilterManager::create(const CommunicatorPtr& communicator, const Objec string allow = props->getProperty("Glacier2.Filter.Category.Accept"); if(allow.empty()) { - allow = props->getProperty("Glacier2.AllowCategories"); - if(!allow.empty()) - { + allow = props->getProperty("Glacier2.AllowCategories"); + if(!allow.empty()) + { communicator->getLogger()->warning( - "Glacier2.AllowCategories has been deprecated, use Glacier2.Filter.Category.Accept instead."); - } + "Glacier2.AllowCategories has been deprecated, use Glacier2.Filter.Category.Accept instead."); + } } vector allowSeq; @@ -256,33 +256,33 @@ Glacier2::FilterManager::create(const CommunicatorPtr& communicator, const Objec // DEPRECATED PROPERTY: Glacier2.AddUserToAllowCategories is to be deprecated // and superseded by Glacier2.Filter.Category.AcceptUser. // - int addUserMode; - if(!props->getProperty("Glacier2.Filter.Category.AcceptUser").empty()) - { - addUserMode = props->getPropertyAsInt("Glacier2.Filter.Category.AcceptUser"); - } - else - { - if(!props->getProperty("Glacier2.AddUserToAllowCategories").empty()) - { + int addUserMode; + if(!props->getProperty("Glacier2.Filter.Category.AcceptUser").empty()) + { + addUserMode = props->getPropertyAsInt("Glacier2.Filter.Category.AcceptUser"); + } + else + { + if(!props->getProperty("Glacier2.AddUserToAllowCategories").empty()) + { communicator->getLogger()->warning( - "Glacier2.AddUserToAllowCategories has been deprecated, \ - use Glacier2.Filter.Category.AcceptUser instead."); - } - addUserMode = props->getPropertyAsInt("Glacier2.AddUserToAllowCategories"); - } + "Glacier2.AddUserToAllowCategories has been deprecated, \ + use Glacier2.Filter.Category.AcceptUser instead."); + } + addUserMode = props->getPropertyAsInt("Glacier2.AddUserToAllowCategories"); + } - if(addUserMode > 0 && !userId.empty()) - { - if(addUserMode == 1) - { - allowSeq.push_back(userId); // Add user id to allowed categories. - } - else if(addUserMode == 2) - { - allowSeq.push_back('_' + userId); // Add user id with prepended underscore to allowed categories. - } - } + if(addUserMode > 0 && !userId.empty()) + { + if(addUserMode == 1) + { + allowSeq.push_back(userId); // Add user id to allowed categories. + } + else if(addUserMode == 2) + { + allowSeq.push_back('_' + userId); // Add user id with prepended underscore to allowed categories. + } + } } Glacier2::StringSetIPtr categoryFilter = new Glacier2::StringSetI(allowSeq); diff --git a/cpp/src/Glacier2/FilterManager.h b/cpp/src/Glacier2/FilterManager.h index dabd62e8a5f..71881846e81 100755 --- a/cpp/src/Glacier2/FilterManager.h +++ b/cpp/src/Glacier2/FilterManager.h @@ -33,37 +33,37 @@ public: StringSetIPtr categories() const { - return _categories; + return _categories; } StringSetIPtr adapterIds() const { - return _adapters; + return _adapters; } IdentitySetIPtr identities() const { - return _identities; + return _identities; } StringSetPrx categoriesPrx() const { - return _categoriesPrx; + return _categoriesPrx; } StringSetPrx adapterIdsPrx() const { - return _adapterIdsPrx; + return _adapterIdsPrx; } IdentitySetPrx identitiesPrx() const { - return _identitiesPrx; + return _identitiesPrx; } static FilterManager* diff --git a/cpp/src/Glacier2/Glacier2Router.cpp b/cpp/src/Glacier2/Glacier2Router.cpp index 9426ae244cd..27fe0be4a3e 100644 --- a/cpp/src/Glacier2/Glacier2Router.cpp +++ b/cpp/src/Glacier2/Glacier2Router.cpp @@ -29,14 +29,14 @@ class AdminI : public Admin public: AdminI(const CommunicatorPtr& communicator) : - _communicator(communicator) + _communicator(communicator) { } virtual void shutdown(const Current&) { - _communicator->shutdown(); + _communicator->shutdown(); } private: @@ -100,30 +100,30 @@ Glacier2::RouterService::start(int argc, char* argv[]) vector args; try { - args = opts.parse(argc, (const char**)argv); + args = opts.parse(argc, (const char**)argv); } catch(const IceUtil::BadOptException& e) { error(e.reason); - usage(argv[0]); - return false; + usage(argv[0]); + return false; } if(opts.isSet("help")) { - usage(argv[0]); - return false; + usage(argv[0]); + return false; } if(opts.isSet("version")) { - print(ICE_STRING_VERSION); - return false; + print(ICE_STRING_VERSION); + return false; } if(!args.empty()) { - usage(argv[0]); - return false; + usage(argv[0]); + return false; } PropertiesPtr properties = communicator()->getProperties(); @@ -137,8 +137,8 @@ Glacier2::RouterService::start(int argc, char* argv[]) if(properties->getProperty(clientEndpointsProperty).empty() && properties->getProperty("Glacier2.Client.Endpoints").empty()) { - error("property `" + clientEndpointsProperty + "' is not set"); - return false; + error("property `" + clientEndpointsProperty + "' is not set"); + return false; } ObjectAdapterPtr clientAdapter = communicator()->createObjectAdapter("Glacier2.Client"); @@ -153,7 +153,7 @@ Glacier2::RouterService::start(int argc, char* argv[]) if(!properties->getProperty(serverEndpointsProperty).empty() || !properties->getProperty("Glacier2.Server.Endpoints").empty()) { - serverAdapter = communicator()->createObjectAdapter("Glacier2.Server"); + serverAdapter = communicator()->createObjectAdapter("Glacier2.Server"); } // @@ -167,7 +167,7 @@ Glacier2::RouterService::start(int argc, char* argv[]) if(!properties->getProperty(adminEndpointsProperty).empty() || !properties->getProperty("Glacier2.Admin.Endpoints").empty()) { - adminAdapter = communicator()->createObjectAdapter("Glacier2.Admin"); + adminAdapter = communicator()->createObjectAdapter("Glacier2.Admin"); } string instanceName = properties->getPropertyWithDefault("Glacier2.InstanceName", "Glacier2"); @@ -193,67 +193,67 @@ Glacier2::RouterService::start(int argc, char* argv[]) nullPermVerifId.name = "NullPermissionsVerifier"; ObjectPrx obj = communicator()->propertyToProxy(verifierProperty); - if(obj->ice_getIdentity() == nullPermVerifId) - { - verifier = PermissionsVerifierPrx::uncheckedCast( - verifierAdapter->add(new NullPermissionsVerifierI(), nullPermVerifId)->ice_collocationOptimized(true)); - } - else - { - try - { - verifier = PermissionsVerifierPrx::checkedCast(obj); - } - catch(const Ice::Exception& ex) - { - ostringstream ostr; - ostr << ex; - error("unable to contact permissions verifier `" + verifierPropertyValue + "'\n" + ostr.str()); - return false; - } - if(!verifier) - { - error("permissions verifier `" + verifierPropertyValue + "' is invalid"); - return false; - } - } + if(obj->ice_getIdentity() == nullPermVerifId) + { + verifier = PermissionsVerifierPrx::uncheckedCast( + verifierAdapter->add(new NullPermissionsVerifierI(), nullPermVerifId)->ice_collocationOptimized(true)); + } + else + { + try + { + verifier = PermissionsVerifierPrx::checkedCast(obj); + } + catch(const Ice::Exception& ex) + { + ostringstream ostr; + ostr << ex; + error("unable to contact permissions verifier `" + verifierPropertyValue + "'\n" + ostr.str()); + return false; + } + if(!verifier) + { + error("permissions verifier `" + verifierPropertyValue + "' is invalid"); + return false; + } + } } else if(!passwordsProperty.empty()) { - ifstream passwordFile(passwordsProperty.c_str()); - if(!passwordFile) - { + ifstream passwordFile(passwordsProperty.c_str()); + if(!passwordFile) + { string err = strerror(errno); - error("cannot open `" + passwordsProperty + "' for reading: " + err); - return false; - } - - map passwords; - - while(true) - { - string userId; - passwordFile >> userId; - if(!passwordFile) - { - break; - } - - string password; - passwordFile >> password; - if(!passwordFile) - { - break; - } - - assert(!userId.empty()); - assert(!password.empty()); - passwords.insert(make_pair(userId, password)); - } - - PermissionsVerifierPtr verifierImpl = new CryptPermissionsVerifierI(passwords); - - verifier = PermissionsVerifierPrx::uncheckedCast(verifierAdapter->addWithUUID(verifierImpl)); + error("cannot open `" + passwordsProperty + "' for reading: " + err); + return false; + } + + map passwords; + + while(true) + { + string userId; + passwordFile >> userId; + if(!passwordFile) + { + break; + } + + string password; + passwordFile >> password; + if(!passwordFile) + { + break; + } + + assert(!userId.empty()); + assert(!password.empty()); + passwords.insert(make_pair(userId, password)); + } + + PermissionsVerifierPtr verifierImpl = new CryptPermissionsVerifierI(passwords); + + verifier = PermissionsVerifierPrx::uncheckedCast(verifierAdapter->addWithUUID(verifierImpl)); } // @@ -265,24 +265,24 @@ Glacier2::RouterService::start(int argc, char* argv[]) if(!sessionManagerPropertyValue.empty()) { try - { - sessionManager = SessionManagerPrx::checkedCast(communicator()->propertyToProxy(sessionManagerProperty)); - } - catch(const Ice::Exception& ex) - { - ostringstream ostr; - ostr << ex; - error("unable to contact session manager `" + sessionManagerPropertyValue + "'\n" + ostr.str()); - return false; - } - if(!sessionManager) - { - error("session manager `" + sessionManagerPropertyValue + "' is invalid"); - return false; - } - sessionManager = - SessionManagerPrx::uncheckedCast(sessionManager->ice_connectionCached(false)->ice_locatorCacheTimeout( - properties->getPropertyAsIntWithDefault("Glacier2.SessionManager.LocatorCacheTimeout", 600))); + { + sessionManager = SessionManagerPrx::checkedCast(communicator()->propertyToProxy(sessionManagerProperty)); + } + catch(const Ice::Exception& ex) + { + ostringstream ostr; + ostr << ex; + error("unable to contact session manager `" + sessionManagerPropertyValue + "'\n" + ostr.str()); + return false; + } + if(!sessionManager) + { + error("session manager `" + sessionManagerPropertyValue + "' is invalid"); + return false; + } + sessionManager = + SessionManagerPrx::uncheckedCast(sessionManager->ice_connectionCached(false)->ice_locatorCacheTimeout( + properties->getPropertyAsIntWithDefault("Glacier2.SessionManager.LocatorCacheTimeout", 600))); } // @@ -297,33 +297,33 @@ Glacier2::RouterService::start(int argc, char* argv[]) nullSSLPermVerifId.category = instanceName; nullSSLPermVerifId.name = "NullSSLPermissionsVerifier"; - ObjectPrx obj = communicator()->propertyToProxy(sslVerifierProperty); - if(obj->ice_getIdentity() == nullSSLPermVerifId) - { + ObjectPrx obj = communicator()->propertyToProxy(sslVerifierProperty); + if(obj->ice_getIdentity() == nullSSLPermVerifId) + { sslVerifier = SSLPermissionsVerifierPrx::uncheckedCast( verifierAdapter->add(new NullSSLPermissionsVerifierI(), nullSSLPermVerifId)-> - ice_collocationOptimized(true)); - } - else - { + ice_collocationOptimized(true)); + } + else + { try - { - sslVerifier = SSLPermissionsVerifierPrx::checkedCast(obj); - } - catch(const Ice::Exception& ex) - { - ostringstream ostr; - ostr << ex; - error("unable to contact ssl permissions verifier `" + sslVerifierPropertyValue + "'\n" + ostr.str()); - return false; - } - if(!sslVerifier) - { - error("ssl permissions verifier `" + sslVerifierPropertyValue + "' is invalid"); - return false; - } - } + { + sslVerifier = SSLPermissionsVerifierPrx::checkedCast(obj); + } + catch(const Ice::Exception& ex) + { + ostringstream ostr; + ostr << ex; + error("unable to contact ssl permissions verifier `" + sslVerifierPropertyValue + "'\n" + ostr.str()); + return false; + } + if(!sslVerifier) + { + error("ssl permissions verifier `" + sslVerifierPropertyValue + "' is invalid"); + return false; + } + } } // @@ -335,31 +335,31 @@ Glacier2::RouterService::start(int argc, char* argv[]) if(!sslSessionManagerPropertyValue.empty()) { try - { - sslSessionManager = - SSLSessionManagerPrx::checkedCast(communicator()->propertyToProxy(sslSessionManagerProperty)); - } - catch(const Ice::Exception& ex) - { - ostringstream ostr; - ostr << ex; - error("unable to ssl session manager `" + sslSessionManagerPropertyValue + "'\n" + ostr.str()); - return false; - } - if(!sslSessionManager) - { - error("ssl session manager `" + sslSessionManagerPropertyValue + "' is invalid"); - return false; - } - sslSessionManager = - SSLSessionManagerPrx::uncheckedCast(sslSessionManager->ice_connectionCached(false)->ice_locatorCacheTimeout( - properties->getPropertyAsIntWithDefault("Glacier2.SSLSessionManager.LocatorCacheTimeout", 600))); + { + sslSessionManager = + SSLSessionManagerPrx::checkedCast(communicator()->propertyToProxy(sslSessionManagerProperty)); + } + catch(const Ice::Exception& ex) + { + ostringstream ostr; + ostr << ex; + error("unable to ssl session manager `" + sslSessionManagerPropertyValue + "'\n" + ostr.str()); + return false; + } + if(!sslSessionManager) + { + error("ssl session manager `" + sslSessionManagerPropertyValue + "' is invalid"); + return false; + } + sslSessionManager = + SSLSessionManagerPrx::uncheckedCast(sslSessionManager->ice_connectionCached(false)->ice_locatorCacheTimeout( + properties->getPropertyAsIntWithDefault("Glacier2.SSLSessionManager.LocatorCacheTimeout", 600))); } if(!verifier && !sslVerifier) { - error("Glacier2 requires a permissions verifier or password file"); - return false; + error("Glacier2 requires a permissions verifier or password file"); + return false; } // @@ -368,17 +368,17 @@ Glacier2::RouterService::start(int argc, char* argv[]) // done here. // _sessionRouter = new SessionRouterI(clientAdapter, serverAdapter, verifier, sessionManager, sslVerifier, - sslSessionManager); + sslSessionManager); // // If we have an admin adapter, we add an admin object. // if(adminAdapter) { - Identity adminId; - adminId.category = instanceName; - adminId.name = "admin"; - adminAdapter->add(new AdminI(communicator()), adminId); + Identity adminId; + adminId.category = instanceName; + adminId.name = "admin"; + adminAdapter->add(new AdminI(communicator()), adminId); } // @@ -389,20 +389,20 @@ Glacier2::RouterService::start(int argc, char* argv[]) clientAdapter->activate(); if(serverAdapter) { - serverAdapter->activate(); + serverAdapter->activate(); } if(adminAdapter) { - adminAdapter->activate(); + adminAdapter->activate(); } } catch(const Ice::Exception& ex) { - ostringstream ostr; - ostr << ex; - error("caught exception activating object adapters\n" + ostr.str()); + ostringstream ostr; + ostr << ex; + error("caught exception activating object adapters\n" + ostr.str()); - stop(); + stop(); return false; } @@ -414,15 +414,15 @@ Glacier2::RouterService::stop() { if(_sessionRouter) { - _sessionRouter->destroy(); - _sessionRouter = 0; + _sessionRouter->destroy(); + _sessionRouter = 0; } return true; } CommunicatorPtr Glacier2::RouterService::initializeCommunicator(int& argc, char* argv[], - const InitializationData& initializationData) + const InitializationData& initializationData) { InitializationData initData = initializationData; initData.properties = createProperties(argc, argv, initializationData.properties); @@ -452,7 +452,7 @@ Glacier2::RouterService::initializeCommunicator(int& argc, char* argv[], // if(initData.properties->getProperty("Ice.MonitorConnections").empty()) { - initData.properties->setProperty("Ice.MonitorConnections", "60"); + initData.properties->setProperty("Ice.MonitorConnections", "60"); } // @@ -470,30 +470,30 @@ void Glacier2::RouterService::usage(const string& appName) { string options = - "Options:\n" - "-h, --help Show this message.\n" - "-v, --version Display the Ice version."; + "Options:\n" + "-h, --help Show this message.\n" + "-v, --version Display the Ice version."; #ifdef _WIN32 if(checkSystem()) { options.append( - "\n" - "\n" - "--service NAME Run as the Windows service NAME.\n" - "\n" - "--install NAME [--display DISP] [--executable EXEC] [args]\n" - " Install as Windows service NAME. If DISP is\n" - " provided, use it as the display name,\n" - " otherwise NAME is used. If EXEC is provided,\n" - " use it as the service executable, otherwise\n" - " this executable is used. Any additional\n" - " arguments are passed unchanged to the\n" - " service at startup.\n" - "--uninstall NAME Uninstall Windows service NAME.\n" - "--start NAME [args] Start Windows service NAME. Any additional\n" - " arguments are passed unchanged to the\n" - " service.\n" - "--stop NAME Stop Windows service NAME." + "\n" + "\n" + "--service NAME Run as the Windows service NAME.\n" + "\n" + "--install NAME [--display DISP] [--executable EXEC] [args]\n" + " Install as Windows service NAME. If DISP is\n" + " provided, use it as the display name,\n" + " otherwise NAME is used. If EXEC is provided,\n" + " use it as the service executable, otherwise\n" + " this executable is used. Any additional\n" + " arguments are passed unchanged to the\n" + " service at startup.\n" + "--uninstall NAME Uninstall Windows service NAME.\n" + "--start NAME [args] Start Windows service NAME. Any additional\n" + " arguments are passed unchanged to the\n" + " service.\n" + "--stop NAME Stop Windows service NAME." ); } #else @@ -502,8 +502,8 @@ Glacier2::RouterService::usage(const string& appName) "\n" "--daemon Run as a daemon.\n" "--noclose Do not close open file descriptors.\n" - "--nochdir Do not change the current working directory.\n" - "--pidfile Write process ID to ." + "--nochdir Do not change the current working directory.\n" + "--pidfile Write process ID to ." ); #endif print("Usage: " + appName + " [options]\n" + options); diff --git a/cpp/src/Glacier2/ProxyVerifier.cpp b/cpp/src/Glacier2/ProxyVerifier.cpp index b0666c696c4..a71c194eed2 100644 --- a/cpp/src/Glacier2/ProxyVerifier.cpp +++ b/cpp/src/Glacier2/ProxyVerifier.cpp @@ -43,67 +43,67 @@ parseGroup(const string& parameter, vector& validPorts, vector& rang istringstream istr(parameter); while(!istr.eof()) { - ws(istr); - int value; - if(!(istr >> value)) - { - InitializationException ex(__FILE__, __LINE__); - ex.reason = "expected number"; - throw ex; - } - ws(istr); - if(!istr.eof()) - { - char c; - if(istr >> c) - { - if(c == ',') - { - validPorts.push_back(value); - } - else if(c == '-') - { - Range r; - r.start = value; - ws(istr); - if(istr.eof()) - { - InitializationException ex(__FILE__, __LINE__); - ex.reason = "Unterminated range"; - throw ex; - } - if(!(istr >> value)) - { - InitializationException ex(__FILE__, __LINE__); - ex.reason = "expected number"; - throw ex; - } - r.end = value; - ws(istr); - if(!istr.eof()) - { - istr >> c; - if(c != ',') - { - InitializationException ex(__FILE__, __LINE__); - ex.reason = "expected comma separator"; - throw ex; - } - } - ranges.push_back(r); - } - else if(!istr.eof()) - { - InitializationException ex(__FILE__, __LINE__); - ex.reason = "unexpected trailing character"; - throw ex; - } - } - } - else - { - validPorts.push_back(value); - } + ws(istr); + int value; + if(!(istr >> value)) + { + InitializationException ex(__FILE__, __LINE__); + ex.reason = "expected number"; + throw ex; + } + ws(istr); + if(!istr.eof()) + { + char c; + if(istr >> c) + { + if(c == ',') + { + validPorts.push_back(value); + } + else if(c == '-') + { + Range r; + r.start = value; + ws(istr); + if(istr.eof()) + { + InitializationException ex(__FILE__, __LINE__); + ex.reason = "Unterminated range"; + throw ex; + } + if(!(istr >> value)) + { + InitializationException ex(__FILE__, __LINE__); + ex.reason = "expected number"; + throw ex; + } + r.end = value; + ws(istr); + if(!istr.eof()) + { + istr >> c; + if(c != ',') + { + InitializationException ex(__FILE__, __LINE__); + ex.reason = "expected comma separator"; + throw ex; + } + } + ranges.push_back(r); + } + else if(!istr.eof()) + { + InitializationException ex(__FILE__, __LINE__); + ex.reason = "unexpected trailing character"; + throw ex; + } + } + } + else + { + validPorts.push_back(value); + } } } @@ -131,13 +131,13 @@ public: bool match(const string&, string::size_type&) { - return true; + return true; } const char* toString() const { - return "(ANY)"; + return "(ANY)"; } }; @@ -150,27 +150,27 @@ class StartsWithString : public AddressMatcher { public: StartsWithString(const string& criteria): - _criteria(criteria), - _description("starts with " + criteria) + _criteria(criteria), + _description("starts with " + criteria) { } bool match(const string& space, string::size_type& pos) { - assert(pos == 0); - bool result = strncmp(space.c_str(), _criteria.c_str(), _criteria.size()) == 0; - if(result) - { - pos += _criteria.size(); - } - return result; + assert(pos == 0); + bool result = strncmp(space.c_str(), _criteria.c_str(), _criteria.size()) == 0; + if(result) + { + pos += _criteria.size(); + } + return result; } const char* toString() const { - return _description.c_str(); + return _description.c_str(); } private: @@ -186,35 +186,35 @@ class EndsWithString : public AddressMatcher { public: EndsWithString(const string& criteria): - _criteria(criteria), - _description("ends with " + criteria) + _criteria(criteria), + _description("ends with " + criteria) { } bool match(const string& space, string::size_type& pos) { - if(space.size() - pos < _criteria.size()) - { - return false; - } + if(space.size() - pos < _criteria.size()) + { + return false; + } - string::size_type spaceEnd = space.size(); - for(string::size_type i = _criteria.size(); i > 0; --i) - { - if(space[spaceEnd - 1] != _criteria[i-1]) - { - return false; - } - --spaceEnd; - } - return true; + string::size_type spaceEnd = space.size(); + for(string::size_type i = _criteria.size(); i > 0; --i) + { + if(space[spaceEnd - 1] != _criteria[i-1]) + { + return false; + } + --spaceEnd; + } + return true; } virtual const char* toString() const { - return _description.c_str(); + return _description.c_str(); } private: @@ -226,26 +226,26 @@ class MatchesString : public AddressMatcher { public: MatchesString(const string& criteria): - _criteria(criteria), - _description("matches " + criteria) + _criteria(criteria), + _description("matches " + criteria) { } bool match(const string& space, string::size_type& pos) { - if(strncmp(space.c_str(), _criteria.c_str(), _criteria.size()) == 0) - { - pos += _criteria.size(); - return true; - } - return false; + if(strncmp(space.c_str(), _criteria.c_str(), _criteria.size()) == 0) + { + pos += _criteria.size(); + return true; + } + return false; } virtual const char* toString() const { - return _description.c_str(); + return _description.c_str(); } private: @@ -261,27 +261,27 @@ class ContainsString : public AddressMatcher { public: ContainsString(const string& criteria): - _criteria(criteria), - _description("contains " + criteria) + _criteria(criteria), + _description("contains " + criteria) { } bool match(const string& space, string::size_type& pos) { - string::size_type offset = space.find(_criteria, pos); - if(offset == string::npos) - { - return false; - } - pos = offset + _criteria.size() +1; - return true; + string::size_type offset = space.find(_criteria, pos); + if(offset == string::npos) + { + return false; + } + pos = offset + _criteria.size() +1; + return true; } virtual const char* toString() const { - return _description.c_str(); + return _description.c_str(); } private: @@ -298,90 +298,90 @@ class MatchesNumber : public AddressMatcher { public: MatchesNumber(const vector& values, const vector& ranges, - const char* descriptionPrefix = "matches "): - _values(values), - _ranges(ranges) - { - ostringstream ostr; - ostr << descriptionPrefix; - { - bool start = true; - for(vector::const_iterator i = values.begin(); i != values.end(); ++i) - { - if(start) - { - if(values.size() > 1) - { - ostr << "one of "; - } - start = false; - } - else - { - ostr << ", "; - } - - ostr << *i; - } - } - if(values.size() > 0 && ranges.size() > 0) - { - ostr << " or "; - } - { - bool start = true; - for(vector::const_iterator i = ranges.begin(); i != ranges.end(); ++i) - { - if(start) - { - start = false; - } - else - { - ostr << ", or"; - } - ostr << i->start << " up to " << i->end; - } - } - ostr << ends; - _description = ostr.str(); + const char* descriptionPrefix = "matches "): + _values(values), + _ranges(ranges) + { + ostringstream ostr; + ostr << descriptionPrefix; + { + bool start = true; + for(vector::const_iterator i = values.begin(); i != values.end(); ++i) + { + if(start) + { + if(values.size() > 1) + { + ostr << "one of "; + } + start = false; + } + else + { + ostr << ", "; + } + + ostr << *i; + } + } + if(values.size() > 0 && ranges.size() > 0) + { + ostr << " or "; + } + { + bool start = true; + for(vector::const_iterator i = ranges.begin(); i != ranges.end(); ++i) + { + if(start) + { + start = false; + } + else + { + ostr << ", or"; + } + ostr << i->start << " up to " << i->end; + } + } + ostr << ends; + _description = ostr.str(); } bool match(const string & space, string::size_type& pos) { - istringstream istr(space.substr(pos)); - int val; - if(!(istr >> val)) - { - return false; - } - pos += istr.tellg(); - { - for(vector::const_iterator i = _values.begin(); i != _values.end(); ++i) - { - if(val == *i) - { - return true; - } - } - } - { - for(vector::const_iterator i = _ranges.begin(); i != _ranges.end(); ++i) - { - if((val >= i->start) && (val <= i->end)) - { - return true; - } - } - } - return false; + istringstream istr(space.substr(pos)); + int val; + if(!(istr >> val)) + { + return false; + } + pos += istr.tellg(); + { + for(vector::const_iterator i = _values.begin(); i != _values.end(); ++i) + { + if(val == *i) + { + return true; + } + } + } + { + for(vector::const_iterator i = _ranges.begin(); i != _ranges.end(); ++i) + { + if((val >= i->start) && (val <= i->end)) + { + return true; + } + } + } + return false; } virtual const char* toString() const { - return _description.c_str(); + return _description.c_str(); } private: @@ -397,27 +397,27 @@ class ContainsNumberMatch : public MatchesNumber { public: ContainsNumberMatch(const vector& values, const vector& ranges): - MatchesNumber(values, ranges, "contains ") + MatchesNumber(values, ranges, "contains ") { } bool match(const string& space, string::size_type& pos) { - while(true) - { - pos = space.find_first_of("0123456789", pos); - if(pos == string::npos) - { - return false; - } - - if(MatchesNumber::match(space, pos)) - { - return true; - } - } - return false; + while(true) + { + pos = space.find_first_of("0123456789", pos); + if(pos == string::npos) + { + return false; + } + + if(MatchesNumber::match(space, pos)) + { + return true; + } + } + return false; } }; @@ -425,20 +425,20 @@ class EndsWithNumber : public MatchesNumber { public: EndsWithNumber(const vector& values, const vector& ranges): - MatchesNumber(values, ranges, "ends with ") + MatchesNumber(values, ranges, "ends with ") { } bool match(const string& space, string::size_type& pos) { - pos = space.find_last_not_of("0123456789", pos); - if(pos == space.size()-1) - { - return false; - } + pos = space.find_last_not_of("0123456789", pos); + if(pos == space.size()-1) + { + return false; + } - return MatchesNumber::match(space, pos); + return MatchesNumber::match(space, pos); } }; @@ -469,13 +469,13 @@ public: AddressMatcher* create(const string& criteria) { - return new StartsWithString(criteria); + return new StartsWithString(criteria); } AddressMatcher* create(const vector& ports, const vector& ranges) { - return new MatchesNumber(ports, ranges); + return new MatchesNumber(ports, ranges); } }; @@ -485,13 +485,13 @@ public: AddressMatcher* create(const string& criteria) { - return new ContainsString(criteria); + return new ContainsString(criteria); } AddressMatcher* create(const vector& ports, const vector& ranges) { - return new ContainsNumberMatch(ports, ranges); + return new ContainsNumberMatch(ports, ranges); } }; @@ -501,13 +501,13 @@ public: AddressMatcher* create(const string& criteria) { - return new MatchesString(criteria); + return new MatchesString(criteria); } AddressMatcher* create(const vector& ports, const vector& ranges) { - return new MatchesNumber(ports, ranges); + return new MatchesNumber(ports, ranges); } }; @@ -517,13 +517,13 @@ public: AddressMatcher* create(const string& criteria) { - return new EndsWithString(criteria); + return new EndsWithString(criteria); } AddressMatcher* create(const vector& ports, const vector& ranges) { - return new EndsWithNumber(ports, ranges); + return new EndsWithNumber(ports, ranges); } }; @@ -534,84 +534,84 @@ class AddressRule : public Glacier2::ProxyRule { public: AddressRule(const CommunicatorPtr& communicator, const vector& address, MatchesNumber* port, - const int traceLevel) : - _communicator(communicator), - _addressRules(address), - _portMatcher(port), - _traceLevel(traceLevel) + const int traceLevel) : + _communicator(communicator), + _addressRules(address), + _portMatcher(port), + _traceLevel(traceLevel) { } ~AddressRule() { - for(vector::const_iterator i = _addressRules.begin(); i != _addressRules.end(); ++i) - { - delete *i; - } - delete _portMatcher; + for(vector::const_iterator i = _addressRules.begin(); i != _addressRules.end(); ++i) + { + delete *i; + } + delete _portMatcher; } virtual bool check(const ObjectPrx& prx) const { - EndpointSeq endpoints = prx->ice_getEndpoints(); - if(endpoints.size() == 0) - { - return false; - } - - for(EndpointSeq::const_iterator i = endpoints.begin(); i != endpoints.end(); ++i) - { - string info = (*i)->toString(); - string host; - if(!extractPart("-h ", info, host)) - { - return false; - } - string port; - if(!extractPart("-p ", info, port)) - { - return false; - } - string::size_type pos = 0; - if(!_portMatcher || _portMatcher->match(port, pos)) - { - pos = 0; - for(vector::const_iterator i = _addressRules.begin(); i != _addressRules.end(); ++i) - { - if(!(*i)->match(host, pos)) - { - if(_traceLevel >= 3) - { - Trace out(_communicator->getLogger(), "Glacier2"); - out << (*i)->toString() << " failed to match " << host << " at pos=" << pos << "\n"; - } - return false; - } - if(_traceLevel >= 3) - { - Trace out(_communicator->getLogger(), "Glacier2"); - out << (*i)->toString() << " matched " << host << " at pos=" << pos << "\n"; - } - } - } - } - return true; + EndpointSeq endpoints = prx->ice_getEndpoints(); + if(endpoints.size() == 0) + { + return false; + } + + for(EndpointSeq::const_iterator i = endpoints.begin(); i != endpoints.end(); ++i) + { + string info = (*i)->toString(); + string host; + if(!extractPart("-h ", info, host)) + { + return false; + } + string port; + if(!extractPart("-p ", info, port)) + { + return false; + } + string::size_type pos = 0; + if(!_portMatcher || _portMatcher->match(port, pos)) + { + pos = 0; + for(vector::const_iterator i = _addressRules.begin(); i != _addressRules.end(); ++i) + { + if(!(*i)->match(host, pos)) + { + if(_traceLevel >= 3) + { + Trace out(_communicator->getLogger(), "Glacier2"); + out << (*i)->toString() << " failed to match " << host << " at pos=" << pos << "\n"; + } + return false; + } + if(_traceLevel >= 3) + { + Trace out(_communicator->getLogger(), "Glacier2"); + out << (*i)->toString() << " matched " << host << " at pos=" << pos << "\n"; + } + } + } + } + return true; } void dump() const { - cerr << "address("; - for(vector::const_iterator i = _addressRules.begin(); i != _addressRules.end(); ++i) - { - cerr << (*i)->toString() << " "; - } - if(_portMatcher != 0) - { - cerr << "):port(" << _portMatcher->toString() << " "; - } - cerr << ")" << endl; + cerr << "address("; + for(vector::const_iterator i = _addressRules.begin(); i != _addressRules.end(); ++i) + { + cerr << (*i)->toString() << " "; + } + if(_portMatcher != 0) + { + cerr << "):port(" << _portMatcher->toString() << " "; + } + cerr << ")" << endl; } private: @@ -619,22 +619,22 @@ private: bool extractPart(const char* opt, const string& source, string& result) const { - string::size_type start = source.find(opt); - if(start == string::npos) - { - return false; - } - start += strlen(opt); - string::size_type end = source.find(' ', start); - if(end != string::npos) - { - result = source.substr(start, end - start); - } - else - { - result = source.substr(start); - } - return true; + string::size_type start = source.find(opt); + if(start == string::npos) + { + return false; + } + start += strlen(opt); + string::size_type end = source.find(' ', start); + if(end != string::npos) + { + result = source.substr(start, end - start); + } + else + { + result = source.substr(start); + } + return true; } CommunicatorPtr _communicator; @@ -645,7 +645,7 @@ private: static void parseProperty(const Ice::CommunicatorPtr& communicator, const string& property, vector& rules, - const int traceLevel) + const int traceLevel) { StartFactory startsWithFactory; WildCardFactory wildCardFactory; @@ -654,165 +654,165 @@ parseProperty(const Ice::CommunicatorPtr& communicator, const string& property, vector allRules; try { - istringstream propertyInput(property); - - while(!propertyInput.eof() && propertyInput.good()) - { - MatchesNumber* portMatch = 0; - vector currentRuleSet; - - string parameter; - ws(propertyInput); - propertyInput >> parameter; - - string portInfo; - string::size_type portPortion = parameter.find(':'); - - string addr; - if(portPortion != string::npos) - { - addr = parameter.substr(0, portPortion); - string port = parameter.substr(portPortion + 1); - string::size_type openBracket = port.find('['); - if(openBracket != string::npos) - { - ++openBracket; - string::size_type closeBracket = port.find(']', openBracket); - if(closeBracket == string::npos) - { - InitializationException ex(__FILE__, __LINE__); - ex.reason = "unclosed group"; - throw ex; - } - port = port.substr(openBracket, closeBracket-openBracket); - } - vector ports; - vector ranges; - parseGroup(port, ports, ranges); - portMatch = new MatchesNumber(ports, ranges); - } - else - { - addr = parameter; - } - - // - // The addr portion can contain alphanumerics, * and - // ranges. - // - string::size_type current = 0; - - if(current == addr.size()) - { - InitializationException ex(__FILE__, __LINE__); - ex.reason = "expected address information before ':'"; - throw ex; - } - - // - // TODO: assuming that there is no leading or trailing whitespace. This - // should probably be confirmed. - // - assert(!isspace(parameter[current])); - assert(!isspace(addr[addr.size() -1])); - - if(current != 0) - { - addr = addr.substr(current); - } - - string::size_type mark = 0; - bool inGroup = false; - AddressMatcherFactory* currentFactory = &startsWithFactory; - - if(addr == "*") - { - // - // Special case. Match everything. - // - currentRuleSet.push_back(new MatchesAny); - } - else - { - for(current = 0; current < addr.size(); ++current) - { - if(addr[current] == '*') - { - if(inGroup) - { - InitializationException ex(__FILE__, __LINE__); - ex.reason = "wildcards not permitted in groups"; - throw ex; - } - // - // current == mark when the wildcard is at the head of a - // string or directly after a group. - // - if(current != mark) - { - currentRuleSet.push_back(currentFactory->create(addr.substr(mark, current-mark))); - } - currentFactory = &wildCardFactory; - mark = current + 1; - } - else if(addr[current] == '[') - { - // ??? what does it mean if current == mark? - if(current != mark) - { - currentRuleSet.push_back(currentFactory->create(addr.substr(mark, current-mark))); - currentFactory = &followingFactory; - } - inGroup = true; - mark = current + 1; - } - else if(addr[current] == ']') - { - if(!inGroup) - { - InitializationException ex(__FILE__, __LINE__); - ex.reason = "group close without group start"; - throw ex; - } - inGroup = false; - if(mark == current) - { - InitializationException ex(__FILE__, __LINE__); - ex.reason = "empty group"; - throw ex; - } - string group = addr.substr(mark, current - mark); - vector numbers; - vector ranges; - parseGroup(group, numbers, ranges); - currentRuleSet.push_back(currentFactory->create(numbers, ranges)); - currentFactory = &followingFactory; - mark = current + 1; - } - } - currentFactory = &endsWithFactory; - - if(inGroup) - { - InitializationException ex(__FILE__, __LINE__); - ex.reason = "unclosed group"; - throw ex; - } - if(mark != current) - { - currentRuleSet.push_back(currentFactory->create(addr.substr(mark, current - mark))); - } - } - allRules.push_back(new AddressRule(communicator, currentRuleSet, portMatch, traceLevel)); - } + istringstream propertyInput(property); + + while(!propertyInput.eof() && propertyInput.good()) + { + MatchesNumber* portMatch = 0; + vector currentRuleSet; + + string parameter; + ws(propertyInput); + propertyInput >> parameter; + + string portInfo; + string::size_type portPortion = parameter.find(':'); + + string addr; + if(portPortion != string::npos) + { + addr = parameter.substr(0, portPortion); + string port = parameter.substr(portPortion + 1); + string::size_type openBracket = port.find('['); + if(openBracket != string::npos) + { + ++openBracket; + string::size_type closeBracket = port.find(']', openBracket); + if(closeBracket == string::npos) + { + InitializationException ex(__FILE__, __LINE__); + ex.reason = "unclosed group"; + throw ex; + } + port = port.substr(openBracket, closeBracket-openBracket); + } + vector ports; + vector ranges; + parseGroup(port, ports, ranges); + portMatch = new MatchesNumber(ports, ranges); + } + else + { + addr = parameter; + } + + // + // The addr portion can contain alphanumerics, * and + // ranges. + // + string::size_type current = 0; + + if(current == addr.size()) + { + InitializationException ex(__FILE__, __LINE__); + ex.reason = "expected address information before ':'"; + throw ex; + } + + // + // TODO: assuming that there is no leading or trailing whitespace. This + // should probably be confirmed. + // + assert(!isspace(parameter[current])); + assert(!isspace(addr[addr.size() -1])); + + if(current != 0) + { + addr = addr.substr(current); + } + + string::size_type mark = 0; + bool inGroup = false; + AddressMatcherFactory* currentFactory = &startsWithFactory; + + if(addr == "*") + { + // + // Special case. Match everything. + // + currentRuleSet.push_back(new MatchesAny); + } + else + { + for(current = 0; current < addr.size(); ++current) + { + if(addr[current] == '*') + { + if(inGroup) + { + InitializationException ex(__FILE__, __LINE__); + ex.reason = "wildcards not permitted in groups"; + throw ex; + } + // + // current == mark when the wildcard is at the head of a + // string or directly after a group. + // + if(current != mark) + { + currentRuleSet.push_back(currentFactory->create(addr.substr(mark, current-mark))); + } + currentFactory = &wildCardFactory; + mark = current + 1; + } + else if(addr[current] == '[') + { + // ??? what does it mean if current == mark? + if(current != mark) + { + currentRuleSet.push_back(currentFactory->create(addr.substr(mark, current-mark))); + currentFactory = &followingFactory; + } + inGroup = true; + mark = current + 1; + } + else if(addr[current] == ']') + { + if(!inGroup) + { + InitializationException ex(__FILE__, __LINE__); + ex.reason = "group close without group start"; + throw ex; + } + inGroup = false; + if(mark == current) + { + InitializationException ex(__FILE__, __LINE__); + ex.reason = "empty group"; + throw ex; + } + string group = addr.substr(mark, current - mark); + vector numbers; + vector ranges; + parseGroup(group, numbers, ranges); + currentRuleSet.push_back(currentFactory->create(numbers, ranges)); + currentFactory = &followingFactory; + mark = current + 1; + } + } + currentFactory = &endsWithFactory; + + if(inGroup) + { + InitializationException ex(__FILE__, __LINE__); + ex.reason = "unclosed group"; + throw ex; + } + if(mark != current) + { + currentRuleSet.push_back(currentFactory->create(addr.substr(mark, current - mark))); + } + } + allRules.push_back(new AddressRule(communicator, currentRuleSet, portMatch, traceLevel)); + } } catch(...) { - for(vector::const_iterator i = allRules.begin(); i != allRules.end(); ++i) - { - delete *i; - } - throw; + for(vector::const_iterator i = allRules.begin(); i != allRules.end(); ++i) + { + delete *i; + } + throw; } rules = allRules; } @@ -825,10 +825,10 @@ match(const vector& rules, const ObjectPrx& proxy) { for(vector::const_iterator i = rules.begin(); i != rules.end(); ++i) { - if((*i)->check(proxy)) - { - return true; - } + if((*i)->check(proxy)) + { + return true; + } } return false; } @@ -841,36 +841,36 @@ class ProxyLengthRule : public ProxyRule { public: ProxyLengthRule(const CommunicatorPtr communicator, const string& count, int traceLevel) : - _communicator(communicator), - _traceLevel(traceLevel) - { - istringstream s(count); - if(!(s >> _count) || !s.eof()) - { - InitializationException ex(__FILE__, __LINE__); - ex.reason = "Error parsing ProxySizeMax property"; - throw ex; - } - if(_count <= 0) - { - InitializationException ex(__FILE__, __LINE__); - ex.reason = "ProxySizeMax must be greater than 1"; - throw ex; - } + _communicator(communicator), + _traceLevel(traceLevel) + { + istringstream s(count); + if(!(s >> _count) || !s.eof()) + { + InitializationException ex(__FILE__, __LINE__); + ex.reason = "Error parsing ProxySizeMax property"; + throw ex; + } + if(_count <= 0) + { + InitializationException ex(__FILE__, __LINE__); + ex.reason = "ProxySizeMax must be greater than 1"; + throw ex; + } } bool check(const ObjectPrx& p) const { - string s = p->ice_toString(); - bool result = (s.size() > _count); - if(_traceLevel >= 1) - { - Trace out(_communicator->getLogger(), "Glacier2"); - out << _communicator->proxyToString(p) << (result ? " exceeds " : " meets ") - << "proxy size restriction\n"; - } - return result; + string s = p->ice_toString(); + bool result = (s.size() > _count); + if(_traceLevel >= 1) + { + Trace out(_communicator->getLogger(), "Glacier2"); + out << _communicator->proxyToString(p) << (result ? " exceeds " : " meets ") + << "proxy size restriction\n"; + } + return result; } private: @@ -892,19 +892,19 @@ Glacier2::ProxyVerifier::ProxyVerifier(const CommunicatorPtr& communicator, cons string s = communicator->getProperties()->getProperty("Glacier2.Filter.Address.Accept"); if(s != "") { - Glacier2::parseProperty(communicator, s, _acceptRules, _traceLevel); + Glacier2::parseProperty(communicator, s, _acceptRules, _traceLevel); } s = communicator->getProperties()->getProperty("Glacier2.Filter.Address.Reject"); if(s != "") { - Glacier2::parseProperty(communicator, s, _rejectRules, _traceLevel); + Glacier2::parseProperty(communicator, s, _rejectRules, _traceLevel); } s = communicator->getProperties()->getProperty("Glacier2.Filter.ProxySizeMax"); if(s != "") { - _rejectRules.push_back(new ProxyLengthRule(communicator, s, _traceLevel)); + _rejectRules.push_back(new ProxyLengthRule(communicator, s, _traceLevel)); } } @@ -912,11 +912,11 @@ Glacier2::ProxyVerifier::~ProxyVerifier() { for(vector::const_iterator i = _acceptRules.begin(); i != _acceptRules.end(); ++i) { - delete (*i); + delete (*i); } for(vector::const_iterator j = _rejectRules.begin(); j != _rejectRules.end(); ++j) { - delete (*j); + delete (*j); } } @@ -928,31 +928,31 @@ Glacier2::ProxyVerifier::verify(const ObjectPrx& proxy) // if(_acceptRules.size() == 0 && _rejectRules.size() == 0) { - return true; + return true; } bool result = false; if(_rejectRules.size() == 0) { - // - // If there are no reject rules, we assume "reject all". - // - result = match(_acceptRules, proxy); + // + // If there are no reject rules, we assume "reject all". + // + result = match(_acceptRules, proxy); } else if(_acceptRules.size() == 0) { - // - // If no accept rules are defined we assume accept all. - // - result = !match(_rejectRules, proxy); + // + // If no accept rules are defined we assume accept all. + // + result = !match(_rejectRules, proxy); } else { - if(match(_acceptRules, proxy)) - { - result = !match(_rejectRules, proxy); - } + if(match(_acceptRules, proxy)) + { + result = !match(_rejectRules, proxy); + } } // @@ -960,15 +960,15 @@ Glacier2::ProxyVerifier::verify(const ObjectPrx& proxy) // if(_traceLevel > 0) { - Trace out(_communicator->getLogger(), "Glacier2"); - if(result) - { - out << "accepted proxy " << _communicator->proxyToString(proxy) << '\n'; - } - else - { - out << "rejected proxy " << _communicator->proxyToString(proxy) << '\n'; - } + Trace out(_communicator->getLogger(), "Glacier2"); + if(result) + { + out << "accepted proxy " << _communicator->proxyToString(proxy) << '\n'; + } + else + { + out << "rejected proxy " << _communicator->proxyToString(proxy) << '\n'; + } } return result; } diff --git a/cpp/src/Glacier2/RequestQueue.cpp b/cpp/src/Glacier2/RequestQueue.cpp index 55f700a0d65..099b73f3640 100644 --- a/cpp/src/Glacier2/RequestQueue.cpp +++ b/cpp/src/Glacier2/RequestQueue.cpp @@ -30,22 +30,22 @@ class AMI_Array_Object_ice_invokeI : public AMI_Array_Object_ice_invoke public: AMI_Array_Object_ice_invokeI(const RequestQueuePtr& requestQueue, const AMD_Array_Object_ice_invokePtr& amdCB) : - _requestQueue(requestQueue), - _amdCB(amdCB) + _requestQueue(requestQueue), + _amdCB(amdCB) { - assert(_amdCB); + assert(_amdCB); } virtual void ice_response(bool ok, const pair& outParams) { - _requestQueue->addResponse(new Response(_amdCB, ok, outParams)); + _requestQueue->addResponse(new Response(_amdCB, ok, outParams)); } virtual void ice_exception(const Exception& ex) { - _requestQueue->addResponse(new Response(_amdCB, ex)); + _requestQueue->addResponse(new Response(_amdCB, ex)); } private: @@ -57,8 +57,8 @@ private: } Glacier2::Request::Request(const ObjectPrx& proxy, const std::pair& inParams, - const Current& current, bool forwardContext, const Ice::Context& sslContext, - const AMD_Array_Object_ice_invokePtr& amdCB) : + const Current& current, bool forwardContext, const Ice::Context& sslContext, + const AMD_Array_Object_ice_invokePtr& amdCB) : _proxy(proxy), _inParams(inParams.first, inParams.second), _current(current), @@ -72,15 +72,15 @@ Glacier2::Request::Request(const ObjectPrx& proxy, const std::pairice_isTwoway()) { - bool ok = true; - pair outParams(0, 0); - _amdCB->ice_response(ok, outParams); + bool ok = true; + pair outParams(0, 0); + _amdCB->ice_response(ok, outParams); } Context::const_iterator p = current.ctx.find("_ovrd"); if(p != current.ctx.end()) { - const_cast(_override) = p->second; + const_cast(_override) = p->second; } } @@ -96,71 +96,71 @@ Glacier2::Request::invoke(const RequestQueuePtr& requestQueue) else { inPair.first = &_inParams[0]; - inPair.second = inPair.first + _inParams.size(); + inPair.second = inPair.first + _inParams.size(); } if(_proxy->ice_isTwoway()) { - AMI_Array_Object_ice_invokePtr cb = new AMI_Array_Object_ice_invokeI(requestQueue, _amdCB); - if(_forwardContext) - { - if(_sslContext.size() > 0) - { - Ice::Context ctx = _current.ctx; - ctx.insert(_sslContext.begin(), _sslContext.end()); - _proxy->ice_invoke_async(cb, _current.operation, _current.mode, inPair, ctx); - } - else - { - _proxy->ice_invoke_async(cb, _current.operation, _current.mode, inPair, _current.ctx); - } - } - else - { - if(_sslContext.size() > 0) - { - _proxy->ice_invoke_async(cb, _current.operation, _current.mode, inPair, _sslContext); - } - else - { - _proxy->ice_invoke_async(cb, _current.operation, _current.mode, inPair); - } - } - return true; // A twoway method is being dispatched. + AMI_Array_Object_ice_invokePtr cb = new AMI_Array_Object_ice_invokeI(requestQueue, _amdCB); + if(_forwardContext) + { + if(_sslContext.size() > 0) + { + Ice::Context ctx = _current.ctx; + ctx.insert(_sslContext.begin(), _sslContext.end()); + _proxy->ice_invoke_async(cb, _current.operation, _current.mode, inPair, ctx); + } + else + { + _proxy->ice_invoke_async(cb, _current.operation, _current.mode, inPair, _current.ctx); + } + } + else + { + if(_sslContext.size() > 0) + { + _proxy->ice_invoke_async(cb, _current.operation, _current.mode, inPair, _sslContext); + } + else + { + _proxy->ice_invoke_async(cb, _current.operation, _current.mode, inPair); + } + } + return true; // A twoway method is being dispatched. } else { - try - { - ByteSeq outParams; - if(_forwardContext) - { - if(_sslContext.size() > 0) - { - Ice::Context ctx = _current.ctx; - ctx.insert(_sslContext.begin(), _sslContext.end()); - _proxy->ice_invoke(_current.operation, _current.mode, inPair, outParams, ctx); - } - else - { - _proxy->ice_invoke(_current.operation, _current.mode, inPair, outParams, _current.ctx); - } - } - else - { - if(_sslContext.size() > 0) - { - _proxy->ice_invoke(_current.operation, _current.mode, inPair, outParams, _sslContext); - } - else - { - _proxy->ice_invoke(_current.operation, _current.mode, inPair, outParams); - } - } - } - catch(const LocalException&) - { - } - return false; + try + { + ByteSeq outParams; + if(_forwardContext) + { + if(_sslContext.size() > 0) + { + Ice::Context ctx = _current.ctx; + ctx.insert(_sslContext.begin(), _sslContext.end()); + _proxy->ice_invoke(_current.operation, _current.mode, inPair, outParams, ctx); + } + else + { + _proxy->ice_invoke(_current.operation, _current.mode, inPair, outParams, _current.ctx); + } + } + else + { + if(_sslContext.size() > 0) + { + _proxy->ice_invoke(_current.operation, _current.mode, inPair, outParams, _sslContext); + } + else + { + _proxy->ice_invoke(_current.operation, _current.mode, inPair, outParams); + } + } + } + catch(const LocalException&) + { + } + return false; } } @@ -172,7 +172,7 @@ Glacier2::Request::override(const RequestPtr& other) const // if(_override.empty() || other->_override.empty()) { - return false; + return false; } // @@ -181,7 +181,7 @@ Glacier2::Request::override(const RequestPtr& other) const // if(_proxy->ice_isTwoway() || other->_proxy->ice_isTwoway()) { - return false; + return false; } // @@ -189,7 +189,7 @@ Glacier2::Request::override(const RequestPtr& other) const // if(_proxy != other->_proxy) { - return false; + return false; } return _override == other->_override; @@ -208,7 +208,7 @@ Glacier2::Request::getConnection() const } Glacier2::Response::Response(const AMD_Array_Object_ice_invokePtr& amdCB, bool ok, - const pair& outParams) : + const pair& outParams) : _amdCB(amdCB), _ok(ok), _outParams(outParams.first, outParams.second) @@ -227,21 +227,21 @@ Glacier2::Response::invoke() { if(_exception.get()) { - _amdCB->ice_exception(*_exception.get()); + _amdCB->ice_exception(*_exception.get()); } else { pair outPair; - if(_outParams.size() == 0) - { - outPair.first = outPair.second = 0; - } - else - { - outPair.first = &_outParams[0]; - outPair.second = outPair.first + _outParams.size(); - } - _amdCB->ice_response(_ok, outPair); + if(_outParams.size() == 0) + { + outPair.first = outPair.second = 0; + } + else + { + outPair.first = &_outParams[0]; + outPair.second = outPair.first + _outParams.size(); + } + _amdCB->ice_response(_ok, outPair); } } @@ -265,12 +265,12 @@ void Glacier2::RequestQueue::destroy() { { - IceUtil::Monitor::Lock lock(*this); - - assert(!_destroy); - _destroy = true; - _sleep = false; - notify(); + IceUtil::Monitor::Lock lock(*this); + + assert(!_destroy); + _destroy = true; + _sleep = false; + notify(); } // @@ -295,14 +295,14 @@ Glacier2::RequestQueue::addRequest(const RequestPtr& request) for(vector::iterator p = _requests.begin(); p != _requests.end(); ++p) { - // + // // If the new request overrides an old one, then abort the old // request and replace it with the new request. - // + // if(request->override(*p)) { *p = request; - return true; + return true; } } @@ -312,11 +312,11 @@ Glacier2::RequestQueue::addRequest(const RequestPtr& request) _requests.push_back(request); if(!_sleep) { - // - // No need to notify if the request queue thread is sleeping, - // once it wakes up it will check if there's requests to send. - // - notify(); + // + // No need to notify if the request queue thread is sleeping, + // once it wakes up it will check if there's requests to send. + // + notify(); } return false; } @@ -336,73 +336,73 @@ Glacier2::RequestQueue::run() ptrdiff_t dispatchCount = 0; // The dispatch count keeps track of the number of outstanding twoway requests. while(true) { - vector requests; - vector responses; + vector requests; + vector responses; { IceUtil::Monitor::Lock lock(*this); - // - // Wait indefinitely if there's no requests/responses to - // send. If the queue is being destroyed we still need to - // wait until all the responses for twoway requests are - // received. - // + // + // Wait indefinitely if there's no requests/responses to + // send. If the queue is being destroyed we still need to + // wait until all the responses for twoway requests are + // received. + // while((!_destroy || dispatchCount != 0) && _responses.empty() && (_requests.empty() || _sleep)) { - if(_sleep) - { - IceUtil::Time now = IceUtil::Time::now(); - if(!timedWait(_sleepDuration)) - { - _sleepDuration = IceUtil::Time(); - } - else - { - _sleepDuration -= IceUtil::Time::now() - now; - } - if(_sleepDuration <= IceUtil::Time()) - { - _sleep = false; - } - } - else - { - wait(); - } + if(_sleep) + { + IceUtil::Time now = IceUtil::Time::now(); + if(!timedWait(_sleepDuration)) + { + _sleepDuration = IceUtil::Time(); + } + else + { + _sleepDuration -= IceUtil::Time::now() - now; + } + if(_sleepDuration <= IceUtil::Time()) + { + _sleep = false; + } + } + else + { + wait(); + } } - // - // If the queue is being destroyed and there's no requests - // or responses to send, we're done. - // + // + // If the queue is being destroyed and there's no requests + // or responses to send, we're done. + // if(_destroy && _requests.empty() && _responses.empty()) { - assert(dispatchCount == 0); // We would have blocked in the wait() above otherwise. + assert(dispatchCount == 0); // We would have blocked in the wait() above otherwise. return; } - // - // If there's requests to sent and we're not sleeping, - // send the requests. If a sleep time is configured, we - // set the sleep duration and set the sleep flag to make - // sure we'll sleep again once we're done sending requests - // and responses. - // - if(!_requests.empty() && !_sleep) - { - requests.swap(_requests); - if(_sleepTime > IceUtil::Time()) - { - _sleep = true; - _sleepDuration = _sleepTime; - } - } - if(!_responses.empty()) - { - responses.swap(_responses); - } - } + // + // If there's requests to sent and we're not sleeping, + // send the requests. If a sleep time is configured, we + // set the sleep duration and set the sleep flag to make + // sure we'll sleep again once we're done sending requests + // and responses. + // + if(!_requests.empty() && !_sleep) + { + requests.swap(_requests); + if(_sleepTime > IceUtil::Time()) + { + _sleep = true; + _sleepDuration = _sleepTime; + } + } + if(!_responses.empty()) + { + responses.swap(_responses); + } + } // // Send requests, flush batch requests, and sleep outside the @@ -410,53 +410,53 @@ Glacier2::RequestQueue::run() // while this is being done. // - set flushSet; - - for(vector::const_iterator p = requests.begin(); p != requests.end(); ++p) - { - if((*p)->isBatch()) - { - try - { - flushSet.insert((*p)->getConnection()); - } - catch(const LocalException&) - { - // Ignore. - } - } - - // - // Invoke returns true if the request expects a response. - // If that's the case we increment the dispatch count to - // ensure that the thread won't be destroyed before the - // response is received. - // - if((*p)->invoke(self)) // Exceptions are caught within invoke(). - { - ++dispatchCount; - } - } - - for(set::const_iterator q = flushSet.begin(); q != flushSet.end(); ++q) - { - try - { - (*q)->flushBatchRequests(); - } - catch(const LocalException&) - { - // Ignore. - } - } - - // - // Send the responses and decrement the dispatch count. - // - for(vector::const_iterator r = responses.begin(); r != responses.end(); ++r) - { - (*r)->invoke(); - } - dispatchCount -= responses.size(); + set flushSet; + + for(vector::const_iterator p = requests.begin(); p != requests.end(); ++p) + { + if((*p)->isBatch()) + { + try + { + flushSet.insert((*p)->getConnection()); + } + catch(const LocalException&) + { + // Ignore. + } + } + + // + // Invoke returns true if the request expects a response. + // If that's the case we increment the dispatch count to + // ensure that the thread won't be destroyed before the + // response is received. + // + if((*p)->invoke(self)) // Exceptions are caught within invoke(). + { + ++dispatchCount; + } + } + + for(set::const_iterator q = flushSet.begin(); q != flushSet.end(); ++q) + { + try + { + (*q)->flushBatchRequests(); + } + catch(const LocalException&) + { + // Ignore. + } + } + + // + // Send the responses and decrement the dispatch count. + // + for(vector::const_iterator r = responses.begin(); r != responses.end(); ++r) + { + (*r)->invoke(); + } + dispatchCount -= responses.size(); } } diff --git a/cpp/src/Glacier2/RequestQueue.h b/cpp/src/Glacier2/RequestQueue.h index 7a9e4db280d..2599b24f7aa 100644 --- a/cpp/src/Glacier2/RequestQueue.h +++ b/cpp/src/Glacier2/RequestQueue.h @@ -28,7 +28,7 @@ class Request : public IceUtil::Shared public: Request(const Ice::ObjectPrx&, const std::pair&, const Ice::Current&, bool, - const Ice::Context&, const Ice::AMD_Array_Object_ice_invokePtr&); + const Ice::Context&, const Ice::AMD_Array_Object_ice_invokePtr&); bool invoke(const RequestQueuePtr&); bool override(const RequestPtr&) const; diff --git a/cpp/src/Glacier2/RouterI.cpp b/cpp/src/Glacier2/RouterI.cpp index c3f34f4c4d6..ff917e8b445 100644 --- a/cpp/src/Glacier2/RouterI.cpp +++ b/cpp/src/Glacier2/RouterI.cpp @@ -19,9 +19,9 @@ using namespace Ice; using namespace Glacier2; Glacier2::RouterI::RouterI(const ObjectAdapterPtr& clientAdapter, const ObjectAdapterPtr& serverAdapter, - const ConnectionPtr& connection, const string& userId, const SessionPrx& session, - const Identity& controlId, const FilterManagerPtr& filters, - const Ice::Context& sslContext) : + const ConnectionPtr& connection, const string& userId, const SessionPrx& session, + const Identity& controlId, const FilterManagerPtr& filters, + const Ice::Context& sslContext) : _communicator(clientAdapter->getCommunicator()), _clientBlobject(new ClientBlobject(_communicator, filters, sslContext)), _serverAdapter(serverAdapter), @@ -39,26 +39,26 @@ Glacier2::RouterI::RouterI(const ObjectAdapterPtr& clientAdapter, const ObjectAd if(_communicator->getProperties()->getPropertyAsInt("Glacier2.ReturnClientProxy") > 0) { const_cast(_clientProxy) = - clientAdapter->createProxy(_communicator->stringToIdentity("dummy")); + clientAdapter->createProxy(_communicator->stringToIdentity("dummy")); } if(serverAdapter) { - ObjectPrx& serverProxy = const_cast(_serverProxy); - Identity ident; - ident.name = "dummy"; - ident.category.resize(20); - char buf[20]; - IceUtil::generateRandom(buf, static_cast(sizeof(buf))); - for(unsigned int i = 0; i < sizeof(buf); ++i) - { - const unsigned char c = static_cast(buf[i]); // A value between 0-255 - ident.category[i] = 33 + c % (127-33); // We use ASCII 33-126 (from ! to ~, w/o space). - } - serverProxy = serverAdapter->createProxy(ident); - - ServerBlobjectPtr& serverBlobject = const_cast(_serverBlobject); - serverBlobject = new ServerBlobject(_communicator, _connection); + ObjectPrx& serverProxy = const_cast(_serverProxy); + Identity ident; + ident.name = "dummy"; + ident.category.resize(20); + char buf[20]; + IceUtil::generateRandom(buf, static_cast(sizeof(buf))); + for(unsigned int i = 0; i < sizeof(buf); ++i) + { + const unsigned char c = static_cast(buf[i]); // A value between 0-255 + ident.category[i] = 33 + c % (127-33); // We use ASCII 33-126 (from ! to ~, w/o space). + } + serverProxy = serverAdapter->createProxy(ident); + + ServerBlobjectPtr& serverBlobject = const_cast(_serverBlobject); + serverBlobject = new ServerBlobject(_communicator, _connection); } } @@ -75,43 +75,43 @@ Glacier2::RouterI::destroy() if(_serverBlobject) { - _serverBlobject->destroy(); + _serverBlobject->destroy(); } if(_session) { if(_serverAdapter) - { - try - { - // - // Remove the session control object. - // - _serverAdapter->remove(_controlId); - } - catch(const NotRegisteredException&) - { - } - catch(const ObjectAdapterDeactivatedException&) - { - // - // Expected if the router has been shutdown. - // - } - } - - // - // This can raise an exception, therefore it must be the last - // statement in this destroy() function. - // - if(_sslContext.size() > 0) - { - _session->destroy(_sslContext); - } - else - { - _session->destroy(); - } + { + try + { + // + // Remove the session control object. + // + _serverAdapter->remove(_controlId); + } + catch(const NotRegisteredException&) + { + } + catch(const ObjectAdapterDeactivatedException&) + { + // + // Expected if the router has been shutdown. + // + } + } + + // + // This can raise an exception, therefore it must be the last + // statement in this destroy() function. + // + if(_sslContext.size() > 0) + { + _session->destroy(_sslContext); + } + else + { + _session->destroy(); + } } } @@ -231,7 +231,7 @@ Glacier2::RouterI::toString() const out << "id = " << _userId << '\n'; if(_serverProxy) { - out << "category = " << _serverProxy->ice_getIdentity().category << '\n'; + out << "category = " << _serverProxy->ice_getIdentity().category << '\n'; } out << _connection->toString(); diff --git a/cpp/src/Glacier2/RouterI.h b/cpp/src/Glacier2/RouterI.h index c046413c7c3..64bccd5d50c 100644 --- a/cpp/src/Glacier2/RouterI.h +++ b/cpp/src/Glacier2/RouterI.h @@ -31,7 +31,7 @@ public: RouterI(const Ice::ObjectAdapterPtr&, const Ice::ObjectAdapterPtr&, const Ice::ConnectionPtr&, const std::string&, const SessionPrx&, const Ice::Identity&, const FilterManagerPtr&, const Ice::Context& sslContext); - + virtual ~RouterI(); void destroy(); diff --git a/cpp/src/Glacier2/RoutingTable.cpp b/cpp/src/Glacier2/RoutingTable.cpp index 6a366130837..b5f73e7ed10 100644 --- a/cpp/src/Glacier2/RoutingTable.cpp +++ b/cpp/src/Glacier2/RoutingTable.cpp @@ -35,69 +35,69 @@ Glacier2::RoutingTable::add(const ObjectProxySeq& unfiltered, const Ice::Current ObjectProxySeq::const_iterator prx; for(prx = unfiltered.begin(); prx != unfiltered.end(); ++prx) { - if(!*prx) // We ignore null proxies. - { - continue; - } + if(!*prx) // We ignore null proxies. + { + continue; + } - if(!_verifier.verify(*prx)) - { - current.con->close(true); - throw ObjectNotExistException(__FILE__, __LINE__); - } - ObjectPrx proxy = (*prx)->ice_twoway()->ice_secure(false)->ice_facet(""); // We add proxies in default form. - proxies.push_back(proxy); + if(!_verifier.verify(*prx)) + { + current.con->close(true); + throw ObjectNotExistException(__FILE__, __LINE__); + } + ObjectPrx proxy = (*prx)->ice_twoway()->ice_secure(false)->ice_facet(""); // We add proxies in default form. + proxies.push_back(proxy); } ObjectProxySeq evictedProxies; for(prx = proxies.begin(); prx != proxies.end(); ++prx) { - ObjectPrx proxy = *prx; - EvictorMap::iterator p = _map.find(proxy->ice_getIdentity()); - - if(p == _map.end()) - { - if(_traceLevel == 1 || _traceLevel >= 3) - { - Trace out(_communicator->getLogger(), "Glacier2"); - out << "adding proxy to routing table:\n" << _communicator->proxyToString(proxy); - } - - EvictorEntryPtr entry = new EvictorEntry; - p = _map.insert(_map.begin(), pair(proxy->ice_getIdentity(), entry)); - EvictorQueue::iterator q = _queue.insert(_queue.end(), p); - entry->proxy = proxy; - entry->pos = q; - } - else - { - if(_traceLevel == 1 || _traceLevel >= 3) - { - Trace out(_communicator->getLogger(), "Glacier2"); - out << "proxy already in routing table:\n" << _communicator->proxyToString(proxy); - } - - EvictorEntryPtr entry = p->second; - _queue.erase(entry->pos); - EvictorQueue::iterator q = _queue.insert(_queue.end(), p); - entry->pos = q; - } - - while(static_cast(_map.size()) > _maxSize) - { - p = _queue.front(); - - if(_traceLevel >= 2) - { - Trace out(_communicator->getLogger(), "Glacier2"); - out << "evicting proxy from routing table:\n" << _communicator->proxyToString(p->second->proxy); - } - - evictedProxies.push_back(p->second->proxy); + ObjectPrx proxy = *prx; + EvictorMap::iterator p = _map.find(proxy->ice_getIdentity()); + + if(p == _map.end()) + { + if(_traceLevel == 1 || _traceLevel >= 3) + { + Trace out(_communicator->getLogger(), "Glacier2"); + out << "adding proxy to routing table:\n" << _communicator->proxyToString(proxy); + } + + EvictorEntryPtr entry = new EvictorEntry; + p = _map.insert(_map.begin(), pair(proxy->ice_getIdentity(), entry)); + EvictorQueue::iterator q = _queue.insert(_queue.end(), p); + entry->proxy = proxy; + entry->pos = q; + } + else + { + if(_traceLevel == 1 || _traceLevel >= 3) + { + Trace out(_communicator->getLogger(), "Glacier2"); + out << "proxy already in routing table:\n" << _communicator->proxyToString(proxy); + } + + EvictorEntryPtr entry = p->second; + _queue.erase(entry->pos); + EvictorQueue::iterator q = _queue.insert(_queue.end(), p); + entry->pos = q; + } + + while(static_cast(_map.size()) > _maxSize) + { + p = _queue.front(); + + if(_traceLevel >= 2) + { + Trace out(_communicator->getLogger(), "Glacier2"); + out << "evicting proxy from routing table:\n" << _communicator->proxyToString(p->second->proxy); + } + + evictedProxies.push_back(p->second->proxy); - _map.erase(p); - _queue.pop_front(); - } + _map.erase(p); + _queue.pop_front(); + } } return evictedProxies; @@ -108,7 +108,7 @@ Glacier2::RoutingTable::get(const Identity& ident) { if(ident.name.empty()) { - return 0; + return 0; } IceUtil::Mutex::Lock sync(*this); @@ -117,15 +117,15 @@ Glacier2::RoutingTable::get(const Identity& ident) if(p == _map.end()) { - return 0; + return 0; } else { - EvictorEntryPtr entry = p->second; - _queue.erase(entry->pos); - EvictorQueue::iterator q = _queue.insert(_queue.end(), p); - entry->pos = q; + EvictorEntryPtr entry = p->second; + _queue.erase(entry->pos); + EvictorQueue::iterator q = _queue.insert(_queue.end(), p); + entry->pos = q; - return entry->proxy; + return entry->proxy; } } diff --git a/cpp/src/Glacier2/RoutingTable.h b/cpp/src/Glacier2/RoutingTable.h index 59c82eb9ff1..140ac29fd42 100644 --- a/cpp/src/Glacier2/RoutingTable.h +++ b/cpp/src/Glacier2/RoutingTable.h @@ -45,8 +45,8 @@ private: friend struct EvictorEntry; struct EvictorEntry : public IceUtil::Shared { - Ice::ObjectPrx proxy; - EvictorQueue::iterator pos; + Ice::ObjectPrx proxy; + EvictorQueue::iterator pos; }; EvictorMap _map; diff --git a/cpp/src/Glacier2/ServerBlobject.cpp b/cpp/src/Glacier2/ServerBlobject.cpp index 2942f2df17e..aafc1c8429f 100644 --- a/cpp/src/Glacier2/ServerBlobject.cpp +++ b/cpp/src/Glacier2/ServerBlobject.cpp @@ -25,8 +25,8 @@ Glacier2::ServerBlobject::~ServerBlobject() void Glacier2::ServerBlobject::ice_invoke_async(const Ice::AMD_Array_Object_ice_invokePtr& amdCB, - const std::pair& inParams, - const Current& current) + const std::pair& inParams, + const Current& current) { ObjectPrx proxy = _connection->createProxy(current.id); assert(proxy); diff --git a/cpp/src/Glacier2/ServerBlobject.h b/cpp/src/Glacier2/ServerBlobject.h index 965341a9f1f..200a951cc59 100644 --- a/cpp/src/Glacier2/ServerBlobject.h +++ b/cpp/src/Glacier2/ServerBlobject.h @@ -26,7 +26,7 @@ public: virtual ~ServerBlobject(); virtual void ice_invoke_async(const Ice::AMD_Array_Object_ice_invokePtr&, - const std::pair&, const Ice::Current&); + const std::pair&, const Ice::Current&); private: diff --git a/cpp/src/Glacier2/SessionRouterI.cpp b/cpp/src/Glacier2/SessionRouterI.cpp index 2052f7cfd45..a095748b52d 100644 --- a/cpp/src/Glacier2/SessionRouterI.cpp +++ b/cpp/src/Glacier2/SessionRouterI.cpp @@ -29,43 +29,43 @@ class SessionControlI : public SessionControl public: SessionControlI(const SessionRouterIPtr& sessionRouter, const ConnectionPtr& connection, - const FilterManagerPtr& filterManager, IceUtil::Time timeout) : + const FilterManagerPtr& filterManager, IceUtil::Time timeout) : _sessionRouter(sessionRouter), - _connection(connection), - _filters(filterManager), - _timeout(static_cast(timeout.toSeconds())) + _connection(connection), + _filters(filterManager), + _timeout(static_cast(timeout.toSeconds())) { } virtual StringSetPrx categories(const Current&) { - return _filters->categoriesPrx(); + return _filters->categoriesPrx(); } virtual StringSetPrx adapterIds(const Current&) { - return _filters->adapterIdsPrx(); + return _filters->adapterIdsPrx(); } virtual IdentitySetPrx identities(const Current&) { - return _filters->identitiesPrx(); + return _filters->identitiesPrx(); } virtual int getSessionTimeout(const Current&) { - return _timeout; + return _timeout; } virtual void destroy(const Current&) { _sessionRouter->destroySession(_connection); - _filters->destroy(); + _filters->destroy(); } private: @@ -81,14 +81,14 @@ class ClientLocator : public ServantLocator public: ClientLocator(const SessionRouterIPtr& sessionRouter) : - _sessionRouter(sessionRouter) + _sessionRouter(sessionRouter) { } virtual ObjectPtr locate(const Current& current, LocalObjectPtr&) { - return _sessionRouter->getRouter(current.con, current.id)->getClientBlobject(); + return _sessionRouter->getRouter(current.con, current.id)->getClientBlobject(); } virtual void @@ -111,14 +111,14 @@ class ServerLocator : public ServantLocator public: ServerLocator(const SessionRouterIPtr& sessionRouter) : - _sessionRouter(sessionRouter) + _sessionRouter(sessionRouter) { } virtual ObjectPtr locate(const Current& current, LocalObjectPtr&) { - return _sessionRouter->getRouter(current.id.category)->getServerBlobject(); + return _sessionRouter->getRouter(current.id.category)->getServerBlobject(); } virtual void @@ -141,19 +141,19 @@ class UserPasswordAuthorizer : public Authorizer public: UserPasswordAuthorizer(const PermissionsVerifierPrx& verifier, const string& user, const string& password) : - _verifier(verifier), _user(user), _password(password) + _verifier(verifier), _user(user), _password(password) { } virtual bool authorize(string& reason, const Ice::Context& ctx) { - if(_verifier) - { - return _verifier->checkPermissions(_user, _password, reason, ctx); - } - reason = "No PermissionsVerifier is available"; - return false; + if(_verifier) + { + return _verifier->checkPermissions(_user, _password, reason, ctx); + } + reason = "No PermissionsVerifier is available"; + return false; } private: @@ -168,20 +168,20 @@ class SSLPasswordAuthorizer : public Authorizer public: SSLPasswordAuthorizer(const SSLPermissionsVerifierPrx& verifier, const SSLInfo& info) : - _verifier(verifier), _info(info) + _verifier(verifier), _info(info) { } virtual bool authorize(string& reason, const Ice::Context& ctx) { - if(_verifier) - { - return _verifier->authorize(_info, reason, ctx); - } + if(_verifier) + { + return _verifier->authorize(_info, reason, ctx); + } - reason = "No SSLPermissionsVerifier is available"; - return false; + reason = "No SSLPermissionsVerifier is available"; + return false; } private: @@ -195,14 +195,14 @@ class UserSessionFactory : public SessionFactory public: UserSessionFactory(const SessionManagerPrx& manager, const string& user) : - _manager(manager), _user(user) + _manager(manager), _user(user) { } virtual SessionPrx create(const SessionControlPrx& control, const Ice::Context& ctx) { - return _manager->create(_user, control, ctx); + return _manager->create(_user, control, ctx); } private: @@ -216,14 +216,14 @@ class SSLSessionFactory : public SessionFactory public: SSLSessionFactory(const SSLSessionManagerPrx& manager, const SSLInfo& info) : - _manager(manager), _info(info) + _manager(manager), _info(info) { } virtual SessionPrx create(const SessionControlPrx& control, const Ice::Context& ctx) { - return _manager->create(_info, control, ctx); + return _manager->create(_info, control, ctx); } private: @@ -237,11 +237,11 @@ private: using namespace Glacier2; Glacier2::SessionRouterI::SessionRouterI(const ObjectAdapterPtr& clientAdapter, - const ObjectAdapterPtr& serverAdapter, - const PermissionsVerifierPrx& verifier, - const SessionManagerPrx& sessionManager, - const SSLPermissionsVerifierPrx& sslVerifier, - const SSLSessionManagerPrx& sslSessionManager) : + const ObjectAdapterPtr& serverAdapter, + const PermissionsVerifierPrx& verifier, + const SessionManagerPrx& sessionManager, + const SSLPermissionsVerifierPrx& sslVerifier, + const SSLSessionManagerPrx& sslSessionManager) : _properties(clientAdapter->getCommunicator()->getProperties()), _logger(clientAdapter->getCommunicator()->getLogger()), _sessionTraceLevel(_properties->getPropertyAsInt("Glacier2.Trace.Session")), @@ -280,12 +280,12 @@ Glacier2::SessionRouterI::SessionRouterI(const ObjectAdapterPtr& clientAdapter, // if(_serverAdapter) { - _serverAdapter->addServantLocator(new ServerLocator(this), ""); + _serverAdapter->addServantLocator(new ServerLocator(this), ""); } if(_sessionThread) { - _sessionThread->start(); + _sessionThread->start(); } } @@ -307,20 +307,20 @@ Glacier2::SessionRouterI::destroy() SessionThreadPtr sessionThread; { - IceUtil::Monitor::Lock lock(*this); - - assert(!_destroy); - _destroy = true; - notify(); - - _routersByConnection.swap(routers); - _routersByConnectionHint = _routersByConnection.end(); - - _routersByCategory.clear(); - _routersByCategoryHint = _routersByCategory.end(); - - sessionThread = _sessionThread; - _sessionThread = 0; + IceUtil::Monitor::Lock lock(*this); + + assert(!_destroy); + _destroy = true; + notify(); + + _routersByConnection.swap(routers); + _routersByConnectionHint = _routersByConnection.end(); + + _routersByCategory.clear(); + _routersByCategoryHint = _routersByCategory.end(); + + sessionThread = _sessionThread; + _sessionThread = 0; } // @@ -329,26 +329,26 @@ Glacier2::SessionRouterI::destroy() // for(map::iterator p = routers.begin(); p != routers.end(); ++p) { - RouterIPtr router = p->second; - - try - { - router->destroy(); - } - catch(const Exception& ex) - { - if(_sessionTraceLevel >= 1) - { - Trace out(_logger, "Glacier2"); - out << "exception while destroying session\n" << ex; - } - } + RouterIPtr router = p->second; + + try + { + router->destroy(); + } + catch(const Exception& ex) + { + if(_sessionTraceLevel >= 1) + { + Trace out(_logger, "Glacier2"); + out << "exception while destroying session\n" << ex; + } + } } if(sessionThread) { - sessionThread->destroy(); - sessionThread->getThreadControl().join(); + sessionThread->destroy(); + sessionThread->getThreadControl().join(); } } @@ -394,10 +394,10 @@ Glacier2::SessionRouterI::createSession(const std::string& userId, const std::st SessionFactoryPtr factory; if(_sessionManager) { - factory = new UserSessionFactory(_sessionManager, userId); + factory = new UserSessionFactory(_sessionManager, userId); } return createSessionInternal(userId, true, new UserPasswordAuthorizer(_verifier, userId, password), factory, - Ice::Context(), current); + Ice::Context(), current); } SessionPrx @@ -405,9 +405,9 @@ Glacier2::SessionRouterI::createSessionFromSecureConnection(const Current& curre { if(!_sslVerifier) { - PermissionDeniedException exc; - exc.reason = "no configured ssl permissions verifier"; - throw exc; + PermissionDeniedException exc; + exc.reason = "no configured ssl permissions verifier"; + throw exc; } string userDN; @@ -419,62 +419,62 @@ Glacier2::SessionRouterI::createSessionFromSecureConnection(const Current& curre // try { - IceSSL::ConnectionInfo info = IceSSL::getConnectionInfo(current.con); - sslinfo.remotePort = ntohs(info.remoteAddr.sin_port); - sslinfo.remoteHost = IceInternal::inetAddrToString(info.remoteAddr.sin_addr); - sslinfo.localPort = ntohs(info.localAddr.sin_port); - sslinfo.localHost = IceInternal::inetAddrToString(info.localAddr.sin_addr); - - sslinfo.cipher = info.cipher; - - if(info.certs.size() > 0) - { - sslinfo.certs.resize(info.certs.size()); - for(unsigned int i = 0; i < info.certs.size(); ++i) - { - sslinfo.certs[i] = info.certs[i]->encode(); - } - userDN = info.certs[0]->getSubjectDN(); - } - - if(_properties->getPropertyAsInt("Glacier2.AddSSLContext") > 0) - { - sslCtx["SSL.Active"] = "1"; - sslCtx["SSL.Cipher"] = sslinfo.cipher; - ostringstream os; - os << sslinfo.remotePort; - sslCtx["SSL.Remote.Port"] = os.str(); - sslCtx["SSL.Remote.Host"] = sslinfo.remoteHost; - os.str(""); - os << ntohs(info.localAddr.sin_port); - sslCtx["SSL.Local.Port"] = os.str(); - sslCtx["SSL.Local.Host"] = sslinfo.localHost; - if(info.certs.size() > 0) - { - sslCtx["SSL.PeerCert"] = info.certs[0]->encode(); - } - } + IceSSL::ConnectionInfo info = IceSSL::getConnectionInfo(current.con); + sslinfo.remotePort = ntohs(info.remoteAddr.sin_port); + sslinfo.remoteHost = IceInternal::inetAddrToString(info.remoteAddr.sin_addr); + sslinfo.localPort = ntohs(info.localAddr.sin_port); + sslinfo.localHost = IceInternal::inetAddrToString(info.localAddr.sin_addr); + + sslinfo.cipher = info.cipher; + + if(info.certs.size() > 0) + { + sslinfo.certs.resize(info.certs.size()); + for(unsigned int i = 0; i < info.certs.size(); ++i) + { + sslinfo.certs[i] = info.certs[i]->encode(); + } + userDN = info.certs[0]->getSubjectDN(); + } + + if(_properties->getPropertyAsInt("Glacier2.AddSSLContext") > 0) + { + sslCtx["SSL.Active"] = "1"; + sslCtx["SSL.Cipher"] = sslinfo.cipher; + ostringstream os; + os << sslinfo.remotePort; + sslCtx["SSL.Remote.Port"] = os.str(); + sslCtx["SSL.Remote.Host"] = sslinfo.remoteHost; + os.str(""); + os << ntohs(info.localAddr.sin_port); + sslCtx["SSL.Local.Port"] = os.str(); + sslCtx["SSL.Local.Host"] = sslinfo.localHost; + if(info.certs.size() > 0) + { + sslCtx["SSL.PeerCert"] = info.certs[0]->encode(); + } + } } catch(const IceSSL::ConnectionInvalidException&) { - PermissionDeniedException exc; - exc.reason = "not ssl connection"; - throw exc; + PermissionDeniedException exc; + exc.reason = "not ssl connection"; + throw exc; } catch(const IceSSL::CertificateEncodingException&) { - PermissionDeniedException exc; - exc.reason = "certificate encoding exception"; - throw exc; + PermissionDeniedException exc; + exc.reason = "certificate encoding exception"; + throw exc; } SessionFactoryPtr factory; if(_sslSessionManager) { - factory = new SSLSessionFactory(_sslSessionManager, sslinfo); + factory = new SSLSessionFactory(_sslSessionManager, sslinfo); } return createSessionInternal(userDN, false, new SSLPasswordAuthorizer(_sslVerifier, sslinfo), factory, sslCtx, - current); + current); } void @@ -489,43 +489,43 @@ Glacier2::SessionRouterI::destroySession(const ConnectionPtr& connection) RouterIPtr router; { - IceUtil::Monitor::Lock lock(*this); - - if(_destroy) - { - connection->close(true); - throw ObjectNotExistException(__FILE__, __LINE__); - } - - map::iterator p; - - if(_routersByConnectionHint != _routersByConnection.end() && _routersByConnectionHint->first == connection) - { - p = _routersByConnectionHint; - } - else - { - p = _routersByConnection.find(connection); - } - - if(p == _routersByConnection.end()) - { - SessionNotExistException exc; - throw exc; - } - - router = p->second; - - _routersByConnection.erase(p++); - _routersByConnectionHint = p; - - if(_serverAdapter) - { - string category = router->getServerProxy(Current())->ice_getIdentity().category; - assert(!category.empty()); - _routersByCategory.erase(category); - _routersByCategoryHint = _routersByCategory.end(); - } + IceUtil::Monitor::Lock lock(*this); + + if(_destroy) + { + connection->close(true); + throw ObjectNotExistException(__FILE__, __LINE__); + } + + map::iterator p; + + if(_routersByConnectionHint != _routersByConnection.end() && _routersByConnectionHint->first == connection) + { + p = _routersByConnectionHint; + } + else + { + p = _routersByConnection.find(connection); + } + + if(p == _routersByConnection.end()) + { + SessionNotExistException exc; + throw exc; + } + + router = p->second; + + _routersByConnection.erase(p++); + _routersByConnectionHint = p; + + if(_serverAdapter) + { + string category = router->getServerProxy(Current())->ice_getIdentity().category; + assert(!category.empty()); + _routersByCategory.erase(category); + _routersByCategoryHint = _routersByCategory.end(); + } } // @@ -534,22 +534,22 @@ Glacier2::SessionRouterI::destroySession(const ConnectionPtr& connection) // try { - if(_sessionTraceLevel >= 1) - { - Trace out(_logger, "Glacier2"); - out << "destroying session\n"; - out << router->toString(); - } - - router->destroy(); + if(_sessionTraceLevel >= 1) + { + Trace out(_logger, "Glacier2"); + out << "destroying session\n"; + out << router->toString(); + } + + router->destroy(); } catch(const Exception& ex) { - if(_sessionTraceLevel >= 1) - { - Trace out(_logger, "Glacier2"); - out << "exception while destroying session\n" << ex; - } + if(_sessionTraceLevel >= 1) + { + Trace out(_logger, "Glacier2"); + out << "exception while destroying session\n" << ex; + } } } @@ -566,34 +566,34 @@ Glacier2::SessionRouterI::getRouter(const ConnectionPtr& connection, const Ice:: if(_destroy) { - connection->close(true); - throw ObjectNotExistException(__FILE__, __LINE__); + connection->close(true); + throw ObjectNotExistException(__FILE__, __LINE__); } map& routers = const_cast&>(_routersByConnection); if(_routersByConnectionHint != routers.end() && _routersByConnectionHint->first == connection) { - return _routersByConnectionHint->second; + return _routersByConnectionHint->second; } map::iterator p = routers.find(connection); if(p != routers.end()) { - _routersByConnectionHint = p; - return p->second; + _routersByConnectionHint = p; + return p->second; } else { - if(_rejectTraceLevel >= 1) - { - Trace out(_logger, "Glacier2"); - out << "rejecting request. no session is associated with the connection.\n"; - out << "identity: " << _clientAdapter->getCommunicator()->identityToString(id); - } - connection->close(true); - throw ObjectNotExistException(__FILE__, __LINE__); + if(_rejectTraceLevel >= 1) + { + Trace out(_logger, "Glacier2"); + out << "rejecting request. no session is associated with the connection.\n"; + out << "identity: " << _clientAdapter->getCommunicator()->identityToString(id); + } + connection->close(true); + throw ObjectNotExistException(__FILE__, __LINE__); } } @@ -604,26 +604,26 @@ Glacier2::SessionRouterI::getRouter(const string& category) const if(_destroy) { - throw ObjectNotExistException(__FILE__, __LINE__); + throw ObjectNotExistException(__FILE__, __LINE__); } map& routers = const_cast&>(_routersByCategory); if(_routersByCategoryHint != routers.end() && _routersByCategoryHint->first == category) { - return _routersByCategoryHint->second; + return _routersByCategoryHint->second; } map::iterator p = routers.find(category); if(p != routers.end()) { - _routersByCategoryHint = p; - return p->second; + _routersByCategoryHint = p; + return p->second; } else { - throw ObjectNotExistException(__FILE__, __LINE__); + throw ObjectNotExistException(__FILE__, __LINE__); } } @@ -633,41 +633,41 @@ Glacier2::SessionRouterI::expireSessions() vector routers; { - IceUtil::Monitor::Lock lock(*this); - - if(_destroy) - { - return; - } - - assert(_sessionTimeout > IceUtil::Time()); - IceUtil::Time minTimestamp = IceUtil::Time::now() - _sessionTimeout; - - map::iterator p = _routersByConnection.begin(); - - while(p != _routersByConnection.end()) - { - if(p->second->getTimestamp() < minTimestamp) - { - RouterIPtr router = p->second; - routers.push_back(router); - - _routersByConnection.erase(p++); - _routersByConnectionHint = p; - - if(_serverAdapter) - { - string category = router->getServerProxy(Current())->ice_getIdentity().category; - assert(!category.empty()); - _routersByCategory.erase(category); - _routersByCategoryHint = _routersByCategory.end(); - } - } - else - { - ++p; - } - } + IceUtil::Monitor::Lock lock(*this); + + if(_destroy) + { + return; + } + + assert(_sessionTimeout > IceUtil::Time()); + IceUtil::Time minTimestamp = IceUtil::Time::now() - _sessionTimeout; + + map::iterator p = _routersByConnection.begin(); + + while(p != _routersByConnection.end()) + { + if(p->second->getTimestamp() < minTimestamp) + { + RouterIPtr router = p->second; + routers.push_back(router); + + _routersByConnection.erase(p++); + _routersByConnectionHint = p; + + if(_serverAdapter) + { + string category = router->getServerProxy(Current())->ice_getIdentity().category; + assert(!category.empty()); + _routersByCategory.erase(category); + _routersByCategoryHint = _routersByCategory.end(); + } + } + else + { + ++p; + } + } } // @@ -676,169 +676,169 @@ Glacier2::SessionRouterI::expireSessions() // for(vector::iterator p = routers.begin(); p != routers.end(); ++p) { - RouterIPtr router = *p; - - try - { - if(_sessionTraceLevel >= 1) - { - Trace out(_logger, "Glacier2"); - out << "expiring session\n"; - out << router->toString(); - } - - router->destroy(); - } - catch(const Exception& ex) - { - if(_sessionTraceLevel >= 1) - { - Trace out(_logger, "Glacier2"); - out << "exception while expiring session\n" << ex; - } - } + RouterIPtr router = *p; + + try + { + if(_sessionTraceLevel >= 1) + { + Trace out(_logger, "Glacier2"); + out << "expiring session\n"; + out << router->toString(); + } + + router->destroy(); + } + catch(const Exception& ex) + { + if(_sessionTraceLevel >= 1) + { + Trace out(_logger, "Glacier2"); + out << "exception while expiring session\n" << ex; + } + } } } SessionPrx Glacier2::SessionRouterI::createSessionInternal(const string& userId, bool allowAddUserMode, - const AuthorizerPtr& authorizer, const SessionFactoryPtr& factory, - const Ice::Context& sslContext, const Current& current) + const AuthorizerPtr& authorizer, const SessionFactoryPtr& factory, + const Ice::Context& sslContext, const Current& current) { { - IceUtil::Monitor::Lock lock(*this); - - if(_destroy) - { - current.con->close(true); - throw ObjectNotExistException(__FILE__, __LINE__); - } - - // - // Check whether a session already exists for the connection. - // - { - map::iterator p; - if(_routersByConnectionHint != _routersByConnection.end() && - _routersByConnectionHint->first == current.con) - { - p = _routersByConnectionHint; - } - else - { - p = _routersByConnection.find(current.con); - } - - if(p != _routersByConnection.end()) - { - CannotCreateSessionException exc; - exc.reason = "session exists"; - throw exc; - } - } - - // - // If some other thread is currently trying to create a - // session, we wait until this thread is finished. - // - bool searchAgain = false; - while(_pending.find(current.con) != _pending.end()) - { - wait(); - - if(_destroy) - { - current.con->close(true); - throw ObjectNotExistException(__FILE__, __LINE__); - } - - searchAgain = true; - } - - // - // Check for existing sessions again if we waited above, as - // new sessions have been added in the meantime. - // - if(searchAgain) - { - map::iterator p; - if(_routersByConnectionHint != _routersByConnection.end() && - _routersByConnectionHint->first == current.con) - { - p = _routersByConnectionHint; - } - else - { - p = _routersByConnection.find(current.con); - } - - if(p != _routersByConnection.end()) - { - CannotCreateSessionException exc; - exc.reason = "session exists"; - throw exc; - } - } - - // - // No session exists yet, so we will try to create one. To - // avoid that other threads try to create sessions for the - // same connection, we add our endpoints to _pending. - // - _pending.insert(current.con); + IceUtil::Monitor::Lock lock(*this); + + if(_destroy) + { + current.con->close(true); + throw ObjectNotExistException(__FILE__, __LINE__); + } + + // + // Check whether a session already exists for the connection. + // + { + map::iterator p; + if(_routersByConnectionHint != _routersByConnection.end() && + _routersByConnectionHint->first == current.con) + { + p = _routersByConnectionHint; + } + else + { + p = _routersByConnection.find(current.con); + } + + if(p != _routersByConnection.end()) + { + CannotCreateSessionException exc; + exc.reason = "session exists"; + throw exc; + } + } + + // + // If some other thread is currently trying to create a + // session, we wait until this thread is finished. + // + bool searchAgain = false; + while(_pending.find(current.con) != _pending.end()) + { + wait(); + + if(_destroy) + { + current.con->close(true); + throw ObjectNotExistException(__FILE__, __LINE__); + } + + searchAgain = true; + } + + // + // Check for existing sessions again if we waited above, as + // new sessions have been added in the meantime. + // + if(searchAgain) + { + map::iterator p; + if(_routersByConnectionHint != _routersByConnection.end() && + _routersByConnectionHint->first == current.con) + { + p = _routersByConnectionHint; + } + else + { + p = _routersByConnection.find(current.con); + } + + if(p != _routersByConnection.end()) + { + CannotCreateSessionException exc; + exc.reason = "session exists"; + throw exc; + } + } + + // + // No session exists yet, so we will try to create one. To + // avoid that other threads try to create sessions for the + // same connection, we add our endpoints to _pending. + // + _pending.insert(current.con); } try { - // - // Authorize. - // - string reason; - bool ok; - - try - { - ok = authorizer->authorize(reason, current.ctx); - } - catch(const Exception& ex) - { - if(_sessionTraceLevel >= 1) - { - Trace out(_logger, "Glacier2"); - out << "exception while verifying password:\n" << ex; - } - - PermissionDeniedException exc; - exc.reason = "internal server error"; - throw exc; - } - - if(!ok) - { - PermissionDeniedException exc; - if(reason.empty()) - { - exc.reason = "permission denied"; - } - else - { - exc.reason = reason; - } - throw exc; - } + // + // Authorize. + // + string reason; + bool ok; + + try + { + ok = authorizer->authorize(reason, current.ctx); + } + catch(const Exception& ex) + { + if(_sessionTraceLevel >= 1) + { + Trace out(_logger, "Glacier2"); + out << "exception while verifying password:\n" << ex; + } + + PermissionDeniedException exc; + exc.reason = "internal server error"; + throw exc; + } + + if(!ok) + { + PermissionDeniedException exc; + if(reason.empty()) + { + exc.reason = "permission denied"; + } + else + { + exc.reason = reason; + } + throw exc; + } } catch(const Exception& ex) { - IceUtil::Monitor::Lock lock(*this); + IceUtil::Monitor::Lock lock(*this); - // - // Signal other threads that we are done with trying to - // establish a session for our connection; - // - _pending.erase(current.con); - notify(); + // + // Signal other threads that we are done with trying to + // establish a session for our connection; + // + _pending.erase(current.con); + notify(); - ex.ice_throw(); + ex.ice_throw(); } @@ -848,151 +848,151 @@ Glacier2::SessionRouterI::createSessionInternal(const string& userId, bool allow try { - // - // The client blobject requires direct access to the full filter - // servant, but proliferating the implementation of the servant - // throughout the router code is undesirable. To avoid lots of - // physical interdependencies, we create the filters and - // clientblobject together and pass the clientblobject to the - // router. We create the clientblobject here since it is - // responsible for creating the filters and we want them to be - // accessible during session creation. - // - FilterManagerPtr filterManager = FilterManager::create(_clientAdapter->getCommunicator(), _serverAdapter, - userId, allowAddUserMode); + // + // The client blobject requires direct access to the full filter + // servant, but proliferating the implementation of the servant + // throughout the router code is undesirable. To avoid lots of + // physical interdependencies, we create the filters and + // clientblobject together and pass the clientblobject to the + // router. We create the clientblobject here since it is + // responsible for creating the filters and we want them to be + // accessible during session creation. + // + FilterManagerPtr filterManager = FilterManager::create(_clientAdapter->getCommunicator(), _serverAdapter, + userId, allowAddUserMode); // - // If we have a session manager configured, we create a - // client-visible session object. - // - if(factory) - { - SessionControlPrx control; - if(_serverAdapter) - { - control = SessionControlPrx::uncheckedCast( - _serverAdapter->addWithUUID( - new SessionControlI(this, current.con, filterManager, _sessionTimeout))); - controlId = control->ice_getIdentity(); - } - session = factory->create(control, current.ctx); - } + // If we have a session manager configured, we create a + // client-visible session object. + // + if(factory) + { + SessionControlPrx control; + if(_serverAdapter) + { + control = SessionControlPrx::uncheckedCast( + _serverAdapter->addWithUUID( + new SessionControlI(this, current.con, filterManager, _sessionTimeout))); + controlId = control->ice_getIdentity(); + } + session = factory->create(control, current.ctx); + } - // - // Add a new per-client router. - // - router = new RouterI(_clientAdapter, _serverAdapter, current.con, userId, - session, controlId, filterManager, sslContext); + // + // Add a new per-client router. + // + router = new RouterI(_clientAdapter, _serverAdapter, current.con, userId, + session, controlId, filterManager, sslContext); } catch(const Exception& ex) { - IceUtil::Monitor::Lock lock(*this); - - // - // Signal other threads that we are done with trying to - // establish a session for our connection; - // - _pending.erase(current.con); - notify(); - - assert(!router); - - if(session) - { - if(_serverAdapter) - { - try - { - _serverAdapter->remove(controlId); - } - catch(const Exception&) - { - // Ignore all exceptions here. - } - } - try - { - session->destroy(); - } - catch(const Exception&) - { - // Ignore all exceptions here. - } - } - - try - { - ex.ice_throw(); - } - catch(const Glacier2::CannotCreateSessionException&) - { - throw; - } - catch(const Exception&) - { - if(_sessionTraceLevel >= 1) - { - Trace out(_logger, "Glacier2"); - out << "exception while creating session with session manager:\n" << ex; - } - - CannotCreateSessionException exc; - exc.reason = "internal server error"; - throw exc; - } + IceUtil::Monitor::Lock lock(*this); + + // + // Signal other threads that we are done with trying to + // establish a session for our connection; + // + _pending.erase(current.con); + notify(); + + assert(!router); + + if(session) + { + if(_serverAdapter) + { + try + { + _serverAdapter->remove(controlId); + } + catch(const Exception&) + { + // Ignore all exceptions here. + } + } + try + { + session->destroy(); + } + catch(const Exception&) + { + // Ignore all exceptions here. + } + } + + try + { + ex.ice_throw(); + } + catch(const Glacier2::CannotCreateSessionException&) + { + throw; + } + catch(const Exception&) + { + if(_sessionTraceLevel >= 1) + { + Trace out(_logger, "Glacier2"); + out << "exception while creating session with session manager:\n" << ex; + } + + CannotCreateSessionException exc; + exc.reason = "internal server error"; + throw exc; + } } { - IceUtil::Monitor::Lock lock(*this); - - // - // Signal other threads that we are done with trying to - // establish a session for our connection; - // - _pending.erase(current.con); - notify(); - - if(_destroy) - { - try - { - router->destroy(); - } - catch(const Exception&) - { - // Ignore all exceptions here. - } - - current.con->close(true); - throw ObjectNotExistException(__FILE__, __LINE__); - } - - _routersByConnectionHint = _routersByConnection.insert( - _routersByConnectionHint, pair(current.con, router)); - - if(_serverAdapter) - { - string category = router->getServerProxy(current)->ice_getIdentity().category; - assert(!category.empty()); - pair::iterator, bool> rc = - _routersByCategory.insert(pair(category, router)); - assert(rc.second); - _routersByCategoryHint = rc.first; - } - - if(_sessionTraceLevel >= 1) - { - Trace out(_logger, "Glacier2"); - out << "created session\n"; - out << router->toString(); - } + IceUtil::Monitor::Lock lock(*this); + + // + // Signal other threads that we are done with trying to + // establish a session for our connection; + // + _pending.erase(current.con); + notify(); + + if(_destroy) + { + try + { + router->destroy(); + } + catch(const Exception&) + { + // Ignore all exceptions here. + } + + current.con->close(true); + throw ObjectNotExistException(__FILE__, __LINE__); + } + + _routersByConnectionHint = _routersByConnection.insert( + _routersByConnectionHint, pair(current.con, router)); + + if(_serverAdapter) + { + string category = router->getServerProxy(current)->ice_getIdentity().category; + assert(!category.empty()); + pair::iterator, bool> rc = + _routersByCategory.insert(pair(category, router)); + assert(rc.second); + _routersByCategoryHint = rc.first; + } + + if(_sessionTraceLevel >= 1) + { + Trace out(_logger, "Glacier2"); + out << "created session\n"; + out << router->toString(); + } } - + return session; } Glacier2::SessionRouterI::SessionThread::SessionThread(const SessionRouterIPtr& sessionRouter, - const IceUtil::Time& sessionTimeout) : + const IceUtil::Time& sessionTimeout) : _sessionRouter(sessionRouter), _sessionTimeout(sessionTimeout) { @@ -1016,27 +1016,27 @@ Glacier2::SessionRouterI::SessionThread::run() { while(true) { - SessionRouterIPtr sessionRouter; + SessionRouterIPtr sessionRouter; - { - IceUtil::Monitor::Lock lock(*this); + { + IceUtil::Monitor::Lock lock(*this); - if(!_sessionRouter) - { - return; - } - - assert(_sessionTimeout > IceUtil::Time()); - timedWait(_sessionTimeout / 4); + if(!_sessionRouter) + { + return; + } + + assert(_sessionTimeout > IceUtil::Time()); + timedWait(_sessionTimeout / 4); - if(!_sessionRouter) - { - return; - } + if(!_sessionRouter) + { + return; + } - sessionRouter = _sessionRouter; - } + sessionRouter = _sessionRouter; + } - sessionRouter->expireSessions(); + sessionRouter->expireSessions(); } } diff --git a/cpp/src/Glacier2/SessionRouterI.h b/cpp/src/Glacier2/SessionRouterI.h index 7fc7a5c2f60..9be3f25e2b0 100644 --- a/cpp/src/Glacier2/SessionRouterI.h +++ b/cpp/src/Glacier2/SessionRouterI.h @@ -48,8 +48,8 @@ class SessionRouterI : public Router, public IceUtil::Monitor public: SessionRouterI(const Ice::ObjectAdapterPtr&, const Ice::ObjectAdapterPtr&, - const PermissionsVerifierPrx&, const SessionManagerPrx&, - const SSLPermissionsVerifierPrx&, const SSLSessionManagerPrx&); + const PermissionsVerifierPrx&, const SessionManagerPrx&, + const SSLPermissionsVerifierPrx&, const SSLSessionManagerPrx&); virtual ~SessionRouterI(); void destroy(); @@ -73,7 +73,7 @@ public: private: SessionPrx createSessionInternal(const std::string&, bool, const AuthorizerPtr&, const SessionFactoryPtr&, - const Ice::Context&, const Ice::Current&); + const Ice::Context&, const Ice::Current&); const Ice::PropertiesPtr _properties; const Ice::LoggerPtr _logger; @@ -91,16 +91,16 @@ private: { public: - SessionThread(const SessionRouterIPtr&, const IceUtil::Time&); - virtual ~SessionThread(); - void destroy(); + SessionThread(const SessionRouterIPtr&, const IceUtil::Time&); + virtual ~SessionThread(); + void destroy(); - virtual void run(); + virtual void run(); private: - SessionRouterIPtr _sessionRouter; - const IceUtil::Time _sessionTimeout; + SessionRouterIPtr _sessionRouter; + const IceUtil::Time _sessionTimeout; }; typedef IceUtil::Handle SessionThreadPtr; SessionThreadPtr _sessionThread; diff --git a/cpp/src/Ice/Application.cpp b/cpp/src/Ice/Application.cpp index ae9a1ea7c4e..adcd5ddfb69 100644 --- a/cpp/src/Ice/Application.cpp +++ b/cpp/src/Ice/Application.cpp @@ -68,26 +68,26 @@ holdInterruptCallback(int signal) { CtrlCHandlerCallback callback = 0; { - StaticMutex::Lock lock(_mutex); - while(!_released) - { - _condVar->wait(lock); - } - - if(_destroyed) - { - // - // Being destroyed by main thread - // - return; - } - assert(_ctrlCHandler != 0); - callback = _ctrlCHandler->getCallback(); + StaticMutex::Lock lock(_mutex); + while(!_released) + { + _condVar->wait(lock); + } + + if(_destroyed) + { + // + // Being destroyed by main thread + // + return; + } + assert(_ctrlCHandler != 0); + callback = _ctrlCHandler->getCallback(); } if(callback != 0) { - callback(signal); + callback(signal); } } @@ -95,60 +95,60 @@ static void destroyOnInterruptCallback(int signal) { { - StaticMutex::Lock lock(_mutex); - if(_destroyed) - { - // - // Being destroyed by main thread - // - return; - } - if(_nohup && signal == SIGHUP) - { - return; - } - - assert(!_callbackInProgress); - _callbackInProgress = true; - _interrupted = true; - _destroyed = true; - } - + StaticMutex::Lock lock(_mutex); + if(_destroyed) + { + // + // Being destroyed by main thread + // + return; + } + if(_nohup && signal == SIGHUP) + { + return; + } + + assert(!_callbackInProgress); + _callbackInProgress = true; + _interrupted = true; + _destroyed = true; + } + assert(_communicator != 0); try { - _communicator->destroy(); + _communicator->destroy(); } catch(const IceUtil::Exception& ex) { - cerr << _appName << " (while destroying in response to signal " << signal - << "): " << ex << endl; + cerr << _appName << " (while destroying in response to signal " << signal + << "): " << ex << endl; } catch(const std::exception& ex) { - cerr << _appName << " (while destroying in response to signal " << signal - << "): std::exception: " << ex.what() << endl; + cerr << _appName << " (while destroying in response to signal " << signal + << "): std::exception: " << ex.what() << endl; } catch(const std::string& msg) { - cerr << _appName << " (while destroying in response to signal " << signal - << "): " << msg << endl; + cerr << _appName << " (while destroying in response to signal " << signal + << "): " << msg << endl; } catch(const char * msg) { - cerr << _appName << " (while destroying in response to signal " << signal - << "): " << msg << endl; + cerr << _appName << " (while destroying in response to signal " << signal + << "): " << msg << endl; } catch(...) { - cerr << _appName << " (while destroying in response to signal " << signal - << "): unknown exception" << endl; + cerr << _appName << " (while destroying in response to signal " << signal + << "): unknown exception" << endl; } { - StaticMutex::Lock lock(_mutex); - _callbackInProgress = false; + StaticMutex::Lock lock(_mutex); + _callbackInProgress = false; } _condVar->signal(); } @@ -158,57 +158,57 @@ static void shutdownOnInterruptCallback(int signal) { { - StaticMutex::Lock lock(_mutex); - if(_destroyed) - { - // - // Being destroyed by main thread - // - return; - } - if(_nohup && signal == SIGHUP) - { - return; - } - assert(!_callbackInProgress); - _callbackInProgress = true; - _interrupted = true; + StaticMutex::Lock lock(_mutex); + if(_destroyed) + { + // + // Being destroyed by main thread + // + return; + } + if(_nohup && signal == SIGHUP) + { + return; + } + assert(!_callbackInProgress); + _callbackInProgress = true; + _interrupted = true; } assert(_communicator != 0); try { - _communicator->shutdown(); + _communicator->shutdown(); } catch(const IceUtil::Exception& ex) { - cerr << _appName << " (while shutting down in response to signal " << signal - << "): " << ex << endl; + cerr << _appName << " (while shutting down in response to signal " << signal + << "): " << ex << endl; } catch(const std::exception& ex) { - cerr << _appName << " (while shutting down in response to signal " << signal - << "): std::exception: " << ex.what() << endl; + cerr << _appName << " (while shutting down in response to signal " << signal + << "): std::exception: " << ex.what() << endl; } catch(const std::string& msg) { - cerr << _appName << " (while shutting down in response to signal " << signal - << "): " << msg << endl; + cerr << _appName << " (while shutting down in response to signal " << signal + << "): " << msg << endl; } catch(const char * msg) { - cerr << _appName << " (while shutting down in response to signal " << signal - << "): " << msg << endl; + cerr << _appName << " (while shutting down in response to signal " << signal + << "): " << msg << endl; } catch(...) { - cerr << _appName << " (while shutting down in response to signal " << signal - << "): unknown exception" << endl; + cerr << _appName << " (while shutting down in response to signal " << signal + << "): unknown exception" << endl; } { - StaticMutex::Lock lock(_mutex); - _callbackInProgress = false; + StaticMutex::Lock lock(_mutex); + _callbackInProgress = false; } _condVar->signal(); } @@ -217,55 +217,55 @@ static void callbackOnInterruptCallback(int signal) { { - StaticMutex::Lock lock(_mutex); - if(_destroyed) - { - // - // Being destroyed by main thread - // - return; - } - // For SIGHUP the user callback is always called. It can - // decide what to do. - assert(!_callbackInProgress); - _callbackInProgress = true; - _interrupted = true; + StaticMutex::Lock lock(_mutex); + if(_destroyed) + { + // + // Being destroyed by main thread + // + return; + } + // For SIGHUP the user callback is always called. It can + // decide what to do. + assert(!_callbackInProgress); + _callbackInProgress = true; + _interrupted = true; } assert(_application != 0); try { - _application->interruptCallback(signal); + _application->interruptCallback(signal); } catch(const IceUtil::Exception& ex) { - cerr << _appName << " (while interrupting in response to signal " << signal - << "): " << ex << endl; + cerr << _appName << " (while interrupting in response to signal " << signal + << "): " << ex << endl; } catch(const std::exception& ex) { - cerr << _appName << " (while interrupting in response to signal " << signal - << "): std::exception: " << ex.what() << endl; + cerr << _appName << " (while interrupting in response to signal " << signal + << "): std::exception: " << ex.what() << endl; } catch(const std::string& msg) { - cerr << _appName << " (while interrupting in response to signal " << signal - << "): " << msg << endl; + cerr << _appName << " (while interrupting in response to signal " << signal + << "): " << msg << endl; } catch(const char * msg) { - cerr << _appName << " (while interrupting in response to signal " << signal - << "): " << msg << endl; + cerr << _appName << " (while interrupting in response to signal " << signal + << "): " << msg << endl; } catch(...) { - cerr << _appName << " (while interrupting in response to signal " << signal - << "): unknown exception" << endl; + cerr << _appName << " (while interrupting in response to signal " << signal + << "): unknown exception" << endl; } { - StaticMutex::Lock lock(_mutex); - _callbackInProgress = false; + StaticMutex::Lock lock(_mutex); + _callbackInProgress = false; } _condVar->signal(); } @@ -295,26 +295,26 @@ Ice::Application::main(int argc, char* argv[], const char* configFile) InitializationData initData; if(configFile) { - try - { - initData.properties = createProperties(); - initData.properties->load(configFile); - } - catch(const IceUtil::Exception& ex) - { - cerr << argv[0] << ": " << ex << endl; - return EXIT_FAILURE; - } - catch(const std::exception& ex) - { - cerr << argv[0] << ": std::exception: " << ex.what() << endl; - return EXIT_FAILURE; - } - catch(...) - { - cerr << argv[0] << ": unknown exception" << endl; - return EXIT_FAILURE; - } + try + { + initData.properties = createProperties(); + initData.properties->load(configFile); + } + catch(const IceUtil::Exception& ex) + { + cerr << argv[0] << ": " << ex << endl; + return EXIT_FAILURE; + } + catch(const std::exception& ex) + { + cerr << argv[0] << ": std::exception: " << ex.what() << endl; + return EXIT_FAILURE; + } + catch(...) + { + cerr << argv[0] << ": unknown exception" << endl; + return EXIT_FAILURE; + } } return main(argc, argv, initData); } @@ -326,26 +326,26 @@ Ice::Application::main(int argc, char* argv[], const char* configFile, const Ice InitializationData initData; if(configFile) { - try - { - initData.properties = createProperties(); - initData.properties->load(configFile); - } - catch(const IceUtil::Exception& ex) - { - cerr << argv[0] << ": " << ex << endl; - return EXIT_FAILURE; - } - catch(const std::exception& ex) - { - cerr << argv[0] << ": std::exception: " << ex.what() << endl; - return EXIT_FAILURE; - } - catch(...) - { - cerr << argv[0] << ": unknown exception" << endl; - return EXIT_FAILURE; - } + try + { + initData.properties = createProperties(); + initData.properties->load(configFile); + } + catch(const IceUtil::Exception& ex) + { + cerr << argv[0] << ": " << ex << endl; + return EXIT_FAILURE; + } + catch(const std::exception& ex) + { + cerr << argv[0] << ": std::exception: " << ex.what() << endl; + return EXIT_FAILURE; + } + catch(...) + { + cerr << argv[0] << ": unknown exception" << endl; + return EXIT_FAILURE; + } } initData.logger = logger; return main(argc, argv, initData); @@ -356,133 +356,133 @@ Ice::Application::main(int argc, char* argv[], const InitializationData& initDat { if(_communicator != 0) { - cerr << argv[0] << ": only one instance of the Application class can be used" << endl; - return EXIT_FAILURE; + cerr << argv[0] << ": only one instance of the Application class can be used" << endl; + return EXIT_FAILURE; } int status; try { - // - // The ctrlCHandler must be created before starting any thread, in particular - // before initializing the communicator. - // - CtrlCHandler ctrCHandler; - _ctrlCHandler = &ctrCHandler; - - try - { - if(_condVar.get() == 0) - { - _condVar.reset(new Cond); - } - - _interrupted = false; - _appName = argv[0]; - - _application = this; - _communicator = initialize(argc, argv, initData); - _destroyed = false; - - // - // Used by destroyOnInterruptCallback and shutdownOnInterruptCallback. - // - _nohup = (_communicator->getProperties()->getPropertyAsInt("Ice.Nohup") > 0); - - // - // The default is to destroy when a signal is received. - // - destroyOnInterrupt(); - status = run(argc, argv); - } - catch(const IceUtil::Exception& ex) - { - cerr << _appName << ": " << ex << endl; - status = EXIT_FAILURE; - } - catch(const std::exception& ex) - { - cerr << _appName << ": std::exception: " << ex.what() << endl; - status = EXIT_FAILURE; - } - catch(const std::string& msg) - { - cerr << _appName << ": " << msg << endl; - status = EXIT_FAILURE; - } - catch(const char* msg) - { - cerr << _appName << ": " << msg << endl; - status = EXIT_FAILURE; - } - catch(...) - { - cerr << _appName << ": unknown exception" << endl; - status = EXIT_FAILURE; - } - - // - // Don't want any new interrupt and at this point (post-run), - // it would not make sense to release a held signal to run - // shutdown or destroy. - // - ignoreInterrupt(); - - { - StaticMutex::Lock lock(_mutex); - while(_callbackInProgress) - { - _condVar->wait(lock); - } - if(_destroyed) - { - _communicator = 0; - } - else - { - _destroyed = true; - // - // And _communicator != 0, meaning will be destroyed - // next, _destroyed = true also ensures that any - // remaining callback won't do anything - // - } - _application = 0; - } - - if(_communicator != 0) - { - try - { - _communicator->destroy(); - } - catch(const IceUtil::Exception& ex) - { - cerr << _appName << ": " << ex << endl; - status = EXIT_FAILURE; - } - catch(const std::exception& ex) - { - cerr << _appName << ": std::exception: " << ex.what() << endl; - status = EXIT_FAILURE; - } - catch(...) - { - cerr << _appName << ": unknown exception" << endl; - status = EXIT_FAILURE; - } - _communicator = 0; - } - - // - // Set _ctrlCHandler to 0 only once communicator->destroy() has completed. - // - _ctrlCHandler = 0; + // + // The ctrlCHandler must be created before starting any thread, in particular + // before initializing the communicator. + // + CtrlCHandler ctrCHandler; + _ctrlCHandler = &ctrCHandler; + + try + { + if(_condVar.get() == 0) + { + _condVar.reset(new Cond); + } + + _interrupted = false; + _appName = argv[0]; + + _application = this; + _communicator = initialize(argc, argv, initData); + _destroyed = false; + + // + // Used by destroyOnInterruptCallback and shutdownOnInterruptCallback. + // + _nohup = (_communicator->getProperties()->getPropertyAsInt("Ice.Nohup") > 0); + + // + // The default is to destroy when a signal is received. + // + destroyOnInterrupt(); + status = run(argc, argv); + } + catch(const IceUtil::Exception& ex) + { + cerr << _appName << ": " << ex << endl; + status = EXIT_FAILURE; + } + catch(const std::exception& ex) + { + cerr << _appName << ": std::exception: " << ex.what() << endl; + status = EXIT_FAILURE; + } + catch(const std::string& msg) + { + cerr << _appName << ": " << msg << endl; + status = EXIT_FAILURE; + } + catch(const char* msg) + { + cerr << _appName << ": " << msg << endl; + status = EXIT_FAILURE; + } + catch(...) + { + cerr << _appName << ": unknown exception" << endl; + status = EXIT_FAILURE; + } + + // + // Don't want any new interrupt and at this point (post-run), + // it would not make sense to release a held signal to run + // shutdown or destroy. + // + ignoreInterrupt(); + + { + StaticMutex::Lock lock(_mutex); + while(_callbackInProgress) + { + _condVar->wait(lock); + } + if(_destroyed) + { + _communicator = 0; + } + else + { + _destroyed = true; + // + // And _communicator != 0, meaning will be destroyed + // next, _destroyed = true also ensures that any + // remaining callback won't do anything + // + } + _application = 0; + } + + if(_communicator != 0) + { + try + { + _communicator->destroy(); + } + catch(const IceUtil::Exception& ex) + { + cerr << _appName << ": " << ex << endl; + status = EXIT_FAILURE; + } + catch(const std::exception& ex) + { + cerr << _appName << ": std::exception: " << ex.what() << endl; + status = EXIT_FAILURE; + } + catch(...) + { + cerr << _appName << ": unknown exception" << endl; + status = EXIT_FAILURE; + } + _communicator = 0; + } + + // + // Set _ctrlCHandler to 0 only once communicator->destroy() has completed. + // + _ctrlCHandler = 0; } catch(const CtrlCHandlerException&) { - cerr << argv[0] << ": only one instance of the Application class can be used" << endl; - status = EXIT_FAILURE; + cerr << argv[0] << ": only one instance of the Application class can be used" << endl; + status = EXIT_FAILURE; } return status; @@ -513,13 +513,13 @@ Ice::Application::destroyOnInterrupt() // if(_ctrlCHandler != 0) { - StaticMutex::Lock lock(_mutex); // we serialize all the interrupt-setting - if(_ctrlCHandler->getCallback() == holdInterruptCallback) - { - _released = true; - _condVar->signal(); - } - _ctrlCHandler->setCallback(destroyOnInterruptCallback); + StaticMutex::Lock lock(_mutex); // we serialize all the interrupt-setting + if(_ctrlCHandler->getCallback() == holdInterruptCallback) + { + _released = true; + _condVar->signal(); + } + _ctrlCHandler->setCallback(destroyOnInterruptCallback); } } @@ -528,13 +528,13 @@ Ice::Application::shutdownOnInterrupt() { if(_ctrlCHandler != 0) { - StaticMutex::Lock lock(_mutex); // we serialize all the interrupt-setting - if(_ctrlCHandler->getCallback() == holdInterruptCallback) - { - _released = true; - _condVar->signal(); - } - _ctrlCHandler->setCallback(shutdownOnInterruptCallback); + StaticMutex::Lock lock(_mutex); // we serialize all the interrupt-setting + if(_ctrlCHandler->getCallback() == holdInterruptCallback) + { + _released = true; + _condVar->signal(); + } + _ctrlCHandler->setCallback(shutdownOnInterruptCallback); } } @@ -543,13 +543,13 @@ Ice::Application::ignoreInterrupt() { if(_ctrlCHandler != 0) { - StaticMutex::Lock lock(_mutex); // we serialize all the interrupt-setting - if(_ctrlCHandler->getCallback() == holdInterruptCallback) - { - _released = true; - _condVar->signal(); - } - _ctrlCHandler->setCallback(0); + StaticMutex::Lock lock(_mutex); // we serialize all the interrupt-setting + if(_ctrlCHandler->getCallback() == holdInterruptCallback) + { + _released = true; + _condVar->signal(); + } + _ctrlCHandler->setCallback(0); } } @@ -558,13 +558,13 @@ Ice::Application::callbackOnInterrupt() { if(_ctrlCHandler != 0) { - StaticMutex::Lock lock(_mutex); // we serialize all the interrupt-setting - if(_ctrlCHandler->getCallback() == holdInterruptCallback) - { - _released = true; - _condVar->signal(); - } - _ctrlCHandler->setCallback(callbackOnInterruptCallback); + StaticMutex::Lock lock(_mutex); // we serialize all the interrupt-setting + if(_ctrlCHandler->getCallback() == holdInterruptCallback) + { + _released = true; + _condVar->signal(); + } + _ctrlCHandler->setCallback(callbackOnInterruptCallback); } } @@ -573,14 +573,14 @@ Ice::Application::holdInterrupt() { if(_ctrlCHandler != 0) { - StaticMutex::Lock lock(_mutex); // we serialize all the interrupt-setting - if(_ctrlCHandler->getCallback() != holdInterruptCallback) - { - _previousCallback = _ctrlCHandler->getCallback(); - _released = false; - _ctrlCHandler->setCallback(holdInterruptCallback); - } - // else, we were already holding signals + StaticMutex::Lock lock(_mutex); // we serialize all the interrupt-setting + if(_ctrlCHandler->getCallback() != holdInterruptCallback) + { + _previousCallback = _ctrlCHandler->getCallback(); + _released = false; + _ctrlCHandler->setCallback(holdInterruptCallback); + } + // else, we were already holding signals } } @@ -589,21 +589,21 @@ Ice::Application::releaseInterrupt() { if(_ctrlCHandler != 0) { - StaticMutex::Lock lock(_mutex); // we serialize all the interrupt-setting - if(_ctrlCHandler->getCallback() == holdInterruptCallback) - { - // - // Note that it's very possible no signal is held; - // in this case the callback is just replaced and - // setting _released to true and signalling _condVar - // do no harm. - // - - _released = true; - _ctrlCHandler->setCallback(_previousCallback); - _condVar->signal(); - } - // Else nothing to release. + StaticMutex::Lock lock(_mutex); // we serialize all the interrupt-setting + if(_ctrlCHandler->getCallback() == holdInterruptCallback) + { + // + // Note that it's very possible no signal is held; + // in this case the callback is just replaced and + // setting _released to true and signalling _condVar + // do no harm. + // + + _released = true; + _ctrlCHandler->setCallback(_previousCallback); + _condVar->signal(); + } + // Else nothing to release. } } diff --git a/cpp/src/Ice/BasicStream.cpp b/cpp/src/Ice/BasicStream.cpp index 67ea3e484a0..2e38c4c12df 100644 --- a/cpp/src/Ice/BasicStream.cpp +++ b/cpp/src/Ice/BasicStream.cpp @@ -51,23 +51,23 @@ IceInternal::BasicStream::clear() { while(_currentReadEncaps && _currentReadEncaps != &_preAllocatedReadEncaps) { - ReadEncaps* oldEncaps = _currentReadEncaps; - _currentReadEncaps = _currentReadEncaps->previous; - delete oldEncaps; + ReadEncaps* oldEncaps = _currentReadEncaps; + _currentReadEncaps = _currentReadEncaps->previous; + delete oldEncaps; } while(_currentWriteEncaps && _currentWriteEncaps != &_preAllocatedWriteEncaps) { - WriteEncaps* oldEncaps = _currentWriteEncaps; - _currentWriteEncaps = _currentWriteEncaps->previous; - delete oldEncaps; + WriteEncaps* oldEncaps = _currentWriteEncaps; + _currentWriteEncaps = _currentWriteEncaps->previous; + delete oldEncaps; } while(_seqDataStack) { - SeqData* oldSeqData = _seqDataStack; - _seqDataStack = _seqDataStack->previous; - delete oldSeqData; + SeqData* oldSeqData = _seqDataStack; + _seqDataStack = _seqDataStack->previous; + delete oldSeqData; } delete _objectList; @@ -91,34 +91,34 @@ IceInternal::BasicStream::swap(BasicStream& other) if(_currentReadEncaps || other._currentReadEncaps) { - _preAllocatedReadEncaps.swap(other._preAllocatedReadEncaps); + _preAllocatedReadEncaps.swap(other._preAllocatedReadEncaps); - if(!_currentReadEncaps) - { - _currentReadEncaps = &_preAllocatedReadEncaps; - other._currentReadEncaps = 0; - } - else if(!other._currentReadEncaps) - { - other._currentReadEncaps = &other._preAllocatedReadEncaps; - _currentReadEncaps = 0; - } + if(!_currentReadEncaps) + { + _currentReadEncaps = &_preAllocatedReadEncaps; + other._currentReadEncaps = 0; + } + else if(!other._currentReadEncaps) + { + other._currentReadEncaps = &other._preAllocatedReadEncaps; + _currentReadEncaps = 0; + } } if(_currentWriteEncaps || other._currentWriteEncaps) { - _preAllocatedWriteEncaps.swap(other._preAllocatedWriteEncaps); + _preAllocatedWriteEncaps.swap(other._preAllocatedWriteEncaps); - if(!_currentWriteEncaps) - { - _currentWriteEncaps = &_preAllocatedWriteEncaps; - other._currentWriteEncaps = 0; - } - else if(!other._currentWriteEncaps) - { - other._currentWriteEncaps = &other._preAllocatedWriteEncaps; - _currentWriteEncaps = 0; - } + if(!_currentWriteEncaps) + { + _currentWriteEncaps = &_preAllocatedWriteEncaps; + other._currentWriteEncaps = 0; + } + else if(!other._currentWriteEncaps) + { + other._currentWriteEncaps = &other._preAllocatedWriteEncaps; + _currentWriteEncaps = 0; + } } std::swap(_seqDataStack, other._seqDataStack); @@ -179,7 +179,7 @@ IceInternal::BasicStream::startSeq(int numElements, int minSize) { if(numElements == 0) // Optimization to avoid pushing a useless stack frame. { - return; + return; } // @@ -192,17 +192,17 @@ IceInternal::BasicStream::startSeq(int numElements, int minSize) int bytesLeft = static_cast(b.end() - i); if(_seqDataStack->previous == 0) // Outermost sequence { - // - // The sequence must fit within the message. - // - if(numElements * minSize > bytesLeft) - { - throw UnmarshalOutOfBoundsException(__FILE__, __LINE__); - } + // + // The sequence must fit within the message. + // + if(numElements * minSize > bytesLeft) + { + throw UnmarshalOutOfBoundsException(__FILE__, __LINE__); + } } else // Nested sequence { - checkSeq(bytesLeft); + checkSeq(bytesLeft); } } @@ -212,17 +212,17 @@ IceInternal::BasicStream::checkFixedSeq(int numElements, int elemSize) int bytesLeft = static_cast(b.end() - i); if(_seqDataStack == 0) // Outermost sequence { - // - // The sequence must fit within the message. - // - if(numElements * elemSize > bytesLeft) - { - throw UnmarshalOutOfBoundsException(__FILE__, __LINE__); - } + // + // The sequence must fit within the message. + // + if(numElements * elemSize > bytesLeft) + { + throw UnmarshalOutOfBoundsException(__FILE__, __LINE__); + } } else // Nested sequence { - checkSeq(bytesLeft - numElements * elemSize); + checkSeq(bytesLeft - numElements * elemSize); } } @@ -231,7 +231,7 @@ IceInternal::BasicStream::endSeq(int sz) { if(sz == 0) // Pop only if something was pushed previously. { - return; + return; } // @@ -300,11 +300,11 @@ IceInternal::BasicStream::skipEncaps() read(sz); if(sz < 0) { - throw NegativeSizeException(__FILE__, __LINE__); + throw NegativeSizeException(__FILE__, __LINE__); } if(i - sizeof(Int) + sz > b.end()) { - throw UnmarshalOutOfBoundsException(__FILE__, __LINE__); + throw UnmarshalOutOfBoundsException(__FILE__, __LINE__); } i += sz - sizeof(Int); } @@ -343,7 +343,7 @@ IceInternal::BasicStream::startReadSlice() read(sz); if(sz < 0) { - throw NegativeSizeException(__FILE__, __LINE__); + throw NegativeSizeException(__FILE__, __LINE__); } _readSlice = i - b.begin(); } @@ -360,12 +360,12 @@ IceInternal::BasicStream::skipSlice() read(sz); if(sz < 0) { - throw NegativeSizeException(__FILE__, __LINE__); + throw NegativeSizeException(__FILE__, __LINE__); } i += sz - sizeof(Int); if(i > b.end()) { - throw UnmarshalOutOfBoundsException(__FILE__, __LINE__); + throw UnmarshalOutOfBoundsException(__FILE__, __LINE__); } } @@ -375,14 +375,14 @@ IceInternal::BasicStream::writeTypeId(const string& id) TypeIdWriteMap::const_iterator k = _currentWriteEncaps->typeIdMap->find(id); if(k != _currentWriteEncaps->typeIdMap->end()) { - write(true); - writeSize(k->second); + write(true); + writeSize(k->second); } else { - _currentWriteEncaps->typeIdMap->insert(make_pair(id, ++_currentWriteEncaps->typeIdIndex)); - write(false); - write(id, false); + _currentWriteEncaps->typeIdMap->insert(make_pair(id, ++_currentWriteEncaps->typeIdIndex)); + write(false); + write(id, false); } } @@ -393,19 +393,19 @@ IceInternal::BasicStream::readTypeId(string& id) read(isIndex); if(isIndex) { - Ice::Int index; - readSize(index); - TypeIdReadMap::const_iterator k = _currentReadEncaps->typeIdMap->find(index); - if(k == _currentReadEncaps->typeIdMap->end()) - { - throw UnmarshalOutOfBoundsException(__FILE__, __LINE__); - } - id = k->second; + Ice::Int index; + readSize(index); + TypeIdReadMap::const_iterator k = _currentReadEncaps->typeIdMap->find(index); + if(k == _currentReadEncaps->typeIdMap->end()) + { + throw UnmarshalOutOfBoundsException(__FILE__, __LINE__); + } + id = k->second; } else { - read(id, false); - _currentReadEncaps->typeIdMap->insert(make_pair(++_currentReadEncaps->typeIdIndex, id)); + read(id, false); + _currentReadEncaps->typeIdMap->insert(make_pair(++_currentReadEncaps->typeIdIndex, id)); } } @@ -414,9 +414,9 @@ IceInternal::BasicStream::writeBlob(const vector& v) { if(!v.empty()) { - Container::size_type pos = b.size(); - resize(pos + v.size()); - memcpy(&b[pos], &v[0], v.size()); + Container::size_type pos = b.size(); + resize(pos + v.size()); + memcpy(&b[pos], &v[0], v.size()); } } @@ -425,16 +425,16 @@ IceInternal::BasicStream::readBlob(vector& v, Int sz) { if(sz > 0) { - if(b.end() - i < sz) - { - throw UnmarshalOutOfBoundsException(__FILE__, __LINE__); - } - vector(i, i + sz).swap(v); - i += sz; + if(b.end() - i < sz) + { + throw UnmarshalOutOfBoundsException(__FILE__, __LINE__); + } + vector(i, i + sz).swap(v); + i += sz; } else { - v.clear(); + v.clear(); } } @@ -445,9 +445,9 @@ IceInternal::BasicStream::write(const Byte* begin, const Byte* end) writeSize(sz); if(sz > 0) { - Container::size_type pos = b.size(); - resize(pos + sz); - memcpy(&b[pos], begin, sz); + Container::size_type pos = b.size(); + resize(pos + sz); + memcpy(&b[pos], begin, sz); } } @@ -476,9 +476,9 @@ IceInternal::BasicStream::write(const vector& v) writeSize(sz); if(sz > 0) { - Container::size_type pos = b.size(); - resize(pos + sz); - copy(v.begin(), v.end(), b.begin() + pos); + Container::size_type pos = b.size(); + resize(pos + sz); + copy(v.begin(), v.end(), b.begin() + pos); } } @@ -517,7 +517,7 @@ IceInternal::BasicStream::write(const bool* begin, const bool* end) { Container::size_type pos = b.size(); resize(pos + sz); - BasicStreamWriteBoolHelper::write(begin, pos, b, sz); + BasicStreamWriteBoolHelper::write(begin, pos, b, sz); } } @@ -550,11 +550,11 @@ struct BasicStreamReadBoolHelper bool* array = new bool[sz]; for(int idx = 0; idx < sz; ++idx) { - array[idx] = static_cast(*(i + idx)); + array[idx] = static_cast(*(i + idx)); } v.first = array; v.second = array + sz; - return array; + return array; } }; @@ -565,7 +565,7 @@ struct BasicStreamReadBoolHelper<1> { v.first = reinterpret_cast(i); v.second = reinterpret_cast(i) + sz; - return 0; + return 0; } }; @@ -580,7 +580,7 @@ IceInternal::BasicStream::read(pair& v) if(sz > 0) { checkFixedSeq(sz, 1); - result = BasicStreamReadBoolHelper::read(v, sz, i); + result = BasicStreamReadBoolHelper::read(v, sz, i); i += sz; } else @@ -614,19 +614,19 @@ IceInternal::BasicStream::write(const Short* begin, const Short* end) writeSize(sz); if(sz > 0) { - Container::size_type pos = b.size(); - resize(pos + sz * sizeof(Short)); + Container::size_type pos = b.size(); + resize(pos + sz * sizeof(Short)); #ifdef ICE_BIG_ENDIAN - const Byte* src = reinterpret_cast(begin) + sizeof(Short) - 1; - Byte* dest = &(*(b.begin() + pos)); - for(int j = 0 ; j < sz ; ++j) - { - *dest++ = *src--; - *dest++ = *src--; - src += 2 * sizeof(Short); - } + const Byte* src = reinterpret_cast(begin) + sizeof(Short) - 1; + Byte* dest = &(*(b.begin() + pos)); + for(int j = 0 ; j < sz ; ++j) + { + *dest++ = *src--; + *dest++ = *src--; + src += 2 * sizeof(Short); + } #else - memcpy(&b[pos], reinterpret_cast(begin), sz * sizeof(Short)); + memcpy(&b[pos], reinterpret_cast(begin), sz * sizeof(Short)); #endif } } @@ -636,7 +636,7 @@ IceInternal::BasicStream::read(Short& v) { if(b.end() - i < static_cast(sizeof(Short))) { - throw UnmarshalOutOfBoundsException(__FILE__, __LINE__); + throw UnmarshalOutOfBoundsException(__FILE__, __LINE__); } const Byte* src = &(*i); i += sizeof(Short); @@ -658,26 +658,26 @@ IceInternal::BasicStream::read(vector& v) readSize(sz); if(sz > 0) { - checkFixedSeq(sz, static_cast(sizeof(Short))); - Container::iterator begin = i; - i += sz * static_cast(sizeof(Short)); - v.resize(sz); + checkFixedSeq(sz, static_cast(sizeof(Short))); + Container::iterator begin = i; + i += sz * static_cast(sizeof(Short)); + v.resize(sz); #ifdef ICE_BIG_ENDIAN - const Byte* src = &(*begin); - Byte* dest = reinterpret_cast(&v[0]) + sizeof(Short) - 1; - for(int j = 0 ; j < sz ; ++j) - { - *dest-- = *src++; - *dest-- = *src++; - dest += 2 * sizeof(Short); - } + const Byte* src = &(*begin); + Byte* dest = reinterpret_cast(&v[0]) + sizeof(Short) - 1; + for(int j = 0 ; j < sz ; ++j) + { + *dest-- = *src++; + *dest-- = *src++; + dest += 2 * sizeof(Short); + } #else - copy(begin, i, reinterpret_cast(&v[0])); + copy(begin, i, reinterpret_cast(&v[0])); #endif } else { - v.clear(); + v.clear(); } } @@ -689,35 +689,35 @@ IceInternal::BasicStream::read(pair& v) readSize(sz); if(sz > 0) { - checkFixedSeq(sz, static_cast(sizeof(Short))); + checkFixedSeq(sz, static_cast(sizeof(Short))); #if defined(__i386) || defined(_M_IX86) v.first = reinterpret_cast(i); - i += sz * static_cast(sizeof(Short)); + i += sz * static_cast(sizeof(Short)); v.second = reinterpret_cast(i); #else result = new Short[sz]; v.first = result; v.second = result + sz; - Container::iterator begin = i; - i += sz * static_cast(sizeof(Short)); + Container::iterator begin = i; + i += sz * static_cast(sizeof(Short)); # ifdef ICE_BIG_ENDIAN - const Byte* src = &(*begin); - Byte* dest = reinterpret_cast(&result[0]) + sizeof(Short) - 1; - for(int j = 0 ; j < sz ; ++j) - { - *dest-- = *src++; - *dest-- = *src++; - dest += 2 * sizeof(Short); - } + const Byte* src = &(*begin); + Byte* dest = reinterpret_cast(&result[0]) + sizeof(Short) - 1; + for(int j = 0 ; j < sz ; ++j) + { + *dest-- = *src++; + *dest-- = *src++; + dest += 2 * sizeof(Short); + } # else - copy(begin, i, reinterpret_cast(&result[0])); + copy(begin, i, reinterpret_cast(&result[0])); # endif #endif } else { - v.first = v.second = 0; + v.first = v.second = 0; } return result; } @@ -729,21 +729,21 @@ IceInternal::BasicStream::write(const Int* begin, const Int* end) writeSize(sz); if(sz > 0) { - Container::size_type pos = b.size(); - resize(pos + sz * sizeof(Int)); + Container::size_type pos = b.size(); + resize(pos + sz * sizeof(Int)); #ifdef ICE_BIG_ENDIAN - const Byte* src = reinterpret_cast(begin) + sizeof(Int) - 1; - Byte* dest = &(*(b.begin() + pos)); - for(int j = 0 ; j < sz ; ++j) - { - *dest++ = *src--; - *dest++ = *src--; - *dest++ = *src--; - *dest++ = *src--; - src += 2 * sizeof(Int); - } + const Byte* src = reinterpret_cast(begin) + sizeof(Int) - 1; + Byte* dest = &(*(b.begin() + pos)); + for(int j = 0 ; j < sz ; ++j) + { + *dest++ = *src--; + *dest++ = *src--; + *dest++ = *src--; + *dest++ = *src--; + src += 2 * sizeof(Int); + } #else - memcpy(&b[pos], reinterpret_cast(begin), sz * sizeof(Int)); + memcpy(&b[pos], reinterpret_cast(begin), sz * sizeof(Int)); #endif } } @@ -755,28 +755,28 @@ IceInternal::BasicStream::read(vector& v) readSize(sz); if(sz > 0) { - checkFixedSeq(sz, static_cast(sizeof(Int))); - Container::iterator begin = i; - i += sz * static_cast(sizeof(Int)); - v.resize(sz); + checkFixedSeq(sz, static_cast(sizeof(Int))); + Container::iterator begin = i; + i += sz * static_cast(sizeof(Int)); + v.resize(sz); #ifdef ICE_BIG_ENDIAN - const Byte* src = &(*begin); - Byte* dest = reinterpret_cast(&v[0]) + sizeof(Int) - 1; - for(int j = 0 ; j < sz ; ++j) - { - *dest-- = *src++; - *dest-- = *src++; - *dest-- = *src++; - *dest-- = *src++; - dest += 2 * sizeof(Int); - } + const Byte* src = &(*begin); + Byte* dest = reinterpret_cast(&v[0]) + sizeof(Int) - 1; + for(int j = 0 ; j < sz ; ++j) + { + *dest-- = *src++; + *dest-- = *src++; + *dest-- = *src++; + *dest-- = *src++; + dest += 2 * sizeof(Int); + } #else - copy(begin, i, reinterpret_cast(&v[0])); + copy(begin, i, reinterpret_cast(&v[0])); #endif } else { - v.clear(); + v.clear(); } } @@ -788,37 +788,37 @@ IceInternal::BasicStream::read(pair& v) readSize(sz); if(sz > 0) { - checkFixedSeq(sz, static_cast(sizeof(Int))); + checkFixedSeq(sz, static_cast(sizeof(Int))); #if defined(__i386) || defined(_M_IX86) v.first = reinterpret_cast(i); - i += sz * static_cast(sizeof(Int)); + i += sz * static_cast(sizeof(Int)); v.second = reinterpret_cast(i); #else result = new Int[sz]; v.first = result; v.second = result + sz; - Container::iterator begin = i; - i += sz * static_cast(sizeof(Int)); + Container::iterator begin = i; + i += sz * static_cast(sizeof(Int)); # ifdef ICE_BIG_ENDIAN - const Byte* src = &(*begin); - Byte* dest = reinterpret_cast(&result[0]) + sizeof(Int) - 1; - for(int j = 0 ; j < sz ; ++j) - { - *dest-- = *src++; - *dest-- = *src++; - *dest-- = *src++; - *dest-- = *src++; - dest += 2 * sizeof(Int); - } + const Byte* src = &(*begin); + Byte* dest = reinterpret_cast(&result[0]) + sizeof(Int) - 1; + for(int j = 0 ; j < sz ; ++j) + { + *dest-- = *src++; + *dest-- = *src++; + *dest-- = *src++; + *dest-- = *src++; + dest += 2 * sizeof(Int); + } # else - copy(begin, i, reinterpret_cast(&result[0])); + copy(begin, i, reinterpret_cast(&result[0])); # endif #endif } else { - v.first = v.second = 0; + v.first = v.second = 0; } return result; } @@ -859,25 +859,25 @@ IceInternal::BasicStream::write(const Long* begin, const Long* end) writeSize(sz); if(sz > 0) { - Container::size_type pos = b.size(); - resize(pos + sz * sizeof(Long)); + Container::size_type pos = b.size(); + resize(pos + sz * sizeof(Long)); #ifdef ICE_BIG_ENDIAN - const Byte* src = reinterpret_cast(begin) + sizeof(Long) - 1; - Byte* dest = &(*(b.begin() + pos)); - for(int j = 0 ; j < sz ; ++j) - { - *dest++ = *src--; - *dest++ = *src--; - *dest++ = *src--; - *dest++ = *src--; - *dest++ = *src--; - *dest++ = *src--; - *dest++ = *src--; - *dest++ = *src--; - src += 2 * sizeof(Long); - } + const Byte* src = reinterpret_cast(begin) + sizeof(Long) - 1; + Byte* dest = &(*(b.begin() + pos)); + for(int j = 0 ; j < sz ; ++j) + { + *dest++ = *src--; + *dest++ = *src--; + *dest++ = *src--; + *dest++ = *src--; + *dest++ = *src--; + *dest++ = *src--; + *dest++ = *src--; + *dest++ = *src--; + src += 2 * sizeof(Long); + } #else - memcpy(&b[pos], reinterpret_cast(begin), sz * sizeof(Long)); + memcpy(&b[pos], reinterpret_cast(begin), sz * sizeof(Long)); #endif } } @@ -887,7 +887,7 @@ IceInternal::BasicStream::read(Long& v) { if(b.end() - i < static_cast(sizeof(Long))) { - throw UnmarshalOutOfBoundsException(__FILE__, __LINE__); + throw UnmarshalOutOfBoundsException(__FILE__, __LINE__); } const Byte* src = &(*i); i += sizeof(Long); @@ -921,32 +921,32 @@ IceInternal::BasicStream::read(vector& v) readSize(sz); if(sz > 0) { - checkFixedSeq(sz, static_cast(sizeof(Long))); - Container::iterator begin = i; - i += sz * static_cast(sizeof(Long)); - v.resize(sz); + checkFixedSeq(sz, static_cast(sizeof(Long))); + Container::iterator begin = i; + i += sz * static_cast(sizeof(Long)); + v.resize(sz); #ifdef ICE_BIG_ENDIAN - const Byte* src = &(*begin); - Byte* dest = reinterpret_cast(&v[0]) + sizeof(Long) - 1; - for(int j = 0 ; j < sz ; ++j) - { - *dest-- = *src++; - *dest-- = *src++; - *dest-- = *src++; - *dest-- = *src++; - *dest-- = *src++; - *dest-- = *src++; - *dest-- = *src++; - *dest-- = *src++; - dest += 2 * sizeof(Long); - } + const Byte* src = &(*begin); + Byte* dest = reinterpret_cast(&v[0]) + sizeof(Long) - 1; + for(int j = 0 ; j < sz ; ++j) + { + *dest-- = *src++; + *dest-- = *src++; + *dest-- = *src++; + *dest-- = *src++; + *dest-- = *src++; + *dest-- = *src++; + *dest-- = *src++; + *dest-- = *src++; + dest += 2 * sizeof(Long); + } #else - copy(begin, i, reinterpret_cast(&v[0])); + copy(begin, i, reinterpret_cast(&v[0])); #endif } else { - v.clear(); + v.clear(); } } @@ -958,41 +958,41 @@ IceInternal::BasicStream::read(pair& v) readSize(sz); if(sz > 0) { - checkFixedSeq(sz, static_cast(sizeof(Long))); + checkFixedSeq(sz, static_cast(sizeof(Long))); #if defined(__i386) || defined(_M_IX86) v.first = reinterpret_cast(i); - i += sz * static_cast(sizeof(Long)); + i += sz * static_cast(sizeof(Long)); v.second = reinterpret_cast(i); #else result = new Long[sz]; v.first = result; v.second = result + sz; - Container::iterator begin = i; - i += sz * static_cast(sizeof(Long)); + Container::iterator begin = i; + i += sz * static_cast(sizeof(Long)); # ifdef ICE_BIG_ENDIAN - const Byte* src = &(*begin); - Byte* dest = reinterpret_cast(&result[0]) + sizeof(Long) - 1; - for(int j = 0 ; j < sz ; ++j) - { - *dest-- = *src++; - *dest-- = *src++; - *dest-- = *src++; - *dest-- = *src++; - *dest-- = *src++; - *dest-- = *src++; - *dest-- = *src++; - *dest-- = *src++; - dest += 2 * sizeof(Long); - } + const Byte* src = &(*begin); + Byte* dest = reinterpret_cast(&result[0]) + sizeof(Long) - 1; + for(int j = 0 ; j < sz ; ++j) + { + *dest-- = *src++; + *dest-- = *src++; + *dest-- = *src++; + *dest-- = *src++; + *dest-- = *src++; + *dest-- = *src++; + *dest-- = *src++; + *dest-- = *src++; + dest += 2 * sizeof(Long); + } # else - copy(begin, i, reinterpret_cast(&result[0])); + copy(begin, i, reinterpret_cast(&result[0])); # endif #endif } else { - v.first = v.second = 0; + v.first = v.second = 0; } return result; } @@ -1025,21 +1025,21 @@ IceInternal::BasicStream::write(const Float* begin, const Float* end) writeSize(sz); if(sz > 0) { - Container::size_type pos = b.size(); - resize(pos + sz * sizeof(Float)); + Container::size_type pos = b.size(); + resize(pos + sz * sizeof(Float)); #ifdef ICE_BIG_ENDIAN - const Byte* src = reinterpret_cast(begin) + sizeof(Float) - 1; - Byte* dest = &(*(b.begin() + pos)); - for(int j = 0 ; j < sz ; ++j) - { - *dest++ = *src--; - *dest++ = *src--; - *dest++ = *src--; - *dest++ = *src--; - src += 2 * sizeof(Float); - } + const Byte* src = reinterpret_cast(begin) + sizeof(Float) - 1; + Byte* dest = &(*(b.begin() + pos)); + for(int j = 0 ; j < sz ; ++j) + { + *dest++ = *src--; + *dest++ = *src--; + *dest++ = *src--; + *dest++ = *src--; + src += 2 * sizeof(Float); + } #else - memcpy(&b[pos], reinterpret_cast(begin), sz * sizeof(Float)); + memcpy(&b[pos], reinterpret_cast(begin), sz * sizeof(Float)); #endif } } @@ -1049,7 +1049,7 @@ IceInternal::BasicStream::read(Float& v) { if(b.end() - i < static_cast(sizeof(Float))) { - throw UnmarshalOutOfBoundsException(__FILE__, __LINE__); + throw UnmarshalOutOfBoundsException(__FILE__, __LINE__); } const Byte* src = &(*i); i += sizeof(Float); @@ -1075,28 +1075,28 @@ IceInternal::BasicStream::read(vector& v) readSize(sz); if(sz > 0) { - checkFixedSeq(sz, static_cast(sizeof(Float))); - Container::iterator begin = i; - i += sz * static_cast(sizeof(Float)); - v.resize(sz); + checkFixedSeq(sz, static_cast(sizeof(Float))); + Container::iterator begin = i; + i += sz * static_cast(sizeof(Float)); + v.resize(sz); #ifdef ICE_BIG_ENDIAN - const Byte* src = &(*begin); - Byte* dest = reinterpret_cast(&v[0]) + sizeof(Float) - 1; - for(int j = 0 ; j < sz ; ++j) - { - *dest-- = *src++; - *dest-- = *src++; - *dest-- = *src++; - *dest-- = *src++; - dest += 2 * sizeof(Float); - } + const Byte* src = &(*begin); + Byte* dest = reinterpret_cast(&v[0]) + sizeof(Float) - 1; + for(int j = 0 ; j < sz ; ++j) + { + *dest-- = *src++; + *dest-- = *src++; + *dest-- = *src++; + *dest-- = *src++; + dest += 2 * sizeof(Float); + } #else - copy(begin, i, reinterpret_cast(&v[0])); + copy(begin, i, reinterpret_cast(&v[0])); #endif } else { - v.clear(); + v.clear(); } } @@ -1108,37 +1108,37 @@ IceInternal::BasicStream::read(pair& v) readSize(sz); if(sz > 0) { - checkFixedSeq(sz, static_cast(sizeof(Float))); + checkFixedSeq(sz, static_cast(sizeof(Float))); #if defined(__i386) || defined(_M_IX86) v.first = reinterpret_cast(i); - i += sz * static_cast(sizeof(Float)); + i += sz * static_cast(sizeof(Float)); v.second = reinterpret_cast(i); #else result = new Float[sz]; v.first = result; v.second = result + sz; - Container::iterator begin = i; - i += sz * static_cast(sizeof(Float)); + Container::iterator begin = i; + i += sz * static_cast(sizeof(Float)); # ifdef ICE_BIG_ENDIAN - const Byte* src = &(*begin); - Byte* dest = reinterpret_cast(&result[0]) + sizeof(Float) - 1; - for(int j = 0 ; j < sz ; ++j) - { - *dest-- = *src++; - *dest-- = *src++; - *dest-- = *src++; - *dest-- = *src++; - dest += 2 * sizeof(Float); - } + const Byte* src = &(*begin); + Byte* dest = reinterpret_cast(&result[0]) + sizeof(Float) - 1; + for(int j = 0 ; j < sz ; ++j) + { + *dest-- = *src++; + *dest-- = *src++; + *dest-- = *src++; + *dest-- = *src++; + dest += 2 * sizeof(Float); + } # else - copy(begin, i, reinterpret_cast(&result[0])); + copy(begin, i, reinterpret_cast(&result[0])); # endif #endif } else { - v.first = v.second = 0; + v.first = v.second = 0; } return result; } @@ -1179,25 +1179,25 @@ IceInternal::BasicStream::write(const Double* begin, const Double* end) writeSize(sz); if(sz > 0) { - Container::size_type pos = b.size(); - resize(pos + sz * sizeof(Double)); + Container::size_type pos = b.size(); + resize(pos + sz * sizeof(Double)); #ifdef ICE_BIG_ENDIAN - const Byte* src = reinterpret_cast(begin) + sizeof(Double) - 1; - Byte* dest = &(*(b.begin() + pos)); - for(int j = 0 ; j < sz ; ++j) - { - *dest++ = *src--; - *dest++ = *src--; - *dest++ = *src--; - *dest++ = *src--; - *dest++ = *src--; - *dest++ = *src--; - *dest++ = *src--; - *dest++ = *src--; - src += 2 * sizeof(Double); - } + const Byte* src = reinterpret_cast(begin) + sizeof(Double) - 1; + Byte* dest = &(*(b.begin() + pos)); + for(int j = 0 ; j < sz ; ++j) + { + *dest++ = *src--; + *dest++ = *src--; + *dest++ = *src--; + *dest++ = *src--; + *dest++ = *src--; + *dest++ = *src--; + *dest++ = *src--; + *dest++ = *src--; + src += 2 * sizeof(Double); + } #else - memcpy(&b[pos], reinterpret_cast(begin), sz * sizeof(Double)); + memcpy(&b[pos], reinterpret_cast(begin), sz * sizeof(Double)); #endif } } @@ -1207,7 +1207,7 @@ IceInternal::BasicStream::read(Double& v) { if(b.end() - i < static_cast(sizeof(Double))) { - throw UnmarshalOutOfBoundsException(__FILE__, __LINE__); + throw UnmarshalOutOfBoundsException(__FILE__, __LINE__); } const Byte* src = &(*i); i += sizeof(Double); @@ -1241,32 +1241,32 @@ IceInternal::BasicStream::read(vector& v) readSize(sz); if(sz > 0) { - checkFixedSeq(sz, static_cast(sizeof(Double))); - Container::iterator begin = i; - i += sz * static_cast(sizeof(Double)); - v.resize(sz); + checkFixedSeq(sz, static_cast(sizeof(Double))); + Container::iterator begin = i; + i += sz * static_cast(sizeof(Double)); + v.resize(sz); #ifdef ICE_BIG_ENDIAN - const Byte* src = &(*begin); - Byte* dest = reinterpret_cast(&v[0]) + sizeof(Double) - 1; - for(int j = 0 ; j < sz ; ++j) - { - *dest-- = *src++; - *dest-- = *src++; - *dest-- = *src++; - *dest-- = *src++; - *dest-- = *src++; - *dest-- = *src++; - *dest-- = *src++; - *dest-- = *src++; - dest += 2 * sizeof(Double); - } + const Byte* src = &(*begin); + Byte* dest = reinterpret_cast(&v[0]) + sizeof(Double) - 1; + for(int j = 0 ; j < sz ; ++j) + { + *dest-- = *src++; + *dest-- = *src++; + *dest-- = *src++; + *dest-- = *src++; + *dest-- = *src++; + *dest-- = *src++; + *dest-- = *src++; + *dest-- = *src++; + dest += 2 * sizeof(Double); + } #else - copy(begin, i, reinterpret_cast(&v[0])); + copy(begin, i, reinterpret_cast(&v[0])); #endif } else { - v.clear(); + v.clear(); } } @@ -1278,41 +1278,41 @@ IceInternal::BasicStream::read(pair& v) readSize(sz); if(sz > 0) { - checkFixedSeq(sz, static_cast(sizeof(Double))); + checkFixedSeq(sz, static_cast(sizeof(Double))); #if defined(__i386) || defined(_M_IX86) v.first = reinterpret_cast(i); - i += sz * static_cast(sizeof(Double)); + i += sz * static_cast(sizeof(Double)); v.second = reinterpret_cast(i); #else result = new Double[sz]; v.first = result; v.second = result + sz; - Container::iterator begin = i; - i += sz * static_cast(sizeof(Double)); + Container::iterator begin = i; + i += sz * static_cast(sizeof(Double)); # ifdef ICE_BIG_ENDIAN - const Byte* src = &(*begin); - Byte* dest = reinterpret_cast(&result[0]) + sizeof(Double) - 1; - for(int j = 0 ; j < sz ; ++j) - { - *dest-- = *src++; - *dest-- = *src++; - *dest-- = *src++; - *dest-- = *src++; - *dest-- = *src++; - *dest-- = *src++; - *dest-- = *src++; - *dest-- = *src++; - dest += 2 * sizeof(Double); - } + const Byte* src = &(*begin); + Byte* dest = reinterpret_cast(&result[0]) + sizeof(Double) - 1; + for(int j = 0 ; j < sz ; ++j) + { + *dest-- = *src++; + *dest-- = *src++; + *dest-- = *src++; + *dest-- = *src++; + *dest-- = *src++; + *dest-- = *src++; + *dest-- = *src++; + *dest-- = *src++; + dest += 2 * sizeof(Double); + } # else - copy(begin, i, reinterpret_cast(&result[0])); + copy(begin, i, reinterpret_cast(&result[0])); # endif #endif } else { - v.first = v.second = 0; + v.first = v.second = 0; } return result; } @@ -1339,22 +1339,22 @@ IceInternal::BasicStream::writeConverted(const string& v) // Impossible to tell, so we guess. If we don't guess correctly, // we'll have to fix the mistake afterwards // - + Int guessedSize = static_cast(v.size()); writeSize(guessedSize); // writeSize() only writes the size; it does not reserve any buffer space. - + size_t firstIndex = b.size(); StreamUTF8BufferI buffer(*this); - + Byte* lastByte = _stringConverter->toUTF8(v.data(), v.data() + v.size(), buffer); if(lastByte != b.end()) { b.resize(lastByte - b.begin()); } size_t lastIndex = b.size(); - + Int actualSize = static_cast(lastIndex - firstIndex); - + // // Check against the guess // @@ -1362,29 +1362,29 @@ IceInternal::BasicStream::writeConverted(const string& v) { if(guessedSize <= 254 && actualSize > 254) { - // - // Move the UTF-8 sequence 4 bytes further - // Use memmove instead of memcpy since the source and destination typically overlap. - // - resize(b.size() + 4); - memmove(b.begin() + firstIndex + 4, b.begin() + firstIndex, actualSize); + // + // Move the UTF-8 sequence 4 bytes further + // Use memmove instead of memcpy since the source and destination typically overlap. + // + resize(b.size() + 4); + memmove(b.begin() + firstIndex + 4, b.begin() + firstIndex, actualSize); } else if(guessedSize > 254 && actualSize <= 254) { - // - // Move the UTF-8 sequence 4 bytes back - // - memmove(b.begin() + firstIndex - 4, b.begin() + firstIndex, actualSize); - resize(b.size() - 4); + // + // Move the UTF-8 sequence 4 bytes back + // + memmove(b.begin() + firstIndex - 4, b.begin() + firstIndex, actualSize); + resize(b.size() - 4); } if(guessedSize <= 254) { - rewriteSize(actualSize, b.begin() + firstIndex - 1); + rewriteSize(actualSize, b.begin() + firstIndex - 1); } else { - rewriteSize(actualSize, b.begin() + firstIndex - 1 - 4); + rewriteSize(actualSize, b.begin() + firstIndex - 1 - 4); } } } @@ -1396,10 +1396,10 @@ IceInternal::BasicStream::write(const string* begin, const string* end, bool con writeSize(sz); if(sz > 0) { - for(int i = 0; i < sz; ++i) - { - write(begin[i], convert); - } + for(int i = 0; i < sz; ++i) + { + write(begin[i], convert); + } } } @@ -1410,15 +1410,15 @@ IceInternal::BasicStream::read(vector& v, bool convert) readSize(sz); if(sz > 0) { - startSeq(sz, 1); - v.resize(sz); - for(int j = 0; j < sz; ++j) - { - read(v[j], convert); - checkSeq(); - endElement(); - } - endSeq(sz); + startSeq(sz, 1); + v.resize(sz); + for(int j = 0; j < sz; ++j) + { + read(v[j], convert); + checkSeq(); + endElement(); + } + endSeq(sz); } else { @@ -1432,7 +1432,7 @@ IceInternal::BasicStream::write(const wstring& v) if(v.empty()) { writeSize(0); - return; + return; } // @@ -1440,22 +1440,22 @@ IceInternal::BasicStream::write(const wstring& v) // Impossible to tell, so we guess. If we don't guess correctly, // we'll have to fix the mistake afterwards // - + Int guessedSize = static_cast(v.size()); writeSize(guessedSize); // writeSize() only writes the size; it does not reserve any buffer space. - + size_t firstIndex = b.size(); StreamUTF8BufferI buffer(*this); - + Byte* lastByte = _wstringConverter->toUTF8(v.data(), v.data() + v.size(), buffer); if(lastByte != b.end()) { b.resize(lastByte - b.begin()); } size_t lastIndex = b.size(); - + Int actualSize = static_cast(lastIndex - firstIndex); - + // // Check against the guess // @@ -1463,29 +1463,29 @@ IceInternal::BasicStream::write(const wstring& v) { if(guessedSize <= 254 && actualSize > 254) { - // - // Move the UTF-8 sequence 4 bytes further - // Use memmove instead of memcpy since the source and destination typically overlap. - // - resize(b.size() + 4); - memmove(b.begin() + firstIndex + 4, b.begin() + firstIndex, actualSize); + // + // Move the UTF-8 sequence 4 bytes further + // Use memmove instead of memcpy since the source and destination typically overlap. + // + resize(b.size() + 4); + memmove(b.begin() + firstIndex + 4, b.begin() + firstIndex, actualSize); } else if(guessedSize > 254 && actualSize <= 254) { - // - // Move the UTF-8 sequence 4 bytes back - // - memmove(b.begin() + firstIndex - 4, b.begin() + firstIndex, actualSize); - resize(b.size() - 4); + // + // Move the UTF-8 sequence 4 bytes back + // + memmove(b.begin() + firstIndex - 4, b.begin() + firstIndex, actualSize); + resize(b.size() - 4); } if(guessedSize <= 254) { - rewriteSize(actualSize, b.begin() + firstIndex - 1); + rewriteSize(actualSize, b.begin() + firstIndex - 1); } else { - rewriteSize(actualSize, b.begin() + firstIndex - 1 - 4); + rewriteSize(actualSize, b.begin() + firstIndex - 1 - 4); } } } @@ -1497,10 +1497,10 @@ IceInternal::BasicStream::write(const wstring* begin, const wstring* end) writeSize(sz); if(sz > 0) { - for(int i = 0; i < sz; ++i) - { - write(begin[i]); - } + for(int i = 0; i < sz; ++i) + { + write(begin[i]); + } } } @@ -1511,15 +1511,15 @@ IceInternal::BasicStream::read(vector& v) readSize(sz); if(sz > 0) { - startSeq(sz, 1); - v.resize(sz); - for(int j = 0; j < sz; ++j) - { - read(v[j]); - checkSeq(); - endElement(); - } - endSeq(sz); + startSeq(sz, 1); + v.resize(sz); + for(int j = 0; j < sz; ++j) + { + read(v[j]); + checkSeq(); + endElement(); + } + endSeq(sz); } else { @@ -1544,50 +1544,50 @@ IceInternal::BasicStream::write(const ObjectPtr& v) { if(!_currentWriteEncaps) // Lazy initialization. { - _currentWriteEncaps = &_preAllocatedWriteEncaps; - _currentWriteEncaps->start = b.size(); + _currentWriteEncaps = &_preAllocatedWriteEncaps; + _currentWriteEncaps->start = b.size(); } if(!_currentWriteEncaps->toBeMarshaledMap) // Lazy initialization. { - _currentWriteEncaps->toBeMarshaledMap = new PtrToIndexMap; - _currentWriteEncaps->marshaledMap = new PtrToIndexMap; - _currentWriteEncaps->typeIdMap = new TypeIdWriteMap; + _currentWriteEncaps->toBeMarshaledMap = new PtrToIndexMap; + _currentWriteEncaps->marshaledMap = new PtrToIndexMap; + _currentWriteEncaps->typeIdMap = new TypeIdWriteMap; } if(v) { - // - // Look for this instance in the to-be-marshaled map. - // - PtrToIndexMap::iterator p = _currentWriteEncaps->toBeMarshaledMap->find(v); - if(p == _currentWriteEncaps->toBeMarshaledMap->end()) - { - // - // Didn't find it, try the marshaled map next. - // - PtrToIndexMap::iterator q = _currentWriteEncaps->marshaledMap->find(v); - if(q == _currentWriteEncaps->marshaledMap->end()) - { - // - // We haven't seen this instance previously, create a - // new index, and insert it into the to-be-marshaled - // map. - // - q = _currentWriteEncaps->toBeMarshaledMap->insert( - _currentWriteEncaps->toBeMarshaledMap->end(), - pair(v, ++_currentWriteEncaps->writeIndex)); - } - p = q; - } - // - // Write the index for the instance. - // - write(-(p->second)); + // + // Look for this instance in the to-be-marshaled map. + // + PtrToIndexMap::iterator p = _currentWriteEncaps->toBeMarshaledMap->find(v); + if(p == _currentWriteEncaps->toBeMarshaledMap->end()) + { + // + // Didn't find it, try the marshaled map next. + // + PtrToIndexMap::iterator q = _currentWriteEncaps->marshaledMap->find(v); + if(q == _currentWriteEncaps->marshaledMap->end()) + { + // + // We haven't seen this instance previously, create a + // new index, and insert it into the to-be-marshaled + // map. + // + q = _currentWriteEncaps->toBeMarshaledMap->insert( + _currentWriteEncaps->toBeMarshaledMap->end(), + pair(v, ++_currentWriteEncaps->writeIndex)); + } + p = q; + } + // + // Write the index for the instance. + // + write(-(p->second)); } else { - write(0); // Write null pointer. + write(0); // Write null pointer. } } @@ -1596,14 +1596,14 @@ IceInternal::BasicStream::read(PatchFunc patchFunc, void* patchAddr) { if(!_currentReadEncaps) // Lazy initialization. { - _currentReadEncaps = &_preAllocatedReadEncaps; + _currentReadEncaps = &_preAllocatedReadEncaps; } if(!_currentReadEncaps->patchMap) // Lazy initialization. { - _currentReadEncaps->patchMap = new PatchMap; - _currentReadEncaps->unmarshaledMap = new IndexToPtrMap; - _currentReadEncaps->typeIdMap = new TypeIdReadMap; + _currentReadEncaps->patchMap = new PatchMap; + _currentReadEncaps->unmarshaledMap = new IndexToPtrMap; + _currentReadEncaps->typeIdMap = new TypeIdReadMap; } ObjectPtr v; @@ -1613,30 +1613,30 @@ IceInternal::BasicStream::read(PatchFunc patchFunc, void* patchAddr) if(index == 0) { - patchFunc(patchAddr, v); // Null Ptr. - return; + patchFunc(patchAddr, v); // Null Ptr. + return; } if(index < 0 && patchAddr) { - PatchMap::iterator p = _currentReadEncaps->patchMap->find(-index); - if(p == _currentReadEncaps->patchMap->end()) - { - // - // We have no outstanding instances to be patched for this - // index, so make a new entry in the patch map. - // - p = _currentReadEncaps->patchMap->insert(make_pair(-index, PatchList())).first; - } - // - // Append a patch entry for this instance. - // - PatchEntry e; - e.patchFunc = patchFunc; - e.patchAddr = patchAddr; - p->second.push_back(e); - patchPointers(-index, _currentReadEncaps->unmarshaledMap->end(), p); - return; + PatchMap::iterator p = _currentReadEncaps->patchMap->find(-index); + if(p == _currentReadEncaps->patchMap->end()) + { + // + // We have no outstanding instances to be patched for this + // index, so make a new entry in the patch map. + // + p = _currentReadEncaps->patchMap->insert(make_pair(-index, PatchList())).first; + } + // + // Append a patch entry for this instance. + // + PatchEntry e; + e.patchFunc = patchFunc; + e.patchAddr = patchAddr; + p->second.push_back(e); + patchPointers(-index, _currentReadEncaps->unmarshaledMap->end(), p); + return; } assert(index > 0); @@ -1645,16 +1645,16 @@ IceInternal::BasicStream::read(PatchFunc patchFunc, void* patchAddr) string id = mostDerivedId; while(true) { - // - // If we slice all the way down to Ice::Object, we throw - // because Ice::Object is abstract. - // + // + // If we slice all the way down to Ice::Object, we throw + // because Ice::Object is abstract. + // if(id == Ice::Object::ice_staticId()) - { - throw NoObjectFactoryException(__FILE__, __LINE__, - "class sliced to ::Ice::Object, which is abstract", - mostDerivedId); - } + { + throw NoObjectFactoryException(__FILE__, __LINE__, + "class sliced to ::Ice::Object, which is abstract", + mostDerivedId); + } // // Try to find a factory registered for the specific type. @@ -1709,7 +1709,7 @@ IceInternal::BasicStream::read(PatchFunc patchFunc, void* patchAddr) traceSlicing("class", id, _slicingCat, _instance->initializationData().logger); } skipSlice(); // Slice off this derived part -- we don't understand it. - readTypeId(id); // Read next id for next iteration. + readTypeId(id); // Read next id for next iteration. continue; } else @@ -1720,8 +1720,8 @@ IceInternal::BasicStream::read(PatchFunc patchFunc, void* patchAddr) } } - IndexToPtrMap::const_iterator unmarshaledPos = - _currentReadEncaps->unmarshaledMap->insert(make_pair(index, v)).first; + IndexToPtrMap::const_iterator unmarshaledPos = + _currentReadEncaps->unmarshaledMap->insert(make_pair(index, v)).first; // // Record each object instance so that readPendingObjects can @@ -1734,9 +1734,9 @@ IceInternal::BasicStream::read(PatchFunc patchFunc, void* patchAddr) } _objectList->push_back(v); - v->__read(this, false); - patchPointers(index, unmarshaledPos, _currentReadEncaps->patchMap->end()); - return; + v->__read(this, false); + patchPointers(index, unmarshaledPos, _currentReadEncaps->patchMap->end()); + return; } // @@ -1754,7 +1754,7 @@ IceInternal::BasicStream::write(const UserException& v) v.__write(this); if(v.__usesClasses()) { - writePendingObjects(); + writePendingObjects(); } } @@ -1768,49 +1768,49 @@ IceInternal::BasicStream::throwException() read(id, false); for(;;) { - // - // Look for a factory for this ID. - // - UserExceptionFactoryPtr factory = factoryTable->getExceptionFactory(id); - if(factory) - { - // - // Got factory -- get the factory to instantiate the - // exception, initialize the exception members, and throw - // the exception. - // - try - { - factory->createAndThrow(); - } - catch(UserException& ex) - { - ex.__read(this, false); - if(usesClasses) - { - readPendingObjects(); - } - ex.ice_throw(); - } - } - else - { - // - // Performance sensitive, so we use lazy initialization - // for tracing. - // - if(_traceSlicing == -1) - { - _traceSlicing = _instance->traceLevels()->slicing; - _slicingCat = _instance->traceLevels()->slicingCat; - } - if(_traceSlicing > 0) - { - traceSlicing("exception", id, _slicingCat, _instance->initializationData().logger); - } - skipSlice(); // Slice off what we don't understand. - read(id, false); // Read type id for next slice. - } + // + // Look for a factory for this ID. + // + UserExceptionFactoryPtr factory = factoryTable->getExceptionFactory(id); + if(factory) + { + // + // Got factory -- get the factory to instantiate the + // exception, initialize the exception members, and throw + // the exception. + // + try + { + factory->createAndThrow(); + } + catch(UserException& ex) + { + ex.__read(this, false); + if(usesClasses) + { + readPendingObjects(); + } + ex.ice_throw(); + } + } + else + { + // + // Performance sensitive, so we use lazy initialization + // for tracing. + // + if(_traceSlicing == -1) + { + _traceSlicing = _instance->traceLevels()->slicing; + _slicingCat = _instance->traceLevels()->slicingCat; + } + if(_traceSlicing > 0) + { + traceSlicing("exception", id, _slicingCat, _instance->initializationData().logger); + } + skipSlice(); // Slice off what we don't understand. + read(id, false); // Read type id for next slice. + } } // @@ -1827,35 +1827,35 @@ IceInternal::BasicStream::writePendingObjects() { if(_currentWriteEncaps && _currentWriteEncaps->toBeMarshaledMap) { - while(_currentWriteEncaps->toBeMarshaledMap->size()) - { - PtrToIndexMap savedMap = *_currentWriteEncaps->toBeMarshaledMap; - writeSize(static_cast(savedMap.size())); - for(PtrToIndexMap::iterator p = savedMap.begin(); p != savedMap.end(); ++p) - { - // - // Add an instance from the old to-be-marshaled map to - // the marshaled map and then ask the instance to - // marshal itself. Any new class instances that are - // triggered by the classes marshaled are added to - // toBeMarshaledMap. - // - _currentWriteEncaps->marshaledMap->insert(*p); - writeInstance(p->first, p->second); - } - - // - // We have marshaled all the instances for this pass, - // substract what we have marshaled from the - // toBeMarshaledMap. - // - PtrToIndexMap newMap; - set_difference(_currentWriteEncaps->toBeMarshaledMap->begin(), - _currentWriteEncaps->toBeMarshaledMap->end(), - savedMap.begin(), savedMap.end(), - insert_iterator(newMap, newMap.begin())); - *_currentWriteEncaps->toBeMarshaledMap = newMap; - } + while(_currentWriteEncaps->toBeMarshaledMap->size()) + { + PtrToIndexMap savedMap = *_currentWriteEncaps->toBeMarshaledMap; + writeSize(static_cast(savedMap.size())); + for(PtrToIndexMap::iterator p = savedMap.begin(); p != savedMap.end(); ++p) + { + // + // Add an instance from the old to-be-marshaled map to + // the marshaled map and then ask the instance to + // marshal itself. Any new class instances that are + // triggered by the classes marshaled are added to + // toBeMarshaledMap. + // + _currentWriteEncaps->marshaledMap->insert(*p); + writeInstance(p->first, p->second); + } + + // + // We have marshaled all the instances for this pass, + // substract what we have marshaled from the + // toBeMarshaledMap. + // + PtrToIndexMap newMap; + set_difference(_currentWriteEncaps->toBeMarshaledMap->begin(), + _currentWriteEncaps->toBeMarshaledMap->end(), + savedMap.begin(), savedMap.end(), + insert_iterator(newMap, newMap.begin())); + *_currentWriteEncaps->toBeMarshaledMap = newMap; + } } writeSize(0); // Zero marker indicates end of sequence of sequences of instances. } @@ -1866,11 +1866,11 @@ IceInternal::BasicStream::readPendingObjects() Int num; do { - readSize(num); - for(Int k = num; k > 0; --k) - { - read(0, 0); - } + readSize(num); + for(Int k = num; k > 0; --k) + { + read(0, 0); + } } while(num); @@ -1970,7 +1970,7 @@ IceInternal::BasicStream::writeInstance(const ObjectPtr& v, Int index) void IceInternal::BasicStream::patchPointers(Int index, IndexToPtrMap::const_iterator unmarshaledPos, - PatchMap::iterator patchPos) + PatchMap::iterator patchPos) { // // Called whenever we have unmarshaled a new instance. The index @@ -1981,34 +1981,34 @@ IceInternal::BasicStream::patchPointers(Int index, IndexToPtrMap::const_iterator // with the new address. // assert( (unmarshaledPos != _currentReadEncaps->unmarshaledMap->end() - && patchPos == _currentReadEncaps->patchMap->end()) - || (unmarshaledPos == _currentReadEncaps->unmarshaledMap->end() - && patchPos != _currentReadEncaps->patchMap->end()) - ); + && patchPos == _currentReadEncaps->patchMap->end()) + || (unmarshaledPos == _currentReadEncaps->unmarshaledMap->end() + && patchPos != _currentReadEncaps->patchMap->end()) + ); if(unmarshaledPos != _currentReadEncaps->unmarshaledMap->end()) { - // - // We have just unmarshaled an instance -- check if something - // needs patching for that instance. - // - patchPos = _currentReadEncaps->patchMap->find(index); - if(patchPos == _currentReadEncaps->patchMap->end()) - { - return; // We don't have anything to patch for the instance just unmarshaled. - } + // + // We have just unmarshaled an instance -- check if something + // needs patching for that instance. + // + patchPos = _currentReadEncaps->patchMap->find(index); + if(patchPos == _currentReadEncaps->patchMap->end()) + { + return; // We don't have anything to patch for the instance just unmarshaled. + } } else { - // - // We have just unmarshaled an index -- check if we have - // unmarshaled the instance for that index yet. - // - unmarshaledPos = _currentReadEncaps->unmarshaledMap->find(index); - if(unmarshaledPos == _currentReadEncaps->unmarshaledMap->end()) - { - return; // We haven't unmarshaled the instance yet. - } + // + // We have just unmarshaled an index -- check if we have + // unmarshaled the instance for that index yet. + // + unmarshaledPos = _currentReadEncaps->unmarshaledMap->find(index); + if(unmarshaledPos == _currentReadEncaps->unmarshaledMap->end()) + { + return; // We haven't unmarshaled the instance yet. + } } assert(patchPos->second.size() > 0); @@ -2020,7 +2020,7 @@ IceInternal::BasicStream::patchPointers(Int index, IndexToPtrMap::const_iterator // for(PatchList::iterator k = patchPos->second.begin(); k != patchPos->second.end(); ++k) { - (*k->patchFunc)(k->patchAddr, v); + (*k->patchFunc)(k->patchAddr, v); } // diff --git a/cpp/src/Ice/Buffer.cpp b/cpp/src/Ice/Buffer.cpp index b0b4ffecdd7..ba09f6f3cfb 100644 --- a/cpp/src/Ice/Buffer.cpp +++ b/cpp/src/Ice/Buffer.cpp @@ -58,31 +58,31 @@ IceInternal::Buffer::Container::reserve(size_type n) { if(n > _capacity) { - _capacity = std::max(n, std::min(2 * _capacity, _maxCapacity)); - _capacity = std::max(static_cast(240), _capacity); + _capacity = std::max(n, std::min(2 * _capacity, _maxCapacity)); + _capacity = std::max(static_cast(240), _capacity); } else if(n < _capacity) { - _capacity = n; + _capacity = n; } else { - return; + return; } if(_buf) { - _buf = reinterpret_cast(::realloc(_buf, _capacity)); + _buf = reinterpret_cast(::realloc(_buf, _capacity)); } else { - _buf = reinterpret_cast(::malloc(_capacity)); + _buf = reinterpret_cast(::malloc(_capacity)); } - + if(!_buf) { - SyscallException ex(__FILE__, __LINE__); - ex.error = getSystemErrno(); - throw ex; + SyscallException ex(__FILE__, __LINE__); + ex.error = getSystemErrno(); + throw ex; } } diff --git a/cpp/src/Ice/CommunicatorI.cpp b/cpp/src/Ice/CommunicatorI.cpp index ec72da06d01..c7ca49ea899 100644 --- a/cpp/src/Ice/CommunicatorI.cpp +++ b/cpp/src/Ice/CommunicatorI.cpp @@ -35,7 +35,7 @@ IceUtil::Handle theCollector = 0; struct GarbageCollectorStats { GarbageCollectorStats() : - runs(0), examined(0), collected(0) + runs(0), examined(0), collected(0) { } int runs; @@ -56,15 +56,15 @@ printGCStats(const IceInternal::GCStats& stats) { if(gcTraceLevel) { - if(gcTraceLevel > 1) - { - Trace out(getProcessLogger(), gcTraceCat); - out << stats.collected << "/" << stats.examined << ", " << stats.time * 1000 << "ms"; - } - ++gcStats.runs; - gcStats.examined += stats.examined; - gcStats.collected += stats.collected; - gcStats.time += stats.time; + if(gcTraceLevel > 1) + { + Trace out(getProcessLogger(), gcTraceCat); + out << stats.collected << "/" << stats.examined << ", " << stats.time * 1000 << "ms"; + } + ++gcStats.runs; + gcStats.examined += stats.examined; + gcStats.collected += stats.collected; + gcStats.time += stats.time; } } @@ -73,37 +73,37 @@ Ice::CommunicatorI::destroy() { if(_instance->destroy()) { - IceUtil::StaticMutex::Lock sync(gcMutex); - - // - // Wait for the collector thread to stop if this is the last communicator - // to be destroyed. - // - bool last = (--communicatorCount == 0); - if(last && gcInterval > 0 && theCollector) - { - theCollector->stop(); - } - - if(theCollector) + IceUtil::StaticMutex::Lock sync(gcMutex); + + // + // Wait for the collector thread to stop if this is the last communicator + // to be destroyed. + // + bool last = (--communicatorCount == 0); + if(last && gcInterval > 0 && theCollector) + { + theCollector->stop(); + } + + if(theCollector) { - theCollector->collectGarbage(); // Collect whenever a communicator is destroyed. - } - - if(last) - { - if(gcTraceLevel) - { - Trace out(getProcessLogger(), gcTraceCat); - out << "totals: " << gcStats.collected << "/" << gcStats.examined << ", " - << gcStats.time * 1000 << "ms" << ", " << gcStats.runs << " run"; - if(gcStats.runs != 1) - { - out << "s"; - } - } - theCollector = 0; // Force destruction of the collector. - } + theCollector->collectGarbage(); // Collect whenever a communicator is destroyed. + } + + if(last) + { + if(gcTraceLevel) + { + Trace out(getProcessLogger(), gcTraceCat); + out << "totals: " << gcStats.collected << "/" << gcStats.examined << ", " + << gcStats.time * 1000 << "ms" << ", " << gcStats.runs << " run"; + if(gcStats.runs != 1) + { + out << "s"; + } + } + theCollector = 0; // Force destruction of the collector. + } } } @@ -263,47 +263,47 @@ Ice::CommunicatorI::CommunicatorI(const InitializationData& initData) __setNoDelete(true); try { - const_cast(_instance) = new Instance(this, initData); + const_cast(_instance) = new Instance(this, initData); // // Keep a reference to the dynamic library list to ensure // the libraries are not unloaded until this Communicator's // destructor is invoked. // - const_cast(_dynamicLibraryList) = _instance->dynamicLibraryList(); + const_cast(_dynamicLibraryList) = _instance->dynamicLibraryList(); } catch(...) { - __setNoDelete(false); - throw; + __setNoDelete(false); + throw; } __setNoDelete(false); { - // - // If this is the first communicator that is created, use that communicator's - // property settings to determine whether to start the garbage collector. - // We remember that communicator's trace and logger settings so the garbage - // collector can continue to log messages even if the first communicator that - // is created isn't the last communicator to be destroyed. - // - IceUtil::StaticMutex::Lock sync(gcMutex); - static bool gcOnce = true; - if(gcOnce) - { - gcTraceLevel = _instance->traceLevels()->gc; - gcTraceCat = _instance->traceLevels()->gcCat; - gcInterval = _instance->initializationData().properties->getPropertyAsInt("Ice.GC.Interval"); - gcOnce = false; - } - if(++communicatorCount == 1) - { - theCollector = new IceInternal::GC(gcInterval, printGCStats); - if(gcInterval > 0) - { - theCollector->start(); - } - } + // + // If this is the first communicator that is created, use that communicator's + // property settings to determine whether to start the garbage collector. + // We remember that communicator's trace and logger settings so the garbage + // collector can continue to log messages even if the first communicator that + // is created isn't the last communicator to be destroyed. + // + IceUtil::StaticMutex::Lock sync(gcMutex); + static bool gcOnce = true; + if(gcOnce) + { + gcTraceLevel = _instance->traceLevels()->gc; + gcTraceCat = _instance->traceLevels()->gcCat; + gcInterval = _instance->initializationData().properties->getPropertyAsInt("Ice.GC.Interval"); + gcOnce = false; + } + if(++communicatorCount == 1) + { + theCollector = new IceInternal::GC(gcInterval, printGCStats); + if(gcInterval > 0) + { + theCollector->start(); + } + } } } @@ -311,8 +311,8 @@ Ice::CommunicatorI::~CommunicatorI() { if(!_instance->destroyed()) { - Warning out(_instance->initializationData().logger); - out << "Ice::Communicator::destroy() has not been called"; + Warning out(_instance->initializationData().logger); + out << "Ice::Communicator::destroy() has not been called"; } } @@ -321,11 +321,11 @@ Ice::CommunicatorI::finishSetup(int& argc, char* argv[]) { try { - _instance->finishSetup(argc, argv); + _instance->finishSetup(argc, argv); } catch(...) { - _instance->destroy(); - throw; + _instance->destroy(); + throw; } } diff --git a/cpp/src/Ice/ConnectionFactory.cpp b/cpp/src/Ice/ConnectionFactory.cpp index 5b33b528d5a..3008dfaa485 100644 --- a/cpp/src/Ice/ConnectionFactory.cpp +++ b/cpp/src/Ice/ConnectionFactory.cpp @@ -45,18 +45,18 @@ IceInternal::OutgoingConnectionFactory::destroy() if(_destroyed) { - return; + return; } #ifdef _STLP_BEGIN_NAMESPACE // voidbind2nd is an STLport extension for broken compilers in IceUtil/Functional.h for_each(_connections.begin(), _connections.end(), - voidbind2nd(Ice::secondVoidMemFun1 - (&ConnectionI::destroy), ConnectionI::CommunicatorDestroyed)); + voidbind2nd(Ice::secondVoidMemFun1 + (&ConnectionI::destroy), ConnectionI::CommunicatorDestroyed)); #else for_each(_connections.begin(), _connections.end(), - bind2nd(Ice::secondVoidMemFun1 - (&ConnectionI::destroy), ConnectionI::CommunicatorDestroyed)); + bind2nd(Ice::secondVoidMemFun1 + (&ConnectionI::destroy), ConnectionI::CommunicatorDestroyed)); #endif _destroyed = true; @@ -69,27 +69,27 @@ IceInternal::OutgoingConnectionFactory::waitUntilFinished() multimap connections; { - IceUtil::Monitor::Lock sync(*this); - - // - // First we wait until the factory is destroyed. We also wait - // until there are no pending connections anymore. Only then - // we can be sure the _connections contains all connections. - // - while(!_destroyed || !_pending.empty()) - { - wait(); - } - - // - // We want to wait until all connections are finished outside the - // thread synchronization. - // - connections.swap(_connections); + IceUtil::Monitor::Lock sync(*this); + + // + // First we wait until the factory is destroyed. We also wait + // until there are no pending connections anymore. Only then + // we can be sure the _connections contains all connections. + // + while(!_destroyed || !_pending.empty()) + { + wait(); + } + + // + // We want to wait until all connections are finished outside the + // thread synchronization. + // + connections.swap(_connections); } for_each(connections.begin(), connections.end(), - Ice::secondVoidMemFun(&ConnectionI::waitUntilFinished)); + Ice::secondVoidMemFun(&ConnectionI::waitUntilFinished)); } ConnectionIPtr @@ -100,131 +100,131 @@ IceInternal::OutgoingConnectionFactory::create(const vector& endpt vector endpoints = endpts; { - IceUtil::Monitor::Lock sync(*this); - - if(_destroyed) - { - throw CommunicatorDestroyedException(__FILE__, __LINE__); - } - - // - // Reap connections for which destruction has completed. - // - std::multimap::iterator p = _connections.begin(); - while(p != _connections.end()) - { - if(p->second->isFinished()) - { - _connections.erase(p++); - } - else - { - ++p; - } - } - - // - // Modify endpoints with overrides. - // - vector::iterator q; - for(q = endpoints.begin(); q != endpoints.end(); ++q) - { - if(_instance->defaultsAndOverrides()->overrideTimeout) - { - *q = (*q)->timeout(_instance->defaultsAndOverrides()->overrideTimeoutValue); - } - - // - // The Connection object does not take the compression flag of - // endpoints into account, but instead gets the information - // about whether messages should be compressed or not from - // other sources. In order to allow connection sharing for - // endpoints that differ in the value of the compression flag - // only, we always set the compression flag to false here in - // this connection factory. - // - *q = (*q)->compress(false); - } - - // - // Search for existing connections. - // - vector::const_iterator r; - for(q = endpoints.begin(), r = endpts.begin(); q != endpoints.end(); ++q, ++r) - { - pair::iterator, - multimap::iterator> pr = _connections.equal_range(*q); - - while(pr.first != pr.second) - { - // - // Don't return connections for which destruction has - // been initiated. The connection must also match the + IceUtil::Monitor::Lock sync(*this); + + if(_destroyed) + { + throw CommunicatorDestroyedException(__FILE__, __LINE__); + } + + // + // Reap connections for which destruction has completed. + // + std::multimap::iterator p = _connections.begin(); + while(p != _connections.end()) + { + if(p->second->isFinished()) + { + _connections.erase(p++); + } + else + { + ++p; + } + } + + // + // Modify endpoints with overrides. + // + vector::iterator q; + for(q = endpoints.begin(); q != endpoints.end(); ++q) + { + if(_instance->defaultsAndOverrides()->overrideTimeout) + { + *q = (*q)->timeout(_instance->defaultsAndOverrides()->overrideTimeoutValue); + } + + // + // The Connection object does not take the compression flag of + // endpoints into account, but instead gets the information + // about whether messages should be compressed or not from + // other sources. In order to allow connection sharing for + // endpoints that differ in the value of the compression flag + // only, we always set the compression flag to false here in + // this connection factory. + // + *q = (*q)->compress(false); + } + + // + // Search for existing connections. + // + vector::const_iterator r; + for(q = endpoints.begin(), r = endpts.begin(); q != endpoints.end(); ++q, ++r) + { + pair::iterator, + multimap::iterator> pr = _connections.equal_range(*q); + + while(pr.first != pr.second) + { + // + // Don't return connections for which destruction has + // been initiated. The connection must also match the // requested thread-per-connection setting. - // - if(!pr.first->second->isDestroyed() && + // + if(!pr.first->second->isDestroyed() && pr.first->second->threadPerConnection() == threadPerConnection) - { - if(_instance->defaultsAndOverrides()->overrideCompress) - { - compress = _instance->defaultsAndOverrides()->overrideCompressValue; - } - else - { - compress = (*r)->compress(); - } - - return pr.first->second; - } - - ++pr.first; - } - } - - // - // If some other thread is currently trying to establish a - // connection to any of our endpoints, we wait until this - // thread is finished. - // - bool searchAgain = false; - while(!_destroyed) - { - for(q = endpoints.begin(); q != endpoints.end(); ++q) - { - if(_pending.find(*q) != _pending.end()) - { - break; - } - } - - if(q == endpoints.end()) - { - break; - } - - searchAgain = true; - - wait(); - } - - if(_destroyed) - { - throw CommunicatorDestroyedException(__FILE__, __LINE__); - } - - // - // Search for existing connections again if we waited above, - // as new connections might have been added in the meantime. - // - if(searchAgain) - { - for(q = endpoints.begin(), r = endpts.begin(); q != endpoints.end(); ++q, ++r) - { - pair::iterator, - multimap::iterator> pr = _connections.equal_range(*q); - - while(pr.first != pr.second) - { + { + if(_instance->defaultsAndOverrides()->overrideCompress) + { + compress = _instance->defaultsAndOverrides()->overrideCompressValue; + } + else + { + compress = (*r)->compress(); + } + + return pr.first->second; + } + + ++pr.first; + } + } + + // + // If some other thread is currently trying to establish a + // connection to any of our endpoints, we wait until this + // thread is finished. + // + bool searchAgain = false; + while(!_destroyed) + { + for(q = endpoints.begin(); q != endpoints.end(); ++q) + { + if(_pending.find(*q) != _pending.end()) + { + break; + } + } + + if(q == endpoints.end()) + { + break; + } + + searchAgain = true; + + wait(); + } + + if(_destroyed) + { + throw CommunicatorDestroyedException(__FILE__, __LINE__); + } + + // + // Search for existing connections again if we waited above, + // as new connections might have been added in the meantime. + // + if(searchAgain) + { + for(q = endpoints.begin(), r = endpts.begin(); q != endpoints.end(); ++q, ++r) + { + pair::iterator, + multimap::iterator> pr = _connections.equal_range(*q); + + while(pr.first != pr.second) + { // // Don't return connections for which destruction has // been initiated. The connection must also match the @@ -232,31 +232,31 @@ IceInternal::OutgoingConnectionFactory::create(const vector& endpt // if(!pr.first->second->isDestroyed() && pr.first->second->threadPerConnection() == threadPerConnection) - { - if(_instance->defaultsAndOverrides()->overrideCompress) - { - compress = _instance->defaultsAndOverrides()->overrideCompressValue; - } - else - { - compress = (*r)->compress(); - } - - return pr.first->second; - } - - ++pr.first; - } - } - } - - // - // No connection to any of our endpoints exists yet, so we - // will try to create one. To avoid that other threads try to - // create connections to the same endpoints, we add our - // endpoints to _pending. - // - _pending.insert(endpoints.begin(), endpoints.end()); + { + if(_instance->defaultsAndOverrides()->overrideCompress) + { + compress = _instance->defaultsAndOverrides()->overrideCompressValue; + } + else + { + compress = (*r)->compress(); + } + + return pr.first->second; + } + + ++pr.first; + } + } + } + + // + // No connection to any of our endpoints exists yet, so we + // will try to create one. To avoid that other threads try to + // create connections to the same endpoints, we add our + // endpoints to _pending. + // + _pending.insert(endpoints.begin(), endpoints.end()); } ConnectionIPtr connection; @@ -266,112 +266,112 @@ IceInternal::OutgoingConnectionFactory::create(const vector& endpt vector::const_iterator r; for(q = endpoints.begin(), r = endpts.begin(); q != endpoints.end(); ++q, ++r) { - EndpointIPtr endpoint = *q; - - try - { - TransceiverPtr transceiver = endpoint->clientTransceiver(); - if(!transceiver) - { - ConnectorPtr connector = endpoint->connector(); - assert(connector); - - Int timeout; - if(_instance->defaultsAndOverrides()->overrideConnectTimeout) - { - timeout = _instance->defaultsAndOverrides()->overrideConnectTimeoutValue; - } - // It is not necessary to check for overrideTimeout, - // the endpoint has already been modified with this - // override, if set. - else - { - timeout = endpoint->timeout(); - } - - transceiver = connector->connect(timeout); - assert(transceiver); - } - connection = new ConnectionI(_instance, transceiver, endpoint, 0, threadPerConnection, + EndpointIPtr endpoint = *q; + + try + { + TransceiverPtr transceiver = endpoint->clientTransceiver(); + if(!transceiver) + { + ConnectorPtr connector = endpoint->connector(); + assert(connector); + + Int timeout; + if(_instance->defaultsAndOverrides()->overrideConnectTimeout) + { + timeout = _instance->defaultsAndOverrides()->overrideConnectTimeoutValue; + } + // It is not necessary to check for overrideTimeout, + // the endpoint has already been modified with this + // override, if set. + else + { + timeout = endpoint->timeout(); + } + + transceiver = connector->connect(timeout); + assert(transceiver); + } + connection = new ConnectionI(_instance, transceiver, endpoint, 0, threadPerConnection, _instance->threadPerConnectionStackSize()); - connection->validate(); - - if(_instance->defaultsAndOverrides()->overrideCompress) - { - compress = _instance->defaultsAndOverrides()->overrideCompressValue; - } - else - { - compress = (*r)->compress(); - } - break; - } - catch(const LocalException& ex) - { - exception.reset(dynamic_cast(ex.ice_clone())); - - // - // If a connection object was constructed, then validate() - // must have raised the exception. - // - if(connection) - { - connection->waitUntilFinished(); // We must call waitUntilFinished() for cleanup. - connection = 0; - } - } - - TraceLevelsPtr traceLevels = _instance->traceLevels(); - if(traceLevels->retry >= 2) - { - Trace out(_instance->initializationData().logger, traceLevels->retryCat); - - out << "connection to endpoint failed"; - if(moreEndpts || q + 1 != endpoints.end()) - { - out << ", trying next endpoint\n"; - } - else - { - out << " and no more endpoints to try\n"; - } - out << *exception.get(); - } + connection->validate(); + + if(_instance->defaultsAndOverrides()->overrideCompress) + { + compress = _instance->defaultsAndOverrides()->overrideCompressValue; + } + else + { + compress = (*r)->compress(); + } + break; + } + catch(const LocalException& ex) + { + exception.reset(dynamic_cast(ex.ice_clone())); + + // + // If a connection object was constructed, then validate() + // must have raised the exception. + // + if(connection) + { + connection->waitUntilFinished(); // We must call waitUntilFinished() for cleanup. + connection = 0; + } + } + + TraceLevelsPtr traceLevels = _instance->traceLevels(); + if(traceLevels->retry >= 2) + { + Trace out(_instance->initializationData().logger, traceLevels->retryCat); + + out << "connection to endpoint failed"; + if(moreEndpts || q + 1 != endpoints.end()) + { + out << ", trying next endpoint\n"; + } + else + { + out << " and no more endpoints to try\n"; + } + out << *exception.get(); + } } { - IceUtil::Monitor::Lock sync(*this); - - // - // Signal other threads that we are done with trying to - // establish connections to our endpoints. - // - for(q = endpoints.begin(); q != endpoints.end(); ++q) - { - _pending.erase(*q); - } - notifyAll(); - - if(!connection) - { - assert(exception.get()); - exception->ice_throw(); - } - else - { - _connections.insert(_connections.end(), - pair(connection->endpoint(), connection)); - - if(_destroyed) - { - connection->destroy(ConnectionI::CommunicatorDestroyed); - throw CommunicatorDestroyedException(__FILE__, __LINE__); - } - else - { - connection->activate(); - } - } + IceUtil::Monitor::Lock sync(*this); + + // + // Signal other threads that we are done with trying to + // establish connections to our endpoints. + // + for(q = endpoints.begin(); q != endpoints.end(); ++q) + { + _pending.erase(*q); + } + notifyAll(); + + if(!connection) + { + assert(exception.get()); + exception->ice_throw(); + } + else + { + _connections.insert(_connections.end(), + pair(connection->endpoint(), connection)); + + if(_destroyed) + { + connection->destroy(ConnectionI::CommunicatorDestroyed); + throw CommunicatorDestroyedException(__FILE__, __LINE__); + } + else + { + connection->activate(); + } + } } assert(connection); @@ -385,7 +385,7 @@ IceInternal::OutgoingConnectionFactory::setRouterInfo(const RouterInfoPtr& route if(_destroyed) { - throw CommunicatorDestroyedException(__FILE__, __LINE__); + throw CommunicatorDestroyedException(__FILE__, __LINE__); } assert(routerInfo); @@ -401,44 +401,44 @@ IceInternal::OutgoingConnectionFactory::setRouterInfo(const RouterInfoPtr& route vector::const_iterator p; for(p = endpoints.begin(); p != endpoints.end(); ++p) { - EndpointIPtr endpoint = *p; - - // - // Modify endpoints with overrides. - // - if(_instance->defaultsAndOverrides()->overrideTimeout) - { - endpoint = endpoint->timeout(_instance->defaultsAndOverrides()->overrideTimeoutValue); - } - - // - // The Connection object does not take the compression flag of - // endpoints into account, but instead gets the information - // about whether messages should be compressed or not from - // other sources. In order to allow connection sharing for - // endpoints that differ in the value of the compression flag - // only, we always set the compression flag to false here in - // this connection factory. - // - endpoint = endpoint->compress(false); - - pair::iterator, - multimap::iterator> pr = _connections.equal_range(endpoint); - - while(pr.first != pr.second) - { - try - { - pr.first->second->setAdapter(adapter); - } - catch(const Ice::LocalException&) - { - // - // Ignore, the connection is being closed or closed. - // - } - ++pr.first; - } + EndpointIPtr endpoint = *p; + + // + // Modify endpoints with overrides. + // + if(_instance->defaultsAndOverrides()->overrideTimeout) + { + endpoint = endpoint->timeout(_instance->defaultsAndOverrides()->overrideTimeoutValue); + } + + // + // The Connection object does not take the compression flag of + // endpoints into account, but instead gets the information + // about whether messages should be compressed or not from + // other sources. In order to allow connection sharing for + // endpoints that differ in the value of the compression flag + // only, we always set the compression flag to false here in + // this connection factory. + // + endpoint = endpoint->compress(false); + + pair::iterator, + multimap::iterator> pr = _connections.equal_range(endpoint); + + while(pr.first != pr.second) + { + try + { + pr.first->second->setAdapter(adapter); + } + catch(const Ice::LocalException&) + { + // + // Ignore, the connection is being closed or closed. + // + } + ++pr.first; + } } } @@ -449,24 +449,24 @@ IceInternal::OutgoingConnectionFactory::removeAdapter(const ObjectAdapterPtr& ad if(_destroyed) { - return; + return; } for(multimap::const_iterator p = _connections.begin(); p != _connections.end(); ++p) { - if(p->second->getAdapter() == adapter) - { - try - { - p->second->setAdapter(0); - } - catch(const Ice::LocalException&) - { - // - // Ignore, the connection is being closed or closed. - // - } - } + if(p->second->getAdapter() == adapter) + { + try + { + p->second->setAdapter(0); + } + catch(const Ice::LocalException&) + { + // + // Ignore, the connection is being closed or closed. + // + } + } } } @@ -476,26 +476,26 @@ IceInternal::OutgoingConnectionFactory::flushBatchRequests() list c; { - IceUtil::Monitor::Lock sync(*this); - - for(std::multimap::const_iterator p = _connections.begin(); - p != _connections.end(); - ++p) - { - c.push_back(p->second); - } + IceUtil::Monitor::Lock sync(*this); + + for(std::multimap::const_iterator p = _connections.begin(); + p != _connections.end(); + ++p) + { + c.push_back(p->second); + } } for(list::const_iterator p = c.begin(); p != c.end(); ++p) { - try - { - (*p)->flushBatchRequests(); - } - catch(const LocalException&) - { - // Ignore. - } + try + { + (*p)->flushBatchRequests(); + } + catch(const LocalException&) + { + // Ignore. + } } } @@ -538,22 +538,22 @@ IceInternal::IncomingConnectionFactory::waitUntilHolding() const list connections; { - IceUtil::Monitor::Lock sync(*this); - - // - // First we wait until the connection factory itself is in holding - // state. - // - while(_state < StateHolding) - { - wait(); - } - - // - // We want to wait until all connections are in holding state - // outside the thread synchronization. - // - connections = _connections; + IceUtil::Monitor::Lock sync(*this); + + // + // First we wait until the connection factory itself is in holding + // state. + // + while(_state < StateHolding) + { + wait(); + } + + // + // We want to wait until all connections are in holding state + // outside the thread synchronization. + // + connections = _connections; } // @@ -569,35 +569,35 @@ IceInternal::IncomingConnectionFactory::waitUntilFinished() list connections; { - IceUtil::Monitor::Lock sync(*this); - - // - // First we wait until the factory is destroyed. If we are using - // an acceptor, we also wait for it to be closed. - // - while(_state != StateClosed || _acceptor) - { - wait(); - } - - threadPerIncomingConnectionFactory = _threadPerIncomingConnectionFactory; - _threadPerIncomingConnectionFactory = 0; - - // - // Clear the OA. See bug 1673 for the details of why this is necessary. - // - _adapter = 0; - - // - // We want to wait until all connections are finished outside the - // thread synchronization. - // - connections.swap(_connections); + IceUtil::Monitor::Lock sync(*this); + + // + // First we wait until the factory is destroyed. If we are using + // an acceptor, we also wait for it to be closed. + // + while(_state != StateClosed || _acceptor) + { + wait(); + } + + threadPerIncomingConnectionFactory = _threadPerIncomingConnectionFactory; + _threadPerIncomingConnectionFactory = 0; + + // + // Clear the OA. See bug 1673 for the details of why this is necessary. + // + _adapter = 0; + + // + // We want to wait until all connections are finished outside the + // thread synchronization. + // + connections.swap(_connections); } if(threadPerIncomingConnectionFactory) { - threadPerIncomingConnectionFactory->getThreadControl().join(); + threadPerIncomingConnectionFactory->getThreadControl().join(); } for_each(connections.begin(), connections.end(), Ice::voidMemFun(&ConnectionI::waitUntilFinished)); @@ -615,7 +615,7 @@ IceInternal::IncomingConnectionFactory::equivalent(const EndpointIPtr& endp) con { if(_transceiver) { - return endp->equivalent(_transceiver); + return endp->equivalent(_transceiver); } assert(_acceptor); @@ -633,7 +633,7 @@ IceInternal::IncomingConnectionFactory::connections() const // Only copy connections which have not been destroyed. // remove_copy_if(_connections.begin(), _connections.end(), back_inserter(result), - Ice::constMemFun(&ConnectionI::isDestroyed)); + Ice::constMemFun(&ConnectionI::isDestroyed)); return result; } @@ -645,14 +645,14 @@ IceInternal::IncomingConnectionFactory::flushBatchRequests() for(list::const_iterator p = c.begin(); p != c.end(); ++p) { - try - { - (*p)->flushBatchRequests(); - } - catch(const LocalException&) - { - // Ignore. - } + try + { + (*p)->flushBatchRequests(); + } + catch(const LocalException&) + { + // Ignore. + } } } @@ -682,13 +682,13 @@ class PromoteFollower public: PromoteFollower(const ThreadPoolPtr& threadPool) : - _threadPool(threadPool) + _threadPool(threadPool) { } ~PromoteFollower() { - _threadPool->promoteFollower(); + _threadPool->promoteFollower(); } private: @@ -704,73 +704,73 @@ IceInternal::IncomingConnectionFactory::message(BasicStream&, const ThreadPoolPt ConnectionIPtr connection; { - IceUtil::Monitor::Lock sync(*this); - - // - // This makes sure that we promote a follower before we leave - // the scope of the mutex above, but after we call accept() - // (if we call it). - // - // If _threadPool is null, then this class doesn't do - // anything. - // - PromoteFollower promote(threadPool); - - if(_state != StateActive) - { - IceUtil::ThreadControl::yield(); - return; - } - - // - // Reap connections for which destruction has completed. - // - _connections.erase(remove_if(_connections.begin(), _connections.end(), - Ice::constMemFun(&ConnectionI::isFinished)), - _connections.end()); - - // - // Now accept a new connection. - // - TransceiverPtr transceiver; - try - { - transceiver = _acceptor->accept(0); - } - catch(const SocketException&) - { - // Ignore socket exceptions. - return; - } - catch(const TimeoutException&) - { - // Ignore timeouts. - return; - } - catch(const LocalException& ex) - { - // Warn about other Ice local exceptions. - if(_warn) - { - Warning out(_instance->initializationData().logger); - out << "connection exception:\n" << ex << '\n' << _acceptor->toString(); - } - return; - } - - assert(transceiver); - - try - { - connection = new ConnectionI(_instance, transceiver, _endpoint, _adapter, _threadPerConnection, + IceUtil::Monitor::Lock sync(*this); + + // + // This makes sure that we promote a follower before we leave + // the scope of the mutex above, but after we call accept() + // (if we call it). + // + // If _threadPool is null, then this class doesn't do + // anything. + // + PromoteFollower promote(threadPool); + + if(_state != StateActive) + { + IceUtil::ThreadControl::yield(); + return; + } + + // + // Reap connections for which destruction has completed. + // + _connections.erase(remove_if(_connections.begin(), _connections.end(), + Ice::constMemFun(&ConnectionI::isFinished)), + _connections.end()); + + // + // Now accept a new connection. + // + TransceiverPtr transceiver; + try + { + transceiver = _acceptor->accept(0); + } + catch(const SocketException&) + { + // Ignore socket exceptions. + return; + } + catch(const TimeoutException&) + { + // Ignore timeouts. + return; + } + catch(const LocalException& ex) + { + // Warn about other Ice local exceptions. + if(_warn) + { + Warning out(_instance->initializationData().logger); + out << "connection exception:\n" << ex << '\n' << _acceptor->toString(); + } + return; + } + + assert(transceiver); + + try + { + connection = new ConnectionI(_instance, transceiver, _endpoint, _adapter, _threadPerConnection, _threadPerConnectionStackSize); - } - catch(const LocalException&) - { - return; - } + } + catch(const LocalException&) + { + return; + } - _connections.push_back(connection); + _connections.push_back(connection); } assert(connection); @@ -781,14 +781,14 @@ IceInternal::IncomingConnectionFactory::message(BasicStream&, const ThreadPoolPt // try { - connection->validate(); + connection->validate(); } catch(const LocalException&) { - IceUtil::Monitor::Lock sync(*this); - connection->waitUntilFinished(); // We must call waitUntilFinished() for cleanup. - _connections.remove(connection); - return; + IceUtil::Monitor::Lock sync(*this); + connection->waitUntilFinished(); // We must call waitUntilFinished() for cleanup. + _connections.remove(connection); + return; } connection->activate(); @@ -808,10 +808,10 @@ IceInternal::IncomingConnectionFactory::finished(const ThreadPoolPtr& threadPool if(_finishedCount == 0 && _state == StateClosed) { - dynamic_cast(_adapter.get())->getThreadPool()->decFdsInUse(); - _acceptor->close(); - _acceptor = 0; - notifyAll(); + dynamic_cast(_adapter.get())->getThreadPool()->decFdsInUse(); + _acceptor->close(); + _acceptor = 0; + notifyAll(); } } @@ -828,7 +828,7 @@ IceInternal::IncomingConnectionFactory::toString() const if(_transceiver) { - return _transceiver->toString(); + return _transceiver->toString(); } assert(_acceptor); @@ -836,9 +836,9 @@ IceInternal::IncomingConnectionFactory::toString() const } IceInternal::IncomingConnectionFactory::IncomingConnectionFactory(const InstancePtr& instance, - const EndpointIPtr& endpoint, - const ObjectAdapterPtr& adapter, - const string& adapterName) : + const EndpointIPtr& endpoint, + const ObjectAdapterPtr& adapter, + const string& adapterName) : EventHandler(instance), _endpoint(endpoint), _adapter(adapter), @@ -849,14 +849,14 @@ IceInternal::IncomingConnectionFactory::IncomingConnectionFactory(const Instance { if(_instance->defaultsAndOverrides()->overrideTimeout) { - const_cast(_endpoint) = - _endpoint->timeout(_instance->defaultsAndOverrides()->overrideTimeoutValue); + const_cast(_endpoint) = + _endpoint->timeout(_instance->defaultsAndOverrides()->overrideTimeoutValue); } if(_instance->defaultsAndOverrides()->overrideCompress) { - const_cast(_endpoint) = - _endpoint->compress(_instance->defaultsAndOverrides()->overrideCompressValue); + const_cast(_endpoint) = + _endpoint->compress(_instance->defaultsAndOverrides()->overrideCompressValue); } ObjectAdapterI* adapterImpl = dynamic_cast(_adapter.get()); @@ -866,75 +866,75 @@ IceInternal::IncomingConnectionFactory::IncomingConnectionFactory(const Instance const_cast(_transceiver) = _endpoint->serverTransceiver(const_cast(_endpoint)); if(_transceiver) { - ConnectionIPtr connection; + ConnectionIPtr connection; - try - { - connection = new ConnectionI(_instance, _transceiver, _endpoint, _adapter, _threadPerConnection, + try + { + connection = new ConnectionI(_instance, _transceiver, _endpoint, _adapter, _threadPerConnection, _threadPerConnectionStackSize); - connection->validate(); - } - catch(const LocalException&) - { - // - // If a connection object was constructed, then validate() - // must have raised the exception. - // - if(connection) - { - connection->waitUntilFinished(); // We must call waitUntilFinished() for cleanup. - } - - return; - } - - _connections.push_back(connection); + connection->validate(); + } + catch(const LocalException&) + { + // + // If a connection object was constructed, then validate() + // must have raised the exception. + // + if(connection) + { + connection->waitUntilFinished(); // We must call waitUntilFinished() for cleanup. + } + + return; + } + + _connections.push_back(connection); } else { - _acceptor = _endpoint->acceptor(const_cast(_endpoint), adapterName); - assert(_acceptor); - _acceptor->listen(); - - __setNoDelete(true); - try - { - if(_threadPerConnection) - { - // - // If we are in thread per connection mode, we also use - // one thread per incoming connection factory, that - // accepts new connections on this endpoint. - // - _threadPerIncomingConnectionFactory = new ThreadPerIncomingConnectionFactory(this); - _threadPerIncomingConnectionFactory->start(_threadPerConnectionStackSize); - } - else - { - adapterImpl->getThreadPool()->incFdsInUse(); - } - } - catch(const IceUtil::Exception& ex) - { - if(_threadPerConnection) - { - Error out(_instance->initializationData().logger); - out << "cannot create thread for incoming connection factory:\n" << ex; - } - - try - { - _acceptor->close(); - } - catch(const LocalException&) - { - // Here we ignore any exceptions in close(). - } - - __setNoDelete(false); - ex.ice_throw(); - } - __setNoDelete(false); + _acceptor = _endpoint->acceptor(const_cast(_endpoint), adapterName); + assert(_acceptor); + _acceptor->listen(); + + __setNoDelete(true); + try + { + if(_threadPerConnection) + { + // + // If we are in thread per connection mode, we also use + // one thread per incoming connection factory, that + // accepts new connections on this endpoint. + // + _threadPerIncomingConnectionFactory = new ThreadPerIncomingConnectionFactory(this); + _threadPerIncomingConnectionFactory->start(_threadPerConnectionStackSize); + } + else + { + adapterImpl->getThreadPool()->incFdsInUse(); + } + } + catch(const IceUtil::Exception& ex) + { + if(_threadPerConnection) + { + Error out(_instance->initializationData().logger); + out << "cannot create thread for incoming connection factory:\n" << ex; + } + + try + { + _acceptor->close(); + } + catch(const LocalException&) + { + // Here we ignore any exceptions in close(). + } + + __setNoDelete(false); + ex.ice_throw(); + } + __setNoDelete(false); } } @@ -951,74 +951,74 @@ IceInternal::IncomingConnectionFactory::setState(State state) { if(_state == state) // Don't switch twice. { - return; + return; } switch(state) { - case StateActive: - { - if(_state != StateHolding) // Can only switch from holding to active. - { - return; - } - if(!_threadPerConnection && _acceptor) - { - registerWithPool(); - } - for_each(_connections.begin(), _connections.end(), Ice::voidMemFun(&ConnectionI::activate)); - break; - } - - case StateHolding: - { - if(_state != StateActive) // Can only switch from active to holding. - { - return; - } - if(!_threadPerConnection && _acceptor) - { - unregisterWithPool(); - } - for_each(_connections.begin(), _connections.end(), Ice::voidMemFun(&ConnectionI::hold)); - break; - } - - case StateClosed: - { - if(_acceptor) - { - if(_threadPerConnection) - { - // - // If we are in thread per connection mode, we connect - // to our own acceptor, which unblocks our thread per - // incoming connection factory stuck in accept(). - // - _acceptor->connectToSelf(); - } - else - { - // - // Otherwise we first must make sure that we are - // registered, then we unregister, and let finished() - // do the close. - // - registerWithPool(); - unregisterWithPool(); - } - } + case StateActive: + { + if(_state != StateHolding) // Can only switch from holding to active. + { + return; + } + if(!_threadPerConnection && _acceptor) + { + registerWithPool(); + } + for_each(_connections.begin(), _connections.end(), Ice::voidMemFun(&ConnectionI::activate)); + break; + } + + case StateHolding: + { + if(_state != StateActive) // Can only switch from active to holding. + { + return; + } + if(!_threadPerConnection && _acceptor) + { + unregisterWithPool(); + } + for_each(_connections.begin(), _connections.end(), Ice::voidMemFun(&ConnectionI::hold)); + break; + } + + case StateClosed: + { + if(_acceptor) + { + if(_threadPerConnection) + { + // + // If we are in thread per connection mode, we connect + // to our own acceptor, which unblocks our thread per + // incoming connection factory stuck in accept(). + // + _acceptor->connectToSelf(); + } + else + { + // + // Otherwise we first must make sure that we are + // registered, then we unregister, and let finished() + // do the close. + // + registerWithPool(); + unregisterWithPool(); + } + } #ifdef _STLP_BEGIN_NAMESPACE - // voidbind2nd is an STLport extension for broken compilers in IceUtil/Functional.h - for_each(_connections.begin(), _connections.end(), - voidbind2nd(Ice::voidMemFun1(&ConnectionI::destroy), ConnectionI::ObjectAdapterDeactivated)); + // voidbind2nd is an STLport extension for broken compilers in IceUtil/Functional.h + for_each(_connections.begin(), _connections.end(), + voidbind2nd(Ice::voidMemFun1(&ConnectionI::destroy), ConnectionI::ObjectAdapterDeactivated)); #else - for_each(_connections.begin(), _connections.end(), - bind2nd(Ice::voidMemFun1(&ConnectionI::destroy), ConnectionI::ObjectAdapterDeactivated)); + for_each(_connections.begin(), _connections.end(), + bind2nd(Ice::voidMemFun1(&ConnectionI::destroy), ConnectionI::ObjectAdapterDeactivated)); #endif - break; - } + break; + } } _state = state; @@ -1033,8 +1033,8 @@ IceInternal::IncomingConnectionFactory::registerWithPool() if(!_registeredWithPool) { - dynamic_cast(_adapter.get())->getThreadPool()->_register(_acceptor->fd(), this); - _registeredWithPool = true; + dynamic_cast(_adapter.get())->getThreadPool()->_register(_acceptor->fd(), this); + _registeredWithPool = true; } } @@ -1046,9 +1046,9 @@ IceInternal::IncomingConnectionFactory::unregisterWithPool() if(_registeredWithPool) { - dynamic_cast(_adapter.get())->getThreadPool()->unregister(_acceptor->fd()); - _registeredWithPool = false; - ++_finishedCount; // For each unregistration, finished() is called once. + dynamic_cast(_adapter.get())->getThreadPool()->unregister(_acceptor->fd()); + _registeredWithPool = false; + ++_finishedCount; // For each unregistration, finished() is called once. } } @@ -1059,111 +1059,111 @@ IceInternal::IncomingConnectionFactory::run() while(true) { - // - // We must accept new connections outside the thread - // synchronization, because we use blocking accept. - // - TransceiverPtr transceiver; - try - { - transceiver = _acceptor->accept(-1); - } - catch(const SocketException&) - { - // Ignore socket exceptions. - } - catch(const TimeoutException&) - { - // Ignore timeouts. - } - catch(const LocalException& ex) - { - // Warn about other Ice local exceptions. - if(_warn) - { - Warning out(_instance->initializationData().logger); - out << "connection exception:\n" << ex << '\n' << _acceptor->toString(); - } - } - - ConnectionIPtr connection; - - { - IceUtil::Monitor::Lock sync(*this); - - while(_state == StateHolding) - { - wait(); - } - - if(_state == StateClosed) - { - if(transceiver) - { - try - { - transceiver->close(); - } - catch(const LocalException&) - { - // Here we ignore any exceptions in close(). - } - } - - try - { - _acceptor->close(); - } - catch(const LocalException& ex) - { - _acceptor = 0; - notifyAll(); - ex.ice_throw(); - } - - _acceptor = 0; - notifyAll(); - return; - } - - assert(_state == StateActive); - - // - // Reap connections for which destruction has completed. - // - _connections.erase(remove_if(_connections.begin(), _connections.end(), - Ice::constMemFun(&ConnectionI::isFinished)), - _connections.end()); - - // - // Create a connection object for the connection. - // - if(transceiver) - { - try - { - connection = new ConnectionI(_instance, transceiver, _endpoint, _adapter, _threadPerConnection, + // + // We must accept new connections outside the thread + // synchronization, because we use blocking accept. + // + TransceiverPtr transceiver; + try + { + transceiver = _acceptor->accept(-1); + } + catch(const SocketException&) + { + // Ignore socket exceptions. + } + catch(const TimeoutException&) + { + // Ignore timeouts. + } + catch(const LocalException& ex) + { + // Warn about other Ice local exceptions. + if(_warn) + { + Warning out(_instance->initializationData().logger); + out << "connection exception:\n" << ex << '\n' << _acceptor->toString(); + } + } + + ConnectionIPtr connection; + + { + IceUtil::Monitor::Lock sync(*this); + + while(_state == StateHolding) + { + wait(); + } + + if(_state == StateClosed) + { + if(transceiver) + { + try + { + transceiver->close(); + } + catch(const LocalException&) + { + // Here we ignore any exceptions in close(). + } + } + + try + { + _acceptor->close(); + } + catch(const LocalException& ex) + { + _acceptor = 0; + notifyAll(); + ex.ice_throw(); + } + + _acceptor = 0; + notifyAll(); + return; + } + + assert(_state == StateActive); + + // + // Reap connections for which destruction has completed. + // + _connections.erase(remove_if(_connections.begin(), _connections.end(), + Ice::constMemFun(&ConnectionI::isFinished)), + _connections.end()); + + // + // Create a connection object for the connection. + // + if(transceiver) + { + try + { + connection = new ConnectionI(_instance, transceiver, _endpoint, _adapter, _threadPerConnection, _threadPerConnectionStackSize); - } - catch(const LocalException&) - { - return; - } - - _connections.push_back(connection); - } - } - - // - // In thread per connection mode, the connection's thread will - // take care of connection validation and activation (for - // non-datagram connections). We don't want to block this - // thread waiting until validation is complete, because in - // contrast to thread pool mode, it is the only thread that - // can accept connections with this factory's - // acceptor. Therefore we don't call validate() and activate() - // from the connection factory in thread per connection mode. - // + } + catch(const LocalException&) + { + return; + } + + _connections.push_back(connection); + } + } + + // + // In thread per connection mode, the connection's thread will + // take care of connection validation and activation (for + // non-datagram connections). We don't want to block this + // thread waiting until validation is complete, because in + // contrast to thread pool mode, it is the only thread that + // can accept connections with this factory's + // acceptor. Therefore we don't call validate() and activate() + // from the connection factory in thread per connection mode. + // } } @@ -1178,22 +1178,22 @@ IceInternal::IncomingConnectionFactory::ThreadPerIncomingConnectionFactory::run( { try { - _factory->run(); + _factory->run(); } catch(const Exception& ex) - { - Error out(_factory->_instance->initializationData().logger); - out << "exception in thread per incoming connection factory:\n" << _factory->toString() << ex; + { + Error out(_factory->_instance->initializationData().logger); + out << "exception in thread per incoming connection factory:\n" << _factory->toString() << ex; } catch(const std::exception& ex) { - Error out(_factory->_instance->initializationData().logger); - out << "std::exception in thread per incoming connection factory:\n" << _factory->toString() << ex.what(); + Error out(_factory->_instance->initializationData().logger); + out << "std::exception in thread per incoming connection factory:\n" << _factory->toString() << ex.what(); } catch(...) { - Error out(_factory->_instance->initializationData().logger); - out << "unknown exception in thread per incoming connection factory:\n" << _factory->toString(); + Error out(_factory->_instance->initializationData().logger); + out << "unknown exception in thread per incoming connection factory:\n" << _factory->toString(); } _factory = 0; // Resolve cyclic dependency. diff --git a/cpp/src/Ice/ConnectionFactory.h b/cpp/src/Ice/ConnectionFactory.h index d7e58df05f5..7758e675b8d 100644 --- a/cpp/src/Ice/ConnectionFactory.h +++ b/cpp/src/Ice/ConnectionFactory.h @@ -91,15 +91,15 @@ public: private: IncomingConnectionFactory(const InstancePtr&, const EndpointIPtr&, const Ice::ObjectAdapterPtr&, - const std::string&); + const std::string&); virtual ~IncomingConnectionFactory(); friend class Ice::ObjectAdapterI; enum State { - StateActive, - StateHolding, - StateClosed + StateActive, + StateHolding, + StateClosed }; void setState(State); @@ -111,13 +111,13 @@ private: class ThreadPerIncomingConnectionFactory : public IceUtil::Thread { public: - - ThreadPerIncomingConnectionFactory(const IncomingConnectionFactoryPtr&); - virtual void run(); + + ThreadPerIncomingConnectionFactory(const IncomingConnectionFactoryPtr&); + virtual void run(); private: - - IncomingConnectionFactoryPtr _factory; + + IncomingConnectionFactoryPtr _factory; }; friend class ThreadPerIncomingConnectionFactory; IceUtil::ThreadPtr _threadPerIncomingConnectionFactory; diff --git a/cpp/src/Ice/ConnectionI.cpp b/cpp/src/Ice/ConnectionI.cpp index d832f87a886..22b4c28cf23 100644 --- a/cpp/src/Ice/ConnectionI.cpp +++ b/cpp/src/Ice/ConnectionI.cpp @@ -41,189 +41,189 @@ Ice::ConnectionI::validate() if(!_endpoint->datagram()) // Datagram connections are always implicitly validated. { - { - IceUtil::Monitor::Lock sync(*this); - - if(_thread && _thread->getThreadControl() != IceUtil::ThreadControl()) - { - // - // In thread per connection mode, this connection's thread - // will take care of connection validation. Therefore all we - // have to do here is to wait until this thread has completed - // validation. - // - while(_state == StateNotValidated) - { - wait(); - } - - if(_state >= StateClosing) - { - assert(_exception.get()); - _exception->ice_throw(); - } - - return; - } - - // - // The connection might already be closed (e.g.: the communicator - // was destroyed or object adapter deactivated.) - // - assert(_state == StateNotValidated || _state == StateClosed); - if(_state == StateClosed) - { - assert(_exception.get()); - _exception->ice_throw(); - } - - if(_adapter) - { - active = true; // The server side has the active role for connection validation. - } - else - { - active = false; // The client side has the passive role for connection validation. - } - } - - try - { - Int timeout; - if(_instance->defaultsAndOverrides()->overrideConnectTimeout) - { - timeout = _instance->defaultsAndOverrides()->overrideConnectTimeoutValue; - } - else - { - timeout = _endpoint->timeout(); - } - - if(active) - { - IceUtil::Mutex::Lock sendSync(_sendMutex); - - if(!_transceiver) // Has the transceiver already been closed? - { - assert(_exception.get()); - _exception->ice_throw(); // The exception is immutable at this point. - } - - BasicStream os(_instance.get()); - os.write(magic[0]); - os.write(magic[1]); - os.write(magic[2]); - os.write(magic[3]); - os.write(protocolMajor); - os.write(protocolMinor); - os.write(encodingMajor); - os.write(encodingMinor); - os.write(validateConnectionMsg); - os.write(static_cast(0)); // Compression status (always zero for validate connection). - os.write(headerSize); // Message size. - os.i = os.b.begin(); - traceHeader("sending validate connection", os, _logger, _traceLevels); - try - { - _transceiver->initialize(timeout); - _transceiver->write(os, timeout); - } - catch(const TimeoutException&) - { - throw ConnectTimeoutException(__FILE__, __LINE__); - } - } - else - { - BasicStream is(_instance.get()); - is.b.resize(headerSize); - is.i = is.b.begin(); - try - { - _transceiver->initialize(timeout); - _transceiver->read(is, timeout); - } - catch(const TimeoutException&) - { - throw ConnectTimeoutException(__FILE__, __LINE__); - } - assert(is.i == is.b.end()); - is.i = is.b.begin(); - Byte m[4]; - is.read(m[0]); - is.read(m[1]); - is.read(m[2]); - is.read(m[3]); - if(m[0] != magic[0] || m[1] != magic[1] || m[2] != magic[2] || m[3] != magic[3]) - { - BadMagicException ex(__FILE__, __LINE__); - ex.badMagic = Ice::ByteSeq(&m[0], &m[0] + sizeof(magic)); - throw ex; - } - Byte pMajor; - Byte pMinor; - is.read(pMajor); - is.read(pMinor); - if(pMajor != protocolMajor) - { - UnsupportedProtocolException ex(__FILE__, __LINE__); - ex.badMajor = static_cast(pMajor); - ex.badMinor = static_cast(pMinor); - ex.major = static_cast(protocolMajor); - ex.minor = static_cast(protocolMinor); - throw ex; - } - Byte eMajor; - Byte eMinor; - is.read(eMajor); - is.read(eMinor); - if(eMajor != encodingMajor) - { - UnsupportedEncodingException ex(__FILE__, __LINE__); - ex.badMajor = static_cast(eMajor); - ex.badMinor = static_cast(eMinor); - ex.major = static_cast(encodingMajor); - ex.minor = static_cast(encodingMinor); - throw ex; - } - Byte messageType; - is.read(messageType); - if(messageType != validateConnectionMsg) - { - throw ConnectionNotValidatedException(__FILE__, __LINE__); - } + { + IceUtil::Monitor::Lock sync(*this); + + if(_thread && _thread->getThreadControl() != IceUtil::ThreadControl()) + { + // + // In thread per connection mode, this connection's thread + // will take care of connection validation. Therefore all we + // have to do here is to wait until this thread has completed + // validation. + // + while(_state == StateNotValidated) + { + wait(); + } + + if(_state >= StateClosing) + { + assert(_exception.get()); + _exception->ice_throw(); + } + + return; + } + + // + // The connection might already be closed (e.g.: the communicator + // was destroyed or object adapter deactivated.) + // + assert(_state == StateNotValidated || _state == StateClosed); + if(_state == StateClosed) + { + assert(_exception.get()); + _exception->ice_throw(); + } + + if(_adapter) + { + active = true; // The server side has the active role for connection validation. + } + else + { + active = false; // The client side has the passive role for connection validation. + } + } + + try + { + Int timeout; + if(_instance->defaultsAndOverrides()->overrideConnectTimeout) + { + timeout = _instance->defaultsAndOverrides()->overrideConnectTimeoutValue; + } + else + { + timeout = _endpoint->timeout(); + } + + if(active) + { + IceUtil::Mutex::Lock sendSync(_sendMutex); + + if(!_transceiver) // Has the transceiver already been closed? + { + assert(_exception.get()); + _exception->ice_throw(); // The exception is immutable at this point. + } + + BasicStream os(_instance.get()); + os.write(magic[0]); + os.write(magic[1]); + os.write(magic[2]); + os.write(magic[3]); + os.write(protocolMajor); + os.write(protocolMinor); + os.write(encodingMajor); + os.write(encodingMinor); + os.write(validateConnectionMsg); + os.write(static_cast(0)); // Compression status (always zero for validate connection). + os.write(headerSize); // Message size. + os.i = os.b.begin(); + traceHeader("sending validate connection", os, _logger, _traceLevels); + try + { + _transceiver->initialize(timeout); + _transceiver->write(os, timeout); + } + catch(const TimeoutException&) + { + throw ConnectTimeoutException(__FILE__, __LINE__); + } + } + else + { + BasicStream is(_instance.get()); + is.b.resize(headerSize); + is.i = is.b.begin(); + try + { + _transceiver->initialize(timeout); + _transceiver->read(is, timeout); + } + catch(const TimeoutException&) + { + throw ConnectTimeoutException(__FILE__, __LINE__); + } + assert(is.i == is.b.end()); + is.i = is.b.begin(); + Byte m[4]; + is.read(m[0]); + is.read(m[1]); + is.read(m[2]); + is.read(m[3]); + if(m[0] != magic[0] || m[1] != magic[1] || m[2] != magic[2] || m[3] != magic[3]) + { + BadMagicException ex(__FILE__, __LINE__); + ex.badMagic = Ice::ByteSeq(&m[0], &m[0] + sizeof(magic)); + throw ex; + } + Byte pMajor; + Byte pMinor; + is.read(pMajor); + is.read(pMinor); + if(pMajor != protocolMajor) + { + UnsupportedProtocolException ex(__FILE__, __LINE__); + ex.badMajor = static_cast(pMajor); + ex.badMinor = static_cast(pMinor); + ex.major = static_cast(protocolMajor); + ex.minor = static_cast(protocolMinor); + throw ex; + } + Byte eMajor; + Byte eMinor; + is.read(eMajor); + is.read(eMinor); + if(eMajor != encodingMajor) + { + UnsupportedEncodingException ex(__FILE__, __LINE__); + ex.badMajor = static_cast(eMajor); + ex.badMinor = static_cast(eMinor); + ex.major = static_cast(encodingMajor); + ex.minor = static_cast(encodingMinor); + throw ex; + } + Byte messageType; + is.read(messageType); + if(messageType != validateConnectionMsg) + { + throw ConnectionNotValidatedException(__FILE__, __LINE__); + } Byte compress; is.read(compress); // Ignore compression status for validate connection. - Int size; - is.read(size); - if(size != headerSize) - { - throw IllegalMessageSizeException(__FILE__, __LINE__); - } - traceHeader("received validate connection", is, _logger, _traceLevels); - } - } - catch(const LocalException& ex) - { - IceUtil::Monitor::Lock sync(*this); - setState(StateClosed, ex); - assert(_exception.get()); - _exception->ice_throw(); - } - } - - { - IceUtil::Monitor::Lock sync(*this); - - if(_acmTimeout > 0) - { - _acmAbsoluteTimeout = IceUtil::Time::now() + IceUtil::Time::seconds(_acmTimeout); - } - - // - // We start out in holding state. - // - setState(StateHolding); + Int size; + is.read(size); + if(size != headerSize) + { + throw IllegalMessageSizeException(__FILE__, __LINE__); + } + traceHeader("received validate connection", is, _logger, _traceLevels); + } + } + catch(const LocalException& ex) + { + IceUtil::Monitor::Lock sync(*this); + setState(StateClosed, ex); + assert(_exception.get()); + _exception->ice_throw(); + } + } + + { + IceUtil::Monitor::Lock sync(*this); + + if(_acmTimeout > 0) + { + _acmAbsoluteTimeout = IceUtil::Time::now() + IceUtil::Time::seconds(_acmTimeout); + } + + // + // We start out in holding state. + // + setState(StateHolding); } } @@ -234,7 +234,7 @@ Ice::ConnectionI::activate() while(_state == StateNotValidated) { - wait(); + wait(); } setState(StateActive); @@ -247,7 +247,7 @@ Ice::ConnectionI::hold() while(_state == StateNotValidated) { - wait(); + wait(); } setState(StateHolding); @@ -260,17 +260,17 @@ Ice::ConnectionI::destroy(DestructionReason reason) switch(reason) { - case ObjectAdapterDeactivated: - { - setState(StateClosing, ObjectAdapterDeactivatedException(__FILE__, __LINE__)); - break; - } + case ObjectAdapterDeactivated: + { + setState(StateClosing, ObjectAdapterDeactivatedException(__FILE__, __LINE__)); + break; + } - case CommunicatorDestroyed: - { - setState(StateClosing, CommunicatorDestroyedException(__FILE__, __LINE__)); - break; - } + case CommunicatorDestroyed: + { + setState(StateClosing, CommunicatorDestroyedException(__FILE__, __LINE__)); + break; + } } } @@ -281,23 +281,23 @@ Ice::ConnectionI::close(bool force) if(force) { - setState(StateClosed, ForcedCloseConnectionException(__FILE__, __LINE__)); + setState(StateClosed, ForcedCloseConnectionException(__FILE__, __LINE__)); } else { - // - // If we do a graceful shutdown, then we wait until all - // outstanding requests have been completed. Otherwise, the - // CloseConnectionException will cause all outstanding - // requests to be retried, regardless of whether the server - // has processed them or not. - // - while(!_requests.empty() || !_asyncRequests.empty()) - { - wait(); - } - - setState(StateClosing, CloseConnectionException(__FILE__, __LINE__)); + // + // If we do a graceful shutdown, then we wait until all + // outstanding requests have been completed. Otherwise, the + // CloseConnectionException will cause all outstanding + // requests to be retried, regardless of whether the server + // has processed them or not. + // + while(!_requests.empty() || !_asyncRequests.empty()) + { + wait(); + } + + setState(StateClosing, CloseConnectionException(__FILE__, __LINE__)); } } @@ -320,37 +320,37 @@ Ice::ConnectionI::isFinished() const IceUtil::ThreadPtr threadPerConnection; { - // - // We can use trylock here, because as long as there are still - // threads operating in this connection object, connection - // destruction is considered as not yet finished. - // - IceUtil::Monitor::TryLock sync(*this); - - if(!sync.acquired()) - { - return false; - } + // + // We can use trylock here, because as long as there are still + // threads operating in this connection object, connection + // destruction is considered as not yet finished. + // + IceUtil::Monitor::TryLock sync(*this); + + if(!sync.acquired()) + { + return false; + } - if(_transceiver || _dispatchCount != 0) - { - return false; - } + if(_transceiver || _dispatchCount != 0) + { + return false; + } - if(_thread && _thread->isAlive()) - { - return false; - } + if(_thread && _thread->isAlive()) + { + return false; + } - assert(_state == StateClosed); + assert(_state == StateClosed); - threadPerConnection = _thread; - _thread = 0; + threadPerConnection = _thread; + _thread = 0; } if(threadPerConnection) { - threadPerConnection->getThreadControl().join(); + threadPerConnection->getThreadControl().join(); } return true; @@ -363,8 +363,8 @@ Ice::ConnectionI::throwException() const if(_exception.get()) { - assert(_state >= StateClosing); - _exception->ice_throw(); + assert(_state >= StateClosing); + _exception->ice_throw(); } } @@ -375,7 +375,7 @@ Ice::ConnectionI::waitUntilHolding() const while(_state < StateHolding || _dispatchCount > 0) { - wait(); + wait(); } } @@ -385,76 +385,76 @@ Ice::ConnectionI::waitUntilFinished() IceUtil::ThreadPtr threadPerConnection; { - IceUtil::Monitor::Lock sync(*this); - - // - // We wait indefinitely until connection closing has been - // initiated. We also wait indefinitely until all outstanding - // requests are completed. Otherwise we couldn't guarantee - // that there are no outstanding calls when deactivate() is - // called on the servant locators. - // - while(_state < StateClosing || _dispatchCount > 0) - { - wait(); - } - - // - // Now we must wait until close() has been called on the - // transceiver. - // - while(_transceiver) - { - if(_state != StateClosed && _endpoint->timeout() >= 0) - { - IceUtil::Time timeout = IceUtil::Time::milliSeconds(_endpoint->timeout()); - IceUtil::Time waitTime = _stateTime + timeout - IceUtil::Time::now(); - - if(waitTime > IceUtil::Time()) - { - // - // We must wait a bit longer until we close this - // connection. - // - if(!timedWait(waitTime)) - { - setState(StateClosed, CloseTimeoutException(__FILE__, __LINE__)); - } - } - else - { - // - // We already waited long enough, so let's close this - // connection! - // - setState(StateClosed, CloseTimeoutException(__FILE__, __LINE__)); - } - - // - // No return here, we must still wait until close() is - // called on the _transceiver. - // - } - else - { - wait(); - } - } - - assert(_state == StateClosed); - - threadPerConnection = _thread; - _thread = 0; - - // - // Clear the OA. See bug 1673 for the details of why this is necessary. - // - _adapter = 0; + IceUtil::Monitor::Lock sync(*this); + + // + // We wait indefinitely until connection closing has been + // initiated. We also wait indefinitely until all outstanding + // requests are completed. Otherwise we couldn't guarantee + // that there are no outstanding calls when deactivate() is + // called on the servant locators. + // + while(_state < StateClosing || _dispatchCount > 0) + { + wait(); + } + + // + // Now we must wait until close() has been called on the + // transceiver. + // + while(_transceiver) + { + if(_state != StateClosed && _endpoint->timeout() >= 0) + { + IceUtil::Time timeout = IceUtil::Time::milliSeconds(_endpoint->timeout()); + IceUtil::Time waitTime = _stateTime + timeout - IceUtil::Time::now(); + + if(waitTime > IceUtil::Time()) + { + // + // We must wait a bit longer until we close this + // connection. + // + if(!timedWait(waitTime)) + { + setState(StateClosed, CloseTimeoutException(__FILE__, __LINE__)); + } + } + else + { + // + // We already waited long enough, so let's close this + // connection! + // + setState(StateClosed, CloseTimeoutException(__FILE__, __LINE__)); + } + + // + // No return here, we must still wait until close() is + // called on the _transceiver. + // + } + else + { + wait(); + } + } + + assert(_state == StateClosed); + + threadPerConnection = _thread; + _thread = 0; + + // + // Clear the OA. See bug 1673 for the details of why this is necessary. + // + _adapter = 0; } if(threadPerConnection) { - threadPerConnection->getThreadControl().join(); + threadPerConnection->getThreadControl().join(); } } @@ -465,12 +465,12 @@ Ice::ConnectionI::monitor() if(!sync.acquired()) { - return; + return; } if(_state != StateActive) { - return; + return; } // @@ -478,11 +478,11 @@ Ice::ConnectionI::monitor() // for(map::iterator p = _asyncRequests.begin(); p != _asyncRequests.end(); ++p) { - if(p->second.t > IceUtil::Time() && p->second.t <= IceUtil::Time::now()) - { - setState(StateClosed, TimeoutException(__FILE__, __LINE__)); - return; - } + if(p->second.t > IceUtil::Time() && p->second.t <= IceUtil::Time::now()) + { + setState(StateClosed, TimeoutException(__FILE__, __LINE__)); + return; + } } // @@ -493,11 +493,11 @@ Ice::ConnectionI::monitor() !_batchStreamInUse && _batchStream.b.empty() && _dispatchCount == 0) { - if(IceUtil::Time::now() >= _acmAbsoluteTimeout) - { - setState(StateClosing, ConnectionTimeoutException(__FILE__, __LINE__)); - return; - } + if(IceUtil::Time::now() >= _acmAbsoluteTimeout) + { + setState(StateClosing, ConnectionTimeoutException(__FILE__, __LINE__)); + return; + } } } @@ -507,162 +507,162 @@ Ice::ConnectionI::sendRequest(BasicStream* os, Outgoing* out, bool compress) Int requestId; { - IceUtil::Monitor::Lock sync(*this); - - assert(!(out && _endpoint->datagram())); // Twoway requests cannot be datagrams. - - if(_exception.get()) - { - // - // If the connection is closed before we even have a chance - // to send our request, we always try to send the request - // again. - // - throw LocalExceptionWrapper(*_exception.get(), true); - } - - assert(_state > StateNotValidated); - assert(_state < StateClosing); - - // - // Only add to the request map if this is a twoway call. - // - if(out) - { - // - // Create a new unique request ID. - // - requestId = _nextRequestId++; - if(requestId <= 0) - { - _nextRequestId = 1; - requestId = _nextRequestId++; - } - - // - // Fill in the request ID. - // - const Byte* p = reinterpret_cast(&requestId); + IceUtil::Monitor::Lock sync(*this); + + assert(!(out && _endpoint->datagram())); // Twoway requests cannot be datagrams. + + if(_exception.get()) + { + // + // If the connection is closed before we even have a chance + // to send our request, we always try to send the request + // again. + // + throw LocalExceptionWrapper(*_exception.get(), true); + } + + assert(_state > StateNotValidated); + assert(_state < StateClosing); + + // + // Only add to the request map if this is a twoway call. + // + if(out) + { + // + // Create a new unique request ID. + // + requestId = _nextRequestId++; + if(requestId <= 0) + { + _nextRequestId = 1; + requestId = _nextRequestId++; + } + + // + // Fill in the request ID. + // + const Byte* p = reinterpret_cast(&requestId); #ifdef ICE_BIG_ENDIAN - reverse_copy(p, p + sizeof(Int), os->b.begin() + headerSize); + reverse_copy(p, p + sizeof(Int), os->b.begin() + headerSize); #else - copy(p, p + sizeof(Int), os->b.begin() + headerSize); + copy(p, p + sizeof(Int), os->b.begin() + headerSize); #endif - // - // Add to the requests map. - // - _requestsHint = _requests.insert(_requests.end(), pair(requestId, out)); - } - - if(_acmTimeout > 0) - { - _acmAbsoluteTimeout = IceUtil::Time::now() + IceUtil::Time::seconds(_acmTimeout); - } + // + // Add to the requests map. + // + _requestsHint = _requests.insert(_requests.end(), pair(requestId, out)); + } + + if(_acmTimeout > 0) + { + _acmAbsoluteTimeout = IceUtil::Time::now() + IceUtil::Time::seconds(_acmTimeout); + } } try { - IceUtil::Mutex::Lock sendSync(_sendMutex); - - if(!_transceiver) // Has the transceiver already been closed? - { - assert(_exception.get()); - _exception->ice_throw(); // The exception is immutable at this point. - } - - if(compress && os->b.size() >= 100) // Only compress messages larger than 100 bytes. - { - // - // Message compressed. Request compressed response, if any. - // - os->b[9] = 2; - - // - // Do compression. - // - BasicStream cstream(_instance.get()); - doCompress(*os, cstream); - - // - // Send the request. - // - os->i = os->b.begin(); - traceRequest("sending request", *os, _logger, _traceLevels); - cstream.i = cstream.b.begin(); - _transceiver->write(cstream, _endpoint->timeout()); - } - else - { - if(compress) - { - // - // Message not compressed. Request compressed response, if any. - // - os->b[9] = 1; - } - - // - // No compression, just fill in the message size. - // - Int sz = static_cast(os->b.size()); - const Byte* p = reinterpret_cast(&sz); + IceUtil::Mutex::Lock sendSync(_sendMutex); + + if(!_transceiver) // Has the transceiver already been closed? + { + assert(_exception.get()); + _exception->ice_throw(); // The exception is immutable at this point. + } + + if(compress && os->b.size() >= 100) // Only compress messages larger than 100 bytes. + { + // + // Message compressed. Request compressed response, if any. + // + os->b[9] = 2; + + // + // Do compression. + // + BasicStream cstream(_instance.get()); + doCompress(*os, cstream); + + // + // Send the request. + // + os->i = os->b.begin(); + traceRequest("sending request", *os, _logger, _traceLevels); + cstream.i = cstream.b.begin(); + _transceiver->write(cstream, _endpoint->timeout()); + } + else + { + if(compress) + { + // + // Message not compressed. Request compressed response, if any. + // + os->b[9] = 1; + } + + // + // No compression, just fill in the message size. + // + Int sz = static_cast(os->b.size()); + const Byte* p = reinterpret_cast(&sz); #ifdef ICE_BIG_ENDIAN - reverse_copy(p, p + sizeof(Int), os->b.begin() + 10); + reverse_copy(p, p + sizeof(Int), os->b.begin() + 10); #else - copy(p, p + sizeof(Int), os->b.begin() + 10); + copy(p, p + sizeof(Int), os->b.begin() + 10); #endif - - // - // Send the request. - // - os->i = os->b.begin(); - traceRequest("sending request", *os, _logger, _traceLevels); - _transceiver->write(*os, _endpoint->timeout()); - } + + // + // Send the request. + // + os->i = os->b.begin(); + traceRequest("sending request", *os, _logger, _traceLevels); + _transceiver->write(*os, _endpoint->timeout()); + } } catch(const LocalException& ex) { - IceUtil::Monitor::Lock sync(*this); - setState(StateClosed, ex); - assert(_exception.get()); - - if(out) - { - // - // If the request has already been removed from the - // request map, we are out of luck. It would mean that - // finished() has been called already, and therefore the - // exception has been set using the Outgoing::finished() - // callback. In this case, we cannot throw the exception - // here, because we must not both raise an exception and - // have Outgoing::finished() called with an - // exception. This means that in some rare cases, a - // request will not be retried even though it could. But I - // honestly don't know how I could avoid this, without a - // very elaborate and complex design, which would be bad - // for performance. - // - map::iterator p = _requests.find(requestId); - if(p != _requests.end()) - { - if(p == _requestsHint) - { - _requests.erase(p++); - _requestsHint = p; - } - else - { - _requests.erase(p); - } - - _exception->ice_throw(); - } - } - else - { - _exception->ice_throw(); - } + IceUtil::Monitor::Lock sync(*this); + setState(StateClosed, ex); + assert(_exception.get()); + + if(out) + { + // + // If the request has already been removed from the + // request map, we are out of luck. It would mean that + // finished() has been called already, and therefore the + // exception has been set using the Outgoing::finished() + // callback. In this case, we cannot throw the exception + // here, because we must not both raise an exception and + // have Outgoing::finished() called with an + // exception. This means that in some rare cases, a + // request will not be retried even though it could. But I + // honestly don't know how I could avoid this, without a + // very elaborate and complex design, which would be bad + // for performance. + // + map::iterator p = _requests.find(requestId); + if(p != _requests.end()) + { + if(p == _requestsHint) + { + _requests.erase(p++); + _requestsHint = p; + } + else + { + _requests.erase(p); + } + + _exception->ice_throw(); + } + } + else + { + _exception->ice_throw(); + } } } @@ -672,156 +672,156 @@ Ice::ConnectionI::sendAsyncRequest(BasicStream* os, const OutgoingAsyncPtr& out, Int requestId; { - IceUtil::Monitor::Lock sync(*this); - - assert(!_endpoint->datagram()); // Twoway requests cannot be datagrams, and async implies twoway. - - if(_exception.get()) - { - // - // If the exception is closed before we even have a chance - // to send our request, we always try to send the request - // again. - // - throw LocalExceptionWrapper(*_exception.get(), true); - } - - assert(_state > StateNotValidated); - assert(_state < StateClosing); - - // - // Create a new unique request ID. - // - requestId = _nextRequestId++; - if(requestId <= 0) - { - _nextRequestId = 1; - requestId = _nextRequestId++; - } - - // - // Fill in the request ID. - // - const Byte* p = reinterpret_cast(&requestId); + IceUtil::Monitor::Lock sync(*this); + + assert(!_endpoint->datagram()); // Twoway requests cannot be datagrams, and async implies twoway. + + if(_exception.get()) + { + // + // If the exception is closed before we even have a chance + // to send our request, we always try to send the request + // again. + // + throw LocalExceptionWrapper(*_exception.get(), true); + } + + assert(_state > StateNotValidated); + assert(_state < StateClosing); + + // + // Create a new unique request ID. + // + requestId = _nextRequestId++; + if(requestId <= 0) + { + _nextRequestId = 1; + requestId = _nextRequestId++; + } + + // + // Fill in the request ID. + // + const Byte* p = reinterpret_cast(&requestId); #ifdef ICE_BIG_ENDIAN - reverse_copy(p, p + sizeof(Int), os->b.begin() + headerSize); + reverse_copy(p, p + sizeof(Int), os->b.begin() + headerSize); #else - copy(p, p + sizeof(Int), os->b.begin() + headerSize); + copy(p, p + sizeof(Int), os->b.begin() + headerSize); #endif - - // - // Add to the async requests map. - // - struct AsyncRequest asyncRequest; - asyncRequest.p = out; - if(_endpoint->timeout() > 0) - { - asyncRequest.t = IceUtil::Time::now() + IceUtil::Time::milliSeconds(_endpoint->timeout()); - } - _asyncRequestsHint = _asyncRequests.insert(_asyncRequests.end(), - pair(requestId, asyncRequest)); - - if(_acmTimeout > 0) - { - _acmAbsoluteTimeout = IceUtil::Time::now() + IceUtil::Time::seconds(_acmTimeout); - } + + // + // Add to the async requests map. + // + struct AsyncRequest asyncRequest; + asyncRequest.p = out; + if(_endpoint->timeout() > 0) + { + asyncRequest.t = IceUtil::Time::now() + IceUtil::Time::milliSeconds(_endpoint->timeout()); + } + _asyncRequestsHint = _asyncRequests.insert(_asyncRequests.end(), + pair(requestId, asyncRequest)); + + if(_acmTimeout > 0) + { + _acmAbsoluteTimeout = IceUtil::Time::now() + IceUtil::Time::seconds(_acmTimeout); + } } try { - IceUtil::Mutex::Lock sendSync(_sendMutex); - - if(!_transceiver) // Has the transceiver already been closed? - { - assert(_exception.get()); - _exception->ice_throw(); // The exception is immutable at this point. - } - - if(compress && os->b.size() >= 100) // Only compress messages larger than 100 bytes. - { - // - // Message compressed. Request compressed response, if any. - // - os->b[9] = 2; - - // - // Do compression. - // - BasicStream cstream(_instance.get()); - doCompress(*os, cstream); - - // - // Send the request. - // - os->i = os->b.begin(); - traceRequest("sending asynchronous request", *os, _logger, _traceLevels); - cstream.i = cstream.b.begin(); - _transceiver->write(cstream, _endpoint->timeout()); - } - else - { - if(compress) - { - // - // Message not compressed. Request compressed response, if any. - // - os->b[9] = 1; - } - - // - // No compression, just fill in the message size. - // - Int sz = static_cast(os->b.size()); - const Byte* p = reinterpret_cast(&sz); + IceUtil::Mutex::Lock sendSync(_sendMutex); + + if(!_transceiver) // Has the transceiver already been closed? + { + assert(_exception.get()); + _exception->ice_throw(); // The exception is immutable at this point. + } + + if(compress && os->b.size() >= 100) // Only compress messages larger than 100 bytes. + { + // + // Message compressed. Request compressed response, if any. + // + os->b[9] = 2; + + // + // Do compression. + // + BasicStream cstream(_instance.get()); + doCompress(*os, cstream); + + // + // Send the request. + // + os->i = os->b.begin(); + traceRequest("sending asynchronous request", *os, _logger, _traceLevels); + cstream.i = cstream.b.begin(); + _transceiver->write(cstream, _endpoint->timeout()); + } + else + { + if(compress) + { + // + // Message not compressed. Request compressed response, if any. + // + os->b[9] = 1; + } + + // + // No compression, just fill in the message size. + // + Int sz = static_cast(os->b.size()); + const Byte* p = reinterpret_cast(&sz); #ifdef ICE_BIG_ENDIAN - reverse_copy(p, p + sizeof(Int), os->b.begin() + 10); + reverse_copy(p, p + sizeof(Int), os->b.begin() + 10); #else - copy(p, p + sizeof(Int), os->b.begin() + 10); + copy(p, p + sizeof(Int), os->b.begin() + 10); #endif - // - // Send the request. - // - os->i = os->b.begin(); - traceRequest("sending asynchronous request", *os, _logger, _traceLevels); - _transceiver->write(*os, _endpoint->timeout()); - } + // + // Send the request. + // + os->i = os->b.begin(); + traceRequest("sending asynchronous request", *os, _logger, _traceLevels); + _transceiver->write(*os, _endpoint->timeout()); + } } catch(const LocalException& ex) { - IceUtil::Monitor::Lock sync(*this); - setState(StateClosed, ex); - assert(_exception.get()); - - // - // If the request has already been removed from the async - // request map, we are out of luck. It would mean that - // finished() has been called already, and therefore the - // exception has been set using the - // OutgoingAsync::__finished() callback. In this case, we - // cannot throw the exception here, because we must not both - // raise an exception and have OutgoingAsync::__finished() - // called with an exception. This means that in some rare - // cases, a request will not be retried even though it - // could. But I honestly don't know how I could avoid this, - // without a very elaborate and complex design, which would be - // bad for performance. - // - map::iterator p = _asyncRequests.find(requestId); - if(p != _asyncRequests.end()) - { - if(p == _asyncRequestsHint) - { - _asyncRequests.erase(p++); - _asyncRequestsHint = p; - } - else - { - _asyncRequests.erase(p); - } - - _exception->ice_throw(); - } + IceUtil::Monitor::Lock sync(*this); + setState(StateClosed, ex); + assert(_exception.get()); + + // + // If the request has already been removed from the async + // request map, we are out of luck. It would mean that + // finished() has been called already, and therefore the + // exception has been set using the + // OutgoingAsync::__finished() callback. In this case, we + // cannot throw the exception here, because we must not both + // raise an exception and have OutgoingAsync::__finished() + // called with an exception. This means that in some rare + // cases, a request will not be retried even though it + // could. But I honestly don't know how I could avoid this, + // without a very elaborate and complex design, which would be + // bad for performance. + // + map::iterator p = _asyncRequests.find(requestId); + if(p != _asyncRequests.end()) + { + if(p == _asyncRequestsHint) + { + _asyncRequests.erase(p++); + _asyncRequestsHint = p; + } + else + { + _asyncRequests.erase(p); + } + + _exception->ice_throw(); + } } } @@ -835,12 +835,12 @@ Ice::ConnectionI::prepareBatchRequest(BasicStream* os) // while(_batchStreamInUse && !_exception.get()) { - wait(); + wait(); } if(_exception.get()) { - _exception->ice_throw(); + _exception->ice_throw(); } assert(_state > StateNotValidated); @@ -848,15 +848,15 @@ Ice::ConnectionI::prepareBatchRequest(BasicStream* os) if(_batchStream.b.empty()) { - try - { - _batchStream.writeBlob(requestBatchHdr, sizeof(requestBatchHdr)); - } - catch(const LocalException& ex) - { - setState(StateClosed, ex); - ex.ice_throw(); - } + try + { + _batchStream.writeBlob(requestBatchHdr, sizeof(requestBatchHdr)); + } + catch(const LocalException& ex) + { + setState(StateClosed, ex); + ex.ice_throw(); + } } _batchStreamInUse = true; @@ -884,41 +884,41 @@ Ice::ConnectionI::finishBatchRequest(BasicStream* os, bool compress) _batchStream.swap(*os); if(_batchAutoFlush) - { - IceUtil::Mutex::Lock sendSync(_sendMutex); - if(!_transceiver) - { - assert(_exception.get()); - _exception->ice_throw(); // The exception is immutable at this point. - } - - // - // Throw memory limit exception if the first message added causes us to - // go over limit. Otherwise put aside the marshalled message that caused - // limit to be exceeded and rollback stream to the marker. - // - try - { - _transceiver->checkSendSize(_batchStream, _instance->messageSizeMax()); - } - catch(const Ice::Exception&) - { - if(_batchRequestNum == 0) - { - resetBatch(true); - throw; - } - vector(_batchStream.b.begin() + _batchMarker, _batchStream.b.end()).swap(lastRequest); - _batchStream.b.resize(_batchMarker); - autoflush = true; - } - } - - if(!autoflush) - { - // - // Increment the number of requests in the batch. - // + { + IceUtil::Mutex::Lock sendSync(_sendMutex); + if(!_transceiver) + { + assert(_exception.get()); + _exception->ice_throw(); // The exception is immutable at this point. + } + + // + // Throw memory limit exception if the first message added causes us to + // go over limit. Otherwise put aside the marshalled message that caused + // limit to be exceeded and rollback stream to the marker. + // + try + { + _transceiver->checkSendSize(_batchStream, _instance->messageSizeMax()); + } + catch(const Ice::Exception&) + { + if(_batchRequestNum == 0) + { + resetBatch(true); + throw; + } + vector(_batchStream.b.begin() + _batchMarker, _batchStream.b.end()).swap(lastRequest); + _batchStream.b.resize(_batchMarker); + autoflush = true; + } + } + + if(!autoflush) + { + // + // Increment the number of requests in the batch. + // ++_batchRequestNum; // @@ -927,7 +927,7 @@ Ice::ConnectionI::finishBatchRequest(BasicStream* os, bool compress) // if(compress) { - _batchRequestCompress = true; + _batchRequestCompress = true; } // @@ -942,41 +942,41 @@ Ice::ConnectionI::finishBatchRequest(BasicStream* os, bool compress) if(autoflush) { // - // We have to keep _batchStreamInUse set until after we insert the - // saved marshalled data into a new stream. - // + // We have to keep _batchStreamInUse set until after we insert the + // saved marshalled data into a new stream. + // flushBatchRequestsInternal(true); IceUtil::Monitor::Lock sync(*this); - // - // Throw memory limit exception if the message that caused us to go over - // limit causes us to exceed the limit by itself. - // + // + // Throw memory limit exception if the message that caused us to go over + // limit causes us to exceed the limit by itself. + // if(sizeof(requestBatchHdr) + lastRequest.size() > _instance->messageSizeMax()) - { - resetBatch(true); - throw MemoryLimitException(__FILE__, __LINE__); - } - - // - // Start a new batch with the last message that caused us to - // go over the limit. - // - try - { - _batchStream.writeBlob(requestBatchHdr, sizeof(requestBatchHdr)); - _batchStream.writeBlob(&lastRequest[0], lastRequest.size()); - } - catch(const LocalException& ex) - { - setState(StateClosed, ex); - ex.ice_throw(); - } + { + resetBatch(true); + throw MemoryLimitException(__FILE__, __LINE__); + } + + // + // Start a new batch with the last message that caused us to + // go over the limit. + // + try + { + _batchStream.writeBlob(requestBatchHdr, sizeof(requestBatchHdr)); + _batchStream.writeBlob(&lastRequest[0], lastRequest.size()); + } + catch(const LocalException& ex) + { + setState(StateClosed, ex); + ex.ice_throw(); + } if(compress) { - _batchRequestCompress = true; + _batchRequestCompress = true; } // @@ -984,7 +984,7 @@ Ice::ConnectionI::finishBatchRequest(BasicStream* os, bool compress) // ++_batchRequestNum; _batchStreamInUse = false; - notifyAll(); + notifyAll(); } } @@ -1011,133 +1011,133 @@ void Ice::ConnectionI::flushBatchRequestsInternal(bool ignoreInUse) { { - IceUtil::Monitor::Lock sync(*this); - - if(!ignoreInUse) - { - while(_batchStreamInUse && !_exception.get()) - { - wait(); - } - } - - if(_exception.get()) - { - _exception->ice_throw(); - } - - if(_batchStream.b.empty()) - { - return; // Nothing to do. - } - - assert(_state > StateNotValidated); - assert(_state < StateClosing); - - _batchStream.i = _batchStream.b.begin(); - - if(_acmTimeout > 0) - { - _acmAbsoluteTimeout = IceUtil::Time::now() + IceUtil::Time::seconds(_acmTimeout); - } - - // - // Prevent that new batch requests are added while we are - // flushing. - // - _batchStreamInUse = true; + IceUtil::Monitor::Lock sync(*this); + + if(!ignoreInUse) + { + while(_batchStreamInUse && !_exception.get()) + { + wait(); + } + } + + if(_exception.get()) + { + _exception->ice_throw(); + } + + if(_batchStream.b.empty()) + { + return; // Nothing to do. + } + + assert(_state > StateNotValidated); + assert(_state < StateClosing); + + _batchStream.i = _batchStream.b.begin(); + + if(_acmTimeout > 0) + { + _acmAbsoluteTimeout = IceUtil::Time::now() + IceUtil::Time::seconds(_acmTimeout); + } + + // + // Prevent that new batch requests are added while we are + // flushing. + // + _batchStreamInUse = true; } try { - IceUtil::Mutex::Lock sendSync(_sendMutex); + IceUtil::Mutex::Lock sendSync(_sendMutex); - if(!_transceiver) // Has the transceiver already been closed? - { - assert(_exception.get()); - _exception->ice_throw(); // The exception is immutable at this point. - } + if(!_transceiver) // Has the transceiver already been closed? + { + assert(_exception.get()); + _exception->ice_throw(); // The exception is immutable at this point. + } - // - // Fill in the number of requests in the batch. - // - const Byte* p = reinterpret_cast(&_batchRequestNum); + // + // Fill in the number of requests in the batch. + // + const Byte* p = reinterpret_cast(&_batchRequestNum); #ifdef ICE_BIG_ENDIAN - reverse_copy(p, p + sizeof(Int), _batchStream.b.begin() + headerSize); + reverse_copy(p, p + sizeof(Int), _batchStream.b.begin() + headerSize); #else - copy(p, p + sizeof(Int), _batchStream.b.begin() + headerSize); + copy(p, p + sizeof(Int), _batchStream.b.begin() + headerSize); #endif - - if(_batchRequestCompress && _batchStream.b.size() >= 100) // Only compress messages larger than 100 bytes. - { - // - // Message compressed. Request compressed response, if any. - // - _batchStream.b[9] = 2; - - // - // Do compression. - // - BasicStream cstream(_instance.get()); - doCompress(_batchStream, cstream); - - // - // Send the batch request. - // - _batchStream.i = _batchStream.b.begin(); - traceBatchRequest("sending batch request", _batchStream, _logger, _traceLevels); - cstream.i = cstream.b.begin(); - _transceiver->write(cstream, _endpoint->timeout()); - } - else - { - if(_batchRequestCompress) - { - // - // Message not compressed. Request compressed response, if any. - // - _batchStream.b[9] = 1; - } - - // - // No compression, just fill in the message size. - // - Int sz = static_cast(_batchStream.b.size()); - const Byte* q = reinterpret_cast(&sz); + + if(_batchRequestCompress && _batchStream.b.size() >= 100) // Only compress messages larger than 100 bytes. + { + // + // Message compressed. Request compressed response, if any. + // + _batchStream.b[9] = 2; + + // + // Do compression. + // + BasicStream cstream(_instance.get()); + doCompress(_batchStream, cstream); + + // + // Send the batch request. + // + _batchStream.i = _batchStream.b.begin(); + traceBatchRequest("sending batch request", _batchStream, _logger, _traceLevels); + cstream.i = cstream.b.begin(); + _transceiver->write(cstream, _endpoint->timeout()); + } + else + { + if(_batchRequestCompress) + { + // + // Message not compressed. Request compressed response, if any. + // + _batchStream.b[9] = 1; + } + + // + // No compression, just fill in the message size. + // + Int sz = static_cast(_batchStream.b.size()); + const Byte* q = reinterpret_cast(&sz); #ifdef ICE_BIG_ENDIAN - reverse_copy(q, q + sizeof(Int), _batchStream.b.begin() + 10); + reverse_copy(q, q + sizeof(Int), _batchStream.b.begin() + 10); #else - copy(q, q + sizeof(Int), _batchStream.b.begin() + 10); + copy(q, q + sizeof(Int), _batchStream.b.begin() + 10); #endif - - // - // Send the batch request. - // - _batchStream.i = _batchStream.b.begin(); - traceBatchRequest("sending batch request", _batchStream, _logger, _traceLevels); - _transceiver->write(_batchStream, _endpoint->timeout()); - } + + // + // Send the batch request. + // + _batchStream.i = _batchStream.b.begin(); + traceBatchRequest("sending batch request", _batchStream, _logger, _traceLevels); + _transceiver->write(_batchStream, _endpoint->timeout()); + } } catch(const LocalException& ex) { - IceUtil::Monitor::Lock sync(*this); - setState(StateClosed, ex); - assert(_exception.get()); + IceUtil::Monitor::Lock sync(*this); + setState(StateClosed, ex); + assert(_exception.get()); - // - // Since batch requests are all oneways (or datagrams), we - // must report the exception to the caller. - // - _exception->ice_throw(); + // + // Since batch requests are all oneways (or datagrams), we + // must report the exception to the caller. + // + _exception->ice_throw(); } { - IceUtil::Monitor::Lock sync(*this); + IceUtil::Monitor::Lock sync(*this); - // - // Reset the batch stream, and notify that flushing is over. - // - resetBatch(!ignoreInUse); + // + // Reset the batch stream, and notify that flushing is over. + // + resetBatch(!ignoreInUse); } } @@ -1162,105 +1162,105 @@ Ice::ConnectionI::resetBatch(bool resetInUse) } } -void -Ice::ConnectionI::sendResponse(BasicStream* os, Byte compressFlag) -{ - try - { - IceUtil::Mutex::Lock sendSync(_sendMutex); - - if(!_transceiver) // Has the transceiver already been closed? - { - assert(_exception.get()); - _exception->ice_throw(); // The exception is immutable at this point. - } - - // - // Only compress if compression was requested by the client, - // and if the message is larger than 100 bytes. - // - if(compressFlag > 0 && os->b.size() >= 100) - { - // - // Message compressed. Request compressed response, if any. - // - os->b[9] = 2; - - // - // Do compression. - // - BasicStream cstream(_instance.get()); - doCompress(*os, cstream); - - // - // Send the reply. - // - os->i = os->b.begin(); - traceReply("sending reply", *os, _logger, _traceLevels); - cstream.i = cstream.b.begin(); - _transceiver->write(cstream, _endpoint->timeout()); - } - else - { - if(compressFlag > 0) - { - // - // Message not compressed. Request compressed response, if any. - // - os->b[9] = 1; - } - - // - // No compression, just fill in the message size. - // - Int sz = static_cast(os->b.size()); - const Byte* p = reinterpret_cast(&sz); +void +Ice::ConnectionI::sendResponse(BasicStream* os, Byte compressFlag) +{ + try + { + IceUtil::Mutex::Lock sendSync(_sendMutex); + + if(!_transceiver) // Has the transceiver already been closed? + { + assert(_exception.get()); + _exception->ice_throw(); // The exception is immutable at this point. + } + + // + // Only compress if compression was requested by the client, + // and if the message is larger than 100 bytes. + // + if(compressFlag > 0 && os->b.size() >= 100) + { + // + // Message compressed. Request compressed response, if any. + // + os->b[9] = 2; + + // + // Do compression. + // + BasicStream cstream(_instance.get()); + doCompress(*os, cstream); + + // + // Send the reply. + // + os->i = os->b.begin(); + traceReply("sending reply", *os, _logger, _traceLevels); + cstream.i = cstream.b.begin(); + _transceiver->write(cstream, _endpoint->timeout()); + } + else + { + if(compressFlag > 0) + { + // + // Message not compressed. Request compressed response, if any. + // + os->b[9] = 1; + } + + // + // No compression, just fill in the message size. + // + Int sz = static_cast(os->b.size()); + const Byte* p = reinterpret_cast(&sz); #ifdef ICE_BIG_ENDIAN - reverse_copy(p, p + sizeof(Int), os->b.begin() + 10); + reverse_copy(p, p + sizeof(Int), os->b.begin() + 10); #else - copy(p, p + sizeof(Int), os->b.begin() + 10); + copy(p, p + sizeof(Int), os->b.begin() + 10); #endif - - // - // Send the reply. - // - os->i = os->b.begin(); - traceReply("sending reply", *os, _logger, _traceLevels); - _transceiver->write(*os, _endpoint->timeout()); - } + + // + // Send the reply. + // + os->i = os->b.begin(); + traceReply("sending reply", *os, _logger, _traceLevels); + _transceiver->write(*os, _endpoint->timeout()); + } } catch(const LocalException& ex) { - IceUtil::Monitor::Lock sync(*this); - setState(StateClosed, ex); - } - - { - IceUtil::Monitor::Lock sync(*this); - - assert(_state > StateNotValidated); - - try - { - if(--_dispatchCount == 0) - { - notifyAll(); - } - - if(_state == StateClosing && _dispatchCount == 0) - { - initiateShutdown(); - } - - if(_acmTimeout > 0) - { - _acmAbsoluteTimeout = IceUtil::Time::now() + IceUtil::Time::seconds(_acmTimeout); - } - } - catch(const LocalException& ex) - { - setState(StateClosed, ex); - } + IceUtil::Monitor::Lock sync(*this); + setState(StateClosed, ex); + } + + { + IceUtil::Monitor::Lock sync(*this); + + assert(_state > StateNotValidated); + + try + { + if(--_dispatchCount == 0) + { + notifyAll(); + } + + if(_state == StateClosing && _dispatchCount == 0) + { + initiateShutdown(); + } + + if(_acmTimeout > 0) + { + _acmAbsoluteTimeout = IceUtil::Time::now() + IceUtil::Time::seconds(_acmTimeout); + } + } + catch(const LocalException& ex) + { + setState(StateClosed, ex); + } } } @@ -1273,19 +1273,19 @@ Ice::ConnectionI::sendNoResponse() try { - if(--_dispatchCount == 0) - { - notifyAll(); - } + if(--_dispatchCount == 0) + { + notifyAll(); + } - if(_state == StateClosing && _dispatchCount == 0) - { - initiateShutdown(); - } + if(_state == StateClosing && _dispatchCount == 0) + { + initiateShutdown(); + } } catch(const LocalException& ex) { - setState(StateClosed, ex); + setState(StateClosed, ex); } } @@ -1308,7 +1308,7 @@ Ice::ConnectionI::setAdapter(const ObjectAdapterPtr& adapter) if(_exception.get()) { - _exception->ice_throw(); + _exception->ice_throw(); } assert(_state < StateClosing); @@ -1317,15 +1317,15 @@ Ice::ConnectionI::setAdapter(const ObjectAdapterPtr& adapter) if(_adapter) { - _servantManager = dynamic_cast(_adapter.get())->getServantManager(); - if(!_servantManager) - { - _adapter = 0; - } + _servantManager = dynamic_cast(_adapter.get())->getServantManager(); + if(!_servantManager) + { + _adapter = 0; + } } else { - _servantManager = 0; + _servantManager = 0; } // @@ -1351,7 +1351,7 @@ Ice::ConnectionI::createProxy(const Identity& ident) const vector connections; connections.push_back(const_cast(this)); ReferencePtr ref = _instance->referenceFactory()->create(ident, _instance->getDefaultContext(), - "", Reference::ModeTwoway, connections); + "", Reference::ModeTwoway, connections); return _instance->proxyFactory()->referenceToProxy(ref); } @@ -1396,28 +1396,28 @@ Ice::ConnectionI::message(BasicStream& stream, const ThreadPoolPtr& threadPool) OutgoingAsyncPtr outAsync; { - IceUtil::Monitor::Lock sync(*this); + IceUtil::Monitor::Lock sync(*this); - // - // We must promote within the synchronization, otherwise there - // could be various race conditions with close connection - // messages and other messages. - // - threadPool->promoteFollower(); + // + // We must promote within the synchronization, otherwise there + // could be various race conditions with close connection + // messages and other messages. + // + threadPool->promoteFollower(); - if(_state != StateClosed) - { - parseMessage(stream, invokeNum, requestId, compress, servantManager, adapter, outAsync); - } + if(_state != StateClosed) + { + parseMessage(stream, invokeNum, requestId, compress, servantManager, adapter, outAsync); + } - // - // parseMessage() can close the connection, so we must check - // for closed state again. - // - if(_state == StateClosed) - { - return; - } + // + // parseMessage() can close the connection, so we must check + // for closed state again. + // + if(_state == StateClosed) + { + return; + } } // @@ -1426,7 +1426,7 @@ Ice::ConnectionI::message(BasicStream& stream, const ThreadPoolPtr& threadPool) // if(outAsync) { - outAsync->__finished(stream); + outAsync->__finished(stream); } // @@ -1450,57 +1450,57 @@ Ice::ConnectionI::finished(const ThreadPoolPtr& threadPool) map asyncRequests; { - IceUtil::Monitor::Lock sync(*this); - - --_finishedCount; - assert(threadPool.get() == _threadPool.get()); + IceUtil::Monitor::Lock sync(*this); + + --_finishedCount; + assert(threadPool.get() == _threadPool.get()); - if(_finishedCount == 0 && _state == StateClosed) - { - _threadPool->decFdsInUse(); + if(_finishedCount == 0 && _state == StateClosed) + { + _threadPool->decFdsInUse(); - // - // We must make sure that nobody is sending when we close - // the transceiver. - // - IceUtil::Mutex::Lock sendSync(_sendMutex); + // + // We must make sure that nobody is sending when we close + // the transceiver. + // + IceUtil::Mutex::Lock sendSync(_sendMutex); - try - { - _transceiver->close(); - } - catch(const LocalException& ex) - { - localEx.reset(dynamic_cast(ex.ice_clone())); - } + try + { + _transceiver->close(); + } + catch(const LocalException& ex) + { + localEx.reset(dynamic_cast(ex.ice_clone())); + } - _transceiver = 0; - notifyAll(); - } + _transceiver = 0; + notifyAll(); + } - if(_state == StateClosed || _state == StateClosing) - { - requests.swap(_requests); - _requestsHint = _requests.end(); + if(_state == StateClosed || _state == StateClosing) + { + requests.swap(_requests); + _requestsHint = _requests.end(); - asyncRequests.swap(_asyncRequests); - _asyncRequestsHint = _asyncRequests.end(); - } + asyncRequests.swap(_asyncRequests); + _asyncRequestsHint = _asyncRequests.end(); + } } for(map::iterator p = requests.begin(); p != requests.end(); ++p) { - p->second->finished(*_exception.get()); // The exception is immutable at this point. + p->second->finished(*_exception.get()); // The exception is immutable at this point. } for(map::iterator q = asyncRequests.begin(); q != asyncRequests.end(); ++q) { - q->second.p->__finished(*_exception.get()); // The exception is immutable at this point. + q->second.p->__finished(*_exception.get()); // The exception is immutable at this point. } if(localEx.get()) { - localEx->ice_throw(); + localEx->ice_throw(); } } @@ -1524,13 +1524,13 @@ Ice::ConnectionI::invokeException(const LocalException& ex, int invokeNum) if(invokeNum > 0) { - assert(_dispatchCount > 0); - _dispatchCount -= invokeNum; - assert(_dispatchCount >= 0); - if(_dispatchCount == 0) - { - notifyAll(); - } + assert(_dispatchCount > 0); + _dispatchCount -= invokeNum; + assert(_dispatchCount >= 0); + if(_dispatchCount == 0) + { + notifyAll(); + } } } @@ -1565,9 +1565,9 @@ Ice::ConnectionI::getTransceiver() const } Ice::ConnectionI::ConnectionI(const InstancePtr& instance, - const TransceiverPtr& transceiver, - const EndpointIPtr& endpoint, - const ObjectAdapterPtr& adapter, + const TransceiverPtr& transceiver, + const EndpointIPtr& endpoint, + const ObjectAdapterPtr& adapter, bool threadPerConnection, size_t threadPerConnectionStackSize) : EventHandler(instance), @@ -1601,92 +1601,92 @@ Ice::ConnectionI::ConnectionI(const InstancePtr& instance, Int& acmTimeout = const_cast(_acmTimeout); if(_endpoint->datagram()) { - acmTimeout = 0; + acmTimeout = 0; } else { - if(_adapter) - { - acmTimeout = _instance->serverACM(); - } - else - { - acmTimeout = _instance->clientACM(); - } + if(_adapter) + { + acmTimeout = _instance->serverACM(); + } + else + { + acmTimeout = _instance->clientACM(); + } } int& compressionLevel = const_cast(_compressionLevel); compressionLevel = _instance->initializationData().properties->getPropertyAsIntWithDefault( - "Ice.Compression.Level", 1); + "Ice.Compression.Level", 1); if(compressionLevel < 1) { - compressionLevel = 1; + compressionLevel = 1; } else if(compressionLevel > 9) { - compressionLevel = 9; + compressionLevel = 9; } ObjectAdapterI* adapterImpl = _adapter ? dynamic_cast(_adapter.get()) : 0; if(adapterImpl) { - _servantManager = adapterImpl->getServantManager(); + _servantManager = adapterImpl->getServantManager(); } __setNoDelete(true); try { - if(!threadPerConnection) - { - // - // Only set _threadPool if we really need it, i.e., if we are - // not in thread per connection mode. Thread pools have lazy - // initialization in Instance, and we don't want them to be - // created if they are not needed. - // - if(adapterImpl) - { - const_cast(_threadPool) = adapterImpl->getThreadPool(); - } - else - { - const_cast(_threadPool) = _instance->clientThreadPool(); - } - _threadPool->incFdsInUse(); - } - else - { - // - // If we are in thread per connection mode, create the - // thread for this connection. - // - _thread = new ThreadPerConnection(this); - _thread->start(threadPerConnectionStackSize); - } + if(!threadPerConnection) + { + // + // Only set _threadPool if we really need it, i.e., if we are + // not in thread per connection mode. Thread pools have lazy + // initialization in Instance, and we don't want them to be + // created if they are not needed. + // + if(adapterImpl) + { + const_cast(_threadPool) = adapterImpl->getThreadPool(); + } + else + { + const_cast(_threadPool) = _instance->clientThreadPool(); + } + _threadPool->incFdsInUse(); + } + else + { + // + // If we are in thread per connection mode, create the + // thread for this connection. + // + _thread = new ThreadPerConnection(this); + _thread->start(threadPerConnectionStackSize); + } } catch(const IceUtil::Exception& ex) { - { - Error out(_logger); - if(threadPerConnection) - { - out << "cannot create thread for connection:\n" << ex; - } - // Otherwise with thread pool the thread pool itself - // prints a warning if the threads cannot be created. - } - - try - { - _transceiver->close(); - } - catch(const LocalException&) - { - // Here we ignore any exceptions in close(). - } - - __setNoDelete(false); - ex.ice_throw(); + { + Error out(_logger); + if(threadPerConnection) + { + out << "cannot create thread for connection:\n" << ex; + } + // Otherwise with thread pool the thread pool itself + // prints a warning if the threads cannot be created. + } + + try + { + _transceiver->close(); + } + catch(const LocalException&) + { + // Here we ignore any exceptions in close(). + } + + __setNoDelete(false); + ex.ice_throw(); } __setNoDelete(false); } @@ -1710,40 +1710,40 @@ Ice::ConnectionI::setState(State state, const LocalException& ex) if(_state == state) // Don't switch twice. { - return; + return; } if(!_exception.get()) { - // - // If we are in closed state, an exception must be set. - // - assert(_state != StateClosed); - - _exception.reset(dynamic_cast(ex.ice_clone())); - - if(_warn) - { - // - // We don't warn if we are not validated. - // - if(_state > StateNotValidated) - { - // - // Don't warn about certain expected exceptions. - // - if(!(dynamic_cast(_exception.get()) || - dynamic_cast(_exception.get()) || - dynamic_cast(_exception.get()) || - dynamic_cast(_exception.get()) || - dynamic_cast(_exception.get()) || - (dynamic_cast(_exception.get()) && _state == StateClosing))) - { - Warning out(_logger); - out << "connection exception:\n" << *_exception.get() << '\n' << _desc; - } - } - } + // + // If we are in closed state, an exception must be set. + // + assert(_state != StateClosed); + + _exception.reset(dynamic_cast(ex.ice_clone())); + + if(_warn) + { + // + // We don't warn if we are not validated. + // + if(_state > StateNotValidated) + { + // + // Don't warn about certain expected exceptions. + // + if(!(dynamic_cast(_exception.get()) || + dynamic_cast(_exception.get()) || + dynamic_cast(_exception.get()) || + dynamic_cast(_exception.get()) || + dynamic_cast(_exception.get()) || + (dynamic_cast(_exception.get()) && _state == StateClosing))) + { + Warning out(_logger); + out << "connection exception:\n" << *_exception.get() << '\n' << _desc; + } + } + } } // @@ -1763,7 +1763,7 @@ Ice::ConnectionI::setState(State state) // if(_endpoint->datagram() && state == StateClosing) { - state = StateClosed; + state = StateClosed; } // @@ -1771,133 +1771,133 @@ Ice::ConnectionI::setState(State state) // if(_state == StateNotValidated && state == StateClosing) { - state = StateClosed; + state = StateClosed; } if(_state == state) // Don't switch twice. { - return; + return; } switch(state) { - case StateNotValidated: - { - assert(false); - break; - } + case StateNotValidated: + { + assert(false); + break; + } - case StateActive: - { - // + case StateActive: + { + // // Can only switch from holding or not validated to // active. - // - if(_state != StateHolding && _state != StateNotValidated) - { - return; - } - if(!_threadPerConnection) - { - registerWithPool(); - } - break; - } - - case StateHolding: - { - // - // Can only switch from active or not validated to - // holding. - // - if(_state != StateActive && _state != StateNotValidated) - { - return; - } - if(!_threadPerConnection) - { - unregisterWithPool(); - } - break; - } - - case StateClosing: - { - // - // Can't change back from closed. - // - if(_state == StateClosed) - { - return; - } - if(!_threadPerConnection) - { - registerWithPool(); // We need to continue to read in closing state. - } - break; - } - - case StateClosed: - { - if(_threadPerConnection) - { - // - // If we are in thread per connection mode, we - // shutdown both for reading and writing. This will - // unblock and read call with an exception. The thread - // per connection then closes the transceiver. - // - _transceiver->shutdownReadWrite(); - } - else if(_state == StateNotValidated) - { - // - // If we change from not validated we can close right - // away. - // - assert(!_registeredWithPool); - - _threadPool->decFdsInUse(); - - // - // We must make sure that nobody is sending when we - // close the transceiver. - // - IceUtil::Mutex::Lock sendSync(_sendMutex); - - try - { - _transceiver->close(); - } - catch(const LocalException&) - { - // Here we ignore any exceptions in close(). - } - - _transceiver = 0; - //notifyAll(); // We notify already below. - } - else - { - // - // Otherwise we first must make sure that we are - // registered, then we unregister, and let finished() - // do the close. - // - registerWithPool(); - unregisterWithPool(); - - // - // We must prevent any further writes when _state == StateClosed. - // However, functions such as sendResponse cannot acquire the main - // mutex in order to check _state. Therefore we shut down the write - // end of the transceiver, which causes subsequent write attempts - // to fail with an exception. - // - _transceiver->shutdownWrite(); - } - break; - } + // + if(_state != StateHolding && _state != StateNotValidated) + { + return; + } + if(!_threadPerConnection) + { + registerWithPool(); + } + break; + } + + case StateHolding: + { + // + // Can only switch from active or not validated to + // holding. + // + if(_state != StateActive && _state != StateNotValidated) + { + return; + } + if(!_threadPerConnection) + { + unregisterWithPool(); + } + break; + } + + case StateClosing: + { + // + // Can't change back from closed. + // + if(_state == StateClosed) + { + return; + } + if(!_threadPerConnection) + { + registerWithPool(); // We need to continue to read in closing state. + } + break; + } + + case StateClosed: + { + if(_threadPerConnection) + { + // + // If we are in thread per connection mode, we + // shutdown both for reading and writing. This will + // unblock and read call with an exception. The thread + // per connection then closes the transceiver. + // + _transceiver->shutdownReadWrite(); + } + else if(_state == StateNotValidated) + { + // + // If we change from not validated we can close right + // away. + // + assert(!_registeredWithPool); + + _threadPool->decFdsInUse(); + + // + // We must make sure that nobody is sending when we + // close the transceiver. + // + IceUtil::Mutex::Lock sendSync(_sendMutex); + + try + { + _transceiver->close(); + } + catch(const LocalException&) + { + // Here we ignore any exceptions in close(). + } + + _transceiver = 0; + //notifyAll(); // We notify already below. + } + else + { + // + // Otherwise we first must make sure that we are + // registered, then we unregister, and let finished() + // do the close. + // + registerWithPool(); + unregisterWithPool(); + + // + // We must prevent any further writes when _state == StateClosed. + // However, functions such as sendResponse cannot acquire the main + // mutex in order to check _state. Therefore we shut down the write + // end of the transceiver, which causes subsequent write attempts + // to fail with an exception. + // + _transceiver->shutdownWrite(); + } + break; + } } // @@ -1909,14 +1909,14 @@ Ice::ConnectionI::setState(State state) ConnectionMonitorPtr connectionMonitor = _instance->connectionMonitor(); if(connectionMonitor) { - if(state == StateActive) - { - connectionMonitor->add(this); - } - else if(_state == StateActive) - { - connectionMonitor->remove(this); - } + if(state == StateActive) + { + connectionMonitor->add(this); + } + else if(_state == StateActive) + { + connectionMonitor->remove(this); + } } _state = state; @@ -1926,14 +1926,14 @@ Ice::ConnectionI::setState(State state) if(_state == StateClosing && _dispatchCount == 0) { - try - { - initiateShutdown(); - } - catch(const LocalException& ex) - { - setState(StateClosed, ex); - } + try + { + initiateShutdown(); + } + catch(const LocalException& ex) + { + setState(StateClosed, ex); + } } } @@ -1945,39 +1945,39 @@ Ice::ConnectionI::initiateShutdown() const if(!_endpoint->datagram()) { - IceUtil::Mutex::Lock sendSync(_sendMutex); - - // - // Before we shut down, we send a close connection message. - // - BasicStream os(_instance.get()); - os.write(magic[0]); - os.write(magic[1]); - os.write(magic[2]); - os.write(magic[3]); - os.write(protocolMajor); - os.write(protocolMinor); - os.write(encodingMajor); - os.write(encodingMinor); - os.write(closeConnectionMsg); - os.write((Byte)1); // Compression status: compression supported but not used. - os.write(headerSize); // Message size. - - // - // Send the message. - // - os.i = os.b.begin(); - traceHeader("sending close connection", os, _logger, _traceLevels); - _transceiver->write(os, _endpoint->timeout()); - // - // The CloseConnection message should be sufficient. Closing the write - // end of the socket is probably an artifact of how things were done - // in IIOP. In fact, shutting down the write end of the socket causes - // problems on Windows by preventing the peer from using the socket. - // For example, the peer is no longer able to continue writing a large - // message after the socket is shutdown. - // - //_transceiver->shutdownWrite(); + IceUtil::Mutex::Lock sendSync(_sendMutex); + + // + // Before we shut down, we send a close connection message. + // + BasicStream os(_instance.get()); + os.write(magic[0]); + os.write(magic[1]); + os.write(magic[2]); + os.write(magic[3]); + os.write(protocolMajor); + os.write(protocolMinor); + os.write(encodingMajor); + os.write(encodingMinor); + os.write(closeConnectionMsg); + os.write((Byte)1); // Compression status: compression supported but not used. + os.write(headerSize); // Message size. + + // + // Send the message. + // + os.i = os.b.begin(); + traceHeader("sending close connection", os, _logger, _traceLevels); + _transceiver->write(os, _endpoint->timeout()); + // + // The CloseConnection message should be sufficient. Closing the write + // end of the socket is probably an artifact of how things were done + // in IIOP. In fact, shutting down the write end of the socket causes + // problems on Windows by preventing the peer from using the socket. + // For example, the peer is no longer able to continue writing a large + // message after the socket is shutdown. + // + //_transceiver->shutdownWrite(); } } @@ -1988,8 +1988,8 @@ Ice::ConnectionI::registerWithPool() if(!_registeredWithPool) { - _threadPool->_register(_transceiver->fd(), this); - _registeredWithPool = true; + _threadPool->_register(_transceiver->fd(), this); + _registeredWithPool = true; } } @@ -2000,9 +2000,9 @@ Ice::ConnectionI::unregisterWithPool() if(_registeredWithPool) { - _threadPool->unregister(_transceiver->fd()); - _registeredWithPool = false; - ++_finishedCount; // For each unregistration, finished() is called once. + _threadPool->unregister(_transceiver->fd()); + _registeredWithPool = false; + ++_finishedCount; // For each unregistration, finished() is called once. } } @@ -2011,59 +2011,59 @@ getBZ2Error(int bzError) { if(bzError == BZ_RUN_OK) { - return ": BZ_RUN_OK"; + return ": BZ_RUN_OK"; } else if(bzError == BZ_FLUSH_OK) { - return ": BZ_FLUSH_OK"; + return ": BZ_FLUSH_OK"; } else if(bzError == BZ_FINISH_OK) { - return ": BZ_FINISH_OK"; + return ": BZ_FINISH_OK"; } else if(bzError == BZ_STREAM_END) { - return ": BZ_STREAM_END"; + return ": BZ_STREAM_END"; } else if(bzError == BZ_CONFIG_ERROR) { - return ": BZ_CONFIG_ERROR"; + return ": BZ_CONFIG_ERROR"; } else if(bzError == BZ_SEQUENCE_ERROR) { - return ": BZ_SEQUENCE_ERROR"; + return ": BZ_SEQUENCE_ERROR"; } else if(bzError == BZ_PARAM_ERROR) { - return ": BZ_PARAM_ERROR"; + return ": BZ_PARAM_ERROR"; } else if(bzError == BZ_MEM_ERROR) { - return ": BZ_MEM_ERROR"; + return ": BZ_MEM_ERROR"; } else if(bzError == BZ_DATA_ERROR) { - return ": BZ_DATA_ERROR"; + return ": BZ_DATA_ERROR"; } else if(bzError == BZ_DATA_ERROR_MAGIC) { - return ": BZ_DATA_ERROR_MAGIC"; + return ": BZ_DATA_ERROR_MAGIC"; } else if(bzError == BZ_IO_ERROR) { - return ": BZ_IO_ERROR"; + return ": BZ_IO_ERROR"; } else if(bzError == BZ_UNEXPECTED_EOF) { - return ": BZ_UNEXPECTED_EOF"; + return ": BZ_UNEXPECTED_EOF"; } else if(bzError == BZ_OUTBUFF_FULL) { - return ": BZ_OUTBUFF_FULL"; + return ": BZ_OUTBUFF_FULL"; } else { - return ""; + return ""; } } @@ -2079,15 +2079,15 @@ Ice::ConnectionI::doCompress(BasicStream& uncompressed, BasicStream& compressed) unsigned int compressedLen = static_cast(uncompressedLen * 1.01 + 600); compressed.b.resize(headerSize + sizeof(Int) + compressedLen); int bzError = BZ2_bzBuffToBuffCompress(reinterpret_cast(&compressed.b[0]) + headerSize + sizeof(Int), - &compressedLen, - reinterpret_cast(&uncompressed.b[0]) + headerSize, - uncompressedLen, - _compressionLevel, 0, 0); + &compressedLen, + reinterpret_cast(&uncompressed.b[0]) + headerSize, + uncompressedLen, + _compressionLevel, 0, 0); if(bzError != BZ_OK) { - CompressionException ex(__FILE__, __LINE__); - ex.reason = "BZ2_bzBuffToBuffCompress failed" + getBZ2Error(bzError); - throw ex; + CompressionException ex(__FILE__, __LINE__); + ex.reason = "BZ2_bzBuffToBuffCompress failed" + getBZ2Error(bzError); + throw ex; } compressed.b.resize(headerSize + sizeof(Int) + compressedLen); @@ -2130,22 +2130,22 @@ Ice::ConnectionI::doUncompress(BasicStream& compressed, BasicStream& uncompresse compressed.read(uncompressedSize); if(uncompressedSize <= headerSize) { - throw IllegalMessageSizeException(__FILE__, __LINE__); + throw IllegalMessageSizeException(__FILE__, __LINE__); } uncompressed.resize(uncompressedSize); unsigned int uncompressedLen = uncompressedSize - headerSize; unsigned int compressedLen = static_cast(compressed.b.size() - headerSize - sizeof(Int)); int bzError = BZ2_bzBuffToBuffDecompress(reinterpret_cast(&uncompressed.b[0]) + headerSize, - &uncompressedLen, - reinterpret_cast(&compressed.b[0]) + headerSize + sizeof(Int), - compressedLen, - 0, 0); + &uncompressedLen, + reinterpret_cast(&compressed.b[0]) + headerSize + sizeof(Int), + compressedLen, + 0, 0); if(bzError != BZ_OK) { - CompressionException ex(__FILE__, __LINE__); - ex.reason = "BZ2_bzBuffToBuffCompress failed" + getBZ2Error(bzError); - throw ex; + CompressionException ex(__FILE__, __LINE__); + ex.reason = "BZ2_bzBuffToBuffCompress failed" + getBZ2Error(bzError); + throw ex; } copy(compressed.b.begin(), compressed.b.begin() + headerSize, uncompressed.b.begin()); @@ -2153,222 +2153,222 @@ Ice::ConnectionI::doUncompress(BasicStream& compressed, BasicStream& uncompresse void Ice::ConnectionI::parseMessage(BasicStream& stream, Int& invokeNum, Int& requestId, Byte& compress, - ServantManagerPtr& servantManager, ObjectAdapterPtr& adapter, - OutgoingAsyncPtr& outAsync) + ServantManagerPtr& servantManager, ObjectAdapterPtr& adapter, + OutgoingAsyncPtr& outAsync) { assert(_state > StateNotValidated && _state < StateClosed); if(_acmTimeout > 0) { - _acmAbsoluteTimeout = IceUtil::Time::now() + IceUtil::Time::seconds(_acmTimeout); + _acmAbsoluteTimeout = IceUtil::Time::now() + IceUtil::Time::seconds(_acmTimeout); } try { - // - // We don't need to check magic and version here. This has - // already been done by the ThreadPool or the - // ThreadPerConnection, which provides us with the stream. - // - assert(stream.i == stream.b.end()); - stream.i = stream.b.begin() + 8; - Byte messageType; - stream.read(messageType); - stream.read(compress); - if(compress == 2) - { - BasicStream ustream(_instance.get()); - doUncompress(stream, ustream); - stream.b.swap(ustream.b); - } - stream.i = stream.b.begin() + headerSize; + // + // We don't need to check magic and version here. This has + // already been done by the ThreadPool or the + // ThreadPerConnection, which provides us with the stream. + // + assert(stream.i == stream.b.end()); + stream.i = stream.b.begin() + 8; + Byte messageType; + stream.read(messageType); + stream.read(compress); + if(compress == 2) + { + BasicStream ustream(_instance.get()); + doUncompress(stream, ustream); + stream.b.swap(ustream.b); + } + stream.i = stream.b.begin() + headerSize; - switch(messageType) - { - case closeConnectionMsg: - { - traceHeader("received close connection", stream, _logger, _traceLevels); - if(_endpoint->datagram()) - { - if(_warn) - { - Warning out(_logger); - out << "ignoring close connection message for datagram connection:\n" << _desc; - } - } - else - { - setState(StateClosed, CloseConnectionException(__FILE__, __LINE__)); - } - break; - } - - case requestMsg: - { - if(_state == StateClosing) - { - traceRequest("received request during closing\n" - "(ignored by server, client will retry)", - stream, _logger, _traceLevels); - } - else - { - traceRequest("received request", stream, _logger, _traceLevels); - stream.read(requestId); - invokeNum = 1; - servantManager = _servantManager; - adapter = _adapter; - ++_dispatchCount; - } - break; - } - - case requestBatchMsg: - { - if(_state == StateClosing) - { - traceBatchRequest("received batch request during closing\n" - "(ignored by server, client will retry)", - stream, _logger, _traceLevels); - } - else - { - traceBatchRequest("received batch request", stream, _logger, _traceLevels); - stream.read(invokeNum); - if(invokeNum < 0) - { - invokeNum = 0; - throw NegativeSizeException(__FILE__, __LINE__); - } - servantManager = _servantManager; - adapter = _adapter; - _dispatchCount += invokeNum; - } - break; - } - - case replyMsg: - { - traceReply("received reply", stream, _logger, _traceLevels); - - stream.read(requestId); - - map::iterator p = _requests.end(); - map::iterator q = _asyncRequests.end(); - - if(_requestsHint != _requests.end()) - { - if(_requestsHint->first == requestId) - { - p = _requestsHint; - } - } - - if(p == _requests.end()) - { - if(_asyncRequestsHint != _asyncRequests.end()) - { - if(_asyncRequestsHint->first == requestId) - { - q = _asyncRequestsHint; - } - } - } - - if(p == _requests.end() && q == _asyncRequests.end()) - { - p = _requests.find(requestId); - } - - if(p == _requests.end() && q == _asyncRequests.end()) - { - q = _asyncRequests.find(requestId); - } - - if(p == _requests.end() && q == _asyncRequests.end()) - { - throw UnknownRequestIdException(__FILE__, __LINE__); - } - - if(p != _requests.end()) - { - p->second->finished(stream); - - if(p == _requestsHint) - { - _requests.erase(p++); - _requestsHint = p; - } - else - { - _requests.erase(p); - } - } - else - { - assert(q != _asyncRequests.end()); - - outAsync = q->second.p; - - if(q == _asyncRequestsHint) - { - _asyncRequests.erase(q++); - _asyncRequestsHint = q; - } - else - { - _asyncRequests.erase(q); - } - } - - break; - } - - case validateConnectionMsg: - { - traceHeader("received validate connection", stream, _logger, _traceLevels); - if(_warn) - { - Warning out(_logger); - out << "ignoring unexpected validate connection message:\n" << _desc; - } - break; - } - - default: - { - traceHeader("received unknown message\n" - "(invalid, closing connection)", - stream, _logger, _traceLevels); - throw UnknownMessageException(__FILE__, __LINE__); - break; - } - } + switch(messageType) + { + case closeConnectionMsg: + { + traceHeader("received close connection", stream, _logger, _traceLevels); + if(_endpoint->datagram()) + { + if(_warn) + { + Warning out(_logger); + out << "ignoring close connection message for datagram connection:\n" << _desc; + } + } + else + { + setState(StateClosed, CloseConnectionException(__FILE__, __LINE__)); + } + break; + } + + case requestMsg: + { + if(_state == StateClosing) + { + traceRequest("received request during closing\n" + "(ignored by server, client will retry)", + stream, _logger, _traceLevels); + } + else + { + traceRequest("received request", stream, _logger, _traceLevels); + stream.read(requestId); + invokeNum = 1; + servantManager = _servantManager; + adapter = _adapter; + ++_dispatchCount; + } + break; + } + + case requestBatchMsg: + { + if(_state == StateClosing) + { + traceBatchRequest("received batch request during closing\n" + "(ignored by server, client will retry)", + stream, _logger, _traceLevels); + } + else + { + traceBatchRequest("received batch request", stream, _logger, _traceLevels); + stream.read(invokeNum); + if(invokeNum < 0) + { + invokeNum = 0; + throw NegativeSizeException(__FILE__, __LINE__); + } + servantManager = _servantManager; + adapter = _adapter; + _dispatchCount += invokeNum; + } + break; + } + + case replyMsg: + { + traceReply("received reply", stream, _logger, _traceLevels); + + stream.read(requestId); + + map::iterator p = _requests.end(); + map::iterator q = _asyncRequests.end(); + + if(_requestsHint != _requests.end()) + { + if(_requestsHint->first == requestId) + { + p = _requestsHint; + } + } + + if(p == _requests.end()) + { + if(_asyncRequestsHint != _asyncRequests.end()) + { + if(_asyncRequestsHint->first == requestId) + { + q = _asyncRequestsHint; + } + } + } + + if(p == _requests.end() && q == _asyncRequests.end()) + { + p = _requests.find(requestId); + } + + if(p == _requests.end() && q == _asyncRequests.end()) + { + q = _asyncRequests.find(requestId); + } + + if(p == _requests.end() && q == _asyncRequests.end()) + { + throw UnknownRequestIdException(__FILE__, __LINE__); + } + + if(p != _requests.end()) + { + p->second->finished(stream); + + if(p == _requestsHint) + { + _requests.erase(p++); + _requestsHint = p; + } + else + { + _requests.erase(p); + } + } + else + { + assert(q != _asyncRequests.end()); + + outAsync = q->second.p; + + if(q == _asyncRequestsHint) + { + _asyncRequests.erase(q++); + _asyncRequestsHint = q; + } + else + { + _asyncRequests.erase(q); + } + } + + break; + } + + case validateConnectionMsg: + { + traceHeader("received validate connection", stream, _logger, _traceLevels); + if(_warn) + { + Warning out(_logger); + out << "ignoring unexpected validate connection message:\n" << _desc; + } + break; + } + + default: + { + traceHeader("received unknown message\n" + "(invalid, closing connection)", + stream, _logger, _traceLevels); + throw UnknownMessageException(__FILE__, __LINE__); + break; + } + } } catch(const SocketException& ex) { - exception(ex); + exception(ex); } catch(const LocalException& ex) { - if(_endpoint->datagram()) - { - if(_warn) - { - Warning out(_logger); - out << "datagram connection exception:\n" << ex << '\n' << _desc; - } - } - else - { - setState(StateClosed, ex); - } + if(_endpoint->datagram()) + { + if(_warn) + { + Warning out(_logger); + out << "datagram connection exception:\n" << ex << '\n' << _desc; + } + } + else + { + setState(StateClosed, ex); + } } } void Ice::ConnectionI::invokeAll(BasicStream& stream, Int invokeNum, Int requestId, Byte compress, - const ServantManagerPtr& servantManager, const ObjectAdapterPtr& adapter) + const ServantManagerPtr& servantManager, const ObjectAdapterPtr& adapter) { // // Note: In contrast to other private or protected methods, this @@ -2377,45 +2377,45 @@ Ice::ConnectionI::invokeAll(BasicStream& stream, Int invokeNum, Int requestId, B try { - while(invokeNum > 0) - { - // - // Prepare the invocation. - // - bool response = !_endpoint->datagram() && requestId != 0; - Incoming in(_instance.get(), this, adapter, response, compress, requestId); - BasicStream* is = in.is(); - stream.swap(*is); - BasicStream* os = in.os(); - - // - // Prepare the response if necessary. - // - if(response) - { - assert(invokeNum == 1); // No further invocations if a response is expected. - os->writeBlob(replyHdr, sizeof(replyHdr)); - - // - // Add the request ID. - // - os->write(requestId); - } - - in.invoke(servantManager); - - // - // If there are more invocations, we need the stream back. - // - if(--invokeNum > 0) - { - stream.swap(*is); - } - } + while(invokeNum > 0) + { + // + // Prepare the invocation. + // + bool response = !_endpoint->datagram() && requestId != 0; + Incoming in(_instance.get(), this, adapter, response, compress, requestId); + BasicStream* is = in.is(); + stream.swap(*is); + BasicStream* os = in.os(); + + // + // Prepare the response if necessary. + // + if(response) + { + assert(invokeNum == 1); // No further invocations if a response is expected. + os->writeBlob(replyHdr, sizeof(replyHdr)); + + // + // Add the request ID. + // + os->write(requestId); + } + + in.invoke(servantManager); + + // + // If there are more invocations, we need the stream back. + // + if(--invokeNum > 0) + { + stream.swap(*is); + } + } } catch(const LocalException& ex) { - invokeException(ex, invokeNum); // Fatal invocation exception + invokeException(ex, invokeNum); // Fatal invocation exception } } @@ -2430,40 +2430,40 @@ Ice::ConnectionI::run() // if(!_endpoint->datagram()) { - try - { - validate(); - } - catch(const LocalException&) - { - IceUtil::Monitor::Lock sync(*this); - - assert(_state == StateClosed); - - // - // We must make sure that nobody is sending when we close - // the transceiver. - // - IceUtil::Mutex::Lock sendSync(_sendMutex); - - if(_transceiver) - { - try - { - _transceiver->close(); - } - catch(const LocalException&) - { - // Here we ignore any exceptions in close(). - } - - _transceiver = 0; - } - notifyAll(); - return; - } - - activate(); + try + { + validate(); + } + catch(const LocalException&) + { + IceUtil::Monitor::Lock sync(*this); + + assert(_state == StateClosed); + + // + // We must make sure that nobody is sending when we close + // the transceiver. + // + IceUtil::Mutex::Lock sendSync(_sendMutex); + + if(_transceiver) + { + try + { + _transceiver->close(); + } + catch(const LocalException&) + { + // Here we ignore any exceptions in close(). + } + + _transceiver = 0; + } + notifyAll(); + return; + } + + activate(); } const bool warnUdp = _instance->initializationData().properties->getPropertyAsInt("Ice.Warn.Datagrams") > 0; @@ -2472,213 +2472,213 @@ Ice::ConnectionI::run() while(!closed) { - // - // We must accept new connections outside the thread - // synchronization, because we use blocking accept. - // - - BasicStream stream(_instance.get()); - - try - { - stream.b.resize(headerSize); - stream.i = stream.b.begin(); - _transceiver->read(stream, -1); - - ptrdiff_t pos = stream.i - stream.b.begin(); - if(pos < headerSize) - { - // - // This situation is possible for small UDP packets. - // - throw IllegalMessageSizeException(__FILE__, __LINE__); - } - stream.i = stream.b.begin(); - const Byte* header; - stream.readBlob(header, headerSize); - if(header[0] != magic[0] || header[1] != magic[1] || header[2] != magic[2] || header[3] != magic[3]) - { - BadMagicException ex(__FILE__, __LINE__); - ex.badMagic = Ice::ByteSeq(&header[0], &header[0] + sizeof(magic)); - throw ex; - } - if(header[4] != protocolMajor) - { - UnsupportedProtocolException ex(__FILE__, __LINE__); - ex.badMajor = static_cast(header[4]); - ex.badMinor = static_cast(header[5]); - ex.major = static_cast(protocolMajor); - ex.minor = static_cast(protocolMinor); - throw ex; - } - if(header[6] != encodingMajor) - { - UnsupportedEncodingException ex(__FILE__, __LINE__); - ex.badMajor = static_cast(header[6]); - ex.badMinor = static_cast(header[7]); - ex.major = static_cast(encodingMajor); - ex.minor = static_cast(encodingMinor); - throw ex; - } - - Int size; - stream.i -= sizeof(Int); - stream.read(size); - if(size < headerSize) - { - throw IllegalMessageSizeException(__FILE__, __LINE__); - } - if(size > static_cast(_instance->messageSizeMax())) - { - throw MemoryLimitException(__FILE__, __LINE__); - } - if(size > static_cast(stream.b.size())) - { - stream.b.resize(size); - } - stream.i = stream.b.begin() + pos; - - if(stream.i != stream.b.end()) - { - if(_endpoint->datagram()) - { - if(warnUdp) - { - Warning out(_logger); - out << "DatagramLimitException: maximum size of " << pos << " exceeded"; - } - throw DatagramLimitException(__FILE__, __LINE__); - } - else - { - _transceiver->read(stream, -1); - assert(stream.i == stream.b.end()); - } - } - } - catch(const DatagramLimitException&) // Expected. - { - continue; - } - catch(const SocketException& ex) - { - exception(ex); - } - catch(const LocalException& ex) - { - if(_endpoint->datagram()) - { - if(_warn) - { - Warning out(_logger); - out << "datagram connection exception:\n" << ex << '\n' << _desc; - } - continue; - } - else - { - exception(ex); - } - } - - Byte compress = 0; - Int requestId = 0; - Int invokeNum = 0; - ServantManagerPtr servantManager; - ObjectAdapterPtr adapter; - OutgoingAsyncPtr outAsync; - - auto_ptr localEx; - - map requests; - map asyncRequests; - - { - IceUtil::Monitor::Lock sync(*this); - - while(_state == StateHolding) - { - wait(); - } - - if(_state != StateClosed) - { - parseMessage(stream, invokeNum, requestId, compress, servantManager, adapter, outAsync); - } - - // + // + // We must accept new connections outside the thread + // synchronization, because we use blocking accept. + // + + BasicStream stream(_instance.get()); + + try + { + stream.b.resize(headerSize); + stream.i = stream.b.begin(); + _transceiver->read(stream, -1); + + ptrdiff_t pos = stream.i - stream.b.begin(); + if(pos < headerSize) + { + // + // This situation is possible for small UDP packets. + // + throw IllegalMessageSizeException(__FILE__, __LINE__); + } + stream.i = stream.b.begin(); + const Byte* header; + stream.readBlob(header, headerSize); + if(header[0] != magic[0] || header[1] != magic[1] || header[2] != magic[2] || header[3] != magic[3]) + { + BadMagicException ex(__FILE__, __LINE__); + ex.badMagic = Ice::ByteSeq(&header[0], &header[0] + sizeof(magic)); + throw ex; + } + if(header[4] != protocolMajor) + { + UnsupportedProtocolException ex(__FILE__, __LINE__); + ex.badMajor = static_cast(header[4]); + ex.badMinor = static_cast(header[5]); + ex.major = static_cast(protocolMajor); + ex.minor = static_cast(protocolMinor); + throw ex; + } + if(header[6] != encodingMajor) + { + UnsupportedEncodingException ex(__FILE__, __LINE__); + ex.badMajor = static_cast(header[6]); + ex.badMinor = static_cast(header[7]); + ex.major = static_cast(encodingMajor); + ex.minor = static_cast(encodingMinor); + throw ex; + } + + Int size; + stream.i -= sizeof(Int); + stream.read(size); + if(size < headerSize) + { + throw IllegalMessageSizeException(__FILE__, __LINE__); + } + if(size > static_cast(_instance->messageSizeMax())) + { + throw MemoryLimitException(__FILE__, __LINE__); + } + if(size > static_cast(stream.b.size())) + { + stream.b.resize(size); + } + stream.i = stream.b.begin() + pos; + + if(stream.i != stream.b.end()) + { + if(_endpoint->datagram()) + { + if(warnUdp) + { + Warning out(_logger); + out << "DatagramLimitException: maximum size of " << pos << " exceeded"; + } + throw DatagramLimitException(__FILE__, __LINE__); + } + else + { + _transceiver->read(stream, -1); + assert(stream.i == stream.b.end()); + } + } + } + catch(const DatagramLimitException&) // Expected. + { + continue; + } + catch(const SocketException& ex) + { + exception(ex); + } + catch(const LocalException& ex) + { + if(_endpoint->datagram()) + { + if(_warn) + { + Warning out(_logger); + out << "datagram connection exception:\n" << ex << '\n' << _desc; + } + continue; + } + else + { + exception(ex); + } + } + + Byte compress = 0; + Int requestId = 0; + Int invokeNum = 0; + ServantManagerPtr servantManager; + ObjectAdapterPtr adapter; + OutgoingAsyncPtr outAsync; + + auto_ptr localEx; + + map requests; + map asyncRequests; + + { + IceUtil::Monitor::Lock sync(*this); + + while(_state == StateHolding) + { + wait(); + } + + if(_state != StateClosed) + { + parseMessage(stream, invokeNum, requestId, compress, servantManager, adapter, outAsync); + } + + // // parseMessage() can close the connection, so we must // check for closed state again. - // - if(_state == StateClosed) - { - // - // We must make sure that nobody is sending when we close - // the transceiver. - // - IceUtil::Mutex::Lock sendSync(_sendMutex); - - try - { - _transceiver->close(); - } - catch(const LocalException& ex) - { - localEx.reset(dynamic_cast(ex.ice_clone())); - } - - _transceiver = 0; - notifyAll(); - - // - // We cannot simply return here. We have to make sure - // that all requests (regular and async) are notified - // about the closed connection below. - // - closed = true; - } - - if(_state == StateClosed || _state == StateClosing) - { - requests.swap(_requests); - _requestsHint = _requests.end(); - - asyncRequests.swap(_asyncRequests); - _asyncRequestsHint = _asyncRequests.end(); - } - } - - // - // Asynchronous replies must be handled outside the thread - // synchronization, so that nested calls are possible. - // - if(outAsync) - { - outAsync->__finished(stream); - } - - // - // Method invocation (or multiple invocations for batch messages) - // must be done outside the thread synchronization, so that nested - // calls are possible. - // - invokeAll(stream, invokeNum, requestId, compress, servantManager, adapter); - - for(map::iterator p = requests.begin(); p != requests.end(); ++p) - { - p->second->finished(*_exception.get()); // The exception is immutable at this point. - } - - for(map::iterator q = asyncRequests.begin(); q != asyncRequests.end(); ++q) - { - q->second.p->__finished(*_exception.get()); // The exception is immutable at this point. - } - - if(localEx.get()) - { - assert(closed); - localEx->ice_throw(); - } + // + if(_state == StateClosed) + { + // + // We must make sure that nobody is sending when we close + // the transceiver. + // + IceUtil::Mutex::Lock sendSync(_sendMutex); + + try + { + _transceiver->close(); + } + catch(const LocalException& ex) + { + localEx.reset(dynamic_cast(ex.ice_clone())); + } + + _transceiver = 0; + notifyAll(); + + // + // We cannot simply return here. We have to make sure + // that all requests (regular and async) are notified + // about the closed connection below. + // + closed = true; + } + + if(_state == StateClosed || _state == StateClosing) + { + requests.swap(_requests); + _requestsHint = _requests.end(); + + asyncRequests.swap(_asyncRequests); + _asyncRequestsHint = _asyncRequests.end(); + } + } + + // + // Asynchronous replies must be handled outside the thread + // synchronization, so that nested calls are possible. + // + if(outAsync) + { + outAsync->__finished(stream); + } + + // + // Method invocation (or multiple invocations for batch messages) + // must be done outside the thread synchronization, so that nested + // calls are possible. + // + invokeAll(stream, invokeNum, requestId, compress, servantManager, adapter); + + for(map::iterator p = requests.begin(); p != requests.end(); ++p) + { + p->second->finished(*_exception.get()); // The exception is immutable at this point. + } + + for(map::iterator q = asyncRequests.begin(); q != asyncRequests.end(); ++q) + { + q->second.p->__finished(*_exception.get()); // The exception is immutable at this point. + } + + if(localEx.get()) + { + assert(closed); + localEx->ice_throw(); + } } } @@ -2700,19 +2700,19 @@ Ice::ConnectionI::ThreadPerConnection::run() _connection->run(); } catch(const Exception& ex) - { - Error out(_connection->_logger); - out << "exception in thread per connection:\n" << _connection->toString() << ex; + { + Error out(_connection->_logger); + out << "exception in thread per connection:\n" << _connection->toString() << ex; } catch(const std::exception& ex) { - Error out(_connection->_logger); - out << "std::exception in thread per connection:\n" << _connection->toString() << ex.what(); + Error out(_connection->_logger); + out << "std::exception in thread per connection:\n" << _connection->toString() << ex.what(); } catch(...) { - Error out(_connection->_logger); - out << "unknown exception in thread per connection:\n" << _connection->toString(); + Error out(_connection->_logger); + out << "unknown exception in thread per connection:\n" << _connection->toString(); } if(_connection->_instance->initializationData().threadHook) diff --git a/cpp/src/Ice/ConnectionI.h b/cpp/src/Ice/ConnectionI.h index 626f1c776be..f07841c5632 100644 --- a/cpp/src/Ice/ConnectionI.h +++ b/cpp/src/Ice/ConnectionI.h @@ -40,15 +40,15 @@ namespace Ice class LocalException; class ICE_API ConnectionI : public Connection, public IceInternal::EventHandler, - public IceUtil::Monitor + public IceUtil::Monitor { public: void validate(); enum DestructionReason { - ObjectAdapterDeactivated, - CommunicatorDestroyed + ObjectAdapterDeactivated, + CommunicatorDestroyed }; void activate(); void hold(); @@ -103,18 +103,18 @@ public: private: ConnectionI(const IceInternal::InstancePtr&, const IceInternal::TransceiverPtr&, - const IceInternal::EndpointIPtr&, const ObjectAdapterPtr&, bool, size_t); + const IceInternal::EndpointIPtr&, const ObjectAdapterPtr&, bool, size_t); virtual ~ConnectionI(); friend class IceInternal::IncomingConnectionFactory; friend class IceInternal::OutgoingConnectionFactory; enum State { - StateNotValidated, - StateActive, - StateHolding, - StateClosing, - StateClosed + StateNotValidated, + StateActive, + StateHolding, + StateClosing, + StateClosed }; void resetBatch(bool); @@ -132,22 +132,22 @@ private: void doUncompress(IceInternal::BasicStream&, IceInternal::BasicStream&); void parseMessage(IceInternal::BasicStream&, Int&, Int&, Byte&, - IceInternal::ServantManagerPtr&, ObjectAdapterPtr&, IceInternal::OutgoingAsyncPtr&); + IceInternal::ServantManagerPtr&, ObjectAdapterPtr&, IceInternal::OutgoingAsyncPtr&); void invokeAll(IceInternal::BasicStream&, Int, Int, Byte, - const IceInternal::ServantManagerPtr&, const ObjectAdapterPtr&); + const IceInternal::ServantManagerPtr&, const ObjectAdapterPtr&); void run(); // For thread per connection. class ThreadPerConnection : public IceUtil::Thread { public: - - ThreadPerConnection(const ConnectionIPtr&); - virtual void run(); + + ThreadPerConnection(const ConnectionIPtr&); + virtual void run(); private: - - ConnectionIPtr _connection; + + ConnectionIPtr _connection; }; friend class ThreadPerConnection; // Defined as mutable because "isFinished() const" sets this to 0. @@ -183,8 +183,8 @@ private: struct AsyncRequest { - IceInternal::OutgoingAsyncPtr p; - IceUtil::Time t; + IceInternal::OutgoingAsyncPtr p; + IceUtil::Time t; }; std::map _asyncRequests; std::map::iterator _asyncRequestsHint; diff --git a/cpp/src/Ice/ConnectionMonitor.cpp b/cpp/src/Ice/ConnectionMonitor.cpp index d67962fb9e9..3c9eee7845a 100644 --- a/cpp/src/Ice/ConnectionMonitor.cpp +++ b/cpp/src/Ice/ConnectionMonitor.cpp @@ -24,13 +24,13 @@ void IceInternal::ConnectionMonitor::destroy() { { - IceUtil::Monitor::Lock sync(*this); - - assert(_instance); - _instance = 0; - _connections.clear(); - - notify(); + IceUtil::Monitor::Lock sync(*this); + + assert(_instance); + _instance = 0; + _connections.clear(); + + notify(); } getThreadControl().join(); @@ -71,53 +71,53 @@ IceInternal::ConnectionMonitor::run() { while(true) { - set connections; - - { - IceUtil::Monitor::Lock sync(*this); - if(_instance && !timedWait(_interval)) - { - connections = _connections; - } + set connections; + + { + IceUtil::Monitor::Lock sync(*this); + if(_instance && !timedWait(_interval)) + { + connections = _connections; + } - if(!_instance) - { - return; - } - } - - // - // Monitor connections outside the thread synchronization, so - // that connections can be added or removed during monitoring. - // - for(set::const_iterator p = connections.begin(); p != connections.end(); ++p) - { - try - { - (*p)->monitor(); - } - catch(const Exception& ex) - { - IceUtil::Monitor::Lock sync(*this); - if(!_instance) - { - return; - } + if(!_instance) + { + return; + } + } + + // + // Monitor connections outside the thread synchronization, so + // that connections can be added or removed during monitoring. + // + for(set::const_iterator p = connections.begin(); p != connections.end(); ++p) + { + try + { + (*p)->monitor(); + } + catch(const Exception& ex) + { + IceUtil::Monitor::Lock sync(*this); + if(!_instance) + { + return; + } - Error out(_instance->initializationData().logger); - out << "exception in connection monitor:\n" << ex; - } - catch(...) - { - IceUtil::Monitor::Lock sync(*this); - if(!_instance) - { - return; - } + Error out(_instance->initializationData().logger); + out << "exception in connection monitor:\n" << ex; + } + catch(...) + { + IceUtil::Monitor::Lock sync(*this); + if(!_instance) + { + return; + } - Error out(_instance->initializationData().logger); - out << "unknown exception in connection monitor"; - } - } + Error out(_instance->initializationData().logger); + out << "unknown exception in connection monitor"; + } + } } } diff --git a/cpp/src/Ice/DLLMain.cpp b/cpp/src/Ice/DLLMain.cpp index 55f94abae45..dab9d417bb4 100755 --- a/cpp/src/Ice/DLLMain.cpp +++ b/cpp/src/Ice/DLLMain.cpp @@ -34,7 +34,7 @@ ice_DLL_Main(HINSTANCE hDLL, DWORD reason, LPVOID reserved) } else if(reason == DLL_THREAD_DETACH) { - Ice::ImplicitContextI::cleanupThread(); + Ice::ImplicitContextI::cleanupThread(); } return TRUE; diff --git a/cpp/src/Ice/DefaultsAndOverrides.cpp b/cpp/src/Ice/DefaultsAndOverrides.cpp index 04f5508d903..64bcd99b63b 100644 --- a/cpp/src/Ice/DefaultsAndOverrides.cpp +++ b/cpp/src/Ice/DefaultsAndOverrides.cpp @@ -38,33 +38,33 @@ IceInternal::DefaultsAndOverrides::DefaultsAndOverrides(const PropertiesPtr& pro value = properties->getProperty("Ice.Override.Timeout"); if(!value.empty()) { - const_cast(overrideTimeout) = true; - const_cast(overrideTimeoutValue) = properties->getPropertyAsInt("Ice.Override.Timeout"); + const_cast(overrideTimeout) = true; + const_cast(overrideTimeoutValue) = properties->getPropertyAsInt("Ice.Override.Timeout"); } value = properties->getProperty("Ice.Override.ConnectTimeout"); if(!value.empty()) { - const_cast(overrideConnectTimeout) = true; - const_cast(overrideConnectTimeoutValue) = properties->getPropertyAsInt("Ice.Override.ConnectTimeout"); + const_cast(overrideConnectTimeout) = true; + const_cast(overrideConnectTimeoutValue) = properties->getPropertyAsInt("Ice.Override.ConnectTimeout"); } value = properties->getProperty("Ice.Override.Compress"); if(!value.empty()) { - const_cast(overrideCompress) = true; - const_cast(overrideCompressValue) = properties->getPropertyAsInt("Ice.Override.Compress"); + const_cast(overrideCompress) = true; + const_cast(overrideCompressValue) = properties->getPropertyAsInt("Ice.Override.Compress"); } value = properties->getProperty("Ice.Override.Secure"); if(!value.empty()) { - const_cast(overrideSecure) = true; - const_cast(overrideSecureValue) = properties->getPropertyAsInt("Ice.Override.Secure"); + const_cast(overrideSecure) = true; + const_cast(overrideSecureValue) = properties->getPropertyAsInt("Ice.Override.Secure"); } const_cast(defaultCollocationOptimization) = - properties->getPropertyAsIntWithDefault("Ice.Default.CollocationOptimization", 1) > 0; + properties->getPropertyAsIntWithDefault("Ice.Default.CollocationOptimization", 1) > 0; value = properties->getPropertyWithDefault("Ice.Default.EndpointSelection", "Random"); if(value == "Random") @@ -83,8 +83,8 @@ IceInternal::DefaultsAndOverrides::DefaultsAndOverrides(const PropertiesPtr& pro } const_cast(defaultLocatorCacheTimeout) = - properties->getPropertyAsIntWithDefault("Ice.Default.LocatorCacheTimeout", -1); + properties->getPropertyAsIntWithDefault("Ice.Default.LocatorCacheTimeout", -1); const_cast(defaultPreferSecure) = - properties->getPropertyAsIntWithDefault("Ice.Default.PreferSecure", 0) > 0; + properties->getPropertyAsIntWithDefault("Ice.Default.PreferSecure", 0) > 0; } diff --git a/cpp/src/Ice/Direct.cpp b/cpp/src/Ice/Direct.cpp index d27825ab907..b25c85fb9e1 100644 --- a/cpp/src/Ice/Direct.cpp +++ b/cpp/src/Ice/Direct.cpp @@ -39,55 +39,55 @@ IceInternal::Direct::Direct(const Current& current) : try { - _servant = servantManager->findServant(_current.id, _current.facet); - if(!_servant) - { - _locator = servantManager->findServantLocator(_current.id.category); - if(!_locator && !_current.id.category.empty()) - { - _locator = servantManager->findServantLocator(""); - } - if(_locator) - { - _servant = _locator->locate(_current, _cookie); - } - } - if(!_servant) - { - if(servantManager && servantManager->hasServant(_current.id)) - { - FacetNotExistException ex(__FILE__, __LINE__); - ex.id = _current.id; - ex.facet = _current.facet; - ex.operation = _current.operation; - throw ex; - } - else - { - ObjectNotExistException ex(__FILE__, __LINE__); - ex.id = _current.id; - ex.facet = _current.facet; - ex.operation = _current.operation; - throw ex; - } - } + _servant = servantManager->findServant(_current.id, _current.facet); + if(!_servant) + { + _locator = servantManager->findServantLocator(_current.id.category); + if(!_locator && !_current.id.category.empty()) + { + _locator = servantManager->findServantLocator(""); + } + if(_locator) + { + _servant = _locator->locate(_current, _cookie); + } + } + if(!_servant) + { + if(servantManager && servantManager->hasServant(_current.id)) + { + FacetNotExistException ex(__FILE__, __LINE__); + ex.id = _current.id; + ex.facet = _current.facet; + ex.operation = _current.operation; + throw ex; + } + else + { + ObjectNotExistException ex(__FILE__, __LINE__); + ex.id = _current.id; + ex.facet = _current.facet; + ex.operation = _current.operation; + throw ex; + } + } } catch(...) { - if(_locator && _servant) - { - try - { - _locator->finished(_current, _servant, _cookie); - } - catch(...) - { - adapter->decDirectCount(); - throw; - } - } - adapter->decDirectCount(); - throw; + if(_locator && _servant) + { + try + { + _locator->finished(_current, _servant, _cookie); + } + catch(...) + { + adapter->decDirectCount(); + throw; + } + } + adapter->decDirectCount(); + throw; } } @@ -104,15 +104,15 @@ IceInternal::Direct::destroy() if(_locator && _servant) { - try - { - _locator->finished(_current, _servant, _cookie); - } - catch(...) - { - adapter->decDirectCount(); - throw; - } + try + { + _locator->finished(_current, _servant, _cookie); + } + catch(...) + { + adapter->decDirectCount(); + throw; + } } adapter->decDirectCount(); diff --git a/cpp/src/Ice/DynamicLibrary.cpp b/cpp/src/Ice/DynamicLibrary.cpp index d1b25c1a46c..769b0368b19 100644 --- a/cpp/src/Ice/DynamicLibrary.cpp +++ b/cpp/src/Ice/DynamicLibrary.cpp @@ -66,21 +66,21 @@ IceInternal::DynamicLibrary::loadEntryPoint(const string& entryPoint, bool useIc libName = libSpec; if(useIceVersion) { - int majorVersion = (ICE_INT_VERSION / 10000); - int minorVersion = (ICE_INT_VERSION / 100) - majorVersion * 100; - ostringstream os; - os << majorVersion * 10 + minorVersion; + int majorVersion = (ICE_INT_VERSION / 10000); + int minorVersion = (ICE_INT_VERSION / 100) - majorVersion * 100; + ostringstream os; + os << majorVersion * 10 + minorVersion; - int patchVersion = ICE_INT_VERSION % 100; - if(patchVersion > 50) - { - os << 'b'; - if(patchVersion >= 52) - { - os << (patchVersion - 50); - } - } - version = os.str(); + int patchVersion = ICE_INT_VERSION % 100; + if(patchVersion > 50) + { + os << 'b'; + if(patchVersion >= 52) + { + os << (patchVersion - 50); + } + } + version = os.str(); } } else @@ -101,7 +101,7 @@ IceInternal::DynamicLibrary::loadEntryPoint(const string& entryPoint, bool useIc lib = "lib" + libName; if(!version.empty()) { - lib += "." + version; + lib += "." + version; } lib += ".dylib"; #elif defined(__hpux) @@ -112,7 +112,7 @@ IceInternal::DynamicLibrary::loadEntryPoint(const string& entryPoint, bool useIc } else { - lib += ".sl"; + lib += ".sl"; } #elif defined(_AIX) lib = "lib" + libName + ".a(lib" + libName + ".so"; diff --git a/cpp/src/Ice/EndpointFactoryManager.cpp b/cpp/src/Ice/EndpointFactoryManager.cpp index bb8a784e9ab..25db4169e20 100644 --- a/cpp/src/Ice/EndpointFactoryManager.cpp +++ b/cpp/src/Ice/EndpointFactoryManager.cpp @@ -75,8 +75,8 @@ IceInternal::EndpointFactoryManager::create(const string& str) const if(beg == string::npos) { EndpointParseException ex(__FILE__, __LINE__); - ex.str = str; - throw ex; + ex.str = str; + throw ex; } string::size_type end = str.find_first_of(delim, beg); diff --git a/cpp/src/Ice/EventLoggerI.cpp b/cpp/src/Ice/EventLoggerI.cpp index a61325f1463..c626e62c83f 100755 --- a/cpp/src/Ice/EventLoggerI.cpp +++ b/cpp/src/Ice/EventLoggerI.cpp @@ -70,7 +70,7 @@ Ice::EventLoggerI::EventLoggerI(const string& appName) : // "EventMessageFile" key should contain the path to this DLL. // err = RegSetValueEx(hKey, "EventMessageFile", 0, REG_EXPAND_SZ, - (unsigned char*)path, static_cast(strlen(path) + 1)); + (unsigned char*)path, static_cast(strlen(path) + 1)); if(err != ERROR_SUCCESS) { RegCloseKey(hKey); diff --git a/cpp/src/Ice/Exception.cpp b/cpp/src/Ice/Exception.cpp index d43712b6658..3141a604d3e 100644 --- a/cpp/src/Ice/Exception.cpp +++ b/cpp/src/Ice/Exception.cpp @@ -56,7 +56,7 @@ Ice::InitializationException::ice_print(ostream& out) const out << ":\ninitialization exception"; if(!reason.empty()) { - out << ":\n" << reason; + out << ":\n" << reason; } } @@ -67,7 +67,7 @@ Ice::UnknownException::ice_print(ostream& out) const out << ":\nunknown exception"; if(!unknown.empty()) { - out << ":\n" << unknown; + out << ":\n" << unknown; } } @@ -78,7 +78,7 @@ Ice::UnknownLocalException::ice_print(ostream& out) const out << ":\nunknown local exception"; if(!unknown.empty()) { - out << ":\n" << unknown; + out << ":\n" << unknown; } } @@ -89,7 +89,7 @@ Ice::UnknownUserException::ice_print(ostream& out) const out << ":\nunknown user exception"; if(!unknown.empty()) { - out << ":\n" << unknown; + out << ":\n" << unknown; } } @@ -238,11 +238,11 @@ Ice::SocketException::ice_print(ostream& out) const out << ":\nsocket exception: "; if(error == 0) { - out << "unknown error"; + out << "unknown error"; } else { - out << errorToString(error); + out << errorToString(error); } } @@ -253,7 +253,7 @@ Ice::FileException::ice_print(ostream& out) const out << ":\nfile exception: " << errorToString(error); if(!path.empty()) { - out << "\npath: " << path; + out << "\npath: " << path; } } @@ -278,11 +278,11 @@ Ice::ConnectionLostException::ice_print(ostream& out) const out << ":\nconnection lost: "; if(error == 0) { - out << "recv() returned zero"; + out << "recv() returned zero"; } else { - out << errorToString(error); + out << errorToString(error); } } @@ -328,7 +328,7 @@ Ice::ProtocolException::ice_print(ostream& out) const out << ":\nprotocol exception"; if(!reason.empty()) { - out << ":\n" << reason; + out << ":\n" << reason; } } @@ -338,23 +338,23 @@ Ice::BadMagicException::ice_print(ostream& out) const Exception::ice_print(out); out << ":\nunknown magic number: "; - ios_base::fmtflags originalFlags = out.flags(); // Save stream state + ios_base::fmtflags originalFlags = out.flags(); // Save stream state ostream::char_type originalFill = out.fill(); - out.flags(ios_base::hex); // Change to hex - out.fill('0'); // Fill with leading zeros + out.flags(ios_base::hex); // Change to hex + out.fill('0'); // Fill with leading zeros out << "0x" << setw(2) << static_cast(static_cast(badMagic[0])) << ", "; out << "0x" << setw(2) << static_cast(static_cast(badMagic[1])) << ", "; out << "0x" << setw(2) << static_cast(static_cast(badMagic[2])) << ", "; out << "0x" << setw(2) << static_cast(static_cast(badMagic[3])); - out.fill(originalFill); // Restore stream state + out.fill(originalFill); // Restore stream state out.flags(originalFlags); if(!reason.empty()) { - out << "\n" << reason; + out << "\n" << reason; } } @@ -374,7 +374,7 @@ Ice::UnsupportedEncodingException::ice_print(ostream& out) const out << "\n(can only support encodings compatible with version " << major << "." << major << ")"; if(!reason.empty()) { - out << "\n" << reason; + out << "\n" << reason; } } @@ -385,7 +385,7 @@ Ice::UnknownMessageException::ice_print(ostream& out) const out << ":\nprotocol error: unknown message type"; if(!reason.empty()) { - out << ":\n" << reason; + out << ":\n" << reason; } } @@ -396,7 +396,7 @@ Ice::ConnectionNotValidatedException::ice_print(ostream& out) const out << ":\nprotocol error: received message over unvalidated connection"; if(!reason.empty()) { - out << ":\n" << reason; + out << ":\n" << reason; } } @@ -407,7 +407,7 @@ Ice::UnknownRequestIdException::ice_print(ostream& out) const out << ":\nprotocol error: unknown request id"; if(!reason.empty()) { - out << ":\n" << reason; + out << ":\n" << reason; } } @@ -418,7 +418,7 @@ Ice::UnknownReplyStatusException::ice_print(ostream& out) const out << ":\nprotocol error: unknown reply status"; if(!reason.empty()) { - out << ":\n" << reason; + out << ":\n" << reason; } } @@ -429,7 +429,7 @@ Ice::CloseConnectionException::ice_print(ostream& out) const out << ":\nprotocol error: connection closed"; if(!reason.empty()) { - out << ":\n" << reason; + out << ":\n" << reason; } } @@ -440,7 +440,7 @@ Ice::ForcedCloseConnectionException::ice_print(ostream& out) const out << ":\nprotocol error: connection forcefully closed"; if(!reason.empty()) { - out << ":\n" << reason; + out << ":\n" << reason; } } @@ -451,7 +451,7 @@ Ice::IllegalMessageSizeException::ice_print(ostream& out) const out << ":\nprotocol error: illegal message size"; if(!reason.empty()) { - out << ":\n" << reason; + out << ":\n" << reason; } } @@ -462,7 +462,7 @@ Ice::CompressionException::ice_print(ostream& out) const out << ":\nprotocol error: failed to compress or uncompress data"; if(!reason.empty()) { - out << ":\n" << reason; + out << ":\n" << reason; } } @@ -473,7 +473,7 @@ Ice::DatagramLimitException::ice_print(ostream& out) const out << ":\nprotocol error: maximum datagram payload size exceeded"; if(!reason.empty()) { - out << ":\n" << reason; + out << ":\n" << reason; } } @@ -484,7 +484,7 @@ Ice::MarshalException::ice_print(ostream& out) const out << ":\nprotocol error: error during marshaling or unmarshaling"; if(!reason.empty()) { - out << ":\n" << reason; + out << ":\n" << reason; } } @@ -495,7 +495,7 @@ Ice::ProxyUnmarshalException::ice_print(ostream& out) const out << ":\nprotocol error: inconsistent proxy data during unmarshaling"; if(!reason.empty()) { - out << ":\n" << reason; + out << ":\n" << reason; } } @@ -506,7 +506,7 @@ Ice::UnmarshalOutOfBoundsException::ice_print(ostream& out) const out << ":\nprotocol error: out of bounds during unmarshaling"; if(!reason.empty()) { - out << ":\n" << reason; + out << ":\n" << reason; } } @@ -517,7 +517,7 @@ Ice::IllegalIndirectionException::ice_print(ostream& out) const out << ":\nprotocol error: encountered illegal protocol indirection"; if(!reason.empty()) { - out << ":\n" << reason; + out << ":\n" << reason; } } @@ -528,21 +528,21 @@ Ice::NoObjectFactoryException::ice_print(ostream& out) const out << ":\nprotocol error: no suitable object factory found for `" << type << "'"; if(!reason.empty()) { - out << ":\n" << reason; + out << ":\n" << reason; } -} +} void Ice::UnexpectedObjectException::ice_print(ostream& out) const { Exception::ice_print(out); out << ":\nunexpected class instance of type `" << type << - "'; expected instance of type `" << expectedType << "'"; + "'; expected instance of type `" << expectedType << "'"; if(!reason.empty()) { - out << ":\n" << reason; + out << ":\n" << reason; } -} +} void Ice::MemoryLimitException::ice_print(ostream& out) const @@ -551,7 +551,7 @@ Ice::MemoryLimitException::ice_print(ostream& out) const out << ":\nprotocol error: memory limit exceeded"; if(!reason.empty()) { - out << ":\n" << reason; + out << ":\n" << reason; } } @@ -562,7 +562,7 @@ Ice::StringConversionException::ice_print(ostream& out) const out << ":\nprotocol error: string conversion failed"; if(!reason.empty()) { - out << ":\n" << reason; + out << ":\n" << reason; } } @@ -573,7 +573,7 @@ Ice::EncapsulationException::ice_print(ostream& out) const out << ":\nprotocol error: illegal encapsulation"; if(!reason.empty()) { - out << ":\n" << reason; + out << ":\n" << reason; } } @@ -584,7 +584,7 @@ Ice::NegativeSizeException::ice_print(ostream& out) const out << ":\nprotocol error: negative size for sequence, dictionary, etc."; if(!reason.empty()) { - out << ":\n" << reason; + out << ":\n" << reason; } } @@ -656,7 +656,7 @@ Ice::SecurityException::ice_print(ostream& out) const out << ":\nsecurity exception"; if(!reason.empty()) { - out << ":\n" << reason; + out << ":\n" << reason; } } diff --git a/cpp/src/Ice/FactoryTableDef.cpp b/cpp/src/Ice/FactoryTableDef.cpp index e31a7fd0a7e..9241c8da8d6 100644 --- a/cpp/src/Ice/FactoryTableDef.cpp +++ b/cpp/src/Ice/FactoryTableDef.cpp @@ -17,11 +17,11 @@ namespace IceInternal { -FactoryTableWrapper factoryTableWrapper; // Single global instance of the wrapper object that - // initializes factoryTable. +FactoryTableWrapper factoryTableWrapper; // Single global instance of the wrapper object that + // initializes factoryTable. -ICE_API FactoryTableDef* factoryTable; // Single global instance of the factory table for - // non-local exceptions and non-abstract classes +ICE_API FactoryTableDef* factoryTable; // Single global instance of the factory table for + // non-local exceptions and non-abstract classes } // @@ -35,11 +35,11 @@ IceInternal::FactoryTableDef::addExceptionFactory(const std::string& t, const Ic EFTable::iterator i = _eft.find(t); if(i == _eft.end()) { - _eft[t] = EFPair(f, 1); + _eft[t] = EFPair(f, 1); } else { - i->second.second++; + i->second.second++; } } @@ -54,23 +54,23 @@ IceInternal::FactoryTableDef::getExceptionFactory(const std::string& t) const #ifdef __APPLE__ if(i == _eft.end()) { - lock.release(); - - // - // Try to find the symbol, if found this should trigger the - // object static constructors to be called. - // - std::string symbol = "__F"; - for(std::string::const_iterator p = t.begin(); p != t.end(); ++p) - { - symbol += ((*p) == ':') ? '_' : *p; - } - symbol += "__initializer"; - dlsym(RTLD_DEFAULT, symbol.c_str()); - - lock.acquire(); - - i = _eft.find(t); + lock.release(); + + // + // Try to find the symbol, if found this should trigger the + // object static constructors to be called. + // + std::string symbol = "__F"; + for(std::string::const_iterator p = t.begin(); p != t.end(); ++p) + { + symbol += ((*p) == ':') ? '_' : *p; + } + symbol += "__initializer"; + dlsym(RTLD_DEFAULT, symbol.c_str()); + + lock.acquire(); + + i = _eft.find(t); } #endif return i != _eft.end() ? i->second.first : IceInternal::UserExceptionFactoryPtr(); @@ -89,10 +89,10 @@ IceInternal::FactoryTableDef::removeExceptionFactory(const std::string& t) EFTable::iterator i = _eft.find(t); if(i != _eft.end()) { - if(--i->second.second == 0) - { - _eft.erase(i); - } + if(--i->second.second == 0) + { + _eft.erase(i); + } } } @@ -106,11 +106,11 @@ IceInternal::FactoryTableDef::addObjectFactory(const std::string& t, const Ice:: OFTable::iterator i = _oft.find(t); if(i == _oft.end()) { - _oft[t] = OFPair(f, 1); + _oft[t] = OFPair(f, 1); } else { - i->second.second++; + i->second.second++; } } @@ -125,23 +125,23 @@ IceInternal::FactoryTableDef::getObjectFactory(const std::string& t) const #ifdef __APPLE__ if(i == _oft.end()) { - lock.release(); - - // - // Try to find the symbol, if found this should trigger the - // object static constructors to be called. - // - std::string symbol = "__F"; - for(std::string::const_iterator p = t.begin(); p != t.end(); ++p) - { - symbol += ((*p) == ':') ? '_' : *p; - } - symbol += "__initializer"; - dlsym(RTLD_DEFAULT, symbol.c_str()); - - lock.acquire(); - - i = _oft.find(t); + lock.release(); + + // + // Try to find the symbol, if found this should trigger the + // object static constructors to be called. + // + std::string symbol = "__F"; + for(std::string::const_iterator p = t.begin(); p != t.end(); ++p) + { + symbol += ((*p) == ':') ? '_' : *p; + } + symbol += "__initializer"; + dlsym(RTLD_DEFAULT, symbol.c_str()); + + lock.acquire(); + + i = _oft.find(t); } #endif return i != _oft.end() ? i->second.first : Ice::ObjectFactoryPtr(); @@ -160,10 +160,10 @@ IceInternal::FactoryTableDef::removeObjectFactory(const std::string& t) OFTable::iterator i = _oft.find(t); if(i != _oft.end()) { - if(--i->second.second == 0) - { - _oft.erase(i); - } + if(--i->second.second == 0) + { + _oft.erase(i); + } } } @@ -193,7 +193,7 @@ IceInternal::FactoryTableWrapper::initialize() IceUtil::StaticMutex::Lock lock(_m); if(_initCount == 0) { - factoryTable = new FactoryTableDef; + factoryTable = new FactoryTableDef; } ++_initCount; } @@ -207,9 +207,9 @@ IceInternal::FactoryTableWrapper::finalize() IceUtil::StaticMutex::Lock lock(_m); if(--_initCount == 0) { - delete factoryTable; + delete factoryTable; } } IceUtil::StaticMutex IceInternal::FactoryTableWrapper::_m = ICE_STATIC_MUTEX_INITIALIZER; -int IceInternal::FactoryTableWrapper::_initCount = 0; // Initialization count +int IceInternal::FactoryTableWrapper::_initCount = 0; // Initialization count diff --git a/cpp/src/Ice/GC.cpp b/cpp/src/Ice/GC.cpp index 432a34a7469..605997439a5 100755 --- a/cpp/src/Ice/GC.cpp +++ b/cpp/src/Ice/GC.cpp @@ -35,14 +35,14 @@ recursivelyReachable(GCShared* p, GCObjectSet& o) { if(o.find(p) == o.end()) { - assert(p); - o.insert(p); - GCCountMap tmp; - p->__gcReachable(tmp); - for(GCCountMap::const_iterator i = tmp.begin(); i != tmp.end(); ++i) - { - recursivelyReachable(i->first, o); - } + assert(p); + o.insert(p); + GCCountMap tmp; + p->__gcReachable(tmp); + for(GCCountMap::const_iterator i = tmp.begin(); i != tmp.end(); ++i) + { + recursivelyReachable(i->first, o); + } } } @@ -82,13 +82,13 @@ IceInternal::GCShared::__decRef() assert(_ref > 0); if(--_ref == 0) { - doDelete = !_noDelete; - _noDelete = true; + doDelete = !_noDelete; + _noDelete = true; } lock.release(); if(doDelete) { - delete this; + delete this; } } @@ -114,10 +114,10 @@ IceInternal::GCShared::__gcIncRef() if(_ref == 0) { #ifdef NDEBUG // To avoid annoying warnings about variables that are not used... - gcObjects.insert(this); + gcObjects.insert(this); #else - std::pair rc = gcObjects.insert(this); - assert(rc.second); + std::pair rc = gcObjects.insert(this); + assert(rc.second); #endif } ++_ref; @@ -131,19 +131,19 @@ IceInternal::GCShared::__gcDecRef() assert(_ref > 0); if(--_ref == 0) { - doDelete = !_noDelete; - _noDelete = true; + doDelete = !_noDelete; + _noDelete = true; #ifdef NDEBUG // To avoid annoying warnings about variables that are not used... - gcObjects.erase(this); + gcObjects.erase(this); #else - GCObjectSet::size_type num = gcObjects.erase(this); - assert(num == 1); + GCObjectSet::size_type num = gcObjects.erase(this); + assert(num == 1); #endif } lock.release(); if(doDelete) { - delete this; + delete this; } } @@ -158,7 +158,7 @@ IceInternal::GC::GC(int interval, StatsCallback cb) StaticMutex::Lock sync(numCollectorsMutex); if(numCollectors++ > 0) { - abort(); // Enforce singleton. + abort(); // Enforce singleton. } _state = NotStarted; @@ -179,33 +179,33 @@ IceInternal::GC::run() assert(_interval > 0); { - Monitor::Lock sync(*this); + Monitor::Lock sync(*this); - _state = Started; - notify(); + _state = Started; + notify(); } Time waitTime = Time::seconds(_interval); while(true) { - bool collect = false; - { - Monitor::Lock sync(*this); - - if(_state == Stopping) - { - _state = Stopped; - return; - } - if(!timedWait(waitTime)) - { - collect = true; - } - } - if(collect) - { - collectGarbage(); - } + bool collect = false; + { + Monitor::Lock sync(*this); + + if(_state == Stopping) + { + _state = Stopped; + return; + } + if(!timedWait(waitTime)) + { + collect = true; + } + } + if(collect) + { + collectGarbage(); + } } } @@ -213,32 +213,32 @@ void IceInternal::GC::stop() { { - Monitor::Lock sync(*this); - - if(_state >= Stopping) - { - return; // Don't attempt to stop the thread twice. - } - - // - // Wait until the thread is actually started. (If we don't do this, we - // can get a problem if a call to stop() immediately follows a call to start(): - // the call to stop() may happen before pthread_create() has scheduled the thread's run() - // function, and then the notify() that is used to tell the thread to stop can be lost. - // - while(_state < Started) - { - wait(); - } + Monitor::Lock sync(*this); + + if(_state >= Stopping) + { + return; // Don't attempt to stop the thread twice. + } + + // + // Wait until the thread is actually started. (If we don't do this, we + // can get a problem if a call to stop() immediately follows a call to start(): + // the call to stop() may happen before pthread_create() has scheduled the thread's run() + // function, and then the notify() that is used to tell the thread to stop can be lost. + // + while(_state < Started) + { + wait(); + } } // // Tell the thread to stop. // { - Monitor::Lock sync(*this); - _state = Stopping; - notify(); + Monitor::Lock sync(*this); + _state = Stopping; + notify(); } getThreadControl().join(); @@ -252,13 +252,13 @@ IceInternal::GC::collectGarbage() // Do nothing if the collector is running already. // { - Monitor::Lock sync(*this); + Monitor::Lock sync(*this); - if(_collecting) - { - return; - } - _collecting = true; + if(_collecting) + { + return; + } + _collecting = true; } RecMutex::Lock sync(gcRecMutex); // Prevent any further class reference count activity. @@ -268,108 +268,108 @@ IceInternal::GC::collectGarbage() if(_statsCallback) { - t = Time::now(); - stats.examined = static_cast(gcObjects.size()); + t = Time::now(); + stats.examined = static_cast(gcObjects.size()); } GCCountMap counts; { - // - // gcObjects contains the set of class instances that have at least one member of class type, - // that is, gcObjects contains all those instances that can point at other instances. - // - // Create a map that, for each object in gcObjects, contains an pair. - // In addition, for each object in gcObjects, add the objects that are immediately (not - // recursively) reachable from that object to a reachable map that counts how many times - // the object is pointed at. - // - GCCountMap reachable; - { - for(GCObjectSet::const_iterator i = gcObjects.begin(); i != gcObjects.end(); ++i) - { - counts.insert(GCCountMap::value_type(*i, (*i)->__getRefUnsafe())); - (*i)->__gcReachable(reachable); - } - } - - // - // Decrement the reference count for each object in the counts map by the count in the reachable - // map. This drops the reference count of each object in the counts map by the number of times that - // the object is pointed at by other objects in the counts map. // - { - for(GCCountMap::const_iterator i = reachable.begin(); i != reachable.end(); ++i) - { - GCCountMap::iterator pos = counts.find(i->first); - assert(pos != counts.end()); - pos->second -= i->second; - } - } + // gcObjects contains the set of class instances that have at least one member of class type, + // that is, gcObjects contains all those instances that can point at other instances. + // + // Create a map that, for each object in gcObjects, contains an pair. + // In addition, for each object in gcObjects, add the objects that are immediately (not + // recursively) reachable from that object to a reachable map that counts how many times + // the object is pointed at. + // + GCCountMap reachable; + { + for(GCObjectSet::const_iterator i = gcObjects.begin(); i != gcObjects.end(); ++i) + { + counts.insert(GCCountMap::value_type(*i, (*i)->__getRefUnsafe())); + (*i)->__gcReachable(reachable); + } + } + + // + // Decrement the reference count for each object in the counts map by the count in the reachable + // map. This drops the reference count of each object in the counts map by the number of times that + // the object is pointed at by other objects in the counts map. + // + { + for(GCCountMap::const_iterator i = reachable.begin(); i != reachable.end(); ++i) + { + GCCountMap::iterator pos = counts.find(i->first); + assert(pos != counts.end()); + pos->second -= i->second; + } + } } { - // - // Any instances in the counts map with a ref count > 0 are referenced from outside the objects in - // gcObjects (and are therefore reachable from the program, for example, via Ptr variable on the stack). - // The set of live objects therefore are all the objects with a reference count > 0, as well as all - // objects that are (recursively) reachable from these objects. - // - GCObjectSet liveObjects; - { - for(GCCountMap::const_iterator i = counts.begin(); i != counts.end(); ++i) - { - if(i->second > 0) - { - recursivelyReachable(i->first, liveObjects); - } - } - } - - // - // Remove all live objects from the counts map. - // - { - for(GCObjectSet::const_iterator i = liveObjects.begin(); i != liveObjects.end(); ++i) - { + // + // Any instances in the counts map with a ref count > 0 are referenced from outside the objects in + // gcObjects (and are therefore reachable from the program, for example, via Ptr variable on the stack). + // The set of live objects therefore are all the objects with a reference count > 0, as well as all + // objects that are (recursively) reachable from these objects. + // + GCObjectSet liveObjects; + { + for(GCCountMap::const_iterator i = counts.begin(); i != counts.end(); ++i) + { + if(i->second > 0) + { + recursivelyReachable(i->first, liveObjects); + } + } + } + + // + // Remove all live objects from the counts map. + // + { + for(GCObjectSet::const_iterator i = liveObjects.begin(); i != liveObjects.end(); ++i) + { #ifndef NDEBUG - size_t erased = + size_t erased = #endif - counts.erase(*i); - assert(erased != 0); - } - } + counts.erase(*i); + assert(erased != 0); + } + } } // // What is left in the counts map can be garbage collected. // { - GCCountMap::const_iterator i; - for(i = counts.begin(); i != counts.end(); ++i) - { - // - // For classes with members that point at potentially-cyclic instances, __gcClear() - // decrements the reference count of the pointed-at instances as many times as they are - // pointed at and clears the corresponding Ptr members in the pointing class. - // For classes that cannot be part of a cycle (because they do not contain class members) - // and are therefore true leaves, __gcClear() assigns 0 to the corresponding class member, - // which either decrements the ref count or, if it reaches zero, deletes the instance as usual. - // - i->first->__gcClear(); - } - for(i = counts.begin(); i != counts.end(); ++i) - { - gcObjects.erase(i->first); // Remove this object from candidate set. - delete i->first; // Delete this object. - } + GCCountMap::const_iterator i; + for(i = counts.begin(); i != counts.end(); ++i) + { + // + // For classes with members that point at potentially-cyclic instances, __gcClear() + // decrements the reference count of the pointed-at instances as many times as they are + // pointed at and clears the corresponding Ptr members in the pointing class. + // For classes that cannot be part of a cycle (because they do not contain class members) + // and are therefore true leaves, __gcClear() assigns 0 to the corresponding class member, + // which either decrements the ref count or, if it reaches zero, deletes the instance as usual. + // + i->first->__gcClear(); + } + for(i = counts.begin(); i != counts.end(); ++i) + { + gcObjects.erase(i->first); // Remove this object from candidate set. + delete i->first; // Delete this object. + } } if(_statsCallback) { - stats.time = Time::now() - t; - stats.collected = static_cast(counts.size()); - _statsCallback(stats); + stats.time = Time::now() - t; + stats.collected = static_cast(counts.size()); + _statsCallback(stats); } // @@ -381,8 +381,8 @@ IceInternal::GC::collectGarbage() counts.clear(); { - Monitor::Lock sync(*this); + Monitor::Lock sync(*this); - _collecting = false; + _collecting = false; } } diff --git a/cpp/src/Ice/IdentityUtil.cpp b/cpp/src/Ice/IdentityUtil.cpp index 8b078b0e96c..4758804b4fb 100644 --- a/cpp/src/Ice/IdentityUtil.cpp +++ b/cpp/src/Ice/IdentityUtil.cpp @@ -81,10 +81,10 @@ Ice::identityToString(const Identity& ident) { if(ident.category.empty()) { - return IceUtil::escapeString(ident.name, "/"); + return IceUtil::escapeString(ident.name, "/"); } else { - return IceUtil::escapeString(ident.category, "/") + '/' + IceUtil::escapeString(ident.name, "/"); + return IceUtil::escapeString(ident.category, "/") + '/' + IceUtil::escapeString(ident.name, "/"); } } diff --git a/cpp/src/Ice/ImplicitContextI.cpp b/cpp/src/Ice/ImplicitContextI.cpp index ab78a011dab..7dd27c0fada 100644 --- a/cpp/src/Ice/ImplicitContextI.cpp +++ b/cpp/src/Ice/ImplicitContextI.cpp @@ -80,14 +80,14 @@ public: struct Slot { - Slot() : - context(0), - owner(-1) // just to avoid UMR; a random value would work as well - { - } - - Context* context; - long owner; + Slot() : + context(0), + owner(-1) // just to avoid UMR; a random value would work as well + { + } + + Context* context; + long owner; }; @@ -129,25 +129,25 @@ ImplicitContextI::create(const std::string& kind) { if(kind == "None" || kind == "") { - return 0; + return 0; } else if(kind == "Shared") { - return new SharedImplicitContext; + return new SharedImplicitContext; } else if(kind == "SharedWithoutLocking") { - return new SharedImplicitContextWithoutLocking; + return new SharedImplicitContextWithoutLocking; } else if(kind == "PerThread") { - return new PerThreadImplicitContext; + return new PerThreadImplicitContext; } else { - throw Ice::InitializationException( - __FILE__, __LINE__, - "'" + kind + "' is not a valid value for Ice.ImplicitContext"); + throw Ice::InitializationException( + __FILE__, __LINE__, + "'" + kind + "' is not a valid value for Ice.ImplicitContext"); return 0; // Keep the compiler happy. } } @@ -158,8 +158,8 @@ ImplicitContextI::cleanupThread() { if(PerThreadImplicitContext::_nextId > 0) { - PerThreadImplicitContext::threadDestructor( - TlsGetValue(PerThreadImplicitContext::_key)); + PerThreadImplicitContext::threadDestructor( + TlsGetValue(PerThreadImplicitContext::_key)); } } #endif @@ -186,7 +186,7 @@ SharedImplicitContextWithoutLocking::get(const string& k) const Context::const_iterator p = _context.find(k); if(p == _context.end()) { - throw NotSetException(__FILE__, __LINE__, k); + throw NotSetException(__FILE__, __LINE__, k); } return p->second; } @@ -197,7 +197,7 @@ SharedImplicitContextWithoutLocking::getWithDefault(const string& k, const strin Context::const_iterator p = _context.find(k); if(p == _context.end()) { - return d; + return d; } return p->second; } @@ -213,7 +213,7 @@ SharedImplicitContextWithoutLocking::remove(const string& k) { if(_context.erase(k) == 0) { - throw NotSetException(__FILE__, __LINE__, k); + throw NotSetException(__FILE__, __LINE__, k); } } @@ -222,17 +222,17 @@ SharedImplicitContextWithoutLocking::write(const Context& proxyCtx, ::IceInterna { if(proxyCtx.size() == 0) { - __write(s, _context, __U__Context()); + __write(s, _context, __U__Context()); } else if(_context.size() == 0) { - __write(s, proxyCtx, __U__Context()); + __write(s, proxyCtx, __U__Context()); } else { - Context combined = proxyCtx; - combined.insert(_context.begin(), _context.end()); - __write(s, combined, __U__Context()); + Context combined = proxyCtx; + combined.insert(_context.begin(), _context.end()); + __write(s, combined, __U__Context()); } } @@ -241,16 +241,16 @@ SharedImplicitContextWithoutLocking::combine(const Context& proxyCtx, Context& c { if(proxyCtx.size() == 0) { - ctx = _context; + ctx = _context; } else if(_context.size() == 0) { - ctx = proxyCtx; + ctx = proxyCtx; } else { - ctx = proxyCtx; - ctx.insert(_context.begin(), _context.end()); + ctx = proxyCtx; + ctx.insert(_context.begin(), _context.end()); } } @@ -307,19 +307,19 @@ SharedImplicitContext::write(const Context& proxyCtx, ::IceInternal::BasicStream IceUtil::Mutex::Lock lock(_mutex); if(proxyCtx.size() == 0) { - __write(s, _context, __U__Context()); + __write(s, _context, __U__Context()); } else if(_context.size() == 0) { - lock.release(); - __write(s, proxyCtx, __U__Context()); + lock.release(); + __write(s, proxyCtx, __U__Context()); } else { - Context combined = proxyCtx; - combined.insert(_context.begin(), _context.end()); - lock.release(); - __write(s, combined, __U__Context()); + Context combined = proxyCtx; + combined.insert(_context.begin(), _context.end()); + lock.release(); + __write(s, combined, __U__Context()); } } @@ -350,22 +350,22 @@ PerThreadImplicitContext::PerThreadImplicitContext() _id = _nextId++; if(_id == 0) { - // - // Initialize; note that we never dealloc this key (it would be - // complex, and since it's a static variable, it's not really a leak) - // + // + // Initialize; note that we never dealloc this key (it would be + // complex, and since it's a static variable, it's not really a leak) + // #ifdef _WIN32 - _key = TlsAlloc(); - if(_key == TLS_OUT_OF_INDEXES) - { - throw IceUtil::ThreadSyscallException(__FILE__, __LINE__, GetLastError()); - } + _key = TlsAlloc(); + if(_key == TLS_OUT_OF_INDEXES) + { + throw IceUtil::ThreadSyscallException(__FILE__, __LINE__, GetLastError()); + } #else - int err = pthread_key_create(&_key, &threadDestructor); - if(err != 0) - { - throw IceUtil::ThreadSyscallException(__FILE__, __LINE__, err); - } + int err = pthread_key_create(&_key, &threadDestructor); + if(err != 0) + { + throw IceUtil::ThreadSyscallException(__FILE__, __LINE__, err); + } #endif } @@ -374,17 +374,17 @@ PerThreadImplicitContext::PerThreadImplicitContext() // if(_indexInUse == 0) { - _indexInUse = new IndexInUse(1); + _indexInUse = new IndexInUse(1); } size_t i = 0; while(i < _indexInUse->size() && (*_indexInUse)[i]) { - i++; + i++; } if(i == _indexInUse->size()) { - _indexInUse->resize(i + 1); + _indexInUse->resize(i + 1); } (*_indexInUse)[i] = true; _index = i; @@ -397,8 +397,8 @@ PerThreadImplicitContext::~PerThreadImplicitContext() if(find(_indexInUse->begin(), _indexInUse->end(), true) == _indexInUse->end()) { - delete _indexInUse; - _indexInUse = 0; + delete _indexInUse; + _indexInUse = 0; } } @@ -408,17 +408,17 @@ PerThreadImplicitContext::threadDestructor(void* v) SlotVector* sv = static_cast(v); if(sv != 0) { - // - // Cleanup each slot - // - for(SlotVector::iterator p = sv->begin(); p != sv->end(); ++p) - { - delete p->context; - } - // - // Then the vector - // - delete sv; + // + // Cleanup each slot + // + for(SlotVector::iterator p = sv->begin(); p != sv->end(); ++p) + { + delete p->context; + } + // + // Then the vector + // + delete sv; } } @@ -432,65 +432,65 @@ PerThreadImplicitContext::getThreadContext(bool allocate) const #endif if(sv == 0) { - if(!allocate) - { - return 0; - } + if(!allocate) + { + return 0; + } - sv = new SlotVector(_index + 1); + sv = new SlotVector(_index + 1); #ifdef _WIN32 - if(TlsSetValue(_key, sv) == 0) - { - throw IceUtil::ThreadSyscallException(__FILE__, __LINE__, GetLastError()); - } + if(TlsSetValue(_key, sv) == 0) + { + throw IceUtil::ThreadSyscallException(__FILE__, __LINE__, GetLastError()); + } #else - if(int err = pthread_setspecific(_key, sv)) - { - throw IceUtil::ThreadSyscallException(__FILE__, __LINE__, err); - } + if(int err = pthread_setspecific(_key, sv)) + { + throw IceUtil::ThreadSyscallException(__FILE__, __LINE__, err); + } #endif } else { - if(sv->size() <= _index) - { - if(!allocate) - { - return 0; - } - else - { - sv->resize(_index + 1); - } - } + if(sv->size() <= _index) + { + if(!allocate) + { + return 0; + } + else + { + sv->resize(_index + 1); + } + } } Slot& slot = (*sv)[_index]; if(slot.context != 0) { - if(slot.owner != _id) - { - // - // Reuse the slot from another (dead) communicator - // - slot.context->clear(); - slot.owner = _id; - } - // - // else keep this slot.context - // + if(slot.owner != _id) + { + // + // Reuse the slot from another (dead) communicator + // + slot.context->clear(); + slot.owner = _id; + } + // + // else keep this slot.context + // } else { - if(allocate) - { - slot.context = new Context; - slot.owner = _id; - } - // - // else keep null slot.context - // + if(allocate) + { + slot.context = new Context; + slot.owner = _id; + } + // + // else keep null slot.context + // } return slot.context; } @@ -505,33 +505,33 @@ PerThreadImplicitContext::clearThreadContext() const #endif if(sv != 0 && _index < sv->size()) { - delete (*sv)[_index].context; - (*sv)[_index].context = 0; - - int i = sv->size() - 1; - while(i >= 0 && (*sv)[i].context == 0) - { - i--; - } - if(i < 0) - { - delete sv; + delete (*sv)[_index].context; + (*sv)[_index].context = 0; + + int i = sv->size() - 1; + while(i >= 0 && (*sv)[i].context == 0) + { + i--; + } + if(i < 0) + { + delete sv; #ifdef _WIN32 - if(TlsSetValue(_key, 0) == 0) - { - IceUtil::ThreadSyscallException(__FILE__, __LINE__, GetLastError()); - } + if(TlsSetValue(_key, 0) == 0) + { + IceUtil::ThreadSyscallException(__FILE__, __LINE__, GetLastError()); + } #else - if(int err = pthread_setspecific(_key, 0)) - { - throw IceUtil::ThreadSyscallException(__FILE__, __LINE__, err); - } + if(int err = pthread_setspecific(_key, 0)) + { + throw IceUtil::ThreadSyscallException(__FILE__, __LINE__, err); + } #endif - } - else - { - sv->resize(i + 1); - } + } + else + { + sv->resize(i + 1); + } } } @@ -542,11 +542,11 @@ PerThreadImplicitContext::getContext() const Context* ctx = getThreadContext(false); if(ctx == 0) { - return Context(); + return Context(); } else { - return *ctx; + return *ctx; } } @@ -555,13 +555,13 @@ PerThreadImplicitContext::setContext(const Context& newContext) { if(newContext.size() == 0) { - clearThreadContext(); + clearThreadContext(); } else { - Context* ctx = getThreadContext(true); - assert(ctx != 0); - *ctx = newContext; + Context* ctx = getThreadContext(true); + assert(ctx != 0); + *ctx = newContext; } } @@ -571,12 +571,12 @@ PerThreadImplicitContext::get(const string& k) const Context* ctx = getThreadContext(false); if(ctx == 0) { - throw NotSetException(__FILE__, __LINE__, k); + throw NotSetException(__FILE__, __LINE__, k); } Context::const_iterator p = ctx->find(k); if(p == ctx->end()) { - throw NotSetException(__FILE__, __LINE__, k); + throw NotSetException(__FILE__, __LINE__, k); } return p->second; } @@ -587,12 +587,12 @@ PerThreadImplicitContext::getWithDefault(const string& k, const string& d) const Context* ctx = getThreadContext(false); if(ctx == 0) { - return d; + return d; } Context::const_iterator p = ctx->find(k); if(p == ctx->end()) { - return d; + return d; } return p->second; } @@ -610,12 +610,12 @@ PerThreadImplicitContext::remove(const string& k) Context* ctx = getThreadContext(false); if(ctx == 0 || ctx->erase(k) == 0) { - throw NotSetException(__FILE__, __LINE__, k); + throw NotSetException(__FILE__, __LINE__, k); } if(ctx->size() == 0) { - clearThreadContext(); + clearThreadContext(); } } @@ -626,17 +626,17 @@ PerThreadImplicitContext::write(const Context& proxyCtx, ::IceInternal::BasicStr if(threadCtx == 0 || threadCtx->size() == 0) { - __write(s, proxyCtx, __U__Context()); + __write(s, proxyCtx, __U__Context()); } else if(proxyCtx.size() == 0) { - __write(s, *threadCtx, __U__Context()); + __write(s, *threadCtx, __U__Context()); } else { - Context combined = proxyCtx; - combined.insert(threadCtx->begin(), threadCtx->end()); - __write(s, combined, __U__Context()); + Context combined = proxyCtx; + combined.insert(threadCtx->begin(), threadCtx->end()); + __write(s, combined, __U__Context()); } } @@ -647,15 +647,15 @@ PerThreadImplicitContext::combine(const Context& proxyCtx, Context& ctx) const if(threadCtx == 0 || threadCtx->size() == 0) { - ctx = proxyCtx; + ctx = proxyCtx; } else if(proxyCtx.size() == 0) { - ctx = *threadCtx; + ctx = *threadCtx; } else { - ctx = proxyCtx; - ctx.insert(threadCtx->begin(), threadCtx->end()); + ctx = proxyCtx; + ctx.insert(threadCtx->begin(), threadCtx->end()); } } diff --git a/cpp/src/Ice/Incoming.cpp b/cpp/src/Ice/Incoming.cpp index bd41e14fef1..22dbebf73e7 100644 --- a/cpp/src/Ice/Incoming.cpp +++ b/cpp/src/Ice/Incoming.cpp @@ -25,8 +25,8 @@ using namespace Ice; using namespace IceInternal; IceInternal::IncomingBase::IncomingBase(Instance* instance, ConnectionI* connection, - const ObjectAdapterPtr& adapter, - bool response, Byte compress, Int requestId) : + const ObjectAdapterPtr& adapter, + bool response, Byte compress, Int requestId) : _response(response), _compress(compress), _os(instance), @@ -74,199 +74,199 @@ IceInternal::IncomingBase::__handleException(const Ice::Exception& ex) { try { - ex.ice_throw(); + ex.ice_throw(); } catch(RequestFailedException& ex) { - if(ex.id.name.empty()) - { - ex.id = _current.id; - } - - if(ex.facet.empty() && !_current.facet.empty()) - { - ex.facet = _current.facet; - } - - if(ex.operation.empty() && !_current.operation.empty()) - { - ex.operation = _current.operation; - } - - if(_os.instance()->initializationData().properties->getPropertyAsIntWithDefault("Ice.Warn.Dispatch", 1) > 1) - { - __warning(ex); - } - - if(_response) - { - _os.endWriteEncaps(); - _os.b.resize(headerSize + 4); // Dispatch status position. - if(dynamic_cast(&ex)) - { - _os.write(static_cast(DispatchObjectNotExist)); - } - else if(dynamic_cast(&ex)) - { - _os.write(static_cast(DispatchFacetNotExist)); - } - else if(dynamic_cast(&ex)) - { - _os.write(static_cast(DispatchOperationNotExist)); - } - else - { - assert(false); - } - - ex.id.__write(&_os); - - // - // For compatibility with the old FacetPath. - // - if(ex.facet.empty()) - { - _os.write(static_cast(0), static_cast(0)); - } - else - { - _os.write(&ex.facet, &ex.facet + 1); - } - - _os.write(ex.operation, false); - - _connection->sendResponse(&_os, _compress); - } - else - { - _connection->sendNoResponse(); - } + if(ex.id.name.empty()) + { + ex.id = _current.id; + } + + if(ex.facet.empty() && !_current.facet.empty()) + { + ex.facet = _current.facet; + } + + if(ex.operation.empty() && !_current.operation.empty()) + { + ex.operation = _current.operation; + } + + if(_os.instance()->initializationData().properties->getPropertyAsIntWithDefault("Ice.Warn.Dispatch", 1) > 1) + { + __warning(ex); + } + + if(_response) + { + _os.endWriteEncaps(); + _os.b.resize(headerSize + 4); // Dispatch status position. + if(dynamic_cast(&ex)) + { + _os.write(static_cast(DispatchObjectNotExist)); + } + else if(dynamic_cast(&ex)) + { + _os.write(static_cast(DispatchFacetNotExist)); + } + else if(dynamic_cast(&ex)) + { + _os.write(static_cast(DispatchOperationNotExist)); + } + else + { + assert(false); + } + + ex.id.__write(&_os); + + // + // For compatibility with the old FacetPath. + // + if(ex.facet.empty()) + { + _os.write(static_cast(0), static_cast(0)); + } + else + { + _os.write(&ex.facet, &ex.facet + 1); + } + + _os.write(ex.operation, false); + + _connection->sendResponse(&_os, _compress); + } + else + { + _connection->sendNoResponse(); + } } catch(const UnknownLocalException& ex) { - if(_os.instance()->initializationData().properties->getPropertyAsIntWithDefault("Ice.Warn.Dispatch", 1) > 0) - { - __warning(ex); - } - - if(_response) - { - _os.endWriteEncaps(); - _os.b.resize(headerSize + 4); // Dispatch status position. - _os.write(static_cast(DispatchUnknownLocalException)); - _os.write(ex.unknown, false); - _connection->sendResponse(&_os, _compress); - } - else - { - _connection->sendNoResponse(); - } + if(_os.instance()->initializationData().properties->getPropertyAsIntWithDefault("Ice.Warn.Dispatch", 1) > 0) + { + __warning(ex); + } + + if(_response) + { + _os.endWriteEncaps(); + _os.b.resize(headerSize + 4); // Dispatch status position. + _os.write(static_cast(DispatchUnknownLocalException)); + _os.write(ex.unknown, false); + _connection->sendResponse(&_os, _compress); + } + else + { + _connection->sendNoResponse(); + } } catch(const UnknownUserException& ex) { - if(_os.instance()->initializationData().properties->getPropertyAsIntWithDefault("Ice.Warn.Dispatch", 1) > 0) - { - __warning(ex); - } - - if(_response) - { - _os.endWriteEncaps(); - _os.b.resize(headerSize + 4); // Dispatch status position. - _os.write(static_cast(DispatchUnknownUserException)); - _os.write(ex.unknown, false); - _connection->sendResponse(&_os, _compress); - } - else - { - _connection->sendNoResponse(); - } + if(_os.instance()->initializationData().properties->getPropertyAsIntWithDefault("Ice.Warn.Dispatch", 1) > 0) + { + __warning(ex); + } + + if(_response) + { + _os.endWriteEncaps(); + _os.b.resize(headerSize + 4); // Dispatch status position. + _os.write(static_cast(DispatchUnknownUserException)); + _os.write(ex.unknown, false); + _connection->sendResponse(&_os, _compress); + } + else + { + _connection->sendNoResponse(); + } } catch(const UnknownException& ex) { - if(_os.instance()->initializationData().properties->getPropertyAsIntWithDefault("Ice.Warn.Dispatch", 1) > 0) - { - __warning(ex); - } - - if(_response) - { - _os.endWriteEncaps(); - _os.b.resize(headerSize + 4); // Dispatch status position. - _os.write(static_cast(DispatchUnknownException)); - _os.write(ex.unknown, false); - _connection->sendResponse(&_os, _compress); - } - else - { - _connection->sendNoResponse(); - } + if(_os.instance()->initializationData().properties->getPropertyAsIntWithDefault("Ice.Warn.Dispatch", 1) > 0) + { + __warning(ex); + } + + if(_response) + { + _os.endWriteEncaps(); + _os.b.resize(headerSize + 4); // Dispatch status position. + _os.write(static_cast(DispatchUnknownException)); + _os.write(ex.unknown, false); + _connection->sendResponse(&_os, _compress); + } + else + { + _connection->sendNoResponse(); + } } catch(const LocalException& ex) { - if(_os.instance()->initializationData().properties->getPropertyAsIntWithDefault("Ice.Warn.Dispatch", 1) > 0) - { - __warning(ex); - } - - if(_response) - { - _os.endWriteEncaps(); - _os.b.resize(headerSize + 4); // Dispatch status position. - _os.write(static_cast(DispatchUnknownLocalException)); - ostringstream str; - str << ex; - _os.write(str.str(), false); - _connection->sendResponse(&_os, _compress); - } - else - { - _connection->sendNoResponse(); - } + if(_os.instance()->initializationData().properties->getPropertyAsIntWithDefault("Ice.Warn.Dispatch", 1) > 0) + { + __warning(ex); + } + + if(_response) + { + _os.endWriteEncaps(); + _os.b.resize(headerSize + 4); // Dispatch status position. + _os.write(static_cast(DispatchUnknownLocalException)); + ostringstream str; + str << ex; + _os.write(str.str(), false); + _connection->sendResponse(&_os, _compress); + } + else + { + _connection->sendNoResponse(); + } } catch(const UserException& ex) { - if(_os.instance()->initializationData().properties->getPropertyAsIntWithDefault("Ice.Warn.Dispatch", 1) > 0) - { - __warning(ex); - } - - if(_response) - { - _os.endWriteEncaps(); - _os.b.resize(headerSize + 4); // Dispatch status position. - _os.write(static_cast(DispatchUnknownUserException)); - ostringstream str; - str << ex; - _os.write(str.str(), false); - _connection->sendResponse(&_os, _compress); - } - else - { - _connection->sendNoResponse(); - } + if(_os.instance()->initializationData().properties->getPropertyAsIntWithDefault("Ice.Warn.Dispatch", 1) > 0) + { + __warning(ex); + } + + if(_response) + { + _os.endWriteEncaps(); + _os.b.resize(headerSize + 4); // Dispatch status position. + _os.write(static_cast(DispatchUnknownUserException)); + ostringstream str; + str << ex; + _os.write(str.str(), false); + _connection->sendResponse(&_os, _compress); + } + else + { + _connection->sendNoResponse(); + } } catch(const Exception& ex) { - if(_os.instance()->initializationData().properties->getPropertyAsIntWithDefault("Ice.Warn.Dispatch", 1) > 0) - { - __warning(ex); - } - - if(_response) - { - _os.endWriteEncaps(); - _os.b.resize(headerSize + 4); // Dispatch status position. - _os.write(static_cast(DispatchUnknownException)); - ostringstream str; - str << ex; - _os.write(str.str(), false); - _connection->sendResponse(&_os, _compress); - } - else - { - _connection->sendNoResponse(); - } + if(_os.instance()->initializationData().properties->getPropertyAsIntWithDefault("Ice.Warn.Dispatch", 1) > 0) + { + __warning(ex); + } + + if(_response) + { + _os.endWriteEncaps(); + _os.b.resize(headerSize + 4); // Dispatch status position. + _os.write(static_cast(DispatchUnknownException)); + ostringstream str; + str << ex; + _os.write(str.str(), false); + _connection->sendResponse(&_os, _compress); + } + else + { + _connection->sendNoResponse(); + } } } @@ -275,22 +275,22 @@ IceInternal::IncomingBase::__handleException(const std::exception& ex) { if(_os.instance()->initializationData().properties->getPropertyAsIntWithDefault("Ice.Warn.Dispatch", 1) > 0) { - __warning(string("std::exception: ") + ex.what()); + __warning(string("std::exception: ") + ex.what()); } if(_response) { - _os.endWriteEncaps(); - _os.b.resize(headerSize + 4); // Dispatch status position. - _os.write(static_cast(DispatchUnknownException)); - ostringstream str; - str << "std::exception: " << ex.what(); - _os.write(str.str(), false); - _connection->sendResponse(&_os, _compress); + _os.endWriteEncaps(); + _os.b.resize(headerSize + 4); // Dispatch status position. + _os.write(static_cast(DispatchUnknownException)); + ostringstream str; + str << "std::exception: " << ex.what(); + _os.write(str.str(), false); + _connection->sendResponse(&_os, _compress); } else { - _connection->sendNoResponse(); + _connection->sendNoResponse(); } } @@ -299,27 +299,27 @@ IceInternal::IncomingBase::__handleException() { if(_os.instance()->initializationData().properties->getPropertyAsIntWithDefault("Ice.Warn.Dispatch", 1) > 0) { - __warning("unknown c++ exception"); + __warning("unknown c++ exception"); } if(_response) { - _os.endWriteEncaps(); - _os.b.resize(headerSize + 4); // Dispatch status position. - _os.write(static_cast(DispatchUnknownException)); - string reason = "unknown c++ exception"; - _os.write(reason, false); - _connection->sendResponse(&_os, _compress); + _os.endWriteEncaps(); + _os.b.resize(headerSize + 4); // Dispatch status position. + _os.write(static_cast(DispatchUnknownException)); + string reason = "unknown c++ exception"; + _os.write(reason, false); + _connection->sendResponse(&_os, _compress); } else { - _connection->sendNoResponse(); + _connection->sendNoResponse(); } } IceInternal::Incoming::Incoming(Instance* instance, ConnectionI* connection, - const ObjectAdapterPtr& adapter, - bool response, Byte compress, Int requestId) : + const ObjectAdapterPtr& adapter, + bool response, Byte compress, Int requestId) : IncomingBase(instance, connection, adapter, response, compress, requestId), _is(instance) { @@ -338,16 +338,16 @@ IceInternal::Incoming::invoke(const ServantManagerPtr& servantManager) // string facet; { - vector facetPath; - _is.read(facetPath); - if(!facetPath.empty()) - { - if(facetPath.size() > 1) - { - throw MarshalException(__FILE__, __LINE__); - } - facet.swap(facetPath[0]); - } + vector facetPath; + _is.read(facetPath); + if(!facetPath.empty()) + { + if(facetPath.size() > 1) + { + throw MarshalException(__FILE__, __LINE__); + } + facet.swap(facetPath[0]); + } } _current.facet.swap(facet); @@ -361,19 +361,19 @@ IceInternal::Incoming::invoke(const ServantManagerPtr& servantManager) _is.readSize(sz); while(sz--) { - pair pr; - _is.read(const_cast(pr.first)); - _is.read(pr.second); - _current.ctx.insert(_current.ctx.end(), pr); + pair pr; + _is.read(const_cast(pr.first)); + _is.read(pr.second); + _current.ctx.insert(_current.ctx.end(), pr); } _is.startReadEncaps(); if(_response) { - assert(_os.b.size() == headerSize + 4); // Dispatch status position. - _os.write(static_cast(0)); - _os.startWriteEncaps(); + assert(_os.b.size() == headerSize + 4); // Dispatch status position. + _os.write(static_cast(0)); + _os.startWriteEncaps(); } // Initialize status to some value, to keep the compiler happy. @@ -387,72 +387,72 @@ IceInternal::Incoming::invoke(const ServantManagerPtr& servantManager) try { - try - { - if(servantManager) - { - _servant = servantManager->findServant(_current.id, _current.facet); - if(!_servant) - { - _locator = servantManager->findServantLocator(_current.id.category); - if(!_locator && !_current.id.category.empty()) - { - _locator = servantManager->findServantLocator(""); - } - if(_locator) - { - _servant = _locator->locate(_current, _cookie); - } - } - } - if(!_servant) - { - if(servantManager && servantManager->hasServant(_current.id)) - { - status = DispatchFacetNotExist; - } - else - { - status = DispatchObjectNotExist; - } - } - else - { - status = _servant->__dispatch(*this, _current); - } - } - catch(...) - { - if(_locator && _servant && status != DispatchAsync) - { - _locator->finished(_current, _servant, _cookie); - } - - throw; - } - - if(_locator && _servant && status != DispatchAsync) - { - _locator->finished(_current, _servant, _cookie); - } + try + { + if(servantManager) + { + _servant = servantManager->findServant(_current.id, _current.facet); + if(!_servant) + { + _locator = servantManager->findServantLocator(_current.id.category); + if(!_locator && !_current.id.category.empty()) + { + _locator = servantManager->findServantLocator(""); + } + if(_locator) + { + _servant = _locator->locate(_current, _cookie); + } + } + } + if(!_servant) + { + if(servantManager && servantManager->hasServant(_current.id)) + { + status = DispatchFacetNotExist; + } + else + { + status = DispatchObjectNotExist; + } + } + else + { + status = _servant->__dispatch(*this, _current); + } + } + catch(...) + { + if(_locator && _servant && status != DispatchAsync) + { + _locator->finished(_current, _servant, _cookie); + } + + throw; + } + + if(_locator && _servant && status != DispatchAsync) + { + _locator->finished(_current, _servant, _cookie); + } } catch(const Exception& ex) { - _is.endReadEncaps(); - __handleException(ex); - return; + _is.endReadEncaps(); + __handleException(ex); + return; } catch(const std::exception& ex) { - _is.endReadEncaps(); - __handleException(ex); - return; + _is.endReadEncaps(); + __handleException(ex); + return; } catch(...) { - _is.endReadEncaps(); - __handleException(); - return; + _is.endReadEncaps(); + __handleException(); + return; } // @@ -469,50 +469,50 @@ IceInternal::Incoming::invoke(const ServantManagerPtr& servantManager) // if(status == DispatchAsync) { - // - // If this was an asynchronous dispatch, we're done here. - // - return; + // + // If this was an asynchronous dispatch, we're done here. + // + return; } if(_response) { - _os.endWriteEncaps(); - - if(status != DispatchOK && status != DispatchUserException) - { - assert(status == DispatchObjectNotExist || - status == DispatchFacetNotExist || - status == DispatchOperationNotExist); - - _os.b.resize(headerSize + 4); // Dispatch status position. - _os.write(static_cast(status)); - - _current.id.__write(&_os); - - // - // For compatibility with the old FacetPath. - // - if(_current.facet.empty()) - { - _os.write(static_cast(0), static_cast(0)); - } - else - { - _os.write(&_current.facet, &_current.facet + 1); - } - - _os.write(_current.operation, false); - } - else - { - *(_os.b.begin() + headerSize + 4) = static_cast(status); // Dispatch status position. - } - - _connection->sendResponse(&_os, _compress); + _os.endWriteEncaps(); + + if(status != DispatchOK && status != DispatchUserException) + { + assert(status == DispatchObjectNotExist || + status == DispatchFacetNotExist || + status == DispatchOperationNotExist); + + _os.b.resize(headerSize + 4); // Dispatch status position. + _os.write(static_cast(status)); + + _current.id.__write(&_os); + + // + // For compatibility with the old FacetPath. + // + if(_current.facet.empty()) + { + _os.write(static_cast(0), static_cast(0)); + } + else + { + _os.write(&_current.facet, &_current.facet + 1); + } + + _os.write(_current.operation, false); + } + else + { + *(_os.b.begin() + headerSize + 4) = static_cast(status); // Dispatch status position. + } + + _connection->sendResponse(&_os, _compress); } else { - _connection->sendNoResponse(); + _connection->sendNoResponse(); } } diff --git a/cpp/src/Ice/IncomingAsync.cpp b/cpp/src/Ice/IncomingAsync.cpp index 00127ea64e9..b7c60f8592d 100644 --- a/cpp/src/Ice/IncomingAsync.cpp +++ b/cpp/src/Ice/IncomingAsync.cpp @@ -41,34 +41,34 @@ IceInternal::IncomingAsync::__response(bool ok) { try { - if(!__servantLocatorFinished()) - { - return; - } - - if(_response) - { - _os.endWriteEncaps(); - - if(ok) - { - *(_os.b.begin() + headerSize + 4) = static_cast(DispatchOK); - } - else - { - *(_os.b.begin() + headerSize + 4) = static_cast(DispatchUserException); - } - - _connection->sendResponse(&_os, _compress); - } - else - { - _connection->sendNoResponse(); - } + if(!__servantLocatorFinished()) + { + return; + } + + if(_response) + { + _os.endWriteEncaps(); + + if(ok) + { + *(_os.b.begin() + headerSize + 4) = static_cast(DispatchOK); + } + else + { + *(_os.b.begin() + headerSize + 4) = static_cast(DispatchUserException); + } + + _connection->sendResponse(&_os, _compress); + } + else + { + _connection->sendNoResponse(); + } } catch(const LocalException& ex) { - _connection->invokeException(ex, 1); // Fatal invocation exception + _connection->invokeException(ex, 1); // Fatal invocation exception } } @@ -77,16 +77,16 @@ IceInternal::IncomingAsync::__exception(const Exception& exc) { try { - if(!__servantLocatorFinished()) - { - return; - } + if(!__servantLocatorFinished()) + { + return; + } - __handleException(exc); + __handleException(exc); } catch(const LocalException& ex) { - _connection->invokeException(ex, 1); // Fatal invocation exception + _connection->invokeException(ex, 1); // Fatal invocation exception } } @@ -95,16 +95,16 @@ IceInternal::IncomingAsync::__exception(const std::exception& exc) { try { - if(!__servantLocatorFinished()) - { - return; - } + if(!__servantLocatorFinished()) + { + return; + } - __handleException(exc); + __handleException(exc); } catch(const LocalException& ex) { - _connection->invokeException(ex, 1); // Fatal invocation exception + _connection->invokeException(ex, 1); // Fatal invocation exception } } @@ -113,16 +113,16 @@ IceInternal::IncomingAsync::__exception() { try { - if(!__servantLocatorFinished()) - { - return; - } + if(!__servantLocatorFinished()) + { + return; + } - __handleException(); + __handleException(); } catch(const LocalException& ex) { - _connection->invokeException(ex, 1); // Fatal invocation exception + _connection->invokeException(ex, 1); // Fatal invocation exception } } @@ -131,26 +131,26 @@ IceInternal::IncomingAsync::__servantLocatorFinished() { try { - if(_locator && _servant) - { - _locator->finished(_current, _servant, _cookie); - } - return true; + if(_locator && _servant) + { + _locator->finished(_current, _servant, _cookie); + } + return true; } catch(const Exception& ex) { - __handleException(ex); - return false; + __handleException(ex); + return false; } catch(const std::exception& ex) { - __handleException(ex); - return false; + __handleException(ex); + return false; } catch(...) { - __handleException(); - return false; + __handleException(); + return false; } } @@ -164,12 +164,12 @@ IceAsync::Ice::AMD_Object_ice_invoke::ice_response(bool ok, const vector& { try { - __os()->writeBlob(outParams); + __os()->writeBlob(outParams); } catch(const LocalException& ex) { - __exception(ex); - return; + __exception(ex); + return; } __response(ok); } @@ -202,12 +202,12 @@ IceAsync::Ice::AMD_Array_Object_ice_invoke::ice_response(bool ok, const pairwriteBlob(outParams.first, static_cast(outParams.second - outParams.first)); + __os()->writeBlob(outParams.first, static_cast(outParams.second - outParams.first)); } catch(const LocalException& ex) { - __exception(ex); - return; + __exception(ex); + return; } __response(ok); } diff --git a/cpp/src/Ice/Initialize.cpp b/cpp/src/Ice/Initialize.cpp index cb7252ddf94..70ce1296280 100644 --- a/cpp/src/Ice/Initialize.cpp +++ b/cpp/src/Ice/Initialize.cpp @@ -32,7 +32,7 @@ Ice::collectGarbage() { if(theCollector) { - theCollector->collectGarbage(); + theCollector->collectGarbage(); } } @@ -80,7 +80,7 @@ Ice::stringSeqToArgs(const StringSeq& args, int& argc, char* argv[]) // if(argv && argcOrig != argc) { - argv[argc] = 0; + argv[argc] = 0; } } @@ -115,7 +115,7 @@ inline void checkIceVersion(Int version) // if(ICE_INT_VERSION != version) { - throw VersionMismatchException(__FILE__, __LINE__); + throw VersionMismatchException(__FILE__, __LINE__); } # else @@ -124,7 +124,7 @@ inline void checkIceVersion(Int version) // if(ICE_INT_VERSION / 100 != version / 100) { - throw VersionMismatchException(__FILE__, __LINE__); + throw VersionMismatchException(__FILE__, __LINE__); } // @@ -132,7 +132,7 @@ inline void checkIceVersion(Int version) // if(version % 100 > 50) { - throw VersionMismatchException(__FILE__, __LINE__); + throw VersionMismatchException(__FILE__, __LINE__); } // @@ -141,7 +141,7 @@ inline void checkIceVersion(Int version) // if(version % 100 > ICE_INT_VERSION % 100) { - throw VersionMismatchException(__FILE__, __LINE__); + throw VersionMismatchException(__FILE__, __LINE__); } # endif @@ -172,42 +172,42 @@ Ice::initialize(StringSeq& args, const InitializationData& initializationData, I CommunicatorPtr communicator; try { - // - // Make a dummy argc/argv. - // (We can't use argsToStringSeq() because that requires an already initialized argv.) - // - int argc = args.size(); - origArgc = argc; - argv = new char*[args.size() + 1]; - int i; - for(i = 0; i != argc; ++i) - { - argv[i] = new char[args[i].size() + 1]; + // + // Make a dummy argc/argv. + // (We can't use argsToStringSeq() because that requires an already initialized argv.) + // + int argc = args.size(); + origArgc = argc; + argv = new char*[args.size() + 1]; + int i; + for(i = 0; i != argc; ++i) + { + argv[i] = new char[args[i].size() + 1]; #if defined(_MSC_VER) && (_MSC_VER >= 1400) - strcpy_s(argv[i], args[i].size() + 1, args[i].c_str()); + strcpy_s(argv[i], args[i].size() + 1, args[i].c_str()); #else - strcpy(argv[i], args[i].c_str()); + strcpy(argv[i], args[i].c_str()); #endif - } - argv[argc] = 0; - - communicator = initialize(argc, argv, initializationData, version); - - args = argsToStringSeq(argc, argv); - - for(i = 0; i < origArgc; ++i) - { - delete[] argv[i]; - } - delete[] argv; + } + argv[argc] = 0; + + communicator = initialize(argc, argv, initializationData, version); + + args = argsToStringSeq(argc, argv); + + for(i = 0; i < origArgc; ++i) + { + delete[] argv[i]; + } + delete[] argv; } catch(...) { - for(int i = 0; i < origArgc; ++i) - { - delete[] argv[i]; - } - delete[] argv; + for(int i = 0; i < origArgc; ++i) + { + delete[] argv[i]; + } + delete[] argv; throw; } return communicator; @@ -249,7 +249,7 @@ Ice::initializeWithLogger(int& argc, char* argv[], const LoggerPtr& logger, Int CommunicatorPtr Ice::initializeWithPropertiesAndLogger(int& argc, char* argv[], const PropertiesPtr& properties, - const LoggerPtr& logger, Int version) + const LoggerPtr& logger, Int version) { InitializationData initData; initData.properties = properties; diff --git a/cpp/src/Ice/Instance.cpp b/cpp/src/Ice/Instance.cpp index 5548d792c9b..ecb2f466bd2 100644 --- a/cpp/src/Ice/Instance.cpp +++ b/cpp/src/Ice/Instance.cpp @@ -98,7 +98,7 @@ IceInternal::Instance::routerManager() const if(_state == StateDestroyed) { - throw CommunicatorDestroyedException(__FILE__, __LINE__); + throw CommunicatorDestroyedException(__FILE__, __LINE__); } return _routerManager; @@ -111,7 +111,7 @@ IceInternal::Instance::locatorManager() const if(_state == StateDestroyed) { - throw CommunicatorDestroyedException(__FILE__, __LINE__); + throw CommunicatorDestroyedException(__FILE__, __LINE__); } return _locatorManager; @@ -124,7 +124,7 @@ IceInternal::Instance::referenceFactory() const if(_state == StateDestroyed) { - throw CommunicatorDestroyedException(__FILE__, __LINE__); + throw CommunicatorDestroyedException(__FILE__, __LINE__); } return _referenceFactory; @@ -137,7 +137,7 @@ IceInternal::Instance::proxyFactory() const if(_state == StateDestroyed) { - throw CommunicatorDestroyedException(__FILE__, __LINE__); + throw CommunicatorDestroyedException(__FILE__, __LINE__); } return _proxyFactory; @@ -150,7 +150,7 @@ IceInternal::Instance::outgoingConnectionFactory() const if(_state == StateDestroyed) { - throw CommunicatorDestroyedException(__FILE__, __LINE__); + throw CommunicatorDestroyedException(__FILE__, __LINE__); } return _outgoingConnectionFactory; @@ -163,7 +163,7 @@ IceInternal::Instance::connectionMonitor() const if(_state == StateDestroyed) { - throw CommunicatorDestroyedException(__FILE__, __LINE__); + throw CommunicatorDestroyedException(__FILE__, __LINE__); } return _connectionMonitor; @@ -176,7 +176,7 @@ IceInternal::Instance::servantFactoryManager() const if(_state == StateDestroyed) { - throw CommunicatorDestroyedException(__FILE__, __LINE__); + throw CommunicatorDestroyedException(__FILE__, __LINE__); } return _servantFactoryManager; @@ -189,7 +189,7 @@ IceInternal::Instance::objectAdapterFactory() const if(_state == StateDestroyed) { - throw CommunicatorDestroyedException(__FILE__, __LINE__); + throw CommunicatorDestroyedException(__FILE__, __LINE__); } return _objectAdapterFactory; @@ -202,12 +202,12 @@ IceInternal::Instance::clientThreadPool() if(_state == StateDestroyed) { - throw CommunicatorDestroyedException(__FILE__, __LINE__); + throw CommunicatorDestroyedException(__FILE__, __LINE__); } if(!_clientThreadPool) // Lazy initialization. { - _clientThreadPool = new ThreadPool(this, "Ice.ThreadPool.Client", 0); + _clientThreadPool = new ThreadPool(this, "Ice.ThreadPool.Client", 0); } return _clientThreadPool; @@ -220,13 +220,13 @@ IceInternal::Instance::serverThreadPool() if(_state == StateDestroyed) { - throw CommunicatorDestroyedException(__FILE__, __LINE__); + throw CommunicatorDestroyedException(__FILE__, __LINE__); } if(!_serverThreadPool) // Lazy initialization. { - int timeout = _initData.properties->getPropertyAsInt("Ice.ServerIdleTime"); - _serverThreadPool = new ThreadPool(this, "Ice.ThreadPool.Server", timeout); + int timeout = _initData.properties->getPropertyAsInt("Ice.ServerIdleTime"); + _serverThreadPool = new ThreadPool(this, "Ice.ThreadPool.Server", timeout); } return _serverThreadPool; @@ -253,7 +253,7 @@ IceInternal::Instance::endpointFactoryManager() const if(_state == StateDestroyed) { - throw CommunicatorDestroyedException(__FILE__, __LINE__); + throw CommunicatorDestroyedException(__FILE__, __LINE__); } return _endpointFactoryManager; @@ -266,7 +266,7 @@ IceInternal::Instance::dynamicLibraryList() const if(_state == StateDestroyed) { - throw CommunicatorDestroyedException(__FILE__, __LINE__); + throw CommunicatorDestroyedException(__FILE__, __LINE__); } return _dynamicLibraryList; @@ -279,7 +279,7 @@ IceInternal::Instance::pluginManager() const if(_state == StateDestroyed) { - throw CommunicatorDestroyedException(__FILE__, __LINE__); + throw CommunicatorDestroyedException(__FILE__, __LINE__); } return _pluginManager; @@ -306,15 +306,15 @@ IceInternal::Instance::flushBatchRequests() ObjectAdapterFactoryPtr adapterFactory; { - IceUtil::RecMutex::Lock sync(*this); + IceUtil::RecMutex::Lock sync(*this); - if(_state == StateDestroyed) - { - throw CommunicatorDestroyedException(__FILE__, __LINE__); - } + if(_state == StateDestroyed) + { + throw CommunicatorDestroyedException(__FILE__, __LINE__); + } - connectionFactory = _outgoingConnectionFactory; - adapterFactory = _objectAdapterFactory; + connectionFactory = _outgoingConnectionFactory; + adapterFactory = _objectAdapterFactory; } connectionFactory->flushBatchRequests(); @@ -328,7 +328,7 @@ IceInternal::Instance::setDefaultContext(const Context& ctx) if(_state == StateDestroyed) { - throw CommunicatorDestroyedException(__FILE__, __LINE__); + throw CommunicatorDestroyedException(__FILE__, __LINE__); } _defaultContext = new SharedContext(ctx); @@ -341,7 +341,7 @@ IceInternal::Instance::getDefaultContext() const if(_state == StateDestroyed) { - throw CommunicatorDestroyedException(__FILE__, __LINE__); + throw CommunicatorDestroyedException(__FILE__, __LINE__); } return _defaultContext; @@ -409,15 +409,15 @@ IceInternal::Instance::stringToIdentity(const string& s) const if(_initData.stringConverter) { string tmpString; - _initData.stringConverter->fromUTF8(reinterpret_cast(ident.name.data()), - reinterpret_cast(ident.name.data() + ident.name.size()), - tmpString); - ident.name = tmpString; + _initData.stringConverter->fromUTF8(reinterpret_cast(ident.name.data()), + reinterpret_cast(ident.name.data() + ident.name.size()), + tmpString); + ident.name = tmpString; - _initData.stringConverter->fromUTF8(reinterpret_cast(ident.category.data()), - reinterpret_cast(ident.category.data() + ident.category.size()), - tmpString); - ident.category = tmpString; + _initData.stringConverter->fromUTF8(reinterpret_cast(ident.category.data()), + reinterpret_cast(ident.category.data() + ident.category.size()), + tmpString); + ident.category = tmpString; } return ident; @@ -432,12 +432,12 @@ IceInternal::Instance::identityToString(const Identity& ident) const { UTF8BufferI buffer; Byte* last = _initData.stringConverter->toUTF8(ident.name.data(), ident.name.data() + ident.name.size(), - buffer); + buffer); name = string(reinterpret_cast(buffer.getBuffer()), last - buffer.getBuffer()); - buffer.reset(); + buffer.reset(); last = _initData.stringConverter->toUTF8(ident.category.data(), ident.category.data() + ident.category.size(), - buffer); + buffer); category = string(reinterpret_cast(buffer.getBuffer()), last - buffer.getBuffer()); } @@ -464,189 +464,189 @@ IceInternal::Instance::Instance(const CommunicatorPtr& communicator, const Initi { try { - __setNoDelete(true); - - IceUtil::StaticMutex::Lock sync(staticMutex); - instanceCount++; - - if(!_initData.properties) - { - _initData.properties = createProperties(); - } - - if(!oneOffDone) - { - // - // StdOut and StdErr redirection - // - string stdOutFilename = _initData.properties->getProperty("Ice.StdOut"); - string stdErrFilename = _initData.properties->getProperty("Ice.StdErr"); - - if(stdOutFilename != "") - { - FILE* file = freopen(stdOutFilename.c_str(), "a", stdout); - if(file == 0) - { - FileException ex(__FILE__, __LINE__); - ex.path = stdOutFilename; - ex.error = getSystemErrno(); - throw ex; - } - } - - if(stdErrFilename != "") - { - FILE* file = freopen(stdErrFilename.c_str(), "a", stderr); - if(file == 0) - { - FileException ex(__FILE__, __LINE__); - ex.path = stdErrFilename; - ex.error = getSystemErrno(); - throw ex; - } - } - - if(_initData.properties->getPropertyAsInt("Ice.NullHandleAbort") > 0) - { - IceUtil::nullHandleAbort = true; - } - + __setNoDelete(true); + + IceUtil::StaticMutex::Lock sync(staticMutex); + instanceCount++; + + if(!_initData.properties) + { + _initData.properties = createProperties(); + } + + if(!oneOffDone) + { + // + // StdOut and StdErr redirection + // + string stdOutFilename = _initData.properties->getProperty("Ice.StdOut"); + string stdErrFilename = _initData.properties->getProperty("Ice.StdErr"); + + if(stdOutFilename != "") + { + FILE* file = freopen(stdOutFilename.c_str(), "a", stdout); + if(file == 0) + { + FileException ex(__FILE__, __LINE__); + ex.path = stdOutFilename; + ex.error = getSystemErrno(); + throw ex; + } + } + + if(stdErrFilename != "") + { + FILE* file = freopen(stdErrFilename.c_str(), "a", stderr); + if(file == 0) + { + FileException ex(__FILE__, __LINE__); + ex.path = stdErrFilename; + ex.error = getSystemErrno(); + throw ex; + } + } + + if(_initData.properties->getPropertyAsInt("Ice.NullHandleAbort") > 0) + { + IceUtil::nullHandleAbort = true; + } + #ifndef _WIN32 - string newUser = _initData.properties->getProperty("Ice.ChangeUser"); - if(!newUser.empty()) - { - struct passwd* pw = getpwnam(newUser.c_str()); - if(!pw) - { - SyscallException ex(__FILE__, __LINE__); - ex.error = getSystemErrno(); - throw ex; - } - - if(setgid(pw->pw_gid) == -1) - { - SyscallException ex(__FILE__, __LINE__); - ex.error = getSystemErrno(); - throw ex; - } - - if(setuid(pw->pw_uid) == -1) - { - SyscallException ex(__FILE__, __LINE__); - ex.error = getSystemErrno(); - throw ex; - } - } + string newUser = _initData.properties->getProperty("Ice.ChangeUser"); + if(!newUser.empty()) + { + struct passwd* pw = getpwnam(newUser.c_str()); + if(!pw) + { + SyscallException ex(__FILE__, __LINE__); + ex.error = getSystemErrno(); + throw ex; + } + + if(setgid(pw->pw_gid) == -1) + { + SyscallException ex(__FILE__, __LINE__); + ex.error = getSystemErrno(); + throw ex; + } + + if(setuid(pw->pw_uid) == -1) + { + SyscallException ex(__FILE__, __LINE__); + ex.error = getSystemErrno(); + throw ex; + } + } #endif - oneOffDone = true; - } - - if(instanceCount == 1) - { - + oneOffDone = true; + } + + if(instanceCount == 1) + { + #ifdef _WIN32 - WORD version = MAKEWORD(1, 1); - WSADATA data; - if(WSAStartup(version, &data) != 0) - { - SocketException ex(__FILE__, __LINE__); - ex.error = getSocketErrno(); - throw ex; - } + WORD version = MAKEWORD(1, 1); + WSADATA data; + if(WSAStartup(version, &data) != 0) + { + SocketException ex(__FILE__, __LINE__); + ex.error = getSocketErrno(); + throw ex; + } #endif - + #ifndef _WIN32 - struct sigaction action; - action.sa_handler = SIG_IGN; - sigemptyset(&action.sa_mask); - action.sa_flags = 0; - sigaction(SIGPIPE, &action, 0); - - if(_initData.properties->getPropertyAsInt("Ice.UseSyslog") > 0) - { - identForOpenlog = _initData.properties->getProperty("Ice.ProgramName"); - if(identForOpenlog.empty()) - { - identForOpenlog = ""; - } - openlog(identForOpenlog.c_str(), LOG_PID, LOG_USER); - } + struct sigaction action; + action.sa_handler = SIG_IGN; + sigemptyset(&action.sa_mask); + action.sa_flags = 0; + sigaction(SIGPIPE, &action, 0); + + if(_initData.properties->getPropertyAsInt("Ice.UseSyslog") > 0) + { + identForOpenlog = _initData.properties->getProperty("Ice.ProgramName"); + if(identForOpenlog.empty()) + { + identForOpenlog = ""; + } + openlog(identForOpenlog.c_str(), LOG_PID, LOG_USER); + } #endif - } - - sync.release(); - + } + + sync.release(); + - if(!_initData.logger) - { + if(!_initData.logger) + { #ifdef _WIN32 - if(_initData.properties->getPropertyAsInt("Ice.UseEventLog") > 0) - { - _initData.logger = new EventLoggerI(_initData.properties->getProperty("Ice.ProgramName")); - } + if(_initData.properties->getPropertyAsInt("Ice.UseEventLog") > 0) + { + _initData.logger = new EventLoggerI(_initData.properties->getProperty("Ice.ProgramName")); + } #else - if(_initData.properties->getPropertyAsInt("Ice.UseSyslog") > 0) - { - _initData.logger = new SysLoggerI; - } + if(_initData.properties->getPropertyAsInt("Ice.UseSyslog") > 0) + { + _initData.logger = new SysLoggerI; + } #endif - else - { - _initData.logger = getProcessLogger(); - } - } - - const_cast(_traceLevels) = new TraceLevels(_initData.properties); - - const_cast(_defaultsAndOverrides) = new DefaultsAndOverrides(_initData.properties); - - { - static const int defaultMessageSizeMax = 1024; - Int num = _initData.properties->getPropertyAsIntWithDefault("Ice.MessageSizeMax", defaultMessageSizeMax); - if(num < 1) - { - const_cast(_messageSizeMax) = defaultMessageSizeMax * 1024; // Ignore stupid values. - } - else if(static_cast(num) > (size_t)(0x7fffffff / 1024)) - { - const_cast(_messageSizeMax) = static_cast(0x7fffffff); - } - else - { - // Property is in kilobytes, _messageSizeMax in bytes. - const_cast(_messageSizeMax) = static_cast(num) * 1024; - } - } - - // - // Client ACM enabled by default. Server ACM disabled by default. - // - const_cast(_clientACM) = _initData.properties->getPropertyAsIntWithDefault("Ice.ACM.Client", 60); - const_cast(_serverACM) = _initData.properties->getPropertyAsInt("Ice.ACM.Server"); - - const_cast(_threadPerConnection) = _initData.properties->getPropertyAsInt("Ice.ThreadPerConnection") > 0; - - { - Int stackSize = _initData.properties->getPropertyAsInt("Ice.ThreadPerConnection.StackSize"); - if(stackSize < 0) - { - stackSize = 0; - } - const_cast(_threadPerConnectionStackSize) = static_cast(stackSize); - } - - const_cast(_implicitContext) = - ImplicitContextI::create(_initData.properties->getProperty("Ice.ImplicitContext")); - - _routerManager = new RouterManager; - - _locatorManager = new LocatorManager; - - _referenceFactory = new ReferenceFactory(this, communicator); - - _proxyFactory = new ProxyFactory(this); - - _endpointFactoryManager = new EndpointFactoryManager(this); + else + { + _initData.logger = getProcessLogger(); + } + } + + const_cast(_traceLevels) = new TraceLevels(_initData.properties); + + const_cast(_defaultsAndOverrides) = new DefaultsAndOverrides(_initData.properties); + + { + static const int defaultMessageSizeMax = 1024; + Int num = _initData.properties->getPropertyAsIntWithDefault("Ice.MessageSizeMax", defaultMessageSizeMax); + if(num < 1) + { + const_cast(_messageSizeMax) = defaultMessageSizeMax * 1024; // Ignore stupid values. + } + else if(static_cast(num) > (size_t)(0x7fffffff / 1024)) + { + const_cast(_messageSizeMax) = static_cast(0x7fffffff); + } + else + { + // Property is in kilobytes, _messageSizeMax in bytes. + const_cast(_messageSizeMax) = static_cast(num) * 1024; + } + } + + // + // Client ACM enabled by default. Server ACM disabled by default. + // + const_cast(_clientACM) = _initData.properties->getPropertyAsIntWithDefault("Ice.ACM.Client", 60); + const_cast(_serverACM) = _initData.properties->getPropertyAsInt("Ice.ACM.Server"); + + const_cast(_threadPerConnection) = _initData.properties->getPropertyAsInt("Ice.ThreadPerConnection") > 0; + + { + Int stackSize = _initData.properties->getPropertyAsInt("Ice.ThreadPerConnection.StackSize"); + if(stackSize < 0) + { + stackSize = 0; + } + const_cast(_threadPerConnectionStackSize) = static_cast(stackSize); + } + + const_cast(_implicitContext) = + ImplicitContextI::create(_initData.properties->getProperty("Ice.ImplicitContext")); + + _routerManager = new RouterManager; + + _locatorManager = new LocatorManager; + + _referenceFactory = new ReferenceFactory(this, communicator); + + _proxyFactory = new ProxyFactory(this); + + _endpointFactoryManager = new EndpointFactoryManager(this); EndpointFactoryPtr tcpEndpointFactory = new TcpEndpointFactory(this); _endpointFactoryManager->add(tcpEndpointFactory); EndpointFactoryPtr udpEndpointFactory = new UdpEndpointFactory(this); @@ -656,28 +656,28 @@ IceInternal::Instance::Instance(const CommunicatorPtr& communicator, const Initi _pluginManager = new PluginManagerI(communicator, _dynamicLibraryList); - _outgoingConnectionFactory = new OutgoingConnectionFactory(this); + _outgoingConnectionFactory = new OutgoingConnectionFactory(this); - _servantFactoryManager = new ObjectFactoryManager(); + _servantFactoryManager = new ObjectFactoryManager(); - _objectAdapterFactory = new ObjectAdapterFactory(this, communicator); + _objectAdapterFactory = new ObjectAdapterFactory(this, communicator); - if(_initData.wstringConverter == 0) - { - _initData.wstringConverter = new UnicodeWstringConverter(); - } + if(_initData.wstringConverter == 0) + { + _initData.wstringConverter = new UnicodeWstringConverter(); + } - __setNoDelete(false); + __setNoDelete(false); } catch(...) { - { - IceUtil::StaticMutex::Lock sync(staticMutex); - --instanceCount; - } - destroy(); - __setNoDelete(false); - throw; + { + IceUtil::StaticMutex::Lock sync(staticMutex); + --instanceCount; + } + destroy(); + __setNoDelete(false); + throw; } } @@ -703,21 +703,21 @@ IceInternal::Instance::~Instance() if(--instanceCount == 0) { #ifdef _WIN32 - WSACleanup(); + WSACleanup(); #endif - + #ifndef _WIN32 - struct sigaction action; - action.sa_handler = SIG_DFL; - sigemptyset(&action.sa_mask); - action.sa_flags = 0; - sigaction(SIGPIPE, &action, 0); - - if(!identForOpenlog.empty()) - { - closelog(); - identForOpenlog.clear(); - } + struct sigaction action; + action.sa_handler = SIG_DFL; + sigemptyset(&action.sa_mask); + action.sa_flags = 0; + sigaction(SIGPIPE, &action, 0); + + if(!identForOpenlog.empty()) + { + closelog(); + identForOpenlog.clear(); + } #endif } } @@ -755,24 +755,24 @@ IceInternal::Instance::finishSetup(int& argc, char* argv[]) bool printProcessId = false; if(!printProcessIdDone && _initData.properties->getPropertyAsInt("Ice.PrintProcessId") > 0) { - // - // Safe double-check locking (no dependent variable!) - // - IceUtil::StaticMutex::Lock sync(staticMutex); - printProcessId = !printProcessIdDone; - - // - // We anticipate: we want to print it once, and we don't care when. - // - printProcessIdDone = true; + // + // Safe double-check locking (no dependent variable!) + // + IceUtil::StaticMutex::Lock sync(staticMutex); + printProcessId = !printProcessIdDone; + + // + // We anticipate: we want to print it once, and we don't care when. + // + printProcessIdDone = true; } if(printProcessId) { #ifdef _MSC_VER - cout << _getpid() << endl; + cout << _getpid() << endl; #else - cout << getpid() << endl; + cout << getpid() << endl; #endif } @@ -782,20 +782,20 @@ IceInternal::Instance::finishSetup(int& argc, char* argv[]) Int interval = 0; if(_clientACM > 0 && _serverACM > 0) { - interval = min(_clientACM, _serverACM); + interval = min(_clientACM, _serverACM); } else if(_clientACM > 0) { - interval = _clientACM; + interval = _clientACM; } else if(_serverACM > 0) { - interval = _serverACM; + interval = _serverACM; } interval = _initData.properties->getPropertyAsIntWithDefault("Ice.MonitorConnections", interval); if(interval > 0) { - _connectionMonitor = new ConnectionMonitor(this, interval); + _connectionMonitor = new ConnectionMonitor(this, interval); } // @@ -808,29 +808,29 @@ bool IceInternal::Instance::destroy() { { - IceUtil::RecMutex::Lock sync(*this); - - // - // If the _state is not StateActive then the instance is - // either being destroyed, or has already been destroyed. - // - if(_state != StateActive) - { - return false; - } + IceUtil::RecMutex::Lock sync(*this); + + // + // If the _state is not StateActive then the instance is + // either being destroyed, or has already been destroyed. + // + if(_state != StateActive) + { + return false; + } - // - // We cannot set state to StateDestroyed otherwise instance - // methods called during the destroy process (such as - // outgoingConnectionFactory() from - // ObjectAdapterI::deactivate() will cause an exception. - // - _state = StateDestroyInProgress; + // + // We cannot set state to StateDestroyed otherwise instance + // methods called during the destroy process (such as + // outgoingConnectionFactory() from + // ObjectAdapterI::deactivate() will cause an exception. + // + _state = StateDestroyInProgress; } if(_objectAdapterFactory) { - _objectAdapterFactory->shutdown(); + _objectAdapterFactory->shutdown(); } if(_outgoingConnectionFactory) @@ -852,74 +852,74 @@ IceInternal::Instance::destroy() ThreadPoolPtr clientThreadPool; { - IceUtil::RecMutex::Lock sync(*this); - - _objectAdapterFactory = 0; - _outgoingConnectionFactory = 0; - - if(_connectionMonitor) - { - _connectionMonitor->destroy(); - _connectionMonitor = 0; - } - - if(_serverThreadPool) - { - _serverThreadPool->destroy(); - std::swap(_serverThreadPool, serverThreadPool); - } - - if(_clientThreadPool) - { - _clientThreadPool->destroy(); - std::swap(_clientThreadPool, clientThreadPool); - } - - if(_servantFactoryManager) - { - _servantFactoryManager->destroy(); - _servantFactoryManager = 0; - } - - if(_referenceFactory) - { - _referenceFactory->destroy(); - _referenceFactory = 0; - } - - // No destroy function defined. - // _proxyFactory->destroy(); - _proxyFactory = 0; - - if(_routerManager) - { - _routerManager->destroy(); - _routerManager = 0; - } - - if(_locatorManager) - { - _locatorManager->destroy(); - _locatorManager = 0; - } - - if(_endpointFactoryManager) - { - _endpointFactoryManager->destroy(); - _endpointFactoryManager = 0; - } - - if(_pluginManager) - { - _pluginManager->destroy(); - _pluginManager = 0; - } - - // No destroy function defined. - // _dynamicLibraryList->destroy(); - _dynamicLibraryList = 0; - - _state = StateDestroyed; + IceUtil::RecMutex::Lock sync(*this); + + _objectAdapterFactory = 0; + _outgoingConnectionFactory = 0; + + if(_connectionMonitor) + { + _connectionMonitor->destroy(); + _connectionMonitor = 0; + } + + if(_serverThreadPool) + { + _serverThreadPool->destroy(); + std::swap(_serverThreadPool, serverThreadPool); + } + + if(_clientThreadPool) + { + _clientThreadPool->destroy(); + std::swap(_clientThreadPool, clientThreadPool); + } + + if(_servantFactoryManager) + { + _servantFactoryManager->destroy(); + _servantFactoryManager = 0; + } + + if(_referenceFactory) + { + _referenceFactory->destroy(); + _referenceFactory = 0; + } + + // No destroy function defined. + // _proxyFactory->destroy(); + _proxyFactory = 0; + + if(_routerManager) + { + _routerManager->destroy(); + _routerManager = 0; + } + + if(_locatorManager) + { + _locatorManager->destroy(); + _locatorManager = 0; + } + + if(_endpointFactoryManager) + { + _endpointFactoryManager->destroy(); + _endpointFactoryManager = 0; + } + + if(_pluginManager) + { + _pluginManager->destroy(); + _pluginManager = 0; + } + + // No destroy function defined. + // _dynamicLibraryList->destroy(); + _dynamicLibraryList = 0; + + _state = StateDestroyed; } // @@ -927,11 +927,11 @@ IceInternal::Instance::destroy() // if(clientThreadPool) { - clientThreadPool->joinWithAllThreads(); + clientThreadPool->joinWithAllThreads(); } if(serverThreadPool) { - serverThreadPool->joinWithAllThreads(); + serverThreadPool->joinWithAllThreads(); } return true; } @@ -956,7 +956,7 @@ IceInternal::UTF8BufferI::getMoreBytes(size_t howMany, Byte* firstUnused) } else { - assert(firstUnused != 0); + assert(firstUnused != 0); _offset = firstUnused - _buffer; _buffer = (Byte*)realloc(_buffer, _offset + howMany); } diff --git a/cpp/src/Ice/Instance.h b/cpp/src/Ice/Instance.h index 3a4245ff2b7..27f875fc181 100644 --- a/cpp/src/Ice/Instance.h +++ b/cpp/src/Ice/Instance.h @@ -81,7 +81,7 @@ public: const Ice::ImplicitContextIPtr& getImplicitContext() const { - return _implicitContext; + return _implicitContext; } private: @@ -94,9 +94,9 @@ private: enum State { - StateActive, - StateDestroyInProgress, - StateDestroyed + StateActive, + StateDestroyInProgress, + StateDestroyed }; State _state; Ice::InitializationData _initData; diff --git a/cpp/src/Ice/LocatorInfo.cpp b/cpp/src/Ice/LocatorInfo.cpp index 146126f95ab..15e27d67d03 100644 --- a/cpp/src/Ice/LocatorInfo.cpp +++ b/cpp/src/Ice/LocatorInfo.cpp @@ -54,7 +54,7 @@ IceInternal::LocatorManager::get(const LocatorPrx& loc) { if(!loc) { - return 0; + return 0; } LocatorPrx locator = LocatorPrx::uncheckedCast(loc->ice_locator(0)); // The locator can't be located. @@ -69,39 +69,39 @@ IceInternal::LocatorManager::get(const LocatorPrx& loc) if(_tableHint != _table.end()) { - if(_tableHint->first == locator) - { - p = _tableHint; - } + if(_tableHint->first == locator) + { + p = _tableHint; + } } if(p == _table.end()) { - p = _table.find(locator); + p = _table.find(locator); } if(p == _table.end()) { - // - // Rely on locator identity for the adapter table. We want to - // have only one table per locator (not one per locator - // proxy). - // - map::iterator t = _locatorTables.find(locator->ice_getIdentity()); - if(t == _locatorTables.end()) - { - t = _locatorTables.insert(_locatorTables.begin(), - pair(locator->ice_getIdentity(), - new LocatorTable())); - } - - _tableHint = _table.insert(_tableHint, - pair(locator, - new LocatorInfo(locator, t->second))); + // + // Rely on locator identity for the adapter table. We want to + // have only one table per locator (not one per locator + // proxy). + // + map::iterator t = _locatorTables.find(locator->ice_getIdentity()); + if(t == _locatorTables.end()) + { + t = _locatorTables.insert(_locatorTables.begin(), + pair(locator->ice_getIdentity(), + new LocatorTable())); + } + + _tableHint = _table.insert(_tableHint, + pair(locator, + new LocatorInfo(locator, t->second))); } else { - _tableHint = p; + _tableHint = p; } return _tableHint->second; @@ -125,7 +125,7 @@ IceInternal::LocatorTable::getAdapterEndpoints(const string& adapter, int ttl, v { if(ttl == 0) // No locator cache. { - return false; + return false; } IceUtil::Mutex::Lock sync(*this); @@ -134,8 +134,8 @@ IceInternal::LocatorTable::getAdapterEndpoints(const string& adapter, int ttl, v if(p != _adapterEndpointsMap.end() && checkTTL(p->second.first, ttl)) { - endpoints = p->second.second; - return true; + endpoints = p->second.second; + return true; } return false; } @@ -149,11 +149,11 @@ IceInternal::LocatorTable::addAdapterEndpoints(const string& adapter, const vect if(p != _adapterEndpointsMap.end()) { - p->second = make_pair(IceUtil::Time::now(), endpoints); + p->second = make_pair(IceUtil::Time::now(), endpoints); } else { - _adapterEndpointsMap.insert(make_pair(adapter, make_pair(IceUtil::Time::now(), endpoints))); + _adapterEndpointsMap.insert(make_pair(adapter, make_pair(IceUtil::Time::now(), endpoints))); } } @@ -165,7 +165,7 @@ IceInternal::LocatorTable::removeAdapterEndpoints(const string& adapter) map > >::iterator p = _adapterEndpointsMap.find(adapter); if(p == _adapterEndpointsMap.end()) { - return vector(); + return vector(); } vector endpoints = p->second.second; @@ -180,7 +180,7 @@ IceInternal::LocatorTable::getProxy(const Identity& id, int ttl, ObjectPrx& prox { if(ttl == 0) // No locator cache { - return false; + return false; } IceUtil::Mutex::Lock sync(*this); @@ -189,8 +189,8 @@ IceInternal::LocatorTable::getProxy(const Identity& id, int ttl, ObjectPrx& prox if(p != _objectMap.end() && checkTTL(p->second.first, ttl)) { - proxy = p->second.second; - return true; + proxy = p->second.second; + return true; } return false; } @@ -204,11 +204,11 @@ IceInternal::LocatorTable::addProxy(const Identity& id, const ObjectPrx& proxy) if(p != _objectMap.end()) { - p->second = make_pair(IceUtil::Time::now(), proxy); + p->second = make_pair(IceUtil::Time::now(), proxy); } else { - _objectMap.insert(make_pair(id, make_pair(IceUtil::Time::now(), proxy))); + _objectMap.insert(make_pair(id, make_pair(IceUtil::Time::now(), proxy))); } } @@ -220,7 +220,7 @@ IceInternal::LocatorTable::removeProxy(const Identity& id) map >::iterator p = _objectMap.find(id); if(p == _objectMap.end()) { - return 0; + return 0; } ObjectPrx proxy = p->second.second; @@ -234,11 +234,11 @@ IceInternal::LocatorTable::checkTTL(const IceUtil::Time& time, int ttl) const assert(ttl != 0); if (ttl < 0) // TTL = infinite { - return true; + return true; } else { - return IceUtil::Time::now() - time <= IceUtil::Time::seconds(ttl); + return IceUtil::Time::now() - time <= IceUtil::Time::seconds(ttl); } } @@ -293,12 +293,12 @@ IceInternal::LocatorInfo::getLocatorRegistry() if(!_locatorRegistry) // Lazy initialization. { - _locatorRegistry = _locator->getRegistry(); + _locatorRegistry = _locator->getRegistry(); - // - // The locator registry can't be located. - // - _locatorRegistry = LocatorRegistryPrx::uncheckedCast(_locatorRegistry->ice_locator(0)); + // + // The locator registry can't be located. + // + _locatorRegistry = LocatorRegistryPrx::uncheckedCast(_locatorRegistry->ice_locator(0)); } return _locatorRegistry; @@ -312,156 +312,156 @@ IceInternal::LocatorInfo::getEndpoints(const IndirectReferencePtr& ref, int ttl, cached = true; try { - if(!ref->getAdapterId().empty()) - { - if(!_table->getAdapterEndpoints(ref->getAdapterId(), ttl, endpoints)) - { - cached = false; - - if(ref->getInstance()->traceLevels()->location >= 1) - { - Trace out(ref->getInstance()->initializationData().logger, - ref->getInstance()->traceLevels()->locationCat); - out << "searching for adapter by id" << "\n"; - out << "adapter = " << ref->getAdapterId(); - } - - object = _locator->findAdapterById(ref->getAdapterId()); - if(object) - { - endpoints = object->__reference()->getEndpoints(); - _table->addAdapterEndpoints(ref->getAdapterId(), endpoints); - } - } - } - else - { - bool objectCached = true; - if(!_table->getProxy(ref->getIdentity(), ttl, object)) - { - if(ref->getInstance()->traceLevels()->location >= 1) - { - Trace out(ref->getInstance()->initializationData().logger, - ref->getInstance()->traceLevels()->locationCat); - out << "searching for object by id" << "\n"; - out << "object = " << ref->getInstance()->identityToString(ref->getIdentity()); - } - - objectCached = false; - object = _locator->findObjectById(ref->getIdentity()); - } - - bool endpointsCached = true; - if(object) - { - DirectReferencePtr odr = DirectReferencePtr::dynamicCast(object->__reference()); - if(odr) - { - endpointsCached = false; - endpoints = odr->getEndpoints(); - } - else - { - IndirectReferencePtr oir = IndirectReferencePtr::dynamicCast(object->__reference()); - assert(oir); - if(!oir->getAdapterId().empty()) - { - endpoints = getEndpoints(oir, ttl, endpointsCached); - } - } - } - - if(!objectCached && !endpoints.empty()) - { - _table->addProxy(ref->getIdentity(), object); - } - - cached = objectCached || endpointsCached; - } + if(!ref->getAdapterId().empty()) + { + if(!_table->getAdapterEndpoints(ref->getAdapterId(), ttl, endpoints)) + { + cached = false; + + if(ref->getInstance()->traceLevels()->location >= 1) + { + Trace out(ref->getInstance()->initializationData().logger, + ref->getInstance()->traceLevels()->locationCat); + out << "searching for adapter by id" << "\n"; + out << "adapter = " << ref->getAdapterId(); + } + + object = _locator->findAdapterById(ref->getAdapterId()); + if(object) + { + endpoints = object->__reference()->getEndpoints(); + _table->addAdapterEndpoints(ref->getAdapterId(), endpoints); + } + } + } + else + { + bool objectCached = true; + if(!_table->getProxy(ref->getIdentity(), ttl, object)) + { + if(ref->getInstance()->traceLevels()->location >= 1) + { + Trace out(ref->getInstance()->initializationData().logger, + ref->getInstance()->traceLevels()->locationCat); + out << "searching for object by id" << "\n"; + out << "object = " << ref->getInstance()->identityToString(ref->getIdentity()); + } + + objectCached = false; + object = _locator->findObjectById(ref->getIdentity()); + } + + bool endpointsCached = true; + if(object) + { + DirectReferencePtr odr = DirectReferencePtr::dynamicCast(object->__reference()); + if(odr) + { + endpointsCached = false; + endpoints = odr->getEndpoints(); + } + else + { + IndirectReferencePtr oir = IndirectReferencePtr::dynamicCast(object->__reference()); + assert(oir); + if(!oir->getAdapterId().empty()) + { + endpoints = getEndpoints(oir, ttl, endpointsCached); + } + } + } + + if(!objectCached && !endpoints.empty()) + { + _table->addProxy(ref->getIdentity(), object); + } + + cached = objectCached || endpointsCached; + } } catch(const AdapterNotFoundException&) { - if(ref->getInstance()->traceLevels()->location >= 1) - { - Trace out(ref->getInstance()->initializationData().logger, - ref->getInstance()->traceLevels()->locationCat); - out << "adapter not found" << "\n"; - out << "adapter = " << ref->getAdapterId(); + if(ref->getInstance()->traceLevels()->location >= 1) + { + Trace out(ref->getInstance()->initializationData().logger, + ref->getInstance()->traceLevels()->locationCat); + out << "adapter not found" << "\n"; + out << "adapter = " << ref->getAdapterId(); } - NotRegisteredException ex(__FILE__, __LINE__); - ex.kindOfObject = "object adapter"; - ex.id = ref->getAdapterId(); - throw ex; + NotRegisteredException ex(__FILE__, __LINE__); + ex.kindOfObject = "object adapter"; + ex.id = ref->getAdapterId(); + throw ex; } catch(const ObjectNotFoundException&) { - if(ref->getInstance()->traceLevels()->location >= 1) - { - Trace out(ref->getInstance()->initializationData().logger, - ref->getInstance()->traceLevels()->locationCat); - out << "object not found" << "\n"; - out << "object = " << ref->getInstance()->identityToString(ref->getIdentity()); + if(ref->getInstance()->traceLevels()->location >= 1) + { + Trace out(ref->getInstance()->initializationData().logger, + ref->getInstance()->traceLevels()->locationCat); + out << "object not found" << "\n"; + out << "object = " << ref->getInstance()->identityToString(ref->getIdentity()); } - NotRegisteredException ex(__FILE__, __LINE__); - ex.kindOfObject = "object"; - ex.id = ref->getInstance()->identityToString(ref->getIdentity()); - throw ex; + NotRegisteredException ex(__FILE__, __LINE__); + ex.kindOfObject = "object"; + ex.id = ref->getInstance()->identityToString(ref->getIdentity()); + throw ex; } catch(const NotRegisteredException&) { - throw; + throw; } catch(const LocalException& ex) { - if(ref->getInstance()->traceLevels()->location >= 1) - { - Trace out(ref->getInstance()->initializationData().logger, - ref->getInstance()->traceLevels()->locationCat); - out << "couldn't contact the locator to retrieve adapter endpoints\n"; - if(ref->getAdapterId().empty()) - { - out << "object = " << ref->getInstance()->identityToString(ref->getIdentity()) << "\n"; - } - else - { - out << "adapter = " << ref->getAdapterId() << "\n"; - } - out << "reason = " << ex; - } - throw; + if(ref->getInstance()->traceLevels()->location >= 1) + { + Trace out(ref->getInstance()->initializationData().logger, + ref->getInstance()->traceLevels()->locationCat); + out << "couldn't contact the locator to retrieve adapter endpoints\n"; + if(ref->getAdapterId().empty()) + { + out << "object = " << ref->getInstance()->identityToString(ref->getIdentity()) << "\n"; + } + else + { + out << "adapter = " << ref->getAdapterId() << "\n"; + } + out << "reason = " << ex; + } + throw; } if(ref->getInstance()->traceLevels()->location >= 1) { if(!endpoints.empty()) - { - if(cached) - { - trace("found endpoints in locator table", ref, endpoints); - } - else - { - trace("retrieved endpoints from locator, adding to locator table", ref, endpoints); - } - } - else - { - Trace out(ref->getInstance()->initializationData().logger, ref->getInstance()->traceLevels()->locationCat); - out << "no endpoints configured for "; - if(ref->getAdapterId().empty()) - { - out << "object\n"; - out << "object = " << ref->getInstance()->identityToString(ref->getIdentity()); - } - else - { - out << "adapter\n"; - out << "adapter = " << ref->getAdapterId(); - } - } + { + if(cached) + { + trace("found endpoints in locator table", ref, endpoints); + } + else + { + trace("retrieved endpoints from locator, adding to locator table", ref, endpoints); + } + } + else + { + Trace out(ref->getInstance()->initializationData().logger, ref->getInstance()->traceLevels()->locationCat); + out << "no endpoints configured for "; + if(ref->getAdapterId().empty()) + { + out << "object\n"; + out << "object = " << ref->getInstance()->identityToString(ref->getIdentity()); + } + else + { + out << "adapter\n"; + out << "adapter = " << ref->getAdapterId(); + } + } } return endpoints; @@ -472,25 +472,25 @@ IceInternal::LocatorInfo::clearObjectCache(const IndirectReferencePtr& ref) { if(ref->getAdapterId().empty()) { - ObjectPrx object = _table->removeProxy(ref->getIdentity()); - if(object) - { - IndirectReferencePtr oir = IndirectReferencePtr::dynamicCast(object->__reference()); - if(oir) - { - if(!oir->getAdapterId().empty()) - { - clearCache(oir); - } - } - else - { - if(ref->getInstance()->traceLevels()->location >= 2) - { - trace("removed endpoints from locator table", ref, object->__reference()->getEndpoints()); - } - } - } + ObjectPrx object = _table->removeProxy(ref->getIdentity()); + if(object) + { + IndirectReferencePtr oir = IndirectReferencePtr::dynamicCast(object->__reference()); + if(oir) + { + if(!oir->getAdapterId().empty()) + { + clearCache(oir); + } + } + else + { + if(ref->getInstance()->traceLevels()->location >= 2) + { + trace("removed endpoints from locator table", ref, object->__reference()->getEndpoints()); + } + } + } } } @@ -499,56 +499,56 @@ IceInternal::LocatorInfo::clearCache(const IndirectReferencePtr& ref) { if(!ref->getAdapterId().empty()) { - vector endpoints = _table->removeAdapterEndpoints(ref->getAdapterId()); + vector endpoints = _table->removeAdapterEndpoints(ref->getAdapterId()); - if(!endpoints.empty() && ref->getInstance()->traceLevels()->location >= 2) - { - trace("removed endpoints from locator table", ref, endpoints); - } + if(!endpoints.empty() && ref->getInstance()->traceLevels()->location >= 2) + { + trace("removed endpoints from locator table", ref, endpoints); + } } else { - ObjectPrx object = _table->removeProxy(ref->getIdentity()); - if(object) - { - IndirectReferencePtr oir = IndirectReferencePtr::dynamicCast(object->__reference()); - if(oir) - { - if(!oir->getAdapterId().empty()) - { - clearCache(oir); - } - } - else - { - if(ref->getInstance()->traceLevels()->location >= 2) - { - trace("removed endpoints from locator table", ref, object->__reference()->getEndpoints()); - } - } - } + ObjectPrx object = _table->removeProxy(ref->getIdentity()); + if(object) + { + IndirectReferencePtr oir = IndirectReferencePtr::dynamicCast(object->__reference()); + if(oir) + { + if(!oir->getAdapterId().empty()) + { + clearCache(oir); + } + } + else + { + if(ref->getInstance()->traceLevels()->location >= 2) + { + trace("removed endpoints from locator table", ref, object->__reference()->getEndpoints()); + } + } + } } } void IceInternal::LocatorInfo::trace(const string& msg, - const IndirectReferencePtr& ref, - const vector& endpoints) + const IndirectReferencePtr& ref, + const vector& endpoints) { Trace out(ref->getInstance()->initializationData().logger, ref->getInstance()->traceLevels()->locationCat); out << msg << '\n'; if(!ref->getAdapterId().empty()) { - out << "adapter = " << ref->getAdapterId() << '\n'; + out << "adapter = " << ref->getAdapterId() << '\n'; } else { - out << "object = " << ref->getInstance()->identityToString(ref->getIdentity()) << '\n'; + out << "object = " << ref->getInstance()->identityToString(ref->getIdentity()) << '\n'; } const char* sep = endpoints.size() > 1 ? ":" : ""; ostringstream o; transform(endpoints.begin(), endpoints.end(), ostream_iterator(o, sep), - Ice::constMemFun(&Endpoint::toString)); + Ice::constMemFun(&Endpoint::toString)); out << "endpoints = " << o.str(); } diff --git a/cpp/src/Ice/LoggerI.cpp b/cpp/src/Ice/LoggerI.cpp index d347e221d91..8e4aef6f8fa 100644 --- a/cpp/src/Ice/LoggerI.cpp +++ b/cpp/src/Ice/LoggerI.cpp @@ -21,7 +21,7 @@ Ice::LoggerI::LoggerI(const string& prefix) { if(!prefix.empty()) { - _prefix = prefix + ": "; + _prefix = prefix + ": "; } } @@ -46,8 +46,8 @@ Ice::LoggerI::trace(const string& category, const string& message) string::size_type idx = 0; while((idx = s.find("\n", idx)) != string::npos) { - s.insert(idx + 1, " "); - ++idx; + s.insert(idx + 1, " "); + ++idx; } IceUtil::StaticMutex::Lock sync(outputMutex); diff --git a/cpp/src/Ice/LoggerUtil.cpp b/cpp/src/Ice/LoggerUtil.cpp index ca888e23688..6d6f907ee61 100644 --- a/cpp/src/Ice/LoggerUtil.cpp +++ b/cpp/src/Ice/LoggerUtil.cpp @@ -30,7 +30,7 @@ Ice::Print::flush() string s = _str.str(); if(!s.empty()) { - _logger->print(s); + _logger->print(s); } _str.str(""); } @@ -64,7 +64,7 @@ Ice::Warning::flush() string s = _str.str(); if(!s.empty()) { - _logger->warning(s); + _logger->warning(s); } _str.str(""); } @@ -98,7 +98,7 @@ Ice::Error::flush() string s = _str.str(); if(!s.empty()) { - _logger->error(s); + _logger->error(s); } _str.str(""); } @@ -133,7 +133,7 @@ Ice::Trace::flush() string s = _str.str(); if(!s.empty()) { - _logger->trace(_category, s); + _logger->trace(_category, s); } _str.str(""); } diff --git a/cpp/src/Ice/Network.cpp b/cpp/src/Ice/Network.cpp index 9cc42da481c..737f2f3f148 100644 --- a/cpp/src/Ice/Network.cpp +++ b/cpp/src/Ice/Network.cpp @@ -73,7 +73,7 @@ IceInternal::acceptInterrupted() { if(interrupted()) { - return true; + return true; } #ifdef _WIN32 @@ -168,7 +168,7 @@ IceInternal::connectionLost() errno == ENOTCONN || errno == ESHUTDOWN || errno == ECONNABORTED || - errno == EPIPE; + errno == EPIPE; #endif } @@ -200,24 +200,24 @@ IceInternal::createSocket(bool udp) if(udp) { - fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP); + fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP); } else { - fd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); + fd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); } if(fd == INVALID_SOCKET) { - SocketException ex(__FILE__, __LINE__); - ex.error = getSocketErrno(); - throw ex; + SocketException ex(__FILE__, __LINE__); + ex.error = getSocketErrno(); + throw ex; } if(!udp) { - setTcpNoDelay(fd); - setKeepAlive(fd); + setTcpNoDelay(fd); + setKeepAlive(fd); } return fd; @@ -230,18 +230,18 @@ IceInternal::closeSocket(SOCKET fd) int error = WSAGetLastError(); if(closesocket(fd) == SOCKET_ERROR) { - SocketException ex(__FILE__, __LINE__); - ex.error = getSocketErrno(); - throw ex; + SocketException ex(__FILE__, __LINE__); + ex.error = getSocketErrno(); + throw ex; } WSASetLastError(error); #else int error = errno; if(close(fd) == SOCKET_ERROR) { - SocketException ex(__FILE__, __LINE__); - ex.error = getSocketErrno(); - throw ex; + SocketException ex(__FILE__, __LINE__); + ex.error = getSocketErrno(); + throw ex; } errno = error; #endif @@ -266,29 +266,29 @@ IceInternal::shutdownSocketWrite(SOCKET fd) { if(shutdown(fd, SHUT_WR) == SOCKET_ERROR) { - // - // Ignore errors indicating that we are shutdown already. - // + // + // Ignore errors indicating that we are shutdown already. + // #if defined(_WIN32) - int error = WSAGetLastError(); - if(error == WSAENOTCONN) - { - return; - } + int error = WSAGetLastError(); + if(error == WSAENOTCONN) + { + return; + } #elif defined(__APPLE__) - if(errno == ENOTCONN || errno == EINVAL) - { - return; - } + if(errno == ENOTCONN || errno == EINVAL) + { + return; + } #else - if(errno == ENOTCONN) - { - return; - } + if(errno == ENOTCONN) + { + return; + } #endif - SocketException ex(__FILE__, __LINE__); - ex.error = getSocketErrno(); - throw ex; + SocketException ex(__FILE__, __LINE__); + ex.error = getSocketErrno(); + throw ex; } } @@ -297,30 +297,30 @@ IceInternal::shutdownSocketReadWrite(SOCKET fd) { if(shutdown(fd, SHUT_RDWR) == SOCKET_ERROR) { - // - // Ignore errors indicating that we are shutdown already. - // + // + // Ignore errors indicating that we are shutdown already. + // #if defined(_WIN32) - int error = WSAGetLastError(); - if(error == WSAENOTCONN) - { - return; - } + int error = WSAGetLastError(); + if(error == WSAENOTCONN) + { + return; + } #elif defined(__APPLE__) - if(errno == ENOTCONN || errno == EINVAL) - { - return; - } + if(errno == ENOTCONN || errno == EINVAL) + { + return; + } #else - if(errno == ENOTCONN) - { - return; - } + if(errno == ENOTCONN) + { + return; + } #endif - SocketException ex(__FILE__, __LINE__); - ex.error = getSocketErrno(); - throw ex; + SocketException ex(__FILE__, __LINE__); + ex.error = getSocketErrno(); + throw ex; } } @@ -330,47 +330,47 @@ IceInternal::setBlock(SOCKET fd, bool block) if(block) { #ifdef _WIN32 - unsigned long arg = 0; - if(ioctlsocket(fd, FIONBIO, &arg) == SOCKET_ERROR) - { - closeSocketNoThrow(fd); - SocketException ex(__FILE__, __LINE__); - ex.error = WSAGetLastError(); - throw ex; - } + unsigned long arg = 0; + if(ioctlsocket(fd, FIONBIO, &arg) == SOCKET_ERROR) + { + closeSocketNoThrow(fd); + SocketException ex(__FILE__, __LINE__); + ex.error = WSAGetLastError(); + throw ex; + } #else - int flags = fcntl(fd, F_GETFL); - flags &= ~O_NONBLOCK; - if(fcntl(fd, F_SETFL, flags) == SOCKET_ERROR) - { - closeSocketNoThrow(fd); - SocketException ex(__FILE__, __LINE__); - ex.error = errno; - throw ex; - } + int flags = fcntl(fd, F_GETFL); + flags &= ~O_NONBLOCK; + if(fcntl(fd, F_SETFL, flags) == SOCKET_ERROR) + { + closeSocketNoThrow(fd); + SocketException ex(__FILE__, __LINE__); + ex.error = errno; + throw ex; + } #endif } else { #ifdef _WIN32 - unsigned long arg = 1; - if(ioctlsocket(fd, FIONBIO, &arg) == SOCKET_ERROR) - { - closeSocketNoThrow(fd); - SocketException ex(__FILE__, __LINE__); - ex.error = WSAGetLastError(); - throw ex; - } + unsigned long arg = 1; + if(ioctlsocket(fd, FIONBIO, &arg) == SOCKET_ERROR) + { + closeSocketNoThrow(fd); + SocketException ex(__FILE__, __LINE__); + ex.error = WSAGetLastError(); + throw ex; + } #else - int flags = fcntl(fd, F_GETFL); - flags |= O_NONBLOCK; - if(fcntl(fd, F_SETFL, flags) == SOCKET_ERROR) - { - closeSocketNoThrow(fd); - SocketException ex(__FILE__, __LINE__); - ex.error = errno; - throw ex; - } + int flags = fcntl(fd, F_GETFL); + flags |= O_NONBLOCK; + if(fcntl(fd, F_SETFL, flags) == SOCKET_ERROR) + { + closeSocketNoThrow(fd); + SocketException ex(__FILE__, __LINE__); + ex.error = errno; + throw ex; + } #endif } } @@ -381,10 +381,10 @@ IceInternal::setTcpNoDelay(SOCKET fd) int flag = 1; if(setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char*)&flag, int(sizeof(int))) == SOCKET_ERROR) { - closeSocketNoThrow(fd); - SocketException ex(__FILE__, __LINE__); - ex.error = getSocketErrno(); - throw ex; + closeSocketNoThrow(fd); + SocketException ex(__FILE__, __LINE__); + ex.error = getSocketErrno(); + throw ex; } } @@ -394,10 +394,10 @@ IceInternal::setKeepAlive(SOCKET fd) int flag = 1; if(setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (char*)&flag, int(sizeof(int))) == SOCKET_ERROR) { - closeSocketNoThrow(fd); - SocketException ex(__FILE__, __LINE__); - ex.error = getSocketErrno(); - throw ex; + closeSocketNoThrow(fd); + SocketException ex(__FILE__, __LINE__); + ex.error = getSocketErrno(); + throw ex; } } @@ -406,10 +406,10 @@ IceInternal::setSendBufferSize(SOCKET fd, int sz) { if(setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (char*)&sz, int(sizeof(int))) == SOCKET_ERROR) { - closeSocketNoThrow(fd); - SocketException ex(__FILE__, __LINE__); - ex.error = getSocketErrno(); - throw ex; + closeSocketNoThrow(fd); + SocketException ex(__FILE__, __LINE__); + ex.error = getSocketErrno(); + throw ex; } } @@ -420,10 +420,10 @@ IceInternal::getSendBufferSize(SOCKET fd) socklen_t len = sizeof(sz); if(getsockopt(fd, SOL_SOCKET, SO_SNDBUF, (char*)&sz, &len) == SOCKET_ERROR || len != sizeof(sz)) { - closeSocketNoThrow(fd); - SocketException ex(__FILE__, __LINE__); - ex.error = getSocketErrno(); - throw ex; + closeSocketNoThrow(fd); + SocketException ex(__FILE__, __LINE__); + ex.error = getSocketErrno(); + throw ex; } return sz; } @@ -433,10 +433,10 @@ IceInternal::setRecvBufferSize(SOCKET fd, int sz) { if(setsockopt(fd, SOL_SOCKET, SO_RCVBUF, (char*)&sz, int(sizeof(int))) == SOCKET_ERROR) { - closeSocketNoThrow(fd); - SocketException ex(__FILE__, __LINE__); - ex.error = getSocketErrno(); - throw ex; + closeSocketNoThrow(fd); + SocketException ex(__FILE__, __LINE__); + ex.error = getSocketErrno(); + throw ex; } } @@ -447,10 +447,10 @@ IceInternal::getRecvBufferSize(SOCKET fd) socklen_t len = sizeof(sz); if(getsockopt(fd, SOL_SOCKET, SO_RCVBUF, (char*)&sz, &len) == SOCKET_ERROR || len != sizeof(sz)) { - closeSocketNoThrow(fd); - SocketException ex(__FILE__, __LINE__); - ex.error = getSocketErrno(); - throw ex; + closeSocketNoThrow(fd); + SocketException ex(__FILE__, __LINE__); + ex.error = getSocketErrno(); + throw ex; } return sz; } @@ -462,19 +462,19 @@ IceInternal::doBind(SOCKET fd, struct sockaddr_in& addr) int flag = 1; if(setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char*)&flag, int(sizeof(int))) == SOCKET_ERROR) { - closeSocketNoThrow(fd); - SocketException ex(__FILE__, __LINE__); - ex.error = getSocketErrno(); - throw ex; + closeSocketNoThrow(fd); + SocketException ex(__FILE__, __LINE__); + ex.error = getSocketErrno(); + throw ex; } #endif if(bind(fd, reinterpret_cast(&addr), int(sizeof(addr))) == SOCKET_ERROR) { - closeSocketNoThrow(fd); - SocketException ex(__FILE__, __LINE__); - ex.error = getSocketErrno(); - throw ex; + closeSocketNoThrow(fd); + SocketException ex(__FILE__, __LINE__); + ex.error = getSocketErrno(); + throw ex; } socklen_t len = static_cast(sizeof(addr)); @@ -492,15 +492,15 @@ IceInternal::doListen(SOCKET fd, int backlog) repeatListen: if(::listen(fd, backlog) == SOCKET_ERROR) { - if(interrupted()) - { - goto repeatListen; - } - - closeSocketNoThrow(fd); - SocketException ex(__FILE__, __LINE__); - ex.error = getSocketErrno(); - throw ex; + if(interrupted()) + { + goto repeatListen; + } + + closeSocketNoThrow(fd); + SocketException ex(__FILE__, __LINE__); + ex.error = getSocketErrno(); + throw ex; } } @@ -522,173 +522,173 @@ IceInternal::doConnect(SOCKET fd, struct sockaddr_in& addr, int timeout) WSAEVENT event = WSACreateEvent(); if(event == 0) { - closeSocketNoThrow(fd); + closeSocketNoThrow(fd); - SocketException ex(__FILE__, __LINE__); - ex.error = WSAGetLastError(); - throw ex; + SocketException ex(__FILE__, __LINE__); + ex.error = WSAGetLastError(); + throw ex; } if(WSAEventSelect(fd, event, FD_CONNECT) == SOCKET_ERROR) { - int error = WSAGetLastError(); + int error = WSAGetLastError(); - WSACloseEvent(event); - closeSocketNoThrow(fd); + WSACloseEvent(event); + closeSocketNoThrow(fd); - SocketException ex(__FILE__, __LINE__); - ex.error = error; - throw ex; + SocketException ex(__FILE__, __LINE__); + ex.error = error; + throw ex; } #endif repeatConnect: if(::connect(fd, reinterpret_cast(&addr), int(sizeof(addr))) == SOCKET_ERROR) { - if(interrupted()) - { - goto repeatConnect; - } - - if(connectInProgress()) - { - int val; + if(interrupted()) + { + goto repeatConnect; + } + + if(connectInProgress()) + { + int val; #ifdef _WIN32 - WSAEVENT events[1]; - events[0] = event; - long tout = (timeout >= 0) ? timeout : WSA_INFINITE; - DWORD rc = WSAWaitForMultipleEvents(1, events, FALSE, tout, FALSE); - if(rc == WSA_WAIT_FAILED) - { - int error = WSAGetLastError(); - - WSACloseEvent(event); - closeSocketNoThrow(fd); - - SocketException ex(__FILE__, __LINE__); - ex.error = error; - throw ex; - } - - if(rc == WSA_WAIT_TIMEOUT) - { - WSACloseEvent(event); - closeSocketNoThrow(fd); - - assert(timeout >= 0); - throw ConnectTimeoutException(__FILE__, __LINE__); - } - assert(rc == WSA_WAIT_EVENT_0); - - WSANETWORKEVENTS nevents; - if(WSAEnumNetworkEvents(fd, event, &nevents) == SOCKET_ERROR) - { - int error = WSAGetLastError(); - WSACloseEvent(event); - closeSocketNoThrow(fd); - - SocketException ex(__FILE__, __LINE__); - ex.error = error; - throw ex; - } - - // - // Now we close the event, because we're finished and - // this code be repeated. - // - WSACloseEvent(event); - - assert(nevents.lNetworkEvents & FD_CONNECT); - val = nevents.iErrorCode[FD_CONNECT_BIT]; + WSAEVENT events[1]; + events[0] = event; + long tout = (timeout >= 0) ? timeout : WSA_INFINITE; + DWORD rc = WSAWaitForMultipleEvents(1, events, FALSE, tout, FALSE); + if(rc == WSA_WAIT_FAILED) + { + int error = WSAGetLastError(); + + WSACloseEvent(event); + closeSocketNoThrow(fd); + + SocketException ex(__FILE__, __LINE__); + ex.error = error; + throw ex; + } + + if(rc == WSA_WAIT_TIMEOUT) + { + WSACloseEvent(event); + closeSocketNoThrow(fd); + + assert(timeout >= 0); + throw ConnectTimeoutException(__FILE__, __LINE__); + } + assert(rc == WSA_WAIT_EVENT_0); + + WSANETWORKEVENTS nevents; + if(WSAEnumNetworkEvents(fd, event, &nevents) == SOCKET_ERROR) + { + int error = WSAGetLastError(); + WSACloseEvent(event); + closeSocketNoThrow(fd); + + SocketException ex(__FILE__, __LINE__); + ex.error = error; + throw ex; + } + + // + // Now we close the event, because we're finished and + // this code be repeated. + // + WSACloseEvent(event); + + assert(nevents.lNetworkEvents & FD_CONNECT); + val = nevents.iErrorCode[FD_CONNECT_BIT]; #else - repeatPoll: - struct pollfd pollFd[1]; - pollFd[0].fd = fd; - pollFd[0].events = POLLOUT; - int ret = ::poll(pollFd, 1, timeout); - if(ret == 0) - { - closeSocketNoThrow(fd); - throw ConnectTimeoutException(__FILE__, __LINE__); - } - else if(ret == SOCKET_ERROR) - { - if(interrupted()) - { - goto repeatPoll; - } - - SocketException ex(__FILE__, __LINE__); - ex.error = getSocketErrno(); - throw ex; - } - - // - // Strange windows bug: The following call to Sleep() is - // necessary, otherwise no error is reported through - // getsockopt. - // - //Sleep(0); - socklen_t len = static_cast(sizeof(int)); - if(getsockopt(fd, SOL_SOCKET, SO_ERROR, reinterpret_cast(&val), &len) == SOCKET_ERROR) - { - closeSocketNoThrow(fd); - SocketException ex(__FILE__, __LINE__); - ex.error = getSocketErrno(); - throw ex; - } + repeatPoll: + struct pollfd pollFd[1]; + pollFd[0].fd = fd; + pollFd[0].events = POLLOUT; + int ret = ::poll(pollFd, 1, timeout); + if(ret == 0) + { + closeSocketNoThrow(fd); + throw ConnectTimeoutException(__FILE__, __LINE__); + } + else if(ret == SOCKET_ERROR) + { + if(interrupted()) + { + goto repeatPoll; + } + + SocketException ex(__FILE__, __LINE__); + ex.error = getSocketErrno(); + throw ex; + } + + // + // Strange windows bug: The following call to Sleep() is + // necessary, otherwise no error is reported through + // getsockopt. + // + //Sleep(0); + socklen_t len = static_cast(sizeof(int)); + if(getsockopt(fd, SOL_SOCKET, SO_ERROR, reinterpret_cast(&val), &len) == SOCKET_ERROR) + { + closeSocketNoThrow(fd); + SocketException ex(__FILE__, __LINE__); + ex.error = getSocketErrno(); + throw ex; + } #endif - - if(val > 0) - { - closeSocketNoThrow(fd); + + if(val > 0) + { + closeSocketNoThrow(fd); #ifdef _WIN32 - WSASetLastError(val); + WSASetLastError(val); #else - errno = val; + errno = val; #endif - if(connectionRefused()) - { - ConnectionRefusedException ex(__FILE__, __LINE__); - ex.error = getSocketErrno(); - throw ex; - } - else if(connectFailed()) - { - ConnectFailedException ex(__FILE__, __LINE__); - ex.error = getSocketErrno(); - throw ex; - } - else - { - SocketException ex(__FILE__, __LINE__); - ex.error = getSocketErrno(); - throw ex; - } - } - - return; - } + if(connectionRefused()) + { + ConnectionRefusedException ex(__FILE__, __LINE__); + ex.error = getSocketErrno(); + throw ex; + } + else if(connectFailed()) + { + ConnectFailedException ex(__FILE__, __LINE__); + ex.error = getSocketErrno(); + throw ex; + } + else + { + SocketException ex(__FILE__, __LINE__); + ex.error = getSocketErrno(); + throw ex; + } + } + + return; + } - closeSocketNoThrow(fd); - if(connectionRefused()) - { - ConnectionRefusedException ex(__FILE__, __LINE__); - ex.error = getSocketErrno(); - throw ex; - } - else if(connectFailed()) - { - ConnectFailedException ex(__FILE__, __LINE__); - ex.error = getSocketErrno(); - throw ex; - } - else - { - SocketException ex(__FILE__, __LINE__); - ex.error = getSocketErrno(); - throw ex; - } + closeSocketNoThrow(fd); + if(connectionRefused()) + { + ConnectionRefusedException ex(__FILE__, __LINE__); + ex.error = getSocketErrno(); + throw ex; + } + else if(connectFailed()) + { + ConnectFailedException ex(__FILE__, __LINE__); + ex.error = getSocketErrno(); + throw ex; + } + else + { + SocketException ex(__FILE__, __LINE__); + ex.error = getSocketErrno(); + throw ex; + } } } @@ -704,60 +704,60 @@ IceInternal::doAccept(SOCKET fd, int timeout) repeatAccept: if((ret = ::accept(fd, 0, 0)) == INVALID_SOCKET) { - if(acceptInterrupted()) - { - goto repeatAccept; - } - - if(wouldBlock()) - { - repeatSelect: - int rs; + if(acceptInterrupted()) + { + goto repeatAccept; + } + + if(wouldBlock()) + { + repeatSelect: + int rs; #ifdef _WIN32 - fd_set fdSet; - FD_ZERO(&fdSet); - FD_SET(fd, &fdSet); - if(timeout >= 0) - { - struct timeval tv; - tv.tv_sec = timeout / 1000; - tv.tv_usec = (timeout - tv.tv_sec * 1000) * 1000; - rs = ::select(static_cast(fd + 1), &fdSet, 0, 0, &tv); - } - else - { - rs = ::select(static_cast(fd + 1), &fdSet, 0, 0, 0); - } + fd_set fdSet; + FD_ZERO(&fdSet); + FD_SET(fd, &fdSet); + if(timeout >= 0) + { + struct timeval tv; + tv.tv_sec = timeout / 1000; + tv.tv_usec = (timeout - tv.tv_sec * 1000) * 1000; + rs = ::select(static_cast(fd + 1), &fdSet, 0, 0, &tv); + } + else + { + rs = ::select(static_cast(fd + 1), &fdSet, 0, 0, 0); + } #else - struct pollfd pollFd[1]; - pollFd[0].fd = fd; - pollFd[0].events = POLLIN; - rs = ::poll(pollFd, 1, timeout); + struct pollfd pollFd[1]; + pollFd[0].fd = fd; + pollFd[0].events = POLLIN; + rs = ::poll(pollFd, 1, timeout); #endif - - if(rs == SOCKET_ERROR) - { - if(interrupted()) - { - goto repeatSelect; - } - - SocketException ex(__FILE__, __LINE__); - ex.error = getSocketErrno(); - throw ex; - } - - if(rs == 0) - { - throw TimeoutException(__FILE__, __LINE__); - } - - goto repeatAccept; - } - - SocketException ex(__FILE__, __LINE__); - ex.error = getSocketErrno(); - throw ex; + + if(rs == SOCKET_ERROR) + { + if(interrupted()) + { + goto repeatSelect; + } + + SocketException ex(__FILE__, __LINE__); + ex.error = getSocketErrno(); + throw ex; + } + + if(rs == 0) + { + throw TimeoutException(__FILE__, __LINE__); + } + + goto repeatAccept; + } + + SocketException ex(__FILE__, __LINE__); + ex.error = getSocketErrno(); + throw ex; } setTcpNoDelay(ret); @@ -786,59 +786,59 @@ IceInternal::getAddress(const string& host, int port, struct sockaddr_in& addr) { #ifdef _WIN32 - // - // Windows XP has getaddrinfo(), but we don't want to require XP to run Ice. - // - - // - // gethostbyname() is thread safe on Windows, with a separate hostent per thread - // - struct hostent* entry; - int retry = 5; - do - { - entry = gethostbyname(host.c_str()); - } - while(entry == 0 && WSAGetLastError() == WSATRY_AGAIN && --retry >= 0); - - if(entry == 0) - { - DNSException ex(__FILE__, __LINE__); - - ex.error = WSAGetLastError(); - ex.host = host; - throw ex; - } - memcpy(&addr.sin_addr, entry->h_addr, entry->h_length); + // + // Windows XP has getaddrinfo(), but we don't want to require XP to run Ice. + // + + // + // gethostbyname() is thread safe on Windows, with a separate hostent per thread + // + struct hostent* entry; + int retry = 5; + do + { + entry = gethostbyname(host.c_str()); + } + while(entry == 0 && WSAGetLastError() == WSATRY_AGAIN && --retry >= 0); + + if(entry == 0) + { + DNSException ex(__FILE__, __LINE__); + + ex.error = WSAGetLastError(); + ex.host = host; + throw ex; + } + memcpy(&addr.sin_addr, entry->h_addr, entry->h_length); #else - struct addrinfo* info = 0; - int retry = 5; - - struct addrinfo hints = { 0 }; - hints.ai_family = PF_INET; - - int rs = 0; - do - { - rs = getaddrinfo(host.c_str(), 0, &hints, &info); - } - while(info == 0 && rs == EAI_AGAIN && --retry >= 0); - - if(rs != 0) - { - DNSException ex(__FILE__, __LINE__); - ex.error = rs; - ex.host = host; - throw ex; - } - - assert(info->ai_family == PF_INET); - struct sockaddr_in* sin = reinterpret_cast(info->ai_addr); - - addr.sin_addr.s_addr = sin->sin_addr.s_addr; - freeaddrinfo(info); + struct addrinfo* info = 0; + int retry = 5; + + struct addrinfo hints = { 0 }; + hints.ai_family = PF_INET; + + int rs = 0; + do + { + rs = getaddrinfo(host.c_str(), 0, &hints, &info); + } + while(info == 0 && rs == EAI_AGAIN && --retry >= 0); + + if(rs != 0) + { + DNSException ex(__FILE__, __LINE__); + ex.error = rs; + ex.host = host; + throw ex; + } + + assert(info->ai_family == PF_INET); + struct sockaddr_in* sin = reinterpret_cast(info->ai_addr); + + addr.sin_addr.s_addr = sin->sin_addr.s_addr; + freeaddrinfo(info); #endif } @@ -871,12 +871,12 @@ IceInternal::createPipe(SOCKET fds[2]) try { - fds[0] = createSocket(false); + fds[0] = createSocket(false); } catch(...) { - ::closesocket(fd); - throw; + ::closesocket(fd); + throw; } try @@ -886,19 +886,19 @@ IceInternal::createPipe(SOCKET fds[2]) } catch(...) { - ::closesocket(fd); - throw; + ::closesocket(fd); + throw; } try { - fds[1] = doAccept(fd, -1); + fds[1] = doAccept(fd, -1); } catch(...) { - ::closesocket(fds[0]); - ::closesocket(fd); - throw; + ::closesocket(fds[0]); + ::closesocket(fd); + throw; } ::closesocket(fd); @@ -909,18 +909,18 @@ IceInternal::createPipe(SOCKET fds[2]) } catch(...) { - ::closesocket(fds[0]); - ::closesocket(fd); - throw; + ::closesocket(fds[0]); + ::closesocket(fd); + throw; } #else if(::pipe(fds) != 0) { - SyscallException ex(__FILE__, __LINE__); - ex.error = getSystemErrno(); - throw ex; + SyscallException ex(__FILE__, __LINE__); + ex.error = getSystemErrno(); + throw ex; } try @@ -929,8 +929,8 @@ IceInternal::createPipe(SOCKET fds[2]) } catch(...) { - closeSocketNoThrow(fds[1]); - throw; + closeSocketNoThrow(fds[1]); + throw; } try @@ -939,8 +939,8 @@ IceInternal::createPipe(SOCKET fds[2]) } catch(...) { - closeSocketNoThrow(fds[0]); - throw; + closeSocketNoThrow(fds[0]); + throw; } #endif @@ -953,196 +953,196 @@ IceInternal::errorToString(int error) { if(error < WSABASEERR) { - LPVOID lpMsgBuf = 0; - DWORD ok = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | - FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, - error, - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language - (LPTSTR)&lpMsgBuf, - 0, - NULL); - if(ok) - { - LPCTSTR msg = (LPCTSTR)lpMsgBuf; - assert(msg && strlen((const char*)msg) > 0); - string result = (const char*)msg; - if(result[result.length() - 1] == '\n') - { - result = result.substr(0, result.length() - 2); - } - LocalFree(lpMsgBuf); - return result; - } - else - { - ostringstream os; - os << "unknown error: " << error; - return os.str(); - } + LPVOID lpMsgBuf = 0; + DWORD ok = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | + FORMAT_MESSAGE_FROM_SYSTEM | + FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, + error, + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language + (LPTSTR)&lpMsgBuf, + 0, + NULL); + if(ok) + { + LPCTSTR msg = (LPCTSTR)lpMsgBuf; + assert(msg && strlen((const char*)msg) > 0); + string result = (const char*)msg; + if(result[result.length() - 1] == '\n') + { + result = result.substr(0, result.length() - 2); + } + LocalFree(lpMsgBuf); + return result; + } + else + { + ostringstream os; + os << "unknown error: " << error; + return os.str(); + } } switch(error) { case WSAEINTR: - return "WSAEINTR"; - + return "WSAEINTR"; + case WSAEBADF: - return "WSAEBADF"; - + return "WSAEBADF"; + case WSAEACCES: - return "WSAEACCES"; - + return "WSAEACCES"; + case WSAEFAULT: - return "WSAEFAULT"; - + return "WSAEFAULT"; + case WSAEINVAL: - return "WSAEINVAL"; - + return "WSAEINVAL"; + case WSAEMFILE: - return "WSAEMFILE"; - + return "WSAEMFILE"; + case WSAEWOULDBLOCK: - return "WSAEWOULDBLOCK"; - + return "WSAEWOULDBLOCK"; + case WSAEINPROGRESS: - return "WSAEINPROGRESS"; - + return "WSAEINPROGRESS"; + case WSAEALREADY: - return "WSAEALREADY"; - + return "WSAEALREADY"; + case WSAENOTSOCK: - return "WSAENOTSOCK"; - + return "WSAENOTSOCK"; + case WSAEDESTADDRREQ: - return "WSAEDESTADDRREQ"; - + return "WSAEDESTADDRREQ"; + case WSAEMSGSIZE: - return "WSAEMSGSIZE"; - + return "WSAEMSGSIZE"; + case WSAEPROTOTYPE: - return "WSAEPROTOTYPE"; - + return "WSAEPROTOTYPE"; + case WSAENOPROTOOPT: - return "WSAENOPROTOOPT"; - + return "WSAENOPROTOOPT"; + case WSAEPROTONOSUPPORT: - return "WSAEPROTONOSUPPORT"; - + return "WSAEPROTONOSUPPORT"; + case WSAESOCKTNOSUPPORT: - return "WSAESOCKTNOSUPPORT"; - + return "WSAESOCKTNOSUPPORT"; + case WSAEOPNOTSUPP: - return "WSAEOPNOTSUPP"; - + return "WSAEOPNOTSUPP"; + case WSAEPFNOSUPPORT: - return "WSAEPFNOSUPPORT"; - + return "WSAEPFNOSUPPORT"; + case WSAEAFNOSUPPORT: - return "WSAEAFNOSUPPORT"; - + return "WSAEAFNOSUPPORT"; + case WSAEADDRINUSE: - return "WSAEADDRINUSE"; - + return "WSAEADDRINUSE"; + case WSAEADDRNOTAVAIL: - return "WSAEADDRNOTAVAIL"; - + return "WSAEADDRNOTAVAIL"; + case WSAENETDOWN: - return "WSAENETDOWN"; - + return "WSAENETDOWN"; + case WSAENETUNREACH: - return "WSAENETUNREACH"; - + return "WSAENETUNREACH"; + case WSAENETRESET: - return "WSAENETRESET"; - + return "WSAENETRESET"; + case WSAECONNABORTED: - return "WSAECONNABORTED"; - + return "WSAECONNABORTED"; + case WSAECONNRESET: - return "WSAECONNRESET"; - + return "WSAECONNRESET"; + case WSAENOBUFS: - return "WSAENOBUFS"; - + return "WSAENOBUFS"; + case WSAEISCONN: - return "WSAEISCONN"; - + return "WSAEISCONN"; + case WSAENOTCONN: - return "WSAENOTCONN"; - + return "WSAENOTCONN"; + case WSAESHUTDOWN: - return "WSAESHUTDOWN"; - + return "WSAESHUTDOWN"; + case WSAETOOMANYREFS: - return "WSAETOOMANYREFS"; - + return "WSAETOOMANYREFS"; + case WSAETIMEDOUT: - return "WSAETIMEDOUT"; - + return "WSAETIMEDOUT"; + case WSAECONNREFUSED: - return "WSAECONNREFUSED"; - + return "WSAECONNREFUSED"; + case WSAELOOP: - return "WSAELOOP"; - + return "WSAELOOP"; + case WSAENAMETOOLONG: - return "WSAENAMETOOLONG"; - + return "WSAENAMETOOLONG"; + case WSAEHOSTDOWN: - return "WSAEHOSTDOWN"; - + return "WSAEHOSTDOWN"; + case WSAEHOSTUNREACH: - return "WSAEHOSTUNREACH"; - + return "WSAEHOSTUNREACH"; + case WSAENOTEMPTY: - return "WSAENOTEMPTY"; - + return "WSAENOTEMPTY"; + case WSAEPROCLIM: - return "WSAEPROCLIM"; - + return "WSAEPROCLIM"; + case WSAEUSERS: - return "WSAEUSERS"; - + return "WSAEUSERS"; + case WSAEDQUOT: - return "WSAEDQUOT"; - + return "WSAEDQUOT"; + case WSAESTALE: - return "WSAESTALE"; - + return "WSAESTALE"; + case WSAEREMOTE: - return "WSAEREMOTE"; - + return "WSAEREMOTE"; + case WSAEDISCON: - return "WSAEDISCON"; - + return "WSAEDISCON"; + case WSASYSNOTREADY: - return "WSASYSNOTREADY"; - + return "WSASYSNOTREADY"; + case WSAVERNOTSUPPORTED: - return "WSAVERNOTSUPPORTED"; - + return "WSAVERNOTSUPPORTED"; + case WSANOTINITIALISED: - return "WSANOTINITIALISED"; - + return "WSANOTINITIALISED"; + case WSAHOST_NOT_FOUND: - return "WSAHOST_NOT_FOUND"; - + return "WSAHOST_NOT_FOUND"; + case WSATRY_AGAIN: - return "WSATRY_AGAIN"; - + return "WSATRY_AGAIN"; + case WSANO_RECOVERY: - return "WSANO_RECOVERY"; - + return "WSANO_RECOVERY"; + case WSANO_DATA: - return "WSANO_DATA"; + return "WSANO_DATA"; default: { - ostringstream os; - os << "unknown socket error: " << error; - return os.str(); + ostringstream os; + os << "unknown socket error: " << error; + return os.str(); } } } @@ -1184,7 +1184,7 @@ IceInternal::fdToString(SOCKET fd) { if(fd == INVALID_SOCKET) { - return ""; + return ""; } struct sockaddr_in localAddr; @@ -1197,11 +1197,11 @@ IceInternal::fdToString(SOCKET fd) s << "local address = " << addrToString(localAddr); if(peerConnected) { - s << "\nremote address = " << addrToString(remoteAddr); + s << "\nremote address = " << addrToString(remoteAddr); } else { - s << "\nremote address = "; + s << "\nremote address = "; } return s.str(); } @@ -1212,10 +1212,10 @@ IceInternal::fdToLocalAddress(SOCKET fd, struct sockaddr_in& addr) socklen_t len = static_cast(sizeof(struct sockaddr_in)); if(getsockname(fd, reinterpret_cast(&addr), &len) == SOCKET_ERROR) { - closeSocketNoThrow(fd); - SocketException ex(__FILE__, __LINE__); - ex.error = getSocketErrno(); - throw ex; + closeSocketNoThrow(fd); + SocketException ex(__FILE__, __LINE__); + ex.error = getSocketErrno(); + throw ex; } } @@ -1225,17 +1225,17 @@ IceInternal::fdToRemoteAddress(SOCKET fd, struct sockaddr_in& addr) socklen_t len = static_cast(sizeof(struct sockaddr_in)); if(getpeername(fd, reinterpret_cast(&addr), &len) == SOCKET_ERROR) { - if(notConnected()) - { - return false; - } - else - { - closeSocketNoThrow(fd); - SocketException ex(__FILE__, __LINE__); - ex.error = getSocketErrno(); - throw ex; - } + if(notConnected()) + { + return false; + } + else + { + closeSocketNoThrow(fd); + SocketException ex(__FILE__, __LINE__); + ex.error = getSocketErrno(); + throw ex; + } } return true; @@ -1275,10 +1275,10 @@ IceInternal::getLocalHosts() if(curr->ifa_addr && curr->ifa_addr->sa_family == AF_INET) { struct sockaddr_in* addr = reinterpret_cast(curr->ifa_addr); - if(addr->sin_addr.s_addr != 0) - { - result.push_back(inetAddrToString((*addr).sin_addr)); - } + if(addr->sin_addr.s_addr != 0) + { + result.push_back(inetAddrToString((*addr).sin_addr)); + } } curr = curr->ifa_next; @@ -1312,17 +1312,17 @@ IceInternal::getLocalHosts() int rs = ioctl(fd, cmd, &ifc); if(rs == SOCKET_ERROR) { - free(ifc.ifc_buf); - closeSocketNoThrow(fd); - SocketException ex(__FILE__, __LINE__); - ex.error = getSocketErrno(); - throw ex; + free(ifc.ifc_buf); + closeSocketNoThrow(fd); + SocketException ex(__FILE__, __LINE__); + ex.error = getSocketErrno(); + throw ex; } else if(ifc.ifc_len == old_ifc_len) { // - // Returned same length twice in a row, finished. - // + // Returned same length twice in a row, finished. + // break; } else @@ -1341,10 +1341,10 @@ IceInternal::getLocalHosts() if(ifr[i].ifr_addr.sa_family == AF_INET) { struct sockaddr_in* addr = reinterpret_cast(&ifr[i].ifr_addr); - if(addr->sin_addr.s_addr != 0) - { - result.push_back(inetAddrToString((*addr).sin_addr)); - } + if(addr->sin_addr.s_addr != 0) + { + result.push_back(inetAddrToString((*addr).sin_addr)); + } } } @@ -1368,8 +1368,8 @@ IceInternal::getLocalAddresses() buffer.resize(1024); unsigned long len = 0; DWORD rs = WSAIoctl(fd, SIO_ADDRESS_LIST_QUERY, 0, 0, - &buffer[0], static_cast(buffer.size()), - &len, 0, 0); + &buffer[0], static_cast(buffer.size()), + &len, 0, 0); if(rs == SOCKET_ERROR) { // @@ -1380,8 +1380,8 @@ IceInternal::getLocalAddresses() { buffer.resize(len); rs = WSAIoctl(fd, SIO_ADDRESS_LIST_QUERY, 0, 0, - &buffer[0], static_cast(buffer.size()), - &len, 0, 0); + &buffer[0], static_cast(buffer.size()), + &len, 0, 0); } if(rs == SOCKET_ERROR) @@ -1433,17 +1433,17 @@ IceInternal::isLocalAddress(const struct sockaddr_in& addr) vector localAddrs = getLocalAddresses(); for(vector::const_iterator p = localAddrs.begin(); p != localAddrs.end(); ++p) { - if(compareAddress(addr0, *p)) - { - return true; - } + if(compareAddress(addr0, *p)) + { + return true; + } } } catch(const Ice::LocalException&) { - // - // TODO: Warning? - // + // + // TODO: Warning? + // } return false; } @@ -1455,17 +1455,17 @@ IceInternal::isPeerLocal(SOCKET fd) struct sockaddr_in remoteAddr; if(getpeername(fd, reinterpret_cast(&remoteAddr), &remoteLen) == SOCKET_ERROR) { - if(notConnected()) - { - return false; - } - else - { - closeSocketNoThrow(fd); - SocketException ex(__FILE__, __LINE__); - ex.error = getSocketErrno(); - throw ex; - } + if(notConnected()) + { + return false; + } + else + { + closeSocketNoThrow(fd); + SocketException ex(__FILE__, __LINE__); + ex.error = getSocketErrno(); + throw ex; + } } return isLocalAddress(remoteAddr); } diff --git a/cpp/src/Ice/Object.cpp b/cpp/src/Ice/Object.cpp index dd6a5d86cd9..34e00c0cae8 100644 --- a/cpp/src/Ice/Object.cpp +++ b/cpp/src/Ice/Object.cpp @@ -152,31 +152,31 @@ DispatchStatus Ice::Object::__dispatch(Incoming& in, const Current& current) { pair r = - equal_range(__all, __all + sizeof(__all) / sizeof(string), current.operation); + equal_range(__all, __all + sizeof(__all) / sizeof(string), current.operation); if(r.first == r.second) { - return DispatchOperationNotExist; - } + return DispatchOperationNotExist; + } switch(r.first - __all) { case 0: { - return ___ice_id(in, current); + return ___ice_id(in, current); } case 1: { - return ___ice_ids(in, current); + return ___ice_ids(in, current); } case 2: - { - return ___ice_isA(in, current); - } - case 3: - { - return ___ice_ping(in, current); - } + { + return ___ice_isA(in, current); + } + case 3: + { + return ___ice_ping(in, current); + } } assert(false); @@ -197,8 +197,8 @@ Ice::Object::__read(BasicStream* __is, bool __rid) { if(__rid) { - string myId; - __is->readTypeId(myId); + string myId; + __is->readTypeId(myId); } __is->startReadSlice(); @@ -208,7 +208,7 @@ Ice::Object::__read(BasicStream* __is, bool __rid) __is->readSize(sz); if(sz != 0) { - throw Ice::MarshalException(__FILE__, __LINE__); + throw Ice::MarshalException(__FILE__, __LINE__); } __is->endReadSlice(); @@ -228,7 +228,7 @@ Ice::Object::__read(const InputStreamPtr& __inS, bool __rid) { if(__rid) { - __inS->readTypeId(); + __inS->readTypeId(); } __inS->startSlice(); @@ -237,7 +237,7 @@ Ice::Object::__read(const InputStreamPtr& __inS, bool __rid) Int sz = __inS->readSize(); if(sz != 0) { - throw Ice::MarshalException(__FILE__, __LINE__); + throw Ice::MarshalException(__FILE__, __LINE__); } __inS->endSlice(); @@ -256,13 +256,13 @@ operationModeToString(OperationMode mode) switch(mode) { case Normal: - return "::Ice::Normal"; + return "::Ice::Normal"; case Nonmutating: - return "::Ice::Nonmutating"; + return "::Ice::Nonmutating"; case Idempotent: - return "::Ice::Idempotent"; + return "::Ice::Idempotent"; } ostringstream os; @@ -275,29 +275,29 @@ Ice::Object::__checkMode(OperationMode expected, OperationMode received) { if(expected != received) { - if(expected == Idempotent && received == Nonmutating) - { - // - // Fine: typically an old client still using the deprecated nonmutating keyword - // - - // - // Note that expected == Nonmutating and received == Idempotent is not ok: - // the server may still use the deprecated nonmutating keyword to detect updates - // and the client should not break this (deprecated) feature. - // - } - else - { - Ice::MarshalException ex(__FILE__, __LINE__); - std::ostringstream __reason; - __reason << "unexpected operation mode. expected = " - << operationModeToString(expected) - << " received = " - << operationModeToString(received); - ex.reason = __reason.str(); - throw ex; - } + if(expected == Idempotent && received == Nonmutating) + { + // + // Fine: typically an old client still using the deprecated nonmutating keyword + // + + // + // Note that expected == Nonmutating and received == Idempotent is not ok: + // the server may still use the deprecated nonmutating keyword to detect updates + // and the client should not break this (deprecated) feature. + // + } + else + { + Ice::MarshalException ex(__FILE__, __LINE__); + std::ostringstream __reason; + __reason << "unexpected operation mode. expected = " + << operationModeToString(expected) + << " received = " + << operationModeToString(received); + ex.reason = __reason.str(); + throw ex; + } } } @@ -312,11 +312,11 @@ Ice::Blobject::__dispatch(Incoming& in, const Current& current) in.os()->writeBlob(outParams); if(ok) { - return DispatchOK; + return DispatchOK; } else { - return DispatchUserException; + return DispatchUserException; } } @@ -332,11 +332,11 @@ Ice::BlobjectArray::__dispatch(Incoming& in, const Current& current) in.os()->writeBlob(outParams); if(ok) { - return DispatchOK; + return DispatchOK; } else { - return DispatchUserException; + return DispatchUserException; } } @@ -349,19 +349,19 @@ Ice::BlobjectAsync::__dispatch(Incoming& in, const Current& current) AMD_Object_ice_invokePtr cb = new ::IceAsync::Ice::AMD_Object_ice_invoke(in); try { - ice_invoke_async(cb, inParams, current); + ice_invoke_async(cb, inParams, current); } catch(const Exception& ex) { - cb->ice_exception(ex); + cb->ice_exception(ex); } catch(const ::std::exception& ex) { - cb->ice_exception(ex); + cb->ice_exception(ex); } catch(...) { - cb->ice_exception(); + cb->ice_exception(); } return DispatchAsync; } @@ -376,19 +376,19 @@ Ice::BlobjectArrayAsync::__dispatch(Incoming& in, const Current& current) AMD_Array_Object_ice_invokePtr cb = new ::IceAsync::Ice::AMD_Array_Object_ice_invoke(in); try { - ice_invoke_async(cb, inParams, current); + ice_invoke_async(cb, inParams, current); } catch(const Exception& ex) { - cb->ice_exception(ex); + cb->ice_exception(ex); } catch(const ::std::exception& ex) { - cb->ice_exception(ex); + cb->ice_exception(ex); } catch(...) { - cb->ice_exception(); + cb->ice_exception(); } return DispatchAsync; } diff --git a/cpp/src/Ice/ObjectAdapterFactory.cpp b/cpp/src/Ice/ObjectAdapterFactory.cpp index 8f93caf12a8..334be027f82 100644 --- a/cpp/src/Ice/ObjectAdapterFactory.cpp +++ b/cpp/src/Ice/ObjectAdapterFactory.cpp @@ -26,23 +26,23 @@ IceInternal::ObjectAdapterFactory::shutdown() map adapters; { - IceUtil::Monitor::Lock sync(*this); - - // - // Ignore shutdown requests if the object adapter factory has - // already been shut down. - // - if(!_instance) - { - return; - } - - adapters = _adapters; - - _instance = 0; - _communicator = 0; - - notifyAll(); + IceUtil::Monitor::Lock sync(*this); + + // + // Ignore shutdown requests if the object adapter factory has + // already been shut down. + // + if(!_instance) + { + return; + } + + adapters = _adapters; + + _instance = 0; + _communicator = 0; + + notifyAll(); } // @@ -50,48 +50,48 @@ IceInternal::ObjectAdapterFactory::shutdown() // deadlocks. // for_each(adapters.begin(), adapters.end(), - IceUtil::secondVoidMemFun(&ObjectAdapter::deactivate)); + IceUtil::secondVoidMemFun(&ObjectAdapter::deactivate)); } void IceInternal::ObjectAdapterFactory::waitForShutdown() { { - IceUtil::Monitor::Lock sync(*this); - - // - // First we wait for the shutdown of the factory itself. - // - while(_instance) - { - wait(); - } - - // - // If some other thread is currently shutting down, we wait - // until this thread is finished. - // - while(_waitForShutdown) - { - wait(); - } - _waitForShutdown = true; + IceUtil::Monitor::Lock sync(*this); + + // + // First we wait for the shutdown of the factory itself. + // + while(_instance) + { + wait(); + } + + // + // If some other thread is currently shutting down, we wait + // until this thread is finished. + // + while(_waitForShutdown) + { + wait(); + } + _waitForShutdown = true; } // // Now we wait for deactivation of each object adapter. // for_each(_adapters.begin(), _adapters.end(), - IceUtil::secondVoidMemFun(&ObjectAdapter::waitForDeactivate)); + IceUtil::secondVoidMemFun(&ObjectAdapter::waitForDeactivate)); { - IceUtil::Monitor::Lock sync(*this); + IceUtil::Monitor::Lock sync(*this); - // - // Signal that waiting is complete. - // - _waitForShutdown = false; - notifyAll(); + // + // Signal that waiting is complete. + // + _waitForShutdown = false; + notifyAll(); } } @@ -114,41 +114,41 @@ IceInternal::ObjectAdapterFactory::destroy() map adapters; { - IceUtil::Monitor::Lock sync(*this); + IceUtil::Monitor::Lock sync(*this); - adapters = _adapters; - _adapters.clear(); + adapters = _adapters; + _adapters.clear(); } // // Now we destroy each object adapter. // for_each(adapters.begin(), adapters.end(), - IceUtil::secondVoidMemFun(&ObjectAdapter::destroy)); + IceUtil::secondVoidMemFun(&ObjectAdapter::destroy)); } ObjectAdapterPtr IceInternal::ObjectAdapterFactory::createObjectAdapter(const string& name, const string& endpoints, - const RouterPrx& router) + const RouterPrx& router) { IceUtil::Monitor::Lock sync(*this); if(!_instance) { - throw ObjectAdapterDeactivatedException(__FILE__, __LINE__); + throw ObjectAdapterDeactivatedException(__FILE__, __LINE__); } map::iterator p = _adapters.find(name); if(p != _adapters.end()) { - throw AlreadyRegisteredException(__FILE__, __LINE__, "object adapter", name); + throw AlreadyRegisteredException(__FILE__, __LINE__, "object adapter", name); } if(name.empty() && (!endpoints.empty() || router != 0)) { InitializationException ex(__FILE__, __LINE__); - ex.reason = "Cannot configure endpoints or router with nameless object adapter"; - throw ex; + ex.reason = "Cannot configure endpoints or router with nameless object adapter"; + throw ex; } ObjectAdapterIPtr adapter; @@ -156,7 +156,7 @@ IceInternal::ObjectAdapterFactory::createObjectAdapter(const string& name, const { string uuid = IceUtil::generateUUID(); adapter = new ObjectAdapterI(_instance, _communicator, this, uuid, "", 0, true); - _adapters.insert(make_pair(uuid, adapter)); + _adapters.insert(make_pair(uuid, adapter)); } else { @@ -173,22 +173,22 @@ IceInternal::ObjectAdapterFactory::findObjectAdapter(const ObjectPrx& proxy) if(!_instance) { - return 0; + return 0; } for(map::iterator p = _adapters.begin(); p != _adapters.end(); ++p) { - try - { - if(p->second->isLocal(proxy)) - { - return p->second; - } - } - catch(const ObjectAdapterDeactivatedException&) - { - // Ignore. - } + try + { + if(p->second->isLocal(proxy)) + { + return p->second; + } + } + catch(const ObjectAdapterDeactivatedException&) + { + // Ignore. + } } return 0; @@ -213,7 +213,7 @@ struct FlushAdapter { void operator() (ObjectAdapterIPtr p) { - p->flushBatchRequests(); + p->flushBatchRequests(); } }; @@ -224,18 +224,18 @@ IceInternal::ObjectAdapterFactory::flushBatchRequests() const { list a; { - IceUtil::Monitor::Lock sync(*this); + IceUtil::Monitor::Lock sync(*this); - for(map::const_iterator p = _adapters.begin(); p != _adapters.end(); ++p) - { - a.push_back(p->second); - } + for(map::const_iterator p = _adapters.begin(); p != _adapters.end(); ++p) + { + a.push_back(p->second); + } } for_each(a.begin(), a.end(), FlushAdapter()); } IceInternal::ObjectAdapterFactory::ObjectAdapterFactory(const InstancePtr& instance, - const CommunicatorPtr& communicator) : + const CommunicatorPtr& communicator) : _instance(instance), _communicator(communicator), _waitForShutdown(false) diff --git a/cpp/src/Ice/ObjectAdapterI.cpp b/cpp/src/Ice/ObjectAdapterI.cpp index 483ad0542a3..b05a9697500 100644 --- a/cpp/src/Ice/ObjectAdapterI.cpp +++ b/cpp/src/Ice/ObjectAdapterI.cpp @@ -74,84 +74,84 @@ Ice::ObjectAdapterI::activate() bool printAdapterReady = false; { - IceUtil::Monitor::Lock sync(*this); - - checkForDeactivation(); - - // - // If the one off initializations of the adapter are already - // done, we just need to activate the incoming connection - // factories and we're done. - // - if(_activateOneOffDone) - { - for_each(_incomingConnectionFactories.begin(), _incomingConnectionFactories.end(), - Ice::voidMemFun(&IncomingConnectionFactory::activate)); - return; - } - - // - // One off initializations of the adapter: update the locator - // registry and print the "adapter ready" message. We set the - // _waitForActivate flag to prevent deactivation from other - // threads while these one off initializations are done. - // - _waitForActivate = true; - - locatorInfo = _locatorInfo; - if(!_noConfig) - { - PropertiesPtr properties = _instance->initializationData().properties; - printAdapterReady = properties->getPropertyAsInt("Ice.PrintAdapterReady") > 0; - // - // DEPREACTED PROPERTY: Remove extra code in future release - // - registerProcess = properties->getPropertyAsIntWithDefault(_propertyPrefix + _name + ".RegisterProcess", - properties->getPropertyAsInt(_name + ".RegisterProcess")) > 0; - } + IceUtil::Monitor::Lock sync(*this); + + checkForDeactivation(); + + // + // If the one off initializations of the adapter are already + // done, we just need to activate the incoming connection + // factories and we're done. + // + if(_activateOneOffDone) + { + for_each(_incomingConnectionFactories.begin(), _incomingConnectionFactories.end(), + Ice::voidMemFun(&IncomingConnectionFactory::activate)); + return; + } + + // + // One off initializations of the adapter: update the locator + // registry and print the "adapter ready" message. We set the + // _waitForActivate flag to prevent deactivation from other + // threads while these one off initializations are done. + // + _waitForActivate = true; + + locatorInfo = _locatorInfo; + if(!_noConfig) + { + PropertiesPtr properties = _instance->initializationData().properties; + printAdapterReady = properties->getPropertyAsInt("Ice.PrintAdapterReady") > 0; + // + // DEPREACTED PROPERTY: Remove extra code in future release + // + registerProcess = properties->getPropertyAsIntWithDefault(_propertyPrefix + _name + ".RegisterProcess", + properties->getPropertyAsInt(_name + ".RegisterProcess")) > 0; + } } try { - Ice::Identity dummy; - dummy.name = "dummy"; - updateLocatorRegistry(locatorInfo, createDirectProxy(dummy), registerProcess); + Ice::Identity dummy; + dummy.name = "dummy"; + updateLocatorRegistry(locatorInfo, createDirectProxy(dummy), registerProcess); } catch(const Ice::LocalException&) { - // - // If we couldn't update the locator registry, we let the - // exception go through and don't activate the adapter to - // allow to user code to retry activating the adapter - // later. - // - { - IceUtil::Monitor::Lock sync(*this); - _waitForActivate = false; - notifyAll(); - } - throw; + // + // If we couldn't update the locator registry, we let the + // exception go through and don't activate the adapter to + // allow to user code to retry activating the adapter + // later. + // + { + IceUtil::Monitor::Lock sync(*this); + _waitForActivate = false; + notifyAll(); + } + throw; } if(printAdapterReady) { - cout << _name << " ready" << endl; + cout << _name << " ready" << endl; } { - IceUtil::Monitor::Lock sync(*this); - assert(!_deactivated); // Not possible if _waitForActivate = true; + IceUtil::Monitor::Lock sync(*this); + assert(!_deactivated); // Not possible if _waitForActivate = true; - // - // Signal threads waiting for the activation. - // - _waitForActivate = false; - notifyAll(); + // + // Signal threads waiting for the activation. + // + _waitForActivate = false; + notifyAll(); - _activateOneOffDone = true; + _activateOneOffDone = true; - for_each(_incomingConnectionFactories.begin(), _incomingConnectionFactories.end(), - Ice::voidMemFun(&IncomingConnectionFactory::activate)); + for_each(_incomingConnectionFactories.begin(), _incomingConnectionFactories.end(), + Ice::voidMemFun(&IncomingConnectionFactory::activate)); } } @@ -161,9 +161,9 @@ Ice::ObjectAdapterI::hold() IceUtil::Monitor::Lock sync(*this); checkForDeactivation(); - + for_each(_incomingConnectionFactories.begin(), _incomingConnectionFactories.end(), - Ice::voidMemFun(&IncomingConnectionFactory::hold)); + Ice::voidMemFun(&IncomingConnectionFactory::hold)); } void @@ -174,7 +174,7 @@ Ice::ObjectAdapterI::waitForHold() checkForDeactivation(); for_each(_incomingConnectionFactories.begin(), _incomingConnectionFactories.end(), - Ice::constVoidMemFun(&IncomingConnectionFactory::waitUntilHolding)); + Ice::constVoidMemFun(&IncomingConnectionFactory::waitUntilHolding)); } void @@ -184,58 +184,58 @@ Ice::ObjectAdapterI::deactivate() OutgoingConnectionFactoryPtr outgoingConnectionFactory; LocatorInfoPtr locatorInfo; { - IceUtil::Monitor::Lock sync(*this); - - // - // Ignore deactivation requests if the object adapter has already - // been deactivated. - // - if(_deactivated) - { - return; - } - - // - // Wait for activation to complete. This is necessary to not - // get out of order locator updates. - // - while(_waitForActivate) - { - wait(); - } - - if(_routerInfo) - { - // - // Remove entry from the router manager. - // - _instance->routerManager()->erase(_routerInfo->getRouter()); - - // - // Clear this object adapter with the router. - // - _routerInfo->setAdapter(0); - } - + IceUtil::Monitor::Lock sync(*this); + + // + // Ignore deactivation requests if the object adapter has already + // been deactivated. + // + if(_deactivated) + { + return; + } + + // + // Wait for activation to complete. This is necessary to not + // get out of order locator updates. + // + while(_waitForActivate) + { + wait(); + } + + if(_routerInfo) + { + // + // Remove entry from the router manager. + // + _instance->routerManager()->erase(_routerInfo->getRouter()); + + // + // Clear this object adapter with the router. + // + _routerInfo->setAdapter(0); + } + incomingConnectionFactories = _incomingConnectionFactories; - outgoingConnectionFactory = _instance->outgoingConnectionFactory(); - locatorInfo = _locatorInfo; + outgoingConnectionFactory = _instance->outgoingConnectionFactory(); + locatorInfo = _locatorInfo; - _deactivated = true; + _deactivated = true; - notifyAll(); + notifyAll(); } try { - updateLocatorRegistry(locatorInfo, 0, false); + updateLocatorRegistry(locatorInfo, 0, false); } catch(const Ice::LocalException&) { - // - // We can't throw exceptions in deactivate so we ignore - // failures to update the locator registry. - // + // + // We can't throw exceptions in deactivate so we ignore + // failures to update the locator registry. + // } // @@ -244,7 +244,7 @@ Ice::ObjectAdapterI::deactivate() // message. // for_each(incomingConnectionFactories.begin(), incomingConnectionFactories.end(), - Ice::voidMemFun(&IncomingConnectionFactory::destroy)); + Ice::voidMemFun(&IncomingConnectionFactory::destroy)); // // Must be called outside the thread synchronization, because @@ -260,23 +260,23 @@ Ice::ObjectAdapterI::waitForDeactivate() vector incomingConnectionFactories; { - IceUtil::Monitor::Lock sync(*this); - - if(_destroyed) - { - return; - } - - // - // Wait for deactivation of the adapter itself, and for - // the return of all direct method calls using this adapter. - // - while(!_deactivated || _directCount > 0) - { - wait(); - } - - incomingConnectionFactories = _incomingConnectionFactories; + IceUtil::Monitor::Lock sync(*this); + + if(_destroyed) + { + return; + } + + // + // Wait for deactivation of the adapter itself, and for + // the return of all direct method calls using this adapter. + // + while(!_deactivated || _directCount > 0) + { + wait(); + } + + incomingConnectionFactories = _incomingConnectionFactories; } // @@ -284,7 +284,7 @@ Ice::ObjectAdapterI::waitForDeactivate() // finished. // for_each(incomingConnectionFactories.begin(), incomingConnectionFactories.end(), - Ice::voidMemFun(&IncomingConnectionFactory::waitUntilFinished)); + Ice::voidMemFun(&IncomingConnectionFactory::waitUntilFinished)); } bool @@ -299,26 +299,26 @@ void Ice::ObjectAdapterI::destroy() { { - IceUtil::Monitor::Lock sync(*this); - - // - // Another thread is in the process of destroying the object - // adapter. Wait for it to finish. - // - while(_destroying) - { - wait(); - } - - // - // Object adpater is already destroyed. - // - if(_destroyed) - { - return; - } - - _destroying = true; + IceUtil::Monitor::Lock sync(*this); + + // + // Another thread is in the process of destroying the object + // adapter. Wait for it to finish. + // + while(_destroying) + { + wait(); + } + + // + // Object adpater is already destroyed. + // + if(_destroyed) + { + return; + } + + _destroying = true; } // @@ -338,41 +338,41 @@ Ice::ObjectAdapterI::destroy() // if(_threadPool) { - _threadPool->destroy(); - _threadPool->joinWithAllThreads(); + _threadPool->destroy(); + _threadPool->joinWithAllThreads(); } ObjectAdapterFactoryPtr objectAdapterFactory; { - IceUtil::Monitor::Lock sync(*this); - - // - // Signal that destroy is complete. - // - _destroying = false; - _destroyed = true; - notifyAll(); - - // - // We're done, now we can throw away all incoming connection - // factories. - // - _incomingConnectionFactories.clear(); - - // - // Remove object references (some of them cyclic). - // - _instance = 0; - _threadPool = 0; - _communicator = 0; - _routerEndpoints.clear(); - _routerInfo = 0; - _publishedEndpoints.clear(); - _locatorInfo = 0; - - objectAdapterFactory = _objectAdapterFactory; - _objectAdapterFactory = 0; + IceUtil::Monitor::Lock sync(*this); + + // + // Signal that destroy is complete. + // + _destroying = false; + _destroyed = true; + notifyAll(); + + // + // We're done, now we can throw away all incoming connection + // factories. + // + _incomingConnectionFactories.clear(); + + // + // Remove object references (some of them cyclic). + // + _instance = 0; + _threadPool = 0; + _communicator = 0; + _routerEndpoints.clear(); + _routerInfo = 0; + _publishedEndpoints.clear(); + _locatorInfo = 0; + + objectAdapterFactory = _objectAdapterFactory; + _objectAdapterFactory = 0; } if(objectAdapterFactory) @@ -549,8 +549,8 @@ Ice::ObjectAdapterI::createReverseProxy(const Identity& ident) const vector::const_iterator p; for(p = _incomingConnectionFactories.begin(); p != _incomingConnectionFactories.end(); ++p) { - list cons = (*p)->connections(); - copy(cons.begin(), cons.end(), back_inserter(connections)); + list cons = (*p)->connections(); + copy(cons.begin(), cons.end(), back_inserter(connections)); } // @@ -558,7 +558,7 @@ Ice::ObjectAdapterI::createReverseProxy(const Identity& ident) const // reference. // ReferencePtr ref = _instance->referenceFactory()->create(ident, _instance->getDefaultContext(), - "", Reference::ModeTwoway, connections); + "", Reference::ModeTwoway, connections); return _instance->proxyFactory()->referenceToProxy(ref); } @@ -582,32 +582,32 @@ Ice::ObjectAdapterI::isLocal(const ObjectPrx& proxy) const IndirectReferencePtr ir = IndirectReferencePtr::dynamicCast(ref); if(ir) { - if(!ir->getAdapterId().empty()) - { - // - // Proxy is local if the reference adapter id matches this - // adapter id. - // - return ir->getAdapterId() == _id; - } - - // - // Get Locator endpoint information for indirect references. - // - LocatorInfoPtr info = ir->getLocatorInfo(); - if(info) - { - bool isCached; - endpoints = info->getEndpoints(ir, ir->getLocatorCacheTimeout(), isCached); - } - else - { - return false; - } + if(!ir->getAdapterId().empty()) + { + // + // Proxy is local if the reference adapter id matches this + // adapter id. + // + return ir->getAdapterId() == _id; + } + + // + // Get Locator endpoint information for indirect references. + // + LocatorInfoPtr info = ir->getLocatorInfo(); + if(info) + { + bool isCached; + endpoints = info->getEndpoints(ir, ir->getLocatorCacheTimeout(), isCached); + } + else + { + return false; + } } else { - endpoints = ref->getEndpoints(); + endpoints = ref->getEndpoints(); } IceUtil::Monitor::Lock sync(*this); @@ -620,14 +620,14 @@ Ice::ObjectAdapterI::isLocal(const ObjectPrx& proxy) const // for(p = endpoints.begin(); p != endpoints.end(); ++p) { - vector::const_iterator q; - for(q = _incomingConnectionFactories.begin(); q != _incomingConnectionFactories.end(); ++q) - { - if((*q)->equivalent(*p)) - { - return true; - } - } + vector::const_iterator q; + for(q = _incomingConnectionFactories.begin(); q != _incomingConnectionFactories.end(); ++q) + { + if((*q)->equivalent(*p)) + { + return true; + } + } } // @@ -639,10 +639,10 @@ Ice::ObjectAdapterI::isLocal(const ObjectPrx& proxy) const { for(p = endpoints.begin(); p != endpoints.end(); ++p) { - if(binary_search(_routerEndpoints.begin(), _routerEndpoints.end(), *p)) // _routerEndpoints is sorted. - { - return true; - } + if(binary_search(_routerEndpoints.begin(), _routerEndpoints.end(), *p)) // _routerEndpoints is sorted. + { + return true; + } } } @@ -654,8 +654,8 @@ Ice::ObjectAdapterI::flushBatchRequests() { vector f; { - IceUtil::Monitor::Lock sync(*this); - f = _incomingConnectionFactories; + IceUtil::Monitor::Lock sync(*this); + f = _incomingConnectionFactories; } for_each(f.begin(), f.end(), Ice::voidMemFun(&IncomingConnectionFactory::flushBatchRequests)); } @@ -683,7 +683,7 @@ Ice::ObjectAdapterI::decDirectCount() assert(_directCount > 0); if(--_directCount == 0) { - notifyAll(); + notifyAll(); } } @@ -700,11 +700,11 @@ Ice::ObjectAdapterI::getThreadPool() const if(_threadPool) { - return _threadPool; + return _threadPool; } else { - return _instance->serverThreadPool(); + return _instance->serverThreadPool(); } } @@ -736,8 +736,8 @@ Ice::ObjectAdapterI::getThreadPerConnectionStackSize() const } Ice::ObjectAdapterI::ObjectAdapterI(const InstancePtr& instance, const CommunicatorPtr& communicator, - const ObjectAdapterFactoryPtr& objectAdapterFactory, const string& name, - const string& endpointInfo, const RouterPrx& router, bool noConfig) : + const ObjectAdapterFactoryPtr& objectAdapterFactory, const string& name, + const string& endpointInfo, const RouterPrx& router, bool noConfig) : _deactivated(false), _instance(instance), _communicator(communicator), @@ -769,28 +769,28 @@ Ice::ObjectAdapterI::ObjectAdapterI(const InstancePtr& instance, const Communica { StringSeq props = filterProperties(_propertyPrefix + _name + "."); if(oldProps.size() == 0 && props.size() == 0) - { + { InitializationException ex(__FILE__, __LINE__); - ex.reason = "object adapter \"" + _name + "\" requires configuration."; - throw ex; + ex.reason = "object adapter \"" + _name + "\" requires configuration."; + throw ex; } } if(oldProps.size() != 0) { - Warning out(_instance->initializationData().logger); - out << "The following properties have been deprecated, please prepend \"Ice.OA.\":"; - for(unsigned int i = 0; i < oldProps.size(); ++i) - { - out << "\n " << oldProps[i]; - } + Warning out(_instance->initializationData().logger); + out << "The following properties have been deprecated, please prepend \"Ice.OA.\":"; + for(unsigned int i = 0; i < oldProps.size(); ++i) + { + out << "\n " << oldProps[i]; + } } const_cast(_id) = properties->getPropertyWithDefault(_propertyPrefix + _name + ".AdapterId", - properties->getProperty(_name + ".AdapterId")); + properties->getProperty(_name + ".AdapterId")); const_cast(_replicaGroupId) = - properties->getPropertyWithDefault(_propertyPrefix + _name + ".ReplicaGroupId", - properties->getProperty(_name + ".ReplicaGroupId")); + properties->getPropertyWithDefault(_propertyPrefix + _name + ".ReplicaGroupId", + properties->getProperty(_name + ".ReplicaGroupId")); __setNoDelete(true); try @@ -811,7 +811,7 @@ Ice::ObjectAdapterI::ObjectAdapterI(const InstancePtr& instance, const Communica if(_threadPerConnection && (threadPoolSize > 0 || threadPoolSizeMax > 0)) { InitializationException ex(__FILE__, __LINE__); - ex.reason = "object adapter \"" + _name + "\" cannot be configured for both\n" + ex.reason = "object adapter \"" + _name + "\" cannot be configured for both\n" "thread pool and thread per connection"; throw ex; } @@ -832,138 +832,138 @@ Ice::ObjectAdapterI::ObjectAdapterI(const InstancePtr& instance, const Communica // Create the per-adapter thread pool, if necessary. This is done before the creation of the incoming // connection factory as the thread pool is needed during creation for the call to incFdsInUse. // - if(threadPoolSize > 0 || threadPoolSizeMax > 0) - { - if(!properties->getProperty(_propertyPrefix + _name + ".ThreadPool.Size").empty() || - !properties->getProperty(_propertyPrefix + _name + ".ThreadPool.SizeMax").empty()) - { + if(threadPoolSize > 0 || threadPoolSizeMax > 0) + { + if(!properties->getProperty(_propertyPrefix + _name + ".ThreadPool.Size").empty() || + !properties->getProperty(_propertyPrefix + _name + ".ThreadPool.SizeMax").empty()) + { _threadPool = new ThreadPool(_instance, _propertyPrefix + _name + ".ThreadPool", 0); - } - else - { + } + else + { _threadPool = new ThreadPool(_instance, _name + ".ThreadPool", 0); - } - } - - if(!router) - { - const_cast(router) = RouterPrx::uncheckedCast( - _instance->proxyFactory()->propertyToProxy(_propertyPrefix + _name + ".Router")); - if(!router) - { - const_cast(router) = RouterPrx::uncheckedCast( - _instance->proxyFactory()->propertyToProxy(_name + ".Router")); - } - } - if(router) - { + } + } + + if(!router) + { + const_cast(router) = RouterPrx::uncheckedCast( + _instance->proxyFactory()->propertyToProxy(_propertyPrefix + _name + ".Router")); + if(!router) + { + const_cast(router) = RouterPrx::uncheckedCast( + _instance->proxyFactory()->propertyToProxy(_name + ".Router")); + } + } + if(router) + { _routerInfo = _instance->routerManager()->get(router); if(_routerInfo) { - // - // Make sure this router is not already registered with another adapter. - // - if(_routerInfo->getAdapter()) - { - throw AlreadyRegisteredException(__FILE__, __LINE__, "object adapter with router", - _instance->identityToString(router->ice_getIdentity())); - } - - // - // Add the router's server proxy endpoints to this object - // adapter. - // - vector endpoints = _routerInfo->getServerEndpoints(); - copy(endpoints.begin(), endpoints.end(), back_inserter(_routerEndpoints)); - sort(_routerEndpoints.begin(), _routerEndpoints.end()); // Must be sorted. - _routerEndpoints.erase(unique(_routerEndpoints.begin(), _routerEndpoints.end()), - _routerEndpoints.end()); - - // - // Associate this object adapter with the router. This way, - // new outgoing connections to the router's client proxy will - // use this object adapter for callbacks. - // - _routerInfo->setAdapter(this); - - // - // Also modify all existing outgoing connections to the - // router's client proxy to use this object adapter for - // callbacks. - // - _instance->outgoingConnectionFactory()->setRouterInfo(_routerInfo); + // + // Make sure this router is not already registered with another adapter. + // + if(_routerInfo->getAdapter()) + { + throw AlreadyRegisteredException(__FILE__, __LINE__, "object adapter with router", + _instance->identityToString(router->ice_getIdentity())); + } + + // + // Add the router's server proxy endpoints to this object + // adapter. + // + vector endpoints = _routerInfo->getServerEndpoints(); + copy(endpoints.begin(), endpoints.end(), back_inserter(_routerEndpoints)); + sort(_routerEndpoints.begin(), _routerEndpoints.end()); // Must be sorted. + _routerEndpoints.erase(unique(_routerEndpoints.begin(), _routerEndpoints.end()), + _routerEndpoints.end()); + + // + // Associate this object adapter with the router. This way, + // new outgoing connections to the router's client proxy will + // use this object adapter for callbacks. + // + _routerInfo->setAdapter(this); + + // + // Also modify all existing outgoing connections to the + // router's client proxy to use this object adapter for + // callbacks. + // + _instance->outgoingConnectionFactory()->setRouterInfo(_routerInfo); + } + } + else + { + // + // Parse the endpoints, but don't store them in the adapter. + // The connection factory might change it, for example, to + // fill in the real port number. + // + vector endpoints; + if(endpointInfo.empty()) + { + endpoints = parseEndpoints(properties->getPropertyWithDefault(_propertyPrefix + _name + ".Endpoints", + properties->getProperty(_name + ".Endpoints"))); } - } - else - { - // - // Parse the endpoints, but don't store them in the adapter. - // The connection factory might change it, for example, to - // fill in the real port number. - // - vector endpoints; - if(endpointInfo.empty()) - { - endpoints = parseEndpoints(properties->getPropertyWithDefault(_propertyPrefix + _name + ".Endpoints", - properties->getProperty(_name + ".Endpoints"))); - } - else - { - endpoints = parseEndpoints(endpointInfo); - } - for(vector::iterator p = endpoints.begin(); p != endpoints.end(); ++p) - { - _incomingConnectionFactories.push_back(new IncomingConnectionFactory(instance, *p, this, _name)); - } - if(endpoints.empty()) - { - TraceLevelsPtr tl = _instance->traceLevels(); - if(tl->network >= 2) - { - Trace out(_instance->initializationData().logger, tl->networkCat); - out << "created adapter `" << name << "' without endpoints"; - } - } - - // - // Parse published endpoints. If set, these are used in proxies - // instead of the connection factory endpoints. - // - string endpts = properties->getPropertyWithDefault(_propertyPrefix + _name + ".PublishedEndpoints", - properties->getProperty(_name + ".PublishedEndpoints")); - _publishedEndpoints = parseEndpoints(endpts); - if(_publishedEndpoints.empty()) - { - transform(_incomingConnectionFactories.begin(), _incomingConnectionFactories.end(), - back_inserter(_publishedEndpoints), Ice::constMemFun(&IncomingConnectionFactory::endpoint)); - } - - // - // Filter out any endpoints that are not meant to be published. - // - _publishedEndpoints.erase(remove_if(_publishedEndpoints.begin(), _publishedEndpoints.end(), - not1(Ice::constMemFun(&EndpointI::publish))), _publishedEndpoints.end()); - } - - string locatorProperty = _propertyPrefix + _name + ".Locator"; - if(!properties->getProperty(locatorProperty).empty()) - { - setLocator(LocatorPrx::uncheckedCast(_instance->proxyFactory()->propertyToProxy(locatorProperty))); - } - else if(!properties->getProperty(_name + ".Locator").empty()) - { - setLocator(LocatorPrx::uncheckedCast(_instance->proxyFactory()->propertyToProxy(_name + ".Locator"))); - } - else - { - setLocator(_instance->referenceFactory()->getDefaultLocator()); - } + else + { + endpoints = parseEndpoints(endpointInfo); + } + for(vector::iterator p = endpoints.begin(); p != endpoints.end(); ++p) + { + _incomingConnectionFactories.push_back(new IncomingConnectionFactory(instance, *p, this, _name)); + } + if(endpoints.empty()) + { + TraceLevelsPtr tl = _instance->traceLevels(); + if(tl->network >= 2) + { + Trace out(_instance->initializationData().logger, tl->networkCat); + out << "created adapter `" << name << "' without endpoints"; + } + } + + // + // Parse published endpoints. If set, these are used in proxies + // instead of the connection factory endpoints. + // + string endpts = properties->getPropertyWithDefault(_propertyPrefix + _name + ".PublishedEndpoints", + properties->getProperty(_name + ".PublishedEndpoints")); + _publishedEndpoints = parseEndpoints(endpts); + if(_publishedEndpoints.empty()) + { + transform(_incomingConnectionFactories.begin(), _incomingConnectionFactories.end(), + back_inserter(_publishedEndpoints), Ice::constMemFun(&IncomingConnectionFactory::endpoint)); + } + + // + // Filter out any endpoints that are not meant to be published. + // + _publishedEndpoints.erase(remove_if(_publishedEndpoints.begin(), _publishedEndpoints.end(), + not1(Ice::constMemFun(&EndpointI::publish))), _publishedEndpoints.end()); + } + + string locatorProperty = _propertyPrefix + _name + ".Locator"; + if(!properties->getProperty(locatorProperty).empty()) + { + setLocator(LocatorPrx::uncheckedCast(_instance->proxyFactory()->propertyToProxy(locatorProperty))); + } + else if(!properties->getProperty(_name + ".Locator").empty()) + { + setLocator(LocatorPrx::uncheckedCast(_instance->proxyFactory()->propertyToProxy(_name + ".Locator"))); + } + else + { + setLocator(_instance->referenceFactory()->getDefaultLocator()); + } } catch(...) { - destroy(); - __setNoDelete(false); - throw; + destroy(); + __setNoDelete(false); + throw; } __setNoDelete(false); } @@ -972,22 +972,22 @@ Ice::ObjectAdapterI::~ObjectAdapterI() { if(!_deactivated) { - Warning out(_instance->initializationData().logger); - out << "object adapter `" << getName() << "' has not been deactivated"; + Warning out(_instance->initializationData().logger); + out << "object adapter `" << getName() << "' has not been deactivated"; } else if(!_destroyed) { - Warning out(_instance->initializationData().logger); - out << "object adapter `" << getName() << "' has not been destroyed"; + Warning out(_instance->initializationData().logger); + out << "object adapter `" << getName() << "' has not been destroyed"; } else { - //assert(!_servantManager); // We don't clear this reference, it needs to be immutable. - assert(!_threadPool); - assert(!_communicator); - assert(_incomingConnectionFactories.empty()); - assert(_directCount == 0); - assert(!_waitForActivate); + //assert(!_servantManager); // We don't clear this reference, it needs to be immutable. + assert(!_threadPool); + assert(!_communicator); + assert(_incomingConnectionFactories.empty()); + assert(_directCount == 0); + assert(!_waitForActivate); } } @@ -996,15 +996,15 @@ Ice::ObjectAdapterI::newProxy(const Identity& ident, const string& facet) const { if(_id.empty()) { - return newDirectProxy(ident, facet); + return newDirectProxy(ident, facet); } else if(_replicaGroupId.empty()) { - return newIndirectProxy(ident, facet, _id); + return newIndirectProxy(ident, facet, _id); } else { - return newIndirectProxy(ident, facet, _replicaGroupId); + return newIndirectProxy(ident, facet, _replicaGroupId); } } @@ -1024,9 +1024,9 @@ Ice::ObjectAdapterI::newDirectProxy(const Identity& ident, const string& facet) // Create a reference and return a proxy for this reference. // ReferencePtr ref = _instance->referenceFactory()->create( - ident, _instance->getDefaultContext(), facet, Reference::ModeTwoway, false, - _instance->defaultsAndOverrides()->defaultPreferSecure, endpoints, 0, - _instance->defaultsAndOverrides()->defaultCollocationOptimization, true, + ident, _instance->getDefaultContext(), facet, Reference::ModeTwoway, false, + _instance->defaultsAndOverrides()->defaultPreferSecure, endpoints, 0, + _instance->defaultsAndOverrides()->defaultCollocationOptimization, true, _instance->defaultsAndOverrides()->defaultEndpointSelection, _instance->threadPerConnection()); return _instance->proxyFactory()->referenceToProxy(ref); @@ -1039,11 +1039,11 @@ Ice::ObjectAdapterI::newIndirectProxy(const Identity& ident, const string& facet // Create an indirect reference with the given adapter id. // ReferencePtr ref = _instance->referenceFactory()->create( - ident, _instance->getDefaultContext(), facet, Reference::ModeTwoway, false, - _instance->defaultsAndOverrides()->defaultPreferSecure, id, 0, - _locatorInfo, _instance->defaultsAndOverrides()->defaultCollocationOptimization, true, + ident, _instance->getDefaultContext(), facet, Reference::ModeTwoway, false, + _instance->defaultsAndOverrides()->defaultPreferSecure, id, 0, + _locatorInfo, _instance->defaultsAndOverrides()->defaultCollocationOptimization, true, _instance->defaultsAndOverrides()->defaultEndpointSelection, _instance->threadPerConnection(), - _instance->defaultsAndOverrides()->defaultLocatorCacheTimeout); + _instance->defaultsAndOverrides()->defaultLocatorCacheTimeout); // // Return a proxy for the reference. @@ -1056,9 +1056,9 @@ Ice::ObjectAdapterI::checkForDeactivation() const { if(_deactivated) { - ObjectAdapterDeactivatedException ex(__FILE__, __LINE__); - ex.name = getName(); - throw ex; + ObjectAdapterDeactivatedException ex(__FILE__, __LINE__); + ex.name = getName(); + throw ex; } } @@ -1085,38 +1085,38 @@ Ice::ObjectAdapterI::parseEndpoints(const string& str) const vector endpoints; while(end < endpts.length()) { - const string delim = " \t\n\r"; - - beg = endpts.find_first_not_of(delim, end); - if(beg == string::npos) - { - break; - } - - end = endpts.find(':', beg); - if(end == string::npos) - { - end = endpts.length(); - } - - if(end == beg) - { - ++end; - continue; - } - - string s = endpts.substr(beg, end - beg); - EndpointIPtr endp = _instance->endpointFactoryManager()->create(s); - if(endp == 0) - { - EndpointParseException ex(__FILE__, __LINE__); - ex.str = s; - throw ex; - } - vector endps = endp->expand(true); - endpoints.insert(endpoints.end(), endps.begin(), endps.end()); - - ++end; + const string delim = " \t\n\r"; + + beg = endpts.find_first_not_of(delim, end); + if(beg == string::npos) + { + break; + } + + end = endpts.find(':', beg); + if(end == string::npos) + { + end = endpts.length(); + } + + if(end == beg) + { + ++end; + continue; + } + + string s = endpts.substr(beg, end - beg); + EndpointIPtr endp = _instance->endpointFactoryManager()->create(s); + if(endp == 0) + { + EndpointParseException ex(__FILE__, __LINE__); + ex.str = s; + throw ex; + } + vector endps = endp->expand(true); + endpoints.insert(endpoints.end(), endps.begin(), endps.end()); + + ++end; } return endpoints; @@ -1124,12 +1124,12 @@ Ice::ObjectAdapterI::parseEndpoints(const string& str) const void ObjectAdapterI::updateLocatorRegistry(const IceInternal::LocatorInfoPtr& locatorInfo, - const Ice::ObjectPrx& proxy, - bool registerProcess) + const Ice::ObjectPrx& proxy, + bool registerProcess) { if(!registerProcess && _id.empty()) { - return; // Nothing to update. + return; // Nothing to update. } // @@ -1147,76 +1147,76 @@ ObjectAdapterI::updateLocatorRegistry(const IceInternal::LocatorInfoPtr& locator string serverId; if(registerProcess) { - assert(_instance); - serverId = _instance->initializationData().properties->getProperty("Ice.ServerId"); - - if(!locatorRegistry) - { - Warning out(_instance->initializationData().logger); - out << "object adapter `" << getName() << "' cannot register the process without a locator registry"; - } - else if(serverId.empty()) - { - Warning out(_instance->initializationData().logger); - out << "object adapter `" << getName() << "' cannot register the process without a value for Ice.ServerId"; - } + assert(_instance); + serverId = _instance->initializationData().properties->getProperty("Ice.ServerId"); + + if(!locatorRegistry) + { + Warning out(_instance->initializationData().logger); + out << "object adapter `" << getName() << "' cannot register the process without a locator registry"; + } + else if(serverId.empty()) + { + Warning out(_instance->initializationData().logger); + out << "object adapter `" << getName() << "' cannot register the process without a value for Ice.ServerId"; + } } if(!locatorRegistry) { - return; + return; } if(!_id.empty()) { - try - { - if(_replicaGroupId.empty()) - { - locatorRegistry->setAdapterDirectProxy(_id, proxy); - } - else - { - locatorRegistry->setReplicatedAdapterDirectProxy(_id, _replicaGroupId, proxy); - } - } - catch(const AdapterNotFoundException&) - { - NotRegisteredException ex(__FILE__, __LINE__); - ex.kindOfObject = "object adapter"; - ex.id = _id; - throw ex; - } - catch(const InvalidReplicaGroupIdException&) - { - NotRegisteredException ex(__FILE__, __LINE__); - ex.kindOfObject = "replica group"; - ex.id = _replicaGroupId; - throw ex; - } - catch(const AdapterAlreadyActiveException&) - { - ObjectAdapterIdInUseException ex(__FILE__, __LINE__); - ex.id = _id; - throw ex; - } - } + try + { + if(_replicaGroupId.empty()) + { + locatorRegistry->setAdapterDirectProxy(_id, proxy); + } + else + { + locatorRegistry->setReplicatedAdapterDirectProxy(_id, _replicaGroupId, proxy); + } + } + catch(const AdapterNotFoundException&) + { + NotRegisteredException ex(__FILE__, __LINE__); + ex.kindOfObject = "object adapter"; + ex.id = _id; + throw ex; + } + catch(const InvalidReplicaGroupIdException&) + { + NotRegisteredException ex(__FILE__, __LINE__); + ex.kindOfObject = "replica group"; + ex.id = _replicaGroupId; + throw ex; + } + catch(const AdapterAlreadyActiveException&) + { + ObjectAdapterIdInUseException ex(__FILE__, __LINE__); + ex.id = _id; + throw ex; + } + } if(registerProcess && !serverId.empty()) { - try - { - ProcessPtr servant = new ProcessI(_communicator); - Ice::ObjectPrx process = createDirectProxy(addWithUUID(servant)->ice_getIdentity()); - locatorRegistry->setServerProcessProxy(serverId, ProcessPrx::uncheckedCast(process)); - } - catch(const ServerNotFoundException&) - { - NotRegisteredException ex(__FILE__, __LINE__); - ex.kindOfObject = "server"; - ex.id = serverId; - throw ex; - } + try + { + ProcessPtr servant = new ProcessI(_communicator); + Ice::ObjectPrx process = createDirectProxy(addWithUUID(servant)->ice_getIdentity()); + locatorRegistry->setServerProcessProxy(serverId, ProcessPrx::uncheckedCast(process)); + } + catch(const ServerNotFoundException&) + { + NotRegisteredException ex(__FILE__, __LINE__); + ex.kindOfObject = "server"; + ex.id = serverId; + throw ex; + } } } @@ -1225,17 +1225,17 @@ Ice::ObjectAdapterI::filterProperties(const string& prefix) { static const string suffixes[] = { - "AdapterId", - "Endpoints", - "Locator", - "PublishedEndpoints", - "RegisterProcess", - "ReplicaGroupId", - "Router", - "ThreadPool.Size", - "ThreadPool.SizeMax", - "ThreadPool.SizeWarn", - "ThreadPool.StackSize" + "AdapterId", + "Endpoints", + "Locator", + "PublishedEndpoints", + "RegisterProcess", + "ReplicaGroupId", + "Router", + "ThreadPool.Size", + "ThreadPool.SizeMax", + "ThreadPool.SizeWarn", + "ThreadPool.StackSize" }; StringSeq propertySet; @@ -1243,9 +1243,9 @@ Ice::ObjectAdapterI::filterProperties(const string& prefix) for(unsigned int i = 0; i < sizeof(suffixes)/sizeof(*suffixes); ++i) { if(props.find(prefix + suffixes[i]) != props.end()) - { - propertySet.push_back(prefix + suffixes[i]); - } + { + propertySet.push_back(prefix + suffixes[i]); + } } return propertySet; @@ -1267,15 +1267,15 @@ Ice::ObjectAdapterI::ProcessI::writeMessage(const string& message, Int fd, const { switch(fd) { - case 1: - { - cout << message << endl; - break; - } - case 2: - { - cerr << message << endl; - break; - } + case 1: + { + cout << message << endl; + break; + } + case 2: + { + cerr << message << endl; + break; + } } } diff --git a/cpp/src/Ice/ObjectAdapterI.h b/cpp/src/Ice/ObjectAdapterI.h index e9b6fe0cb6f..b61b7e3e1a7 100644 --- a/cpp/src/Ice/ObjectAdapterI.h +++ b/cpp/src/Ice/ObjectAdapterI.h @@ -89,8 +89,8 @@ public: private: ObjectAdapterI(const IceInternal::InstancePtr&, const CommunicatorPtr&, - const IceInternal::ObjectAdapterFactoryPtr&, const std::string&, const std::string&, - const RouterPrx&, bool); + const IceInternal::ObjectAdapterFactoryPtr&, const std::string&, const std::string&, + const RouterPrx&, bool); virtual ~ObjectAdapterI(); friend class IceInternal::ObjectAdapterFactory; @@ -135,7 +135,7 @@ private: ProcessI(const CommunicatorPtr&); virtual void shutdown(const Current&); - virtual void writeMessage(const std::string&, Int, const Current&); + virtual void writeMessage(const std::string&, Int, const Current&); private: diff --git a/cpp/src/Ice/ObjectFactoryManager.cpp b/cpp/src/Ice/ObjectFactoryManager.cpp index c52894f4234..5ed3f2a7d38 100644 --- a/cpp/src/Ice/ObjectFactoryManager.cpp +++ b/cpp/src/Ice/ObjectFactoryManager.cpp @@ -28,10 +28,10 @@ IceInternal::ObjectFactoryManager::add(const ObjectFactoryPtr& factory, const st if((_factoryMapHint != _factoryMap.end() && _factoryMapHint->first == id) || _factoryMap.find(id) != _factoryMap.end()) { - AlreadyRegisteredException ex(__FILE__, __LINE__); - ex.kindOfObject = "object factory"; - ex.id = id; - throw ex; + AlreadyRegisteredException ex(__FILE__, __LINE__); + ex.kindOfObject = "object factory"; + ex.id = id; + throw ex; } _factoryMapHint = _factoryMap.insert(_factoryMapHint, pair(id, factory)); @@ -42,41 +42,41 @@ IceInternal::ObjectFactoryManager::remove(const string& id) { ObjectFactoryPtr factory = 0; { - IceUtil::Mutex::Lock sync(*this); - - FactoryMap::iterator p = _factoryMap.end(); - if(_factoryMapHint != _factoryMap.end()) - { - if(_factoryMapHint->first == id) - { - p = _factoryMapHint; - } - } - - if(p == _factoryMap.end()) - { - p = _factoryMap.find(id); - if(p == _factoryMap.end()) - { - NotRegisteredException ex(__FILE__, __LINE__); - ex.kindOfObject = "object factory"; - ex.id = id; - throw ex; - } - } - assert(p != _factoryMap.end()); - - factory = p->second; - - if(p == _factoryMapHint) - { - _factoryMap.erase(p++); - _factoryMapHint = p; - } - else - { - _factoryMap.erase(p); - } + IceUtil::Mutex::Lock sync(*this); + + FactoryMap::iterator p = _factoryMap.end(); + if(_factoryMapHint != _factoryMap.end()) + { + if(_factoryMapHint->first == id) + { + p = _factoryMapHint; + } + } + + if(p == _factoryMap.end()) + { + p = _factoryMap.find(id); + if(p == _factoryMap.end()) + { + NotRegisteredException ex(__FILE__, __LINE__); + ex.kindOfObject = "object factory"; + ex.id = id; + throw ex; + } + } + assert(p != _factoryMap.end()); + + factory = p->second; + + if(p == _factoryMapHint) + { + _factoryMap.erase(p++); + _factoryMapHint = p; + } + else + { + _factoryMap.erase(p); + } } // @@ -96,25 +96,25 @@ IceInternal::ObjectFactoryManager::find(const string& id) const FactoryMap::iterator p = factoryMap.end(); if(_factoryMapHint != factoryMap.end()) { - if(_factoryMapHint->first == id) - { - p = _factoryMapHint; - } + if(_factoryMapHint->first == id) + { + p = _factoryMapHint; + } } if(p == factoryMap.end()) { - p = factoryMap.find(id); + p = factoryMap.find(id); } if(p != factoryMap.end()) { - _factoryMapHint = p; - return p->second; + _factoryMapHint = p; + return p->second; } else { - return 0; + return 0; } } @@ -128,14 +128,14 @@ IceInternal::ObjectFactoryManager::destroy() { FactoryMap oldMap; { - IceUtil::Mutex::Lock sync(*this); - oldMap.swap(_factoryMap); - _factoryMapHint = _factoryMap.end(); + IceUtil::Mutex::Lock sync(*this); + oldMap.swap(_factoryMap); + _factoryMapHint = _factoryMap.end(); } // // Destroy all outside lock // for_each(oldMap.begin(), oldMap.end(), - Ice::secondVoidMemFun(&ObjectFactory::destroy)); + Ice::secondVoidMemFun(&ObjectFactory::destroy)); } diff --git a/cpp/src/Ice/Outgoing.cpp b/cpp/src/Ice/Outgoing.cpp index c16f5618c05..33a6fc3931a 100644 --- a/cpp/src/Ice/Outgoing.cpp +++ b/cpp/src/Ice/Outgoing.cpp @@ -46,7 +46,7 @@ IceInternal::LocalExceptionWrapper::retry() const } IceInternal::Outgoing::Outgoing(ConnectionI* connection, Reference* ref, const string& operation, - OperationMode mode, const Context* context, bool compress) : + OperationMode mode, const Context* context, bool compress) : _connection(connection), _reference(ref), _state(StateUnsent), @@ -56,80 +56,80 @@ IceInternal::Outgoing::Outgoing(ConnectionI* connection, Reference* ref, const s { switch(_reference->getMode()) { - case Reference::ModeTwoway: - case Reference::ModeOneway: - case Reference::ModeDatagram: - { - _os.writeBlob(requestHdr, sizeof(requestHdr)); - break; - } - - case Reference::ModeBatchOneway: - case Reference::ModeBatchDatagram: - { - _connection->prepareBatchRequest(&_os); - break; - } + case Reference::ModeTwoway: + case Reference::ModeOneway: + case Reference::ModeDatagram: + { + _os.writeBlob(requestHdr, sizeof(requestHdr)); + break; + } + + case Reference::ModeBatchOneway: + case Reference::ModeBatchDatagram: + { + _connection->prepareBatchRequest(&_os); + break; + } } try { - _reference->getIdentity().__write(&_os); - - // - // For compatibility with the old FacetPath. - // - if(_reference->getFacet().empty()) - { - _os.write(static_cast(0), static_cast(0)); - } - else - { - string facet = _reference->getFacet(); - _os.write(&facet, &facet + 1); - } - - _os.write(operation, false); - - _os.write(static_cast(mode)); - - if(context != 0) - { - // - // Explicit context - // - __write(&_os, *context, __U__Context()); - } - else - { - // - // Implicit context - // - const ImplicitContextIPtr& implicitContext = - _reference->getInstance()->getImplicitContext(); - - const Context& prxContext = _reference->getContext()->getValue(); - - if(implicitContext == 0) - { - __write(&_os, prxContext, __U__Context()); - } - else - { - implicitContext->write(prxContext, &_os); - } - } - - // - // Input and output parameters are always sent in an - // encapsulation, which makes it possible to forward requests as - // blobs. - // - _os.startWriteEncaps(); + _reference->getIdentity().__write(&_os); + + // + // For compatibility with the old FacetPath. + // + if(_reference->getFacet().empty()) + { + _os.write(static_cast(0), static_cast(0)); + } + else + { + string facet = _reference->getFacet(); + _os.write(&facet, &facet + 1); + } + + _os.write(operation, false); + + _os.write(static_cast(mode)); + + if(context != 0) + { + // + // Explicit context + // + __write(&_os, *context, __U__Context()); + } + else + { + // + // Implicit context + // + const ImplicitContextIPtr& implicitContext = + _reference->getInstance()->getImplicitContext(); + + const Context& prxContext = _reference->getContext()->getValue(); + + if(implicitContext == 0) + { + __write(&_os, prxContext, __U__Context()); + } + else + { + implicitContext->write(prxContext, &_os); + } + } + + // + // Input and output parameters are always sent in an + // encapsulation, which makes it possible to forward requests as + // blobs. + // + _os.startWriteEncaps(); } catch(const LocalException& ex) { - abort(ex); + abort(ex); } } @@ -142,145 +142,145 @@ IceInternal::Outgoing::invoke() switch(_reference->getMode()) { - case Reference::ModeTwoway: - { - // - // We let all exceptions raised by sending directly - // propagate to the caller, because they can be retried - // without violating "at-most-once". In case of such - // exceptions, the connection object does not call back on - // this object, so we don't need to lock the mutex, keep - // track of state, or save exceptions. - // - _connection->sendRequest(&_os, this, _compress); - - // - // Wait until the request has completed, or until the - // request times out. - // - - bool timedOut = false; - - { - IceUtil::Monitor::Lock sync(_monitor); - - // + case Reference::ModeTwoway: + { + // + // We let all exceptions raised by sending directly + // propagate to the caller, because they can be retried + // without violating "at-most-once". In case of such + // exceptions, the connection object does not call back on + // this object, so we don't need to lock the mutex, keep + // track of state, or save exceptions. + // + _connection->sendRequest(&_os, this, _compress); + + // + // Wait until the request has completed, or until the + // request times out. + // + + bool timedOut = false; + + { + IceUtil::Monitor::Lock sync(_monitor); + + // // It's possible that the request has already // completed, due to a regular response, or because of // an exception. So we only change the state to "in // progress" if it is still "unsent". - // - if(_state == StateUnsent) - { - _state = StateInProgress; - } - - Int timeout = _connection->timeout(); - while(_state == StateInProgress && !timedOut) - { - if(timeout >= 0) - { - _monitor.timedWait(IceUtil::Time::milliSeconds(timeout)); - - if(_state == StateInProgress) - { - timedOut = true; - } - } - else - { - _monitor.wait(); - } - } - } - - if(timedOut) - { - // - // Must be called outside the synchronization of this - // object. - // - _connection->exception(TimeoutException(__FILE__, __LINE__)); - - // - // We must wait until the exception set above has - // propagated to this Outgoing object. - // - { - IceUtil::Monitor::Lock sync(_monitor); - - while(_state == StateInProgress) - { - _monitor.wait(); - } - } - } - - if(_exception.get()) - { - // - // A CloseConnectionException indicates graceful - // server shutdown, and is therefore always repeatable - // without violating "at-most-once". That's because by - // sending a close connection message, the server - // guarantees that all outstanding requests can safely - // be repeated. - // - // An ObjectNotExistException can always be retried as - // well without violating "at-most-once". - // - if(dynamic_cast(_exception.get()) || - dynamic_cast(_exception.get())) - { - _exception->ice_throw(); - } - - // - // Throw the exception wrapped in a - // LocalExceptionWrapper, to indicate that the request - // cannot be resent without potentially violating the - // "at-most-once" principle. - // - throw LocalExceptionWrapper(*_exception.get(), false); - } - - if(_state == StateUserException) - { - return false; - } - - assert(_state == StateOK); - break; - } - - case Reference::ModeOneway: - case Reference::ModeDatagram: - { - // - // For oneway and datagram requests, the connection object - // never calls back on this object. Therefore we don't - // need to lock the mutex or save exceptions. We simply - // let all exceptions from sending propagate to the - // caller, because such exceptions can be retried without - // violating "at-most-once". - // - _state = StateInProgress; - _connection->sendRequest(&_os, 0, _compress); - break; - } - - case Reference::ModeBatchOneway: - case Reference::ModeBatchDatagram: - { - // - // For batch oneways and datagrams, the same rules as for - // regular oneways and datagrams (see comment above) - // apply. - // - _state = StateInProgress; - _connection->finishBatchRequest(&_os, _compress); - break; - } + // + if(_state == StateUnsent) + { + _state = StateInProgress; + } + + Int timeout = _connection->timeout(); + while(_state == StateInProgress && !timedOut) + { + if(timeout >= 0) + { + _monitor.timedWait(IceUtil::Time::milliSeconds(timeout)); + + if(_state == StateInProgress) + { + timedOut = true; + } + } + else + { + _monitor.wait(); + } + } + } + + if(timedOut) + { + // + // Must be called outside the synchronization of this + // object. + // + _connection->exception(TimeoutException(__FILE__, __LINE__)); + + // + // We must wait until the exception set above has + // propagated to this Outgoing object. + // + { + IceUtil::Monitor::Lock sync(_monitor); + + while(_state == StateInProgress) + { + _monitor.wait(); + } + } + } + + if(_exception.get()) + { + // + // A CloseConnectionException indicates graceful + // server shutdown, and is therefore always repeatable + // without violating "at-most-once". That's because by + // sending a close connection message, the server + // guarantees that all outstanding requests can safely + // be repeated. + // + // An ObjectNotExistException can always be retried as + // well without violating "at-most-once". + // + if(dynamic_cast(_exception.get()) || + dynamic_cast(_exception.get())) + { + _exception->ice_throw(); + } + + // + // Throw the exception wrapped in a + // LocalExceptionWrapper, to indicate that the request + // cannot be resent without potentially violating the + // "at-most-once" principle. + // + throw LocalExceptionWrapper(*_exception.get(), false); + } + + if(_state == StateUserException) + { + return false; + } + + assert(_state == StateOK); + break; + } + + case Reference::ModeOneway: + case Reference::ModeDatagram: + { + // + // For oneway and datagram requests, the connection object + // never calls back on this object. Therefore we don't + // need to lock the mutex or save exceptions. We simply + // let all exceptions from sending propagate to the + // caller, because such exceptions can be retried without + // violating "at-most-once". + // + _state = StateInProgress; + _connection->sendRequest(&_os, 0, _compress); + break; + } + + case Reference::ModeBatchOneway: + case Reference::ModeBatchDatagram: + { + // + // For batch oneways and datagrams, the same rules as for + // regular oneways and datagrams (see comment above) + // apply. + // + _state = StateInProgress; + _connection->finishBatchRequest(&_os, _compress); + break; + } } return true; @@ -298,14 +298,14 @@ IceInternal::Outgoing::abort(const LocalException& ex) // if(_reference->getMode() == Reference::ModeBatchOneway || _reference->getMode() == Reference::ModeBatchDatagram) { - _connection->abortBatchRequest(); - - // - // If we abort a batch requests, we cannot retry, because not - // only the batch request that caused the problem will be - // aborted, but all other requests in the batch as well. - // - throw LocalExceptionWrapper(ex, false); + _connection->abortBatchRequest(); + + // + // If we abort a batch requests, we cannot retry, because not + // only the batch request that caused the problem will be + // aborted, but all other requests in the batch as well. + // + throw LocalExceptionWrapper(ex, false); } ex.ice_throw(); @@ -326,152 +326,152 @@ IceInternal::Outgoing::finished(BasicStream& is) switch(static_cast(status)) { - case DispatchOK: - { - // - // Input and output parameters are always sent in an - // encapsulation, which makes it possible to forward - // oneway requests as blobs. - // - _is.startReadEncaps(); - _state = StateOK; // The state must be set last, in case there is an exception. - break; - } - - case DispatchUserException: - { - // - // Input and output parameters are always sent in an - // encapsulation, which makes it possible to forward - // oneway requests as blobs. - // - _is.startReadEncaps(); - _state = StateUserException; // The state must be set last, in case there is an exception. - break; - } - - case DispatchObjectNotExist: - case DispatchFacetNotExist: - case DispatchOperationNotExist: - { - // - // Don't read the exception members directly into the - // exception. Otherwise if reading fails and raises an - // exception, you will have a memory leak. - // - Identity ident; - ident.__read(&_is); - - // - // For compatibility with the old FacetPath. - // - vector facetPath; - _is.read(facetPath); - string facet; - if(!facetPath.empty()) - { - if(facetPath.size() > 1) - { - throw MarshalException(__FILE__, __LINE__); - } - facet.swap(facetPath[0]); - } - - string operation; - _is.read(operation, false); - - RequestFailedException* ex; - switch(static_cast(status)) - { - case DispatchObjectNotExist: - { - ex = new ObjectNotExistException(__FILE__, __LINE__); - break; - } - - case DispatchFacetNotExist: - { - ex = new FacetNotExistException(__FILE__, __LINE__); - break; - } - - case DispatchOperationNotExist: - { - ex = new OperationNotExistException(__FILE__, __LINE__); - break; - } - - default: - { - ex = 0; // To keep the compiler from complaining. - assert(false); - break; - } - } - - ex->id = ident; - ex->facet = facet; - ex->operation = operation; - _exception.reset(ex); - - _state = StateLocalException; // The state must be set last, in case there is an exception. - break; - } - - case DispatchUnknownException: - case DispatchUnknownLocalException: - case DispatchUnknownUserException: - { - // - // Don't read the exception members directly into the - // exception. Otherwise if reading fails and raises an - // exception, you will have a memory leak. - // - string unknown; - _is.read(unknown, false); - - UnknownException* ex; - switch(static_cast(status)) - { - case DispatchUnknownException: - { - ex = new UnknownException(__FILE__, __LINE__); - break; - } - - case DispatchUnknownLocalException: - { - ex = new UnknownLocalException(__FILE__, __LINE__); - break; - } - - case DispatchUnknownUserException: - { - ex = new UnknownUserException(__FILE__, __LINE__); - break; - } - - default: - { - ex = 0; // To keep the compiler from complaining. - assert(false); - break; - } - } - - ex->unknown = unknown; - _exception.reset(ex); - - _state = StateLocalException; // The state must be set last, in case there is an exception. - break; - } - - default: - { - _exception.reset(new UnknownReplyStatusException(__FILE__, __LINE__)); - _state = StateLocalException; - break; - } + case DispatchOK: + { + // + // Input and output parameters are always sent in an + // encapsulation, which makes it possible to forward + // oneway requests as blobs. + // + _is.startReadEncaps(); + _state = StateOK; // The state must be set last, in case there is an exception. + break; + } + + case DispatchUserException: + { + // + // Input and output parameters are always sent in an + // encapsulation, which makes it possible to forward + // oneway requests as blobs. + // + _is.startReadEncaps(); + _state = StateUserException; // The state must be set last, in case there is an exception. + break; + } + + case DispatchObjectNotExist: + case DispatchFacetNotExist: + case DispatchOperationNotExist: + { + // + // Don't read the exception members directly into the + // exception. Otherwise if reading fails and raises an + // exception, you will have a memory leak. + // + Identity ident; + ident.__read(&_is); + + // + // For compatibility with the old FacetPath. + // + vector facetPath; + _is.read(facetPath); + string facet; + if(!facetPath.empty()) + { + if(facetPath.size() > 1) + { + throw MarshalException(__FILE__, __LINE__); + } + facet.swap(facetPath[0]); + } + + string operation; + _is.read(operation, false); + + RequestFailedException* ex; + switch(static_cast(status)) + { + case DispatchObjectNotExist: + { + ex = new ObjectNotExistException(__FILE__, __LINE__); + break; + } + + case DispatchFacetNotExist: + { + ex = new FacetNotExistException(__FILE__, __LINE__); + break; + } + + case DispatchOperationNotExist: + { + ex = new OperationNotExistException(__FILE__, __LINE__); + break; + } + + default: + { + ex = 0; // To keep the compiler from complaining. + assert(false); + break; + } + } + + ex->id = ident; + ex->facet = facet; + ex->operation = operation; + _exception.reset(ex); + + _state = StateLocalException; // The state must be set last, in case there is an exception. + break; + } + + case DispatchUnknownException: + case DispatchUnknownLocalException: + case DispatchUnknownUserException: + { + // + // Don't read the exception members directly into the + // exception. Otherwise if reading fails and raises an + // exception, you will have a memory leak. + // + string unknown; + _is.read(unknown, false); + + UnknownException* ex; + switch(static_cast(status)) + { + case DispatchUnknownException: + { + ex = new UnknownException(__FILE__, __LINE__); + break; + } + + case DispatchUnknownLocalException: + { + ex = new UnknownLocalException(__FILE__, __LINE__); + break; + } + + case DispatchUnknownUserException: + { + ex = new UnknownUserException(__FILE__, __LINE__); + break; + } + + default: + { + ex = 0; // To keep the compiler from complaining. + assert(false); + break; + } + } + + ex->unknown = unknown; + _exception.reset(ex); + + _state = StateLocalException; // The state must be set last, in case there is an exception. + break; + } + + default: + { + _exception.reset(new UnknownReplyStatusException(__FILE__, __LINE__)); + _state = StateLocalException; + break; + } } _monitor.notify(); diff --git a/cpp/src/Ice/OutgoingAsync.cpp b/cpp/src/Ice/OutgoingAsync.cpp index e03c3b58d57..ad53705d9e9 100644 --- a/cpp/src/Ice/OutgoingAsync.cpp +++ b/cpp/src/Ice/OutgoingAsync.cpp @@ -56,148 +56,148 @@ IceInternal::OutgoingAsync::__finished(BasicStream& is) try { - __is->swap(is); - - Byte b; - __is->read(b); - status = static_cast(b); - - switch(status) - { - case DispatchOK: - case DispatchUserException: - { - __is->startReadEncaps(); - break; - } - - case DispatchObjectNotExist: - case DispatchFacetNotExist: - case DispatchOperationNotExist: - { - Identity ident; - ident.__read(__is); - - // - // For compatibility with the old FacetPath. - // - vector facetPath; - __is->read(facetPath); - string facet; - if(!facetPath.empty()) - { - if(facetPath.size() > 1) - { - throw MarshalException(__FILE__, __LINE__); - } - facet.swap(facetPath[0]); - } - - string operation; - __is->read(operation, false); - - auto_ptr ex; - switch(static_cast(status)) - { - case DispatchObjectNotExist: - { - ex.reset(new ObjectNotExistException(__FILE__, __LINE__)); - break; - } - - case DispatchFacetNotExist: - { - ex.reset(new FacetNotExistException(__FILE__, __LINE__)); - break; - } - - case DispatchOperationNotExist: - { - ex.reset(new OperationNotExistException(__FILE__, __LINE__)); - break; - } - - default: - { - assert(false); - break; - } - } - - ex->id = ident; - ex->facet = facet; - ex->operation = operation; - ex->ice_throw(); - } - - case DispatchUnknownException: - case DispatchUnknownLocalException: - case DispatchUnknownUserException: - { - string unknown; - __is->read(unknown, false); - - auto_ptr ex; - switch(static_cast(status)) - { - case DispatchUnknownException: - { - ex.reset(new UnknownException(__FILE__, __LINE__)); - break; - } - - case DispatchUnknownLocalException: - { - ex.reset(new UnknownLocalException(__FILE__, __LINE__)); - break; - } - - case DispatchUnknownUserException: - { - ex.reset(new UnknownUserException(__FILE__, __LINE__)); - break; - } - - default: - { - assert(false); - break; - } - } - - ex->unknown = unknown; - ex->ice_throw(); - } - - default: - { - throw UnknownReplyStatusException(__FILE__, __LINE__); - } - } + __is->swap(is); + + Byte b; + __is->read(b); + status = static_cast(b); + + switch(status) + { + case DispatchOK: + case DispatchUserException: + { + __is->startReadEncaps(); + break; + } + + case DispatchObjectNotExist: + case DispatchFacetNotExist: + case DispatchOperationNotExist: + { + Identity ident; + ident.__read(__is); + + // + // For compatibility with the old FacetPath. + // + vector facetPath; + __is->read(facetPath); + string facet; + if(!facetPath.empty()) + { + if(facetPath.size() > 1) + { + throw MarshalException(__FILE__, __LINE__); + } + facet.swap(facetPath[0]); + } + + string operation; + __is->read(operation, false); + + auto_ptr ex; + switch(static_cast(status)) + { + case DispatchObjectNotExist: + { + ex.reset(new ObjectNotExistException(__FILE__, __LINE__)); + break; + } + + case DispatchFacetNotExist: + { + ex.reset(new FacetNotExistException(__FILE__, __LINE__)); + break; + } + + case DispatchOperationNotExist: + { + ex.reset(new OperationNotExistException(__FILE__, __LINE__)); + break; + } + + default: + { + assert(false); + break; + } + } + + ex->id = ident; + ex->facet = facet; + ex->operation = operation; + ex->ice_throw(); + } + + case DispatchUnknownException: + case DispatchUnknownLocalException: + case DispatchUnknownUserException: + { + string unknown; + __is->read(unknown, false); + + auto_ptr ex; + switch(static_cast(status)) + { + case DispatchUnknownException: + { + ex.reset(new UnknownException(__FILE__, __LINE__)); + break; + } + + case DispatchUnknownLocalException: + { + ex.reset(new UnknownLocalException(__FILE__, __LINE__)); + break; + } + + case DispatchUnknownUserException: + { + ex.reset(new UnknownUserException(__FILE__, __LINE__)); + break; + } + + default: + { + assert(false); + break; + } + } + + ex->unknown = unknown; + ex->ice_throw(); + } + + default: + { + throw UnknownReplyStatusException(__FILE__, __LINE__); + } + } } catch(const LocalException& ex) { - __finished(ex); - return; + __finished(ex); + return; } assert(status == DispatchOK || status == DispatchUserException); try { - __response(status == DispatchOK); + __response(status == DispatchOK); } catch(const Exception& ex) { - warning(ex); + warning(ex); } catch(const std::exception& ex) { - warning(ex); + warning(ex); } catch(...) { - warning(); + warning(); } cleanup(); @@ -210,48 +210,48 @@ IceInternal::OutgoingAsync::__finished(const LocalException& exc) if(__os) // Don't retry if cleanup() was already called. { - // - // A CloseConnectionException indicates graceful server - // shutdown, and is therefore always repeatable without - // violating "at-most-once". That's because by sending a close - // connection message, the server guarantees that all - // outstanding requests can safely be repeated. Otherwise, we - // can also retry if the operation mode is Nonmutating or - // Idempotent. - // - // An ObjectNotExistException can always be retried as - // well without violating "at-most-once". - // - if(_mode == Nonmutating || _mode == Idempotent || dynamic_cast(&exc) || - dynamic_cast(&exc)) - { - try - { - _proxy->__handleException(_delegate, exc, _cnt); - __send(); - return; - } - catch(const LocalException&) - { - } - } + // + // A CloseConnectionException indicates graceful server + // shutdown, and is therefore always repeatable without + // violating "at-most-once". That's because by sending a close + // connection message, the server guarantees that all + // outstanding requests can safely be repeated. Otherwise, we + // can also retry if the operation mode is Nonmutating or + // Idempotent. + // + // An ObjectNotExistException can always be retried as + // well without violating "at-most-once". + // + if(_mode == Nonmutating || _mode == Idempotent || dynamic_cast(&exc) || + dynamic_cast(&exc)) + { + try + { + _proxy->__handleException(_delegate, exc, _cnt); + __send(); + return; + } + catch(const LocalException&) + { + } + } } try { - ice_exception(exc); + ice_exception(exc); } catch(const Exception& ex) { - warning(ex); + warning(ex); } catch(const std::exception& ex) { - warning(ex); + warning(ex); } catch(...) { - warning(); + warning(); } cleanup(); @@ -259,90 +259,90 @@ IceInternal::OutgoingAsync::__finished(const LocalException& exc) void IceInternal::OutgoingAsync::__prepare(const ObjectPrx& prx, const string& operation, OperationMode mode, - const Context* context) + const Context* context) { IceUtil::Monitor::Lock sync(_monitor); try { - // - // We must first wait for other requests to finish. - // - while(__os) - { - _monitor.wait(); - } - - // - // Can't call async via a oneway proxy. - // - prx->__checkTwowayOnly(operation); - - _proxy = prx; + // + // We must first wait for other requests to finish. + // + while(__os) + { + _monitor.wait(); + } + + // + // Can't call async via a oneway proxy. + // + prx->__checkTwowayOnly(operation); + + _proxy = prx; _delegate = 0; - _cnt = 0; - _mode = mode; - - ReferencePtr ref = _proxy->__reference(); - assert(!__is); - __is = new BasicStream(ref->getInstance().get()); - assert(!__os); - __os = new BasicStream(ref->getInstance().get()); - - __os->writeBlob(requestHdr, sizeof(requestHdr)); - - ref->getIdentity().__write(__os); - - // - // For compatibility with the old FacetPath. - // - if(ref->getFacet().empty()) - { - __os->write(static_cast(0), static_cast(0)); - } - else - { - string facet = ref->getFacet(); - __os->write(&facet, &facet + 1); - } - - __os->write(operation, false); - - __os->write(static_cast(_mode)); - - if(context != 0) - { - // - // Explicit context - // - __write(__os, *context, __U__Context()); - } - else - { - // - // Implicit context - // - const ImplicitContextIPtr& implicitContext = - ref->getInstance()->getImplicitContext(); - - const Context& prxContext = ref->getContext()->getValue(); - - if(implicitContext == 0) - { - __write(__os, prxContext, __U__Context()); - } - else - { - implicitContext->write(prxContext, __os); - } - } - - __os->startWriteEncaps(); + _cnt = 0; + _mode = mode; + + ReferencePtr ref = _proxy->__reference(); + assert(!__is); + __is = new BasicStream(ref->getInstance().get()); + assert(!__os); + __os = new BasicStream(ref->getInstance().get()); + + __os->writeBlob(requestHdr, sizeof(requestHdr)); + + ref->getIdentity().__write(__os); + + // + // For compatibility with the old FacetPath. + // + if(ref->getFacet().empty()) + { + __os->write(static_cast(0), static_cast(0)); + } + else + { + string facet = ref->getFacet(); + __os->write(&facet, &facet + 1); + } + + __os->write(operation, false); + + __os->write(static_cast(_mode)); + + if(context != 0) + { + // + // Explicit context + // + __write(__os, *context, __U__Context()); + } + else + { + // + // Implicit context + // + const ImplicitContextIPtr& implicitContext = + ref->getInstance()->getImplicitContext(); + + const Context& prxContext = ref->getContext()->getValue(); + + if(implicitContext == 0) + { + __write(__os, prxContext, __U__Context()); + } + else + { + implicitContext->write(prxContext, __os); + } + } + + __os->startWriteEncaps(); } catch(const LocalException& ex) { - cleanup(); - ex.ice_throw(); + cleanup(); + ex.ice_throw(); } } @@ -353,37 +353,37 @@ IceInternal::OutgoingAsync::__send() try { - while(true) - { - bool compress; - _delegate = _proxy->__getDelegate(); - Ice::ConnectionIPtr connection = _delegate->__getConnection(compress); - try - { - connection->sendAsyncRequest(__os, this, compress); - - // - // Don't do anything after sendAsyncRequest() returned - // without an exception. I such case, there will be - // callbacks, i.e., calls to the __finished() - // functions. Since there is no mutex protection, we - // cannot modify state here and in such callbacks. - // - return; - } - catch(const LocalExceptionWrapper& ex) - { - _proxy->__handleExceptionWrapper(_delegate, ex); - } - catch(const LocalException& ex) - { - _proxy->__handleException(_delegate, ex, _cnt); - } - } + while(true) + { + bool compress; + _delegate = _proxy->__getDelegate(); + Ice::ConnectionIPtr connection = _delegate->__getConnection(compress); + try + { + connection->sendAsyncRequest(__os, this, compress); + + // + // Don't do anything after sendAsyncRequest() returned + // without an exception. I such case, there will be + // callbacks, i.e., calls to the __finished() + // functions. Since there is no mutex protection, we + // cannot modify state here and in such callbacks. + // + return; + } + catch(const LocalExceptionWrapper& ex) + { + _proxy->__handleExceptionWrapper(_delegate, ex); + } + catch(const LocalException& ex) + { + _proxy->__handleException(_delegate, ex, _cnt); + } + } } catch(const LocalException& ex) { - __finished(ex); + __finished(ex); } } @@ -392,13 +392,13 @@ IceInternal::OutgoingAsync::warning(const Exception& ex) const { if(__os) // Don't print anything if cleanup() was already called. { - ReferencePtr ref = _proxy->__reference(); - if(ref->getInstance()->initializationData().properties-> - getPropertyAsIntWithDefault("Ice.Warn.AMICallback", 1) > 0) - { - Warning out(ref->getInstance()->initializationData().logger); - out << "Ice::Exception raised by AMI callback:\n" << ex; - } + ReferencePtr ref = _proxy->__reference(); + if(ref->getInstance()->initializationData().properties-> + getPropertyAsIntWithDefault("Ice.Warn.AMICallback", 1) > 0) + { + Warning out(ref->getInstance()->initializationData().logger); + out << "Ice::Exception raised by AMI callback:\n" << ex; + } } } @@ -407,13 +407,13 @@ IceInternal::OutgoingAsync::warning(const std::exception& ex) const { if(__os) // Don't print anything if cleanup() was already called. { - ReferencePtr ref = _proxy->__reference(); - if(ref->getInstance()->initializationData().properties-> - getPropertyAsIntWithDefault("Ice.Warn.AMICallback", 1) > 0) - { - Warning out(ref->getInstance()->initializationData().logger); - out << "std::exception raised by AMI callback:\n" << ex.what(); - } + ReferencePtr ref = _proxy->__reference(); + if(ref->getInstance()->initializationData().properties-> + getPropertyAsIntWithDefault("Ice.Warn.AMICallback", 1) > 0) + { + Warning out(ref->getInstance()->initializationData().logger); + out << "std::exception raised by AMI callback:\n" << ex.what(); + } } } @@ -422,13 +422,13 @@ IceInternal::OutgoingAsync::warning() const { if(__os) // Don't print anything if cleanup() was already called. { - ReferencePtr ref = _proxy->__reference(); - if(ref->getInstance()->initializationData().properties-> - getPropertyAsIntWithDefault("Ice.Warn.AMICallback", 1) > 0) - { - Warning out(ref->getInstance()->initializationData().logger); - out << "unknown exception raised by AMI callback"; - } + ReferencePtr ref = _proxy->__reference(); + if(ref->getInstance()->initializationData().properties-> + getPropertyAsIntWithDefault("Ice.Warn.AMICallback", 1) > 0) + { + Warning out(ref->getInstance()->initializationData().logger); + out << "unknown exception raised by AMI callback"; + } } } @@ -445,18 +445,18 @@ IceInternal::OutgoingAsync::cleanup() void Ice::AMI_Object_ice_invoke::__invoke(const ObjectPrx& prx, const string& operation, OperationMode mode, - const vector& inParams, const Context* context) + const vector& inParams, const Context* context) { try { - __prepare(prx, operation, mode, context); - __os->writeBlob(inParams); - __os->endWriteEncaps(); + __prepare(prx, operation, mode, context); + __os->writeBlob(inParams); + __os->endWriteEncaps(); } catch(const LocalException& ex) { - __finished(ex); - return; + __finished(ex); + return; } __send(); } @@ -467,31 +467,31 @@ Ice::AMI_Object_ice_invoke::__response(bool ok) // ok == true means no user exce vector outParams; try { - Int sz = __is->getReadEncapsSize(); - __is->readBlob(outParams, sz); + Int sz = __is->getReadEncapsSize(); + __is->readBlob(outParams, sz); } catch(const LocalException& ex) { - __finished(ex); - return; + __finished(ex); + return; } ice_response(ok, outParams); } void Ice::AMI_Array_Object_ice_invoke::__invoke(const ObjectPrx& prx, const string& operation, OperationMode mode, - const pair& inParams, const Context* context) + const pair& inParams, const Context* context) { try { - __prepare(prx, operation, mode, context); - __os->writeBlob(inParams.first, static_cast(inParams.second - inParams.first)); - __os->endWriteEncaps(); + __prepare(prx, operation, mode, context); + __os->writeBlob(inParams.first, static_cast(inParams.second - inParams.first)); + __os->endWriteEncaps(); } catch(const LocalException& ex) { - __finished(ex); - return; + __finished(ex); + return; } __send(); } @@ -502,14 +502,14 @@ Ice::AMI_Array_Object_ice_invoke::__response(bool ok) // ok == true means no use pair outParams; try { - Int sz = __is->getReadEncapsSize(); - __is->readBlob(outParams.first, sz); - outParams.second = outParams.first + sz; + Int sz = __is->getReadEncapsSize(); + __is->readBlob(outParams.first, sz); + outParams.second = outParams.first + sz; } catch(const LocalException& ex) { - __finished(ex); - return; + __finished(ex); + return; } ice_response(ok, outParams); } diff --git a/cpp/src/Ice/PluginManagerI.cpp b/cpp/src/Ice/PluginManagerI.cpp index b199954e938..123c74c0be8 100644 --- a/cpp/src/Ice/PluginManagerI.cpp +++ b/cpp/src/Ice/PluginManagerI.cpp @@ -29,9 +29,9 @@ Ice::PluginManagerI::initializePlugins() { if(_initialized) { - InitializationException ex(__FILE__, __LINE__); - ex.reason = "plugins already initialized"; - throw ex; + InitializationException ex(__FILE__, __LINE__); + ex.reason = "plugins already initialized"; + throw ex; } // @@ -40,30 +40,30 @@ Ice::PluginManagerI::initializePlugins() vector initializedPlugins; try { - for(vector::iterator p = _initOrder.begin(); p != _initOrder.end(); ++p) - { - (*p)->initialize(); - initializedPlugins.push_back(*p); - } + for(vector::iterator p = _initOrder.begin(); p != _initOrder.end(); ++p) + { + (*p)->initialize(); + initializedPlugins.push_back(*p); + } } catch(...) { - // - // Destroy the plugins that have been successfully initialized, in the - // reverse order. - // - for(vector::reverse_iterator p = initializedPlugins.rbegin(); p != initializedPlugins.rend(); ++p) - { - try - { - (*p)->destroy(); - } - catch(...) - { - // Ignore. - } - } - throw; + // + // Destroy the plugins that have been successfully initialized, in the + // reverse order. + // + for(vector::reverse_iterator p = initializedPlugins.rbegin(); p != initializedPlugins.rend(); ++p) + { + try + { + (*p)->destroy(); + } + catch(...) + { + // Ignore. + } + } + throw; } _initialized = true; @@ -76,7 +76,7 @@ Ice::PluginManagerI::getPlugin(const string& name) if(!_communicator) { - throw CommunicatorDestroyedException(__FILE__, __LINE__); + throw CommunicatorDestroyedException(__FILE__, __LINE__); } map::const_iterator r = _plugins.find(name); @@ -98,16 +98,16 @@ Ice::PluginManagerI::addPlugin(const string& name, const PluginPtr& plugin) if(!_communicator) { - throw CommunicatorDestroyedException(__FILE__, __LINE__); + throw CommunicatorDestroyedException(__FILE__, __LINE__); } map::const_iterator r = _plugins.find(name); if(r != _plugins.end()) { AlreadyRegisteredException ex(__FILE__, __LINE__); - ex.kindOfObject = _kindOfObject; - ex.id = name; - throw ex; + ex.kindOfObject = _kindOfObject; + ex.id = name; + throw ex; } _plugins[name] = plugin; } @@ -119,15 +119,15 @@ Ice::PluginManagerI::destroy() if(_communicator) { - map::iterator r; - for(r = _plugins.begin(); r != _plugins.end(); ++r) - { - r->second->destroy(); - r->second = 0; - } - - _logger = 0; - _communicator = 0; + map::iterator r; + for(r = _plugins.begin(); r != _plugins.end(); ++r) + { + r->second->destroy(); + r->second = 0; + } + + _logger = 0; + _communicator = 0; } _libraries = 0; @@ -166,44 +166,44 @@ Ice::PluginManagerI::loadPlugins(int& argc, char* argv[]) string::size_type beg = 0; if(!loadOrder.empty()) { - const string delim = ", \t\n"; - beg = loadOrder.find_first_not_of(delim, beg); - while(beg != string::npos) - { - string name; - string::size_type end = loadOrder.find_first_of(delim, beg); - if(end == string::npos) - { - name = loadOrder.substr(beg); - beg = end; - } - else - { - name = loadOrder.substr(beg, end - beg); - beg = loadOrder.find_first_not_of(delim, end); - } - - map::iterator p = _plugins.find(name); - if(p != _plugins.end()) - { - PluginInitializationException ex(__FILE__, __LINE__); - ex.reason = "plugin `" + name + "' already loaded"; - throw ex; - } - - PropertyDict::iterator q = plugins.find("Ice.Plugin." + name); - if(q != plugins.end()) - { - loadPlugin(name, q->second, cmdArgs, false); - plugins.erase(q); - } - else - { - PluginInitializationException ex(__FILE__, __LINE__); - ex.reason = "plugin `" + name + "' not defined"; - throw ex; - } - } + const string delim = ", \t\n"; + beg = loadOrder.find_first_not_of(delim, beg); + while(beg != string::npos) + { + string name; + string::size_type end = loadOrder.find_first_of(delim, beg); + if(end == string::npos) + { + name = loadOrder.substr(beg); + beg = end; + } + else + { + name = loadOrder.substr(beg, end - beg); + beg = loadOrder.find_first_not_of(delim, end); + } + + map::iterator p = _plugins.find(name); + if(p != _plugins.end()) + { + PluginInitializationException ex(__FILE__, __LINE__); + ex.reason = "plugin `" + name + "' already loaded"; + throw ex; + } + + PropertyDict::iterator q = plugins.find("Ice.Plugin." + name); + if(q != plugins.end()) + { + loadPlugin(name, q->second, cmdArgs, false); + plugins.erase(q); + } + else + { + PluginInitializationException ex(__FILE__, __LINE__); + ex.reason = "plugin `" + name + "' not defined"; + throw ex; + } + } } // @@ -213,7 +213,7 @@ Ice::PluginManagerI::loadPlugins(int& argc, char* argv[]) for(p = plugins.begin(); p != plugins.end(); ++p) { string name = p->first.substr(prefix.size()); - loadPlugin(name, p->second, cmdArgs, false); + loadPlugin(name, p->second, cmdArgs, false); } string loggerStr = properties->getProperty("Ice.LoggerPlugin"); @@ -231,7 +231,7 @@ Ice::PluginManagerI::loadPlugins(int& argc, char* argv[]) // if(properties->getPropertyAsIntWithDefault("Ice.InitPlugins", 1) > 0) { - initializePlugins(); + initializePlugins(); } } @@ -249,26 +249,26 @@ Ice::PluginManagerI::loadPlugin(const string& name, const string& pluginSpec, St string::size_type pos = pluginSpec.find_first_of(delim); if(pos == string::npos) { - entryPoint = pluginSpec; + entryPoint = pluginSpec; } else { - entryPoint = pluginSpec.substr(0, pos); - string::size_type beg = pluginSpec.find_first_not_of(delim, pos); - while(beg != string::npos) - { - string::size_type end = pluginSpec.find_first_of(delim, beg); - if(end == string::npos) - { - args.push_back(pluginSpec.substr(beg)); - beg = end; - } - else - { - args.push_back(pluginSpec.substr(beg, end - beg)); - beg = pluginSpec.find_first_not_of(delim, end); - } - } + entryPoint = pluginSpec.substr(0, pos); + string::size_type beg = pluginSpec.find_first_not_of(delim, pos); + while(beg != string::npos) + { + string::size_type end = pluginSpec.find_first_of(delim, beg); + if(end == string::npos) + { + args.push_back(pluginSpec.substr(beg)); + beg = end; + } + else + { + args.push_back(pluginSpec.substr(beg, end - beg)); + beg = pluginSpec.find_first_not_of(delim, end); + } + } } // @@ -307,15 +307,15 @@ Ice::PluginManagerI::loadPlugin(const string& name, const string& pluginSpec, St if(isLogger) { LOGGER_FACTORY factory = (LOGGER_FACTORY)sym; - _logger = factory(_communicator, args); - if(!_logger) - { + _logger = factory(_communicator, args); + if(!_logger) + { PluginInitializationException e(__FILE__, __LINE__); ostringstream out; out << "failure in entry point `" << entryPoint << "'"; e.reason = out.str(); throw e; - } + } } else { diff --git a/cpp/src/Ice/PropertiesI.cpp b/cpp/src/Ice/PropertiesI.cpp index 84b0f29bce3..86ddccf7cae 100644 --- a/cpp/src/Ice/PropertiesI.cpp +++ b/cpp/src/Ice/PropertiesI.cpp @@ -28,11 +28,11 @@ Ice::PropertiesI::getProperty(const string& key) map::const_iterator p = _properties.find(key); if(p != _properties.end()) { - return p->second; + return p->second; } else { - return string(); + return string(); } } @@ -44,11 +44,11 @@ Ice::PropertiesI::getPropertyWithDefault(const string& key, const string& value) map::const_iterator p = _properties.find(key); if(p != _properties.end()) { - return p->second; + return p->second; } else { - return value; + return value; } } @@ -66,11 +66,11 @@ Ice::PropertiesI::getPropertyAsIntWithDefault(const string& key, Int value) map::const_iterator p = _properties.find(key); if(p != _properties.end()) { - istringstream v(p->second); - if(!(v >> value) || !v.eof()) - { - return 0; - } + istringstream v(p->second); + if(!(v >> value) || !v.eof()) + { + return 0; + } } return value; @@ -99,7 +99,7 @@ Ice::PropertiesI::setProperty(const string& key, const string& value) { if(key.empty()) { - return; + return; } // @@ -109,28 +109,28 @@ Ice::PropertiesI::setProperty(const string& key, const string& value) string::size_type dotPos = key.find('.'); if(dotPos != string::npos) { - string prefix = key.substr(0, dotPos); - for(const char* const** i = IceInternal::PropertyNames::validProps; *i != 0; ++i) - { - string pattern(*i[0]); - dotPos = pattern.find('.'); - assert(dotPos != string::npos); - string propPrefix = pattern.substr(0, dotPos); - if(propPrefix != prefix) - { - continue; - } - - bool found = false; - for(const char* const* j = *i; *j != 0 && !found; ++j) - { - found = IceUtil::match(key, *j); - } - if(!found) - { - logger->warning("unknown property: " + key); - } - } + string prefix = key.substr(0, dotPos); + for(const char* const** i = IceInternal::PropertyNames::validProps; *i != 0; ++i) + { + string pattern(*i[0]); + dotPos = pattern.find('.'); + assert(dotPos != string::npos); + string propPrefix = pattern.substr(0, dotPos); + if(propPrefix != prefix) + { + continue; + } + + bool found = false; + for(const char* const* j = *i; *j != 0 && !found; ++j) + { + found = IceUtil::match(key, *j); + } + if(!found) + { + logger->warning("unknown property: " + key); + } + } } IceUtil::Mutex::Lock sync(*this); @@ -140,11 +140,11 @@ Ice::PropertiesI::setProperty(const string& key, const string& value) // if(!value.empty()) { - _properties[key] = value; + _properties[key] = value; } else { - _properties.erase(key); + _properties.erase(key); } } @@ -158,7 +158,7 @@ Ice::PropertiesI::getCommandLineOptions() map::const_iterator p; for(p = _properties.begin(); p != _properties.end(); ++p) { - result.push_back("--" + p->first + "=" + p->second); + result.push_back("--" + p->first + "=" + p->second); } return result; } @@ -169,7 +169,7 @@ Ice::PropertiesI::parseCommandLineOptions(const string& prefix, const StringSeq& string pfx = prefix; if(!pfx.empty() && pfx[pfx.size() - 1] != '.') { - pfx += '.'; + pfx += '.'; } pfx = "--" + pfx; @@ -215,7 +215,7 @@ Ice::PropertiesI::load(const std::string& file) if(!in) { FileException ex(__FILE__, __LINE__); - ex.path = file; + ex.path = file; ex.error = getSystemErrno(); throw ex; } @@ -223,7 +223,7 @@ Ice::PropertiesI::load(const std::string& file) char line[1024]; while(in.getline(line, 1024)) { - parseLine(line, _converter); + parseLine(line, _converter); } } @@ -250,24 +250,24 @@ Ice::PropertiesI::PropertiesI(StringSeq& args, const PropertiesPtr& defaults, co { if(defaults != 0) { - _properties = defaults->getPropertiesForPrefix(""); + _properties = defaults->getPropertiesForPrefix(""); } StringSeq::iterator q = args.begin(); if(_properties.find("Ice.ProgramName") == _properties.end()) { - if(q != args.end()) - { - // - // Use the first argument as the value for Ice.ProgramName. Replace - // any backslashes in this value with forward slashes, in case this - // value is used by the event logger. - // - string name = *q; - replace(name.begin(), name.end(), '\\', '/'); - setProperty("Ice.ProgramName", name); - } + if(q != args.end()) + { + // + // Use the first argument as the value for Ice.ProgramName. Replace + // any backslashes in this value with forward slashes, in case this + // value is used by the event logger. + // + string name = *q; + replace(name.begin(), name.end(), '\\', '/'); + setProperty("Ice.ProgramName", name); + } } StringSeq tmp; @@ -283,27 +283,27 @@ Ice::PropertiesI::PropertiesI(StringSeq& args, const PropertiesPtr& defaults, co s += "=1"; } parseLine(s.substr(2), 0); - loadConfigFiles = true; + loadConfigFiles = true; } else { - tmp.push_back(s); + tmp.push_back(s); } - ++q; + ++q; } args = tmp; if(!loadConfigFiles) { - // - // If Ice.Config is not set, load from ICE_CONFIG (if set) - // - loadConfigFiles = (_properties.find("Ice.Config") == _properties.end()); + // + // If Ice.Config is not set, load from ICE_CONFIG (if set) + // + loadConfigFiles = (_properties.find("Ice.Config") == _properties.end()); } if(loadConfigFiles) { - loadConfig(); + loadConfig(); } args = parseIceCommandLineOptions(args); @@ -319,25 +319,25 @@ Ice::PropertiesI::parseLine(const string& line, const StringConverterPtr& conver string::size_type idx = s.find('#'); if(idx != string::npos) { - s.erase(idx); + s.erase(idx); } idx = s.find_last_not_of(delim); if(idx != string::npos && idx + 1 < s.length()) { - s.erase(idx + 1); + s.erase(idx + 1); } string::size_type beg = s.find_first_not_of(delim); if(beg == string::npos) { - return; + return; } string::size_type end = s.find_first_of(delim + "=", beg); if(end == string::npos) { - return; + return; } string key = s.substr(beg, end - beg); @@ -345,7 +345,7 @@ Ice::PropertiesI::parseLine(const string& line, const StringConverterPtr& conver end = s.find('=', end); if(end == string::npos) { - return; + return; } ++end; @@ -353,20 +353,20 @@ Ice::PropertiesI::parseLine(const string& line, const StringConverterPtr& conver beg = s.find_first_not_of(delim, end); if(beg != string::npos) { - end = s.length(); - value = s.substr(beg, end - beg); + end = s.length(); + value = s.substr(beg, end - beg); } if(converter) { string tmp; - converter->fromUTF8(reinterpret_cast(key.data()), - reinterpret_cast(key.data() + key.size()), tmp); - key.swap(tmp); + converter->fromUTF8(reinterpret_cast(key.data()), + reinterpret_cast(key.data() + key.size()), tmp); + key.swap(tmp); - converter->fromUTF8(reinterpret_cast(value.data()), - reinterpret_cast(value.data() + value.size()), tmp); - value.swap(tmp); + converter->fromUTF8(reinterpret_cast(value.data()), + reinterpret_cast(value.data() + value.size()), tmp); + value.swap(tmp); } setProperty(key, value); diff --git a/cpp/src/Ice/Protocol.cpp b/cpp/src/Ice/Protocol.cpp index 793748dbae2..fbe3f832934 100644 --- a/cpp/src/Ice/Protocol.cpp +++ b/cpp/src/Ice/Protocol.cpp @@ -12,7 +12,7 @@ namespace IceInternal { -const Ice::Byte magic[] = { 0x49, 0x63, 0x65, 0x50 }; // 'I', 'c', 'e', 'P' +const Ice::Byte magic[] = { 0x49, 0x63, 0x65, 0x50 }; // 'I', 'c', 'e', 'P' #ifdef __BCPLUSPLUS__ const Ice::Byte requestHdr[headerSize + sizeof(Ice::Int)] = diff --git a/cpp/src/Ice/Proxy.cpp b/cpp/src/Ice/Proxy.cpp index eb20297fb6a..2ad7d17e5da 100644 --- a/cpp/src/Ice/Proxy.cpp +++ b/cpp/src/Ice/Proxy.cpp @@ -56,23 +56,23 @@ IceInternal::checkedCastImpl(const ObjectPrx& b, const string& f, const string& if(b) { - ObjectPrx bb = b->ice_facet(f); - try - { - if(context == 0 ? bb->ice_isA(typeId) : bb->ice_isA(typeId, *context)) - { - return bb; - } + ObjectPrx bb = b->ice_facet(f); + try + { + if(context == 0 ? bb->ice_isA(typeId) : bb->ice_isA(typeId, *context)) + { + return bb; + } #ifndef NDEBUG - else - { - assert(typeId != "::Ice::Object"); - } + else + { + assert(typeId != "::Ice::Object"); + } #endif - } - catch(const FacetNotExistException&) - { - } + } + catch(const FacetNotExistException&) + { + } } return 0; } @@ -132,21 +132,21 @@ IceProxy::Ice::Object::ice_isA(const string& typeId, const Context* context) int __cnt = 0; while(true) { - Handle< ::IceDelegate::Ice::Object> __del; - try - { - __checkTwowayOnly("ice_isA"); - __del = __getDelegate(); - return __del->ice_isA(typeId, context); - } - catch(const LocalExceptionWrapper& __ex) - { - __handleExceptionWrapperRelaxed(__del, __ex, __cnt); - } - catch(const LocalException& __ex) - { - __handleException(__del, __ex, __cnt); - } + Handle< ::IceDelegate::Ice::Object> __del; + try + { + __checkTwowayOnly("ice_isA"); + __del = __getDelegate(); + return __del->ice_isA(typeId, context); + } + catch(const LocalExceptionWrapper& __ex) + { + __handleExceptionWrapperRelaxed(__del, __ex, __cnt); + } + catch(const LocalException& __ex) + { + __handleException(__del, __ex, __cnt); + } } } @@ -156,21 +156,21 @@ IceProxy::Ice::Object::ice_ping(const Context* context) int __cnt = 0; while(true) { - Handle< ::IceDelegate::Ice::Object> __del; - try - { - __del = __getDelegate(); - __del->ice_ping(context); - return; - } - catch(const LocalExceptionWrapper& __ex) - { - __handleExceptionWrapperRelaxed(__del, __ex, __cnt); - } - catch(const LocalException& __ex) - { - __handleException(__del, __ex, __cnt); - } + Handle< ::IceDelegate::Ice::Object> __del; + try + { + __del = __getDelegate(); + __del->ice_ping(context); + return; + } + catch(const LocalExceptionWrapper& __ex) + { + __handleExceptionWrapperRelaxed(__del, __ex, __cnt); + } + catch(const LocalException& __ex) + { + __handleException(__del, __ex, __cnt); + } } } @@ -180,21 +180,21 @@ IceProxy::Ice::Object::ice_ids(const Context* context) int __cnt = 0; while(true) { - Handle< ::IceDelegate::Ice::Object> __del; - try - { - __checkTwowayOnly("ice_ids"); - __del = __getDelegate(); - return __del->ice_ids(context); - } - catch(const LocalExceptionWrapper& __ex) - { - __handleExceptionWrapperRelaxed(__del, __ex, __cnt); - } - catch(const LocalException& __ex) - { - __handleException(__del, __ex, __cnt); - } + Handle< ::IceDelegate::Ice::Object> __del; + try + { + __checkTwowayOnly("ice_ids"); + __del = __getDelegate(); + return __del->ice_ids(context); + } + catch(const LocalExceptionWrapper& __ex) + { + __handleExceptionWrapperRelaxed(__del, __ex, __cnt); + } + catch(const LocalException& __ex) + { + __handleException(__del, __ex, __cnt); + } } } @@ -204,31 +204,31 @@ IceProxy::Ice::Object::ice_id(const Context* context) int __cnt = 0; while(true) { - Handle< ::IceDelegate::Ice::Object> __del; - try - { - __checkTwowayOnly("ice_id"); - __del = __getDelegate(); - return __del->ice_id(context); - } - catch(const LocalExceptionWrapper& __ex) - { - __handleExceptionWrapperRelaxed(__del, __ex, __cnt); - } - catch(const LocalException& __ex) - { - __handleException(__del, __ex, __cnt); - } + Handle< ::IceDelegate::Ice::Object> __del; + try + { + __checkTwowayOnly("ice_id"); + __del = __getDelegate(); + return __del->ice_id(context); + } + catch(const LocalExceptionWrapper& __ex) + { + __handleExceptionWrapperRelaxed(__del, __ex, __cnt); + } + catch(const LocalException& __ex) + { + __handleException(__del, __ex, __cnt); + } } } bool IceProxy::Ice::Object::ice_invoke(const string& operation, - OperationMode mode, - const vector& inParams, - vector& outParams, - const Context* context) + OperationMode mode, + const vector& inParams, + vector& outParams, + const Context* context) { pair inPair; if(inParams.size() == 0) @@ -238,7 +238,7 @@ IceProxy::Ice::Object::ice_invoke(const string& operation, else { inPair.first = &inParams[0]; - inPair.second = inPair.first + inParams.size(); + inPair.second = inPair.first + inParams.size(); } return ice_invoke(operation, mode, inPair, outParams, context); } @@ -246,73 +246,73 @@ IceProxy::Ice::Object::ice_invoke(const string& operation, bool IceProxy::Ice::Object::ice_invoke(const string& operation, - OperationMode mode, - const pair& inParams, - vector& outParams, - const Context* context) + OperationMode mode, + const pair& inParams, + vector& outParams, + const Context* context) { int __cnt = 0; while(true) { - Handle< ::IceDelegate::Ice::Object> __del; - try - { - __del = __getDelegate(); - return __del->ice_invoke(operation, mode, inParams, outParams, context); - } - catch(const LocalExceptionWrapper& __ex) - { - bool canRetry = mode == Nonmutating || mode == Idempotent; - if(canRetry) - { - __handleExceptionWrapperRelaxed(__del, __ex, __cnt); - } - else - { - __handleExceptionWrapper(__del, __ex); - } - } - catch(const LocalException& __ex) - { - __handleException(__del, __ex, __cnt); - } + Handle< ::IceDelegate::Ice::Object> __del; + try + { + __del = __getDelegate(); + return __del->ice_invoke(operation, mode, inParams, outParams, context); + } + catch(const LocalExceptionWrapper& __ex) + { + bool canRetry = mode == Nonmutating || mode == Idempotent; + if(canRetry) + { + __handleExceptionWrapperRelaxed(__del, __ex, __cnt); + } + else + { + __handleExceptionWrapper(__del, __ex); + } + } + catch(const LocalException& __ex) + { + __handleException(__del, __ex, __cnt); + } } } void IceProxy::Ice::Object::ice_invoke_async(const AMI_Object_ice_invokePtr& cb, - const string& operation, - OperationMode mode, - const vector& inParams) + const string& operation, + OperationMode mode, + const vector& inParams) { cb->__invoke(this, operation, mode, inParams, 0); } void IceProxy::Ice::Object::ice_invoke_async(const AMI_Object_ice_invokePtr& cb, - const string& operation, - OperationMode mode, - const vector& inParams, - const Context& context) + const string& operation, + OperationMode mode, + const vector& inParams, + const Context& context) { cb->__invoke(this, operation, mode, inParams, &context); } void IceProxy::Ice::Object::ice_invoke_async(const AMI_Array_Object_ice_invokePtr& cb, - const string& operation, - OperationMode mode, - const pair& inParams) + const string& operation, + OperationMode mode, + const pair& inParams) { cb->__invoke(this, operation, mode, inParams, 0); } void IceProxy::Ice::Object::ice_invoke_async(const AMI_Array_Object_ice_invokePtr& cb, - const string& operation, - OperationMode mode, - const pair& inParams, - const Context& context) + const string& operation, + OperationMode mode, + const pair& inParams, + const Context& context) { cb->__invoke(this, operation, mode, inParams, &context); } @@ -332,13 +332,13 @@ IceProxy::Ice::Object::ice_identity(const Identity& newIdentity) const } if(newIdentity == _reference->getIdentity()) { - return ObjectPrx(const_cast< ::IceProxy::Ice::Object*>(this)); + return ObjectPrx(const_cast< ::IceProxy::Ice::Object*>(this)); } else { - ObjectPrx proxy(new ::IceProxy::Ice::Object()); - proxy->setup(_reference->changeIdentity(newIdentity)); - return proxy; + ObjectPrx proxy(new ::IceProxy::Ice::Object()); + proxy->setup(_reference->changeIdentity(newIdentity)); + return proxy; } } @@ -387,13 +387,13 @@ IceProxy::Ice::Object::ice_facet(const string& newFacet) const { if(newFacet == _reference->getFacet()) { - return ObjectPrx(const_cast< ::IceProxy::Ice::Object*>(this)); + return ObjectPrx(const_cast< ::IceProxy::Ice::Object*>(this)); } else { - ObjectPrx proxy(new ::IceProxy::Ice::Object()); - proxy->setup(_reference->changeFacet(newFacet)); - return proxy; + ObjectPrx proxy(new ::IceProxy::Ice::Object()); + proxy->setup(_reference->changeFacet(newFacet)); + return proxy; } } @@ -414,13 +414,13 @@ IceProxy::Ice::Object::ice_adapterId(const string& newAdapterId) const { if(newAdapterId == _reference->getAdapterId()) { - return ObjectPrx(const_cast< ::IceProxy::Ice::Object*>(this)); + return ObjectPrx(const_cast< ::IceProxy::Ice::Object*>(this)); } else { - ObjectPrx proxy(new ::IceProxy::Ice::Object()); - proxy->setup(_reference->changeAdapterId(newAdapterId)); - return proxy; + ObjectPrx proxy(new ::IceProxy::Ice::Object()); + proxy->setup(_reference->changeAdapterId(newAdapterId)); + return proxy; } } @@ -437,7 +437,7 @@ IceProxy::Ice::Object::ice_getEndpoints() const EndpointSeq retSeq; for(vector::const_iterator p = endpoints.begin(); p != endpoints.end(); ++p) { - retSeq.push_back(EndpointPtr::dynamicCast(*p)); + retSeq.push_back(EndpointPtr::dynamicCast(*p)); } return retSeq; } @@ -448,18 +448,18 @@ IceProxy::Ice::Object::ice_endpoints(const EndpointSeq& newEndpoints) const vector endpoints; for(EndpointSeq::const_iterator p = newEndpoints.begin(); p != newEndpoints.end(); ++p) { - endpoints.push_back(EndpointIPtr::dynamicCast(*p)); + endpoints.push_back(EndpointIPtr::dynamicCast(*p)); } if(endpoints == _reference->getEndpoints()) { - return ObjectPrx(const_cast< ::IceProxy::Ice::Object*>(this)); + return ObjectPrx(const_cast< ::IceProxy::Ice::Object*>(this)); } else { - ObjectPrx proxy(new ::IceProxy::Ice::Object()); - proxy->setup(_reference->changeEndpoints(endpoints)); - return proxy; + ObjectPrx proxy(new ::IceProxy::Ice::Object()); + proxy->setup(_reference->changeEndpoints(endpoints)); + return proxy; } } @@ -480,13 +480,13 @@ IceProxy::Ice::Object::ice_locatorCacheTimeout(Int newTimeout) const { if(newTimeout == _reference->getLocatorCacheTimeout()) { - return ObjectPrx(const_cast< ::IceProxy::Ice::Object*>(this)); + return ObjectPrx(const_cast< ::IceProxy::Ice::Object*>(this)); } else { - ObjectPrx proxy(new ::IceProxy::Ice::Object()); - proxy->setup(_reference->changeLocatorCacheTimeout(newTimeout)); - return proxy; + ObjectPrx proxy(new ::IceProxy::Ice::Object()); + proxy->setup(_reference->changeLocatorCacheTimeout(newTimeout)); + return proxy; } } @@ -501,13 +501,13 @@ IceProxy::Ice::Object::ice_connectionCached(bool newCache) const { if(newCache == _reference->getCacheConnection()) { - return ObjectPrx(const_cast< ::IceProxy::Ice::Object*>(this)); + return ObjectPrx(const_cast< ::IceProxy::Ice::Object*>(this)); } else { - ObjectPrx proxy(new ::IceProxy::Ice::Object()); - proxy->setup(_reference->changeCacheConnection(newCache)); - return proxy; + ObjectPrx proxy(new ::IceProxy::Ice::Object()); + proxy->setup(_reference->changeCacheConnection(newCache)); + return proxy; } } @@ -522,13 +522,13 @@ IceProxy::Ice::Object::ice_endpointSelection(EndpointSelectionType newType) cons { if(newType == _reference->getEndpointSelection()) { - return ObjectPrx(const_cast< ::IceProxy::Ice::Object*>(this)); + return ObjectPrx(const_cast< ::IceProxy::Ice::Object*>(this)); } else { - ObjectPrx proxy(new ::IceProxy::Ice::Object()); - proxy->setup(_reference->changeEndpointSelection(newType)); - return proxy; + ObjectPrx proxy(new ::IceProxy::Ice::Object()); + proxy->setup(_reference->changeEndpointSelection(newType)); + return proxy; } } @@ -543,13 +543,13 @@ IceProxy::Ice::Object::ice_secure(bool b) const { if(b == _reference->getSecure()) { - return ObjectPrx(const_cast< ::IceProxy::Ice::Object*>(this)); + return ObjectPrx(const_cast< ::IceProxy::Ice::Object*>(this)); } else { - ObjectPrx proxy(new ::IceProxy::Ice::Object()); - proxy->setup(_reference->changeSecure(b)); - return proxy; + ObjectPrx proxy(new ::IceProxy::Ice::Object()); + proxy->setup(_reference->changeSecure(b)); + return proxy; } } @@ -564,13 +564,13 @@ IceProxy::Ice::Object::ice_preferSecure(bool b) const { if(b == _reference->getPreferSecure()) { - return ObjectPrx(const_cast< ::IceProxy::Ice::Object*>(this)); + return ObjectPrx(const_cast< ::IceProxy::Ice::Object*>(this)); } else { - ObjectPrx proxy(new ::IceProxy::Ice::Object()); - proxy->setup(_reference->changePreferSecure(b)); - return proxy; + ObjectPrx proxy(new ::IceProxy::Ice::Object()); + proxy->setup(_reference->changePreferSecure(b)); + return proxy; } } @@ -587,13 +587,13 @@ IceProxy::Ice::Object::ice_router(const RouterPrx& router) const ReferencePtr ref = _reference->changeRouter(router); if(ref == _reference) { - return ObjectPrx(const_cast< ::IceProxy::Ice::Object*>(this)); + return ObjectPrx(const_cast< ::IceProxy::Ice::Object*>(this)); } else { - ObjectPrx proxy(new ::IceProxy::Ice::Object()); - proxy->setup(ref); - return proxy; + ObjectPrx proxy(new ::IceProxy::Ice::Object()); + proxy->setup(ref); + return proxy; } } @@ -610,13 +610,13 @@ IceProxy::Ice::Object::ice_locator(const LocatorPrx& locator) const ReferencePtr ref = _reference->changeLocator(locator); if(ref == _reference) { - return ObjectPrx(const_cast< ::IceProxy::Ice::Object*>(this)); + return ObjectPrx(const_cast< ::IceProxy::Ice::Object*>(this)); } else { - ObjectPrx proxy(new ::IceProxy::Ice::Object()); - proxy->setup(ref); - return proxy; + ObjectPrx proxy(new ::IceProxy::Ice::Object()); + proxy->setup(ref); + return proxy; } } @@ -637,13 +637,13 @@ IceProxy::Ice::Object::ice_collocationOptimized(bool b) const { if(b == _reference->getCollocationOptimization()) { - return ObjectPrx(const_cast< ::IceProxy::Ice::Object*>(this)); + return ObjectPrx(const_cast< ::IceProxy::Ice::Object*>(this)); } else { - ObjectPrx proxy(new ::IceProxy::Ice::Object()); - proxy->setup(_reference->changeCollocationOptimization(b)); - return proxy; + ObjectPrx proxy(new ::IceProxy::Ice::Object()); + proxy->setup(_reference->changeCollocationOptimization(b)); + return proxy; } } @@ -652,13 +652,13 @@ IceProxy::Ice::Object::ice_twoway() const { if(_reference->getMode() == Reference::ModeTwoway) { - return ObjectPrx(const_cast< ::IceProxy::Ice::Object*>(this)); + return ObjectPrx(const_cast< ::IceProxy::Ice::Object*>(this)); } else { - ObjectPrx proxy(new ::IceProxy::Ice::Object()); - proxy->setup(_reference->changeMode(Reference::ModeTwoway)); - return proxy; + ObjectPrx proxy(new ::IceProxy::Ice::Object()); + proxy->setup(_reference->changeMode(Reference::ModeTwoway)); + return proxy; } } @@ -673,13 +673,13 @@ IceProxy::Ice::Object::ice_oneway() const { if(_reference->getMode() == Reference::ModeOneway) { - return ObjectPrx(const_cast< ::IceProxy::Ice::Object*>(this)); + return ObjectPrx(const_cast< ::IceProxy::Ice::Object*>(this)); } else { - ObjectPrx proxy(new ::IceProxy::Ice::Object()); - proxy->setup(_reference->changeMode(Reference::ModeOneway)); - return proxy; + ObjectPrx proxy(new ::IceProxy::Ice::Object()); + proxy->setup(_reference->changeMode(Reference::ModeOneway)); + return proxy; } } @@ -694,13 +694,13 @@ IceProxy::Ice::Object::ice_batchOneway() const { if(_reference->getMode() == Reference::ModeBatchOneway) { - return ObjectPrx(const_cast< ::IceProxy::Ice::Object*>(this)); + return ObjectPrx(const_cast< ::IceProxy::Ice::Object*>(this)); } else { - ObjectPrx proxy(new ::IceProxy::Ice::Object()); - proxy->setup(_reference->changeMode(Reference::ModeBatchOneway)); - return proxy; + ObjectPrx proxy(new ::IceProxy::Ice::Object()); + proxy->setup(_reference->changeMode(Reference::ModeBatchOneway)); + return proxy; } } @@ -715,13 +715,13 @@ IceProxy::Ice::Object::ice_datagram() const { if(_reference->getMode() == Reference::ModeDatagram) { - return ObjectPrx(const_cast< ::IceProxy::Ice::Object*>(this)); + return ObjectPrx(const_cast< ::IceProxy::Ice::Object*>(this)); } else { - ObjectPrx proxy(new ::IceProxy::Ice::Object()); - proxy->setup(_reference->changeMode(Reference::ModeDatagram)); - return proxy; + ObjectPrx proxy(new ::IceProxy::Ice::Object()); + proxy->setup(_reference->changeMode(Reference::ModeDatagram)); + return proxy; } } @@ -736,13 +736,13 @@ IceProxy::Ice::Object::ice_batchDatagram() const { if(_reference->getMode() == Reference::ModeBatchDatagram) { - return ObjectPrx(const_cast< ::IceProxy::Ice::Object*>(this)); + return ObjectPrx(const_cast< ::IceProxy::Ice::Object*>(this)); } else { - ObjectPrx proxy(new ::IceProxy::Ice::Object()); - proxy->setup(_reference->changeMode(Reference::ModeBatchDatagram)); - return proxy; + ObjectPrx proxy(new ::IceProxy::Ice::Object()); + proxy->setup(_reference->changeMode(Reference::ModeBatchDatagram)); + return proxy; } } @@ -758,13 +758,13 @@ IceProxy::Ice::Object::ice_compress(bool b) const ReferencePtr ref = _reference->changeCompress(b); if(ref == _reference) { - return ObjectPrx(const_cast< ::IceProxy::Ice::Object*>(this)); + return ObjectPrx(const_cast< ::IceProxy::Ice::Object*>(this)); } else { - ObjectPrx proxy(new ::IceProxy::Ice::Object()); - proxy->setup(ref); - return proxy; + ObjectPrx proxy(new ::IceProxy::Ice::Object()); + proxy->setup(ref); + return proxy; } } @@ -774,13 +774,13 @@ IceProxy::Ice::Object::ice_timeout(int t) const ReferencePtr ref = _reference->changeTimeout(t); if(ref == _reference) { - return ObjectPrx(const_cast< ::IceProxy::Ice::Object*>(this)); + return ObjectPrx(const_cast< ::IceProxy::Ice::Object*>(this)); } else { - ObjectPrx proxy(new ::IceProxy::Ice::Object()); - proxy->setup(ref); - return proxy; + ObjectPrx proxy(new ::IceProxy::Ice::Object()); + proxy->setup(ref); + return proxy; } } @@ -790,13 +790,13 @@ IceProxy::Ice::Object::ice_connectionId(const string& id) const ReferencePtr ref = _reference->changeConnectionId(id); if(ref == _reference) { - return ObjectPrx(const_cast< ::IceProxy::Ice::Object*>(this)); + return ObjectPrx(const_cast< ::IceProxy::Ice::Object*>(this)); } else { - ObjectPrx proxy(new ::IceProxy::Ice::Object()); - proxy->setup(ref); - return proxy; + ObjectPrx proxy(new ::IceProxy::Ice::Object()); + proxy->setup(ref); + return proxy; } } @@ -834,17 +834,17 @@ IceProxy::Ice::Object::ice_getConnection() int __cnt = 0; while(true) { - Handle< ::IceDelegate::Ice::Object> __del; - try - { - __del = __getDelegate(); - bool compress; - return __del->__getConnection(compress); - } - catch(const LocalException& __ex) - { - __handleException(__del, __ex, __cnt); - } + Handle< ::IceDelegate::Ice::Object> __del; + try + { + __del = __getDelegate(); + bool compress; + return __del->__getConnection(compress); + } + catch(const LocalException& __ex) + { + __handleException(__del, __ex, __cnt); + } } } @@ -853,20 +853,20 @@ IceProxy::Ice::Object::ice_getCachedConnection() const { Handle< ::IceDelegate::Ice::Object> __del; { - IceUtil::Mutex::Lock sync(*this); - __del = _delegate; + IceUtil::Mutex::Lock sync(*this); + __del = _delegate; } if(__del) { - try - { - bool compress; - return __del->__getConnection(compress); - } - catch(const CollocationOptimizationException&) - { - } + try + { + bool compress; + return __del->__getConnection(compress); + } + catch(const CollocationOptimizationException&) + { + } } return 0; } @@ -885,11 +885,11 @@ IceProxy::Ice::Object::__copyFrom(const ObjectPrx& from) Handle< ::IceDelegateM::Ice::Object> delegateM; { - IceUtil::Mutex::Lock sync(*from.get()); + IceUtil::Mutex::Lock sync(*from.get()); - ref = from->_reference; - delegateD = dynamic_cast< ::IceDelegateD::Ice::Object*>(from->_delegate.get()); - delegateM = dynamic_cast< ::IceDelegateM::Ice::Object*>(from->_delegate.get()); + ref = from->_reference; + delegateD = dynamic_cast< ::IceDelegateD::Ice::Object*>(from->_delegate.get()); + delegateM = dynamic_cast< ::IceDelegateM::Ice::Object*>(from->_delegate.get()); } // @@ -904,31 +904,31 @@ IceProxy::Ice::Object::__copyFrom(const ObjectPrx& from) if(_reference->getCacheConnection()) { - // - // The _delegate attribute is only used if "cache connection" - // is enabled. If it's not enabled, we don't keep track of the - // delegate -- a new delegate is created for each invocations. - // + // + // The _delegate attribute is only used if "cache connection" + // is enabled. If it's not enabled, we don't keep track of the + // delegate -- a new delegate is created for each invocations. + // - if(delegateD) - { - Handle< ::IceDelegateD::Ice::Object> delegate = __createDelegateD(); - delegate->__copyFrom(delegateD); - _delegate = delegate; - } - else if(delegateM) - { - Handle< ::IceDelegateM::Ice::Object> delegate = __createDelegateM(); - delegate->__copyFrom(delegateM); - _delegate = delegate; - } + if(delegateD) + { + Handle< ::IceDelegateD::Ice::Object> delegate = __createDelegateD(); + delegate->__copyFrom(delegateD); + _delegate = delegate; + } + else if(delegateM) + { + Handle< ::IceDelegateM::Ice::Object> delegate = __createDelegateM(); + delegate->__copyFrom(delegateM); + _delegate = delegate; + } } } void IceProxy::Ice::Object::__handleException(const ::IceInternal::Handle< ::IceDelegate::Ice::Object>& delegate, - const LocalException& ex, - int& cnt) + const LocalException& ex, + int& cnt) { // // Only _delegate needs to be mutex protected here. @@ -936,7 +936,7 @@ IceProxy::Ice::Object::__handleException(const ::IceInternal::Handle< ::IceDeleg IceUtil::Mutex::Lock sync(*this); if(delegate.get() == _delegate.get()) { - _delegate = 0; + _delegate = 0; } ProxyFactoryPtr proxyFactory; @@ -946,9 +946,9 @@ IceProxy::Ice::Object::__handleException(const ::IceInternal::Handle< ::IceDeleg } catch(const CommunicatorDestroyedException&) { - // - // The communicator is already destroyed, so we cannot retry. - // + // + // The communicator is already destroyed, so we cannot retry. + // ex.ice_throw(); } @@ -958,37 +958,37 @@ IceProxy::Ice::Object::__handleException(const ::IceInternal::Handle< ::IceDeleg void IceProxy::Ice::Object::__handleExceptionWrapper(const ::IceInternal::Handle< ::IceDelegate::Ice::Object>& delegate, - const LocalExceptionWrapper& ex) + const LocalExceptionWrapper& ex) { { - IceUtil::Mutex::Lock sync(*this); - if(delegate.get() == _delegate.get()) - { - _delegate = 0; - } + IceUtil::Mutex::Lock sync(*this); + if(delegate.get() == _delegate.get()) + { + _delegate = 0; + } } if(!ex.retry()) { - ex.get()->ice_throw(); + ex.get()->ice_throw(); } } void IceProxy::Ice::Object::__handleExceptionWrapperRelaxed(const ::IceInternal::Handle< ::IceDelegate::Ice::Object>& del, - const LocalExceptionWrapper& ex, int& cnt) + const LocalExceptionWrapper& ex, int& cnt) { if(!ex.retry()) { - __handleException(del, *ex.get(), cnt); + __handleException(del, *ex.get(), cnt); } else { - IceUtil::Mutex::Lock sync(*this); - if(del.get() == _delegate.get()) - { - _delegate = 0; - } + IceUtil::Mutex::Lock sync(*this); + if(del.get() == _delegate.get()) + { + _delegate = 0; + } } } @@ -1009,8 +1009,8 @@ IceProxy::Ice::Object::__checkTwowayOnly(const char* name) const if(!ice_isTwoway()) { TwowayOnlyException ex(__FILE__, __LINE__); - ex.operation = name; - throw ex; + ex.operation = name; + throw ex; } } @@ -1025,8 +1025,8 @@ IceProxy::Ice::Object::__checkTwowayOnly(const string& name) const if(!ice_isTwoway()) { TwowayOnlyException ex(__FILE__, __LINE__); - ex.operation = name; - throw ex; + ex.operation = name; + throw ex; } } @@ -1043,47 +1043,47 @@ IceProxy::Ice::Object::__getDelegate() if(_delegate) { - return _delegate; + return _delegate; } Handle< ::IceDelegate::Ice::Object> delegate; if(_reference->getCollocationOptimization()) { - ObjectAdapterPtr adapter = _reference->getInstance()->objectAdapterFactory()->findObjectAdapter(this); - if(adapter) - { - Handle< ::IceDelegateD::Ice::Object> d = __createDelegateD(); - d->setup(_reference, adapter); - delegate = d; - } + ObjectAdapterPtr adapter = _reference->getInstance()->objectAdapterFactory()->findObjectAdapter(this); + if(adapter) + { + Handle< ::IceDelegateD::Ice::Object> d = __createDelegateD(); + d->setup(_reference, adapter); + delegate = d; + } } if(!delegate) { - Handle< ::IceDelegateM::Ice::Object> d = __createDelegateM(); - d->setup(_reference); - delegate = d; - - // - // If this proxy is for a non-local object, and we are - // using a router, then add this proxy to the router info - // object. - // - RouterInfoPtr ri = _reference->getRouterInfo(); - if(ri) - { - ri->addProxy(this); - } + Handle< ::IceDelegateM::Ice::Object> d = __createDelegateM(); + d->setup(_reference); + delegate = d; + + // + // If this proxy is for a non-local object, and we are + // using a router, then add this proxy to the router info + // object. + // + RouterInfoPtr ri = _reference->getRouterInfo(); + if(ri) + { + ri->addProxy(this); + } } if(_reference->getCacheConnection()) { - // - // The _delegate attribute is only used if "cache connection" - // is enabled. If it's not enabled, we don't keep track of the - // delegate -- a new delegate is created for each invocations. - // - _delegate = delegate; + // + // The _delegate attribute is only used if "cache connection" + // is enabled. If it's not enabled, we don't keep track of the + // delegate -- a new delegate is created for each invocations. + // + _delegate = delegate; } return delegate; @@ -1126,34 +1126,34 @@ IceDelegateM::Ice::Object::ice_isA(const string& __id, const Context* context) Outgoing __og(__connection.get(), __reference.get(), __operation, ::Ice::Nonmutating, context, __compress); try { - BasicStream* __os = __og.os(); - __os->write(__id, false); + BasicStream* __os = __og.os(); + __os->write(__id, false); } catch(const ::Ice::LocalException& __ex) { - __og.abort(__ex); + __og.abort(__ex); } bool __ret; bool __ok = __og.invoke(); try { - BasicStream* __is = __og.is(); - if(!__ok) - { - try - { - __is->throwException(); - } - catch(const ::Ice::UserException& __ex) - { - throw ::Ice::UnknownUserException(__FILE__, __LINE__, __ex.ice_name()); - } - } + BasicStream* __is = __og.is(); + if(!__ok) + { + try + { + __is->throwException(); + } + catch(const ::Ice::UserException& __ex) + { + throw ::Ice::UnknownUserException(__FILE__, __LINE__, __ex.ice_name()); + } + } __is->read(__ret); } catch(const ::Ice::LocalException& __ex) { - throw ::IceInternal::LocalExceptionWrapper(__ex, false); + throw ::IceInternal::LocalExceptionWrapper(__ex, false); } return __ret; } @@ -1166,22 +1166,22 @@ IceDelegateM::Ice::Object::ice_ping(const Context* context) bool __ok = __og.invoke(); try { - BasicStream* __is = __og.is(); - if(!__ok) - { - try - { - __is->throwException(); - } - catch(const ::Ice::UserException& __ex) - { - throw ::Ice::UnknownUserException(__FILE__, __LINE__, __ex.ice_name()); - } - } + BasicStream* __is = __og.is(); + if(!__ok) + { + try + { + __is->throwException(); + } + catch(const ::Ice::UserException& __ex) + { + throw ::Ice::UnknownUserException(__FILE__, __LINE__, __ex.ice_name()); + } + } } catch(const ::Ice::LocalException& __ex) { - throw ::IceInternal::LocalExceptionWrapper(__ex, false); + throw ::IceInternal::LocalExceptionWrapper(__ex, false); } } @@ -1194,23 +1194,23 @@ IceDelegateM::Ice::Object::ice_ids(const Context* context) bool __ok = __og.invoke(); try { - BasicStream* __is = __og.is(); - if(!__ok) - { - try - { - __is->throwException(); - } - catch(const ::Ice::UserException& __ex) - { - throw ::Ice::UnknownUserException(__FILE__, __LINE__, __ex.ice_name()); - } - } - __is->read(__ret, false); + BasicStream* __is = __og.is(); + if(!__ok) + { + try + { + __is->throwException(); + } + catch(const ::Ice::UserException& __ex) + { + throw ::Ice::UnknownUserException(__FILE__, __LINE__, __ex.ice_name()); + } + } + __is->read(__ret, false); } catch(const ::Ice::LocalException& __ex) { - throw ::IceInternal::LocalExceptionWrapper(__ex, false); + throw ::IceInternal::LocalExceptionWrapper(__ex, false); } return __ret; } @@ -1224,23 +1224,23 @@ IceDelegateM::Ice::Object::ice_id(const Context* context) bool __ok = __og.invoke(); try { - BasicStream* __is = __og.is(); - if(!__ok) - { - try - { - __is->throwException(); - } - catch(const ::Ice::UserException& __ex) - { - throw ::Ice::UnknownUserException(__FILE__, __LINE__, __ex.ice_name()); - } - } - __is->read(__ret, false); + BasicStream* __is = __og.is(); + if(!__ok) + { + try + { + __is->throwException(); + } + catch(const ::Ice::UserException& __ex) + { + throw ::Ice::UnknownUserException(__FILE__, __LINE__, __ex.ice_name()); + } + } + __is->read(__ret, false); } catch(const ::Ice::LocalException& __ex) { - throw ::IceInternal::LocalExceptionWrapper(__ex, false); + throw ::IceInternal::LocalExceptionWrapper(__ex, false); } return __ret; } @@ -1248,19 +1248,19 @@ IceDelegateM::Ice::Object::ice_id(const Context* context) bool IceDelegateM::Ice::Object::ice_invoke(const string& operation, OperationMode mode, - const pair& inParams, - vector& outParams, - const Context* context) + const pair& inParams, + vector& outParams, + const Context* context) { Outgoing __og(__connection.get(), __reference.get(), operation, mode, context, __compress); try { - BasicStream* __os = __og.os(); - __os->writeBlob(inParams.first, static_cast(inParams.second - inParams.first)); + BasicStream* __os = __og.os(); + __os->writeBlob(inParams.first, static_cast(inParams.second - inParams.first)); } catch(const ::Ice::LocalException& __ex) { - __og.abort(__ex); + __og.abort(__ex); } bool ok = __og.invoke(); if(__reference->getMode() == Reference::ModeTwoway) @@ -1329,19 +1329,19 @@ IceDelegateD::Ice::Object::ice_isA(const string& __id, const Context* context) __initCurrent(__current, "ice_isA", ::Ice::Nonmutating, context); while(true) { - Direct __direct(__current); - bool __ret; - try - { - __ret = __direct.servant()->ice_isA(__id, __current); - } - catch(...) - { - __direct.destroy(); - throw; - } - __direct.destroy(); - return __ret; + Direct __direct(__current); + bool __ret; + try + { + __ret = __direct.servant()->ice_isA(__id, __current); + } + catch(...) + { + __direct.destroy(); + throw; + } + __direct.destroy(); + return __ret; } return false; // To keep the Visual C++ compiler happy. } @@ -1353,18 +1353,18 @@ IceDelegateD::Ice::Object::ice_ping(const ::Ice::Context* context) __initCurrent(__current, "ice_ping", ::Ice::Nonmutating, context); while(true) { - Direct __direct(__current); - try - { - __direct.servant()->ice_ping(__current); - } - catch(...) - { - __direct.destroy(); - throw; - } - __direct.destroy(); - return; + Direct __direct(__current); + try + { + __direct.servant()->ice_ping(__current); + } + catch(...) + { + __direct.destroy(); + throw; + } + __direct.destroy(); + return; } } @@ -1375,19 +1375,19 @@ IceDelegateD::Ice::Object::ice_ids(const ::Ice::Context* context) __initCurrent(__current, "ice_ids", ::Ice::Nonmutating, context); while(true) { - Direct __direct(__current); - vector __ret; - try - { - __ret = __direct.servant()->ice_ids(__current); - } - catch(...) - { - __direct.destroy(); - throw; - } - __direct.destroy(); - return __ret; + Direct __direct(__current); + vector __ret; + try + { + __ret = __direct.servant()->ice_ids(__current); + } + catch(...) + { + __direct.destroy(); + throw; + } + __direct.destroy(); + return __ret; } return vector(); // To keep the Visual C++ compiler happy. } @@ -1399,29 +1399,29 @@ IceDelegateD::Ice::Object::ice_id(const ::Ice::Context* context) __initCurrent(__current, "ice_id", ::Ice::Nonmutating, context); while(true) { - Direct __direct(__current); - string __ret; - try - { - __ret = __direct.servant()->ice_id(__current); - } - catch(...) - { - __direct.destroy(); - throw; - } - __direct.destroy(); - return __ret; + Direct __direct(__current); + string __ret; + try + { + __ret = __direct.servant()->ice_id(__current); + } + catch(...) + { + __direct.destroy(); + throw; + } + __direct.destroy(); + return __ret; } return string(); // To keep the Visual C++ compiler happy. } bool IceDelegateD::Ice::Object::ice_invoke(const string&, - OperationMode, - const pair& inParams, - vector&, - const Context*) + OperationMode, + const pair& inParams, + vector&, + const Context*) { throw CollocationOptimizationException(__FILE__, __LINE__); return false; @@ -1456,7 +1456,7 @@ IceDelegateD::Ice::Object::__copyFrom(const ::IceInternal::Handle< ::IceDelegate void IceDelegateD::Ice::Object::__initCurrent(Current& current, const string& op, OperationMode mode, - const Context* context) + const Context* context) { current.adapter = __adapter; current.id = __reference->getIdentity(); @@ -1465,29 +1465,29 @@ IceDelegateD::Ice::Object::__initCurrent(Current& current, const string& op, Ope current.mode = mode; if(context != 0) { - // - // Explicit context - // - current.ctx = *context; + // + // Explicit context + // + current.ctx = *context; } else { - // - // Implicit context - // - const ImplicitContextIPtr& implicitContext = - __reference->getInstance()->getImplicitContext(); + // + // Implicit context + // + const ImplicitContextIPtr& implicitContext = + __reference->getInstance()->getImplicitContext(); - const Context& prxContext = __reference->getContext()->getValue(); + const Context& prxContext = __reference->getContext()->getValue(); - if(implicitContext == 0) - { - current.ctx = prxContext; - } - else - { - implicitContext->combine(prxContext, current.ctx); - } + if(implicitContext == 0) + { + current.ctx = prxContext; + } + else + { + implicitContext->combine(prxContext, current.ctx); + } } current.requestId = -1; } @@ -1512,19 +1512,19 @@ Ice::proxyIdentityLess(const ObjectPrx& lhs, const ObjectPrx& rhs) { if(!lhs && !rhs) { - return false; + return false; } else if(!lhs && rhs) { - return true; + return true; } else if(lhs && !rhs) { - return false; + return false; } else { - return lhs->ice_getIdentity() < rhs->ice_getIdentity(); + return lhs->ice_getIdentity() < rhs->ice_getIdentity(); } } @@ -1533,19 +1533,19 @@ Ice::proxyIdentityEqual(const ObjectPrx& lhs, const ObjectPrx& rhs) { if(!lhs && !rhs) { - return true; + return true; } else if(!lhs && rhs) { - return false; + return false; } else if(lhs && !rhs) { - return false; + return false; } else { - return lhs->ice_getIdentity() == rhs->ice_getIdentity(); + return lhs->ice_getIdentity() == rhs->ice_getIdentity(); } } @@ -1554,43 +1554,43 @@ Ice::proxyIdentityAndFacetLess(const ObjectPrx& lhs, const ObjectPrx& rhs) { if(!lhs && !rhs) { - return false; + return false; } else if(!lhs && rhs) { - return true; + return true; } else if(lhs && !rhs) { - return false; + return false; } else { - Identity lhsIdentity = lhs->ice_getIdentity(); - Identity rhsIdentity = rhs->ice_getIdentity(); - - if(lhsIdentity < rhsIdentity) - { - return true; - } - else if(rhsIdentity < lhsIdentity) - { - return false; - } - - string lhsFacet = lhs->ice_getFacet(); - string rhsFacet = rhs->ice_getFacet(); - - if(lhsFacet < rhsFacet) - { - return true; - } - else if(rhsFacet < lhsFacet) - { - return false; - } - - return false; + Identity lhsIdentity = lhs->ice_getIdentity(); + Identity rhsIdentity = rhs->ice_getIdentity(); + + if(lhsIdentity < rhsIdentity) + { + return true; + } + else if(rhsIdentity < lhsIdentity) + { + return false; + } + + string lhsFacet = lhs->ice_getFacet(); + string rhsFacet = rhs->ice_getFacet(); + + if(lhsFacet < rhsFacet) + { + return true; + } + else if(rhsFacet < lhsFacet) + { + return false; + } + + return false; } } @@ -1599,33 +1599,33 @@ Ice::proxyIdentityAndFacetEqual(const ObjectPrx& lhs, const ObjectPrx& rhs) { if(!lhs && !rhs) { - return true; + return true; } else if(!lhs && rhs) { - return false; + return false; } else if(lhs && !rhs) { - return false; + return false; } else { - Identity lhsIdentity = lhs->ice_getIdentity(); - Identity rhsIdentity = rhs->ice_getIdentity(); - - if(lhsIdentity == rhsIdentity) - { - string lhsFacet = lhs->ice_getFacet(); - string rhsFacet = rhs->ice_getFacet(); - - if(lhsFacet == rhsFacet) - { - return true; - } - } - - return false; + Identity lhsIdentity = lhs->ice_getIdentity(); + Identity rhsIdentity = rhs->ice_getIdentity(); + + if(lhsIdentity == rhsIdentity) + { + string lhsFacet = lhs->ice_getFacet(); + string rhsFacet = rhs->ice_getFacet(); + + if(lhsFacet == rhsFacet) + { + return true; + } + } + + return false; } } diff --git a/cpp/src/Ice/ProxyFactory.cpp b/cpp/src/Ice/ProxyFactory.cpp index 3de3450d22f..338cd0a62fb 100644 --- a/cpp/src/Ice/ProxyFactory.cpp +++ b/cpp/src/Ice/ProxyFactory.cpp @@ -39,11 +39,11 @@ IceInternal::ProxyFactory::proxyToString(const ObjectPrx& proxy) const { if(proxy) { - return proxy->__reference()->toString(); + return proxy->__reference()->toString(); } else { - return ""; + return ""; } } @@ -69,13 +69,13 @@ IceInternal::ProxyFactory::proxyToStream(const ObjectPrx& proxy, BasicStream* s) { if(proxy) { - proxy->__reference()->getIdentity().__write(s); - proxy->__reference()->streamWrite(s); + proxy->__reference()->getIdentity().__write(s); + proxy->__reference()->streamWrite(s); } else { - Identity ident; - ident.__write(s); + Identity ident; + ident.__write(s); } } @@ -104,48 +104,48 @@ IceInternal::ProxyFactory::checkRetryAfterException(const LocalException& ex, co if(one) { - LocatorInfoPtr li = ref->getLocatorInfo(); - if(li) - { - // - // We retry ObjectNotExistException if the reference is - // indirect. - // - li->clearObjectCache(IndirectReferencePtr::dynamicCast(ref)); - } - else if(ref->getRouterInfo() && one->operation == "ice_add_proxy") - { - // - // If we have a router, an ObjectNotExistException with an - // operation name "ice_add_proxy" indicates to the client - // that the router isn't aware of the proxy (for example, - // because it was evicted by the router). In this case, we - // must *always* retry, so that the missing proxy is added - // to the router. - // - if(traceLevels->retry >= 1) - { - Trace out(logger, traceLevels->retryCat); - out << "retrying operation call to add proxy to router\n" << ex; - } - return; // We must always retry, so we don't look at the retry count. - } - else - { - // - // For all other cases, we don't retry - // ObjectNotExistException. - // - ex.ice_throw(); - } + LocatorInfoPtr li = ref->getLocatorInfo(); + if(li) + { + // + // We retry ObjectNotExistException if the reference is + // indirect. + // + li->clearObjectCache(IndirectReferencePtr::dynamicCast(ref)); + } + else if(ref->getRouterInfo() && one->operation == "ice_add_proxy") + { + // + // If we have a router, an ObjectNotExistException with an + // operation name "ice_add_proxy" indicates to the client + // that the router isn't aware of the proxy (for example, + // because it was evicted by the router). In this case, we + // must *always* retry, so that the missing proxy is added + // to the router. + // + if(traceLevels->retry >= 1) + { + Trace out(logger, traceLevels->retryCat); + out << "retrying operation call to add proxy to router\n" << ex; + } + return; // We must always retry, so we don't look at the retry count. + } + else + { + // + // For all other cases, we don't retry + // ObjectNotExistException. + // + ex.ice_throw(); + } } else if(dynamic_cast(&ex)) { - // + // // We don't retry other *NotExistException, which are all // derived from RequestFailedException. - // - ex.ice_throw(); + // + ex.ice_throw(); } // @@ -172,7 +172,7 @@ IceInternal::ProxyFactory::checkRetryAfterException(const LocalException& ex, co // if(dynamic_cast(&ex)) { - ex.ice_throw(); + ex.ice_throw(); } ++cnt; @@ -180,33 +180,33 @@ IceInternal::ProxyFactory::checkRetryAfterException(const LocalException& ex, co if(cnt > static_cast(_retryIntervals.size())) { - if(traceLevels->retry >= 1) - { - Trace out(logger, traceLevels->retryCat); - out << "cannot retry operation call because retry limit has been exceeded\n" << ex; - } - ex.ice_throw(); + if(traceLevels->retry >= 1) + { + Trace out(logger, traceLevels->retryCat); + out << "cannot retry operation call because retry limit has been exceeded\n" << ex; + } + ex.ice_throw(); } int interval = _retryIntervals[cnt - 1]; if(traceLevels->retry >= 1) { - Trace out(logger, traceLevels->retryCat); - out << "retrying operation call"; - if(interval > 0) - { - out << " in " << interval << "ms"; - } - out << " because of exception\n" << ex; + Trace out(logger, traceLevels->retryCat); + out << "retrying operation call"; + if(interval > 0) + { + out << " in " << interval << "ms"; + } + out << " because of exception\n" << ex; } if(interval > 0) { - // - // Sleep before retrying. - // - IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(interval)); + // + // Sleep before retrying. + // + IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(interval)); } } @@ -220,46 +220,46 @@ IceInternal::ProxyFactory::ProxyFactory(const InstancePtr& instance) : while(true) { - const string delim = " \t"; + const string delim = " \t"; - beg = str.find_first_not_of(delim, end); - if(beg == string::npos) - { - if(_retryIntervals.empty()) - { - _retryIntervals.push_back(0); - } - break; - } + beg = str.find_first_not_of(delim, end); + if(beg == string::npos) + { + if(_retryIntervals.empty()) + { + _retryIntervals.push_back(0); + } + break; + } - end = str.find_first_of(delim, beg); - if(end == string::npos) - { - end = str.length(); - } - - if(beg == end) - { - break; - } + end = str.find_first_of(delim, beg); + if(end == string::npos) + { + end = str.length(); + } + + if(beg == end) + { + break; + } - istringstream value(str.substr(beg, end - beg)); + istringstream value(str.substr(beg, end - beg)); - int v; - if(!(value >> v) || !value.eof()) - { - v = 0; - } + int v; + if(!(value >> v) || !value.eof()) + { + v = 0; + } - // - // If -1 is the first value, no retry and wait intervals. - // - if(v == -1 && _retryIntervals.empty()) - { - break; - } + // + // If -1 is the first value, no retry and wait intervals. + // + if(v == -1 && _retryIntervals.empty()) + { + break; + } - _retryIntervals.push_back(v > 0 ? v : 0); + _retryIntervals.push_back(v > 0 ? v : 0); } } diff --git a/cpp/src/Ice/Reference.cpp b/cpp/src/Ice/Reference.cpp index 99308ff37af..2dfe49d0e55 100644 --- a/cpp/src/Ice/Reference.cpp +++ b/cpp/src/Ice/Reference.cpp @@ -41,7 +41,7 @@ struct RandomNumberGenerator : public std::unary_function { ptrdiff_t operator()(ptrdiff_t d) { - return IceUtil::random(static_cast(d)); + return IceUtil::random(static_cast(d)); } }; @@ -74,7 +74,7 @@ IceInternal::Reference::changeMode(Mode newMode) const { if(newMode == _mode) { - return ReferencePtr(const_cast(this)); + return ReferencePtr(const_cast(this)); } ReferencePtr r = _instance->referenceFactory()->copy(this); r->_mode = newMode; @@ -86,7 +86,7 @@ IceInternal::Reference::changeIdentity(const Identity& newIdentity) const { if(newIdentity == _identity) { - return ReferencePtr(const_cast(this)); + return ReferencePtr(const_cast(this)); } ReferencePtr r = _instance->referenceFactory()->copy(this); r->_identity = newIdentity; @@ -98,7 +98,7 @@ IceInternal::Reference::changeFacet(const string& newFacet) const { if(newFacet == _facet) { - return ReferencePtr(const_cast(this)); + return ReferencePtr(const_cast(this)); } ReferencePtr r = _instance->referenceFactory()->copy(this); r->_facet = newFacet; @@ -132,19 +132,19 @@ Reference::hash() const for(q = _context->getValue().begin(); q != _context->getValue().end(); ++q) { - for(p = q->first.begin(); p != q->first.end(); ++p) - { - h = 5 * h + *p; - } - for(p = q->second.begin(); p != q->second.end(); ++p) - { - h = 5 * h + *p; - } + for(p = q->first.begin(); p != q->first.end(); ++p) + { + h = 5 * h + *p; + } + for(p = q->second.begin(); p != q->second.end(); ++p) + { + h = 5 * h + *p; + } } for(p = _facet.begin(); p != _facet.end(); ++p) { - h = 5 * h + *p; + h = 5 * h + *p; } h = 5 * h + static_cast(getSecure()); @@ -168,11 +168,11 @@ IceInternal::Reference::streamWrite(BasicStream* s) const // if(_facet.empty()) { - s->write(static_cast(0), static_cast(0)); + s->write(static_cast(0), static_cast(0)); } else { - s->write(&_facet, &_facet + 1); + s->write(&_facet, &_facet + 1); } s->write(static_cast(_mode)); @@ -213,66 +213,66 @@ IceInternal::Reference::toString() const { s << " -f "; - // - // If the encoded facet string contains characters which - // the reference parser uses as separators, then we enclose - // the facet string in quotes. - // - string fs = _facet; + // + // If the encoded facet string contains characters which + // the reference parser uses as separators, then we enclose + // the facet string in quotes. + // + string fs = _facet; if(_instance->initializationData().stringConverter) { UTF8BufferI buffer; Byte* last = - _instance->initializationData().stringConverter->toUTF8(fs.data(), fs.data() + fs.size(), buffer); - fs = string(reinterpret_cast(buffer.getBuffer()), last - buffer.getBuffer()); + _instance->initializationData().stringConverter->toUTF8(fs.data(), fs.data() + fs.size(), buffer); + fs = string(reinterpret_cast(buffer.getBuffer()), last - buffer.getBuffer()); + } + fs = IceUtil::escapeString(fs, ""); + if(fs.find_first_of(" :@") != string::npos) + { + s << '"' << fs << '"'; + } + else + { + s << fs; } - fs = IceUtil::escapeString(fs, ""); - if(fs.find_first_of(" :@") != string::npos) - { - s << '"' << fs << '"'; - } - else - { - s << fs; - } } switch(_mode) { - case ModeTwoway: - { - s << " -t"; - break; - } - - case ModeOneway: - { - s << " -o"; - break; - } - - case ModeBatchOneway: - { - s << " -O"; - break; - } - - case ModeDatagram: - { - s << " -d"; - break; - } - - case ModeBatchDatagram: - { - s << " -D"; - break; - } + case ModeTwoway: + { + s << " -t"; + break; + } + + case ModeOneway: + { + s << " -o"; + break; + } + + case ModeBatchOneway: + { + s << " -O"; + break; + } + + case ModeDatagram: + { + s << " -d"; + break; + } + + case ModeBatchDatagram: + { + s << " -D"; + break; + } } if(getSecure()) { - s << " -s"; + s << " -s"; } return s.str(); @@ -289,27 +289,27 @@ IceInternal::Reference::operator==(const Reference& r) const if(getType() != r.getType()) { - return false; + return false; } if(_mode != r._mode) { - return false; + return false; } if(_identity != r._identity) { - return false; + return false; } if(_context->getValue() != r._context->getValue()) { - return false; + return false; } if(_facet != r._facet) { - return false; + return false; } return true; @@ -330,47 +330,47 @@ IceInternal::Reference::operator<(const Reference& r) const if(_mode < r._mode) { - return true; + return true; } else if(r._mode < _mode) { - return false; + return false; } if(_identity < r._identity) { - return true; + return true; } else if(r._identity < _identity) { - return false; + return false; } if(_context->getValue() < r._context->getValue()) { - return true; + return true; } else if(r._context->getValue() < _context->getValue()) { - return false; + return false; } if(_facet < r._facet) { - return true; + return true; } else if(r._facet < _facet) { - return false; + return false; } if(getType() < r.getType()) { - return true; + return true; } else if(r.getType() < getType()) { - return false; + return false; } return false; @@ -383,7 +383,7 @@ public: bool operator()(ConnectionIPtr p) const { - return p->endpoint()->datagram(); + return p->endpoint()->datagram(); } }; @@ -394,12 +394,12 @@ public: bool operator()(ConnectionIPtr p) const { - return p->endpoint()->secure(); + return p->endpoint()->secure(); } }; IceInternal::Reference::Reference(const InstancePtr& inst, const CommunicatorPtr& com, const Identity& ident, - const SharedContextPtr& ctx, const string& fs, Mode md) : + const SharedContextPtr& ctx, const string& fs, Mode md) : _hashInitialized(false), _instance(inst), _communicator(com), @@ -425,8 +425,8 @@ void IceInternal::incRef(IceInternal::FixedReference* p) { p->__incRef(); } void IceInternal::decRef(IceInternal::FixedReference* p) { p->__decRef(); } IceInternal::FixedReference::FixedReference(const InstancePtr& inst, const CommunicatorPtr& com, const Identity& ident, - const SharedContextPtr& ctx, const string& fs, Mode md, - const vector& fixedConns) : + const SharedContextPtr& ctx, const string& fs, Mode md, + const vector& fixedConns) : Reference(inst, com, ident, ctx, fs, md), _fixedConnections(fixedConns) { @@ -620,9 +620,9 @@ IceInternal::FixedReference::getConnection(bool& compress) const vector filteredConns = filterConnections(_fixedConnections); if(filteredConns.empty()) { - NoEndpointException ex(__FILE__, __LINE__); - ex.proxy = ""; // No stringified representation for fixed proxies - throw ex; + NoEndpointException ex(__FILE__, __LINE__); + ex.proxy = ""; // No stringified representation for fixed proxies + throw ex; } ConnectionIPtr connection = filteredConns[0]; @@ -669,7 +669,7 @@ IceInternal::FixedReference::operator<(const Reference& r) const { const FixedReference* rhs = dynamic_cast(&r); assert(rhs); - return _fixedConnections < rhs->_fixedConnections; + return _fixedConnections < rhs->_fixedConnections; } return false; } @@ -693,28 +693,28 @@ IceInternal::FixedReference::filterConnections(const vector& all switch(getMode()) { - case Reference::ModeTwoway: - case Reference::ModeOneway: - case Reference::ModeBatchOneway: - { - // - // Filter out datagram connections. - // + case Reference::ModeTwoway: + case Reference::ModeOneway: + case Reference::ModeBatchOneway: + { + // + // Filter out datagram connections. + // connections.erase(remove_if(connections.begin(), connections.end(), ConnectionIsDatagram()), - connections.end()); - break; - } - - case Reference::ModeDatagram: - case Reference::ModeBatchDatagram: - { - // - // Filter out non-datagram connections. - // + connections.end()); + break; + } + + case Reference::ModeDatagram: + case Reference::ModeBatchDatagram: + { + // + // Filter out non-datagram connections. + // connections.erase(remove_if(connections.begin(), connections.end(), not1(ConnectionIsDatagram())), - connections.end()); - break; - } + connections.end()); + break; + } } // @@ -733,17 +733,17 @@ IceInternal::FixedReference::filterConnections(const vector& all DefaultsAndOverridesPtr overrides = getInstance()->defaultsAndOverrides(); if(overrides->overrideSecure ? overrides->overrideSecureValue : getSecure()) { - connections.erase(remove_if(connections.begin(), connections.end(), not1(ConnectionIsSecure())), - connections.end()); + connections.erase(remove_if(connections.begin(), connections.end(), not1(ConnectionIsSecure())), + connections.end()); } else { - // - // We must use stable_partition() instead of just simply - // partition(), because otherwise some STL implementations - // order our now randomized connections. - // - stable_partition(connections.begin(), connections.end(), not1(ConnectionIsSecure())); + // + // We must use stable_partition() instead of just simply + // partition(), because otherwise some STL implementations + // order our now randomized connections. + // + stable_partition(connections.begin(), connections.end(), not1(ConnectionIsSecure())); } return connections; @@ -758,10 +758,10 @@ IceInternal::RoutableReference::getRoutedEndpoints() const if(_routerInfo) { // - // If we route, we send everything to the router's client - // proxy endpoints. - // - return _routerInfo->getClientEndpoints(); + // If we route, we send everything to the router's client + // proxy endpoints. + // + return _routerInfo->getClientEndpoints(); } return vector(); } @@ -807,7 +807,7 @@ IceInternal::RoutableReference::changeSecure(bool newSecure) const { if(newSecure == _secure) { - return RoutableReferencePtr(const_cast(this)); + return RoutableReferencePtr(const_cast(this)); } RoutableReferencePtr r = RoutableReferencePtr::dynamicCast(getInstance()->referenceFactory()->copy(this)); r->_secure = newSecure; @@ -819,7 +819,7 @@ IceInternal::RoutableReference::changePreferSecure(bool newPreferSecure) const { if(newPreferSecure == _preferSecure) { - return RoutableReferencePtr(const_cast(this)); + return RoutableReferencePtr(const_cast(this)); } RoutableReferencePtr r = RoutableReferencePtr::dynamicCast(getInstance()->referenceFactory()->copy(this)); r->_preferSecure = newPreferSecure; @@ -832,7 +832,7 @@ IceInternal::RoutableReference::changeRouter(const RouterPrx& newRouter) const RouterInfoPtr newRouterInfo = getInstance()->routerManager()->get(newRouter); if(newRouterInfo == _routerInfo) { - return RoutableReferencePtr(const_cast(this)); + return RoutableReferencePtr(const_cast(this)); } RoutableReferencePtr r = RoutableReferencePtr::dynamicCast(getInstance()->referenceFactory()->copy(this)); r->_routerInfo = newRouterInfo; @@ -844,7 +844,7 @@ IceInternal::RoutableReference::changeCollocationOptimization(bool newCollocatio { if(newCollocationOptimization == _collocationOptimization) { - return RoutableReferencePtr(const_cast(this)); + return RoutableReferencePtr(const_cast(this)); } RoutableReferencePtr r = RoutableReferencePtr::dynamicCast(getInstance()->referenceFactory()->copy(this)); r->_collocationOptimization = newCollocationOptimization; @@ -856,7 +856,7 @@ IceInternal::RoutableReference::changeCompress(bool newCompress) const { if(_overrideCompress && newCompress == _compress) { - return RoutableReferencePtr(const_cast(this)); + return RoutableReferencePtr(const_cast(this)); } RoutableReferencePtr r = RoutableReferencePtr::dynamicCast(getInstance()->referenceFactory()->copy(this)); r->_compress = newCompress; @@ -869,7 +869,7 @@ IceInternal::RoutableReference::changeTimeout(int newTimeout) const { if(_overrideTimeout && newTimeout == _timeout) { - return RoutableReferencePtr(const_cast(this)); + return RoutableReferencePtr(const_cast(this)); } RoutableReferencePtr r = RoutableReferencePtr::dynamicCast(getInstance()->referenceFactory()->copy(this)); r->_timeout = newTimeout; @@ -882,7 +882,7 @@ IceInternal::RoutableReference::changeConnectionId(const string& id) const { if(id == _connectionId) { - return RoutableReferencePtr(const_cast(this)); + return RoutableReferencePtr(const_cast(this)); } RoutableReferencePtr r = RoutableReferencePtr::dynamicCast(getInstance()->referenceFactory()->copy(this)); r->_connectionId = id; @@ -894,7 +894,7 @@ IceInternal::RoutableReference::changeCacheConnection(bool newCache) const { if(newCache == _cacheConnection) { - return RoutableReferencePtr(const_cast(this)); + return RoutableReferencePtr(const_cast(this)); } RoutableReferencePtr r = RoutableReferencePtr::dynamicCast(getInstance()->referenceFactory()->copy(this)); r->_cacheConnection = newCache; @@ -906,7 +906,7 @@ IceInternal::RoutableReference::changeEndpointSelection(EndpointSelectionType ne { if(newType == _endpointSelection) { - return RoutableReferencePtr(const_cast(this)); + return RoutableReferencePtr(const_cast(this)); } RoutableReferencePtr r = RoutableReferencePtr::dynamicCast(getInstance()->referenceFactory()->copy(this)); r->_endpointSelection = newType; @@ -945,35 +945,35 @@ IceInternal::RoutableReference::operator==(const Reference& r) const } if(_secure != rhs->_secure) { - return false; + return false; } if(_preferSecure != rhs->_preferSecure) { - return false; + return false; } if(_collocationOptimization != rhs->_collocationOptimization) { - return false; + return false; } if(_cacheConnection != rhs->_cacheConnection) { - return false; + return false; } if(_endpointSelection != rhs->_endpointSelection) { - return false; + return false; } if(_connectionId != rhs->_connectionId) { - return false; + return false; } if(_overrideCompress != rhs->_overrideCompress || _overrideCompress && _compress != rhs->_compress) { - return false; + return false; } if(_overrideTimeout != rhs->_overrideTimeout || _overrideTimeout && _timeout != rhs->_timeout) { - return false; + return false; } if(_threadPerConnection != rhs->_threadPerConnection) { @@ -1002,93 +1002,93 @@ IceInternal::RoutableReference::operator<(const Reference& r) const if(Reference::operator==(r)) { const RoutableReference* rhs = dynamic_cast(&r); - assert(rhs); - if(!_secure && rhs->_secure) - { - return true; - } - else if(rhs->_secure < _secure) - { - return false; - } - else if(!_preferSecure && rhs->_preferSecure) - { - return true; - } - else if(rhs->_preferSecure < _preferSecure) - { - return false; - } - if(!_collocationOptimization && rhs->_collocationOptimization) - { - return true; - } - else if(rhs->_collocationOptimization < _collocationOptimization) - { - return false; - } - if(!_cacheConnection && rhs->_cacheConnection) - { - return true; - } - else if(rhs->_cacheConnection < _cacheConnection) - { - return false; - } - if(_endpointSelection < rhs->_endpointSelection) - { - return true; - } - else if(rhs->_endpointSelection < _endpointSelection) - { - return false; - } - if(_connectionId < rhs->_connectionId) - { - return true; - } - else if(rhs->_connectionId < _connectionId) - { - return false; - } - if(!_overrideCompress && rhs->_overrideCompress) - { - return true; - } - else if(rhs->_overrideCompress < _overrideCompress) - { - return false; - } - else if(_overrideCompress) - { - if(!_compress && rhs->_compress) - { - return true; - } - else if(rhs->_compress < _compress) - { - return false; - } - } - if(!_overrideTimeout && rhs->_overrideTimeout) - { - return true; - } - else if(rhs->_overrideTimeout < _overrideTimeout) - { - return false; - } - else if(_overrideTimeout) - { - if(_timeout < rhs->_timeout) - { - return true; - } - else if(rhs->_timeout < _timeout) - { - return false; - } - } + assert(rhs); + if(!_secure && rhs->_secure) + { + return true; + } + else if(rhs->_secure < _secure) + { + return false; + } + else if(!_preferSecure && rhs->_preferSecure) + { + return true; + } + else if(rhs->_preferSecure < _preferSecure) + { + return false; + } + if(!_collocationOptimization && rhs->_collocationOptimization) + { + return true; + } + else if(rhs->_collocationOptimization < _collocationOptimization) + { + return false; + } + if(!_cacheConnection && rhs->_cacheConnection) + { + return true; + } + else if(rhs->_cacheConnection < _cacheConnection) + { + return false; + } + if(_endpointSelection < rhs->_endpointSelection) + { + return true; + } + else if(rhs->_endpointSelection < _endpointSelection) + { + return false; + } + if(_connectionId < rhs->_connectionId) + { + return true; + } + else if(rhs->_connectionId < _connectionId) + { + return false; + } + if(!_overrideCompress && rhs->_overrideCompress) + { + return true; + } + else if(rhs->_overrideCompress < _overrideCompress) + { + return false; + } + else if(_overrideCompress) + { + if(!_compress && rhs->_compress) + { + return true; + } + else if(rhs->_compress < _compress) + { + return false; + } + } + if(!_overrideTimeout && rhs->_overrideTimeout) + { + return true; + } + else if(rhs->_overrideTimeout < _overrideTimeout) + { + return false; + } + else if(_overrideTimeout) + { + if(_timeout < rhs->_timeout) + { + return true; + } + else if(rhs->_timeout < _timeout) + { + return false; + } + } if(!_threadPerConnection && rhs->_threadPerConnection) { return true; @@ -1097,15 +1097,15 @@ IceInternal::RoutableReference::operator<(const Reference& r) const { return false; } - return _routerInfo < rhs->_routerInfo; + return _routerInfo < rhs->_routerInfo; } return false; } IceInternal::RoutableReference::RoutableReference(const InstancePtr& inst, const CommunicatorPtr& com, - const Identity& ident, const SharedContextPtr& ctx, const string& fs, - Mode md, bool sec, bool prefSec, const RouterInfoPtr& rtrInfo, - bool collocationOpt, bool cacheConnection, + const Identity& ident, const SharedContextPtr& ctx, const string& fs, + Mode md, bool sec, bool prefSec, const RouterInfoPtr& rtrInfo, + bool collocationOpt, bool cacheConnection, EndpointSelectionType endpointSelection, bool threadPerConnection) : Reference(inst, com, ident, ctx, fs, md), _secure(sec), @@ -1148,36 +1148,36 @@ IceInternal::RoutableReference::createConnection(const vector& all // Filter out unknown endpoints. // endpoints.erase(remove_if(endpoints.begin(), endpoints.end(), Ice::constMemFun(&EndpointI::unknown)), - endpoints.end()); + endpoints.end()); // // Filter out endpoints according to the mode of the reference. // switch(getMode()) { - case Reference::ModeTwoway: - case Reference::ModeOneway: - case Reference::ModeBatchOneway: - { - // - // Filter out datagram endpoints. - // + case Reference::ModeTwoway: + case Reference::ModeOneway: + case Reference::ModeBatchOneway: + { + // + // Filter out datagram endpoints. + // endpoints.erase(remove_if(endpoints.begin(), endpoints.end(), Ice::constMemFun(&EndpointI::datagram)), endpoints.end()); - break; - } - - case Reference::ModeDatagram: - case Reference::ModeBatchDatagram: - { - // - // Filter out non-datagram endpoints. - // + break; + } + + case Reference::ModeDatagram: + case Reference::ModeBatchDatagram: + { + // + // Filter out non-datagram endpoints. + // endpoints.erase(remove_if(endpoints.begin(), endpoints.end(), - not1(Ice::constMemFun(&EndpointI::datagram))), + not1(Ice::constMemFun(&EndpointI::datagram))), endpoints.end()); - break; - } + break; + } } // @@ -1185,22 +1185,22 @@ IceInternal::RoutableReference::createConnection(const vector& all // switch(getEndpointSelection()) { - case Random: - { - RandomNumberGenerator rng; - random_shuffle(endpoints.begin(), endpoints.end(), rng); - break; - } - case Ordered: - { - // Nothing to do. - break; - } - default: - { - assert(false); - break; - } + case Random: + { + RandomNumberGenerator rng; + random_shuffle(endpoints.begin(), endpoints.end(), rng); + break; + } + case Ordered: + { + // Nothing to do. + break; + } + default: + { + assert(false); + break; + } } // @@ -1212,33 +1212,33 @@ IceInternal::RoutableReference::createConnection(const vector& all DefaultsAndOverridesPtr overrides = getInstance()->defaultsAndOverrides(); if(overrides->overrideSecure ? overrides->overrideSecureValue : getSecure()) { - endpoints.erase(remove_if(endpoints.begin(), endpoints.end(), not1(Ice::constMemFun(&EndpointI::secure))), - endpoints.end()); + endpoints.erase(remove_if(endpoints.begin(), endpoints.end(), not1(Ice::constMemFun(&EndpointI::secure))), + endpoints.end()); } else if(getPreferSecure()) { - // - // We must use stable_partition() instead of just simply - // partition(), because otherwise some STL implementations - // order our now randomized endpoints. - // - stable_partition(endpoints.begin(), endpoints.end(), Ice::constMemFun(&EndpointI::secure)); + // + // We must use stable_partition() instead of just simply + // partition(), because otherwise some STL implementations + // order our now randomized endpoints. + // + stable_partition(endpoints.begin(), endpoints.end(), Ice::constMemFun(&EndpointI::secure)); } else { - // - // We must use stable_partition() instead of just simply - // partition(), because otherwise some STL implementations - // order our now randomized endpoints. - // - stable_partition(endpoints.begin(), endpoints.end(), not1(Ice::constMemFun(&EndpointI::secure))); + // + // We must use stable_partition() instead of just simply + // partition(), because otherwise some STL implementations + // order our now randomized endpoints. + // + stable_partition(endpoints.begin(), endpoints.end(), not1(Ice::constMemFun(&EndpointI::secure))); } if(endpoints.empty()) { NoEndpointException ex(__FILE__, __LINE__); - ex.proxy = toString(); - throw ex; + ex.proxy = toString(); + throw ex; } // @@ -1247,42 +1247,42 @@ IceInternal::RoutableReference::createConnection(const vector& all OutgoingConnectionFactoryPtr factory = getInstance()->outgoingConnectionFactory(); if(getCacheConnection() || endpoints.size() == 1) { - // - // Get an existing connection or create one if there's no - // existing connection to one of the given endpoints. - // - return factory->create(endpoints, false, _threadPerConnection, comp); + // + // Get an existing connection or create one if there's no + // existing connection to one of the given endpoints. + // + return factory->create(endpoints, false, _threadPerConnection, comp); } else { - // - // Go through the list of endpoints and try to create the - // connection until it succeeds. This is different from just - // calling create() with the given endpoints since this might - // create a new connection even if there's an existing - // connection for one of the endpoints. - // - - auto_ptr exception; - vector endpoint; - endpoint.push_back(0); - - for(vector::const_iterator p = endpoints.begin(); p != endpoints.end(); ++p) - { - try - { - endpoint.back() = *p; - return factory->create(endpoint, p + 1 == endpoints.end(), _threadPerConnection, comp); - } - catch(const LocalException& ex) - { - exception.reset(dynamic_cast(ex.ice_clone())); - } - } - - assert(exception.get()); - exception->ice_throw(); - return 0; // Keeps the compiler happy. + // + // Go through the list of endpoints and try to create the + // connection until it succeeds. This is different from just + // calling create() with the given endpoints since this might + // create a new connection even if there's an existing + // connection for one of the endpoints. + // + + auto_ptr exception; + vector endpoint; + endpoint.push_back(0); + + for(vector::const_iterator p = endpoints.begin(); p != endpoints.end(); ++p) + { + try + { + endpoint.back() = *p; + return factory->create(endpoint, p + 1 == endpoints.end(), _threadPerConnection, comp); + } + catch(const LocalException& ex) + { + exception.reset(dynamic_cast(ex.ice_clone())); + } + } + + assert(exception.get()); + exception->ice_throw(); + return 0; // Keeps the compiler happy. } } @@ -1291,15 +1291,15 @@ IceInternal::RoutableReference::applyOverrides(vector& endpoints) { for(vector::iterator p = endpoints.begin(); p != endpoints.end(); ++p) { - *p = (*p)->connectionId(_connectionId); - if(_overrideCompress) - { - *p = (*p)->compress(_compress); - } - if(_overrideTimeout) - { - *p = (*p)->timeout(_timeout); - } + *p = (*p)->connectionId(_connectionId); + if(_overrideCompress) + { + *p = (*p)->compress(_compress); + } + if(_overrideTimeout) + { + *p = (*p)->timeout(_timeout); + } } } @@ -1307,9 +1307,9 @@ void IceInternal::incRef(IceInternal::DirectReference* p) { p->__incRef(); } void IceInternal::decRef(IceInternal::DirectReference* p) { p->__decRef(); } IceInternal::DirectReference::DirectReference(const InstancePtr& inst, const CommunicatorPtr& com, - const Identity& ident, const SharedContextPtr& ctx, const string& fs, - Mode md, bool sec, bool prefSec, const vector& endpts, - const RouterInfoPtr& rtrInfo, bool collocationOpt, bool cacheConnection, + const Identity& ident, const SharedContextPtr& ctx, const string& fs, + Mode md, bool sec, bool prefSec, const vector& endpts, + const RouterInfoPtr& rtrInfo, bool collocationOpt, bool cacheConnection, EndpointSelectionType endpointSelection, bool threadPerConnection) : RoutableReference(inst, com, ident, ctx, fs, md, sec, prefSec, rtrInfo, collocationOpt, cacheConnection, endpointSelection, threadPerConnection), @@ -1353,12 +1353,12 @@ IceInternal::DirectReference::changeCompress(bool newCompress) const DirectReferencePtr r = DirectReferencePtr::dynamicCast(RoutableReference::changeCompress(newCompress)); if(r.get() != this) // Also override the compress flag on the endpoints if it was updated. { - vector newEndpoints; - for(vector::const_iterator p = _endpoints.begin(); p != _endpoints.end(); ++p) - { - newEndpoints.push_back((*p)->compress(newCompress)); - } - r->_endpoints = newEndpoints; + vector newEndpoints; + for(vector::const_iterator p = _endpoints.begin(); p != _endpoints.end(); ++p) + { + newEndpoints.push_back((*p)->compress(newCompress)); + } + r->_endpoints = newEndpoints; } return r; } @@ -1369,12 +1369,12 @@ IceInternal::DirectReference::changeTimeout(int newTimeout) const DirectReferencePtr r = DirectReferencePtr::dynamicCast(RoutableReference::changeTimeout(newTimeout)); if(r.get() != this) // Also override the timeout on the endpoints if it was updated. { - vector newEndpoints; - for(vector::const_iterator p = _endpoints.begin(); p != _endpoints.end(); ++p) - { - newEndpoints.push_back((*p)->timeout(newTimeout)); - } - r->_endpoints = newEndpoints; + vector newEndpoints; + for(vector::const_iterator p = _endpoints.begin(); p != _endpoints.end(); ++p) + { + newEndpoints.push_back((*p)->timeout(newTimeout)); + } + r->_endpoints = newEndpoints; } return r; } @@ -1385,12 +1385,12 @@ IceInternal::DirectReference::changeConnectionId(const string& newConnectionId) DirectReferencePtr r = DirectReferencePtr::dynamicCast(RoutableReference::changeConnectionId(newConnectionId)); if(r.get() != this) // Also override the connection id on the endpoints if it was updated. { - vector newEndpoints; - for(vector::const_iterator p = _endpoints.begin(); p != _endpoints.end(); ++p) - { - newEndpoints.push_back((*p)->connectionId(newConnectionId)); - } - r->_endpoints = newEndpoints; + vector newEndpoints; + for(vector::const_iterator p = _endpoints.begin(); p != _endpoints.end(); ++p) + { + newEndpoints.push_back((*p)->connectionId(newConnectionId)); + } + r->_endpoints = newEndpoints; } return r; } @@ -1406,17 +1406,17 @@ IceInternal::DirectReference::changeAdapterId(const string& newAdapterId) const { if(!newAdapterId.empty()) { - LocatorInfoPtr locatorInfo = - getInstance()->locatorManager()->get(getInstance()->referenceFactory()->getDefaultLocator()); - return getInstance()->referenceFactory()->create(getIdentity(), getContext(), getFacet(), getMode(), - getSecure(), getPreferSecure(), newAdapterId, getRouterInfo(), - locatorInfo, getCollocationOptimization(), + LocatorInfoPtr locatorInfo = + getInstance()->locatorManager()->get(getInstance()->referenceFactory()->getDefaultLocator()); + return getInstance()->referenceFactory()->create(getIdentity(), getContext(), getFacet(), getMode(), + getSecure(), getPreferSecure(), newAdapterId, getRouterInfo(), + locatorInfo, getCollocationOptimization(), getCacheConnection(), getEndpointSelection(), getThreadPerConnection(), getLocatorCacheTimeout()); } else { - return DirectReferencePtr(const_cast(this)); + return DirectReferencePtr(const_cast(this)); } } @@ -1425,7 +1425,7 @@ IceInternal::DirectReference::changeEndpoints(const vector& newEnd { if(newEndpoints == _endpoints) { - return DirectReferencePtr(const_cast(this)); + return DirectReferencePtr(const_cast(this)); } DirectReferencePtr r = DirectReferencePtr::dynamicCast(getInstance()->referenceFactory()->copy(this)); r->_endpoints = newEndpoints; @@ -1442,14 +1442,14 @@ IceInternal::DirectReference::streamWrite(BasicStream* s) const s->writeSize(sz); if(sz) { - for(vector::const_iterator p = _endpoints.begin(); p != _endpoints.end(); ++p) - { - (*p)->streamWrite(s); - } + for(vector::const_iterator p = _endpoints.begin(); p != _endpoints.end(); ++p) + { + (*p)->streamWrite(s); + } } else { - s->write(string("")); // Adapter id. + s->write(string("")); // Adapter id. } } @@ -1468,12 +1468,12 @@ IceInternal::DirectReference::toString() const vector::const_iterator p; for(p = _endpoints.begin(); p != _endpoints.end(); ++p) { - string endp = (*p)->toString(); - if(!endp.empty()) - { - result.append(":"); - result.append(endp); - } + string endp = (*p)->toString(); + if(!endp.empty()) + { + result.append(":"); + result.append(endp); + } } return result; } @@ -1486,7 +1486,7 @@ IceInternal::DirectReference::getConnection(bool& comp) const if(endpts.empty()) { - endpts = _endpoints; // Endpoint overrides are already applied on these endpoints. + endpts = _endpoints; // Endpoint overrides are already applied on these endpoints. } ConnectionIPtr connection = createConnection(endpts, comp); @@ -1540,8 +1540,8 @@ IceInternal::DirectReference::operator<(const Reference& r) const if(RoutableReference::operator==(r)) { const DirectReference* rhs = dynamic_cast(&r); - assert(rhs); - return _endpoints < rhs->_endpoints; + assert(rhs); + return _endpoints < rhs->_endpoints; } return false; } @@ -1562,10 +1562,10 @@ void IceInternal::incRef(IceInternal::IndirectReference* p) { p->__incRef(); } void IceInternal::decRef(IceInternal::IndirectReference* p) { p->__decRef(); } IceInternal::IndirectReference::IndirectReference(const InstancePtr& inst, const CommunicatorPtr& com, - const Identity& ident, const SharedContextPtr& ctx, const string& fs, - Mode md, bool sec, bool prefSec, const string& adptid, - const RouterInfoPtr& rtrInfo, const LocatorInfoPtr& locInfo, - bool collocationOpt, bool cacheConnection, + const Identity& ident, const SharedContextPtr& ctx, const string& fs, + Mode md, bool sec, bool prefSec, const string& adptid, + const RouterInfoPtr& rtrInfo, const LocatorInfoPtr& locInfo, + bool collocationOpt, bool cacheConnection, EndpointSelectionType endpointSelection, bool threadPerConnection, int locatorCacheTimeout) : RoutableReference(inst, com, ident, ctx, fs, md, sec, prefSec, rtrInfo, collocationOpt, cacheConnection, @@ -1606,7 +1606,7 @@ IceInternal::IndirectReference::changeLocator(const LocatorPrx& newLocator) cons LocatorInfoPtr newLocatorInfo = getInstance()->locatorManager()->get(newLocator); if(newLocatorInfo == _locatorInfo) { - return IndirectReferencePtr(const_cast(this)); + return IndirectReferencePtr(const_cast(this)); } IndirectReferencePtr r = IndirectReferencePtr::dynamicCast(getInstance()->referenceFactory()->copy(this)); r->_locatorInfo = newLocatorInfo; @@ -1618,7 +1618,7 @@ IceInternal::IndirectReference::changeAdapterId(const string& newAdapterId) cons { if(newAdapterId == _adapterId) { - return IndirectReferencePtr(const_cast(this)); + return IndirectReferencePtr(const_cast(this)); } IndirectReferencePtr r = IndirectReferencePtr::dynamicCast(getInstance()->referenceFactory()->copy(this)); r->_adapterId = newAdapterId; @@ -1630,14 +1630,14 @@ IceInternal::IndirectReference::changeEndpoints(const vector& newE { if(!newEndpoints.empty()) { - return getInstance()->referenceFactory()->create(getIdentity(), getContext(), getFacet(), getMode(), - getSecure(), getPreferSecure(), newEndpoints, getRouterInfo(), - getCollocationOptimization(), getCacheConnection(), + return getInstance()->referenceFactory()->create(getIdentity(), getContext(), getFacet(), getMode(), + getSecure(), getPreferSecure(), newEndpoints, getRouterInfo(), + getCollocationOptimization(), getCacheConnection(), getEndpointSelection(), getThreadPerConnection()); } else { - return IndirectReferencePtr(const_cast(this)); + return IndirectReferencePtr(const_cast(this)); } } @@ -1646,7 +1646,7 @@ IceInternal::IndirectReference::changeLocatorCacheTimeout(int timeout) const { if(timeout == _locatorCacheTimeout) { - return IndirectReferencePtr(const_cast(this)); + return IndirectReferencePtr(const_cast(this)); } IndirectReferencePtr r = IndirectReferencePtr::dynamicCast(getInstance()->referenceFactory()->copy(this)); r->_locatorCacheTimeout = timeout; @@ -1690,18 +1690,18 @@ IceInternal::IndirectReference::toString() const { UTF8BufferI buffer; Byte* last = getInstance()->initializationData().stringConverter->toUTF8(a.data(), a.data() + a.size(), buffer); - a = string(reinterpret_cast(buffer.getBuffer()), last - buffer.getBuffer()); + a = string(reinterpret_cast(buffer.getBuffer()), last - buffer.getBuffer()); } a = IceUtil::escapeString(a, ""); if(a.find_first_of(" ") != string::npos) { - result.append("\""); - result.append(a); - result.append("\""); + result.append("\""); + result.append(a); + result.append("\""); } else { - result.append(_adapterId); + result.append(_adapterId); } return result; } @@ -1713,59 +1713,59 @@ IceInternal::IndirectReference::getConnection(bool& comp) const while(true) { - vector endpts = RoutableReference::getRoutedEndpoints(); - bool cached = false; - if(endpts.empty() && _locatorInfo) - { - const IndirectReferencePtr self = const_cast(this); - endpts = _locatorInfo->getEndpoints(self, _locatorCacheTimeout, cached); - } - - applyOverrides(endpts); - - try - { - connection = createConnection(endpts, comp); - assert(connection); - } - catch(const NoEndpointException& ex) - { - throw ex; // No need to retry if there's no endpoints. - } - catch(const LocalException& ex) - { - if(!getRouterInfo()) - { - assert(_locatorInfo); - - // COMPILERFIX: Braces needed to prevent BCB from causing Reference refCount from - // being decremented twice when loop continues. - { - const IndirectReferencePtr self = const_cast(this); - _locatorInfo->clearCache(self); - } - - if(cached) - { - // COMPILERFIX: Braces needed to prevent BCB from causing TraceLevels refCount from - // being decremented twice when loop continues. - { - TraceLevelsPtr traceLevels = getInstance()->traceLevels(); - if(traceLevels->retry >= 2) - { - Trace out(getInstance()->initializationData().logger, traceLevels->retryCat); - out << "connection to cached endpoints failed\n" - << "removing endpoints from cache and trying one more time\n" << ex; - } - } - continue; - } - } - - throw; - } - - break; + vector endpts = RoutableReference::getRoutedEndpoints(); + bool cached = false; + if(endpts.empty() && _locatorInfo) + { + const IndirectReferencePtr self = const_cast(this); + endpts = _locatorInfo->getEndpoints(self, _locatorCacheTimeout, cached); + } + + applyOverrides(endpts); + + try + { + connection = createConnection(endpts, comp); + assert(connection); + } + catch(const NoEndpointException& ex) + { + throw ex; // No need to retry if there's no endpoints. + } + catch(const LocalException& ex) + { + if(!getRouterInfo()) + { + assert(_locatorInfo); + + // COMPILERFIX: Braces needed to prevent BCB from causing Reference refCount from + // being decremented twice when loop continues. + { + const IndirectReferencePtr self = const_cast(this); + _locatorInfo->clearCache(self); + } + + if(cached) + { + // COMPILERFIX: Braces needed to prevent BCB from causing TraceLevels refCount from + // being decremented twice when loop continues. + { + TraceLevelsPtr traceLevels = getInstance()->traceLevels(); + if(traceLevels->retry >= 2) + { + Trace out(getInstance()->initializationData().logger, traceLevels->retryCat); + out << "connection to cached endpoints failed\n" + << "removing endpoints from cache and trying one more time\n" << ex; + } + } + continue; + } + } + + throw; + } + + break; } // @@ -1815,7 +1815,7 @@ IceInternal::IndirectReference::operator==(const Reference& r) const } return _adapterId == rhs->_adapterId && _locatorInfo == rhs->_locatorInfo && - _locatorCacheTimeout == rhs->_locatorCacheTimeout; + _locatorCacheTimeout == rhs->_locatorCacheTimeout; } bool @@ -1838,26 +1838,26 @@ IceInternal::IndirectReference::operator<(const Reference& r) const if(RoutableReference::operator==(r)) { const IndirectReference* rhs = dynamic_cast(&r); - assert(rhs); - if(_adapterId < rhs->_adapterId) - { - return true; - } - else if(rhs->_adapterId < _adapterId) - { - return false; - } - - if(_locatorInfo < rhs->_locatorInfo) - { - return true; - } - else if(rhs->_locatorInfo < _locatorInfo) - { - return false; - } - - return _locatorCacheTimeout < rhs->_locatorCacheTimeout; + assert(rhs); + if(_adapterId < rhs->_adapterId) + { + return true; + } + else if(rhs->_adapterId < _adapterId) + { + return false; + } + + if(_locatorInfo < rhs->_locatorInfo) + { + return true; + } + else if(rhs->_locatorInfo < _locatorInfo) + { + return false; + } + + return _locatorCacheTimeout < rhs->_locatorCacheTimeout; } return false; } diff --git a/cpp/src/Ice/Reference.h b/cpp/src/Ice/Reference.h index bd88dcc6826..4b9a07c259e 100644 --- a/cpp/src/Ice/Reference.h +++ b/cpp/src/Ice/Reference.h @@ -35,19 +35,19 @@ public: enum Type { - TypeDirect, - TypeIndirect, - TypeFixed + TypeDirect, + TypeIndirect, + TypeFixed }; enum Mode { - ModeTwoway, - ModeOneway, - ModeBatchOneway, - ModeDatagram, - ModeBatchDatagram, - ModeLast = ModeBatchDatagram + ModeTwoway, + ModeOneway, + ModeBatchOneway, + ModeDatagram, + ModeBatchDatagram, + ModeLast = ModeBatchDatagram }; Mode getMode() const { return _mode; } @@ -125,7 +125,7 @@ public: protected: Reference(const InstancePtr&, const Ice::CommunicatorPtr&, const Ice::Identity&, const SharedContextPtr&, - const std::string&, Mode); + const std::string&, Mode); Reference(const Reference&); IceUtil::RecMutex _hashMutex; // For lazy initialization of hash value. @@ -148,7 +148,7 @@ class FixedReference : public Reference public: FixedReference(const InstancePtr&, const Ice::CommunicatorPtr&, const Ice::Identity&, const SharedContextPtr&, - const std::string&, Mode, const std::vector&); + const std::string&, Mode, const std::vector&); const std::vector& getFixedConnections() const; @@ -238,7 +238,7 @@ public: protected: RoutableReference(const InstancePtr&, const Ice::CommunicatorPtr&, const Ice::Identity&, const SharedContextPtr&, - const std::string&, Mode, bool, bool, const RouterInfoPtr&, bool, bool, + const std::string&, Mode, bool, bool, const RouterInfoPtr&, bool, bool, Ice::EndpointSelectionType, bool); RoutableReference(const RoutableReference&); @@ -267,7 +267,7 @@ class DirectReference : public RoutableReference public: DirectReference(const InstancePtr&, const Ice::CommunicatorPtr&, const Ice::Identity&, const SharedContextPtr&, - const std::string&, Mode, bool, bool, const std::vector&, const RouterInfoPtr&, bool, + const std::string&, Mode, bool, bool, const std::vector&, const RouterInfoPtr&, bool, bool, Ice::EndpointSelectionType, bool); virtual Type getType() const; @@ -307,8 +307,8 @@ class IndirectReference : public RoutableReference public: IndirectReference(const InstancePtr&, const Ice::CommunicatorPtr&, const Ice::Identity&, const SharedContextPtr&, - const std::string&, Mode, bool, bool, const std::string&, const RouterInfoPtr&, - const LocatorInfoPtr&, bool, bool, Ice::EndpointSelectionType, bool, int); + const std::string&, Mode, bool, bool, const std::string&, const RouterInfoPtr&, + const LocatorInfoPtr&, bool, bool, Ice::EndpointSelectionType, bool, int); virtual LocatorInfoPtr getLocatorInfo() const { return _locatorInfo; } diff --git a/cpp/src/Ice/ReferenceFactory.cpp b/cpp/src/Ice/ReferenceFactory.cpp index 9e2105beaa7..13348367d9a 100644 --- a/cpp/src/Ice/ReferenceFactory.cpp +++ b/cpp/src/Ice/ReferenceFactory.cpp @@ -38,7 +38,7 @@ IceInternal::ReferenceFactory::copy(const Reference* r) const if(!_instance) { - throw CommunicatorDestroyedException(__FILE__, __LINE__); + throw CommunicatorDestroyedException(__FILE__, __LINE__); } const Ice::Identity& ident = r->getIdentity(); @@ -52,14 +52,14 @@ IceInternal::ReferenceFactory::copy(const Reference* r) const ReferencePtr IceInternal::ReferenceFactory::create(const Identity& ident, - const SharedContextPtr& context, - const string& facet, - Reference::Mode mode, - bool secure, - bool preferSecure, - const vector& endpoints, - const RouterInfoPtr& routerInfo, - bool collocationOptimization, + const SharedContextPtr& context, + const string& facet, + Reference::Mode mode, + bool secure, + bool preferSecure, + const vector& endpoints, + const RouterInfoPtr& routerInfo, + bool collocationOptimization, bool cacheConnection, EndpointSelectionType endpointSelection, bool threadPerConnection) @@ -68,7 +68,7 @@ IceInternal::ReferenceFactory::create(const Identity& ident, if(!_instance) { - throw CommunicatorDestroyedException(__FILE__, __LINE__); + throw CommunicatorDestroyedException(__FILE__, __LINE__); } if(ident.name.empty() && ident.category.empty()) @@ -80,31 +80,31 @@ IceInternal::ReferenceFactory::create(const Identity& ident, // Create new reference // return new DirectReference(_instance, _communicator, ident, context, facet, mode, secure, preferSecure, - endpoints, routerInfo, collocationOptimization, cacheConnection, endpointSelection, + endpoints, routerInfo, collocationOptimization, cacheConnection, endpointSelection, threadPerConnection); } ReferencePtr IceInternal::ReferenceFactory::create(const Identity& ident, - const SharedContextPtr& context, - const string& facet, - Reference::Mode mode, - bool secure, - bool preferSecure, - const string& adapterId, - const RouterInfoPtr& routerInfo, - const LocatorInfoPtr& locatorInfo, - bool collocationOptimization, + const SharedContextPtr& context, + const string& facet, + Reference::Mode mode, + bool secure, + bool preferSecure, + const string& adapterId, + const RouterInfoPtr& routerInfo, + const LocatorInfoPtr& locatorInfo, + bool collocationOptimization, bool cacheConnection, EndpointSelectionType endpointSelection, bool threadPerConnection, - int locatorCacheTimeout) + int locatorCacheTimeout) { IceUtil::Mutex::Lock sync(*this); if(!_instance) { - throw CommunicatorDestroyedException(__FILE__, __LINE__); + throw CommunicatorDestroyedException(__FILE__, __LINE__); } if(ident.name.empty() && ident.category.empty()) @@ -116,22 +116,22 @@ IceInternal::ReferenceFactory::create(const Identity& ident, // Create new reference // return new IndirectReference(_instance, _communicator, ident, context, facet, mode, secure, preferSecure, - adapterId, routerInfo, locatorInfo, collocationOptimization, cacheConnection, + adapterId, routerInfo, locatorInfo, collocationOptimization, cacheConnection, endpointSelection, threadPerConnection, locatorCacheTimeout); } ReferencePtr IceInternal::ReferenceFactory::create(const Identity& ident, - const SharedContextPtr& context, - const string& facet, - Reference::Mode mode, - const vector& fixedConnections) + const SharedContextPtr& context, + const string& facet, + Reference::Mode mode, + const vector& fixedConnections) { IceUtil::Mutex::Lock sync(*this); if(!_instance) { - throw CommunicatorDestroyedException(__FILE__, __LINE__); + throw CommunicatorDestroyedException(__FILE__, __LINE__); } if(ident.name.empty() && ident.category.empty()) @@ -162,9 +162,9 @@ IceInternal::ReferenceFactory::create(const string& str) beg = s.find_first_not_of(delim, end); if(beg == string::npos) { - ProxyParseException ex(__FILE__, __LINE__); - ex.str = str; - throw ex; + ProxyParseException ex(__FILE__, __LINE__); + ex.str = str; + throw ex; } // @@ -175,9 +175,9 @@ IceInternal::ReferenceFactory::create(const string& str) end = IceUtil::checkQuote(s, beg); if(end == string::npos) { - ProxyParseException ex(__FILE__, __LINE__); - ex.str = str; - throw ex; + ProxyParseException ex(__FILE__, __LINE__); + ex.str = str; + throw ex; } else if(end == 0) { @@ -197,9 +197,9 @@ IceInternal::ReferenceFactory::create(const string& str) if(beg == end) { - ProxyParseException ex(__FILE__, __LINE__); - ex.str = str; - throw ex; + ProxyParseException ex(__FILE__, __LINE__); + ex.str = str; + throw ex; } // @@ -243,54 +243,54 @@ IceInternal::ReferenceFactory::create(const string& str) while(true) { - beg = s.find_first_not_of(delim, end); - if(beg == string::npos) - { - break; - } + beg = s.find_first_not_of(delim, end); + if(beg == string::npos) + { + break; + } if(s[beg] == ':' || s[beg] == '@') { break; } - end = s.find_first_of(delim + ":@", beg); - if(end == string::npos) - { - end = s.length(); - } - - if(beg == end) - { - break; - } - - string option = s.substr(beg, end - beg); - if(option.length() != 2 || option[0] != '-') - { - ProxyParseException ex(__FILE__, __LINE__); - ex.str = str; - throw ex; - } + end = s.find_first_of(delim + ":@", beg); + if(end == string::npos) + { + end = s.length(); + } + + if(beg == end) + { + break; + } + + string option = s.substr(beg, end - beg); + if(option.length() != 2 || option[0] != '-') + { + ProxyParseException ex(__FILE__, __LINE__); + ex.str = str; + throw ex; + } // // Check for the presence of an option argument. The // argument may be enclosed in single or double // quotation marks. // - string argument; - string::size_type argumentBeg = s.find_first_not_of(delim, end); - if(argumentBeg != string::npos) - { + string argument; + string::size_type argumentBeg = s.find_first_not_of(delim, end); + if(argumentBeg != string::npos) + { if(s[argumentBeg] != '@' && s[argumentBeg] != ':' && s[argumentBeg] != '-') { beg = argumentBeg; end = IceUtil::checkQuote(s, beg); if(end == string::npos) { - ProxyParseException ex(__FILE__, __LINE__); - ex.str = str; - throw ex; + ProxyParseException ex(__FILE__, __LINE__); + ex.str = str; + throw ex; } else if(end == 0) { @@ -307,122 +307,122 @@ IceInternal::ReferenceFactory::create(const string& str) argument = s.substr(beg, end - beg); end++; // Skip trailing quote } - } - } - - // - // If any new options are added here, - // IceInternal::Reference::toString() and its derived classes must be updated as well. - // - switch(option[1]) - { - case 'f': - { - if(argument.empty()) - { - ProxyParseException ex(__FILE__, __LINE__); - ex.str = str; - throw ex; - } - - if(!IceUtil::unescapeString(argument, 0, argument.size(), facet)) - { - ProxyParseException ex(__FILE__, __LINE__); - ex.str = str; - throw ex; - } - - if(_instance->initializationData().stringConverter) - { - string tmpFacet; - _instance->initializationData().stringConverter->fromUTF8( - reinterpret_cast(facet.data()), - reinterpret_cast(facet.data() + facet.size()), tmpFacet); - facet = tmpFacet; - } - - break; - } - - case 't': - { - if(!argument.empty()) - { - ProxyParseException ex(__FILE__, __LINE__); - ex.str = str; - throw ex; - } - mode = Reference::ModeTwoway; - break; - } - - case 'o': - { - if(!argument.empty()) - { - ProxyParseException ex(__FILE__, __LINE__); - ex.str = str; - throw ex; - } - mode = Reference::ModeOneway; - break; - } - - case 'O': - { - if(!argument.empty()) - { - ProxyParseException ex(__FILE__, __LINE__); - ex.str = str; - throw ex; - } - mode = Reference::ModeBatchOneway; - break; - } - - case 'd': - { - if(!argument.empty()) - { - ProxyParseException ex(__FILE__, __LINE__); - ex.str = str; - throw ex; - } - mode = Reference::ModeDatagram; - break; - } - - case 'D': - { - if(!argument.empty()) - { - ProxyParseException ex(__FILE__, __LINE__); - ex.str = str; - throw ex; - } - mode = Reference::ModeBatchDatagram; - break; - } - - case 's': - { - if(!argument.empty()) - { - ProxyParseException ex(__FILE__, __LINE__); - ex.str = str; - throw ex; - } - secure = true; - break; - } - - default: - { - ProxyParseException ex(__FILE__, __LINE__); - ex.str = str; - throw ex; - } - } + } + } + + // + // If any new options are added here, + // IceInternal::Reference::toString() and its derived classes must be updated as well. + // + switch(option[1]) + { + case 'f': + { + if(argument.empty()) + { + ProxyParseException ex(__FILE__, __LINE__); + ex.str = str; + throw ex; + } + + if(!IceUtil::unescapeString(argument, 0, argument.size(), facet)) + { + ProxyParseException ex(__FILE__, __LINE__); + ex.str = str; + throw ex; + } + + if(_instance->initializationData().stringConverter) + { + string tmpFacet; + _instance->initializationData().stringConverter->fromUTF8( + reinterpret_cast(facet.data()), + reinterpret_cast(facet.data() + facet.size()), tmpFacet); + facet = tmpFacet; + } + + break; + } + + case 't': + { + if(!argument.empty()) + { + ProxyParseException ex(__FILE__, __LINE__); + ex.str = str; + throw ex; + } + mode = Reference::ModeTwoway; + break; + } + + case 'o': + { + if(!argument.empty()) + { + ProxyParseException ex(__FILE__, __LINE__); + ex.str = str; + throw ex; + } + mode = Reference::ModeOneway; + break; + } + + case 'O': + { + if(!argument.empty()) + { + ProxyParseException ex(__FILE__, __LINE__); + ex.str = str; + throw ex; + } + mode = Reference::ModeBatchOneway; + break; + } + + case 'd': + { + if(!argument.empty()) + { + ProxyParseException ex(__FILE__, __LINE__); + ex.str = str; + throw ex; + } + mode = Reference::ModeDatagram; + break; + } + + case 'D': + { + if(!argument.empty()) + { + ProxyParseException ex(__FILE__, __LINE__); + ex.str = str; + throw ex; + } + mode = Reference::ModeBatchDatagram; + break; + } + + case 's': + { + if(!argument.empty()) + { + ProxyParseException ex(__FILE__, __LINE__); + ex.str = str; + throw ex; + } + secure = true; + break; + } + + default: + { + ProxyParseException ex(__FILE__, __LINE__); + ex.str = str; + throw ex; + } + } } RouterInfoPtr routerInfo = _instance->routerManager()->get(getDefaultRouter()); @@ -430,9 +430,9 @@ IceInternal::ReferenceFactory::create(const string& str) if(beg == string::npos) { - return create(ident, _instance->getDefaultContext(), facet, mode, secure, - _instance->defaultsAndOverrides()->defaultPreferSecure, "", routerInfo, - locatorInfo, _instance->defaultsAndOverrides()->defaultCollocationOptimization, + return create(ident, _instance->getDefaultContext(), facet, mode, secure, + _instance->defaultsAndOverrides()->defaultPreferSecure, "", routerInfo, + locatorInfo, _instance->defaultsAndOverrides()->defaultCollocationOptimization, true, _instance->defaultsAndOverrides()->defaultEndpointSelection, _instance->threadPerConnection(), _instance->defaultsAndOverrides()->defaultLocatorCacheTimeout); } @@ -441,118 +441,118 @@ IceInternal::ReferenceFactory::create(const string& str) switch(s[beg]) { - case ':': - { - vector unknownEndpoints; - end = beg; - - while(end < s.length() && s[end] == ':') - { - beg = end + 1; - - end = s.find(':', beg); - if(end == string::npos) - { - end = s.length(); - } - - string es = s.substr(beg, end - beg); - EndpointIPtr endp = _instance->endpointFactoryManager()->create(es); - if(endp != 0) - { - vector endps = endp->expand(false); - endpoints.insert(endpoints.end(), endps.begin(), endps.end()); - } - else - { - unknownEndpoints.push_back(es); - } - } - if(endpoints.size() == 0) - { - EndpointParseException ex(__FILE__, __LINE__); - ex.str = unknownEndpoints.front(); - throw ex; - } - else if(unknownEndpoints.size() != 0 && - _instance->initializationData().properties-> - getPropertyAsIntWithDefault("Ice.Warn.Endpoints", 1) > 0) - { - Warning out(_instance->initializationData().logger); - out << "Proxy contains unknown endpoints:"; - for(unsigned int idx = 0; idx < unknownEndpoints.size(); ++idx) - { - out << " `" << unknownEndpoints[idx] << "'"; - } - } - - return create(ident, _instance->getDefaultContext(), facet, mode, secure, - _instance->defaultsAndOverrides()->defaultPreferSecure, endpoints, routerInfo, - _instance->defaultsAndOverrides()->defaultCollocationOptimization, true, + case ':': + { + vector unknownEndpoints; + end = beg; + + while(end < s.length() && s[end] == ':') + { + beg = end + 1; + + end = s.find(':', beg); + if(end == string::npos) + { + end = s.length(); + } + + string es = s.substr(beg, end - beg); + EndpointIPtr endp = _instance->endpointFactoryManager()->create(es); + if(endp != 0) + { + vector endps = endp->expand(false); + endpoints.insert(endpoints.end(), endps.begin(), endps.end()); + } + else + { + unknownEndpoints.push_back(es); + } + } + if(endpoints.size() == 0) + { + EndpointParseException ex(__FILE__, __LINE__); + ex.str = unknownEndpoints.front(); + throw ex; + } + else if(unknownEndpoints.size() != 0 && + _instance->initializationData().properties-> + getPropertyAsIntWithDefault("Ice.Warn.Endpoints", 1) > 0) + { + Warning out(_instance->initializationData().logger); + out << "Proxy contains unknown endpoints:"; + for(unsigned int idx = 0; idx < unknownEndpoints.size(); ++idx) + { + out << " `" << unknownEndpoints[idx] << "'"; + } + } + + return create(ident, _instance->getDefaultContext(), facet, mode, secure, + _instance->defaultsAndOverrides()->defaultPreferSecure, endpoints, routerInfo, + _instance->defaultsAndOverrides()->defaultCollocationOptimization, true, _instance->defaultsAndOverrides()->defaultEndpointSelection, _instance->threadPerConnection()); - break; - } - case '@': - { - beg = s.find_first_not_of(delim, beg + 1); - if(beg == string::npos) - { - ProxyParseException ex(__FILE__, __LINE__); - ex.str = str; - throw ex; - } - - end = IceUtil::checkQuote(s, beg); - if(end == string::npos) - { - ProxyParseException ex(__FILE__, __LINE__); - ex.str = str; - throw ex; - } - else if(end == 0) - { - end = s.find_first_of(delim, beg); - if(end == string::npos) - { - end = s.size(); - } - } - else - { - beg++; // Skip leading quote - } - - - if(!IceUtil::unescapeString(s, beg, end, adapter) || adapter.size() == 0) - { - ProxyParseException ex(__FILE__, __LINE__); - ex.str = str; - throw ex; - } + break; + } + case '@': + { + beg = s.find_first_not_of(delim, beg + 1); + if(beg == string::npos) + { + ProxyParseException ex(__FILE__, __LINE__); + ex.str = str; + throw ex; + } + + end = IceUtil::checkQuote(s, beg); + if(end == string::npos) + { + ProxyParseException ex(__FILE__, __LINE__); + ex.str = str; + throw ex; + } + else if(end == 0) + { + end = s.find_first_of(delim, beg); + if(end == string::npos) + { + end = s.size(); + } + } + else + { + beg++; // Skip leading quote + } + + + if(!IceUtil::unescapeString(s, beg, end, adapter) || adapter.size() == 0) + { + ProxyParseException ex(__FILE__, __LINE__); + ex.str = str; + throw ex; + } if(_instance->initializationData().stringConverter) { - string tmpAdapter; + string tmpAdapter; _instance->initializationData().stringConverter->fromUTF8( - reinterpret_cast(adapter.data()), - reinterpret_cast(adapter.data() + adapter.size()), tmpAdapter); - adapter = tmpAdapter; + reinterpret_cast(adapter.data()), + reinterpret_cast(adapter.data() + adapter.size()), tmpAdapter); + adapter = tmpAdapter; } - - return create(ident, _instance->getDefaultContext(), facet, mode, secure, - _instance->defaultsAndOverrides()->defaultPreferSecure, adapter, routerInfo, locatorInfo, - _instance->defaultsAndOverrides()->defaultCollocationOptimization, true, + + return create(ident, _instance->getDefaultContext(), facet, mode, secure, + _instance->defaultsAndOverrides()->defaultPreferSecure, adapter, routerInfo, locatorInfo, + _instance->defaultsAndOverrides()->defaultCollocationOptimization, true, _instance->defaultsAndOverrides()->defaultEndpointSelection, _instance->threadPerConnection(), - _instance->defaultsAndOverrides()->defaultLocatorCacheTimeout); - break; - } - default: - { - ProxyParseException ex(__FILE__, __LINE__); - ex.str = str; - throw ex; - } + _instance->defaultsAndOverrides()->defaultLocatorCacheTimeout); + break; + } + default: + { + ProxyParseException ex(__FILE__, __LINE__); + ex.str = str; + throw ex; + } } return 0; // Unreachable, prevents compiler warning. @@ -573,7 +573,7 @@ IceInternal::ReferenceFactory::createFromProperties(const string& propertyPrefix if(!properties->getProperty(property).empty()) { ref = ref->changeLocator( - LocatorPrx::uncheckedCast(_communicator->propertyToProxy(property))); + LocatorPrx::uncheckedCast(_communicator->propertyToProxy(property))); } property = propertyPrefix + ".LocatorCacheTimeout"; @@ -586,7 +586,7 @@ IceInternal::ReferenceFactory::createFromProperties(const string& propertyPrefix if(!properties->getProperty(property).empty()) { ref = ref->changeRouter( - RouterPrx::uncheckedCast(_communicator->propertyToProxy(property))); + RouterPrx::uncheckedCast(_communicator->propertyToProxy(property))); } property = propertyPrefix + ".PreferSecure"; @@ -606,19 +606,19 @@ IceInternal::ReferenceFactory::createFromProperties(const string& propertyPrefix { string type = properties->getProperty(property); if(type == "Random") - { - ref = ref->changeEndpointSelection(Random); - } - else if(type == "Ordered") - { - ref = ref->changeEndpointSelection(Ordered); - } - else - { - EndpointSelectionTypeParseException ex(__FILE__, __LINE__); - ex.str = type; - throw ex; - } + { + ref = ref->changeEndpointSelection(Random); + } + else if(type == "Ordered") + { + ref = ref->changeEndpointSelection(Ordered); + } + else + { + EndpointSelectionTypeParseException ex(__FILE__, __LINE__); + ex.str = type; + throw ex; + } } property = propertyPrefix + ".CollocationOptimization"; @@ -646,7 +646,7 @@ IceInternal::ReferenceFactory::create(const Identity& ident, BasicStream* s) if(ident.name.empty() && ident.category.empty()) { - return 0; + return 0; } // @@ -657,10 +657,10 @@ IceInternal::ReferenceFactory::create(const Identity& ident, BasicStream* s) string facet; if(!facetPath.empty()) { - if(facetPath.size() > 1) - { - throw ProxyUnmarshalException(__FILE__, __LINE__); - } + if(facetPath.size() > 1) + { + throw ProxyUnmarshalException(__FILE__, __LINE__); + } facet.swap(facetPath[0]); } @@ -669,7 +669,7 @@ IceInternal::ReferenceFactory::create(const Identity& ident, BasicStream* s) Reference::Mode mode = static_cast(modeAsByte); if(mode < 0 || mode > Reference::ModeLast) { - throw ProxyUnmarshalException(__FILE__, __LINE__); + throw ProxyUnmarshalException(__FILE__, __LINE__); } bool secure; @@ -686,25 +686,25 @@ IceInternal::ReferenceFactory::create(const Identity& ident, BasicStream* s) if(sz > 0) { - endpoints.reserve(sz); - while(sz--) - { - EndpointIPtr endpoint = _instance->endpointFactoryManager()->read(s); - endpoints.push_back(endpoint); - } - return create(ident, _instance->getDefaultContext(), facet, mode, secure, - _instance->defaultsAndOverrides()->defaultPreferSecure, endpoints, routerInfo, - _instance->defaultsAndOverrides()->defaultCollocationOptimization, true, - _instance->defaultsAndOverrides()->defaultEndpointSelection, _instance->threadPerConnection()); + endpoints.reserve(sz); + while(sz--) + { + EndpointIPtr endpoint = _instance->endpointFactoryManager()->read(s); + endpoints.push_back(endpoint); + } + return create(ident, _instance->getDefaultContext(), facet, mode, secure, + _instance->defaultsAndOverrides()->defaultPreferSecure, endpoints, routerInfo, + _instance->defaultsAndOverrides()->defaultCollocationOptimization, true, + _instance->defaultsAndOverrides()->defaultEndpointSelection, _instance->threadPerConnection()); } else { - s->read(adapterId); - return create(ident, _instance->getDefaultContext(), facet, mode, secure, - _instance->defaultsAndOverrides()->defaultPreferSecure, adapterId, routerInfo, locatorInfo, - _instance->defaultsAndOverrides()->defaultCollocationOptimization, true, - _instance->defaultsAndOverrides()->defaultEndpointSelection, _instance->threadPerConnection(), - _instance->defaultsAndOverrides()->defaultLocatorCacheTimeout); + s->read(adapterId); + return create(ident, _instance->getDefaultContext(), facet, mode, secure, + _instance->defaultsAndOverrides()->defaultPreferSecure, adapterId, routerInfo, locatorInfo, + _instance->defaultsAndOverrides()->defaultCollocationOptimization, true, + _instance->defaultsAndOverrides()->defaultEndpointSelection, _instance->threadPerConnection(), + _instance->defaultsAndOverrides()->defaultLocatorCacheTimeout); } } @@ -749,7 +749,7 @@ IceInternal::ReferenceFactory::destroy() if(!_instance) { - throw CommunicatorDestroyedException(__FILE__, __LINE__); + throw CommunicatorDestroyedException(__FILE__, __LINE__); } _instance = 0; diff --git a/cpp/src/Ice/ReferenceFactory.h b/cpp/src/Ice/ReferenceFactory.h index cea63de6757..e687c956255 100644 --- a/cpp/src/Ice/ReferenceFactory.h +++ b/cpp/src/Ice/ReferenceFactory.h @@ -32,19 +32,19 @@ public: // Create a direct reference. // ReferencePtr create(const ::Ice::Identity&, const SharedContextPtr&, const ::std::string&, - Reference::Mode, bool, bool, const ::std::vector&, - const RouterInfoPtr&, bool, bool, Ice::EndpointSelectionType, bool); + Reference::Mode, bool, bool, const ::std::vector&, + const RouterInfoPtr&, bool, bool, Ice::EndpointSelectionType, bool); // // Create an indirect reference. // ReferencePtr create(const ::Ice::Identity&, const SharedContextPtr&, const ::std::string&, - Reference::Mode, bool, bool, const ::std::string&, - const RouterInfoPtr&, const LocatorInfoPtr&, bool, bool, Ice::EndpointSelectionType, bool, int); + Reference::Mode, bool, bool, const ::std::string&, + const RouterInfoPtr&, const LocatorInfoPtr&, bool, bool, Ice::EndpointSelectionType, bool, int); // // Create a fixed reference. // ReferencePtr create(const ::Ice::Identity&, const SharedContextPtr&, const ::std::string&, - Reference::Mode, const ::std::vector< ::Ice::ConnectionIPtr>&); + Reference::Mode, const ::std::vector< ::Ice::ConnectionIPtr>&); // // Create a reference from a string. diff --git a/cpp/src/Ice/RouterInfo.cpp b/cpp/src/Ice/RouterInfo.cpp index d5294304d2c..8eb60be1bdd 100644 --- a/cpp/src/Ice/RouterInfo.cpp +++ b/cpp/src/Ice/RouterInfo.cpp @@ -45,7 +45,7 @@ IceInternal::RouterManager::get(const RouterPrx& rtr) { if(!rtr) { - return 0; + return 0; } RouterPrx router = RouterPrx::uncheckedCast(rtr->ice_router(0)); // The router cannot be routed. @@ -56,24 +56,24 @@ IceInternal::RouterManager::get(const RouterPrx& rtr) if(_tableHint != _table.end()) { - if(_tableHint->first == router) - { - p = _tableHint; - } + if(_tableHint->first == router) + { + p = _tableHint; + } } if(p == _table.end()) { - p = _table.find(router); + p = _table.find(router); } if(p == _table.end()) { - _tableHint = _table.insert(_tableHint, pair(router, new RouterInfo(router))); + _tableHint = _table.insert(_tableHint, pair(router, new RouterInfo(router))); } else { - _tableHint = p; + _tableHint = p; } return _tableHint->second; @@ -85,26 +85,26 @@ IceInternal::RouterManager::erase(const RouterPrx& rtr) RouterInfoPtr info; if(rtr) { - RouterPrx router = RouterPrx::uncheckedCast(rtr->ice_router(0)); // The router cannot be routed. - IceUtil::Mutex::Lock sync(*this); - - map::iterator p = _table.end(); - if(_tableHint != _table.end() && _tableHint->first == router) - { - p = _tableHint; - _tableHint = _table.end(); - } - - if(p == _table.end()) - { - p = _table.find(router); - } - - if(p != _table.end()) - { - info = p->second; - _table.erase(p); - } + RouterPrx router = RouterPrx::uncheckedCast(rtr->ice_router(0)); // The router cannot be routed. + IceUtil::Mutex::Lock sync(*this); + + map::iterator p = _table.end(); + if(_tableHint != _table.end() && _tableHint->first == router) + { + p = _tableHint; + _tableHint = _table.end(); + } + + if(p == _table.end()) + { + p = _table.find(router); + } + + if(p != _table.end()) + { + info = p->second; + _table.erase(p); + } } return info; @@ -161,34 +161,34 @@ IceInternal::RouterInfo::getClientEndpoints() if(_clientEndpoints.size() == 0) // Lazy initialization. { - ObjectPrx clientProxy = _router->getClientProxy(); - if(!clientProxy) - { - // - // If getClientProxy() return nil, use router endpoints. - // - _clientEndpoints = _router->__reference()->getEndpoints(); - } - else - { - clientProxy = clientProxy->ice_router(0); // The client proxy cannot be routed. - - // - // In order to avoid creating a new connection to the router, - // we must use the same timeout as the already existing - // connection. - // - try - { - clientProxy = clientProxy->ice_timeout(_router->ice_getConnection()->timeout()); - } - catch(const Ice::CollocationOptimizationException&) - { - // Ignore - collocated router - } - - _clientEndpoints = clientProxy->__reference()->getEndpoints(); - } + ObjectPrx clientProxy = _router->getClientProxy(); + if(!clientProxy) + { + // + // If getClientProxy() return nil, use router endpoints. + // + _clientEndpoints = _router->__reference()->getEndpoints(); + } + else + { + clientProxy = clientProxy->ice_router(0); // The client proxy cannot be routed. + + // + // In order to avoid creating a new connection to the router, + // we must use the same timeout as the already existing + // connection. + // + try + { + clientProxy = clientProxy->ice_timeout(_router->ice_getConnection()->timeout()); + } + catch(const Ice::CollocationOptimizationException&) + { + // Ignore - collocated router + } + + _clientEndpoints = clientProxy->__reference()->getEndpoints(); + } } return _clientEndpoints; @@ -201,15 +201,15 @@ IceInternal::RouterInfo::getServerEndpoints() if(_serverEndpoints.size() == 0) // Lazy initialization. { - ObjectPrx serverProxy = _router->getServerProxy(); - if(!serverProxy) - { - throw NoEndpointException(__FILE__, __LINE__); - } + ObjectPrx serverProxy = _router->getServerProxy(); + if(!serverProxy) + { + throw NoEndpointException(__FILE__, __LINE__); + } - serverProxy = serverProxy->ice_router(0); // The server proxy cannot be routed. + serverProxy = serverProxy->ice_router(0); // The server proxy cannot be routed. - _serverEndpoints = serverProxy->__reference()->getEndpoints(); + _serverEndpoints = serverProxy->__reference()->getEndpoints(); } return _serverEndpoints; @@ -226,25 +226,25 @@ IceInternal::RouterInfo::addProxy(const ObjectPrx& proxy) if(p == _identities.end()) { - // - // Only add the proxy to the router if it's not already in our local map. - // - ObjectProxySeq proxies; - proxies.push_back(proxy); - ObjectProxySeq evictedProxies = _router->addProxies(proxies); - - // - // If we successfully added the proxy to the router, we add it to our local map. - // - _identities.insert(_identities.begin(), proxy->ice_getIdentity()); - - // - // We also must remove whatever proxies the router evicted. - // - for(ObjectProxySeq::iterator q = evictedProxies.begin(); q != evictedProxies.end(); ++q) - { - _identities.erase((*q)->ice_getIdentity()); - } + // + // Only add the proxy to the router if it's not already in our local map. + // + ObjectProxySeq proxies; + proxies.push_back(proxy); + ObjectProxySeq evictedProxies = _router->addProxies(proxies); + + // + // If we successfully added the proxy to the router, we add it to our local map. + // + _identities.insert(_identities.begin(), proxy->ice_getIdentity()); + + // + // We also must remove whatever proxies the router evicted. + // + for(ObjectProxySeq::iterator q = evictedProxies.begin(); q != evictedProxies.end(); ++q) + { + _identities.erase((*q)->ice_getIdentity()); + } } } diff --git a/cpp/src/Ice/ServantManager.cpp b/cpp/src/Ice/ServantManager.cpp index 4f2ad489d1e..0a9a6d010ce 100644 --- a/cpp/src/Ice/ServantManager.cpp +++ b/cpp/src/Ice/ServantManager.cpp @@ -35,26 +35,26 @@ IceInternal::ServantManager::addServant(const ObjectPtr& object, const Identity& if(p == _servantMapMap.end() || p->first != ident) { - p = _servantMapMap.find(ident); + p = _servantMapMap.find(ident); } if(p == _servantMapMap.end()) { - p = _servantMapMap.insert(_servantMapMapHint, pair(ident, FacetMap())); + p = _servantMapMap.insert(_servantMapMapHint, pair(ident, FacetMap())); } else { - if(p->second.find(facet) != p->second.end()) - { - AlreadyRegisteredException ex(__FILE__, __LINE__); - ex.kindOfObject = "servant"; - ex.id = _instance->identityToString(ident); - if(!facet.empty()) - { - ex.id += " -f " + IceUtil::escapeString(facet, ""); - } - throw ex; - } + if(p->second.find(facet) != p->second.end()) + { + AlreadyRegisteredException ex(__FILE__, __LINE__); + ex.kindOfObject = "servant"; + ex.id = _instance->identityToString(ident); + if(!facet.empty()) + { + ex.id += " -f " + IceUtil::escapeString(facet, ""); + } + throw ex; + } } _servantMapMapHint = p; @@ -81,19 +81,19 @@ IceInternal::ServantManager::removeServant(const Identity& ident, const string& if(p == _servantMapMap.end() || p->first != ident) { - p = _servantMapMap.find(ident); + p = _servantMapMap.find(ident); } if(p == _servantMapMap.end() || (q = p->second.find(facet)) == p->second.end()) { - NotRegisteredException ex(__FILE__, __LINE__); - ex.kindOfObject = "servant"; - ex.id = _instance->identityToString(ident); - if(!facet.empty()) - { - ex.id += " -f " + IceUtil::escapeString(facet, ""); - } - throw ex; + NotRegisteredException ex(__FILE__, __LINE__); + ex.kindOfObject = "servant"; + ex.id = _instance->identityToString(ident); + if(!facet.empty()) + { + ex.id += " -f " + IceUtil::escapeString(facet, ""); + } + throw ex; } servant = q->second; @@ -101,15 +101,15 @@ IceInternal::ServantManager::removeServant(const Identity& ident, const string& if(p->second.empty()) { - if(p == _servantMapMapHint) - { - _servantMapMap.erase(p++); - _servantMapMapHint = p; - } - else - { - _servantMapMap.erase(p); - } + if(p == _servantMapMapHint) + { + _servantMapMap.erase(p++); + _servantMapMapHint = p; + } + else + { + _servantMapMap.erase(p); + } } return servant; } @@ -125,27 +125,27 @@ IceInternal::ServantManager::removeAllFacets(const Identity& ident) if(p == _servantMapMap.end() || p->first != ident) { - p = _servantMapMap.find(ident); + p = _servantMapMap.find(ident); } if(p == _servantMapMap.end()) { - NotRegisteredException ex(__FILE__, __LINE__); - ex.kindOfObject = "servant"; - ex.id = _instance->identityToString(ident); - throw ex; + NotRegisteredException ex(__FILE__, __LINE__); + ex.kindOfObject = "servant"; + ex.id = _instance->identityToString(ident); + throw ex; } FacetMap result = p->second; if(p == _servantMapMapHint) { - _servantMapMap.erase(p++); - _servantMapMapHint = p; + _servantMapMap.erase(p++); + _servantMapMapHint = p; } else { - _servantMapMap.erase(p); + _servantMapMap.erase(p); } return result; @@ -171,17 +171,17 @@ IceInternal::ServantManager::findServant(const Identity& ident, const string& fa if(p == servantMapMap.end() || p->first != ident) { - p = servantMapMap.find(ident); + p = servantMapMap.find(ident); } if(p == servantMapMap.end() || (q = p->second.find(facet)) == p->second.end()) { - return 0; + return 0; } else { - _servantMapMapHint = p; - return q->second; + _servantMapMapHint = p; + return q->second; } } @@ -198,17 +198,17 @@ IceInternal::ServantManager::findAllFacets(const Identity& ident) const if(p == servantMapMap.end() || p->first != ident) { - p = servantMapMap.find(ident); + p = servantMapMap.find(ident); } if(p == servantMapMap.end()) { - return FacetMap(); + return FacetMap(); } else { - _servantMapMapHint = p; - return p->second; + _servantMapMapHint = p; + return p->second; } } @@ -230,18 +230,18 @@ IceInternal::ServantManager::hasServant(const Identity& ident) const if(p == servantMapMap.end() || p->first != ident) { - p = servantMapMap.find(ident); + p = servantMapMap.find(ident); } if(p == servantMapMap.end()) { - return false; + return false; } else { - _servantMapMapHint = p; - assert(!p->second.empty()); - return true; + _servantMapMapHint = p; + assert(!p->second.empty()); + return true; } } @@ -255,10 +255,10 @@ IceInternal::ServantManager::addServantLocator(const ServantLocatorPtr& locator, if((_locatorMapHint != _locatorMap.end() && _locatorMapHint->first == category) || _locatorMap.find(category) != _locatorMap.end()) { - AlreadyRegisteredException ex(__FILE__, __LINE__); - ex.kindOfObject = "servant locator"; - ex.id = IceUtil::escapeString(category, ""); - throw ex; + AlreadyRegisteredException ex(__FILE__, __LINE__); + ex.kindOfObject = "servant locator"; + ex.id = IceUtil::escapeString(category, ""); + throw ex; } _locatorMapHint = _locatorMap.insert(_locatorMapHint, pair(category, locator)); @@ -278,30 +278,30 @@ IceInternal::ServantManager::findServantLocator(const string& category) const //assert(_instance); // Must not be called after destruction. map& locatorMap = - const_cast&>(_locatorMap); + const_cast&>(_locatorMap); map::iterator p = locatorMap.end(); if(_locatorMapHint != locatorMap.end()) { - if(_locatorMapHint->first == category) - { - p = _locatorMapHint; - } + if(_locatorMapHint->first == category) + { + p = _locatorMapHint; + } } if(p == locatorMap.end()) { - p = locatorMap.find(category); + p = locatorMap.find(category); } if(p != locatorMap.end()) { - _locatorMapHint = p; - return p->second; + _locatorMapHint = p; + return p->second; } else { - return 0; + return 0; } } @@ -330,40 +330,40 @@ IceInternal::ServantManager::destroy() map locatorMap; { - IceUtil::Mutex::Lock sync(*this); - - assert(_instance); // Must not be called after destruction. - - servantMapMap.swap(_servantMapMap); - _servantMapMapHint = _servantMapMap.end(); - - for(map::const_iterator p = _locatorMap.begin(); p != _locatorMap.end(); ++p) - { - try - { - p->second->deactivate(p->first); - } - catch(const Exception& ex) - { - Error out(_instance->initializationData().logger); - out << "exception during locator deactivation:\n" - << "object adapter: `" << _adapterName << "'\n" - << "locator category: `" << p->first << "'\n" - << ex; - } - catch(...) - { - Error out(_instance->initializationData().logger); - out << "unknown exception during locator deactivation:\n" - << "object adapter: `" << _adapterName << "'\n" - << "locator category: `" << p->first << "'"; - } - } - - locatorMap.swap(_locatorMap); - _locatorMapHint = _locatorMap.end(); - - _instance = 0; + IceUtil::Mutex::Lock sync(*this); + + assert(_instance); // Must not be called after destruction. + + servantMapMap.swap(_servantMapMap); + _servantMapMapHint = _servantMapMap.end(); + + for(map::const_iterator p = _locatorMap.begin(); p != _locatorMap.end(); ++p) + { + try + { + p->second->deactivate(p->first); + } + catch(const Exception& ex) + { + Error out(_instance->initializationData().logger); + out << "exception during locator deactivation:\n" + << "object adapter: `" << _adapterName << "'\n" + << "locator category: `" << p->first << "'\n" + << ex; + } + catch(...) + { + Error out(_instance->initializationData().logger); + out << "unknown exception during locator deactivation:\n" + << "object adapter: `" << _adapterName << "'\n" + << "locator category: `" << p->first << "'"; + } + } + + locatorMap.swap(_locatorMap); + _locatorMapHint = _locatorMap.end(); + + _instance = 0; } // diff --git a/cpp/src/Ice/Service.cpp b/cpp/src/Ice/Service.cpp index 21f6a579eb5..d4232d2aefe 100755 --- a/cpp/src/Ice/Service.cpp +++ b/cpp/src/Ice/Service.cpp @@ -107,19 +107,19 @@ private: { public: - StatusThread(ServiceStatusManager* manager) : - _manager(manager) - { - } + StatusThread(ServiceStatusManager* manager) : + _manager(manager) + { + } - virtual void run() - { - _manager->run(); - } + virtual void run() + { + _manager->run(); + } private: - ServiceStatusManager* _manager; + ServiceStatusManager* _manager; }; friend class StatusThread; @@ -159,26 +159,26 @@ Ice::Service::shutdown() { if(_communicator) { - try - { - _communicator->shutdown(); - } - catch(const CommunicatorDestroyedException&) - { - // - // Expected if the service communicator is being destroyed. - // - } - catch(const Ice::Exception& ex) - { - ostringstream ostr; - ostr << "exception during shutdown:\n" << ex; - warning(ostr.str()); - } - catch(...) - { - warning("unknown exception during shutdown"); - } + try + { + _communicator->shutdown(); + } + catch(const CommunicatorDestroyedException&) + { + // + // Expected if the service communicator is being destroyed. + // + } + catch(const Ice::Exception& ex) + { + ostringstream ostr; + ostr << "exception during shutdown:\n" << ex; + warning(ostr.str()); + } + catch(...) + { + warning("unknown exception during shutdown"); + } } return true; } @@ -204,48 +204,48 @@ Ice::Service::main(int& argc, char* argv[], const InitializationData& initData) { if(strcmp(argv[idx], "--service") == 0) { - // - // When running as a service, we need a logger to use for reporting any - // failures that occur prior to initializing a communicator. After we have - // a communicator, we can use the configured logger instead. If a logger - // is defined in InitializationData, we'll use that. Otherwise, we create - // a temporary event logger. - // - // We postpone the initialization of the communicator until serviceMain so - // that we can incorporate the executable's arguments and the service's - // arguments into one vector. - // - _logger = initData.logger; - if(!_logger) - { - try - { - // - // Use the executable name as the source for the temporary logger. - // - string loggerName = _name; - transform(loggerName.begin(), loggerName.end(), loggerName.begin(), ::tolower); - string::size_type pos = loggerName.find_last_of("\\/"); - if(pos != string::npos) - { - loggerName.erase(0, pos + 1); // Remove leading path. - } - pos = loggerName.rfind(".exe"); - if(pos != string::npos) - { - loggerName.erase(pos, loggerName.size() - pos); // Remove .exe extension. - } - - _logger = new EventLoggerI(loggerName); - } - catch(const IceUtil::Exception& ex) - { - ostringstream ostr; - ostr << ex; - error("unable to create EventLogger:\n" + ostr.str()); - return EXIT_FAILURE; - } - } + // + // When running as a service, we need a logger to use for reporting any + // failures that occur prior to initializing a communicator. After we have + // a communicator, we can use the configured logger instead. If a logger + // is defined in InitializationData, we'll use that. Otherwise, we create + // a temporary event logger. + // + // We postpone the initialization of the communicator until serviceMain so + // that we can incorporate the executable's arguments and the service's + // arguments into one vector. + // + _logger = initData.logger; + if(!_logger) + { + try + { + // + // Use the executable name as the source for the temporary logger. + // + string loggerName = _name; + transform(loggerName.begin(), loggerName.end(), loggerName.begin(), ::tolower); + string::size_type pos = loggerName.find_last_of("\\/"); + if(pos != string::npos) + { + loggerName.erase(0, pos + 1); // Remove leading path. + } + pos = loggerName.rfind(".exe"); + if(pos != string::npos) + { + loggerName.erase(pos, loggerName.size() - pos); // Remove .exe extension. + } + + _logger = new EventLoggerI(loggerName); + } + catch(const IceUtil::Exception& ex) + { + ostringstream ostr; + ostr << ex; + error("unable to create EventLogger:\n" + ostr.str()); + return EXIT_FAILURE; + } + } if(idx + 1 >= argc) { @@ -439,17 +439,17 @@ Ice::Service::main(int& argc, char* argv[], const InitializationData& initData) changeDirectory = false; } - else if(strcmp(argv[idx], "--pidfile") == 0) + else if(strcmp(argv[idx], "--pidfile") == 0) { - if(idx + 1 < argc) - { - pidFile = argv[idx + 1]; - } - else - { - cerr << argv[0] << ": --pidfile must be followed by an argument" << endl; - return EXIT_FAILURE; - } + if(idx + 1 < argc) + { + pidFile = argv[idx + 1]; + } + else + { + cerr << argv[0] << ": --pidfile must be followed by an argument" << endl; + return EXIT_FAILURE; + } for(int i = idx; i + 2 < argc; ++i) { @@ -835,8 +835,8 @@ Ice::Service::startService(const string& name, const vector& args) } else { - showServiceStatus("Service failed to start.", status); - return EXIT_FAILURE; + showServiceStatus("Service failed to start.", status); + return EXIT_FAILURE; } return EXIT_SUCCESS; @@ -893,8 +893,8 @@ Ice::Service::stopService(const string& name) } else { - showServiceStatus("Service failed to stop.", status); - return EXIT_FAILURE; + showServiceStatus("Service failed to stop.", status); + return EXIT_FAILURE; } return EXIT_SUCCESS; @@ -1137,11 +1137,11 @@ Ice::Service::terminateService(DWORD exitCode) status.dwControlsAccepted = 0; if(exitCode != 0) { - status.dwWin32ExitCode = ERROR_SERVICE_SPECIFIC_ERROR; + status.dwWin32ExitCode = ERROR_SERVICE_SPECIFIC_ERROR; } else { - status.dwWin32ExitCode = 0; + status.dwWin32ExitCode = 0; } status.dwServiceSpecificExitCode = exitCode; status.dwCheckPoint = 0; @@ -1155,7 +1155,7 @@ Ice::Service::waitForServiceState(SC_HANDLE hService, DWORD pendingState, SERVIC { if(!QueryServiceStatus(hService, &status)) { - return false; + return false; } // @@ -1226,38 +1226,38 @@ Ice::Service::showServiceStatus(const string& msg, SERVICE_STATUS& status) switch(status.dwCurrentState) { case SERVICE_STOPPED: - state = "STOPPED"; - break; + state = "STOPPED"; + break; case SERVICE_START_PENDING: - state = "START PENDING"; - break; + state = "START PENDING"; + break; case SERVICE_STOP_PENDING: - state = "STOP PENDING"; - break; + state = "STOP PENDING"; + break; case SERVICE_RUNNING: - state = "RUNNING"; - break; + state = "RUNNING"; + break; case SERVICE_CONTINUE_PENDING: - state = "CONTINUE PENDING"; - break; + state = "CONTINUE PENDING"; + break; case SERVICE_PAUSE_PENDING: - state = "PAUSE PENDING"; - break; + state = "PAUSE PENDING"; + break; case SERVICE_PAUSED: - state = "PAUSED"; - break; + state = "PAUSED"; + break; default: - state = "UNKNOWN"; - break; + state = "UNKNOWN"; + break; } ostringstream ostr; ostr << msg << endl - << " Current state: " << state << endl - << " Exit code: " << status.dwWin32ExitCode << endl - << " Service specific exit code: " << status.dwServiceSpecificExitCode << endl - << " Check point: " << status.dwCheckPoint << endl - << " Wait hint: " << status.dwWaitHint; + << " Current state: " << state << endl + << " Exit code: " << status.dwWin32ExitCode << endl + << " Service specific exit code: " << status.dwServiceSpecificExitCode << endl + << " Check point: " << status.dwCheckPoint << endl + << " Wait hint: " << status.dwWaitHint; trace(ostr.str()); } @@ -1314,14 +1314,14 @@ Ice::Service::serviceMain(int argc, char* argv[]) ostringstream ostr; ostr << "exception occurred while initializing a communicator:\n" << ex; error(ostr.str()); - terminateService(EXIT_FAILURE); + terminateService(EXIT_FAILURE); return; } catch(...) { delete[] args; error("unknown exception occurred while initializing a communicator"); - terminateService(EXIT_FAILURE); + terminateService(EXIT_FAILURE); return; } @@ -1345,8 +1345,8 @@ Ice::Service::serviceMain(int argc, char* argv[]) // // Change the current status from START_PENDING to RUNNING. // - serviceStatusManager->stopUpdate(); - serviceStatusManager->changeStatus(SERVICE_RUNNING, SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN); + serviceStatusManager->stopUpdate(); + serviceStatusManager->changeStatus(SERVICE_RUNNING, SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN); // // Wait for the service to be shut down. @@ -1396,21 +1396,21 @@ Ice::Service::control(int ctrl) case SERVICE_CONTROL_SHUTDOWN: case SERVICE_CONTROL_STOP: { - serviceStatusManager->startUpdate(SERVICE_STOP_PENDING); - shutdown(); - break; + serviceStatusManager->startUpdate(SERVICE_STOP_PENDING); + shutdown(); + break; } default: { - if(ctrl != SERVICE_CONTROL_INTERROGATE) - { - ostringstream ostr; - ostr << "unrecognized service control code " << ctrl; - error(ostr.str()); - } + if(ctrl != SERVICE_CONTROL_INTERROGATE) + { + ostringstream ostr; + ostr << "unrecognized service control code " << ctrl; + error(ostr.str()); + } - serviceStatusManager->reportStatus(); - break; + serviceStatusManager->reportStatus(); + break; } } } @@ -1449,20 +1449,20 @@ Ice::ServiceStatusManager::stopUpdate() IceUtil::ThreadPtr thread; { - Lock sync(*this); + Lock sync(*this); - if(_thread) - { - _stopped = true; - notify(); - thread = _thread; - _thread = 0; - } + if(_thread) + { + _stopped = true; + notify(); + thread = _thread; + _thread = 0; + } } if(thread) { - thread->getThreadControl().join(); + thread->getThreadControl().join(); } } @@ -1581,11 +1581,11 @@ Ice::Service::runDaemon(int argc, char* argv[], const InitializationData& initDa break; } cerr << argv[0] << ": failure occurred in daemon"; - if(strlen(msg) > 0) - { - cerr << ':' << endl << msg; - } - cerr << endl; + if(strlen(msg) > 0) + { + cerr << ':' << endl << msg; + } + cerr << endl; _exit(EXIT_FAILURE); } @@ -1644,7 +1644,7 @@ Ice::Service::runDaemon(int argc, char* argv[], const InitializationData& initDa } } - vector fdsToClose; + vector fdsToClose; if(_closeFiles) { // @@ -1665,13 +1665,13 @@ Ice::Service::runDaemon(int argc, char* argv[], const InitializationData& initDa { if(fcntl(i, F_GETFL) != -1) { - // - // Don't close the write end of the pipe. - // - if(i != fds[1]) - { - fdsToClose.push_back(i); - } + // + // Don't close the write end of the pipe. + // + if(i != fds[1]) + { + fdsToClose.push_back(i); + } } } } @@ -1694,21 +1694,21 @@ Ice::Service::runDaemon(int argc, char* argv[], const InitializationData& initDa { // // Close unnecessary file descriptors. - // - PropertiesPtr properties = _communicator->getProperties(); - string stdOut = properties->getProperty("Ice.StdOut"); - string stdErr = properties->getProperty("Ice.StdErr"); + // + PropertiesPtr properties = _communicator->getProperties(); + string stdOut = properties->getProperty("Ice.StdOut"); + string stdErr = properties->getProperty("Ice.StdErr"); - vector::const_iterator p; - for(p = fdsToClose.begin(); p != fdsToClose.end(); ++p) + vector::const_iterator p; + for(p = fdsToClose.begin(); p != fdsToClose.end(); ++p) { - // - // NOTE: Do not close stdout if Ice.StdOut is defined. Likewise for Ice.StdErr. - // - if((*p == 1 && !stdOut.empty()) || (*p == 2 && !stdErr.empty())) - { - continue; - } + // + // NOTE: Do not close stdout if Ice.StdOut is defined. Likewise for Ice.StdErr. + // + if((*p == 1 && !stdOut.empty()) || (*p == 2 && !stdErr.empty())) + { + continue; + } close(*p); } @@ -1718,31 +1718,31 @@ Ice::Service::runDaemon(int argc, char* argv[], const InitializationData& initDa int fd; fd = open("/dev/null", O_RDWR); assert(fd == 0); - if(stdOut.empty()) - { - fd = dup2(0, 1); - assert(fd == 1); - } - if(stdErr.empty()) - { - fd = dup2(1, 2); - assert(fd == 2); - } + if(stdOut.empty()) + { + fd = dup2(0, 1); + assert(fd == 1); + } + if(stdErr.empty()) + { + fd = dup2(1, 2); + assert(fd == 2); + } + } + + // + // Write PID + // + if(_pidFile.size() > 0) + { + ofstream of(_pidFile.c_str()); + of << getpid() << endl; + + if(!of) + { + warning("Could not write PID file " + _pidFile); + } } - - // - // Write PID - // - if(_pidFile.size() > 0) - { - ofstream of(_pidFile.c_str()); - of << getpid() << endl; - - if(!of) - { - warning("Could not write PID file " + _pidFile); - } - } // // Use the configured logger. diff --git a/cpp/src/Ice/SharedContext.h b/cpp/src/Ice/SharedContext.h index c44858ffb34..1d551f9d406 100644 --- a/cpp/src/Ice/SharedContext.h +++ b/cpp/src/Ice/SharedContext.h @@ -32,13 +32,13 @@ public: } SharedContext(const Ice::Context& val) : - _val(val) + _val(val) { } inline const Ice::Context& getValue() { - return _val; + return _val; } private: diff --git a/cpp/src/Ice/SliceChecksums.cpp b/cpp/src/Ice/SliceChecksums.cpp index eb44bfa5946..98390369e18 100644 --- a/cpp/src/Ice/SliceChecksums.cpp +++ b/cpp/src/Ice/SliceChecksums.cpp @@ -22,8 +22,8 @@ public: ~SliceChecksumDictDestroyer() { - delete _sliceChecksums; - _sliceChecksums = 0; + delete _sliceChecksums; + _sliceChecksums = 0; } }; static SliceChecksumDictDestroyer destroyer; @@ -34,7 +34,7 @@ Ice::sliceChecksums() IceUtil::StaticMutex::Lock lock(_mutex); if(_sliceChecksums == 0) { - _sliceChecksums = new SliceChecksumDict(); + _sliceChecksums = new SliceChecksumDict(); } return *_sliceChecksums; } @@ -44,7 +44,7 @@ IceInternal::SliceChecksumInit::SliceChecksumInit(const char* checksums[]) IceUtil::StaticMutex::Lock lock(_mutex); if(_sliceChecksums == 0) { - _sliceChecksums = new SliceChecksumDict(); + _sliceChecksums = new SliceChecksumDict(); } for(int i = 0; checksums[i] != 0; i += 2) diff --git a/cpp/src/Ice/StringConverter.cpp b/cpp/src/Ice/StringConverter.cpp index 566bfac4abb..985111f9aa9 100755 --- a/cpp/src/Ice/StringConverter.cpp +++ b/cpp/src/Ice/StringConverter.cpp @@ -19,8 +19,8 @@ namespace Ice Byte* UnicodeWstringConverter::toUTF8(const wchar_t* sourceStart, - const wchar_t* sourceEnd, - UTF8Buffer& buffer) const + const wchar_t* sourceEnd, + UTF8Buffer& buffer) const { // // The "chunk size" is the maximum of the number of characters in the @@ -34,27 +34,27 @@ UnicodeWstringConverter::toUTF8(const wchar_t* sourceStart, ConversionResult result; while((result = - convertUTFWstringToUTF8(sourceStart, sourceEnd, - targetStart, targetEnd, lenientConversion)) - == targetExhausted) + convertUTFWstringToUTF8(sourceStart, sourceEnd, + targetStart, targetEnd, lenientConversion)) + == targetExhausted) { - targetStart = buffer.getMoreBytes(chunkSize, targetStart); - targetEnd = targetStart + chunkSize; + targetStart = buffer.getMoreBytes(chunkSize, targetStart); + targetEnd = targetStart + chunkSize; } - + switch(result) { - case conversionOK: - break; - case sourceExhausted: - throw StringConversionException(__FILE__, __LINE__, "wide string source exhausted"); - case sourceIllegal: - throw StringConversionException(__FILE__, __LINE__, "wide string source illegal"); - default: - { - assert(0); - throw StringConversionException(__FILE__, __LINE__); - } + case conversionOK: + break; + case sourceExhausted: + throw StringConversionException(__FILE__, __LINE__, "wide string source exhausted"); + case sourceIllegal: + throw StringConversionException(__FILE__, __LINE__, "wide string source illegal"); + default: + { + assert(0); + throw StringConversionException(__FILE__, __LINE__); + } } return targetStart; } @@ -62,24 +62,24 @@ UnicodeWstringConverter::toUTF8(const wchar_t* sourceStart, void UnicodeWstringConverter::fromUTF8(const Byte* sourceStart, const Byte* sourceEnd, - wstring& target) const + wstring& target) const { ConversionResult result = - convertUTF8ToUTFWstring(sourceStart, sourceEnd, target, lenientConversion); + convertUTF8ToUTFWstring(sourceStart, sourceEnd, target, lenientConversion); switch(result) - { - case conversionOK: - break; - case sourceExhausted: - throw StringConversionException(__FILE__, __LINE__, "UTF-8 string source exhausted"); - case sourceIllegal: - throw StringConversionException(__FILE__, __LINE__, "UTF-8 string source illegal"); - default: - { - assert(0); - throw StringConversionException(__FILE__, __LINE__); - } + { + case conversionOK: + break; + case sourceExhausted: + throw StringConversionException(__FILE__, __LINE__, "UTF-8 string source exhausted"); + case sourceIllegal: + throw StringConversionException(__FILE__, __LINE__, "UTF-8 string source illegal"); + default: + { + assert(0); + throw StringConversionException(__FILE__, __LINE__); + } } } } diff --git a/cpp/src/Ice/TcpAcceptor.cpp b/cpp/src/Ice/TcpAcceptor.cpp index 3a933042bbd..193aefe8175 100644 --- a/cpp/src/Ice/TcpAcceptor.cpp +++ b/cpp/src/Ice/TcpAcceptor.cpp @@ -30,8 +30,8 @@ IceInternal::TcpAcceptor::close() { if(_traceLevels->network >= 1) { - Trace out(_logger, _traceLevels->networkCat); - out << "stopping to accept tcp connections at " << toString(); + Trace out(_logger, _traceLevels->networkCat); + out << "stopping to accept tcp connections at " << toString(); } SOCKET fd = _fd; @@ -44,18 +44,18 @@ IceInternal::TcpAcceptor::listen() { try { - doListen(_fd, _backlog); + doListen(_fd, _backlog); } catch(...) { - _fd = INVALID_SOCKET; - throw; + _fd = INVALID_SOCKET; + throw; } if(_traceLevels->network >= 1) { - Trace out(_logger, _traceLevels->networkCat); - out << "accepting tcp connections at " << toString(); + Trace out(_logger, _traceLevels->networkCat); + out << "accepting tcp connections at " << toString(); } } @@ -67,8 +67,8 @@ IceInternal::TcpAcceptor::accept(int timeout) if(_traceLevels->network >= 1) { - Trace out(_logger, _traceLevels->networkCat); - out << "accepted tcp connection\n" << fdToString(fd); + Trace out(_logger, _traceLevels->networkCat); + out << "accepted tcp connection\n" << fdToString(fd); } return new TcpTransceiver(_instance, fd); @@ -116,20 +116,20 @@ IceInternal::TcpAcceptor::TcpAcceptor(const InstancePtr& instance, const string& try { - _fd = createSocket(false); - setBlock(_fd, false); - getAddress(host, port, _addr); - if(_traceLevels->network >= 2) - { - Trace out(_logger, _traceLevels->networkCat); - out << "attempting to bind to tcp socket " << toString(); - } - doBind(_fd, _addr); + _fd = createSocket(false); + setBlock(_fd, false); + getAddress(host, port, _addr); + if(_traceLevels->network >= 2) + { + Trace out(_logger, _traceLevels->networkCat); + out << "attempting to bind to tcp socket " << toString(); + } + doBind(_fd, _addr); } catch(...) { - _fd = INVALID_SOCKET; - throw; + _fd = INVALID_SOCKET; + throw; } } diff --git a/cpp/src/Ice/TcpConnector.cpp b/cpp/src/Ice/TcpConnector.cpp index 22ca94ab15d..935aaa9a84a 100644 --- a/cpp/src/Ice/TcpConnector.cpp +++ b/cpp/src/Ice/TcpConnector.cpp @@ -24,8 +24,8 @@ IceInternal::TcpConnector::connect(int timeout) { if(_traceLevels->network >= 2) { - Trace out(_logger, _traceLevels->networkCat); - out << "trying to establish tcp connection to " << toString(); + Trace out(_logger, _traceLevels->networkCat); + out << "trying to establish tcp connection to " << toString(); } SOCKET fd = createSocket(false); @@ -34,8 +34,8 @@ IceInternal::TcpConnector::connect(int timeout) if(_traceLevels->network >= 1) { - Trace out(_logger, _traceLevels->networkCat); - out << "tcp connection established\n" << fdToString(fd); + Trace out(_logger, _traceLevels->networkCat); + out << "tcp connection established\n" << fdToString(fd); } return new TcpTransceiver(_instance, fd); diff --git a/cpp/src/Ice/TcpEndpointI.cpp b/cpp/src/Ice/TcpEndpointI.cpp index 817008a0141..6cf54872826 100644 --- a/cpp/src/Ice/TcpEndpointI.cpp +++ b/cpp/src/Ice/TcpEndpointI.cpp @@ -22,7 +22,7 @@ using namespace Ice; using namespace IceInternal; IceInternal::TcpEndpointI::TcpEndpointI(const InstancePtr& instance, const string& ho, Int po, Int ti, - const string& conId, bool co, bool pub) : + const string& conId, bool co, bool pub) : _instance(instance), _host(ho), _port(po), @@ -47,96 +47,96 @@ IceInternal::TcpEndpointI::TcpEndpointI(const InstancePtr& instance, const strin while(true) { - beg = str.find_first_not_of(delim, end); - if(beg == string::npos) - { - break; - } - - end = str.find_first_of(delim, beg); - if(end == string::npos) - { - end = str.length(); - } - - string option = str.substr(beg, end - beg); - if(option.length() != 2 || option[0] != '-') - { - EndpointParseException ex(__FILE__, __LINE__); - ex.str = "tcp " + str; - throw ex; - } - - string argument; - string::size_type argumentBeg = str.find_first_not_of(delim, end); - if(argumentBeg != string::npos && str[argumentBeg] != '-') - { - beg = argumentBeg; - end = str.find_first_of(delim, beg); - if(end == string::npos) - { - end = str.length(); - } - argument = str.substr(beg, end - beg); - } - - switch(option[1]) - { - case 'h': - { - if(argument.empty()) - { - EndpointParseException ex(__FILE__, __LINE__); - ex.str = "tcp " + str; - throw ex; - } - const_cast(_host) = argument; - break; - } - - case 'p': - { - istringstream p(argument); - if(!(p >> const_cast(_port)) || !p.eof() || _port < 0 || _port > 65535) - { - EndpointParseException ex(__FILE__, __LINE__); - ex.str = "tcp " + str; - throw ex; - } - break; - } - - case 't': - { - istringstream t(argument); - if(!(t >> const_cast(_timeout)) || !t.eof()) - { - EndpointParseException ex(__FILE__, __LINE__); - ex.str = "tcp " + str; - throw ex; - } - break; - } - - case 'z': - { - if(!argument.empty()) - { - EndpointParseException ex(__FILE__, __LINE__); - ex.str = "tcp " + str; - throw ex; - } - const_cast(_compress) = true; - break; - } - - default: - { - EndpointParseException ex(__FILE__, __LINE__); - ex.str = "tcp " + str; - throw ex; - } - } + beg = str.find_first_not_of(delim, end); + if(beg == string::npos) + { + break; + } + + end = str.find_first_of(delim, beg); + if(end == string::npos) + { + end = str.length(); + } + + string option = str.substr(beg, end - beg); + if(option.length() != 2 || option[0] != '-') + { + EndpointParseException ex(__FILE__, __LINE__); + ex.str = "tcp " + str; + throw ex; + } + + string argument; + string::size_type argumentBeg = str.find_first_not_of(delim, end); + if(argumentBeg != string::npos && str[argumentBeg] != '-') + { + beg = argumentBeg; + end = str.find_first_of(delim, beg); + if(end == string::npos) + { + end = str.length(); + } + argument = str.substr(beg, end - beg); + } + + switch(option[1]) + { + case 'h': + { + if(argument.empty()) + { + EndpointParseException ex(__FILE__, __LINE__); + ex.str = "tcp " + str; + throw ex; + } + const_cast(_host) = argument; + break; + } + + case 'p': + { + istringstream p(argument); + if(!(p >> const_cast(_port)) || !p.eof() || _port < 0 || _port > 65535) + { + EndpointParseException ex(__FILE__, __LINE__); + ex.str = "tcp " + str; + throw ex; + } + break; + } + + case 't': + { + istringstream t(argument); + if(!(t >> const_cast(_timeout)) || !t.eof()) + { + EndpointParseException ex(__FILE__, __LINE__); + ex.str = "tcp " + str; + throw ex; + } + break; + } + + case 'z': + { + if(!argument.empty()) + { + EndpointParseException ex(__FILE__, __LINE__); + ex.str = "tcp " + str; + throw ex; + } + const_cast(_compress) = true; + break; + } + + default: + { + EndpointParseException ex(__FILE__, __LINE__); + ex.str = "tcp " + str; + throw ex; + } + } } } @@ -181,11 +181,11 @@ IceInternal::TcpEndpointI::toString() const s << "tcp -h " << _host << " -p " << _port; if(_timeout != -1) { - s << " -t " << _timeout; + s << " -t " << _timeout; } if(_compress) { - s << " -z"; + s << " -z"; } return s.str(); } @@ -207,11 +207,11 @@ IceInternal::TcpEndpointI::timeout(Int timeout) const { if(timeout == _timeout) { - return const_cast(this); + return const_cast(this); } else { - return new TcpEndpointI(_instance, _host, _port, timeout, _connectionId, _compress, _publish); + return new TcpEndpointI(_instance, _host, _port, timeout, _connectionId, _compress, _publish); } } @@ -220,11 +220,11 @@ IceInternal::TcpEndpointI::connectionId(const string& connectionId) const { if(connectionId == _connectionId) { - return const_cast(this); + return const_cast(this); } else { - return new TcpEndpointI(_instance, _host, _port, _timeout, connectionId, _compress, _publish); + return new TcpEndpointI(_instance, _host, _port, _timeout, connectionId, _compress, _publish); } } @@ -239,11 +239,11 @@ IceInternal::TcpEndpointI::compress(bool compress) const { if(compress == _compress) { - return const_cast(this); + return const_cast(this); } else { - return new TcpEndpointI(_instance, _host, _port, _timeout, _connectionId, compress, _publish); + return new TcpEndpointI(_instance, _host, _port, _timeout, _connectionId, compress, _publish); } } @@ -297,18 +297,18 @@ IceInternal::TcpEndpointI::expand(bool server) const { if(_host.empty()) { - const_cast(_host) = _instance->defaultsAndOverrides()->defaultHost; - if(_host.empty()) - { - if(server) - { - const_cast(_host) = "0.0.0.0"; - } - else - { - const_cast(_host) = "127.0.0.1"; - } - } + const_cast(_host) = _instance->defaultsAndOverrides()->defaultHost; + if(_host.empty()) + { + if(server) + { + const_cast(_host) = "0.0.0.0"; + } + else + { + const_cast(_host) = "127.0.0.1"; + } + } } else if(_host == "*") { @@ -319,11 +319,11 @@ IceInternal::TcpEndpointI::expand(bool server) const if(_host == "0.0.0.0") { vector hosts = getLocalHosts(); - for(unsigned int i = 0; i < hosts.size(); ++i) - { - endps.push_back(new TcpEndpointI(_instance, hosts[i], _port, _timeout, _connectionId, _compress, - hosts.size() == 1 || hosts[i] != "127.0.0.1")); - } + for(unsigned int i = 0; i < hosts.size(); ++i) + { + endps.push_back(new TcpEndpointI(_instance, hosts[i], _port, _timeout, _connectionId, _compress, + hosts.size() == 1 || hosts[i] != "127.0.0.1")); + } } else { @@ -350,7 +350,7 @@ IceInternal::TcpEndpointI::equivalent(const AcceptorPtr& acceptor) const const TcpAcceptor* tcpAcceptor = dynamic_cast(acceptor.get()); if(!tcpAcceptor) { - return false; + return false; } return tcpAcceptor->equivalent(_host, _port); } @@ -361,52 +361,52 @@ IceInternal::TcpEndpointI::operator==(const EndpointI& r) const const TcpEndpointI* p = dynamic_cast(&r); if(!p) { - return false; + return false; } if(this == p) { - return true; + return true; } if(_port != p->_port) { - return false; + return false; } if(_timeout != p->_timeout) { - return false; + return false; } if(_connectionId != p->_connectionId) { - return false; + return false; } if(_compress != p->_compress) { - return false; + return false; } if(_host != p->_host) { - // - // We do the most time-consuming part of the comparison last. - // - struct sockaddr_in laddr; - struct sockaddr_in raddr; - try - { - getAddress(_host, _port, laddr); - getAddress(p->_host, p->_port, raddr); - } - catch(const DNSException&) - { - return false; - } + // + // We do the most time-consuming part of the comparison last. + // + struct sockaddr_in laddr; + struct sockaddr_in raddr; + try + { + getAddress(_host, _port, laddr); + getAddress(p->_host, p->_port, raddr); + } + catch(const DNSException&) + { + return false; + } - return compareAddress(laddr, raddr); + return compareAddress(laddr, raddr); } return true; @@ -429,76 +429,76 @@ IceInternal::TcpEndpointI::operator<(const EndpointI& r) const if(this == p) { - return false; + return false; } if(_port < p->_port) { - return true; + return true; } else if(p->_port < _port) { - return false; + return false; } if(_timeout < p->_timeout) { - return true; + return true; } else if(p->_timeout < _timeout) { - return false; + return false; } if(_connectionId < p->_connectionId) { - return true; + return true; } else if(p->_connectionId < _connectionId) { - return false; + return false; } if(!_compress && p->_compress) { - return true; + return true; } else if(p->_compress < _compress) { - return false; + return false; } if(_host != p->_host) { - // - // We do the most time-consuming part of the comparison last. - // - struct sockaddr_in laddr; - try - { - getAddress(_host, _port, laddr); - } - catch(const DNSException&) - { - } - - struct sockaddr_in raddr; - try - { - getAddress(p->_host, p->_port, raddr); - } - catch(const DNSException&) - { - } - - if(laddr.sin_addr.s_addr < raddr.sin_addr.s_addr) - { - return true; - } - else if(raddr.sin_addr.s_addr < laddr.sin_addr.s_addr) - { - return false; - } + // + // We do the most time-consuming part of the comparison last. + // + struct sockaddr_in laddr; + try + { + getAddress(_host, _port, laddr); + } + catch(const DNSException&) + { + } + + struct sockaddr_in raddr; + try + { + getAddress(p->_host, p->_port, raddr); + } + catch(const DNSException&) + { + } + + if(laddr.sin_addr.s_addr < raddr.sin_addr.s_addr) + { + return true; + } + else if(raddr.sin_addr.s_addr < laddr.sin_addr.s_addr) + { + return false; + } } return false; diff --git a/cpp/src/Ice/TcpTransceiver.cpp b/cpp/src/Ice/TcpTransceiver.cpp index 4eb5f54fa02..541843223b7 100644 --- a/cpp/src/Ice/TcpTransceiver.cpp +++ b/cpp/src/Ice/TcpTransceiver.cpp @@ -32,20 +32,20 @@ IceInternal::TcpTransceiver::close() { if(_traceLevels->network >= 1) { - Trace out(_logger, _traceLevels->networkCat); - out << "closing tcp connection\n" << toString(); + Trace out(_logger, _traceLevels->networkCat); + out << "closing tcp connection\n" << toString(); } assert(_fd != INVALID_SOCKET); try { - closeSocket(_fd); - _fd = INVALID_SOCKET; + closeSocket(_fd); + _fd = INVALID_SOCKET; } catch(const SocketException&) { - _fd = INVALID_SOCKET; - throw; + _fd = INVALID_SOCKET; + throw; } } @@ -54,8 +54,8 @@ IceInternal::TcpTransceiver::shutdownWrite() { if(_traceLevels->network >= 2) { - Trace out(_logger, _traceLevels->networkCat); - out << "shutting down tcp connection for writing\n" << toString(); + Trace out(_logger, _traceLevels->networkCat); + out << "shutting down tcp connection for writing\n" << toString(); } assert(_fd != INVALID_SOCKET); @@ -67,8 +67,8 @@ IceInternal::TcpTransceiver::shutdownReadWrite() { if(_traceLevels->network >= 2) { - Trace out(_logger, _traceLevels->networkCat); - out << "shutting down tcp connection for reading and writing\n" << toString(); + Trace out(_logger, _traceLevels->networkCat); + out << "shutting down tcp connection for reading and writing\n" << toString(); } assert(_fd != INVALID_SOCKET); @@ -87,112 +87,112 @@ IceInternal::TcpTransceiver::write(Buffer& buf, int timeout) // if(_isPeerLocal && packetSize > 64 * 1024) { - packetSize = 64 * 1024; + packetSize = 64 * 1024; } #endif while(buf.i != buf.b.end()) { - assert(_fd != INVALID_SOCKET); - ssize_t ret = ::send(_fd, reinterpret_cast(&*buf.i), packetSize, 0); - - if(ret == 0) - { - ConnectionLostException ex(__FILE__, __LINE__); - ex.error = 0; - throw ex; - } - - if(ret == SOCKET_ERROR) - { - if(interrupted()) - { - continue; - } - - if(noBuffers() && packetSize > 1024) - { - packetSize /= 2; - continue; - } - - if(wouldBlock()) - { - repeatSelect: - - int rs; - assert(_fd != INVALID_SOCKET); + assert(_fd != INVALID_SOCKET); + ssize_t ret = ::send(_fd, reinterpret_cast(&*buf.i), packetSize, 0); + + if(ret == 0) + { + ConnectionLostException ex(__FILE__, __LINE__); + ex.error = 0; + throw ex; + } + + if(ret == SOCKET_ERROR) + { + if(interrupted()) + { + continue; + } + + if(noBuffers() && packetSize > 1024) + { + packetSize /= 2; + continue; + } + + if(wouldBlock()) + { + repeatSelect: + + int rs; + assert(_fd != INVALID_SOCKET); #ifdef _WIN32 - FD_SET(_fd, &_wFdSet); - - if(timeout >= 0) - { - struct timeval tv; - tv.tv_sec = timeout / 1000; - tv.tv_usec = (timeout - tv.tv_sec * 1000) * 1000; - rs = ::select(static_cast(_fd + 1), 0, &_wFdSet, 0, &tv); - } - else - { - rs = ::select(static_cast(_fd + 1), 0, &_wFdSet, 0, 0); - } + FD_SET(_fd, &_wFdSet); + + if(timeout >= 0) + { + struct timeval tv; + tv.tv_sec = timeout / 1000; + tv.tv_usec = (timeout - tv.tv_sec * 1000) * 1000; + rs = ::select(static_cast(_fd + 1), 0, &_wFdSet, 0, &tv); + } + else + { + rs = ::select(static_cast(_fd + 1), 0, &_wFdSet, 0, 0); + } #else - struct pollfd pollFd[1]; - pollFd[0].fd = _fd; - pollFd[0].events = POLLOUT; - rs = ::poll(pollFd, 1, timeout); -#endif - if(rs == SOCKET_ERROR) - { - if(interrupted()) - { - goto repeatSelect; - } - - SocketException ex(__FILE__, __LINE__); - ex.error = getSocketErrno(); - throw ex; - } - - if(rs == 0) - { - throw TimeoutException(__FILE__, __LINE__); - } - - continue; - } - - if(connectionLost()) - { - ConnectionLostException ex(__FILE__, __LINE__); - ex.error = getSocketErrno(); - throw ex; - } - else - { - SocketException ex(__FILE__, __LINE__); - ex.error = getSocketErrno(); - throw ex; - } - } - - if(_traceLevels->network >= 3) - { - Trace out(_logger, _traceLevels->networkCat); - out << "sent " << ret << " of " << packetSize << " bytes via tcp\n" << toString(); - } - - if(_stats) - { - _stats->bytesSent(type(), static_cast(ret)); - } - - buf.i += ret; - - if(packetSize > buf.b.end() - buf.i) - { - packetSize = static_cast(buf.b.end() - buf.i); - } + struct pollfd pollFd[1]; + pollFd[0].fd = _fd; + pollFd[0].events = POLLOUT; + rs = ::poll(pollFd, 1, timeout); +#endif + if(rs == SOCKET_ERROR) + { + if(interrupted()) + { + goto repeatSelect; + } + + SocketException ex(__FILE__, __LINE__); + ex.error = getSocketErrno(); + throw ex; + } + + if(rs == 0) + { + throw TimeoutException(__FILE__, __LINE__); + } + + continue; + } + + if(connectionLost()) + { + ConnectionLostException ex(__FILE__, __LINE__); + ex.error = getSocketErrno(); + throw ex; + } + else + { + SocketException ex(__FILE__, __LINE__); + ex.error = getSocketErrno(); + throw ex; + } + } + + if(_traceLevels->network >= 3) + { + Trace out(_logger, _traceLevels->networkCat); + out << "sent " << ret << " of " << packetSize << " bytes via tcp\n" << toString(); + } + + if(_stats) + { + _stats->bytesSent(type(), static_cast(ret)); + } + + buf.i += ret; + + if(packetSize > buf.b.end() - buf.i) + { + packetSize = static_cast(buf.b.end() - buf.i); + } } } @@ -204,125 +204,125 @@ IceInternal::TcpTransceiver::read(Buffer& buf, int timeout) while(buf.i != buf.b.end()) { - assert(_fd != INVALID_SOCKET); - ssize_t ret = ::recv(_fd, reinterpret_cast(&*buf.i), packetSize, 0); - - if(ret == 0) - { - // - // If the connection is lost when reading data, we shut - // down the write end of the socket. This helps to unblock - // threads that are stuck in send() or select() while - // sending data. Note: I don't really understand why - // send() or select() sometimes don't detect a connection - // loss. Therefore this helper to make them detect it. - // - //assert(_fd != INVALID_SOCKET); - //shutdownSocketReadWrite(_fd); - - ConnectionLostException ex(__FILE__, __LINE__); - ex.error = 0; - throw ex; - } - - if(ret == SOCKET_ERROR) - { - if(interrupted()) - { - continue; - } - - if(noBuffers() && packetSize > 1024) - { - packetSize /= 2; - continue; - } - - if(wouldBlock()) - { - repeatSelect: - - int rs; - assert(_fd != INVALID_SOCKET); + assert(_fd != INVALID_SOCKET); + ssize_t ret = ::recv(_fd, reinterpret_cast(&*buf.i), packetSize, 0); + + if(ret == 0) + { + // + // If the connection is lost when reading data, we shut + // down the write end of the socket. This helps to unblock + // threads that are stuck in send() or select() while + // sending data. Note: I don't really understand why + // send() or select() sometimes don't detect a connection + // loss. Therefore this helper to make them detect it. + // + //assert(_fd != INVALID_SOCKET); + //shutdownSocketReadWrite(_fd); + + ConnectionLostException ex(__FILE__, __LINE__); + ex.error = 0; + throw ex; + } + + if(ret == SOCKET_ERROR) + { + if(interrupted()) + { + continue; + } + + if(noBuffers() && packetSize > 1024) + { + packetSize /= 2; + continue; + } + + if(wouldBlock()) + { + repeatSelect: + + int rs; + assert(_fd != INVALID_SOCKET); #ifdef _WIN32 - FD_SET(_fd, &_rFdSet); - - if(timeout >= 0) - { - struct timeval tv; - tv.tv_sec = timeout / 1000; - tv.tv_usec = (timeout - tv.tv_sec * 1000) * 1000; - rs = ::select(static_cast(_fd + 1), &_rFdSet, 0, 0, &tv); - } - else - { - rs = ::select(static_cast(_fd + 1), &_rFdSet, 0, 0, 0); - } + FD_SET(_fd, &_rFdSet); + + if(timeout >= 0) + { + struct timeval tv; + tv.tv_sec = timeout / 1000; + tv.tv_usec = (timeout - tv.tv_sec * 1000) * 1000; + rs = ::select(static_cast(_fd + 1), &_rFdSet, 0, 0, &tv); + } + else + { + rs = ::select(static_cast(_fd + 1), &_rFdSet, 0, 0, 0); + } #else - struct pollfd pollFd[1]; - pollFd[0].fd = _fd; - pollFd[0].events = POLLIN; - rs = ::poll(pollFd, 1, timeout); + struct pollfd pollFd[1]; + pollFd[0].fd = _fd; + pollFd[0].events = POLLIN; + rs = ::poll(pollFd, 1, timeout); #endif - if(rs == SOCKET_ERROR) - { - if(interrupted()) - { - goto repeatSelect; - } - - SocketException ex(__FILE__, __LINE__); - ex.error = getSocketErrno(); - throw ex; - } - - if(rs == 0) - { - throw TimeoutException(__FILE__, __LINE__); - } - - continue; - } - - if(connectionLost()) - { - // - // See the commment above about shutting down the - // socket if the connection is lost while reading - // data. - // - //assert(_fd != INVALID_SOCKET); - //shutdownSocketReadWrite(_fd); - - ConnectionLostException ex(__FILE__, __LINE__); - ex.error = getSocketErrno(); - throw ex; - } - else - { - SocketException ex(__FILE__, __LINE__); - ex.error = getSocketErrno(); - throw ex; - } - } - - if(_traceLevels->network >= 3) - { - Trace out(_logger, _traceLevels->networkCat); - out << "received " << ret << " of " << packetSize << " bytes via tcp\n" << toString(); - } - - if(_stats) - { - _stats->bytesReceived(type(), static_cast(ret)); - } - - buf.i += ret; - - if(packetSize > buf.b.end() - buf.i) - { - packetSize = static_cast(buf.b.end() - buf.i); - } + if(rs == SOCKET_ERROR) + { + if(interrupted()) + { + goto repeatSelect; + } + + SocketException ex(__FILE__, __LINE__); + ex.error = getSocketErrno(); + throw ex; + } + + if(rs == 0) + { + throw TimeoutException(__FILE__, __LINE__); + } + + continue; + } + + if(connectionLost()) + { + // + // See the commment above about shutting down the + // socket if the connection is lost while reading + // data. + // + //assert(_fd != INVALID_SOCKET); + //shutdownSocketReadWrite(_fd); + + ConnectionLostException ex(__FILE__, __LINE__); + ex.error = getSocketErrno(); + throw ex; + } + else + { + SocketException ex(__FILE__, __LINE__); + ex.error = getSocketErrno(); + throw ex; + } + } + + if(_traceLevels->network >= 3) + { + Trace out(_logger, _traceLevels->networkCat); + out << "received " << ret << " of " << packetSize << " bytes via tcp\n" << toString(); + } + + if(_stats) + { + _stats->bytesReceived(type(), static_cast(ret)); + } + + buf.i += ret; + + if(packetSize > buf.b.end() - buf.i) + { + packetSize = static_cast(buf.b.end() - buf.i); + } } } @@ -348,7 +348,7 @@ IceInternal::TcpTransceiver::checkSendSize(const Buffer& buf, size_t messageSize { if(buf.b.size() > messageSizeMax) { - throw MemoryLimitException(__FILE__, __LINE__); + throw MemoryLimitException(__FILE__, __LINE__); } } diff --git a/cpp/src/Ice/ThreadPool.cpp b/cpp/src/Ice/ThreadPool.cpp index 87b315b9cba..6e122f575f0 100644 --- a/cpp/src/Ice/ThreadPool.cpp +++ b/cpp/src/Ice/ThreadPool.cpp @@ -61,9 +61,9 @@ IceInternal::ThreadPool::ThreadPool(const InstancePtr& instance, const string& p _epollFd = epoll_create(1); if(_epollFd < 0) { - SocketException ex(__FILE__, __LINE__); - ex.error = getSocketErrno(); - throw ex; + SocketException ex(__FILE__, __LINE__); + ex.error = getSocketErrno(); + throw ex; } _events.resize(1); epoll_event event; @@ -71,9 +71,9 @@ IceInternal::ThreadPool::ThreadPool(const InstancePtr& instance, const string& p event.data.fd = _fdIntrRead; if(epoll_ctl(_epollFd, EPOLL_CTL_ADD, _fdIntrRead, &event) != 0) { - SocketException ex(__FILE__, __LINE__); - ex.error = getSocketErrno(); - throw ex; + SocketException ex(__FILE__, __LINE__); + ex.error = getSocketErrno(); + throw ex; } #else _pollFdSet.resize(1); @@ -90,8 +90,8 @@ IceInternal::ThreadPool::ThreadPool(const InstancePtr& instance, const string& p if(size < 1) { Warning out(_instance->initializationData().logger); - out << _prefix << ".Size < 1; Size adjusted to 1"; - size = 1; + out << _prefix << ".Size < 1; Size adjusted to 1"; + size = 1; } int sizeMax = @@ -99,17 +99,17 @@ IceInternal::ThreadPool::ThreadPool(const InstancePtr& instance, const string& p if(sizeMax < size) { Warning out(_instance->initializationData().logger); - out << _prefix << ".SizeMax < " << _prefix << ".Size; SizeMax adjusted to Size (" << size << ")"; - sizeMax = size; - } + out << _prefix << ".SizeMax < " << _prefix << ".Size; SizeMax adjusted to Size (" << size << ")"; + sizeMax = size; + } int sizeWarn = _instance->initializationData().properties-> - getPropertyAsIntWithDefault(_prefix + ".SizeWarn", sizeMax * 80 / 100); + getPropertyAsIntWithDefault(_prefix + ".SizeWarn", sizeMax * 80 / 100); if(sizeWarn > sizeMax) { - Warning out(_instance->initializationData().logger); - out << _prefix << ".SizeWarn > " << _prefix << ".SizeMax; adjusted SizeWarn to SizeMax (" << sizeMax << ")"; - sizeWarn = sizeMax; + Warning out(_instance->initializationData().logger); + out << _prefix << ".SizeWarn > " << _prefix << ".SizeMax; adjusted SizeWarn to SizeMax (" << sizeMax << ")"; + sizeWarn = sizeMax; } const_cast(_size) = size; @@ -120,38 +120,38 @@ IceInternal::ThreadPool::ThreadPool(const InstancePtr& instance, const string& p if(stackSize < 0) { Warning out(_instance->initializationData().logger); - out << _prefix << ".StackSize < 0; Size adjusted to OS default"; - stackSize = 0; + out << _prefix << ".StackSize < 0; Size adjusted to OS default"; + stackSize = 0; } const_cast(_stackSize) = static_cast(stackSize); __setNoDelete(true); try { - for(int i = 0 ; i < _size ; ++i) - { - IceUtil::ThreadPtr thread = new EventHandlerThread(this); - thread->start(_stackSize); - _threads.push_back(thread); - ++_running; - } + for(int i = 0 ; i < _size ; ++i) + { + IceUtil::ThreadPtr thread = new EventHandlerThread(this); + thread->start(_stackSize); + _threads.push_back(thread); + ++_running; + } } catch(const IceUtil::Exception& ex) { - { - Error out(_instance->initializationData().logger); - out << "cannot create thread for `" << _prefix << "':\n" << ex; - } + { + Error out(_instance->initializationData().logger); + out << "cannot create thread for `" << _prefix << "':\n" << ex; + } - destroy(); - joinWithAllThreads(); - __setNoDelete(false); - throw; + destroy(); + joinWithAllThreads(); + __setNoDelete(false); + throw; } catch(...) { - __setNoDelete(false); - throw; + __setNoDelete(false); + throw; } __setNoDelete(false); } @@ -162,33 +162,33 @@ IceInternal::ThreadPool::~ThreadPool() try { - closeSocket(_fdIntrWrite); + closeSocket(_fdIntrWrite); } catch(const LocalException& ex) { - Error out(_instance->initializationData().logger); - out << "exception in `" << _prefix << "' while calling closeSocket():\n" << ex; + Error out(_instance->initializationData().logger); + out << "exception in `" << _prefix << "' while calling closeSocket():\n" << ex; } try { - closeSocket(_fdIntrRead); + closeSocket(_fdIntrRead); } catch(const LocalException& ex) { - Error out(_instance->initializationData().logger); - out << "exception in `" << _prefix << "' while calling closeSocket():\n" << ex; + Error out(_instance->initializationData().logger); + out << "exception in `" << _prefix << "' while calling closeSocket():\n" << ex; } #ifdef __linux try { - closeSocket(_epollFd); + closeSocket(_epollFd); } catch(const LocalException& ex) { - Error out(_instance->initializationData().logger); - out << "exception in `" << _prefix << "' while calling closeSocket():\n" << ex; + Error out(_instance->initializationData().logger); + out << "exception in `" << _prefix << "' while calling closeSocket():\n" << ex; } #endif } @@ -214,15 +214,15 @@ IceInternal::ThreadPool::incFdsInUse() assert(!_destroyed); if(_fdsInUse + 1 > FD_SETSIZE) { - Warning warn(_instance->initializationData().logger); - warn << "maximum number of connections exceeded"; + Warning warn(_instance->initializationData().logger); + warn << "maximum number of connections exceeded"; - // - // No appropriate errno. - // - SocketException ex(__FILE__, __LINE__); - ex.error = 0; - throw ex; + // + // No appropriate errno. + // + SocketException ex(__FILE__, __LINE__); + ex.error = 0; + throw ex; } ++_fdsInUse; #endif @@ -238,8 +238,8 @@ IceInternal::ThreadPool::decFdsInUse() assert(!_destroyed); if(_fdsInUse <= 1) { - Trace trace(_instance->initializationData().logger, "ThreadPool"); - trace << _prefix << ": about to assert"; + Trace trace(_instance->initializationData().logger, "ThreadPool"); + trace << _prefix << ": about to assert"; } assert(_fdsInUse > 1); // _fdIntrRead is always in use. --_fdsInUse; @@ -269,41 +269,41 @@ IceInternal::ThreadPool::promoteFollower() { if(_sizeMax > 1) { - IceUtil::Monitor::Lock sync(*this); + IceUtil::Monitor::Lock sync(*this); - assert(!_promote); - _promote = true; - notify(); + assert(!_promote); + _promote = true; + notify(); - if(!_destroyed) - { - assert(_inUse >= 0); - ++_inUse; - - if(_inUse == _sizeWarn) - { - Warning out(_instance->initializationData().logger); - out << "thread pool `" << _prefix << "' is running low on threads\n" - << "Size=" << _size << ", " << "SizeMax=" << _sizeMax << ", " << "SizeWarn=" << _sizeWarn; - } - - assert(_inUse <= _running); - if(_inUse < _sizeMax && _inUse == _running) - { - try - { - IceUtil::ThreadPtr thread = new EventHandlerThread(this); - thread->start(_stackSize); - _threads.push_back(thread); - ++_running; - } - catch(const IceUtil::Exception& ex) - { - Error out(_instance->initializationData().logger); - out << "cannot create thread for `" << _prefix << "':\n" << ex; - } - } - } + if(!_destroyed) + { + assert(_inUse >= 0); + ++_inUse; + + if(_inUse == _sizeWarn) + { + Warning out(_instance->initializationData().logger); + out << "thread pool `" << _prefix << "' is running low on threads\n" + << "Size=" << _size << ", " << "SizeMax=" << _sizeMax << ", " << "SizeWarn=" << _sizeWarn; + } + + assert(_inUse <= _running); + if(_inUse < _sizeMax && _inUse == _running) + { + try + { + IceUtil::ThreadPtr thread = new EventHandlerThread(this); + thread->start(_stackSize); + _threads.push_back(thread); + ++_running; + } + catch(const IceUtil::Exception& ex) + { + Error out(_instance->initializationData().logger); + out << "cannot create thread for `" << _prefix << "':\n" << ex; + } + } + } } } @@ -319,7 +319,7 @@ IceInternal::ThreadPool::joinWithAllThreads() assert(_destroyed); for(vector::iterator p = _threads.begin(); p != _threads.end(); ++p) { - (*p)->getThreadControl().join(); + (*p)->getThreadControl().join(); } } @@ -339,26 +339,26 @@ repeat: #ifdef _WIN32 if(::recv(_fdIntrRead, &c, 1, 0) == SOCKET_ERROR) { - if(interrupted()) - { - goto repeat; - } + if(interrupted()) + { + goto repeat; + } - SocketException ex(__FILE__, __LINE__); - ex.error = getSocketErrno(); - throw ex; + SocketException ex(__FILE__, __LINE__); + ex.error = getSocketErrno(); + throw ex; } #else if(::read(_fdIntrRead, &c, 1) == -1) { - if(interrupted()) - { - goto repeat; - } + if(interrupted()) + { + goto repeat; + } - SyscallException ex(__FILE__, __LINE__); - ex.error = getSystemErrno(); - throw ex; + SyscallException ex(__FILE__, __LINE__); + ex.error = getSystemErrno(); + throw ex; } #endif } @@ -373,26 +373,26 @@ repeat: #ifdef _WIN32 if(::send(_fdIntrWrite, &c, 1, 0) == SOCKET_ERROR) { - if(interrupted()) - { - goto repeat; - } + if(interrupted()) + { + goto repeat; + } - SocketException ex(__FILE__, __LINE__); - ex.error = getSocketErrno(); - throw ex; + SocketException ex(__FILE__, __LINE__); + ex.error = getSocketErrno(); + throw ex; } #else if(::write(_fdIntrWrite, &c, 1) == -1) { - if(interrupted()) - { - goto repeat; - } + if(interrupted()) + { + goto repeat; + } - SyscallException ex(__FILE__, __LINE__); - ex.error = getSystemErrno(); - throw ex; + SyscallException ex(__FILE__, __LINE__); + ex.error = getSystemErrno(); + throw ex; } #endif } @@ -404,467 +404,467 @@ IceInternal::ThreadPool::run() if(_sizeMax > 1) { - IceUtil::Monitor::Lock sync(*this); + IceUtil::Monitor::Lock sync(*this); - while(!_promote) - { - wait(); - } + while(!_promote) + { + wait(); + } - _promote = false; + _promote = false; } while(true) { - int ret; + int ret; #if defined(_WIN32) - fd_set fdSet; - memcpy(&fdSet, &_fdSet, sizeof(fd_set)); - if(_timeout > 0) - { - struct timeval tv; - tv.tv_sec = _timeout; - tv.tv_usec = 0; - ret = ::select(static_cast(_maxFd + 1), &fdSet, 0, 0, &tv); - } - else - { - ret = ::select(static_cast(_maxFd + 1), &fdSet, 0, 0, 0); - } + fd_set fdSet; + memcpy(&fdSet, &_fdSet, sizeof(fd_set)); + if(_timeout > 0) + { + struct timeval tv; + tv.tv_sec = _timeout; + tv.tv_usec = 0; + ret = ::select(static_cast(_maxFd + 1), &fdSet, 0, 0, &tv); + } + else + { + ret = ::select(static_cast(_maxFd + 1), &fdSet, 0, 0, 0); + } #elif defined(__linux) - ret = epoll_wait(_epollFd, &_events[0], _events.size(), _timeout > 0 ? _timeout * 1000 : -1); + ret = epoll_wait(_epollFd, &_events[0], _events.size(), _timeout > 0 ? _timeout * 1000 : -1); #else - ret = poll(&_pollFdSet[0], _pollFdSet.size(), _timeout > 0 ? _timeout * 1000 : -1); + ret = poll(&_pollFdSet[0], _pollFdSet.size(), _timeout > 0 ? _timeout * 1000 : -1); #endif - if(ret == SOCKET_ERROR) - { - if(interrupted()) - { - continue; - } - - SocketException ex(__FILE__, __LINE__); - ex.error = getSocketErrno(); - //throw ex; - Error out(_instance->initializationData().logger); - out << "exception in `" << _prefix << "':\n" << ex; - continue; - } - - EventHandlerPtr handler; - bool finished = false; - bool shutdown = false; + if(ret == SOCKET_ERROR) + { + if(interrupted()) + { + continue; + } + + SocketException ex(__FILE__, __LINE__); + ex.error = getSocketErrno(); + //throw ex; + Error out(_instance->initializationData().logger); + out << "exception in `" << _prefix << "':\n" << ex; + continue; + } + + EventHandlerPtr handler; + bool finished = false; + bool shutdown = false; - { - IceUtil::Monitor::Lock sync(*this); - - if(ret == 0) // We initiate a shutdown if there is a thread pool timeout. - { - assert(_timeout > 0); - _timeout = 0; - shutdown = true; - } - else - { - bool interrupted = false; + { + IceUtil::Monitor::Lock sync(*this); + + if(ret == 0) // We initiate a shutdown if there is a thread pool timeout. + { + assert(_timeout > 0); + _timeout = 0; + shutdown = true; + } + else + { + bool interrupted = false; #if defined(_WIN32) - interrupted = FD_ISSET(_fdIntrRead, &fdSet); + interrupted = FD_ISSET(_fdIntrRead, &fdSet); #elif defined(__linux) for(int i = 0; i < ret; ++i) - { - if(_events[i].data.fd == _fdIntrRead) - { - interrupted = true; - break; - } - } + { + if(_events[i].data.fd == _fdIntrRead) + { + interrupted = true; + break; + } + } #else - assert(_pollFdSet[0].fd == _fdIntrRead); + assert(_pollFdSet[0].fd == _fdIntrRead); interrupted = _pollFdSet[0].revents != 0; #endif - if(interrupted) - { - // - // There are two possiblities for an interrupt: - // - // 1. The thread pool has been destroyed. - // - // 2. An event handler was registered or unregistered. - // + if(interrupted) + { + // + // There are two possiblities for an interrupt: + // + // 1. The thread pool has been destroyed. + // + // 2. An event handler was registered or unregistered. + // - // - // Thread pool destroyed? - // - if(_destroyed) - { - // - // Don't clear the interrupt if destroyed, so that - // the other threads exit as well. - // - return true; - } - - clearInterrupt(); - - // - // An event handler must have been registered or - // unregistered. - // - assert(!_changes.empty()); - pair change = _changes.front(); - _changes.pop_front(); - - if(change.second) // Addition if handler is set. - { - _handlerMap.insert(change); + // + // Thread pool destroyed? + // + if(_destroyed) + { + // + // Don't clear the interrupt if destroyed, so that + // the other threads exit as well. + // + return true; + } + + clearInterrupt(); + + // + // An event handler must have been registered or + // unregistered. + // + assert(!_changes.empty()); + pair change = _changes.front(); + _changes.pop_front(); + + if(change.second) // Addition if handler is set. + { + _handlerMap.insert(change); #if defined(_WIN32) - FD_SET(change.first, &_fdSet); + FD_SET(change.first, &_fdSet); #elif defined(__linux) - epoll_event event; - event.events = EPOLLIN; - event.data.fd = change.first; - if(epoll_ctl(_epollFd, EPOLL_CTL_ADD, change.first, &event) != 0) - { - Error out(_instance->initializationData().logger); - out << "error while adding filedescriptor to epoll set:\n"; - out << errorToString(getSocketErrno()); - continue; - } - _events.resize(_handlerMap.size() + 1); + epoll_event event; + event.events = EPOLLIN; + event.data.fd = change.first; + if(epoll_ctl(_epollFd, EPOLL_CTL_ADD, change.first, &event) != 0) + { + Error out(_instance->initializationData().logger); + out << "error while adding filedescriptor to epoll set:\n"; + out << errorToString(getSocketErrno()); + continue; + } + _events.resize(_handlerMap.size() + 1); #else - struct pollfd pollFd; - pollFd.fd = change.first; - pollFd.events = POLLIN; - _pollFdSet.push_back(pollFd); + struct pollfd pollFd; + pollFd.fd = change.first; + pollFd.events = POLLIN; + _pollFdSet.push_back(pollFd); #endif - _maxFd = max(_maxFd, change.first); - _minFd = min(_minFd, change.first); - continue; - } - else // Removal if handler is not set. - { - map::iterator p = _handlerMap.find(change.first); - assert(p != _handlerMap.end()); - handler = p->second; - finished = true; - _handlerMap.erase(p); + _maxFd = max(_maxFd, change.first); + _minFd = min(_minFd, change.first); + continue; + } + else // Removal if handler is not set. + { + map::iterator p = _handlerMap.find(change.first); + assert(p != _handlerMap.end()); + handler = p->second; + finished = true; + _handlerMap.erase(p); #if defined(_WIN32) - FD_CLR(change.first, &_fdSet); + FD_CLR(change.first, &_fdSet); #elif defined(__linux) - epoll_event event; - event.events = 0; - if(epoll_ctl(_epollFd, EPOLL_CTL_DEL, change.first, &event) != 0) - { - Error out(_instance->initializationData().logger); - out << "error while adding filedescriptor to epoll set:\n"; - out << errorToString(getSocketErrno()); - continue; - } - _events.resize(_handlerMap.size() + 1); + epoll_event event; + event.events = 0; + if(epoll_ctl(_epollFd, EPOLL_CTL_DEL, change.first, &event) != 0) + { + Error out(_instance->initializationData().logger); + out << "error while adding filedescriptor to epoll set:\n"; + out << errorToString(getSocketErrno()); + continue; + } + _events.resize(_handlerMap.size() + 1); #else - for(vector::iterator p = _pollFdSet.begin(); p != _pollFdSet.end(); ++p) - { - if(p->fd == change.first) - { - _pollFdSet.erase(p); - break; - } - } + for(vector::iterator p = _pollFdSet.begin(); p != _pollFdSet.end(); ++p) + { + if(p->fd == change.first) + { + _pollFdSet.erase(p); + break; + } + } #endif - _maxFd = _fdIntrRead; - _minFd = _fdIntrRead; - if(!_handlerMap.empty()) - { - _maxFd = max(_maxFd, (--_handlerMap.end())->first); - _minFd = min(_minFd, _handlerMap.begin()->first); - } - // Don't continue; we have to call - // finished() on the event handler below, outside - // the thread synchronization. - } - } - else - { - // - // Round robin for the filedescriptors. - // - SOCKET largerFd = _maxFd + 1; - SOCKET smallestFd = _maxFd + 1; + _maxFd = _fdIntrRead; + _minFd = _fdIntrRead; + if(!_handlerMap.empty()) + { + _maxFd = max(_maxFd, (--_handlerMap.end())->first); + _minFd = min(_minFd, _handlerMap.begin()->first); + } + // Don't continue; we have to call + // finished() on the event handler below, outside + // the thread synchronization. + } + } + else + { + // + // Round robin for the filedescriptors. + // + SOCKET largerFd = _maxFd + 1; + SOCKET smallestFd = _maxFd + 1; #if defined(_WIN32) - if(fdSet.fd_count == 0) - { - Error out(_instance->initializationData().logger); - out << "select() in `" << _prefix << "' returned " << ret - << " but no filedescriptor is readable"; - continue; - } - for(u_short i = 0; i < fdSet.fd_count; ++i) - { - SOCKET fd = fdSet.fd_array[i]; + if(fdSet.fd_count == 0) + { + Error out(_instance->initializationData().logger); + out << "select() in `" << _prefix << "' returned " << ret + << " but no filedescriptor is readable"; + continue; + } + for(u_short i = 0; i < fdSet.fd_count; ++i) + { + SOCKET fd = fdSet.fd_array[i]; #elif defined(__linux) - for(int i = 0; i < ret; ++i) - { - SOCKET fd = _events[i].data.fd; + for(int i = 0; i < ret; ++i) + { + SOCKET fd = _events[i].data.fd; #else for(vector::const_iterator p = _pollFdSet.begin(); p != _pollFdSet.end(); ++p) - { - if(p->revents == 0) - { - continue; - } - SOCKET fd = p->fd; + { + if(p->revents == 0) + { + continue; + } + SOCKET fd = p->fd; #endif - assert(fd != INVALID_SOCKET); - if(fd > _lastFd || _lastFd == INVALID_SOCKET) - { - largerFd = min(largerFd, fd); - } - - smallestFd = min(smallestFd, fd); - } - - if(largerFd <= _maxFd) - { - assert(largerFd >= _minFd); - _lastFd = largerFd; - } - else - { - assert(smallestFd >= _minFd && smallestFd <= _maxFd); - _lastFd = smallestFd; - } - assert(_lastFd != _fdIntrRead); - map::iterator p = _handlerMap.find(_lastFd); - if(p == _handlerMap.end()) - { - Error out(_instance->initializationData().logger); - out << "filedescriptor " << _lastFd << " not registered with `" << _prefix << "'"; - continue; - } - - handler = p->second; - } - } - } - - // - // Now we are outside the thread synchronization. - // + assert(fd != INVALID_SOCKET); + if(fd > _lastFd || _lastFd == INVALID_SOCKET) + { + largerFd = min(largerFd, fd); + } + + smallestFd = min(smallestFd, fd); + } + + if(largerFd <= _maxFd) + { + assert(largerFd >= _minFd); + _lastFd = largerFd; + } + else + { + assert(smallestFd >= _minFd && smallestFd <= _maxFd); + _lastFd = smallestFd; + } + assert(_lastFd != _fdIntrRead); + map::iterator p = _handlerMap.find(_lastFd); + if(p == _handlerMap.end()) + { + Error out(_instance->initializationData().logger); + out << "filedescriptor " << _lastFd << " not registered with `" << _prefix << "'"; + continue; + } + + handler = p->second; + } + } + } + + // + // Now we are outside the thread synchronization. + // - if(shutdown) - { - // - // Initiate server shutdown. - // - ObjectAdapterFactoryPtr factory; - try - { - factory = _instance->objectAdapterFactory(); - } - catch(const Ice::CommunicatorDestroyedException&) - { - continue; - } + if(shutdown) + { + // + // Initiate server shutdown. + // + ObjectAdapterFactoryPtr factory; + try + { + factory = _instance->objectAdapterFactory(); + } + catch(const Ice::CommunicatorDestroyedException&) + { + continue; + } - promoteFollower(); - factory->shutdown(); + promoteFollower(); + factory->shutdown(); - // - // No "continue", because we want shutdown to be done in - // its own thread from this pool. Therefore we called - // promoteFollower(). - // - } - else - { - assert(handler); - - if(finished) - { - // - // Notify a handler about it's removal from the thread - // pool. - // - try - { - // - // "self" is faster than "this", as the reference - // count is not modified. - // - handler->finished(self); - } - catch(const LocalException& ex) - { - Error out(_instance->initializationData().logger); - out << "exception in `" << _prefix << "' while calling finished():\n" - << ex << '\n' << handler->toString(); - } + // + // No "continue", because we want shutdown to be done in + // its own thread from this pool. Therefore we called + // promoteFollower(). + // + } + else + { + assert(handler); + + if(finished) + { + // + // Notify a handler about it's removal from the thread + // pool. + // + try + { + // + // "self" is faster than "this", as the reference + // count is not modified. + // + handler->finished(self); + } + catch(const LocalException& ex) + { + Error out(_instance->initializationData().logger); + out << "exception in `" << _prefix << "' while calling finished():\n" + << ex << '\n' << handler->toString(); + } - // - // No "continue", because we want finished() to be - // called in its own thread from this pool. Note that - // this means that finished() must call - // promoteFollower(). - // - } - else - { - // - // If the handler is "readable", try to read a - // message. - // - BasicStream stream(_instance.get()); - if(handler->readable()) - { - try - { - read(handler); - } - catch(const TimeoutException&) // Expected. - { - continue; - } - catch(const DatagramLimitException&) // Expected. - { - continue; - } - catch(const SocketException& ex) - { - handler->exception(ex); - continue; - } - catch(const LocalException& ex) - { - if(handler->datagram()) - { - if(_instance->initializationData().properties-> - getPropertyAsInt("Ice.Warn.Connections") > 0) - { - Warning out(_instance->initializationData().logger); - out << "datagram connection exception:\n" << ex << '\n' << handler->toString(); - } - } - else - { - handler->exception(ex); - } - continue; - } - - stream.swap(handler->_stream); - assert(stream.i == stream.b.end()); - } - - // - // Provide a new mesage to the handler. - // - try - { - // - // "self" is faster than "this", as the reference - // count is not modified. - // - handler->message(stream, self); - } - catch(const LocalException& ex) - { - Error out(_instance->initializationData().logger); - out << "exception in `" << _prefix << "' while calling message():\n" - << ex << '\n' << handler->toString(); - } - - // - // No "continue", because we want message() to be - // called in its own thread from this pool. Note that - // this means that message() must call - // promoteFollower(). - // - } - } + // + // No "continue", because we want finished() to be + // called in its own thread from this pool. Note that + // this means that finished() must call + // promoteFollower(). + // + } + else + { + // + // If the handler is "readable", try to read a + // message. + // + BasicStream stream(_instance.get()); + if(handler->readable()) + { + try + { + read(handler); + } + catch(const TimeoutException&) // Expected. + { + continue; + } + catch(const DatagramLimitException&) // Expected. + { + continue; + } + catch(const SocketException& ex) + { + handler->exception(ex); + continue; + } + catch(const LocalException& ex) + { + if(handler->datagram()) + { + if(_instance->initializationData().properties-> + getPropertyAsInt("Ice.Warn.Connections") > 0) + { + Warning out(_instance->initializationData().logger); + out << "datagram connection exception:\n" << ex << '\n' << handler->toString(); + } + } + else + { + handler->exception(ex); + } + continue; + } + + stream.swap(handler->_stream); + assert(stream.i == stream.b.end()); + } + + // + // Provide a new mesage to the handler. + // + try + { + // + // "self" is faster than "this", as the reference + // count is not modified. + // + handler->message(stream, self); + } + catch(const LocalException& ex) + { + Error out(_instance->initializationData().logger); + out << "exception in `" << _prefix << "' while calling message():\n" + << ex << '\n' << handler->toString(); + } + + // + // No "continue", because we want message() to be + // called in its own thread from this pool. Note that + // this means that message() must call + // promoteFollower(). + // + } + } - if(_sizeMax > 1) - { - IceUtil::Monitor::Lock sync(*this); - - if(!_destroyed) - { - // - // First we reap threads that have been destroyed before. - // - int sz = static_cast(_threads.size()); - assert(_running <= sz); - if(_running < sz) - { - vector::iterator start = - partition(_threads.begin(), _threads.end(), IceUtil::constMemFun(&IceUtil::Thread::isAlive)); + if(_sizeMax > 1) + { + IceUtil::Monitor::Lock sync(*this); + + if(!_destroyed) + { + // + // First we reap threads that have been destroyed before. + // + int sz = static_cast(_threads.size()); + assert(_running <= sz); + if(_running < sz) + { + vector::iterator start = + partition(_threads.begin(), _threads.end(), IceUtil::constMemFun(&IceUtil::Thread::isAlive)); - for(vector::iterator p = start; p != _threads.end(); ++p) - { - (*p)->getThreadControl().join(); - } + for(vector::iterator p = start; p != _threads.end(); ++p) + { + (*p)->getThreadControl().join(); + } - _threads.erase(start, _threads.end()); - } - - // - // Now we check if this thread can be destroyed, based - // on a load factor. - // + _threads.erase(start, _threads.end()); + } + + // + // Now we check if this thread can be destroyed, based + // on a load factor. + // - // - // The load factor jumps immediately to the number of - // threads that are currently in use, but decays - // exponentially if the number of threads in use is - // smaller than the load factor. This reflects that we - // create threads immediately when they are needed, - // but want the number of threads to slowly decline to - // the configured minimum. - // - double inUse = static_cast(_inUse); - if(_load < inUse) - { - _load = inUse; - } - else - { - const double loadFactor = 0.05; // TODO: Configurable? - const double oneMinusLoadFactor = 1 - loadFactor; - _load = _load * oneMinusLoadFactor + inUse * loadFactor; - } - - if(_running > _size) - { - int load = static_cast(_load + 0.5); + // + // The load factor jumps immediately to the number of + // threads that are currently in use, but decays + // exponentially if the number of threads in use is + // smaller than the load factor. This reflects that we + // create threads immediately when they are needed, + // but want the number of threads to slowly decline to + // the configured minimum. + // + double inUse = static_cast(_inUse); + if(_load < inUse) + { + _load = inUse; + } + else + { + const double loadFactor = 0.05; // TODO: Configurable? + const double oneMinusLoadFactor = 1 - loadFactor; + _load = _load * oneMinusLoadFactor + inUse * loadFactor; + } + + if(_running > _size) + { + int load = static_cast(_load + 0.5); - // - // We add one to the load factor because on - // additional thread is needed for select(). - // - if(load + 1 < _running) - { - assert(_inUse > 0); - --_inUse; - - assert(_running > 0); - --_running; - - return false; - } - } - - assert(_inUse > 0); - --_inUse; - } + // + // We add one to the load factor because on + // additional thread is needed for select(). + // + if(load + 1 < _running) + { + assert(_inUse > 0); + --_inUse; + + assert(_running > 0); + --_running; + + return false; + } + } + + assert(_inUse > 0); + --_inUse; + } - while(!_promote) - { - wait(); - } - - _promote = false; - } + while(!_promote) + { + wait(); + } + + _promote = false; + } } } @@ -875,32 +875,32 @@ IceInternal::ThreadPool::read(const EventHandlerPtr& handler) if(stream.b.size() == 0) { - stream.b.resize(headerSize); - stream.i = stream.b.begin(); + stream.b.resize(headerSize); + stream.i = stream.b.begin(); } if(stream.i != stream.b.end()) { - handler->read(stream); - assert(stream.i == stream.b.end()); + handler->read(stream); + assert(stream.i == stream.b.end()); } ptrdiff_t pos = stream.i - stream.b.begin(); if(pos < headerSize) { - // - // This situation is possible for small UDP packets. - // - throw IllegalMessageSizeException(__FILE__, __LINE__); + // + // This situation is possible for small UDP packets. + // + throw IllegalMessageSizeException(__FILE__, __LINE__); } stream.i = stream.b.begin(); const Byte* m; stream.readBlob(m, static_cast(sizeof(magic))); if(m[0] != magic[0] || m[1] != magic[1] || m[2] != magic[2] || m[3] != magic[3]) { - BadMagicException ex(__FILE__, __LINE__); - ex.badMagic = Ice::ByteSeq(&m[0], &m[0] + sizeof(magic)); - throw ex; + BadMagicException ex(__FILE__, __LINE__); + ex.badMagic = Ice::ByteSeq(&m[0], &m[0] + sizeof(magic)); + throw ex; } Byte pMajor; Byte pMinor; @@ -909,12 +909,12 @@ IceInternal::ThreadPool::read(const EventHandlerPtr& handler) if(pMajor != protocolMajor || static_cast(pMinor) > static_cast(protocolMinor)) { - UnsupportedProtocolException ex(__FILE__, __LINE__); - ex.badMajor = static_cast(pMajor); - ex.badMinor = static_cast(pMinor); - ex.major = static_cast(protocolMajor); - ex.minor = static_cast(protocolMinor); - throw ex; + UnsupportedProtocolException ex(__FILE__, __LINE__); + ex.badMajor = static_cast(pMajor); + ex.badMinor = static_cast(pMinor); + ex.major = static_cast(protocolMajor); + ex.minor = static_cast(protocolMinor); + throw ex; } Byte eMajor; Byte eMinor; @@ -923,12 +923,12 @@ IceInternal::ThreadPool::read(const EventHandlerPtr& handler) if(eMajor != encodingMajor || static_cast(eMinor) > static_cast(encodingMinor)) { - UnsupportedEncodingException ex(__FILE__, __LINE__); - ex.badMajor = static_cast(eMajor); - ex.badMinor = static_cast(eMinor); - ex.major = static_cast(encodingMajor); - ex.minor = static_cast(encodingMinor); - throw ex; + UnsupportedEncodingException ex(__FILE__, __LINE__); + ex.badMajor = static_cast(eMajor); + ex.badMinor = static_cast(eMinor); + ex.major = static_cast(encodingMajor); + ex.minor = static_cast(encodingMinor); + throw ex; } Byte messageType; stream.read(messageType); @@ -938,36 +938,36 @@ IceInternal::ThreadPool::read(const EventHandlerPtr& handler) stream.read(size); if(size < headerSize) { - throw IllegalMessageSizeException(__FILE__, __LINE__); + throw IllegalMessageSizeException(__FILE__, __LINE__); } if(size > static_cast(_instance->messageSizeMax())) { - throw MemoryLimitException(__FILE__, __LINE__); + throw MemoryLimitException(__FILE__, __LINE__); } if(size > static_cast(stream.b.size())) { - stream.b.resize(size); + stream.b.resize(size); } stream.i = stream.b.begin() + pos; if(stream.i != stream.b.end()) { - if(handler->datagram()) - { - if(_warnUdp) - { - Warning out(_instance->initializationData().logger); - out << "DatagramLimitException: maximum size of " << pos << " exceeded"; - stream.resize(0); - stream.i = stream.b.begin(); - } - throw DatagramLimitException(__FILE__, __LINE__); - } - else - { - handler->read(stream); - assert(stream.i == stream.b.end()); - } + if(handler->datagram()) + { + if(_warnUdp) + { + Warning out(_instance->initializationData().logger); + out << "DatagramLimitException: maximum size of " << pos << " exceeded"; + stream.resize(0); + stream.i = stream.b.begin(); + } + throw DatagramLimitException(__FILE__, __LINE__); + } + else + { + handler->read(stream); + assert(stream.i == stream.b.end()); + } } } @@ -988,39 +988,39 @@ IceInternal::ThreadPool::EventHandlerThread::run() try { - promote = _pool->run(); + promote = _pool->run(); } catch(const Exception& ex) - { - Error out(_pool->_instance->initializationData().logger); - out << "exception in `" << _pool->_prefix << "':\n" << ex; - promote = true; + { + Error out(_pool->_instance->initializationData().logger); + out << "exception in `" << _pool->_prefix << "':\n" << ex; + promote = true; } catch(const std::exception& ex) { - Error out(_pool->_instance->initializationData().logger); - out << "std::exception in `" << _pool->_prefix << "':\n" << ex.what(); - promote = true; + Error out(_pool->_instance->initializationData().logger); + out << "std::exception in `" << _pool->_prefix << "':\n" << ex.what(); + promote = true; } catch(...) { - Error out(_pool->_instance->initializationData().logger); - out << "unknown exception in `" << _pool->_prefix << "'"; - promote = true; + Error out(_pool->_instance->initializationData().logger); + out << "unknown exception in `" << _pool->_prefix << "'"; + promote = true; } if(promote && _pool->_sizeMax > 1) { - // - // Promote a follower, but w/o modifying _inUse or creating - // new threads. - // - { - IceUtil::Monitor::Lock sync(*_pool.get()); - assert(!_pool->_promote); - _pool->_promote = true; - _pool->notify(); - } + // + // Promote a follower, but w/o modifying _inUse or creating + // new threads. + // + { + IceUtil::Monitor::Lock sync(*_pool.get()); + assert(!_pool->_promote); + _pool->_promote = true; + _pool->notify(); + } } if(_pool->_instance->initializationData().threadHook) diff --git a/cpp/src/Ice/ThreadPool.h b/cpp/src/Ice/ThreadPool.h index a0ecc923a46..6cda824ee5e 100644 --- a/cpp/src/Ice/ThreadPool.h +++ b/cpp/src/Ice/ThreadPool.h @@ -94,13 +94,13 @@ private: class EventHandlerThread : public IceUtil::Thread { public: - - EventHandlerThread(const ThreadPoolPtr&); - virtual void run(); + + EventHandlerThread(const ThreadPoolPtr&); + virtual void run(); private: - ThreadPoolPtr _pool; + ThreadPoolPtr _pool; }; friend class EventHandlerThread; diff --git a/cpp/src/Ice/TraceUtil.cpp b/cpp/src/Ice/TraceUtil.cpp index 6dfc11c029c..cc89bf153ee 100644 --- a/cpp/src/Ice/TraceUtil.cpp +++ b/cpp/src/Ice/TraceUtil.cpp @@ -53,29 +53,29 @@ printRequestHeader(ostream& s, BasicStream& stream) s << "\nmode = " << static_cast(mode) << ' '; switch(mode) { - case Normal: - { - s << "(normal)"; - break; - } - - case Nonmutating: - { - s << "(nonmutating)"; - break; - } - - case Idempotent: - { - s << "(idempotent)"; - break; - } - - default: - { - s << "(unknown)"; - break; - } + case Normal: + { + s << "(normal)"; + break; + } + + case Nonmutating: + { + s << "(nonmutating)"; + break; + } + + case Idempotent: + { + s << "(idempotent)"; + break; + } + + default: + { + s << "(unknown)"; + break; + } } Int sz; @@ -83,14 +83,14 @@ printRequestHeader(ostream& s, BasicStream& stream) s << "\ncontext = "; while(sz--) { - pair pair; - stream.read(pair.first); - stream.read(pair.second); - s << pair.first << '/' << pair.second; - if(sz) - { - s << ", "; - } + pair pair; + stream.read(pair.first); + stream.read(pair.second); + s << pair.first << '/' << pair.second; + if(sz) + { + s << ", "; + } } } @@ -98,7 +98,7 @@ static void printHeader(ostream& s, BasicStream& stream) { Byte magicNumber; - stream.read(magicNumber); // Don't bother printing the magic number + stream.read(magicNumber); // Don't bother printing the magic number stream.read(magicNumber); stream.read(magicNumber); stream.read(magicNumber); @@ -123,41 +123,41 @@ printHeader(ostream& s, BasicStream& stream) switch(type) { - case requestMsg: - { - s << "(request)"; - break; - } - - case requestBatchMsg: - { - s << "(batch request)"; - break; - } - - case replyMsg: - { - s << "(reply)"; - break; - } - - case closeConnectionMsg: - { - s << "(close connection)"; - break; - } - - case validateConnectionMsg: - { - s << "(validate connection)"; - break; - } - - default: - { - s << "(unknown)"; - break; - } + case requestMsg: + { + s << "(request)"; + break; + } + + case requestBatchMsg: + { + s << "(batch request)"; + break; + } + + case replyMsg: + { + s << "(reply)"; + break; + } + + case closeConnectionMsg: + { + s << "(close connection)"; + break; + } + + case validateConnectionMsg: + { + s << "(validate connection)"; + break; + } + + default: + { + s << "(unknown)"; + break; + } } Byte compress; @@ -166,29 +166,29 @@ printHeader(ostream& s, BasicStream& stream) switch(compress) { - case 0: - { - s << "(not compressed; do not compress response, if any)"; - break; - } - - case 1: - { - s << "(not compressed; compress response, if any)"; - break; - } - - case 2: - { - s << "(compressed; compress response, if any)"; - break; - } - - default: - { - s << "(unknown)"; - break; - } + case 0: + { + s << "(not compressed; do not compress response, if any)"; + break; + } + + case 1: + { + s << "(not compressed; compress response, if any)"; + break; + } + + case 2: + { + s << "(compressed; compress response, if any)"; + break; + } + + default: + { + s << "(unknown)"; + break; + } } Int size; @@ -198,198 +198,198 @@ printHeader(ostream& s, BasicStream& stream) void IceInternal::traceHeader(const char* heading, const BasicStream& str, const LoggerPtr& logger, - const TraceLevelsPtr& tl) + const TraceLevelsPtr& tl) { if(tl->protocol >= 1) { - BasicStream& stream = const_cast(str); - BasicStream::Container::iterator p = stream.i; - stream.i = stream.b.begin(); + BasicStream& stream = const_cast(str); + BasicStream::Container::iterator p = stream.i; + stream.i = stream.b.begin(); - ostringstream s; - s << heading; - printHeader(s, stream); + ostringstream s; + s << heading; + printHeader(s, stream); - logger->trace(tl->protocolCat, s.str()); - stream.i = p; + logger->trace(tl->protocolCat, s.str()); + stream.i = p; } } void IceInternal::traceRequest(const char* heading, const BasicStream& str, const LoggerPtr& logger, - const TraceLevelsPtr& tl) + const TraceLevelsPtr& tl) { if(tl->protocol >= 1) { - BasicStream& stream = const_cast(str); - BasicStream::Container::iterator p = stream.i; - stream.i = stream.b.begin(); - - ostringstream s; - s << heading; - printHeader(s, stream); - - Int requestId; - stream.read(requestId); - s << "\nrequest id = " << requestId; - if(requestId == 0) - { - s << " (oneway)"; - } - - printRequestHeader(s, stream); - - logger->trace(tl->protocolCat, s.str()); - stream.i = p; + BasicStream& stream = const_cast(str); + BasicStream::Container::iterator p = stream.i; + stream.i = stream.b.begin(); + + ostringstream s; + s << heading; + printHeader(s, stream); + + Int requestId; + stream.read(requestId); + s << "\nrequest id = " << requestId; + if(requestId == 0) + { + s << " (oneway)"; + } + + printRequestHeader(s, stream); + + logger->trace(tl->protocolCat, s.str()); + stream.i = p; } } void IceInternal::traceBatchRequest(const char* heading, const BasicStream& str, const LoggerPtr& logger, - const TraceLevelsPtr& tl) + const TraceLevelsPtr& tl) { if(tl->protocol >= 1) { - BasicStream& stream = const_cast(str); - BasicStream::Container::iterator p = stream.i; - stream.i = stream.b.begin(); - - ostringstream s; - s << heading; - printHeader(s, stream); - - int batchRequestNum; - stream.read(batchRequestNum); - s << "\nnumber of requests = " << batchRequestNum; - - for(int i = 0; i < batchRequestNum; ++i) - { - s << "\nrequest #" << i << ':'; - printRequestHeader(s, stream); - stream.skipEncaps(); - } - - logger->trace(tl->protocolCat, s.str()); - stream.i = p; + BasicStream& stream = const_cast(str); + BasicStream::Container::iterator p = stream.i; + stream.i = stream.b.begin(); + + ostringstream s; + s << heading; + printHeader(s, stream); + + int batchRequestNum; + stream.read(batchRequestNum); + s << "\nnumber of requests = " << batchRequestNum; + + for(int i = 0; i < batchRequestNum; ++i) + { + s << "\nrequest #" << i << ':'; + printRequestHeader(s, stream); + stream.skipEncaps(); + } + + logger->trace(tl->protocolCat, s.str()); + stream.i = p; } } void IceInternal::traceReply(const char* heading, const BasicStream& str, const LoggerPtr& logger, - const TraceLevelsPtr& tl) + const TraceLevelsPtr& tl) { if(tl->protocol >= 1) { - BasicStream& stream = const_cast(str); - BasicStream::Container::iterator p = stream.i; - stream.i = stream.b.begin(); - - ostringstream s; - s << heading; - printHeader(s, stream); - - Int requestId; - stream.read(requestId); - s << "\nrequest id = " << requestId; - - Byte status; - stream.read(status); - s << "\nreply status = " << static_cast(status) << ' '; - switch(static_cast(status)) - { - case DispatchOK: - { - s << "(ok)"; - break; - } - - case DispatchUserException: - { - s << "(user exception)"; - break; - } - - case DispatchObjectNotExist: - case DispatchFacetNotExist: - case DispatchOperationNotExist: - { - switch(static_cast(status)) - { - case DispatchObjectNotExist: - { - s << "(object not exist)"; - break; - } - - case DispatchFacetNotExist: - { - s << "(facet not exist)"; - break; - } - - case DispatchOperationNotExist: - { - s << "(operation not exist)"; - break; - } - - default: - { - assert(false); - break; - } - } - - printIdentityFacetOperation(s, stream); - break; - } - - case DispatchUnknownException: - case DispatchUnknownLocalException: - case DispatchUnknownUserException: - { - switch(static_cast(status)) - { - case DispatchUnknownException: - { - s << "(unknown exception)"; - break; - } - - case DispatchUnknownLocalException: - { - s << "(unknown local exception)"; - break; - } - - case DispatchUnknownUserException: - { - s << "(unknown user exception)"; - break; - } - - default: - { - assert(false); - break; - } - } - - string unknown; - stream.read(unknown, false); - s << "\nunknown = " << unknown; - break; - } - - default: - { - s << "(unknown)"; - break; - } - } - - logger->trace(tl->protocolCat, s.str()); - stream.i = p; + BasicStream& stream = const_cast(str); + BasicStream::Container::iterator p = stream.i; + stream.i = stream.b.begin(); + + ostringstream s; + s << heading; + printHeader(s, stream); + + Int requestId; + stream.read(requestId); + s << "\nrequest id = " << requestId; + + Byte status; + stream.read(status); + s << "\nreply status = " << static_cast(status) << ' '; + switch(static_cast(status)) + { + case DispatchOK: + { + s << "(ok)"; + break; + } + + case DispatchUserException: + { + s << "(user exception)"; + break; + } + + case DispatchObjectNotExist: + case DispatchFacetNotExist: + case DispatchOperationNotExist: + { + switch(static_cast(status)) + { + case DispatchObjectNotExist: + { + s << "(object not exist)"; + break; + } + + case DispatchFacetNotExist: + { + s << "(facet not exist)"; + break; + } + + case DispatchOperationNotExist: + { + s << "(operation not exist)"; + break; + } + + default: + { + assert(false); + break; + } + } + + printIdentityFacetOperation(s, stream); + break; + } + + case DispatchUnknownException: + case DispatchUnknownLocalException: + case DispatchUnknownUserException: + { + switch(static_cast(status)) + { + case DispatchUnknownException: + { + s << "(unknown exception)"; + break; + } + + case DispatchUnknownLocalException: + { + s << "(unknown local exception)"; + break; + } + + case DispatchUnknownUserException: + { + s << "(unknown user exception)"; + break; + } + + default: + { + assert(false); + break; + } + } + + string unknown; + stream.read(unknown, false); + s << "\nunknown = " << unknown; + break; + } + + default: + { + s << "(unknown)"; + break; + } + } + + logger->trace(tl->protocolCat, s.str()); + stream.i = p; } } @@ -402,9 +402,9 @@ IceInternal::traceSlicing(const char* kind, const string& typeId, const char* sl static set slicingIds; if(slicingIds.insert(typeId).second) { - string s("unknown "); - s += kind; - s += " type `" + typeId + "'"; - logger->trace(slicingCat, s); + string s("unknown "); + s += kind; + s += " type `" + typeId + "'"; + logger->trace(slicingCat, s); } } diff --git a/cpp/src/Ice/UdpEndpointI.cpp b/cpp/src/Ice/UdpEndpointI.cpp index d3ca4a84719..6681e8becbf 100644 --- a/cpp/src/Ice/UdpEndpointI.cpp +++ b/cpp/src/Ice/UdpEndpointI.cpp @@ -21,7 +21,7 @@ using namespace Ice; using namespace IceInternal; IceInternal::UdpEndpointI::UdpEndpointI(const InstancePtr& instance, const string& ho, Int po, bool conn, - const string& conId, bool co, bool pub) : + const string& conId, bool co, bool pub) : _instance(instance), _host(ho), _port(po), @@ -54,209 +54,209 @@ IceInternal::UdpEndpointI::UdpEndpointI(const InstancePtr& instance, const strin while(true) { - beg = str.find_first_not_of(delim, end); - if(beg == string::npos) - { - break; - } - - end = str.find_first_of(delim, beg); - if(end == string::npos) - { - end = str.length(); - } - - string option = str.substr(beg, end - beg); - if(option.length() != 2 || option[0] != '-') - { - EndpointParseException ex(__FILE__, __LINE__); - ex.str = "udp " + str; - throw ex; - } - - string argument; - string::size_type argumentBeg = str.find_first_not_of(delim, end); - if(argumentBeg != string::npos && str[argumentBeg] != '-') - { - beg = argumentBeg; - end = str.find_first_of(delim + ":", beg); - if(end == string::npos) - { - end = str.length(); - } - argument = str.substr(beg, end - beg); - } - - switch(option[1]) - { - case 'v': - { - if(argument.empty()) - { - EndpointParseException ex(__FILE__, __LINE__); - ex.str = "udp " + str; - throw ex; - } - - string::size_type pos = argument.find('.'); - if(pos == string::npos) - { - EndpointParseException ex(__FILE__, __LINE__); - ex.str = "udp " + str; - throw ex; - } - string majorStr = argument.substr(0, pos); - string minorStr = argument.substr(pos + 1, string::npos); - - istringstream majStr(majorStr); - Int majVersion; - if(!(majStr >> majVersion) || !majStr.eof()) - { - EndpointParseException ex(__FILE__, __LINE__); - ex.str = "udp " + str; - throw ex; - } - - istringstream minStr(minorStr); - Int minVersion; - if(!(minStr >> minVersion) || !minStr.eof()) - { - EndpointParseException ex(__FILE__, __LINE__); - ex.str = "udp " + str; - throw ex; - } - - if(majVersion < 1 || majVersion > 255 || minVersion < 0 || minVersion > 255) - { - EndpointParseException ex(__FILE__, __LINE__); - ex.str = "udp " + str; - throw ex; - } - - if(majVersion != protocolMajor) - { - UnsupportedProtocolException ex(__FILE__, __LINE__); - ex.badMajor = majVersion; - ex.badMinor = minVersion; - ex.major = static_cast(protocolMajor); - ex.minor = static_cast(protocolMinor); - throw ex; - } - - const_cast(_protocolMajor) = majVersion; - const_cast(_protocolMinor) = minVersion; - - break; - } - - case 'e': - { - if(argument.empty()) - { - EndpointParseException ex(__FILE__, __LINE__); - ex.str = "udp " + str; - throw ex; - } - string::size_type pos = argument.find('.'); - string majorStr = argument.substr(0, pos); - string minorStr = argument.substr(pos + 1, string::npos); - - istringstream majStr(majorStr); - Int majVersion; - if(!(majStr >> majVersion) || !majStr.eof()) - { - EndpointParseException ex(__FILE__, __LINE__); - ex.str = "udp " + str; - throw ex; - } - - istringstream minStr(minorStr); - Int minVersion; - if(!(minStr >> minVersion) || !minStr.eof()) - { - EndpointParseException ex(__FILE__, __LINE__); - ex.str = "udp " + str; - throw ex; - } - - if(majVersion < 1 || majVersion > 255 || minVersion < 0 || minVersion > 255) - { - EndpointParseException ex(__FILE__, __LINE__); - ex.str = "udp " + str; - throw ex; - } - - if(majVersion != static_cast(encodingMajor)) - { - UnsupportedEncodingException ex(__FILE__, __LINE__); - ex.badMajor = majVersion; - ex.badMinor = minVersion; - ex.major = static_cast(encodingMajor); - ex.minor = static_cast(encodingMinor); - throw ex; - } - - const_cast(_encodingMajor) = majVersion; - const_cast(_encodingMinor) = minVersion; - - break; - } - - case 'h': - { - if(argument.empty()) - { - EndpointParseException ex(__FILE__, __LINE__); - ex.str = "udp " + str; - throw ex; - } - const_cast(_host) = argument; - break; - } - - case 'p': - { - istringstream p(argument); - if(!(p >> const_cast(_port)) || !p.eof() || _port < 0 || _port > 65535) - { - EndpointParseException ex(__FILE__, __LINE__); - ex.str = "udp " + str; - throw ex; - } - break; - } - - case 'c': - { - if(!argument.empty()) - { - EndpointParseException ex(__FILE__, __LINE__); - ex.str = "udp " + str; - throw ex; - } - const_cast(_connect) = true; - break; - } - - case 'z': - { - if(!argument.empty()) - { - EndpointParseException ex(__FILE__, __LINE__); - ex.str = "udp " + str; - throw ex; - } - const_cast(_compress) = true; - break; - } - - default: - { - EndpointParseException ex(__FILE__, __LINE__); - ex.str = "udp " + str; - throw ex; - } - } + beg = str.find_first_not_of(delim, end); + if(beg == string::npos) + { + break; + } + + end = str.find_first_of(delim, beg); + if(end == string::npos) + { + end = str.length(); + } + + string option = str.substr(beg, end - beg); + if(option.length() != 2 || option[0] != '-') + { + EndpointParseException ex(__FILE__, __LINE__); + ex.str = "udp " + str; + throw ex; + } + + string argument; + string::size_type argumentBeg = str.find_first_not_of(delim, end); + if(argumentBeg != string::npos && str[argumentBeg] != '-') + { + beg = argumentBeg; + end = str.find_first_of(delim + ":", beg); + if(end == string::npos) + { + end = str.length(); + } + argument = str.substr(beg, end - beg); + } + + switch(option[1]) + { + case 'v': + { + if(argument.empty()) + { + EndpointParseException ex(__FILE__, __LINE__); + ex.str = "udp " + str; + throw ex; + } + + string::size_type pos = argument.find('.'); + if(pos == string::npos) + { + EndpointParseException ex(__FILE__, __LINE__); + ex.str = "udp " + str; + throw ex; + } + string majorStr = argument.substr(0, pos); + string minorStr = argument.substr(pos + 1, string::npos); + + istringstream majStr(majorStr); + Int majVersion; + if(!(majStr >> majVersion) || !majStr.eof()) + { + EndpointParseException ex(__FILE__, __LINE__); + ex.str = "udp " + str; + throw ex; + } + + istringstream minStr(minorStr); + Int minVersion; + if(!(minStr >> minVersion) || !minStr.eof()) + { + EndpointParseException ex(__FILE__, __LINE__); + ex.str = "udp " + str; + throw ex; + } + + if(majVersion < 1 || majVersion > 255 || minVersion < 0 || minVersion > 255) + { + EndpointParseException ex(__FILE__, __LINE__); + ex.str = "udp " + str; + throw ex; + } + + if(majVersion != protocolMajor) + { + UnsupportedProtocolException ex(__FILE__, __LINE__); + ex.badMajor = majVersion; + ex.badMinor = minVersion; + ex.major = static_cast(protocolMajor); + ex.minor = static_cast(protocolMinor); + throw ex; + } + + const_cast(_protocolMajor) = majVersion; + const_cast(_protocolMinor) = minVersion; + + break; + } + + case 'e': + { + if(argument.empty()) + { + EndpointParseException ex(__FILE__, __LINE__); + ex.str = "udp " + str; + throw ex; + } + string::size_type pos = argument.find('.'); + string majorStr = argument.substr(0, pos); + string minorStr = argument.substr(pos + 1, string::npos); + + istringstream majStr(majorStr); + Int majVersion; + if(!(majStr >> majVersion) || !majStr.eof()) + { + EndpointParseException ex(__FILE__, __LINE__); + ex.str = "udp " + str; + throw ex; + } + + istringstream minStr(minorStr); + Int minVersion; + if(!(minStr >> minVersion) || !minStr.eof()) + { + EndpointParseException ex(__FILE__, __LINE__); + ex.str = "udp " + str; + throw ex; + } + + if(majVersion < 1 || majVersion > 255 || minVersion < 0 || minVersion > 255) + { + EndpointParseException ex(__FILE__, __LINE__); + ex.str = "udp " + str; + throw ex; + } + + if(majVersion != static_cast(encodingMajor)) + { + UnsupportedEncodingException ex(__FILE__, __LINE__); + ex.badMajor = majVersion; + ex.badMinor = minVersion; + ex.major = static_cast(encodingMajor); + ex.minor = static_cast(encodingMinor); + throw ex; + } + + const_cast(_encodingMajor) = majVersion; + const_cast(_encodingMinor) = minVersion; + + break; + } + + case 'h': + { + if(argument.empty()) + { + EndpointParseException ex(__FILE__, __LINE__); + ex.str = "udp " + str; + throw ex; + } + const_cast(_host) = argument; + break; + } + + case 'p': + { + istringstream p(argument); + if(!(p >> const_cast(_port)) || !p.eof() || _port < 0 || _port > 65535) + { + EndpointParseException ex(__FILE__, __LINE__); + ex.str = "udp " + str; + throw ex; + } + break; + } + + case 'c': + { + if(!argument.empty()) + { + EndpointParseException ex(__FILE__, __LINE__); + ex.str = "udp " + str; + throw ex; + } + const_cast(_connect) = true; + break; + } + + case 'z': + { + if(!argument.empty()) + { + EndpointParseException ex(__FILE__, __LINE__); + ex.str = "udp " + str; + throw ex; + } + const_cast(_compress) = true; + break; + } + + default: + { + EndpointParseException ex(__FILE__, __LINE__); + ex.str = "udp " + str; + throw ex; + } + } } } @@ -280,21 +280,21 @@ IceInternal::UdpEndpointI::UdpEndpointI(BasicStream* s) : s->read(const_cast(_encodingMinor)); if(_protocolMajor != protocolMajor) { - UnsupportedProtocolException ex(__FILE__, __LINE__); - ex.badMajor = _protocolMajor; - ex.badMinor = _protocolMinor; - ex.major = static_cast(protocolMajor); - ex.minor = static_cast(protocolMinor); - throw ex; + UnsupportedProtocolException ex(__FILE__, __LINE__); + ex.badMajor = _protocolMajor; + ex.badMinor = _protocolMinor; + ex.major = static_cast(protocolMajor); + ex.minor = static_cast(protocolMinor); + throw ex; } if(_encodingMajor != encodingMajor) { - UnsupportedEncodingException ex(__FILE__, __LINE__); - ex.badMajor = _encodingMajor; - ex.badMinor = _encodingMinor; - ex.major = static_cast(encodingMajor); - ex.minor = static_cast(encodingMinor); - throw ex; + UnsupportedEncodingException ex(__FILE__, __LINE__); + ex.badMajor = _encodingMajor; + ex.badMinor = _encodingMinor; + ex.major = static_cast(encodingMajor); + ex.minor = static_cast(encodingMinor); + throw ex; } // Not transmitted. //s->read(const_cast(_connect)); @@ -335,28 +335,28 @@ IceInternal::UdpEndpointI::toString() const if(_protocolMajor != Byte(1) || _protocolMinor != Byte(0)) { - s << " -v " - << static_cast(static_cast(_protocolMajor)) << "." - << static_cast(static_cast(_protocolMinor)); + s << " -v " + << static_cast(static_cast(_protocolMajor)) << "." + << static_cast(static_cast(_protocolMinor)); } if(_encodingMajor != Byte(1) || _encodingMinor != Byte(0)) { - s << " -e " - << static_cast(static_cast(_encodingMajor)) << "." - << static_cast(static_cast(_encodingMinor)); + s << " -e " + << static_cast(static_cast(_encodingMajor)) << "." + << static_cast(static_cast(_encodingMinor)); } s << " -h " << _host << " -p " << _port; if(_connect) { - s << " -c"; + s << " -c"; } if(_compress) { - s << " -z"; + s << " -z"; } return s.str(); @@ -385,11 +385,11 @@ IceInternal::UdpEndpointI::connectionId(const string& connectionId) const { if(connectionId == _connectionId) { - return const_cast(this); + return const_cast(this); } else { - return new UdpEndpointI(_instance, _host, _port, _connect, connectionId, _compress, _publish); + return new UdpEndpointI(_instance, _host, _port, _connect, connectionId, _compress, _publish); } } @@ -404,11 +404,11 @@ IceInternal::UdpEndpointI::compress(bool compress) const { if(compress == _compress) { - return const_cast(this); + return const_cast(this); } else { - return new UdpEndpointI(_instance, _host, _port, _connect, _connectionId, compress, _publish); + return new UdpEndpointI(_instance, _host, _port, _connect, _connectionId, compress, _publish); } } @@ -487,7 +487,7 @@ IceInternal::UdpEndpointI::expand(bool server) const for(unsigned int i = 0; i < hosts.size(); ++i) { endps.push_back(new UdpEndpointI(_instance, hosts[i], _port, _connect, _connectionId, _compress, - hosts.size() == 1 || hosts[i] != "127.0.0.1")); + hosts.size() == 1 || hosts[i] != "127.0.0.1")); } } else @@ -509,7 +509,7 @@ IceInternal::UdpEndpointI::equivalent(const TransceiverPtr& transceiver) const const UdpTransceiver* udpTransceiver = dynamic_cast(transceiver.get()); if(!udpTransceiver) { - return false; + return false; } return udpTransceiver->equivalent(_host, _port); } @@ -526,72 +526,72 @@ IceInternal::UdpEndpointI::operator==(const EndpointI& r) const const UdpEndpointI* p = dynamic_cast(&r); if(!p) { - return false; + return false; } if(this == p) { - return true; + return true; } if(_port != p->_port) { - return false; + return false; } if(_compress != p->_compress) { - return false; + return false; } if(_connectionId != p->_connectionId) { - return false; + return false; } if(_connect != p->_connect) { - return false; + return false; } if(_protocolMajor != p->_protocolMajor) { - return false; + return false; } if(_protocolMinor != p->_protocolMinor) { - return false; + return false; } if(_encodingMajor != p->_encodingMajor) { - return false; + return false; } if(_encodingMinor != p->_encodingMinor) { - return false; + return false; } if(_host != p->_host) { - // - // We do the most time-consuming part of the comparison last. - // - struct sockaddr_in laddr; - struct sockaddr_in raddr; - try - { - getAddress(_host, _port, laddr); - getAddress(p->_host, p->_port, raddr); - } - catch(const DNSException&) - { - return false; - } + // + // We do the most time-consuming part of the comparison last. + // + struct sockaddr_in laddr; + struct sockaddr_in raddr; + try + { + getAddress(_host, _port, laddr); + getAddress(p->_host, p->_port, raddr); + } + catch(const DNSException&) + { + return false; + } - return compareAddress(laddr, raddr); + return compareAddress(laddr, raddr); } return true; @@ -614,112 +614,112 @@ IceInternal::UdpEndpointI::operator<(const EndpointI& r) const if(this == p) { - return false; + return false; } if(_port < p->_port) { - return true; + return true; } else if(p->_port < _port) { - return false; + return false; } if(_connectionId < p->_connectionId) { - return true; + return true; } else if(p->_connectionId < _connectionId) { - return false; + return false; } if(!_compress && p->_compress) { - return true; + return true; } else if(p->_compress < _compress) { - return false; + return false; } if(!_connect && p->_connect) { - return true; + return true; } else if(!p->_connect && _connect) { - return false; + return false; } if(_protocolMajor < p->_protocolMajor) { - return true; + return true; } else if(p->_protocolMajor < _protocolMajor) { - return false; + return false; } if(_protocolMinor < p->_protocolMinor) { - return true; + return true; } else if(p->_protocolMinor < _protocolMinor) { - return false; + return false; } if(_encodingMajor < p->_encodingMajor) { - return true; + return true; } else if(p->_encodingMajor < _encodingMajor) { - return false; + return false; } if(_encodingMinor < p->_encodingMinor) { - return true; + return true; } else if(p->_encodingMinor < _encodingMinor) { - return false; + return false; } if(_host != p->_host) { - // - // We do the most time-consuming part of the comparison last. - // - struct sockaddr_in laddr; - try - { - getAddress(_host, _port, laddr); - } - catch(const DNSException&) - { - } - - struct sockaddr_in raddr; - try - { - getAddress(p->_host, p->_port, raddr); - } - catch(const DNSException&) - { - } - - if(laddr.sin_addr.s_addr < raddr.sin_addr.s_addr) - { - return true; - } - else if(raddr.sin_addr.s_addr < laddr.sin_addr.s_addr) - { - return false; - } + // + // We do the most time-consuming part of the comparison last. + // + struct sockaddr_in laddr; + try + { + getAddress(_host, _port, laddr); + } + catch(const DNSException&) + { + } + + struct sockaddr_in raddr; + try + { + getAddress(p->_host, p->_port, raddr); + } + catch(const DNSException&) + { + } + + if(laddr.sin_addr.s_addr < raddr.sin_addr.s_addr) + { + return true; + } + else if(raddr.sin_addr.s_addr < laddr.sin_addr.s_addr) + { + return false; + } } return false; diff --git a/cpp/src/Ice/UdpTransceiver.cpp b/cpp/src/Ice/UdpTransceiver.cpp index f7e26883e38..4853d98aaa9 100644 --- a/cpp/src/Ice/UdpTransceiver.cpp +++ b/cpp/src/Ice/UdpTransceiver.cpp @@ -33,8 +33,8 @@ IceInternal::UdpTransceiver::close() { if(_traceLevels->network >= 1) { - Trace out(_logger, _traceLevels->networkCat); - out << "closing udp connection\n" << toString(); + Trace out(_logger, _traceLevels->networkCat); + out << "closing udp connection\n" << toString(); } assert(_fd != INVALID_SOCKET); @@ -52,8 +52,8 @@ IceInternal::UdpTransceiver::shutdownReadWrite() { if(_traceLevels->network >= 2) { - Trace out(_logger, _traceLevels->networkCat); - out << "shutting down udp connection for reading and writing\n" << toString(); + Trace out(_logger, _traceLevels->networkCat); + out << "shutting down udp connection for reading and writing\n" << toString(); } // @@ -84,10 +84,10 @@ IceInternal::UdpTransceiver::shutdownReadWrite() // if(!_connect) { - struct sockaddr_in unspec; - memset(&unspec, 0, sizeof(unspec)); - unspec.sin_family = AF_UNSPEC; - ::connect(_fd, reinterpret_cast(&unspec), int(sizeof(unspec))); + struct sockaddr_in unspec; + memset(&unspec, 0, sizeof(unspec)); + unspec.sin_family = AF_UNSPEC; + ::connect(_fd, reinterpret_cast(&unspec), int(sizeof(unspec))); } // @@ -117,10 +117,10 @@ IceInternal::UdpTransceiver::write(Buffer& buf, int) const int packetSize = min(_maxPacketSize, _sndSize - _udpOverhead); if(packetSize < static_cast(buf.b.size())) { - // - // We don't log a warning here because the client gets an exception anyway. - // - throw DatagramLimitException(__FILE__, __LINE__); + // + // We don't log a warning here because the client gets an exception anyway. + // + throw DatagramLimitException(__FILE__, __LINE__); } repeat: @@ -128,62 +128,62 @@ repeat: assert(_fd != INVALID_SOCKET); #ifdef _WIN32 ssize_t ret = ::send(_fd, reinterpret_cast(&buf.b[0]), - static_cast(buf.b.size()), 0); + static_cast(buf.b.size()), 0); #else ssize_t ret = ::send(_fd, reinterpret_cast(&buf.b[0]), - buf.b.size(), 0); + buf.b.size(), 0); #endif if(ret == SOCKET_ERROR) { - if(interrupted()) - { - goto repeat; - } + if(interrupted()) + { + goto repeat; + } - if(wouldBlock()) - { - repeatSelect: + if(wouldBlock()) + { + repeatSelect: - assert(_fd != INVALID_SOCKET); + assert(_fd != INVALID_SOCKET); #ifdef _WIN32 - FD_SET(_fd, &_wFdSet); - int rs = ::select(static_cast(_fd + 1), 0, &_wFdSet, 0, 0); + FD_SET(_fd, &_wFdSet); + int rs = ::select(static_cast(_fd + 1), 0, &_wFdSet, 0, 0); #else - struct pollfd fdSet[1]; - fdSet[0].fd = _fd; - fdSet[0].events = POLLOUT; - int rs = ::poll(fdSet, 1, -1); + struct pollfd fdSet[1]; + fdSet[0].fd = _fd; + fdSet[0].events = POLLOUT; + int rs = ::poll(fdSet, 1, -1); #endif - if(rs == SOCKET_ERROR) - { - if(interrupted()) - { - goto repeatSelect; - } - - SocketException ex(__FILE__, __LINE__); - ex.error = getSocketErrno(); - throw ex; - } - - goto repeat; - } - - SocketException ex(__FILE__, __LINE__); - ex.error = getSocketErrno(); - throw ex; + if(rs == SOCKET_ERROR) + { + if(interrupted()) + { + goto repeatSelect; + } + + SocketException ex(__FILE__, __LINE__); + ex.error = getSocketErrno(); + throw ex; + } + + goto repeat; + } + + SocketException ex(__FILE__, __LINE__); + ex.error = getSocketErrno(); + throw ex; } if(_traceLevels->network >= 3) { - Trace out(_logger, _traceLevels->networkCat); - out << "sent " << ret << " bytes via udp\n" << toString(); + Trace out(_logger, _traceLevels->networkCat); + out << "sent " << ret << " bytes via udp\n" << toString(); } if(_stats) { - _stats->bytesSent(type(), static_cast(ret)); + _stats->bytesSent(type(), static_cast(ret)); } assert(ret == static_cast(buf.b.size())); @@ -203,16 +203,16 @@ IceInternal::UdpTransceiver::read(Buffer& buf, int) const int packetSize = min(_maxPacketSize, _rcvSize - _udpOverhead); if(packetSize < static_cast(buf.b.size())) { - // - // We log a warning here because this is the server side -- without the - // the warning, there would only be silence. - // - if(_warn) - { - Warning out(_logger); - out << "DatagramLimitException: maximum size of " << packetSize << " exceeded"; - } - throw DatagramLimitException(__FILE__, __LINE__); + // + // We log a warning here because this is the server side -- without the + // the warning, there would only be silence. + // + if(_warn) + { + Warning out(_logger); + out << "DatagramLimitException: maximum size of " << packetSize << " exceeded"; + } + throw DatagramLimitException(__FILE__, __LINE__); } buf.b.resize(packetSize); buf.i = buf.b.begin(); @@ -223,107 +223,107 @@ repeat: // Check the shutdown flag. // { - IceUtil::Mutex::Lock sync(_shutdownReadWriteMutex); - if(_shutdownReadWrite) - { - throw ConnectionLostException(__FILE__, __LINE__); - } + IceUtil::Mutex::Lock sync(_shutdownReadWriteMutex); + if(_shutdownReadWrite) + { + throw ConnectionLostException(__FILE__, __LINE__); + } } ssize_t ret; if(_connect) { - // - // If we must connect, then we connect to the first peer that - // sends us a packet. - // - struct sockaddr_in peerAddr; - memset(&peerAddr, 0, sizeof(struct sockaddr_in)); - socklen_t len = static_cast(sizeof(peerAddr)); - assert(_fd != INVALID_SOCKET); - ret = recvfrom(_fd, reinterpret_cast(&buf.b[0]), packetSize, - 0, reinterpret_cast(&peerAddr), &len); - if(ret != SOCKET_ERROR) - { - doConnect(_fd, peerAddr, -1); - _connect = false; // We are connected now. - - if(_traceLevels->network >= 1) - { - Trace out(_logger, _traceLevels->networkCat); - out << "connected udp socket\n" << toString(); - } - } + // + // If we must connect, then we connect to the first peer that + // sends us a packet. + // + struct sockaddr_in peerAddr; + memset(&peerAddr, 0, sizeof(struct sockaddr_in)); + socklen_t len = static_cast(sizeof(peerAddr)); + assert(_fd != INVALID_SOCKET); + ret = recvfrom(_fd, reinterpret_cast(&buf.b[0]), packetSize, + 0, reinterpret_cast(&peerAddr), &len); + if(ret != SOCKET_ERROR) + { + doConnect(_fd, peerAddr, -1); + _connect = false; // We are connected now. + + if(_traceLevels->network >= 1) + { + Trace out(_logger, _traceLevels->networkCat); + out << "connected udp socket\n" << toString(); + } + } } else { - assert(_fd != INVALID_SOCKET); - ret = ::recv(_fd, reinterpret_cast(&buf.b[0]), packetSize, 0); + assert(_fd != INVALID_SOCKET); + ret = ::recv(_fd, reinterpret_cast(&buf.b[0]), packetSize, 0); } if(ret == SOCKET_ERROR) { - if(interrupted()) - { - goto repeat; - } - - if(wouldBlock()) - { - repeatSelect: - - assert(_fd != INVALID_SOCKET); + if(interrupted()) + { + goto repeat; + } + + if(wouldBlock()) + { + repeatSelect: + + assert(_fd != INVALID_SOCKET); #ifdef _WIN32 - FD_SET(_fd, &_rFdSet); - int rs = ::select(static_cast(_fd + 1), &_rFdSet, 0, 0, 0); + FD_SET(_fd, &_rFdSet); + int rs = ::select(static_cast(_fd + 1), &_rFdSet, 0, 0, 0); #else - struct pollfd fdSet[1]; - fdSet[0].fd = _fd; - fdSet[0].events = POLLIN; - int rs = ::poll(fdSet, 1, -1); + struct pollfd fdSet[1]; + fdSet[0].fd = _fd; + fdSet[0].events = POLLIN; + int rs = ::poll(fdSet, 1, -1); #endif - if(rs == SOCKET_ERROR) - { - if(interrupted()) - { - goto repeatSelect; - } - - SocketException ex(__FILE__, __LINE__); - ex.error = getSocketErrno(); - throw ex; - } - - goto repeat; - } - - if(recvTruncated()) - { - DatagramLimitException ex(__FILE__, __LINE__); - if(_warn) - { - Warning out(_logger); - out << "DatagramLimitException: maximum size of " << packetSize << " exceeded"; - } - throw ex; - - } - - SocketException ex(__FILE__, __LINE__); - ex.error = getSocketErrno(); - throw ex; + if(rs == SOCKET_ERROR) + { + if(interrupted()) + { + goto repeatSelect; + } + + SocketException ex(__FILE__, __LINE__); + ex.error = getSocketErrno(); + throw ex; + } + + goto repeat; + } + + if(recvTruncated()) + { + DatagramLimitException ex(__FILE__, __LINE__); + if(_warn) + { + Warning out(_logger); + out << "DatagramLimitException: maximum size of " << packetSize << " exceeded"; + } + throw ex; + + } + + SocketException ex(__FILE__, __LINE__); + ex.error = getSocketErrno(); + throw ex; } if(_traceLevels->network >= 3) { - Trace out(_logger, _traceLevels->networkCat); - out << "received " << ret << " bytes via udp\n" << toString(); + Trace out(_logger, _traceLevels->networkCat); + out << "received " << ret << " bytes via udp\n" << toString(); } if(_stats) { - _stats->bytesReceived(type(), static_cast(ret)); + _stats->bytesReceived(type(), static_cast(ret)); } buf.b.resize(ret); @@ -352,12 +352,12 @@ IceInternal::UdpTransceiver::checkSendSize(const Buffer& buf, size_t messageSize { if(buf.b.size() > messageSizeMax) { - throw MemoryLimitException(__FILE__, __LINE__); + throw MemoryLimitException(__FILE__, __LINE__); } const int packetSize = min(_maxPacketSize, _sndSize - _udpOverhead); if(packetSize < static_cast(buf.b.size())) { - throw DatagramLimitException(__FILE__, __LINE__); + throw DatagramLimitException(__FILE__, __LINE__); } } @@ -386,23 +386,23 @@ IceInternal::UdpTransceiver::UdpTransceiver(const InstancePtr& instance, const s { try { - _fd = createSocket(true); - setBufSize(instance); - setBlock(_fd, false); - getAddress(host, port, _addr); - doConnect(_fd, _addr, -1); - _connect = false; // We're connected now - - if(_traceLevels->network >= 1) - { - Trace out(_logger, _traceLevels->networkCat); - out << "starting to send udp packets\n" << toString(); - } + _fd = createSocket(true); + setBufSize(instance); + setBlock(_fd, false); + getAddress(host, port, _addr); + doConnect(_fd, _addr, -1); + _connect = false; // We're connected now + + if(_traceLevels->network >= 1) + { + Trace out(_logger, _traceLevels->networkCat); + out << "starting to send udp packets\n" << toString(); + } } catch(...) { - _fd = INVALID_SOCKET; - throw; + _fd = INVALID_SOCKET; + throw; } #ifdef _WIN32 @@ -422,27 +422,27 @@ IceInternal::UdpTransceiver::UdpTransceiver(const InstancePtr& instance, const s { try { - _fd = createSocket(true); - setBufSize(instance); - setBlock(_fd, false); - getAddress(host, port, _addr); - if(_traceLevels->network >= 2) - { - Trace out(_logger, _traceLevels->networkCat); - out << "attempting to bind to udp socket " << addrToString(_addr); - } - doBind(_fd, _addr); - - if(_traceLevels->network >= 1) - { - Trace out(_logger, _traceLevels->networkCat); - out << "starting to receive udp packets\n" << toString(); - } + _fd = createSocket(true); + setBufSize(instance); + setBlock(_fd, false); + getAddress(host, port, _addr); + if(_traceLevels->network >= 2) + { + Trace out(_logger, _traceLevels->networkCat); + out << "attempting to bind to udp socket " << addrToString(_addr); + } + doBind(_fd, _addr); + + if(_traceLevels->network >= 1) + { + Trace out(_logger, _traceLevels->networkCat); + out << "starting to receive udp packets\n" << toString(); + } } catch(...) { - _fd = INVALID_SOCKET; - throw; + _fd = INVALID_SOCKET; + throw; } #ifdef _WIN32 @@ -467,66 +467,66 @@ IceInternal::UdpTransceiver::setBufSize(const InstancePtr& instance) for(int i = 0; i < 2; ++i) { - string direction; - string prop; - int* addr; - int dfltSize; - if(i == 0) - { - direction = "receive"; - prop = "Ice.UDP.RcvSize"; - addr = &_rcvSize; - dfltSize = getRecvBufferSize(_fd); - _rcvSize = dfltSize; - } - else - { - direction = "send"; - prop = "Ice.UDP.SndSize"; - addr = &_sndSize; - dfltSize = getSendBufferSize(_fd); - _sndSize = dfltSize; - } - - // - // Get property for buffer size and check for sanity. - // - Int sizeRequested = instance->initializationData().properties->getPropertyAsIntWithDefault(prop, dfltSize); - if(sizeRequested < _udpOverhead) - { - Warning out(_logger); - out << "Invalid " << prop << " value of " << sizeRequested << " adjusted to " << dfltSize; - sizeRequested = dfltSize; - } - - if(sizeRequested != dfltSize) - { - // - // Try to set the buffer size. The kernel will silently adjust - // the size to an acceptable value. Then read the size back to - // get the size that was actually set. - // - if(i == 0) - { - setRecvBufferSize(_fd, sizeRequested); - *addr = getRecvBufferSize(_fd); - } - else - { - setSendBufferSize(_fd, sizeRequested); - *addr = getSendBufferSize(_fd); - } - - // - // Warn if the size that was set is less than the requested size. - // - if(*addr < sizeRequested) - { - Warning out(_logger); - out << "UDP " << direction << " buffer size: requested size of " - << sizeRequested << " adjusted to " << *addr; - } - } + string direction; + string prop; + int* addr; + int dfltSize; + if(i == 0) + { + direction = "receive"; + prop = "Ice.UDP.RcvSize"; + addr = &_rcvSize; + dfltSize = getRecvBufferSize(_fd); + _rcvSize = dfltSize; + } + else + { + direction = "send"; + prop = "Ice.UDP.SndSize"; + addr = &_sndSize; + dfltSize = getSendBufferSize(_fd); + _sndSize = dfltSize; + } + + // + // Get property for buffer size and check for sanity. + // + Int sizeRequested = instance->initializationData().properties->getPropertyAsIntWithDefault(prop, dfltSize); + if(sizeRequested < _udpOverhead) + { + Warning out(_logger); + out << "Invalid " << prop << " value of " << sizeRequested << " adjusted to " << dfltSize; + sizeRequested = dfltSize; + } + + if(sizeRequested != dfltSize) + { + // + // Try to set the buffer size. The kernel will silently adjust + // the size to an acceptable value. Then read the size back to + // get the size that was actually set. + // + if(i == 0) + { + setRecvBufferSize(_fd, sizeRequested); + *addr = getRecvBufferSize(_fd); + } + else + { + setSendBufferSize(_fd, sizeRequested); + *addr = getSendBufferSize(_fd); + } + + // + // Warn if the size that was set is less than the requested size. + // + if(*addr < sizeRequested) + { + Warning out(_logger); + out << "UDP " << direction << " buffer size: requested size of " + << sizeRequested << " adjusted to " << *addr; + } + } } } diff --git a/cpp/src/Ice/UnknownEndpointI.cpp b/cpp/src/Ice/UnknownEndpointI.cpp index 80a3b5c5b1d..12a46a347dc 100644 --- a/cpp/src/Ice/UnknownEndpointI.cpp +++ b/cpp/src/Ice/UnknownEndpointI.cpp @@ -153,12 +153,12 @@ IceInternal::UnknownEndpointI::operator==(const EndpointI& r) const const UnknownEndpointI* p = dynamic_cast(&r); if(!p) { - return false; + return false; } if(this == p) { - return true; + return true; } if(_type != p->_type) @@ -168,7 +168,7 @@ IceInternal::UnknownEndpointI::operator==(const EndpointI& r) const if(_rawBytes != p->_rawBytes) { - return false; + return false; } return true; @@ -191,25 +191,25 @@ IceInternal::UnknownEndpointI::operator<(const EndpointI& r) const if(this == p) { - return false; + return false; } if(_type < p->_type) { - return true; + return true; } else if(p->_type < _type) { - return false; + return false; } if(_rawBytes < p->_rawBytes) { - return true; + return true; } else if(p->_rawBytes < _rawBytes) { - return false; + return false; } return false; diff --git a/cpp/src/IceBox/Admin.cpp b/cpp/src/IceBox/Admin.cpp index 777f6bc0054..74234008973 100644 --- a/cpp/src/IceBox/Admin.cpp +++ b/cpp/src/IceBox/Admin.cpp @@ -58,24 +58,24 @@ Client::run(int argc, char* argv[]) vector commands; try { - commands = opts.parse(argc, (const char**)argv); + commands = opts.parse(argc, (const char**)argv); } catch(const IceUtil::BadOptException& e) { cerr << e.reason << endl; - usage(); - return EXIT_FAILURE; + usage(); + return EXIT_FAILURE; } if(opts.isSet("help")) { - usage(); - return EXIT_SUCCESS; + usage(); + return EXIT_SUCCESS; } if(opts.isSet("version")) { - cout << ICE_STRING_VERSION << endl; - return EXIT_SUCCESS; + cout << ICE_STRING_VERSION << endl; + return EXIT_SUCCESS; } if(commands.empty()) @@ -93,34 +93,34 @@ Client::run(int argc, char* argv[]) if(properties->getProperty("Ice.Default.Locator").empty()) { // - // DEPRECATED PROPERTY: Remove extra code in future release. - // - string managerEndpoints = - properties->getPropertyWithDefault("Ice.OA.IceBox.ServiceManager.Endpoints", - properties->getProperty("IceBox.ServiceManager.Endpoints")); - if(managerEndpoints.empty()) - { - cerr << appName() << ": property `Ice.OA.IceBox.ServiceManager.Endpoints' is not set" << endl; - return EXIT_FAILURE; - } - - managerProxy = "\"" + communicator()->identityToString(managerIdentity) + "\" :" + managerEndpoints; + // DEPRECATED PROPERTY: Remove extra code in future release. + // + string managerEndpoints = + properties->getPropertyWithDefault("Ice.OA.IceBox.ServiceManager.Endpoints", + properties->getProperty("IceBox.ServiceManager.Endpoints")); + if(managerEndpoints.empty()) + { + cerr << appName() << ": property `Ice.OA.IceBox.ServiceManager.Endpoints' is not set" << endl; + return EXIT_FAILURE; + } + + managerProxy = "\"" + communicator()->identityToString(managerIdentity) + "\" :" + managerEndpoints; } else { // - // DEPRECATED PROPERTY: Remove extra code in future release. - // - string managerAdapterId = - properties->getPropertyWithDefault("Ice.OA.IceBox.ServiceManager.AdapterId", - properties->getProperty("IceBox.ServiceManager.AdapterId")); - if(managerAdapterId.empty()) - { - cerr << appName() << ": property `Ice.OA.IceBox.ServiceManager.AdapterId' is not set" << endl; - return EXIT_FAILURE; - } - - managerProxy = "\"" + communicator()->identityToString(managerIdentity) + "\" @" + managerAdapterId; + // DEPRECATED PROPERTY: Remove extra code in future release. + // + string managerAdapterId = + properties->getPropertyWithDefault("Ice.OA.IceBox.ServiceManager.AdapterId", + properties->getProperty("IceBox.ServiceManager.AdapterId")); + if(managerAdapterId.empty()) + { + cerr << appName() << ": property `Ice.OA.IceBox.ServiceManager.AdapterId' is not set" << endl; + return EXIT_FAILURE; + } + + managerProxy = "\"" + communicator()->identityToString(managerIdentity) + "\" @" + managerAdapterId; } ObjectPrx base = communicator()->stringToProxy(managerProxy); @@ -154,48 +154,48 @@ Client::run(int argc, char* argv[]) { manager->shutdown(); } - else if((*r) == "start") - { - if(++r == commands.end()) - { + else if((*r) == "start") + { + if(++r == commands.end()) + { cerr << appName() << ": no service name specified." << endl; return EXIT_FAILURE; - } - - try - { - manager->startService(*r); - } - catch(const IceBox::NoSuchServiceException&) - { + } + + try + { + manager->startService(*r); + } + catch(const IceBox::NoSuchServiceException&) + { cerr << appName() << ": unknown service `" << *r << "'" << endl; - } - catch(const IceBox::AlreadyStartedException&) - { + } + catch(const IceBox::AlreadyStartedException&) + { cerr << appName() << ": service already started." << endl; - } - } - else if((*r) == "stop") - { - if(++r == commands.end()) - { + } + } + else if((*r) == "stop") + { + if(++r == commands.end()) + { cerr << appName() << ": no service name specified." << endl; return EXIT_FAILURE; - } - - try - { - manager->stopService(*r); - } - catch(const IceBox::NoSuchServiceException&) - { + } + + try + { + manager->stopService(*r); + } + catch(const IceBox::NoSuchServiceException&) + { cerr << appName() << ": unknown service `" << *r << "'" << endl; - } - catch(const IceBox::AlreadyStoppedException&) - { + } + catch(const IceBox::AlreadyStoppedException&) + { cerr << appName() << ": service already stopped." << endl; - } - } + } + } else { cerr << appName() << ": unknown command `" << *r << "'" << endl; diff --git a/cpp/src/IceBox/Service.cpp b/cpp/src/IceBox/Service.cpp index 881c263fe25..295d0c45817 100644 --- a/cpp/src/IceBox/Service.cpp +++ b/cpp/src/IceBox/Service.cpp @@ -88,7 +88,7 @@ IceBox::IceBoxService::stop() if(_serviceManager) { _serviceManager->stop(); - _serviceManager = 0; + _serviceManager = 0; } return true; } @@ -129,8 +129,8 @@ IceBox::IceBoxService::usage(const string& appName) "\n" "--daemon Run as a daemon.\n" "--noclose Do not close open file descriptors.\n" - "--nochdir Do not change the current working directory.\n" - "--pidfile Write process ID to ." + "--nochdir Do not change the current working directory.\n" + "--pidfile Write process ID to ." ); #endif print("Usage: " + appName + " [options]\n" + options); diff --git a/cpp/src/IceBox/ServiceManagerI.cpp b/cpp/src/IceBox/ServiceManagerI.cpp index c3097d5b99e..047be74601b 100644 --- a/cpp/src/IceBox/ServiceManagerI.cpp +++ b/cpp/src/IceBox/ServiceManagerI.cpp @@ -53,33 +53,33 @@ IceBox::ServiceManagerI::startService(const string& name, const Current&) vector::iterator p; for(p = _services.begin(); p != _services.end(); ++p) { - ServiceInfo& info = *p; - if(info.name == name) - { - if(info.active) - { - throw AlreadyStartedException(); - } - - try - { - info.service->start(name, info.communicator == 0 ? _communicator : info.communicator, info.args); - info.active = true; - } - catch(const Ice::Exception& ex) - { + ServiceInfo& info = *p; + if(info.name == name) + { + if(info.active) + { + throw AlreadyStartedException(); + } + + try + { + info.service->start(name, info.communicator == 0 ? _communicator : info.communicator, info.args); + info.active = true; + } + catch(const Ice::Exception& ex) + { Warning out(_logger); - out << "ServiceManager: exception in start for service " << info.name << ":\n"; - out << ex; - } - catch(...) - { + out << "ServiceManager: exception in start for service " << info.name << ":\n"; + out << ex; + } + catch(...) + { Warning out(_logger); - out << "ServiceManager: unknown exception in start for service " << info.name; - } + out << "ServiceManager: unknown exception in start for service " << info.name; + } - return; - } + return; + } } throw NoSuchServiceException(); @@ -97,33 +97,33 @@ IceBox::ServiceManagerI::stopService(const string& name, const Current&) vector::iterator p; for(p = _services.begin(); p != _services.end(); ++p) { - ServiceInfo& info = *p; - if(info.name == name) - { - if(!info.active) - { - throw AlreadyStoppedException(); - } - - try - { - info.service->stop(); - info.active = false; - } - catch(const Ice::Exception& ex) - { + ServiceInfo& info = *p; + if(info.name == name) + { + if(!info.active) + { + throw AlreadyStoppedException(); + } + + try + { + info.service->stop(); + info.active = false; + } + catch(const Ice::Exception& ex) + { Warning out(_logger); - out << "ServiceManager: exception in stop for service " << info.name << ":\n"; - out << ex; - } - catch(...) - { + out << "ServiceManager: exception in stop for service " << info.name << ":\n"; + out << ex; + } + catch(...) + { Warning out(_logger); - out << "ServiceManager: unknown exception in stop for service " << info.name; - } + out << "ServiceManager: unknown exception in stop for service " << info.name; + } - return; - } + return; + } } throw NoSuchServiceException(); @@ -149,10 +149,10 @@ IceBox::ServiceManagerI::start() // ObjectAdapterPtr adapter = _communicator->createObjectAdapter("IceBox.ServiceManager"); - PropertiesPtr properties = _communicator->getProperties(); + PropertiesPtr properties = _communicator->getProperties(); Identity identity; - identity.category = properties->getPropertyWithDefault("IceBox.InstanceName", "IceBox"); - identity.name = "ServiceManager"; + identity.category = properties->getPropertyWithDefault("IceBox.InstanceName", "IceBox"); + identity.name = "ServiceManager"; adapter->add(obj, identity); // @@ -191,7 +191,7 @@ IceBox::ServiceManagerI::start() // const string prefix = "IceBox.Service."; PropertyDict services = properties->getPropertiesForPrefix(prefix); - PropertyDict::iterator p; + PropertyDict::iterator p; for(StringSeq::const_iterator q = loadOrder.begin(); q != loadOrder.end(); ++q) { p = services.find(prefix + *q); @@ -204,8 +204,8 @@ IceBox::ServiceManagerI::start() load(*q, p->second); services.erase(p); } - for(p = services.begin(); p != services.end(); ++p) - { + for(p = services.begin(); p != services.end(); ++p) + { string name = p->first.substr(prefix.size()); load(name, p->second); } @@ -228,16 +228,16 @@ IceBox::ServiceManagerI::start() cout << bundleName << " ready" << endl; } - try - { - adapter->activate(); - } - catch(const ObjectAdapterDeactivatedException&) - { - // - // Expected if the communicator has been shutdown. - // - } + try + { + adapter->activate(); + } + catch(const ObjectAdapterDeactivatedException&) + { + // + // Expected if the communicator has been shutdown. + // + } } catch(const FailureException& ex) { @@ -279,16 +279,16 @@ IceBox::ServiceManagerI::load(const string& name, const string& value) else { entryPoint = value.substr(0, pos); - try - { - args = IceUtil::Options::split(value.substr(pos + 1)); - } - catch(const IceUtil::BadOptException& ex) - { - FailureException e(__FILE__, __LINE__); - e.reason = "ServiceManager: invalid arguments for service `" + name + "':\n" + ex.reason; - throw e; - } + try + { + args = IceUtil::Options::split(value.substr(pos + 1)); + } + catch(const IceUtil::BadOptException& ex) + { + FailureException e(__FILE__, __LINE__); + e.reason = "ServiceManager: invalid arguments for service `" + name + "':\n" + ex.reason; + throw e; + } } start(name, entryPoint, args); } @@ -363,148 +363,148 @@ IceBox::ServiceManagerI::start(const string& service, const string& entryPoint, // try { - // - // If Ice.UseSharedCommunicator. is not defined, create - // a communicator for the service. The communicator inherits - // from the shared communicator properties. If it's defined - // add the service properties to the shared commnunicator - // property set. - // - PropertiesPtr properties = _communicator->getProperties(); - - - if(properties->getPropertyAsInt("IceBox.UseSharedCommunicator." + service) > 0) - { - PropertiesPtr serviceProperties = createProperties(info.args, properties); - - // - // Erase properties in 'properties' - // - PropertyDict allProps = properties->getPropertiesForPrefix(""); - for(PropertyDict::iterator p = allProps.begin(); p != allProps.end(); ++p) - { - if(serviceProperties->getProperty(p->first) == "") - { - properties->setProperty(p->first, ""); - } - } - - // - // Put all serviceProperties into 'properties' - // - properties->parseCommandLineOptions("", serviceProperties->getCommandLineOptions()); - - // - // Parse .* command line options - // (the Ice command line options were parse by the createProperties above) - // - info.args = properties->parseCommandLineOptions(service, info.args); - } - else - { - string name = properties->getProperty("Ice.ProgramName"); - PropertiesPtr serviceProperties; - if(properties->getPropertyAsInt("IceBox.InheritContainerProperties") > 0) - { - serviceProperties = createProperties(info.args, properties); - } - else - { - serviceProperties = createProperties(info.args); - } - - if(name == serviceProperties->getProperty("Ice.ProgramName")) - { - // - // If the service did not set its own program-name, and - // the icebox program-name != service, append the service name to the - // program name. - // - if(name != service) - { - name = name.empty() ? service : name + "-" + service; - } - serviceProperties->setProperty("Ice.ProgramName", name); - } - - // - // Parse .* command line options - // (the Ice command line options were parsed by the createProperties above) - // - info.args = serviceProperties->parseCommandLineOptions(service, info.args); - - // - // Remaining command line options are passed to the - // communicator with argc/argv. This is necessary for Ice - // plugin properties (e.g.: IceSSL). - // - int argc = static_cast(info.args.size()); - char** argv = new char*[argc + 1]; - int i = 0; - for(Ice::StringSeq::const_iterator p = info.args.begin(); p != info.args.end(); ++p, ++i) - { - argv[i] = strdup(p->c_str()); - } - argv[argc] = 0; - - InitializationData initData; - initData.properties = serviceProperties; - info.communicator = initialize(argc, argv, initData); - - for(i = 0; i < argc + 1; ++i) - { - free(argv[i]); - } - delete[] argv; - } - - CommunicatorPtr communicator = info.communicator ? info.communicator : _communicator; - - // - // Start the service. - // - try - { - info.service->start(service, communicator, info.args); - info.active = true; - } - catch(...) - { - if(info.communicator) - { - try - { - info.communicator->shutdown(); - info.communicator->waitForShutdown(); - } - catch(const Ice::CommunicatorDestroyedException&) - { - // - // Ignore, the service might have already destroyed - // the communicator for its own reasons. - // - } - catch(const Ice::Exception& ex) - { - Warning out(_logger); - out << "ServiceManager: exception in shutting down communicator for service " << service << ":\n"; - out << ex; - } - - try - { - info.communicator->destroy(); - info.communicator = 0; - } - catch(const Exception& ex) - { - Warning out(_logger); - out << "ServiceManager: exception in shutting down communicator for service " << service << ":\n"; - out << ex; - } - } - throw; - } + // + // If Ice.UseSharedCommunicator. is not defined, create + // a communicator for the service. The communicator inherits + // from the shared communicator properties. If it's defined + // add the service properties to the shared commnunicator + // property set. + // + PropertiesPtr properties = _communicator->getProperties(); + + + if(properties->getPropertyAsInt("IceBox.UseSharedCommunicator." + service) > 0) + { + PropertiesPtr serviceProperties = createProperties(info.args, properties); + + // + // Erase properties in 'properties' + // + PropertyDict allProps = properties->getPropertiesForPrefix(""); + for(PropertyDict::iterator p = allProps.begin(); p != allProps.end(); ++p) + { + if(serviceProperties->getProperty(p->first) == "") + { + properties->setProperty(p->first, ""); + } + } + + // + // Put all serviceProperties into 'properties' + // + properties->parseCommandLineOptions("", serviceProperties->getCommandLineOptions()); + + // + // Parse .* command line options + // (the Ice command line options were parse by the createProperties above) + // + info.args = properties->parseCommandLineOptions(service, info.args); + } + else + { + string name = properties->getProperty("Ice.ProgramName"); + PropertiesPtr serviceProperties; + if(properties->getPropertyAsInt("IceBox.InheritContainerProperties") > 0) + { + serviceProperties = createProperties(info.args, properties); + } + else + { + serviceProperties = createProperties(info.args); + } + + if(name == serviceProperties->getProperty("Ice.ProgramName")) + { + // + // If the service did not set its own program-name, and + // the icebox program-name != service, append the service name to the + // program name. + // + if(name != service) + { + name = name.empty() ? service : name + "-" + service; + } + serviceProperties->setProperty("Ice.ProgramName", name); + } + + // + // Parse .* command line options + // (the Ice command line options were parsed by the createProperties above) + // + info.args = serviceProperties->parseCommandLineOptions(service, info.args); + + // + // Remaining command line options are passed to the + // communicator with argc/argv. This is necessary for Ice + // plugin properties (e.g.: IceSSL). + // + int argc = static_cast(info.args.size()); + char** argv = new char*[argc + 1]; + int i = 0; + for(Ice::StringSeq::const_iterator p = info.args.begin(); p != info.args.end(); ++p, ++i) + { + argv[i] = strdup(p->c_str()); + } + argv[argc] = 0; + + InitializationData initData; + initData.properties = serviceProperties; + info.communicator = initialize(argc, argv, initData); + + for(i = 0; i < argc + 1; ++i) + { + free(argv[i]); + } + delete[] argv; + } + + CommunicatorPtr communicator = info.communicator ? info.communicator : _communicator; + + // + // Start the service. + // + try + { + info.service->start(service, communicator, info.args); + info.active = true; + } + catch(...) + { + if(info.communicator) + { + try + { + info.communicator->shutdown(); + info.communicator->waitForShutdown(); + } + catch(const Ice::CommunicatorDestroyedException&) + { + // + // Ignore, the service might have already destroyed + // the communicator for its own reasons. + // + } + catch(const Ice::Exception& ex) + { + Warning out(_logger); + out << "ServiceManager: exception in shutting down communicator for service " << service << ":\n"; + out << ex; + } + + try + { + info.communicator->destroy(); + info.communicator = 0; + } + catch(const Exception& ex) + { + Warning out(_logger); + out << "ServiceManager: exception in shutting down communicator for service " << service << ":\n"; + out << ex; + } + } + throw; + } info.library = library; _services.push_back(info); @@ -515,12 +515,12 @@ IceBox::ServiceManagerI::start(const string& service, const string& entryPoint, } catch(const Exception& ex) { - ostringstream s; - s << "ServiceManager: exception while starting service " << service << ":\n"; - s << ex; + ostringstream s; + s << "ServiceManager: exception while starting service " << service << ":\n"; + s << ex; - FailureException e(__FILE__, __LINE__); - e.reason = s.str(); + FailureException e(__FILE__, __LINE__); + e.reason = s.str(); throw e; } } @@ -541,103 +541,103 @@ IceBox::ServiceManagerI::stopAll() // for(p = _services.rbegin(); p != _services.rend(); ++p) { - ServiceInfo& info = *p; - try - { - info.service->stop(); - info.active = false; - } - catch(const Ice::Exception& ex) - { + ServiceInfo& info = *p; + try + { + info.service->stop(); + info.active = false; + } + catch(const Ice::Exception& ex) + { Warning out(_logger); - out << "ServiceManager: exception in stop for service " << info.name << ":\n"; - out << ex; - } - catch(...) - { + out << "ServiceManager: exception in stop for service " << info.name << ":\n"; + out << ex; + } + catch(...) + { Warning out(_logger); - out << "ServiceManager: unknown exception in stop for service " << info.name; - } + out << "ServiceManager: unknown exception in stop for service " << info.name; + } } for(p = _services.rbegin(); p != _services.rend(); ++p) { - ServiceInfo& info = *p; - - if(info.communicator) - { - try - { - info.communicator->shutdown(); - info.communicator->waitForShutdown(); - } - catch(const Ice::CommunicatorDestroyedException&) - { - // - // Ignore, the service might have already destroyed - // the communicator for its own reasons. - // - } - catch(const Ice::Exception& ex) - { - Warning out(_logger); - out << "ServiceManager: exception in stop for service " << info.name << ":\n"; - out << ex; - } - } - - // - // Release the service, the service communicator and then the library. The order is important, - // the service must be released before destroying the communicator so that the communicator - // leak detector doesn't report potential leaks, and the communicator must be destroyed before - // the library is released since the library will destroy its global state. - // - try - { - info.service = 0; - } - catch(const Exception& ex) - { - Warning out(_logger); - out << "ServiceManager: exception in stop for service " << info.name << ":\n"; - out << ex; - } - catch(...) - { + ServiceInfo& info = *p; + + if(info.communicator) + { + try + { + info.communicator->shutdown(); + info.communicator->waitForShutdown(); + } + catch(const Ice::CommunicatorDestroyedException&) + { + // + // Ignore, the service might have already destroyed + // the communicator for its own reasons. + // + } + catch(const Ice::Exception& ex) + { + Warning out(_logger); + out << "ServiceManager: exception in stop for service " << info.name << ":\n"; + out << ex; + } + } + + // + // Release the service, the service communicator and then the library. The order is important, + // the service must be released before destroying the communicator so that the communicator + // leak detector doesn't report potential leaks, and the communicator must be destroyed before + // the library is released since the library will destroy its global state. + // + try + { + info.service = 0; + } + catch(const Exception& ex) + { Warning out(_logger); - out << "ServiceManager: unknown exception in stop for service " << info.name; - } - - if(info.communicator) - { - try - { - info.communicator->destroy(); - info.communicator = 0; - } - catch(const Exception& ex) - { - Warning out(_logger); - out << "ServiceManager: exception in stop for service " << info.name << ":\n"; - out << ex; - } - } - - try - { - info.library = 0; - } - catch(const Exception& ex) - { - Warning out(_logger); - out << "ServiceManager: exception in stop for service " << info.name << ":\n"; - out << ex; - } - catch(...) - { + out << "ServiceManager: exception in stop for service " << info.name << ":\n"; + out << ex; + } + catch(...) + { Warning out(_logger); - out << "ServiceManager: unknown exception in stop for service " << info.name; - } + out << "ServiceManager: unknown exception in stop for service " << info.name; + } + + if(info.communicator) + { + try + { + info.communicator->destroy(); + info.communicator = 0; + } + catch(const Exception& ex) + { + Warning out(_logger); + out << "ServiceManager: exception in stop for service " << info.name << ":\n"; + out << ex; + } + } + + try + { + info.library = 0; + } + catch(const Exception& ex) + { + Warning out(_logger); + out << "ServiceManager: exception in stop for service " << info.name << ":\n"; + out << ex; + } + catch(...) + { + Warning out(_logger); + out << "ServiceManager: unknown exception in stop for service " << info.name; + } } _services.clear(); diff --git a/cpp/src/IceBox/ServiceManagerI.h b/cpp/src/IceBox/ServiceManagerI.h index 95a12ad6096..5484aa7b3fa 100644 --- a/cpp/src/IceBox/ServiceManagerI.h +++ b/cpp/src/IceBox/ServiceManagerI.h @@ -39,10 +39,10 @@ public: ::std::string name; ServicePtr service; ::IceInternal::DynamicLibraryPtr library; - ::Ice::CommunicatorPtr communicator; - ::std::string envName; - bool active; - Ice::StringSeq args; + ::Ice::CommunicatorPtr communicator; + ::std::string envName; + bool active; + Ice::StringSeq args; }; bool start(); diff --git a/cpp/src/IceGrid/Activator.cpp b/cpp/src/IceGrid/Activator.cpp index c9535ba7814..8d6c04aa3ca 100644 --- a/cpp/src/IceGrid/Activator.cpp +++ b/cpp/src/IceGrid/Activator.cpp @@ -41,14 +41,14 @@ class TerminationListenerThread : public IceUtil::Thread public: TerminationListenerThread(Activator& activator) : - _activator(activator) + _activator(activator) { } virtual void run() { - _activator.runTerminationListener(); + _activator.runTerminationListener(); } private: @@ -81,8 +81,8 @@ reportChildError(int err, int fd, const char* cannot, const char* name) strcat(msg, "'"); if(err) { - strcat(msg, ": "); - strcat(msg, strerror(err)); + strcat(msg, ": "); + strcat(msg, strerror(err)); } write(fd, msg, strlen(msg)); close(fd); @@ -102,68 +102,68 @@ signalToString(int signal) { switch(signal) { - case SIGHUP: - { - return ICE_STRING(SIGHUP); - } - case SIGINT: - { - return ICE_STRING(SIGINT); - } - case SIGQUIT: - { - return ICE_STRING(SIGQUIT); - } - case SIGILL: - { - return ICE_STRING(SIGILL); - } - case SIGTRAP: - { - return ICE_STRING(SIGTRAP); - } - case SIGABRT: - { - return ICE_STRING(SIGABRT); - } - case SIGBUS: - { - return ICE_STRING(SIGBUS); - } - case SIGFPE: - { - return ICE_STRING(SIGFPE); - } - case SIGKILL: - { - return ICE_STRING(SIGKILL); - } - case SIGUSR1: - { - return ICE_STRING(SIGUSR1); - } - case SIGSEGV: - { - return ICE_STRING(SIGSEGV); - } - case SIGPIPE: - { - return ICE_STRING(SIGPIPE); - } - case SIGALRM: - { - return ICE_STRING(SIGALRM); - } - case SIGTERM: - { - return ICE_STRING(SIGTERM); - } - default: - { - ostringstream os; - os << "signal " << signal; - return os.str(); - } + case SIGHUP: + { + return ICE_STRING(SIGHUP); + } + case SIGINT: + { + return ICE_STRING(SIGINT); + } + case SIGQUIT: + { + return ICE_STRING(SIGQUIT); + } + case SIGILL: + { + return ICE_STRING(SIGILL); + } + case SIGTRAP: + { + return ICE_STRING(SIGTRAP); + } + case SIGABRT: + { + return ICE_STRING(SIGABRT); + } + case SIGBUS: + { + return ICE_STRING(SIGBUS); + } + case SIGFPE: + { + return ICE_STRING(SIGFPE); + } + case SIGKILL: + { + return ICE_STRING(SIGKILL); + } + case SIGUSR1: + { + return ICE_STRING(SIGUSR1); + } + case SIGSEGV: + { + return ICE_STRING(SIGSEGV); + } + case SIGPIPE: + { + return ICE_STRING(SIGPIPE); + } + case SIGALRM: + { + return ICE_STRING(SIGALRM); + } + case SIGTERM: + { + return ICE_STRING(SIGTERM); + } + default: + { + ostringstream os; + os << "signal " << signal; + return os.str(); + } } #endif } @@ -177,77 +177,77 @@ stringToSignal(const string& str) if(str == ICE_STRING(SIGHUP)) { - return SIGHUP; + return SIGHUP; } else if(str == ICE_STRING(SIGINT)) { - return SIGINT; + return SIGINT; } else if(str == ICE_STRING(SIGQUIT)) { - return SIGQUIT; + return SIGQUIT; } else if(str == ICE_STRING(SIGILL)) { - return SIGILL; + return SIGILL; } else if(str == ICE_STRING(SIGTRAP)) { - return SIGTRAP; + return SIGTRAP; } else if(str == ICE_STRING(SIGABRT)) { - return SIGABRT; + return SIGABRT; } else if(str == ICE_STRING(SIGBUS)) { - return SIGBUS; + return SIGBUS; } else if(str == ICE_STRING(SIGFPE)) { - return SIGFPE; + return SIGFPE; } else if(str == ICE_STRING(SIGKILL)) { - return SIGKILL; + return SIGKILL; } else if(str == ICE_STRING(SIGUSR1)) { - return SIGUSR1; + return SIGUSR1; } else if(str == ICE_STRING(SIGSEGV)) { - return SIGSEGV; + return SIGSEGV; } else if(str == ICE_STRING(SIGUSR2)) { - return SIGUSR2; + return SIGUSR2; } else if(str == ICE_STRING(SIGPIPE)) { - return SIGPIPE; + return SIGPIPE; } else if(str == ICE_STRING(SIGALRM)) { - return SIGALRM; + return SIGALRM; } else if(str == ICE_STRING(SIGTERM)) { - return SIGTERM; + return SIGTERM; } else { - if(str != "") - { - char* end; - long int signal = strtol(str.c_str(), &end, 10); - if(*end == '\0' && signal > 0 && signal < 64) - { - return static_cast(signal); - } - } - throw BadSignalException("unknown signal `" + str + "'"); - return SIGTERM; // Keep the compiler happy. + if(str != "") + { + char* end; + long int signal = strtol(str.c_str(), &end, 10); + if(*end == '\0' && signal > 0 && signal < 64) + { + return static_cast(signal); + } + } + throw BadSignalException("unknown signal `" + str + "'"); + return SIGTERM; // Keep the compiler happy. } } #endif @@ -268,17 +268,17 @@ Activator::Activator(const TraceLevelsPtr& traceLevels) : if(_hIntr == NULL) { - SyscallException ex(__FILE__, __LINE__); - ex.error = getSystemErrno(); - throw ex; + SyscallException ex(__FILE__, __LINE__); + ex.error = getSystemErrno(); + throw ex; } #else int fds[2]; if(pipe(fds) != 0) { - SyscallException ex(__FILE__, __LINE__); - ex.error = getSystemErrno(); - throw ex; + SyscallException ex(__FILE__, __LINE__); + ex.error = getSystemErrno(); + throw ex; } _fdIntrRead = fds[0]; _fdIntrWrite = fds[1]; @@ -307,56 +307,56 @@ Activator::~Activator() int Activator::activate(const string& name, - const string& exePath, - const string& pwdPath, + const string& exePath, + const string& pwdPath, #ifndef _WIN32 - uid_t uid, - gid_t gid, + uid_t uid, + gid_t gid, #endif - const Ice::StringSeq& options, - const Ice::StringSeq& envs, - const ServerIPtr& server) + const Ice::StringSeq& options, + const Ice::StringSeq& envs, + const ServerIPtr& server) { IceUtil::Monitor< IceUtil::Mutex>::Lock sync(*this); if(_deactivating) { - throw string("The node is being shutdown."); + throw string("The node is being shutdown."); } string path = exePath; if(path.empty()) { - throw string("The server executable path is empty."); + throw string("The server executable path is empty."); } string pwd = IcePatch2::simplify(pwdPath); #ifdef _WIN32 if(!IcePatch2::isAbsolute(path)) { - if(path.find('/') == string::npos) - { - // - // Get the absolute pathname of the executable. - // - char absbuf[_MAX_PATH]; - char* filePart; - string ext = path.size() <= 4 || path[path.size() - 4] != '.' ? ".exe" : ""; - if(SearchPath(NULL, path.c_str(), ext.c_str(), _MAX_PATH, absbuf, &filePart) == 0) - { - if(_traceLevels->activator > 0) - { - Trace out(_traceLevels->logger, _traceLevels->activatorCat); - out << "cannot convert `" << path << "' into an absolute path"; - } - throw string("The server executable path `" + path + "' can't be converted into an absolute path."); - } - path = absbuf; - } - else if(!pwd.empty()) - { - path = pwd + "/" + path; - } + if(path.find('/') == string::npos) + { + // + // Get the absolute pathname of the executable. + // + char absbuf[_MAX_PATH]; + char* filePart; + string ext = path.size() <= 4 || path[path.size() - 4] != '.' ? ".exe" : ""; + if(SearchPath(NULL, path.c_str(), ext.c_str(), _MAX_PATH, absbuf, &filePart) == 0) + { + if(_traceLevels->activator > 0) + { + Trace out(_traceLevels->logger, _traceLevels->activatorCat); + out << "cannot convert `" << path << "' into an absolute path"; + } + throw string("The server executable path `" + path + "' can't be converted into an absolute path."); + } + path = absbuf; + } + else if(!pwd.empty()) + { + path = pwd + "/" + path; + } } // @@ -364,17 +364,17 @@ Activator::activate(const string& name, // if(!pwd.empty()) { - char absbuf[_MAX_PATH]; - if(_fullpath(absbuf, pwd.c_str(), _MAX_PATH) == NULL) - { - if(_traceLevels->activator > 0) - { - Trace out(_traceLevels->logger, _traceLevels->activatorCat); - out << "cannot convert `" << pwd << "' into an absolute path"; - } - throw string("The server working directory path `" + pwd + "' can't be converted into an absolute path."); - } - pwd = absbuf; + char absbuf[_MAX_PATH]; + if(_fullpath(absbuf, pwd.c_str(), _MAX_PATH) == NULL) + { + if(_traceLevels->activator > 0) + { + Trace out(_traceLevels->logger, _traceLevels->activatorCat); + out << "cannot convert `" << pwd << "' into an absolute path"; + } + throw string("The server working directory path `" + pwd + "' can't be converted into an absolute path."); + } + pwd = absbuf; } #endif @@ -387,41 +387,41 @@ Activator::activate(const string& name, if(_traceLevels->activator > 0) { - Ice::Trace out(_traceLevels->logger, _traceLevels->activatorCat); - out << "activating server `" << name << "'"; - if(_traceLevels->activator > 1) - { - out << "\n"; - out << "path = " << path << "\n"; - if(pwd.empty()) - { + Ice::Trace out(_traceLevels->logger, _traceLevels->activatorCat); + out << "activating server `" << name << "'"; + if(_traceLevels->activator > 1) + { + out << "\n"; + out << "path = " << path << "\n"; + if(pwd.empty()) + { #ifdef _WIN32 - char cwd[_MAX_PATH]; - if(_getcwd(cwd, _MAX_PATH) != NULL) + char cwd[_MAX_PATH]; + if(_getcwd(cwd, _MAX_PATH) != NULL) #else - char cwd[PATH_MAX]; - if(getcwd(cwd, PATH_MAX) != NULL) + char cwd[PATH_MAX]; + if(getcwd(cwd, PATH_MAX) != NULL) #endif - { - out << "pwd = " << string(cwd) << "\n"; - } - } - else - { - out << "pwd = " << pwd << "\n"; - } + { + out << "pwd = " << string(cwd) << "\n"; + } + } + else + { + out << "pwd = " << pwd << "\n"; + } #ifndef _WIN32 - out << "uid/gid = " << uid << "/" << gid << "\n"; + out << "uid/gid = " << uid << "/" << gid << "\n"; #endif - if(!envs.empty()) - { - out << "envs = " << toString(envs, ", ") << "\n"; - } - if(!args.empty()) - { - out << "args = " << toString(args); - } - } + if(!envs.empty()) + { + out << "envs = " << toString(envs, ", ") << "\n"; + } + if(!args.empty()) + { + out << "args = " << toString(args); + } + } } // @@ -500,8 +500,8 @@ Activator::activate(const string& name, string::size_type pos = s.find('='); if(pos != string::npos) { - string key = s.substr(0, pos); - std::transform(key.begin(), key.end(), key.begin(), toupper); + string key = s.substr(0, pos); + std::transform(key.begin(), key.end(), key.begin(), toupper); envMap.insert(map::value_type(key, s.substr(pos + 1))); } var += s.size(); @@ -514,9 +514,9 @@ Activator::activate(const string& name, string::size_type pos = s.find('='); if(pos != string::npos) { - string key = s.substr(0, pos); - std::transform(key.begin(), key.end(), key.begin(), toupper); - envMap.erase(key); + string key = s.substr(0, pos); + std::transform(key.begin(), key.end(), key.begin(), toupper); + envMap.erase(key); envMap.insert(map::value_type(key, s.substr(pos + 1))); } } @@ -591,9 +591,9 @@ Activator::activate(const string& name, int fds[2]; if(pipe(fds) != 0) { - SyscallException ex(__FILE__, __LINE__); - ex.error = getSystemErrno(); - throw ex; + SyscallException ex(__FILE__, __LINE__); + ex.error = getSystemErrno(); + throw ex; } // @@ -604,8 +604,8 @@ Activator::activate(const string& name, int i = 0; for(StringSeq::const_iterator p = args.begin(); p != args.end(); ++p, ++i) { - assert(i < argc); - argv[i] = strdup(p->c_str()); + assert(i < argc); + argv[i] = strdup(p->c_str()); } assert(i == argc); argv[argc] = 0; @@ -615,7 +615,7 @@ Activator::activate(const string& name, i = 0; for(StringSeq::const_iterator q = envs.begin(); q != envs.end(); ++q) { - envArray[i++] = strdup(q->c_str()); + envArray[i++] = strdup(q->c_str()); } // @@ -626,118 +626,118 @@ Activator::activate(const string& name, pid_t pid = fork(); if(pid == -1) { - SyscallException ex(__FILE__, __LINE__); - ex.error = getSystemErrno(); - throw ex; + SyscallException ex(__FILE__, __LINE__); + ex.error = getSystemErrno(); + throw ex; } if(pid == 0) // Child process. { - // - // Until exec, we can only use async-signal safe functions - // - - // - // Change the uid/gid under which the process will run. - // - if(setgid(gid) == -1) - { - ostringstream os; - os << gid; - reportChildError(getSystemErrno(), fds[1], "cannot set process group id", os.str().c_str()); - } - - if(setuid(uid) == -1) - { - ostringstream os; - os << uid; - reportChildError(getSystemErrno(), fds[1], "cannot set process user id", os.str().c_str()); - } - - // - // Assign a new process group for this process. - // - setpgid(0, 0); - - // - // Close all file descriptors, except for standard input, - // standard output, standard error, and the write side - // of the newly created pipe. - // - int maxFd = static_cast(sysconf(_SC_OPEN_MAX)); - for(int fd = 3; fd < maxFd; ++fd) - { - if(fd != fds[1]) - { - close(fd); - } - } - - for(i = 0; i < envCount; i++) - { - if(putenv(envArray[i]) != 0) - { - reportChildError(errno, fds[1], "cannot set environment variable", envArray[i]); - } - } - // - // Each env is leaked on purpose ... see man putenv(). - // - delete[] envArray; - - // - // Change working directory. - // - if(strlen(pwdCStr) != 0) - { - if(chdir(pwdCStr) == -1) - { - reportChildError(errno, fds[1], "cannot change working directory to", pwdCStr); - } - } - - if(execvp(argv[0], argv) == -1) - { - reportChildError(errno, fds[1], "cannot execute", argv[0]); - } + // + // Until exec, we can only use async-signal safe functions + // + + // + // Change the uid/gid under which the process will run. + // + if(setgid(gid) == -1) + { + ostringstream os; + os << gid; + reportChildError(getSystemErrno(), fds[1], "cannot set process group id", os.str().c_str()); + } + + if(setuid(uid) == -1) + { + ostringstream os; + os << uid; + reportChildError(getSystemErrno(), fds[1], "cannot set process user id", os.str().c_str()); + } + + // + // Assign a new process group for this process. + // + setpgid(0, 0); + + // + // Close all file descriptors, except for standard input, + // standard output, standard error, and the write side + // of the newly created pipe. + // + int maxFd = static_cast(sysconf(_SC_OPEN_MAX)); + for(int fd = 3; fd < maxFd; ++fd) + { + if(fd != fds[1]) + { + close(fd); + } + } + + for(i = 0; i < envCount; i++) + { + if(putenv(envArray[i]) != 0) + { + reportChildError(errno, fds[1], "cannot set environment variable", envArray[i]); + } + } + // + // Each env is leaked on purpose ... see man putenv(). + // + delete[] envArray; + + // + // Change working directory. + // + if(strlen(pwdCStr) != 0) + { + if(chdir(pwdCStr) == -1) + { + reportChildError(errno, fds[1], "cannot change working directory to", pwdCStr); + } + } + + if(execvp(argv[0], argv) == -1) + { + reportChildError(errno, fds[1], "cannot execute", argv[0]); + } } else // Parent process. { - close(fds[1]); - - for(i = 0; argv[i]; i++) - { - free(argv[i]); - } - free(argv); - - for(i = 0; i < envCount; ++i) - { - free(envArray[i]); - } - delete[] envArray; - - Process process; - process.pid = pid; - process.pipeFd = fds[0]; - process.server = server; - _processes.insert(make_pair(name, process)); - - int flags = fcntl(process.pipeFd, F_GETFL); - flags |= O_NONBLOCK; - fcntl(process.pipeFd, F_SETFL, flags); - - setInterrupt(); + close(fds[1]); + + for(i = 0; argv[i]; i++) + { + free(argv[i]); + } + free(argv); + + for(i = 0; i < envCount; ++i) + { + free(envArray[i]); + } + delete[] envArray; + + Process process; + process.pid = pid; + process.pipeFd = fds[0]; + process.server = server; + _processes.insert(make_pair(name, process)); + + int flags = fcntl(process.pipeFd, F_GETFL); + flags |= O_NONBLOCK; + fcntl(process.pipeFd, F_SETFL, flags); + + setInterrupt(); // // Don't print the following trace, this might interfere with the // output of the started process if it fails with an error message. // -// if(_traceLevels->activator > 0) -// { -// Ice::Trace out(_traceLevels->logger, _traceLevels->activatorCat); -// out << "activated server `" << name << "' (pid = " << pid << ")"; -// } +// if(_traceLevels->activator > 0) +// { +// Ice::Trace out(_traceLevels->logger, _traceLevels->activatorCat); +// out << "activated server `" << name << "' (pid = " << pid << ")"; +// } } return pid; @@ -751,10 +751,10 @@ Activator::deactivate(const string& name, const Ice::ProcessPrx& process) Ice::Int pid = getServerPid(name); if(pid == 0) { - // - // Server is already deactivated. - // - return; + // + // Server is already deactivated. + // + return; } #endif @@ -763,21 +763,21 @@ Activator::deactivate(const string& name, const Ice::ProcessPrx& process) // if(process) { - if(_traceLevels->activator > 1) - { - Ice::Trace out(_traceLevels->logger, _traceLevels->activatorCat); - out << "deactivating `" << name << "' using process proxy"; - } - try - { - process->shutdown(); - return; - } - catch(const Ice::LocalException& ex) - { - Ice::Warning out(_traceLevels->logger); - out << "exception occurred while deactivating `" << name << "' using process proxy:\n" << ex; - } + if(_traceLevels->activator > 1) + { + Ice::Trace out(_traceLevels->logger, _traceLevels->activatorCat); + out << "deactivating `" << name << "' using process proxy"; + } + try + { + process->shutdown(); + return; + } + catch(const Ice::LocalException& ex) + { + Ice::Warning out(_traceLevels->logger); + out << "exception occurred while deactivating `" << name << "' using process proxy:\n" << ex; + } } if(_traceLevels->activator > 1) @@ -820,10 +820,10 @@ Activator::kill(const string& name) Ice::Int pid = getServerPid(name); if(pid == 0) { - // - // Server is already deactivated. - // - return; + // + // Server is already deactivated. + // + return; } HANDLE hnd = OpenProcess(PROCESS_TERMINATE, FALSE, pid); @@ -840,8 +840,8 @@ Activator::kill(const string& name) if(_traceLevels->activator > 1) { - Ice::Trace out(_traceLevels->logger, _traceLevels->activatorCat); - out << "terminating server `" << name << "' (pid = " << pid << ")"; + Ice::Trace out(_traceLevels->logger, _traceLevels->activatorCat); + out << "terminating server `" << name << "' (pid = " << pid << ")"; } #else @@ -869,24 +869,24 @@ Activator::sendSignal(const string& name, int signal) Ice::Int pid = getServerPid(name); if(pid == 0) { - // - // Server is already deactivated. - // - return; + // + // Server is already deactivated. + // + return; } int ret = ::kill(static_cast(pid), signal); if(ret != 0 && getSystemErrno() != ESRCH) { - SyscallException ex(__FILE__, __LINE__); - ex.error = getSystemErrno(); - throw ex; + SyscallException ex(__FILE__, __LINE__); + ex.error = getSystemErrno(); + throw ex; } if(_traceLevels->activator > 1) { - Ice::Trace out(_traceLevels->logger, _traceLevels->activatorCat); - out << "sent " << signalToString(signal) << " to server `" << name << "' (pid = " << pid << ")"; + Ice::Trace out(_traceLevels->logger, _traceLevels->activatorCat); + out << "sent " << signalToString(signal) << " to server `" << name << "' (pid = " << pid << ")"; } #endif } @@ -899,7 +899,7 @@ Activator::getServerPid(const string& name) map::const_iterator p = _processes.find(name); if(p == _processes.end()) { - return 0; + return 0; } return static_cast(p->second.pid); @@ -921,7 +921,7 @@ Activator::waitForShutdown() IceUtil::Monitor< IceUtil::Mutex>::Lock sync(*this); while(!_deactivating) { - wait(); + wait(); } } @@ -945,9 +945,9 @@ Activator::destroy() { map processes; { - IceUtil::Monitor< IceUtil::Mutex>::Lock sync(*this); - assert(_deactivating); - processes = _processes; + IceUtil::Monitor< IceUtil::Mutex>::Lock sync(*this); + assert(_deactivating); + processes = _processes; } // @@ -955,30 +955,30 @@ Activator::destroy() // for(map::iterator p = processes.begin(); p != processes.end(); ++p) { - // - // Stop the server. The listener thread should detect the - // process deactivation and remove it from the activator's - // list of active processes. - // - try - { - p->second.server->stop_async(0); - } - catch(const ServerStopException&) - { - // Server already stopped or destroyed. - } - catch(const ObjectNotExistException&) - { - // - // Expected if the server was in the process of being destroyed. - // - } - catch(const Ice::LocalException& ex) - { - Ice::Warning out(_traceLevels->logger); - out << "unexpected exception raised by server `" << p->first << "' stop:\n" << ex; - } + // + // Stop the server. The listener thread should detect the + // process deactivation and remove it from the activator's + // list of active processes. + // + try + { + p->second.server->stop_async(0); + } + catch(const ServerStopException&) + { + // Server already stopped or destroyed. + } + catch(const ObjectNotExistException&) + { + // + // Expected if the server was in the process of being destroyed. + // + } + catch(const Ice::LocalException& ex) + { + Ice::Warning out(_traceLevels->logger); + out << "unexpected exception raised by server `" << p->first << "' stop:\n" << ex; + } } // @@ -996,21 +996,21 @@ Activator::runTerminationListener() { while(true) { - try - { - terminationListener(); - break; - } - catch(const Exception& ex) - { - Error out(_traceLevels->logger); - out << "exception in process termination listener:\n" << ex; - } - catch(...) - { - Error out(_traceLevels->logger); - out << "unknown exception in process termination listener"; - } + try + { + terminationListener(); + break; + } + catch(const Exception& ex) + { + Error out(_traceLevels->logger); + out << "exception in process termination listener:\n" << ex; + } + catch(...) + { + Error out(_traceLevels->logger); + out << "unknown exception in process termination listener"; + } } } @@ -1051,60 +1051,60 @@ Activator::terminationListener() assert(pos < handles.size()); HANDLE hnd = handles[pos]; - vector terminated; - bool deactivated = false; - { - IceUtil::Monitor< IceUtil::Mutex>::Lock sync(*this); - - if(hnd == _hIntr) - { - clearInterrupt(); - } - else - { - for(map::iterator p = _processes.begin(); p != _processes.end(); ++p) - { - if(p->second.hnd == hnd) - { - terminated.push_back(p->second); - _processes.erase(p); - break; - } - } + vector terminated; + bool deactivated = false; + { + IceUtil::Monitor< IceUtil::Mutex>::Lock sync(*this); + + if(hnd == _hIntr) + { + clearInterrupt(); + } + else + { + for(map::iterator p = _processes.begin(); p != _processes.end(); ++p) + { + if(p->second.hnd == hnd) + { + terminated.push_back(p->second); + _processes.erase(p); + break; + } + } + } + + deactivated = _deactivating && _processes.empty(); + } + + for(vector::const_iterator p = terminated.begin(); p != terminated.end(); ++p) + { + DWORD status; + GetExitCodeProcess(p->hnd, &status); + CloseHandle(p->hnd); + assert(status != STILL_ACTIVE); + + if(_traceLevels->activator > 0) + { + Ice::Trace out(_traceLevels->logger, _traceLevels->activatorCat); + out << "detected termination of server `" << p->server->getId() << "'"; + if(status != 0) + { + out << "\nexit code = " << status; + } + } + + try + { + p->server->terminated("", status); } + catch(const Ice::LocalException& ex) + { + Ice::Warning out(_traceLevels->logger); + out << "unexpected exception raised by server `" << p->server->getId() << "' termination:\n" << ex; + } + } - deactivated = _deactivating && _processes.empty(); - } - - for(vector::const_iterator p = terminated.begin(); p != terminated.end(); ++p) - { - DWORD status; - GetExitCodeProcess(p->hnd, &status); - CloseHandle(p->hnd); - assert(status != STILL_ACTIVE); - - if(_traceLevels->activator > 0) - { - Ice::Trace out(_traceLevels->logger, _traceLevels->activatorCat); - out << "detected termination of server `" << p->server->getId() << "'"; - if(status != 0) - { - out << "\nexit code = " << status; - } - } - - try - { - p->server->terminated("", status); - } - catch(const Ice::LocalException& ex) - { - Ice::Warning out(_traceLevels->logger); - out << "unexpected exception raised by server `" << p->server->getId() << "' termination:\n" << ex; - } - } - - if(deactivated) + if(deactivated) { return; } @@ -1112,197 +1112,197 @@ Activator::terminationListener() #else while(true) { - fd_set fdSet; - int maxFd = _fdIntrRead; - FD_ZERO(&fdSet); - FD_SET(_fdIntrRead, &fdSet); - - { - IceUtil::Monitor< IceUtil::Mutex>::Lock sync(*this); - - for(map::iterator p = _processes.begin(); p != _processes.end(); ++p) - { - int fd = p->second.pipeFd; - FD_SET(fd, &fdSet); - if(maxFd < fd) - { - maxFd = fd; - } - } - } - + fd_set fdSet; + int maxFd = _fdIntrRead; + FD_ZERO(&fdSet); + FD_SET(_fdIntrRead, &fdSet); + + { + IceUtil::Monitor< IceUtil::Mutex>::Lock sync(*this); + + for(map::iterator p = _processes.begin(); p != _processes.end(); ++p) + { + int fd = p->second.pipeFd; + FD_SET(fd, &fdSet); + if(maxFd < fd) + { + maxFd = fd; + } + } + } + repeatSelect: - int ret = ::select(maxFd + 1, &fdSet, 0, 0, 0); - assert(ret != 0); - - if(ret == -1) - { + int ret = ::select(maxFd + 1, &fdSet, 0, 0, 0); + assert(ret != 0); + + if(ret == -1) + { #ifdef EPROTO - if(errno == EINTR || errno == EPROTO) - { - goto repeatSelect; - } + if(errno == EINTR || errno == EPROTO) + { + goto repeatSelect; + } #else - if(errno == EINTR) - { - goto repeatSelect; - } + if(errno == EINTR) + { + goto repeatSelect; + } #endif - - SyscallException ex(__FILE__, __LINE__); - ex.error = getSystemErrno(); - throw ex; - } - - vector terminated; - bool deactivated = false; - { - IceUtil::Monitor< IceUtil::Mutex>::Lock sync(*this); - - if(FD_ISSET(_fdIntrRead, &fdSet)) - { - clearInterrupt(); - - if(_deactivating && _processes.empty()) + + SyscallException ex(__FILE__, __LINE__); + ex.error = getSystemErrno(); + throw ex; + } + + vector terminated; + bool deactivated = false; + { + IceUtil::Monitor< IceUtil::Mutex>::Lock sync(*this); + + if(FD_ISSET(_fdIntrRead, &fdSet)) + { + clearInterrupt(); + + if(_deactivating && _processes.empty()) { return; } - } - - map::iterator p = _processes.begin(); - while(p != _processes.end()) - { - int fd = p->second.pipeFd; - if(!FD_ISSET(fd, &fdSet)) - { - ++p; - continue; - } - - char s[16]; - ssize_t rs; - string message; - - // - // Read the message over the pipe. - // - while((rs = read(fd, &s, 16)) > 0) - { - message.append(s, rs); - } - - // - // Keep the received message. - // - if(!message.empty()) - { - p->second.msg += message; - } - - if(rs == -1) - { - if(errno != EAGAIN || message.empty()) - { - SyscallException ex(__FILE__, __LINE__); - ex.error = getSystemErrno(); - throw ex; - } - - ++p; - } - else if(rs == 0) - { - // - // If the pipe was closed, the process has terminated. - // - - terminated.push_back(p->second); + } + + map::iterator p = _processes.begin(); + while(p != _processes.end()) + { + int fd = p->second.pipeFd; + if(!FD_ISSET(fd, &fdSet)) + { + ++p; + continue; + } + + char s[16]; + ssize_t rs; + string message; + + // + // Read the message over the pipe. + // + while((rs = read(fd, &s, 16)) > 0) + { + message.append(s, rs); + } + + // + // Keep the received message. + // + if(!message.empty()) + { + p->second.msg += message; + } + + if(rs == -1) + { + if(errno != EAGAIN || message.empty()) + { + SyscallException ex(__FILE__, __LINE__); + ex.error = getSystemErrno(); + throw ex; + } + + ++p; + } + else if(rs == 0) + { + // + // If the pipe was closed, the process has terminated. + // + + terminated.push_back(p->second); - close(p->second.pipeFd); - _processes.erase(p++); - } - } - - // - // We are deactivating and there's no more active processes. - // - deactivated = _deactivating && _processes.empty(); - } - - for(vector::const_iterator p = terminated.begin(); p != terminated.end(); ++p) - { - int status; + close(p->second.pipeFd); + _processes.erase(p++); + } + } + + // + // We are deactivating and there's no more active processes. + // + deactivated = _deactivating && _processes.empty(); + } + + for(vector::const_iterator p = terminated.begin(); p != terminated.end(); ++p) + { + int status; #if defined(__linux) - int nRetry = 0; - while(true) // The while loop is necessary for the linux workaround. - { - pid_t pid = waitpid(p->pid, &status, 0); - if(pid < 0) - { - // - // Some Linux distribution have a bogus waitpid() (e.g.: CentOS 4.x). It doesn't - // block and reports an incorrect ECHILD error on the first call. We sleep a - // little and retry to work around this issue (it appears from testing that a - // single retry is enough but to make sure we retry up to 10 times before to throw.) - // - if(errno == ECHILD && nRetry < 10) - { - // Wait 1ms, 11ms, 21ms, etc. - IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(nRetry * 10 + 1)); - ++nRetry; - continue; - } - SyscallException ex(__FILE__, __LINE__); - ex.error = getSystemErrno(); - throw ex; - } - assert(pid == p->pid); - break; - } + int nRetry = 0; + while(true) // The while loop is necessary for the linux workaround. + { + pid_t pid = waitpid(p->pid, &status, 0); + if(pid < 0) + { + // + // Some Linux distribution have a bogus waitpid() (e.g.: CentOS 4.x). It doesn't + // block and reports an incorrect ECHILD error on the first call. We sleep a + // little and retry to work around this issue (it appears from testing that a + // single retry is enough but to make sure we retry up to 10 times before to throw.) + // + if(errno == ECHILD && nRetry < 10) + { + // Wait 1ms, 11ms, 21ms, etc. + IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(nRetry * 10 + 1)); + ++nRetry; + continue; + } + SyscallException ex(__FILE__, __LINE__); + ex.error = getSystemErrno(); + throw ex; + } + assert(pid == p->pid); + break; + } #else - pid_t pid = waitpid(p->pid, &status, 0); - if(pid < 0) - { - SyscallException ex(__FILE__, __LINE__); - ex.error = getSystemErrno(); - throw ex; - } - assert(pid == p->pid); + pid_t pid = waitpid(p->pid, &status, 0); + if(pid < 0) + { + SyscallException ex(__FILE__, __LINE__); + ex.error = getSystemErrno(); + throw ex; + } + assert(pid == p->pid); #endif - if(_traceLevels->activator > 0) - { - Ice::Trace out(_traceLevels->logger, _traceLevels->activatorCat); - out << "detected termination of server `" << p->server->getId() << "'"; - if(!p->msg.empty()) - { - out << "\nreason = " << p->msg; - } - if(WIFEXITED(status) && status != 0) - { - out << "\nexit code = " << WEXITSTATUS(status); - } - else if(WIFSIGNALED(status)) - { - out << "\nsignal = " << signalToString(WTERMSIG(status)); - } - } - - try - { - p->server->terminated(p->msg, status); - } - catch(const Ice::LocalException& ex) - { - Ice::Warning out(_traceLevels->logger); - out << "unexpected exception raised by server `" << p->server->getId() << "' termination:\n" << ex; - } - } - - if(deactivated) - { - return; - } + if(_traceLevels->activator > 0) + { + Ice::Trace out(_traceLevels->logger, _traceLevels->activatorCat); + out << "detected termination of server `" << p->server->getId() << "'"; + if(!p->msg.empty()) + { + out << "\nreason = " << p->msg; + } + if(WIFEXITED(status) && status != 0) + { + out << "\nexit code = " << WEXITSTATUS(status); + } + else if(WIFSIGNALED(status)) + { + out << "\nsignal = " << signalToString(WTERMSIG(status)); + } + } + + try + { + p->server->terminated(p->msg, status); + } + catch(const Ice::LocalException& ex) + { + Ice::Warning out(_traceLevels->logger); + out << "unexpected exception raised by server `" << p->server->getId() << "' termination:\n" << ex; + } + } + + if(deactivated) + { + return; + } } #endif } diff --git a/cpp/src/IceGrid/Activator.h b/cpp/src/IceGrid/Activator.h index 40c7a9b3878..24a2b60f800 100644 --- a/cpp/src/IceGrid/Activator.h +++ b/cpp/src/IceGrid/Activator.h @@ -37,9 +37,9 @@ public: virtual int activate(const std::string&, const std::string&, const std::string&, #ifndef _WIN32 - uid_t, gid_t, + uid_t, gid_t, #endif - const Ice::StringSeq&, const Ice::StringSeq&, const ServerIPtr&); + const Ice::StringSeq&, const Ice::StringSeq&, const ServerIPtr&); virtual void deactivate(const std::string&, const Ice::ProcessPrx&); virtual void kill(const std::string&); virtual void sendSignal(const std::string&, const std::string&); @@ -67,11 +67,11 @@ private: DWORD pid; HANDLE hnd; #else - pid_t pid; - int pipeFd; - std::string msg; + pid_t pid; + int pipeFd; + std::string msg; #endif - ServerIPtr server; + ServerIPtr server; }; TraceLevelsPtr _traceLevels; diff --git a/cpp/src/IceGrid/AdapterCache.cpp b/cpp/src/IceGrid/AdapterCache.cpp index 5ebd4ba6c8d..64d235bacea 100644 --- a/cpp/src/IceGrid/AdapterCache.cpp +++ b/cpp/src/IceGrid/AdapterCache.cpp @@ -28,7 +28,7 @@ struct ReplicaLoadComp : binary_function& lhs, const pair& rhs) { - return lhs.first < rhs.first; + return lhs.first < rhs.first; } }; @@ -36,12 +36,12 @@ struct ReplicaPriorityComp : binary_functiongetPriority() < rhs->getPriority(); + return lhs->getPriority() < rhs->getPriority(); } }; struct TransformToReplicaLoad : - public unary_function > + public unary_function > { public: @@ -50,7 +50,7 @@ public: pair operator()(const ServerAdapterEntryPtr& value) { - return make_pair(value->getLeastLoadedNodeLoad(_loadSample), value); + return make_pair(value->getLeastLoadedNodeLoad(_loadSample), value); } LoadSample _loadSample; @@ -61,7 +61,7 @@ struct TransformToReplica : public unary_function& value) { - return value.second; + return value.second; } }; @@ -82,9 +82,9 @@ AdapterCache::addServerAdapter(const AdapterDescriptor& desc, const ServerEntryP if(!desc.replicaGroupId.empty()) { - ReplicaGroupEntryPtr repEntry = ReplicaGroupEntryPtr::dynamicCast(getImpl(desc.replicaGroupId)); - assert(repEntry); - repEntry->addReplica(desc.id, entry); + ReplicaGroupEntryPtr repEntry = ReplicaGroupEntryPtr::dynamicCast(getImpl(desc.replicaGroupId)); + assert(repEntry); + repEntry->addReplica(desc.id, entry); } return entry; @@ -107,7 +107,7 @@ AdapterCache::get(const string& id) const AdapterEntryPtr entry = getImpl(id); if(!entry) { - throw AdapterNotExistException(id); + throw AdapterNotExistException(id); } return entry; } @@ -124,9 +124,9 @@ AdapterCache::removeServerAdapter(const string& id) string replicaGroupId = entry->getReplicaGroupId(); if(!replicaGroupId.empty()) { - ReplicaGroupEntryPtr repEntry = ReplicaGroupEntryPtr::dynamicCast(getImpl(replicaGroupId)); - assert(repEntry); - repEntry->removeReplica(id); + ReplicaGroupEntryPtr repEntry = ReplicaGroupEntryPtr::dynamicCast(getImpl(replicaGroupId)); + assert(repEntry); + repEntry->removeReplica(id); } } @@ -142,8 +142,8 @@ AdapterCache::addImpl(const string& id, const AdapterEntryPtr& entry) { if(_traceLevels && _traceLevels->adapter > 0) { - Ice::Trace out(_traceLevels->logger, _traceLevels->adapterCat); - out << "added adapter `" << id << "'"; + Ice::Trace out(_traceLevels->logger, _traceLevels->adapterCat); + out << "added adapter `" << id << "'"; } return Cache::addImpl(id, entry); } @@ -153,8 +153,8 @@ AdapterCache::removeImpl(const string& id) { if(_traceLevels && _traceLevels->adapter > 0) { - Ice::Trace out(_traceLevels->logger, _traceLevels->adapterCat); - out << "removed adapter `" << id << "'"; + Ice::Trace out(_traceLevels->logger, _traceLevels->adapterCat); + out << "removed adapter `" << id << "'"; } Cache::removeImpl(id); } @@ -185,11 +185,11 @@ AdapterEntry::getApplication() const } ServerAdapterEntry::ServerAdapterEntry(AdapterCache& cache, - const string& id, - const string& application, - const string& replicaGroupId, - int priority, - const ServerEntryPtr& server) : + const string& id, + const string& application, + const string& replicaGroupId, + int priority, + const ServerEntryPtr& server) : AdapterEntry(cache, id, application), _replicaGroupId(replicaGroupId), _priority(priority), @@ -213,23 +213,23 @@ ServerAdapterEntry::getLeastLoadedNodeLoad(LoadSample loadSample) const { try { - return _server->getLoad(loadSample); + return _server->getLoad(loadSample); } catch(const ServerNotExistException&) { - // This might happen if the application is updated concurrently. + // This might happen if the application is updated concurrently. } catch(const NodeNotExistException&) { - // This might happen if the application is updated concurrently. + // This might happen if the application is updated concurrently. } catch(const NodeUnreachableException&) { } catch(const Ice::Exception& ex) { - Ice::Error error(_cache.getTraceLevels()->logger); - error << "unexpected exception while getting node load:\n" << ex; + Ice::Error error(_cache.getTraceLevels()->logger); + error << "unexpected exception while getting node load:\n" << ex; } return 999.9f; } @@ -242,7 +242,7 @@ ServerAdapterEntry::getAdapterInfo() const info.replicaGroupId = _replicaGroupId; try { - info.proxy = _server->getAdapter(_id, true)->getDirectProxy(); + info.proxy = _server->getAdapter(_id, true)->getDirectProxy(); } catch(const Ice::Exception&) { @@ -257,15 +257,15 @@ ServerAdapterEntry::getProxy(const string& replicaGroupId, bool upToDate) const { if(replicaGroupId.empty()) { - return _server->getAdapter(_id, upToDate); + return _server->getAdapter(_id, upToDate); } else { - if(_replicaGroupId != replicaGroupId) // Validate the replica group. - { - throw Ice::InvalidReplicaGroupIdException(); - } - return _server->getAdapter(_id, upToDate); + if(_replicaGroupId != replicaGroupId) // Validate the replica group. + { + throw Ice::InvalidReplicaGroupIdException(); + } + return _server->getAdapter(_id, upToDate); } } @@ -276,9 +276,9 @@ ServerAdapterEntry::getPriority() const } ReplicaGroupEntry::ReplicaGroupEntry(AdapterCache& cache, - const string& id, - const string& application, - const LoadBalancingPolicyPtr& policy) : + const string& id, + const string& application, + const LoadBalancingPolicyPtr& policy) : AdapterEntry(cache, id, application), _lastReplica(0) { @@ -298,13 +298,13 @@ ReplicaGroupEntry::removeReplica(const string& replicaId) Lock sync(*this); for(vector::iterator p = _replicas.begin(); p != _replicas.end(); ++p) { - if(replicaId == (*p)->getId()) - { - _replicas.erase(p); - // Make sure _lastReplica is still within the bounds. - _lastReplica = _replicas.empty() ? 0 : _lastReplica % static_cast(_replicas.size()); - break; - } + if(replicaId == (*p)->getId()) + { + _replicas.erase(p); + // Make sure _lastReplica is still within the bounds. + _lastReplica = _replicas.empty() ? 0 : _lastReplica % static_cast(_replicas.size()); + break; + } } } @@ -323,22 +323,22 @@ ReplicaGroupEntry::update(const LoadBalancingPolicyPtr& policy) AdaptiveLoadBalancingPolicyPtr alb = AdaptiveLoadBalancingPolicyPtr::dynamicCast(_loadBalancing); if(alb) { - if(alb->loadSample == "1") - { - _loadSample = LoadSample1; - } - else if(alb->loadSample == "5") - { - _loadSample = LoadSample5; - } - else if(alb->loadSample == "15") - { - _loadSample = LoadSample15; - } - else - { - _loadSample = LoadSample1; - } + if(alb->loadSample == "1") + { + _loadSample = LoadSample1; + } + else if(alb->loadSample == "5") + { + _loadSample = LoadSample5; + } + else if(alb->loadSample == "15") + { + _loadSample = LoadSample15; + } + else + { + _loadSample = LoadSample1; + } } } @@ -349,59 +349,59 @@ ReplicaGroupEntry::getLocatorAdapterInfo(LocatorAdapterInfoSeq& adapters, int& n bool adaptive = false; LoadSample loadSample = LoadSample1; { - Lock sync(*this); - replicaGroup = true; - nReplicas = _loadBalancingNReplicas > 0 ? _loadBalancingNReplicas : static_cast(_replicas.size()); - - if(_replicas.empty()) - { - return; - } - - replicas.reserve(_replicas.size()); - if(RoundRobinLoadBalancingPolicyPtr::dynamicCast(_loadBalancing)) - { - for(unsigned int i = 0; i < _replicas.size(); ++i) - { - replicas.push_back(_replicas[(_lastReplica + i) % _replicas.size()]); - } - _lastReplica = (_lastReplica + 1) % static_cast(_replicas.size()); - } - else if(AdaptiveLoadBalancingPolicyPtr::dynamicCast(_loadBalancing)) - { - replicas = _replicas; - RandomNumberGenerator rng; - random_shuffle(replicas.begin(), replicas.end(), rng); - loadSample = _loadSample; - adaptive = true; - } - else if(OrderedLoadBalancingPolicyPtr::dynamicCast(_loadBalancing)) - { - replicas = _replicas; - sort(replicas.begin(), replicas.end(), ReplicaPriorityComp()); - } - else if(RandomLoadBalancingPolicyPtr::dynamicCast(_loadBalancing)) - { - replicas = _replicas; - RandomNumberGenerator rng; - random_shuffle(replicas.begin(), replicas.end(), rng); - } + Lock sync(*this); + replicaGroup = true; + nReplicas = _loadBalancingNReplicas > 0 ? _loadBalancingNReplicas : static_cast(_replicas.size()); + + if(_replicas.empty()) + { + return; + } + + replicas.reserve(_replicas.size()); + if(RoundRobinLoadBalancingPolicyPtr::dynamicCast(_loadBalancing)) + { + for(unsigned int i = 0; i < _replicas.size(); ++i) + { + replicas.push_back(_replicas[(_lastReplica + i) % _replicas.size()]); + } + _lastReplica = (_lastReplica + 1) % static_cast(_replicas.size()); + } + else if(AdaptiveLoadBalancingPolicyPtr::dynamicCast(_loadBalancing)) + { + replicas = _replicas; + RandomNumberGenerator rng; + random_shuffle(replicas.begin(), replicas.end(), rng); + loadSample = _loadSample; + adaptive = true; + } + else if(OrderedLoadBalancingPolicyPtr::dynamicCast(_loadBalancing)) + { + replicas = _replicas; + sort(replicas.begin(), replicas.end(), ReplicaPriorityComp()); + } + else if(RandomLoadBalancingPolicyPtr::dynamicCast(_loadBalancing)) + { + replicas = _replicas; + RandomNumberGenerator rng; + random_shuffle(replicas.begin(), replicas.end(), rng); + } } if(adaptive) { - // - // This must be done outside the synchronization block since - // the trasnform() might call and lock each server adapter - // entry. We also can't sort directly as the load of each - // server adapter is not stable so we first take a snapshot of - // each adapter and sort the snapshot. - // - vector > rl; - transform(replicas.begin(), replicas.end(), back_inserter(rl), TransformToReplicaLoad(loadSample)); - sort(rl.begin(), rl.end(), ReplicaLoadComp()); - replicas.clear(); - transform(rl.begin(), rl.end(), back_inserter(replicas), TransformToReplica()); + // + // This must be done outside the synchronization block since + // the trasnform() might call and lock each server adapter + // entry. We also can't sort directly as the load of each + // server adapter is not stable so we first take a snapshot of + // each adapter and sort the snapshot. + // + vector > rl; + transform(replicas.begin(), replicas.end(), back_inserter(rl), TransformToReplicaLoad(loadSample)); + sort(rl.begin(), rl.end(), ReplicaLoadComp()); + replicas.clear(); + transform(rl.begin(), rl.end(), back_inserter(replicas), TransformToReplica()); } // @@ -411,21 +411,21 @@ ReplicaGroupEntry::getLocatorAdapterInfo(LocatorAdapterInfoSeq& adapters, int& n // for(vector::const_iterator p = replicas.begin(); p != replicas.end(); ++p) { - try - { - int dummy; - bool dummy2; - (*p)->getLocatorAdapterInfo(adapters, dummy, dummy2); - } - catch(const AdapterNotExistException&) - { - } - catch(const NodeUnreachableException&) - { - } - catch(const DeploymentException&) - { - } + try + { + int dummy; + bool dummy2; + (*p)->getLocatorAdapterInfo(adapters, dummy, dummy2); + } + catch(const AdapterNotExistException&) + { + } + catch(const NodeUnreachableException&) + { + } + catch(const DeploymentException&) + { + } } } @@ -434,25 +434,25 @@ ReplicaGroupEntry::getLeastLoadedNodeLoad(LoadSample loadSample) const { vector replicas; { - Lock sync(*this); - replicas = _replicas; + Lock sync(*this); + replicas = _replicas; } if(replicas.empty()) { - return 999.9f; + return 999.9f; } else if(replicas.size() == 1) { - return replicas.back()->getLeastLoadedNodeLoad(loadSample); + return replicas.back()->getLeastLoadedNodeLoad(loadSample); } else { - RandomNumberGenerator rng; - random_shuffle(replicas.begin(), replicas.end(), rng); - vector > rl; - transform(replicas.begin(), replicas.end(), back_inserter(rl), TransformToReplicaLoad(loadSample)); - return min_element(rl.begin(), rl.end(), ReplicaLoadComp())->first; + RandomNumberGenerator rng; + random_shuffle(replicas.begin(), replicas.end(), rng); + vector > rl; + transform(replicas.begin(), replicas.end(), back_inserter(rl), TransformToReplicaLoad(loadSample)); + return min_element(rl.begin(), rl.end(), ReplicaLoadComp())->first; } } @@ -461,16 +461,16 @@ ReplicaGroupEntry::getAdapterInfo() const { vector replicas; { - Lock sync(*this); - replicas = _replicas; + Lock sync(*this); + replicas = _replicas; } AdapterInfoSeq infos; for(vector::const_iterator p = replicas.begin(); p != replicas.end(); ++p) { - AdapterInfoSeq infs = (*p)->getAdapterInfo(); - assert(infs.size() == 1); - infos.push_back(infs[0]); + AdapterInfoSeq infs = (*p)->getAdapterInfo(); + assert(infs.size() == 1); + infos.push_back(infs[0]); } return infos; } diff --git a/cpp/src/IceGrid/AdapterCache.h b/cpp/src/IceGrid/AdapterCache.h index 14debc9838d..8e45f5b186e 100644 --- a/cpp/src/IceGrid/AdapterCache.h +++ b/cpp/src/IceGrid/AdapterCache.h @@ -65,7 +65,7 @@ class ServerAdapterEntry : public AdapterEntry public: ServerAdapterEntry(AdapterCache&, const std::string&, const std::string&, const std::string&, int, - const ServerEntryPtr&); + const ServerEntryPtr&); virtual void getLocatorAdapterInfo(LocatorAdapterInfoSeq&, int&, bool&); virtual float getLeastLoadedNodeLoad(LoadSample) const; diff --git a/cpp/src/IceGrid/AdminI.cpp b/cpp/src/IceGrid/AdminI.cpp index 70a95368cd4..cf2d752f6b9 100644 --- a/cpp/src/IceGrid/AdminI.cpp +++ b/cpp/src/IceGrid/AdminI.cpp @@ -36,48 +36,48 @@ public: ServerProxyWrapper(const DatabasePtr& database, const string& id) : _id(id) { - _proxy = database->getServer(_id)->getProxy(_activationTimeout, _deactivationTimeout, _node); + _proxy = database->getServer(_id)->getProxy(_activationTimeout, _deactivationTimeout, _node); } void useActivationTimeout() { - _proxy = ServerPrx::uncheckedCast(_proxy->ice_timeout(_activationTimeout * 1000)); + _proxy = ServerPrx::uncheckedCast(_proxy->ice_timeout(_activationTimeout * 1000)); } void useDeactivationTimeout() { - _proxy = ServerPrx::uncheckedCast(_proxy->ice_timeout(_deactivationTimeout * 1000)); + _proxy = ServerPrx::uncheckedCast(_proxy->ice_timeout(_deactivationTimeout * 1000)); } IceProxy::IceGrid::Server* operator->() const { - return _proxy.get(); + return _proxy.get(); } void handleException(const Ice::Exception& ex) { - try - { - ex.ice_throw(); - } - catch(const Ice::UserException&) - { - throw; - } - catch(const Ice::ObjectNotExistException&) - { - throw ServerNotExistException(_id); - } - catch(const Ice::LocalException& e) - { - ostringstream os; - os << e; - throw NodeUnreachableException(_node, os.str()); - } + try + { + ex.ice_throw(); + } + catch(const Ice::UserException&) + { + throw; + } + catch(const Ice::ObjectNotExistException&) + { + throw ServerNotExistException(_id); + } + catch(const Ice::LocalException& e) + { + ostringstream os; + os << e; + throw NodeUnreachableException(_node, os.str()); + } } private: @@ -95,13 +95,13 @@ class AMDPatcherFeedbackAggregator : public PatcherFeedbackAggregator public: AMDPatcherFeedbackAggregator(const AmdCB& cb, - Ice::Identity id, - const TraceLevelsPtr& traceLevels, - const string& type, - const string& name, - int nodeCount) : - PatcherFeedbackAggregator(id, traceLevels, type, name, nodeCount), - _cb(cb) + Ice::Identity id, + const TraceLevelsPtr& traceLevels, + const string& type, + const string& name, + int nodeCount) : + PatcherFeedbackAggregator(id, traceLevels, type, name, nodeCount), + _cb(cb) { } @@ -110,13 +110,13 @@ private: void response() { - _cb->ice_response(); + _cb->ice_response(); } void exception(const Ice::Exception& ex) { - _cb->ice_exception(ex); + _cb->ice_exception(ex); } const AmdCB _cb; @@ -125,11 +125,11 @@ private: template PatcherFeedbackAggregatorPtr static newPatcherFeedback(const AmdCB& cb, - Ice::Identity id, - const TraceLevelsPtr& traceLevels, - const string& type, - const string& name, - int nodeCount) + Ice::Identity id, + const TraceLevelsPtr& traceLevels, + const string& type, + const string& name, + int nodeCount) { return new AMDPatcherFeedbackAggregator(cb, id, traceLevels, type, name, nodeCount); } @@ -200,9 +200,9 @@ AdminI::instantiateServer(const string& app, const string& node, const ServerIns void AdminI::patchApplication_async(const AMD_Admin_patchApplicationPtr& amdCB, - const string& name, - bool shutdown, - const Current& current) + const string& name, + bool shutdown, + const Current& current) { ApplicationHelper helper(current.adapter->getCommunicator(), _database->getApplicationInfo(name).descriptor); DistributionDescriptor appDistrib; @@ -211,8 +211,8 @@ AdminI::patchApplication_async(const AMD_Admin_patchApplicationPtr& amdCB, if(nodes.empty()) { - amdCB->ice_response(); - return; + amdCB->ice_response(); + return; } Ice::Identity id; @@ -220,39 +220,39 @@ AdminI::patchApplication_async(const AMD_Admin_patchApplicationPtr& amdCB, id.name = IceUtil::generateUUID(); PatcherFeedbackAggregatorPtr feedback = - newPatcherFeedback(amdCB, id, _traceLevels, "application", name, static_cast(nodes.size())); + newPatcherFeedback(amdCB, id, _traceLevels, "application", name, static_cast(nodes.size())); for(vector::const_iterator p = nodes.begin(); p != nodes.end(); ++p) { - try - { - if(_traceLevels->patch > 0) - { - Ice::Trace out(_traceLevels->logger, _traceLevels->patchCat); - out << "started patching of application `" << name << "' on node `" << *p << "'"; - } - - NodeEntryPtr node = _database->getNode(*p); - Resolver resolve(node->getInfo(), _database->getCommunicator()); - DistributionDescriptor desc = resolve(appDistrib); - InternalDistributionDescriptorPtr intAppDistrib = new InternalDistributionDescriptor(desc.icepatch, - desc.directories); - node->getSession()->patch(feedback, name, "", intAppDistrib, shutdown); - } - catch(const NodeNotExistException&) - { - feedback->failed(*p, "node doesn't exist"); - } - catch(const NodeUnreachableException& e) - { - feedback->failed(*p, "node is unreachable: " + e.reason); - } - catch(const Ice::Exception& e) - { - ostringstream os; - os << e; - feedback->failed(*p, "node is unreachable:\n" + os.str()); - } + try + { + if(_traceLevels->patch > 0) + { + Ice::Trace out(_traceLevels->logger, _traceLevels->patchCat); + out << "started patching of application `" << name << "' on node `" << *p << "'"; + } + + NodeEntryPtr node = _database->getNode(*p); + Resolver resolve(node->getInfo(), _database->getCommunicator()); + DistributionDescriptor desc = resolve(appDistrib); + InternalDistributionDescriptorPtr intAppDistrib = new InternalDistributionDescriptor(desc.icepatch, + desc.directories); + node->getSession()->patch(feedback, name, "", intAppDistrib, shutdown); + } + catch(const NodeNotExistException&) + { + feedback->failed(*p, "node doesn't exist"); + } + catch(const NodeUnreachableException& e) + { + feedback->failed(*p, "node is unreachable: " + e.reason); + } + catch(const Ice::Exception& e) + { + ostringstream os; + os << e; + feedback->failed(*p, "node is unreachable:\n" + os.str()); + } } } @@ -269,49 +269,49 @@ AdminI::getDefaultApplicationDescriptor(const Current& current) const string path = properties->getProperty("IceGrid.Registry.DefaultTemplates"); if(path.empty()) { - throw DeploymentException("no default templates configured, you need to set " - "IceGrid.Registry.DefaultTemplates in the IceGrid registry configuration."); + throw DeploymentException("no default templates configured, you need to set " + "IceGrid.Registry.DefaultTemplates in the IceGrid registry configuration."); } ApplicationDescriptor desc; try { - desc = DescriptorParser::parseDescriptor(path, current.adapter->getCommunicator()); + desc = DescriptorParser::parseDescriptor(path, current.adapter->getCommunicator()); } catch(const IceXML::ParserException& ex) { - throw DeploymentException("can't parse default templates:\n" + ex.reason()); + throw DeploymentException("can't parse default templates:\n" + ex.reason()); } desc.name = ""; if(!desc.nodes.empty()) { - Ice::Warning warn(_traceLevels->logger); - warn << "default application descriptor:\nnode definitions are not allowed."; - desc.nodes.clear(); + Ice::Warning warn(_traceLevels->logger); + warn << "default application descriptor:\nnode definitions are not allowed."; + desc.nodes.clear(); } if(!desc.distrib.icepatch.empty() || !desc.distrib.directories.empty()) { - Ice::Warning warn(_traceLevels->logger); - warn << "default application descriptor:\ndistribution is not allowed."; - desc.distrib = DistributionDescriptor(); + Ice::Warning warn(_traceLevels->logger); + warn << "default application descriptor:\ndistribution is not allowed."; + desc.distrib = DistributionDescriptor(); } if(!desc.replicaGroups.empty()) { - Ice::Warning warn(_traceLevels->logger); - warn << "default application descriptor:\nreplica group definitions are not allowed."; - desc.replicaGroups.clear(); + Ice::Warning warn(_traceLevels->logger); + warn << "default application descriptor:\nreplica group definitions are not allowed."; + desc.replicaGroups.clear(); } if(!desc.description.empty()) { - Ice::Warning warn(_traceLevels->logger); - warn << "default application descriptor:\ndescription is not allowed."; - desc.description = ""; + Ice::Warning warn(_traceLevels->logger); + warn << "default application descriptor:\ndescription is not allowed."; + desc.description = ""; } if(!desc.variables.empty()) { - Ice::Warning warn(_traceLevels->logger); - warn << "default application descriptor:\nvariable definitions are not allowed."; - desc.variables.clear(); + Ice::Warning warn(_traceLevels->logger); + warn << "default application descriptor:\nvariable definitions are not allowed."; + desc.variables.clear(); } return desc; } @@ -334,12 +334,12 @@ AdminI::getServerState(const string& id, const Current&) const ServerProxyWrapper proxy(_database, id); try { - return proxy->getState(); + return proxy->getState(); } catch(const Ice::Exception& ex) { - proxy.handleException(ex); - return Inactive; + proxy.handleException(ex); + return Inactive; } } @@ -349,12 +349,12 @@ AdminI::getServerPid(const string& id, const Current&) const ServerProxyWrapper proxy(_database, id); try { - return proxy->getPid(); + return proxy->getPid(); } catch(const Ice::Exception& ex) { - proxy.handleException(ex); - return 0; + proxy.handleException(ex); + return 0; } } @@ -365,11 +365,11 @@ AdminI::startServer(const string& id, const Current&) proxy.useActivationTimeout(); try { - proxy->start(); + proxy->start(); } catch(const Ice::Exception& ex) { - proxy.handleException(ex); + proxy.handleException(ex); } } @@ -380,20 +380,20 @@ AdminI::stopServer(const string& id, const Current&) proxy.useDeactivationTimeout(); try { - proxy->stop(); + proxy->stop(); } catch(const Ice::TimeoutException&) { } catch(const Ice::Exception& ex) { - proxy.handleException(ex); + proxy.handleException(ex); } } void AdminI::patchServer_async(const AMD_Admin_patchServerPtr& amdCB, const string& id, bool shutdown, - const Current& current) + const Current& current) { ServerInfo info = _database->getServer(id)->getInfo(); ApplicationInfo appInfo = _database->getApplicationInfo(info.application); @@ -404,8 +404,8 @@ AdminI::patchServer_async(const AMD_Admin_patchServerPtr& amdCB, const string& i if(appDistrib.icepatch.empty() && nodes.empty()) { - amdCB->ice_response(); - return; + amdCB->ice_response(); + return; } assert(nodes.size() == 1); @@ -415,37 +415,37 @@ AdminI::patchServer_async(const AMD_Admin_patchServerPtr& amdCB, const string& i identity.name = IceUtil::generateUUID(); PatcherFeedbackAggregatorPtr feedback = - newPatcherFeedback(amdCB, identity, _traceLevels, "server", id, static_cast(nodes.size())); + newPatcherFeedback(amdCB, identity, _traceLevels, "server", id, static_cast(nodes.size())); vector::const_iterator p = nodes.begin(); try { - if(_traceLevels->patch > 0) - { - Ice::Trace out(_traceLevels->logger, _traceLevels->patchCat); - out << "started patching of server `" << id << "' on node `" << *p << "'"; - } + if(_traceLevels->patch > 0) + { + Ice::Trace out(_traceLevels->logger, _traceLevels->patchCat); + out << "started patching of server `" << id << "' on node `" << *p << "'"; + } - NodeEntryPtr node = _database->getNode(*p); - Resolver resolve(node->getInfo(), _database->getCommunicator()); - DistributionDescriptor desc = resolve(appDistrib); - InternalDistributionDescriptorPtr intAppDistrib = new InternalDistributionDescriptor(desc.icepatch, - desc.directories); - node->getSession()->patch(feedback, info.application, id, intAppDistrib, shutdown); + NodeEntryPtr node = _database->getNode(*p); + Resolver resolve(node->getInfo(), _database->getCommunicator()); + DistributionDescriptor desc = resolve(appDistrib); + InternalDistributionDescriptorPtr intAppDistrib = new InternalDistributionDescriptor(desc.icepatch, + desc.directories); + node->getSession()->patch(feedback, info.application, id, intAppDistrib, shutdown); } catch(const NodeNotExistException&) { - feedback->failed(*p, "node doesn't exist"); + feedback->failed(*p, "node doesn't exist"); } catch(const NodeUnreachableException& e) { - feedback->failed(*p, "node is unreachable: " + e.reason); + feedback->failed(*p, "node is unreachable: " + e.reason); } catch(const Ice::Exception& e) { - ostringstream os; - os << e; - feedback->failed(*p, "node is unreachable:\n" + os.str()); + ostringstream os; + os << e; + feedback->failed(*p, "node is unreachable:\n" + os.str()); } } @@ -455,11 +455,11 @@ AdminI::sendSignal(const string& id, const string& signal, const Current&) ServerProxyWrapper proxy(_database, id); try { - proxy->sendSignal(signal); + proxy->sendSignal(signal); } catch(const Ice::Exception& ex) { - proxy.handleException(ex); + proxy.handleException(ex); } } @@ -469,11 +469,11 @@ AdminI::writeMessage(const string& id, const string& message, Int fd, const Curr ServerProxyWrapper proxy(_database, id); try { - proxy->writeMessage(message, fd); + proxy->writeMessage(message, fd); } catch(const Ice::Exception& ex) { - proxy.handleException(ex); + proxy.handleException(ex); } } @@ -489,11 +489,11 @@ AdminI::enableServer(const string& id, bool enable, const Ice::Current&) ServerProxyWrapper proxy(_database, id); try { - proxy->setEnabled(enable); + proxy->setEnabled(enable); } catch(const Ice::Exception& ex) { - proxy.handleException(ex); + proxy.handleException(ex); } } @@ -503,12 +503,12 @@ AdminI::isServerEnabled(const ::std::string& id, const Ice::Current&) const ServerProxyWrapper proxy(_database, id); try { - return proxy->isEnabled(); + return proxy->isEnabled(); } catch(const Ice::Exception& ex) { - proxy.handleException(ex); - return true; // Keeps the compiler happy. + proxy.handleException(ex); + return true; // Keeps the compiler happy. } } @@ -537,15 +537,15 @@ AdminI::addObject(const Ice::ObjectPrx& proxy, const ::Ice::Current& current) checkIsMaster(); try { - addObjectWithType(proxy, proxy->ice_id(), current); + addObjectWithType(proxy, proxy->ice_id(), current); } catch(const Ice::LocalException& e) { - ostringstream os; + ostringstream os; - os << "failed to invoke ice_id() on proxy `" + current.adapter->getCommunicator()->proxyToString(proxy); - os << "':\n" << e; - throw DeploymentException(os.str()); + os << "failed to invoke ice_id() on proxy `" + current.adapter->getCommunicator()->proxyToString(proxy); + os << "':\n" << e; + throw DeploymentException(os.str()); } } @@ -556,9 +556,9 @@ AdminI::updateObject(const Ice::ObjectPrx& proxy, const ::Ice::Current& current) const Ice::Identity id = proxy->ice_getIdentity(); if(id.category == _database->getInstanceName()) { - DeploymentException ex; - ex.reason ="updating object `" + _database->getCommunicator()->identityToString(id) + "' is not allowed"; - throw ex; + DeploymentException ex; + ex.reason ="updating object `" + _database->getCommunicator()->identityToString(id) + "' is not allowed"; + throw ex; } _database->updateObject(proxy); } @@ -570,9 +570,9 @@ AdminI::addObjectWithType(const Ice::ObjectPrx& proxy, const string& type, const const Ice::Identity id = proxy->ice_getIdentity(); if(id.category == _database->getInstanceName()) { - DeploymentException ex; - ex.reason = "adding object `" + _database->getCommunicator()->identityToString(id) + "' is not allowed"; - throw ex; + DeploymentException ex; + ex.reason = "adding object `" + _database->getCommunicator()->identityToString(id) + "' is not allowed"; + throw ex; } ObjectInfo info; @@ -587,9 +587,9 @@ AdminI::removeObject(const Ice::Identity& id, const Ice::Current& current) checkIsMaster(); if(id.category == _database->getInstanceName()) { - DeploymentException ex; - ex.reason = "removing object `" + _database->getCommunicator()->identityToString(id) + "' is not allowed"; - throw ex; + DeploymentException ex; + ex.reason = "removing object `" + _database->getCommunicator()->identityToString(id) + "' is not allowed"; + throw ex; } _database->removeObject(id); } @@ -623,20 +623,20 @@ AdminI::pingNode(const string& name, const Current&) const { try { - _database->getNode(name)->getProxy()->ice_ping(); - return true; + _database->getNode(name)->getProxy()->ice_ping(); + return true; } catch(const NodeUnreachableException&) { - return false; + return false; } catch(const Ice::ObjectNotExistException&) { - throw NodeNotExistException(); + throw NodeNotExistException(); } catch(const Ice::LocalException&) { - return false; + return false; } } @@ -645,17 +645,17 @@ AdminI::getNodeLoad(const string& name, const Current&) const { try { - return _database->getNode(name)->getProxy()->getLoad(); + return _database->getNode(name)->getProxy()->getLoad(); } catch(const Ice::ObjectNotExistException&) { - throw NodeNotExistException(); + throw NodeNotExistException(); } catch(const Ice::LocalException& ex) { - ostringstream os; - os << ex; - throw NodeUnreachableException(name, os.str()); + ostringstream os; + os << ex; + throw NodeUnreachableException(name, os.str()); } return LoadInfo(); // Keep the compiler happy. } @@ -665,17 +665,17 @@ AdminI::shutdownNode(const string& name, const Current&) { try { - _database->getNode(name)->getProxy()->shutdown(); + _database->getNode(name)->getProxy()->shutdown(); } catch(const Ice::ObjectNotExistException&) { - throw NodeNotExistException(name); + throw NodeNotExistException(name); } catch(const Ice::LocalException& ex) { - ostringstream os; - os << ex; - throw NodeUnreachableException(name, os.str()); + ostringstream os; + os << ex; + throw NodeUnreachableException(name, os.str()); } } @@ -684,18 +684,18 @@ AdminI::getNodeHostname(const string& name, const Current&) const { try { - return _database->getNode(name)->getInfo()->hostname; + return _database->getNode(name)->getInfo()->hostname; } catch(const Ice::ObjectNotExistException&) { - throw NodeNotExistException(name); + throw NodeNotExistException(name); } catch(const Ice::LocalException& ex) { - ostringstream os; - os << ex; - throw NodeUnreachableException(name, os.str()); - return ""; // Keep the compiler happy. + ostringstream os; + os << ex; + throw NodeUnreachableException(name, os.str()); + return ""; // Keep the compiler happy. } } @@ -711,11 +711,11 @@ AdminI::getRegistryInfo(const string& name, const Ice::Current&) const { if(name == _registry->getName()) { - return _registry->getInfo(); + return _registry->getInfo(); } else { - return toRegistryInfo(_database->getReplica(name)->getInfo()); + return toRegistryInfo(_database->getReplica(name)->getInfo()); } } @@ -724,21 +724,21 @@ AdminI::pingRegistry(const string& name, const Current&) const { if(name == _registry->getName()) { - return true; + return true; } try { - _database->getReplica(name)->getProxy()->ice_ping(); - return true; + _database->getReplica(name)->getProxy()->ice_ping(); + return true; } catch(const Ice::ObjectNotExistException&) { - throw RegistryNotExistException(); + throw RegistryNotExistException(); } catch(const Ice::LocalException&) { - return false; + return false; } return false; } @@ -748,23 +748,23 @@ AdminI::shutdownRegistry(const string& name, const Current&) { if(name == _registry->getName()) { - _registry->shutdown(); - return; + _registry->shutdown(); + return; } try { - _database->getReplica(name)->getProxy()->shutdown(); + _database->getReplica(name)->getProxy()->shutdown(); } catch(const Ice::ObjectNotExistException&) { - throw RegistryNotExistException(name); + throw RegistryNotExistException(name); } catch(const Ice::LocalException& ex) { - ostringstream os; - os << ex; - throw RegistryUnreachableException(name, os.str()); + ostringstream os; + os << ex; + throw RegistryUnreachableException(name, os.str()); } } @@ -793,9 +793,9 @@ AdminI::checkIsMaster() const { if(!_database->isMaster()) { - DeploymentException ex; - ex.reason = "this operation is only allowed on the master registry."; - throw ex; + DeploymentException ex; + ex.reason = "this operation is only allowed on the master registry."; + throw ex; } } diff --git a/cpp/src/IceGrid/AdminI.h b/cpp/src/IceGrid/AdminI.h index bce347df242..a5c63735ad9 100644 --- a/cpp/src/IceGrid/AdminI.h +++ b/cpp/src/IceGrid/AdminI.h @@ -39,9 +39,9 @@ public: virtual void updateApplication(const ApplicationUpdateDescriptor&, const Ice::Current&); virtual void removeApplication(const std::string&, const Ice::Current&); virtual void instantiateServer(const std::string&, const std::string&, const ServerInstanceDescriptor&, - const Ice::Current&); + const Ice::Current&); virtual void patchApplication_async(const AMD_Admin_patchApplicationPtr&, const std::string&, bool, - const Ice::Current&); + const Ice::Current&); virtual ApplicationInfo getApplicationInfo(const ::std::string&, const Ice::Current&) const; virtual ApplicationDescriptor getDefaultApplicationDescriptor(const Ice::Current&) const; virtual Ice::StringSeq getAllApplicationNames(const Ice::Current&) const; diff --git a/cpp/src/IceGrid/AdminSessionI.cpp b/cpp/src/IceGrid/AdminSessionI.cpp index 44a634abd5d..8422018e210 100644 --- a/cpp/src/IceGrid/AdminSessionI.cpp +++ b/cpp/src/IceGrid/AdminSessionI.cpp @@ -20,10 +20,10 @@ using namespace std; using namespace IceGrid; FileIteratorI::FileIteratorI(const AdminSessionIPtr& session, - const FileReaderPrx& reader, - const string& filename, - Ice::Long offset, - int messageSizeMax) : + const FileReaderPrx& reader, + const string& filename, + Ice::Long offset, + int messageSizeMax) : _session(session), _reader(reader), _filename(filename), @@ -37,13 +37,13 @@ FileIteratorI::read(int size, Ice::StringSeq& lines, const Ice::Current& current { try { - return _reader->read(_filename, _offset, size > _messageSizeMax ? _messageSizeMax : size, _offset, lines); + return _reader->read(_filename, _offset, size > _messageSizeMax ? _messageSizeMax : size, _offset, lines); } catch(const Ice::LocalException& ex) { - ostringstream os; - os << ex; - throw FileNotAvailableException(os.str()); + ostringstream os; + os << ex; + throw FileNotAvailableException(os.str()); } return false; // Keep the compiler happy. } @@ -67,8 +67,8 @@ AdminSessionI::~AdminSessionI() Ice::ObjectPrx AdminSessionI::registerWithServantLocator(const SessionServantLocatorIPtr& servantLoc, - const Ice::ConnectionPtr& con, - const RegistryIPtr& registry) + const Ice::ConnectionPtr& con, + const RegistryIPtr& registry) { Ice::ObjectPrx proxy = BaseSessionI::registerWithServantLocator(servantLoc, con); _admin = AdminPrx::uncheckedCast(servantLoc->add(new AdminI(_database, registry, this), con)); @@ -94,18 +94,18 @@ AdminSessionI::getAdmin(const Ice::Current& current) const void AdminSessionI::setObservers(const RegistryObserverPrx& registryObserver, - const NodeObserverPrx& nodeObserver, - const ApplicationObserverPrx& appObserver, - const AdapterObserverPrx& adapterObserver, - const ObjectObserverPrx& objectObserver, - const Ice::Current& current) + const NodeObserverPrx& nodeObserver, + const ApplicationObserverPrx& appObserver, + const AdapterObserverPrx& adapterObserver, + const ObjectObserverPrx& objectObserver, + const Ice::Current& current) { Lock sync(*this); if(_destroyed) { - Ice::ObjectNotExistException ex(__FILE__, __LINE__); - ex.id = current.id; - throw ex; + Ice::ObjectNotExistException ex(__FILE__, __LINE__); + ex.id = current.id; + throw ex; } if(registryObserver) @@ -114,7 +114,7 @@ AdminSessionI::setObservers(const RegistryObserverPrx& registryObserver, } else { - setupObserverSubscription(RegistryObserverTopicName, Ice::ObjectPrx()); + setupObserverSubscription(RegistryObserverTopicName, Ice::ObjectPrx()); } if(nodeObserver) @@ -156,18 +156,18 @@ AdminSessionI::setObservers(const RegistryObserverPrx& registryObserver, void AdminSessionI::setObserversByIdentity(const Ice::Identity& registryObserver, - const Ice::Identity& nodeObserver, - const Ice::Identity& appObserver, - const Ice::Identity& adapterObserver, - const Ice::Identity& objectObserver, - const Ice::Current& current) + const Ice::Identity& nodeObserver, + const Ice::Identity& appObserver, + const Ice::Identity& adapterObserver, + const Ice::Identity& objectObserver, + const Ice::Current& current) { Lock sync(*this); if(_destroyed) { - Ice::ObjectNotExistException ex(__FILE__, __LINE__); - ex.id = current.id; - throw ex; + Ice::ObjectNotExistException ex(__FILE__, __LINE__); + ex.id = current.id; + throw ex; } setupObserverSubscription(RegistryObserverTopicName, toProxy(registryObserver, current.con)); @@ -184,9 +184,9 @@ AdminSessionI::startUpdate(const Ice::Current& current) Lock sync(*this); if(_destroyed) { - Ice::ObjectNotExistException ex(__FILE__, __LINE__); - ex.id = current.id; - throw ex; + Ice::ObjectNotExistException ex(__FILE__, __LINE__); + ex.id = current.id; + throw ex; } int serial = _database->lock(this, _id); @@ -199,9 +199,9 @@ AdminSessionI::finishUpdate(const Ice::Current& current) Lock sync(*this); if(_destroyed) { - Ice::ObjectNotExistException ex(__FILE__, __LINE__); - ex.id = current.id; - throw ex; + Ice::ObjectNotExistException ex(__FILE__, __LINE__); + ex.id = current.id; + throw ex; } _database->unlock(this); @@ -249,11 +249,11 @@ AdminSessionI::openRegistryStdOut(const string& name, int nLines, const Ice::Cur FileReaderPrx reader; if(name == _replicaName) { - reader = _database->getReplicaCache().getInternalRegistry(); + reader = _database->getReplicaCache().getInternalRegistry(); } else { - reader = _database->getReplica(name)->getProxy(); + reader = _database->getReplica(name)->getProxy(); } return addFileIterator(reader, "stdout", nLines, current); } @@ -264,11 +264,11 @@ AdminSessionI::openRegistryStdErr(const string& name, int nLines, const Ice::Cur FileReaderPrx reader; if(name == _replicaName) { - reader = _database->getReplicaCache().getInternalRegistry(); + reader = _database->getReplicaCache().getInternalRegistry(); } else { - reader = _database->getReplica(name)->getProxy(); + reader = _database->getReplica(name)->getProxy(); } return addFileIterator(reader, "stderr", nLines, current); } @@ -284,14 +284,14 @@ AdminSessionI::setupObserverSubscription(TopicName name, const Ice::ObjectPrx& o { if(_observers[name] && _observers[name] != observer) { - _database->getObserverTopic(name)->unsubscribe(_observers[name]); - _observers[name] = 0; + _database->getObserverTopic(name)->unsubscribe(_observers[name]); + _observers[name] = 0; } if(observer) { - _observers[name] = observer; - _database->getObserverTopic(name)->subscribe(_observers[name]); + _observers[name] = observer; + _database->getObserverTopic(name)->subscribe(_observers[name]); } } @@ -303,16 +303,16 @@ AdminSessionI::toProxy(const Ice::Identity& id, const Ice::ConnectionPtr& connec FileIteratorPrx AdminSessionI::addFileIterator(const FileReaderPrx& reader, - const string& filename, - int nLines, - const Ice::Current& current) + const string& filename, + int nLines, + const Ice::Current& current) { Lock sync(*this); if(_destroyed) { - Ice::ObjectNotExistException ex(__FILE__, __LINE__); - ex.id = current.id; - throw ex; + Ice::ObjectNotExistException ex(__FILE__, __LINE__); + ex.id = current.id; + throw ex; } // @@ -338,12 +338,12 @@ AdminSessionI::addFileIterator(const FileReaderPrx& reader, Ice::ObjectPtr servant = new FileIteratorI(this, reader, filename, offset, messageSizeMax); if(_servantLocator) { - obj = _servantLocator->add(servant, current.con); + obj = _servantLocator->add(servant, current.con); } else { - assert(_adapter); - obj = _adapter->addWithUUID(servant); + assert(_adapter); + obj = _adapter->addWithUUID(servant); } _iterators.insert(obj->ice_getIdentity()); return FileIteratorPrx::uncheckedCast(obj); @@ -355,18 +355,18 @@ AdminSessionI::removeFileIterator(const Ice::Identity& id, const Ice::Current& c Lock sync(*this); if(_servantLocator) { - _servantLocator->remove(id); + _servantLocator->remove(id); } else { - try - { - assert(_adapter); - _adapter->remove(id); - } - catch(const Ice::ObjectAdapterDeactivatedException&) - { - } + try + { + assert(_adapter); + _adapter->remove(id); + } + catch(const Ice::ObjectAdapterDeactivatedException&) + { + } } _iterators.erase(id); } @@ -378,7 +378,7 @@ AdminSessionI::destroyImpl(bool shutdown) try { - _database->unlock(this); + _database->unlock(this); } catch(AccessDeniedException&) { @@ -390,58 +390,58 @@ AdminSessionI::destroyImpl(bool shutdown) // if(!shutdown) { - if(_servantLocator) - { - _servantLocator->remove(_admin->ice_getIdentity()); - } - else if(_adapter) - { - try - { - _adapter->remove(_admin->ice_getIdentity()); - } - catch(const Ice::ObjectAdapterDeactivatedException&) - { - } - } - - // - // Unregister the iterators from the session servant locator or - // object adapter. - // - for(set::const_iterator p = _iterators.begin(); p != _iterators.end(); ++p) - { - if(_servantLocator) - { - _servantLocator->remove(*p); - } - else if(_adapter) - { - try - { - _adapter->remove(*p); - } - catch(const Ice::ObjectAdapterDeactivatedException&) - { - } - } - } - - // - // Unsubscribe from the topics. - // - setupObserverSubscription(RegistryObserverTopicName, 0); - setupObserverSubscription(NodeObserverTopicName, 0); - setupObserverSubscription(ApplicationObserverTopicName, 0); - setupObserverSubscription(AdapterObserverTopicName, 0); - setupObserverSubscription(ObjectObserverTopicName, 0); + if(_servantLocator) + { + _servantLocator->remove(_admin->ice_getIdentity()); + } + else if(_adapter) + { + try + { + _adapter->remove(_admin->ice_getIdentity()); + } + catch(const Ice::ObjectAdapterDeactivatedException&) + { + } + } + + // + // Unregister the iterators from the session servant locator or + // object adapter. + // + for(set::const_iterator p = _iterators.begin(); p != _iterators.end(); ++p) + { + if(_servantLocator) + { + _servantLocator->remove(*p); + } + else if(_adapter) + { + try + { + _adapter->remove(*p); + } + catch(const Ice::ObjectAdapterDeactivatedException&) + { + } + } + } + + // + // Unsubscribe from the topics. + // + setupObserverSubscription(RegistryObserverTopicName, 0); + setupObserverSubscription(NodeObserverTopicName, 0); + setupObserverSubscription(ApplicationObserverTopicName, 0); + setupObserverSubscription(AdapterObserverTopicName, 0); + setupObserverSubscription(ObjectObserverTopicName, 0); } } AdminSessionFactory::AdminSessionFactory(const Ice::ObjectAdapterPtr& adapter, - const DatabasePtr& database, - const ReapThreadPtr& reaper, - const RegistryIPtr& registry) : + const DatabasePtr& database, + const ReapThreadPtr& reaper, + const RegistryIPtr& registry) : _adapter(adapter), _database(database), _timeout(registry->getSessionTimeout()), @@ -470,21 +470,21 @@ AdminSessionFactory::createGlacier2Session(const string& sessionId, const Glacie int timeout = 0; if(ctl) { - try - { - ctl->identities()->add(ids); - } - catch(const Ice::LocalException&) - { - session->destroy(Ice::Current()); - return 0; - } - timeout = ctl->getSessionTimeout(); + try + { + ctl->identities()->add(ids); + } + catch(const Ice::LocalException&) + { + session->destroy(Ice::Current()); + return 0; + } + timeout = ctl->getSessionTimeout(); } if(timeout > 0) { - _reaper->add(new SessionReapable(_database->getTraceLevels()->logger, session), timeout); + _reaper->add(new SessionReapable(_database->getTraceLevels()->logger, session), timeout); } return Glacier2::SessionPrx::uncheckedCast(proxy); @@ -518,24 +518,24 @@ AdminSSLSessionManagerI::AdminSSLSessionManagerI(const AdminSessionFactoryPtr& f Glacier2::SessionPrx AdminSSLSessionManagerI::create(const Glacier2::SSLInfo& info, - const Glacier2::SessionControlPrx& ctl, - const Ice::Current& current) + const Glacier2::SessionControlPrx& ctl, + const Ice::Current& current) { string userDN; if(!info.certs.empty()) // TODO: Require userDN? { - try - { - IceSSL::CertificatePtr cert = IceSSL::Certificate::decode(info.certs[0]); - userDN = cert->getSubjectDN(); - } - catch(const Ice::Exception& ex) - { - // This shouldn't happen, the SSLInfo is supposed to be encoded by Glacier2. - Ice::Error out(_factory->getTraceLevels()->logger); - out << "SSL session manager couldn't decode SSL certificates:\n" << ex; - return 0; - } + try + { + IceSSL::CertificatePtr cert = IceSSL::Certificate::decode(info.certs[0]); + userDN = cert->getSubjectDN(); + } + catch(const Ice::Exception& ex) + { + // This shouldn't happen, the SSLInfo is supposed to be encoded by Glacier2. + Ice::Error out(_factory->getTraceLevels()->logger); + out << "SSL session manager couldn't decode SSL certificates:\n" << ex; + return 0; + } } return _factory->createGlacier2Session(userDN, ctl); diff --git a/cpp/src/IceGrid/AdminSessionI.h b/cpp/src/IceGrid/AdminSessionI.h index 0f0ec222c72..7fc506b7cc9 100644 --- a/cpp/src/IceGrid/AdminSessionI.h +++ b/cpp/src/IceGrid/AdminSessionI.h @@ -32,7 +32,7 @@ public: virtual ~AdminSessionI(); virtual Ice::ObjectPrx registerWithServantLocator(const SessionServantLocatorIPtr&, const Ice::ConnectionPtr&, - const RegistryIPtr&); + const RegistryIPtr&); virtual Ice::ObjectPrx registerWithObjectAdapter(const Ice::ObjectAdapterPtr&, const RegistryIPtr&); virtual void keepAlive(const Ice::Current& current) { BaseSessionI::keepAlive(current); } @@ -40,10 +40,10 @@ public: virtual AdminPrx getAdmin(const Ice::Current& = Ice::Current()) const; virtual void setObservers(const RegistryObserverPrx&, const NodeObserverPrx&, const ApplicationObserverPrx&, - const AdapterObserverPrx&, const ObjectObserverPrx&, const Ice::Current&); + const AdapterObserverPrx&, const ObjectObserverPrx&, const Ice::Current&); virtual void setObserversByIdentity(const Ice::Identity&, const Ice::Identity&, const Ice::Identity&, - const Ice::Identity&, const Ice::Identity&, const Ice::Current&); + const Ice::Identity&, const Ice::Identity&, const Ice::Current&); virtual int startUpdate(const Ice::Current&); virtual void finishUpdate(const Ice::Current&); @@ -121,7 +121,7 @@ public: AdminSSLSessionManagerI(const AdminSessionFactoryPtr&); virtual Glacier2::SessionPrx create(const Glacier2::SSLInfo&, const Glacier2::SessionControlPrx&, - const Ice::Current&); + const Ice::Current&); private: diff --git a/cpp/src/IceGrid/Allocatable.cpp b/cpp/src/IceGrid/Allocatable.cpp index 428bed9d086..5d05acda6b8 100644 --- a/cpp/src/IceGrid/Allocatable.cpp +++ b/cpp/src/IceGrid/Allocatable.cpp @@ -25,20 +25,20 @@ AllocationRequest::pending() if(_timeout == 0) { - _state = Canceled; - canceled(AllocationTimeoutException()); - return false; + _state = Canceled; + canceled(AllocationTimeoutException()); + return false; } else if(!_session->addAllocationRequest(this)) { - _state = Canceled; - canceled(AllocationException("session destroyed")); - return false; + _state = Canceled; + canceled(AllocationException("session destroyed")); + return false; } if(_timeout > 0) { - _session->getWaitQueue()->add(this, IceUtil::Time::milliSeconds(_timeout)); + _session->getWaitQueue()->add(this, IceUtil::Time::milliSeconds(_timeout)); } _state = Pending; return true; @@ -51,19 +51,19 @@ AllocationRequest::allocate(const AllocatablePtr& allocatable, const SessionIPtr switch(_state) { case Initial: - break; + break; case Canceled: - return false; + return false; case Pending: - if(_timeout > 0) - { - _session->getWaitQueue()->remove(this); - } - _session->removeAllocationRequest(this); - break; + if(_timeout > 0) + { + _session->getWaitQueue()->remove(this); + } + _session->removeAllocationRequest(this); + break; case Allocated: - assert(false); - break; + assert(false); + break; } // @@ -71,14 +71,14 @@ AllocationRequest::allocate(const AllocatablePtr& allocatable, const SessionIPtr // if(_session == session) { - _state = Canceled; - canceled(AllocationException("already allocated by the session")); - return false; + _state = Canceled; + canceled(AllocationException("already allocated by the session")); + return false; } else { - _state = Allocated; - return true; + _state = Allocated; + return true; } } @@ -89,17 +89,17 @@ AllocationRequest::cancel(const AllocationException& ex) switch(_state) { case Initial: - break; + break; case Canceled: case Allocated: - return; + return; case Pending: - if(_timeout > 0) - { - _session->getWaitQueue()->remove(this); - } - _session->removeAllocationRequest(this); - break; + if(_timeout > 0) + { + _session->getWaitQueue()->remove(this); + } + _session->removeAllocationRequest(this); + break; } _state = Canceled; @@ -113,13 +113,13 @@ AllocationRequest::expired(bool destroyed) switch(_state) { case Initial: - assert(false); + assert(false); case Canceled: case Allocated: - return; + return; case Pending: - _session->removeAllocationRequest(this); - break; + _session->removeAllocationRequest(this); + break; } _state = Canceled; @@ -175,7 +175,7 @@ Allocatable::checkAllocatable() { if(!isAllocatable()) { - throw AllocationException("not allocatable"); + throw AllocationException("not allocatable"); } } @@ -184,11 +184,11 @@ Allocatable::allocate(const AllocationRequestPtr& request, bool fromRelease) { try { - return allocate(request, false, fromRelease); + return allocate(request, false, fromRelease); } catch(const SessionDestroyedException&) { - return false; // The session was destroyed + return false; // The session was destroyed } } @@ -197,11 +197,11 @@ Allocatable::tryAllocate(const AllocationRequestPtr& request, bool fromRelease) { try { - return allocate(request, true, fromRelease); + return allocate(request, true, fromRelease); } catch(const AllocationException&) { - return false; // Not allocatable + return false; // Not allocatable } } @@ -211,117 +211,117 @@ Allocatable::release(const SessionIPtr& session, bool fromRelease) bool isReleased = false; bool hasRequests = false; { - Lock sync(*this); - if(!fromRelease) - { - while(_releasing) - { - wait(); - } - assert(!_releasing); - } - - if(!_session || _session != session) - { - throw AllocationException("can't release object which is not allocated"); - } - - if(--_count == 0) - { - _session = 0; - - released(session); - - isReleased = true; - - if(!fromRelease && !_requests.empty()) - { - assert(!_parent); - _releasing = true; // Prevent new allocations. - hasRequests = true; - } - } + Lock sync(*this); + if(!fromRelease) + { + while(_releasing) + { + wait(); + } + assert(!_releasing); + } + + if(!_session || _session != session) + { + throw AllocationException("can't release object which is not allocated"); + } + + if(--_count == 0) + { + _session = 0; + + released(session); + + isReleased = true; + + if(!fromRelease && !_requests.empty()) + { + assert(!_parent); + _releasing = true; // Prevent new allocations. + hasRequests = true; + } + } } if(isReleased) { - releasedNoSync(session); + releasedNoSync(session); } if(_parent) { - _parent->release(session, fromRelease); + _parent->release(session, fromRelease); } else if(!fromRelease) { - if(hasRequests) - { - while(true) - { - AllocationRequestPtr request; - AllocatablePtr allocatable; - { - Lock sync(*this); - allocatable = dequeueAllocationAttempt(request); - if(!allocatable) - { - assert(_count == 0 && _requests.empty()); - _releasing = false; - notifyAll(); - return; - } - } - - // - // Try to allocate the allocatable with the request or if - // there's no request, just notify the allocatable that it can - // be allocated again. - // - if(request && allocatable->allocate(request, true) || !request && allocatable->canTryAllocate()) - { - while(true) - { - { - Lock sync(*this); - assert(_count); - - allocatable = 0; - request = 0; - - // - // Check if there's other requests from the session - // waiting to allocate this allocatable. - // - list >::iterator p = _requests.begin(); - while(p != _requests.end()) - { - if(p->second && p->second->getSession() == _session) - { - allocatable = p->first; - request = p->second; - _requests.erase(p); - break; - } - ++p; - } - if(!allocatable) - { - _releasing = false; - notifyAll(); - return; // We're done, the allocatable was released (but is allocated again)! - } - } - - assert(allocatable && request); - allocatable->allocate(request, true); - } - } - } - } - else if(isReleased) - { - canTryAllocate(); // Notify that this allocatable can be allocated. - } + if(hasRequests) + { + while(true) + { + AllocationRequestPtr request; + AllocatablePtr allocatable; + { + Lock sync(*this); + allocatable = dequeueAllocationAttempt(request); + if(!allocatable) + { + assert(_count == 0 && _requests.empty()); + _releasing = false; + notifyAll(); + return; + } + } + + // + // Try to allocate the allocatable with the request or if + // there's no request, just notify the allocatable that it can + // be allocated again. + // + if(request && allocatable->allocate(request, true) || !request && allocatable->canTryAllocate()) + { + while(true) + { + { + Lock sync(*this); + assert(_count); + + allocatable = 0; + request = 0; + + // + // Check if there's other requests from the session + // waiting to allocate this allocatable. + // + list >::iterator p = _requests.begin(); + while(p != _requests.end()) + { + if(p->second && p->second->getSession() == _session) + { + allocatable = p->first; + request = p->second; + _requests.erase(p); + break; + } + ++p; + } + if(!allocatable) + { + _releasing = false; + notifyAll(); + return; // We're done, the allocatable was released (but is allocated again)! + } + } + + assert(allocatable && request); + allocatable->allocate(request, true); + } + } + } + } + else if(isReleased) + { + canTryAllocate(); // Notify that this allocatable can be allocated. + } } } @@ -340,20 +340,20 @@ Allocatable::operator<(const Allocatable& r) const void Allocatable::queueAllocationAttempt(const AllocatablePtr& allocatable, - const AllocationRequestPtr& request, - bool tryAllocate) + const AllocationRequestPtr& request, + bool tryAllocate) { assert(!_parent); if(!tryAllocate) { - if(request->pending()) - { - _requests.push_back(make_pair(allocatable, request)); - } + if(request->pending()) + { + _requests.push_back(make_pair(allocatable, request)); + } } else { - _requests.push_back(make_pair(allocatable, AllocationRequestPtr())); + _requests.push_back(make_pair(allocatable, AllocationRequestPtr())); } } @@ -362,8 +362,8 @@ Allocatable::queueAllocationAttemptFromChild(const AllocatablePtr& allocatable) { if(_parent) { - _parent->queueAllocationAttemptFromChild(allocatable); - return; + _parent->queueAllocationAttemptFromChild(allocatable); + return; } Lock sync(*this); @@ -375,14 +375,14 @@ Allocatable::dequeueAllocationAttempt(AllocationRequestPtr& request) { if(_requests.empty()) { - return 0; + return 0; } pair alloc = _requests.front(); _requests.pop_front(); if(alloc.second) { - request = alloc.second; + request = alloc.second; } return alloc.first; } @@ -392,130 +392,130 @@ Allocatable::allocate(const AllocationRequestPtr& request, bool tryAllocate, boo { if(_parent && !_parent->allocateFromChild(request, this, tryAllocate, fromRelease)) { - return false; + return false; } bool queueWithParent = false; int allocationCount = 0; try { - Lock sync(*this); - checkAllocatable(); - - if(!_session && (fromRelease || !_releasing)) - { - if(request->allocate(this, _session)) - { - try - { - allocated(request->getSession()); // This might throw SessionDestroyedException - } - catch(const SessionDestroyedException&) - { - request->canceled(AllocationException("session destroyed")); - throw; - } - assert(_count == 0); - _session = request->getSession(); - request->allocated(this, request->getSession()); - ++_count; - allocationCount = _count; - } - } - else if(_session == request->getSession()) - { - if(!tryAllocate) - { - if(request->allocate(this, _session)) - { - assert(_count > 0); - ++_count; - request->allocated(this, _session); - allocationCount = _count; - } - } - else - { - queueWithParent = true; - } - } - else - { - queueAllocationAttempt(this, request, tryAllocate); - } + Lock sync(*this); + checkAllocatable(); + + if(!_session && (fromRelease || !_releasing)) + { + if(request->allocate(this, _session)) + { + try + { + allocated(request->getSession()); // This might throw SessionDestroyedException + } + catch(const SessionDestroyedException&) + { + request->canceled(AllocationException("session destroyed")); + throw; + } + assert(_count == 0); + _session = request->getSession(); + request->allocated(this, request->getSession()); + ++_count; + allocationCount = _count; + } + } + else if(_session == request->getSession()) + { + if(!tryAllocate) + { + if(request->allocate(this, _session)) + { + assert(_count > 0); + ++_count; + request->allocated(this, _session); + allocationCount = _count; + } + } + else + { + queueWithParent = true; + } + } + else + { + queueAllocationAttempt(this, request, tryAllocate); + } } catch(const SessionDestroyedException& ex) { - if(_parent) - { - _parent->release(request->getSession(), fromRelease); - } - throw ex; + if(_parent) + { + _parent->release(request->getSession(), fromRelease); + } + throw ex; } catch(const AllocationException& ex) { - if(_parent) - { - _parent->release(request->getSession(), fromRelease); - } - throw ex; + if(_parent) + { + _parent->release(request->getSession(), fromRelease); + } + throw ex; } if(allocationCount == 1) { - allocatedNoSync(request->getSession()); + allocatedNoSync(request->getSession()); } else if(allocationCount == 0 && _parent) { - if(queueWithParent) - { - _parent->queueAllocationAttemptFromChild(this); - } - _parent->release(request->getSession(), fromRelease); + if(queueWithParent) + { + _parent->queueAllocationAttemptFromChild(this); + } + _parent->release(request->getSession(), fromRelease); } return allocationCount > 0; } bool Allocatable::allocateFromChild(const AllocationRequestPtr& request, - const AllocatablePtr& child, - bool tryAllocate, - bool fromRelease) + const AllocatablePtr& child, + bool tryAllocate, + bool fromRelease) { if(_parent && !_parent->allocateFromChild(request, child, tryAllocate, fromRelease)) { - return false; + return false; } int allocationCount = 0; { - Lock sync(*this); - if((!_session || _session == request->getSession()) && (fromRelease || !_releasing)) - { - if(!_session) - { - try - { - allocated(request->getSession()); - } - catch(const SessionDestroyedException&) - { - // Ignore - } - } - _session = request->getSession(); - ++_count; - allocationCount = _count; - } - else - { - queueAllocationAttempt(child, request, tryAllocate); - } + Lock sync(*this); + if((!_session || _session == request->getSession()) && (fromRelease || !_releasing)) + { + if(!_session) + { + try + { + allocated(request->getSession()); + } + catch(const SessionDestroyedException&) + { + // Ignore + } + } + _session = request->getSession(); + ++_count; + allocationCount = _count; + } + else + { + queueAllocationAttempt(child, request, tryAllocate); + } } if(allocationCount == 1) { - allocatedNoSync(request->getSession()); + allocatedNoSync(request->getSession()); } return allocationCount > 0; } diff --git a/cpp/src/IceGrid/Allocatable.h b/cpp/src/IceGrid/Allocatable.h index 325cfeb6bd7..11543ffc426 100644 --- a/cpp/src/IceGrid/Allocatable.h +++ b/cpp/src/IceGrid/Allocatable.h @@ -58,10 +58,10 @@ private: enum State { - Initial, - Pending, - Canceled, - Allocated + Initial, + Pending, + Canceled, + Allocated }; const SessionIPtr _session; diff --git a/cpp/src/IceGrid/AllocatableObjectCache.cpp b/cpp/src/IceGrid/AllocatableObjectCache.cpp index 97484f85949..7df3a45afc3 100644 --- a/cpp/src/IceGrid/AllocatableObjectCache.cpp +++ b/cpp/src/IceGrid/AllocatableObjectCache.cpp @@ -26,7 +26,7 @@ struct AllocatableObjectEntryCI : binary_functiongetProxy(), rhs->getProxy()); + return ::Ice::proxyIdentityLess(lhs->getProxy(), rhs->getProxy()); } }; @@ -45,7 +45,7 @@ AllocatableObjectCache::TypeEntry::add(const AllocatableObjectEntryPtr& obj) _objects.insert(lower_bound(_objects.begin(), _objects.end(), obj, AllocatableObjectEntryCI()), obj); if(!_requests.empty()) { - canTryAllocate(obj, false); + canTryAllocate(obj, false); } } @@ -62,10 +62,10 @@ AllocatableObjectCache::TypeEntry::remove(const AllocatableObjectEntryPtr& obj) if(!_requests.empty() && _objects.empty()) { - for(list::const_iterator p = _requests.begin(); p != _requests.end(); ++p) - { - (*p)->cancel(AllocationException("no allocatable objects with type `" + obj->getType() + "' registered")); - } + for(list::const_iterator p = _requests.begin(); p != _requests.end(); ++p) + { + (*p)->cancel(AllocationException("no allocatable objects with type `" + obj->getType() + "' registered")); + } } return _objects.empty(); } @@ -78,7 +78,7 @@ AllocatableObjectCache::TypeEntry::addAllocationRequest(const ObjectAllocationRe // if(request->pending()) { - _requests.push_back(request); + _requests.push_back(request); } } @@ -91,31 +91,31 @@ AllocatableObjectCache::TypeEntry::canTryAllocate(const AllocatableObjectEntryPt list::iterator p = _requests.begin(); while(p != _requests.end()) { - AllocationRequestPtr request = *p; - try - { - if(request->isCanceled()) // If the request has been canceled, we just remove it. - { - p = _requests.erase(p); - } - else if(entry->tryAllocate(request, fromRelease)) - { - p = _requests.erase(p); - return true; // The request successfully allocated the entry! - } - else if(entry->getSession()) // If entry is allocated, we're done - { - return false; - } - else - { - ++p; - } - } - catch(const SessionDestroyedException&) - { - p = _requests.erase(p); - } + AllocationRequestPtr request = *p; + try + { + if(request->isCanceled()) // If the request has been canceled, we just remove it. + { + p = _requests.erase(p); + } + else if(entry->tryAllocate(request, fromRelease)) + { + p = _requests.erase(p); + return true; // The request successfully allocated the entry! + } + else if(entry->getSession()) // If entry is allocated, we're done + { + return false; + } + else + { + ++p; + } + } + catch(const SessionDestroyedException&) + { + p = _requests.erase(p); + } } return false; } @@ -139,14 +139,14 @@ AllocatableObjectCache::add(const ObjectInfo& info, const AllocatablePtr& parent map::iterator p = _types.find(entry->getType()); if(p == _types.end()) { - p = _types.insert(p, map::value_type(entry->getType(), TypeEntry())); + p = _types.insert(p, map::value_type(entry->getType(), TypeEntry())); } p->second.add(entry); if(_traceLevels && _traceLevels->object > 0) { - Ice::Trace out(_traceLevels->logger, _traceLevels->objectCat); - out << "added allocatable object `" << _communicator->identityToString(id) << "'"; + Ice::Trace out(_traceLevels->logger, _traceLevels->objectCat); + out << "added allocatable object `" << _communicator->identityToString(id) << "'"; } } @@ -157,7 +157,7 @@ AllocatableObjectCache::get(const Ice::Identity& id) const AllocatableObjectEntryPtr entry = getImpl(id); if(!entry) { - throw ObjectNotRegisteredException(id); + throw ObjectNotRegisteredException(id); } return entry; } @@ -167,23 +167,23 @@ AllocatableObjectCache::remove(const Ice::Identity& id) { AllocatableObjectEntryPtr entry; { - Lock sync(*this); - entry = getImpl(id); - assert(entry); - removeImpl(id); - - map::iterator p = _types.find(entry->getType()); - assert(p != _types.end()); - if(p->second.remove(entry)) - { - _types.erase(p); - } - - if(_traceLevels && _traceLevels->object > 0) - { - Ice::Trace out(_traceLevels->logger, _traceLevels->objectCat); - out << "removed allocatable object `" << _communicator->identityToString(id) << "'"; - } + Lock sync(*this); + entry = getImpl(id); + assert(entry); + removeImpl(id); + + map::iterator p = _types.find(entry->getType()); + assert(p != _types.end()); + if(p->second.remove(entry)) + { + _types.erase(p); + } + + if(_traceLevels && _traceLevels->object > 0) + { + Ice::Trace out(_traceLevels->logger, _traceLevels->objectCat); + out << "removed allocatable object `" << _communicator->identityToString(id) << "'"; + } } // @@ -202,7 +202,7 @@ AllocatableObjectCache::allocateByType(const string& type, const ObjectAllocatio map::iterator p = _types.find(type); if(p == _types.end()) { - throw AllocationException("no allocatable objects with type `" + type + "' registered"); + throw AllocationException("no allocatable objects with type `" + type + "' registered"); } vector objects = p->second.getObjects(); @@ -210,17 +210,17 @@ AllocatableObjectCache::allocateByType(const string& type, const ObjectAllocatio random_shuffle(objects.begin(), objects.end(), rng); // TODO: OPTIMIZE try { - for(vector::const_iterator q = objects.begin(); q != objects.end(); ++q) - { - if((*q)->tryAllocate(request)) - { - return; - } - } + for(vector::const_iterator q = objects.begin(); q != objects.end(); ++q) + { + if((*q)->tryAllocate(request)) + { + return; + } + } } catch(const SessionDestroyedException&) { - return; // The request has been answered already, no need to throw here. + return; // The request has been answered already, no need to throw here. } p->second.addAllocationRequest(request); @@ -236,14 +236,14 @@ AllocatableObjectCache::canTryAllocate(const AllocatableObjectEntryPtr& entry) map::iterator p = _types.find(entry->getType()); if(p == _types.end()) { - return false; + return false; } return p->second.canTryAllocate(entry, true); } AllocatableObjectEntry::AllocatableObjectEntry(AllocatableObjectCache& cache, - const ObjectInfo& info, - const AllocatablePtr& parent) : + const ObjectInfo& info, + const AllocatablePtr& parent) : Allocatable(true, parent), _cache(cache), _info(info), @@ -281,29 +281,29 @@ AllocatableObjectEntry::allocated(const SessionIPtr& session) TraceLevelsPtr traceLevels = _cache.getTraceLevels(); if(traceLevels && traceLevels->object > 1) { - Ice::Trace out(traceLevels->logger, traceLevels->objectCat); - out << "object `" << _info.proxy->ice_toString() << "' allocated by `" << session->getId() << "' (" << _count - << ")"; + Ice::Trace out(traceLevels->logger, traceLevels->objectCat); + out << "object `" << _info.proxy->ice_toString() << "' allocated by `" << session->getId() << "' (" << _count + << ")"; } Glacier2::SessionControlPrx ctl = session->getSessionControl(); if(ctl) { - try - { - Ice::IdentitySeq seq(1); - seq.push_back(_info.proxy->ice_getIdentity()); - ctl->identities()->add(seq); - } - catch(const Ice::LocalException& ex) - { - if(traceLevels && traceLevels->object > 0) - { - Ice::Trace out(traceLevels->logger, traceLevels->objectCat); - out << "couldn't add Glacier2 filter for object `" << _info.proxy->ice_toString(); - out << "' allocated by `" << session->getId() << "':\n" << ex; - } - } + try + { + Ice::IdentitySeq seq(1); + seq.push_back(_info.proxy->ice_getIdentity()); + ctl->identities()->add(seq); + } + catch(const Ice::LocalException& ex) + { + if(traceLevels && traceLevels->object > 0) + { + Ice::Trace out(traceLevels->logger, traceLevels->objectCat); + out << "couldn't add Glacier2 filter for object `" << _info.proxy->ice_toString(); + out << "' allocated by `" << session->getId() << "':\n" << ex; + } + } } } @@ -320,28 +320,28 @@ AllocatableObjectEntry::released(const SessionIPtr& session) Glacier2::SessionControlPrx ctl = session->getSessionControl(); if(ctl) { - try - { - Ice::IdentitySeq seq(1); - seq.push_back(_info.proxy->ice_getIdentity()); - ctl->identities()->remove(seq); - } - catch(const Ice::LocalException& ex) - { - if(traceLevels && traceLevels->object > 0) - { - Ice::Trace out(traceLevels->logger, traceLevels->objectCat); - out << "couldn't remove Glacier2 filter for object `" << _info.proxy->ice_toString(); - out << "' allocated by `" << session->getId() << "':\n" << ex; - } - } + try + { + Ice::IdentitySeq seq(1); + seq.push_back(_info.proxy->ice_getIdentity()); + ctl->identities()->remove(seq); + } + catch(const Ice::LocalException& ex) + { + if(traceLevels && traceLevels->object > 0) + { + Ice::Trace out(traceLevels->logger, traceLevels->objectCat); + out << "couldn't remove Glacier2 filter for object `" << _info.proxy->ice_toString(); + out << "' allocated by `" << session->getId() << "':\n" << ex; + } + } } if(traceLevels && traceLevels->object > 1) { - Ice::Trace out(traceLevels->logger, traceLevels->objectCat); - out << "object `" << _info.proxy->ice_toString() << "' released by `" << session->getId() << "' (" << _count - << ")"; + Ice::Trace out(traceLevels->logger, traceLevels->objectCat); + out << "object `" << _info.proxy->ice_toString() << "' released by `" << session->getId() << "' (" << _count + << ")"; } } @@ -350,19 +350,19 @@ AllocatableObjectEntry::destroy() { SessionIPtr session; { - Lock sync(*this); - _destroyed = true; - session = _session; + Lock sync(*this); + _destroyed = true; + session = _session; } if(session) { - try - { - release(session); - } - catch(const AllocationException&) - { - } + try + { + release(session); + } + catch(const AllocationException&) + { + } } } @@ -371,7 +371,7 @@ AllocatableObjectEntry::checkAllocatable() { if(_destroyed) { - throw ObjectNotRegisteredException(_info.proxy->ice_getIdentity()); + throw ObjectNotRegisteredException(_info.proxy->ice_getIdentity()); } Allocatable::checkAllocatable(); diff --git a/cpp/src/IceGrid/AllocatableObjectCache.h b/cpp/src/IceGrid/AllocatableObjectCache.h index a46279e04e1..8c794a1f91f 100644 --- a/cpp/src/IceGrid/AllocatableObjectCache.h +++ b/cpp/src/IceGrid/AllocatableObjectCache.h @@ -59,12 +59,12 @@ private: virtual void allocated(const AllocatablePtr& allocatable, const SessionIPtr& session) { - response(AllocatableObjectEntryPtr::dynamicCast(allocatable)->getProxy()); + response(AllocatableObjectEntryPtr::dynamicCast(allocatable)->getProxy()); } virtual void canceled(const AllocationException& ex) { - exception(ex); + exception(ex); } }; typedef IceUtil::Handle ObjectAllocationRequestPtr; @@ -92,20 +92,20 @@ private: { public: - TypeEntry(); + TypeEntry(); - void add(const AllocatableObjectEntryPtr&); - bool remove(const AllocatableObjectEntryPtr&); - - void addAllocationRequest(const ObjectAllocationRequestPtr&); - bool canTryAllocate(const AllocatableObjectEntryPtr&, bool); + void add(const AllocatableObjectEntryPtr&); + bool remove(const AllocatableObjectEntryPtr&); + + void addAllocationRequest(const ObjectAllocationRequestPtr&); + bool canTryAllocate(const AllocatableObjectEntryPtr&, bool); - const std::vector& getObjects() const { return _objects; } + const std::vector& getObjects() const { return _objects; } private: - - std::vector _objects; - std::list _requests; + + std::vector _objects; + std::list _requests; }; const Ice::CommunicatorPtr _communicator; diff --git a/cpp/src/IceGrid/Cache.h b/cpp/src/IceGrid/Cache.h index 284ba6953d0..295aa4a55b4 100644 --- a/cpp/src/IceGrid/Cache.h +++ b/cpp/src/IceGrid/Cache.h @@ -38,21 +38,21 @@ public: bool has(const Key& key) const { - Lock sync(*this); - return getImpl(key); + Lock sync(*this); + return getImpl(key); } void remove(const Key& key) { - Lock sync(*this); - removeImpl(key); + Lock sync(*this); + removeImpl(key); } void setTraceLevels(const TraceLevelsPtr& traceLevels) { - _traceLevels = traceLevels; + _traceLevels = traceLevels; } const TraceLevelsPtr& getTraceLevels() const { return _traceLevels; } @@ -62,66 +62,66 @@ protected: virtual ValuePtr getImpl(const Key& key) const { - typename ValueMap::iterator p = const_cast(_entries).end(); - if(_entriesHint != p) - { - if(_entriesHint->first == key) - { - p = _entriesHint; - } - } - - if(p == const_cast(_entries).end()) - { - p = const_cast(_entries).find(key); - } - - if(p != const_cast(_entries).end()) - { - const_cast(_entriesHint) = p; - return p->second; - } - else - { - return 0; - } + typename ValueMap::iterator p = const_cast(_entries).end(); + if(_entriesHint != p) + { + if(_entriesHint->first == key) + { + p = _entriesHint; + } + } + + if(p == const_cast(_entries).end()) + { + p = const_cast(_entries).find(key); + } + + if(p != const_cast(_entries).end()) + { + const_cast(_entriesHint) = p; + return p->second; + } + else + { + return 0; + } } virtual ValuePtr addImpl(const Key& key, const ValuePtr& entry) { - typename ValueMap::value_type v(key, entry); - _entriesHint = _entries.insert(_entriesHint, v); - return entry; + typename ValueMap::value_type v(key, entry); + _entriesHint = _entries.insert(_entriesHint, v); + return entry; } virtual void removeImpl(const Key& key) { - typename ValueMap::iterator p = _entries.end(); - if(_entriesHint != _entries.end()) - { - if(_entriesHint->first == key) - { - p = _entriesHint; - } - } - - if(p == _entries.end()) - { - p = _entries.find(key); - } - - assert(p != _entries.end()); - if(p->second->canRemove()) - { - _entries.erase(p); - _entriesHint = _entries.end(); - } - else - { - _entriesHint = p; - } + typename ValueMap::iterator p = _entries.end(); + if(_entriesHint != _entries.end()) + { + if(_entriesHint->first == key) + { + p = _entriesHint; + } + } + + if(p == _entries.end()) + { + p = _entries.find(key); + } + + assert(p != _entries.end()); + if(p->second->canRemove()) + { + _entries.erase(p); + _entriesHint = _entries.end(); + } + else + { + _entriesHint = p; + } } TraceLevelsPtr _traceLevels; @@ -139,8 +139,8 @@ public: virtual std::vector getAll(const std::string& expr) { - IceUtil::Monitor::Lock sync(*this); - return getMatchingKeys >(Cache::_entries, expr); + IceUtil::Monitor::Lock sync(*this); + return getMatchingKeys >(Cache::_entries, expr); } }; diff --git a/cpp/src/IceGrid/Client.cpp b/cpp/src/IceGrid/Client.cpp index 965fc931a3b..08f1b384dd1 100644 --- a/cpp/src/IceGrid/Client.cpp +++ b/cpp/src/IceGrid/Client.cpp @@ -33,7 +33,7 @@ class SessionKeepAliveThread : public IceUtil::Thread, public IceUtil::MonitorkeepAlive(); } catch(const Ice::Exception&) { - break; + break; } } } @@ -103,7 +103,7 @@ static void interruptCallback(int signal) IceUtil::StaticMutex::Lock lock(_staticMutex); if(_globalClient) { - _globalClient->interrupted(); + _globalClient->interrupted(); } } @@ -118,23 +118,23 @@ void Client::usage() { cerr << "Usage: " << appName() << " [options] [file...]\n"; - cerr << - "Options:\n" - "-h, --help Show this message.\n" - "-v, --version Display the Ice version.\n" - "-DNAME Define NAME as 1.\n" - "-DNAME=DEF Define NAME as DEF.\n" - "-UNAME Remove any definition for NAME.\n" - "-IDIR Put DIR in the include file search path.\n" - "-e COMMANDS Execute COMMANDS.\n" - "-d, --debug Print debug messages.\n" + cerr << + "Options:\n" + "-h, --help Show this message.\n" + "-v, --version Display the Ice version.\n" + "-DNAME Define NAME as 1.\n" + "-DNAME=DEF Define NAME as DEF.\n" + "-UNAME Remove any definition for NAME.\n" + "-IDIR Put DIR in the include file search path.\n" + "-e COMMANDS Execute COMMANDS.\n" + "-d, --debug Print debug messages.\n" "-s, --server Start icegridadmin as a server (to parse XML files).\n" "-u, --username Login with the given username.\n" "-p, --password Login with the given password.\n" "-s, --ssl Authenticate through SSL.\n" "-r, --routed Login through a Glacier2 router.\n" "-R, --replica NAME Connect to the replica NAME.\n" - ; + ; } int @@ -144,74 +144,74 @@ Client::main(int argc, char* argv[]) try { - _appName = argv[0]; - _communicator = Ice::initialize(argc, argv); - - { - IceUtil::StaticMutex::Lock sync(_staticMutex); - _globalClient = this; - } - _ctrlCHandler.setCallback(interruptCallback); - - try - { - run(argc, argv); - } - catch(const Ice::CommunicatorDestroyedException&) - { - // Expected if the client is interrupted during the initialization. - } + _appName = argv[0]; + _communicator = Ice::initialize(argc, argv); + + { + IceUtil::StaticMutex::Lock sync(_staticMutex); + _globalClient = this; + } + _ctrlCHandler.setCallback(interruptCallback); + + try + { + run(argc, argv); + } + catch(const Ice::CommunicatorDestroyedException&) + { + // Expected if the client is interrupted during the initialization. + } } catch(const IceUtil::Exception& ex) { - cerr << _appName << ": " << ex << endl; - status = EXIT_FAILURE; + cerr << _appName << ": " << ex << endl; + status = EXIT_FAILURE; } catch(const std::exception& ex) { - cerr << _appName << ": std::exception: " << ex.what() << endl; - status = EXIT_FAILURE; + cerr << _appName << ": std::exception: " << ex.what() << endl; + status = EXIT_FAILURE; } catch(const std::string& msg) { - cerr << _appName << ": " << msg << endl; - status = EXIT_FAILURE; + cerr << _appName << ": " << msg << endl; + status = EXIT_FAILURE; } catch(const char* msg) { - cerr << _appName << ": " << msg << endl; - status = EXIT_FAILURE; + cerr << _appName << ": " << msg << endl; + status = EXIT_FAILURE; } catch(...) { - cerr << _appName << ": unknown exception" << endl; - status = EXIT_FAILURE; + cerr << _appName << ": unknown exception" << endl; + status = EXIT_FAILURE; } if(_communicator) { - try - { - _communicator->destroy(); - } - catch(const Ice::CommunicatorDestroyedException&) - { - } - catch(const Ice::Exception& ex) - { - cerr << ex << endl; - status = EXIT_FAILURE; - } + try + { + _communicator->destroy(); + } + catch(const Ice::CommunicatorDestroyedException&) + { + } + catch(const Ice::Exception& ex) + { + cerr << ex << endl; + status = EXIT_FAILURE; + } } _ctrlCHandler.setCallback(0); { - IceUtil::StaticMutex::Lock sync(_staticMutex); - _globalClient = 0; + IceUtil::StaticMutex::Lock sync(_staticMutex); + _globalClient = 0; } return status; - + } void @@ -220,21 +220,21 @@ Client::interrupted() Lock sync(*this); if(_parser) // If there's an interactive parser, notify the parser. { - _parser->interrupt(); + _parser->interrupt(); } else { - // - // Otherwise, destroy the communicator. - // - assert(_communicator); - try - { - _communicator->destroy(); - } - catch(const Ice::Exception&) - { - } + // + // Otherwise, destroy the communicator. + // + assert(_communicator); + try + { + _communicator->destroy(); + } + catch(const Ice::Exception&) + { + } } } @@ -263,103 +263,103 @@ Client::run(int argc, char* argv[]) vector args; try { - args = opts.parse(argc, (const char**)argv); + args = opts.parse(argc, (const char**)argv); } catch(const IceUtil::BadOptException& e) { cerr << e.reason << endl; - usage(); - return EXIT_FAILURE; + usage(); + return EXIT_FAILURE; } if(opts.isSet("help")) { - usage(); - return EXIT_SUCCESS; + usage(); + return EXIT_SUCCESS; } if(opts.isSet("version")) { - cout << ICE_STRING_VERSION << endl; - return EXIT_SUCCESS; + cout << ICE_STRING_VERSION << endl; + return EXIT_SUCCESS; } if(opts.isSet("server")) { - ObjectAdapterPtr adapter = communicator()->createObjectAdapterWithEndpoints("FileParser", "tcp -h localhost"); - adapter->activate(); - ObjectPrx proxy = adapter->add(new FileParserI, communicator()->stringToIdentity("FileParser")); - cout << proxy << endl; + ObjectAdapterPtr adapter = communicator()->createObjectAdapterWithEndpoints("FileParser", "tcp -h localhost"); + adapter->activate(); + ObjectPrx proxy = adapter->add(new FileParserI, communicator()->stringToIdentity("FileParser")); + cout << proxy << endl; - communicator()->waitForShutdown(); - return EXIT_SUCCESS; + communicator()->waitForShutdown(); + return EXIT_SUCCESS; } if(opts.isSet("D")) { - vector optargs = opts.argVec("D"); - for(vector::const_iterator i = optargs.begin(); i != optargs.end(); ++i) - { - cpp += " -D" + *i; - } + vector optargs = opts.argVec("D"); + for(vector::const_iterator i = optargs.begin(); i != optargs.end(); ++i) + { + cpp += " -D" + *i; + } } if(opts.isSet("U")) { - vector optargs = opts.argVec("U"); - for(vector::const_iterator i = optargs.begin(); i != optargs.end(); ++i) - { - cpp += " -U" + *i; - } + vector optargs = opts.argVec("U"); + for(vector::const_iterator i = optargs.begin(); i != optargs.end(); ++i) + { + cpp += " -U" + *i; + } } if(opts.isSet("I")) { - vector optargs = opts.argVec("I"); - for(vector::const_iterator i = optargs.begin(); i != optargs.end(); ++i) - { - cpp += " -I" + *i; - } + vector optargs = opts.argVec("I"); + for(vector::const_iterator i = optargs.begin(); i != optargs.end(); ++i) + { + cpp += " -I" + *i; + } } if(opts.isSet("e")) { - vector optargs = opts.argVec("e"); - for(vector::const_iterator i = optargs.begin(); i != optargs.end(); ++i) - { - commands += *i + ";"; - } + vector optargs = opts.argVec("e"); + for(vector::const_iterator i = optargs.begin(); i != optargs.end(); ++i) + { + commands += *i + ";"; + } } debug = opts.isSet("debug"); if(!args.empty() && !commands.empty()) { - cerr << appName() << ": `-e' option cannot be used if input files are given" << endl; - usage(); - return EXIT_FAILURE; + cerr << appName() << ": `-e' option cannot be used if input files are given" << endl; + usage(); + return EXIT_FAILURE; } string instanceName; if(communicator()->getDefaultLocator()) { - instanceName = communicator()->getDefaultLocator()->ice_getIdentity().category; + instanceName = communicator()->getDefaultLocator()->ice_getIdentity().category; } else { - instanceName = communicator()->getProperties()->getPropertyWithDefault("IceGrid.InstanceName", "IceGrid"); + instanceName = communicator()->getProperties()->getPropertyWithDefault("IceGrid.InstanceName", "IceGrid"); } bool ssl = communicator()->getProperties()->getPropertyAsInt("IceGridAdmin.AuthenticateUsingSSL"); if(opts.isSet("ssl")) { - ssl = true; + ssl = true; } string id = communicator()->getProperties()->getProperty("IceGridAdmin.Username"); if(!opts.optArg("username").empty()) { - id = opts.optArg("username"); + id = opts.optArg("username"); } string password = communicator()->getProperties()->getProperty("IceGridAdmin.Password"); if(!opts.optArg("password").empty()) { - password = opts.optArg("password"); + password = opts.optArg("password"); } // @@ -370,12 +370,12 @@ Client::run(int argc, char* argv[]) bool routed = properties->getPropertyAsIntWithDefault("IceGridAdmin.Routed", communicator()->getDefaultRouter()); if(opts.isSet("routed")) { - routed = true; + routed = true; } string replica = properties->getProperty("IceGridAdmin.Replica"); if(!opts.optArg("replica").empty()) { - replica = opts.optArg("replica"); + replica = opts.optArg("replica"); } AdminSessionPrx session; @@ -383,227 +383,227 @@ Client::run(int argc, char* argv[]) int status = EXIT_SUCCESS; try { - int timeout; - if(routed) - { - Glacier2::RouterPrx router = Glacier2::RouterPrx::checkedCast(communicator()->getDefaultRouter()); - if(!router) - { - cerr << argv[0] << ": configured router is not a Glacier2 router" << endl; - return EXIT_FAILURE; - } - - // Use SSL if available. - try - { - router = Glacier2::RouterPrx::checkedCast(router->ice_secure(true)); - } - catch(const Ice::NoEndpointException&) - { - } - - if(ssl) - { - session = AdminSessionPrx::uncheckedCast(router->createSessionFromSecureConnection()); - if(!session) - { - cerr << argv[0] - << ": Glacier2 returned a null session, please set the Glacier2.SSLSessionManager property" - << endl; - return EXIT_FAILURE; - } - } - else - { - while(id.empty()) - { - cout << "user id: " << flush; - getline(cin, id); - id = trim(id); - } - - if(password.empty()) - { - cout << "password: " << flush; - getline(cin, password); - password = trim(password); - } - - session = AdminSessionPrx::uncheckedCast(router->createSession(id, password)); - if(!session) - { - cerr << argv[0] - << ": Glacier2 returned a null session, please set the Glacier2.SessionManager property" - << endl; - return EXIT_FAILURE; - } - } - timeout = static_cast(router->getSessionTimeout()); - } - else - { - Identity registryId; - registryId.category = instanceName; - registryId.name = "Registry"; - if(!replica.empty() && replica != "Master") - { - registryId.name += "-" + replica; - } - - RegistryPrx registry; - try - { - registry = RegistryPrx::checkedCast( - communicator()->stringToProxy("\"" + communicator()->identityToString(registryId) + "\"")); - if(!registry) - { - cerr << argv[0] << ": could not contact registry" << endl; - return EXIT_FAILURE; - } - } - catch(const Ice::NotRegisteredException&) - { - cerr << argv[0] << ": no active registry replica named `" << replica << "'" << endl; - return EXIT_FAILURE; - } - - // Use SSL if available. - try - { - registry = RegistryPrx::checkedCast(registry->ice_secure(true)); - } - catch(const Ice::NoEndpointException&) - { - } - - if(ssl) - { - session = registry->createAdminSessionFromSecureConnection(); - } - else - { - while(id.empty()) - { - cout << "user id: " << flush; - getline(cin, id); - id = trim(id); - } - - if(password.empty()) - { - cout << "password: " << flush; - getline(cin, password); - password = trim(password); - } - - session = registry->createAdminSession(id, password); - } - assert(session); - timeout = registry->getSessionTimeout(); - } - - keepAlive = new SessionKeepAliveThread(session, timeout / 2); - keepAlive->start(); - - AdminPrx admin = session->getAdmin(); - - Ice::SliceChecksumDict serverChecksums = admin->getSliceChecksums(); - Ice::SliceChecksumDict localChecksums = Ice::sliceChecksums(); - - // - // The following slice types are only used by the admin CLI. - // - localChecksums.erase("::IceGrid::FileParser"); - localChecksums.erase("::IceGrid::ParseException"); - - for(Ice::SliceChecksumDict::const_iterator q = localChecksums.begin(); q != localChecksums.end(); ++q) - { - Ice::SliceChecksumDict::const_iterator r = serverChecksums.find(q->first); - if(r == serverChecksums.end()) - { - cerr << appName() << ": server is using unknown Slice type `" << q->first << "'" << endl; - } - else if(q->second != r->second) - { - cerr << appName() << ": server is using a different Slice definition of `" << q->first << "'" << endl; - } - } - - { - Lock sync(*this); - _parser = Parser::createParser(communicator(), session, admin, args.empty() && commands.empty()); - } - - if(!args.empty()) // Files given - { - // Process files given on the command line - for(vector::const_iterator i = args.begin(); i != args.end(); ++i) - { - ifstream test(i->c_str()); - if(!test) - { - cerr << appName() << ": can't open `" << *i << "' for reading: " << strerror(errno) << endl; - return EXIT_FAILURE; - } - test.close(); - - string cmd = cpp + " " + *i; + int timeout; + if(routed) + { + Glacier2::RouterPrx router = Glacier2::RouterPrx::checkedCast(communicator()->getDefaultRouter()); + if(!router) + { + cerr << argv[0] << ": configured router is not a Glacier2 router" << endl; + return EXIT_FAILURE; + } + + // Use SSL if available. + try + { + router = Glacier2::RouterPrx::checkedCast(router->ice_secure(true)); + } + catch(const Ice::NoEndpointException&) + { + } + + if(ssl) + { + session = AdminSessionPrx::uncheckedCast(router->createSessionFromSecureConnection()); + if(!session) + { + cerr << argv[0] + << ": Glacier2 returned a null session, please set the Glacier2.SSLSessionManager property" + << endl; + return EXIT_FAILURE; + } + } + else + { + while(id.empty()) + { + cout << "user id: " << flush; + getline(cin, id); + id = trim(id); + } + + if(password.empty()) + { + cout << "password: " << flush; + getline(cin, password); + password = trim(password); + } + + session = AdminSessionPrx::uncheckedCast(router->createSession(id, password)); + if(!session) + { + cerr << argv[0] + << ": Glacier2 returned a null session, please set the Glacier2.SessionManager property" + << endl; + return EXIT_FAILURE; + } + } + timeout = static_cast(router->getSessionTimeout()); + } + else + { + Identity registryId; + registryId.category = instanceName; + registryId.name = "Registry"; + if(!replica.empty() && replica != "Master") + { + registryId.name += "-" + replica; + } + + RegistryPrx registry; + try + { + registry = RegistryPrx::checkedCast( + communicator()->stringToProxy("\"" + communicator()->identityToString(registryId) + "\"")); + if(!registry) + { + cerr << argv[0] << ": could not contact registry" << endl; + return EXIT_FAILURE; + } + } + catch(const Ice::NotRegisteredException&) + { + cerr << argv[0] << ": no active registry replica named `" << replica << "'" << endl; + return EXIT_FAILURE; + } + + // Use SSL if available. + try + { + registry = RegistryPrx::checkedCast(registry->ice_secure(true)); + } + catch(const Ice::NoEndpointException&) + { + } + + if(ssl) + { + session = registry->createAdminSessionFromSecureConnection(); + } + else + { + while(id.empty()) + { + cout << "user id: " << flush; + getline(cin, id); + id = trim(id); + } + + if(password.empty()) + { + cout << "password: " << flush; + getline(cin, password); + password = trim(password); + } + + session = registry->createAdminSession(id, password); + } + assert(session); + timeout = registry->getSessionTimeout(); + } + + keepAlive = new SessionKeepAliveThread(session, timeout / 2); + keepAlive->start(); + + AdminPrx admin = session->getAdmin(); + + Ice::SliceChecksumDict serverChecksums = admin->getSliceChecksums(); + Ice::SliceChecksumDict localChecksums = Ice::sliceChecksums(); + + // + // The following slice types are only used by the admin CLI. + // + localChecksums.erase("::IceGrid::FileParser"); + localChecksums.erase("::IceGrid::ParseException"); + + for(Ice::SliceChecksumDict::const_iterator q = localChecksums.begin(); q != localChecksums.end(); ++q) + { + Ice::SliceChecksumDict::const_iterator r = serverChecksums.find(q->first); + if(r == serverChecksums.end()) + { + cerr << appName() << ": server is using unknown Slice type `" << q->first << "'" << endl; + } + else if(q->second != r->second) + { + cerr << appName() << ": server is using a different Slice definition of `" << q->first << "'" << endl; + } + } + + { + Lock sync(*this); + _parser = Parser::createParser(communicator(), session, admin, args.empty() && commands.empty()); + } + + if(!args.empty()) // Files given + { + // Process files given on the command line + for(vector::const_iterator i = args.begin(); i != args.end(); ++i) + { + ifstream test(i->c_str()); + if(!test) + { + cerr << appName() << ": can't open `" << *i << "' for reading: " << strerror(errno) << endl; + return EXIT_FAILURE; + } + test.close(); + + string cmd = cpp + " " + *i; #ifdef _WIN32 - FILE* cppHandle = _popen(cmd.c_str(), "r"); + FILE* cppHandle = _popen(cmd.c_str(), "r"); #else - FILE* cppHandle = popen(cmd.c_str(), "r"); + FILE* cppHandle = popen(cmd.c_str(), "r"); #endif - if(cppHandle == NULL) - { - cerr << appName() << ": can't run C++ preprocessor: " << strerror(errno) << endl; - return EXIT_FAILURE; - } - - int parseStatus = _parser->parse(cppHandle, debug); - + if(cppHandle == NULL) + { + cerr << appName() << ": can't run C++ preprocessor: " << strerror(errno) << endl; + return EXIT_FAILURE; + } + + int parseStatus = _parser->parse(cppHandle, debug); + #ifdef _WIN32 - _pclose(cppHandle); + _pclose(cppHandle); #else - pclose(cppHandle); + pclose(cppHandle); #endif - if(parseStatus == EXIT_FAILURE) - { - status = EXIT_FAILURE; - } - } - } - else if(!commands.empty()) // Commands were given - { - int parseStatus = _parser->parse(commands, debug); - if(parseStatus == EXIT_FAILURE) - { - status = EXIT_FAILURE; - } - } - else // No commands, let's use standard input - { - _parser->showBanner(); - - int parseStatus = _parser->parse(stdin, debug); - if(parseStatus == EXIT_FAILURE) - { - status = EXIT_FAILURE; - } - } + if(parseStatus == EXIT_FAILURE) + { + status = EXIT_FAILURE; + } + } + } + else if(!commands.empty()) // Commands were given + { + int parseStatus = _parser->parse(commands, debug); + if(parseStatus == EXIT_FAILURE) + { + status = EXIT_FAILURE; + } + } + else // No commands, let's use standard input + { + _parser->showBanner(); + + int parseStatus = _parser->parse(stdin, debug); + if(parseStatus == EXIT_FAILURE) + { + status = EXIT_FAILURE; + } + } } catch(const IceGrid::PermissionDeniedException& ex) { - cout << "permission denied:\n" << ex.reason << endl; - return EXIT_FAILURE; + cout << "permission denied:\n" << ex.reason << endl; + return EXIT_FAILURE; } catch(...) { - if(keepAlive) - { - keepAlive->destroy(); - keepAlive->getThreadControl().join(); - } + if(keepAlive) + { + keepAlive->destroy(); + keepAlive->getThreadControl().join(); + } if(session) { @@ -615,7 +615,7 @@ Client::run(int argc, char* argv[]) { } } - throw; + throw; } keepAlive->destroy(); diff --git a/cpp/src/IceGrid/Database.cpp b/cpp/src/IceGrid/Database.cpp index aa4803f9269..15dafc7bf4d 100644 --- a/cpp/src/IceGrid/Database.cpp +++ b/cpp/src/IceGrid/Database.cpp @@ -38,17 +38,17 @@ struct ObjectLoadCI : binary_function&, pair& lhs, const pair& rhs) { - return lhs.second < rhs.second; + return lhs.second < rhs.second; } }; } Database::Database(const Ice::ObjectAdapterPtr& registryAdapter, - const IceStorm::TopicManagerPrx& topicManager, - const string& instanceName, - const TraceLevelsPtr& traceLevels, - const RegistryInfo& info) : + const IceStorm::TopicManagerPrx& topicManager, + const string& instanceName, + const TraceLevelsPtr& traceLevels, + const RegistryInfo& info) : _communicator(registryAdapter->getCommunicator()), _internalAdapter(registryAdapter), _topicManager(topicManager), @@ -72,31 +72,31 @@ Database::Database(const Ice::ObjectAdapterPtr& registryAdapter, ServerEntrySeq entries; for(StringApplicationInfoDict::iterator p = _applications.begin(); p != _applications.end(); ++p) { - try - { - // - // Create an application helper for the application - // without instantiating. The application might be invalid - // if we need to upgrade it. - // - ApplicationInfo info = p->second; - - ApplicationHelper helper(_communicator, p->second.descriptor, false, false); - if(helper.upgrade(info.descriptor)) - { - ++info.revision; - info.updateUser = "IceGrid Registry (database upgrade)"; - info.updateTime = IceUtil::Time::now().toMilliSeconds(); - p.set(info); - } - - load(ApplicationHelper(_communicator, info.descriptor), entries, info.uuid, info.revision); - } - catch(const DeploymentException& ex) - { - Ice::Error err(_traceLevels->logger); - err << "invalid application `" << p->first << "':\n" << ex.reason; - } + try + { + // + // Create an application helper for the application + // without instantiating. The application might be invalid + // if we need to upgrade it. + // + ApplicationInfo info = p->second; + + ApplicationHelper helper(_communicator, p->second.descriptor, false, false); + if(helper.upgrade(info.descriptor)) + { + ++info.revision; + info.updateUser = "IceGrid Registry (database upgrade)"; + info.updateTime = IceUtil::Time::now().toMilliSeconds(); + p.set(info); + } + + load(ApplicationHelper(_communicator, info.descriptor), entries, info.uuid, info.revision); + } + catch(const DeploymentException& ex) + { + Ice::Error err(_traceLevels->logger); + err << "invalid application `" << p->first << "':\n" << ex.reason; + } } _serverCache.setTraceLevels(_traceLevels); @@ -141,17 +141,17 @@ Database::getObserverTopic(TopicName name) const switch(name) { case RegistryObserverTopicName: - return _registryObserverTopic; + return _registryObserverTopic; case NodeObserverTopicName: - return _nodeObserverTopic; + return _nodeObserverTopic; case ApplicationObserverTopicName: - return _applicationObserverTopic; + return _applicationObserverTopic; case AdapterObserverTopicName: - return _adapterObserverTopic; + return _adapterObserverTopic; case ObjectObserverTopicName: - return _objectObserverTopic; + return _objectObserverTopic; default: - break; + break; } return 0; } @@ -161,7 +161,7 @@ Database::checkSessionLock(AdminSessionI* session) { if(_lock != 0 && session != _lock) { - throw AccessDeniedException(_lockUserId); // Lock held by another session. + throw AccessDeniedException(_lockUserId); // Lock held by another session. } } @@ -172,7 +172,7 @@ Database::lock(AdminSessionI* session, const string& userId) if(_lock != 0 && session != _lock) { - throw AccessDeniedException(_lockUserId); // Lock held by another session. + throw AccessDeniedException(_lockUserId); // Lock held by another session. } assert(_lock == 0 || _lock == session); @@ -188,7 +188,7 @@ Database::unlock(AdminSessionI* session) Lock sync(*this); if(_lock != session) { - throw AccessDeniedException(); + throw AccessDeniedException(); } _lock = 0; @@ -200,54 +200,54 @@ Database::syncApplications(const ApplicationInfoSeq& applications) { int serial; { - Lock sync(*this); + Lock sync(*this); - Freeze::TransactionHolder txHolder(_connection); - ServerEntrySeq entries; - set names; - for(ApplicationInfoSeq::const_iterator p = applications.begin(); p != applications.end(); ++p) - { - try - { - StringApplicationInfoDict::const_iterator s = _applications.find(p->descriptor.name); - if(s != _applications.end()) - { - ApplicationHelper previous(_communicator, s->second.descriptor); - ApplicationHelper helper(_communicator, p->descriptor); - reload(previous, helper, entries, p->uuid, p->revision); - } - else - { - load(ApplicationHelper(_communicator, p->descriptor), entries, p->uuid, p->revision); - } - } - catch(const DeploymentException& ex) - { - Ice::Warning warn(_traceLevels->logger); - warn << "invalid application `" << p->descriptor.name << "':\n" << ex.reason; - } - _applications.put(StringApplicationInfoDict::value_type(p->descriptor.name, *p)); - names.insert(p->descriptor.name); - } - - StringApplicationInfoDict::iterator s = _applications.begin(); - while(s != _applications.end()) - { - if(names.find(s->first) == names.end()) - { - unload(ApplicationHelper(_communicator, s->second.descriptor), entries); - _applications.erase(s++); - } - else - { - ++s; - } - } - ++_applicationSerial; + Freeze::TransactionHolder txHolder(_connection); + ServerEntrySeq entries; + set names; + for(ApplicationInfoSeq::const_iterator p = applications.begin(); p != applications.end(); ++p) + { + try + { + StringApplicationInfoDict::const_iterator s = _applications.find(p->descriptor.name); + if(s != _applications.end()) + { + ApplicationHelper previous(_communicator, s->second.descriptor); + ApplicationHelper helper(_communicator, p->descriptor); + reload(previous, helper, entries, p->uuid, p->revision); + } + else + { + load(ApplicationHelper(_communicator, p->descriptor), entries, p->uuid, p->revision); + } + } + catch(const DeploymentException& ex) + { + Ice::Warning warn(_traceLevels->logger); + warn << "invalid application `" << p->descriptor.name << "':\n" << ex.reason; + } + _applications.put(StringApplicationInfoDict::value_type(p->descriptor.name, *p)); + names.insert(p->descriptor.name); + } + + StringApplicationInfoDict::iterator s = _applications.begin(); + while(s != _applications.end()) + { + if(names.find(s->first) == names.end()) + { + unload(ApplicationHelper(_communicator, s->second.descriptor), entries); + _applications.erase(s++); + } + else + { + ++s; + } + } + ++_applicationSerial; - serial = _applicationObserverTopic->applicationInit(_applicationSerial, applications); + serial = _applicationObserverTopic->applicationInit(_applicationSerial, applications); - txHolder.commit(); + txHolder.commit(); } _applicationObserverTopic->waitForSyncedSubscribers(serial); } @@ -257,15 +257,15 @@ Database::syncAdapters(const AdapterInfoSeq& adapters) { int serial; { - Lock sync(*this); - Freeze::TransactionHolder txHolder(_connection); - _adapters.clear(); - for(AdapterInfoSeq::const_iterator r = adapters.begin(); r != adapters.end(); ++r) - { - _adapters.put(StringAdapterInfoDict::value_type(r->id, *r)); - } - serial = _adapterObserverTopic->adapterInit(adapters); - txHolder.commit(); + Lock sync(*this); + Freeze::TransactionHolder txHolder(_connection); + _adapters.clear(); + for(AdapterInfoSeq::const_iterator r = adapters.begin(); r != adapters.end(); ++r) + { + _adapters.put(StringAdapterInfoDict::value_type(r->id, *r)); + } + serial = _adapterObserverTopic->adapterInit(adapters); + txHolder.commit(); } _adapterObserverTopic->waitForSyncedSubscribers(serial); } @@ -275,15 +275,15 @@ Database::syncObjects(const ObjectInfoSeq& objects) { int serial; { - Lock sync(*this); - Freeze::TransactionHolder txHolder(_connection); - _objects.clear(); - for(ObjectInfoSeq::const_iterator q = objects.begin(); q != objects.end(); ++q) - { - _objects.put(IdentityObjectInfoDict::value_type(q->proxy->ice_getIdentity(), *q)); - } - serial = _objectObserverTopic->objectInit(objects); - txHolder.commit(); + Lock sync(*this); + Freeze::TransactionHolder txHolder(_connection); + _objects.clear(); + for(ObjectInfoSeq::const_iterator q = objects.begin(); q != objects.end(); ++q) + { + _objects.put(IdentityObjectInfoDict::value_type(q->proxy->ice_getIdentity(), *q)); + } + serial = _objectObserverTopic->objectInit(objects); + txHolder.commit(); } _objectObserverTopic->waitForSyncedSubscribers(serial); } @@ -293,62 +293,62 @@ Database::addApplication(const ApplicationInfo& info, AdminSessionI* session) { ServerEntrySeq entries; { - Lock sync(*this); - checkSessionLock(session); + Lock sync(*this); + checkSessionLock(session); - while(_updating.find(info.descriptor.name) != _updating.end()) - { - wait(); - } + while(_updating.find(info.descriptor.name) != _updating.end()) + { + wait(); + } - if(_applications.find(info.descriptor.name) != _applications.end()) - { - throw DeploymentException("application `" + info.descriptor.name + "' already exists"); - } + if(_applications.find(info.descriptor.name) != _applications.end()) + { + throw DeploymentException("application `" + info.descriptor.name + "' already exists"); + } - ApplicationHelper helper(_communicator, info.descriptor, true); - checkForAddition(helper); - load(helper, entries, info.uuid, info.revision); - startUpdating(info.descriptor.name); + ApplicationHelper helper(_communicator, info.descriptor, true); + checkForAddition(helper); + load(helper, entries, info.uuid, info.revision); + startUpdating(info.descriptor.name); } if(_master) { - try - { - for_each(entries.begin(), entries.end(), IceUtil::voidMemFun(&ServerEntry::syncAndWait)); - } - catch(const DeploymentException& ex) - { - try - { - Lock sync(*this); - entries.clear(); - unload(ApplicationHelper(_communicator, info.descriptor), entries); - } - catch(const DeploymentException& ex) - { - Ice::Error err(_traceLevels->logger); - err << "failed to rollback previous application `" << info.descriptor.name << "':\n" << ex.reason; - } - finishUpdating(info.descriptor.name); - throw ex; - } + try + { + for_each(entries.begin(), entries.end(), IceUtil::voidMemFun(&ServerEntry::syncAndWait)); + } + catch(const DeploymentException& ex) + { + try + { + Lock sync(*this); + entries.clear(); + unload(ApplicationHelper(_communicator, info.descriptor), entries); + } + catch(const DeploymentException& ex) + { + Ice::Error err(_traceLevels->logger); + err << "failed to rollback previous application `" << info.descriptor.name << "':\n" << ex.reason; + } + finishUpdating(info.descriptor.name); + throw ex; + } } int serial; { - Lock sync(*this); - ++_applicationSerial; - _applications.put(StringApplicationInfoDict::value_type(info.descriptor.name, info)); + Lock sync(*this); + ++_applicationSerial; + _applications.put(StringApplicationInfoDict::value_type(info.descriptor.name, info)); - serial = _applicationObserverTopic->applicationAdded(_applicationSerial, info); + serial = _applicationObserverTopic->applicationAdded(_applicationSerial, info); - if(_traceLevels->application > 0) - { - Ice::Trace out(_traceLevels->logger, _traceLevels->applicationCat); - out << "added application `" << info.descriptor.name << "'"; - } + if(_traceLevels->application > 0) + { + Ice::Trace out(_traceLevels->logger, _traceLevels->applicationCat); + out << "added application `" << info.descriptor.name << "'"; + } } _applicationObserverTopic->waitForSyncedSubscribers(serial); @@ -364,35 +364,35 @@ Database::updateApplication(const ApplicationUpdateInfo& updt, AdminSessionI* se ApplicationDescriptor newDesc; ApplicationUpdateInfo update = updt; { - Lock sync(*this); - checkSessionLock(session); + Lock sync(*this); + checkSessionLock(session); - while(_updating.find(update.descriptor.name) != _updating.end()) - { - wait(); - } + while(_updating.find(update.descriptor.name) != _updating.end()) + { + wait(); + } - StringApplicationInfoDict::const_iterator p = _applications.find(update.descriptor.name); - if(p == _applications.end()) - { - throw ApplicationNotExistException(update.descriptor.name); - } - oldApp = p->second; + StringApplicationInfoDict::const_iterator p = _applications.find(update.descriptor.name); + if(p == _applications.end()) + { + throw ApplicationNotExistException(update.descriptor.name); + } + oldApp = p->second; - if(update.revision < 0) - { - update.revision = oldApp.revision + 1; - } + if(update.revision < 0) + { + update.revision = oldApp.revision + 1; + } - ApplicationHelper previous(_communicator, oldApp.descriptor); - ApplicationHelper helper(_communicator, previous.update(update.descriptor), true); + ApplicationHelper previous(_communicator, oldApp.descriptor); + ApplicationHelper helper(_communicator, previous.update(update.descriptor), true); - checkForUpdate(previous, helper); - reload(previous, helper, entries, oldApp.uuid, oldApp.revision + 1); + checkForUpdate(previous, helper); + reload(previous, helper, entries, oldApp.uuid, oldApp.revision + 1); - newDesc = helper.getDefinition(); + newDesc = helper.getDefinition(); - startUpdating(update.descriptor.name); + startUpdating(update.descriptor.name); } finishApplicationUpdate(entries, update, oldApp, newDesc, session); @@ -405,33 +405,33 @@ Database::syncApplicationDescriptor(const ApplicationDescriptor& newDesc, AdminS ApplicationUpdateInfo update; ApplicationInfo oldApp; { - Lock sync(*this); - checkSessionLock(session); + Lock sync(*this); + checkSessionLock(session); - while(_updating.find(update.descriptor.name) != _updating.end()) - { - wait(); - } + while(_updating.find(update.descriptor.name) != _updating.end()) + { + wait(); + } - StringApplicationInfoDict::const_iterator p = _applications.find(newDesc.name); - if(p == _applications.end()) - { - throw ApplicationNotExistException(newDesc.name); - } - oldApp = p->second; + StringApplicationInfoDict::const_iterator p = _applications.find(newDesc.name); + if(p == _applications.end()) + { + throw ApplicationNotExistException(newDesc.name); + } + oldApp = p->second; - ApplicationHelper previous(_communicator, oldApp.descriptor); - ApplicationHelper helper(_communicator, newDesc, true); + ApplicationHelper previous(_communicator, oldApp.descriptor); + ApplicationHelper helper(_communicator, newDesc, true); - update.updateTime = IceUtil::Time::now().toMilliSeconds(); - update.updateUser = _lockUserId; - update.revision = oldApp.revision + 1; - update.descriptor = helper.diff(previous); - - checkForUpdate(previous, helper); - reload(previous, helper, entries, oldApp.uuid, oldApp.revision + 1); + update.updateTime = IceUtil::Time::now().toMilliSeconds(); + update.updateUser = _lockUserId; + update.revision = oldApp.revision + 1; + update.descriptor = helper.diff(previous); + + checkForUpdate(previous, helper); + reload(previous, helper, entries, oldApp.uuid, oldApp.revision + 1); - startUpdating(update.descriptor.name); + startUpdating(update.descriptor.name); } finishApplicationUpdate(entries, update, oldApp, newDesc, session); @@ -439,44 +439,44 @@ Database::syncApplicationDescriptor(const ApplicationDescriptor& newDesc, AdminS void Database::instantiateServer(const string& application, - const string& node, - const ServerInstanceDescriptor& instance, - AdminSessionI* session) + const string& node, + const ServerInstanceDescriptor& instance, + AdminSessionI* session) { ServerEntrySeq entries; ApplicationUpdateInfo update; ApplicationInfo oldApp; ApplicationDescriptor newDesc; { - Lock sync(*this); - checkSessionLock(session); + Lock sync(*this); + checkSessionLock(session); - while(_updating.find(application) != _updating.end()) - { - wait(); - } + while(_updating.find(application) != _updating.end()) + { + wait(); + } - StringApplicationInfoDict::const_iterator p = _applications.find(application); - if(p == _applications.end()) - { - throw ApplicationNotExistException(application); - } - oldApp = p->second; + StringApplicationInfoDict::const_iterator p = _applications.find(application); + if(p == _applications.end()) + { + throw ApplicationNotExistException(application); + } + oldApp = p->second; - ApplicationHelper previous(_communicator, oldApp.descriptor); - ApplicationHelper helper(_communicator, previous.instantiateServer(node, instance), true); + ApplicationHelper previous(_communicator, oldApp.descriptor); + ApplicationHelper helper(_communicator, previous.instantiateServer(node, instance), true); - update.updateTime = IceUtil::Time::now().toMilliSeconds(); - update.updateUser = _lockUserId; - update.revision = oldApp.revision + 1; - update.descriptor = helper.diff(previous); + update.updateTime = IceUtil::Time::now().toMilliSeconds(); + update.updateUser = _lockUserId; + update.revision = oldApp.revision + 1; + update.descriptor = helper.diff(previous); - checkForUpdate(previous, helper); - reload(previous, helper, entries, oldApp.uuid, oldApp.revision + 1); + checkForUpdate(previous, helper); + reload(previous, helper, entries, oldApp.uuid, oldApp.revision + 1); - newDesc = helper.getDefinition(); + newDesc = helper.getDefinition(); - startUpdating(update.descriptor.name); + startUpdating(update.descriptor.name); } finishApplicationUpdate(entries, update, oldApp, newDesc, session); @@ -488,55 +488,55 @@ Database::removeApplication(const string& name, AdminSessionI* session) ServerEntrySeq entries; int serial; { - Lock sync(*this); - checkSessionLock(session); - - while(_updating.find(name) != _updating.end()) - { - wait(); - } - - StringApplicationInfoDict::iterator p = _applications.find(name); - if(p == _applications.end()) - { - throw ApplicationNotExistException(name); - } - - try - { - ApplicationHelper helper(_communicator, p->second.descriptor); - unload(helper, entries); - } - catch(const DeploymentException&) - { - // - // For some reasons the application became invalid. If - // it's invalid, it's most likely not loaded either. So we - // ignore the error and erase the descriptor. - // - } - - startUpdating(name); + Lock sync(*this); + checkSessionLock(session); + + while(_updating.find(name) != _updating.end()) + { + wait(); + } + + StringApplicationInfoDict::iterator p = _applications.find(name); + if(p == _applications.end()) + { + throw ApplicationNotExistException(name); + } + + try + { + ApplicationHelper helper(_communicator, p->second.descriptor); + unload(helper, entries); + } + catch(const DeploymentException&) + { + // + // For some reasons the application became invalid. If + // it's invalid, it's most likely not loaded either. So we + // ignore the error and erase the descriptor. + // + } + + startUpdating(name); } if(_master) { - for_each(entries.begin(), entries.end(), IceUtil::voidMemFun(&ServerEntry::sync)); - for_each(entries.begin(), entries.end(), IceUtil::voidMemFun(&ServerEntry::waitNoThrow)); + for_each(entries.begin(), entries.end(), IceUtil::voidMemFun(&ServerEntry::sync)); + for_each(entries.begin(), entries.end(), IceUtil::voidMemFun(&ServerEntry::waitNoThrow)); } { - Lock sync(*this); - _applications.erase(name); - ++_applicationSerial; + Lock sync(*this); + _applications.erase(name); + ++_applicationSerial; - serial = _applicationObserverTopic->applicationRemoved(_applicationSerial, name); + serial = _applicationObserverTopic->applicationRemoved(_applicationSerial, name); - if(_traceLevels->application > 0) - { - Ice::Trace out(_traceLevels->logger, _traceLevels->applicationCat); - out << "removed application `" << name << "'"; - } + if(_traceLevels->application > 0) + { + Ice::Trace out(_traceLevels->logger, _traceLevels->applicationCat); + out << "removed application `" << name << "'"; + } } _applicationObserverTopic->waitForSyncedSubscribers(serial); @@ -553,7 +553,7 @@ Database::getApplicationInfo(const std::string& name) StringApplicationInfoDict::const_iterator p = descriptors.find(name); if(p == descriptors.end()) { - throw ApplicationNotExistException(name); + throw ApplicationNotExistException(name); } return p->second; @@ -569,18 +569,18 @@ Database::getAllApplications(const string& expression) void Database::waitForApplicationUpdate(const AMD_NodeSession_waitForApplicationUpdatePtr& cb, - const string& application, - int revision) + const string& application, + int revision) { Lock sync(*this); map >::iterator p = _updating.find(application); if(p != _updating.end()) { - p->second.push_back(cb); + p->second.push_back(cb); } else { - cb->ice_response(); + cb->ice_response(); } } @@ -637,67 +637,67 @@ Database::setAdapterDirectProxy(const string& adapterId, const string& replicaGr { int serial; { - Lock sync(*this); - if(_adapterCache.has(adapterId)) - { - throw AdapterExistsException(adapterId); - } - - StringAdapterInfoDict::iterator p = _adapters.find(adapterId); - AdapterInfo info; - bool updated = false; - if(proxy) - { - if(p != _adapters.end()) - { - info = p->second; - info.proxy = proxy; - info.replicaGroupId = replicaGroupId; - p.set(info); - updated = true; - } - else - { - info.id = adapterId; - info.proxy = proxy; - info.replicaGroupId = replicaGroupId; - _adapters.put(StringAdapterInfoDict::value_type(adapterId, info)); - } - } - else - { - if(p == _adapters.end()) - { - return; - } - _adapters.erase(p); - } - - if(_traceLevels->adapter > 0) - { - Ice::Trace out(_traceLevels->logger, _traceLevels->adapterCat); - out << (proxy ? (updated ? "updated" : "added") : "removed") << " adapter `" << adapterId << "'"; - if(!replicaGroupId.empty()) - { - out << " with replica group `" << replicaGroupId << "'"; - } - } + Lock sync(*this); + if(_adapterCache.has(adapterId)) + { + throw AdapterExistsException(adapterId); + } + + StringAdapterInfoDict::iterator p = _adapters.find(adapterId); + AdapterInfo info; + bool updated = false; + if(proxy) + { + if(p != _adapters.end()) + { + info = p->second; + info.proxy = proxy; + info.replicaGroupId = replicaGroupId; + p.set(info); + updated = true; + } + else + { + info.id = adapterId; + info.proxy = proxy; + info.replicaGroupId = replicaGroupId; + _adapters.put(StringAdapterInfoDict::value_type(adapterId, info)); + } + } + else + { + if(p == _adapters.end()) + { + return; + } + _adapters.erase(p); + } + + if(_traceLevels->adapter > 0) + { + Ice::Trace out(_traceLevels->logger, _traceLevels->adapterCat); + out << (proxy ? (updated ? "updated" : "added") : "removed") << " adapter `" << adapterId << "'"; + if(!replicaGroupId.empty()) + { + out << " with replica group `" << replicaGroupId << "'"; + } + } - if(proxy) - { - if(updated) - { - serial = _adapterObserverTopic->adapterUpdated(info); - } - else - { - serial = _adapterObserverTopic->adapterAdded(info); - } - } - else - { - serial = _adapterObserverTopic->adapterRemoved(adapterId); - } + if(proxy) + { + if(updated) + { + serial = _adapterObserverTopic->adapterUpdated(info); + } + else + { + serial = _adapterObserverTopic->adapterAdded(info); + } + } + else + { + serial = _adapterObserverTopic->adapterRemoved(adapterId); + } } _adapterObserverTopic->waitForSyncedSubscribers(serial); } @@ -710,18 +710,18 @@ Database::getAdapterDirectProxy(const string& id) StringAdapterInfoDict::const_iterator p = adapters.find(id); if(p != adapters.end()) { - return p->second.proxy; + return p->second.proxy; } Ice::EndpointSeq endpoints; for(p = adapters.findByReplicaGroupId(id, true); p != adapters.end(); ++p) { - Ice::EndpointSeq edpts = p->second.proxy->ice_getEndpoints(); - endpoints.insert(endpoints.end(), edpts.begin(), edpts.end()); + Ice::EndpointSeq edpts = p->second.proxy->ice_getEndpoints(); + endpoints.insert(endpoints.end(), edpts.begin(), edpts.end()); } if(!endpoints.empty()) { - return _communicator->stringToProxy("dummy:default")->ice_endpoints(endpoints); + return _communicator->stringToProxy("dummy:default")->ice_endpoints(endpoints); } throw AdapterNotExistException(id); @@ -732,61 +732,61 @@ Database::removeAdapter(const string& adapterId) { int serial; { - Lock sync(*this); - if(_adapterCache.has(adapterId)) - { - AdapterEntryPtr adpt = _adapterCache.get(adapterId); - DeploymentException ex; - ex.reason = "removing adapter `" + adapterId + "' is not allowed:\n"; - ex.reason += "the adapter was added with the application descriptor `" + adpt->getApplication() + "'"; - throw ex; - } - - Freeze::TransactionHolder txHolder(_connection); // Required because of the iterator - - StringAdapterInfoDict::iterator p = _adapters.find(adapterId); - AdapterInfoSeq infos; - if(p != _adapters.end()) - { - _adapters.erase(p); - } - else - { - p = _adapters.findByReplicaGroupId(adapterId, true); - if(p == _adapters.end()) - { - throw AdapterNotExistException(adapterId); - } - - while(p != _adapters.end()) - { - AdapterInfo info = p->second; - info.replicaGroupId = ""; - infos.push_back(info); - _adapters.put(StringAdapterInfoDict::value_type(p->first, info)); - ++p; - } - } - - if(_traceLevels->adapter > 0) - { - Ice::Trace out(_traceLevels->logger, _traceLevels->adapterCat); - out << "removed " << (infos.empty() ? "adapter" : "replica group") << " `" << adapterId << "'"; - } - - if(infos.empty()) - { - serial = _adapterObserverTopic->adapterRemoved(adapterId); - } - else - { - for(AdapterInfoSeq::const_iterator p = infos.begin(); p != infos.end(); ++p) - { - serial = _adapterObserverTopic->adapterUpdated(*p); - } - } - - txHolder.commit(); + Lock sync(*this); + if(_adapterCache.has(adapterId)) + { + AdapterEntryPtr adpt = _adapterCache.get(adapterId); + DeploymentException ex; + ex.reason = "removing adapter `" + adapterId + "' is not allowed:\n"; + ex.reason += "the adapter was added with the application descriptor `" + adpt->getApplication() + "'"; + throw ex; + } + + Freeze::TransactionHolder txHolder(_connection); // Required because of the iterator + + StringAdapterInfoDict::iterator p = _adapters.find(adapterId); + AdapterInfoSeq infos; + if(p != _adapters.end()) + { + _adapters.erase(p); + } + else + { + p = _adapters.findByReplicaGroupId(adapterId, true); + if(p == _adapters.end()) + { + throw AdapterNotExistException(adapterId); + } + + while(p != _adapters.end()) + { + AdapterInfo info = p->second; + info.replicaGroupId = ""; + infos.push_back(info); + _adapters.put(StringAdapterInfoDict::value_type(p->first, info)); + ++p; + } + } + + if(_traceLevels->adapter > 0) + { + Ice::Trace out(_traceLevels->logger, _traceLevels->adapterCat); + out << "removed " << (infos.empty() ? "adapter" : "replica group") << " `" << adapterId << "'"; + } + + if(infos.empty()) + { + serial = _adapterObserverTopic->adapterRemoved(adapterId); + } + else + { + for(AdapterInfoSeq::const_iterator p = infos.begin(); p != infos.end(); ++p) + { + serial = _adapterObserverTopic->adapterUpdated(*p); + } + } + + txHolder.commit(); } _adapterObserverTopic->waitForSyncedSubscribers(serial); } @@ -807,7 +807,7 @@ Database::getAdapterInfo(const string& id) // try { - return _adapterCache.get(id)->getAdapterInfo(); + return _adapterCache.get(id)->getAdapterInfo(); } catch(AdapterNotExistException&) { @@ -822,9 +822,9 @@ Database::getAdapterInfo(const string& id) StringAdapterInfoDict::const_iterator p = adapters.find(id); if(p != adapters.end()) { - AdapterInfoSeq infos; - infos.push_back(p->second); - return infos; + AdapterInfoSeq infos; + infos.push_back(p->second); + return infos; } // @@ -834,13 +834,13 @@ Database::getAdapterInfo(const string& id) p = adapters.findByReplicaGroupId(id, true); if(p != adapters.end()) { - AdapterInfoSeq infos; - while(p != adapters.end()) - { - infos.push_back(p->second); - ++p; - } - return infos; + AdapterInfoSeq infos; + while(p != adapters.end()) + { + infos.push_back(p->second); + ++p; + } + return infos; } throw AdapterNotExistException(id); @@ -857,15 +857,15 @@ Database::getAllAdapters(const string& expression) set groups; for(StringAdapterInfoDict::const_iterator p = _adapters.begin(); p != _adapters.end(); ++p) { - if(expression.empty() || IceUtil::match(p->first, expression, true)) - { - result.push_back(p->first); - } - string replicaGroupId = p->second.replicaGroupId; - if(!replicaGroupId.empty() && (expression.empty() || IceUtil::match(replicaGroupId, expression, true))) - { - groups.insert(replicaGroupId); - } + if(expression.empty() || IceUtil::match(p->first, expression, true)) + { + result.push_back(p->first); + } + string replicaGroupId = p->second.replicaGroupId; + if(!replicaGroupId.empty() && (expression.empty() || IceUtil::match(replicaGroupId, expression, true))) + { + groups.insert(replicaGroupId); + } } // // COMPILERFIX: We're not using result.insert() here, this doesn't compile on Sun. @@ -873,7 +873,7 @@ Database::getAllAdapters(const string& expression) //result.insert(result.end(), groups.begin(), groups.end()) for(set::const_iterator q = groups.begin(); q != groups.end(); ++q) { - result.push_back(*q); + result.push_back(*q); } return result; } @@ -883,27 +883,27 @@ Database::addObject(const ObjectInfo& info) { int serial; { - Lock sync(*this); - const Ice::Identity id = info.proxy->ice_getIdentity(); - - if(_objectCache.has(id)) - { - throw ObjectExistsException(id); - } - - if(_objects.find(id) != _objects.end()) - { - throw ObjectExistsException(id); - } - _objects.put(IdentityObjectInfoDict::value_type(id, info)); - - serial = _objectObserverTopic->objectAdded(info); - - if(_traceLevels->object > 0) - { - Ice::Trace out(_traceLevels->logger, _traceLevels->objectCat); - out << "added object `" << _communicator->identityToString(id) << "'"; - } + Lock sync(*this); + const Ice::Identity id = info.proxy->ice_getIdentity(); + + if(_objectCache.has(id)) + { + throw ObjectExistsException(id); + } + + if(_objects.find(id) != _objects.end()) + { + throw ObjectExistsException(id); + } + _objects.put(IdentityObjectInfoDict::value_type(id, info)); + + serial = _objectObserverTopic->objectAdded(info); + + if(_traceLevels->object > 0) + { + Ice::Trace out(_traceLevels->logger, _traceLevels->objectCat); + out << "added object `" << _communicator->identityToString(id) << "'"; + } } _objectObserverTopic->waitForSyncedSubscribers(serial); } @@ -913,31 +913,31 @@ Database::addOrUpdateObject(const ObjectInfo& info) { int serial; { - Lock sync(*this); - const Ice::Identity id = info.proxy->ice_getIdentity(); - - if(_objectCache.has(id)) - { - throw ObjectExistsException(id); - } - - bool update = _objects.find(id) != _objects.end(); - _objects.put(IdentityObjectInfoDict::value_type(id, info)); - - if(update) - { - serial = _objectObserverTopic->objectUpdated(info); - } - else - { - serial = _objectObserverTopic->objectAdded(info); - } - - if(_traceLevels->object > 0) - { - Ice::Trace out(_traceLevels->logger, _traceLevels->objectCat); - out << (!update ? "added" : "updated") << " object `" << _communicator->identityToString(id) << "'"; - } + Lock sync(*this); + const Ice::Identity id = info.proxy->ice_getIdentity(); + + if(_objectCache.has(id)) + { + throw ObjectExistsException(id); + } + + bool update = _objects.find(id) != _objects.end(); + _objects.put(IdentityObjectInfoDict::value_type(id, info)); + + if(update) + { + serial = _objectObserverTopic->objectUpdated(info); + } + else + { + serial = _objectObserverTopic->objectAdded(info); + } + + if(_traceLevels->object > 0) + { + Ice::Trace out(_traceLevels->logger, _traceLevels->objectCat); + out << (!update ? "added" : "updated") << " object `" << _communicator->identityToString(id) << "'"; + } } _objectObserverTopic->waitForSyncedSubscribers(serial); } @@ -947,33 +947,33 @@ Database::removeObject(const Ice::Identity& id) { int serial; { - Lock sync(*this); - if(_objectCache.has(id)) - { - DeploymentException ex; - ex.reason = "removing object `" + _communicator->identityToString(id) + "' is not allowed:\n"; - ex.reason += "the object was added with the application descriptor `"; - ex.reason += _objectCache.get(id)->getApplication(); - ex.reason += "'"; - throw ex; - } - - IdentityObjectInfoDict::iterator p = _objects.find(id); - if(p == _objects.end()) - { - ObjectNotRegisteredException ex; - ex.id = id; - throw ex; - } - _objects.erase(p); - - serial = _objectObserverTopic->objectRemoved(id); - - if(_traceLevels->object > 0) - { - Ice::Trace out(_traceLevels->logger, _traceLevels->objectCat); - out << "removed object `" << _communicator->identityToString(id) << "'"; - } + Lock sync(*this); + if(_objectCache.has(id)) + { + DeploymentException ex; + ex.reason = "removing object `" + _communicator->identityToString(id) + "' is not allowed:\n"; + ex.reason += "the object was added with the application descriptor `"; + ex.reason += _objectCache.get(id)->getApplication(); + ex.reason += "'"; + throw ex; + } + + IdentityObjectInfoDict::iterator p = _objects.find(id); + if(p == _objects.end()) + { + ObjectNotRegisteredException ex; + ex.id = id; + throw ex; + } + _objects.erase(p); + + serial = _objectObserverTopic->objectRemoved(id); + + if(_traceLevels->object > 0) + { + Ice::Trace out(_traceLevels->logger, _traceLevels->objectCat); + out << "removed object `" << _communicator->identityToString(id) << "'"; + } } _objectObserverTopic->waitForSyncedSubscribers(serial); } @@ -983,39 +983,39 @@ Database::updateObject(const Ice::ObjectPrx& proxy) { int serial; { - Lock sync(*this); - - const Ice::Identity id = proxy->ice_getIdentity(); - if(_objectCache.has(id)) - { - DeploymentException ex; - ex.reason = "updating object `" + _communicator->identityToString(id) + "' is not allowed:\n"; - ex.reason += "the object was added with the application descriptor `"; - ex.reason += _objectCache.get(id)->getApplication(); - ex.reason += "'"; - throw ex; - } + Lock sync(*this); + + const Ice::Identity id = proxy->ice_getIdentity(); + if(_objectCache.has(id)) + { + DeploymentException ex; + ex.reason = "updating object `" + _communicator->identityToString(id) + "' is not allowed:\n"; + ex.reason += "the object was added with the application descriptor `"; + ex.reason += _objectCache.get(id)->getApplication(); + ex.reason += "'"; + throw ex; + } - IdentityObjectInfoDict::iterator p = _objects.find(id); - if(p == _objects.end()) - { - ObjectNotRegisteredException ex; - ex.id = id; - throw ex; - } - - ObjectInfo info; - info = p->second; - info.proxy = proxy; - p.set(info); + IdentityObjectInfoDict::iterator p = _objects.find(id); + if(p == _objects.end()) + { + ObjectNotRegisteredException ex; + ex.id = id; + throw ex; + } + + ObjectInfo info; + info = p->second; + info.proxy = proxy; + p.set(info); - serial = _objectObserverTopic->objectUpdated(info); - - if(_traceLevels->object > 0) - { - Ice::Trace out(_traceLevels->logger, _traceLevels->objectCat); - out << "updated object `" << _communicator->identityToString(id) << "'"; - } + serial = _objectObserverTopic->objectUpdated(info); + + if(_traceLevels->object > 0) + { + Ice::Trace out(_traceLevels->logger, _traceLevels->objectCat); + out << "updated object `" << _communicator->identityToString(id) << "'"; + } } _objectObserverTopic->waitForSyncedSubscribers(serial); } @@ -1027,7 +1027,7 @@ Database::addOrUpdateObjectsInDatabase(const ObjectInfoSeq& objects) Freeze::TransactionHolder txHolder(_connection); for(ObjectInfoSeq::const_iterator p = objects.begin(); p != objects.end(); ++p) { - _objects.put(IdentityObjectInfoDict::value_type(p->proxy->ice_getIdentity(), *p)); + _objects.put(IdentityObjectInfoDict::value_type(p->proxy->ice_getIdentity(), *p)); } int serial = _objectObserverTopic->objectsAddedOrUpdated(objects); txHolder.commit(); @@ -1041,7 +1041,7 @@ Database::removeObjectsInDatabase(const ObjectInfoSeq& objects) Freeze::TransactionHolder txHolder(_connection); for(ObjectInfoSeq::const_iterator p = objects.begin(); p != objects.end(); ++p) { - _objects.erase(p->proxy->ice_getIdentity()); + _objects.erase(p->proxy->ice_getIdentity()); } _objectObserverTopic->objectsRemoved(objects); txHolder.commit(); @@ -1052,10 +1052,10 @@ Database::getObjectProxy(const Ice::Identity& id) { try { - // - // Only return proxies for non allocatable objects. - // - return _objectCache.get(id)->getProxy(); + // + // Only return proxies for non allocatable objects. + // + return _objectCache.get(id)->getProxy(); } catch(ObjectNotRegisteredException&) { @@ -1066,9 +1066,9 @@ Database::getObjectProxy(const Ice::Identity& id) IdentityObjectInfoDict::const_iterator p = objects.find(id); if(p == objects.end()) { - ObjectNotRegisteredException ex; - ex.id = id; - throw ex; + ObjectNotRegisteredException ex; + ex.id = id; + throw ex; } return p->second.proxy; } @@ -1079,7 +1079,7 @@ Database::getObjectByType(const string& type) Ice::ObjectProxySeq objs = getObjectsByType(type); if(objs.empty()) { - return 0; + return 0; } return objs[IceUtil::random(static_cast(objs.size()))]; } @@ -1090,7 +1090,7 @@ Database::getObjectByTypeOnLeastLoadedNode(const string& type, LoadSample sample Ice::ObjectProxySeq objs = getObjectsByType(type); if(objs.empty()) { - return 0; + return 0; } RandomNumberGenerator rng; @@ -1099,18 +1099,18 @@ Database::getObjectByTypeOnLeastLoadedNode(const string& type, LoadSample sample objectsWithLoad.reserve(objs.size()); for(Ice::ObjectProxySeq::const_iterator p = objs.begin(); p != objs.end(); ++p) { - float load = 1.0f; - if(!(*p)->ice_getAdapterId().empty()) - { - try - { - load = _adapterCache.get((*p)->ice_getAdapterId())->getLeastLoadedNodeLoad(sample); - } - catch(const AdapterNotExistException&) - { - } - } - objectsWithLoad.push_back(make_pair(*p, load)); + float load = 1.0f; + if(!(*p)->ice_getAdapterId().empty()) + { + try + { + load = _adapterCache.get((*p)->ice_getAdapterId())->getLeastLoadedNodeLoad(sample); + } + catch(const AdapterNotExistException&) + { + } + } + objectsWithLoad.push_back(make_pair(*p, load)); } return min_element(objectsWithLoad.begin(), objectsWithLoad.end(), ObjectLoadCI())->first; } @@ -1124,7 +1124,7 @@ Database::getObjectsByType(const string& type) IdentityObjectInfoDict objects(connection, _objectDbName); for(IdentityObjectInfoDict::const_iterator p = objects.findByType(type); p != objects.end(); ++p) { - proxies.push_back(p->second.proxy); + proxies.push_back(p->second.proxy); } return proxies; } @@ -1134,8 +1134,8 @@ Database::getObjectInfo(const Ice::Identity& id) { try { - ObjectEntryPtr object = _objectCache.get(id); - return object->getObjectInfo(); + ObjectEntryPtr object = _objectCache.get(id); + return object->getObjectInfo(); } catch(ObjectNotRegisteredException&) { @@ -1146,7 +1146,7 @@ Database::getObjectInfo(const Ice::Identity& id) IdentityObjectInfoDict::const_iterator p = objects.find(id); if(p == objects.end()) { - throw ObjectNotRegisteredException(id); + throw ObjectNotRegisteredException(id); } return p->second; } @@ -1159,10 +1159,10 @@ Database::getAllObjectInfos(const string& expression) IdentityObjectInfoDict objects(connection, _objectDbName); for(IdentityObjectInfoDict::const_iterator p = objects.begin(); p != objects.end(); ++p) { - if(expression.empty() || IceUtil::match(_communicator->identityToString(p->first), expression, true)) - { - infos.push_back(p->second); - } + if(expression.empty() || IceUtil::match(_communicator->identityToString(p->first), expression, true)) + { + infos.push_back(p->second); + } } return infos; } @@ -1175,7 +1175,7 @@ Database::getObjectInfosByType(const string& type) IdentityObjectInfoDict objects(connection, _objectDbName); for(IdentityObjectInfoDict::const_iterator p = objects.findByType(type); p != objects.end(); ++p) { - infos.push_back(p->second); + infos.push_back(p->second); } return infos; } @@ -1183,11 +1183,11 @@ Database::getObjectInfosByType(const string& type) void Database::addInternalObject(const ObjectInfo& info, bool replace) { - Lock sync(*this); + Lock sync(*this); const Ice::Identity id = info.proxy->ice_getIdentity(); if(!replace && _internalObjects.find(id) != _internalObjects.end()) { - throw ObjectExistsException(id); + throw ObjectExistsException(id); } _internalObjects.put(IdentityObjectInfoDict::value_type(id, info)); } @@ -1199,9 +1199,9 @@ Database::removeInternalObject(const Ice::Identity& id) IdentityObjectInfoDict::iterator p = _internalObjects.find(id); if(p == _internalObjects.end()) { - ObjectNotRegisteredException ex; - ex.id = id; - throw ex; + ObjectNotRegisteredException ex; + ex.id = id; + throw ex; } _internalObjects.erase(p); } @@ -1214,7 +1214,7 @@ Database::getInternalObjectsByType(const string& type) Ice::ObjectProxySeq proxies; for(IdentityObjectInfoDict::const_iterator p = internalObjects.findByType(type); p != internalObjects.end(); ++p) { - proxies.push_back(p->second.proxy); + proxies.push_back(p->second.proxy); } return proxies; } @@ -1261,9 +1261,9 @@ Database::checkServerForAddition(const string& id) { if(_serverCache.has(id)) { - DeploymentException ex; - ex.reason = "server `" + id + "' is already registered"; - throw ex; + DeploymentException ex; + ex.reason = "server `" + id + "' is already registered"; + throw ex; } } @@ -1274,9 +1274,9 @@ Database::checkAdapterForAddition(const string& id) _adapters.find(id) != _adapters.end() || _adapters.findByReplicaGroupId(id) != _adapters.end()) { - DeploymentException ex; - ex.reason = "adapter `" + id + "' is already registered"; - throw ex; + DeploymentException ex; + ex.reason = "adapter `" + id + "' is already registered"; + throw ex; } } @@ -1287,9 +1287,9 @@ Database::checkObjectForAddition(const Ice::Identity& objectId) _allocatableObjectCache.has(objectId) || _objects.find(objectId) != _objects.end()) { - DeploymentException ex; - ex.reason = "object `" + _communicator->identityToString(objectId) + "' is already registered"; - throw ex; + DeploymentException ex; + ex.reason = "object `" + _communicator->identityToString(objectId) + "' is already registered"; + throw ex; } } @@ -1300,27 +1300,27 @@ Database::load(const ApplicationHelper& app, ServerEntrySeq& entries, const stri const string application = app.getInstance().name; for(NodeDescriptorDict::const_iterator n = nodes.begin(); n != nodes.end(); ++n) { - _nodeCache.get(n->first, true)->addDescriptor(application, n->second); + _nodeCache.get(n->first, true)->addDescriptor(application, n->second); } const ReplicaGroupDescriptorSeq& adpts = app.getInstance().replicaGroups; for(ReplicaGroupDescriptorSeq::const_iterator r = adpts.begin(); r != adpts.end(); ++r) { - assert(!r->id.empty()); - _adapterCache.addReplicaGroup(*r, application); - for(ObjectDescriptorSeq::const_iterator o = r->objects.begin(); o != r->objects.end(); ++o) - { - ObjectInfo info; - info.type = o->type; - info.proxy = _communicator->stringToProxy("\"" + _communicator->identityToString(o->id) + "\" @ " + r->id); - _objectCache.add(info, application); - } + assert(!r->id.empty()); + _adapterCache.addReplicaGroup(*r, application); + for(ObjectDescriptorSeq::const_iterator o = r->objects.begin(); o != r->objects.end(); ++o) + { + ObjectInfo info; + info.type = o->type; + info.proxy = _communicator->stringToProxy("\"" + _communicator->identityToString(o->id) + "\" @ " + r->id); + _objectCache.add(info, application); + } } map servers = app.getServerInfos(uuid, revision); for(map::const_iterator p = servers.begin(); p != servers.end(); ++p) { - entries.push_back(_serverCache.add(p->second)); + entries.push_back(_serverCache.add(p->second)); } } @@ -1330,33 +1330,33 @@ Database::unload(const ApplicationHelper& app, ServerEntrySeq& entries) map servers = app.getServerInfos("", 0); for(map::const_iterator p = servers.begin(); p != servers.end(); ++p) { - entries.push_back(_serverCache.remove(p->first)); + entries.push_back(_serverCache.remove(p->first)); } const ReplicaGroupDescriptorSeq& adpts = app.getInstance().replicaGroups; for(ReplicaGroupDescriptorSeq::const_iterator r = adpts.begin(); r != adpts.end(); ++r) { - for(ObjectDescriptorSeq::const_iterator o = r->objects.begin(); o != r->objects.end(); ++o) - { - _objectCache.remove(o->id); - } - _adapterCache.removeReplicaGroup(r->id); + for(ObjectDescriptorSeq::const_iterator o = r->objects.begin(); o != r->objects.end(); ++o) + { + _objectCache.remove(o->id); + } + _adapterCache.removeReplicaGroup(r->id); } const NodeDescriptorDict& nodes = app.getInstance().nodes; const string application = app.getInstance().name; for(NodeDescriptorDict::const_iterator n = nodes.begin(); n != nodes.end(); ++n) { - _nodeCache.get(n->first)->removeDescriptor(application); + _nodeCache.get(n->first)->removeDescriptor(application); } } void Database::reload(const ApplicationHelper& oldApp, - const ApplicationHelper& newApp, - ServerEntrySeq& entries, - const string& uuid, - int revision) + const ApplicationHelper& newApp, + ServerEntrySeq& entries, + const string& uuid, + int revision) { const string application = oldApp.getInstance().name; @@ -1369,24 +1369,24 @@ Database::reload(const ApplicationHelper& oldApp, map::const_iterator p; for(p = newServers.begin(); p != newServers.end(); ++p) { - map::const_iterator q = oldServers.find(p->first); - if(q == oldServers.end()) - { - load.push_back(p->second); - } - else - { - _serverCache.remove(p->first, false); // Don't destroy the server if it was updated. - load.push_back(p->second); - } + map::const_iterator q = oldServers.find(p->first); + if(q == oldServers.end()) + { + load.push_back(p->second); + } + else + { + _serverCache.remove(p->first, false); // Don't destroy the server if it was updated. + load.push_back(p->second); + } } for(p = oldServers.begin(); p != oldServers.end(); ++p) { - map::const_iterator q = newServers.find(p->first); - if(q == newServers.end()) - { - entries.push_back(_serverCache.remove(p->first)); - } + map::const_iterator q = newServers.find(p->first); + if(q == newServers.end()) + { + entries.push_back(_serverCache.remove(p->first)); + } } // @@ -1397,22 +1397,22 @@ Database::reload(const ApplicationHelper& oldApp, ReplicaGroupDescriptorSeq::const_iterator r; for(r = oldAdpts.begin(); r != oldAdpts.end(); ++r) { - ReplicaGroupDescriptorSeq::const_iterator t; - for(t = newAdpts.begin(); t != newAdpts.end(); ++t) - { - if(t->id == r->id) - { - break; - } - } - for(ObjectDescriptorSeq::const_iterator o = r->objects.begin(); o != r->objects.end(); ++o) - { - _objectCache.remove(o->id); - } - if(t == newAdpts.end()) - { - _adapterCache.removeReplicaGroup(r->id); - } + ReplicaGroupDescriptorSeq::const_iterator t; + for(t = newAdpts.begin(); t != newAdpts.end(); ++t) + { + if(t->id == r->id) + { + break; + } + } + for(ObjectDescriptorSeq::const_iterator o = r->objects.begin(); o != r->objects.end(); ++o) + { + _objectCache.remove(o->id); + } + if(t == newAdpts.end()) + { + _adapterCache.removeReplicaGroup(r->id); + } } // @@ -1422,7 +1422,7 @@ Database::reload(const ApplicationHelper& oldApp, NodeDescriptorDict::const_iterator n; for(n = oldNodes.begin(); n != oldNodes.end(); ++n) { - _nodeCache.get(n->first)->removeDescriptor(application); + _nodeCache.get(n->first)->removeDescriptor(application); } // @@ -1431,7 +1431,7 @@ Database::reload(const ApplicationHelper& oldApp, const NodeDescriptorDict& newNodes = newApp.getInstance().nodes; for(n = newNodes.begin(); n != newNodes.end(); ++n) { - _nodeCache.get(n->first, true)->addDescriptor(application, n->second); + _nodeCache.get(n->first, true)->addDescriptor(application, n->second); } // @@ -1439,24 +1439,24 @@ Database::reload(const ApplicationHelper& oldApp, // for(r = newAdpts.begin(); r != newAdpts.end(); ++r) { - try - { - ReplicaGroupEntryPtr entry = ReplicaGroupEntryPtr::dynamicCast(_adapterCache.get(r->id)); - assert(entry); - entry->update(r->loadBalancing); - } - catch(const AdapterNotExistException&) - { - _adapterCache.addReplicaGroup(*r, application); - } - - for(ObjectDescriptorSeq::const_iterator o = r->objects.begin(); o != r->objects.end(); ++o) - { - ObjectInfo info; - info.type = o->type; - info.proxy = _communicator->stringToProxy(_communicator->identityToString(o->id) + "@" + r->id); - _objectCache.add(info, application); - } + try + { + ReplicaGroupEntryPtr entry = ReplicaGroupEntryPtr::dynamicCast(_adapterCache.get(r->id)); + assert(entry); + entry->update(r->loadBalancing); + } + catch(const AdapterNotExistException&) + { + _adapterCache.addReplicaGroup(*r, application); + } + + for(ObjectDescriptorSeq::const_iterator o = r->objects.begin(); o != r->objects.end(); ++o) + { + ObjectInfo info; + info.type = o->type; + info.proxy = _communicator->stringToProxy(_communicator->identityToString(o->id) + "@" + r->id); + _objectCache.add(info, application); + } } // @@ -1464,51 +1464,51 @@ Database::reload(const ApplicationHelper& oldApp, // for(vector::const_iterator q = load.begin(); q != load.end(); ++q) { - entries.push_back(_serverCache.add(*q)); + entries.push_back(_serverCache.add(*q)); } } void Database::finishApplicationUpdate(ServerEntrySeq& entries, - const ApplicationUpdateInfo& update, - const ApplicationInfo& oldApp, - const ApplicationDescriptor& newDesc, - AdminSessionI* session) + const ApplicationUpdateInfo& update, + const ApplicationInfo& oldApp, + const ApplicationDescriptor& newDesc, + AdminSessionI* session) { if(_master) { - // - // Load the servers on the nodes. If a server couldn't be - // deployed we unload the application and throw. - // - try - { - for_each(entries.begin(), entries.end(), IceUtil::voidMemFun(&ServerEntry::syncAndWait)); - } - catch(const DeploymentException& ex) - { - ApplicationUpdateInfo newUpdate; - { - Lock sync(*this); - entries.clear(); - ApplicationHelper previous(_communicator, newDesc); - ApplicationHelper helper(_communicator, oldApp.descriptor); - reload(previous, helper, entries, oldApp.uuid, oldApp.revision); - } - - try - { - for_each(entries.begin(), entries.end(), IceUtil::voidMemFun(&ServerEntry::syncAndWait)); - } - catch(const DeploymentException& ex) - { - Ice::Error err(_traceLevels->logger); - err << "failed to rollback previous application `" << oldApp.descriptor.name << "':\n" << ex.reason; - } - - finishUpdating(newDesc.name); - throw ex; - } + // + // Load the servers on the nodes. If a server couldn't be + // deployed we unload the application and throw. + // + try + { + for_each(entries.begin(), entries.end(), IceUtil::voidMemFun(&ServerEntry::syncAndWait)); + } + catch(const DeploymentException& ex) + { + ApplicationUpdateInfo newUpdate; + { + Lock sync(*this); + entries.clear(); + ApplicationHelper previous(_communicator, newDesc); + ApplicationHelper helper(_communicator, oldApp.descriptor); + reload(previous, helper, entries, oldApp.uuid, oldApp.revision); + } + + try + { + for_each(entries.begin(), entries.end(), IceUtil::voidMemFun(&ServerEntry::syncAndWait)); + } + catch(const DeploymentException& ex) + { + Ice::Error err(_traceLevels->logger); + err << "failed to rollback previous application `" << oldApp.descriptor.name << "':\n" << ex.reason; + } + + finishUpdating(newDesc.name); + throw ex; + } } // @@ -1516,24 +1516,24 @@ Database::finishApplicationUpdate(ServerEntrySeq& entries, // int serial; { - Lock sync(*this); - - ApplicationInfo info = oldApp; - info.updateTime = update.updateTime; - info.updateUser = update.updateUser; - info.revision = update.revision; - info.descriptor = newDesc; - - _applications.put(StringApplicationInfoDict::value_type(update.descriptor.name, info)); - ++_applicationSerial; + Lock sync(*this); + + ApplicationInfo info = oldApp; + info.updateTime = update.updateTime; + info.updateUser = update.updateUser; + info.revision = update.revision; + info.descriptor = newDesc; + + _applications.put(StringApplicationInfoDict::value_type(update.descriptor.name, info)); + ++_applicationSerial; - if(_traceLevels->application > 0) - { - Ice::Trace out(_traceLevels->logger, _traceLevels->applicationCat); - out << "updated application `" << update.descriptor.name << "'"; - } - - serial = _applicationObserverTopic->applicationUpdated(_applicationSerial, update); + if(_traceLevels->application > 0) + { + Ice::Trace out(_traceLevels->logger, _traceLevels->applicationCat); + out << "updated application `" << update.descriptor.name << "'"; + } + + serial = _applicationObserverTopic->applicationUpdated(_applicationSerial, update); } _applicationObserverTopic->waitForSyncedSubscribers(serial); @@ -1556,9 +1556,9 @@ Database::finishUpdating(const string& name) map >::iterator p = _updating.find(name); assert(p != _updating.end()); for(vector::const_iterator q = p->second.begin(); - q != p->second.end(); ++q) + q != p->second.end(); ++q) { - (*q)->ice_response(); + (*q)->ice_response(); } _updating.erase(p); diff --git a/cpp/src/IceGrid/Database.h b/cpp/src/IceGrid/Database.h index 339d52722e8..a02bbe02eb2 100644 --- a/cpp/src/IceGrid/Database.h +++ b/cpp/src/IceGrid/Database.h @@ -51,7 +51,7 @@ class Database : public IceUtil::Shared, public IceUtil::Monitor public: Database(const Ice::ObjectAdapterPtr&, const IceStorm::TopicManagerPrx&, const std::string&, const TraceLevelsPtr&, - const RegistryInfo&); + const RegistryInfo&); virtual ~Database(); std::string getInstanceName() const; @@ -133,7 +133,7 @@ private: void unload(const ApplicationHelper&, ServerEntrySeq&); void reload(const ApplicationHelper&, const ApplicationHelper&, ServerEntrySeq&, const std::string&, int); void finishApplicationUpdate(ServerEntrySeq&, const ApplicationUpdateInfo&, const ApplicationInfo&, - const ApplicationDescriptor&, AdminSessionI*); + const ApplicationDescriptor&, AdminSessionI*); void checkSessionLock(AdminSessionI*); diff --git a/cpp/src/IceGrid/DescriptorBuilder.cpp b/cpp/src/IceGrid/DescriptorBuilder.cpp index a5405ad18c9..eeb0c11c723 100644 --- a/cpp/src/IceGrid/DescriptorBuilder.cpp +++ b/cpp/src/IceGrid/DescriptorBuilder.cpp @@ -16,9 +16,9 @@ using namespace std; using namespace IceGrid; XmlAttributesHelper::XmlAttributesHelper(const IceXML::Attributes& attrs, - const Ice::LoggerPtr& logger, - const string& filename, - int line) : + const Ice::LoggerPtr& logger, + const string& filename, + int line) : _attributes(attrs), _logger(logger), _filename(filename), @@ -32,17 +32,17 @@ XmlAttributesHelper::checkUnknownAttributes() vector notUsed; for(map::const_iterator p = _attributes.begin(); p != _attributes.end(); ++p) { - if(_used.find(p->first) == _used.end()) - { - notUsed.push_back(p->first); - } + if(_used.find(p->first) == _used.end()) + { + notUsed.push_back(p->first); + } } if(!notUsed.empty()) { - ostringstream os; - os << "unknown attributes in <" << _filename << "> descriptor, line " << _line << ":\n" << toString(notUsed); - throw os.str(); + ostringstream os; + os << "unknown attributes in <" << _filename << "> descriptor, line " << _line << ":\n" << toString(notUsed); + throw os.str(); } } @@ -60,12 +60,12 @@ XmlAttributesHelper::operator()(const string& name) const IceXML::Attributes::const_iterator p = _attributes.find(name); if(p == _attributes.end()) { - throw "missing attribute '" + name + "'"; + throw "missing attribute '" + name + "'"; } string v = p->second; if(v.empty()) { - throw "attribute '" + name + "' is empty"; + throw "attribute '" + name + "' is empty"; } return v; } @@ -77,11 +77,11 @@ XmlAttributesHelper::operator()(const string& name, const string& def) const IceXML::Attributes::const_iterator p = _attributes.find(name); if(p == _attributes.end()) { - return def; + return def; } else { - return p->second; + return p->second; } } @@ -90,7 +90,7 @@ XmlAttributesHelper::asMap() const { for(map::const_iterator p = _attributes.begin(); p != _attributes.end(); ++p) { - _used.insert(p->first); + _used.insert(p->first); } return _attributes; } @@ -102,21 +102,21 @@ XmlAttributesHelper::asBool(const string& name) const IceXML::Attributes::const_iterator p = _attributes.find(name); if(p == _attributes.end()) { - throw "missing attribute '" + name + "'"; - return true; // Keep the compiler happy. + throw "missing attribute '" + name + "'"; + return true; // Keep the compiler happy. } else if(p->second == "true") { - return true; + return true; } else if(p->second == "false") { - return false; + return false; } else { - throw "invalid attribute `" + name + "': value is not 'false' or 'true'"; - return true; // Keep the compiler happy. + throw "invalid attribute `" + name + "': value is not 'false' or 'true'"; + return true; // Keep the compiler happy. } } @@ -127,20 +127,20 @@ XmlAttributesHelper::asBool(const string& name, bool def) const IceXML::Attributes::const_iterator p = _attributes.find(name); if(p == _attributes.end()) { - return def; + return def; } else if(p->second == "true") { - return true; + return true; } else if(p->second == "false") { - return false; + return false; } else { - throw "invalid attribute `" + name + "': value is not 'false' or 'true'"; - return true; // Keep the compiler happy. + throw "invalid attribute `" + name + "': value is not 'false' or 'true'"; + return true; // Keep the compiler happy. } } @@ -206,11 +206,11 @@ PropertySetDescriptorBuilder::addPropertySet(const XmlAttributesHelper& attrs) { if(attrs.contains("id") || !attrs.contains("refid")) { - throw "only can be a child of a element"; + throw "only can be a child of a element"; } if(!_descriptor.properties.empty()) { - throw " can't be defined after a element"; + throw " can't be defined after a element"; } _descriptor.references.push_back(attrs("refid")); _inPropertySetRef = true; @@ -221,15 +221,15 @@ PropertySetDescriptorBuilder::finish() { if(_inPropertySetRef) { - _inPropertySetRef = false; - return false; + _inPropertySetRef = false; + return false; } return true; } ApplicationDescriptorBuilder::ApplicationDescriptorBuilder(const Ice::CommunicatorPtr& communicator, - const XmlAttributesHelper& attrs, - const map& overrides) : + const XmlAttributesHelper& attrs, + const map& overrides) : _communicator(communicator), _overrides(overrides) { @@ -238,9 +238,9 @@ ApplicationDescriptorBuilder::ApplicationDescriptorBuilder(const Ice::Communicat } ApplicationDescriptorBuilder::ApplicationDescriptorBuilder(const Ice::CommunicatorPtr& communicator, - const ApplicationDescriptor& app, - const XmlAttributesHelper& attrs, - const map& overrides) : + const ApplicationDescriptor& app, + const XmlAttributesHelper& attrs, + const map& overrides) : _communicator(communicator), _descriptor(app), _overrides(overrides) @@ -274,8 +274,8 @@ ApplicationDescriptorBuilder::finishReplicaGroup() { if(!_descriptor.replicaGroups.back().loadBalancing) { - _descriptor.replicaGroups.back().loadBalancing = new RandomLoadBalancingPolicy(); - _descriptor.replicaGroups.back().loadBalancing->nReplicas = "0"; + _descriptor.replicaGroups.back().loadBalancing = new RandomLoadBalancingPolicy(); + _descriptor.replicaGroups.back().loadBalancing->nReplicas = "0"; } } @@ -286,25 +286,25 @@ ApplicationDescriptorBuilder::setLoadBalancing(const XmlAttributesHelper& attrs) string type = attrs("type"); if(type == "random") { - policy = new RandomLoadBalancingPolicy(); + policy = new RandomLoadBalancingPolicy(); } else if(type == "ordered") { - policy = new OrderedLoadBalancingPolicy(); + policy = new OrderedLoadBalancingPolicy(); } else if(type == "round-robin") { - policy = new RoundRobinLoadBalancingPolicy(); + policy = new RoundRobinLoadBalancingPolicy(); } else if(type == "adaptive") { - AdaptiveLoadBalancingPolicyPtr alb = new AdaptiveLoadBalancingPolicy(); - alb->loadSample = attrs("load-sample", "1"); - policy = alb; + AdaptiveLoadBalancingPolicyPtr alb = new AdaptiveLoadBalancingPolicy(); + alb->loadSample = attrs("load-sample", "1"); + policy = alb; } else { - throw "invalid load balancing policy `" + type + "'"; + throw "invalid load balancing policy `" + type + "'"; } policy->nReplicas = attrs("n-replicas", "1"); _descriptor.replicaGroups.back().loadBalancing = policy; @@ -324,7 +324,7 @@ ApplicationDescriptorBuilder::addObject(const XmlAttributesHelper& attrs) object.id = _communicator->stringToIdentity(attrs("identity")); if(attrs.contains("property")) { - throw "property attribute is not allowed in object descriptors from a replica group"; + throw "property attribute is not allowed in object descriptors from a replica group"; } _descriptor.replicaGroups.back().objects.push_back(object); } @@ -334,11 +334,11 @@ ApplicationDescriptorBuilder::addVariable(const XmlAttributesHelper& attrs) { if(!isOverride(attrs("name"))) { - _descriptor.variables[attrs("name")] = attrs("value", ""); + _descriptor.variables[attrs("name")] = attrs("value", ""); } else { - attrs.contains("value"); // NOTE: prevents warning about "value" not being used. + attrs.contains("value"); // NOTE: prevents warning about "value" not being used. } } @@ -381,11 +381,11 @@ ApplicationDescriptorBuilder::addServerTemplate(const string& id, const Template { if(!templ.descriptor) { - throw "invalid server template `" + id + "': server definition is missing"; + throw "invalid server template `" + id + "': server definition is missing"; } if(!_descriptor.serverTemplates.insert(make_pair(id, templ)).second) { - throw "duplicate server template `" + id + "'"; + throw "duplicate server template `" + id + "'"; } } @@ -394,11 +394,11 @@ ApplicationDescriptorBuilder::addServiceTemplate(const string& id, const Templat { if(!templ.descriptor) { - throw "invalid service template `" + id + "': service definition is missing"; + throw "invalid service template `" + id + "': service definition is missing"; } if(!_descriptor.serviceTemplates.insert(make_pair(id, templ)).second) { - throw "duplicate service template `" + id + "'"; + throw "duplicate service template `" + id + "'"; } } @@ -407,7 +407,7 @@ ApplicationDescriptorBuilder::addPropertySet(const string& id, const PropertySet { if(!_descriptor.propertySets.insert(make_pair(id, desc)).second) { - throw "duplicate property set `" + id + "'"; + throw "duplicate property set `" + id + "'"; } } @@ -442,7 +442,7 @@ ServerInstanceDescriptorBuilder::createPropertySet(const XmlAttributesHelper& at string service; if(attrs.contains("service")) { - service = attrs("service"); // Can't be empty. + service = attrs("service"); // Can't be empty. } PropertySetDescriptorBuilder* builder = new PropertySetDescriptorBuilder(); @@ -462,8 +462,8 @@ ServerInstanceDescriptorBuilder::addPropertySet(const string& service, const Pro } NodeDescriptorBuilder::NodeDescriptorBuilder(ApplicationDescriptorBuilder& app, - const NodeDescriptor& desc, - const XmlAttributesHelper& attrs) : + const NodeDescriptor& desc, + const XmlAttributesHelper& attrs) : _application(app), _descriptor(desc) { @@ -504,11 +504,11 @@ NodeDescriptorBuilder::addVariable(const XmlAttributesHelper& attrs) { if(!_application.isOverride(attrs("name"))) { - _descriptor.variables[attrs("name")] = attrs("value", ""); + _descriptor.variables[attrs("name")] = attrs("value", ""); } else { - attrs.contains("value"); // NOTE: prevents warning about "value" not being used. + attrs.contains("value"); // NOTE: prevents warning about "value" not being used. } } @@ -529,7 +529,7 @@ NodeDescriptorBuilder::addPropertySet(const string& id, const PropertySetDescrip { if(!_descriptor.propertySets.insert(make_pair(id, desc)).second) { - throw "duplicate property set `" + id + "'"; + throw "duplicate property set `" + id + "'"; } } @@ -540,8 +540,8 @@ NodeDescriptorBuilder::setDescription(const string& description) } TemplateDescriptorBuilder::TemplateDescriptorBuilder(ApplicationDescriptorBuilder& application, - const XmlAttributesHelper& attrs, - bool serviceTemplate) : + const XmlAttributesHelper& attrs, + bool serviceTemplate) : _application(application), _serviceTemplate(serviceTemplate), _id(attrs("id")) @@ -554,13 +554,13 @@ TemplateDescriptorBuilder::addParameter(const XmlAttributesHelper& attrs) if(find(_descriptor.parameters.begin(), _descriptor.parameters.end(), attrs("name")) != _descriptor.parameters.end()) { - throw "duplicate parameter `" + attrs("name") + "'"; + throw "duplicate parameter `" + attrs("name") + "'"; } _descriptor.parameters.push_back(attrs("name")); if(attrs.contains("default")) { - _descriptor.parameterDefaults.insert(make_pair(attrs("name"), attrs("default", ""))); + _descriptor.parameterDefaults.insert(make_pair(attrs("name"), attrs("default", ""))); } } @@ -575,7 +575,7 @@ TemplateDescriptorBuilder::createServer(const XmlAttributesHelper& attrs) { if(_serviceTemplate) { - throw " element can't be a child of "; + throw " element can't be a child of "; } return new ServerDescriptorBuilder(_application.getCommunicator(), attrs); } @@ -585,7 +585,7 @@ TemplateDescriptorBuilder::createIceBox(const XmlAttributesHelper& attrs) { if(_serviceTemplate) { - throw " element can't be a child of "; + throw " element can't be a child of "; } return new IceBoxDescriptorBuilder(_application.getCommunicator(), attrs); } @@ -595,7 +595,7 @@ TemplateDescriptorBuilder::createService(const XmlAttributesHelper& attrs) { if(!_serviceTemplate) { - throw " element can't be a child of "; + throw " element can't be a child of "; } return new ServiceDescriptorBuilder(_application.getCommunicator(), attrs); } @@ -621,7 +621,7 @@ CommunicatorDescriptorBuilder::finish() // before references to property sets. // _descriptor->propertySet.properties.insert(_descriptor->propertySet.properties.begin(), - _hiddenProperties.begin(), _hiddenProperties.end()); + _hiddenProperties.begin(), _hiddenProperties.end()); } void @@ -660,23 +660,23 @@ CommunicatorDescriptorBuilder::addAdapter(const XmlAttributesHelper& attrs) desc.name = attrs("name"); if(attrs.contains("id")) { - desc.id = attrs("id"); + desc.id = attrs("id"); } else { - string fqn = "${server}"; - if(ServiceDescriptorPtr::dynamicCast(_descriptor)) - { - fqn += ".${service}"; - } - desc.id = fqn + "." + desc.name; + string fqn = "${server}"; + if(ServiceDescriptorPtr::dynamicCast(_descriptor)) + { + fqn += ".${service}"; + } + desc.id = fqn + "." + desc.name; } desc.replicaGroupId = attrs("replica-group", ""); desc.priority = attrs("priority", ""); desc.registerProcess = attrs.asBool("register-process", false); if(desc.id == "") { - throw "empty `id' for adapter `" + desc.name + "'"; + throw "empty `id' for adapter `" + desc.name + "'"; } desc.serverLifetime = attrs.asBool("server-lifetime", true); _descriptor->adapters.push_back(desc); @@ -698,7 +698,7 @@ CommunicatorDescriptorBuilder::addObject(const XmlAttributesHelper& attrs) object.id = _communicator->stringToIdentity(attrs("identity")); if(attrs.contains("property")) { - addProperty(_hiddenProperties, attrs("property"), attrs("identity")); + addProperty(_hiddenProperties, attrs("property"), attrs("identity")); } _descriptor->adapters.back().objects.push_back(object); } @@ -711,7 +711,7 @@ CommunicatorDescriptorBuilder::addAllocatable(const XmlAttributesHelper& attrs) object.id = _communicator->stringToIdentity(attrs("identity")); if(attrs.contains("property")) { - addProperty(_hiddenProperties, attrs("property"), attrs("identity")); + addProperty(_hiddenProperties, attrs("property"), attrs("identity")); } _descriptor->adapters.back().allocatables.push_back(object); } @@ -726,28 +726,28 @@ CommunicatorDescriptorBuilder::addDbEnv(const XmlAttributesHelper& attrs) DbEnvDescriptorSeq::iterator p; for(p = _descriptor->dbEnvs.begin(); p != _descriptor->dbEnvs.end(); ++p) { - // - // We are re-opening the dbenv element to define more properties. - // - if(p->name == desc.name) - { - break; - } + // + // We are re-opening the dbenv element to define more properties. + // + if(p->name == desc.name) + { + break; + } } if(p != _descriptor->dbEnvs.end()) { - // - // Remove the previously defined dbenv, we'll add it back again when - // the dbenv element end tag is reached. - // - desc = *p; - _descriptor->dbEnvs.erase(p); - } + // + // Remove the previously defined dbenv, we'll add it back again when + // the dbenv element end tag is reached. + // + desc = *p; + _descriptor->dbEnvs.erase(p); + } if(desc.dbHome.empty()) { - desc.dbHome = attrs("home", ""); + desc.dbHome = attrs("home", ""); } _descriptor->dbEnvs.push_back(desc); @@ -758,9 +758,9 @@ CommunicatorDescriptorBuilder::addDbEnvProperty(const XmlAttributesHelper& attrs { if(!_descriptor->dbEnvs.back().dbHome.empty()) { - throw "can't add property to the database environment:\n" - "properties are only allowed if the database\n" - "environment home directory is managed by the node"; + throw "can't add property to the database environment:\n" + "properties are only allowed if the database\n" + "environment home directory is managed by the node"; } PropertyDescriptor prop; @@ -780,7 +780,7 @@ CommunicatorDescriptorBuilder::addLog(const XmlAttributesHelper& attrs) { if(attrs.contains("property")) { - addProperty(_hiddenProperties, attrs("property"), attrs("path")); + addProperty(_hiddenProperties, attrs("property"), attrs("path")); } _descriptor->logs.push_back(attrs("path")); } @@ -819,7 +819,7 @@ ServiceInstanceDescriptorBuilder::addPropertySet(const PropertySetDescriptor& de } ServerDescriptorBuilder::ServerDescriptorBuilder(const Ice::CommunicatorPtr& communicator, - const XmlAttributesHelper& attrs) : + const XmlAttributesHelper& attrs) : CommunicatorDescriptorBuilder(communicator) { init(new ServerDescriptor(), attrs); @@ -898,7 +898,7 @@ ServerDescriptorBuilder::addDistributionDirectory(const string& directory) } IceBoxDescriptorBuilder::IceBoxDescriptorBuilder(const Ice::CommunicatorPtr& communicator, - const XmlAttributesHelper& attrs) : + const XmlAttributesHelper& attrs) : ServerDescriptorBuilder(communicator) { init(new IceBoxDescriptor(), attrs); @@ -916,18 +916,18 @@ IceBoxDescriptorBuilder::finish() { if(getProperty(_descriptor->propertySet.properties, "IceBox.InstanceName").empty()) { - _hiddenProperties.push_back(createProperty("IceBox.InstanceName", "${server}")); + _hiddenProperties.push_back(createProperty("IceBox.InstanceName", "${server}")); } if(_descriptor->adapters.empty()) { - if(getProperty(_descriptor->propertySet.properties, "Ice.OA.IceBox.ServiceManager.Endpoints").empty()) - { - _hiddenProperties.push_back(createProperty("Ice.OA.IceBox.ServiceManager.Endpoints", "tcp -h 127.0.0.1")); - } - if(getProperty(_descriptor->propertySet.properties, "Ice.OA.IceBox.ServiceManager.RegisterProcess").empty()) - { - _hiddenProperties.push_back(createProperty("Ice.OA.IceBox.ServiceManager.RegisterProcess", "1")); - } + if(getProperty(_descriptor->propertySet.properties, "Ice.OA.IceBox.ServiceManager.Endpoints").empty()) + { + _hiddenProperties.push_back(createProperty("Ice.OA.IceBox.ServiceManager.Endpoints", "tcp -h 127.0.0.1")); + } + if(getProperty(_descriptor->propertySet.properties, "Ice.OA.IceBox.ServiceManager.RegisterProcess").empty()) + { + _hiddenProperties.push_back(createProperty("Ice.OA.IceBox.ServiceManager.RegisterProcess", "1")); + } } ServerDescriptorBuilder::finish(); @@ -950,7 +950,7 @@ IceBoxDescriptorBuilder::addAdapter(const XmlAttributesHelper& attrs) { if(attrs("name") != "IceBox.ServiceManager") { - throw " element can't be a child of an element"; + throw " element can't be a child of an element"; } ServerDescriptorBuilder::addAdapter(attrs); @@ -978,7 +978,7 @@ IceBoxDescriptorBuilder::addService(const ServiceDescriptorPtr& desc) } ServiceDescriptorBuilder::ServiceDescriptorBuilder(const Ice::CommunicatorPtr& communicator, - const XmlAttributesHelper& attrs) : + const XmlAttributesHelper& attrs) : CommunicatorDescriptorBuilder(communicator) { init(new ServiceDescriptor(), attrs); diff --git a/cpp/src/IceGrid/DescriptorBuilder.h b/cpp/src/IceGrid/DescriptorBuilder.h index 04f0ca60d4e..532df9e61df 100644 --- a/cpp/src/IceGrid/DescriptorBuilder.h +++ b/cpp/src/IceGrid/DescriptorBuilder.h @@ -89,9 +89,9 @@ class ApplicationDescriptorBuilder : public DescriptorBuilder public: ApplicationDescriptorBuilder(const Ice::CommunicatorPtr&, const XmlAttributesHelper&, - const std::map&); + const std::map&); ApplicationDescriptorBuilder(const Ice::CommunicatorPtr&, const ApplicationDescriptor&, const XmlAttributesHelper&, - const std::map&); + const std::map&); const ApplicationDescriptor& getDescriptor() const; diff --git a/cpp/src/IceGrid/DescriptorHelper.cpp b/cpp/src/IceGrid/DescriptorHelper.cpp index 1e540b5938f..f1cf78d4367 100644 --- a/cpp/src/IceGrid/DescriptorHelper.cpp +++ b/cpp/src/IceGrid/DescriptorHelper.cpp @@ -25,7 +25,7 @@ struct GetReplicaGroupId : unary_function(lhs.objects.begin(), lhs.objects.end()) != - set(rhs.objects.begin(), rhs.objects.end())) - { - return false; - } - if(lhs.loadBalancing && rhs.loadBalancing) - { - if(lhs.loadBalancing->ice_id() != rhs.loadBalancing->ice_id()) - { - return false; - } - if(lhs.loadBalancing->nReplicas != rhs.loadBalancing->nReplicas) - { - return false; - } - AdaptiveLoadBalancingPolicyPtr alhs = AdaptiveLoadBalancingPolicyPtr::dynamicCast(lhs.loadBalancing); - AdaptiveLoadBalancingPolicyPtr arhs = AdaptiveLoadBalancingPolicyPtr::dynamicCast(rhs.loadBalancing); - if(alhs && arhs && alhs->loadSample != arhs->loadSample) - { - return false; - } - } - else if(lhs.loadBalancing || rhs.loadBalancing) - { - return false; - } - - return true; + if(lhs.id != rhs.id) + { + return false; + } + if(set(lhs.objects.begin(), lhs.objects.end()) != + set(rhs.objects.begin(), rhs.objects.end())) + { + return false; + } + if(lhs.loadBalancing && rhs.loadBalancing) + { + if(lhs.loadBalancing->ice_id() != rhs.loadBalancing->ice_id()) + { + return false; + } + if(lhs.loadBalancing->nReplicas != rhs.loadBalancing->nReplicas) + { + return false; + } + AdaptiveLoadBalancingPolicyPtr alhs = AdaptiveLoadBalancingPolicyPtr::dynamicCast(lhs.loadBalancing); + AdaptiveLoadBalancingPolicyPtr arhs = AdaptiveLoadBalancingPolicyPtr::dynamicCast(rhs.loadBalancing); + if(alhs && arhs && alhs->loadSample != arhs->loadSample) + { + return false; + } + } + else if(lhs.loadBalancing || rhs.loadBalancing) + { + return false; + } + + return true; } }; @@ -133,18 +133,18 @@ getSeqUpdatedEltsWithEq(const Seq& lseq, const Seq& rseq, GetKeyFunc func, EqFun Seq result; for(typename Seq::const_iterator p = rseq.begin(); p != rseq.end(); ++p) { - typename Seq::const_iterator q = lseq.begin(); - for(; q != lseq.end(); ++q) - { - if(func(*p) == func(*q)) - { - break; - } - } - if(q == lseq.end() || !eq(*p, *q)) - { - result.push_back(*p); - } + typename Seq::const_iterator q = lseq.begin(); + for(; q != lseq.end(); ++q) + { + if(func(*p) == func(*q)) + { + break; + } + } + if(q == lseq.end() || !eq(*p, *q)) + { + result.push_back(*p); + } } return result; } @@ -155,18 +155,18 @@ getSeqRemovedElts(const Seq& lseq, const Seq& rseq, GetKeyFunc func) Ice::StringSeq removed; for(typename Seq::const_iterator p = lseq.begin(); p != lseq.end(); ++p) { - typename Seq::const_iterator q; - for(q = rseq.begin(); q != rseq.end(); ++q) - { - if(func(*p) == func(*q)) - { - break; - } - } - if(q == rseq.end()) - { - removed.push_back(func(*p)); - } + typename Seq::const_iterator q; + for(q = rseq.begin(); q != rseq.end(); ++q) + { + if(func(*p) == func(*q)) + { + break; + } + } + if(q == rseq.end()) + { + removed.push_back(func(*p)); + } } return removed; } @@ -178,21 +178,21 @@ updateSeqElts(const Seq& seq, const Seq& update, const Ice::StringSeq& remove, G set removed(remove.begin(), remove.end()); for(typename Seq::const_iterator p = seq.begin(); p != seq.end(); ++p) { - if(removed.find(func(*p)) == removed.end()) - { - typename Seq::const_iterator q = update.begin(); - for(; q != update.end(); ++q) - { - if(func(*p) == func(*q)) - { - break; - } - } - if(q == update.end()) - { - result.push_back(*p); - } - } + if(removed.find(func(*p)) == removed.end()) + { + typename Seq::const_iterator q = update.begin(); + for(; q != update.end(); ++q) + { + if(func(*p) == func(*q)) + { + break; + } + } + if(q == update.end()) + { + result.push_back(*p); + } + } } return result; } @@ -213,11 +213,11 @@ getDictUpdatedEltsWithEq(const Dict& ldict, const Dict& rdict, EqFunc eq) Dict result; for(typename Dict::const_iterator p = rdict.begin(); p != rdict.end(); ++p) { - typename Dict::const_iterator q = ldict.find(p->first); - if(q == ldict.end() || !eq(p->second, q->second)) - { - result.insert(*p); - } + typename Dict::const_iterator q = ldict.find(p->first); + if(q == ldict.end() || !eq(p->second, q->second)) + { + result.insert(*p); + } } return result; } @@ -228,10 +228,10 @@ getDictRemovedElts(const Dict& ldict, const Dict& rdict) Ice::StringSeq removed; for(typename Dict::const_iterator p = ldict.begin(); p != ldict.end(); ++p) { - if(rdict.find(p->first) == rdict.end()) - { - removed.push_back(p->first); - } + if(rdict.find(p->first) == rdict.end()) + { + removed.push_back(p->first); + } } return removed; } @@ -242,11 +242,11 @@ updateDictElts(const Dict& dict, const Dict& update, const Ice::StringSeq& remov Dict result = dict; for(Ice::StringSeq::const_iterator p = remove.begin(); p != remove.end(); ++p) { - result.erase(*p); + result.erase(*p); } for(typename Dict::const_iterator q = update.begin(); q != update.end(); ++q) { - result[q->first] = q->second; + result[q->first] = q->second; } return result; } @@ -281,63 +281,63 @@ Resolver::Resolver(const ApplicationDescriptor& app, const Ice::CommunicatorPtr& for(StringStringDict::const_iterator v = _variables.begin(); v != _variables.end(); ++v) { - if(v->first == "") - { - exception("empty variable name"); - } + if(v->first == "") + { + exception("empty variable name"); + } } TemplateDescriptorDict::const_iterator t; for(t = _application->serverTemplates.begin(); t != _application->serverTemplates.end(); ++t) { - if(t->first == "") - { - exception("empty server template id"); - } - if(!t->second.descriptor) - { - exception("invalid server template `" + t->first + "': server definition is empty"); - } - - Ice::StringSeq params = t->second.parameters; - sort(params.begin(), params.end()); - Ice::StringSeq wdups = params; - Ice::StringSeq dups; - set_difference(wdups.begin(), wdups.end(), params.begin(), unique(params.begin(), params.end()), - back_inserter(dups)); - if(!dups.empty()) - { - dups.erase(unique(dups.begin(), dups.end()), dups.end()); - exception("invalid server template `" + t->first + "': duplicate parameters " + toString(dups)); - } + if(t->first == "") + { + exception("empty server template id"); + } + if(!t->second.descriptor) + { + exception("invalid server template `" + t->first + "': server definition is empty"); + } + + Ice::StringSeq params = t->second.parameters; + sort(params.begin(), params.end()); + Ice::StringSeq wdups = params; + Ice::StringSeq dups; + set_difference(wdups.begin(), wdups.end(), params.begin(), unique(params.begin(), params.end()), + back_inserter(dups)); + if(!dups.empty()) + { + dups.erase(unique(dups.begin(), dups.end()), dups.end()); + exception("invalid server template `" + t->first + "': duplicate parameters " + toString(dups)); + } } for(t = _application->serviceTemplates.begin(); t != _application->serviceTemplates.end(); ++t) { - if(t->first == "") - { - exception("empty service template id"); - } - if(!t->second.descriptor) - { - exception("invalid service template `" + t->first + "': service definition is empty"); - } - Ice::StringSeq params = t->second.parameters; - sort(params.begin(), params.end()); - Ice::StringSeq wdups = params; - Ice::StringSeq dups; - set_difference(wdups.begin(), wdups.end(), params.begin(), unique(params.begin(), params.end()), - back_inserter(dups)); - if(!dups.empty()) - { - dups.erase(unique(dups.begin(), dups.end()), dups.end()); - exception("invalid server template `" + t->first + "': duplicate parameters " + toString(dups)); - } + if(t->first == "") + { + exception("empty service template id"); + } + if(!t->second.descriptor) + { + exception("invalid service template `" + t->first + "': service definition is empty"); + } + Ice::StringSeq params = t->second.parameters; + sort(params.begin(), params.end()); + Ice::StringSeq wdups = params; + Ice::StringSeq dups; + set_difference(wdups.begin(), wdups.end(), params.begin(), unique(params.begin(), params.end()), + back_inserter(dups)); + if(!dups.empty()) + { + dups.erase(unique(dups.begin(), dups.end()), dups.end()); + exception("invalid server template `" + t->first + "': duplicate parameters " + toString(dups)); + } } } Resolver::Resolver(const Resolver& resolve, - const map& values, - bool params) : + const map& values, + bool params) : _application(resolve._application), _communicator(resolve._communicator), _escape(resolve._escape), @@ -351,20 +351,20 @@ Resolver::Resolver(const Resolver& resolve, { if(params) { - checkReserved("parameter", values); + checkReserved("parameter", values); } else { - _variables.insert(resolve._variables.begin(), resolve._variables.end()); - checkReserved("variable", values); + _variables.insert(resolve._variables.begin(), resolve._variables.end()); + checkReserved("variable", values); } for(StringStringDict::const_iterator v = _variables.begin(); v != _variables.end(); ++v) { - if(v->first == "") - { - exception("empty variable name"); - } + if(v->first == "") + { + exception("empty variable name"); + } } } @@ -390,40 +390,40 @@ Resolver::operator()(const string& value, const string& name, bool allowEmpty) c { try { - string val; - try - { - val = substitute(value, true, true); - } - catch(const string& reason) - { - throw "invalid variable `" + value + "': " + reason; - } - catch(const char* reason) - { - throw "invalid variable `" + value + "': " + reason; - } - - if(!allowEmpty) - { - if(value.empty()) - { - throw "empty string"; - } - else if(val.empty()) - { - throw "the value of `" + value + "' is an empty string"; - } - } - return val; + string val; + try + { + val = substitute(value, true, true); + } + catch(const string& reason) + { + throw "invalid variable `" + value + "': " + reason; + } + catch(const char* reason) + { + throw "invalid variable `" + value + "': " + reason; + } + + if(!allowEmpty) + { + if(value.empty()) + { + throw "empty string"; + } + else if(val.empty()) + { + throw "the value of `" + value + "' is an empty string"; + } + } + return val; } catch(const string& reason) { - exception("invalid value for attribute `" + name + "':\n" + reason); + exception("invalid value for attribute `" + name + "':\n" + reason); } catch(const char* reason) { - exception("invalid value for attribute `" + name + "':\n" + reason); + exception("invalid value for attribute `" + name + "':\n" + reason); } return ""; // To prevent compiler warning. } @@ -434,7 +434,7 @@ Resolver::operator()(const Ice::StringSeq& values, const string& name) const Ice::StringSeq result; for(Ice::StringSeq::const_iterator p = values.begin(); p != values.end(); ++p) { - result.push_back(operator()(*p, name)); + result.push_back(operator()(*p, name)); } return result; } @@ -454,10 +454,10 @@ Resolver::operator()(const PropertyDescriptorSeq& properties, const string& name PropertyDescriptorSeq result; for(PropertyDescriptorSeq::const_iterator q = properties.begin(); q != properties.end(); ++q) { - PropertyDescriptor prop; - prop.name = operator()(q->name, name + " name"); - prop.value = operator()(q->value, name + " value"); - result.push_back(prop); + PropertyDescriptor prop; + prop.name = operator()(q->name, name + " name"); + prop.value = operator()(q->value, name + " value"); + result.push_back(prop); } return result; } @@ -469,10 +469,10 @@ Resolver::operator()(const PropertySetDescriptorDict& propertySets) const PropertySetDescriptorDict::const_iterator ps; for(ps = propertySets.begin(); ps != propertySets.end(); ++ps) { - PropertySetDescriptor desc; - desc.references = operator()(ps->second.references, "property set `" + ps->first + "' reference"); - desc.properties = operator()(ps->second.properties, "property set `" + ps->first + "' property"); - result.insert(make_pair(ps->first, desc)); + PropertySetDescriptor desc; + desc.references = operator()(ps->second.references, "property set `" + ps->first + "' reference"); + desc.properties = operator()(ps->second.properties, "property set `" + ps->first + "' property"); + result.insert(make_pair(ps->first, desc)); } return result; } @@ -483,10 +483,10 @@ Resolver::operator()(const ObjectDescriptorSeq& objects, const string& type) con ObjectDescriptorSeq result; for(ObjectDescriptorSeq::const_iterator q = objects.begin(); q != objects.end(); ++q) { - ObjectDescriptor obj; - obj.type = operator()(q->type, type + " object type"); - obj.id = operator()(q->id, type + " object identity"); - result.push_back(obj); + ObjectDescriptor obj; + obj.type = operator()(q->type, type + " object type"); + obj.id = operator()(q->id, type + " object identity"); + result.push_back(obj); } return result; } @@ -499,7 +499,7 @@ Resolver::operator()(const Ice::Identity& value, const string& name) const Ice::Identity id = _communicator->stringToIdentity(str); if(id.name.empty()) { - exception("invalid object identity `" + _communicator->identityToString(value) + "': name empty"); + exception("invalid object identity `" + _communicator->identityToString(value) + "': name empty"); } return id; } @@ -520,20 +520,20 @@ Resolver::asInt(const string& value, const string& name) const string v = operator()(value, name); if(!v.empty()) { - string::size_type beg = v.find_first_not_of(' '); - string::size_type end = v.find_last_not_of(' '); - v = v.substr(beg == string::npos ? 0 : beg, end == string::npos ? v.length() - 1 : end - beg + 1); + string::size_type beg = v.find_first_not_of(' '); + string::size_type end = v.find_last_not_of(' '); + v = v.substr(beg == string::npos ? 0 : beg, end == string::npos ? v.length() - 1 : end - beg + 1); - int val; - istringstream is(v); - if(!(is >> val) || !is.eof()) - { - exception("invalid value `" + value + "' for `" + name + "':\nnot an integer"); - } + int val; + istringstream is(v); + if(!(is >> val) || !is.eof()) + { + exception("invalid value `" + value + "' for `" + name + "':\nnot an integer"); + } - ostringstream os; - os << val; - v = os.str(); + ostringstream os; + os << val; + v = os.str(); } return v; } @@ -544,16 +544,16 @@ Resolver::asFloat(const string& value, const string& name) const string v = operator()(value, name); if(!v.empty()) { - string::size_type beg = v.find_first_not_of(' '); - string::size_type end = v.find_last_not_of(' '); - v = v.substr(beg == string::npos ? 0 : beg, end == string::npos ? v.length() - 1 : end - beg + 1); + string::size_type beg = v.find_first_not_of(' '); + string::size_type end = v.find_last_not_of(' '); + v = v.substr(beg == string::npos ? 0 : beg, end == string::npos ? v.length() - 1 : end - beg + 1); - float val; - istringstream is(v); - if(!(is >> val) || !is.eof()) - { - exception("invalid value `" + value + "' for `" + name + "':\nnot a float"); - } + float val; + istringstream is(v); + if(!(is >> val) || !is.eof()) + { + exception("invalid value `" + value + "' for `" + name + "':\nnot a float"); + } } return v; } @@ -563,38 +563,38 @@ Resolver::asId(const string& value, const string& name, bool allowEmpty) const { try { - if(!allowEmpty && value.empty()) - { - throw "empty string"; - } - - string val; - try - { - val = substitute(value, true, false); - } - catch(const string& reason) - { - throw "invalid variable `" + value + "':\n" + reason; - } - catch(const char* reason) - { - throw "invalid variable `" + value + "':\n" + reason; - } - - if(!allowEmpty && val.empty()) - { - throw "the value of `" + value + "' is an empty string"; - } - return val; + if(!allowEmpty && value.empty()) + { + throw "empty string"; + } + + string val; + try + { + val = substitute(value, true, false); + } + catch(const string& reason) + { + throw "invalid variable `" + value + "':\n" + reason; + } + catch(const char* reason) + { + throw "invalid variable `" + value + "':\n" + reason; + } + + if(!allowEmpty && val.empty()) + { + throw "the value of `" + value + "' is an empty string"; + } + return val; } catch(const string& reason) { - exception("invalid value for attribute `" + name + "':\n" + reason); + exception("invalid value for attribute `" + name + "':\n" + reason); } catch(const char* reason) { - exception("invalid value for attribute `" + name + "':\n" + reason); + exception("invalid value for attribute `" + name + "':\n" + reason); } return ""; // To prevent compiler warning. } @@ -611,15 +611,15 @@ Resolver::setContext(const string& context) { try { - _context = substitute(context, true, true); + _context = substitute(context, true, true); } catch(const string& reason) { - exception(reason); + exception(reason); } catch(const char* reason) { - exception(reason); + exception(reason); } } @@ -631,10 +631,10 @@ Resolver::addPropertySets(const PropertySetDescriptorDict& propertySets) PropertySetDescriptorDict::const_iterator p; for(p = propertySets.begin(); p != propertySets.end(); ++p) { - if(!_propertySets.insert(*p).second) - { - exception("property set with id `" + p->first + "' is already defined at this scope"); - } + if(!_propertySets.insert(*p).second) + { + exception("property set with id `" + p->first + "' is already defined at this scope"); + } } _propertySets.insert(oldPropertySets.begin(), oldPropertySets.end()); @@ -643,7 +643,7 @@ Resolver::addPropertySets(const PropertySetDescriptorDict& propertySets) // for(p = propertySets.begin(); p != propertySets.end(); ++p) { - getProperties(p->second.references); + getProperties(p->second.references); } } @@ -653,7 +653,7 @@ Resolver::getPropertySet(const string& id) const PropertySetDescriptorDict::const_iterator p = _propertySets.find(id); if(p == _propertySets.end()) { - exception("invalid reference to property set, property set `" + id + "' doesn't exist"); + exception("invalid reference to property set, property set `" + id + "' doesn't exist"); } return p->second; } @@ -684,7 +684,7 @@ Resolver::getServerTemplate(const string& tmpl) const TemplateDescriptorDict::const_iterator p = _application->serverTemplates.find(tmpl); if(p == _application->serverTemplates.end()) { - throw DeploymentException("unknown server template `" + tmpl + "'"); + throw DeploymentException("unknown server template `" + tmpl + "'"); } return p->second; } @@ -696,7 +696,7 @@ Resolver::getServiceTemplate(const string& tmpl) const TemplateDescriptorDict::const_iterator p = _application->serviceTemplates.find(tmpl); if(p == _application->serviceTemplates.end()) { - throw DeploymentException("unknown service template `" + tmpl + "'"); + throw DeploymentException("unknown service template `" + tmpl + "'"); } return p->second; } @@ -706,22 +706,22 @@ Resolver::hasReplicaGroup(const string& id) const { if(!_application) { - // - // If we don't know the application descrpitor we assume that - // the replica group exists (this is possible if the resolver - // wasn't built from an application helper, that's the case if - // it's built from NodeCache just to resolve ${node.*} and - // ${session.*} variables. - // - return true; + // + // If we don't know the application descrpitor we assume that + // the replica group exists (this is possible if the resolver + // wasn't built from an application helper, that's the case if + // it's built from NodeCache just to resolve ${node.*} and + // ${session.*} variables. + // + return true; } ReplicaGroupDescriptorSeq::const_iterator p; for(p = _application->replicaGroups.begin(); p != _application->replicaGroups.end(); ++p) { - if(p->id == id) - { - return true; - } + if(p->id == id) + { + return true; + } } return false; } @@ -735,66 +735,66 @@ Resolver::substitute(const string& v, bool useParams, bool useIgnored) const while((beg = value.find("${", beg)) != string::npos) { - if(beg > 0 && value[beg - 1] == '$') - { - string::size_type escape = beg - 1; - while(escape > 0 && value[escape - 1] == '$') - { - --escape; - } - - if((beg - escape) % 2) - { - if(_escape) - { - value.replace(escape, beg - escape, (beg - escape) / 2, '$'); - } - ++beg; - continue; - } - else - { - value.replace(escape, beg - escape, (beg - escape) / 2, '$'); - beg -= (beg - escape) / 2; - } - } - - end = value.find("}", beg); - if(end == string::npos) - { - throw "malformed variable name `" + value + "'"; - } - - // - // Get the name of the variable and get its value if the - // variable is not currently ignored (in which case we do - // nothing, the variable will be substituted later). If the - // name refered to a parameter we don't do any recursive - // substitution: the parameter value is computed at the point - // of definition. - // - string name = value.substr(beg + 2, end - beg - 2); - if(_ignore.find(name) != _ignore.end()) - { - if(useIgnored) - { - ++beg; - continue; - } - else - { - throw "use of the `" + name + "' variable is now allowed here"; - } - } - - bool param; - string val = getVariable(name, useParams, param); - if(!param) - { - val = substitute(val, false, useIgnored); // Recursive resolution - } - value.replace(beg, end - beg + 1, val); - beg += val.length(); + if(beg > 0 && value[beg - 1] == '$') + { + string::size_type escape = beg - 1; + while(escape > 0 && value[escape - 1] == '$') + { + --escape; + } + + if((beg - escape) % 2) + { + if(_escape) + { + value.replace(escape, beg - escape, (beg - escape) / 2, '$'); + } + ++beg; + continue; + } + else + { + value.replace(escape, beg - escape, (beg - escape) / 2, '$'); + beg -= (beg - escape) / 2; + } + } + + end = value.find("}", beg); + if(end == string::npos) + { + throw "malformed variable name `" + value + "'"; + } + + // + // Get the name of the variable and get its value if the + // variable is not currently ignored (in which case we do + // nothing, the variable will be substituted later). If the + // name refered to a parameter we don't do any recursive + // substitution: the parameter value is computed at the point + // of definition. + // + string name = value.substr(beg + 2, end - beg - 2); + if(_ignore.find(name) != _ignore.end()) + { + if(useIgnored) + { + ++beg; + continue; + } + else + { + throw "use of the `" + name + "' variable is now allowed here"; + } + } + + bool param; + string val = getVariable(name, useParams, param); + if(!param) + { + val = substitute(val, false, useIgnored); // Recursive resolution + } + value.replace(beg, end - beg + 1, val); + beg += val.length(); } return value; } @@ -810,25 +810,25 @@ Resolver::getVariable(const string& name, bool checkParams, bool& param) const map::const_iterator p = _reserved.find(name); if(p != _reserved.end()) { - if(p->second.empty()) - { - throw "undefined variable `" + name + "'"; - } - return p->second; + if(p->second.empty()) + { + throw "undefined variable `" + name + "'"; + } + return p->second; } if(checkParams) { - p = _parameters.find(name); - if(p != _parameters.end()) - { - param = true; - return p->second; - } + p = _parameters.find(name); + if(p != _parameters.end()) + { + param = true; + return p->second; + } } p = _variables.find(name); if(p != _variables.end()) { - return p->second; + return p->second; } throw "undefined variable `" + name + "'"; @@ -841,21 +841,21 @@ Resolver::getProperties(const Ice::StringSeq& references, set& resolved) PropertyDescriptorSeq properties; for(Ice::StringSeq::const_iterator p = references.begin(); p != references.end(); ++p) { - if(resolved.find(*p) != resolved.end()) - { - exception("detected circular dependency with property reference `" + *p + "'"); - } - - PropertySetDescriptor desc = getPropertySet(*p); - if(!desc.references.empty()) - { - resolved.insert(*p); - PropertyDescriptorSeq p = getProperties(desc.references, resolved); - properties.insert(properties.end(), p.begin(), p.end()); - } - - PropertyDescriptorSeq pds = operator()(desc.properties); - properties.insert(properties.end(), pds.begin(), pds.end()); + if(resolved.find(*p) != resolved.end()) + { + exception("detected circular dependency with property reference `" + *p + "'"); + } + + PropertySetDescriptor desc = getPropertySet(*p); + if(!desc.references.empty()) + { + resolved.insert(*p); + PropertyDescriptorSeq p = getProperties(desc.references, resolved); + properties.insert(properties.end(), p.begin(), p.end()); + } + + PropertyDescriptorSeq pds = operator()(desc.properties); + properties.insert(properties.end(), pds.begin(), pds.end()); } return properties; } @@ -890,10 +890,10 @@ Resolver::checkReserved(const string& type, const map& values) c { for(map::const_iterator p = values.begin(); p != values.end(); ++p) { - if(_reserved.find(p->first) != _reserved.end()) - { - exception("invalid " + type + " `" + p->first + "': reserved variable name"); - } + if(_reserved.find(p->first) != _reserved.end()) + { + exception("invalid " + type + " `" + p->first + "': reserved variable name"); + } } } @@ -907,34 +907,34 @@ CommunicatorHelper::operator==(const CommunicatorHelper& helper) const { if(_desc->ice_id() != helper._desc->ice_id()) { - return false; + return false; } if(_desc->description != helper._desc->description) { - return false; + return false; } if(set(_desc->adapters.begin(), _desc->adapters.end()) != set(helper._desc->adapters.begin(), helper._desc->adapters.end())) { - return false; + return false; } if(_desc->propertySet != helper._desc->propertySet) { - return false; + return false; } if(set(_desc->dbEnvs.begin(), _desc->dbEnvs.end()) != set(helper._desc->dbEnvs.begin(), helper._desc->dbEnvs.end())) { - return false; + return false; } if(_desc->logs != helper._desc->logs) { - return false; + return false; } return true; @@ -950,23 +950,23 @@ void CommunicatorHelper::getIds(multiset& adapterIds, multiset& objectIds) const { for(AdapterDescriptorSeq::const_iterator p = _desc->adapters.begin(); p != _desc->adapters.end(); ++p) - { - if(!p->id.empty()) - { - adapterIds.insert(p->id); - } - - set ids; - ObjectDescriptorSeq::const_iterator q; - for(q = p->objects.begin(); q != p->objects.end(); ++q) - { - ids.insert(q->id); - } - for(q = p->allocatables.begin(); q != p->allocatables.end(); ++q) - { - ids.insert(q->id); - } - objectIds.insert(ids.begin(), ids.end()); + { + if(!p->id.empty()) + { + adapterIds.insert(p->id); + } + + set ids; + ObjectDescriptorSeq::const_iterator q; + for(q = p->objects.begin(); q != p->objects.end(); ++q) + { + ids.insert(q->id); + } + for(q = p->allocatables.begin(); q != p->allocatables.end(); ++q) + { + ids.insert(q->id); + } + objectIds.insert(ids.begin(), ids.end()); } } @@ -978,44 +978,44 @@ CommunicatorHelper::instantiateImpl(const CommunicatorDescriptorPtr& instance, c for(AdapterDescriptorSeq::const_iterator p = _desc->adapters.begin(); p != _desc->adapters.end(); ++p) { - AdapterDescriptor adapter; - adapter.name = resolve(p->name, "object adapter name", false); - adapter.description = resolve(p->description, "object adapter description"); - adapter.id = resolve.asId(p->id, "object adapter id"); - adapter.registerProcess = p->registerProcess; - adapter.serverLifetime = p->serverLifetime; - adapter.replicaGroupId = resolve.asId(p->replicaGroupId, "object adapter replica group id", true); - if(!adapter.replicaGroupId.empty() && !resolve.hasReplicaGroup(adapter.replicaGroupId)) - { - resolve.exception("unknown replica group `" + adapter.replicaGroupId + "'"); - } - adapter.priority = resolve.asInt(p->priority, "object adapter priority"); - adapter.objects = resolve(p->objects, "well-known"); - adapter.allocatables = resolve(p->allocatables, "allocatable"); - instance->adapters.push_back(adapter); - - // - // Make sure the endpoints are defined. - // - if(IceGrid::getProperty(instance->propertySet.properties, "Ice.OA." + adapter.name + ".Endpoints").empty()) - { - resolve.exception("invalid endpoints for adapter `" + adapter.name + "': empty string"); - } + AdapterDescriptor adapter; + adapter.name = resolve(p->name, "object adapter name", false); + adapter.description = resolve(p->description, "object adapter description"); + adapter.id = resolve.asId(p->id, "object adapter id"); + adapter.registerProcess = p->registerProcess; + adapter.serverLifetime = p->serverLifetime; + adapter.replicaGroupId = resolve.asId(p->replicaGroupId, "object adapter replica group id", true); + if(!adapter.replicaGroupId.empty() && !resolve.hasReplicaGroup(adapter.replicaGroupId)) + { + resolve.exception("unknown replica group `" + adapter.replicaGroupId + "'"); + } + adapter.priority = resolve.asInt(p->priority, "object adapter priority"); + adapter.objects = resolve(p->objects, "well-known"); + adapter.allocatables = resolve(p->allocatables, "allocatable"); + instance->adapters.push_back(adapter); + + // + // Make sure the endpoints are defined. + // + if(IceGrid::getProperty(instance->propertySet.properties, "Ice.OA." + adapter.name + ".Endpoints").empty()) + { + resolve.exception("invalid endpoints for adapter `" + adapter.name + "': empty string"); + } } for(DbEnvDescriptorSeq::const_iterator s = _desc->dbEnvs.begin(); s != _desc->dbEnvs.end(); ++s) { - DbEnvDescriptor dbEnv; - dbEnv.name = resolve(s->name, "database environment name", false); - dbEnv.description = resolve(s->description, "database environment description"); - dbEnv.dbHome = resolve(s->dbHome, "database environment home directory"); - dbEnv.properties = resolve(s->properties, "database environment property"); - instance->dbEnvs.push_back(dbEnv); + DbEnvDescriptor dbEnv; + dbEnv.name = resolve(s->name, "database environment name", false); + dbEnv.description = resolve(s->description, "database environment description"); + dbEnv.dbHome = resolve(s->dbHome, "database environment home directory"); + dbEnv.properties = resolve(s->properties, "database environment property"); + instance->dbEnvs.push_back(dbEnv); } for(Ice::StringSeq::const_iterator l = _desc->logs.begin(); l != _desc->logs.end(); ++l) { - instance->logs.push_back(resolve(*l, "log path", false)); + instance->logs.push_back(resolve(*l, "log path", false)); } } @@ -1039,17 +1039,17 @@ CommunicatorHelper::upgrade(CommunicatorDescriptorPtr& desc) const bool upgraded = false; for(AdapterDescriptorSeq::const_iterator p = _desc->adapters.begin(); p != _desc->adapters.end(); ++p) { - const string oaPrefix = p->name + "."; - for(PropertyDescriptorSeq::iterator q = properties.begin(); q != properties.end(); ++q) - { - if(q->name.find(oaPrefix) == 0 && - q->name.size() > oaPrefix.size() && - oaProperties.find(q->name.substr(oaPrefix.size())) != oaProperties.end()) - { - q->name = "Ice.OA." + q->name; - upgraded = true; - } - } + const string oaPrefix = p->name + "."; + for(PropertyDescriptorSeq::iterator q = properties.begin(); q != properties.end(); ++q) + { + if(q->name.find(oaPrefix) == 0 && + q->name.size() > oaPrefix.size() && + oaProperties.find(q->name.substr(oaPrefix.size())) != oaProperties.end()) + { + q->name = "Ice.OA." + q->name; + upgraded = true; + } + } } return upgraded; } @@ -1059,48 +1059,48 @@ CommunicatorHelper::print(const Ice::CommunicatorPtr& communicator, Output& out) { if(!_desc->description.empty()) { - out << nl << "description"; - out << sb; - out << nl << _desc->description; - out << eb; + out << nl << "description"; + out << sb; + out << nl << _desc->description; + out << eb; } set hiddenProperties; { - for(DbEnvDescriptorSeq::const_iterator p = _desc->dbEnvs.begin(); p != _desc->dbEnvs.end(); ++p) - { - printDbEnv(out, *p); - } + for(DbEnvDescriptorSeq::const_iterator p = _desc->dbEnvs.begin(); p != _desc->dbEnvs.end(); ++p) + { + printDbEnv(out, *p); + } } { - for(AdapterDescriptorSeq::const_iterator p = _desc->adapters.begin(); p != _desc->adapters.end(); ++p) - { - hiddenProperties.insert("Ice.OA." + p->name + ".Endpoints"); - printObjectAdapter(communicator, out, *p); - } + for(AdapterDescriptorSeq::const_iterator p = _desc->adapters.begin(); p != _desc->adapters.end(); ++p) + { + hiddenProperties.insert("Ice.OA." + p->name + ".Endpoints"); + printObjectAdapter(communicator, out, *p); + } } { - for(Ice::StringSeq::const_iterator p = _desc->logs.begin(); p != _desc->logs.end(); ++p) - { - out << nl << "log `" << *p << "'"; - } + for(Ice::StringSeq::const_iterator p = _desc->logs.begin(); p != _desc->logs.end(); ++p) + { + out << nl << "log `" << *p << "'"; + } } if(!_desc->propertySet.properties.empty() || !_desc->propertySet.references.empty()) { - out << nl << "properties"; - out << sb; - if(!_desc->propertySet.references.empty()) - { - out << nl << "references = " << toString(_desc->propertySet.references); - } - PropertyDescriptorSeq::const_iterator q; - for(q = _desc->propertySet.properties.begin(); q != _desc->propertySet.properties.end(); ++q) - { - if(hiddenProperties.find(q->name) == hiddenProperties.end()) - { - out << nl << q->name << " = `" << q->value << "'"; - } - } - out << eb; + out << nl << "properties"; + out << sb; + if(!_desc->propertySet.references.empty()) + { + out << nl << "references = " << toString(_desc->propertySet.references); + } + PropertyDescriptorSeq::const_iterator q; + for(q = _desc->propertySet.properties.begin(); q != _desc->propertySet.properties.end(); ++q) + { + if(hiddenProperties.find(q->name) == hiddenProperties.end()) + { + out << nl << q->name << " = `" << q->value << "'"; + } + } + out << eb; } } @@ -1110,82 +1110,82 @@ CommunicatorHelper::printDbEnv(Output& out, const DbEnvDescriptor& dbEnv) const out << nl << "database environment `" << dbEnv.name << "'"; if(!dbEnv.dbHome.empty() || !dbEnv.properties.empty() || !dbEnv.description.empty()) { - out << sb; - if(!dbEnv.dbHome.empty()) - { - out << nl << "home = `" << dbEnv.dbHome << "'"; - } - if(!dbEnv.description.empty()) - { - out << nl << "description = `" << dbEnv.description << "'"; - } - if(!dbEnv.properties.empty()) - { - out << nl << "properties"; - out << sb; - for(PropertyDescriptorSeq::const_iterator p = dbEnv.properties.begin(); p != dbEnv.properties.end(); ++p) - { - out << nl << p->name << " = `" << p->value << "'"; - } - out << eb; - } - out << eb; + out << sb; + if(!dbEnv.dbHome.empty()) + { + out << nl << "home = `" << dbEnv.dbHome << "'"; + } + if(!dbEnv.description.empty()) + { + out << nl << "description = `" << dbEnv.description << "'"; + } + if(!dbEnv.properties.empty()) + { + out << nl << "properties"; + out << sb; + for(PropertyDescriptorSeq::const_iterator p = dbEnv.properties.begin(); p != dbEnv.properties.end(); ++p) + { + out << nl << p->name << " = `" << p->value << "'"; + } + out << eb; + } + out << eb; } } void CommunicatorHelper::printObjectAdapter(const Ice::CommunicatorPtr& communicator, - Output& out, - const AdapterDescriptor& adapter) const + Output& out, + const AdapterDescriptor& adapter) const { out << nl << "adapter `" << adapter.name << "'"; out << sb; if(!adapter.id.empty()) { - out << nl << "id = `" << adapter.id << "'"; + out << nl << "id = `" << adapter.id << "'"; } if(!adapter.replicaGroupId.empty()) { - out << nl << "replica group id = `" << adapter.replicaGroupId << "'"; + out << nl << "replica group id = `" << adapter.replicaGroupId << "'"; } if(!adapter.priority.empty()) { - out << nl << "priority = `" << adapter.priority << "'"; + out << nl << "priority = `" << adapter.priority << "'"; } string endpoints = getProperty("Ice.OA." + adapter.name + ".Endpoints"); if(!endpoints.empty()) { - out << nl << "endpoints = `" << endpoints << "'"; + out << nl << "endpoints = `" << endpoints << "'"; } out << nl << "register process = `" << (adapter.registerProcess ? "true" : "false") << "'"; out << nl << "server lifetime = `" << (adapter.serverLifetime ? "true" : "false") << "'"; ObjectDescriptorSeq::const_iterator p; for(p = adapter.objects.begin(); p != adapter.objects.end(); ++p) { - out << nl << "well-known object"; - out << sb; - out << nl << "identity = `" << communicator->identityToString(p->id) << "' "; - if(!p->type.empty()) - { - out << nl << "type = `" << p->type << "'"; - } - out << eb; + out << nl << "well-known object"; + out << sb; + out << nl << "identity = `" << communicator->identityToString(p->id) << "' "; + if(!p->type.empty()) + { + out << nl << "type = `" << p->type << "'"; + } + out << eb; } for(p = adapter.allocatables.begin(); p != adapter.allocatables.end(); ++p) { - out << nl << "allocatable"; - out << sb; - out << nl << "identity = `" << communicator->identityToString(p->id) << "' "; - if(!p->type.empty()) - { - out << nl << "type = `" << p->type << "'"; - } - out << eb; + out << nl << "allocatable"; + out << sb; + out << nl << "identity = `" << communicator->identityToString(p->id) << "' "; + if(!p->type.empty()) + { + out << nl << "type = `" << p->type << "'"; + } + out << eb; } if(!adapter.description.empty()) { - out << nl << "description = `" << adapter.description << "'"; + out << nl << "description = `" << adapter.description << "'"; } out << eb; } @@ -1207,17 +1207,17 @@ ServiceHelper::operator==(const ServiceHelper& helper) const { if(!CommunicatorHelper::operator==(helper)) { - return false; + return false; } if(_desc->name != helper._desc->name) { - return false; + return false; } if(_desc->entry != helper._desc->entry) { - return false; + return false; } return true; @@ -1237,7 +1237,7 @@ ServiceHelper::getDescriptor() const ServiceDescriptorPtr ServiceHelper::instantiate(const Resolver& resolver, const PropertyDescriptorSeq& props, - const PropertySetDescriptorDict& serviceProps) const + const PropertySetDescriptorDict& serviceProps) const { ServiceDescriptorPtr service = new ServiceDescriptor(); instantiateImpl(service, resolver, props, serviceProps); @@ -1246,9 +1246,9 @@ ServiceHelper::instantiate(const Resolver& resolver, const PropertyDescriptorSeq void ServiceHelper::instantiateImpl(const ServiceDescriptorPtr& instance, - const Resolver& resolve, - const PropertyDescriptorSeq& props, - const PropertySetDescriptorDict& serviceProps) const + const Resolver& resolve, + const PropertyDescriptorSeq& props, + const PropertySetDescriptorDict& serviceProps) const { CommunicatorHelper::instantiateImpl(instance, resolve); instance->name = resolve(_desc->name, "name", false); @@ -1257,9 +1257,9 @@ ServiceHelper::instantiateImpl(const ServiceDescriptorPtr& instance, PropertySetDescriptorDict::const_iterator p = serviceProps.find(instance->name); if(p != serviceProps.end()) { - instance->propertySet.properties.insert(instance->propertySet.properties.end(), - p->second.properties.begin(), - p->second.properties.end()); + instance->propertySet.properties.insert(instance->propertySet.properties.end(), + p->second.properties.begin(), + p->second.properties.end()); } } @@ -1284,69 +1284,69 @@ ServerHelper::operator==(const ServerHelper& helper) const { if(!CommunicatorHelper::operator==(helper)) { - return false; + return false; } if(_desc->id != helper._desc->id) { - return false; + return false; } if(_desc->exe != helper._desc->exe) { - return false; + return false; } if(_desc->pwd != helper._desc->pwd) { - return false; + return false; } if(set(_desc->options.begin(), _desc->options.end()) != set(helper._desc->options.begin(), helper._desc->options.end())) { - return false; + return false; } if(set(_desc->envs.begin(), _desc->envs.end()) != set(helper._desc->envs.begin(), helper._desc->envs.end())) { - return false; + return false; } if(_desc->activation != helper._desc->activation) { - return false; + return false; } if(_desc->activationTimeout != helper._desc->activationTimeout) { - return false; + return false; } if(_desc->deactivationTimeout != helper._desc->deactivationTimeout) { - return false; + return false; } if(_desc->distrib != helper._desc->distrib) { - return false; + return false; } if(_desc->allocatable != helper._desc->allocatable) { - return false; + return false; } if(_desc->user != helper._desc->user) { - return false; + return false; } if(_desc->iceVersion != helper._desc->iceVersion) { - return false; + return false; } return true; @@ -1366,12 +1366,12 @@ ServerHelper::getDescriptor() const ServerDescriptorPtr ServerHelper::instantiate(const Resolver& resolver, - const PropertyDescriptorSeq& props, - const PropertySetDescriptorDict& serviceProps) const + const PropertyDescriptorSeq& props, + const PropertySetDescriptorDict& serviceProps) const { if(!serviceProps.empty()) { - resolver.exception("service property sets are only allowed in IceBox server instances"); + resolver.exception("service property sets are only allowed in IceBox server instances"); } ServerDescriptorPtr server = new ServerDescriptor(); @@ -1399,70 +1399,70 @@ ServerHelper::printImpl(const Ice::CommunicatorPtr& communicator, Output& out, c { if(!info.application.empty()) { - out << nl << "application = `" << info.application << "'"; - out << nl << "application uuid = `" << info.uuid << "'"; - out << nl << "application revision = `" << info.revision << "'"; + out << nl << "application = `" << info.application << "'"; + out << nl << "application uuid = `" << info.uuid << "'"; + out << nl << "application revision = `" << info.revision << "'"; } if(!info.node.empty()) { - out << nl << "node = `" << info.node << "'"; + out << nl << "node = `" << info.node << "'"; } if(!info.sessionId.empty()) { - out << nl << "session id = `" << info.sessionId << "'"; + out << nl << "session id = `" << info.sessionId << "'"; } out << nl << "exe = `" << _desc->exe << "'"; if(!_desc->pwd.empty()) { - out << nl << "pwd = `" << _desc->pwd << "'"; + out << nl << "pwd = `" << _desc->pwd << "'"; } out << nl << "activation = `" << _desc->activation << "'"; if(!_desc->activationTimeout.empty() && _desc->activationTimeout != "0") { - out << nl << "activationTimeout = `" << _desc->activationTimeout << "'"; + out << nl << "activationTimeout = `" << _desc->activationTimeout << "'"; } if(!_desc->deactivationTimeout.empty() && _desc->deactivationTimeout != "0") { - out << nl << "deactivationTimeout = `" << _desc->deactivationTimeout << "'"; + out << nl << "deactivationTimeout = `" << _desc->deactivationTimeout << "'"; } if(!_desc->user.empty()) { - out << nl << "user = `" << _desc->user << "'"; + out << nl << "user = `" << _desc->user << "'"; } if(!_desc->iceVersion.empty()) { - out << nl << "ice version = `" << _desc->iceVersion << "'"; + out << nl << "ice version = `" << _desc->iceVersion << "'"; } if(!_desc->applicationDistrib) { - out << nl << "application distribution = `false'"; + out << nl << "application distribution = `false'"; } if(!_desc->options.empty()) { - out << nl << "options = `" << toString(_desc->options) << "'"; + out << nl << "options = `" << toString(_desc->options) << "'"; } if(!_desc->envs.empty()) { - out << nl << "envs = `" << toString(_desc->envs) << "'"; + out << nl << "envs = `" << toString(_desc->envs) << "'"; } if(!_desc->distrib.icepatch.empty()) { - out << nl << "distribution"; - out << sb; - out << nl << "proxy = `" << _desc->distrib.icepatch << "'"; - if(!_desc->distrib.directories.empty()) - { - out << nl << "directories = `" << toString(_desc->distrib.directories) << "'"; - } - out << eb; + out << nl << "distribution"; + out << sb; + out << nl << "proxy = `" << _desc->distrib.icepatch << "'"; + if(!_desc->distrib.directories.empty()) + { + out << nl << "directories = `" << toString(_desc->distrib.directories) << "'"; + } + out << eb; } CommunicatorHelper::print(communicator, out); } void ServerHelper::instantiateImpl(const ServerDescriptorPtr& instance, - const Resolver& resolve, - const PropertyDescriptorSeq& props) const + const Resolver& resolve, + const PropertyDescriptorSeq& props) const { CommunicatorHelper::instantiateImpl(instance, resolve); @@ -1476,22 +1476,22 @@ ServerHelper::instantiateImpl(const ServerDescriptorPtr& instance, instance->iceVersion = resolve(_desc->iceVersion, "ice version"); if(!instance->iceVersion.empty()) { - int version = getMMVersion(instance->iceVersion); - if(version < 0) - { - resolve.exception("invalid ice version: " + instance->iceVersion); - } - else if(version > ICE_INT_VERSION) - { - //resolve.exception("invalid ice version: " + instance->iceVersion + " is superior to the IceGrid \n" - //"registry version (" + ICE_STRING_VERSION + ")"); - if(resolve.warningEnabled()) - { - Ice::Warning out(resolve.getCommunicator()->getLogger()); - out << "invalid ice version: " << instance->iceVersion << " is superior to the IceGrid "; - out << "registry version (" << ICE_STRING_VERSION << ")"; - } - } + int version = getMMVersion(instance->iceVersion); + if(version < 0) + { + resolve.exception("invalid ice version: " + instance->iceVersion); + } + else if(version > ICE_INT_VERSION) + { + //resolve.exception("invalid ice version: " + instance->iceVersion + " is superior to the IceGrid \n" + //"registry version (" + ICE_STRING_VERSION + ")"); + if(resolve.warningEnabled()) + { + Ice::Warning out(resolve.getCommunicator()->getLogger()); + out << "invalid ice version: " << instance->iceVersion << " is superior to the IceGrid "; + out << "registry version (" << ICE_STRING_VERSION << ")"; + } + } } if(!instance->activation.empty() && instance->activation != "manual" && @@ -1499,7 +1499,7 @@ ServerHelper::instantiateImpl(const ServerDescriptorPtr& instance, instance->activation != "always" && instance->activation != "session") { - resolve.exception("unknown activation `" + instance->activation + "'"); + resolve.exception("unknown activation `" + instance->activation + "'"); } instance->activationTimeout = resolve.asInt(_desc->activationTimeout, "activation timeout"); instance->deactivationTimeout = resolve.asInt(_desc->deactivationTimeout, "deactivation timeout"); @@ -1515,7 +1515,7 @@ IceBoxHelper::IceBoxHelper(const IceBoxDescriptorPtr& descriptor) : { for(ServiceInstanceDescriptorSeq::const_iterator p = _desc->services.begin(); p != _desc->services.end(); ++p) { - _services.push_back(ServiceInstanceHelper(*p)); + _services.push_back(ServiceInstanceHelper(*p)); } } @@ -1524,12 +1524,12 @@ IceBoxHelper::operator==(const IceBoxHelper& helper) const { if(!ServerHelper::operator==(helper)) { - return false; + return false; } - + if(_services != helper._services) { - return false; + return false; } return true; @@ -1543,8 +1543,8 @@ IceBoxHelper::operator!=(const IceBoxHelper& helper) const ServerDescriptorPtr IceBoxHelper::instantiate(const Resolver& resolver, - const PropertyDescriptorSeq& props, - const PropertySetDescriptorDict& serviceProps) const + const PropertyDescriptorSeq& props, + const PropertySetDescriptorDict& serviceProps) const { IceBoxDescriptorPtr iceBox = new IceBoxDescriptor(); instantiateImpl(iceBox, resolver, props, serviceProps); @@ -1557,7 +1557,7 @@ IceBoxHelper::getIds(multiset& adapterIds, multiset& obje CommunicatorHelper::getIds(adapterIds, objectIds); for(vector::const_iterator p = _services.begin(); p != _services.end(); ++p) { - p->getIds(adapterIds, objectIds); + p->getIds(adapterIds, objectIds); } } @@ -1568,16 +1568,16 @@ IceBoxHelper::upgrade(CommunicatorDescriptorPtr& communicator) const IceBoxDescriptorPtr iceBox = IceBoxDescriptorPtr::dynamicCast(communicator); for(ServiceInstanceDescriptorSeq::iterator p = iceBox->services.begin(); p != iceBox->services.end(); ++p) { - if(p->descriptor) - { - CommunicatorDescriptorPtr com; - if(ServiceHelper(p->descriptor).upgrade(com)) - { - upgraded = true; - p->descriptor = ServiceDescriptorPtr::dynamicCast(com); - assert(p->descriptor); - } - } + if(p->descriptor) + { + CommunicatorDescriptorPtr com; + if(ServiceHelper(p->descriptor).upgrade(com)) + { + upgraded = true; + p->descriptor = ServiceDescriptorPtr::dynamicCast(com); + assert(p->descriptor); + } + } } return upgraded; } @@ -1599,42 +1599,42 @@ IceBoxHelper::print(const Ice::CommunicatorPtr& communicator, Output& out, const printImpl(communicator, out, info); for(vector::const_iterator p = _services.begin(); p != _services.end(); ++p) { - out << nl; - p->print(communicator, out); + out << nl; + p->print(communicator, out); } out << eb; } void IceBoxHelper::instantiateImpl(const IceBoxDescriptorPtr& instance, - const Resolver& resolver, - const PropertyDescriptorSeq& props, - const PropertySetDescriptorDict& serviceProps) const + const Resolver& resolver, + const PropertyDescriptorSeq& props, + const PropertySetDescriptorDict& serviceProps) const { ServerHelper::instantiateImpl(instance, resolver, props); set serviceNames; for(vector::const_iterator p = _services.begin(); p != _services.end(); ++p) { - ServiceInstanceDescriptor desc = p->instantiate(resolver, serviceProps); - assert(desc.descriptor); - serviceNames.insert(desc.descriptor->name); - instance->services.push_back(desc); + ServiceInstanceDescriptor desc = p->instantiate(resolver, serviceProps); + assert(desc.descriptor); + serviceNames.insert(desc.descriptor->name); + instance->services.push_back(desc); } for(PropertySetDescriptorDict::const_iterator q = serviceProps.begin(); q != serviceProps.end(); ++q) { - if(serviceNames.find(q->first) == serviceNames.end()) - { - resolver.exception("invalid service property set: service `" + q->first + "' doesn't exist"); - } + if(serviceNames.find(q->first) == serviceNames.end()) + { + resolver.exception("invalid service property set: service `" + q->first + "' doesn't exist"); + } } } map InstanceHelper::instantiateParams(const Resolver& resolve, - const string& tmpl, - const map& parameters, - const vector& requiredParameters, - const map& defaults) const + const string& tmpl, + const map& parameters, + const vector& requiredParameters, + const map& defaults) const { map params; @@ -1642,42 +1642,42 @@ InstanceHelper::instantiateParams(const Resolver& resolve, set unknown; for(map::const_iterator p = parameters.begin(); p != parameters.end(); ++p) { - if(required.find(p->first) == required.end()) - { - unknown.insert(p->first); - } - params.insert(make_pair(p->first, resolve(p->second, "parameter `" + p->first + "'"))); + if(required.find(p->first) == required.end()) + { + unknown.insert(p->first); + } + params.insert(make_pair(p->first, resolve(p->second, "parameter `" + p->first + "'"))); } if(!unknown.empty()) { - ostringstream os; - os << "unknown parameters when instantiating `" + tmpl + "' template: "; - copy(unknown.begin(), unknown.end(), ostream_iterator(os, " ")); - resolve.exception(os.str()); + ostringstream os; + os << "unknown parameters when instantiating `" + tmpl + "' template: "; + copy(unknown.begin(), unknown.end(), ostream_iterator(os, " ")); + resolve.exception(os.str()); } set missingParams; for(set::const_iterator q = required.begin(); q != required.end(); ++q) { - if(params.find(*q) == params.end()) - { - map::const_iterator r = defaults.find(*q); - if(r == defaults.end()) - { - missingParams.insert(*q); - } - else - { - params.insert(make_pair(r->first, resolve(r->second, "default parameter `" + r->first + "'"))); - } - } + if(params.find(*q) == params.end()) + { + map::const_iterator r = defaults.find(*q); + if(r == defaults.end()) + { + missingParams.insert(*q); + } + else + { + params.insert(make_pair(r->first, resolve(r->second, "default parameter `" + r->first + "'"))); + } + } } if(!missingParams.empty()) { - ostringstream os; - os << "undefined parameters when instantiating `" + tmpl + "' template: "; - copy(missingParams.begin(), missingParams.end(), ostream_iterator(os, " ")); - resolve.exception(os.str()); + ostringstream os; + os << "undefined parameters when instantiating `" + tmpl + "' template: "; + copy(missingParams.begin(), missingParams.end(), ostream_iterator(os, " ")); + resolve.exception(os.str()); } return params; @@ -1693,12 +1693,12 @@ ServiceInstanceHelper::ServiceInstanceHelper(const ServiceInstanceDescriptor& de // if(_def._cpp_template.empty() && !_def.descriptor) { - throw DeploymentException("invalid service instance: no template defined"); + throw DeploymentException("invalid service instance: no template defined"); } if(_def.descriptor) { - _service = ServiceHelper(_def.descriptor); + _service = ServiceHelper(_def.descriptor); } } @@ -1707,13 +1707,13 @@ ServiceInstanceHelper::operator==(const ServiceInstanceHelper& helper) const { if(_def._cpp_template.empty()) { - return _service == helper._service; + return _service == helper._service; } else { - return _def._cpp_template == helper._def._cpp_template && - _def.parameterValues == helper._def.parameterValues && - _def.propertySet == helper._def.propertySet; + return _def._cpp_template == helper._def._cpp_template && + _def.parameterValues == helper._def.parameterValues && + _def.propertySet == helper._def.propertySet; } } @@ -1730,14 +1730,14 @@ ServiceInstanceHelper::instantiate(const Resolver& resolve, const PropertySetDes std::map parameterValues; if(!def.getDescriptor()) { - assert(!_def._cpp_template.empty()); - TemplateDescriptor tmpl = resolve.getServiceTemplate(_def._cpp_template); - def = ServiceHelper(ServiceDescriptorPtr::dynamicCast(tmpl.descriptor)); - parameterValues = instantiateParams(resolve, - _def._cpp_template, - _def.parameterValues, - tmpl.parameters, - tmpl.parameterDefaults); + assert(!_def._cpp_template.empty()); + TemplateDescriptor tmpl = resolve.getServiceTemplate(_def._cpp_template); + def = ServiceHelper(ServiceDescriptorPtr::dynamicCast(tmpl.descriptor)); + parameterValues = instantiateParams(resolve, + _def._cpp_template, + _def.parameterValues, + tmpl.parameters, + tmpl.parameterDefaults); } // @@ -1776,36 +1776,36 @@ ServiceInstanceHelper::print(const Ice::CommunicatorPtr& communicator, Output& o { if(_service.getDescriptor()) { - _service.print(communicator, out); + _service.print(communicator, out); } else { - assert(!_def._cpp_template.empty()); - out << "service instance"; - out << sb; - out << nl << "template = `" << _def._cpp_template << "'"; - out << nl << "parameters"; - out << sb; - for(StringStringDict::const_iterator p = _def.parameterValues.begin(); p != _def.parameterValues.end(); ++p) - { - out << nl << p->first << " = `" << p->second << "'"; - } - out << eb; - out << eb; + assert(!_def._cpp_template.empty()); + out << "service instance"; + out << sb; + out << nl << "template = `" << _def._cpp_template << "'"; + out << nl << "parameters"; + out << sb; + for(StringStringDict::const_iterator p = _def.parameterValues.begin(); p != _def.parameterValues.end(); ++p) + { + out << nl << p->first << " = `" << p->second << "'"; + } + out << eb; + out << eb; } } ServerInstanceHelper::ServerInstanceHelper(const ServerInstanceDescriptor& desc, - const Resolver& resolve, - bool instantiate) : + const Resolver& resolve, + bool instantiate) : _def(desc) { init(0, resolve, instantiate); } ServerInstanceHelper::ServerInstanceHelper(const ServerDescriptorPtr& definition, - const Resolver& resolve, - bool instantiate) : + const Resolver& resolve, + bool instantiate) : _def(ServerInstanceDescriptor()) { init(definition, resolve, instantiate); @@ -1821,21 +1821,21 @@ ServerInstanceHelper::init(const ServerDescriptorPtr& definition, const Resolver std::map parameterValues; if(!def) { - if(_def._cpp_template.empty()) - { - resolve.exception("invalid server instance: template is not defined"); - } - - // - // Get the server definition and the template property sets. - // - TemplateDescriptor tmpl = resolve.getServerTemplate(_def._cpp_template); - def = ServerDescriptorPtr::dynamicCast(tmpl.descriptor); - parameterValues = instantiateParams(resolve, - _def._cpp_template, - _def.parameterValues, - tmpl.parameters, - tmpl.parameterDefaults); + if(_def._cpp_template.empty()) + { + resolve.exception("invalid server instance: template is not defined"); + } + + // + // Get the server definition and the template property sets. + // + TemplateDescriptor tmpl = resolve.getServerTemplate(_def._cpp_template); + def = ServerDescriptorPtr::dynamicCast(tmpl.descriptor); + parameterValues = instantiateParams(resolve, + _def._cpp_template, + _def.parameterValues, + tmpl.parameters, + tmpl.parameterDefaults); } assert(def); @@ -1854,7 +1854,7 @@ ServerInstanceHelper::init(const ServerDescriptorPtr& definition, const Resolver if(!instantiate) { - return; // We're done. + return; // We're done. } // @@ -1863,30 +1863,30 @@ ServerInstanceHelper::init(const ServerDescriptorPtr& definition, const Resolver // if(svrResolve(def->activation, "server activation", true) == "session") { - svrResolve.addIgnored("session.id"); + svrResolve.addIgnored("session.id"); } - + // // Instantiate the server instance definition (we use the server // resolver above, so using parameters in properties is possible). // if(!_def._cpp_template.empty()) { - _instance._cpp_template = _def._cpp_template; - _instance.parameterValues = parameterValues; - _instance.propertySet = svrResolve(_def.propertySet); - for(PropertySetDescriptorDict::const_iterator p = _def.servicePropertySets.begin(); - p != _def.servicePropertySets.end(); ++p) - { - _instance.servicePropertySets.insert(make_pair(svrResolve(p->first), svrResolve(p->second))); - } + _instance._cpp_template = _def._cpp_template; + _instance.parameterValues = parameterValues; + _instance.propertySet = svrResolve(_def.propertySet); + for(PropertySetDescriptorDict::const_iterator p = _def.servicePropertySets.begin(); + p != _def.servicePropertySets.end(); ++p) + { + _instance.servicePropertySets.insert(make_pair(svrResolve(p->first), svrResolve(p->second))); + } } // // Instantiate the server definition. // ServerDescriptorPtr inst = _serverDefinition->instantiate(svrResolve, _instance.propertySet.properties, - _instance.servicePropertySets); + _instance.servicePropertySets); _serverInstance = createHelper(inst); } @@ -1895,14 +1895,14 @@ ServerInstanceHelper::operator==(const ServerInstanceHelper& helper) const { if(_def._cpp_template.empty()) { - return *_serverDefinition == *helper._serverDefinition; + return *_serverDefinition == *helper._serverDefinition; } else { - return _def._cpp_template == helper._def._cpp_template && - _def.parameterValues == helper._def.parameterValues && - _def.propertySet == helper._def.propertySet && - _def.servicePropertySets == helper._def.servicePropertySets; + return _def._cpp_template == helper._def._cpp_template && + _def.parameterValues == helper._def.parameterValues && + _def.propertySet == helper._def.propertySet && + _def.servicePropertySets == helper._def.servicePropertySets; } } @@ -1954,16 +1954,16 @@ ServerInstanceHelper::getIds(multiset& adapterIds, multisetsecond.getDefinition()); + update.serverInstances.push_back(p->second.getDefinition()); } update.removeServers = getDictRemovedElts(helper._serverInstances, _serverInstances); updated = getDictUpdatedElts(helper._servers, _servers); for(ServerInstanceHelperDict::const_iterator q = updated.begin(); q != updated.end(); ++q) { - update.servers.push_back(q->second.getServerDefinition()); + update.servers.push_back(q->second.getServerDefinition()); } Ice::StringSeq removed = getDictRemovedElts(helper._servers, _servers); update.removeServers.insert(update.removeServers.end(), removed.begin(), removed.end()); @@ -2137,63 +2137,63 @@ NodeHelper::update(const NodeUpdateDescriptor& update, const Resolver& appResolv ServerInstanceDescriptorSeq::const_iterator q; for(q = update.serverInstances.begin(); q != update.serverInstances.end(); ++q) { - ServerInstanceHelper helper(*q, resolve, false); - if(!added.insert(helper.getId()).second) - { - resolve.exception("duplicate server `" + helper.getId() + "' in node `" + _name + "'"); - } - def.serverInstances.push_back(helper.getDefinition()); + ServerInstanceHelper helper(*q, resolve, false); + if(!added.insert(helper.getId()).second) + { + resolve.exception("duplicate server `" + helper.getId() + "' in node `" + _name + "'"); + } + def.serverInstances.push_back(helper.getDefinition()); } for(r = _serverInstances.begin(); r != _serverInstances.end(); ++r) { - if(removed.find(r->first) != removed.end() || added.find(r->first) != added.end()) - { - continue; - } - - // - // Re-instantiate the server. Make sure the server ID didn't - // change, if the ID of a server changes the update descriptor - // has to remove the server and add an update entry for it. - // - ServerInstanceHelper helper(r->second.getDefinition(), resolve, false); - if(helper.getId() != r->first) - { - resolve.exception("invalid update in node `" + _name + "':\n" + "server instance id `" + r->first + - "' changed to `" + helper.getId() + "'"); - } - def.serverInstances.push_back(helper.getDefinition()); + if(removed.find(r->first) != removed.end() || added.find(r->first) != added.end()) + { + continue; + } + + // + // Re-instantiate the server. Make sure the server ID didn't + // change, if the ID of a server changes the update descriptor + // has to remove the server and add an update entry for it. + // + ServerInstanceHelper helper(r->second.getDefinition(), resolve, false); + if(helper.getId() != r->first) + { + resolve.exception("invalid update in node `" + _name + "':\n" + "server instance id `" + r->first + + "' changed to `" + helper.getId() + "'"); + } + def.serverInstances.push_back(helper.getDefinition()); } added.clear(); for(ServerDescriptorSeq::const_iterator s = update.servers.begin(); s != update.servers.end(); ++s) { - ServerInstanceHelper helper(*s, resolve, false); - if(!added.insert(helper.getId()).second) - { - resolve.exception("duplicate server `" + helper.getId() + "' in node `" + _name + "'"); - } - def.servers.push_back(helper.getServerDefinition()); + ServerInstanceHelper helper(*s, resolve, false); + if(!added.insert(helper.getId()).second) + { + resolve.exception("duplicate server `" + helper.getId() + "' in node `" + _name + "'"); + } + def.servers.push_back(helper.getServerDefinition()); } for(r = _servers.begin(); r != _servers.end(); ++r) { - if(removed.find(r->first) != removed.end() || added.find(r->first) != added.end()) - { - continue; - } - - // - // Re-instantiate the server. Make sure the server ID didn't - // change, if the ID of a server changes the update descriptor - // has to remove the server and add an update entry for it. - // - ServerInstanceHelper helper(r->second.getServerDefinition(), resolve, false); - if(helper.getId() != r->first) - { - resolve.exception("invalid update in node `" + _name + "':\nserver instance id `" + r->first + - "' changed to `" + helper.getId() + "'"); - } - def.servers.push_back(helper.getServerDefinition()); + if(removed.find(r->first) != removed.end() || added.find(r->first) != added.end()) + { + continue; + } + + // + // Re-instantiate the server. Make sure the server ID didn't + // change, if the ID of a server changes the update descriptor + // has to remove the server and add an update entry for it. + // + ServerInstanceHelper helper(r->second.getServerDefinition(), resolve, false); + if(helper.getId() != r->first) + { + resolve.exception("invalid update in node `" + _name + "':\nserver instance id `" + r->first + + "' changed to `" + helper.getId() + "'"); + } + def.servers.push_back(helper.getServerDefinition()); } return def; } @@ -2206,12 +2206,12 @@ NodeHelper::upgrade(NodeDescriptor& desc) const bool upgraded = false; for(ServerDescriptorSeq::iterator j = desc.servers.begin(); j != desc.servers.end(); ++j) { - CommunicatorDescriptorPtr com; - if(createHelper(*j)->upgrade(com)) - { - *j = ServerDescriptorPtr::dynamicCast(com); - upgraded = true; - } + CommunicatorDescriptorPtr com; + if(createHelper(*j)->upgrade(com)) + { + *j = ServerDescriptorPtr::dynamicCast(com); + upgraded = true; + } } return upgraded; @@ -2224,13 +2224,13 @@ NodeHelper::getIds(multiset& serverIds, multiset& adapterIds, mu ServerInstanceHelperDict::const_iterator p; for(p = _serverInstances.begin(); p != _serverInstances.end(); ++p) { - serverIds.insert(p->first); - p->second.getIds(adapterIds, objectIds); + serverIds.insert(p->first); + p->second.getIds(adapterIds, objectIds); } for(p = _servers.begin(); p != _servers.end(); ++p) { - serverIds.insert(p->first); - p->second.getIds(adapterIds, objectIds); + serverIds.insert(p->first); + p->second.getIds(adapterIds, objectIds); } } @@ -2255,23 +2255,23 @@ NodeHelper::getServerInfos(const string& app, const string& uuid, int revision, ServerInstanceHelperDict::const_iterator p; for(p = _serverInstances.begin(); p != _serverInstances.end(); ++p) { - ServerInfo info; - info.node = _name; - info.application = app; - info.uuid = uuid; - info.revision = revision; - info.descriptor = p->second.getServerInstance(); - servers.insert(make_pair(p->second.getId(), info)); + ServerInfo info; + info.node = _name; + info.application = app; + info.uuid = uuid; + info.revision = revision; + info.descriptor = p->second.getServerInstance(); + servers.insert(make_pair(p->second.getId(), info)); } for(p = _servers.begin(); p != _servers.end(); ++p) { - ServerInfo info; - info.node = _name; - info.application = app; - info.uuid = uuid; - info.revision = revision; - info.descriptor = p->second.getServerInstance(); - servers.insert(make_pair(p->second.getId(), info)); + ServerInfo info; + info.node = _name; + info.application = app; + info.uuid = uuid; + info.revision = revision; + info.descriptor = p->second.getServerInstance(); + servers.insert(make_pair(p->second.getId(), info)); } } @@ -2285,38 +2285,38 @@ NodeHelper::hasDistributions(const string& server) const // if(server.empty()) { - ServerInstanceHelperDict::const_iterator p; - for(p = _serverInstances.begin(); p != _serverInstances.end(); ++p) - { - if(!p->second.getServerInstance()->distrib.icepatch.empty()) - { - return true; - } - } - for(p = _servers.begin(); p != _servers.end(); ++p) - { - if(!p->second.getServerInstance()->distrib.icepatch.empty()) - { - return true; - } - } + ServerInstanceHelperDict::const_iterator p; + for(p = _serverInstances.begin(); p != _serverInstances.end(); ++p) + { + if(!p->second.getServerInstance()->distrib.icepatch.empty()) + { + return true; + } + } + for(p = _servers.begin(); p != _servers.end(); ++p) + { + if(!p->second.getServerInstance()->distrib.icepatch.empty()) + { + return true; + } + } } else { - ServerInstanceHelperDict::const_iterator p = _serverInstances.find(server); - if(p == _serverInstances.end()) - { - p = _servers.find(server); - if(p == _servers.end()) - { - return false; - } - } + ServerInstanceHelperDict::const_iterator p = _serverInstances.find(server); + if(p == _serverInstances.end()) + { + p = _servers.find(server); + if(p == _servers.end()) + { + return false; + } + } - if(!p->second.getServerInstance()->distrib.icepatch.empty()) - { - return true; - } + if(!p->second.getServerInstance()->distrib.icepatch.empty()) + { + return true; + } } return false; @@ -2343,45 +2343,45 @@ NodeHelper::print(Output& out) const out << sb; if(!_instance.loadFactor.empty()) { - out << nl << "load factor = `" << _instance.loadFactor << "'"; + out << nl << "load factor = `" << _instance.loadFactor << "'"; } if(!_instance.description.empty()) { - out << nl << "description = `" << _instance.description << "'"; + out << nl << "description = `" << _instance.description << "'"; } if(!_instance.variables.empty()) { - out << nl << "variables"; - out << sb; - for(StringStringDict::const_iterator q = _instance.variables.begin(); q != _instance.variables.end(); ++q) - { - out << nl << q->first << " = `" << q->second << "'"; - } - out << eb; + out << nl << "variables"; + out << sb; + for(StringStringDict::const_iterator q = _instance.variables.begin(); q != _instance.variables.end(); ++q) + { + out << nl << q->first << " = `" << q->second << "'"; + } + out << eb; } if(!_instance.propertySets.empty()) { - PropertySetDescriptorDict::const_iterator q; - for(q = _instance.propertySets.begin(); q != _instance.propertySets.end(); ++q) - { - out << nl << "properties `" << q->first << "'"; - out << sb; - if(!q->second.references.empty()) - { - out << nl << "references = " << toString(q->second.references); - } - PropertyDescriptorSeq::const_iterator r; - for(r = q->second.properties.begin(); r != q->second.properties.end(); ++r) - { - out << nl << r->name << " = `" << r->value << "'"; - } - out << eb; - } + PropertySetDescriptorDict::const_iterator q; + for(q = _instance.propertySets.begin(); q != _instance.propertySets.end(); ++q) + { + out << nl << "properties `" << q->first << "'"; + out << sb; + if(!q->second.references.empty()) + { + out << nl << "references = " << toString(q->second.references); + } + PropertyDescriptorSeq::const_iterator r; + for(r = q->second.properties.begin(); r != q->second.properties.end(); ++r) + { + out << nl << r->name << " = `" << r->value << "'"; + } + out << eb; + } } if(_serverInstances.empty() && _servers.empty()) { - return; + return; } out << nl << "servers"; @@ -2389,11 +2389,11 @@ NodeHelper::print(Output& out) const ServerInstanceHelperDict::const_iterator p; for(p = _serverInstances.begin(); p != _serverInstances.end(); ++p) { - out << nl << p->first; + out << nl << p->first; } for(p = _servers.begin(); p != _servers.end(); ++p) { - out << nl << p->first; + out << nl << p->first; } out << eb; out << eb; @@ -2428,7 +2428,7 @@ NodeHelper::printDiff(Output& out, const NodeHelper& helper) const _def.loadFactor == helper._def.loadFactor && _def.description == helper._def.description) { - return; + return; } // @@ -2440,116 +2440,116 @@ NodeHelper::printDiff(Output& out, const NodeHelper& helper) const if(_def.loadFactor != helper._def.loadFactor) { - out << nl << "load factor udpated"; + out << nl << "load factor udpated"; } if(_def.description != helper._def.description) { - out << nl << "description udpated"; + out << nl << "description udpated"; } if(!updatedPs.empty() || !removedPs.empty()) { - out << nl << "property sets udpated"; + out << nl << "property sets udpated"; } if(!variables.empty() || !removeVariables.empty()) { - out << nl << "variables udpated"; + out << nl << "variables udpated"; } if(!updated.empty() || !removed.empty()) { - out << nl << "servers"; - out << sb; - ServerInstanceHelperDict::const_iterator p; - for(p = updated.begin(); p != updated.end(); ++p) - { - if(helper._serverInstances.find(p->first) == helper._serverInstances.end() && - helper._servers.find(p->first) == helper._servers.end()) - { - out << nl << "server `" << p->first << "' added"; - } - } - for(p = updated.begin(); p != updated.end(); ++p) - { - if(helper._serverInstances.find(p->first) != helper._serverInstances.end() || - helper._servers.find(p->first) != helper._servers.end()) - { - out << nl << "server `" << p->first << "' updated"; - } - } - for(Ice::StringSeq::const_iterator q = removed.begin(); q != removed.end(); ++q) - { - out << nl << "server `" << *q << "' removed"; - } - out << eb; + out << nl << "servers"; + out << sb; + ServerInstanceHelperDict::const_iterator p; + for(p = updated.begin(); p != updated.end(); ++p) + { + if(helper._serverInstances.find(p->first) == helper._serverInstances.end() && + helper._servers.find(p->first) == helper._servers.end()) + { + out << nl << "server `" << p->first << "' added"; + } + } + for(p = updated.begin(); p != updated.end(); ++p) + { + if(helper._serverInstances.find(p->first) != helper._serverInstances.end() || + helper._servers.find(p->first) != helper._servers.end()) + { + out << nl << "server `" << p->first << "' updated"; + } + } + for(Ice::StringSeq::const_iterator q = removed.begin(); q != removed.end(); ++q) + { + out << nl << "server `" << *q << "' removed"; + } + out << eb; } out << eb; } ApplicationHelper::ApplicationHelper(const Ice::CommunicatorPtr& communicator, - const ApplicationDescriptor& desc, - bool enableWarning, - bool instantiate) : + const ApplicationDescriptor& desc, + bool enableWarning, + bool instantiate) : _communicator(communicator), _def(desc) { if(_def.name.empty()) { - throw DeploymentException("invalid application: empty name"); + throw DeploymentException("invalid application: empty name"); } Resolver resolve(_def, communicator, enableWarning); if(instantiate) { - // - // Instantiate the application definition. - // - _instance.name = _def.name; - _instance.variables = _def.variables; - _instance.serverTemplates = _def.serverTemplates; - _instance.serviceTemplates = _def.serviceTemplates; - _instance.description = resolve(_def.description, "description"); - _instance.distrib = resolve(_def.distrib); - _instance.propertySets = resolve(_def.propertySets); - - for(ReplicaGroupDescriptorSeq::iterator r = _def.replicaGroups.begin(); r != _def.replicaGroups.end(); ++r) - { - ReplicaGroupDescriptor desc; - desc.id = resolve.asId(r->id, "replica group id", false); - desc.description = resolve(r->description, "replica group description"); - desc.objects = resolve(r->objects, "replica group well-known"); - if(!r->loadBalancing) - { - resolve.exception("replica group load balancing is not set"); - } - desc.loadBalancing = LoadBalancingPolicyPtr::dynamicCast(r->loadBalancing->ice_clone()); - desc.loadBalancing->nReplicas = - resolve.asInt(r->loadBalancing->nReplicas, "replica group number of replicas"); - if(desc.loadBalancing->nReplicas.empty()) - { - resolve.exception("invalid replica group load balancing number of replicas value: empty value"); - } - else if(desc.loadBalancing->nReplicas[0] == '-') - { - resolve.exception("invalid replica group load balancing number of replicas value: inferior to 0"); - } - AdaptiveLoadBalancingPolicyPtr al = AdaptiveLoadBalancingPolicyPtr::dynamicCast(desc.loadBalancing); - if(al) - { - al->loadSample = resolve(al->loadSample, "replica group load sample"); - if(al->loadSample != "" && al->loadSample != "1" && al->loadSample != "5" && al->loadSample != "15") - { - resolve.exception("invalid load sample value (allowed values are 1, 5 or 15)"); - } - } - _instance.replicaGroups.push_back(desc); - } - - // - // Set the named property sets on the resolver. We use the - // instantiated named property sets here -- named property sets - // must be fully definied at the application level. - // - resolve.addPropertySets(_instance.propertySets); + // + // Instantiate the application definition. + // + _instance.name = _def.name; + _instance.variables = _def.variables; + _instance.serverTemplates = _def.serverTemplates; + _instance.serviceTemplates = _def.serviceTemplates; + _instance.description = resolve(_def.description, "description"); + _instance.distrib = resolve(_def.distrib); + _instance.propertySets = resolve(_def.propertySets); + + for(ReplicaGroupDescriptorSeq::iterator r = _def.replicaGroups.begin(); r != _def.replicaGroups.end(); ++r) + { + ReplicaGroupDescriptor desc; + desc.id = resolve.asId(r->id, "replica group id", false); + desc.description = resolve(r->description, "replica group description"); + desc.objects = resolve(r->objects, "replica group well-known"); + if(!r->loadBalancing) + { + resolve.exception("replica group load balancing is not set"); + } + desc.loadBalancing = LoadBalancingPolicyPtr::dynamicCast(r->loadBalancing->ice_clone()); + desc.loadBalancing->nReplicas = + resolve.asInt(r->loadBalancing->nReplicas, "replica group number of replicas"); + if(desc.loadBalancing->nReplicas.empty()) + { + resolve.exception("invalid replica group load balancing number of replicas value: empty value"); + } + else if(desc.loadBalancing->nReplicas[0] == '-') + { + resolve.exception("invalid replica group load balancing number of replicas value: inferior to 0"); + } + AdaptiveLoadBalancingPolicyPtr al = AdaptiveLoadBalancingPolicyPtr::dynamicCast(desc.loadBalancing); + if(al) + { + al->loadSample = resolve(al->loadSample, "replica group load sample"); + if(al->loadSample != "" && al->loadSample != "1" && al->loadSample != "5" && al->loadSample != "15") + { + resolve.exception("invalid load sample value (allowed values are 1, 5 or 15)"); + } + } + _instance.replicaGroups.push_back(desc); + } + + // + // Set the named property sets on the resolver. We use the + // instantiated named property sets here -- named property sets + // must be fully definied at the application level. + // + resolve.addPropertySets(_instance.propertySets); } // @@ -2558,11 +2558,11 @@ ApplicationHelper::ApplicationHelper(const Ice::CommunicatorPtr& communicator, NodeHelperDict::const_iterator n; for(NodeDescriptorDict::const_iterator p = _def.nodes.begin(); p != _def.nodes.end(); ++p) { - n = _nodes.insert(make_pair(p->first, NodeHelper(p->first, p->second, resolve, instantiate))).first; - if(instantiate) - { - _instance.nodes.insert(make_pair(n->first, n->second.getInstance())); - } + n = _nodes.insert(make_pair(p->first, NodeHelper(p->first, p->second, resolve, instantiate))).first; + if(instantiate) + { + _instance.nodes.insert(make_pair(n->first, n->second.getInstance())); + } } // @@ -2571,52 +2571,52 @@ ApplicationHelper::ApplicationHelper(const Ice::CommunicatorPtr& communicator, // if(instantiate) { - multiset serverIds; - multiset adapterIds; - multiset objectIds; - for(n = _nodes.begin(); n != _nodes.end(); ++n) - { - n->second.getIds(serverIds, adapterIds, objectIds); - } - - for(ReplicaGroupDescriptorSeq::iterator r = _def.replicaGroups.begin(); r != _def.replicaGroups.end(); ++r) - { - if(r->id.empty()) - { - throw DeploymentException("replica group id is empty"); - } - if(adapterIds.find(r->id) != adapterIds.end()) - { - throw DeploymentException("duplicate replica group `" + r->id + "'"); - } - adapterIds.insert(r->id); - for(ObjectDescriptorSeq::const_iterator o = r->objects.begin(); o != r->objects.end(); ++o) - { - objectIds.insert(o->id); - } - } - - for(multiset::const_iterator s = serverIds.begin(); s != serverIds.end(); ++s) - { - if(serverIds.count(*s) > 1) - { - resolve.exception("duplicate server `" + *s + "'"); - } - } - for(multiset::const_iterator a = adapterIds.begin(); a != adapterIds.end(); ++a) - { - if(adapterIds.count(*a) > 1) - { - resolve.exception("duplicate adapter `" + *a + "'"); - } - } - for(multiset::const_iterator o = objectIds.begin(); o != objectIds.end(); ++o) - { - if(objectIds.count(*o) > 1) - { - resolve.exception("duplicate object `" + _communicator->identityToString(*o) + "'"); - } - } + multiset serverIds; + multiset adapterIds; + multiset objectIds; + for(n = _nodes.begin(); n != _nodes.end(); ++n) + { + n->second.getIds(serverIds, adapterIds, objectIds); + } + + for(ReplicaGroupDescriptorSeq::iterator r = _def.replicaGroups.begin(); r != _def.replicaGroups.end(); ++r) + { + if(r->id.empty()) + { + throw DeploymentException("replica group id is empty"); + } + if(adapterIds.find(r->id) != adapterIds.end()) + { + throw DeploymentException("duplicate replica group `" + r->id + "'"); + } + adapterIds.insert(r->id); + for(ObjectDescriptorSeq::const_iterator o = r->objects.begin(); o != r->objects.end(); ++o) + { + objectIds.insert(o->id); + } + } + + for(multiset::const_iterator s = serverIds.begin(); s != serverIds.end(); ++s) + { + if(serverIds.count(*s) > 1) + { + resolve.exception("duplicate server `" + *s + "'"); + } + } + for(multiset::const_iterator a = adapterIds.begin(); a != adapterIds.end(); ++a) + { + if(adapterIds.count(*a) > 1) + { + resolve.exception("duplicate adapter `" + *a + "'"); + } + } + for(multiset::const_iterator o = objectIds.begin(); o != objectIds.end(); ++o) + { + if(objectIds.count(*o) > 1) + { + resolve.exception("duplicate object `" + _communicator->identityToString(*o) + "'"); + } + } } } @@ -2629,7 +2629,7 @@ ApplicationHelper::diff(const ApplicationHelper& helper) const updt.name = _def.name; if(_def.description != helper._def.description) { - updt.description = new BoxedString(_def.description); + updt.description = new BoxedString(_def.description); } updt.variables = getDictUpdatedElts(helper._def.variables, _def.variables); @@ -2640,7 +2640,7 @@ ApplicationHelper::diff(const ApplicationHelper& helper) const if(_def.distrib != helper._def.distrib) { - updt.distrib = new BoxedDistributionDescriptor(_def.distrib); + updt.distrib = new BoxedDistributionDescriptor(_def.distrib); } GetReplicaGroupId rk; @@ -2657,23 +2657,23 @@ ApplicationHelper::diff(const ApplicationHelper& helper) const NodeHelperDict updated = getDictUpdatedElts(helper._nodes, _nodes); for(NodeHelperDict::const_iterator p = updated.begin(); p != updated.end(); ++p) { - NodeHelperDict::const_iterator q = helper._nodes.find(p->first); - if(q == helper._nodes.end()) - { - NodeUpdateDescriptor nodeUpdate; - const NodeDescriptor& node = p->second.getDefinition(); - nodeUpdate.name = p->first; - nodeUpdate.variables = node.variables; - nodeUpdate.servers = node.servers; - nodeUpdate.serverInstances = node.serverInstances; - nodeUpdate.loadFactor = new BoxedString(node.loadFactor); - nodeUpdate.description = new BoxedString(node.description); - updt.nodes.push_back(nodeUpdate); - } - else - { - updt.nodes.push_back(p->second.diff(q->second)); - } + NodeHelperDict::const_iterator q = helper._nodes.find(p->first); + if(q == helper._nodes.end()) + { + NodeUpdateDescriptor nodeUpdate; + const NodeDescriptor& node = p->second.getDefinition(); + nodeUpdate.name = p->first; + nodeUpdate.variables = node.variables; + nodeUpdate.servers = node.servers; + nodeUpdate.serverInstances = node.serverInstances; + nodeUpdate.loadFactor = new BoxedString(node.loadFactor); + nodeUpdate.description = new BoxedString(node.description); + updt.nodes.push_back(nodeUpdate); + } + else + { + updt.nodes.push_back(p->second.diff(q->second)); + } } updt.removeNodes = getDictRemovedElts(helper._nodes, _nodes); @@ -2698,50 +2698,50 @@ ApplicationHelper::update(const ApplicationUpdateDescriptor& updt) const Resolver resolve(def, _communicator, false); // A resolver based on the *updated* application descriptor. for(NodeUpdateDescriptorSeq::const_iterator p = updt.nodes.begin(); p != updt.nodes.end(); ++p) { - NodeHelperDict::const_iterator q = _nodes.find(p->name); - if(q != _nodes.end()) // Updated node - { - // - // COMPILERBUG: AIX xlC (Visual Age 6, 64bit builds) - // requires the `desc' temporary here. We can't do the - // update call in the make_pair call directly (this - // results in a SEGFAULT at runtime). - // - NodeDescriptor desc = q->second.update(*p, resolve); - def.nodes.insert(make_pair(p->name, desc)); - } - else // New node - { - NodeDescriptor desc; - desc.variables = p->variables; - if(!p->removeVariables.empty()) - { - resolve.exception("can't remove variables for node `" + p->name + "': node doesn't exist"); - } - desc.propertySets = p->propertySets; - if(!p->removePropertySets.empty()) - { - resolve.exception("can't remove property sets for node `" + p->name + "': node doesn't exist"); - } - desc.servers = p->servers; - desc.serverInstances = p->serverInstances; - if(!p->removeServers.empty()) - { - resolve.exception("can't remove servers for node `" + p->name + "': node doesn't exist"); - } - desc.loadFactor = p->loadFactor ? p->loadFactor->value : string(""); - desc.description = p->description ? p->description->value : string(""); - def.nodes.insert(make_pair(p->name, desc)); - } + NodeHelperDict::const_iterator q = _nodes.find(p->name); + if(q != _nodes.end()) // Updated node + { + // + // COMPILERBUG: AIX xlC (Visual Age 6, 64bit builds) + // requires the `desc' temporary here. We can't do the + // update call in the make_pair call directly (this + // results in a SEGFAULT at runtime). + // + NodeDescriptor desc = q->second.update(*p, resolve); + def.nodes.insert(make_pair(p->name, desc)); + } + else // New node + { + NodeDescriptor desc; + desc.variables = p->variables; + if(!p->removeVariables.empty()) + { + resolve.exception("can't remove variables for node `" + p->name + "': node doesn't exist"); + } + desc.propertySets = p->propertySets; + if(!p->removePropertySets.empty()) + { + resolve.exception("can't remove property sets for node `" + p->name + "': node doesn't exist"); + } + desc.servers = p->servers; + desc.serverInstances = p->serverInstances; + if(!p->removeServers.empty()) + { + resolve.exception("can't remove servers for node `" + p->name + "': node doesn't exist"); + } + desc.loadFactor = p->loadFactor ? p->loadFactor->value : string(""); + desc.description = p->description ? p->description->value : string(""); + def.nodes.insert(make_pair(p->name, desc)); + } } set removedNodes(updt.removeNodes.begin(), updt.removeNodes.end()); for(NodeHelperDict::const_iterator n = _nodes.begin(); n != _nodes.end(); ++n) { - if(removedNodes.find(n->first) != removedNodes.end() || def.nodes.find(n->first) != def.nodes.end()) - { - continue; // Node was removed or updated. - } - def.nodes.insert(make_pair(n->first, n->second.getDefinition())); + if(removedNodes.find(n->first) != removedNodes.end() || def.nodes.find(n->first) != def.nodes.end()) + { + continue; // Node was removed or updated. + } + def.nodes.insert(make_pair(n->first, n->second.getDefinition())); } return def; @@ -2754,24 +2754,24 @@ ApplicationHelper::upgrade(ApplicationDescriptor& desc) const bool upgraded = false; for(NodeHelperDict::const_iterator n = _nodes.begin(); n != _nodes.end(); ++n) { - NodeDescriptor nodeDesc; - if(n->second.upgrade(nodeDesc)) - { - desc.nodes[n->first] = nodeDesc; - upgraded = true; - } + NodeDescriptor nodeDesc; + if(n->second.upgrade(nodeDesc)) + { + desc.nodes[n->first] = nodeDesc; + upgraded = true; + } } TemplateDescriptorDict::iterator t; for(t = desc.serverTemplates.begin(); t != desc.serverTemplates.end(); ++t) { - ServerDescriptorPtr desc = ServerDescriptorPtr::dynamicCast(t->second.descriptor); - upgraded |= createHelper(desc)->upgrade(t->second.descriptor); + ServerDescriptorPtr desc = ServerDescriptorPtr::dynamicCast(t->second.descriptor); + upgraded |= createHelper(desc)->upgrade(t->second.descriptor); } for(t = desc.serviceTemplates.begin(); t != desc.serviceTemplates.end(); ++t) { - ServiceDescriptorPtr desc = ServiceDescriptorPtr::dynamicCast(t->second.descriptor); - upgraded |= ServiceHelper(desc).upgrade(t->second.descriptor); + ServiceDescriptorPtr desc = ServiceDescriptorPtr::dynamicCast(t->second.descriptor); + upgraded |= ServiceHelper(desc).upgrade(t->second.descriptor); } return upgraded; @@ -2790,13 +2790,13 @@ ApplicationHelper::instantiateServer(const string& node, const ServerInstanceDes NodeDescriptorDict::iterator q = def.nodes.find(node); if(q == def.nodes.end()) { - NodeDescriptor desc; - desc.serverInstances.push_back(instance); - def.nodes.insert(make_pair(node, desc)); + NodeDescriptor desc; + desc.serverInstances.push_back(instance); + def.nodes.insert(make_pair(node, desc)); } else { - q->second.serverInstances.push_back(instance); + q->second.serverInstances.push_back(instance); } return def; } @@ -2810,16 +2810,16 @@ ApplicationHelper::getIds(set& serverIds, set& adapterIds, setsecond.getIds(sIds, aIds, oIds); + p->second.getIds(sIds, aIds, oIds); } ReplicaGroupDescriptorSeq::const_iterator r; for(r = _def.replicaGroups.begin(); r != _def.replicaGroups.end(); ++r) { - aIds.insert(r->id); - for(ObjectDescriptorSeq::const_iterator o = r->objects.begin(); o != r->objects.end(); ++o) - { - oIds.insert(o->id); - } + aIds.insert(r->id); + for(ObjectDescriptorSeq::const_iterator o = r->objects.begin(); o != r->objects.end(); ++o) + { + oIds.insert(o->id); + } } copy(sIds.begin(), sIds.end(), inserter(serverIds, serverIds.begin())); @@ -2848,34 +2848,34 @@ ApplicationHelper::getServerInfos(const string& uuid, int revision) const map servers; for(NodeHelperDict::const_iterator n = _nodes.begin(); n != _nodes.end(); ++n) { - n->second.getServerInfos(_def.name, uuid, revision, servers); + n->second.getServerInfos(_def.name, uuid, revision, servers); } return servers; } void ApplicationHelper::getDistributions(DistributionDescriptor& distribution, - vector& nodes, - const string& server) const + vector& nodes, + const string& server) const { assert(!_instance.name.empty()); distribution = _instance.distrib; for(NodeHelperDict::const_iterator n = _nodes.begin(); n != _nodes.end(); ++n) { - if(n->second.hasDistributions(server)) - { - nodes.push_back(n->first); - if(!server.empty()) - { - break; - } - } - else if(!_instance.distrib.icepatch.empty() && - (server.empty() && n->second.hasServers() || n->second.hasServer(server))) - { - nodes.push_back(n->first); - } + if(n->second.hasDistributions(server)) + { + nodes.push_back(n->first); + if(!server.empty()) + { + break; + } + } + else if(!_instance.distrib.icepatch.empty() && + (server.empty() && n->second.hasServers() || n->second.hasServer(server))) + { + nodes.push_back(n->first); + } } } @@ -2895,109 +2895,109 @@ ApplicationHelper::print(Output& out, const ApplicationInfo& info) const if(!_instance.description.empty()) { - out << nl << "description = `" << _instance.description << "'"; + out << nl << "description = `" << _instance.description << "'"; } if(!_instance.variables.empty()) { - out << nl << "variables"; - out << sb; - for(StringStringDict::const_iterator p = _instance.variables.begin(); p != _instance.variables.end(); - ++p) - { - out << nl << p->first << " = `" << p->second << "'"; - } - out << eb; + out << nl << "variables"; + out << sb; + for(StringStringDict::const_iterator p = _instance.variables.begin(); p != _instance.variables.end(); + ++p) + { + out << nl << p->first << " = `" << p->second << "'"; + } + out << eb; } if(!_instance.propertySets.empty()) { - PropertySetDescriptorDict::const_iterator q; - for(q = _instance.propertySets.begin(); q != _instance.propertySets.end(); ++q) - { - out << nl << "properties `" << q->first << "'"; - out << sb; - if(!q->second.references.empty()) - { - out << nl << "references = " << toString(q->second.references); - } - PropertyDescriptorSeq::const_iterator r; - for(r = q->second.properties.begin(); r != q->second.properties.end(); ++r) - { - out << nl << r->name << " = `" << r->value << "'"; - } - out << eb; - } + PropertySetDescriptorDict::const_iterator q; + for(q = _instance.propertySets.begin(); q != _instance.propertySets.end(); ++q) + { + out << nl << "properties `" << q->first << "'"; + out << sb; + if(!q->second.references.empty()) + { + out << nl << "references = " << toString(q->second.references); + } + PropertyDescriptorSeq::const_iterator r; + for(r = q->second.properties.begin(); r != q->second.properties.end(); ++r) + { + out << nl << r->name << " = `" << r->value << "'"; + } + out << eb; + } } if(!_instance.distrib.icepatch.empty()) { - out << nl << "distribution"; - out << sb; - out << nl << "proxy = `" << _instance.distrib.icepatch << "'"; - if(!_instance.distrib.directories.empty()) - { - out << nl << "directories = `" << toString(_instance.distrib.directories) << "'"; - } - out << eb; + out << nl << "distribution"; + out << sb; + out << nl << "proxy = `" << _instance.distrib.icepatch << "'"; + if(!_instance.distrib.directories.empty()) + { + out << nl << "directories = `" << toString(_instance.distrib.directories) << "'"; + } + out << eb; } if(!_instance.replicaGroups.empty()) { - out << nl << "replica groups"; - out << sb; - ReplicaGroupDescriptorSeq::const_iterator p; - for(p = _instance.replicaGroups.begin(); p != _instance.replicaGroups.end(); ++p) - { - out << nl << "id = `" << p->id << "' load balancing = `"; - if(!p->loadBalancing) - { - out << "default (return all endpoints)"; - } - else if(RandomLoadBalancingPolicyPtr::dynamicCast(p->loadBalancing)) - { - out << "random"; - } - else if(RoundRobinLoadBalancingPolicyPtr::dynamicCast(p->loadBalancing)) - { - out << "round-robin"; - } - else if(AdaptiveLoadBalancingPolicyPtr::dynamicCast(p->loadBalancing)) - { - out << "adaptive" ; - } - else - { - out << ""; - } - out << "'"; - } - out << eb; + out << nl << "replica groups"; + out << sb; + ReplicaGroupDescriptorSeq::const_iterator p; + for(p = _instance.replicaGroups.begin(); p != _instance.replicaGroups.end(); ++p) + { + out << nl << "id = `" << p->id << "' load balancing = `"; + if(!p->loadBalancing) + { + out << "default (return all endpoints)"; + } + else if(RandomLoadBalancingPolicyPtr::dynamicCast(p->loadBalancing)) + { + out << "random"; + } + else if(RoundRobinLoadBalancingPolicyPtr::dynamicCast(p->loadBalancing)) + { + out << "round-robin"; + } + else if(AdaptiveLoadBalancingPolicyPtr::dynamicCast(p->loadBalancing)) + { + out << "adaptive" ; + } + else + { + out << ""; + } + out << "'"; + } + out << eb; } if(!_instance.serverTemplates.empty()) { - out << nl << "server templates"; - out << sb; - TemplateDescriptorDict::const_iterator p; - for(p = _instance.serverTemplates.begin(); p != _instance.serverTemplates.end(); ++p) - { - out << nl << p->first; - } - out << eb; + out << nl << "server templates"; + out << sb; + TemplateDescriptorDict::const_iterator p; + for(p = _instance.serverTemplates.begin(); p != _instance.serverTemplates.end(); ++p) + { + out << nl << p->first; + } + out << eb; } if(!_instance.serviceTemplates.empty()) { - out << nl << "service templates"; - out << sb; - TemplateDescriptorDict::const_iterator p; - for(p = _instance.serviceTemplates.begin(); p != _instance.serviceTemplates.end(); ++p) - { - out << nl << p->first; - } - out << eb; + out << nl << "service templates"; + out << sb; + TemplateDescriptorDict::const_iterator p; + for(p = _instance.serviceTemplates.begin(); p != _instance.serviceTemplates.end(); ++p) + { + out << nl << p->first; + } + out << eb; } if(!_nodes.empty()) { - for(NodeHelperDict::const_iterator p = _nodes.begin(); p != _nodes.end(); ++p) - { - p->second.print(out); - } + for(NodeHelperDict::const_iterator p = _nodes.begin(); p != _nodes.end(); ++p) + { + p->second.print(out); + } } out << eb; } @@ -3011,157 +3011,157 @@ ApplicationHelper::printDiff(Output& out, const ApplicationHelper& helper) const out << sb; { - map variables = getDictUpdatedElts(helper._def.variables, _def.variables); - Ice::StringSeq removeVariables = getDictRemovedElts(helper._def.variables, _def.variables); - if(!variables.empty() || !removeVariables.empty()) - { - out << nl << "variables udpated"; - } - } - { - if(_def.distrib != helper._def.distrib) - { - out << nl << "distribution updated"; - } - } - { - PropertySetDescriptorDict updt = getDictUpdatedElts(helper._def.propertySets, _def.propertySets); - Ice::StringSeq removed = getDictRemovedElts(helper._def.propertySets, _def.propertySets); - if(!updt.empty() || !removed.empty()) - { - out << nl << "property sets udpated"; - } - } - { - GetReplicaGroupId rk; - ReplicaGroupEq req; - ReplicaGroupDescriptorSeq updated = - getSeqUpdatedEltsWithEq(helper._def.replicaGroups, _def.replicaGroups, rk, req); - Ice::StringSeq removed = getSeqRemovedElts(helper._def.replicaGroups, _def.replicaGroups, rk); - if(!updated.empty() || !removed.empty()) - { - out << nl << "replica groups"; - out << sb; - ReplicaGroupDescriptorSeq::iterator p = updated.begin(); - while(p != updated.end()) - { - ReplicaGroupDescriptorSeq::const_iterator r; - for(r = helper._def.replicaGroups.begin(); r != helper._def.replicaGroups.end(); - ++r) - { - if(p->id == r->id) - { - out << nl << "replica group `" << r->id << "' updated"; - p = updated.erase(p); - break; - } - } - if(r == helper._def.replicaGroups.end()) - { - ++p; - } - } - for(p = updated.begin(); p != updated.end(); ++p) - { - out << nl << "replica group `" << p->id << "' added"; - } - for(Ice::StringSeq::const_iterator q = removed.begin(); q != removed.end(); ++q) - { - out << nl << "replica group `" << *q << "' removed"; - } - out << eb; - } - } - - { - TemplateDescriptorEqual eq; - TemplateDescriptorDict updated; - updated = getDictUpdatedEltsWithEq(helper._def.serverTemplates, _def.serverTemplates, eq); - Ice::StringSeq removed = getDictRemovedElts(helper._def.serverTemplates, _def.serverTemplates); - if(!updated.empty() || !removed.empty()) - { - out << nl << "server templates"; - out << sb; - for(TemplateDescriptorDict::const_iterator p = updated.begin(); p != updated.end(); ++p) - { - if(helper._def.serverTemplates.find(p->first) == helper._def.serverTemplates.end()) - { - out << nl << "server template `" << p->first << "' added"; - } - } - for(TemplateDescriptorDict::const_iterator q = updated.begin(); q != updated.end(); ++q) - { - if(helper._def.serverTemplates.find(q->first) != helper._def.serverTemplates.end()) - { - out << nl << "server template `" << q->first << "' updated"; - } - } - for(Ice::StringSeq::const_iterator r = removed.begin(); r != removed.end(); ++r) - { - out << nl << "server template `" << *r << "' removed"; - } - out << eb; - } - } - { - TemplateDescriptorEqual eq; - TemplateDescriptorDict updated; - updated = getDictUpdatedEltsWithEq(helper._def.serviceTemplates, _def.serviceTemplates, eq); - Ice::StringSeq removed = getDictRemovedElts(helper._def.serviceTemplates, _def.serviceTemplates); - if(!updated.empty() || !removed.empty()) - { - out << nl << "service templates"; - out << sb; - for(TemplateDescriptorDict::const_iterator p = updated.begin(); p != updated.end(); ++p) - { - if(helper._def.serviceTemplates.find(p->first) == helper._def.serviceTemplates.end()) - { - out << nl << "service template `" << p->first << "' added"; - } - } - for(TemplateDescriptorDict::const_iterator q = updated.begin(); q != updated.end(); ++q) - { - if(helper._def.serviceTemplates.find(q->first) != helper._def.serviceTemplates.end()) - { - out << nl << "service template `" << q->first << "' updated"; - } - } - for(Ice::StringSeq::const_iterator r = removed.begin(); r != removed.end(); ++r) - { - out << nl << "service template `" << *r << "' removed"; - } - out << eb; - } - } - { - NodeHelperDict updated = getDictUpdatedElts(helper._nodes, _nodes); - Ice::StringSeq removed = getDictRemovedElts(helper._nodes, _nodes); - if(!updated.empty() || !removed.empty()) - { - out << nl << "nodes"; - out << sb; - for(NodeHelperDict::const_iterator p = updated.begin(); p != updated.end(); ++p) - { - NodeHelperDict::const_iterator q = helper._nodes.find(p->first); - if(q == helper._nodes.end()) - { - p->second.print(out); - } - } - for(NodeHelperDict::const_iterator r = updated.begin(); r != updated.end(); ++r) - { - NodeHelperDict::const_iterator q = helper._nodes.find(r->first); - if(q != helper._nodes.end()) - { - r->second.printDiff(out, q->second); - } - } - for(Ice::StringSeq::const_iterator s = removed.begin(); s != removed.end(); ++s) - { - out << nl << "node `" << *s << "' removed"; - } - out << eb; - } + map variables = getDictUpdatedElts(helper._def.variables, _def.variables); + Ice::StringSeq removeVariables = getDictRemovedElts(helper._def.variables, _def.variables); + if(!variables.empty() || !removeVariables.empty()) + { + out << nl << "variables udpated"; + } + } + { + if(_def.distrib != helper._def.distrib) + { + out << nl << "distribution updated"; + } + } + { + PropertySetDescriptorDict updt = getDictUpdatedElts(helper._def.propertySets, _def.propertySets); + Ice::StringSeq removed = getDictRemovedElts(helper._def.propertySets, _def.propertySets); + if(!updt.empty() || !removed.empty()) + { + out << nl << "property sets udpated"; + } + } + { + GetReplicaGroupId rk; + ReplicaGroupEq req; + ReplicaGroupDescriptorSeq updated = + getSeqUpdatedEltsWithEq(helper._def.replicaGroups, _def.replicaGroups, rk, req); + Ice::StringSeq removed = getSeqRemovedElts(helper._def.replicaGroups, _def.replicaGroups, rk); + if(!updated.empty() || !removed.empty()) + { + out << nl << "replica groups"; + out << sb; + ReplicaGroupDescriptorSeq::iterator p = updated.begin(); + while(p != updated.end()) + { + ReplicaGroupDescriptorSeq::const_iterator r; + for(r = helper._def.replicaGroups.begin(); r != helper._def.replicaGroups.end(); + ++r) + { + if(p->id == r->id) + { + out << nl << "replica group `" << r->id << "' updated"; + p = updated.erase(p); + break; + } + } + if(r == helper._def.replicaGroups.end()) + { + ++p; + } + } + for(p = updated.begin(); p != updated.end(); ++p) + { + out << nl << "replica group `" << p->id << "' added"; + } + for(Ice::StringSeq::const_iterator q = removed.begin(); q != removed.end(); ++q) + { + out << nl << "replica group `" << *q << "' removed"; + } + out << eb; + } + } + + { + TemplateDescriptorEqual eq; + TemplateDescriptorDict updated; + updated = getDictUpdatedEltsWithEq(helper._def.serverTemplates, _def.serverTemplates, eq); + Ice::StringSeq removed = getDictRemovedElts(helper._def.serverTemplates, _def.serverTemplates); + if(!updated.empty() || !removed.empty()) + { + out << nl << "server templates"; + out << sb; + for(TemplateDescriptorDict::const_iterator p = updated.begin(); p != updated.end(); ++p) + { + if(helper._def.serverTemplates.find(p->first) == helper._def.serverTemplates.end()) + { + out << nl << "server template `" << p->first << "' added"; + } + } + for(TemplateDescriptorDict::const_iterator q = updated.begin(); q != updated.end(); ++q) + { + if(helper._def.serverTemplates.find(q->first) != helper._def.serverTemplates.end()) + { + out << nl << "server template `" << q->first << "' updated"; + } + } + for(Ice::StringSeq::const_iterator r = removed.begin(); r != removed.end(); ++r) + { + out << nl << "server template `" << *r << "' removed"; + } + out << eb; + } + } + { + TemplateDescriptorEqual eq; + TemplateDescriptorDict updated; + updated = getDictUpdatedEltsWithEq(helper._def.serviceTemplates, _def.serviceTemplates, eq); + Ice::StringSeq removed = getDictRemovedElts(helper._def.serviceTemplates, _def.serviceTemplates); + if(!updated.empty() || !removed.empty()) + { + out << nl << "service templates"; + out << sb; + for(TemplateDescriptorDict::const_iterator p = updated.begin(); p != updated.end(); ++p) + { + if(helper._def.serviceTemplates.find(p->first) == helper._def.serviceTemplates.end()) + { + out << nl << "service template `" << p->first << "' added"; + } + } + for(TemplateDescriptorDict::const_iterator q = updated.begin(); q != updated.end(); ++q) + { + if(helper._def.serviceTemplates.find(q->first) != helper._def.serviceTemplates.end()) + { + out << nl << "service template `" << q->first << "' updated"; + } + } + for(Ice::StringSeq::const_iterator r = removed.begin(); r != removed.end(); ++r) + { + out << nl << "service template `" << *r << "' removed"; + } + out << eb; + } + } + { + NodeHelperDict updated = getDictUpdatedElts(helper._nodes, _nodes); + Ice::StringSeq removed = getDictRemovedElts(helper._nodes, _nodes); + if(!updated.empty() || !removed.empty()) + { + out << nl << "nodes"; + out << sb; + for(NodeHelperDict::const_iterator p = updated.begin(); p != updated.end(); ++p) + { + NodeHelperDict::const_iterator q = helper._nodes.find(p->first); + if(q == helper._nodes.end()) + { + p->second.print(out); + } + } + for(NodeHelperDict::const_iterator r = updated.begin(); r != updated.end(); ++r) + { + NodeHelperDict::const_iterator q = helper._nodes.find(r->first); + if(q != helper._nodes.end()) + { + r->second.printDiff(out, q->second); + } + } + for(Ice::StringSeq::const_iterator s = removed.begin(); s != removed.end(); ++s) + { + out << nl << "node `" << *s << "' removed"; + } + out << eb; + } } out << eb; } @@ -3173,15 +3173,15 @@ IceGrid::descriptorEqual(const ServerDescriptorPtr& lhs, const ServerDescriptorP IceBoxDescriptorPtr rhsIceBox = IceBoxDescriptorPtr::dynamicCast(rhs); if(lhsIceBox && rhsIceBox) { - return IceBoxHelper(lhsIceBox) == IceBoxHelper(rhsIceBox); + return IceBoxHelper(lhsIceBox) == IceBoxHelper(rhsIceBox); } else if(!lhsIceBox && !rhsIceBox) { - return ServerHelper(lhs) == ServerHelper(rhs); + return ServerHelper(lhs) == ServerHelper(rhs); } else { - return false; + return false; } } @@ -3191,10 +3191,10 @@ IceGrid::createHelper(const ServerDescriptorPtr& desc) IceBoxDescriptorPtr iceBox = IceBoxDescriptorPtr::dynamicCast(desc); if(iceBox) { - return new IceBoxHelper(iceBox); + return new IceBoxHelper(iceBox); } else { - return new ServerHelper(desc); + return new ServerHelper(desc); } } diff --git a/cpp/src/IceGrid/DescriptorHelper.h b/cpp/src/IceGrid/DescriptorHelper.h index 6ca60f0a170..2564d68d18d 100644 --- a/cpp/src/IceGrid/DescriptorHelper.h +++ b/cpp/src/IceGrid/DescriptorHelper.h @@ -120,14 +120,14 @@ public: ServiceDescriptorPtr getDescriptor() const; ServiceDescriptorPtr instantiate(const Resolver&, const PropertyDescriptorSeq&, - const PropertySetDescriptorDict&) const; + const PropertySetDescriptorDict&) const; void print(const Ice::CommunicatorPtr&, IceUtil::Output&) const; protected: void instantiateImpl(const ServiceDescriptorPtr&, const Resolver&, const PropertyDescriptorSeq&, - const PropertySetDescriptorDict&) const; + const PropertySetDescriptorDict&) const; private: @@ -146,7 +146,7 @@ public: ServerDescriptorPtr getDescriptor() const; virtual ServerDescriptorPtr instantiate(const Resolver&, const PropertyDescriptorSeq&, - const PropertySetDescriptorDict&) const; + const PropertySetDescriptorDict&) const; void print(const Ice::CommunicatorPtr&, IceUtil::Output&) const; void print(const Ice::CommunicatorPtr&, IceUtil::Output&, const ServerInfo&) const; @@ -167,10 +167,10 @@ class InstanceHelper protected: std::map instantiateParams(const Resolver&, - const std::string&, - const std::map&, - const std::vector&, - const std::map&) const; + const std::string&, + const std::map&, + const std::vector&, + const std::map&) const; }; @@ -206,7 +206,7 @@ public: bool operator!=(const IceBoxHelper&) const; virtual ServerDescriptorPtr instantiate(const Resolver&, const PropertyDescriptorSeq&, - const PropertySetDescriptorDict&) const; + const PropertySetDescriptorDict&) const; virtual void getIds(std::multiset&, std::multiset&) const; @@ -218,7 +218,7 @@ public: protected: void instantiateImpl(const IceBoxDescriptorPtr&, const Resolver&, const PropertyDescriptorSeq&, - const PropertySetDescriptorDict&) const; + const PropertySetDescriptorDict&) const; private: diff --git a/cpp/src/IceGrid/DescriptorParser.cpp b/cpp/src/IceGrid/DescriptorParser.cpp index 4fd68f57a7f..fac00758c70 100644 --- a/cpp/src/IceGrid/DescriptorParser.cpp +++ b/cpp/src/IceGrid/DescriptorParser.cpp @@ -114,366 +114,366 @@ DescriptorHandler::startElement(const string& name, const IceXML::Attributes& at try { - if(name == "icegrid") - { - if(!_isTopLevel) - { - error("element is a top level element"); - } - _isTopLevel = false; - } - else if(_isTopLevel) - { - error("only the element is allowed at the top-level"); - } - else if(name == "target") - { - if(!_isCurrentTargetDeployable) - { - ++_targetCounter; - } - else - { - _isCurrentTargetDeployable = isTargetDeployable(attributes("name")); - _targetCounter = 1; - return; - } - } - else if(!isCurrentTargetDeployable()) - { - // - // We don't bother to parse the elements if the elements are enclosed in a target element - // which won't be deployed. - // - attributes.asMap(); - return; - } - else if(name == "include") - { - string targets = attributes("targets", ""); - string file = attributes("file"); - if(file[0] != '/') - { - string::size_type end = _filename.find_last_of('/'); - if(end != string::npos) - { - file = _filename.substr(0, end) + "/" + file; - } - } - - string oldFileName = _filename; - vector oldTargets = _targets; - _isTopLevel = true; - _filename = file; - _targets = getTargets(targets); - - IceXML::Parser::parse(file, *this); - - _filename = oldFileName; - _targets = oldTargets; - } - else if(name == "application") - { - if(_currentApplication.get()) - { - error("only one element is allowed"); - } - - bool importTemplates = attributes.asBool("import-default-templates", false); - - // - // TODO: is ignoring importTemplates the desired behavior when _admin == 0? - // - if(importTemplates && _admin != 0) - { - try - { - ApplicationDescriptor application = _admin->getDefaultApplicationDescriptor(); - _currentApplication.reset(new ApplicationDescriptorBuilder(_communicator, application, - attributes, _overrides)); - } - catch(const DeploymentException& ex) - { - throw ex.reason; - } - } - else - { - _currentApplication.reset(new ApplicationDescriptorBuilder(_communicator, attributes, _overrides)); - } - } - else if(name == "node") - { - if(!_currentApplication.get()) - { - error("the element can only be a child of an element"); - } - _currentNode.reset(_currentApplication->createNode(attributes)); - } - else if(name == "server-instance") - { - if(!_currentNode.get() || _currentServer.get()) - { - error("the element can only be a child of a element"); - } - _currentServerInstance.reset(_currentNode->createServerInstance(attributes)); - } - else if(name == "server") - { - if(!_currentNode.get() && !_currentTemplate.get() || _currentServer.get()) - { - error("the element can only be a child of a or element"); - } - if(_currentNode.get()) - { - _currentServer.reset(_currentNode->createServer(attributes)); - } - else - { - _currentServer.reset(_currentTemplate->createServer(attributes)); - } - _currentCommunicator = _currentServer.get(); - } - else if(name == "icebox") - { - if(!_currentNode.get() && !_currentTemplate.get() || _currentServer.get()) - { - error("the element can only be a child of a or element"); - } - if(_currentNode.get()) - { - _currentServer.reset(_currentNode->createIceBox(attributes)); - } - else - { - _currentServer.reset(_currentTemplate->createIceBox(attributes)); - } - _currentCommunicator = _currentServer.get(); - } - else if(name == "server-template") - { - if(!_currentApplication.get() || _currentTemplate.get() || _currentNode.get()) - { - error("the element can only be a child of an element"); - } - _currentTemplate.reset(_currentApplication->createServerTemplate(attributes)); - } - else if(name == "service-instance") - { - if(!_currentServer.get()) - { - error("the element can only be a child of an element"); - } - _currentServiceInstance.reset(_currentServer->createServiceInstance(attributes)); - } - else if(name == "service") - { - if(!_currentServer.get() && !_currentTemplate.get() || _currentService.get()) - { - error("the element can only be a child of an or element"); - } - - if(_currentServer.get()) - { - _currentService.reset(_currentServer->createService(attributes)); - } - else - { - _currentService.reset(_currentTemplate->createService(attributes)); - } - _currentCommunicator = _currentService.get(); - } - else if(name == "service-template") - { - if(!_currentApplication.get() || _currentNode.get() || _currentTemplate.get()) - { - error("the element can only be a child of an element"); - } - - _currentTemplate.reset(_currentApplication->createServiceTemplate(attributes)); - } - else if(name == "replica-group") - { - if(!_currentApplication.get()) - { - error("the element can only be a child of an element"); - } - _currentApplication->addReplicaGroup(attributes); - _inReplicaGroup = true; - } - else if(name == "load-balancing") - { - if(!_inReplicaGroup) - { - error("the element can only be a child of a element"); - } - _currentApplication->setLoadBalancing(attributes); - } - else if(name == "variable") - { - if(_currentNode.get()) - { - _currentNode->addVariable(attributes); - } - else if(_currentApplication.get()) - { - _currentApplication->addVariable(attributes); - } - else - { - error("the element can only be a child of an or element"); - } - } - else if(name == "parameter") - { - if(!_currentTemplate.get()) - { - error("the element can only be a child of a