/[webpac2]/trunk/lib/WebPAC/Validate.pm
This is repository of my old source code which isn't updated any more. Go to git.rot13.org for current projects!
ViewVC logotype

Contents of /trunk/lib/WebPAC/Validate.pm

Parent Directory Parent Directory | Revision Log Revision Log


Revision 864 - (show annotations)
Sun May 27 22:24:30 2007 UTC (16 years, 11 months ago) by dpavlin
File size: 12965 byte(s)
 r1280@llin:  dpavlin | 2007-05-28 00:24:21 +0200
 various fixes to make save_delimiters_tamplates produce output file

1 package WebPAC::Validate;
2
3 use warnings;
4 use strict;
5
6 use blib;
7
8 use base 'WebPAC::Common';
9 use File::Slurp;
10 use List::Util qw/first/;
11 use Data::Dump qw/dump/;
12 use WebPAC::Normalize qw/_pack_subfields_hash/;
13 use Storable qw/dclone/;
14
15 =head1 NAME
16
17 WebPAC::Validate - provide simple validation for records
18
19 =head1 VERSION
20
21 Version 0.12
22
23 =cut
24
25 our $VERSION = '0.12';
26
27 =head1 SYNOPSIS
28
29 This module provide a simple way to validate your file against a simple
30 configuration file in following format:
31
32 # field 10 doesn't have any subfields
33 10
34 # same with 101
35 101
36 # field 200 have valid subfields a-g
37 # and field e is repeatable
38 200 a b c d e* f g
39 # field 205 can have only subfield a
40 # and must exists
41 205! a
42 # while 210 can have a c or d
43 210 a c d
44 # field which is ignored in validation
45 999-
46
47 =head1 FUNCTIONS
48
49 =head2 new
50
51 Create new validation object
52
53 my $validate = new WebPAC::Validate(
54 path => 'conf/validate/file',
55 delimiters => [ ' : ', ' / ', ' ; ', ' , ' ],
56 delimiters_path => 'conf/validate/delimiters/file',
57 );
58
59 Optional parametar C<delimiters> will turn on validating of delimiters. Be
60 careful here, those delimiters are just stuck into regex, so they can
61 contain L<perlre> regexpes.
62
63 C<path> and C<delimiters_path> can be specified by L<read_validate_file> and
64 L<read_validate_delimiters> calls.
65
66 =cut
67
68 sub new {
69 my $class = shift;
70 my $self = {@_};
71 bless($self, $class);
72
73 my $log = $self->_get_logger();
74
75 $self->read_validate_file( $self->{path} ) if ( $self->{path} );
76
77 if ( $self->{delimiters} ) {
78 $self->{delimiters_regex} = '(\^[a-z0-9]|' . join('|', @{ $self->{delimiters} }) . ')';
79 $log->info("validation check delimiters with regex $self->{delimiters_regex}");
80 }
81
82 $self->read_validate_delimiters_file( $self->{delimiters_path} ) if ( $self->{delimiters_path} );
83
84 return $self;
85 }
86
87
88 =head2 read_validate_file
89
90 Specify validate rules file
91
92 $validate->read_validate_file( 'conf/validate/file' );
93
94 Returns number of lines in file
95
96 =cut
97
98 sub read_validate_file {
99 my $self = shift;
100
101 my $path = shift || die "no path?";
102
103 my $log = $self->_get_logger();
104
105 my $v_file = read_file( $path ) ||
106 $log->logdie("can't open validate path $path: $!");
107
108 my $v;
109 delete( $self->{must_exist} );
110 delete( $self->{must_exist_sf} );
111 delete( $self->{dont_validate} );
112 my $curr_line = 1;
113
114 foreach my $l (split(/[\n\r]+/, $v_file)) {
115 $curr_line++;
116
117 # skip comments and whitespaces
118 next if ($l =~ /^#/ || $l =~ /^\s*$/);
119
120 $l =~ s/^\s+//;
121 $l =~ s/\s+$//;
122
123 my @d = split(/\s+/, $l);
124
125 my $fld = shift @d;
126
127 if ($fld =~ s/!$//) {
128 $self->{must_exist}->{$fld}++;
129 } elsif ($fld =~ s/-$//) {
130 $self->{dont_validate}->{$fld}++;
131 }
132
133 $log->logdie("need field name in line $curr_line: $l") unless (defined($fld));
134
135 if (@d) {
136 $v->{$fld} = [ map {
137 my $sf = $_;
138 if ( $sf =~ s/!(\*)?$/$1/ ) {
139 $self->{must_exist_sf}->{ $fld }->{ $sf }++;
140 };
141 $sf;
142 } @d ];
143 } else {
144 $v->{$fld} = 1;
145 }
146
147 }
148
149 $log->debug("current validation rules: ", dump($v));
150
151 $self->{rules} = $v;
152
153 $log->info("validation uses rules from $path");
154
155 return $curr_line;
156 }
157
158 =head2 read_validate_delimiters_file
159
160 $validate->read_validate_delimiters_file( 'conf/validate/delimiters/file' );
161
162 =cut
163
164 sub read_validate_delimiters_file {
165 my $self = shift;
166
167 my $path = shift || die "no path?";
168
169 my $log = $self->_get_logger();
170
171 delete( $self->{_validate_delimiters_templates} );
172 delete( $self->{_delimiters_templates} );
173
174 if ( -e $path ) {
175 $log->info("using delimiter validation rules from $path");
176 open(my $d, $path) || $log->fatal("can't open $path: $!");
177 while(<$d>) {
178 chomp($d);
179 if (/^\s*(#*)\s*(\d+)\t+(\d+)\t+(.*)$/) {
180 my ($comment,$field,$count,$template) = ($1,$2,$3,$4);
181 $self->{_validate_delimiters_templates}->{$field}->{$template} = $count unless ($comment);
182 } else {
183 warn "## ignored $d\n";
184 }
185 }
186 close($d);
187 #warn "_validate_delimiters_templates = ",dump( $self->{_validate_delimiters_templates} );
188 } else {
189 $log->warn("delimiters path $path doesn't exist, it will be created after this run");
190 }
191 $self->{delimiters_path} = $path;
192 }
193
194 =head2 validate_rec
195
196 Validate record and return errors
197
198 my @errors = $validate->validate_rec( $rec, $rec_dump );
199
200 =cut
201
202 sub validate_rec {
203 my $self = shift;
204
205 my $log = $self->_get_logger();
206
207 my $rec = shift || $log->logdie("validate_rec need record");
208 my $rec_dump = shift;
209
210 $log->logdie("rec isn't HASH") unless (ref($rec) eq 'HASH');
211 # $log->logdie("can't find validation rules") unless (my $r = $self->{rules});
212 my $r = $self->{rules};
213
214 my $errors;
215
216 $log->debug("rec = ", sub { dump($rec) }, "keys = ", keys %{ $rec });
217
218 my $fields;
219
220 foreach my $f (keys %{ $rec }) {
221
222 next if (!defined($f) || $f eq '' || $f eq '000');
223
224 # first check delimiters
225 if ( my $regex = $self->{delimiters_regex} ) {
226
227 foreach my $v (@{ $rec->{$f} }) {
228 my $l = _pack_subfields_hash( $v, 1 );
229 my $subfield_dump = $l;
230 my $template = '';
231 $l =~ s/$regex/$template.=$1/eg;
232 #warn "## template: $template\n";
233
234 if ( $template ) {
235 $self->{_delimiters_templates}->{$f}->{$template}++;
236
237 if ( my $v = $self->{_validate_delimiters_templates} ) {
238 if ( ! defined( $v->{$f}->{$template} ) ) {
239 $errors->{$f}->{potentially_invalid_combination} = $template;
240 $errors->{$f}->{dump} = $subfield_dump;
241 #} else {
242 # warn "## $f $template ok\n";
243 }
244 }
245 }
246 }
247 }
248
249 next unless ( $r ); # skip validation of no rules are specified
250
251 next if (defined( $self->{dont_validate}->{$f} ));
252
253 # track field usage
254 $fields->{$f}++;
255
256 if ( ! defined($r->{$f}) ) {
257 $errors->{ $f }->{unexpected} = "this field is not expected";
258 next;
259 }
260
261
262 if (ref($rec->{$f}) ne 'ARRAY') {
263 $errors->{ $f }->{not_repeatable} = "probably bug in parsing input data";
264 next;
265 }
266
267 foreach my $v (@{ $rec->{$f} }) {
268 # can we have subfields?
269 if (ref($r->{$f}) eq 'ARRAY') {
270 # are values hashes? (has subfields)
271 if (! defined($v)) {
272 # $errors->{$f}->{empty} = undef;
273 # $errors->{dump} = $rec_dump if ($rec_dump);
274 } elsif (ref($v) ne 'HASH') {
275 $errors->{$f}->{missing_subfield} = join(",", @{ $r->{$f} }) . " required";
276 next;
277 } else {
278
279 my $h = dclone( $v );
280
281 my $sf_repeatable;
282
283 delete($v->{subfields}) if (defined($v->{subfields}));
284
285 my $subfields;
286
287 foreach my $sf (keys %{ $v }) {
288
289 $subfields->{ $sf }++;
290
291 # is non-repeatable but with multiple values?
292 if ( ! first { $_ eq $sf.'*' } @{$r->{$f}} ) {
293 if ( ref($v->{$sf}) eq 'ARRAY' ) {
294 $sf_repeatable->{$sf}++;
295 };
296 if (! first { $_ eq $sf } @{ $r->{$f} }) {
297 $errors->{ $f }->{subfield}->{extra}->{$sf}++;
298 }
299 }
300
301 }
302 if (my @r_sf = sort keys( %$sf_repeatable )) {
303
304 foreach my $sf (@r_sf) {
305 $errors->{$f}->{subfield}->{extra_repeatable}->{$sf}++;
306 $errors->{$f}->{dump} = _pack_subfields_hash( $h, 1 );
307 }
308
309 }
310
311 if ( defined( $self->{must_exist_sf}->{$f} ) ) {
312 foreach my $sf (sort keys %{ $self->{must_exist_sf}->{$f} }) {
313 #warn "====> $f $sf must exist\n";
314 $errors->{$f}->{subfield}->{missing}->{$sf}++
315 unless defined( $subfields->{$sf} );
316 }
317 }
318
319 }
320 } elsif (ref($v) eq 'HASH') {
321 $errors->{$f}->{unexpected_subfields}++;
322 $errors->{$f}->{dump} = _pack_subfields_hash( $v, 1 );
323 }
324 }
325 }
326
327 $log->debug("_delimiters_templates = ", sub { dump( $self->{_delimiters_templates} ) } );
328
329 foreach my $must (sort keys %{ $self->{must_exist} }) {
330 next if ($fields->{$must});
331 $errors->{$must}->{missing}++;
332 $errors->{dump} = $rec_dump if ($rec_dump);
333 }
334
335 if ($errors) {
336 $log->debug("errors: ", $self->report_error( $errors ) );
337
338 my $mfn = $rec->{'000'}->[0] || $log->logconfess("record ", sub { dump( $rec ) }, " doesn't have MFN");
339 $self->{errors}->{$mfn} = $errors;
340 }
341
342 #$log->logcluck("return from this function is ARRAY") unless wantarray;
343
344 return $errors;
345 }
346
347 =head2 reset
348
349 Clean all accumulated errors for this input and remember delimiter templates
350 for L<save_delimiters_templates>
351
352 $validate->reset;
353
354 This function B<must> be called after each input to provide accurate statistics.
355
356 =cut
357
358 sub reset {
359 my $self = shift;
360
361 my $log = $self->_get_logger;
362
363 delete ($self->{errors});
364
365 if ( ! $self->{_delimiters_templates} ) {
366 $log->debug("called without _delimiters_templates?");
367 return;
368 }
369
370 foreach my $f ( keys %{ $self->{_delimiters_templates} } ) {
371 foreach my $t ( keys %{ $self->{_delimiters_templates}->{$f} } ) {
372 $self->{_accumulated_delimiters_templates}->{$f}->{$t} +=
373 $self->{_delimiters_templates}->{$f}->{$t};
374 }
375 }
376 $log->debug("_accumulated_delimiters_templates = ", sub { dump( $self->{_accumulated_delimiters_templates} ) } );
377 delete ($self->{_delimiters_templates});
378 }
379
380 =head2 all_errors
381
382 Return hash with all errors
383
384 print dump( $validate->all_errors );
385
386 =cut
387
388 sub all_errors {
389 my $self = shift;
390 return $self->{errors};
391 }
392
393 =head2 report_error
394
395 Produce nice humanly readable report of single error
396
397 print $validate->report_error( $error_hash );
398
399 =cut
400
401 sub report_error {
402 my $self = shift;
403
404 my $h = shift || die "no hash?";
405
406 sub _unroll {
407 my ($self, $tree, $accumulated) = @_;
408
409 my $log = $self->_get_logger();
410
411 $log->debug("# ",
412 ( $tree ? "tree: $tree " : '' ),
413 ( $accumulated ? "accumulated: $accumulated " : '' ),
414 );
415
416 my $results;
417
418 if (ref($tree) ne 'HASH') {
419 return ("$accumulated\t($tree)", undef);
420 }
421
422 my $dump;
423
424 foreach my $k (sort keys %{ $tree }) {
425
426 if ($k eq 'dump') {
427 $dump = $tree->{dump};
428 #warn "## dump ",dump($dump),"\n";
429 next;
430 }
431
432 $log->debug("current: $k");
433
434 my ($new_results, $new_dump) = $self->_unroll($tree->{$k},
435 $accumulated ? "$accumulated\t$k" : $k
436 );
437
438 $log->debug( "new_results: ", sub { dump($new_results) } ) if ( $new_results );
439
440 push @$results, $new_results if ($new_results);
441 $dump = $new_dump if ($new_dump);
442
443 }
444
445 $log->debug( "results: ", sub { dump($results) } ) if ( $results );
446
447 if ($#$results == 0) {
448 return ($results->[0], $dump);
449 } else {
450 return ($results, $dump);
451 }
452 }
453
454
455 sub _reformat {
456 my $l = shift;
457 $l =~ s/\t/ /g;
458 $l =~ s/_/ /g;
459 return $l;
460 }
461
462 my $out = '';
463
464 for my $f (sort keys %{ $h }) {
465 $out .= "$f: ";
466
467 my ($r, $d) = $self->_unroll( $h->{$f} );
468 my $e;
469 if (ref($r) eq 'ARRAY') {
470 $e .= join(", ", map { _reformat( $_ ) } @$r);
471 } else {
472 $e .= _reformat( $r );
473 }
474 $e .= "\n\t$d" if ($d);
475
476 $out .= $e . "\n";
477 }
478 return $out;
479 }
480
481
482 =head2 report
483
484 Produce nice humanly readable report of errors
485
486 print $validate->report;
487
488 =cut
489
490 sub report {
491 my $self = shift;
492 my $e = $self->{errors} || return;
493
494 my $out;
495 foreach my $mfn (sort { $a <=> $b } keys %$e) {
496 $out .= "MFN $mfn\n" . $self->report_error( $e->{$mfn} ) . "\n";
497 }
498
499 return $out;
500
501 }
502
503 =head2 delimiters_templates
504
505 Generate report of delimiter tamplates
506
507 my $report = $validate->delimiter_teplates(
508 report => 1,
509 current_input => 1,
510 );
511
512 Options:
513
514 =over 4
515
516 =item report
517
518 Generate humanly readable report with single fields
519
520 =item current_input
521
522 Report just current_input and not accumulated data
523
524 =back
525
526 =cut
527
528 sub delimiters_templates {
529 my $self = shift;
530
531 my $args = {@_};
532
533 my $t = $self->{_accumulated_delimiters_templates};
534 $t = $self->{_delimiters_templates} if ( $args->{current_input} );
535
536 my $log = $self->_get_logger;
537
538 unless ($t) {
539 $log->error("called without delimiters");
540 return;
541 }
542
543 my $out;
544
545 foreach my $f (sort { $a <=> $b } keys %$t) {
546 $out .= "$f\n" if ( $args->{report} );
547 foreach my $template (sort { $a cmp $b } keys %{ $t->{$f} }) {
548 my $count = $t->{$f}->{$template};
549 $out .=
550 ( $count ? "" : "# " ) .
551 ( $args->{report} ? "" : "$f" ) .
552 "\t$count\t$template\n";
553 }
554 }
555
556 return $out;
557 }
558
559 =head2 save_delimiters_templates
560
561 Save accumulated delimiter templates
562
563 $validator->save_delimiters_template( '/path/to/validate/delimiters' );
564
565 =cut
566
567 sub save_delimiters_templates {
568 my $self = shift;
569
570 my $path = shift;
571 $path ||= $self->{delimiters_path};
572
573 my $log = $self->_get_logger;
574
575 $log->logdie("need path") unless ( $path );
576
577
578 if ( ! $self->{_accumulated_delimiters_templates} ) {
579 $log->error('no _accumulated_delimiters_templates found, reset');
580 $self->reset;
581 }
582
583 if ( $self->{_delimiters_templates} ) {
584 $log->error('found _delimiters_templates, calling reset');
585 $self->reset;
586 }
587
588 $path .= '.new' if ( -e $path );
589
590 open(my $d, '>', $path) || $log->fatal("can't open $path: $!");
591 print $d $self->delimiters_templates;
592 close($d);
593
594 $log->info("new delimiters templates saved to $path");
595 }
596
597 =head1 AUTHOR
598
599 Dobrica Pavlinusic, C<< <dpavlin@rot13.org> >>
600
601 =head1 COPYRIGHT & LICENSE
602
603 Copyright 2006 Dobrica Pavlinusic, All Rights Reserved.
604
605 This program is free software; you can redistribute it and/or modify it
606 under the same terms as Perl itself.
607
608 =cut
609
610 1; # End of WebPAC::Validate

  ViewVC Help
Powered by ViewVC 1.1.26