Wombat/Connector/HttpResponseBase.pm untested

filter: Statementstmt 0.0% 0 / 251 Branchbran 0.0% 0 / 94 Conditioncond 0.0% 0 / 20 MC/DCmcdc 0.0% 0 / 12 Subroutinesub 0.0% 0 / 42 Podpod 0.0% 0 / 30 totaltotal 0.0% 0 / 449 CC 48 SCAR 32.8
CC
48
Cov
0%
isEncodeable
132.0
sendHeaders
42.0
setHeader
30.0
CRAP 26.5
1 # -*- Mode: Perl; indent-tabs-mode: nil; -*-
2  
3 package Wombat::Connector::HttpResponseBase;
4  
5 =pod
6  
7 =head1 NAME
8  
9 Wombat::Connector::HttpResponseBase - internal http response base class
10  
11 =head1 SYNOPSIS
12  
13 package My::Connector::HttpResponse;
14  
15 use base qw(Wombat::Connector::HttpResponseBase);
16  
17 =head1 DESCRIPTION
18  
19 Convenience base implementation of B<Wombat::HttpResponse> and
20 B<Servlet::Http::HttpServletResponse> which can be used for most
21 connectors that implement the HTTP protocol. Only connector-specific
22 methods need to be implemented. Extends
23 B<Wombat::Connector::ResponseBase>.
24  
25 =cut
26  
27 use base qw(Wombat::HttpResponse Wombat::Connector::ResponseBase);
28 use fields qw(cookies headers message status);
29 use strict;
30 use warnings;
31  
32 use HTTP::Headers ();
33 use Servlet::Http::HttpServletResponse ();
34 use Servlet::Util::Exception ();
35 use URI ();
36 use Wombat::Connector::HttpResponseFacade ();
37 use Wombat::Globals ();
38 use Wombat::Util::CookieTools ();
39  
40 use constant STATUS_MESSAGES =>
41 {
42 100 => 'Continue',
43 101 => 'Switching Protocols',
44 200 => 'OK',
45 201 => 'Created',
46 202 => 'Accepted',
47 203 => 'Non-Authoritative Information',
48 204 => 'No Content',
49 205 => 'Reset Content',
50 206 => 'Partial Content',
51 300 => 'Multiple Choices',
52 301 => 'Moved Permanently',
53 302 => 'Moved Temporarily',
54 303 => 'See Other',
55 304 => 'Not Modified',
56 305 => 'Use Proxy',
57 400 => 'Bad Request',
58 401 => 'Unauthorized',
59 402 => 'Payment Required',
60 403 => 'Forbidden',
61 404 => 'Not Found',
62 405 => 'Method Not Allowed',
63 406 => 'Not Acceptable',
64 407 => 'Proxy Authentication Required',
65 408 => 'Request Timeout',
66 409 => 'Conflict',
67 410 => 'Gone',
68 411 => 'Length Required',
69 412 => 'Precondition Failed',
70 413 => 'Request Entity Too Large',
71 414 => 'Request URI Too Long',
72 415 => 'Unsupported Media Type',
73 416 => 'Requested Range Not Satisfiable',
74 417 => 'Expectation Failed',
75 500 => 'Internal Server Error',
76 501 => 'Not Implemented',
77 502 => 'Bad Gateway',
78 503 => 'Service Unavailable',
79 504 => 'Gateway Timeout',
80 505 => 'HTTP Version Not Supported',
81 };
82  
83 =pod
84  
85 =head1 CONSTRUCTOR
86  
87 =over
88  
89 =item new()
90  
91 Construct and return a B<Wombat::Connector::HttpResponseBase>
92 instance, initializing fields appropriately. If subclasses override the
93 constructor, they must be sure to call
94  
95 $self->SUPER::new();
96  
97 =back
98  
99 =cut
100  
101 sub new {
102 my $self = shift;
103 my $facade = shift;
104  
105 $self = fields::new($self) unless ref $self;
106 $self->SUPER::new($facade);
107  
108 return $self;
109 }
110  
111 =pod
112  
113 =head1 ACCESSOR METHODS
114  
115 =over
116  
117 =item getCookies()
118  
119 Return the list of Cookies for this Response.
120  
121 =cut
122  
123 sub getCookies {
124 my $self = shift;
125  
126 my @cookies = @{ $self->{cookies} };
127  
128 return wantarray ? @cookies : \@cookies;
129 }
130  
131 =item addCookie($cookie)
132  
133 Add the specified Cookie to those that will be included with this Response.
134  
135 B<Parameters:>
136  
137 =over
138  
139 =item $cookie
140  
141 the B<Servlet::Http::Cookie> to be added
142  
143 =back
144  
145 =cut
146  
147 sub addCookie {
148 my $self = shift;
149 my $cookie = shift;
150  
151 return 1 if $self->isCommitted();
152 return 1 if $self->isIncluded();
153  
154 push @{ $self->{cookies} }, $cookie;
155  
156 return 1;
157 }
158  
159 =pod
160  
161 =item clearCookies()
162  
163 Clear the list of Cookies for this Response;
164  
165 =cut
166  
167 sub clearCookies {
168 my $self = shift;
169  
170 $self->{cookies} = [];
171  
172 return 1;
173 }
174  
175 =pod
176  
177 =item addDateHeader($name, $date)
178  
179 Add a date value for the named response header.
180  
181 B<Parameters:>
182  
183 =over
184  
185 =item $name
186  
187 the name of the response header
188  
189 =item $date
190  
191 the additional header value
192  
193 =back
194  
195 =cut
196  
197 sub addDateHeader {
198 my $self = shift;
199 my $name = shift;
200 my $value = shift;
201  
202 return 1 if $self->isCommitted();
203 return 1 if $self->isIncluded();
204  
205 $self->addHeader($name, $value);
206  
207 return 1;
208 }
209  
210 =pod
211  
212 =item setDateHeader($name, $date)
213  
214 Set the date value for the named response header.
215  
216 B<Parameters:>
217  
218 =over
219  
220 =item $name
221  
222 the name of the header
223  
224 =item $date
225  
226 the header value
227  
228 =back
229  
230 =cut
231  
232 sub setDateHeader {
233 my $self = shift;
234 my $name = shift;
235 my $value = shift;
236  
237 return 1 if $self->isCommitted();
238 return 1 if $self->isIncluded();
239  
240 $self->setHeader($name, $value);
241  
242 return 1;
243 }
244  
245 =pod
246  
247 =item addHeader($name, $value)
248  
249 Add a value for the named response header.
250  
251 B<Parameters:>
252  
253 =over
254  
255 =item $name
256  
257 the name of the response header
258  
259 =item $value
260  
261 the additional header value
262  
263 =back
264  
265 =cut
266  
267 sub addHeader {
268 my $self = shift;
269 my $name = shift;
270 my $value = shift;
271  
272 return 1 if $self->isCommitted();
273 return 1 if $self->isIncluded();
274  
275 $self->{headers}->push_header($name, $value);
276  
277 return 1;
278 }
279  
280 =pod
281  
282 =item getHeader($name)
283  
284 Return the value for the first occurrence of the named response
285 header. For all values, use C<getHeaderValues()>.
286  
287 B<Parameters:>
288  
289 =over
290  
291 =item $name
292  
293 the header name
294  
295 =back
296  
297 =cut
298  
299 sub getHeader {
300 my $self = shift;
301 my $name = shift;
302  
303 return $self->getHeaderValues($name)->[0];
304 }
305  
306 =pod
307  
308 =item getHeaderNames()
309  
310 Return a list of all the header names set for this Response.
311  
312 =cut
313  
314 sub getHeaderNames {
315 my $self = shift;
316  
317 my %names;
318 $self->{headers}->scan(sub { $names{$_[0]} = 1 });
319  
320 my @names = keys %names;
321  
322 return wantarray ? @names : \@names;
323 }
324  
325 =pod
326  
327 =item getHeaderValues($name)
328  
329 Return the list of values for the named response header.
330  
331 B<Parameters:>
332  
333 =over
334  
335 =item $name
336  
337 the header name
338  
339 =back
340  
341 =cut
342  
343 sub getHeaderValues {
344 my $self = shift;
345 my $name = shift;
346  
347 my @vals = $self->{headers}->header($name);
348  
349 return wantarray ? @vals : \@vals;
350 }
351  
352 =item setHeader($name, $value)
353  
354 Set the value for the named response header.
355  
356 B<Parameters:>
357  
358 =over
359  
360 =item $name
361  
362 the name of the response header
363  
364 =item $value
365  
366 the header value
367  
368 =back
369  
370 =cut
371  
372 sub setHeader {
373 my $self = shift;
374 my $name = shift;
375 my $value = shift;
376  
377 return 1 if $self->isCommitted();
378 return 1 if $self->isIncluded();
379  
380 my $match = lc $name;
381 if ($match eq 'content-type') {
382 $self->setContentLength($value);
383 } elsif ($match eq 'content-length') {
384 $self->setContentType($value);
385 } else {
386 $self->{headers}->header($name, $value);
387 }
388  
389 return 1;
390 }
391  
392 =pod
393  
394 =item clearHeaders()
395  
396 Clear the set of headers for this Response;
397  
398 =cut
399  
400 sub clearHeaders {
401 my $self = shift;
402  
403 $self->{headers}->scan(sub {
404 # superclass takes care of these
405 next if (lc $_[0] eq 'content-type' ||
406 lc $_[0] eq 'content-length');
407 $self->{headers}->remove_header($_[0]);
408 });
409  
410 return 1;
411 }
412  
413 =pod
414  
415 =item setLocale($loc)
416  
417 Set the locale for this Response. The character encoding for this
418 Response will be set to the encoding specified by the locale, and the
419 I<Content-Language> header will be set to the language specified by
420 the locale.
421  
422 B<Parameters:>
423  
424 =over
425  
426 =item $loc
427  
428 the locale for the response
429  
430 =back
431  
432 =cut
433  
434 sub setLocale {
435 my $self = shift;
436 my $locale = shift;
437  
438 $self->SUPER::setLocale($locale);
439  
440 if ($self->{locale}) {
441 # XXX: set content-language header
442 }
443  
444 return 1;
445 }
446  
447 =pod
448  
449 =pod
450  
451 =item getMessage()
452  
453 Return the status message for this Response.
454  
455 =cut
456  
457 sub getMessage {
458 my $self = shift;
459  
460 return $self->{message};
461 }
462  
463 =pod
464  
465 =item getStatus()
466  
467 Return the HTTP status code for this Response.
468  
469 =cut
470  
471 sub getStatus {
472 my $self = shift;
473  
474 return $self->{status};
475 }
476  
477 =pod
478  
479 =item setStatus($code)
480  
481 Set the status code for this response.
482  
483 B<Parameters:>
484  
485 =over
486  
487 =item $code
488  
489 the HTTP status code
490  
491 =back
492  
493 =cut
494  
495 sub setStatus {
496 my $self = shift;
497 my $status = shift;
498  
499 return 1 if $self->isIncluded();
500  
501 $self->{status} = $status;
502 $self->{message} = $self->getStatusMessage($status);
503  
504 return 1;
505 }
506  
507 =pod
508  
509 =back
510  
511 =head1 PUBLIC METHODS
512  
513 =over
514  
515 =item containsHeader($name)
516  
517 Return a boolean value indicating whether or not the named response
518 header has already been set.
519  
520 B<Parameters:>
521  
522 =over
523  
524 =item $name
525  
526 the name of the header
527  
528 =back
529  
530 =cut
531  
532 sub containsHeader {
533 my $self = shift;
534 my $name = shift;
535  
536 return defined $self->getHeader($name);
537 }
538  
539 =pod
540  
541 =item encodeRedirectURL($url)
542  
543 Encode the session ID for this Response into the specified redirect
544 URL, if necessary.
545  
546 B<Parameters:>
547  
548 =over
549  
550 =item $url
551  
552 the url to be encoded
553  
554 =back
555  
556 =cut
557  
558 sub encodeRedirectURL {
559 my $self = shift;
560 my $url = shift;
561  
562 if ($self->isEncodeable($self->toAbsolute($url))) {
563 my $freq = $self->{request}->getRequest();
564 $url = $self->toEncoded($url, $freq->getSession()->getId());
565 }
566  
567 return $url;
568 }
569  
570 =pod
571  
572 =item encodeURL($url)
573  
574 Encode the session ID for this Response into the specified URL, if
575 necessary.
576  
577 B<Parameters:>
578  
579 =over
580  
581 =item $url
582  
583 the url to be encoded
584  
585 =back
586  
587 =cut
588  
589 sub encodeURL {
590 my $self = shift;
591 my $url = shift;
592  
593 if ($self->isEncodeable($self->toAbsolute($url))) {
594 my $freq = $self->{request}->getRequest();
595 $url = $self->toEncoded($url, $freq->getSession()->getId());
596 }
597  
598 return $url;
599 }
600  
601 =pod
602  
603 =item finishResponse()
604  
605 Perform whatever actions are required to flush and close the output
606 handle or writer, including sending headers if the response is not
607 already committed.
608  
609 B<Throws:>
610  
611 =over
612  
613 =item Servlet::Util::IOException
614  
615 if an input or output error occurs
616  
617 =back
618  
619 =cut
620  
621 sub finishResponse {
622 my $self = shift;
623  
624 $self->sendHeaders() unless $self->isCommitted();
625  
626 return $self->SUPER::finishResponse(@_);
627 }
628  
629 =pod
630  
631 =item flushBuffer()
632  
633 Force any content in the buffer to be written to the client. Headers
634 are automatically sent and the response is committed on the first
635 invocation of this method.
636  
637 B<Throws:>
638  
639 =over
640  
641 =item B<Servlet::Util::IOException>
642  
643 =back
644  
645 =cut
646  
647 sub flushBuffer {
648 my $self = shift;
649  
650 $self->sendHeaders() unless $self->isCommitted();
651  
652 return $self->SUPER::flushBuffer(@_);
653 }
654  
655 =pod
656  
657 =item reset()
658  
659 Clear any data that exists in the content buffer and unsets the
660 content length and content type, all cookies and headers, and the
661 status and message.
662  
663 B<Throws:>
664  
665 =over
666  
667 =item B<Servlet::Util::IllegalStateException>
668  
669 if the response has already been committed
670  
671 =back
672  
673 =cut
674  
675 sub reset {
676 my $self = shift;
677  
678 $self->SUPER::reset(@_);
679  
680 $self->clearHeaders();
681 $self->clearCookies();
682  
683 my $status = Servlet::Http::HttpServletResponse::SC_OK;
684 $self->setStatus($status);
685  
686 return 1;
687 }
688  
689 =pod
690  
691 =item sendError($code, [$message])
692  
693 Send an error response with the specified status and optional message.
694  
695 B<Parameters:>
696  
697 =over
698  
699 =item $code
700  
701 the error status code
702  
703 =item $message
704  
705 the optional descriptive message; if unspecified, the standard message
706 for the given status code will be used.
707  
708 =back
709  
710 B<Throws:>
711  
712 =over
713  
714 =item B<Servlet::Util::IOException>
715  
716 if an input or output exception occurs
717  
718 =item B<Servlet::Util::IllegalStateException>
719  
720 if the response has already been committed
721  
722 =back
723  
724 =cut
725  
726 sub sendError {
727 my $self = shift;
728 my $status = shift;
729 my $message = shift;
730  
731 if ($self->isCommitted()) {
732 my $msg = "sendError: response already committed";
733 Servlet::Util::IllegalStateException->throw($msg);
734 }
735  
736 return 1 if $self->isIncluded();
737  
738 $self->setStatus($status);
739 $self->{message} = $message if $message;
740 $self->setError();
741  
742 $self->resetBuffer();
743  
744 return 1;
745 }
746  
747 =pod
748  
749 =item sendRedirect($location)
750  
751 Send a temporary redirect to the specified URL.
752  
753 B<Parameters:>
754  
755 =over
756  
757 =item $location
758  
759 the redirect location URL
760  
761 =back
762  
763 B<Throws:>
764  
765 =over
766  
767 =item B<Servlet::Util::IOException>
768  
769 if an input or output exception occurs
770  
771 =item B<Servlet::Util::IllegalStateException>
772  
773 if the response has already been committed
774  
775 =back
776  
777 =cut
778  
779 sub sendRedirect {
780 my $self = shift;
781 my $location = shift;
782  
783 if ($self->isCommitted()) {
784 my $msg = "sendRedirect: response already committed";
785 Servlet::Util::IllegalStateException->throw($msg);
786 }
787  
788 return 1 if $self->isIncluded();
789  
790 $self->setHeader("Location", $self->toAbsolute($location));
791  
792 my $status = Servlet::Http::HttpServletResponse::SC_MOVED_TEMPORARILY;
793 $self->setStatus($status);
794  
795 return 1;
796 }
797  
798 =pod
799  
800 =back
801  
802 =head1 PACKAGE METHODS
803  
804 =over
805  
806 =item sendHeaders()
807  
808 Write response headers to the output handle, committing the
809 response. Usually doesn't need to be called by other classes, but will
810 be called the first time the buffer is flushed.
811  
812 =cut
813  
814 sub sendHeaders {
815 my $self = shift;
816 my $request = $self->getRequest();
817  
818 # send status line
819 $self->{handle}->print($request->getProtocol());
820 $self->{handle}->print(' ');
821 $self->{handle}->print($self->getStatus());
822 my $message = $self->getMessage();
823 if ($message) {
824 $self->{handle}->print(' ');
825 $self->{handle}->print($message);
826 }
827 $self->{handle}->print("\r\n");
828  
829 # send main headers
830 if ($self->{contentType}) {
831 $self->{handle}->print("Content-Type: $self->{contentType}\r\n");
832 }
833  
834 if ($self->{contentLength} >= 0) {
835 $self->{handle}->print("Content-Length: $self->{contentLength}\r\n");
836 }
837  
838 # send other headers
839 for my $name ($self->getHeaderNames()) {
840 for my $value ($self->getHeaderValues($name)) {
841 $self->{handle}->print("$name: $value\r\n");
842 }
843 }
844  
845 # add session id cookie if necessary
846 my $sessionCookie = Wombat::Util::RequestUtil->makeSessionCookie($request);
847 $self->addCookie($sessionCookie) if $sessionCookie;
848  
849 # send cookies
850 for my $cookie ($self->getCookies()) {
851 my $name = Wombat::Util::CookieTools->getCookieHeaderName($cookie);
852 my $value = Wombat::Util::CookieTools->getCookieHeaderValue($cookie);
853 $self->{handle}->print("$name: $value\r\n");
854 }
855  
856 $self->{handle}->print("\r\n");
857 $self->{handle}->flush();
858  
859 # Wombat::Globals::DEBUG &&
860 # $self->debug("sent headers");
861  
862 unless ($self->{committed}) {
863 $self->{committed} = 1;
864  
865 # Wombat::Globals::DEBUG &&
866 # $self->debug("committed response");
867 }
868  
869 return 1;
870 }
871  
872 =pod
873  
874 =item recycle()
875  
876 Release all object references and initialize instances variables in
877 preparation for use or reuse of this object.
878  
879 =cut
880  
881 sub recycle {
882 my $self = shift;
883 my $facade = shift;
884  
885 $self->SUPER::recycle($facade);
886  
887 $self->{cookies} = [];
888 $self->{headers} = HTTP::Headers->new();
889  
890 my $status = Servlet::Http::HttpServletResponse::SC_OK;
891 $self->{status} = $status;
892 $self->{message} = $self->getStatusMessage($status);
893  
894 $self->{facade} = $facade ||
895 Wombat::Connector::HttpResponseFacade->new($self);
896  
897 return 1;
898 }
899  
900 # private
901  
902 sub getStatusMessage {
903 my $self = shift;
904 my $status = shift;
905  
906 return STATUS_MESSAGES->{$status};
907 }
908  
909 sub isEncodeable {
910 my $self = shift;
911 my $location = shift;
912  
913 return undef unless $location;
914  
915 # is this an intra-document reference?
916 return undef if $location =~ m|^\#|;
917  
918 # is there a valid session that does not use cookies?
919 my $freq = $self->{request}->getRequest();
920 return undef if $freq->isRequestedSessionIdFromCookie();
921  
922 my $session = $freq->getSession();
923 return undef unless $session;
924  
925 # does the url match down to the context path?
926 my $abs = $self->toAbsolute($location);
927  
928 my $uriScheme = $abs->scheme() || '';
929 return undef unless lc $freq->getScheme() eq lc $uriScheme;
930  
931 my $uriHost = $abs->host() || '';
932 return undef unless lc $freq->getServerName() eq lc $uriHost;
933  
934 my $serverPort = $freq->getServerPort();
935 $serverPort ||= $freq->isSecure() ? 443 : 80;
936 my $uriPort = $abs->port() || -1;
937 return undef unless $serverPort == $uriPort;
938  
939 my $contextPath = $self->{application}->getPath();
940 if ($contextPath) {
941 my $uriPath = $abs->path() || '';
942 return undef unless $uriPath =~ m|^$contextPath|;
943 }
944  
945 return 1;
946 }
947  
948 sub toAbsolute {
949 my $self = shift;
950 my $location = shift;
951  
952 return undef unless $location;
953  
954 my $abs = URI->new_abs($location, $self->getRequest()->getRequestURL());
955 Servlet::Util::IllegalArgumentException->throw($location) unless $abs;
956  
957 return $abs;
958 }
959  
960 sub toEncoded {
961 my $self = shift;
962 my $url = shift;
963 my $id = shift;
964  
965 return $url unless $url && defined $id;
966  
967 my ($path, $query) = split /\?/, $url;
968  
969 my $new = join('?', $path,
970 (join '=', Wombat::Globals::SESSION_PARAMETER_NAME, $id));
971  
972 $new = join '&', $new, $query if defined $query;
973  
974 return $new;
975 }
976  
977 =pod
978  
979 =back
980  
981 =cut
982  
983 1;
984 __END__