00001 /* 00002 * PayloadBlock.cpp 00003 * 00004 * Created on: 29.05.2009 00005 * Author: morgenro 00006 */ 00007 00008 #include "ibrdtn/data/PayloadBlock.h" 00009 #include "ibrdtn/data/Exceptions.h" 00010 #include <ibrcommon/thread/MutexLock.h> 00011 00012 namespace dtn 00013 { 00014 namespace data 00015 { 00016 PayloadBlock::PayloadBlock() 00017 : Block(PayloadBlock::BLOCK_TYPE), _blobref(ibrcommon::TmpFileBLOB::create()) 00018 { 00019 } 00020 00021 PayloadBlock::PayloadBlock(ibrcommon::BLOB::Reference ref) 00022 : Block(PayloadBlock::BLOCK_TYPE), _blobref(ref) 00023 { 00024 } 00025 00026 PayloadBlock::~PayloadBlock() 00027 { 00028 } 00029 00030 ibrcommon::BLOB::Reference PayloadBlock::getBLOB() const 00031 { 00032 return _blobref; 00033 } 00034 00035 size_t PayloadBlock::getLength() const 00036 { 00037 ibrcommon::BLOB::Reference blobref = _blobref; 00038 ibrcommon::MutexLock l(blobref); 00039 return blobref.getSize(); 00040 } 00041 00042 std::ostream& PayloadBlock::serialize(std::ostream &stream) const 00043 { 00044 ibrcommon::BLOB::Reference blobref = _blobref; 00045 ibrcommon::MutexLock l(blobref); 00046 00047 // remember the old exceptions state 00048 std::ios::iostate oldstate = (*blobref).exceptions(); 00049 00050 // activate exceptions for this method 00051 (*blobref).exceptions(std::ios::badbit | std::ios::eofbit); 00052 00053 try { 00054 // write payload 00055 stream << (*blobref).rdbuf(); 00056 } catch (std::exception &ex) { 00057 // restore the old state 00058 (*blobref).exceptions(oldstate); 00059 00060 throw dtn::SerializationFailedException(ex.what()); 00061 } 00062 00063 // restore the old state 00064 (*blobref).exceptions(oldstate); 00065 00066 return stream; 00067 } 00068 00069 std::istream& PayloadBlock::deserialize(std::istream &stream) 00070 { 00071 ibrcommon::MutexLock l(_blobref); 00072 00073 // clear the blob 00074 _blobref.clear(); 00075 00076 // remember the old exceptions state 00077 std::ios::iostate oldstate = (*_blobref).exceptions(); 00078 00079 // activate exceptions for this method 00080 (*_blobref).exceptions(std::ios::badbit | std::ios::eofbit); 00081 00082 try { 00083 // read payload 00084 const int buffer_size = 0x1000; 00085 char buffer[buffer_size]; 00086 ssize_t remain = _blocksize; 00087 00088 while (remain > 0 && stream.good()) 00089 { 00090 if (remain > buffer_size) 00091 { 00092 stream.read(buffer, buffer_size); 00093 } 00094 else 00095 { 00096 stream.read(buffer, remain); 00097 } 00098 00099 (*_blobref).write(buffer, stream.gcount()); 00100 00101 remain -= stream.gcount(); 00102 } 00103 } catch (std::exception &ex) { 00104 // restore the old state 00105 (*_blobref).exceptions(oldstate); 00106 00107 throw dtn::SerializationFailedException(ex.what()); 00108 } 00109 00110 // restore the old state 00111 (*_blobref).exceptions(oldstate); 00112 00113 // unset block not processed bit 00114 set(dtn::data::Block::FORWARDED_WITHOUT_PROCESSED, false); 00115 00116 return stream; 00117 } 00118 } 00119 }
1.7.1