File: JSONRPC.pm

package info (click to toggle)
libjson-perl 1.00-2
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 168 kB
  • ctags: 116
  • sloc: perl: 1,158; makefile: 45
file content (482 lines) | stat: -rwxr-xr-x 8,392 bytes parent folder | download
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
package JSONRPC;

 # JSON-RPC server and client

use strict;
use JSON;

use vars qw($VERSION);

$VERSION = 0.99;


sub new {
	my $self = bless {}, shift;
	$self->jsonParser( JSON::Parser->new() );
	$self->jsonConverter( JSON::Converter->new );
	$self;
}


sub proxy { # re-bless a client class
	my ($self,$url,$proxy_url) = @_;
	$self = $self->new unless(ref($self));
	my $class = ref($self) ? ref($self) . '::Client' : 'JSONRPC::Client';
	$self = bless $self, $class;
	$self->{_proxy} = [$url,$proxy_url] if(@_ > 1);
	$self;
}


# JSONRPC::Transport::XXX->dispatch_to('MyApp')->handle();
# This module looks for the method from MyApp.pm.
# looks for a method from the corresponding package name when a client call it.
# At present, only the module name can be specified. 

sub dispatch_to {
	my $class = shift;
	my $self  = ref($class) ? $class : $class->new;
	my @srv   = @_;

	if(@srv){
		$self->{_dispatch_to} = [ @srv ] ;
		$self;
	}
	else{
		@{ $self->{_dispatch_to} };
	}
}


# to a reqeust from a response (subclass must have the implementation.)

sub handle { }


# get a request from client (subclass must have the implementation.)
# The return value is a HTTP::Request object.

sub requset { }


# return a response (subclass must have the implementation.)

sub response { }


# an error that should cut connection (subclass must have the implementation.)

sub invalid_request {}


# the process in case not making response (subclass must have the implementation.)

sub no_response {}


# return a mthod name and any parameters from JSON-RPC data structure.

sub get_request_data {
	my $self   = shift;
	my $js     = $self->{json_data};
	my $method = $js->{method} || '';
	my $params = $js->{params} || [];
	return ($method,$params);
}


# look for the method from module names set by the dispatch_to().
# $r is a HTTP::Request object.

sub find_method {
	my ($self, $method, $r) = @_;
	my $path  = ($r and $r->uri) ? ($r->uri->path || '') : '';

	$path =~ s{^/|/$}{}g;
	$path =~ s{/}{::}g;

	no strict 'refs';

	for my $srv ( @{$self->{_dispatch_to}} ){

		if($srv =~ m{/}){ # URI
			my $class = _path_to_class($srv);
			if($path eq $class){
				unless(defined %{"$class\::"}){
					eval qq| require $class |;
					if($@){ warn $@; return; }
				}
				if(my $func = $class->can($method)){
					return $func;
				}
			}
			else{
				next;
			}
		}
		else{
			if(my $func = $srv->can($method)){
				return $func;
			}
		}
	}

	return;
}

sub _path_to_class {
	my $path = $_[0];
	$path =~ s{^/|/$}{}g;
	$path =~ s{/}{::}g;
	return $path;
}

# execution of method : return value is JSON-RPC data struture.
# $func->($self,@$params) returns a scalar or a hash ref or an array ref.

sub handle_method {
	my ($self, $r)       = @_;
	my ($method,$params) = $self->get_request_data();

	if( my $func = $self->find_method($method, $r) ){
		my $result = $func->($self,@$params);
		$self->set_response_data($result)
	}
	else{
		$self->set_err('No such a method.');
	}
}


# execution of notification

sub notification {
	my $self  = shift;
	my ($method,$params) = $self->get_request_data();

	if(my $func = $self->find_method($method)){
		$func->($self,@$params);
	}

	return 1;
}


# convert Perl data into JSON for a response.

sub set_response_data {
	my $self  = shift;
	my $value = shift;
	my $id    = $self->request_id;
	my $error = $self->error;

	if(!defined $value){ $value = JSON::Null; }
	if(!defined $error){ $error = JSON::Null; }

	my $result = {
		id     => $id,
		result => $value,
		error  => $error,
	};

	return $self->jsonConverter->objToJson($result);
}


# convert Perl data into JSON for an error response.

sub set_err {
	my $self  = shift;
	my $error = shift;
	my $id    = $self->request_id;

	my $result = {
		id     => $id,
		result => JSON::Null,
		error  => $error,
	};

	return $self->jsonConverter->objToJson($result);
}


# accessor of error object

sub error {
	my $self = shift;
	$self->{_error} = $_[0] if(@_ > 0);
	$self->{_error};
}


# accessor of id

sub request_id {
	my $self = shift;

	if(@_ > 0){
		$self->{_request_id} = $_[0];
		if(ref($self->{_request_id}) =~ /JSON/ and !defined $self->{_request_id}->{value}){
			$self->{_request_id} = undef;
		}
	}

	$self->{_request_id};
}


# accessor to JSON::Parser

sub jsonParser {
	$_[0]->{json_parser} = $_[1] if(@_ > 1);
	return $_[0]->{json_parser};
}


# accessor to JSON::Converter

sub jsonConverter {
	$_[0]->{json_converter} = $_[1] if(@_ > 1);
	return $_[0]->{json_converter};
}


#
# Client
#

package JSONRPC::Client;

use base qw(JSONRPC);
use vars qw($AUTOLOAD);


sub AUTOLOAD {
	my $self = shift;
	my $attr = $AUTOLOAD;

	$attr =~ s/.*:://;

	return if($attr eq 'DESTROY');

	$attr =~ s/^_//;

	my $res = $self->call($attr,[@_])->result;

	if($res->error){
		$self->{_error} = $res->{error};
		return;
	}
	else{
		$res->result;
	}
}


# call($method, $params $id)
# without $id, 'JsonRpcClient' is set.
# explicitly set undef into $id, notification mode.

sub call {
	my ($self, $method, $params, $id) = @_;

	if(@_ == 3){ $id = 'JsonRpcClient'; }
	$self->{_id} = $id;

	my $content = eval q|
		$self->jsonConverter->objToJson({
			method => $method, params => $params, id => $id
		})
	| or die $@;

	$self->{_response} = $self->send($content);
	$self;
}


# post data (subclass must have the implementation.)

sub send {}


# return the result value.

sub result {
	my ($self) = @_;
	my $response  = $self->{_response};

	my $result = bless {
		success => $response->is_success,
		error   => undef,
		result  => undef,
		id      => undef,
	}, 'JSONRPC::Response';

	unless( $response->is_success ){
		$self->{_error} = $response->code;
		$result->error($response->code);
		return $result;
	}
	else{
		$self->{_error} = undef;
	}

	my $json = $response->content;
	my $obj  = eval q| $self->jsonParser->jsonToObj($json, {unmapping => 1}) |;

	return if(!$obj); # notification?

	if($obj->{id} eq $self->{_id}){
		$result->result( $obj->{result} );
		$result->error( $obj->{error} );
		$result->id( $obj->{id} );
	}

	return $result;
}


# accessor to status code. (when response is not sucessful, set status code)

sub error { $_[0]->{_error}; }


#
#
#

package JSONRPC::Response;

use base qw(HTTP::Response);

sub is_success { $_[0]->{success} }

sub result {
	$_[0]->{result} = $_[1] if(@_ > 1);
	$_[0]->{result};
}


sub error {
	$_[0]->{error} = $_[1] if(@_ > 1);
	$_[0]->{error};
}


sub id {
	$_[0]->{id} = $_[1] if(@_ > 1);
	$_[0]->{id};
}


1;
__END__


=head1 NAME

 JSONRPC - Perl implementation of JSON-RPC protocol

=head1 SYNOPSIS

 #--------------------------
 # In your application class
 package MyApp;

 sub own_method { # called by clients
     my ($server, @params) = @_; # $server is JSONRPC object.
     ...
     # return a scalar value or a hashref or an arryaref.
 }

 #--------------------------
 # In your main cgi script.
 use JSONRPC::Transport::HTTP;
 use MyApp;

 # a la XMLRPC::Lite
 JSONRPC::Transport::HTTP::CGI->dispatch_to('MyApp')->handle();


 #--------------------------
 # Client version
 use JSONRPC::Transport::HTTP;
 my $uri = 'http://www.example.com/MyApp/Test/';

 my $res = JSONRPC::Transport::HTTP
            ->proxy($uri)
            ->call('echo',['This is test.'])
            ->result;

 if($res->error){
   print $res->error,"\n";
 }
 else{
   print $res->result,"\n";
 }

 # or

 my $client = JSONRPC::Transport::HTTP->proxy($uri);
 
 print $client->echo('This is test.'); # the alias, _echo is same.


=head1 DESCRIPTION

This module implementes JSON-RPC (L<http://json-rpc.org/>) server
and client. Most ideas were borrowed from L<XMLRPC::Lite>.
Currently C<JSONRPC> provides CGI server function.


=head1 METHOD

=over 4


=item dispatch_to


=item handle


=item jsonParser

The accessor of a JSON::Parser object.

 my $srv = JSONRPC::Transport::HTTP::CGI->new;
 $srv->jsonParser->{unmapping} = 1;


=item jsonConverter

The accessor of a JSON::Converter object.

=item proxy($uri,[$proxy_uri])

takes a service uri and optional proxy uri.
returns a client object.

=back

=head1 SEE ALSO

L<JSONRPC::Transport::HTTP>
L<JSON>
L<XMLRPC::Lite>
L<http://json-rpc.org/>


=head1 AUTHOR

Makamaka Hannyaharamitu, E<lt>makamaka[at]cpan.orgE<gt>

=head1 COPYRIGHT AND LICENSE

Copyright 2005 by Makamaka Hannyaharamitu

This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself. 

=cut