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
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
// Copyright 2015 Hugo Duncan
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/// A module for http resources
use hyper::header::EntityTag;
use iron::{IronError, IronResult, Request, Response, status};
use iron::headers::{self,Encoding, QualityItem};
use iron::method;
use iron::modifier::Set;
use mime::{Mime,TopLevel,SubLevel};
use std::{error,fmt};
use std::boxed::Box;
use time::Tm;
use content_neg;
use hyper_headers;

use self::ResourceError::*;

/// Austenite's Error Type
#[derive(Debug,PartialEq,Clone)]
pub enum ResourceError{
    /// Function not implemented
    NotImplemented,
}

impl fmt::Display for ResourceError {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        write!(fmt, "{:?}", self)
    }
}

impl error::Error for ResourceError {
    fn description(&self) -> &str {
        "ResourceError"
    }
}

impl error::FromError<ResourceError> for IronError {
    fn from_error(err: ResourceError) -> IronError {
        IronError{
            error: Box::new(err),
            response: Response::with(
                (status::NotImplemented, "Not implemented"))
        }}
}

/// Result type for resource trait functions.
pub type ResourceResult = Result<(),ResourceError>;

fn strong_match(_: &EntityTag, _: &EntityTag) -> bool {
    assert!(false,"not implemented");
    true
}

fn weak_match(_: &EntityTag, _: &EntityTag) -> bool {
    assert!(false,"not implemented");
    true
}

/// Cannot use this due to https://github.com/rust-lang/rust/issues/11403
macro_rules! decision_fn {
    ($decision:ident, $thenv:ident, $elsev:ident) => (
        fn concat_idents!($decision,_decision)
            (&self, req: &Request, resp: &mut Response) -> ResourceResult {
                let decision=self.$decision(req);
                debug!(concat!(stringify!($decision),": {}"), decision);
                if decsion {
                    self.$thenv(req,resp)
                } else {
                    self.$elsev(req,resp)
                }
            }
        )
}

macro_rules! decision_body {
    ($me:ident, $req:ident, $resp:ident,
     $decision:ident, $thenv:ident, $elsev:ident) => (
        {
            let decision=$me.$decision($req, $resp);
            debug!(concat!(stringify!($decision),": {}"), decision);
            if decision {
                $me.$thenv($req,$resp)
            } else {
                $me.$elsev($req,$resp)
            }
        }
        );
    // same, but with an expression rather than an identifier for the decision
    ($me:ident, $req:ident, $resp:ident,
     $decision:expr, $thenv:ident, $elsev:ident) => (
        {
            let decision=$decision;
            debug!(concat!(stringify!($decision),": {}"), decision);
            if decision {
                $me.$thenv($req,$resp)
            } else {
                $me.$elsev($req,$resp)
            }
        }
        )
}

/// Main trait for an HTTP resource.
///
/// Implement this trait's optional functions to control how the HTTP
/// request is handled.

pub trait Resource {
    // Trait functions that can be overridden

    /// Override to control service availability.  If this returns
    /// false, then a 503 ServiceUnavailable reply will result.
    /// Defaults to true.
    fn service_available(&self, _: &Request, _: &mut Response) -> bool {
        return true;
    }

    /// Override to control known HTTP verbs.  If this returns false,
    /// then a 501 NotImplemented reply will result.  Defaults to
    /// true.
    fn known_method(&self, req: &Request, _: &mut Response) -> bool {
        match req.method {
            method::Extension(_) => false,
            _ => true
        }
    }

    /// Override to limit uri length.  If this returns true, then a
    /// 414 RequestUriTooLong reply will result.  Defaults to false.
    fn uri_too_long(&self, _: &Request, _: &mut Response) -> bool {
        return false;
    }

    /// Override to control valid HTTP verbs for the request.  If this
    /// returns false, then a 405 MethodNotAllowed reply will result.
    /// Defaults to alowing GET and HEAD.
    fn method_allowed(&self, req: &Request, _: &mut Response) -> bool {
        match req.method {
            method::Get|method::Head => true,
            _ => false
        }
    }

    /// Override to control request validity.  If this returns false,
    /// then a 405 MethodNotAllowed reply will result.  Defaults to
    /// alowing GET and HEAD.
    fn malformed(&self, _: &Request, _: &mut Response) -> bool {
        false
    }

    /// Override to control request authentication.  If this returns
    /// false, then a 401 Unauthorized reply will result.  Defaults to
    /// true.
    fn authorized(&self, _: &Request, _: &mut Response) -> bool {
        true
    }

    /// Override to control request authorisation.  If this returns
    /// false, then a 403 Forbidden reply will result.  Defaults to
    /// true.
    fn allowed(&self, _: &Request, _: &mut Response) -> bool {
        true
    }

    /// Override to control content header validity.  If this returns
    /// false, then a 501 NotImplemented reply will result.  Defaults
    /// to true.
    fn valid_content_header(&self, _: &Request, _: &mut Response) -> bool {
        true
    }

    /// Override to control content type validity.  If this returns
    /// false, then a 415 UnsupportedMediaType reply will result.
    /// Defaults to true.
    fn known_content_type(&self, _: &Request, _: &mut Response) -> bool {
        true
    }

    /// Override to control content length validity.  If this returns
    /// false, then a 413 RequestEntityTooLarge reply will result.
    /// Defaults to true.
    fn valid_entity_length(&self, _: &Request, _: &mut Response) -> bool {
        true
    }

    /// Override to control whether an entity exists.  If this returns
    /// false, then the entity is deemed not too exist.  This effects
    /// the handling of POST, PUT, and DELETE verbs.  Defaults to
    /// true.
    fn exists(&self, _: &Request, _: &mut Response) -> bool {
        true
    }

    /// Override to control whether an entity once existed.  If this
    /// returns false, then the entity is deemed not to have existed.
    /// This effects the handling of GET, POST, and PUT verbs.
    /// Defaults to true.
    fn existed(&self, _: &Request, _: &mut Response) -> bool {
        false
    }

    /// Control whether an entity is returned.  If false, returns 205 NoContent.
    /// Defaults to false.
    fn respond_with_entity(&self, _: &Request, _: &mut Response) -> bool {
        false
    }

    /// Indicates whether an entity was successfully created for the request.
    /// Defaults to true.
    fn new(&self, _: &Request, _: &mut Response) -> bool {
        true
    }

    /// Controls whether to redirect after a POST request.  Defaults
    /// to false.
    fn post_redirect(&self, _: &Request, _: &mut Response) -> bool {
        false
    }

    /// Indicates the PUT request should be made to a different URL.
    /// Defaults to false.
    fn put_to_different_url(&self, _: &Request, _: &mut Response) -> bool {
        false
    }

    /// Controls whether to return a 300 MultipleChoices response.
    /// Defaults to false.
    fn multiple_representations(&self, _: &Request, _: &mut Response) -> bool {
        false
    }

    /// Indicates the PUT request has resulted in a conflict.  If this
    /// returns true, it will cause a 409 Conflict response.  Defaults
    /// to false.
    fn conflict(&self, _: &Request, _: &mut Response) -> bool {
        false
    }

    /// Controls whether a POST to a non existing entity is handled.
    /// When false, causes a 410 Gone response.  Defaults to true.
    fn can_post_to_missing(&self, _: &Request, _: &mut Response) -> bool {
        true
    }

    /// Controls whether a POST to a deleted entity is handled.
    /// When false, causes a 410 Gone response.  Defaults to false.
    fn can_post_to_gone(&self, _: &Request, _: &mut Response) -> bool {
        false
    }

    /// Controls whether a PUT to a non-existing entity is handled.
    /// When false, causes a 501 NotImplemented response.  Defaults to true.
    fn can_put_to_missing(&self, _: &Request, _: &mut Response) -> bool {
        true
    }

    /// Indicates whether a resource was moved permanently.  Defaults
    /// to false.
    fn moved_permanently(&self, _: &Request, _: &mut Response) -> bool {
        false
    }

    /// Indicates whether a resource was moved temporarily.  Defaults
    /// to false.
    fn moved_temporarily(&self, _: &Request, _: &mut Response) -> bool {
        false
    }

    /// Indicates whether a delete request was processed.  Defaults to
    /// true.
    fn delete_enacted(&self, _: &Request, _: &mut Response) -> bool {
        true
    }

    /// Indicates whether an entity is processable.  Returns 422
    /// UnprocessableEntity when false.  Defaults to true.
    fn processable(&self, _: &Request, _: &mut Response) -> bool {
        true
    }

    /// Return an optional ETag for the entity
    fn etag(&self, _: &Request,
            _: &mut Response) -> Option<headers::Etag> {
        None
    }

    /// Return an optional last modified time for the entity
    fn last_modified(&self, _: &Request, _: &Response) -> Option<Tm> {
        None
    }

    // Actions

    /// Execute a DELETE request.  Will assert! by default.
    fn delete(&self, _: &Request, _: &mut Response) -> ResourceResult {
        assert!(false, "not implemented, delete");
        Err(NotImplemented)
    }

    /// Execute a PATCH request.  Will assert! by default.
    fn patch(&self, _: &Request, _: &mut Response) -> ResourceResult {
        assert!(false, "not implemented, patch");
        Err(NotImplemented)
    }

    /// Execute a POST request.  Will assert! by default.
    fn post(&self, _: &Request, _: &mut Response) -> ResourceResult {
        assert!(false, "not implemented, post");
        Err(NotImplemented)
    }

    /// Execute a PUT request.  Will assert! by default.
    fn put(&self, _: &Request, _: &mut Response) -> ResourceResult {
        assert!(false, "not implemented, put");
        Err(NotImplemented)
    }



    // some data returning methods - not sure these are really wanted

    /// Return a vector of available languages.
    fn available_languages(&self, _: &Request,
                           _: &mut Response) -> Vec<String> {
        vec!["*".to_string()]
    }

    /// Return a vector of available charsets.
    fn available_charsets(&self, _: &Request,
                          _: &mut Response) -> Vec<String> {
        vec!["UTF-8".to_string()]
    }

    /// Return a vector of available encodings.
    fn available_encodings(&self, _: &Request,
                           _: &mut Response) -> Vec<Encoding> {
        vec![Encoding::Identity]
    }

    /// Return a vector of available content types.
    fn available_content_types(&self, _: &Request,
                               _: &mut Response) -> Vec<Mime> {
        vec![]
    }


    /// base logic

    #[allow(missing_docs)]
    fn accept_exists(&self, req: &Request, resp: &mut Response) -> bool {
        match req.headers.get::<headers::Accept>() {
            Some(_) => true,
            None => match content_neg::best_content_type(
                &vec![QualityItem::<Mime>{
                    item: Mime(TopLevel::Star, SubLevel::Star, vec![]),
                    quality: 1.0f32
                }],
                &self.available_content_types(req,resp)) {
                Some(ct) => {resp.set_mut(ct); true}
                None => false
            }
        }
    }

    #[allow(missing_docs)]
    fn media_type_available(&self, req: &Request, resp: &mut Response) -> bool {
        match req.headers.get::<headers::Accept>() {
            Some(cts) => match content_neg::best_content_type(
                &cts,
                &self.available_content_types(req,resp)) {
                Some(ct) => {resp.set_mut(ct); true}
                None => false
            },
            None => true
        }
    }



    #[allow(missing_docs)]
    fn language_available(&self, req: &Request, resp: &mut Response) -> bool {
        match req.headers.get::<hyper_headers::AcceptLanguage>() {
            Some(_) => match content_neg::best_language(
                vec![QualityItem::<String>{
                    item: "*".to_string(),
                    quality: 1.0f32}],
                &self.available_languages(req,resp)) {
                Some(l) => {resp.set_mut(l); true}
                None => false
            },
            None =>  true
        }
    }

    #[allow(missing_docs)]
    fn charset_available(&self, req: &Request, resp: &mut Response) -> bool {
        match req.headers.get::<hyper_headers::AcceptCharset>() {
            Some(&hyper_headers::AcceptCharset(ref x)) => match content_neg::best_charset(
                x, &self.available_charsets(req,resp)) {
                Some(l) => {resp.set_mut(l); true}
                None => false
            },
            None =>  true
        }
    }

    #[allow(missing_docs)]
    fn encoding_available(&self, req: &Request, resp: &mut Response) -> bool {
        match req.headers.get::<headers::AcceptEncoding>() {
            Some(&headers::AcceptEncoding(ref x)) => match content_neg::best_encoding(
                x, &self.available_encodings(req,resp)) {
                Some(_) => {  // FIXME resp.set_mut(l);
                    true}
                None => false
            },
            None =>  true
        }
    }

    #[allow(missing_docs)]
    fn if_match(&self, req: &Request, resp: &mut Response) -> bool {
        match req.headers.get::<headers::Etag>() {
            Some(&headers::Etag(ref x)) => {
                match self.etag(req, resp) {
                    Some(ref tag) => strong_match(x,tag),
                    None => false
                }
            },
            _ => false
        }
    }

    #[allow(missing_docs)]
    fn if_none_match(&self, req: &Request, resp: &mut Response) -> bool {
        match req.headers.get::<headers::Etag>() {
            Some(&headers::Etag(ref x)) => {
                match self.etag(req, resp) {
                    Some(ref tag) => weak_match(x,tag),
                    None => false
                }
            },
            _ => false
        }
    }

    #[allow(missing_docs)]
    fn if_match_star(&self, req: &Request, _: &mut Response) -> bool {
        match req.headers.get::<hyper_headers::IfMatch>() {
            Some(&hyper_headers::IfMatch(hyper_headers::EntityTagMatch::Star)) =>
                true,
            _ => false
        }
    }

    #[allow(missing_docs)]
    fn if_none_match_star(&self, req: &Request, _: &mut Response) -> bool {
        match req.headers.get::<hyper_headers::IfNoneMatch>() {
            Some(&hyper_headers::IfNoneMatch(hyper_headers::EntityTagMatch::Star)) =>
                true,
            _ => false
        }
    }

    #[allow(missing_docs)]
    fn unmodified_since(&self, req: &Request, resp: &mut Response) -> bool {
        match req.headers.get::<headers::IfUnmodifiedSince>() {
            Some(ref x) => {
                match self.last_modified(req, resp) {
                    Some(ref y) => y<=x,
                    None => false
                }
            }
            None => false
        }
    }

    #[allow(missing_docs)]
    fn modified_since(&self, req: &Request, resp: &mut Response) -> bool {
        match req.headers.get::<headers::IfUnmodifiedSince>() {
            Some(ref x) => {
                match self.last_modified(req, resp) {
                    Some(ref y) => y>x,
                    None => false
                }
            }
            None => false
        }
    }

    #[allow(missing_docs)]
    fn if_match_star_exists_for_missing(&self, req: &Request,
                                        _: &mut Response) -> bool {
        match req.headers.get::<hyper_headers::IfMatch>() {
            Some(&hyper_headers::IfMatch(hyper_headers::EntityTagMatch::Star)) => true,
            _ => false
        }
    }

    /// logic functions
    #[allow(missing_docs)]
    fn service_available_decision(&self,
                                  req: &Request,
                                  resp: &mut Response) -> ResourceResult {
        decision_body!(self, req, resp, service_available,
                       known_method_decision, handle_service_unavailable)
    }

    #[allow(missing_docs)]
    fn known_method_decision(&self, req: &Request,
                             resp: &mut Response) -> ResourceResult {
        decision_body!(self, req, resp, known_method,
                       uri_too_long_decision, handle_unknown_method)
    }

    #[allow(missing_docs)]
    fn uri_too_long_decision(&self, req: &Request,
                             resp: &mut Response) -> ResourceResult {
        decision_body!(self, req, resp, uri_too_long,
                       handle_uri_too_long, method_allowed_decision)
    }

    #[allow(missing_docs)]
    fn method_allowed_decision(&self, req: &Request,
                               resp: &mut Response) -> ResourceResult {
        decision_body!(self, req, resp, method_allowed,
                       malformed_decision, handle_method_not_allowed)
    }

    #[allow(missing_docs)]
    fn malformed_decision(&self, req: &Request,
                          resp: &mut Response) -> ResourceResult {
        decision_body!(self, req, resp, malformed,
                       handle_malformed, authorized_decision)
    }

    #[allow(missing_docs)]
    fn authorized_decision(&self, req: &Request,
                           resp: &mut Response) -> ResourceResult {
        decision_body!(self, req, resp, authorized,
                       allowed_decision, handle_unauthorized)
    }

    #[allow(missing_docs)]
    fn allowed_decision(&self, req: &Request,
                        resp: &mut Response) -> ResourceResult {
        decision_body!(self, req, resp, allowed,
                       valid_content_header_decision, handle_forbidden)
    }

    #[allow(missing_docs)]
    fn valid_content_header_decision(&self,
                                     req: &Request,
                                     resp: &mut Response)
                                     -> ResourceResult {
        decision_body!(self, req, resp, valid_content_header,
                       known_content_type_decision, handle_not_implemented)
    }

    #[allow(missing_docs)]
    fn known_content_type_decision(&self,
                                   req: &Request,
                                   resp: &mut Response)
                                   -> ResourceResult {
        decision_body!(self, req, resp, known_content_type,
                       valid_entity_length_decision,
                       handle_unsupported_media_type)
    }

    #[allow(missing_docs)]
    fn valid_entity_length_decision(&self,
                                    req: &Request,
                                    resp: &mut Response)
                                    -> ResourceResult {
        decision_body!(self, req, resp, valid_entity_length,
                       is_options_decision,
                       handle_request_entity_too_large)
    }

    #[allow(missing_docs)]
    fn is_options_decision(&self, req: &Request,
                           resp: &mut Response) -> ResourceResult {
        decision_body!(self, req, resp, req.method == method::Options,
                       handle_options, accept_exists_decision)
    }

    #[allow(missing_docs)]
    fn accept_exists_decision(&self, req: &Request,
                              resp: &mut Response) -> ResourceResult {
        decision_body!(self, req, resp, accept_exists,
                       media_type_available_decision,
                       accept_language_exists_decision)
    }

    #[allow(missing_docs)]
    fn media_type_available_decision(&self,
                                     req: &Request,
                                     resp: &mut Response)
                                     -> ResourceResult {
        decision_body!(self, req, resp, media_type_available,
                       accept_language_exists_decision,
                       handle_not_acceptable)
    }

    #[allow(missing_docs)]
    fn accept_language_exists_decision(&self,
                                       req: &Request,
                                       resp: &mut Response)
                                       -> ResourceResult {
        decision_body!(self, req, resp,
                       header_exists::<hyper_headers::AcceptLanguage>(req),
                       language_available_decision,
                       accept_charset_exists_decision)
                                       }

    #[allow(missing_docs)]
    fn language_available_decision(&self,
                                   req: &Request,
                                   resp: &mut Response)
                                   -> ResourceResult {
        decision_body!(self, req, resp, language_available,
                       accept_charset_exists_decision,
                       handle_not_acceptable)
    }

    #[allow(missing_docs)]
    fn accept_charset_exists_decision(&self,
                                      req: &Request,
                                      resp: &mut Response)
                                      -> ResourceResult {
        decision_body!(self, req, resp,
                       header_exists::<hyper_headers::AcceptCharset>(req),
                       charset_available_decision,
                       accept_encoding_exists_decision)
    }

    #[allow(missing_docs)]
    fn charset_available_decision(&self,
                                  req: &Request,
                                  resp: &mut Response) -> ResourceResult {
        decision_body!(self, req, resp, charset_available,
                       accept_encoding_exists_decision,
                       handle_not_acceptable)
    }

    #[allow(missing_docs)]
    fn accept_encoding_exists_decision(&self,
                                       req: &Request,
                                       resp: &mut Response)
                                       -> ResourceResult {
        decision_body!(self, req, resp,
                       header_exists::<headers::AcceptEncoding>(req),
                       encoding_available_decision,
                       processable_decision)
    }

    #[allow(missing_docs)]
    fn encoding_available_decision(&self,
                                   req: &Request,
                                   resp: &mut Response)
                                   -> ResourceResult {
        decision_body!(self, req, resp, encoding_available,
                       processable_decision,
                       handle_not_acceptable)
    }

    #[allow(missing_docs)]
    fn processable_decision(&self,
                            req: &Request,
                            resp: &mut Response) -> ResourceResult {
        decision_body!(self, req, resp, processable,
                       exists_decision,
                       handle_unprocessable_entity)
    }

    #[allow(missing_docs)]
    fn exists_decision(&self,
                       req: &Request,
                       resp: &mut Response) -> ResourceResult {
        decision_body!(self, req, resp, exists,
                       if_match_exists_decision,
                       if_match_star_exists_for_missing_decision)
    }

    #[allow(missing_docs)]
    fn if_match_exists_decision(&self,
                                req: &Request,
                                resp: &mut Response) -> ResourceResult {
        decision_body!(self, req, resp,
                       header_exists::<hyper_headers::IfMatch>(req),
                       if_match_star_decision,
                       if_unmodified_since_exists_decision)
    }

    #[allow(missing_docs)]
    fn if_match_star_decision(&self,
                              req: &Request,
                              resp: &mut Response) -> ResourceResult {
        decision_body!(self, req, resp, if_match_star,
                       if_unmodified_since_exists_decision,
                       if_match_decision)
    }

    #[allow(missing_docs)]
    fn if_match_decision(&self,
                                          req: &Request,
                                          resp: &mut Response) -> ResourceResult {
        decision_body!(self, req, resp, if_match,
                       if_unmodified_since_exists_decision,
                       handle_precondition_failed)
    }

    #[allow(missing_docs)]
    fn if_unmodified_since_exists_decision(&self,
                                           req: &Request,
                                           resp: &mut Response)
                                           -> ResourceResult {
        decision_body!(self, req, resp,
                       header_exists::<headers::IfUnmodifiedSince>(req),
                       if_unmodified_since_decision,
                       if_none_match_exists_decision)
    }

    #[allow(missing_docs)]
    fn if_unmodified_since_decision(&self,
                                 req: &Request,
                                 resp: &mut Response) -> ResourceResult {
        decision_body!(self, req, resp, unmodified_since,
                       handle_precondition_failed,
                       if_none_match_exists_decision)
    }

    #[allow(missing_docs)]
    fn if_none_match_exists_decision(&self,
                                     req: &Request,
                                     resp: &mut Response)
                                     -> ResourceResult {
        decision_body!(self, req, resp,
                       header_exists::<hyper_headers::IfNoneMatch>(req),
                       if_none_match_star_decision,
                       if_modified_since_exists_decision)
    }

    #[allow(missing_docs)]
    fn if_none_match_star_decision(&self,
                                   req: &Request,
                                   resp: &mut Response) -> ResourceResult {
        decision_body!(self, req, resp, if_none_match_star,
                       if_none_match_decision,
                       none_match_status_decision)
    }

    #[allow(missing_docs)]
    fn if_none_match_decision(&self,
                        req: &Request,
                        resp: &mut Response) -> ResourceResult {
        decision_body!(self, req, resp, if_none_match,
                       none_match_status_decision,
                       if_modified_since_exists_decision)
    }

    #[allow(missing_docs)]
    fn none_match_status_decision(&self,
                                  req: &Request,
                                  resp: &mut Response) -> ResourceResult {
        decision_body!(self, req, resp,
                       req.method == method::Get || req.method == method::Head,
                       handle_not_modified,
                       handle_precondition_failed)
    }

    #[allow(missing_docs)]
    fn if_modified_since_exists_decision(&self,
                                         req: &Request,
                                         resp: &mut Response)
                                         -> ResourceResult {
        decision_body!(self, req, resp,
                       header_exists::<headers::IfModifiedSince>(req),
                       if_modified_since_decision,
                       method_delete_decision)
    }

    #[allow(missing_docs)]
    fn if_modified_since_decision(&self,
                                  req: &Request,
                                  resp: &mut Response) -> ResourceResult {
        decision_body!(self, req, resp, modified_since,
                       method_delete_decision,
                       handle_not_modified)
    }

    #[allow(missing_docs)]
    fn method_delete_decision(&self,
                                req: &Request,
                                resp: &mut Response) -> ResourceResult {
        decision_body!(self, req, resp, req.method == method::Delete,
                       delete,
                       method_patch_decision)
    }

    #[allow(missing_docs)]
    fn method_patch_decision(&self,
                                req: &Request,
                                resp: &mut Response) -> ResourceResult {
        decision_body!(self, req, resp, req.method == method::Patch,
                       patch,
                       post_to_existing_decision)
    }

    #[allow(missing_docs)]
    fn post_to_existing_decision(&self,
                                 req: &Request,
                                 resp: &mut Response) -> ResourceResult {
        decision_body!(self, req, resp, req.method == method::Post,
                       post,
                       put_to_existing_decision)
    }

    #[allow(missing_docs)]
    fn put_to_existing_decision(&self,
                                req: &Request,
                                resp: &mut Response) -> ResourceResult {
        decision_body!(self, req, resp, req.method == method::Put,
                       conflict_decision,
                       multiple_representations_decision)
    }

    #[allow(missing_docs)]
    fn if_match_star_exists_for_missing_decision(&self,
                                                 req: &Request,
                                                 resp: &mut Response) -> ResourceResult {
        decision_body!(self, req, resp, if_match_star_exists_for_missing,
                       handle_precondition_failed,
                       method_put_decision)
    }

    #[allow(missing_docs)]
    fn method_put_decision(&self,
                           req: &Request,
                           resp: &mut Response) -> ResourceResult {
        decision_body!(self, req, resp, req.method == method::Put,
                       put_to_different_url_decision,
                       existed_decision)
    }

    #[allow(missing_docs)]
    fn put_to_different_url_decision(&self,
                                     req: &Request,
                                     resp: &mut Response) -> ResourceResult {
        decision_body!(self, req, resp, put_to_different_url,
                       handle_moved_permanently,
                       can_put_to_missing_decision)
    }

    #[allow(missing_docs)]
    fn can_put_to_missing_decision(&self,
                                 req: &Request,
                                 resp: &mut Response) -> ResourceResult {
        decision_body!(self, req, resp, can_put_to_missing,
                       conflict_decision,
                       handle_not_implemented)
    }

    #[allow(missing_docs)]
    fn conflict_decision(&self,
                         req: &Request,
                         resp: &mut Response) -> ResourceResult {
        decision_body!(self, req, resp, conflict,
                       handle_conflict,
                       put)
    }

    #[allow(missing_docs)]
    fn existed_decision(&self,
                                 req: &Request,
                                 resp: &mut Response) -> ResourceResult {
        decision_body!(self, req, resp, existed,
                       moved_permanently_decision,
                       post_to_missing_decision)
    }

    #[allow(missing_docs)]
    fn moved_permanently_decision(&self,
                                  req: &Request,
                                  resp: &mut Response) -> ResourceResult {
        decision_body!(self, req, resp, moved_permanently,
                       handle_moved_permanently,
                       moved_temporarily_decision)
    }

    #[allow(missing_docs)]
    fn moved_temporarily_decision(&self,
                                  req: &Request,
                                  resp: &mut Response) -> ResourceResult {
        decision_body!(self, req, resp, moved_temporarily,
                       handle_moved_temporarily,
                       post_to_gone_decision)
    }

    #[allow(missing_docs)]
    fn post_to_gone_decision(&self,
                                  req: &Request,
                                  resp: &mut Response) -> ResourceResult {
        decision_body!(self, req, resp, req.method == method::Post,
                       can_post_to_gone_decision,
                       handle_gone)
    }

    #[allow(missing_docs)]
    fn can_post_to_gone_decision(&self,
                                 req: &Request,
                                 resp: &mut Response) -> ResourceResult {
        decision_body!(self, req, resp, can_post_to_gone,
                       post,
                       handle_gone)
    }

    #[allow(missing_docs)]
    fn post_to_missing_decision(&self,
                                req: &Request,
                                resp: &mut Response) -> ResourceResult {
        decision_body!(self, req, resp, req.method == method::Post,
                       can_post_to_missing_decision,
                       handle_not_found)
    }

    #[allow(missing_docs)]
    fn can_post_to_missing_decision(&self,
                                    req: &Request,
                                    resp: &mut Response) -> ResourceResult {
        decision_body!(self, req, resp, can_post_to_missing,
                       post,
                       handle_not_found)
    }

    #[allow(missing_docs)]
    fn post_redirect_decision(&self,
                              req: &Request,
                              resp: &mut Response) -> ResourceResult {
        decision_body!(self, req, resp, post_redirect,
                       handle_see_other,
                       new_decision)
    }

    #[allow(missing_docs)]
    fn new_decision(&self,
                    req: &Request,
                    resp: &mut Response) -> ResourceResult {
        decision_body!(self, req, resp, new,
                       handle_created,
                       respond_with_entity_decision)
    }

    #[allow(missing_docs)]
    fn respond_with_entity_decision(&self,
                                    req: &Request,
                                    resp: &mut Response) -> ResourceResult {
        decision_body!(self, req, resp, respond_with_entity,
                       multiple_representations_decision,
                       handle_no_content)
    }

    #[allow(missing_docs)]
    fn multiple_representations_decision(&self,
                                    req: &Request,
                                    resp: &mut Response) -> ResourceResult {
        decision_body!(self, req, resp, multiple_representations,
                       handle_multiple_representations,
                       handle_ok)
    }

    // default handlers

    #[allow(missing_docs)]
    fn handle_service_unavailable(&self, _: &Request,
                                  resp: &mut Response) -> ResourceResult {
        resp.set_mut((status::ServiceUnavailable, "Service unavailable"));
        Ok(())
    }

    #[allow(missing_docs)]
    fn handle_unknown_method(&self, _: &Request,
                             resp: &mut Response) -> ResourceResult {
        resp.set_mut((status::NotImplemented, "Unknown method"));
        Ok(())
    }

    #[allow(missing_docs)]
    fn handle_uri_too_long(&self, _: &Request,
                           resp: &mut Response) -> ResourceResult {
        resp.set_mut((status::NotImplemented, "Request URI too long"));
        Ok(())
    }

    #[allow(missing_docs)]
    fn handle_method_not_allowed(&self, _: &Request,
                                 resp: &mut Response) -> ResourceResult {
        resp.set_mut((status::MethodNotAllowed, "Method not allowed"));
        Ok(())
    }

    #[allow(missing_docs)]
    fn handle_malformed(&self, _: &Request,
                        resp: &mut Response) -> ResourceResult {
        resp.set_mut((status::BadRequest, "Bad request"));
        Ok(())
    }

    #[allow(missing_docs)]
    fn handle_unauthorized(&self, _: &Request,
                           resp: &mut Response) -> ResourceResult {
        resp.set_mut((status::Unauthorized, "Unauthorized"));
        Ok(())
    }

    #[allow(missing_docs)]
    fn handle_forbidden(&self, _: &Request,
                        resp: &mut Response) -> ResourceResult {
        resp.set_mut((status::Forbidden, "Forbidden"));
        Ok(())
    }

    #[allow(missing_docs)]
    fn handle_not_implemented(&self, _: &Request,
                              resp: &mut Response) -> ResourceResult {
        resp.set_mut((status::NotImplemented, "Not implemented"));
        Ok(())
    }

    #[allow(missing_docs)]
    fn handle_unsupported_media_type(&self, _: &Request,
                                     resp: &mut Response) -> ResourceResult {
        resp.set_mut((status::UnsupportedMediaType, "Unsupported media type"));
        Ok(())
    }

    #[allow(missing_docs)]
    fn handle_request_entity_too_large(&self, _: &Request,
                                       resp: &mut Response) -> ResourceResult {
        resp.set_mut((status::RequestEntityTooLarge,
                      "Request entity too large"));
        Ok(())
    }

    #[allow(missing_docs)]
    fn handle_not_acceptable(&self, _: &Request,
                             resp: &mut Response) -> ResourceResult {
        resp.set_mut((status::NotAcceptable, "Not Acceptable"));
        Ok(())
    }

    #[allow(missing_docs)]
    fn handle_unprocessable_entity(&self, _: &Request,
                                   resp: &mut Response) -> ResourceResult {
        resp.set_mut((status::UnprocessableEntity, "Unprocessable entity"));
        Ok(())
    }

    #[allow(missing_docs)]
    fn handle_conflict(&self, _: &Request,
                       resp: &mut Response) -> ResourceResult {
        resp.set_mut((status::Conflict, "Conflict"));
        Ok(())
    }

    #[allow(missing_docs)]
    fn handle_see_other(&self, _: &Request,
                        resp: &mut Response) -> ResourceResult {
        resp.set_mut((status::SeeOther, "Conflict"));
        Ok(())
    }

    #[allow(missing_docs)]
    fn handle_created(&self, _: &Request,
                      resp: &mut Response) -> ResourceResult {
        resp.set_mut((status::Created, "Created"));
        Ok(())
    }

    #[allow(missing_docs)]
    fn handle_precondition_failed(&self, _: &Request,
                                  resp: &mut Response) -> ResourceResult {
        resp.set_mut((status::PreconditionFailed, "Precondition failed"));
        Ok(())
    }

    #[allow(missing_docs)]
    fn handle_not_modified(&self, _: &Request,
                           resp: &mut Response) -> ResourceResult {
        resp.set_mut((status::NotModified, "Not modified"));
        Ok(())
    }

    #[allow(missing_docs)]
    fn handle_moved_permanently(&self, _: &Request,
                                resp: &mut Response) -> ResourceResult {
        resp.set_mut((status::PermanentRedirect, "Permanent redirect"));
        Ok(())
    }

    #[allow(missing_docs)]
    fn handle_moved_temporarily(&self, _: &Request,
                                resp: &mut Response) -> ResourceResult {
        resp.set_mut((status::TemporaryRedirect, "Temporary redirect"));
        Ok(())
    }

    #[allow(missing_docs)]
    fn handle_gone(&self, _: &Request, resp: &mut Response) -> ResourceResult {
        resp.set_mut((status::Gone, "Gone"));
        Ok(())
    }

    #[allow(missing_docs)]
    fn handle_not_found(&self, _: &Request,
                        resp: &mut Response) -> ResourceResult {
        resp.set_mut((status::NotFound, "Not found"));
        Ok(())
    }

    #[allow(missing_docs)]
    fn handle_no_content(&self, _: &Request,
                         resp: &mut Response) -> ResourceResult {
        resp.set_mut((status::NoContent, "No content"));
        Ok(())
    }

    #[allow(missing_docs)]
    fn handle_multiple_representations(&self, _: &Request,
                                       resp: &mut Response) -> ResourceResult {
        resp.set_mut((status::MultipleChoices, "Multiple Choices"));
        Ok(())
    }

    #[allow(missing_docs)]
    fn handle_ok(&self,
                 _: &Request,
                 resp: &mut Response) -> ResourceResult {
        resp.set_mut(status::Ok);
        Ok(())
    }

    #[allow(missing_docs)]
    fn handle_options(&self, _: &Request,
                      resp: &mut Response) -> ResourceResult {
        resp.set_mut((status::Ok, ""));
        Ok(())
    }


}

/// Handler for a resource
pub fn handle<T>(resource: &T,
                 req: &mut Request) -> IronResult<Response> where T: Resource {
    let mut resp = Response::new();
    try!(resource.service_available_decision(req, &mut resp));
    Ok(resp)
}

fn header_exists<T: headers::Header+headers::HeaderFormat>(req: &Request) -> bool {
    req.headers.get::<T>().is_some()
}

macro_rules! resource {
    ($s:ident) => {
        impl Resource for $s {}
        resource_handler!($s);
    }
}

macro_rules! resource_handler {
    ($s:ident) => {
        impl Handler for $s {
            fn handle(&self, req: &mut Request) -> IronResult<Response> {
            handle(self, req)
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::{Arc,Mutex};
    use hyper::{self, IpAddr};
    use hyper::server::Listening;
    use iron::{Handler, Iron, IronResult, Request, Response, status};
    use iron::error::HttpResult;
    use iron::modifier::Set;


    fn http_server<T>(resource: T) -> HttpResult<Listening> where T: Resource+Handler+Sync+Send {
        let address = IpAddr::Ipv4Addr(127,0,0,1);
        let count = Arc::new(Mutex::new(0u8));
        let server_count = count.clone();
        Iron::new(resource).listen((address,0u16))
    }

    struct GetOk;
    resource!(GetOk);

    #[test]
    fn test_get_ok() {
      let mut listen = http_server(GetOk).unwrap();
      let mut client = hyper::Client::new();
       match client.get(&format!("http://127.0.0.1:{}", listen.socket.port)[])
          .send() {
              Ok(ref mut r) => {
                  assert_eq!("", r.read_to_string().unwrap());
                  assert_eq!(status::Ok, r.status);
              },
              Err(x) => assert!(false, "get failed")
          };
       listen.close().unwrap();
    }


    struct GetOkContent;
    resource_handler!(GetOkContent);

    impl Resource for GetOkContent {
        fn handle_ok(&self, req: &Request, resp: &mut Response) -> ResourceResult {
            resp.set_mut((status::Ok, "hello"));
            Ok(())
        }
    }

    #[test]
    fn test_get_ok_content() {
      let mut listen = http_server(GetOkContent).unwrap();
      let mut client = hyper::Client::new();
       match client.get(&format!("http://127.0.0.1:{}", listen.socket.port)[])
          .send() {
              Ok(ref mut r) => {
                  assert_eq!("hello", r.read_to_string().unwrap());
                  assert_eq!(status::Ok, r.status);
              },
              Err(x) => assert!(false, "get failed")
          };
       listen.close().unwrap();
    }
}