summaryrefslogtreecommitdiffstats
blob: 3fd246c92018317f7444951a2cc2527d7423986a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/*
 * Copyright (c) 2011-2016 Isode Limited.
 * All rights reserved.
 * See the COPYING file for more information.
 */

#include <Swiften/Entity/PayloadPersister.h>

#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>

#include <Swiften/Base/ByteArray.h>
#include <Swiften/Base/Log.h>
#include <Swiften/Parser/PayloadParser.h>
#include <Swiften/Parser/PayloadParserFactory.h>
#include <Swiften/Parser/PayloadParsers/UnitTest/PayloadParserTester.h>
#include <Swiften/Serializer/PayloadSerializer.h>

using namespace Swift;

PayloadPersister::PayloadPersister() {
}

PayloadPersister::~PayloadPersister() {
}

void PayloadPersister::savePayload(std::shared_ptr<Payload> payload, const boost::filesystem::path& path) {
    try {
        if (!boost::filesystem::exists(path.parent_path())) {
            boost::filesystem::create_directories(path.parent_path());
        }
        boost::filesystem::ofstream file(path);
        file << getSerializer()->serialize(payload);
        file.close();
    }
    catch (const boost::filesystem::filesystem_error& e) {
        SWIFT_LOG(error) << e.what() << std::endl;
    }
}

std::shared_ptr<Payload> PayloadPersister::loadPayload(const boost::filesystem::path& path) {
    try {
        if (boost::filesystem::exists(path)) {
            ByteArray data;
            readByteArrayFromFile(data, path);
            std::shared_ptr<PayloadParser> parser(createParser());
            PayloadParserTester tester(parser.get());
            tester.parse(byteArrayToString(data));
            return parser->getPayload();
        }
    }
    catch (const boost::filesystem::filesystem_error& e) {
        SWIFT_LOG(error) << e.what() << std::endl;
    }
    return std::shared_ptr<Payload>();
}