PurgeStrategy.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  1. //
  2. // PurgeStrategy.cpp
  3. //
  4. // $Id: //poco/1.4/Foundation/src/PurgeStrategy.cpp#1 $
  5. //
  6. // Library: Foundation
  7. // Package: Logging
  8. // Module: FileChannel
  9. //
  10. // Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
  11. // and Contributors.
  12. //
  13. // SPDX-License-Identifier: BSL-1.0
  14. //
  15. #include "Poco/PurgeStrategy.h"
  16. #include "Poco/Path.h"
  17. #include "Poco/DirectoryIterator.h"
  18. #include "Poco/Timestamp.h"
  19. namespace Poco {
  20. //
  21. // PurgeStrategy
  22. //
  23. PurgeStrategy::PurgeStrategy()
  24. {
  25. }
  26. PurgeStrategy::~PurgeStrategy()
  27. {
  28. }
  29. void PurgeStrategy::list(const std::string& path, std::vector<File>& files)
  30. {
  31. Path p(path);
  32. p.makeAbsolute();
  33. Path parent = p.parent();
  34. std::string baseName = p.getFileName();
  35. baseName.append(".");
  36. DirectoryIterator it(parent);
  37. DirectoryIterator end;
  38. while (it != end)
  39. {
  40. if (it.name().compare(0, baseName.size(), baseName) == 0)
  41. {
  42. files.push_back(*it);
  43. }
  44. ++it;
  45. }
  46. }
  47. //
  48. // PurgeByAgeStrategy
  49. //
  50. PurgeByAgeStrategy::PurgeByAgeStrategy(const Timespan& age): _age(age)
  51. {
  52. }
  53. PurgeByAgeStrategy::~PurgeByAgeStrategy()
  54. {
  55. }
  56. void PurgeByAgeStrategy::purge(const std::string& path)
  57. {
  58. std::vector<File> files;
  59. list(path, files);
  60. for (std::vector<File>::iterator it = files.begin(); it != files.end(); ++it)
  61. {
  62. if (it->getLastModified().isElapsed(_age.totalMicroseconds()))
  63. {
  64. it->remove();
  65. }
  66. }
  67. }
  68. //
  69. // PurgeByCountStrategy
  70. //
  71. PurgeByCountStrategy::PurgeByCountStrategy(int count): _count(count)
  72. {
  73. poco_assert(count > 0);
  74. }
  75. PurgeByCountStrategy::~PurgeByCountStrategy()
  76. {
  77. }
  78. void PurgeByCountStrategy::purge(const std::string& path)
  79. {
  80. std::vector<File> files;
  81. list(path, files);
  82. while (files.size() > _count)
  83. {
  84. std::vector<File>::iterator it = files.begin();
  85. std::vector<File>::iterator purgeIt = it;
  86. Timestamp purgeTS = purgeIt->getLastModified();
  87. ++it;
  88. while (it != files.end())
  89. {
  90. Timestamp md(it->getLastModified());
  91. if (md <= purgeTS)
  92. {
  93. purgeTS = md;
  94. purgeIt = it;
  95. }
  96. ++it;
  97. }
  98. purgeIt->remove();
  99. files.erase(purgeIt);
  100. }
  101. }
  102. } // namespace Poco