BeeeOn Gateway  v2020.3.1-2-g6f737dc
Platform to interconnect the IoT world
SafeWriter.h
1 #pragma once
2 
3 #include <string>
4 #include <utility>
5 
6 #include <Poco/CountingStream.h>
7 #include <Poco/DigestStream.h>
8 #include <Poco/File.h>
9 #include <Poco/FileStream.h>
10 #include <Poco/Path.h>
11 #include <Poco/SHA1Engine.h>
12 #include <Poco/TemporaryFile.h>
13 
14 #include "util/Loggable.h"
15 
16 namespace BeeeOn {
17 
31 public:
32  SafeWriter(const Poco::File &tmpFile);
33  SafeWriter(const Poco::File &tmpFile, const std::string &ext);
34  ~SafeWriter();
35 
41  std::ostream &stream(bool force = false);
42 
48  void flush();
49 
55  void reset();
56 
63  std::pair<Poco::DigestEngine::Digest, size_t> finalize();
64 
71  void commitAs(const Poco::File &targetFile);
72 
73 protected:
83  void createLockFile(bool force);
84 
85 private:
86  Poco::File m_tmpFile;
87  Poco::FileOutputStream m_fileStream;
88  Poco::SHA1Engine m_engine;
89  Poco::DigestOutputStream m_digestStream;
90  Poco::DigestEngine::Digest m_recentDigest;
91  Poco::CountingOutputStream m_countingStream;
92  size_t m_recentLength;
93  std::ostream &m_stream;
94  bool m_created;
95  bool m_finalized;
96  bool m_committed;
97 };
98 
99 }
void reset()
Reset the writer and allow to try writing again before commit succeeds.
Definition: SafeWriter.cpp:109
void flush()
Flush the given stream. It is recommended to prefer this call instead of stream().flush() because the underlying stream implementation might not propagate flushing properly.
Definition: SafeWriter.cpp:102
std::ostream & stream(bool force=false)
Definition: SafeWriter.cpp:60
void commitAs(const Poco::File &targetFile)
Commit the prepared temporary file as follows:
Definition: SafeWriter.cpp:161
void createLockFile(bool force)
Create the temporary lock file atomically. It fails in the case when the lock file already exists unl...
Definition: SafeWriter.cpp:85
Definition: Loggable.h:19
SafeWriter is a helper that allows to perform file writes that are atomic. SafeWriter always rewrites...
Definition: SafeWriter.h:30
std::pair< Poco::DigestEngine::Digest, size_t > finalize()
Definition: SafeWriter.cpp:137