daas 0.2.2

A software development kit for Data as a Service (DaaS).
Documentation
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
//! The `daas` module provides functionality and Object Oriented implementation of a Data as a Service (DaaS) object.
//!
//! # Examples
//!
//!
//! Create DaaS object that represents a new purchase of clothing from an online store.
//!
//! ```
//! #[macro_use]
//! extern crate serde_json;
//! extern crate pbd;
//! extern crate daas;
//!
//! use serde_json::value::*;
//! use pbd::dua::DUA;
//! use pbd::dtc::Tracker;
//! use daas::doc::{DaaSDoc};
//!
//! fn main() {
//!		let src = "iStore".to_string();
//!		let uid = 5000;
//!		let cat = "order".to_string();
//!		let sub = "clothing".to_string();
//!		let auth = "istore_app".to_string();
//!		let mut dua = Vec::new();
//!		dua.push(DUA {
//!		    agreement_name: "billing".to_string(),
//!		    location: "https://dua.org/agreements/v1/billing.pdf".to_string(),
//!		    agreed_dtm: 1553988607,
//!		});
//!     let tracker = Tracker::new(DaaSDoc::make_id(cat.clone(), sub.clone(), src.clone(), uid.clone()));
//!		let data = String::from(r#"{
//!         "product": "leather coat",
//!         "quantity": 1,
//!		    "status": "new"
//!		}"#).as_bytes().to_vec();
//!
//!		let doc = DaaSDoc::new(src, uid, cat, sub, auth, dua,tracker, data);
//!
//!     assert_eq!(doc.source_uid, uid);
//! }
//! ```

use crate::errors::*;
use crate::*;
use pbd::dtc::Tracker;
use pbd::dua::DUA;
use serde_json::Value;
use std::collections::BTreeMap;

// Repesentation of a map for storing metadata about the data object
type Metadata = BTreeMap<String, String>;

/// Represents an existing DaaS document (after it has been saved and assigned a _rev value)
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct DaaSDoc {
    /// The unique identifier
    pub _id: String,
    /// The revision number
    pub _rev: Option<String>,
    /// The name of the data source
    pub source_name: String,
    /// The unique identifier that the data source provides
    pub source_uid: usize,
    /// The name of the category (e.g.: order)
    pub category: String,
    /// The name of the subcategory (e.g.: clothing)
    pub subcategory: String,
    /// The name of the author who created the document
    pub author: String,
    /// The indicator that represents if the document is waiting to be processed (processed = true, needs to be processed = false)
    pub process_ind: bool,
    /// The Unix Epoch time when the document was last updated, (e.g.: 1555972752)
    pub last_updated: u64,
    /// The list of Data Usage Agreements for the data represented in the DaaS Document
    pub data_usage_agreements: Vec<DUA>,
    /// The Data Tracker Chain that represents the lineage of the DaaS Document
    pub data_tracker: Tracker,
    // The list of metadata about the data object (key, value)
    pub meta_data: Metadata,
    // List of tags to provide context about the data object
    pub tags: Vec<String>,
    /// The byte slice that represents the data from the data source managed by the DaaS document
    pub data_obj: Vec<u8>,
}

/// Represents an new DaaS document (before it has been saved and assigned a _rev value)
#[derive(Serialize, Deserialize, Debug, Clone)]
struct DaaSDocNoRev {
    /// The unique identifier
    pub _id: String,
    /// The name of the data source
    pub source_name: String,
    /// The unique identifier that the data source provides
    pub source_uid: usize,
    /// The name of the category (e.g.: order)
    pub category: String,
    /// The name of the subcategory (e.g.: clothing)
    pub subcategory: String,
    /// The name of the author who created the document
    pub author: String,
    /// The indicator that represents if the document is waiting to be processed (processed = true, needs to be processed = false)
    pub process_ind: bool,
    /// The Unix Epoch time when the document was last updated, (e.g.: 1555972752)
    pub last_updated: u64,
    /// The list of Data Usage Agreements for the data represented in the DaaS Document
    pub data_usage_agreements: Vec<DUA>,
    /// The Data Tracker Chain that represents the lineage of the DaaS Document
    pub data_tracker: Tracker,
    /// The byte slice that represents the data from the data source managed by the DaaS document
    pub data_obj: Vec<u8>,
}

impl DaaSDoc {
    /// Delimiter used for building the unique identifier value for the DaaS document
    //pub const DELIMITER: &'static str = "~";

    /// Constructor
    ///
    /// # Arguments
    ///
    /// * src_name: String - The name of the data source.</br>
    /// * src_uid: usize - The unique identifier that the data source provided.</br>
    /// * cat: String - The name of the category (e.g.: order).</br>
    /// * sub: String - The name of the subcategory (e.g.: clothing).</br>
    /// * auth: String - The name of the auithor who created the document.</br>
    /// * data: Value - The json value that represents the data from the data source managed by the DaaS document.</br>
    ///
    /// #Example
    ///
    /// ```
    /// #[macro_use]
    /// extern crate serde_json;
    /// extern crate pbd;
    /// extern crate daas;
    ///
    /// use serde_json::value::*;
    /// use pbd::dua::DUA;
    /// use pbd::dtc::Tracker;
    /// use daas::doc::{DaaSDoc};
    ///
    /// fn main() {
    ///     let src = "iStore".to_string();
    ///     let src = "iStore".to_string();
    ///     let uid = 5000;
    ///     let cat = "order".to_string();
    ///     let sub = "clothing".to_string();
    ///     let auth = "istore_app".to_string();     
    ///     let mut dua = Vec::new();
    ///     dua.push(DUA::new("billing".to_string(),"https://dua.org/agreements/v1/billing.pdf".to_string(),1553988607));
    ///     let tracker = Tracker::new(DaaSDoc::make_id(cat.clone(), sub.clone(), src.clone(), uid.clone()));
    ///     let data = String::from(r#"{"status": "new"}"#).as_bytes().to_vec();
    ///     
    ///     let doc = DaaSDoc::new(src.clone(), uid, cat.clone(), sub.clone(), auth.clone(), dua, tracker, data);
    ///     
    ///     println!("{:?}", doc._id);
    /// }
    /// ```
    pub fn new(
        src_name: String,
        src_uid: usize,
        cat: String,
        subcat: String,
        auth: String,
        duas: Vec<DUA>,
        dtc: Tracker,
        data: Vec<u8>,
    ) -> DaaSDoc {
        let this_id = DaaSDoc::make_id(cat.clone(), subcat.clone(), src_name.clone(), src_uid);

        DaaSDoc {
            _id: this_id.clone(),
            _rev: None,
            source_name: src_name,
            source_uid: src_uid,
            category: cat,
            subcategory: subcat,
            author: auth,
            process_ind: false,
            last_updated: get_unix_now!(),
            data_usage_agreements: duas,
            data_tracker: dtc,
            meta_data: Metadata::new(),
            tags: Vec::new(),
            data_obj: data,
        }
    }

    /// Adds an entry to the metadata
    ///
    /// # Arguments
    ///
    /// * key: String - The key used to identify the name of the metadata property.</br>
    /// * value: String - The value used to define the metadata property.</br>
    ///    
    /// #Example
    ///
    /// ```
    /// #[macro_use]
    /// extern crate serde_json;
    /// extern crate pbd;
    /// extern crate daas;
    ///
    /// use serde_json::value::*;
    /// use pbd::dua::DUA;
    /// use pbd::dtc::Tracker;
    /// use daas::doc::{DaaSDoc};
    ///
    /// fn main() {
    ///     let src = "iStore".to_string();
    ///     let uid = 5000;
    ///     let cat = "order".to_string();
    ///     let sub = "clothing".to_string();
    ///     let auth = "istore_app".to_string();
    ///     let mut dua = Vec::new();
    ///     dua.push(DUA::new("billing".to_string(),"https://dua.org/agreements/v1/billing.pdf".to_string(),1553988607));
    ///     let tracker = Tracker::new(DaaSDoc::make_id(cat.clone(), sub.clone(), src.clone(), uid.clone()));
    ///     let data = String::from(r#"{"status": "new"}"#).as_bytes().to_vec();
    ///     
    ///     let mut doc = DaaSDoc::new(src.clone(), uid, cat.clone(), sub.clone(), auth.clone(), dua, tracker, data);
    ///     doc.add_meta("foo".to_string(),"bar".to_string());
    ///   
    ///     assert_eq!(doc.get_meta("foo".to_string()), "bar");
    /// }
    /// ```
    pub fn add_meta(&mut self, key: String, value: String) {
        let _ = &self.meta_data.insert(key, value);
    }

    /// Adds a tag
    ///
    /// # Arguments
    ///
    /// * tag: String - The textual label to use as a tag.</br>
    ///    
    /// #Example
    ///
    /// ```
    /// #[macro_use]
    /// extern crate serde_json;
    /// extern crate pbd;
    /// extern crate daas;
    ///
    /// use serde_json::value::*;
    /// use pbd::dua::DUA;
    /// use pbd::dtc::Tracker;
    /// use daas::doc::{DaaSDoc};
    ///
    /// fn main() {
    ///     let src = "iStore".to_string();
    ///     let uid = 5000;
    ///     let cat = "order".to_string();
    ///     let sub = "clothing".to_string();
    ///     let auth = "istore_app".to_string();
    ///     let mut dua = Vec::new();
    ///     dua.push(DUA::new("billing".to_string(),"https://dua.org/agreements/v1/billing.pdf".to_string(),1553988607));
    ///     let tracker = Tracker::new(DaaSDoc::make_id(cat.clone(), sub.clone(), src.clone(), uid.clone()));
    ///     let data = String::from(r#"{"status": "new"}"#).as_bytes().to_vec();
    ///     
    ///     let mut doc = DaaSDoc::new(src.clone(), uid, cat.clone(), sub.clone(), auth.clone(), dua,tracker,  data);
    ///     doc.add_tag("foo".to_string());
    ///     doc.add_tag("bar".to_string());
    ///   
    ///     println!("There are {} tags for this DaaSDoc", doc.get_tags().len());
    /// }
    /// ```
    pub fn add_tag(&mut self, tag: String) {
        let _ = &self.tags.push(tag);
    }

    /// Returns the data source json value as a reference
    ///
    /// #Example
    ///
    /// ```
    /// #[macro_use]
    /// extern crate serde_json;
    /// extern crate pbd;
    /// extern crate daas;
    ///
    /// use serde_json::value::*;
    /// use pbd::dua::DUA;
    /// use pbd::dtc::Tracker;
    /// use daas::doc::{DaaSDoc};
    ///
    /// fn main() {
    ///     let src = "iStore".to_string();
    ///     let uid = 5000;
    ///     let cat = "order".to_string();
    ///     let sub = "clothing".to_string();
    ///     let auth = "istore_app".to_string();
    ///     let mut dua = Vec::new();
    ///     dua.push(DUA::new("billing".to_string(),"https://dua.org/agreements/v1/billing.pdf".to_string(),1553988607));
    ///     let tracker = Tracker::new(DaaSDoc::make_id(cat.clone(), sub.clone(), src.clone(), uid.clone()));
    ///     let data = String::from(r#"{"status": "new"}"#).as_bytes().to_vec();
    ///     
    ///     let doc = DaaSDoc::new(src.clone(), uid, cat.clone(), sub.clone(), auth.clone(), dua, tracker, data);
    ///     
    ///     let dat: Value = serde_json::from_str(&String::from_utf8(doc.data_obj).unwrap()).unwrap();
    ///     assert_eq!(dat.get("status").unwrap(), "new");
    /// }
    /// ```
    pub fn data_obj_as_ref(&mut self) -> &mut Vec<u8> {
        &mut self.data_obj
    }

    /// Constructs a DaaSDoc object from a serialized string
    ///
    /// # Arguments
    ///
    /// * serialized: &str - The string that represents the serialized object.</br>
    ///
    /// #Example
    ///
    /// ```
    /// extern crate daas;
    ///
    /// use daas::doc::DaaSDoc;
    ///
    /// fn main() {
    ///     let serialized = r#"{"_id":"order|clothing|iStore|5000","_rev":null,"source_name":"iStore","source_uid":5000,"category":"order","subcategory":"clothing","author":"istore_app","process_ind":false,"last_updated":1553988607,"data_usage_agreements":[{"agreement_name":"billing","location":"www.dua.org/billing.pdf","agreed_dtm":1553988607}],"data_tracker":{"chain":[{"identifier":{"data_id":"order~clothing~iStore~5000","index":0,"timestamp":0,"actor_id":"","previous_hash":"0"},"hash":"72259503327276020952102368672148358485","nonce":5}]},"meta_data":{},"tags":[],"data_obj":[123,34,115,116,97,116,117,115,34,58,32,34,110,101,119,34,125]}"#;
    ///     let doc = DaaSDoc::from_serialized(&serialized.as_bytes()).unwrap();
    ///     
    ///     assert_eq!(doc.source_uid, 5000);
    /// }
    /// ```
    pub fn from_serialized(serialized: &[u8]) -> Result<DaaSDoc, DaaSDocError> {
        match serde_json::from_slice(&serialized) {
            Ok(doc) => Ok(doc),
            Err(err) => {
                error!("{}", err);
                Err(DaaSDocError)
            }
        }
    }

    /// Returns the value of a metadata entry
    ///
    /// # Arguments
    ///
    /// * key: String - The key used to identify the name of the metadata property.</br>
    /// * value: String - The value used to define the metadata property.</br>
    ///    
    /// #Example
    ///
    /// ```
    /// #[macro_use]
    /// extern crate serde_json;
    /// extern crate pbd;
    /// extern crate daas;
    ///
    /// use serde_json::value::*;
    /// use pbd::dua::DUA;
    /// use pbd::dtc::Tracker;
    /// use daas::doc::{DaaSDoc};
    ///
    /// fn main() {
    ///     let src = "iStore".to_string();
    ///     let uid = 5000;
    ///     let cat = "order".to_string();
    ///     let sub = "clothing".to_string();
    ///     let auth = "istore_app".to_string();
    ///     let mut dua = Vec::new();
    ///     dua.push(DUA::new("billing".to_string(),"https://dua.org/agreements/v1/billing.pdf".to_string(),1553988607));
    ///     let tracker = Tracker::new(DaaSDoc::make_id(cat.clone(), sub.clone(), src.clone(), uid.clone()));
    ///     let data = String::from(r#"{"status": "new"}"#).as_bytes().to_vec();
    ///     
    ///     let mut doc = DaaSDoc::new(src.clone(), uid, cat.clone(), sub.clone(), auth.clone(), dua, tracker, data);
    ///     doc.add_meta("foowho".to_string(),"me".to_string());
    ///     doc.add_meta("foo".to_string(),"bar".to_string());
    ///   
    ///     println!("foo {}", doc.get_meta("foowho".to_string()) );
    /// }
    /// ```
    pub fn get_meta(&mut self, key: String) -> String {
        self.meta_data.get(&key).unwrap().to_string()
    }

    /// Returns a list of related tags
    ///    
    /// #Example
    ///
    /// ```
    /// #[macro_use]
    /// extern crate serde_json;
    /// extern crate pbd;
    /// extern crate daas;
    ///
    /// use serde_json::value::*;
    /// use pbd::dua::DUA;
    /// use pbd::dtc::Tracker;
    /// use daas::doc::{DaaSDoc};
    ///
    /// fn main() {
    ///     let src = "iStore".to_string();
    ///     let uid = 5000;
    ///     let cat = "order".to_string();
    ///     let sub = "clothing".to_string();
    ///     let auth = "istore_app".to_string();
    ///     let mut dua = Vec::new();
    ///     dua.push(DUA::new("billing".to_string(),"https://dua.org/agreements/v1/billing.pdf".to_string(),1553988607));
    ///     let tracker = Tracker::new(DaaSDoc::make_id(cat.clone(), sub.clone(), src.clone(), uid.clone()));
    ///     let data = String::from(r#"{"status": "new"}"#).as_bytes().to_vec();
    ///     
    ///     let mut doc = DaaSDoc::new(src.clone(), uid, cat.clone(), sub.clone(), auth.clone(), dua, tracker, data);
    ///     doc.add_tag("foo".to_string());
    ///     doc.add_tag("bar".to_string());
    ///   
    ///     println!("Tags: {:?}", doc.get_tags());
    /// }
    /// ```
    pub fn get_tags(&self) -> Vec<String> {
        self.tags.clone()
    }

    /// Determines if a tag is related to the DaaSDoc
    ///    
    /// #Example
    ///
    /// ```
    /// #[macro_use]
    /// extern crate serde_json;
    /// extern crate pbd;
    /// extern crate daas;
    ///
    /// use serde_json::value::*;
    /// use pbd::dua::DUA;
    /// use pbd::dtc::Tracker;
    /// use daas::doc::{DaaSDoc};
    ///
    /// fn main() {
    ///     let src = "iStore".to_string();
    ///     let uid = 5000;
    ///     let cat = "order".to_string();
    ///     let sub = "clothing".to_string();
    ///     let auth = "istore_app".to_string();
    ///     let mut dua = Vec::new();
    ///     dua.push(DUA::new("billing".to_string(),"https://dua.org/agreements/v1/billing.pdf".to_string(),1553988607));
    ///     let tracker = Tracker::new(DaaSDoc::make_id(cat.clone(), sub.clone(), src.clone(), uid.clone()));
    ///     let data = String::from(r#"{"status": "new"}"#).as_bytes().to_vec();
    ///     
    ///     let mut doc = DaaSDoc::new(src.clone(), uid, cat.clone(), sub.clone(), auth.clone(), dua, tracker, data);
    ///     doc.add_tag("foo".to_string());
    ///     doc.add_tag("bar".to_string());
    ///   
    ///     assert!(doc.has_tag("foo".to_string()));
    /// }
    /// ```
    pub fn has_tag(&self, tag: String) -> bool {
        self.tags.contains(&tag)
    }

    /// A shared function that returns the unique identifier
    ///
    /// # Arguments
    ///
    /// * cat: String - The name of the category (e.g.: order).</br>
    /// * sub: String - The name of the subcategory (e.g.: clothing).</br>
    /// * src_name: String - The name of the data source.</br>
    /// * src_uid: usize - The unique identifier that the data source provided.</br>
    ///
    pub fn make_id(cat: String, subcat: String, src_name: String, src_uid: usize) -> String {
        format!(
            "{}{}{}{}{}{}{}",
            cat, DELIMITER, subcat, DELIMITER, src_name, DELIMITER, src_uid
        )
        .to_string()
    }

    /// Serializes the DaaSDoc object
    ///
    /// #Example
    ///
    /// ```
    /// #[macro_use]
    /// extern crate serde_json;
    /// extern crate pbd;
    /// extern crate daas;
    ///
    /// use serde_json::value::*;
    /// use pbd::dua::DUA;
    /// use pbd::dtc::Tracker;
    /// use daas::doc::{DaaSDoc};
    ///
    /// fn main() {
    ///     let src = "iStore".to_string();
    ///     let src = "iStore".to_string();
    ///     let uid = 5000;
    ///     let cat = "order".to_string();
    ///     let sub = "clothing".to_string();
    ///     let auth = "istore_app".to_string();
    ///     let mut dua = Vec::new();
    ///     dua.push(DUA::new("billing".to_string(),"https://dua.org/agreements/v1/billing.pdf".to_string(),1553988607));
    ///     let tracker = Tracker::new(DaaSDoc::make_id(cat.clone(), sub.clone(), src.clone(), uid.clone()));
    ///     let data = String::from(r#"{"status": "new"}"#).as_bytes().to_vec();
    ///     
    ///     let mut doc = DaaSDoc::new(src.clone(), uid, cat.clone(), sub.clone(), auth.clone(), dua, tracker, data);
    ///     
    ///     println!("{:?}", doc.serialize());
    /// }
    /// ```
    pub fn serialize(&mut self) -> String {
        serde_json::to_string(&self).unwrap()
    }

    /// Serializes the DaaSDoc object without the _rev attribute
    ///
    /// #Example
    ///
    /// ```
    /// #[macro_use]
    /// extern crate serde_json;
    /// extern crate pbd;
    /// extern crate daas;
    ///
    /// use serde_json::value::*;
    /// use pbd::dua::DUA;
    /// use pbd::dtc::Tracker;
    /// use daas::doc::{DaaSDoc};
    ///
    /// fn main() {
    ///     let src = "iStore".to_string();
    ///     let src = "iStore".to_string();
    ///     let uid = 5000;
    ///     let cat = "order".to_string();
    ///     let sub = "clothing".to_string();
    ///     let auth = "istore_app".to_string();
    ///     let mut dua = Vec::new();
    ///     dua.push(DUA::new("billing".to_string(),"https://dua.org/agreements/v1/billing.pdf".to_string(),1553988607));
    ///     let tracker = Tracker::new(DaaSDoc::make_id(cat.clone(), sub.clone(), src.clone(), uid.clone()));
    ///     let data = String::from(r#"{"status": "new"}"#).as_bytes().to_vec();
    ///     
    ///     let mut doc = DaaSDoc::new(src.clone(), uid, cat.clone(), sub.clone(), auth.clone(), dua, tracker, data);
    ///     
    ///     println!("{:?}", doc.serialize_without_rev());
    /// }
    /// ```
    pub fn serialize_without_rev(&mut self) -> String {
        let no_rev: DaaSDocNoRev = DaaSDocNoRev {
            _id: self._id.clone(),
            source_name: self.source_name.clone(),
            source_uid: self.source_uid.clone(),
            category: self.category.clone(),
            subcategory: self.subcategory.clone(),
            author: self.author.clone(),
            process_ind: self.process_ind.clone(),
            last_updated: get_unix_now!(),
            data_usage_agreements: self.data_usage_agreements.clone(),
            data_tracker: self.data_tracker.clone(),
            data_obj: self.data_obj.clone(),
        };

        let serialized: String = serde_json::to_string(&no_rev).unwrap();

        serialized
    }

    /// Verifies that the DaaS document passes al the security and privacy rules.
    ///
    /// + Must have at least one Dat Usage Agreement
    /// + Must have a Data Tracker Chain that has not been tampered with or replaced with a fake one
    ///
    /// #Example
    ///
    /// ```
    /// #[macro_use]
    /// extern crate serde_json;
    /// extern crate pbd;
    /// extern crate daas;
    ///
    /// use serde_json::value::*;
    /// use pbd::dua::DUA;
    /// use pbd::dtc::Tracker;
    /// use daas::doc::{DaaSDoc};
    ///
    /// fn main() {
    ///     let src = "iStore".to_string();
    ///     let uid = 5000;
    ///     let cat = "order".to_string();
    ///     let sub = "clothing".to_string();
    ///     let auth = "istore_app".to_string();
    ///     let mut dua = Vec::new();
    ///     dua.push( DUA {
    ///         agreement_name: "billing".to_string(),
    ///         location: "www.dua.org/billing.pdf".to_string(),
    ///         agreed_dtm: 1553988607,
    ///     });
    ///     let tracker = Tracker::from_serialized(r#"[{"identifier":{"data_id":"order~clothing~iStore~tampered","index":0,"timestamp":0,"actor_id":"","previous_hash":"0"},"hash":"72259503327276020952102368672148358485","nonce":5}]"#);
    ///     let data = String::from(r#"{"status": "new"}"#).as_bytes().to_vec();
    ///     let doc = DaaSDoc::new(src.clone(), uid, cat.clone(), sub.clone(), auth.clone(), dua, tracker.unwrap(), data);
    ///     
    ///     assert!(doc.validate().is_err());
    /// }
    /// ```
    pub fn validate(self) -> Result<Self, DaaSSecurityError> {
        let mut chck: bool = false;

        chck = match self.validate_has_usage_agreement() {
            Ok(_) => true,
            Err(err) => return Err(err),
        };

        chck = match self.validate_matching_tracker() {
            Ok(_) => true,
            Err(err) => return Err(err),
        };

        chck = match self.validate_untampered_tracker() {
            Ok(_) => true,
            Err(err) => return Err(err),
        };

        match chck {
            true => Ok(self),
            false => return Err(DaaSSecurityError::ValidationError),
        }
    }

    fn validate_matching_tracker(&self) -> Result<(), DaaSSecurityError> {
        match self.data_tracker.get(0).unwrap().identifier.data_id == self._id {
            true => Ok(()),
            false => {
                warn!(
                    "DaaS detected a mismatched tracker in docoument {} and has rejected it.",
                    self._id
                );
                Err(DaaSSecurityError::TamperedDataError)
            }
        }
    }

    fn validate_untampered_tracker(&self) -> Result<(), DaaSSecurityError> {
        match self.data_tracker.is_valid() {
            true => Ok(()),
            false => {
                warn!(
                    "DaaS detected a tampered docoument {} and has rejected it.",
                    self._id
                );
                Err(DaaSSecurityError::TamperedDataError)
            }
        }
    }

    fn validate_has_usage_agreement(&self) -> Result<(), DaaSSecurityError> {
        match self.data_usage_agreements.is_empty() {
            false => match self.data_usage_agreements[0].agreed_dtm < get_unix_now!() {
                true => Ok(()),
                false => {
                    warn!("DaaS detected an invalid usage agreement for docoument {} and has rejected it.", self._id);
                    Err(DaaSSecurityError::BadAgreementError)
                }
            },
            true => {
                warn!(
                    "DaaS detected a missing usage agreement for docoument {} and has rejected it.",
                    self._id
                );
                Err(DaaSSecurityError::MissingAgreementError)
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs::File;
    use std::io::prelude::*;

    fn get_default_daasdoc() -> DaaSDoc {
        let src = "iStore".to_string();
        let uid = 5000;
        let cat = "order".to_string();
        let sub = "clothing".to_string();
        let auth = "istore_app".to_string();
        let dua = get_dua();
        let dtc = get_dtc(src.clone(), uid.clone(), cat.clone(), sub.clone());
        let data = String::from(r#"{"status": "new"}"#).as_bytes().to_vec();
        let doc = DaaSDoc::new(
            src.clone(),
            uid,
            cat.clone(),
            sub.clone(),
            auth.clone(),
            dua,
            dtc,
            data,
        );

        doc
    }

    fn get_dua() -> Vec<DUA> {
        let mut v = Vec::new();
        v.push(DUA {
            agreement_name: "billing".to_string(),
            location: "www.dua.org/billing.pdf".to_string(),
            agreed_dtm: 1553988607,
        });
        v
    }

    fn get_dtc(src_name: String, src_uid: usize, cat: String, subcat: String) -> Tracker {
        Tracker::new(DaaSDoc::make_id(
            cat.clone(),
            subcat.clone(),
            src_name.clone(),
            src_uid,
        ))
    }

    #[test]
    fn test_has_tag_ok() {
        let mut doc = get_default_daasdoc();
        doc.add_tag("foo".to_string());
        doc.add_tag("bar".to_string());

        assert_eq!(doc.has_tag("foo".to_string()), true);
        assert_eq!(doc.has_tag("me".to_string()), false);
    }

    #[test]
    fn test_new_obj_ok() {
        let _doc = get_default_daasdoc();

        assert!(true);
    }

    #[test]
    fn test_doc_id_ok() {
        let src = "iStore".to_string();
        let uid = 5000;
        let cat = "order".to_string();
        let sub = "clothing".to_string();
        let auth = "istore_app".to_string();
        let id = format!("{}~{}~{}~{}", cat, sub, src, uid).to_string();
        let dua = get_dua();
        let dtc = get_dtc(src.clone(), uid.clone(), cat.clone(), sub.clone());
        let data = String::from(r#"{"status": "new"}"#).as_bytes().to_vec();
        let doc = DaaSDoc::new(src, uid, cat, sub, auth, dua, dtc, data);

        assert_eq!(doc._id, id);
    }

    #[test]
    fn test_doc_rev_empty() {
        let doc = get_default_daasdoc();

        assert!(doc._rev.is_none());
    }

    #[test]
    fn test_doc_attributes_ok() {
        let src = "iStore".to_string();
        let uid = 5000;
        let cat = "order".to_string();
        let sub = "clothing".to_string();
        let auth = "istore_app".to_string();
        let doc = get_default_daasdoc();

        assert_eq!(doc.author, auth);
        assert_eq!(doc.source_name, src);
        assert_eq!(doc.source_uid, uid);
        assert_eq!(doc.category, cat);
        assert_eq!(doc.subcategory, sub);
        assert_eq!(doc.process_ind, false);
    }

    #[test]
    fn test_doc_binary_data_ok() {
        let src = "iStore".to_string();
        let uid = 16500;
        let cat = "order".to_string();
        let sub = "music".to_string();
        let auth = "istore_app".to_string();
        let dua = get_dua();
        let dtc = get_dtc(src.clone(), uid.clone(), cat.clone(), sub.clone());

        let mut f = match File::open("./tests/example_audio_clip.mp3") {
            Ok(aud) => aud,
            Err(err) => {
                panic!("Cannot read the audio file: {}", err);
            }
        };

        let mut data = Vec::new();
        f.read_to_end(&mut data).unwrap();

        let mut doc = DaaSDoc::new(
            src.clone(),
            uid,
            cat.clone(),
            sub.clone(),
            auth.clone(),
            dua,
            dtc,
            data,
        );

        assert_eq!(doc.data_obj_as_ref().len(), 764176);
    }

    #[test]
    fn test_doc_data_ok() {
        let doc = get_default_daasdoc();
        let dat: Value = serde_json::from_str(&String::from_utf8(doc.data_obj).unwrap()).unwrap();

        assert_eq!(dat.get("status").unwrap(), "new");
    }

    #[test]
    fn test_from_serialize() {
        let src = "iStore".to_string();
        let uid = 5000;
        let cat = "order".to_string();
        let sub = "clothing".to_string();
        let auth = "istore_app".to_string();
        let id = format!("{}~{}~{}~{}", cat, sub, src, uid).to_string();
        let serialized = r#"{
            "_id":"order~clothing~iStore~5000",
            "_rev":null,"source_name":"iStore",
            "source_uid":5000,"category":"order",
            "subcategory":"clothing",
            "author":"istore_app",
            "process_ind":false,
            "last_updated":1582765594,
            "data_usage_agreements":[{"agreement_name":"billing","location":"www.dua.org/billing.pdf","agreed_dtm":1553988607}],
            "data_tracker":{"chain":[{"identifier":{"data_id":"order~clothing~iStore~5000","index":0,"timestamp":0,"actor_id":"","previous_hash":"0"},"hash":"72259503327276020952102368672148358485","nonce":5}]},
            "meta_data":{},
            "tags":[],
            "data_obj":[123,34,115,116,97,116,117,115,34,58,32,34,110,101,119,34,125]}"#;
        let dua = get_dua();
        let doc = DaaSDoc::from_serialized(&serialized.as_bytes()).unwrap();
        let dat: Value = serde_json::from_str(&String::from_utf8(doc.data_obj).unwrap()).unwrap();

        assert_eq!(doc._id, id);
        assert!(doc._rev.is_none());
        assert_eq!(doc.source_name, src);
        assert_eq!(doc.source_uid, uid);
        assert_eq!(doc.category, cat);
        assert_eq!(doc.subcategory, sub);
        assert_eq!(doc.author, auth);
        assert_eq!(doc.process_ind, false);
        assert_eq!(
            doc.data_usage_agreements[0].agreement_name,
            dua[0].agreement_name
        );
        assert_eq!(dat.get("status").unwrap(), "new");
    }

    #[test]
    fn test_meta_data_ok() {
        let mut doc = get_default_daasdoc();
        doc.add_meta("foo".to_string(), "bar".to_string());

        assert_eq!(doc.get_meta("foo".to_string()), "bar");
    }

    #[test]
    fn test_validate_doc_ok() {
        let doc = get_default_daasdoc();

        assert!(doc.validate().is_ok());
    }

    #[test]
    fn test_validate_doc_tampered_dtc() {
        let src = "iStore".to_string();
        let uid = 5000;
        let cat = "order".to_string();
        let sub = "clothing".to_string();
        let auth = "istore_app".to_string();
        let dua = get_dua();
        let tracker = Tracker::from_serialized(
            r#"[{"identifier":{"data_id":"order~clothing~iStore~6000","index":0,"timestamp":0,"actor_id":"","previous_hash":"0"},"hash":"72259503327276020952102368672148358485","nonce":5}]"#,
        );
        let data = String::from(r#"{"status": "new"}"#).as_bytes().to_vec();
        let doc = DaaSDoc::new(
            src.clone(),
            uid,
            cat.clone(),
            sub.clone(),
            auth.clone(),
            dua,
            tracker.unwrap(),
            data,
        );

        assert!(doc.validate().is_err());
    }

    #[test]
    fn test_validate_doc_fake_dtc() {
        let src = "iStore".to_string();
        let uid = 5000;
        let cat = "order".to_string();
        let sub = "clothing".to_string();
        let auth = "istore_app".to_string();
        let dua = get_dua();
        let tracker = Tracker::from_serialized(
            r#"[{"identifier":{"data_id":"order~clothing~iStore~5000","index":0,"timestamp":0,"actor_id":"","previous_hash":"0"},"hash":"7225950332727602095210236867214835840","nonce":5}]"#,
        );
        let data = String::from(r#"{"status": "new"}"#).as_bytes().to_vec();
        let doc = DaaSDoc::new(
            src.clone(),
            uid,
            cat.clone(),
            sub.clone(),
            auth.clone(),
            dua,
            tracker.unwrap(),
            data,
        );

        assert!(doc.validate().is_err());
    }

    #[test]
    fn test_tagging_ok() {
        let mut doc = get_default_daasdoc();
        doc.add_tag("foo".to_string());
        doc.add_tag("bar".to_string());

        assert_eq!(doc.get_tags().len(), 2);
    }
}