summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorTobias Markmann <tm@ayena.de>2012-03-20 00:05:55 (GMT)
committerRemko Tronçon <git@el-tramo.be>2012-03-20 19:13:43 (GMT)
commit3d6694b0c698fff63d11f8bb4aa995c1df882315 (patch)
treea46ccace647f23a65100cf69c951345aa6dea7ab
parent3d27d98ccc232ae7bfacfd5a3f85f44b6c2e9cc9 (diff)
downloadswift-contrib-3d6694b0c698fff63d11f8bb4aa995c1df882315.zip
swift-contrib-3d6694b0c698fff63d11f8bb4aa995c1df882315.tar.bz2
boost::shared_ptr<?>(new ?(...)) -> boost::make_shared<?>(...) transformation where possible.
License: This patch is BSD-licensed, see http://www.opensource.org/licenses/bsd-license.php
-rw-r--r--Limber/Server/ServerFromClientSession.cpp5
-rw-r--r--Limber/main.cpp2
-rw-r--r--Slimber/FileVCardCollection.cpp3
-rw-r--r--Slimber/Server.cpp2
-rw-r--r--Slimber/UnitTest/LinkLocalPresenceManagerTest.cpp2
-rw-r--r--Swift/Controllers/Chat/ChatController.cpp3
-rw-r--r--Swift/Controllers/Chat/ChatControllerBase.cpp3
-rw-r--r--Swift/Controllers/Chat/ChatsManager.cpp3
-rw-r--r--Swift/Controllers/Chat/UnitTest/ChatsManagerTest.cpp4
-rw-r--r--Swift/Controllers/Chat/UserSearchController.cpp3
-rw-r--r--Swift/Controllers/MainController.cpp6
-rw-r--r--Swift/Controllers/Roster/UnitTest/RosterTest.cpp4
-rw-r--r--Swift/Controllers/StatusTracker.cpp8
-rw-r--r--Swift/QtUI/EventViewer/main.cpp2
-rw-r--r--Swift/QtUI/QtLoginWindow.cpp2
-rw-r--r--Swiften/Avatars/UnitTest/VCardUpdateAvatarManagerTest.cpp2
-rw-r--r--Swiften/Client/UnitTest/ClientSessionTest.cpp20
-rw-r--r--Swiften/Component/ComponentSession.cpp3
-rw-r--r--Swiften/Component/UnitTest/ComponentSessionTest.cpp4
-rw-r--r--Swiften/Disco/DiscoInfoResponder.cpp6
-rw-r--r--Swiften/Disco/GetDiscoInfoRequest.h6
-rw-r--r--Swiften/Disco/GetDiscoItemsRequest.h6
-rw-r--r--Swiften/Disco/JIDDiscoInfoResponder.cpp6
-rw-r--r--Swiften/Disco/UnitTest/CapsManagerTest.cpp12
-rw-r--r--Swiften/Disco/UnitTest/EntityCapsManagerTest.cpp12
-rw-r--r--Swiften/Elements/UnitTest/StanzaTest.cpp66
-rw-r--r--Swiften/Examples/SendFile/SendFile.cpp2
-rw-r--r--Swiften/FileTransfer/OutgoingSIFileTransfer.cpp3
-rw-r--r--Swiften/FileTransfer/UnitTest/IBBSendSessionTest.cpp2
-rw-r--r--Swiften/FileTransfer/UnitTest/SOCKS5BytestreamClientSessionTest.cpp2
-rw-r--r--Swiften/FileTransfer/UnitTest/SOCKS5BytestreamServerSessionTest.cpp4
-rw-r--r--Swiften/LinkLocal/IncomingLinkLocalSession.cpp3
-rw-r--r--Swiften/LinkLocal/UnitTest/LinkLocalConnectorTest.cpp5
-rw-r--r--Swiften/LinkLocal/UnitTest/LinkLocalServiceBrowserTest.cpp3
-rw-r--r--Swiften/MUC/MUCBookmarkManager.cpp3
-rw-r--r--Swiften/Parser/PayloadParsers/SecurityLabelsCatalogParser.cpp4
-rw-r--r--Swiften/Parser/UnitTest/StanzaParserTest.cpp2
-rw-r--r--Swiften/Presence/UnitTest/DirectedPresenceSenderTest.cpp4
-rw-r--r--Swiften/Queries/Requests/GetPrivateStorageRequest.h3
-rw-r--r--Swiften/Queries/Requests/GetSecurityLabelsCatalogRequest.h4
-rw-r--r--Swiften/Queries/Requests/SetPrivateStorageRequest.h3
-rw-r--r--Swiften/Queries/Responders/SoftwareVersionResponder.cpp4
-rw-r--r--Swiften/Queries/UnitTest/IQRouterTest.cpp23
-rw-r--r--Swiften/Queries/UnitTest/RequestTest.cpp2
-rw-r--r--Swiften/Queries/UnitTest/ResponderTest.cpp5
-rw-r--r--Swiften/Serializer/PayloadSerializers/CommandSerializer.cpp7
-rw-r--r--Swiften/Serializer/PayloadSerializers/DiscoInfoSerializer.cpp3
-rw-r--r--Swiften/Serializer/PayloadSerializers/FormSerializer.cpp7
-rw-r--r--Swiften/Serializer/PayloadSerializers/IBBSerializer.cpp3
-rw-r--r--Swiften/Serializer/PayloadSerializers/InBandRegistrationPayloadSerializer.cpp3
-rw-r--r--Swiften/Serializer/PayloadSerializers/JinglePayloadSerializer.cpp2
-rw-r--r--Swiften/Serializer/PayloadSerializers/MUCOwnerPayloadSerializer.cpp4
-rw-r--r--Swiften/Serializer/PayloadSerializers/MUCUserPayloadSerializer.cpp3
-rw-r--r--Swiften/Serializer/PayloadSerializers/NicknameSerializer.cpp3
-rw-r--r--Swiften/Serializer/PayloadSerializers/PrivateStorageSerializer.cpp3
-rw-r--r--Swiften/Serializer/PayloadSerializers/ResourceBindSerializer.cpp5
-rw-r--r--Swiften/Serializer/PayloadSerializers/RosterItemExchangeSerializer.cpp3
-rw-r--r--Swiften/Serializer/PayloadSerializers/RosterSerializer.cpp5
-rw-r--r--Swiften/Serializer/PayloadSerializers/SearchPayloadSerializer.cpp3
-rw-r--r--Swiften/Serializer/PayloadSerializers/SecurityLabelSerializer.cpp8
-rw-r--r--Swiften/Serializer/PayloadSerializers/SecurityLabelsCatalogSerializer.cpp4
-rw-r--r--Swiften/Serializer/PayloadSerializers/StatusSerializer.h4
-rw-r--r--Swiften/Serializer/PayloadSerializers/StorageSerializer.cpp5
-rw-r--r--Swiften/Serializer/PayloadSerializers/StreamInitiationSerializer.cpp7
-rw-r--r--Swiften/Serializer/PayloadSerializers/VCardSerializer.cpp31
-rw-r--r--Swiften/Serializer/PayloadSerializers/VCardUpdateSerializer.cpp3
-rw-r--r--Swiften/Serializer/StreamFeaturesSerializer.cpp12
-rw-r--r--Swiften/Serializer/XML/UnitTest/XMLElementTest.cpp6
-rw-r--r--Swiften/Session/BOSHSessionStream.cpp2
-rw-r--r--Swiften/Session/BasicSessionStream.cpp11
-rw-r--r--Swiften/StreamStack/UnitTest/XMPPLayerTest.cpp2
71 files changed, 241 insertions, 184 deletions
diff --git a/Limber/Server/ServerFromClientSession.cpp b/Limber/Server/ServerFromClientSession.cpp
index fd361b7..71a8fef 100644
--- a/Limber/Server/ServerFromClientSession.cpp
+++ b/Limber/Server/ServerFromClientSession.cpp
@@ -1,92 +1,93 @@
/*
* Copyright (c) 2010 Remko Tronçon
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
#include "Limber/Server/ServerFromClientSession.h"
+#include <boost/smart_ptr/make_shared.hpp>
#include <boost/bind.hpp>
#include "Swiften/Elements/ProtocolHeader.h"
#include "Limber/Server/UserRegistry.h"
#include "Swiften/Network/Connection.h"
#include "Swiften/StreamStack/XMPPLayer.h"
#include "Swiften/Elements/StreamFeatures.h"
#include "Swiften/Elements/ResourceBind.h"
#include "Swiften/Elements/StartSession.h"
#include "Swiften/Elements/IQ.h"
#include "Swiften/Elements/AuthSuccess.h"
#include "Swiften/Elements/AuthFailure.h"
#include "Swiften/Elements/AuthRequest.h"
#include "Swiften/SASL/PLAINMessage.h"
namespace Swift {
ServerFromClientSession::ServerFromClientSession(
const std::string& id,
boost::shared_ptr<Connection> connection,
PayloadParserFactoryCollection* payloadParserFactories,
PayloadSerializerCollection* payloadSerializers,
XMLParserFactory* xmlParserFactory,
UserRegistry* userRegistry) :
Session(connection, payloadParserFactories, payloadSerializers, xmlParserFactory),
id_(id),
userRegistry_(userRegistry),
authenticated_(false),
initialized(false),
allowSASLEXTERNAL(false) {
}
void ServerFromClientSession::handleElement(boost::shared_ptr<Element> element) {
if (isInitialized()) {
onElementReceived(element);
}
else {
if (AuthRequest* authRequest = dynamic_cast<AuthRequest*>(element.get())) {
if (authRequest->getMechanism() == "PLAIN" || (allowSASLEXTERNAL && authRequest->getMechanism() == "EXTERNAL")) {
if (authRequest->getMechanism() == "EXTERNAL") {
- getXMPPLayer()->writeElement(boost::shared_ptr<AuthSuccess>(new AuthSuccess()));
+ getXMPPLayer()->writeElement(boost::make_shared<AuthSuccess>());
authenticated_ = true;
getXMPPLayer()->resetParser();
}
else {
PLAINMessage plainMessage(authRequest->getMessage() ? *authRequest->getMessage() : createSafeByteArray(""));
if (userRegistry_->isValidUserPassword(JID(plainMessage.getAuthenticationID(), getLocalJID().getDomain()), plainMessage.getPassword())) {
- getXMPPLayer()->writeElement(boost::shared_ptr<AuthSuccess>(new AuthSuccess()));
+ getXMPPLayer()->writeElement(boost::make_shared<AuthSuccess>());
user_ = plainMessage.getAuthenticationID();
authenticated_ = true;
getXMPPLayer()->resetParser();
}
else {
getXMPPLayer()->writeElement(boost::shared_ptr<AuthFailure>(new AuthFailure));
finishSession(AuthenticationFailedError);
}
}
}
else {
getXMPPLayer()->writeElement(boost::shared_ptr<AuthFailure>(new AuthFailure));
finishSession(NoSupportedAuthMechanismsError);
}
}
else if (IQ* iq = dynamic_cast<IQ*>(element.get())) {
if (boost::shared_ptr<ResourceBind> resourceBind = iq->getPayload<ResourceBind>()) {
setRemoteJID(JID(user_, getLocalJID().getDomain(), resourceBind->getResource()));
boost::shared_ptr<ResourceBind> resultResourceBind(new ResourceBind());
resultResourceBind->setJID(getRemoteJID());
getXMPPLayer()->writeElement(IQ::createResult(JID(), iq->getID(), resultResourceBind));
}
else if (iq->getPayload<StartSession>()) {
getXMPPLayer()->writeElement(IQ::createResult(getRemoteJID(), iq->getID()));
setInitialized();
}
}
}
}
void ServerFromClientSession::handleStreamStart(const ProtocolHeader& incomingHeader) {
setLocalJID(JID("", incomingHeader.getTo()));
ProtocolHeader header;
header.setFrom(incomingHeader.getTo());
header.setID(id_);
diff --git a/Limber/main.cpp b/Limber/main.cpp
index 350b357..3db3092 100644
--- a/Limber/main.cpp
+++ b/Limber/main.cpp
@@ -29,71 +29,71 @@
using namespace Swift;
class Server {
public:
Server(UserRegistry* userRegistry, EventLoop* eventLoop) : userRegistry_(userRegistry) {
serverFromClientConnectionServer_ = BoostConnectionServer::create(5222, boostIOServiceThread_.getIOService(), eventLoop);
serverFromClientConnectionServer_->onNewConnection.connect(boost::bind(&Server::handleNewConnection, this, _1));
serverFromClientConnectionServer_->start();
}
private:
void handleNewConnection(boost::shared_ptr<Connection> c) {
boost::shared_ptr<ServerFromClientSession> session(new ServerFromClientSession(idGenerator_.generateID(), c, &payloadParserFactories_, &payloadSerializers_, &xmlParserFactory, userRegistry_));
serverFromClientSessions_.push_back(session);
session->onElementReceived.connect(boost::bind(&Server::handleElementReceived, this, _1, session));
session->onSessionFinished.connect(boost::bind(&Server::handleSessionFinished, this, session));
session->startSession();
}
void handleSessionFinished(boost::shared_ptr<ServerFromClientSession> session) {
serverFromClientSessions_.erase(std::remove(serverFromClientSessions_.begin(), serverFromClientSessions_.end(), session), serverFromClientSessions_.end());
}
void handleElementReceived(boost::shared_ptr<Element> element, boost::shared_ptr<ServerFromClientSession> session) {
boost::shared_ptr<Stanza> stanza(boost::dynamic_pointer_cast<Stanza>(element));
if (!stanza) {
return;
}
stanza->setFrom(session->getRemoteJID());
if (!stanza->getTo().isValid()) {
stanza->setTo(JID(session->getLocalJID()));
}
if (!stanza->getTo().isValid() || stanza->getTo() == session->getLocalJID() || stanza->getTo() == session->getRemoteJID().toBare()) {
if (boost::shared_ptr<IQ> iq = boost::dynamic_pointer_cast<IQ>(stanza)) {
if (iq->getPayload<RosterPayload>()) {
- session->sendElement(IQ::createResult(iq->getFrom(), iq->getID(), boost::shared_ptr<RosterPayload>(new RosterPayload())));
+ session->sendElement(IQ::createResult(iq->getFrom(), iq->getID(), boost::make_shared<RosterPayload>())));
}
if (iq->getPayload<VCard>()) {
if (iq->getType() == IQ::Get) {
boost::shared_ptr<VCard> vcard(new VCard());
vcard->setNickname(iq->getFrom().getNode());
session->sendElement(IQ::createResult(iq->getFrom(), iq->getID(), vcard));
}
else {
session->sendElement(IQ::createError(iq->getFrom(), iq->getID(), ErrorPayload::Forbidden, ErrorPayload::Cancel));
}
}
else {
session->sendElement(IQ::createError(iq->getFrom(), iq->getID(), ErrorPayload::FeatureNotImplemented, ErrorPayload::Cancel));
}
}
}
}
private:
IDGenerator idGenerator_;
PlatformXMLParserFactory xmlParserFactory;
UserRegistry* userRegistry_;
BoostIOServiceThread boostIOServiceThread_;
boost::shared_ptr<BoostConnectionServer> serverFromClientConnectionServer_;
std::vector< boost::shared_ptr<ServerFromClientSession> > serverFromClientSessions_;
FullPayloadParserFactoryCollection payloadParserFactories_;
FullPayloadSerializerCollection payloadSerializers_;
};
int main() {
SimpleEventLoop eventLoop;
SimpleUserRegistry userRegistry;
userRegistry.addUser(JID("remko@localhost"), "remko");
userRegistry.addUser(JID("kevin@localhost"), "kevin");
userRegistry.addUser(JID("remko@limber.swift.im"), "remko");
diff --git a/Slimber/FileVCardCollection.cpp b/Slimber/FileVCardCollection.cpp
index 97ade08..24249d4 100644
--- a/Slimber/FileVCardCollection.cpp
+++ b/Slimber/FileVCardCollection.cpp
@@ -1,43 +1,44 @@
/*
* Copyright (c) 2010 Remko Tronçon
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
#include "Slimber/FileVCardCollection.h"
+#include <boost/smart_ptr/make_shared.hpp>
#include <boost/filesystem/fstream.hpp>
#include <Swiften/Base/ByteArray.h>
#include <Swiften/Elements/VCard.h>
#include <Swiften/Serializer/PayloadSerializers/VCardSerializer.h>
#include <Swiften/Parser/PayloadParsers/UnitTest/PayloadParserTester.h>
#include <Swiften/Parser/PayloadParsers/VCardParser.h>
namespace Swift {
FileVCardCollection::FileVCardCollection(boost::filesystem::path dir) : vcardsPath(dir) {
}
boost::shared_ptr<VCard> FileVCardCollection::getOwnVCard() const {
if (boost::filesystem::exists(vcardsPath / std::string("vcard.xml"))) {
ByteArray data;
readByteArrayFromFile(data, boost::filesystem::path(vcardsPath / std::string("vcard.xml")).string());
VCardParser parser;
PayloadParserTester tester(&parser);
tester.parse(byteArrayToString(data));
return boost::dynamic_pointer_cast<VCard>(parser.getPayload());
}
else {
- return boost::shared_ptr<VCard>(new VCard());
+ return boost::make_shared<VCard>();
}
}
void FileVCardCollection::setOwnVCard(boost::shared_ptr<VCard> v) {
boost::filesystem::ofstream file(vcardsPath / std::string("vcard.xml"));
file << VCardSerializer().serializePayload(v);
file.close();
}
}
diff --git a/Slimber/Server.cpp b/Slimber/Server.cpp
index 769217f..b63ca67 100644
--- a/Slimber/Server.cpp
+++ b/Slimber/Server.cpp
@@ -295,71 +295,71 @@ void Server::handleLinkLocalSessionFinished(boost::shared_ptr<Session> session)
void Server::handleLinkLocalElementReceived(boost::shared_ptr<Element> element, boost::shared_ptr<Session> session) {
if (boost::shared_ptr<Stanza> stanza = boost::dynamic_pointer_cast<Stanza>(element)) {
JID fromJID = session->getRemoteJID();
if (!presenceManager->getServiceForJID(fromJID.toBare())) {
return; // TODO: Send error back
}
stanza->setFrom(fromJID);
serverFromClientSession->sendElement(stanza);
}
}
void Server::handleConnectFinished(boost::shared_ptr<LinkLocalConnector> connector, bool error) {
if (error) {
std::cerr << "Error connecting" << std::endl;
// TODO: Send back queued stanzas
}
else {
boost::shared_ptr<OutgoingLinkLocalSession> outgoingSession(
new OutgoingLinkLocalSession(
selfJID, connector->getService().getJID(), connector->getConnection(),
&payloadParserFactories, &payloadSerializers, &xmlParserFactory));
foreach(const boost::shared_ptr<Element> element, connector->getQueuedElements()) {
outgoingSession->queueElement(element);
}
registerLinkLocalSession(outgoingSession);
}
connectors.erase(std::remove(connectors.begin(), connectors.end(), connector), connectors.end());
}
void Server::registerLinkLocalSession(boost::shared_ptr<Session> session) {
session->onSessionFinished.connect(
boost::bind(&Server::handleLinkLocalSessionFinished, this, session));
session->onElementReceived.connect(
boost::bind(&Server::handleLinkLocalElementReceived, this, _1, session));
linkLocalSessions.push_back(session);
- //tracers.push_back(boost::shared_ptr<SessionTracer>(new SessionTracer(session)));
+ //tracers.push_back(boost::make_shared<SessionTracer>(session));
session->startSession();
}
boost::shared_ptr<Session> Server::getLinkLocalSessionForJID(const JID& jid) {
foreach(const boost::shared_ptr<Session> session, linkLocalSessions) {
if (session->getRemoteJID() == jid) {
return session;
}
}
return boost::shared_ptr<Session>();
}
boost::shared_ptr<LinkLocalConnector> Server::getLinkLocalConnectorForJID(const JID& jid) {
foreach(const boost::shared_ptr<LinkLocalConnector> connector, connectors) {
if (connector->getService().getJID() == jid) {
return connector;
}
}
return boost::shared_ptr<LinkLocalConnector>();
}
void Server::handleServiceRegistered(const DNSSDServiceID& service) {
selfJID = JID(service.getName());
}
void Server::handleRosterChanged(boost::shared_ptr<RosterPayload> roster) {
if (rosterRequested) {
assert(serverFromClientSession);
boost::shared_ptr<IQ> iq = IQ::createRequest(
IQ::Set, serverFromClientSession->getRemoteJID(),
idGenerator.generateID(), roster);
iq->setFrom(serverFromClientSession->getRemoteJID().toBare());
serverFromClientSession->sendElement(iq);
}
}
diff --git a/Slimber/UnitTest/LinkLocalPresenceManagerTest.cpp b/Slimber/UnitTest/LinkLocalPresenceManagerTest.cpp
index e45861b..c138b2c 100644
--- a/Slimber/UnitTest/LinkLocalPresenceManagerTest.cpp
+++ b/Slimber/UnitTest/LinkLocalPresenceManagerTest.cpp
@@ -10,71 +10,71 @@
#include <map>
#include <Swiften/Elements/Presence.h>
#include <Swiften/Elements/RosterPayload.h>
#include <Swiften/Elements/RosterItemPayload.h>
#include "Slimber/LinkLocalPresenceManager.h"
#include <Swiften/LinkLocal/LinkLocalServiceInfo.h>
#include <Swiften/LinkLocal/LinkLocalServiceBrowser.h>
#include <Swiften/LinkLocal/DNSSD/DNSSDServiceID.h>
#include <Swiften/LinkLocal/DNSSD/DNSSDResolveServiceQuery.h>
#include <Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuerier.h>
#include <Swiften/EventLoop/DummyEventLoop.h>
using namespace Swift;
class LinkLocalPresenceManagerTest : public CppUnit::TestFixture {
CPPUNIT_TEST_SUITE(LinkLocalPresenceManagerTest);
CPPUNIT_TEST(testConstructor);
CPPUNIT_TEST(testServiceAdded);
CPPUNIT_TEST(testServiceRemoved);
CPPUNIT_TEST(testServiceChanged);
CPPUNIT_TEST(testGetRoster);
CPPUNIT_TEST(testGetAllPresence);
CPPUNIT_TEST(testGetRoster_InfoWithNick);
CPPUNIT_TEST(testGetRoster_InfoWithFirstName);
CPPUNIT_TEST(testGetRoster_InfoWithLastName);
CPPUNIT_TEST(testGetRoster_InfoWithFirstAndLastName);
CPPUNIT_TEST(testGetRoster_NoInfo);
CPPUNIT_TEST(testGetServiceForJID);
CPPUNIT_TEST(testGetServiceForJID_NoMatch);
CPPUNIT_TEST_SUITE_END();
public:
void setUp() {
eventLoop = new DummyEventLoop();
- querier = boost::shared_ptr<FakeDNSSDQuerier>(new FakeDNSSDQuerier("wonderland.lit", eventLoop));
+ querier = boost::make_shared<FakeDNSSDQuerier>("wonderland.lit", eventLoop);
browser = new LinkLocalServiceBrowser(querier);
browser->start();
}
void tearDown() {
browser->stop();
delete browser;
delete eventLoop;
}
void testConstructor() {
addService("alice@wonderland");
addService("rabbit@teaparty");
boost::shared_ptr<LinkLocalPresenceManager> testling(createTestling());
CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(testling->getRoster()->getItems().size()));
CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(testling->getAllPresence().size()));
}
void testServiceAdded() {
boost::shared_ptr<LinkLocalPresenceManager> testling(createTestling());
addService("alice@wonderland", "Alice");
CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(rosterChanges.size()));
CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(rosterChanges[0]->getItems().size()));
boost::optional<RosterItemPayload> item = rosterChanges[0]->getItem(JID("alice@wonderland"));
CPPUNIT_ASSERT(item);
CPPUNIT_ASSERT_EQUAL(std::string("Alice"), item->getName());
CPPUNIT_ASSERT_EQUAL(RosterItemPayload::Both, item->getSubscription());
CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(presenceChanges.size()));
CPPUNIT_ASSERT(StatusShow::Online == presenceChanges[0]->getShow());
CPPUNIT_ASSERT(JID("alice@wonderland") == presenceChanges[0]->getFrom());
}
diff --git a/Swift/Controllers/Chat/ChatController.cpp b/Swift/Controllers/Chat/ChatController.cpp
index ea0e8ea..610c8e8 100644
--- a/Swift/Controllers/Chat/ChatController.cpp
+++ b/Swift/Controllers/Chat/ChatController.cpp
@@ -1,44 +1,45 @@
/*
* Copyright (c) 2010-2012 Kevin Smith
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
#include "Swift/Controllers/Chat/ChatController.h"
#include <boost/bind.hpp>
+#include <boost/smart_ptr/make_shared.hpp>
#include <stdio.h>
#include <Swift/Controllers/Intl.h>
#include <Swiften/Base/format.h>
#include <Swiften/Base/Algorithm.h>
#include <Swiften/Avatars/AvatarManager.h>
#include <Swiften/Chat/ChatStateNotifier.h>
#include <Swiften/Chat/ChatStateTracker.h>
#include <Swiften/Client/StanzaChannel.h>
#include <Swift/Controllers/UIInterfaces/ChatWindowFactory.h>
#include <Swiften/Client/NickResolver.h>
#include <Swift/Controllers/XMPPEvents/EventController.h>
#include <Swift/Controllers/FileTransfer/FileTransferController.h>
#include <Swift/Controllers/StatusUtil.h>
#include <Swiften/Disco/EntityCapsProvider.h>
#include <Swiften/Base/foreach.h>
#include <Swift/Controllers/UIEvents/UIEventStream.h>
#include <Swift/Controllers/UIEvents/SendFileUIEvent.h>
#include <Swiften/Elements/DeliveryReceipt.h>
#include <Swiften/Elements/DeliveryReceiptRequest.h>
#include <Swift/Controllers/SettingConstants.h>
#include <Swiften/Base/Log.h>
namespace Swift {
/**
* The controller does not gain ownership of the stanzaChannel, nor the factory.
*/
ChatController::ChatController(const JID& self, StanzaChannel* stanzaChannel, IQRouter* iqRouter, ChatWindowFactory* chatWindowFactory, const JID &contact, NickResolver* nickResolver, PresenceOracle* presenceOracle, AvatarManager* avatarManager, bool isInMUC, bool useDelayForLatency, UIEventStream* eventStream, EventController* eventController, TimerFactory* timerFactory, EntityCapsProvider* entityCapsProvider, bool userWantsReceipts, SettingsProvider* settings)
: ChatControllerBase(self, stanzaChannel, iqRouter, chatWindowFactory, contact, presenceOracle, avatarManager, useDelayForLatency, eventStream, eventController, timerFactory, entityCapsProvider), eventStream_(eventStream), userWantsReceipts_(userWantsReceipts), settings_(settings) {
isInMUC_ = isInMUC;
lastWasPresence_ = false;
chatStateNotifier_ = new ChatStateNotifier(stanzaChannel, contact, entityCapsProvider);
chatStateTracker_ = new ChatStateTracker();
@@ -289,59 +290,59 @@ std::string ChatController::getStatusChangeString(boost::shared_ptr<Presence> pr
response = QT_TRANSLATE_NOOP("", "%1% has gone offline");
} else if (presence->getType() == Presence::Available) {
StatusShow::Type show = presence->getShow();
if (show == StatusShow::Online || show == StatusShow::FFC) {
response = QT_TRANSLATE_NOOP("", "%1% has become available");
} else if (show == StatusShow::Away || show == StatusShow::XA) {
response = QT_TRANSLATE_NOOP("", "%1% has gone away");
} else if (show == StatusShow::DND) {
response = QT_TRANSLATE_NOOP("", "%1% is now busy");
}
}
if (!response.empty()) {
response = str(format(response) % nick);
}
if (!presence->getStatus().empty()) {
response += " (" + presence->getStatus() + ")";
}
return response + ".";
}
void ChatController::handlePresenceChange(boost::shared_ptr<Presence> newPresence) {
bool me = false;
if (toJID_.isBare()) {
newPresence = presenceOracle_->getHighestPriorityPresence(toJID_);
if ((newPresence ? newPresence->getShow() : StatusShow::None) != lastShownStatus_) {
me = true;
}
} else if (toJID_.equals(newPresence->getFrom(), JID::WithResource)) {
me = true;
}
if (!me) {
return;
}
if (!newPresence) {
- newPresence = boost::shared_ptr<Presence>(new Presence());
+ newPresence = boost::make_shared<Presence>();
newPresence->setType(Presence::Unavailable);
}
lastShownStatus_ = newPresence->getShow();
chatStateTracker_->handlePresenceChange(newPresence);
chatStateNotifier_->setContactIsOnline(newPresence->getType() == Presence::Available);
std::string newStatusChangeString = getStatusChangeString(newPresence);
if (newStatusChangeString != lastStatusChangeString_) {
if (lastWasPresence_) {
chatWindow_->replaceLastMessage(newStatusChangeString);
} else {
chatWindow_->addPresenceMessage(newStatusChangeString);
}
lastStatusChangeString_ = newStatusChangeString;
lastWasPresence_ = true;
}
}
boost::optional<boost::posix_time::ptime> ChatController::getMessageTimestamp(boost::shared_ptr<Message> message) const {
return message->getTimestamp();
}
}
diff --git a/Swift/Controllers/Chat/ChatControllerBase.cpp b/Swift/Controllers/Chat/ChatControllerBase.cpp
index db71397..f590ffd 100644
--- a/Swift/Controllers/Chat/ChatControllerBase.cpp
+++ b/Swift/Controllers/Chat/ChatControllerBase.cpp
@@ -1,48 +1,49 @@
/*
* Copyright (c) 2010-2011 Kevin Smith
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
#include "Swift/Controllers/Chat/ChatControllerBase.h"
#include <sstream>
#include <map>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
+#include <boost/smart_ptr/make_shared.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/algorithm/string.hpp>
#include <Swift/Controllers/Intl.h>
#include <Swiften/Base/format.h>
#include <Swiften/Base/String.h>
#include <Swiften/Client/StanzaChannel.h>
#include <Swiften/Elements/Delay.h>
#include <Swiften/Elements/MUCInvitationPayload.h>
#include <Swiften/Elements/MUCUserPayload.h>
#include <Swiften/Base/foreach.h>
#include <Swift/Controllers/XMPPEvents/EventController.h>
#include <Swiften/Disco/EntityCapsProvider.h>
#include <Swift/Controllers/UIInterfaces/ChatWindow.h>
#include <Swift/Controllers/UIInterfaces/ChatWindowFactory.h>
#include <Swiften/Queries/Requests/GetSecurityLabelsCatalogRequest.h>
#include <Swiften/Avatars/AvatarManager.h>
namespace Swift {
ChatControllerBase::ChatControllerBase(const JID& self, StanzaChannel* stanzaChannel, IQRouter* iqRouter, ChatWindowFactory* chatWindowFactory, const JID &toJID, PresenceOracle* presenceOracle, AvatarManager* avatarManager, bool useDelayForLatency, UIEventStream* eventStream, EventController* eventController, TimerFactory* timerFactory, EntityCapsProvider* entityCapsProvider) : selfJID_(self), stanzaChannel_(stanzaChannel), iqRouter_(iqRouter), chatWindowFactory_(chatWindowFactory), toJID_(toJID), labelsEnabled_(false), presenceOracle_(presenceOracle), avatarManager_(avatarManager), useDelayForLatency_(useDelayForLatency), eventController_(eventController), timerFactory_(timerFactory), entityCapsProvider_(entityCapsProvider) {
chatWindow_ = chatWindowFactory_->createChatWindow(toJID, eventStream);
chatWindow_->onAllMessagesRead.connect(boost::bind(&ChatControllerBase::handleAllMessagesRead, this));
chatWindow_->onSendMessageRequest.connect(boost::bind(&ChatControllerBase::handleSendMessageRequest, this, _1, _2));
entityCapsProvider_->onCapsChanged.connect(boost::bind(&ChatControllerBase::handleCapsChanged, this, _1));
setOnline(stanzaChannel->isAvailable() && iqRouter->isAvailable());
createDayChangeTimer();
}
ChatControllerBase::~ChatControllerBase() {
delete chatWindow_;
}
void ChatControllerBase::handleCapsChanged(const JID& jid) {
if (jid.compare(toJID_, JID::WithoutResource) == 0) {
@@ -88,71 +89,71 @@ void ChatControllerBase::setAvailableServerFeatures(boost::shared_ptr<DiscoInfo>
}
}
void ChatControllerBase::handleAllMessagesRead() {
if (!unreadMessages_.empty()) {
foreach (boost::shared_ptr<MessageEvent> messageEvent, unreadMessages_) {
messageEvent->read();
}
unreadMessages_.clear();
chatWindow_->setUnreadMessageCount(0);
onUnreadCountChanged();
}
}
int ChatControllerBase::getUnreadCount() {
return unreadMessages_.size();
}
void ChatControllerBase::handleSendMessageRequest(const std::string &body, bool isCorrectionMessage) {
if (!stanzaChannel_->isAvailable() || body.empty()) {
return;
}
boost::shared_ptr<Message> message(new Message());
message->setTo(toJID_);
message->setType(Swift::Message::Chat);
message->setBody(body);
if (labelsEnabled_) {
SecurityLabelsCatalog::Item labelItem = chatWindow_->getSelectedSecurityLabel();
if (labelItem.getLabel()) {
message->addPayload(labelItem.getLabel());
}
}
preSendMessageRequest(message);
if (useDelayForLatency_) {
boost::posix_time::ptime now = boost::posix_time::microsec_clock::universal_time();
- message->addPayload(boost::shared_ptr<Delay>(new Delay(now, selfJID_)));
+ message->addPayload(boost::make_shared<Delay>(now, selfJID_));
}
if (isCorrectionMessage) {
message->addPayload(boost::shared_ptr<Replace> (new Replace(lastSentMessageStanzaID_)));
}
message->setID(lastSentMessageStanzaID_ = idGenerator_.generateID());
stanzaChannel_->sendMessage(message);
postSendMessage(message->getBody(), boost::dynamic_pointer_cast<Stanza>(message));
onActivity(message->getBody());
}
void ChatControllerBase::handleSecurityLabelsCatalogResponse(boost::shared_ptr<SecurityLabelsCatalog> catalog, ErrorPayload::ref error) {
if (!error) {
if (catalog->getItems().size() == 0) {
chatWindow_->setSecurityLabelsEnabled(false);
labelsEnabled_ = false;
} else {
labelsEnabled_ = true;
chatWindow_->setAvailableSecurityLabels(catalog->getItems());
chatWindow_->setSecurityLabelsEnabled(true);
}
} else {
labelsEnabled_ = false;
chatWindow_->setSecurityLabelsError();
}
}
void ChatControllerBase::showChatWindow() {
chatWindow_->show();
}
void ChatControllerBase::activateChatWindow() {
chatWindow_->activate();
}
std::string ChatControllerBase::addMessage(const std::string& message, const std::string& senderName, bool senderIsSelf, const boost::shared_ptr<SecurityLabel> label, const std::string& avatarPath, const boost::posix_time::ptime& time) {
diff --git a/Swift/Controllers/Chat/ChatsManager.cpp b/Swift/Controllers/Chat/ChatsManager.cpp
index 118f1e8..aea5ef4 100644
--- a/Swift/Controllers/Chat/ChatsManager.cpp
+++ b/Swift/Controllers/Chat/ChatsManager.cpp
@@ -1,45 +1,46 @@
/*
* Copyright (c) 2010-2011 Kevin Smith
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
#include "Swift/Controllers/Chat/ChatsManager.h"
#include <boost/bind.hpp>
#include <boost/algorithm/string.hpp>
+#include <boost/smart_ptr/make_shared.hpp>
#include <Swiften/Base/foreach.h>
#include <Swift/Controllers/Chat/ChatController.h>
#include <Swift/Controllers/Chat/ChatControllerBase.h>
#include <Swift/Controllers/Chat/MUCSearchController.h>
#include <Swift/Controllers/XMPPEvents/EventController.h>
#include <Swift/Controllers/Chat/MUCController.h>
#include <Swift/Controllers/UIEvents/RequestChatUIEvent.h>
#include <Swift/Controllers/UIEvents/JoinMUCUIEvent.h>
#include <Swift/Controllers/UIEvents/RequestJoinMUCUIEvent.h>
#include <Swift/Controllers/UIEvents/AddMUCBookmarkUIEvent.h>
#include <Swift/Controllers/UIEvents/RemoveMUCBookmarkUIEvent.h>
#include <Swift/Controllers/UIEvents/EditMUCBookmarkUIEvent.h>
#include <Swift/Controllers/UIInterfaces/ChatListWindowFactory.h>
#include <Swift/Controllers/UIInterfaces/JoinMUCWindow.h>
#include <Swift/Controllers/UIInterfaces/JoinMUCWindowFactory.h>
#include <Swiften/Presence/PresenceSender.h>
#include <Swiften/Client/NickResolver.h>
#include <Swiften/MUC/MUCManager.h>
#include <Swiften/Elements/ChatState.h>
#include <Swiften/Elements/MUCUserPayload.h>
#include <Swiften/Elements/DeliveryReceipt.h>
#include <Swiften/Elements/DeliveryReceiptRequest.h>
#include <Swiften/MUC/MUCBookmarkManager.h>
#include <Swift/Controllers/FileTransfer/FileTransferController.h>
#include <Swift/Controllers/FileTransfer/FileTransferOverview.h>
#include <Swift/Controllers/ProfileSettingsProvider.h>
#include <Swiften/Avatars/AvatarManager.h>
#include <Swiften/Elements/MUCInvitationPayload.h>
#include <Swiften/Roster/XMPPRoster.h>
#include <Swift/Controllers/Settings/SettingsProvider.h>
#include <Swift/Controllers/SettingConstants.h>
#include <Swiften/Client/StanzaChannel.h>
namespace Swift {
@@ -57,71 +58,71 @@ ChatsManager::ChatsManager(
JoinMUCWindowFactory* joinMUCWindowFactory,
NickResolver* nickResolver,
PresenceOracle* presenceOracle,
PresenceSender* presenceSender,
UIEventStream* uiEventStream,
ChatListWindowFactory* chatListWindowFactory,
bool useDelayForLatency,
TimerFactory* timerFactory,
MUCRegistry* mucRegistry,
EntityCapsProvider* entityCapsProvider,
MUCManager* mucManager,
MUCSearchWindowFactory* mucSearchWindowFactory,
ProfileSettingsProvider* profileSettings,
FileTransferOverview* ftOverview,
XMPPRoster* roster,
bool eagleMode,
SettingsProvider* settings) :
jid_(jid),
joinMUCWindowFactory_(joinMUCWindowFactory),
useDelayForLatency_(useDelayForLatency),
mucRegistry_(mucRegistry),
entityCapsProvider_(entityCapsProvider),
mucManager(mucManager),
ftOverview_(ftOverview),
roster_(roster),
eagleMode_(eagleMode),
settings_(settings) {
timerFactory_ = timerFactory;
eventController_ = eventController;
stanzaChannel_ = stanzaChannel;
iqRouter_ = iqRouter;
chatWindowFactory_ = chatWindowFactory;
nickResolver_ = nickResolver;
presenceOracle_ = presenceOracle;
avatarManager_ = NULL;
- serverDiscoInfo_ = boost::shared_ptr<DiscoInfo>(new DiscoInfo());
+ serverDiscoInfo_ = boost::make_shared<DiscoInfo>();
presenceSender_ = presenceSender;
uiEventStream_ = uiEventStream;
mucBookmarkManager_ = NULL;
profileSettings_ = profileSettings;
presenceOracle_->onPresenceChange.connect(boost::bind(&ChatsManager::handlePresenceChange, this, _1));
uiEventConnection_ = uiEventStream_->onUIEvent.connect(boost::bind(&ChatsManager::handleUIEvent, this, _1));
chatListWindow_ = chatListWindowFactory->createChatListWindow(uiEventStream_);
chatListWindow_->onMUCBookmarkActivated.connect(boost::bind(&ChatsManager::handleMUCBookmarkActivated, this, _1));
chatListWindow_->onRecentActivated.connect(boost::bind(&ChatsManager::handleRecentActivated, this, _1));
chatListWindow_->onClearRecentsRequested.connect(boost::bind(&ChatsManager::handleClearRecentsRequested, this));
joinMUCWindow_ = NULL;
mucSearchController_ = new MUCSearchController(jid_, mucSearchWindowFactory, iqRouter, profileSettings_);
mucSearchController_->onMUCSelected.connect(boost::bind(&ChatsManager::handleMUCSelectedAfterSearch, this, _1));
ftOverview_->onNewFileTransferController.connect(boost::bind(&ChatsManager::handleNewFileTransferController, this, _1));
roster_->onJIDAdded.connect(boost::bind(&ChatsManager::handleJIDAddedToRoster, this, _1));
roster_->onJIDRemoved.connect(boost::bind(&ChatsManager::handleJIDRemovedFromRoster, this, _1));
roster_->onJIDUpdated.connect(boost::bind(&ChatsManager::handleJIDUpdatedInRoster, this, _1));
roster_->onRosterCleared.connect(boost::bind(&ChatsManager::handleRosterCleared, this));
settings_->onSettingChanged.connect(boost::bind(&ChatsManager::handleSettingChanged, this, _1));
userWantsReceipts_ = settings_->getSetting(SettingConstants::REQUEST_DELIVERYRECEIPTS);
setupBookmarks();
loadRecents();
}
ChatsManager::~ChatsManager() {
settings_->onSettingChanged.disconnect(boost::bind(&ChatsManager::handleSettingChanged, this, _1));
roster_->onJIDAdded.disconnect(boost::bind(&ChatsManager::handleJIDAddedToRoster, this, _1));
roster_->onJIDRemoved.disconnect(boost::bind(&ChatsManager::handleJIDRemovedFromRoster, this, _1));
roster_->onJIDUpdated.disconnect(boost::bind(&ChatsManager::handleJIDUpdatedInRoster, this, _1));
roster_->onRosterCleared.disconnect(boost::bind(&ChatsManager::handleRosterCleared, this));
diff --git a/Swift/Controllers/Chat/UnitTest/ChatsManagerTest.cpp b/Swift/Controllers/Chat/UnitTest/ChatsManagerTest.cpp
index cd868e6..bbfb22f 100644
--- a/Swift/Controllers/Chat/UnitTest/ChatsManagerTest.cpp
+++ b/Swift/Controllers/Chat/UnitTest/ChatsManagerTest.cpp
@@ -55,71 +55,71 @@ using namespace Swift;
class DummyCapsProvider : public CapsProvider {
DiscoInfo::ref getCaps(const std::string&) const {return DiscoInfo::ref(new DiscoInfo());}
};
class ChatsManagerTest : public CppUnit::TestFixture {
CPPUNIT_TEST_SUITE(ChatsManagerTest);
CPPUNIT_TEST(testFirstOpenWindowIncoming);
CPPUNIT_TEST(testSecondOpenWindowIncoming);
CPPUNIT_TEST(testFirstOpenWindowOutgoing);
CPPUNIT_TEST(testFirstOpenWindowBareToFull);
CPPUNIT_TEST(testSecondWindow);
CPPUNIT_TEST(testUnbindRebind);
CPPUNIT_TEST(testNoDuplicateUnbind);
CPPUNIT_TEST(testThreeMUCWindows);
CPPUNIT_TEST(testChatControllerPresenceAccessUpdatedOnRemoveFromRoster);
CPPUNIT_TEST(testChatControllerPresenceAccessUpdatedOnAddToRoster);
CPPUNIT_TEST(testChatControllerPresenceAccessUpdatedOnSubscriptionChangeToBoth);
CPPUNIT_TEST(testChatControllerPresenceAccessUpdatedOnSubscriptionChangeToFrom);
CPPUNIT_TEST_SUITE_END();
public:
void setUp() {
mocks_ = new MockRepository();
jid_ = JID("test@test.com/resource");
stanzaChannel_ = new DummyStanzaChannel();
iqChannel_ = new DummyIQChannel();
iqRouter_ = new IQRouter(iqChannel_);
capsProvider_ = new DummyCapsProvider();
eventController_ = new EventController();
chatWindowFactory_ = mocks_->InterfaceMock<ChatWindowFactory>();
joinMUCWindowFactory_ = mocks_->InterfaceMock<JoinMUCWindowFactory>();
xmppRoster_ = new XMPPRosterImpl();
mucRegistry_ = new MUCRegistry();
nickResolver_ = new NickResolver(jid_.toBare(), xmppRoster_, NULL, mucRegistry_);
presenceOracle_ = new PresenceOracle(stanzaChannel_);
- serverDiscoInfo_ = boost::shared_ptr<DiscoInfo>(new DiscoInfo());
+ serverDiscoInfo_ = boost::make_shared<DiscoInfo>();
presenceSender_ = new StanzaChannelPresenceSender(stanzaChannel_);
directedPresenceSender_ = new DirectedPresenceSender(presenceSender_);
mucManager_ = new MUCManager(stanzaChannel_, iqRouter_, directedPresenceSender_, mucRegistry_);
uiEventStream_ = new UIEventStream();
entityCapsManager_ = new EntityCapsManager(capsProvider_, stanzaChannel_);
chatListWindowFactory_ = mocks_->InterfaceMock<ChatListWindowFactory>();
mucSearchWindowFactory_ = mocks_->InterfaceMock<MUCSearchWindowFactory>();
settings_ = new DummySettingsProvider();
profileSettings_ = new ProfileSettingsProvider("a", settings_);
chatListWindow_ = new MockChatListWindow();
ftManager_ = new DummyFileTransferManager();
ftOverview_ = new FileTransferOverview(ftManager_);
mocks_->ExpectCall(chatListWindowFactory_, ChatListWindowFactory::createChatListWindow).With(uiEventStream_).Return(chatListWindow_);
manager_ = new ChatsManager(jid_, stanzaChannel_, iqRouter_, eventController_, chatWindowFactory_, joinMUCWindowFactory_, nickResolver_, presenceOracle_, directedPresenceSender_, uiEventStream_, chatListWindowFactory_, true, NULL, mucRegistry_, entityCapsManager_, mucManager_, mucSearchWindowFactory_, profileSettings_, ftOverview_, xmppRoster_, false, settings_);
avatarManager_ = new NullAvatarManager();
manager_->setAvatarManager(avatarManager_);
};
void tearDown() {
//delete chatListWindowFactory
delete profileSettings_;
delete avatarManager_;
delete manager_;
delete ftOverview_;
delete ftManager_;
delete directedPresenceSender_;
delete presenceSender_;
delete presenceOracle_;
delete nickResolver_;
delete mucRegistry_;
delete stanzaChannel_;
delete eventController_;
delete iqRouter_;
@@ -225,71 +225,71 @@ public:
std::string fullJIDString2("testling@test.com/resource2");
MockChatWindow* window = new MockChatWindow();//mocks_->InterfaceMock<ChatWindow>();
mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(JID(bareJIDString), uiEventStream_).Return(window);
uiEventStream_->send(boost::shared_ptr<UIEvent>(new RequestChatUIEvent(JID(bareJIDString))));
boost::shared_ptr<Message> message1(new Message());
message1->setFrom(JID(fullJIDString1));
std::string messageBody1("This is a legible message.");
message1->setBody(messageBody1);
manager_->handleIncomingMessage(message1);
CPPUNIT_ASSERT_EQUAL(messageBody1, window->lastMessageBody_);
boost::shared_ptr<Presence> jid1Online(new Presence());
jid1Online->setFrom(JID(fullJIDString1));
boost::shared_ptr<Presence> jid1Offline(new Presence());
jid1Offline->setFrom(JID(fullJIDString1));
jid1Offline->setType(Presence::Unavailable);
presenceOracle_->onPresenceChange(jid1Offline);
boost::shared_ptr<Message> message2(new Message());
message2->setFrom(JID(fullJIDString2));
std::string messageBody2("This is another legible message.");
message2->setBody(messageBody2);
manager_->handleIncomingMessage(message2);
CPPUNIT_ASSERT_EQUAL(messageBody2, window->lastMessageBody_);
}
/**
* Test that MUC PMs get opened in the right windows
*/
void testThreeMUCWindows() {
JID muc("testling@test.com");
ChatWindow* mucWindow = new MockChatWindow();
mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(muc, uiEventStream_).Return(mucWindow);
- uiEventStream_->send(boost::shared_ptr<JoinMUCUIEvent>(new JoinMUCUIEvent(muc, std::string("nick"))));
+ uiEventStream_->send(boost::make_shared<JoinMUCUIEvent>(muc, std::string("nick")));
std::string messageJIDString1("testling@test.com/1");
ChatWindow* window1 = new MockChatWindow();//mocks_->InterfaceMock<ChatWindow>();
mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(JID(messageJIDString1), uiEventStream_).Return(window1);
uiEventStream_->send(boost::shared_ptr<UIEvent>(new RequestChatUIEvent(JID(messageJIDString1))));
std::string messageJIDString2("testling@test.com/2");
ChatWindow* window2 = new MockChatWindow();//mocks_->InterfaceMock<ChatWindow>();
mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(JID(messageJIDString2), uiEventStream_).Return(window2);
uiEventStream_->send(boost::shared_ptr<UIEvent>(new RequestChatUIEvent(JID(messageJIDString2))));
std::string messageJIDString3("testling@test.com/3");
ChatWindow* window3 = new MockChatWindow();//mocks_->InterfaceMock<ChatWindow>();
mocks_->ExpectCall(chatWindowFactory_, ChatWindowFactory::createChatWindow).With(JID(messageJIDString3), uiEventStream_).Return(window3);
uiEventStream_->send(boost::shared_ptr<UIEvent>(new RequestChatUIEvent(JID(messageJIDString3))));
/* Refetch an earlier window */
/* We do not expect a new window to be created */
uiEventStream_->send(boost::shared_ptr<UIEvent>(new RequestChatUIEvent(JID(messageJIDString1))));
}
/**
Test that a second window isn't unbound where there's already an unbound one.
Bind 1
Bind 2
Unbind 1
Unbind 2 (but it doesn't)
Sent to bound 2
Rebind 1
*/
void testNoDuplicateUnbind() {
diff --git a/Swift/Controllers/Chat/UserSearchController.cpp b/Swift/Controllers/Chat/UserSearchController.cpp
index d6a920d..af962e9 100644
--- a/Swift/Controllers/Chat/UserSearchController.cpp
+++ b/Swift/Controllers/Chat/UserSearchController.cpp
@@ -1,45 +1,46 @@
/*
* Copyright (c) 2010 Kevin Smith
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
#include <Swift/Controllers/Chat/UserSearchController.h>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
+#include <boost/smart_ptr/make_shared.hpp>
#include <Swiften/Base/foreach.h>
#include <Swiften/Disco/GetDiscoInfoRequest.h>
#include <Swiften/Disco/GetDiscoItemsRequest.h>
#include <Swiften/Disco/DiscoServiceWalker.h>
#include <Swiften/VCards/VCardManager.h>
#include <Swift/Controllers/ContactEditController.h>
#include <Swift/Controllers/UIEvents/UIEventStream.h>
#include <Swift/Controllers/UIEvents/RequestChatWithUserDialogUIEvent.h>
#include <Swift/Controllers/UIEvents/RequestAddUserDialogUIEvent.h>
#include <Swift/Controllers/UIInterfaces/UserSearchWindow.h>
#include <Swift/Controllers/UIInterfaces/UserSearchWindowFactory.h>
#include <Swift/Controllers/Roster/RosterController.h>
namespace Swift {
UserSearchController::UserSearchController(Type type, const JID& jid, UIEventStream* uiEventStream, VCardManager* vcardManager, UserSearchWindowFactory* factory, IQRouter* iqRouter, RosterController* rosterController) : type_(type), jid_(jid), uiEventStream_(uiEventStream), vcardManager_(vcardManager), factory_(factory), iqRouter_(iqRouter), rosterController_(rosterController) {
uiEventStream_->onUIEvent.connect(boost::bind(&UserSearchController::handleUIEvent, this, _1));
vcardManager_->onVCardChanged.connect(boost::bind(&UserSearchController::handleVCardChanged, this, _1, _2));
window_ = NULL;
discoWalker_ = NULL;
}
UserSearchController::~UserSearchController() {
endDiscoWalker();
delete discoWalker_;
if (window_) {
window_->onNameSuggestionRequested.disconnect(boost::bind(&UserSearchController::handleNameSuggestionRequest, this, _1));
window_->onFormRequested.disconnect(boost::bind(&UserSearchController::handleFormRequested, this, _1));
window_->onSearchRequested.disconnect(boost::bind(&UserSearchController::handleSearch, this, _1, _2));
delete window_;
}
vcardManager_->onVCardChanged.disconnect(boost::bind(&UserSearchController::handleVCardChanged, this, _1, _2));
uiEventStream_->onUIEvent.disconnect(boost::bind(&UserSearchController::handleUIEvent, this, _1));
}
@@ -72,71 +73,71 @@ void UserSearchController::handleFormRequested(const JID& service) {
window_->setSearchError(false);
window_->setServerSupportsSearch(true);
//Abort a previous search if is active
endDiscoWalker();
delete discoWalker_;
discoWalker_ = new DiscoServiceWalker(service, iqRouter_);
discoWalker_->onServiceFound.connect(boost::bind(&UserSearchController::handleDiscoServiceFound, this, _1, _2));
discoWalker_->onWalkComplete.connect(boost::bind(&UserSearchController::handleDiscoWalkFinished, this));
discoWalker_->beginWalk();
}
void UserSearchController::endDiscoWalker() {
if (discoWalker_) {
discoWalker_->endWalk();
discoWalker_->onServiceFound.disconnect(boost::bind(&UserSearchController::handleDiscoServiceFound, this, _1, _2));
discoWalker_->onWalkComplete.disconnect(boost::bind(&UserSearchController::handleDiscoWalkFinished, this));
}
}
void UserSearchController::handleDiscoServiceFound(const JID& jid, boost::shared_ptr<DiscoInfo> info) {
//bool isUserDirectory = false;
bool supports55 = false;
foreach (DiscoInfo::Identity identity, info->getIdentities()) {
if ((identity.getCategory() == "directory"
&& identity.getType() == "user")) {
//isUserDirectory = true;
}
}
std::vector<std::string> features = info->getFeatures();
supports55 = std::find(features.begin(), features.end(), DiscoInfo::JabberSearchFeature) != features.end();
if (/*isUserDirectory && */supports55) { //FIXME: once M-Link correctly advertises directoryness.
/* Abort further searches.*/
endDiscoWalker();
- boost::shared_ptr<GenericRequest<SearchPayload> > searchRequest(new GenericRequest<SearchPayload>(IQ::Get, jid, boost::shared_ptr<SearchPayload>(new SearchPayload()), iqRouter_));
+ boost::shared_ptr<GenericRequest<SearchPayload> > searchRequest(new GenericRequest<SearchPayload>(IQ::Get, jid, boost::make_shared<SearchPayload>(), iqRouter_));
searchRequest->onResponse.connect(boost::bind(&UserSearchController::handleFormResponse, this, _1, _2));
searchRequest->send();
}
}
void UserSearchController::handleFormResponse(boost::shared_ptr<SearchPayload> fields, ErrorPayload::ref error) {
if (error || !fields) {
window_->setServerSupportsSearch(false);
return;
}
window_->setSearchFields(fields);
}
void UserSearchController::handleSearch(boost::shared_ptr<SearchPayload> fields, const JID& jid) {
boost::shared_ptr<GenericRequest<SearchPayload> > searchRequest(new GenericRequest<SearchPayload>(IQ::Set, jid, fields, iqRouter_));
searchRequest->onResponse.connect(boost::bind(&UserSearchController::handleSearchResponse, this, _1, _2));
searchRequest->send();
}
void UserSearchController::handleSearchResponse(boost::shared_ptr<SearchPayload> resultsPayload, ErrorPayload::ref error) {
if (error || !resultsPayload) {
window_->setSearchError(true);
return;
}
std::vector<UserSearchResult> results;
if (resultsPayload->getForm()) {
window_->setResultsForm(resultsPayload->getForm());
} else {
foreach (SearchPayload::Item item, resultsPayload->getItems()) {
JID jid(item.jid);
std::map<std::string, std::string> fields;
fields["first"] = item.first;
fields["last"] = item.last;
diff --git a/Swift/Controllers/MainController.cpp b/Swift/Controllers/MainController.cpp
index cd7e673..e923cff 100644
--- a/Swift/Controllers/MainController.cpp
+++ b/Swift/Controllers/MainController.cpp
@@ -349,71 +349,71 @@ void MainController::reconnectAfterError() {
void MainController::handleChangeStatusRequest(StatusShow::Type show, const std::string &statusText) {
boost::shared_ptr<Presence> presence(new Presence());
if (show == StatusShow::None) {
// Note: this is misleading, None doesn't mean unavailable on the wire.
presence->setType(Presence::Unavailable);
resetPendingReconnects();
myStatusLooksOnline_ = false;
offlineRequested_ = true;
}
else {
offlineRequested_ = false;
presence->setShow(show);
}
presence->setStatus(statusText);
statusTracker_->setRequestedPresence(presence);
if (presence->getType() != Presence::Unavailable) {
profileSettings_->storeInt("lastShow", presence->getShow());
profileSettings_->storeString("lastStatus", presence->getStatus());
}
if (presence->getType() != Presence::Unavailable && !client_->isAvailable()) {
performLoginFromCachedCredentials();
} else {
sendPresence(presence);
}
}
void MainController::sendPresence(boost::shared_ptr<Presence> presence) {
rosterController_->getWindow()->setMyStatusType(presence->getShow());
rosterController_->getWindow()->setMyStatusText(presence->getStatus());
systemTrayController_->setMyStatusType(presence->getShow());
notifier_->setTemporarilyDisabled(presence->getShow() == StatusShow::DND);
// Add information and send
if (!vCardPhotoHash_.empty()) {
- presence->updatePayload(boost::shared_ptr<VCardUpdate>(new VCardUpdate(vCardPhotoHash_)));
+ presence->updatePayload(boost::make_shared<VCardUpdate>(vCardPhotoHash_));
}
client_->getPresenceSender()->sendPresence(presence);
if (presence->getType() == Presence::Unavailable) {
logout();
}
}
void MainController::handleInputIdleChanged(bool idle) {
if (!statusTracker_) {
//Haven't logged in yet.
return;
}
if (settings_->getSetting(SettingConstants::IDLE_GOES_OFFLINE)) {
if (idle) {
logout();
}
}
else {
if (idle) {
if (statusTracker_->goAutoAway()) {
if (client_ && client_->isAvailable()) {
sendPresence(statusTracker_->getNextPresence());
}
}
} else {
if (statusTracker_->goAutoUnAway()) {
if (client_ && client_->isAvailable()) {
sendPresence(statusTracker_->getNextPresence());
}
}
}
}
}
@@ -550,71 +550,71 @@ void MainController::handleDisconnected(const boost::optional<ClientError>& erro
case ClientError::InvalidServerIdentityError: certificateErrorMessage = QT_TRANSLATE_NOOP("", "Certificate does not match the host identity"); break;
}
bool forceReconnectAfterCertificateTrust = false;
if (!certificateErrorMessage.empty()) {
Certificate::ref certificate = certificateTrustChecker_->getLastCertificate();
if (loginWindow_->askUserToTrustCertificatePermanently(certificateErrorMessage, certificate)) {
certificateStorage_->addCertificate(certificate);
forceReconnectAfterCertificateTrust = true;
}
else {
message = QT_TRANSLATE_NOOP("", "Certificate error");
}
}
if (forceReconnectAfterCertificateTrust) {
performLoginFromCachedCredentials();
}
else if (!rosterController_) { //hasn't been logged in yet
signOut();
loginWindow_->setMessage(message);
loginWindow_->setIsLoggingIn(false);
} else {
logout();
if (settings_->getSetting(SettingConstants::FORGET_PASSWORDS)) {
message = str(format(QT_TRANSLATE_NOOP("", "Disconnected from %1%: %2%. To reconnect, Sign Out and provide your password again.")) % jid_.getDomain() % message);
} else {
if (!offlineRequested_) {
setReconnectTimer();
}
if (lastDisconnectError_) {
message = str(format(QT_TRANSLATE_NOOP("", "Reconnect to %1% failed: %2%. Will retry in %3% seconds.")) % jid_.getDomain() % message % boost::lexical_cast<std::string>(timeBeforeNextReconnect_));
lastDisconnectError_->conclude();
} else {
message = str(format(QT_TRANSLATE_NOOP("", "Disconnected from %1%: %2%.")) % jid_.getDomain() % message);
}
- lastDisconnectError_ = boost::shared_ptr<ErrorEvent>(new ErrorEvent(JID(jid_.getDomain()), message));
+ lastDisconnectError_ = boost::make_shared<ErrorEvent>(JID(jid_.getDomain()), message);
eventController_->handleIncomingEvent(lastDisconnectError_);
}
}
}
else if (!rosterController_) { //hasn't been logged in yet
loginWindow_->setIsLoggingIn(false);
}
}
void MainController::setReconnectTimer() {
if (timeBeforeNextReconnect_ < 0) {
timeBeforeNextReconnect_ = 1;
} else {
timeBeforeNextReconnect_ = timeBeforeNextReconnect_ >= 150 ? 300 : timeBeforeNextReconnect_ * 2; // Randomly selected by roll of a die, as required by 3920bis
}
if (reconnectTimer_) {
reconnectTimer_->stop();
}
reconnectTimer_ = networkFactories_->getTimerFactory()->createTimer(timeBeforeNextReconnect_ * 1000);
reconnectTimer_->onTick.connect(boost::bind(&MainController::reconnectAfterError, this));
reconnectTimer_->start();
}
void MainController::handleCancelLoginRequest() {
signOut();
}
void MainController::signOut() {
if (settings_->getSetting(SettingConstants::FORGET_PASSWORDS)) {
purgeCachedCredentials();
}
eventController_->clear();
logout();
loginWindow_->loggedOut();
resetClient();
@@ -643,55 +643,55 @@ void MainController::setManagersOffline() {
if (rosterController_) {
rosterController_->setEnabled(false);
}
if (profileController_) {
profileController_->setAvailable(false);
}
if (contactEditController_) {
contactEditController_->setAvailable(false);
}
}
void MainController::handleServerDiscoInfoResponse(boost::shared_ptr<DiscoInfo> info, ErrorPayload::ref error) {
if (!error) {
chatsManager_->setServerDiscoInfo(info);
adHocManager_->setServerDiscoInfo(info);
}
}
void MainController::handleVCardReceived(const JID& jid, VCard::ref vCard) {
if (!jid.equals(jid_, JID::WithoutResource) || !vCard || vCard->getPhoto().empty()) {
return;
}
std::string hash = Hexify::hexify(SHA1::getHash(vCard->getPhoto()));
if (hash != vCardPhotoHash_) {
vCardPhotoHash_ = hash;
if (client_ && client_->isAvailable()) {
sendPresence(statusTracker_->getNextPresence());
}
}
}
void MainController::handleNotificationClicked(const JID& jid) {
assert(chatsManager_);
if (clientInitialized_) {
if (client_->getMUCRegistry()->isMUC(jid)) {
- uiEventStream_->send(boost::shared_ptr<JoinMUCUIEvent>(new JoinMUCUIEvent(jid)));
+ uiEventStream_->send(boost::make_shared<JoinMUCUIEvent>(jid));
}
else {
uiEventStream_->send(boost::shared_ptr<UIEvent>(new RequestChatUIEvent(jid)));
}
}
}
void MainController::handleQuitRequest() {
if (client_ && client_->isActive()) {
quitRequested_ = true;
client_->disconnect();
}
else {
resetClient();
loginWindow_->quit();
}
}
}
diff --git a/Swift/Controllers/Roster/UnitTest/RosterTest.cpp b/Swift/Controllers/Roster/UnitTest/RosterTest.cpp
index 4444e8a..0c3e769 100644
--- a/Swift/Controllers/Roster/UnitTest/RosterTest.cpp
+++ b/Swift/Controllers/Roster/UnitTest/RosterTest.cpp
@@ -66,80 +66,80 @@ class RosterTest : public CppUnit::TestFixture {
roster_->removeContact(jid2_);
CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(static_cast<GroupRosterItem*>(roster_->getRoot()->getChildren()[0])->getChildren().size()));
CPPUNIT_ASSERT_EQUAL(std::string("Bert"), static_cast<GroupRosterItem*>(roster_->getRoot()->getChildren()[0])->getChildren()[0]->getDisplayName());
}
void testRemoveSecondContactSameBare() {
JID jid4a("a@b/c");
JID jid4b("a@b/d");
roster_->addContact(jid4a, JID(), "Bert", "group1", "");
roster_->addContact(jid4b, JID(), "Cookie", "group1", "");
CPPUNIT_ASSERT_EQUAL(std::string("Cookie"), static_cast<GroupRosterItem*>(roster_->getRoot()->getChildren()[0])->getChildren()[1]->getDisplayName());
roster_->removeContact(jid4b);
CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(static_cast<GroupRosterItem*>(roster_->getRoot()->getChildren()[0])->getChildren().size()));
CPPUNIT_ASSERT_EQUAL(std::string("Bert"), static_cast<GroupRosterItem*>(roster_->getRoot()->getChildren()[0])->getChildren()[0]->getDisplayName());
}
void testApplyPresenceLikeMUC() {
JID jid4a("a@b/c");
JID jid4b("a@b/d");
JID jid4c("a@b/e");
roster_->addContact(jid4a, JID(), "Bird", "group1", "");
roster_->addContact(jid4b, JID(), "Cookie", "group1", "");
roster_->removeContact(jid4b);
roster_->addContact(jid4c, JID(), "Bert", "group1", "");
roster_->addContact(jid4b, JID(), "Ernie", "group1", "");
boost::shared_ptr<Presence> presence(new Presence());
presence->setShow(StatusShow::DND);
presence->setFrom(jid4a);
roster_->applyOnItems(SetPresence(presence, JID::WithResource));
presence->setFrom(jid4b);
roster_->applyOnItems(SetPresence(presence, JID::WithResource));
presence->setFrom(jid4c);
roster_->applyOnItems(SetPresence(presence, JID::WithResource));
- presence = boost::shared_ptr<Presence>(new Presence());
+ presence = boost::make_shared<Presence>();
presence->setFrom(jid4b);
presence->setShow(StatusShow::Online);
roster_->applyOnItems(SetPresence(presence, JID::WithResource));
std::vector<RosterItem*> children = static_cast<GroupRosterItem*>(roster_->getRoot()->getDisplayedChildren()[0])->getDisplayedChildren();
CPPUNIT_ASSERT_EQUAL(3, static_cast<int>(children.size()));
/* Check order */
CPPUNIT_ASSERT_EQUAL(std::string("Ernie"), children[0]->getDisplayName());
CPPUNIT_ASSERT_EQUAL(std::string("Bert"), children[1]->getDisplayName());
CPPUNIT_ASSERT_EQUAL(std::string("Bird"), children[2]->getDisplayName());
- presence = boost::shared_ptr<Presence>(new Presence());
+ presence = boost::make_shared<Presence>();
presence->setFrom(jid4c);
presence->setType(Presence::Unavailable);
roster_->removeContact(jid4c);
roster_->applyOnItems(SetPresence(presence, JID::WithResource));
}
void testReSortLikeMUC() {
JID jid4a("a@b/c");
JID jid4b("a@b/d");
JID jid4c("a@b/e");
roster_->addContact(jid4a, JID(), "Bird", "group1", "");
roster_->addContact(jid4b, JID(), "Cookie", "group2", "");
roster_->addContact(jid4b, JID(), "Ernie", "group1", "");
roster_->getGroup("group1")->setManualSort("2");
roster_->getGroup("group2")->setManualSort("1");
GroupRosterItem* root = roster_->getRoot();
const std::vector<RosterItem*> kids = root->getDisplayedChildren();
CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(2), kids.size());
CPPUNIT_ASSERT_EQUAL(std::string("group2"), kids[0]->getDisplayName());
CPPUNIT_ASSERT_EQUAL(std::string("group1"), kids[1]->getDisplayName());
}
private:
Roster *roster_;
JID jid1_;
JID jid2_;
JID jid3_;
};
CPPUNIT_TEST_SUITE_REGISTRATION(RosterTest);
diff --git a/Swift/Controllers/StatusTracker.cpp b/Swift/Controllers/StatusTracker.cpp
index 8f67b9f..0c88f4d 100644
--- a/Swift/Controllers/StatusTracker.cpp
+++ b/Swift/Controllers/StatusTracker.cpp
@@ -1,52 +1,54 @@
/*
* Copyright (c) 2010 Kevin Smith
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
#include "Swift/Controllers/StatusTracker.h"
+#include <boost/smart_ptr/make_shared.hpp>
+
namespace Swift {
StatusTracker::StatusTracker() {
isAutoAway_ = false;
- queuedPresence_ = boost::shared_ptr<Presence>(new Presence());
+ queuedPresence_ = boost::make_shared<Presence>();
}
boost::shared_ptr<Presence> StatusTracker::getNextPresence() {
boost::shared_ptr<Presence> presence;
if (isAutoAway_) {
- presence = boost::shared_ptr<Presence>(new Presence());
+ presence = boost::make_shared<Presence>();
presence->setShow(StatusShow::Away);
presence->setStatus(queuedPresence_->getStatus());
} else {
presence = queuedPresence_;
}
return presence;
}
void StatusTracker::setRequestedPresence(boost::shared_ptr<Presence> presence) {
isAutoAway_ = false;
queuedPresence_ = presence;
// if (presence->getType() == Presence::Unavailable) {
-// queuedPresence_ = boost::shared_ptr<Presence>(new Presence());
+// queuedPresence_ = boost::make_shared<Presence>();
// }
}
bool StatusTracker::goAutoAway() {
if (queuedPresence_->getShow() != StatusShow::Online) {
return false;
}
isAutoAway_ = true;
return true;
}
bool StatusTracker::goAutoUnAway() {
if (!isAutoAway_) {
return false;
}
isAutoAway_ = false;
return true;
}
}
diff --git a/Swift/QtUI/EventViewer/main.cpp b/Swift/QtUI/EventViewer/main.cpp
index afdb442..07a437c 100644
--- a/Swift/QtUI/EventViewer/main.cpp
+++ b/Swift/QtUI/EventViewer/main.cpp
@@ -1,31 +1,31 @@
/*
* Copyright (c) 2010 Kevin Smith
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
#include <QtGui>
#include "EventView.h"
#include "EventModel.h"
#include "QtEventWindow.h"
#include "Swiften/Events/MessageEvent.h"
#include "Swiften/Events/ErrorEvent.h"
#include "Swiften/JID/JID.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
Swift::UIEventStream eventStream;
Swift::QtEventWindow* viewer = new Swift::QtEventWindow(&eventStream);
viewer->show();
boost::shared_ptr<Swift::Message> message1(new Swift::Message());
message1->setBody("Oooh, shiny");
boost::shared_ptr<Swift::MessageEvent> event1(new Swift::MessageEvent(message1));
viewer->addEvent(boost::dynamic_pointer_cast<Swift::StanzaEvent>(event1), true);
for (int i = 0; i < 100; i++) {
viewer->addEvent(boost::dynamic_pointer_cast<Swift::StanzaEvent>(event1), false);
}
- viewer->addEvent(boost::dynamic_pointer_cast<Swift::StanzaEvent>(boost::shared_ptr<Swift::ErrorEvent>(new Swift::ErrorEvent(Swift::JID("me@example.com"), "Something bad did happen to you."))), true);
+ viewer->addEvent(boost::dynamic_pointer_cast<Swift::StanzaEvent>(boost::make_shared<Swift::ErrorEvent>(Swift::JID("me@example.com"), "Something bad did happen to you.")), true);
return app.exec();
}
diff --git a/Swift/QtUI/QtLoginWindow.cpp b/Swift/QtUI/QtLoginWindow.cpp
index a3b7837..dc6001b 100644
--- a/Swift/QtUI/QtLoginWindow.cpp
+++ b/Swift/QtUI/QtLoginWindow.cpp
@@ -373,71 +373,71 @@ void QtLoginWindow::setLoginAutomatically(bool loginAutomatically) {
loginAutomatically_->setChecked(loginAutomatically);
}
void QtLoginWindow::handleCertficateChecked(bool checked) {
if (checked) {
#ifdef HAVE_SCHANNEL
certificateFile_ = P2QSTRING(selectCAPICertificate());
if (certificateFile_.isEmpty()) {
certificateButton_->setChecked(false);
}
#else
certificateFile_ = QFileDialog::getOpenFileName(this, tr("Select an authentication certificate"), QString(), QString("*.cert;*.p12;*.pfx"));
if (certificateFile_.isEmpty()) {
certificateButton_->setChecked(false);
}
#endif
}
else {
certificateFile_ = "";
}
}
void QtLoginWindow::handleAbout() {
if (!aboutDialog_) {
aboutDialog_ = new QtAboutWidget();
aboutDialog_->show();
}
else {
aboutDialog_->show();
aboutDialog_->raise();
aboutDialog_->activateWindow();
}
}
void QtLoginWindow::handleShowXMLConsole() {
- uiEventStream_->send(boost::shared_ptr<RequestXMLConsoleUIEvent>(new RequestXMLConsoleUIEvent()));
+ uiEventStream_->send(boost::make_shared<RequestXMLConsoleUIEvent>());
}
void QtLoginWindow::handleShowFileTransferOverview() {
uiEventStream_->send(boost::make_shared<RequestFileTransferListUIEvent>());
}
void QtLoginWindow::handleToggleSounds(bool enabled) {
settings_->storeSetting(SettingConstants::PLAY_SOUNDS, enabled);
}
void QtLoginWindow::handleToggleNotifications(bool enabled) {
settings_->storeSetting(SettingConstants::SHOW_NOTIFICATIONS, enabled);
}
void QtLoginWindow::handleQuit() {
onQuitRequest();
}
void QtLoginWindow::quit() {
QApplication::quit();
}
void QtLoginWindow::setInitialMenus() {
menuBar_->clear();
menuBar_->addMenu(swiftMenu_);
#ifdef SWIFTEN_PLATFORM_MACOSX
menuBar_->addMenu(generalMenu_);
#endif
}
void QtLoginWindow::morphInto(MainWindow *mainWindow) {
QtMainWindow *qtMainWindow = dynamic_cast<QtMainWindow*>(mainWindow);
assert(qtMainWindow);
stack_->removeWidget(loginWidgetWrapper_);
stack_->addWidget(qtMainWindow);
diff --git a/Swiften/Avatars/UnitTest/VCardUpdateAvatarManagerTest.cpp b/Swiften/Avatars/UnitTest/VCardUpdateAvatarManagerTest.cpp
index 821412b..60e76f8 100644
--- a/Swiften/Avatars/UnitTest/VCardUpdateAvatarManagerTest.cpp
+++ b/Swiften/Avatars/UnitTest/VCardUpdateAvatarManagerTest.cpp
@@ -126,71 +126,71 @@ class VCardUpdateAvatarManagerTest : public CppUnit::TestFixture {
stanzaChannel->setAvailable(false);
stanzaChannel->setAvailable(true);
CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(changes.size()));
CPPUNIT_ASSERT_EQUAL(user1.toBare(), changes[0]);
CPPUNIT_ASSERT_EQUAL(std::string(""), testling->getAvatarHash(user1.toBare()));
}
void testStanzaChannelReset_ReceiveHashAfterResetUpdatesHash() {
boost::shared_ptr<VCardUpdateAvatarManager> testling = createManager();
stanzaChannel->onPresenceReceived(createPresenceWithPhotoHash(user1, avatar1Hash));
stanzaChannel->onIQReceived(createVCardResult(avatar1));
changes.clear();
stanzaChannel->sentStanzas.clear();
stanzaChannel->setAvailable(false);
stanzaChannel->setAvailable(true);
stanzaChannel->onPresenceReceived(createPresenceWithPhotoHash(user1, avatar1Hash));
CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(changes.size()));
CPPUNIT_ASSERT_EQUAL(user1.toBare(), changes[1]);
CPPUNIT_ASSERT_EQUAL(avatar1Hash, testling->getAvatarHash(user1.toBare()));
}
private:
boost::shared_ptr<VCardUpdateAvatarManager> createManager() {
boost::shared_ptr<VCardUpdateAvatarManager> result(new VCardUpdateAvatarManager(vcardManager, stanzaChannel, avatarStorage, mucRegistry));
result->onAvatarChanged.connect(boost::bind(&VCardUpdateAvatarManagerTest::handleAvatarChanged, this, _1));
return result;
}
boost::shared_ptr<Presence> createPresenceWithPhotoHash(const JID& jid, const std::string& hash) {
boost::shared_ptr<Presence> presence(new Presence());
presence->setFrom(jid);
- presence->addPayload(boost::shared_ptr<VCardUpdate>(new VCardUpdate(hash)));
+ presence->addPayload(boost::make_shared<VCardUpdate>(hash));
return presence;
}
IQ::ref createVCardResult(const ByteArray& avatar) {
VCard::ref vcard(new VCard());
if (!avatar.empty()) {
vcard->setPhoto(avatar);
}
return IQ::createResult(JID("baz@fum.com"), stanzaChannel->sentStanzas[0]->getTo(), stanzaChannel->sentStanzas[0]->getID(), vcard);
}
void handleAvatarChanged(const JID& jid) {
changes.push_back(jid);
}
private:
struct DummyMUCRegistry : public MUCRegistry {
bool isMUC(const JID& jid) const { return std::find(mucs_.begin(), mucs_.end(), jid) != mucs_.end(); }
std::vector<JID> mucs_;
};
JID ownJID;
DummyStanzaChannel* stanzaChannel;
IQRouter* iqRouter;
DummyMUCRegistry* mucRegistry;
AvatarMemoryStorage* avatarStorage;
VCardManager* vcardManager;
VCardMemoryStorage* vcardStorage;
ByteArray avatar1;
std::string avatar1Hash;
std::vector<JID> changes;
JID user1;
JID user2;
};
diff --git a/Swiften/Client/UnitTest/ClientSessionTest.cpp b/Swiften/Client/UnitTest/ClientSessionTest.cpp
index 22db8fc..a6d5a3a 100644
--- a/Swiften/Client/UnitTest/ClientSessionTest.cpp
+++ b/Swiften/Client/UnitTest/ClientSessionTest.cpp
@@ -34,71 +34,71 @@
using namespace Swift;
class ClientSessionTest : public CppUnit::TestFixture {
CPPUNIT_TEST_SUITE(ClientSessionTest);
CPPUNIT_TEST(testStart_Error);
CPPUNIT_TEST(testStart_StreamError);
CPPUNIT_TEST(testStartTLS);
CPPUNIT_TEST(testStartTLS_ServerError);
CPPUNIT_TEST(testStartTLS_ConnectError);
CPPUNIT_TEST(testStartTLS_InvalidIdentity);
CPPUNIT_TEST(testStart_StreamFeaturesWithoutResourceBindingFails);
CPPUNIT_TEST(testAuthenticate);
CPPUNIT_TEST(testAuthenticate_Unauthorized);
CPPUNIT_TEST(testAuthenticate_NoValidAuthMechanisms);
CPPUNIT_TEST(testAuthenticate_PLAINOverNonTLS);
CPPUNIT_TEST(testAuthenticate_RequireTLS);
CPPUNIT_TEST(testStreamManagement);
CPPUNIT_TEST(testStreamManagement_Failed);
CPPUNIT_TEST(testFinishAcksStanzas);
/*
CPPUNIT_TEST(testResourceBind);
CPPUNIT_TEST(testResourceBind_ChangeResource);
CPPUNIT_TEST(testResourceBind_EmptyResource);
CPPUNIT_TEST(testResourceBind_Error);
CPPUNIT_TEST(testSessionStart);
CPPUNIT_TEST(testSessionStart_Error);
CPPUNIT_TEST(testSessionStart_AfterResourceBind);
CPPUNIT_TEST(testWhitespacePing);
CPPUNIT_TEST(testReceiveElementAfterSessionStarted);
CPPUNIT_TEST(testSendElement);
*/
CPPUNIT_TEST_SUITE_END();
public:
void setUp() {
- server = boost::shared_ptr<MockSessionStream>(new MockSessionStream());
+ server = boost::make_shared<MockSessionStream>();
sessionFinishedReceived = false;
needCredentials = false;
blindCertificateTrustChecker = new BlindCertificateTrustChecker();
}
void tearDown() {
delete blindCertificateTrustChecker;
}
void testStart_Error() {
boost::shared_ptr<ClientSession> session(createSession());
session->start();
server->breakConnection();
CPPUNIT_ASSERT_EQUAL(ClientSession::Finished, session->getState());
CPPUNIT_ASSERT(sessionFinishedReceived);
CPPUNIT_ASSERT(sessionFinishedError);
}
void testStart_StreamError() {
boost::shared_ptr<ClientSession> session(createSession());
session->start();
server->sendStreamStart();
server->sendStreamError();
CPPUNIT_ASSERT_EQUAL(ClientSession::Finished, session->getState());
CPPUNIT_ASSERT(sessionFinishedReceived);
CPPUNIT_ASSERT(sessionFinishedError);
}
void testStartTLS() {
boost::shared_ptr<ClientSession> session(createSession());
session->setCertificateTrustChecker(blindCertificateTrustChecker);
session->start();
server->receiveStreamStart();
@@ -388,147 +388,147 @@ class ClientSessionTest : public CppUnit::TestFixture {
}
virtual bool isTLSEncrypted() {
return tlsEncrypted;
}
virtual ByteArray getTLSFinishMessage() const {
return ByteArray();
}
virtual Certificate::ref getPeerCertificate() const {
return Certificate::ref(new SimpleCertificate());
}
virtual boost::shared_ptr<CertificateVerificationError> getPeerCertificateVerificationError() const {
return boost::shared_ptr<CertificateVerificationError>();
}
virtual bool supportsZLibCompression() {
return true;
}
virtual void addZLibCompression() {
compressed = true;
}
virtual void setWhitespacePingEnabled(bool enabled) {
whitespacePingEnabled = enabled;
}
virtual void resetXMPPParser() {
resetCount++;
}
void breakConnection() {
- onClosed(boost::shared_ptr<SessionStream::Error>(new SessionStream::Error(SessionStream::Error::ConnectionReadError)));
+ onClosed(boost::make_shared<SessionStream::Error>(SessionStream::Error::ConnectionReadError));
}
void breakTLS() {
- onClosed(boost::shared_ptr<SessionStream::Error>(new SessionStream::Error(SessionStream::Error::TLSError)));
+ onClosed(boost::make_shared<SessionStream::Error>(SessionStream::Error::TLSError));
}
void sendStreamStart() {
ProtocolHeader header;
header.setTo("foo.com");
return onStreamStartReceived(header);
}
void sendStreamFeaturesWithStartTLS() {
boost::shared_ptr<StreamFeatures> streamFeatures(new StreamFeatures());
streamFeatures->setHasStartTLS();
onElementReceived(streamFeatures);
}
void sendStreamError() {
onElementReceived(boost::make_shared<StreamError>());
}
void sendTLSProceed() {
- onElementReceived(boost::shared_ptr<TLSProceed>(new TLSProceed()));
+ onElementReceived(boost::make_shared<TLSProceed>());
}
void sendTLSFailure() {
- onElementReceived(boost::shared_ptr<StartTLSFailure>(new StartTLSFailure()));
+ onElementReceived(boost::make_shared<StartTLSFailure>());
}
void sendStreamFeaturesWithMultipleAuthentication() {
boost::shared_ptr<StreamFeatures> streamFeatures(new StreamFeatures());
streamFeatures->addAuthenticationMechanism("PLAIN");
streamFeatures->addAuthenticationMechanism("DIGEST-MD5");
streamFeatures->addAuthenticationMechanism("SCRAM-SHA1");
onElementReceived(streamFeatures);
}
void sendStreamFeaturesWithPLAINAuthentication() {
boost::shared_ptr<StreamFeatures> streamFeatures(new StreamFeatures());
streamFeatures->addAuthenticationMechanism("PLAIN");
onElementReceived(streamFeatures);
}
void sendStreamFeaturesWithUnknownAuthentication() {
boost::shared_ptr<StreamFeatures> streamFeatures(new StreamFeatures());
streamFeatures->addAuthenticationMechanism("UNKNOWN");
onElementReceived(streamFeatures);
}
void sendStreamFeaturesWithBindAndStreamManagement() {
boost::shared_ptr<StreamFeatures> streamFeatures(new StreamFeatures());
streamFeatures->setHasResourceBind();
streamFeatures->setHasStreamManagement();
onElementReceived(streamFeatures);
}
void sendEmptyStreamFeatures() {
onElementReceived(boost::make_shared<StreamFeatures>());
}
void sendAuthSuccess() {
- onElementReceived(boost::shared_ptr<AuthSuccess>(new AuthSuccess()));
+ onElementReceived(boost::make_shared<AuthSuccess>());
}
void sendAuthFailure() {
- onElementReceived(boost::shared_ptr<AuthFailure>(new AuthFailure()));
+ onElementReceived(boost::make_shared<AuthFailure>());
}
void sendStreamManagementEnabled() {
- onElementReceived(boost::shared_ptr<StreamManagementEnabled>(new StreamManagementEnabled()));
+ onElementReceived(boost::make_shared<StreamManagementEnabled>());
}
void sendStreamManagementFailed() {
- onElementReceived(boost::shared_ptr<StreamManagementFailed>(new StreamManagementFailed()));
+ onElementReceived(boost::make_shared<StreamManagementFailed>());
}
void sendBindResult() {
boost::shared_ptr<ResourceBind> resourceBind(new ResourceBind());
resourceBind->setJID(JID("foo@bar.com/bla"));
boost::shared_ptr<IQ> iq = IQ::createResult(JID("foo@bar.com"), bindID, resourceBind);
onElementReceived(iq);
}
void sendMessage() {
boost::shared_ptr<Message> message = boost::make_shared<Message>();
message->setTo(JID("foo@bar.com/bla"));
onElementReceived(message);
}
void receiveStreamStart() {
Event event = popEvent();
CPPUNIT_ASSERT(event.header);
}
void receiveStartTLS() {
Event event = popEvent();
CPPUNIT_ASSERT(event.element);
CPPUNIT_ASSERT(boost::dynamic_pointer_cast<StartTLSRequest>(event.element));
}
void receiveAuthRequest(const std::string& mech) {
Event event = popEvent();
CPPUNIT_ASSERT(event.element);
boost::shared_ptr<AuthRequest> request(boost::dynamic_pointer_cast<AuthRequest>(event.element));
CPPUNIT_ASSERT(request);
CPPUNIT_ASSERT_EQUAL(mech, request->getMechanism());
}
void receiveStreamManagementEnable() {
@@ -723,52 +723,52 @@ CPPUNIT_TEST_SUITE_REGISTRATION(ClientSessionTest);
boost::shared_ptr<MockSession> session(createSession("me@foo.com/Bar"));
session->onSessionStarted.connect(boost::bind(&ClientSessionTest::setSessionStarted, this));
getMockServer()->expectStreamStart();
getMockServer()->sendStreamStart();
getMockServer()->sendStreamFeaturesWithResourceBindAndSession();
getMockServer()->expectResourceBind("Bar", "session-bind");
getMockServer()->sendResourceBindResponse("me@foo.com/Bar", "session-bind");
getMockServer()->expectSessionStart("session-start");
getMockServer()->sendSessionStartResponse("session-start");
session->startSession();
processEvents();
CPPUNIT_ASSERT_EQUAL(ClientSession::SessionStarted, session->getState());
CPPUNIT_ASSERT(sessionStarted_);
}
void testWhitespacePing() {
boost::shared_ptr<MockSession> session(createSession("me@foo.com/Bar"));
getMockServer()->expectStreamStart();
getMockServer()->sendStreamStart();
getMockServer()->sendStreamFeatures();
session->startSession();
processEvents();
CPPUNIT_ASSERT(session->getWhitespacePingLayer());
}
void testReceiveElementAfterSessionStarted() {
boost::shared_ptr<MockSession> session(createSession("me@foo.com/Bar"));
getMockServer()->expectStreamStart();
getMockServer()->sendStreamStart();
getMockServer()->sendStreamFeatures();
session->startSession();
processEvents();
getMockServer()->expectMessage();
- session->sendElement(boost::shared_ptr<Message>(new Message()));
+ session->sendElement(boost::make_shared<Message>()));
}
void testSendElement() {
boost::shared_ptr<MockSession> session(createSession("me@foo.com/Bar"));
session->onElementReceived.connect(boost::bind(&ClientSessionTest::addReceivedElement, this, _1));
getMockServer()->expectStreamStart();
getMockServer()->sendStreamStart();
getMockServer()->sendStreamFeatures();
getMockServer()->sendMessage();
session->startSession();
processEvents();
CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(receivedElements_.size()));
CPPUNIT_ASSERT(boost::dynamic_pointer_cast<Message>(receivedElements_[0]));
}
#endif
diff --git a/Swiften/Component/ComponentSession.cpp b/Swiften/Component/ComponentSession.cpp
index af11146..51d9d15 100644
--- a/Swiften/Component/ComponentSession.cpp
+++ b/Swiften/Component/ComponentSession.cpp
@@ -1,44 +1,45 @@
/*
* Copyright (c) 2010 Remko Tronçon
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
#include <Swiften/Component/ComponentSession.h>
#include <boost/bind.hpp>
+#include <boost/smart_ptr/make_shared.hpp>
#include <Swiften/Elements/ProtocolHeader.h>
#include <Swiften/Elements/ComponentHandshake.h>
#include <Swiften/Session/SessionStream.h>
#include <Swiften/Component/ComponentHandshakeGenerator.h>
namespace Swift {
ComponentSession::ComponentSession(const JID& jid, const std::string& secret, boost::shared_ptr<SessionStream> stream) : jid(jid), secret(secret), stream(stream), state(Initial) {
}
ComponentSession::~ComponentSession() {
}
void ComponentSession::start() {
stream->onStreamStartReceived.connect(boost::bind(&ComponentSession::handleStreamStart, shared_from_this(), _1));
stream->onElementReceived.connect(boost::bind(&ComponentSession::handleElement, shared_from_this(), _1));
stream->onClosed.connect(boost::bind(&ComponentSession::handleStreamClosed, shared_from_this(), _1));
assert(state == Initial);
state = WaitingForStreamStart;
sendStreamHeader();
}
void ComponentSession::sendStreamHeader() {
ProtocolHeader header;
header.setTo(jid);
stream->writeHeader(header);
}
void ComponentSession::sendStanza(boost::shared_ptr<Stanza> stanza) {
stream->writeElement(stanza);
}
void ComponentSession::handleStreamStart(const ProtocolHeader& header) {
@@ -69,47 +70,47 @@ void ComponentSession::handleElement(boost::shared_ptr<Element> element) {
finishSession(Error::AuthenticationFailedError);
}
else {
finishSession(Error::UnexpectedElementError);
}
}
bool ComponentSession::checkState(State state) {
if (this->state != state) {
finishSession(Error::UnexpectedElementError);
return false;
}
return true;
}
void ComponentSession::handleStreamClosed(boost::shared_ptr<Swift::Error> streamError) {
State oldState = state;
state = Finished;
stream->setWhitespacePingEnabled(false);
stream->onStreamStartReceived.disconnect(boost::bind(&ComponentSession::handleStreamStart, shared_from_this(), _1));
stream->onElementReceived.disconnect(boost::bind(&ComponentSession::handleElement, shared_from_this(), _1));
stream->onClosed.disconnect(boost::bind(&ComponentSession::handleStreamClosed, shared_from_this(), _1));
if (oldState == Finishing) {
onFinished(error);
}
else {
onFinished(streamError);
}
}
void ComponentSession::finish() {
finishSession(boost::shared_ptr<Error>());
}
void ComponentSession::finishSession(Error::Type error) {
- finishSession(boost::shared_ptr<Swift::ComponentSession::Error>(new Swift::ComponentSession::Error(error)));
+ finishSession(boost::make_shared<Swift::ComponentSession::Error>(error));
}
void ComponentSession::finishSession(boost::shared_ptr<Swift::Error> finishError) {
state = Finishing;
error = finishError;
assert(stream->isOpen());
stream->writeFooter();
stream->close();
}
}
diff --git a/Swiften/Component/UnitTest/ComponentSessionTest.cpp b/Swiften/Component/UnitTest/ComponentSessionTest.cpp
index 1541cce..9763c7f 100644
--- a/Swiften/Component/UnitTest/ComponentSessionTest.cpp
+++ b/Swiften/Component/UnitTest/ComponentSessionTest.cpp
@@ -1,64 +1,64 @@
/*
* Copyright (c) 2010 Remko Tronçon
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <deque>
#include <boost/bind.hpp>
#include <boost/optional.hpp>
#include <Swiften/Session/SessionStream.h>
#include <Swiften/Component/ComponentSession.h>
#include <Swiften/Elements/ComponentHandshake.h>
#include <Swiften/Elements/AuthFailure.h>
using namespace Swift;
class ComponentSessionTest : public CppUnit::TestFixture {
CPPUNIT_TEST_SUITE(ComponentSessionTest);
CPPUNIT_TEST(testStart);
CPPUNIT_TEST(testStart_Error);
CPPUNIT_TEST(testStart_Unauthorized);
CPPUNIT_TEST_SUITE_END();
public:
void setUp() {
- server = boost::shared_ptr<MockSessionStream>(new MockSessionStream());
+ server = boost::make_shared<MockSessionStream>();
sessionFinishedReceived = false;
}
void testStart() {
boost::shared_ptr<ComponentSession> session(createSession());
session->start();
server->receiveStreamStart();
server->sendStreamStart();
server->receiveHandshake();
server->sendHandshakeResponse();
CPPUNIT_ASSERT(server->whitespacePingEnabled);
session->finish();
CPPUNIT_ASSERT(!server->whitespacePingEnabled);
}
void testStart_Error() {
boost::shared_ptr<ComponentSession> session(createSession());
session->start();
server->breakConnection();
CPPUNIT_ASSERT_EQUAL(ComponentSession::Finished, session->getState());
CPPUNIT_ASSERT(sessionFinishedReceived);
CPPUNIT_ASSERT(sessionFinishedError);
}
void testStart_Unauthorized() {
boost::shared_ptr<ComponentSession> session(createSession());
session->start();
server->receiveStreamStart();
server->sendStreamStart();
server->receiveHandshake();
server->sendHandshakeError();
@@ -127,71 +127,71 @@ class ComponentSessionTest : public CppUnit::TestFixture {
}
virtual bool isTLSEncrypted() {
return false;
}
virtual ByteArray getTLSFinishMessage() const {
return ByteArray();
}
virtual Certificate::ref getPeerCertificate() const {
return Certificate::ref();
}
virtual boost::shared_ptr<CertificateVerificationError> getPeerCertificateVerificationError() const {
return boost::shared_ptr<CertificateVerificationError>();
}
virtual bool supportsZLibCompression() {
return true;
}
virtual void addZLibCompression() {
assert(false);
}
virtual void setWhitespacePingEnabled(bool enabled) {
whitespacePingEnabled = enabled;
}
virtual void resetXMPPParser() {
resetCount++;
}
void breakConnection() {
- onClosed(boost::shared_ptr<SessionStream::Error>(new SessionStream::Error(SessionStream::Error::ConnectionReadError)));
+ onClosed(boost::make_shared<SessionStream::Error>(SessionStream::Error::ConnectionReadError));
}
void sendStreamStart() {
ProtocolHeader header;
header.setFrom("service.foo.com");
return onStreamStartReceived(header);
}
void sendHandshakeResponse() {
onElementReceived(ComponentHandshake::ref(new ComponentHandshake()));
}
void sendHandshakeError() {
// FIXME: This isn't the correct element
onElementReceived(AuthFailure::ref(new AuthFailure()));
}
void receiveStreamStart() {
Event event = popEvent();
CPPUNIT_ASSERT(event.header);
}
void receiveHandshake() {
Event event = popEvent();
CPPUNIT_ASSERT(event.element);
ComponentHandshake::ref handshake(boost::dynamic_pointer_cast<ComponentHandshake>(event.element));
CPPUNIT_ASSERT(handshake);
CPPUNIT_ASSERT_EQUAL(std::string("4c4f8a41141722c8bbfbdd92d827f7b2fc0a542b"), handshake->getData());
}
Event popEvent() {
CPPUNIT_ASSERT(!receivedEvents.empty());
Event event = receivedEvents.front();
receivedEvents.pop_front();
return event;
diff --git a/Swiften/Disco/DiscoInfoResponder.cpp b/Swiften/Disco/DiscoInfoResponder.cpp
index a8dd9f0..9e58bff 100644
--- a/Swiften/Disco/DiscoInfoResponder.cpp
+++ b/Swiften/Disco/DiscoInfoResponder.cpp
@@ -1,47 +1,49 @@
/*
* Copyright (c) 2010 Remko Tronçon
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
+#include <boost/smart_ptr/make_shared.hpp>
+
#include <Swiften/Disco/DiscoInfoResponder.h>
#include <Swiften/Queries/IQRouter.h>
#include <Swiften/Elements/DiscoInfo.h>
namespace Swift {
DiscoInfoResponder::DiscoInfoResponder(IQRouter* router) : GetResponder<DiscoInfo>(router) {
}
void DiscoInfoResponder::clearDiscoInfo() {
info_ = DiscoInfo();
nodeInfo_.clear();
}
void DiscoInfoResponder::setDiscoInfo(const DiscoInfo& info) {
info_ = info;
}
void DiscoInfoResponder::setDiscoInfo(const std::string& node, const DiscoInfo& info) {
DiscoInfo newInfo(info);
newInfo.setNode(node);
nodeInfo_[node] = newInfo;
}
bool DiscoInfoResponder::handleGetRequest(const JID& from, const JID&, const std::string& id, boost::shared_ptr<DiscoInfo> info) {
if (info->getNode().empty()) {
- sendResponse(from, id, boost::shared_ptr<DiscoInfo>(new DiscoInfo(info_)));
+ sendResponse(from, id, boost::make_shared<DiscoInfo>(info_));
}
else {
std::map<std::string,DiscoInfo>::const_iterator i = nodeInfo_.find(info->getNode());
if (i != nodeInfo_.end()) {
- sendResponse(from, id, boost::shared_ptr<DiscoInfo>(new DiscoInfo((*i).second)));
+ sendResponse(from, id, boost::make_shared<DiscoInfo>((*i).second));
}
else {
sendError(from, id, ErrorPayload::ItemNotFound, ErrorPayload::Cancel);
}
}
return true;
}
}
diff --git a/Swiften/Disco/GetDiscoInfoRequest.h b/Swiften/Disco/GetDiscoInfoRequest.h
index e211632..c9a4c97 100644
--- a/Swiften/Disco/GetDiscoInfoRequest.h
+++ b/Swiften/Disco/GetDiscoInfoRequest.h
@@ -1,35 +1,37 @@
/*
* Copyright (c) 2010 Remko Tronçon
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
#pragma once
+#include <boost/smart_ptr/make_shared.hpp>
+
#include <Swiften/Queries/GenericRequest.h>
#include <Swiften/Elements/DiscoInfo.h>
namespace Swift {
class GetDiscoInfoRequest : public GenericRequest<DiscoInfo> {
public:
typedef boost::shared_ptr<GetDiscoInfoRequest> ref;
static ref create(const JID& jid, IQRouter* router) {
return ref(new GetDiscoInfoRequest(jid, router));
}
static ref create(const JID& jid, const std::string& node, IQRouter* router) {
return ref(new GetDiscoInfoRequest(jid, node, router));
}
private:
GetDiscoInfoRequest(const JID& jid, IQRouter* router) :
- GenericRequest<DiscoInfo>(IQ::Get, jid, boost::shared_ptr<DiscoInfo>(new DiscoInfo()), router) {
+ GenericRequest<DiscoInfo>(IQ::Get, jid, boost::make_shared<DiscoInfo>(), router) {
}
GetDiscoInfoRequest(const JID& jid, const std::string& node, IQRouter* router) :
- GenericRequest<DiscoInfo>(IQ::Get, jid, boost::shared_ptr<DiscoInfo>(new DiscoInfo()), router) {
+ GenericRequest<DiscoInfo>(IQ::Get, jid, boost::make_shared<DiscoInfo>(), router) {
getPayloadGeneric()->setNode(node);
}
};
}
diff --git a/Swiften/Disco/GetDiscoItemsRequest.h b/Swiften/Disco/GetDiscoItemsRequest.h
index 20d18f8..c4ed579 100644
--- a/Swiften/Disco/GetDiscoItemsRequest.h
+++ b/Swiften/Disco/GetDiscoItemsRequest.h
@@ -1,35 +1,37 @@
/*
* Copyright (c) 2010 Kevin Smith
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
#pragma once
+#include <boost/smart_ptr/make_shared.hpp>
+
#include <Swiften/Queries/GenericRequest.h>
#include <Swiften/Elements/DiscoItems.h>
namespace Swift {
class GetDiscoItemsRequest : public GenericRequest<DiscoItems> {
public:
typedef boost::shared_ptr<GetDiscoItemsRequest> ref;
static ref create(const JID& jid, IQRouter* router) {
return ref(new GetDiscoItemsRequest(jid, router));
}
static ref create(const JID& jid, const std::string& node, IQRouter* router) {
return ref(new GetDiscoItemsRequest(jid, node, router));
}
private:
GetDiscoItemsRequest(const JID& jid, IQRouter* router) :
- GenericRequest<DiscoItems>(IQ::Get, jid, boost::shared_ptr<DiscoItems>(new DiscoItems()), router) {
+ GenericRequest<DiscoItems>(IQ::Get, jid, boost::make_shared<DiscoItems>(), router) {
}
GetDiscoItemsRequest(const JID& jid, const std::string& node, IQRouter* router) :
- GenericRequest<DiscoItems>(IQ::Get, jid, boost::shared_ptr<DiscoItems>(new DiscoItems()), router) {
+ GenericRequest<DiscoItems>(IQ::Get, jid, boost::make_shared<DiscoItems>(), router) {
getPayloadGeneric()->setNode(node);
}
};
}
diff --git a/Swiften/Disco/JIDDiscoInfoResponder.cpp b/Swiften/Disco/JIDDiscoInfoResponder.cpp
index 0a25bef..4aed254 100644
--- a/Swiften/Disco/JIDDiscoInfoResponder.cpp
+++ b/Swiften/Disco/JIDDiscoInfoResponder.cpp
@@ -1,54 +1,56 @@
/*
* Copyright (c) 2010 Remko Tronçon
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
+#include <boost/smart_ptr/make_shared.hpp>
+
#include <Swiften/Disco/JIDDiscoInfoResponder.h>
#include <Swiften/Queries/IQRouter.h>
#include <Swiften/Elements/DiscoInfo.h>
namespace Swift {
JIDDiscoInfoResponder::JIDDiscoInfoResponder(IQRouter* router) : GetResponder<DiscoInfo>(router) {
}
void JIDDiscoInfoResponder::clearDiscoInfo(const JID& jid) {
info.erase(jid);
}
void JIDDiscoInfoResponder::setDiscoInfo(const JID& jid, const DiscoInfo& discoInfo) {
JIDDiscoInfoMap::iterator i = info.insert(std::make_pair(jid, JIDDiscoInfo())).first;
i->second.discoInfo = discoInfo;
}
void JIDDiscoInfoResponder::setDiscoInfo(const JID& jid, const std::string& node, const DiscoInfo& discoInfo) {
JIDDiscoInfoMap::iterator i = info.insert(std::make_pair(jid, JIDDiscoInfo())).first;
DiscoInfo newInfo(discoInfo);
newInfo.setNode(node);
i->second.nodeDiscoInfo[node] = newInfo;
}
bool JIDDiscoInfoResponder::handleGetRequest(const JID& from, const JID& to, const std::string& id, boost::shared_ptr<DiscoInfo> discoInfo) {
JIDDiscoInfoMap::const_iterator i = info.find(to);
if (i != info.end()) {
if (discoInfo->getNode().empty()) {
- sendResponse(from, to, id, boost::shared_ptr<DiscoInfo>(new DiscoInfo(i->second.discoInfo)));
+ sendResponse(from, to, id, boost::make_shared<DiscoInfo>(i->second.discoInfo));
}
else {
std::map<std::string,DiscoInfo>::const_iterator j = i->second.nodeDiscoInfo.find(discoInfo->getNode());
if (j != i->second.nodeDiscoInfo.end()) {
- sendResponse(from, to, id, boost::shared_ptr<DiscoInfo>(new DiscoInfo(j->second)));
+ sendResponse(from, to, id, boost::make_shared<DiscoInfo>(j->second));
}
else {
sendError(from, to, id, ErrorPayload::ItemNotFound, ErrorPayload::Cancel);
}
}
}
else {
sendError(from, to, id, ErrorPayload::ItemNotFound, ErrorPayload::Cancel);
}
return true;
}
}
diff --git a/Swiften/Disco/UnitTest/CapsManagerTest.cpp b/Swiften/Disco/UnitTest/CapsManagerTest.cpp
index 0681569..ca55c48 100644
--- a/Swiften/Disco/UnitTest/CapsManagerTest.cpp
+++ b/Swiften/Disco/UnitTest/CapsManagerTest.cpp
@@ -13,80 +13,80 @@
#include <Swiften/Disco/CapsMemoryStorage.h>
#include <Swiften/Disco/CapsInfoGenerator.h>
#include <Swiften/Queries/IQRouter.h>
#include <Swiften/Elements/CapsInfo.h>
#include <Swiften/Elements/DiscoInfo.h>
#include <Swiften/Client/DummyStanzaChannel.h>
using namespace Swift;
class CapsManagerTest : public CppUnit::TestFixture {
CPPUNIT_TEST_SUITE(CapsManagerTest);
CPPUNIT_TEST(testReceiveNewHashRequestsDisco);
CPPUNIT_TEST(testReceiveSameHashDoesNotRequestDisco);
CPPUNIT_TEST(testReceiveLegacyCapsDoesNotRequestDisco);
CPPUNIT_TEST(testReceiveSameHashFromSameUserAfterFailedDiscoDoesNotRequestDisco);
CPPUNIT_TEST(testReceiveSameHashFromDifferentUserAfterFailedDiscoRequestsDisco);
CPPUNIT_TEST(testReceiveSameHashFromDifferentUserAfterIncorrectVerificationRequestsDisco);
CPPUNIT_TEST(testReceiveDifferentHashFromSameUserAfterFailedDiscoDoesNotRequestDisco);
CPPUNIT_TEST(testReceiveSameHashAfterSuccesfulDiscoDoesNotRequestDisco);
CPPUNIT_TEST(testReceiveSuccesfulDiscoStoresCaps);
CPPUNIT_TEST(testReceiveIncorrectVerificationDiscoDoesNotStoreCaps);
CPPUNIT_TEST(testReceiveFailingDiscoFallsBack);
CPPUNIT_TEST(testReceiveNoDiscoFallsBack);
CPPUNIT_TEST(testReceiveFailingFallbackDiscoFallsBack);
CPPUNIT_TEST(testReceiveSameHashFromFailingUserAfterReconnectRequestsDisco);
CPPUNIT_TEST(testReconnectResetsFallback);
CPPUNIT_TEST(testReconnectResetsRequests);
CPPUNIT_TEST_SUITE_END();
public:
void setUp() {
stanzaChannel = new DummyStanzaChannel();
iqRouter = new IQRouter(stanzaChannel);
storage = new CapsMemoryStorage();
user1 = JID("user1@bar.com/bla");
- discoInfo1 = boost::shared_ptr<DiscoInfo>(new DiscoInfo());
+ discoInfo1 = boost::make_shared<DiscoInfo>();
discoInfo1->addFeature("http://swift.im/feature1");
- capsInfo1 = boost::shared_ptr<CapsInfo>(new CapsInfo(CapsInfoGenerator("http://node1.im").generateCapsInfo(*discoInfo1.get())));
- capsInfo1alt = boost::shared_ptr<CapsInfo>(new CapsInfo(CapsInfoGenerator("http://node2.im").generateCapsInfo(*discoInfo1.get())));
+ capsInfo1 = boost::make_shared<CapsInfo>(CapsInfoGenerator("http://node1.im").generateCapsInfo(*discoInfo1.get()));
+ capsInfo1alt = boost::make_shared<CapsInfo>(CapsInfoGenerator("http://node2.im").generateCapsInfo(*discoInfo1.get()));
user2 = JID("user2@foo.com/baz");
- discoInfo2 = boost::shared_ptr<DiscoInfo>(new DiscoInfo());
+ discoInfo2 = boost::make_shared<DiscoInfo>();
discoInfo2->addFeature("http://swift.im/feature2");
- capsInfo2 = boost::shared_ptr<CapsInfo>(new CapsInfo(CapsInfoGenerator("http://node2.im").generateCapsInfo(*discoInfo2.get())));
+ capsInfo2 = boost::make_shared<CapsInfo>(CapsInfoGenerator("http://node2.im").generateCapsInfo(*discoInfo2.get()));
user3 = JID("user3@foo.com/baz");
- legacyCapsInfo = boost::shared_ptr<CapsInfo>(new CapsInfo("http://swift.im", "ver1", ""));
+ legacyCapsInfo = boost::make_shared<CapsInfo>("http://swift.im", "ver1", "");
}
void tearDown() {
delete storage;
delete iqRouter;
delete stanzaChannel;
}
void testReceiveNewHashRequestsDisco() {
boost::shared_ptr<CapsManager> testling = createManager();
sendPresenceWithCaps(user1, capsInfo1);
CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<DiscoInfo>(0, user1, IQ::Get));
boost::shared_ptr<DiscoInfo> discoInfo(stanzaChannel->sentStanzas[0]->getPayload<DiscoInfo>());
CPPUNIT_ASSERT(discoInfo);
CPPUNIT_ASSERT_EQUAL("http://node1.im#" + capsInfo1->getVersion(), discoInfo->getNode());
}
void testReceiveSameHashDoesNotRequestDisco() {
boost::shared_ptr<CapsManager> testling = createManager();
sendPresenceWithCaps(user1, capsInfo1);
stanzaChannel->sentStanzas.clear();
sendPresenceWithCaps(user1, capsInfo1);
CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(stanzaChannel->sentStanzas.size()));
}
void testReceiveLegacyCapsDoesNotRequestDisco() {
boost::shared_ptr<CapsManager> testling = createManager();
sendPresenceWithCaps(user1, legacyCapsInfo);
CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(stanzaChannel->sentStanzas.size()));
}
void testReceiveSameHashAfterSuccesfulDiscoDoesNotRequestDisco() {
diff --git a/Swiften/Disco/UnitTest/EntityCapsManagerTest.cpp b/Swiften/Disco/UnitTest/EntityCapsManagerTest.cpp
index 7b61cb5..0fd966d 100644
--- a/Swiften/Disco/UnitTest/EntityCapsManagerTest.cpp
+++ b/Swiften/Disco/UnitTest/EntityCapsManagerTest.cpp
@@ -2,80 +2,80 @@
* Copyright (c) 2010 Remko Tronçon
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <vector>
#include <boost/bind.hpp>
#include <Swiften/Disco/EntityCapsManager.h>
#include <Swiften/Disco/CapsProvider.h>
#include <Swiften/Elements/CapsInfo.h>
#include <Swiften/Client/DummyStanzaChannel.h>
#include <Swiften/Disco/CapsInfoGenerator.h>
using namespace Swift;
class EntityCapsManagerTest : public CppUnit::TestFixture {
CPPUNIT_TEST_SUITE(EntityCapsManagerTest);
CPPUNIT_TEST(testReceiveKnownHash);
CPPUNIT_TEST(testReceiveKnownHashTwiceDoesNotTriggerChange);
CPPUNIT_TEST(testReceiveUnknownHashDoesNotTriggerChange);
CPPUNIT_TEST(testReceiveUnknownHashAfterKnownHashTriggersChangeAndClearsCaps);
CPPUNIT_TEST(testReceiveUnavailablePresenceAfterKnownHashTriggersChangeAndClearsCaps);
CPPUNIT_TEST(testReconnectTriggersChangeAndClearsCaps);
CPPUNIT_TEST(testHashAvailable);
CPPUNIT_TEST_SUITE_END();
public:
void setUp() {
stanzaChannel = new DummyStanzaChannel();
capsProvider = new DummyCapsProvider();
user1 = JID("user1@bar.com/bla");
- discoInfo1 = boost::shared_ptr<DiscoInfo>(new DiscoInfo());
+ discoInfo1 = boost::make_shared<DiscoInfo>();
discoInfo1->addFeature("http://swift.im/feature1");
- capsInfo1 = boost::shared_ptr<CapsInfo>(new CapsInfo(CapsInfoGenerator("http://node1.im").generateCapsInfo(*discoInfo1.get())));
- capsInfo1alt = boost::shared_ptr<CapsInfo>(new CapsInfo(CapsInfoGenerator("http://node2.im").generateCapsInfo(*discoInfo1.get())));
+ capsInfo1 = boost::make_shared<CapsInfo>(CapsInfoGenerator("http://node1.im").generateCapsInfo(*discoInfo1.get()));
+ capsInfo1alt = boost::make_shared<CapsInfo>(CapsInfoGenerator("http://node2.im").generateCapsInfo(*discoInfo1.get()));
user2 = JID("user2@foo.com/baz");
- discoInfo2 = boost::shared_ptr<DiscoInfo>(new DiscoInfo());
+ discoInfo2 = boost::make_shared<DiscoInfo>();
discoInfo2->addFeature("http://swift.im/feature2");
- capsInfo2 = boost::shared_ptr<CapsInfo>(new CapsInfo(CapsInfoGenerator("http://node2.im").generateCapsInfo(*discoInfo2.get())));
+ capsInfo2 = boost::make_shared<CapsInfo>(CapsInfoGenerator("http://node2.im").generateCapsInfo(*discoInfo2.get()));
user3 = JID("user3@foo.com/baz");
- legacyCapsInfo = boost::shared_ptr<CapsInfo>(new CapsInfo("http://swift.im", "ver1", ""));
+ legacyCapsInfo = boost::make_shared<CapsInfo>("http://swift.im", "ver1", "");
}
void tearDown() {
delete capsProvider;
delete stanzaChannel;
}
void testReceiveKnownHash() {
boost::shared_ptr<EntityCapsManager> testling = createManager();
capsProvider->caps[capsInfo1->getVersion()] = discoInfo1;
sendPresenceWithCaps(user1, capsInfo1);
CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(changes.size()));
CPPUNIT_ASSERT_EQUAL(user1, changes[0]);
CPPUNIT_ASSERT_EQUAL(discoInfo1, testling->getCaps(user1));
}
void testReceiveKnownHashTwiceDoesNotTriggerChange() {
boost::shared_ptr<EntityCapsManager> testling = createManager();
capsProvider->caps[capsInfo1->getVersion()] = discoInfo1;
sendPresenceWithCaps(user1, capsInfo1);
changes.clear();
sendPresenceWithCaps(user1, capsInfo1);
CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(changes.size()));
}
void testReceiveUnknownHashDoesNotTriggerChange() {
boost::shared_ptr<EntityCapsManager> testling = createManager();
sendPresenceWithCaps(user1, capsInfo1);
CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(changes.size()));
}
diff --git a/Swiften/Elements/UnitTest/StanzaTest.cpp b/Swiften/Elements/UnitTest/StanzaTest.cpp
index 0319b52..4bb59b1 100644
--- a/Swiften/Elements/UnitTest/StanzaTest.cpp
+++ b/Swiften/Elements/UnitTest/StanzaTest.cpp
@@ -37,195 +37,195 @@ class StanzaTest : public CppUnit::TestFixture
CPPUNIT_TEST_SUITE_END();
public:
class MyPayload1 : public Payload {
public:
MyPayload1() {}
};
class MyPayload2 : public Payload {
public:
MyPayload2(const std::string& s = "") : text_(s) {}
std::string text_;
};
class MyPayload3 : public Payload {
public:
MyPayload3() {}
};
class DestroyingPayload : public Payload {
public:
DestroyingPayload(bool* alive) : alive_(alive) {
}
~DestroyingPayload() {
(*alive_) = false;
}
private:
bool* alive_;
};
void testConstructor_Copy() {
Message m;
- m.addPayload(boost::shared_ptr<MyPayload1>(new MyPayload1()));
- m.addPayload(boost::shared_ptr<MyPayload2>(new MyPayload2()));
+ m.addPayload(boost::make_shared<MyPayload1>());
+ m.addPayload(boost::make_shared<MyPayload2>());
Message copy(m);
CPPUNIT_ASSERT(copy.getPayload<MyPayload1>());
CPPUNIT_ASSERT(copy.getPayload<MyPayload2>());
}
void testDestructor() {
bool payloadAlive = true;
{
Message m;
- m.addPayload(boost::shared_ptr<DestroyingPayload>(new DestroyingPayload(&payloadAlive)));
+ m.addPayload(boost::make_shared<DestroyingPayload>(&payloadAlive));
}
CPPUNIT_ASSERT(!payloadAlive);
}
void testDestructor_Copy() {
bool payloadAlive = true;
Message* m1 = new Message();
- m1->addPayload(boost::shared_ptr<DestroyingPayload>(new DestroyingPayload(&payloadAlive)));
+ m1->addPayload(boost::make_shared<DestroyingPayload>(&payloadAlive));
Message* m2 = new Message(*m1);
delete m1;
CPPUNIT_ASSERT(payloadAlive);
delete m2;
CPPUNIT_ASSERT(!payloadAlive);
}
void testGetPayload() {
Message m;
- m.addPayload(boost::shared_ptr<MyPayload1>(new MyPayload1()));
- m.addPayload(boost::shared_ptr<MyPayload2>(new MyPayload2()));
- m.addPayload(boost::shared_ptr<MyPayload3>(new MyPayload3()));
+ m.addPayload(boost::make_shared<MyPayload1>());
+ m.addPayload(boost::make_shared<MyPayload2>());
+ m.addPayload(boost::make_shared<MyPayload3>());
boost::shared_ptr<MyPayload2> p(m.getPayload<MyPayload2>());
CPPUNIT_ASSERT(p);
}
void testGetPayload_NoSuchPayload() {
Message m;
- m.addPayload(boost::shared_ptr<MyPayload1>(new MyPayload1()));
- m.addPayload(boost::shared_ptr<MyPayload3>(new MyPayload3()));
+ m.addPayload(boost::make_shared<MyPayload1>());
+ m.addPayload(boost::make_shared<MyPayload3>());
boost::shared_ptr<MyPayload2> p(m.getPayload<MyPayload2>());
CPPUNIT_ASSERT(!p);
}
void testGetPayloads() {
Message m;
boost::shared_ptr<MyPayload2> payload1(new MyPayload2());
boost::shared_ptr<MyPayload2> payload2(new MyPayload2());
- m.addPayload(boost::shared_ptr<MyPayload1>(new MyPayload1()));
+ m.addPayload(boost::make_shared<MyPayload1>());
m.addPayload(payload1);
- m.addPayload(boost::shared_ptr<MyPayload3>(new MyPayload3()));
+ m.addPayload(boost::make_shared<MyPayload3>());
m.addPayload(payload2);
CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(2), m.getPayloads<MyPayload2>().size());
CPPUNIT_ASSERT_EQUAL(payload1, m.getPayloads<MyPayload2>()[0]);
CPPUNIT_ASSERT_EQUAL(payload2, m.getPayloads<MyPayload2>()[1]);
}
void testUpdatePayload_ExistingPayload() {
Message m;
- m.addPayload(boost::shared_ptr<MyPayload1>(new MyPayload1()));
- m.addPayload(boost::shared_ptr<MyPayload2>(new MyPayload2("foo")));
- m.addPayload(boost::shared_ptr<MyPayload3>(new MyPayload3()));
+ m.addPayload(boost::make_shared<MyPayload1>());
+ m.addPayload(boost::make_shared<MyPayload2>("foo"));
+ m.addPayload(boost::make_shared<MyPayload3>());
- m.updatePayload(boost::shared_ptr<MyPayload2>(new MyPayload2("bar")));
+ m.updatePayload(boost::make_shared<MyPayload2>("bar"));
CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(3), m.getPayloads().size());
boost::shared_ptr<MyPayload2> p(m.getPayload<MyPayload2>());
CPPUNIT_ASSERT_EQUAL(std::string("bar"), p->text_);
}
void testUpdatePayload_NewPayload() {
Message m;
- m.addPayload(boost::shared_ptr<MyPayload1>(new MyPayload1()));
- m.addPayload(boost::shared_ptr<MyPayload3>(new MyPayload3()));
+ m.addPayload(boost::make_shared<MyPayload1>());
+ m.addPayload(boost::make_shared<MyPayload3>());
- m.updatePayload(boost::shared_ptr<MyPayload2>(new MyPayload2("bar")));
+ m.updatePayload(boost::make_shared<MyPayload2>("bar"));
CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(3), m.getPayloads().size());
boost::shared_ptr<MyPayload2> p(m.getPayload<MyPayload2>());
CPPUNIT_ASSERT_EQUAL(std::string("bar"), p->text_);
}
void testGetPayloadOfSameType() {
Message m;
- m.addPayload(boost::shared_ptr<MyPayload1>(new MyPayload1()));
- m.addPayload(boost::shared_ptr<MyPayload2>(new MyPayload2("foo")));
- m.addPayload(boost::shared_ptr<MyPayload3>(new MyPayload3()));
+ m.addPayload(boost::make_shared<MyPayload1>());
+ m.addPayload(boost::make_shared<MyPayload2>("foo"));
+ m.addPayload(boost::make_shared<MyPayload3>());
- boost::shared_ptr<MyPayload2> payload(boost::dynamic_pointer_cast<MyPayload2>(m.getPayloadOfSameType(boost::shared_ptr<MyPayload2>(new MyPayload2("bar")))));
+ boost::shared_ptr<MyPayload2> payload(boost::dynamic_pointer_cast<MyPayload2>(m.getPayloadOfSameType(boost::make_shared<MyPayload2>("bar"))));
CPPUNIT_ASSERT(payload);
CPPUNIT_ASSERT_EQUAL(std::string("foo"), payload->text_);
}
void testGetPayloadOfSameType_NoSuchPayload() {
Message m;
- m.addPayload(boost::shared_ptr<MyPayload1>(new MyPayload1()));
- m.addPayload(boost::shared_ptr<MyPayload3>(new MyPayload3()));
+ m.addPayload(boost::make_shared<MyPayload1>());
+ m.addPayload(boost::make_shared<MyPayload3>());
- CPPUNIT_ASSERT(!m.getPayloadOfSameType(boost::shared_ptr<MyPayload2>(new MyPayload2("bar"))));
+ CPPUNIT_ASSERT(!m.getPayloadOfSameType(boost::make_shared<MyPayload2>("bar")));
}
void testGetTimestamp() {
Message m;
- m.addPayload(boost::shared_ptr<Delay>(new Delay(boost::posix_time::from_time_t(1))));
+ m.addPayload(boost::make_shared<Delay>(boost::posix_time::from_time_t(1)));
boost::optional<boost::posix_time::ptime> timestamp = m.getTimestamp();
CPPUNIT_ASSERT(timestamp);
CPPUNIT_ASSERT_EQUAL(std::string("1970-Jan-01 00:00:01"), boost::posix_time::to_simple_string(*timestamp));
}
void testGetTimestamp_TimestampWithFrom() {
Message m;
- m.addPayload(boost::shared_ptr<Delay>(new Delay(boost::posix_time::from_time_t(1), JID("foo@bar.com"))));
+ m.addPayload(boost::make_shared<Delay>(boost::posix_time::from_time_t(1), JID("foo@bar.com")));
boost::optional<boost::posix_time::ptime> timestamp = m.getTimestamp();
CPPUNIT_ASSERT(timestamp);
CPPUNIT_ASSERT_EQUAL(std::string("1970-Jan-01 00:00:01"), boost::posix_time::to_simple_string(*timestamp));
}
void testGetTimestamp_NoDelay() {
Message m;
CPPUNIT_ASSERT(!m.getTimestamp());
}
void testGetTimestampFrom() {
Message m;
- m.addPayload(boost::shared_ptr<Delay>(new Delay(boost::posix_time::from_time_t(0))));
- m.addPayload(boost::shared_ptr<Delay>(new Delay(boost::posix_time::from_time_t(1), JID("foo1@bar.com"))));
- m.addPayload(boost::shared_ptr<Delay>(new Delay(boost::posix_time::from_time_t(2), JID("foo2@bar.com"))));
- m.addPayload(boost::shared_ptr<Delay>(new Delay(boost::posix_time::from_time_t(3), JID("foo3@bar.com"))));
+ m.addPayload(boost::make_shared<Delay>(boost::posix_time::from_time_t(0)));
+ m.addPayload(boost::make_shared<Delay>(boost::posix_time::from_time_t(1), JID("foo1@bar.com")));
+ m.addPayload(boost::make_shared<Delay>(boost::posix_time::from_time_t(2), JID("foo2@bar.com")));
+ m.addPayload(boost::make_shared<Delay>(boost::posix_time::from_time_t(3), JID("foo3@bar.com")));
boost::optional<boost::posix_time::ptime> timestamp = m.getTimestampFrom(JID("foo2@bar.com"));
CPPUNIT_ASSERT(timestamp);
CPPUNIT_ASSERT_EQUAL(std::string("1970-Jan-01 00:00:02"), boost::posix_time::to_simple_string(*timestamp));
}
void testGetTimestampFrom_Fallsback() {
Message m;
- m.addPayload(boost::shared_ptr<Delay>(new Delay(boost::posix_time::from_time_t(1), JID("foo1@bar.com"))));
- m.addPayload(boost::shared_ptr<Delay>(new Delay(boost::posix_time::from_time_t(3), JID("foo3@bar.com"))));
+ m.addPayload(boost::make_shared<Delay>(boost::posix_time::from_time_t(1), JID("foo1@bar.com")));
+ m.addPayload(boost::make_shared<Delay>(boost::posix_time::from_time_t(3), JID("foo3@bar.com")));
boost::optional<boost::posix_time::ptime> timestamp = m.getTimestampFrom(JID("foo2@bar.com"));
CPPUNIT_ASSERT(timestamp);
CPPUNIT_ASSERT_EQUAL(std::string("1970-Jan-01 00:00:01"), boost::posix_time::to_simple_string(*timestamp));
}
};
CPPUNIT_TEST_SUITE_REGISTRATION(StanzaTest);
diff --git a/Swiften/Examples/SendFile/SendFile.cpp b/Swiften/Examples/SendFile/SendFile.cpp
index 9b2105b..df3cea4 100644
--- a/Swiften/Examples/SendFile/SendFile.cpp
+++ b/Swiften/Examples/SendFile/SendFile.cpp
@@ -47,71 +47,71 @@ class FileSender {
client = new Swift::Client(jid, password, &networkFactories);
client->onConnected.connect(boost::bind(&FileSender::handleConnected, this));
client->onDisconnected.connect(boost::bind(&FileSender::handleDisconnected, this, _1));
tracer = new ClientXMLTracer(client);
client->getEntityCapsProvider()->onCapsChanged.connect(boost::bind(&FileSender::handleCapsChanged, this, _1));
}
~FileSender() {
delete tracer;
client->onDisconnected.disconnect(boost::bind(&FileSender::handleDisconnected, this, _1));
client->onConnected.disconnect(boost::bind(&FileSender::handleConnected, this));
delete client;
}
void start() {
client->connect();
}
private:
void handleConnected() {
client->sendPresence(Presence::create());
client->getFileTransferManager()->startListeningOnPort(19999);
//ByteArray fileData;
//readByteArrayFromFile(fileData, file.string());
// gather file information
/*StreamInitiationFileInfo fileInfo;
fileInfo.setName(file.filename());
fileInfo.setSize(boost::filesystem::file_size(file));
fileInfo.setDescription("Some file!");
fileInfo.setDate(boost::posix_time::from_time_t(boost::filesystem::last_write_time(file)));*/
//fileInfo.setHash(Hexify::hexify(MD5::getHash(fileData)));
/*
- transfer = new OutgoingSIFileTransfer("myid", client->getJID(), recipient, file.filename(), boost::filesystem::file_size(file), "A file", boost::shared_ptr<FileReadBytestream>(new FileReadBytestream(file)), client->getIQRouter(), socksBytestreamServer);
+ transfer = new OutgoingSIFileTransfer("myid", client->getJID(), recipient, file.filename(), boost::filesystem::file_size(file), "A file", boost::make_shared<FileReadBytestream>(file)), client->getIQRouter(), socksBytestreamServer);
transfer->onFinished.connect(boost::bind(&FileSender::handleFileTransferFinished, this, _1));
transfer->start();
*/
}
void handleCapsChanged(JID jid) {
if (jid.toBare() == recipient) {
// create ReadBytestream from file
boost::shared_ptr<FileReadBytestream> fileStream = boost::make_shared<FileReadBytestream>(file);
outgoingFileTransfer = client->getFileTransferManager()->createOutgoingFileTransfer(recipient, file, "Some File!", fileStream);
if (outgoingFileTransfer) {
std::cout << "started FT" << std::endl;
outgoingFileTransfer->start();
// TODO: getting notified about FT status and end
} else {
std::cout << "[ ERROR ] " << recipient << " doesn't support any kind of file transfer!" << std::endl;
//client->disconnect();
}
}
}
void handleDisconnected(const boost::optional<ClientError>&) {
std::cerr << "Error!" << std::endl;
exit(-1);
}
void handleFileTransferFinished(const boost::optional<FileTransferError>& error) {
std::cout << "File transfer finished" << std::endl;
if (error) {
exit(-1);
}
else {
exit(0);
diff --git a/Swiften/FileTransfer/OutgoingSIFileTransfer.cpp b/Swiften/FileTransfer/OutgoingSIFileTransfer.cpp
index 8a8237a..fc0a551 100644
--- a/Swiften/FileTransfer/OutgoingSIFileTransfer.cpp
+++ b/Swiften/FileTransfer/OutgoingSIFileTransfer.cpp
@@ -1,78 +1,79 @@
/*
* Copyright (c) 2010 Remko Tronçon
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
#include <Swiften/FileTransfer/OutgoingSIFileTransfer.h>
#include <boost/bind.hpp>
+#include <boost/smart_ptr/make_shared.hpp>
#include <Swiften/FileTransfer/StreamInitiationRequest.h>
#include <Swiften/FileTransfer/BytestreamsRequest.h>
#include <Swiften/FileTransfer/SOCKS5BytestreamServer.h>
#include <Swiften/FileTransfer/IBBSendSession.h>
namespace Swift {
OutgoingSIFileTransfer::OutgoingSIFileTransfer(const std::string& id, const JID& from, const JID& to, const std::string& name, int size, const std::string& description, boost::shared_ptr<ReadBytestream> bytestream, IQRouter* iqRouter, SOCKS5BytestreamServer* socksServer) : id(id), from(from), to(to), name(name), size(size), description(description), bytestream(bytestream), iqRouter(iqRouter), socksServer(socksServer) {
}
void OutgoingSIFileTransfer::start() {
StreamInitiation::ref streamInitiation(new StreamInitiation());
streamInitiation->setID(id);
streamInitiation->setFileInfo(StreamInitiationFileInfo(name, description, size));
//streamInitiation->addProvidedMethod("http://jabber.org/protocol/bytestreams");
streamInitiation->addProvidedMethod("http://jabber.org/protocol/ibb");
StreamInitiationRequest::ref request = StreamInitiationRequest::create(to, streamInitiation, iqRouter);
request->onResponse.connect(boost::bind(&OutgoingSIFileTransfer::handleStreamInitiationRequestResponse, this, _1, _2));
request->send();
}
void OutgoingSIFileTransfer::stop() {
}
void OutgoingSIFileTransfer::handleStreamInitiationRequestResponse(StreamInitiation::ref response, ErrorPayload::ref error) {
if (error) {
finish(FileTransferError());
}
else {
if (response->getRequestedMethod() == "http://jabber.org/protocol/bytestreams") {
socksServer->addReadBytestream(id, from, to, bytestream);
Bytestreams::ref bytestreams(new Bytestreams());
bytestreams->setStreamID(id);
HostAddressPort addressPort = socksServer->getAddressPort();
bytestreams->addStreamHost(Bytestreams::StreamHost(addressPort.getAddress().toString(), from, addressPort.getPort()));
BytestreamsRequest::ref request = BytestreamsRequest::create(to, bytestreams, iqRouter);
request->onResponse.connect(boost::bind(&OutgoingSIFileTransfer::handleBytestreamsRequestResponse, this, _1, _2));
request->send();
}
else if (response->getRequestedMethod() == "http://jabber.org/protocol/ibb") {
- ibbSession = boost::shared_ptr<IBBSendSession>(new IBBSendSession(id, from, to, bytestream, iqRouter));
+ ibbSession = boost::make_shared<IBBSendSession>(id, from, to, bytestream, iqRouter);
ibbSession->onFinished.connect(boost::bind(&OutgoingSIFileTransfer::handleIBBSessionFinished, this, _1));
ibbSession->start();
}
}
}
void OutgoingSIFileTransfer::handleBytestreamsRequestResponse(Bytestreams::ref, ErrorPayload::ref error) {
if (error) {
finish(FileTransferError());
}
//socksServer->onTransferFinished.connect();
}
void OutgoingSIFileTransfer::finish(boost::optional<FileTransferError> error) {
if (ibbSession) {
ibbSession->onFinished.disconnect(boost::bind(&OutgoingSIFileTransfer::handleIBBSessionFinished, this, _1));
ibbSession.reset();
}
socksServer->removeReadBytestream(id, from, to);
onFinished(error);
}
void OutgoingSIFileTransfer::handleIBBSessionFinished(boost::optional<FileTransferError> error) {
finish(error);
}
}
diff --git a/Swiften/FileTransfer/UnitTest/IBBSendSessionTest.cpp b/Swiften/FileTransfer/UnitTest/IBBSendSessionTest.cpp
index d12f99e..13b73bb 100644
--- a/Swiften/FileTransfer/UnitTest/IBBSendSessionTest.cpp
+++ b/Swiften/FileTransfer/UnitTest/IBBSendSessionTest.cpp
@@ -5,71 +5,71 @@
*/
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <vector>
#include <boost/bind.hpp>
#include <Swiften/Base/ByteArray.h>
#include <Swiften/FileTransfer/IBBSendSession.h>
#include <Swiften/FileTransfer/ByteArrayReadBytestream.h>
#include <Swiften/Queries/IQRouter.h>
#include <Swiften/Client/DummyStanzaChannel.h>
using namespace Swift;
class IBBSendSessionTest : public CppUnit::TestFixture {
CPPUNIT_TEST_SUITE(IBBSendSessionTest);
CPPUNIT_TEST(testStart);
CPPUNIT_TEST(testStart_ResponseStartsSending);
CPPUNIT_TEST(testResponseContinuesSending);
CPPUNIT_TEST(testRespondToAllFinishes);
CPPUNIT_TEST(testErrorResponseFinishesWithError);
CPPUNIT_TEST(testStopDuringSessionCloses);
CPPUNIT_TEST(testStopAfterFinishedDoesNotClose);
CPPUNIT_TEST(testDataStreamPauseStopsSendingData);
CPPUNIT_TEST(testDataStreamResumeAfterPauseSendsData);
CPPUNIT_TEST(testDataStreamResumeBeforePauseDoesNotSendData);
CPPUNIT_TEST(testDataStreamResumeAfterResumeDoesNotSendData);
CPPUNIT_TEST_SUITE_END();
public:
void setUp() {
stanzaChannel = new DummyStanzaChannel();
iqRouter = new IQRouter(stanzaChannel);
- bytestream = boost::shared_ptr<ByteArrayReadBytestream>(new ByteArrayReadBytestream(createByteArray("abcdefg")));
+ bytestream = boost::make_shared<ByteArrayReadBytestream>(createByteArray("abcdefg"));
finished = false;
}
void tearDown() {
delete iqRouter;
delete stanzaChannel;
}
void testStart() {
boost::shared_ptr<IBBSendSession> testling = createSession("foo@bar.com/baz");
testling->setBlockSize(1234);
testling->start();
CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(stanzaChannel->sentStanzas.size()));
CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<IBB>(0, JID("foo@bar.com/baz"), IQ::Set));
IBB::ref ibb = stanzaChannel->sentStanzas[0]->getPayload<IBB>();
CPPUNIT_ASSERT_EQUAL(IBB::Open, ibb->getAction());
CPPUNIT_ASSERT_EQUAL(1234, ibb->getBlockSize());
CPPUNIT_ASSERT_EQUAL(std::string("myid"), ibb->getStreamID());
}
void testStart_ResponseStartsSending() {
boost::shared_ptr<IBBSendSession> testling = createSession("foo@bar.com/baz");
testling->setBlockSize(3);
testling->start();
stanzaChannel->onIQReceived(createIBBResult());
CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(stanzaChannel->sentStanzas.size()));
CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<IBB>(1, JID("foo@bar.com/baz"), IQ::Set));
IBB::ref ibb = stanzaChannel->sentStanzas[1]->getPayload<IBB>();
CPPUNIT_ASSERT_EQUAL(IBB::Data, ibb->getAction());
CPPUNIT_ASSERT(createByteArray("abc") == ibb->getData());
CPPUNIT_ASSERT_EQUAL(0, ibb->getSequenceNumber());
diff --git a/Swiften/FileTransfer/UnitTest/SOCKS5BytestreamClientSessionTest.cpp b/Swiften/FileTransfer/UnitTest/SOCKS5BytestreamClientSessionTest.cpp
index 527e0ca..bb0d9b6 100644
--- a/Swiften/FileTransfer/UnitTest/SOCKS5BytestreamClientSessionTest.cpp
+++ b/Swiften/FileTransfer/UnitTest/SOCKS5BytestreamClientSessionTest.cpp
@@ -25,71 +25,71 @@
#include <Swiften/FileTransfer/ByteArrayReadBytestream.h>
#include <Swiften/FileTransfer/ByteArrayWriteBytestream.h>
#include <Swiften/FileTransfer/SOCKS5BytestreamClientSession.h>
#include <Swiften/FileTransfer/SOCKS5BytestreamRegistry.h>
#include <Swiften/JID/JID.h>
#include <Swiften/Network/DummyConnection.h>
#include <Swiften/Network/DummyTimerFactory.h>
#include <Swiften/StringCodecs/Hexify.h>
using namespace Swift;
boost::mt19937 randomGen;
class SOCKS5BytestreamClientSessionTest : public CppUnit::TestFixture {
CPPUNIT_TEST_SUITE(SOCKS5BytestreamClientSessionTest);
CPPUNIT_TEST(testForSessionReady);
CPPUNIT_TEST(testErrorHandlingHello);
CPPUNIT_TEST(testErrorHandlingRequest);
CPPUNIT_TEST(testWriteBytestream);
CPPUNIT_TEST(testReadBytestream);
CPPUNIT_TEST_SUITE_END();
const HostAddressPort destinationAddressPort;
const std::string destination;
public:
SOCKS5BytestreamClientSessionTest() : destinationAddressPort(HostAddressPort(HostAddress("127.0.0.1"), 8888)),
destination(SOCKS5BytestreamRegistry::getHostname("foo", JID("requester@example.com/test"), JID("target@example.com/test"))), eventLoop(NULL), timerFactory(NULL) { }
void setUp() {
randomGen.seed(time(NULL));
eventLoop = new DummyEventLoop();
timerFactory = new DummyTimerFactory();
connection = boost::make_shared<MockeryConnection>(failingPorts, true, eventLoop);
//connection->onDataSent.connect(boost::bind(&SOCKS5BytestreamServerSessionTest::handleDataWritten, this, _1));
- //stream1 = boost::shared_ptr<ByteArrayReadBytestream>(new ByteArrayReadBytestream(createByteArray("abcdefg")));
+ //stream1 = boost::make_shared<ByteArrayReadBytestream>(createByteArray("abcdefg")));
// connection->onDataRead.connect(boost::bind(&SOCKS5BytestreamClientSessionTest::handleDataRead, this, _1));
}
void tearDown() {
//connection.reset();
delete timerFactory;
delete eventLoop;
}
void testForSessionReady() {
TestHelper helper;
connection->onDataSent.connect(boost::bind(&TestHelper::handleConnectionDataWritten, &helper, _1));
SOCKS5BytestreamClientSession::ref clientSession = boost::make_shared<SOCKS5BytestreamClientSession>(connection, destinationAddressPort, destination, timerFactory);
clientSession->onSessionReady.connect(boost::bind(&TestHelper::handleSessionReady, &helper, _1));
clientSession->start();
eventLoop->processEvents();
CPPUNIT_ASSERT(createByteArray("\x05\x01\x00", 3) == helper.unprocessedInput);
helper.unprocessedInput.clear();
serverRespondHelloOK();
eventLoop->processEvents();
CPPUNIT_ASSERT_EQUAL(createByteArray("\x05\x01\x00\x03", 4), createByteArray(&helper.unprocessedInput[0], 4));
CPPUNIT_ASSERT_EQUAL(createByteArray(destination.size()), createByteArray(helper.unprocessedInput[4]));
CPPUNIT_ASSERT_EQUAL(createByteArray(destination), createByteArray(&helper.unprocessedInput[5], destination.size()));
CPPUNIT_ASSERT_EQUAL(createByteArray("\x00", 1), createByteArray(&helper.unprocessedInput[5 + destination.size()], 1));
helper.unprocessedInput.clear();
serverRespondRequestOK();
eventLoop->processEvents();
CPPUNIT_ASSERT_EQUAL(true, helper.sessionReadyCalled);
CPPUNIT_ASSERT_EQUAL(false, helper.sessionReadyError);
}
diff --git a/Swiften/FileTransfer/UnitTest/SOCKS5BytestreamServerSessionTest.cpp b/Swiften/FileTransfer/UnitTest/SOCKS5BytestreamServerSessionTest.cpp
index 4fe72c0..e6df862 100644
--- a/Swiften/FileTransfer/UnitTest/SOCKS5BytestreamServerSessionTest.cpp
+++ b/Swiften/FileTransfer/UnitTest/SOCKS5BytestreamServerSessionTest.cpp
@@ -3,73 +3,73 @@
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
#include <Swiften/Base/ByteArray.h>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <boost/bind.hpp>
#include <Swiften/Base/Concat.h>
#include <Swiften/FileTransfer/SOCKS5BytestreamServerSession.h>
#include <Swiften/FileTransfer/ByteArrayReadBytestream.h>
#include <Swiften/FileTransfer/SOCKS5BytestreamRegistry.h>
#include <Swiften/Network/DummyConnection.h>
#include <Swiften/EventLoop/DummyEventLoop.h>
#include <Swiften/Base/StartStopper.h>
using namespace Swift;
class SOCKS5BytestreamServerSessionTest : public CppUnit::TestFixture {
CPPUNIT_TEST_SUITE(SOCKS5BytestreamServerSessionTest);
CPPUNIT_TEST(testAuthenticate);
CPPUNIT_TEST(testAuthenticate_Chunked);
CPPUNIT_TEST(testRequest);
CPPUNIT_TEST(testRequest_UnknownBytestream);
CPPUNIT_TEST(testReceiveData);
CPPUNIT_TEST(testReceiveData_Chunked);
CPPUNIT_TEST_SUITE_END();
public:
void setUp() {
receivedDataChunks = 0;
eventLoop = new DummyEventLoop();
bytestreams = new SOCKS5BytestreamRegistry();
- connection = boost::shared_ptr<DummyConnection>(new DummyConnection(eventLoop));
+ connection = boost::make_shared<DummyConnection>(eventLoop);
connection->onDataSent.connect(boost::bind(&SOCKS5BytestreamServerSessionTest::handleDataWritten, this, _1));
- stream1 = boost::shared_ptr<ByteArrayReadBytestream>(new ByteArrayReadBytestream(createByteArray("abcdefg")));
+ stream1 = boost::make_shared<ByteArrayReadBytestream>(createByteArray("abcdefg"));
}
void tearDown() {
connection.reset();
delete bytestreams;
delete eventLoop;
}
void testAuthenticate() {
boost::shared_ptr<SOCKS5BytestreamServerSession> testling(createSession());
StartStopper<SOCKS5BytestreamServerSession> stopper(testling.get());
receive(createSafeByteArray("\x05\x02\x01\x02"));
CPPUNIT_ASSERT(createByteArray("\x05\x00", 2) == receivedData);
}
void testAuthenticate_Chunked() {
boost::shared_ptr<SOCKS5BytestreamServerSession> testling(createSession());
StartStopper<SOCKS5BytestreamServerSession> stopper(testling.get());
receive(createSafeByteArray("\x05\x02\x01"));
CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(receivedData.size()));
receive(createSafeByteArray("\x01"));
CPPUNIT_ASSERT(createByteArray("\x05\x00", 2) == receivedData);
}
void testRequest() {
boost::shared_ptr<SOCKS5BytestreamServerSession> testling(createSession());
StartStopper<SOCKS5BytestreamServerSession> stopper(testling.get());
bytestreams->addReadBytestream("abcdef", stream1);
authenticate();
ByteArray hostname(createByteArray("abcdef"));
diff --git a/Swiften/LinkLocal/IncomingLinkLocalSession.cpp b/Swiften/LinkLocal/IncomingLinkLocalSession.cpp
index b89de81..610b28b 100644
--- a/Swiften/LinkLocal/IncomingLinkLocalSession.cpp
+++ b/Swiften/LinkLocal/IncomingLinkLocalSession.cpp
@@ -1,69 +1,70 @@
/*
* Copyright (c) 2010 Remko Tronçon
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
#include <Swiften/LinkLocal/IncomingLinkLocalSession.h>
#include <boost/bind.hpp>
+#include <boost/smart_ptr/make_shared.hpp>
#include <Swiften/Elements/ProtocolHeader.h>
#include <Swiften/Network/Connection.h>
#include <Swiften/StreamStack/StreamStack.h>
#include <Swiften/StreamStack/ConnectionLayer.h>
#include <Swiften/StreamStack/XMPPLayer.h>
#include <Swiften/Elements/StreamFeatures.h>
#include <Swiften/Elements/IQ.h>
namespace Swift {
IncomingLinkLocalSession::IncomingLinkLocalSession(
const JID& localJID,
boost::shared_ptr<Connection> connection,
PayloadParserFactoryCollection* payloadParserFactories,
PayloadSerializerCollection* payloadSerializers,
XMLParserFactory* xmlParserFactory) :
Session(connection, payloadParserFactories, payloadSerializers, xmlParserFactory),
initialized(false) {
setLocalJID(localJID);
}
void IncomingLinkLocalSession::handleStreamStart(const ProtocolHeader& incomingHeader) {
setRemoteJID(JID(incomingHeader.getFrom()));
if (!getRemoteJID().isValid()) {
finishSession();
return;
}
ProtocolHeader header;
header.setFrom(getLocalJID());
getXMPPLayer()->writeHeader(header);
if (incomingHeader.getVersion() == "1.0") {
- getXMPPLayer()->writeElement(boost::shared_ptr<StreamFeatures>(new StreamFeatures()));
+ getXMPPLayer()->writeElement(boost::make_shared<StreamFeatures>());
}
else {
setInitialized();
}
}
void IncomingLinkLocalSession::handleElement(boost::shared_ptr<Element> element) {
boost::shared_ptr<Stanza> stanza = boost::dynamic_pointer_cast<Stanza>(element);
// If we get our first stanza before streamfeatures, our session is implicitly
// initialized
if (stanza && !isInitialized()) {
setInitialized();
}
onElementReceived(element);
}
void IncomingLinkLocalSession::setInitialized() {
initialized = true;
onSessionStarted();
}
}
diff --git a/Swiften/LinkLocal/UnitTest/LinkLocalConnectorTest.cpp b/Swiften/LinkLocal/UnitTest/LinkLocalConnectorTest.cpp
index 474c772..dd5e884 100644
--- a/Swiften/LinkLocal/UnitTest/LinkLocalConnectorTest.cpp
+++ b/Swiften/LinkLocal/UnitTest/LinkLocalConnectorTest.cpp
@@ -1,71 +1,70 @@
/*
* Copyright (c) 2010 Remko Tronçon
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <boost/bind.hpp>
#include <Swiften/LinkLocal/LinkLocalConnector.h>
#include <Swiften/LinkLocal/LinkLocalService.h>
#include <Swiften/LinkLocal/DNSSD/DNSSDServiceID.h>
#include <Swiften/LinkLocal/DNSSD/DNSSDResolveHostnameQuery.h>
#include <Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuerier.h>
#include <Swiften/EventLoop/DummyEventLoop.h>
#include <Swiften/Network/FakeConnection.h>
using namespace Swift;
class LinkLocalConnectorTest : public CppUnit::TestFixture {
CPPUNIT_TEST_SUITE(LinkLocalConnectorTest);
CPPUNIT_TEST(testConnect);
CPPUNIT_TEST(testConnect_UnableToResolve);
CPPUNIT_TEST(testConnect_UnableToConnect);
CPPUNIT_TEST(testCancel_DuringResolve);
CPPUNIT_TEST(testCancel_DuringConnect);
CPPUNIT_TEST_SUITE_END();
public:
void setUp() {
eventLoop = new DummyEventLoop();
- querier = boost::shared_ptr<FakeDNSSDQuerier>(
- new FakeDNSSDQuerier("rabbithole.local", eventLoop));
- connection = boost::shared_ptr<FakeConnection>(new FakeConnection(eventLoop));
+ querier = boost::make_shared<FakeDNSSDQuerier>("rabbithole.local", eventLoop);
+ connection = boost::make_shared<FakeConnection>(eventLoop);
connectFinished = false;
}
void tearDown() {
querier->clearAllQueriesEverRun();
delete eventLoop;
}
void testConnect() {
boost::shared_ptr<LinkLocalConnector>
testling(createConnector("rabbithole.local", 1234));
querier->setAddress("rabbithole.local", HostAddress("192.168.1.1"));
testling->connect();
eventLoop->processEvents();
CPPUNIT_ASSERT(connectFinished);
CPPUNIT_ASSERT(!connectError);
CPPUNIT_ASSERT(connection->connectedTo);
CPPUNIT_ASSERT_EQUAL(std::string(connection->connectedTo->getAddress().toString()), std::string("192.168.1.1"));
CPPUNIT_ASSERT_EQUAL(connection->connectedTo->getPort(), 1234);
}
void testConnect_UnableToResolve() {
boost::shared_ptr<LinkLocalConnector>
testling(createConnector("rabbithole.local", 1234));
querier->setAddress("rabbithole.local", boost::optional<HostAddress>());
testling->connect();
eventLoop->processEvents();
CPPUNIT_ASSERT(connectFinished);
CPPUNIT_ASSERT(connectError);
CPPUNIT_ASSERT(!connection->connectedTo);
}
diff --git a/Swiften/LinkLocal/UnitTest/LinkLocalServiceBrowserTest.cpp b/Swiften/LinkLocal/UnitTest/LinkLocalServiceBrowserTest.cpp
index c0fd248..93deea5 100644
--- a/Swiften/LinkLocal/UnitTest/LinkLocalServiceBrowserTest.cpp
+++ b/Swiften/LinkLocal/UnitTest/LinkLocalServiceBrowserTest.cpp
@@ -1,80 +1,81 @@
/*
* Copyright (c) 2010 Remko Tronçon
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <boost/bind.hpp>
+#include <boost/smart_ptr/make_shared.hpp>
#include <map>
#include <Swiften/LinkLocal/LinkLocalServiceBrowser.h>
#include <Swiften/LinkLocal/LinkLocalService.h>
#include <Swiften/LinkLocal/DNSSD/DNSSDServiceID.h>
#include <Swiften/LinkLocal/DNSSD/DNSSDResolveServiceQuery.h>
#include <Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuerier.h>
#include <Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDResolveServiceQuery.h>
#include <Swiften/EventLoop/DummyEventLoop.h>
using namespace Swift;
class LinkLocalServiceBrowserTest : public CppUnit::TestFixture {
CPPUNIT_TEST_SUITE(LinkLocalServiceBrowserTest);
CPPUNIT_TEST(testConstructor);
CPPUNIT_TEST(testStart);
CPPUNIT_TEST(testServiceAdded);
CPPUNIT_TEST(testServiceAdded_NoServiceInfo);
CPPUNIT_TEST(testServiceAdded_RegisteredService);
CPPUNIT_TEST(testServiceAdded_UnregisteredService);
CPPUNIT_TEST(testServiceAdded_Twice);
CPPUNIT_TEST(testServiceChanged);
CPPUNIT_TEST(testServiceRemoved);
CPPUNIT_TEST(testServiceRemoved_UnregisteredService);
CPPUNIT_TEST(testError_BrowseErrorAfterStart);
CPPUNIT_TEST(testError_BrowseErrorAfterResolve);
CPPUNIT_TEST(testRegisterService);
CPPUNIT_TEST(testRegisterService_Error);
CPPUNIT_TEST(testRegisterService_Reregister);
CPPUNIT_TEST(testUpdateService);
CPPUNIT_TEST_SUITE_END();
public:
void setUp() {
eventLoop = new DummyEventLoop();
- querier = boost::shared_ptr<FakeDNSSDQuerier>(new FakeDNSSDQuerier("wonderland.lit", eventLoop));
+ querier = boost::make_shared<FakeDNSSDQuerier>("wonderland.lit", eventLoop);
aliceServiceID = new DNSSDServiceID("alice", "wonderland.lit");
aliceServiceInfo = new DNSSDResolveServiceQuery::Result("_presence._tcp.wonderland.lit", "xmpp.wonderland.lit", 1234, LinkLocalServiceInfo().toTXTRecord());
testServiceID = new DNSSDServiceID("foo", "bar.local");
testServiceInfo = new DNSSDResolveServiceQuery::Result("_presence._tcp.bar.local", "xmpp.bar.local", 1234, LinkLocalServiceInfo().toTXTRecord());
testServiceInfo2 = new DNSSDResolveServiceQuery::Result("_presence.tcp.bar.local", "xmpp.foo.local", 2345, LinkLocalServiceInfo().toTXTRecord());
errorStopReceived = false;
normalStopReceived = false;
}
void tearDown() {
querier->clearAllQueriesEverRun();
addedServices.clear();
removedServices.clear();
changedServices.clear();
delete aliceServiceID;
delete aliceServiceInfo;
delete testServiceInfo2;
delete testServiceInfo;
delete testServiceID;
delete eventLoop;
}
void testConstructor() {
boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling();
CPPUNIT_ASSERT(!testling->isRunning());
CPPUNIT_ASSERT(!testling->hasError());
}
void testStart() {
boost::shared_ptr<LinkLocalServiceBrowser> testling = createTestling();
testling->start();
CPPUNIT_ASSERT(testling->isRunning());
diff --git a/Swiften/MUC/MUCBookmarkManager.cpp b/Swiften/MUC/MUCBookmarkManager.cpp
index 643a8c4..8a63745 100644
--- a/Swiften/MUC/MUCBookmarkManager.cpp
+++ b/Swiften/MUC/MUCBookmarkManager.cpp
@@ -1,44 +1,45 @@
/*
* Copyright (c) 2010 Remko Tronçon
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
#include "MUCBookmarkManager.h"
#include <boost/bind.hpp>
+#include <boost/smart_ptr/make_shared.hpp>
#include <iostream>
#include <Swiften/Base/foreach.h>
#include <Swiften/Queries/IQRouter.h>
#include <Swiften/Queries/Requests/GetPrivateStorageRequest.h>
#include <Swiften/Queries/Requests/SetPrivateStorageRequest.h>
namespace Swift {
MUCBookmarkManager::MUCBookmarkManager(IQRouter* iqRouter) {
iqRouter_ = iqRouter;
ready_ = false;
GetPrivateStorageRequest<Storage>::ref request = GetPrivateStorageRequest<Storage>::create(iqRouter_);
request->onResponse.connect(boost::bind(&MUCBookmarkManager::handleBookmarksReceived, this, _1, _2));
request->send();
}
void MUCBookmarkManager::handleBookmarksReceived(boost::shared_ptr<Storage> payload, ErrorPayload::ref error) {
if (error) {
return;
}
ready_ = true;
onBookmarksReady();
storage = payload;
std::vector<MUCBookmark> receivedBookmarks;
foreach (Storage::Room room, payload->getRooms()) {
receivedBookmarks.push_back(MUCBookmark(room));
}
std::vector<MUCBookmark> newBookmarks;
foreach (const MUCBookmark& oldBookmark, bookmarks_) {
@@ -66,55 +67,55 @@ void MUCBookmarkManager::replaceBookmark(const MUCBookmark& oldBookmark, const M
if (!ready_) return;
for (size_t i = 0; i < bookmarks_.size(); i++) {
if (bookmarks_[i] == oldBookmark) {
bookmarks_[i] = newBookmark;
flush();
onBookmarkRemoved(oldBookmark);
onBookmarkAdded(newBookmark);
return;
}
}
}
void MUCBookmarkManager::addBookmark(const MUCBookmark& bookmark) {
if (!ready_) return;
bookmarks_.push_back(bookmark);
onBookmarkAdded(bookmark);
flush();
}
void MUCBookmarkManager::removeBookmark(const MUCBookmark& bookmark) {
if (!ready_) return;
std::vector<MUCBookmark>::iterator it;
for (it = bookmarks_.begin(); it != bookmarks_.end(); ++it) {
if ((*it) == bookmark) {
bookmarks_.erase(it);
onBookmarkRemoved(bookmark);
break;
}
}
flush();
}
void MUCBookmarkManager::flush() {
if (!storage) {
- storage = boost::shared_ptr<Storage>(new Storage());
+ storage = boost::make_shared<Storage>();
}
// Update the storage element
storage->clearRooms();
foreach(const MUCBookmark& bookmark, bookmarks_) {
storage->addRoom(bookmark.toStorage());
}
// Send an iq to save the storage element
SetPrivateStorageRequest<Storage>::ref request = SetPrivateStorageRequest<Storage>::create(storage, iqRouter_);
// FIXME: We should care about the result
//request->onResponse.connect(boost::bind(&MUCBookmarkManager::handleBookmarksSet, this, _1, _2));
request->send();
}
const std::vector<MUCBookmark>& MUCBookmarkManager::getBookmarks() const {
return bookmarks_;
}
}
diff --git a/Swiften/Parser/PayloadParsers/SecurityLabelsCatalogParser.cpp b/Swiften/Parser/PayloadParsers/SecurityLabelsCatalogParser.cpp
index e90573f..922a00e 100644
--- a/Swiften/Parser/PayloadParsers/SecurityLabelsCatalogParser.cpp
+++ b/Swiften/Parser/PayloadParsers/SecurityLabelsCatalogParser.cpp
@@ -1,64 +1,66 @@
/*
* Copyright (c) 2010 Remko Tronçon
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
+#include <boost/smart_ptr/make_shared.hpp>
+
#include <Swiften/Parser/PayloadParsers/SecurityLabelsCatalogParser.h>
#include <Swiften/Parser/PayloadParsers/SecurityLabelParserFactory.h>
#include <Swiften/Parser/PayloadParsers/SecurityLabelParser.h>
namespace Swift {
SecurityLabelsCatalogParser::SecurityLabelsCatalogParser() : level_(TopLevel), labelParser_(0) {
labelParserFactory_ = new SecurityLabelParserFactory();
}
SecurityLabelsCatalogParser::~SecurityLabelsCatalogParser() {
delete labelParserFactory_;
}
void SecurityLabelsCatalogParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
++level_;
if (level_ == PayloadLevel) {
getPayloadInternal()->setTo(JID(attributes.getAttribute("to")));
getPayloadInternal()->setName(attributes.getAttribute("name"));
getPayloadInternal()->setDescription(attributes.getAttribute("desc"));
}
else if (level_ == ItemLevel && element == "item" && ns == "urn:xmpp:sec-label:catalog:2") {
- currentItem_ = boost::shared_ptr<SecurityLabelsCatalog::Item>(new SecurityLabelsCatalog::Item());
+ currentItem_ = boost::make_shared<SecurityLabelsCatalog::Item>();
currentItem_->setSelector(attributes.getAttribute("selector"));
currentItem_->setIsDefault(attributes.getBoolAttribute("default", false));
}
else if (level_ == LabelLevel) {
assert(!labelParser_);
if (labelParserFactory_->canParse(element, ns, attributes)) {
labelParser_ = dynamic_cast<SecurityLabelParser*>(labelParserFactory_->createPayloadParser());
assert(labelParser_);
}
}
if (labelParser_) {
labelParser_->handleStartElement(element, ns, attributes);
}
}
void SecurityLabelsCatalogParser::handleEndElement(const std::string& element, const std::string& ns) {
if (labelParser_) {
labelParser_->handleEndElement(element, ns);
}
if (level_ == LabelLevel && labelParser_ && currentItem_) {
boost::shared_ptr<SecurityLabel> currentLabel = labelParser_->getLabelPayload();
assert(currentLabel);
currentItem_->setLabel(currentLabel);
delete labelParser_;
labelParser_ = 0;
}
else if (level_ == ItemLevel && element == "item" && ns == "urn:xmpp:sec-label:catalog:2") {
if (currentItem_) {
getPayloadInternal()->addItem(SecurityLabelsCatalog::Item(*currentItem_));
currentItem_.reset();
}
}
--level_;
}
diff --git a/Swiften/Parser/UnitTest/StanzaParserTest.cpp b/Swiften/Parser/UnitTest/StanzaParserTest.cpp
index b2ddb39..88e6dec 100644
--- a/Swiften/Parser/UnitTest/StanzaParserTest.cpp
+++ b/Swiften/Parser/UnitTest/StanzaParserTest.cpp
@@ -161,52 +161,52 @@ class StanzaParserTest : public CppUnit::TestFixture {
};
class MyPayload2Parser : public GenericPayloadParser<MyPayload2>
{
public:
MyPayload2Parser() {}
virtual void handleStartElement(const std::string&, const std::string&, const AttributeMap&) {}
virtual void handleEndElement(const std::string&, const std::string&) {}
virtual void handleCharacterData(const std::string&) {}
};
class MyPayload2ParserFactory : public PayloadParserFactory
{
public:
MyPayload2ParserFactory() {}
PayloadParser* createPayloadParser() { return new MyPayload2Parser(); }
bool canParse(const std::string& element, const std::string&, const AttributeMap&) const {
return element == "mypayload2";
}
};
class MyStanza : public Stanza
{
public:
MyStanza() {}
};
class MyStanzaParser : public StanzaParser
{
public:
MyStanzaParser(PayloadParserFactoryCollection* collection) : StanzaParser(collection)
{
- stanza_ = boost::shared_ptr<MyStanza>(new MyStanza());
+ stanza_ = boost::make_shared<MyStanza>();
}
virtual boost::shared_ptr<Element> getElement() const {
return stanza_;
}
private:
boost::shared_ptr<MyStanza> stanza_;
};
MyPayload1ParserFactory factory1_;
MyPayload2ParserFactory factory2_;
PayloadParserFactoryCollection* factoryCollection_;
};
CPPUNIT_TEST_SUITE_REGISTRATION(StanzaParserTest);
diff --git a/Swiften/Presence/UnitTest/DirectedPresenceSenderTest.cpp b/Swiften/Presence/UnitTest/DirectedPresenceSenderTest.cpp
index 5b385c2..0da78e6 100644
--- a/Swiften/Presence/UnitTest/DirectedPresenceSenderTest.cpp
+++ b/Swiften/Presence/UnitTest/DirectedPresenceSenderTest.cpp
@@ -1,68 +1,68 @@
/*
* Copyright (c) 2010 Remko Tronçon
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <Swiften/Client/DummyStanzaChannel.h>
#include <Swiften/Presence/DirectedPresenceSender.h>
#include <Swiften/Presence/StanzaChannelPresenceSender.h>
using namespace Swift;
class DirectedPresenceSenderTest : public CppUnit::TestFixture {
CPPUNIT_TEST_SUITE(DirectedPresenceSenderTest);
CPPUNIT_TEST(testSendPresence);
CPPUNIT_TEST(testSendPresence_UndirectedPresenceWithDirectedPresenceReceivers);
CPPUNIT_TEST(testSendPresence_DirectedPresenceWithDirectedPresenceReceivers);
CPPUNIT_TEST(testAddDirectedPresenceReceiver);
CPPUNIT_TEST(testAddDirectedPresenceReceiver_WithoutSendingPresence);
CPPUNIT_TEST(testAddDirectedPresenceReceiver_AfterSendingDirectedPresence);
CPPUNIT_TEST(testRemoveDirectedPresenceReceiver);
CPPUNIT_TEST(testRemoveDirectedPresenceReceiver_WithoutSendingPresence);
CPPUNIT_TEST_SUITE_END();
public:
void setUp() {
channel = new DummyStanzaChannel();
- testPresence = boost::shared_ptr<Presence>(new Presence());
+ testPresence = boost::make_shared<Presence>();
testPresence->setStatus("Foo");
- secondTestPresence = boost::shared_ptr<Presence>(new Presence());
+ secondTestPresence = boost::make_shared<Presence>();
secondTestPresence->setStatus("Bar");
stanzaChannelPresenceSender = new StanzaChannelPresenceSender(channel);
}
void tearDown() {
delete stanzaChannelPresenceSender;
delete channel;
}
void testSendPresence() {
boost::shared_ptr<DirectedPresenceSender> testling(createPresenceSender());
testling->sendPresence(testPresence);
CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel->sentStanzas.size()));
boost::shared_ptr<Presence> presence = boost::dynamic_pointer_cast<Presence>(channel->sentStanzas[0]);
CPPUNIT_ASSERT(testPresence == presence);
}
void testSendPresence_UndirectedPresenceWithDirectedPresenceReceivers() {
boost::shared_ptr<DirectedPresenceSender> testling(createPresenceSender());
testling->addDirectedPresenceReceiver(JID("alice@wonderland.lit/teaparty"), DirectedPresenceSender::AndSendPresence);
testling->sendPresence(testPresence);
CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(channel->sentStanzas.size()));
boost::shared_ptr<Presence> presence = boost::dynamic_pointer_cast<Presence>(channel->sentStanzas[0]);
CPPUNIT_ASSERT(testPresence == presence);
presence = boost::dynamic_pointer_cast<Presence>(channel->sentStanzas[1]);
CPPUNIT_ASSERT_EQUAL(testPresence->getStatus(), presence->getStatus());
CPPUNIT_ASSERT_EQUAL(JID("alice@wonderland.lit/teaparty"), presence->getTo());
}
void testSendPresence_DirectedPresenceWithDirectedPresenceReceivers() {
boost::shared_ptr<DirectedPresenceSender> testling(createPresenceSender());
testling->addDirectedPresenceReceiver(JID("alice@wonderland.lit/teaparty"), DirectedPresenceSender::AndSendPresence);
diff --git a/Swiften/Queries/Requests/GetPrivateStorageRequest.h b/Swiften/Queries/Requests/GetPrivateStorageRequest.h
index b0eefb2..b5fd97f 100644
--- a/Swiften/Queries/Requests/GetPrivateStorageRequest.h
+++ b/Swiften/Queries/Requests/GetPrivateStorageRequest.h
@@ -1,43 +1,44 @@
/*
* Copyright (c) 2010 Remko Tronçon
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
#pragma once
#include <Swiften/Base/boost_bsignals.h>
#include <boost/shared_ptr.hpp>
+#include <boost/smart_ptr/make_shared.hpp>
#include <Swiften/Queries/Request.h>
#include <Swiften/Elements/PrivateStorage.h>
#include <Swiften/Elements/ErrorPayload.h>
namespace Swift {
template<typename PAYLOAD_TYPE>
class GetPrivateStorageRequest : public Request {
public:
typedef boost::shared_ptr<GetPrivateStorageRequest<PAYLOAD_TYPE> > ref;
static ref create(IQRouter* router) {
return ref(new GetPrivateStorageRequest(router));
}
private:
- GetPrivateStorageRequest(IQRouter* router) : Request(IQ::Get, JID(), boost::shared_ptr<PrivateStorage>(new PrivateStorage(boost::shared_ptr<Payload>(new PAYLOAD_TYPE()))), router) {
+ GetPrivateStorageRequest(IQRouter* router) : Request(IQ::Get, JID(), boost::make_shared<PrivateStorage>(boost::shared_ptr<Payload>(new PAYLOAD_TYPE())), router) {
}
virtual void handleResponse(boost::shared_ptr<Payload> payload, ErrorPayload::ref error) {
boost::shared_ptr<PrivateStorage> storage = boost::dynamic_pointer_cast<PrivateStorage>(payload);
if (storage) {
onResponse(boost::dynamic_pointer_cast<PAYLOAD_TYPE>(storage->getPayload()), error);
}
else {
onResponse(boost::shared_ptr<PAYLOAD_TYPE>(), error);
}
}
public:
boost::signal<void (boost::shared_ptr<PAYLOAD_TYPE>, ErrorPayload::ref)> onResponse;
};
}
diff --git a/Swiften/Queries/Requests/GetSecurityLabelsCatalogRequest.h b/Swiften/Queries/Requests/GetSecurityLabelsCatalogRequest.h
index a6f782b..943adef 100644
--- a/Swiften/Queries/Requests/GetSecurityLabelsCatalogRequest.h
+++ b/Swiften/Queries/Requests/GetSecurityLabelsCatalogRequest.h
@@ -1,30 +1,32 @@
/*
* Copyright (c) 2010 Remko Tronçon
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
#pragma once
+#include <boost/smart_ptr/make_shared.hpp>
+
#include <Swiften/Queries/GenericRequest.h>
#include <Swiften/Elements/SecurityLabelsCatalog.h>
namespace Swift {
class GetSecurityLabelsCatalogRequest : public GenericRequest<SecurityLabelsCatalog> {
public:
typedef boost::shared_ptr<GetSecurityLabelsCatalogRequest> ref;
static ref create(const JID& recipient, IQRouter* router) {
return ref(new GetSecurityLabelsCatalogRequest(recipient, router));
}
private:
GetSecurityLabelsCatalogRequest(
const JID& recipient,
IQRouter* router) :
GenericRequest<SecurityLabelsCatalog>(
- IQ::Get, JID(), boost::shared_ptr<SecurityLabelsCatalog>(new SecurityLabelsCatalog(recipient)), router) {
+ IQ::Get, JID(), boost::make_shared<SecurityLabelsCatalog>(recipient), router) {
}
};
}
diff --git a/Swiften/Queries/Requests/SetPrivateStorageRequest.h b/Swiften/Queries/Requests/SetPrivateStorageRequest.h
index f795742..f65f819 100644
--- a/Swiften/Queries/Requests/SetPrivateStorageRequest.h
+++ b/Swiften/Queries/Requests/SetPrivateStorageRequest.h
@@ -1,37 +1,38 @@
/*
* Copyright (c) 2010 Remko Tronçon
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
#pragma once
#include <Swiften/Base/boost_bsignals.h>
#include <boost/shared_ptr.hpp>
+#include <boost/smart_ptr/make_shared.hpp>
#include <Swiften/Queries/Request.h>
#include <Swiften/Elements/PrivateStorage.h>
#include <Swiften/Elements/ErrorPayload.h>
namespace Swift {
template<typename PAYLOAD_TYPE>
class SetPrivateStorageRequest : public Request {
public:
typedef boost::shared_ptr<SetPrivateStorageRequest<PAYLOAD_TYPE> > ref;
static ref create(boost::shared_ptr<PAYLOAD_TYPE> payload, IQRouter* router) {
return ref(new SetPrivateStorageRequest<PAYLOAD_TYPE>(payload, router));
}
private:
- SetPrivateStorageRequest(boost::shared_ptr<PAYLOAD_TYPE> payload, IQRouter* router) : Request(IQ::Set, JID(), boost::shared_ptr<PrivateStorage>(new PrivateStorage(payload)), router) {
+ SetPrivateStorageRequest(boost::shared_ptr<PAYLOAD_TYPE> payload, IQRouter* router) : Request(IQ::Set, JID(), boost::make_shared<PrivateStorage>(payload), router) {
}
virtual void handleResponse(boost::shared_ptr<Payload>, ErrorPayload::ref error) {
onResponse(error);
}
public:
boost::signal<void (ErrorPayload::ref)> onResponse;
};
}
diff --git a/Swiften/Queries/Responders/SoftwareVersionResponder.cpp b/Swiften/Queries/Responders/SoftwareVersionResponder.cpp
index 3f9616a..55328fb 100644
--- a/Swiften/Queries/Responders/SoftwareVersionResponder.cpp
+++ b/Swiften/Queries/Responders/SoftwareVersionResponder.cpp
@@ -1,26 +1,28 @@
/*
* Copyright (c) 2010 Remko Tronçon
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
+#include <boost/smart_ptr/make_shared.hpp>
+
#include <Swiften/Queries/Responders/SoftwareVersionResponder.h>
#include <Swiften/Queries/IQRouter.h>
namespace Swift {
SoftwareVersionResponder::SoftwareVersionResponder(IQRouter* router) : GetResponder<SoftwareVersion>(router) {
}
void SoftwareVersionResponder::setVersion(const std::string& client, const std::string& version, const std::string& os) {
this->client = client;
this->version = version;
this->os = os;
}
bool SoftwareVersionResponder::handleGetRequest(const JID& from, const JID&, const std::string& id, boost::shared_ptr<SoftwareVersion>) {
- sendResponse(from, id, boost::shared_ptr<SoftwareVersion>(new SoftwareVersion(client, version, os)));
+ sendResponse(from, id, boost::make_shared<SoftwareVersion>(client, version, os));
return true;
}
}
diff --git a/Swiften/Queries/UnitTest/IQRouterTest.cpp b/Swiften/Queries/UnitTest/IQRouterTest.cpp
index f06b967..ee27a67 100644
--- a/Swiften/Queries/UnitTest/IQRouterTest.cpp
+++ b/Swiften/Queries/UnitTest/IQRouterTest.cpp
@@ -1,169 +1,170 @@
/*
* Copyright (c) 2010 Remko Tronçon
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <boost/shared_ptr.hpp>
+#include <boost/smart_ptr/make_shared.hpp>
#include <boost/bind.hpp>
#include <Swiften/Queries/IQHandler.h>
#include <Swiften/Queries/IQRouter.h>
#include <Swiften/Queries/DummyIQChannel.h>
using namespace Swift;
class IQRouterTest : public CppUnit::TestFixture {
CPPUNIT_TEST_SUITE(IQRouterTest);
CPPUNIT_TEST(testRemoveHandler);
CPPUNIT_TEST(testRemoveHandler_AfterHandleIQ);
CPPUNIT_TEST(testHandleIQ_SuccesfulHandlerFirst);
CPPUNIT_TEST(testHandleIQ_SuccesfulHandlerLast);
CPPUNIT_TEST(testHandleIQ_NoSuccesfulHandler);
CPPUNIT_TEST(testHandleIQ_HandlerRemovedDuringHandle);
CPPUNIT_TEST(testSendIQ_WithFrom);
CPPUNIT_TEST(testSendIQ_WithoutFrom);
CPPUNIT_TEST(testHandleIQ_WithFrom);
CPPUNIT_TEST_SUITE_END();
public:
void setUp() {
channel_ = new DummyIQChannel();
}
void tearDown() {
delete channel_;
}
void testRemoveHandler() {
IQRouter testling(channel_);
DummyIQHandler handler1(true, &testling);
DummyIQHandler handler2(true, &testling);
testling.removeHandler(&handler1);
- channel_->onIQReceived(boost::shared_ptr<IQ>(new IQ()));
+ channel_->onIQReceived(boost::make_shared<IQ>());
CPPUNIT_ASSERT_EQUAL(0, handler1.called);
CPPUNIT_ASSERT_EQUAL(1, handler2.called);
}
void testRemoveHandler_AfterHandleIQ() {
IQRouter testling(channel_);
DummyIQHandler handler2(true, &testling);
DummyIQHandler handler1(true, &testling);
- channel_->onIQReceived(boost::shared_ptr<IQ>(new IQ()));
+ channel_->onIQReceived(boost::make_shared<IQ>());
testling.removeHandler(&handler1);
- channel_->onIQReceived(boost::shared_ptr<IQ>(new IQ()));
+ channel_->onIQReceived(boost::make_shared<IQ>());
CPPUNIT_ASSERT_EQUAL(1, handler1.called);
CPPUNIT_ASSERT_EQUAL(1, handler2.called);
}
void testHandleIQ_SuccesfulHandlerFirst() {
IQRouter testling(channel_);
DummyIQHandler handler2(false, &testling);
DummyIQHandler handler1(true, &testling);
- channel_->onIQReceived(boost::shared_ptr<IQ>(new IQ()));
+ channel_->onIQReceived(boost::make_shared<IQ>());
CPPUNIT_ASSERT_EQUAL(1, handler1.called);
CPPUNIT_ASSERT_EQUAL(0, handler2.called);
CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(channel_->iqs_.size()));
}
void testHandleIQ_SuccesfulHandlerLast() {
IQRouter testling(channel_);
DummyIQHandler handler2(true, &testling);
DummyIQHandler handler1(false, &testling);
- channel_->onIQReceived(boost::shared_ptr<IQ>(new IQ()));
+ channel_->onIQReceived(boost::make_shared<IQ>());
CPPUNIT_ASSERT_EQUAL(1, handler1.called);
CPPUNIT_ASSERT_EQUAL(1, handler2.called);
CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(channel_->iqs_.size()));
}
void testHandleIQ_NoSuccesfulHandler() {
IQRouter testling(channel_);
DummyIQHandler handler(false, &testling);
- channel_->onIQReceived(boost::shared_ptr<IQ>(new IQ()));
+ channel_->onIQReceived(boost::make_shared<IQ>());
CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size()));
CPPUNIT_ASSERT(channel_->iqs_[0]->getPayload<ErrorPayload>());
}
void testHandleIQ_HandlerRemovedDuringHandle() {
IQRouter testling(channel_);
DummyIQHandler handler2(true, &testling);
RemovingIQHandler handler1(&testling);
- channel_->onIQReceived(boost::shared_ptr<IQ>(new IQ()));
- channel_->onIQReceived(boost::shared_ptr<IQ>(new IQ()));
+ channel_->onIQReceived(boost::make_shared<IQ>());
+ channel_->onIQReceived(boost::make_shared<IQ>());
CPPUNIT_ASSERT_EQUAL(1, handler1.called);
CPPUNIT_ASSERT_EQUAL(2, handler2.called);
}
void testSendIQ_WithFrom() {
IQRouter testling(channel_);
testling.setFrom(JID("foo@bar.com/baz"));
- testling.sendIQ(boost::shared_ptr<IQ>(new IQ()));
+ testling.sendIQ(boost::make_shared<IQ>());
CPPUNIT_ASSERT_EQUAL(JID("foo@bar.com/baz"), channel_->iqs_[0]->getFrom());
}
void testSendIQ_WithoutFrom() {
IQRouter testling(channel_);
- testling.sendIQ(boost::shared_ptr<IQ>(new IQ()));
+ testling.sendIQ(boost::make_shared<IQ>());
CPPUNIT_ASSERT_EQUAL(JID(), channel_->iqs_[0]->getFrom());
}
void testHandleIQ_WithFrom() {
IQRouter testling(channel_);
testling.setFrom(JID("foo@bar.com/baz"));
DummyIQHandler handler(false, &testling);
- channel_->onIQReceived(boost::shared_ptr<IQ>(new IQ()));
+ channel_->onIQReceived(boost::make_shared<IQ>());
CPPUNIT_ASSERT_EQUAL(JID("foo@bar.com/baz"), channel_->iqs_[0]->getFrom());
}
private:
struct DummyIQHandler : public IQHandler {
DummyIQHandler(bool handle, IQRouter* router) : handle(handle), router(router), called(0) {
router->addHandler(this);
}
~DummyIQHandler() {
router->removeHandler(this);
}
virtual bool handleIQ(boost::shared_ptr<IQ>) {
called++;
return handle;
}
bool handle;
IQRouter* router;
int called;
};
struct RemovingIQHandler : public IQHandler {
RemovingIQHandler(IQRouter* router) : router(router), called(0) {
router->addHandler(this);
}
virtual bool handleIQ(boost::shared_ptr<IQ>) {
called++;
router->removeHandler(this);
return false;
}
IQRouter* router;
int called;
diff --git a/Swiften/Queries/UnitTest/RequestTest.cpp b/Swiften/Queries/UnitTest/RequestTest.cpp
index 52d62fb..cf9b381 100644
--- a/Swiften/Queries/UnitTest/RequestTest.cpp
+++ b/Swiften/Queries/UnitTest/RequestTest.cpp
@@ -98,71 +98,71 @@ class RequestTest : public CppUnit::TestFixture {
CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size()));
CPPUNIT_ASSERT_EQUAL(IQ::Get, channel_->iqs_[0]->getType());
}
void testHandleIQ() {
MyRequest testling(IQ::Get, JID("foo@bar.com/baz"), payload_, router_);
testling.onResponse.connect(boost::bind(&RequestTest::handleResponse, this, _1, _2));
testling.send();
channel_->onIQReceived(createResponse(JID("foo@bar.com/baz"),"test-id"));
CPPUNIT_ASSERT_EQUAL(1, responsesReceived_);
CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(receivedErrors.size()));
CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size()));
}
// FIXME: Doesn't test that it didn't handle the payload
void testHandleIQ_InvalidID() {
MyRequest testling(IQ::Get, JID("foo@bar.com/baz"), payload_, router_);
testling.onResponse.connect(boost::bind(&RequestTest::handleResponse, this, _1, _2));
testling.send();
channel_->onIQReceived(createResponse(JID("foo@bar.com/baz"),"different-id"));
CPPUNIT_ASSERT_EQUAL(0, responsesReceived_);
CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(receivedErrors.size()));
CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size()));
}
void testHandleIQ_Error() {
MyRequest testling(IQ::Get, JID("foo@bar.com/baz"), payload_, router_);
testling.onResponse.connect(boost::bind(&RequestTest::handleResponse, this, _1, _2));
testling.send();
boost::shared_ptr<IQ> error = createError(JID("foo@bar.com/baz"),"test-id");
- boost::shared_ptr<Payload> errorPayload = boost::shared_ptr<ErrorPayload>(new ErrorPayload(ErrorPayload::InternalServerError));
+ boost::shared_ptr<Payload> errorPayload = boost::make_shared<ErrorPayload>(ErrorPayload::InternalServerError);
error->addPayload(errorPayload);
channel_->onIQReceived(error);
CPPUNIT_ASSERT_EQUAL(0, responsesReceived_);
CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(receivedErrors.size()));
CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size()));
CPPUNIT_ASSERT_EQUAL(ErrorPayload::InternalServerError, receivedErrors[0].getCondition());
}
void testHandleIQ_ErrorWithoutPayload() {
MyRequest testling(IQ::Get, JID("foo@bar.com/baz"), payload_, router_);
testling.onResponse.connect(boost::bind(&RequestTest::handleResponse, this, _1, _2));
testling.send();
channel_->onIQReceived(createError(JID("foo@bar.com/baz"),"test-id"));
CPPUNIT_ASSERT_EQUAL(0, responsesReceived_);
CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(receivedErrors.size()));
CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel_->iqs_.size()));
CPPUNIT_ASSERT_EQUAL(ErrorPayload::UndefinedCondition, receivedErrors[0].getCondition());
}
void testHandleIQ_BeforeSend() {
MyRequest testling(IQ::Get, JID("foo@bar.com/baz"), payload_, router_);
testling.onResponse.connect(boost::bind(&RequestTest::handleResponse, this, _1, _2));
channel_->onIQReceived(createResponse(JID("foo@bar.com/baz"),"test-id"));
CPPUNIT_ASSERT_EQUAL(0, responsesReceived_);
CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(receivedErrors.size()));
CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(channel_->iqs_.size()));
}
void testHandleIQ_DifferentPayload() {
MyRequest testling(IQ::Get, JID("foo@bar.com/baz"), payload_, router_);
testling.onResponse.connect(boost::bind(&RequestTest::handleDifferentResponse, this, _1, _2));
diff --git a/Swiften/Queries/UnitTest/ResponderTest.cpp b/Swiften/Queries/UnitTest/ResponderTest.cpp
index a256346..6d40b6c 100644
--- a/Swiften/Queries/UnitTest/ResponderTest.cpp
+++ b/Swiften/Queries/UnitTest/ResponderTest.cpp
@@ -1,70 +1,71 @@
/*
* Copyright (c) 2010 Remko Tronçon
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <boost/shared_ptr.hpp>
+#include <boost/smart_ptr/make_shared.hpp>
#include <boost/bind.hpp>
#include <Swiften/Queries/Responder.h>
#include <Swiften/Queries/IQRouter.h>
#include <Swiften/Queries/DummyIQChannel.h>
#include <Swiften/Elements/SoftwareVersion.h>
using namespace Swift;
class ResponderTest : public CppUnit::TestFixture {
CPPUNIT_TEST_SUITE(ResponderTest);
CPPUNIT_TEST(testConstructor);
CPPUNIT_TEST(testStart);
CPPUNIT_TEST(testStop);
CPPUNIT_TEST(testHandleIQ_Set);
CPPUNIT_TEST(testHandleIQ_Get);
CPPUNIT_TEST(testHandleIQ_Error);
CPPUNIT_TEST(testHandleIQ_Result);
CPPUNIT_TEST(testHandleIQ_NoPayload);
CPPUNIT_TEST_SUITE_END();
public:
void setUp() {
channel_ = new DummyIQChannel();
router_ = new IQRouter(channel_);
- payload_ = boost::shared_ptr<SoftwareVersion>(new SoftwareVersion("foo"));
+ payload_ = boost::make_shared<SoftwareVersion>("foo");
}
void tearDown() {
delete router_;
delete channel_;
}
void testConstructor() {
MyResponder testling(router_);
channel_->onIQReceived(createRequest(IQ::Set));
CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(testling.setPayloads_.size()));
}
void testStart() {
MyResponder testling(router_);
testling.start();
channel_->onIQReceived(createRequest(IQ::Set));
CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(testling.setPayloads_.size()));
}
void testStop() {
MyResponder testling(router_);
testling.start();
testling.stop();
channel_->onIQReceived(createRequest(IQ::Set));
CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(testling.setPayloads_.size()));
}
void testHandleIQ_Set() {
@@ -76,71 +77,71 @@ class ResponderTest : public CppUnit::TestFixture {
CPPUNIT_ASSERT(payload_ == testling.setPayloads_[0]);
CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(testling.getPayloads_.size()));
}
void testHandleIQ_Get() {
MyResponder testling(router_);
CPPUNIT_ASSERT(dynamic_cast<IQHandler*>(&testling)->handleIQ(createRequest(IQ::Get)));
CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(testling.getPayloads_.size()));
CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(testling.setPayloads_.size()));
CPPUNIT_ASSERT(payload_ == testling.getPayloads_[0]);
}
void testHandleIQ_Error() {
MyResponder testling(router_);
CPPUNIT_ASSERT(!dynamic_cast<IQHandler*>(&testling)->handleIQ(createRequest(IQ::Error)));
CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(testling.getPayloads_.size()));
CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(testling.setPayloads_.size()));
}
void testHandleIQ_Result() {
MyResponder testling(router_);
CPPUNIT_ASSERT(!dynamic_cast<IQHandler*>(&testling)->handleIQ(createRequest(IQ::Result)));
CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(testling.getPayloads_.size()));
CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(testling.setPayloads_.size()));
}
void testHandleIQ_NoPayload() {
MyResponder testling(router_);
- CPPUNIT_ASSERT(!dynamic_cast<IQHandler*>(&testling)->handleIQ(boost::shared_ptr<IQ>(new IQ(IQ::Get))));
+ CPPUNIT_ASSERT(!dynamic_cast<IQHandler*>(&testling)->handleIQ(boost::make_shared<IQ>(IQ::Get)));
CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(testling.getPayloads_.size()));
CPPUNIT_ASSERT_EQUAL(0, static_cast<int>(testling.setPayloads_.size()));
}
private:
boost::shared_ptr<IQ> createRequest(IQ::Type type) {
boost::shared_ptr<IQ> iq(new IQ(type));
iq->addPayload(payload_);
iq->setID("myid");
iq->setFrom(JID("foo@bar.com/baz"));
return iq;
}
private:
class MyResponder : public Responder<SoftwareVersion> {
public:
MyResponder(IQRouter* router) : Responder<SoftwareVersion>(router), getRequestResponse_(true), setRequestResponse_(true) {}
virtual bool handleGetRequest(const JID& from, const JID&, const std::string& id, boost::shared_ptr<SoftwareVersion> payload) {
CPPUNIT_ASSERT_EQUAL(JID("foo@bar.com/baz"), from);
CPPUNIT_ASSERT_EQUAL(std::string("myid"), id);
getPayloads_.push_back(payload);
return getRequestResponse_;
}
virtual bool handleSetRequest(const JID& from, const JID&, const std::string& id, boost::shared_ptr<SoftwareVersion> payload) {
CPPUNIT_ASSERT_EQUAL(JID("foo@bar.com/baz"), from);
CPPUNIT_ASSERT_EQUAL(std::string("myid"), id);
setPayloads_.push_back(payload);
return setRequestResponse_;
}
bool getRequestResponse_;
bool setRequestResponse_;
std::vector<boost::shared_ptr<SoftwareVersion> > getPayloads_;
diff --git a/Swiften/Serializer/PayloadSerializers/CommandSerializer.cpp b/Swiften/Serializer/PayloadSerializers/CommandSerializer.cpp
index 2fb86b0..40acd8e 100644
--- a/Swiften/Serializer/PayloadSerializers/CommandSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/CommandSerializer.cpp
@@ -1,95 +1,96 @@
/*
* Copyright (c) 2010 Kevin Smith
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/CommandSerializer.h>
#include <boost/shared_ptr.hpp>
+#include <boost/smart_ptr/make_shared.hpp>
#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLTextNode.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
#include <Swiften/Serializer/PayloadSerializers/FormSerializer.h>
namespace Swift {
CommandSerializer::CommandSerializer() {
}
std::string CommandSerializer::serializePayload(boost::shared_ptr<Command> command) const {
XMLElement commandElement("command", "http://jabber.org/protocol/commands");
commandElement.setAttribute("node", command->getNode());
if (!command->getSessionID().empty()) {
commandElement.setAttribute("sessionid", command->getSessionID());
}
std::string action = actionToString(command->getAction());
if (!action.empty()) {
commandElement.setAttribute("action", action);
}
std::string status;
switch (command->getStatus()) {
case Command::Executing: status = "executing";break;
case Command::Completed: status = "completed";break;
case Command::Canceled: status = "canceled";break;
case Command::NoStatus: break;
}
if (!status.empty()) {
commandElement.setAttribute("status", status);
}
if (command->getAvailableActions().size() > 0) {
std::string actions = "<actions";
std::string executeAction = actionToString(command->getExecuteAction());
if (!executeAction.empty()) {
actions += " execute='" + executeAction + "'";
}
actions += ">";
foreach (Command::Action action, command->getAvailableActions()) {
actions += "<" + actionToString(action) + "/>";
}
actions += "</actions>";
- commandElement.addNode(boost::shared_ptr<XMLRawTextNode>(new XMLRawTextNode(actions)));
+ commandElement.addNode(boost::make_shared<XMLRawTextNode>(actions));
}
foreach (Command::Note note, command->getNotes()) {
boost::shared_ptr<XMLElement> noteElement(new XMLElement("note"));
std::string type;
switch (note.type) {
case Command::Note::Info: type = "info"; break;
case Command::Note::Warn: type = "warn"; break;
case Command::Note::Error: type = "error"; break;
}
if (!type.empty()) {
noteElement->setAttribute("type", type);
}
- noteElement->addNode(boost::shared_ptr<XMLTextNode>(new XMLTextNode(note.note)));
+ noteElement->addNode(boost::make_shared<XMLTextNode>(note.note));
commandElement.addNode(noteElement);
}
Form::ref form = command->getForm();
if (form) {
- commandElement.addNode(boost::shared_ptr<XMLRawTextNode>(new XMLRawTextNode(FormSerializer().serialize(form))));
+ commandElement.addNode(boost::make_shared<XMLRawTextNode>(FormSerializer().serialize(form)));
}
return commandElement.serialize();
}
std::string CommandSerializer::actionToString(Command::Action action) const {
std::string string;
switch (action) {
case Command::Cancel: string = "cancel"; break;
case Command::Execute: string = "execute"; break;
case Command::Complete: string = "complete"; break;
case Command::Prev: string = "prev"; break;
case Command::Next: string = "next"; break;
case Command::NoAction: break;
}
return string;
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/DiscoInfoSerializer.cpp b/Swiften/Serializer/PayloadSerializers/DiscoInfoSerializer.cpp
index e2c6f59..03b3eb2 100644
--- a/Swiften/Serializer/PayloadSerializers/DiscoInfoSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/DiscoInfoSerializer.cpp
@@ -1,47 +1,48 @@
/*
* Copyright (c) 2010 Remko Tronçon
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/DiscoInfoSerializer.h>
#include <boost/shared_ptr.hpp>
+#include <boost/smart_ptr/make_shared.hpp>
#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
#include <Swiften/Serializer/PayloadSerializers/FormSerializer.h>
namespace Swift {
DiscoInfoSerializer::DiscoInfoSerializer() : GenericPayloadSerializer<DiscoInfo>() {
}
std::string DiscoInfoSerializer::serializePayload(boost::shared_ptr<DiscoInfo> discoInfo) const {
XMLElement queryElement("query", "http://jabber.org/protocol/disco#info");
if (!discoInfo->getNode().empty()) {
queryElement.setAttribute("node", discoInfo->getNode());
}
foreach(const DiscoInfo::Identity& identity, discoInfo->getIdentities()) {
boost::shared_ptr<XMLElement> identityElement(new XMLElement("identity"));
if (!identity.getLanguage().empty()) {
identityElement->setAttribute("xml:lang", identity.getLanguage());
}
identityElement->setAttribute("category", identity.getCategory());
identityElement->setAttribute("name", identity.getName());
identityElement->setAttribute("type", identity.getType());
queryElement.addNode(identityElement);
}
foreach(const std::string& feature, discoInfo->getFeatures()) {
boost::shared_ptr<XMLElement> featureElement(new XMLElement("feature"));
featureElement->setAttribute("var", feature);
queryElement.addNode(featureElement);
}
foreach(const Form::ref extension, discoInfo->getExtensions()) {
- queryElement.addNode(boost::shared_ptr<XMLRawTextNode>(new XMLRawTextNode(FormSerializer().serialize(extension))));
+ queryElement.addNode(boost::make_shared<XMLRawTextNode>(FormSerializer().serialize(extension)));
}
return queryElement.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/FormSerializer.cpp b/Swiften/Serializer/PayloadSerializers/FormSerializer.cpp
index 15c4f32..ba658e3 100644
--- a/Swiften/Serializer/PayloadSerializers/FormSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/FormSerializer.cpp
@@ -1,44 +1,45 @@
/*
* Copyright (c) 2010 Kevin Smith
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/FormSerializer.h>
#include <boost/shared_ptr.hpp>
+#include <boost/smart_ptr/make_shared.hpp>
#include <iostream>
#include <string>
#include <Swiften/Base/String.h>
#include <Swiften/Base/Algorithm.h>
#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/XML/XMLTextNode.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
using namespace Swift;
namespace {
template<typename T> void serializeValueAsString(boost::shared_ptr<FormField> field, boost::shared_ptr<XMLElement> parent) {
std::string value = boost::dynamic_pointer_cast<T>(field)->getValue();
if (!value.empty()) {
boost::shared_ptr<XMLElement> valueElement(new XMLElement("value"));
valueElement->addNode(XMLTextNode::create(value));
parent->addNode(valueElement);
}
}
}
namespace Swift {
FormSerializer::FormSerializer() : GenericPayloadSerializer<Form>() {
}
std::string FormSerializer::serializePayload(boost::shared_ptr<Form> form) const {
boost::shared_ptr<XMLElement> formElement(new XMLElement("x", "jabber:x:data"));
std::string type;
switch (form->getType()) {
case Form::FormType: type = "form"; break;
case Form::SubmitType: type = "submit"; break;
case Form::CancelType: type = "cancel"; break;
@@ -49,75 +50,75 @@ std::string FormSerializer::serializePayload(boost::shared_ptr<Form> form) cons
multiLineify(form->getTitle(), "title", formElement);
}
if (!form->getInstructions().empty()) {
multiLineify(form->getInstructions(), "instructions", formElement);
}
foreach(boost::shared_ptr<FormField> field, form->getFields()) {
formElement->addNode(fieldToXML(field, true));
}
if (!form->getReportedFields().empty()) {
boost::shared_ptr<XMLElement> reportedElement(new XMLElement("reported"));
foreach(FormField::ref field, form->getReportedFields()) {
reportedElement->addNode(fieldToXML(field, true));
}
formElement->addNode(reportedElement);
}
foreach(Form::FormItem item, form->getItems()) {
boost::shared_ptr<XMLElement> itemElement(new XMLElement("item"));
foreach(FormField::ref field, item) {
itemElement->addNode(fieldToXML(field, false));
}
formElement->addNode(itemElement);
}
return formElement->serialize();
}
boost::shared_ptr<XMLElement> FormSerializer::fieldToXML(boost::shared_ptr<FormField> field, bool withTypeAttribute) const {
boost::shared_ptr<XMLElement> fieldElement(new XMLElement("field"));
if (!field->getName().empty()) {
fieldElement->setAttribute("var", field->getName());
}
if (!field->getLabel().empty()) {
fieldElement->setAttribute("label", field->getLabel());
}
if (field->getRequired()) {
- fieldElement->addNode(boost::shared_ptr<XMLElement>(new XMLElement("required")));
+ fieldElement->addNode(boost::make_shared<XMLElement>("required"));
}
if (!field->getDescription().empty()) {
boost::shared_ptr<XMLElement> descriptionElement(new XMLElement("desc"));
- descriptionElement->addNode(boost::shared_ptr<XMLTextNode>(new XMLTextNode(field->getDescription())));
+ descriptionElement->addNode(boost::make_shared<XMLTextNode>(field->getDescription()));
fieldElement->addNode(descriptionElement);
}
// Set the value and type
std::string fieldType;
if (boost::dynamic_pointer_cast<BooleanFormField>(field)) {
fieldType = "boolean";
boost::shared_ptr<XMLElement> valueElement(new XMLElement("value"));
valueElement->addNode(XMLTextNode::create(boost::dynamic_pointer_cast<BooleanFormField>(field)->getValue() ? "1" : "0"));
fieldElement->addNode(valueElement);
}
else if (boost::dynamic_pointer_cast<FixedFormField>(field)) {
fieldType = "fixed";
serializeValueAsString<FixedFormField>(field, fieldElement);
}
else if (boost::dynamic_pointer_cast<HiddenFormField>(field)) {
fieldType = "hidden";
serializeValueAsString<HiddenFormField>(field, fieldElement);
}
else if (boost::dynamic_pointer_cast<ListSingleFormField>(field)) {
fieldType = "list-single";
serializeValueAsString<ListSingleFormField>(field, fieldElement);
}
else if (boost::dynamic_pointer_cast<TextPrivateFormField>(field)) {
fieldType = "text-private";
serializeValueAsString<TextPrivateFormField>(field, fieldElement);
}
else if (boost::dynamic_pointer_cast<TextSingleFormField>(field)) {
fieldType = "text-single";
serializeValueAsString<TextSingleFormField>(field, fieldElement);
}
else if (boost::dynamic_pointer_cast<JIDMultiFormField>(field)) {
fieldType = "jid-multi";
std::vector<JID> jids = boost::dynamic_pointer_cast<JIDMultiFormField>(field)->getValue();
foreach(const JID& jid, jids) {
@@ -142,41 +143,41 @@ boost::shared_ptr<XMLElement> FormSerializer::fieldToXML(boost::shared_ptr<FormF
}
}
else if (boost::dynamic_pointer_cast<TextMultiFormField>(field)) {
fieldType = "text-multi";
multiLineify(boost::dynamic_pointer_cast<TextMultiFormField>(field)->getValue(), "value", fieldElement);
}
else {
assert(false);
}
if (!fieldType.empty() && withTypeAttribute) {
fieldElement->setAttribute("type", fieldType);
}
foreach (const FormField::Option& option, field->getOptions()) {
boost::shared_ptr<XMLElement> optionElement(new XMLElement("option"));
if (!option.label.empty()) {
optionElement->setAttribute("label", option.label);
}
boost::shared_ptr<XMLElement> valueElement(new XMLElement("value"));
valueElement->addNode(XMLTextNode::create(option.value));
optionElement->addNode(valueElement);
fieldElement->addNode(optionElement);
}
return fieldElement;
}
void FormSerializer::multiLineify(const std::string& text, const std::string& elementName, boost::shared_ptr<XMLElement> element) const {
std::string unRdText(text);
erase(unRdText, '\r');
std::vector<std::string> lines = String::split(unRdText, '\n');
foreach (std::string line, lines) {
boost::shared_ptr<XMLElement> lineElement(new XMLElement(elementName));
- lineElement->addNode(boost::shared_ptr<XMLTextNode>(new XMLTextNode(line)));
+ lineElement->addNode(boost::make_shared<XMLTextNode>(line));
element->addNode(lineElement);
}
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/IBBSerializer.cpp b/Swiften/Serializer/PayloadSerializers/IBBSerializer.cpp
index f3dad80..e78cdb4 100644
--- a/Swiften/Serializer/PayloadSerializers/IBBSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/IBBSerializer.cpp
@@ -1,53 +1,54 @@
/*
* Copyright (c) 2010 Remko Tronçon
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/IBBSerializer.h>
#include <boost/shared_ptr.hpp>
+#include <boost/smart_ptr/make_shared.hpp>
#include <boost/lexical_cast.hpp>
#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLTextNode.h>
#include <Swiften/StringCodecs/Base64.h>
namespace Swift {
IBBSerializer::IBBSerializer() {
}
std::string IBBSerializer::serializePayload(boost::shared_ptr<IBB> ibb) const {
switch(ibb->getAction()) {
case IBB::Data: {
XMLElement ibbElement("data", "http://jabber.org/protocol/ibb");
ibbElement.setAttribute("sid", ibb->getStreamID());
if (ibb->getSequenceNumber() >= 0) {
ibbElement.setAttribute("seq", boost::lexical_cast<std::string>(ibb->getSequenceNumber()));
}
- ibbElement.addNode(boost::shared_ptr<XMLTextNode>(new XMLTextNode(Base64::encode(ibb->getData()))));
+ ibbElement.addNode(boost::make_shared<XMLTextNode>(Base64::encode(ibb->getData())));
return ibbElement.serialize();
}
case IBB::Open: {
XMLElement ibbElement("open", "http://jabber.org/protocol/ibb");
ibbElement.setAttribute("sid", ibb->getStreamID());
switch (ibb->getStanzaType()) {
case IBB::IQStanza: ibbElement.setAttribute("stanza", "iq"); break;
case IBB::MessageStanza: ibbElement.setAttribute("stanza", "message"); break;
}
assert(ibb->getBlockSize() > 0);
ibbElement.setAttribute("block-size", boost::lexical_cast<std::string>(ibb->getBlockSize()));
return ibbElement.serialize();
}
case IBB::Close: {
XMLElement ibbElement("close", "http://jabber.org/protocol/ibb");
ibbElement.setAttribute("sid", ibb->getStreamID());
return ibbElement.serialize();
}
}
return "";
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/InBandRegistrationPayloadSerializer.cpp b/Swiften/Serializer/PayloadSerializers/InBandRegistrationPayloadSerializer.cpp
index 12b1bb5..0db546e 100644
--- a/Swiften/Serializer/PayloadSerializers/InBandRegistrationPayloadSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/InBandRegistrationPayloadSerializer.cpp
@@ -1,44 +1,45 @@
/*
* Copyright (c) 2010 Remko Tronçon
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/InBandRegistrationPayloadSerializer.h>
#include <boost/shared_ptr.hpp>
+#include <boost/smart_ptr/make_shared.hpp>
#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
#include <Swiften/Serializer/PayloadSerializers/FormSerializer.h>
namespace Swift {
InBandRegistrationPayloadSerializer::InBandRegistrationPayloadSerializer() {
}
std::string InBandRegistrationPayloadSerializer::serializePayload(boost::shared_ptr<InBandRegistrationPayload> registration) const {
XMLElement registerElement("query", "jabber:iq:register");
if (registration->isRegistered()) {
registerElement.addNode(XMLElement::ref(new XMLElement("registered")));
}
if (registration->isRemove()) {
registerElement.addNode(XMLElement::ref(new XMLElement("remove")));
}
if (registration->getInstructions()) {
registerElement.addNode(XMLElement::ref(new XMLElement("instructions", "", *registration->getInstructions())));
}
if (registration->getUsername()) {
registerElement.addNode(XMLElement::ref(new XMLElement("username", "", *registration->getUsername())));
}
if (registration->getNick()) {
registerElement.addNode(XMLElement::ref(new XMLElement("nick", "", *registration->getNick())));
}
@@ -71,42 +72,42 @@ std::string InBandRegistrationPayloadSerializer::serializePayload(boost::shared_
}
if (registration->getState()) {
registerElement.addNode(XMLElement::ref(new XMLElement("state", "", *registration->getState())));
}
if (registration->getZip()) {
registerElement.addNode(XMLElement::ref(new XMLElement("zip", "", *registration->getZip())));
}
if (registration->getPhone()) {
registerElement.addNode(XMLElement::ref(new XMLElement("phone", "", *registration->getPhone())));
}
if (registration->getURL()) {
registerElement.addNode(XMLElement::ref(new XMLElement("url", "", *registration->getURL())));
}
if (registration->getDate()) {
registerElement.addNode(XMLElement::ref(new XMLElement("date", "", *registration->getDate())));
}
if (registration->getMisc()) {
registerElement.addNode(XMLElement::ref(new XMLElement("misc", "", *registration->getMisc())));
}
if (registration->getText()) {
registerElement.addNode(XMLElement::ref(new XMLElement("text", "", *registration->getText())));
}
if (registration->getKey()) {
registerElement.addNode(XMLElement::ref(new XMLElement("key", "", *registration->getKey())));
}
if (Form::ref form = registration->getForm()) {
- registerElement.addNode(boost::shared_ptr<XMLRawTextNode>(new XMLRawTextNode(FormSerializer().serialize(form))));
+ registerElement.addNode(boost::make_shared<XMLRawTextNode>(FormSerializer().serialize(form)));
}
return registerElement.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/JinglePayloadSerializer.cpp b/Swiften/Serializer/PayloadSerializers/JinglePayloadSerializer.cpp
index c16a2e4..a04687b 100644
--- a/Swiften/Serializer/PayloadSerializers/JinglePayloadSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/JinglePayloadSerializer.cpp
@@ -11,71 +11,71 @@
#include <boost/smart_ptr/intrusive_ptr.hpp>
#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/XML/XMLNode.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
#include <Swiften/Serializer/PayloadSerializers/JingleContentPayloadSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/JingleFileTransferHashSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/JingleFileTransferReceivedSerializer.h>
#include <Swiften/Serializer/PayloadSerializerCollection.h>
#include <Swiften/Elements/JinglePayload.h>
#include <Swiften/Elements/JingleContentPayload.h>
#include <Swiften/Elements/JingleIBBTransportPayload.h>
#include <Swiften/Elements/JingleFileTransferDescription.h>
#include <Swiften/Elements/JingleFileTransferHash.h>
#include <Swiften/Elements/JingleFileTransferReceived.h>
namespace Swift {
JinglePayloadSerializer::JinglePayloadSerializer(PayloadSerializerCollection* serializers) : serializers(serializers) {
}
std::string JinglePayloadSerializer::serializePayload(boost::shared_ptr<JinglePayload> payload) const {
XMLElement jinglePayload("jingle", "urn:xmpp:jingle:1");
jinglePayload.setAttribute("action", actionToString(payload->getAction()));
jinglePayload.setAttribute("initiator", payload->getInitiator());
jinglePayload.setAttribute("sid", payload->getSessionID());
std::vector<boost::shared_ptr<Payload> > payloads = payload->getPayloads();
if (!payloads.empty()) {
foreach(boost::shared_ptr<Payload> subPayload, payloads) {
PayloadSerializer* serializer = serializers->getPayloadSerializer(subPayload);
if (serializer) {
- jinglePayload.addNode(boost::shared_ptr<XMLRawTextNode>(new XMLRawTextNode(serializer->serialize(subPayload))));
+ jinglePayload.addNode(boost::make_shared<XMLRawTextNode>(serializer->serialize(subPayload)));
}
}
}
if (payload->getReason().is_initialized()) {
boost::shared_ptr<XMLElement> reason = boost::make_shared<XMLElement>("reason");
reason->addNode(boost::make_shared<XMLElement>(reasonTypeToString(payload->getReason()->type)));
if (!payload->getReason()->text.empty()) {
reason->addNode(boost::make_shared<XMLElement>("desc", "", payload->getReason()->text));
}
jinglePayload.addNode(reason);
}
return jinglePayload.serialize();
}
std::string JinglePayloadSerializer::actionToString(JinglePayload::Action action) const {
switch(action) {
case JinglePayload::ContentAccept:
return "content-accept";
case JinglePayload::ContentAdd:
return "content-add";
case JinglePayload::ContentModify:
return "content-modify";
case JinglePayload::ContentReject:
return "content-reject";
case JinglePayload::ContentRemove:
return "content-remove";
case JinglePayload::DescriptionInfo:
return "description-info";
case JinglePayload::SecurityInfo:
return "security-info";
case JinglePayload::SessionAccept:
return "session-accept";
case JinglePayload::SessionInfo:
diff --git a/Swiften/Serializer/PayloadSerializers/MUCOwnerPayloadSerializer.cpp b/Swiften/Serializer/PayloadSerializers/MUCOwnerPayloadSerializer.cpp
index f86b59e..3cb8cf6 100644
--- a/Swiften/Serializer/PayloadSerializers/MUCOwnerPayloadSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/MUCOwnerPayloadSerializer.cpp
@@ -1,30 +1,32 @@
/*
* Copyright (c) 2010 Kevin Smith
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/MUCOwnerPayloadSerializer.h>
+#include <boost/smart_ptr/make_shared.hpp>
+
#include <Swiften/Serializer/PayloadSerializerCollection.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
namespace Swift {
MUCOwnerPayloadSerializer::MUCOwnerPayloadSerializer(PayloadSerializerCollection* serializers) : GenericPayloadSerializer<MUCOwnerPayload>(), serializers(serializers) {
}
std::string MUCOwnerPayloadSerializer::serializePayload(boost::shared_ptr<MUCOwnerPayload> mucOwner) const {
XMLElement mucElement("query", "http://jabber.org/protocol/muc#owner");
boost::shared_ptr<Payload> payload = mucOwner->getPayload();
if (payload) {
PayloadSerializer* serializer = serializers->getPayloadSerializer(payload);
if (serializer) {
- mucElement.addNode(boost::shared_ptr<XMLRawTextNode>(new XMLRawTextNode(serializer->serialize(payload))));
+ mucElement.addNode(boost::make_shared<XMLRawTextNode>(serializer->serialize(payload)));
}
}
return mucElement.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/MUCUserPayloadSerializer.cpp b/Swiften/Serializer/PayloadSerializers/MUCUserPayloadSerializer.cpp
index 66ca5d0..2e60654 100644
--- a/Swiften/Serializer/PayloadSerializers/MUCUserPayloadSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/MUCUserPayloadSerializer.cpp
@@ -1,72 +1,73 @@
/*
* Copyright (c) 2010 Kevin Smith
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/MUCUserPayloadSerializer.h>
#include <sstream>
#include <boost/shared_ptr.hpp>
+#include <boost/smart_ptr/make_shared.hpp>
#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLTextNode.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
#include <Swiften/Serializer/PayloadSerializers/MUCItemSerializer.h>
#include <Swiften/Serializer/PayloadSerializerCollection.h>
namespace Swift {
MUCUserPayloadSerializer::MUCUserPayloadSerializer(PayloadSerializerCollection* serializers) : GenericPayloadSerializer<MUCUserPayload>(), serializers(serializers) {
}
std::string MUCUserPayloadSerializer::serializePayload(boost::shared_ptr<MUCUserPayload> payload) const {
XMLElement mucElement("x", "http://jabber.org/protocol/muc#user");
foreach (const MUCUserPayload::StatusCode statusCode, payload->getStatusCodes()) {
boost::shared_ptr<XMLElement> statusElement(new XMLElement("status"));
std::ostringstream code;
code << statusCode.code;
statusElement->setAttribute("code", code.str());
mucElement.addNode(statusElement);
}
foreach (const MUCItem& item, payload->getItems()) {
mucElement.addNode(MUCItemSerializer::itemToElement(item));
}
if (payload->getPassword()) {
boost::shared_ptr<XMLElement> passwordElement = boost::make_shared<XMLElement>("password");
passwordElement->addNode(boost::make_shared<XMLTextNode>(*payload->getPassword()));
}
if (payload->getInvite()) {
MUCUserPayload::Invite invite = *payload->getInvite();
boost::shared_ptr<XMLElement> inviteElement = boost::make_shared<XMLElement>("invite");
if (invite.to.isValid()) {
inviteElement->setAttribute("to", invite.to.toString());
}
if (invite.from.isValid()) {
inviteElement->setAttribute("from", invite.from.toString());
}
if (!invite.reason.empty()) {
boost::shared_ptr<XMLElement> reasonElement = boost::make_shared<XMLElement>("reason");
reasonElement->addNode(boost::make_shared<XMLTextNode>(invite.reason));
}
mucElement.addNode(inviteElement);
}
boost::shared_ptr<Payload> childPayload = payload->getPayload();
if (childPayload) {
PayloadSerializer* serializer = serializers->getPayloadSerializer(childPayload);
if (serializer) {
- mucElement.addNode(boost::shared_ptr<XMLRawTextNode>(new XMLRawTextNode(serializer->serialize(childPayload))));
+ mucElement.addNode(boost::make_shared<XMLRawTextNode>(serializer->serialize(childPayload)));
}
}
return mucElement.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/NicknameSerializer.cpp b/Swiften/Serializer/PayloadSerializers/NicknameSerializer.cpp
index 38a5db5..33385b0 100644
--- a/Swiften/Serializer/PayloadSerializers/NicknameSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/NicknameSerializer.cpp
@@ -1,25 +1,26 @@
/*
* Copyright (c) 2010 Remko Tronçon
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/NicknameSerializer.h>
#include <boost/shared_ptr.hpp>
+#include <boost/smart_ptr/make_shared.hpp>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLTextNode.h>
namespace Swift {
NicknameSerializer::NicknameSerializer() : GenericPayloadSerializer<Nickname>() {
}
std::string NicknameSerializer::serializePayload(boost::shared_ptr<Nickname> nick) const {
XMLElement nickElement("nick", "http://jabber.org/protocol/nick");
- nickElement.addNode(boost::shared_ptr<XMLTextNode>(new XMLTextNode(nick->getNickname())));
+ nickElement.addNode(boost::make_shared<XMLTextNode>(nick->getNickname()));
return nickElement.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/PrivateStorageSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PrivateStorageSerializer.cpp
index 6cb226c..cfba552 100644
--- a/Swiften/Serializer/PayloadSerializers/PrivateStorageSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/PrivateStorageSerializer.cpp
@@ -1,34 +1,35 @@
/*
* Copyright (c) 2010 Remko Tronçon
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/PrivateStorageSerializer.h>
#include <boost/shared_ptr.hpp>
+#include <boost/smart_ptr/make_shared.hpp>
#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLTextNode.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
#include <Swiften/Serializer/PayloadSerializerCollection.h>
namespace Swift {
PrivateStorageSerializer::PrivateStorageSerializer(PayloadSerializerCollection* serializers) : serializers(serializers) {
}
std::string PrivateStorageSerializer::serializePayload(boost::shared_ptr<PrivateStorage> storage) const {
XMLElement storageElement("query", "jabber:iq:private");
boost::shared_ptr<Payload> payload = storage->getPayload();
if (payload) {
PayloadSerializer* serializer = serializers->getPayloadSerializer(payload);
if (serializer) {
- storageElement.addNode(boost::shared_ptr<XMLRawTextNode>(new XMLRawTextNode(serializer->serialize(payload))));
+ storageElement.addNode(boost::make_shared<XMLRawTextNode>(serializer->serialize(payload)));
}
}
return storageElement.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/ResourceBindSerializer.cpp b/Swiften/Serializer/PayloadSerializers/ResourceBindSerializer.cpp
index af0c609..c72734b 100644
--- a/Swiften/Serializer/PayloadSerializers/ResourceBindSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/ResourceBindSerializer.cpp
@@ -1,34 +1,35 @@
/*
* Copyright (c) 2010 Remko Tronçon
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/ResourceBindSerializer.h>
#include <boost/shared_ptr.hpp>
+#include <boost/smart_ptr/make_shared.hpp>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLTextNode.h>
namespace Swift {
ResourceBindSerializer::ResourceBindSerializer() : GenericPayloadSerializer<ResourceBind>() {
}
std::string ResourceBindSerializer::serializePayload(boost::shared_ptr<ResourceBind> resourceBind) const {
XMLElement bindElement("bind", "urn:ietf:params:xml:ns:xmpp-bind");
if (resourceBind->getJID().isValid()) {
boost::shared_ptr<XMLElement> jidNode(new XMLElement("jid"));
- jidNode->addNode(boost::shared_ptr<XMLTextNode>(new XMLTextNode(resourceBind->getJID().toString())));
+ jidNode->addNode(boost::make_shared<XMLTextNode>(resourceBind->getJID().toString()));
bindElement.addNode(jidNode);
}
else if (!resourceBind->getResource().empty()) {
boost::shared_ptr<XMLElement> resourceNode(new XMLElement("resource"));
- resourceNode->addNode(boost::shared_ptr<XMLTextNode>(new XMLTextNode(resourceBind->getResource())));
+ resourceNode->addNode(boost::make_shared<XMLTextNode>(resourceBind->getResource()));
bindElement.addNode(resourceNode);
}
return bindElement.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/RosterItemExchangeSerializer.cpp b/Swiften/Serializer/PayloadSerializers/RosterItemExchangeSerializer.cpp
index b60db12..39eaf7d 100644
--- a/Swiften/Serializer/PayloadSerializers/RosterItemExchangeSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/RosterItemExchangeSerializer.cpp
@@ -1,46 +1,47 @@
/*
* Copyright (c) 2011 Jan Kaluza
* Licensed under the Simplified BSD license.
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/RosterItemExchangeSerializer.h>
#include <boost/shared_ptr.hpp>
+#include <boost/smart_ptr/make_shared.hpp>
#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/XML/XMLTextNode.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
#include <Swiften/Serializer/XML/XMLElement.h>
namespace Swift {
RosterItemExchangeSerializer::RosterItemExchangeSerializer() : GenericPayloadSerializer<RosterItemExchangePayload>() {
}
std::string RosterItemExchangeSerializer::serializePayload(boost::shared_ptr<RosterItemExchangePayload> roster) const {
XMLElement queryElement("x", "http://jabber.org/protocol/rosterx");
foreach(const RosterItemExchangePayload::Item& item, roster->getItems()) {
boost::shared_ptr<XMLElement> itemElement(new XMLElement("item"));
itemElement->setAttribute("jid", item.getJID());
itemElement->setAttribute("name", item.getName());
switch (item.getAction()) {
case RosterItemExchangePayload::Item::Add: itemElement->setAttribute("action", "add"); break;
case RosterItemExchangePayload::Item::Modify: itemElement->setAttribute("action", "modify"); break;
case RosterItemExchangePayload::Item::Delete: itemElement->setAttribute("action", "delete"); break;
}
foreach(const std::string& group, item.getGroups()) {
boost::shared_ptr<XMLElement> groupElement(new XMLElement("group"));
- groupElement->addNode(boost::shared_ptr<XMLTextNode>(new XMLTextNode(group)));
+ groupElement->addNode(boost::make_shared<XMLTextNode>(group));
itemElement->addNode(groupElement);
}
queryElement.addNode(itemElement);
}
return queryElement.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/RosterSerializer.cpp b/Swiften/Serializer/PayloadSerializers/RosterSerializer.cpp
index 84f36d2..d2d143d 100644
--- a/Swiften/Serializer/PayloadSerializers/RosterSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/RosterSerializer.cpp
@@ -1,60 +1,61 @@
/*
* Copyright (c) 2010 Remko Tronçon
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/RosterSerializer.h>
#include <boost/shared_ptr.hpp>
+#include <boost/smart_ptr/make_shared.hpp>
#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/XML/XMLTextNode.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
#include <Swiften/Serializer/XML/XMLElement.h>
namespace Swift {
RosterSerializer::RosterSerializer() : GenericPayloadSerializer<RosterPayload>() {
}
std::string RosterSerializer::serializePayload(boost::shared_ptr<RosterPayload> roster) const {
XMLElement queryElement("query", "jabber:iq:roster");
if (roster->getVersion()) {
queryElement.setAttribute("ver", *roster->getVersion());
}
foreach(const RosterItemPayload& item, roster->getItems()) {
boost::shared_ptr<XMLElement> itemElement(new XMLElement("item"));
itemElement->setAttribute("jid", item.getJID());
itemElement->setAttribute("name", item.getName());
switch (item.getSubscription()) {
case RosterItemPayload::To: itemElement->setAttribute("subscription", "to"); break;
case RosterItemPayload::From: itemElement->setAttribute("subscription", "from"); break;
case RosterItemPayload::Both: itemElement->setAttribute("subscription", "both"); break;
case RosterItemPayload::Remove: itemElement->setAttribute("subscription", "remove"); break;
case RosterItemPayload::None: itemElement->setAttribute("subscription", "none"); break;
}
if (item.getSubscriptionRequested()) {
itemElement->setAttribute("ask", "subscribe");
}
foreach(const std::string& group, item.getGroups()) {
boost::shared_ptr<XMLElement> groupElement(new XMLElement("group"));
- groupElement->addNode(boost::shared_ptr<XMLTextNode>(new XMLTextNode(group)));
+ groupElement->addNode(boost::make_shared<XMLTextNode>(group));
itemElement->addNode(groupElement);
}
if (!item.getUnknownContent().empty()) {
- itemElement->addNode(boost::shared_ptr<XMLRawTextNode>(new XMLRawTextNode(item.getUnknownContent())));
+ itemElement->addNode(boost::make_shared<XMLRawTextNode>(item.getUnknownContent()));
}
queryElement.addNode(itemElement);
}
return queryElement.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/SearchPayloadSerializer.cpp b/Swiften/Serializer/PayloadSerializers/SearchPayloadSerializer.cpp
index a5cd634..07dd8de 100644
--- a/Swiften/Serializer/PayloadSerializers/SearchPayloadSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/SearchPayloadSerializer.cpp
@@ -1,62 +1,63 @@
/*
* Copyright (c) 2010 Remko Tronçon
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/SearchPayloadSerializer.h>
#include <boost/shared_ptr.hpp>
+#include <boost/smart_ptr/make_shared.hpp>
#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
#include <Swiften/Serializer/PayloadSerializers/FormSerializer.h>
namespace Swift {
SearchPayloadSerializer::SearchPayloadSerializer() {
}
std::string SearchPayloadSerializer::serializePayload(boost::shared_ptr<SearchPayload> searchPayload) const {
XMLElement searchElement("query", "jabber:iq:search");
if (searchPayload->getInstructions()) {
searchElement.addNode(XMLElement::ref(new XMLElement("instructions", "", *searchPayload->getInstructions())));
}
if (searchPayload->getNick()) {
searchElement.addNode(XMLElement::ref(new XMLElement("nick", "", *searchPayload->getNick())));
}
if (searchPayload->getFirst()) {
searchElement.addNode(XMLElement::ref(new XMLElement("first", "", *searchPayload->getFirst())));
}
if (searchPayload->getLast()) {
searchElement.addNode(XMLElement::ref(new XMLElement("last", "", *searchPayload->getLast())));
}
if (searchPayload->getEMail()) {
searchElement.addNode(XMLElement::ref(new XMLElement("email", "", *searchPayload->getEMail())));
}
foreach(const SearchPayload::Item& item, searchPayload->getItems()) {
XMLElement::ref itemElement(new XMLElement("item"));
itemElement->setAttribute("jid", item.jid);
itemElement->addNode(XMLElement::ref(new XMLElement("first", "", item.first)));
itemElement->addNode(XMLElement::ref(new XMLElement("last", "", item.last)));
itemElement->addNode(XMLElement::ref(new XMLElement("nick", "", item.nick)));
itemElement->addNode(XMLElement::ref(new XMLElement("email", "", item.email)));
searchElement.addNode(itemElement);
}
if (Form::ref form = searchPayload->getForm()) {
- searchElement.addNode(boost::shared_ptr<XMLRawTextNode>(new XMLRawTextNode(FormSerializer().serialize(form))));
+ searchElement.addNode(boost::make_shared<XMLRawTextNode>(FormSerializer().serialize(form)));
}
return searchElement.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/SecurityLabelSerializer.cpp b/Swiften/Serializer/PayloadSerializers/SecurityLabelSerializer.cpp
index 51079ee..7a0b513 100644
--- a/Swiften/Serializer/PayloadSerializers/SecurityLabelSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/SecurityLabelSerializer.cpp
@@ -1,44 +1,46 @@
/*
* Copyright (c) 2010 Remko Tronçon
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
+#include <boost/smart_ptr/make_shared.hpp>
+
#include <Swiften/Serializer/PayloadSerializers/SecurityLabelSerializer.h>
#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
#include <Swiften/Serializer/XML/XMLTextNode.h>
#include <Swiften/Serializer/XML/XMLElement.h>
namespace Swift {
SecurityLabelSerializer::SecurityLabelSerializer() : GenericPayloadSerializer<SecurityLabel>() {
}
std::string SecurityLabelSerializer::serializePayload(boost::shared_ptr<SecurityLabel> label) const {
XMLElement element("securitylabel", "urn:xmpp:sec-label:0");
if (!label->getDisplayMarking().empty()) {
boost::shared_ptr<XMLElement> displayMarking(new XMLElement("displaymarking"));
if (!label->getForegroundColor().empty()) {
displayMarking->setAttribute("fgcolor", label->getForegroundColor());
}
if (!label->getBackgroundColor().empty()) {
displayMarking->setAttribute("bgcolor", label->getBackgroundColor());
}
- displayMarking->addNode(boost::shared_ptr<XMLTextNode>(new XMLTextNode(label->getDisplayMarking())));
+ displayMarking->addNode(boost::make_shared<XMLTextNode>(label->getDisplayMarking()));
element.addNode(displayMarking);
}
boost::shared_ptr<XMLElement> labelElement(new XMLElement("label"));
- labelElement->addNode(boost::shared_ptr<XMLRawTextNode>(new XMLRawTextNode(label->getLabel())));
+ labelElement->addNode(boost::make_shared<XMLRawTextNode>(label->getLabel()));
element.addNode(labelElement);
foreach(const std::string& equivalentLabel, label->getEquivalentLabels()) {
boost::shared_ptr<XMLElement> equivalentLabelElement(new XMLElement("equivalentlabel"));
- equivalentLabelElement->addNode(boost::shared_ptr<XMLRawTextNode>(new XMLRawTextNode(equivalentLabel)));
+ equivalentLabelElement->addNode(boost::make_shared<XMLRawTextNode>(equivalentLabel));
element.addNode(equivalentLabelElement);
}
return element.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/SecurityLabelsCatalogSerializer.cpp b/Swiften/Serializer/PayloadSerializers/SecurityLabelsCatalogSerializer.cpp
index 1078292..8871eff 100644
--- a/Swiften/Serializer/PayloadSerializers/SecurityLabelsCatalogSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/SecurityLabelsCatalogSerializer.cpp
@@ -1,44 +1,46 @@
/*
* Copyright (c) 2010 Remko Tronçon
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
+#include <boost/smart_ptr/make_shared.hpp>
+
#include <Swiften/Serializer/PayloadSerializers/SecurityLabelsCatalogSerializer.h>
#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
#include <Swiften/Serializer/PayloadSerializers/SecurityLabelSerializer.h>
namespace Swift {
SecurityLabelsCatalogSerializer::SecurityLabelsCatalogSerializer() : GenericPayloadSerializer<SecurityLabelsCatalog>() {
}
std::string SecurityLabelsCatalogSerializer::serializePayload(boost::shared_ptr<SecurityLabelsCatalog> catalog) const {
XMLElement element("catalog", "urn:xmpp:sec-label:catalog:2");
if (!catalog->getName().empty()) {
element.setAttribute("name", catalog->getName());
}
if (catalog->getTo().isValid()) {
element.setAttribute("to", catalog->getTo());
}
if (!catalog->getDescription().empty()) {
element.setAttribute("desc", catalog->getDescription());
}
foreach (const SecurityLabelsCatalog::Item& item, catalog->getItems()) {
boost::shared_ptr<XMLElement> itemElement(new XMLElement("item"));
itemElement->setAttribute("selector", item.getSelector());
if (item.getIsDefault()) {
itemElement->setAttribute("default", "true");
}
if (item.getLabel()) {
std::string serializedLabel = SecurityLabelSerializer().serialize(item.getLabel());
- itemElement->addNode(boost::shared_ptr<XMLRawTextNode>(new XMLRawTextNode(serializedLabel)));
+ itemElement->addNode(boost::make_shared<XMLRawTextNode>(serializedLabel));
}
element.addNode(itemElement);
}
return element.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/StatusSerializer.h b/Swiften/Serializer/PayloadSerializers/StatusSerializer.h
index a8de26f..bd076ae 100644
--- a/Swiften/Serializer/PayloadSerializers/StatusSerializer.h
+++ b/Swiften/Serializer/PayloadSerializers/StatusSerializer.h
@@ -1,25 +1,27 @@
/*
* Copyright (c) 2010 Remko Tronçon
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
#pragma once
+#include <boost/smart_ptr/make_shared.hpp>
+
#include <Swiften/Serializer/GenericPayloadSerializer.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLTextNode.h>
#include <Swiften/Elements/Status.h>
namespace Swift {
class StatusSerializer : public GenericPayloadSerializer<Status> {
public:
StatusSerializer() : GenericPayloadSerializer<Status>() {}
virtual std::string serializePayload(boost::shared_ptr<Status> status) const {
XMLElement element("status");
- element.addNode(boost::shared_ptr<XMLTextNode>(new XMLTextNode(status->getText())));
+ element.addNode(boost::make_shared<XMLTextNode>(status->getText()));
return element.serialize();
}
};
}
diff --git a/Swiften/Serializer/PayloadSerializers/StorageSerializer.cpp b/Swiften/Serializer/PayloadSerializers/StorageSerializer.cpp
index 77fb3c0..296d5dd 100644
--- a/Swiften/Serializer/PayloadSerializers/StorageSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/StorageSerializer.cpp
@@ -1,51 +1,52 @@
/*
* Copyright (c) 2010 Remko Tronçon
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/StorageSerializer.h>
#include <boost/shared_ptr.hpp>
+#include <boost/smart_ptr/make_shared.hpp>
#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLTextNode.h>
namespace Swift {
StorageSerializer::StorageSerializer() : GenericPayloadSerializer<Storage>() {
}
std::string StorageSerializer::serializePayload(boost::shared_ptr<Storage> storage) const {
XMLElement storageElement("storage", "storage:bookmarks");
foreach(const Storage::Room& room, storage->getRooms()) {
boost::shared_ptr<XMLElement> conferenceElement(new XMLElement("conference"));
conferenceElement->setAttribute("name", room.name);
conferenceElement->setAttribute("jid", room.jid);
conferenceElement->setAttribute("autojoin", room.autoJoin ? "1" : "0");
if (!room.nick.empty()) {
boost::shared_ptr<XMLElement> nickElement(new XMLElement("nick"));
- nickElement->addNode(boost::shared_ptr<XMLTextNode>(new XMLTextNode(room.nick)));
+ nickElement->addNode(boost::make_shared<XMLTextNode>(room.nick));
conferenceElement->addNode(nickElement);
}
if (room.password) {
boost::shared_ptr<XMLElement> passwordElement(new XMLElement("password"));
- passwordElement->addNode(boost::shared_ptr<XMLTextNode>(new XMLTextNode(*room.password)));
+ passwordElement->addNode(boost::make_shared<XMLTextNode>(*room.password));
conferenceElement->addNode(passwordElement);
}
storageElement.addNode(conferenceElement);
}
foreach(const Storage::URL& url, storage->getURLs()) {
boost::shared_ptr<XMLElement> urlElement(new XMLElement("url"));
urlElement->setAttribute("name", url.name);
urlElement->setAttribute("url", url.url);
storageElement.addNode(urlElement);
}
return storageElement.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/StreamInitiationSerializer.cpp b/Swiften/Serializer/PayloadSerializers/StreamInitiationSerializer.cpp
index 9ccfab2..030b024 100644
--- a/Swiften/Serializer/PayloadSerializers/StreamInitiationSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/StreamInitiationSerializer.cpp
@@ -1,73 +1,74 @@
/*
* Copyright (c) 2010 Remko Tronçon
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/StreamInitiationSerializer.h>
#include <boost/shared_ptr.hpp>
+#include <boost/smart_ptr/make_shared.hpp>
#include <boost/lexical_cast.hpp>
#include <Swiften/Base/foreach.h>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLTextNode.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
#include <Swiften/Serializer/PayloadSerializers/FormSerializer.h>
#define FILE_TRANSFER_NS "http://jabber.org/protocol/si/profile/file-transfer"
#define FEATURE_NEG_NS "http://jabber.org/protocol/feature-neg"
namespace Swift {
StreamInitiationSerializer::StreamInitiationSerializer() {
}
std::string StreamInitiationSerializer::serializePayload(boost::shared_ptr<StreamInitiation> streamInitiation) const {
assert(streamInitiation->getIsFileTransfer());
XMLElement siElement("si", "http://jabber.org/protocol/si");
if (!streamInitiation->getID().empty()) {
siElement.setAttribute("id", streamInitiation->getID());
}
siElement.setAttribute("profile", FILE_TRANSFER_NS);
if (streamInitiation->getFileInfo()) {
StreamInitiationFileInfo file = *streamInitiation->getFileInfo();
boost::shared_ptr<XMLElement> fileElement(new XMLElement("file", "http://jabber.org/protocol/si/profile/file-transfer"));
fileElement->setAttribute("name", file.getName());
if (file.getSize() != 0) {
fileElement->setAttribute("size", boost::lexical_cast<std::string>(file.getSize()));
}
if (!file.getDescription().empty()) {
boost::shared_ptr<XMLElement> descElement(new XMLElement("desc"));
- descElement->addNode(boost::shared_ptr<XMLTextNode>(new XMLTextNode(file.getDescription())));
+ descElement->addNode(boost::make_shared<XMLTextNode>(file.getDescription()));
fileElement->addNode(descElement);
}
siElement.addNode(fileElement);
}
boost::shared_ptr<XMLElement> featureElement(new XMLElement("feature", FEATURE_NEG_NS));
if (streamInitiation->getProvidedMethods().size() > 0) {
Form::ref form(new Form(Form::FormType));
ListSingleFormField::ref field = ListSingleFormField::create();
field->setName("stream-method");
foreach(const std::string& method, streamInitiation->getProvidedMethods()) {
field->addOption(FormField::Option("", method));
}
form->addField(field);
- featureElement->addNode(boost::shared_ptr<XMLRawTextNode>(new XMLRawTextNode(FormSerializer().serialize(form))));
+ featureElement->addNode(boost::make_shared<XMLRawTextNode>(FormSerializer().serialize(form)));
}
else if (!streamInitiation->getRequestedMethod().empty()) {
Form::ref form(new Form(Form::SubmitType));
ListSingleFormField::ref field = ListSingleFormField::create(streamInitiation->getRequestedMethod());
field->setName("stream-method");
form->addField(field);
- featureElement->addNode(boost::shared_ptr<XMLRawTextNode>(new XMLRawTextNode(FormSerializer().serialize(form))));
+ featureElement->addNode(boost::make_shared<XMLRawTextNode>(FormSerializer().serialize(form)));
}
siElement.addNode(featureElement);
return siElement.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/VCardSerializer.cpp b/Swiften/Serializer/PayloadSerializers/VCardSerializer.cpp
index 17a6b49..1512c6c 100644
--- a/Swiften/Serializer/PayloadSerializers/VCardSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/VCardSerializer.cpp
@@ -1,110 +1,111 @@
/*
* Copyright (c) 2010 Remko Tronçon
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/VCardSerializer.h>
#include <boost/shared_ptr.hpp>
+#include <boost/smart_ptr/make_shared.hpp>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLTextNode.h>
#include <Swiften/Serializer/XML/XMLRawTextNode.h>
#include <Swiften/StringCodecs/Base64.h>
#include <Swiften/Base/foreach.h>
namespace Swift {
VCardSerializer::VCardSerializer() : GenericPayloadSerializer<VCard>() {
}
std::string VCardSerializer::serializePayload(boost::shared_ptr<VCard> vcard) const {
XMLElement queryElement("vCard", "vcard-temp");
if (!vcard->getVersion().empty()) {
boost::shared_ptr<XMLElement> versionElement(new XMLElement("VERSION"));
- versionElement->addNode(boost::shared_ptr<XMLTextNode>(new XMLTextNode(vcard->getVersion())));
+ versionElement->addNode(boost::make_shared<XMLTextNode>(vcard->getVersion()));
queryElement.addNode(versionElement);
}
if (!vcard->getFullName().empty()) {
boost::shared_ptr<XMLElement> fullNameElement(new XMLElement("FN"));
- fullNameElement->addNode(boost::shared_ptr<XMLTextNode>(new XMLTextNode(vcard->getFullName())));
+ fullNameElement->addNode(boost::make_shared<XMLTextNode>(vcard->getFullName()));
queryElement.addNode(fullNameElement);
}
if (!vcard->getGivenName().empty() || !vcard->getFamilyName().empty() || !vcard->getMiddleName().empty() || !vcard->getPrefix().empty() || !vcard->getSuffix().empty()) {
boost::shared_ptr<XMLElement> nameElement(new XMLElement("N"));
if (!vcard->getFamilyName().empty()) {
boost::shared_ptr<XMLElement> familyNameElement(new XMLElement("FAMILY"));
- familyNameElement->addNode(boost::shared_ptr<XMLTextNode>(new XMLTextNode(vcard->getFamilyName())));
+ familyNameElement->addNode(boost::make_shared<XMLTextNode>(vcard->getFamilyName()));
nameElement->addNode(familyNameElement);
}
if (!vcard->getGivenName().empty()) {
boost::shared_ptr<XMLElement> givenNameElement(new XMLElement("GIVEN"));
- givenNameElement->addNode(boost::shared_ptr<XMLTextNode>(new XMLTextNode(vcard->getGivenName())));
+ givenNameElement->addNode(boost::make_shared<XMLTextNode>(vcard->getGivenName()));
nameElement->addNode(givenNameElement);
}
if (!vcard->getMiddleName().empty()) {
boost::shared_ptr<XMLElement> middleNameElement(new XMLElement("MIDDLE"));
- middleNameElement->addNode(boost::shared_ptr<XMLTextNode>(new XMLTextNode(vcard->getMiddleName())));
+ middleNameElement->addNode(boost::make_shared<XMLTextNode>(vcard->getMiddleName()));
nameElement->addNode(middleNameElement);
}
if (!vcard->getPrefix().empty()) {
boost::shared_ptr<XMLElement> prefixElement(new XMLElement("PREFIX"));
- prefixElement->addNode(boost::shared_ptr<XMLTextNode>(new XMLTextNode(vcard->getPrefix())));
+ prefixElement->addNode(boost::make_shared<XMLTextNode>(vcard->getPrefix()));
nameElement->addNode(prefixElement);
}
if (!vcard->getSuffix().empty()) {
boost::shared_ptr<XMLElement> suffixElement(new XMLElement("SUFFIX"));
- suffixElement->addNode(boost::shared_ptr<XMLTextNode>(new XMLTextNode(vcard->getSuffix())));
+ suffixElement->addNode(boost::make_shared<XMLTextNode>(vcard->getSuffix()));
nameElement->addNode(suffixElement);
}
queryElement.addNode(nameElement);
}
foreach(const VCard::EMailAddress& emailAddress, vcard->getEMailAddresses()) {
boost::shared_ptr<XMLElement> emailElement(new XMLElement("EMAIL"));
boost::shared_ptr<XMLElement> userIDElement(new XMLElement("USERID"));
- userIDElement->addNode(boost::shared_ptr<XMLTextNode>(new XMLTextNode(emailAddress.address)));
+ userIDElement->addNode(boost::make_shared<XMLTextNode>(emailAddress.address));
emailElement->addNode(userIDElement);
if (emailAddress.isHome) {
- emailElement->addNode(boost::shared_ptr<XMLElement>(new XMLElement("HOME")));
+ emailElement->addNode(boost::make_shared<XMLElement>("HOME"));
}
if (emailAddress.isWork) {
- emailElement->addNode(boost::shared_ptr<XMLElement>(new XMLElement("WORK")));
+ emailElement->addNode(boost::make_shared<XMLElement>("WORK"));
}
if (emailAddress.isInternet) {
- emailElement->addNode(boost::shared_ptr<XMLElement>(new XMLElement("INTERNET")));
+ emailElement->addNode(boost::make_shared<XMLElement>("INTERNET"));
}
if (emailAddress.isPreferred) {
- emailElement->addNode(boost::shared_ptr<XMLElement>(new XMLElement("PREF")));
+ emailElement->addNode(boost::make_shared<XMLElement>("PREF"));
}
if (emailAddress.isX400) {
- emailElement->addNode(boost::shared_ptr<XMLElement>(new XMLElement("X400")));
+ emailElement->addNode(boost::make_shared<XMLElement>("X400"));
}
queryElement.addNode(emailElement);
}
if (!vcard->getNickname().empty()) {
boost::shared_ptr<XMLElement> nickElement(new XMLElement("NICKNAME"));
- nickElement->addNode(boost::shared_ptr<XMLTextNode>(new XMLTextNode(vcard->getNickname())));
+ nickElement->addNode(boost::make_shared<XMLTextNode>(vcard->getNickname()));
queryElement.addNode(nickElement);
}
if (!vcard->getPhoto().empty() || !vcard->getPhotoType().empty()) {
XMLElement::ref photoElement(new XMLElement("PHOTO"));
if (!vcard->getPhotoType().empty()) {
XMLElement::ref typeElement(new XMLElement("TYPE"));
typeElement->addNode(XMLTextNode::ref(new XMLTextNode(vcard->getPhotoType())));
photoElement->addNode(typeElement);
}
if (!vcard->getPhoto().empty()) {
XMLElement::ref binvalElement(new XMLElement("BINVAL"));
binvalElement->addNode(XMLTextNode::ref(new XMLTextNode(Base64::encode(vcard->getPhoto()))));
photoElement->addNode(binvalElement);
}
queryElement.addNode(photoElement);
}
if (!vcard->getUnknownContent().empty()) {
- queryElement.addNode(boost::shared_ptr<XMLRawTextNode>(new XMLRawTextNode(vcard->getUnknownContent())));
+ queryElement.addNode(boost::make_shared<XMLRawTextNode>(vcard->getUnknownContent()));
}
return queryElement.serialize();
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/VCardUpdateSerializer.cpp b/Swiften/Serializer/PayloadSerializers/VCardUpdateSerializer.cpp
index c06262f..78c700b 100644
--- a/Swiften/Serializer/PayloadSerializers/VCardUpdateSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/VCardUpdateSerializer.cpp
@@ -1,27 +1,28 @@
/*
* Copyright (c) 2010 Remko Tronçon
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
#include <Swiften/Serializer/PayloadSerializers/VCardUpdateSerializer.h>
#include <boost/shared_ptr.hpp>
+#include <boost/smart_ptr/make_shared.hpp>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLTextNode.h>
namespace Swift {
VCardUpdateSerializer::VCardUpdateSerializer() : GenericPayloadSerializer<VCardUpdate>() {
}
std::string VCardUpdateSerializer::serializePayload(boost::shared_ptr<VCardUpdate> vcardUpdate) const {
XMLElement updateElement("x", "vcard-temp:x:update");
boost::shared_ptr<XMLElement> photoElement(new XMLElement("photo"));
- photoElement->addNode(boost::shared_ptr<XMLTextNode>(new XMLTextNode(vcardUpdate->getPhotoHash())));
+ photoElement->addNode(boost::make_shared<XMLTextNode>(vcardUpdate->getPhotoHash()));
updateElement.addNode(photoElement);
return updateElement.serialize();
}
}
diff --git a/Swiften/Serializer/StreamFeaturesSerializer.cpp b/Swiften/Serializer/StreamFeaturesSerializer.cpp
index fb7bb8c..2344349 100644
--- a/Swiften/Serializer/StreamFeaturesSerializer.cpp
+++ b/Swiften/Serializer/StreamFeaturesSerializer.cpp
@@ -1,60 +1,60 @@
/*
* Copyright (c) 2010 Remko Tronçon
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
#include <Swiften/Serializer/StreamFeaturesSerializer.h>
#include <boost/smart_ptr/make_shared.hpp>
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLTextNode.h>
#include <Swiften/Base/foreach.h>
namespace Swift {
StreamFeaturesSerializer::StreamFeaturesSerializer() {
}
SafeByteArray StreamFeaturesSerializer::serialize(boost::shared_ptr<Element> element) const {
boost::shared_ptr<StreamFeatures> streamFeatures(boost::dynamic_pointer_cast<StreamFeatures>(element));
XMLElement streamFeaturesElement("stream:features");
if (streamFeatures->hasStartTLS()) {
- streamFeaturesElement.addNode(boost::shared_ptr<XMLElement>(new XMLElement("starttls", "urn:ietf:params:xml:ns:xmpp-tls")));
+ streamFeaturesElement.addNode(boost::make_shared<XMLElement>("starttls", "urn:ietf:params:xml:ns:xmpp-tls"));
}
if (!streamFeatures->getCompressionMethods().empty()) {
boost::shared_ptr<XMLElement> compressionElement(new XMLElement("compression", "http://jabber.org/features/compress"));
foreach(const std::string& method, streamFeatures->getCompressionMethods()) {
boost::shared_ptr<XMLElement> methodElement(new XMLElement("method"));
- methodElement->addNode(boost::shared_ptr<XMLTextNode>(new XMLTextNode(method)));
+ methodElement->addNode(boost::make_shared<XMLTextNode>(method));
compressionElement->addNode(methodElement);
}
streamFeaturesElement.addNode(compressionElement);
}
if (!streamFeatures->getAuthenticationMechanisms().empty()) {
boost::shared_ptr<XMLElement> mechanismsElement(new XMLElement("mechanisms", "urn:ietf:params:xml:ns:xmpp-sasl"));
foreach(const std::string& mechanism, streamFeatures->getAuthenticationMechanisms()) {
boost::shared_ptr<XMLElement> mechanismElement(new XMLElement("mechanism"));
- mechanismElement->addNode(boost::shared_ptr<XMLTextNode>(new XMLTextNode(mechanism)));
+ mechanismElement->addNode(boost::make_shared<XMLTextNode>(mechanism));
mechanismsElement->addNode(mechanismElement);
}
streamFeaturesElement.addNode(mechanismsElement);
}
if (streamFeatures->hasResourceBind()) {
- streamFeaturesElement.addNode(boost::shared_ptr<XMLElement>(new XMLElement("bind", "urn:ietf:params:xml:ns:xmpp-bind")));
+ streamFeaturesElement.addNode(boost::make_shared<XMLElement>("bind", "urn:ietf:params:xml:ns:xmpp-bind"));
}
if (streamFeatures->hasSession()) {
- streamFeaturesElement.addNode(boost::shared_ptr<XMLElement>(new XMLElement("session", "urn:ietf:params:xml:ns:xmpp-session")));
+ streamFeaturesElement.addNode(boost::make_shared<XMLElement>("session", "urn:ietf:params:xml:ns:xmpp-session"));
}
if (streamFeatures->hasStreamManagement()) {
- streamFeaturesElement.addNode(boost::shared_ptr<XMLElement>(new XMLElement("sm", "urn:xmpp:sm:2")));
+ streamFeaturesElement.addNode(boost::make_shared<XMLElement>("sm", "urn:xmpp:sm:2"));
}
if (streamFeatures->hasRosterVersioning()) {
streamFeaturesElement.addNode(boost::make_shared<XMLElement>("ver", "urn:xmpp:features:rosterver"));
}
return createSafeByteArray(streamFeaturesElement.serialize());
}
}
diff --git a/Swiften/Serializer/XML/UnitTest/XMLElementTest.cpp b/Swiften/Serializer/XML/UnitTest/XMLElementTest.cpp
index b70128b..a2197b0 100644
--- a/Swiften/Serializer/XML/UnitTest/XMLElementTest.cpp
+++ b/Swiften/Serializer/XML/UnitTest/XMLElementTest.cpp
@@ -1,68 +1,70 @@
/*
* Copyright (c) 2010 Remko Tronçon
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
+#include <boost/smart_ptr/make_shared.hpp>
+
#include <Swiften/Serializer/XML/XMLElement.h>
#include <Swiften/Serializer/XML/XMLTextNode.h>
using namespace Swift;
class XMLElementTest : public CppUnit::TestFixture
{
CPPUNIT_TEST_SUITE(XMLElementTest);
CPPUNIT_TEST(testSerialize);
CPPUNIT_TEST(testSerialize_NoChildren);
CPPUNIT_TEST(testSerialize_SpecialAttributeCharacters);
CPPUNIT_TEST(testSerialize_EmptyAttributeValue);
CPPUNIT_TEST_SUITE_END();
public:
XMLElementTest() {}
void testSerialize() {
XMLElement testling("foo", "http://example.com");
testling.setAttribute("myatt", "myval");
boost::shared_ptr<XMLElement> barElement(new XMLElement("bar"));
- barElement->addNode(boost::shared_ptr<XMLTextNode>(new XMLTextNode("Blo")));
+ barElement->addNode(boost::make_shared<XMLTextNode>("Blo"));
testling.addNode(barElement);
boost::shared_ptr<XMLElement> bazElement(new XMLElement("baz"));
- bazElement->addNode(boost::shared_ptr<XMLTextNode>(new XMLTextNode("Bli&</stream>")));
+ bazElement->addNode(boost::make_shared<XMLTextNode>("Bli&</stream>"));
testling.addNode(bazElement);
std::string result = testling.serialize();
std::string expectedResult =
"<foo myatt=\"myval\" xmlns=\"http://example.com\">"
"<bar>Blo</bar>"
"<baz>Bli&amp;&lt;/stream&gt;</baz>"
"</foo>";
CPPUNIT_ASSERT_EQUAL(expectedResult, result);
}
void testSerialize_NoChildren() {
XMLElement testling("foo", "http://example.com");
CPPUNIT_ASSERT_EQUAL(std::string("<foo xmlns=\"http://example.com\"/>"), testling.serialize());
}
void testSerialize_SpecialAttributeCharacters() {
XMLElement testling("foo");
testling.setAttribute("myatt", "<\"'&>");
CPPUNIT_ASSERT_EQUAL(std::string("<foo myatt=\"&lt;&quot;&apos;&amp;&gt;\"/>"), testling.serialize());
}
void testSerialize_EmptyAttributeValue() {
XMLElement testling("foo");
testling.setAttribute("myatt", "");
CPPUNIT_ASSERT_EQUAL(std::string("<foo myatt=\"\"/>"), testling.serialize());
}
};
CPPUNIT_TEST_SUITE_REGISTRATION(XMLElementTest);
diff --git a/Swiften/Session/BOSHSessionStream.cpp b/Swiften/Session/BOSHSessionStream.cpp
index d706d43..ce5df35 100644
--- a/Swiften/Session/BOSHSessionStream.cpp
+++ b/Swiften/Session/BOSHSessionStream.cpp
@@ -131,71 +131,71 @@ Certificate::ref BOSHSessionStream::getPeerCertificate() const {
boost::shared_ptr<CertificateVerificationError> BOSHSessionStream::getPeerCertificateVerificationError() const {
return boost::shared_ptr<CertificateVerificationError>();
}
ByteArray BOSHSessionStream::getTLSFinishMessage() const {
return ByteArray();
}
bool BOSHSessionStream::supportsZLibCompression() {
return false;
}
void BOSHSessionStream::addZLibCompression() {
}
void BOSHSessionStream::setWhitespacePingEnabled(bool /*enabled*/) {
return;
}
void BOSHSessionStream::resetXMPPParser() {
xmppLayer->resetParser();
}
void BOSHSessionStream::handleStreamStartReceived(const ProtocolHeader& header) {
onStreamStartReceived(header);
}
void BOSHSessionStream::handleElementReceived(boost::shared_ptr<Element> element) {
onElementReceived(element);
}
void BOSHSessionStream::handleXMPPError() {
available = false;
- onClosed(boost::shared_ptr<Error>(new Error(Error::ParseError)));
+ onClosed(boost::make_shared<Error>(Error::ParseError));
}
void BOSHSessionStream::handlePoolSessionStarted() {
fakeStreamHeaderReceipt();
}
void BOSHSessionStream::handlePoolSessionTerminated(BOSHError::ref error) {
eventLoop->postEvent(boost::bind(&BOSHSessionStream::fakeStreamFooterReceipt, this, error), shared_from_this());
}
void BOSHSessionStream::writeHeader(const ProtocolHeader& header) {
streamHeader = header;
/*First time we're told to do this, don't (the sending of the initial header is handled on connect)
On subsequent requests we should restart the stream the BOSH way.
*/
if (!firstHeader) {
eventLoop->postEvent(boost::bind(&BOSHSessionStream::fakeStreamHeaderReceipt, this), shared_from_this());
eventLoop->postEvent(boost::bind(&BOSHConnectionPool::restartStream, connectionPool), shared_from_this());
}
firstHeader = false;
}
void BOSHSessionStream::fakeStreamHeaderReceipt() {
std::stringstream header;
header << "<stream:stream xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' from='";
header << streamHeader.getTo() << "' id='dummy' version='1.0'>";
xmppLayer->handleDataRead(createSafeByteArray(header.str()));
}
void BOSHSessionStream::fakeStreamFooterReceipt(BOSHError::ref error) {
std::string footer("</stream:stream>");
xmppLayer->handleDataRead(createSafeByteArray(footer));
onClosed(error);
diff --git a/Swiften/Session/BasicSessionStream.cpp b/Swiften/Session/BasicSessionStream.cpp
index 70bbeea..f50c5d5 100644
--- a/Swiften/Session/BasicSessionStream.cpp
+++ b/Swiften/Session/BasicSessionStream.cpp
@@ -1,44 +1,45 @@
/*
* Copyright (c) 2010 Remko Tronçon
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
#include <Swiften/Session/BasicSessionStream.h>
#include <boost/bind.hpp>
+#include <boost/smart_ptr/make_shared.hpp>
#include <Swiften/StreamStack/XMPPLayer.h>
#include <Swiften/StreamStack/StreamStack.h>
#include <Swiften/StreamStack/ConnectionLayer.h>
#include <Swiften/StreamStack/WhitespacePingLayer.h>
#include <Swiften/StreamStack/CompressionLayer.h>
#include <Swiften/StreamStack/TLSLayer.h>
#include <Swiften/TLS/TLSContextFactory.h>
#include <Swiften/TLS/TLSContext.h>
namespace Swift {
BasicSessionStream::BasicSessionStream(
StreamType streamType,
boost::shared_ptr<Connection> connection,
PayloadParserFactoryCollection* payloadParserFactories,
PayloadSerializerCollection* payloadSerializers,
TLSContextFactory* tlsContextFactory,
TimerFactory* timerFactory,
XMLParserFactory* xmlParserFactory) :
available(false),
connection(connection),
payloadParserFactories(payloadParserFactories),
payloadSerializers(payloadSerializers),
tlsContextFactory(tlsContextFactory),
timerFactory(timerFactory),
streamType(streamType),
compressionLayer(NULL),
tlsLayer(NULL),
whitespacePingLayer(NULL) {
xmppLayer = new XMPPLayer(payloadParserFactories, payloadSerializers, xmlParserFactory, streamType);
xmppLayer->onStreamStart.connect(boost::bind(&BasicSessionStream::handleStreamStartReceived, this, _1));
xmppLayer->onElement.connect(boost::bind(&BasicSessionStream::handleElementReceived, this, _1));
xmppLayer->onError.connect(boost::bind(&BasicSessionStream::handleXMPPError, this));
xmppLayer->onDataRead.connect(boost::bind(&BasicSessionStream::handleDataRead, this, _1));
@@ -78,131 +79,131 @@ void BasicSessionStream::writeHeader(const ProtocolHeader& header) {
assert(available);
xmppLayer->writeHeader(header);
}
void BasicSessionStream::writeElement(boost::shared_ptr<Element> element) {
assert(available);
xmppLayer->writeElement(element);
}
void BasicSessionStream::writeFooter() {
assert(available);
xmppLayer->writeFooter();
}
void BasicSessionStream::writeData(const std::string& data) {
assert(available);
xmppLayer->writeData(data);
}
void BasicSessionStream::close() {
connection->disconnect();
}
bool BasicSessionStream::isOpen() {
return available;
}
bool BasicSessionStream::supportsTLSEncryption() {
return tlsContextFactory && tlsContextFactory->canCreate();
}
void BasicSessionStream::addTLSEncryption() {
assert(available);
tlsLayer = new TLSLayer(tlsContextFactory);
if (hasTLSCertificate() && !tlsLayer->setClientCertificate(getTLSCertificate())) {
- onClosed(boost::shared_ptr<Error>(new Error(Error::InvalidTLSCertificateError)));
+ onClosed(boost::make_shared<Error>(Error::InvalidTLSCertificateError));
}
else {
streamStack->addLayer(tlsLayer);
tlsLayer->onError.connect(boost::bind(&BasicSessionStream::handleTLSError, this));
tlsLayer->onConnected.connect(boost::bind(&BasicSessionStream::handleTLSConnected, this));
tlsLayer->connect();
}
}
bool BasicSessionStream::isTLSEncrypted() {
return tlsLayer;
}
Certificate::ref BasicSessionStream::getPeerCertificate() const {
return tlsLayer->getPeerCertificate();
}
boost::shared_ptr<CertificateVerificationError> BasicSessionStream::getPeerCertificateVerificationError() const {
return tlsLayer->getPeerCertificateVerificationError();
}
ByteArray BasicSessionStream::getTLSFinishMessage() const {
return tlsLayer->getContext()->getFinishMessage();
}
bool BasicSessionStream::supportsZLibCompression() {
return true;
}
void BasicSessionStream::addZLibCompression() {
compressionLayer = new CompressionLayer();
streamStack->addLayer(compressionLayer);
}
void BasicSessionStream::setWhitespacePingEnabled(bool enabled) {
if (enabled) {
if (!whitespacePingLayer) {
whitespacePingLayer = new WhitespacePingLayer(timerFactory);
streamStack->addLayer(whitespacePingLayer);
}
whitespacePingLayer->setActive();
}
else if (whitespacePingLayer) {
whitespacePingLayer->setInactive();
}
}
void BasicSessionStream::resetXMPPParser() {
xmppLayer->resetParser();
}
void BasicSessionStream::handleStreamStartReceived(const ProtocolHeader& header) {
onStreamStartReceived(header);
}
void BasicSessionStream::handleElementReceived(boost::shared_ptr<Element> element) {
onElementReceived(element);
}
void BasicSessionStream::handleXMPPError() {
available = false;
- onClosed(boost::shared_ptr<Error>(new Error(Error::ParseError)));
+ onClosed(boost::make_shared<Error>(Error::ParseError));
}
void BasicSessionStream::handleTLSConnected() {
onTLSEncrypted();
}
void BasicSessionStream::handleTLSError() {
available = false;
- onClosed(boost::shared_ptr<Error>(new Error(Error::TLSError)));
+ onClosed(boost::make_shared<Error>(Error::TLSError));
}
void BasicSessionStream::handleConnectionFinished(const boost::optional<Connection::Error>& error) {
available = false;
if (error == Connection::ReadError) {
- onClosed(boost::shared_ptr<Error>(new Error(Error::ConnectionReadError)));
+ onClosed(boost::make_shared<Error>(Error::ConnectionReadError));
}
else if (error) {
- onClosed(boost::shared_ptr<Error>(new Error(Error::ConnectionWriteError)));
+ onClosed(boost::make_shared<Error>(Error::ConnectionWriteError));
}
else {
onClosed(boost::shared_ptr<Error>());
}
}
void BasicSessionStream::handleDataRead(const SafeByteArray& data) {
onDataRead(data);
}
void BasicSessionStream::handleDataWritten(const SafeByteArray& data) {
onDataWritten(data);
}
};
diff --git a/Swiften/StreamStack/UnitTest/XMPPLayerTest.cpp b/Swiften/StreamStack/UnitTest/XMPPLayerTest.cpp
index 8123c00..a6098f1 100644
--- a/Swiften/StreamStack/UnitTest/XMPPLayerTest.cpp
+++ b/Swiften/StreamStack/UnitTest/XMPPLayerTest.cpp
@@ -51,71 +51,71 @@ class XMPPLayerTest : public CppUnit::TestFixture {
CPPUNIT_ASSERT_EQUAL(1, errorReceived_);
}
void testResetParser() {
testling_->onElement.connect(boost::bind(&XMPPLayerTest::handleElement, this, _1));
testling_->onError.connect(boost::bind(&XMPPLayerTest::handleError, this));
testling_->handleDataRead(createSafeByteArray("<stream:stream to=\"example.com\" xmlns=\"jabber:client\" xmlns:stream=\"http://etherx.jabber.org/streams\" >"));
testling_->resetParser();
testling_->handleDataRead(createSafeByteArray("<stream:stream to=\"example.com\" xmlns=\"jabber:client\" xmlns:stream=\"http://etherx.jabber.org/streams\" >"));
testling_->handleDataRead(createSafeByteArray("<presence/>"));
CPPUNIT_ASSERT_EQUAL(1, elementsReceived_);
CPPUNIT_ASSERT_EQUAL(0, errorReceived_);
}
void testResetParser_FromSlot() {
testling_->onElement.connect(boost::bind(&XMPPLayerTest::handleElementAndReset, this, _1));
testling_->handleDataRead(createSafeByteArray("<stream:stream to=\"example.com\" xmlns=\"jabber:client\" xmlns:stream=\"http://etherx.jabber.org/streams\" ><presence/>"));
testling_->handleDataRead(createSafeByteArray("<stream:stream to=\"example.com\" xmlns=\"jabber:client\" xmlns:stream=\"http://etherx.jabber.org/streams\" ><presence/>"));
CPPUNIT_ASSERT_EQUAL(2, elementsReceived_);
CPPUNIT_ASSERT_EQUAL(0, errorReceived_);
}
void testWriteHeader() {
ProtocolHeader header;
header.setTo("example.com");
testling_->writeHeader(header);
CPPUNIT_ASSERT_EQUAL(std::string("<?xml version=\"1.0\"?><stream:stream xmlns=\"jabber:client\" xmlns:stream=\"http://etherx.jabber.org/streams\" to=\"example.com\" version=\"1.0\">"), lowLayer_->writtenData);
}
void testWriteElement() {
- testling_->writeElement(boost::shared_ptr<Presence>(new Presence()));
+ testling_->writeElement(boost::make_shared<Presence>());
CPPUNIT_ASSERT_EQUAL(std::string("<presence/>"), lowLayer_->writtenData);
}
void testWriteFooter() {
testling_->writeFooter();
CPPUNIT_ASSERT_EQUAL(std::string("</stream:stream>"), lowLayer_->writtenData);
}
void handleElement(boost::shared_ptr<Element>) {
++elementsReceived_;
}
void handleElementAndReset(boost::shared_ptr<Element>) {
++elementsReceived_;
testling_->resetParser();
}
void handleError() {
++errorReceived_;
}
private:
class XMPPLayerExposed : public XMPPLayer {
public:
XMPPLayerExposed(
PayloadParserFactoryCollection* payloadParserFactories,
PayloadSerializerCollection* payloadSerializers,
XMLParserFactory* xmlParserFactory,
StreamType streamType) : XMPPLayer(payloadParserFactories, payloadSerializers, xmlParserFactory, streamType) {}
using XMPPLayer::handleDataRead;
using HighLayer::setChildLayer;
};