/[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

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

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 665 by dpavlin, Mon Sep 11 11:57:30 2006 UTC revision 849 by dpavlin, Sun May 27 10:50:37 2007 UTC
# Line 18  WebPAC::Validate - provide simple valida Line 18  WebPAC::Validate - provide simple valida
18    
19  =head1 VERSION  =head1 VERSION
20    
21  Version 0.07  Version 0.12
22    
23  =cut  =cut
24    
25  our $VERSION = '0.07';  our $VERSION = '0.12';
26    
27  =head1 SYNOPSIS  =head1 SYNOPSIS
28    
# Line 41  configuration file in following format: Line 41  configuration file in following format:
41    205! a    205! a
42    # while 210 can have a c or d    # while 210 can have a c or d
43    210 a c d    210 a c d
44      # field which is ignored in validation
45      999-
46    
47  =head1 FUNCTIONS  =head1 FUNCTIONS
48    
# Line 50  Create new validation object Line 52  Create new validation object
52    
53    my $validate = new WebPAC::Validate(    my $validate = new WebPAC::Validate(
54          path => 'conf/validate/file',          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  =cut  =cut
64    
65  sub new {  sub new {
# Line 61  sub new { Line 69  sub new {
69    
70          my $log = $self->_get_logger();          my $log = $self->_get_logger();
71    
72          foreach my $p (qw/path/) {          $log->logdie("need path or delimiters_path") unless ( $self->{path} || $self->{delimiters_path} );
                 $log->logconfess("need $p") unless ($self->{$p});  
         }  
73    
74          my $v_file = read_file( $self->{path} ) ||          if ( $self->{path} ) {
                 $log->logdie("can't open validate path $self->{path}: $!");  
75    
76          my $v;                  my $v_file = read_file( $self->{path} ) ||
77          my $curr_line = 1;                          $log->logdie("can't open validate path $self->{path}: $!");
78    
79          foreach my $l (split(/[\n\r]+/, $v_file)) {                  my $v;
80                  $curr_line++;                  my $curr_line = 1;
81    
82                  # skip comments and whitespaces                  foreach my $l (split(/[\n\r]+/, $v_file)) {
83                  next if ($l =~ /^#/ || $l =~ /^\s*$/);                          $curr_line++;
84    
85                  $l =~ s/^\s+//;                          # skip comments and whitespaces
86                  $l =~ s/\s+$//;                          next if ($l =~ /^#/ || $l =~ /^\s*$/);
87    
88                  my @d = split(/\s+/, $l);                          $l =~ s/^\s+//;
89                            $l =~ s/\s+$//;
90    
91                  my $fld = shift @d;                          my @d = split(/\s+/, $l);
92    
93                  if ($fld =~ s/!$//) {                          my $fld = shift @d;
                         $self->{must_exist}->{$fld}++;  
                 }  
94    
95                  $log->logdie("need field name in line $curr_line: $l") unless (defined($fld));                          if ($fld =~ s/!$//) {
96                                    $self->{must_exist}->{$fld}++;
97                            } elsif ($fld =~ s/-$//) {
98                                    $self->{dont_validate}->{$fld}++;
99                            }
100    
101                            $log->logdie("need field name in line $curr_line: $l") unless (defined($fld));
102    
103                            if (@d) {
104                                    $v->{$fld} = [ map {
105                                            my $sf = $_;
106                                            if ( $sf =~ s/!(\*)?$/$1/ ) {
107                                                    $self->{must_exist_sf}->{ $fld }->{ $sf }++;
108                                            };
109                                            $sf;
110                                    } @d ];
111                            } else {
112                                    $v->{$fld} = 1;
113                            }
114    
                 if (@d) {  
                         $v->{$fld} = [ map {  
                                 my $sf = $_;  
                                 if ( $sf =~ s/!(\*)?$/$1/ ) {  
                                         $self->{must_exist_sf}->{ $fld }->{ $sf }++;  
                                 };  
                                 $sf;  
                         } @d ];  
                 } else {  
                         $v->{$fld} = 1;  
115                  }                  }
116    
117          }                  $log->debug("current validation rules: ", dump($v));
118    
119          $log->debug("current validation rules: ", dump($v));                  $self->{rules} = $v;
120    
121          $self->{rules} = $v;                  $log->info("validation uses rules from $self->{path}");
122            }
123    
124          $log->info("validation uses rules from $self->{path}");          if ( $self->{delimiters} ) {
125                    $self->{delimiters_regex} = '(\^[a-z0-9]|' . join('|', @{ $self->{delimiters} }) . ')';
126                    $log->info("validation check delimiters with regex $self->{delimiters_regex}");
127            }
128    
129            if ( my $path = $self->{delimiters_path} ) {
130                    if ( -e $path ) {
131                            $log->info("using delimiter validation rules from $path");
132                            open(my $d, $path) || $log->fatal("can't open $path: $!");
133                            while(<$d>) {
134                                    chomp($d);
135                                    if (/^\s*(#*)\s*(\d+)\t+(\d+)\t+(.*)$/) {
136                                            my ($comment,$field,$count,$template) = ($1,$2,$3,$4);
137                                            $self->{_validate_delimiters_templates}->{$field}->{$template} = $count unless ($comment);
138                                    } else {
139                                            warn "## ignored $d\n";
140                                    }
141                            }
142                            close($d);
143                            #warn "_validate_delimiters_templates = ",dump( $self->{_validate_delimiters_templates} );
144                    } else {
145                            $log->warn("delimiters path $path doesn't exist, it will be created after this run");
146                    }
147            }
148    
149          $self ? return $self : return undef;          $self ? return $self : return undef;
150  }  }
151    
152  =head2 validate_errors  =head2 validate_rec
153    
154  Validate record and return errors  Validate record and return errors
155    
156    my @errors = $validate->validate_errors( $rec, $rec_dump );    my @errors = $validate->validate_rec( $rec, $rec_dump );
157    
158  =cut  =cut
159    
160  sub validate_errors {  sub validate_rec {
161          my $self = shift;          my $self = shift;
162    
163          my $log = $self->_get_logger();          my $log = $self->_get_logger();
164    
165          my $rec = shift || $log->logdie("validate_errors need record");          my $rec = shift || $log->logdie("validate_rec need record");
166          my $rec_dump = shift;          my $rec_dump = shift;
167    
168          $log->logdie("rec isn't HASH") unless (ref($rec) eq 'HASH');          $log->logdie("rec isn't HASH") unless (ref($rec) eq 'HASH');
169          $log->logdie("can't find validation rules") unless (my $r = $self->{rules});  #       $log->logdie("can't find validation rules") unless (my $r = $self->{rules});
170            my $r = $self->{rules};
171    
172          my $errors;          my $errors;
173    
# Line 142  sub validate_errors { Line 179  sub validate_errors {
179    
180                  next if (!defined($f) || $f eq '' || $f eq '000');                  next if (!defined($f) || $f eq '' || $f eq '000');
181    
182                    # first check delimiters
183                    if ( my $regex = $self->{delimiters_regex} ) {
184    
185                            foreach my $v (@{ $rec->{$f} }) {
186                                    my $l = _pack_subfields_hash( $v, 1 );
187                                    my $subfield_dump = $l;
188                                    my $template = '';
189                                    $l =~ s/$regex/$template.=$1/eg;
190                                    #warn "## template: $template\n";
191    
192                                    if ( $template ) {
193                                            $self->{_delimiters_templates}->{$f}->{$template}++;
194    
195                                            if ( my $v = $self->{_validate_delimiters_templates} ) {
196                                                    if ( ! defined( $v->{$f}->{$template} ) ) {
197                                                            $errors->{$f}->{potentially_invalid_combination} = $template;
198                                                            $errors->{$f}->{dump} = $subfield_dump;
199                                                    #} else {
200                                                    #       warn "## $f $template ok\n";
201                                                    }
202                                            }
203                                    }
204                            }
205                    }
206    
207                    next unless ( $r );     # skip validation of no rules are specified
208    
209                    next if (defined( $self->{dont_validate}->{$f} ));
210    
211                    # track field usage
212                  $fields->{$f}++;                  $fields->{$f}++;
213    
214                  if ( ! defined($r->{$f}) ) {                  if ( ! defined($r->{$f}) ) {
215                          $errors->{field}->{ $f }->{unexpected} = "this field is not expected";                          $errors->{ $f }->{unexpected} = "this field is not expected";
216                          next;                          next;
217                  }                  }
218    
219    
220                  if (ref($rec->{$f}) ne 'ARRAY') {                  if (ref($rec->{$f}) ne 'ARRAY') {
221                          $errors->{field}->{ $f }->{not_repeatable} = "probably bug in parsing input data";                          $errors->{ $f }->{not_repeatable} = "probably bug in parsing input data";
222                          next;                          next;
223                  }                  }
224    
# Line 160  sub validate_errors { Line 227  sub validate_errors {
227                          if (ref($r->{$f}) eq 'ARRAY') {                          if (ref($r->{$f}) eq 'ARRAY') {
228                                  # are values hashes? (has subfields)                                  # are values hashes? (has subfields)
229                                  if (! defined($v)) {                                  if (! defined($v)) {
230  #                                       $errors->{field}->{$f}->{empty} = undef;  #                                       $errors->{$f}->{empty} = undef;
231  #                                       $errors->{dump} = $rec_dump if ($rec_dump);  #                                       $errors->{dump} = $rec_dump if ($rec_dump);
232                                  } elsif (ref($v) ne 'HASH') {                                  } elsif (ref($v) ne 'HASH') {
233                                          $errors->{field}->{$f}->{missing_subfield} = join(",", @{ $r->{$f} }) . " required";                                          $errors->{$f}->{missing_subfield} = join(",", @{ $r->{$f} }) . " required";
234                                          next;                                          next;
235                                  } else {                                  } else {
236    
# Line 185  sub validate_errors { Line 252  sub validate_errors {
252                                                                  $sf_repeatable->{$sf}++;                                                                  $sf_repeatable->{$sf}++;
253                                                          };                                                          };
254                                                          if (! first { $_ eq $sf } @{ $r->{$f} }) {                                                          if (! first { $_ eq $sf } @{ $r->{$f} }) {
255                                                                  $errors->{field}->{ $f }->{subfield}->{extra}->{$sf}++;                                                                  $errors->{ $f }->{subfield}->{extra}->{$sf}++;
256                                                          }                                                          }
257                                                  }                                                  }
258    
# Line 193  sub validate_errors { Line 260  sub validate_errors {
260                                          if (my @r_sf = sort keys( %$sf_repeatable )) {                                          if (my @r_sf = sort keys( %$sf_repeatable )) {
261    
262                                                  foreach my $sf (@r_sf) {                                                  foreach my $sf (@r_sf) {
263                                                          $errors->{field}->{$f}->{subfield}->{extra_repeatable}->{$sf}++;                                                          $errors->{$f}->{subfield}->{extra_repeatable}->{$sf}++;
264                                                          $errors->{field}->{$f}->{dump} =                                                          $errors->{$f}->{dump} = _pack_subfields_hash( $h, 1 );
                                                                 join('', _pack_subfields_hash( $h, 1 ) );  
265                                                  }                                                  }
266    
267                                          }                                          }
# Line 203  sub validate_errors { Line 269  sub validate_errors {
269                                          if ( defined( $self->{must_exist_sf}->{$f} ) ) {                                          if ( defined( $self->{must_exist_sf}->{$f} ) ) {
270                                                  foreach my $sf (sort keys %{ $self->{must_exist_sf}->{$f} }) {                                                  foreach my $sf (sort keys %{ $self->{must_exist_sf}->{$f} }) {
271  #warn "====> $f $sf must exist\n";  #warn "====> $f $sf must exist\n";
272                                                          $errors->{field}->{$f}->{subfield}->{missing}->{$sf}++                                                          $errors->{$f}->{subfield}->{missing}->{$sf}++
273                                                                  unless defined( $subfields->{$sf} );                                                                  unless defined( $subfields->{$sf} );
274                                                  }                                                  }
275                                          }                                          }
276    
277                                  }                                  }
278                          } elsif (ref($v) eq 'HASH') {                          } elsif (ref($v) eq 'HASH') {
279                                  $errors->{field}->{$f}->{unexpected_subfields}++;                                  $errors->{$f}->{unexpected_subfields}++;
280                                  $errors->{field}->{$f}->{dump} =                                  $errors->{$f}->{dump} = _pack_subfields_hash( $v, 1 );
                                         join('', _pack_subfields_hash( $v, 1 ) );  
281                          }                          }
282                  }                  }
283          }          }
284    
285            $log->debug("_delimiters_templates = ", dump( $self->{_delimiters_templates} ) );
286    
287          foreach my $must (sort keys %{ $self->{must_exist} }) {          foreach my $must (sort keys %{ $self->{must_exist} }) {
288                  next if ($fields->{$must});                  next if ($fields->{$must});
289                  $errors->{field}->{$must}->{missing}++;                  $errors->{$must}->{missing}++;
290                  $errors->{dump} = $rec_dump if ($rec_dump);                  $errors->{dump} = $rec_dump if ($rec_dump);
291          }          }
292    
293          if ($errors) {          if ($errors) {
294                  $log->debug("errors: ", sub { dump( $errors ) } );                  $log->debug("errors: ", $self->report_error( $errors ) );
295    
296                  my $mfn = $rec->{'000'}->[0] || $log->logconfess("record ", dump( $rec ), " doesn't have MFN");                  my $mfn = $rec->{'000'}->[0] || $log->logconfess("record ", dump( $rec ), " doesn't have MFN");
297                  $self->{errors}->{$mfn} = $errors;                  $self->{errors}->{$mfn} = $errors;
# Line 235  sub validate_errors { Line 302  sub validate_errors {
302          return $errors;          return $errors;
303  }  }
304    
305  =head2 reset_errors  =head2 reset
306    
307  Clean all accumulated errors for this input  Clean all accumulated errors for this input and remember delimiter templates
308    for L<save_delimiters_templates>
309    
310    $validate->reset_errors;    $validate->reset;
311    
312    This function B<must> be called after each input to provide accurate statistics.
313    
314  =cut  =cut
315    
316  sub reset_errors {  sub reset {
317          my $self = shift;          my $self = shift;
318    
319            my $log = $self->_get_logger;
320    
321          delete ($self->{errors});          delete ($self->{errors});
322    
323            if ( ! $self->{_delimiters_templates} ) {
324                    $log->debug("called without _delimiters_templates?");
325                    return;
326            }
327    
328            foreach my $f ( keys %{ $self->{_delimiters_templates} } ) {
329                    foreach my $t ( keys %{ $self->{_delimiters_templates}->{$f} } ) {
330                            $self->{_accumulated_delimiters_templates}->{$f}->{$t} +=
331                                    $self->{_delimiters_templates}->{$f}->{$t};
332                    }
333            }
334            $log->debug("_accumulated_delimiters_templates = ", dump( $self->{_accumulated_delimiter_templates} ));
335            delete ($self->{_delimiters_templates});
336  }  }
337    
338  =head2 all_errors  =head2 all_errors
# Line 261  sub all_errors { Line 348  sub all_errors {
348          return $self->{errors};          return $self->{errors};
349  }  }
350    
351  =head2 report  =head2 report_error
352    
353  Produce nice humanly readable report of errors  Produce nice humanly readable report of single error
354    
355    print $validate->report;    print $validate->report_error( $error_hash );
356    
357  =cut  =cut
358    
359  sub report {  sub report_error {
360          my $self = shift;          my $self = shift;
361    
362          my $log = $self->_get_logger();          my $h = shift || die "no hash?";
363    
364            sub _unroll {
365                    my ($self, $tree, $accumulated) = @_;
366    
367          sub unroll {                  my $log = $self->_get_logger();
                 my ($tree, $accumulated) = @_;  
368    
369                  $log->debug("# ",                  $log->debug("# ",
370                          ( $tree                 ? "tree: $tree "                                        : '' ),                          ( $tree                 ? "tree: $tree "                                        : '' ),
# Line 294  sub report { Line 383  sub report {
383    
384                          if ($k eq 'dump') {                          if ($k eq 'dump') {
385                                  $dump = $tree->{dump};                                  $dump = $tree->{dump};
386                                  warn "## dump: $dump\n";                                  #warn "## dump ",dump($dump),"\n";
387                                  next;                                  next;
388                          }                          }
389    
390                          $log->debug("current: $k");                          $log->debug("current: $k");
391    
392                          my ($new_results, $new_dump) = unroll($tree->{$k},                          my ($new_results, $new_dump) = $self->_unroll($tree->{$k},
393                                  $accumulated ? "$accumulated\t$k" : $k                                  $accumulated ? "$accumulated\t$k" : $k
394                          );                          );
395    
# Line 324  sub report { Line 413  sub report {
413                  }                  }
414          }          }
415    
416    
417            sub _reformat {
418                    my $l = shift;
419                    $l =~ s/\t/ /g;
420                    $l =~ s/_/ /g;
421                    return $l;
422            }
423    
424          my $out = '';          my $out = '';
425    
426            for my $f (sort keys %{ $h }) {
427                    $out .= "$f: ";
428                    
429                    my ($r, $d) = $self->_unroll( $h->{$f} );
430                    my $e;
431                    if (ref($r) eq 'ARRAY') {
432                            $e .= join(", ", map { _reformat( $_ ) } @$r);
433                    } else {
434                            $e .= _reformat( $r );
435                    }
436                    $e .= "\n\t$d" if ($d);
437    
438                    $out .= $e . "\n";
439            }
440            return $out;
441    }
442    
443    
444    =head2 report
445    
446    Produce nice humanly readable report of errors
447    
448      print $validate->report;
449    
450    =cut
451    
452    sub report {
453            my $self = shift;
454          my $e = $self->{errors} || return;          my $e = $self->{errors} || return;
455    
456          foreach my $mfn (sort keys %$e) {          my $out;
457                  my ($r, $d) = unroll( $e->{$mfn} );          foreach my $mfn (sort { $a <=> $b } keys %$e) {
458                  $out .= "MFN $mfn\n", dump($r), "\t$d\n\n";                  $out .= "MFN $mfn\n" . $self->report_error( $e->{$mfn} ) . "\n";
459          }          }
460    
461          return $out;          return $out;
462    
463    }
464    
465    =head2 delimiters_templates
466    
467    Generate report of delimiter tamplates
468    
469      my $report = $validate->delimiter_teplates(
470            report => 1,
471            accumulated => 1,
472      );
473    
474    Options:
475    
476    =over 4
477    
478    =item report
479    
480    Generate humanly readable report with single fields
481    
482    =item accumulated
483    
484    Use accumulated data from all inputs
485    
486    =back
487    
488    =cut
489    
490    sub delimiters_templates {
491            my $self = shift;
492    
493            my $args = {@_};
494    
495            my $t;
496            if ( $args->{accumulated} ) {
497                    $t = $self->{_accumulated_delimiters_templates};
498            } else {
499                    $t = $self->{_delimiters_templates};
500            }
501    
502            my $log = $self->_get_logger;
503    
504            unless ($t) {
505                    $log->error("called without delimiters");
506                    return;
507            }
508    
509            my $out;
510    
511            foreach my $f (sort { $a <=> $b } keys %$t) {
512                    $out .= "$f\n" if ( $args->{report} );
513                    foreach my $template (sort { $a cmp $b } keys %{ $t->{$f} }) {
514                            my $count = $t->{$f}->{$template};
515                            $out .=
516                                    ( $count ? "" : "# " ) .
517                                    ( $args->{report} ? "" : "$f" ) .
518                                    "\t$count\t$template\n";
519                    }
520            }
521    
522            return $out;
523    }
524    
525    =head2 save_delimiters_templates
526    
527    Save accumulated delimiter templates
528    
529      $validator->save_delimiters_template( '/path/to/validate/delimiters' );
530    
531    =cut
532    
533    sub save_delimiters_templates {
534            my $self = shift;
535    
536            my $path = $self->{delimiters_path};
537    
538            return unless ( $path );
539    
540            my $log = $self->_get_logger;
541    
542            if ( ! $self->{_accumulated_delimiters_templates} ) {
543                    $log->error('no _accumulated_delimiters_templates found, reset');
544                    $self->reset;
545            }
546    
547            if ( ! $self->{_delimiters_templates} ) {
548                    $log->error('found _delimiters_templates, calling reset');
549                    $self->reset;
550            }
551    
552            $path .= '.new' if ( -e $path );
553    
554            open(my $d, '>', $path) || $log->fatal("can't open $path: $!");
555            print $d $self->delimiters_templates( accumulated => 1 );
556            close($d);
557    
558            $log->info("new delimiters templates saved to $path");
559  }  }
560    
561  =head1 AUTHOR  =head1 AUTHOR

Legend:
Removed from v.665  
changed lines
  Added in v.849

  ViewVC Help
Powered by ViewVC 1.1.26