Mercurial > pub > Impl
annotate Lib/IMPL/Web/Application/Response.pm @ 95:67eb8eaec3d4
Added a security authority property to the Context and Security classes
Added a WriteResponse method to the SecureCookie class
Added a setCookie method to the Response class
| author | wizard |
|---|---|
| date | Thu, 29 Apr 2010 02:21:27 +0400 |
| parents | 9f5795a10939 |
| children | 964587c5183c |
| rev | line source |
|---|---|
|
59
0f3e369553bd
Rewritten property implementation (probably become slower but more flexible)
wizard
parents:
58
diff
changeset
|
1 package IMPL::Web::Application::Response; |
| 57 | 2 use strict; |
| 3 | |
| 4 use base qw(IMPL::Object IMPL::Object::Autofill); | |
| 5 | |
| 6 require IMPL::Exception; | |
| 7 require CGI; | |
| 8 require CGI::Cookie; | |
| 9 | |
| 58 | 10 use Carp; |
|
63
76b878ad6596
Added serialization support for the IMPL::Object::List
wizard
parents:
59
diff
changeset
|
11 use Encode; |
| 57 | 12 use IMPL::Class::Property; |
| 13 | |
|
63
76b878ad6596
Added serialization support for the IMPL::Object::List
wizard
parents:
59
diff
changeset
|
14 #todo: add binary method to set a binary encoding, set it automatic when type isn't a text |
|
76b878ad6596
Added serialization support for the IMPL::Object::List
wizard
parents:
59
diff
changeset
|
15 |
| 57 | 16 BEGIN { |
| 67 | 17 # автозаполнение буде происходить в порядке объявления |
| 57 | 18 public property query => prop_get | owner_set; # cgi query |
| 19 public property status => prop_all, { validator => \&_checkHeaderPrinted }; | |
| 20 public property contentType => prop_all, { validator => \&_checkHeaderPrinted }; # String | |
| 58 | 21 public property charset => { get => \&_charset, set => \&_charset }, { validator => \&_checkHeaderPrinted }; |
| 57 | 22 public property expires => prop_all, { validator => \&_checkHeaderPrinted }; |
| 23 public property cookies => prop_all, { validator => \&_checkHeaderPrinted }; # Hash | |
| 24 | |
| 58 | 25 public property buffered => prop_all, { validator => \&_canChangeBuffer }; # Boolean |
| 57 | 26 public property streamOut => prop_get | owner_set; # stream |
| 27 public property streamBody => {get => \&getStreamBody }; # stream | |
| 58 | 28 public property isHeaderPrinted => prop_get | owner_set; # Boolean |
| 57 | 29 |
| 30 private property _bufferBody => prop_all; | |
| 31 private property _streamBody => prop_all; | |
| 32 } | |
| 33 | |
| 34 __PACKAGE__->PassThroughArgs; | |
| 35 | |
| 67 | 36 our %CTOR = ( |
| 37 'IMPL::Object::Autofill' => sub { | |
| 38 my %args = @_; | |
| 39 | |
| 40 $args{query} = CGI->new($args{query} || {}); | |
| 41 | |
| 42 %args; | |
| 43 } | |
| 44 ); | |
| 45 | |
| 57 | 46 sub CTOR { |
| 47 my ($this,%args) = @_; | |
| 48 | |
| 65 | 49 if (lc $this->streamOut eq 'memory') { |
| 50 my $dummy = ''; | |
| 51 open my $hout, '>:encoding(utf8)', \$dummy or die new IMPL::Exception("Failed to create memory stream",$!); | |
| 52 $this->streamOut($hout); | |
| 53 } elsif (not $this->streamOut) { | |
| 54 $this->streamOut(*STDOUT); | |
| 55 } else { | |
| 56 die new IMPL::InvalidArgumentException("Invalid parameter value",$this->streamOut); | |
| 57 } | |
| 58 | |
|
63
76b878ad6596
Added serialization support for the IMPL::Object::List
wizard
parents:
59
diff
changeset
|
59 $this->buffered(1) unless defined $this->buffered; |
|
76b878ad6596
Added serialization support for the IMPL::Object::List
wizard
parents:
59
diff
changeset
|
60 binmode $this->streamOut, ":encoding(".$this->charset.")"; |
| 57 | 61 } |
| 62 | |
| 63 sub _checkHeaderPrinted { | |
| 64 my ($this,$value) = @_; | |
| 65 | |
| 66 die new IMPL::InvalidOperationException() if $this->isHeaderPrinted; | |
| 67 } | |
| 68 | |
| 58 | 69 sub _canChangeBuffer { |
| 70 my ($this,$value) = @_; | |
| 71 | |
| 72 die new IMPL::InvalidOperationException() if $this->isHeaderPrinted or $this->_streamBody; | |
| 73 } | |
| 74 | |
| 75 sub _charset { | |
| 76 my $this = shift; | |
| 77 | |
|
63
76b878ad6596
Added serialization support for the IMPL::Object::List
wizard
parents:
59
diff
changeset
|
78 if (@_) { |
|
76b878ad6596
Added serialization support for the IMPL::Object::List
wizard
parents:
59
diff
changeset
|
79 my $charset = $this->query->charset(@_); |
|
76b878ad6596
Added serialization support for the IMPL::Object::List
wizard
parents:
59
diff
changeset
|
80 |
|
76b878ad6596
Added serialization support for the IMPL::Object::List
wizard
parents:
59
diff
changeset
|
81 my $hout = $this->streamOut; |
|
76b878ad6596
Added serialization support for the IMPL::Object::List
wizard
parents:
59
diff
changeset
|
82 |
|
76b878ad6596
Added serialization support for the IMPL::Object::List
wizard
parents:
59
diff
changeset
|
83 binmode $hout; |
|
76b878ad6596
Added serialization support for the IMPL::Object::List
wizard
parents:
59
diff
changeset
|
84 binmode $hout, ":encoding($charset)"; |
|
76b878ad6596
Added serialization support for the IMPL::Object::List
wizard
parents:
59
diff
changeset
|
85 |
|
76b878ad6596
Added serialization support for the IMPL::Object::List
wizard
parents:
59
diff
changeset
|
86 return $charset; |
|
76b878ad6596
Added serialization support for the IMPL::Object::List
wizard
parents:
59
diff
changeset
|
87 } else { |
|
76b878ad6596
Added serialization support for the IMPL::Object::List
wizard
parents:
59
diff
changeset
|
88 return $this->query->charset; |
|
76b878ad6596
Added serialization support for the IMPL::Object::List
wizard
parents:
59
diff
changeset
|
89 } |
| 58 | 90 } |
| 91 | |
| 57 | 92 sub _PrintHeader { |
| 93 my ($this) = @_; | |
| 94 | |
| 95 unless ($this->isHeaderPrinted) { | |
| 96 $this->isHeaderPrinted(1); | |
| 97 | |
| 98 my %opt; | |
| 99 | |
| 100 $opt{-type} = $this->contentType if $this->contentType; | |
| 101 $opt{-status} = $this->status if $this->status; | |
| 102 $opt{-expires} = $this->expires if $this->expires; | |
| 103 | |
| 104 my $refCookies = $this->cookies; | |
| 105 $opt{-cookie} = [map CGI::Cookie->new(-name => $_, $refCookies->{$_} ), keys %$refCookies] if $refCookies; | |
| 106 | |
| 107 my $hOut = $this->streamOut; | |
| 108 | |
| 109 print $hOut $this->query->header( | |
| 110 %opt | |
| 111 ); | |
| 112 } | |
| 113 } | |
| 114 | |
|
95
67eb8eaec3d4
Added a security authority property to the Context and Security classes
wizard
parents:
67
diff
changeset
|
115 sub setCookie { |
|
67eb8eaec3d4
Added a security authority property to the Context and Security classes
wizard
parents:
67
diff
changeset
|
116 my ($this,$name,$value) = @_; |
|
67eb8eaec3d4
Added a security authority property to the Context and Security classes
wizard
parents:
67
diff
changeset
|
117 |
|
67eb8eaec3d4
Added a security authority property to the Context and Security classes
wizard
parents:
67
diff
changeset
|
118 unless ($this->cookies) { |
|
67eb8eaec3d4
Added a security authority property to the Context and Security classes
wizard
parents:
67
diff
changeset
|
119 $this->cookies({$name,$value}); |
|
67eb8eaec3d4
Added a security authority property to the Context and Security classes
wizard
parents:
67
diff
changeset
|
120 } else { |
|
67eb8eaec3d4
Added a security authority property to the Context and Security classes
wizard
parents:
67
diff
changeset
|
121 $this->_checkHeaderPrinted(); |
|
67eb8eaec3d4
Added a security authority property to the Context and Security classes
wizard
parents:
67
diff
changeset
|
122 $this->cookies->{$name} = $value; |
|
67eb8eaec3d4
Added a security authority property to the Context and Security classes
wizard
parents:
67
diff
changeset
|
123 } |
|
67eb8eaec3d4
Added a security authority property to the Context and Security classes
wizard
parents:
67
diff
changeset
|
124 return $value; |
|
67eb8eaec3d4
Added a security authority property to the Context and Security classes
wizard
parents:
67
diff
changeset
|
125 } |
|
67eb8eaec3d4
Added a security authority property to the Context and Security classes
wizard
parents:
67
diff
changeset
|
126 |
| 57 | 127 sub getStreamBody { |
| 128 my ($this) = @_; | |
| 129 | |
| 58 | 130 return undef unless $this->streamOut; |
| 57 | 131 |
| 58 | 132 unless ($this->_streamBody) { |
| 133 if ($this->buffered) { | |
| 134 my $buffer = ""; | |
|
63
76b878ad6596
Added serialization support for the IMPL::Object::List
wizard
parents:
59
diff
changeset
|
135 |
| 58 | 136 $this->_bufferBody(\$buffer); |
| 137 | |
|
63
76b878ad6596
Added serialization support for the IMPL::Object::List
wizard
parents:
59
diff
changeset
|
138 open my $hBody, ">:encoding(utf-8)", \$buffer or die new IMPL::Exception("Failed to create buffer",$!); |
|
76b878ad6596
Added serialization support for the IMPL::Object::List
wizard
parents:
59
diff
changeset
|
139 |
|
76b878ad6596
Added serialization support for the IMPL::Object::List
wizard
parents:
59
diff
changeset
|
140 Encode::_utf8_on($buffer); |
| 58 | 141 |
| 142 $this->_streamBody($hBody); | |
| 143 } else { | |
| 144 $this->_PrintHeader(); | |
| 145 $this->_streamBody($this->streamOut); | |
| 146 } | |
| 57 | 147 } |
| 58 | 148 |
| 149 return $this->_streamBody; | |
| 57 | 150 } |
| 151 | |
| 152 sub Complete { | |
| 153 my ($this) = @_; | |
| 154 | |
| 155 return 0 unless $this->streamOut; | |
| 156 | |
| 157 my $hOut = $this->streamOut; | |
| 158 | |
| 159 $this->_PrintHeader(); | |
| 160 | |
|
63
76b878ad6596
Added serialization support for the IMPL::Object::List
wizard
parents:
59
diff
changeset
|
161 $this->_streamBody(undef); |
|
76b878ad6596
Added serialization support for the IMPL::Object::List
wizard
parents:
59
diff
changeset
|
162 |
| 57 | 163 if ($this->buffered) { |
| 164 print $hOut ${$this->_bufferBody}; | |
|
63
76b878ad6596
Added serialization support for the IMPL::Object::List
wizard
parents:
59
diff
changeset
|
165 } |
| 57 | 166 |
| 167 $this->_bufferBody(undef); | |
| 168 $this->streamOut(undef); | |
| 169 | |
| 170 return 1; | |
| 171 } | |
| 172 | |
| 173 sub Discard { | |
| 174 my ($this) = @_; | |
| 175 | |
| 58 | 176 carp "Discarding sent response" if $this->isHeaderPrinted; |
| 177 | |
| 57 | 178 $this->_streamBody(undef); |
| 179 $this->_bufferBody(undef); | |
| 180 $this->streamOut(undef); | |
| 181 } | |
| 182 | |
| 183 1; | |
| 184 | |
| 185 __END__ | |
| 186 | |
| 187 =pod | |
| 188 | |
| 67 | 189 =head1 NAME |
| 190 | |
| 191 C<IMPL::Web::Application::Response> - Ответ веб сервера непосредственно клиенту. | |
| 192 | |
| 58 | 193 =head1 DESCRIPTION |
| 57 | 194 |
| 67 | 195 C<[Infrastructure]> |
| 196 | |
| 197 Позволяет сформировать основные свойства заголовка и тело ответа. | |
| 198 | |
| 199 Создается объектом C<IMPL::Web::Application::Action> в процессе обработки запроса. | |
| 200 | |
| 201 Может использоваться обработчиками C<IMPL::Web::QueryHandler> в процессе выполнения запроса. | |
| 58 | 202 |
| 203 Объект позволяет буфферизировать вывод в тело ответа, что позволяет отменить или изменить | |
| 67 | 204 ответ в последний момент. Свойство C< isHeaderPrinted > используется для определения факта |
| 205 отправлки данных клиенту. | |
| 58 | 206 |
| 207 =head1 PROPERTIES | |
| 208 | |
| 209 =head2 HTTP Header | |
| 210 | |
| 211 Свойства отвечающие за заголовок HTTP ответа. Эти своства могут быть изменены до тех пор пока | |
| 212 не будет отправлен заголовок. В противном случае выдается исключение C< IMPL::InvalidOperationException >. | |
| 213 | |
| 214 =over | |
| 215 | |
| 67 | 216 =item C< [get] query > |
| 58 | 217 |
| 218 CGI запрос, который используется для вывода данных, заголовка и пр. Существует всегда. | |
| 219 | |
| 67 | 220 =item C< [get,set] status > |
| 58 | 221 |
| 222 Код ошибки HTTP. Например, '200 OK'. По умолчанию не установлен, при отправке клиенту бедт отправлен '200 ОК'. | |
| 223 | |
| 67 | 224 =item C< [get,set] contentType > |
| 58 | 225 |
| 226 Тип MIME. По умолчанию не установлен, подразумивается 'text/html'. | |
| 227 | |
| 67 | 228 =item C< [get,set] charset > |
| 58 | 229 |
| 230 Кодировка, синоним свойства query->charset. | |
| 231 | |
| 67 | 232 =item C< [get,set] expires > |
| 58 | 233 |
| 234 Определяет время жизни контента, например '+10m'. По умолчанию не задано и не передается. | |
| 235 | |
| 67 | 236 =item C< [get,set] cookies > |
| 58 | 237 |
| 238 Хеш массив с cookies, например C< { cart => ['foo','bar'], display => 'list' } >. | |
| 239 | |
| 240 =back | |
| 241 | |
| 242 =head2 Response behaviour | |
| 243 | |
| 244 Свойства отвечающие за поведение ответа. | |
| 245 | |
| 246 =over | |
| 247 | |
| 67 | 248 =item C< [get,set] buffered > |
| 58 | 249 |
| 250 C< True > - то тело ответа пишется в буффер и будет отправлено при вызове метода C< Complete >, | |
| 251 заголовок также будет отправлен после вызова метода C< Complete >. | |
| 252 | |
| 253 C< False > - тело ответа пишется непосредственно в поток к клиенту, при этом заголовок | |
| 254 будет отправлен при первом обращении к свойству C< streamBody > | |
| 255 | |
| 256 Это свойство можно менять до первого обращения к потоку для записи в тело ответа. | |
| 257 | |
| 67 | 258 =item C< [get] streamOut > |
| 58 | 259 |
| 260 Стандартный вывод CGI приложения. | |
| 261 | |
| 67 | 262 =item C< [get] streamBody > |
| 58 | 263 |
| 264 Поток для записи в тело ответа. | |
| 265 | |
| 67 | 266 =item C< [get] isHeadPrinted > |
| 58 | 267 |
| 268 Признак того, что заголовок уже был отправлен клиенту. | |
| 269 | |
| 270 =back | |
| 271 | |
| 272 =head1 METHODS | |
| 273 | |
| 274 =over | |
| 275 | |
| 276 =item C< Complete > | |
| 277 | |
| 278 Завершает отправку ответа. | |
| 279 | |
| 280 =item C< Discard > | |
| 281 | |
| 282 Отменяет отправку ответа, при этом если часть данных (например, заголовок) | |
| 283 уже была отправлена, выдает предупреждение в STDERR. | |
| 284 | |
| 285 =back | |
| 57 | 286 |
| 67 | 287 =head1 REMARKS |
| 288 | |
| 289 Данный объект является автозаполняемым, т.е. все его свойства можно задать через | |
| 290 именованные параметры конструктора. | |
| 291 | |
| 57 | 292 =cut |
