source: gs2-extensions/parallel-building/trunk/src/perllib/plugins/MetadataXMLPlugin.pm@ 24626

Last change on this file since 24626 was 24626, checked in by jmt12, 13 years ago

An (almost) complete copy of the perllib directory from a (circa SEP2011) head checkout from Greenstone 2 trunk - in order to try and make merging in this extension a little easier later on (as there have been some major changes to buildcol.pl commited in the main trunk but not in the x64 branch)

File size: 12.5 KB
Line 
1###########################################################################
2#
3# MetadataXMLPlugin.pm --
4# A component of the Greenstone digital library software
5# from the New Zealand Digital Library Project at the
6# University of Waikato, New Zealand.
7#
8# Copyright (C) 2006 New Zealand Digital Library Project
9#
10# This program is free software; you can redistribute it and/or modify
11# it under the terms of the GNU General Public License as published by
12# the Free Software Foundation; either version 2 of the License, or
13# (at your option) any later version.
14#
15# This program is distributed in the hope that it will be useful,
16# but WITHOUT ANY WARRANTY; without even the implied warranty of
17# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18# GNU General Public License for more details.
19#
20# You should have received a copy of the GNU General Public License
21# along with this program; if not, write to the Free Software
22# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23#
24###########################################################################
25
26# MetadataXMLPlugin process metadata.xml files in a collection
27
28# Here's an example of a metadata file that uses three FileSet structures
29# (ignore the # characters):
30
31#<?xml version="1.0" encoding="UTF-8" standalone="no"?>
32#<!DOCTYPE DirectoryMetadata SYSTEM "http://greenstone.org/dtd/DirectoryMetadata/1.0/DirectoryMetadata.dtd">
33#<DirectoryMetadata>
34# <FileSet>
35# <FileName>nugget.*</FileName>
36# <Description>
37# <Metadata name="Title">Nugget Point, The Catlins</Metadata>
38# <Metadata name="Place" mode="accumulate">Nugget Point</Metadata>
39# </Description>
40# </FileSet>
41# <FileSet>
42# <FileName>nugget-point-1.jpg</FileName>
43# <Description>
44# <Metadata name="Title">Nugget Point Lighthouse, The Catlins</Metadata>
45# <Metadata name="Subject">Lighthouse</Metadata>
46# </Description>
47# </FileSet>
48# <FileSet>
49# <FileName>kaka-point-dir</FileName>
50# <Description>
51# <Metadata name="Title">Kaka Point, The Catlins</Metadata>
52# </Description>
53# </FileSet>
54#</DirectoryMetadata>
55
56# Metadata elements are read and applied to files in the order they appear
57# in the file.
58#
59# The FileName element describes the subfiles in the directory that the
60# metadata applies to as a perl regular expression (a FileSet group may
61# contain multiple FileName elements). So, <FileName>nugget.*</FileName>
62# indicates that the metadata records in the following Description block
63# apply to every subfile that starts with "nugget". For these files, a
64# Title metadata element is set, overriding any old value that the Title
65# might have had.
66#
67# Occasionally, we want to have multiple metadata values applied to a
68# document; in this case we use the "mode=accumulate" attribute of the
69# particular Metadata element. In the second metadata element of the first
70# FileSet above, the "Place" metadata is accumulating, and may therefore be
71# given several values. If we wanted to override these values and use a
72# single metadata element again, we could set the mode attribute to
73# "override" instead. Remember: every element is assumed to be in override
74# mode unless you specify otherwise, so if you want to accumulate metadata
75# for some field, every occurance must have "mode=accumulate" specified.
76#
77# The second FileSet element above applies to a specific file, called
78# nugget-point-1.jpg. This element overrides the Title metadata set in the
79# first FileSet, and adds a "Subject" metadata field.
80#
81# The third and final FileSet sets metadata for a subdirectory rather than
82# a file. The metadata specified (a Title) will be passed into the
83# subdirectory and applied to every file that occurs in the subdirectory
84# (and to every subsubdirectory and its contents, and so on) unless the
85# metadata is explictly overridden later in the import.
86
87package MetadataXMLPlugin;
88
89use strict;
90no strict 'refs';
91
92use Encode;
93
94use BasePlugin;
95use util;
96use metadatautil;
97
98sub BEGIN {
99 @MetadataXMLPlugin::ISA = ('BasePlugin');
100
101 # ensure Greenstone's CPAN is on the path (but check first) [jmt12]
102 my $inc_paths = join(':', @INC);
103 my $gsdl_perllib_path = $ENV{'GSDLHOME'} . '/perllib/cpan';
104 if ($inc_paths !~ /$gsdl_perllib_path/)
105 {
106 unshift (@INC, $gsdl_perllib_path);
107 }
108}
109
110use XMLParser;
111
112my $arguments = [
113 { 'name' => "process_exp",
114 'desc' => "{BasePlugin.process_exp}",
115 'type' => "regexp",
116 'reqd' => "no",
117 'deft' => &get_default_process_exp() }
118
119];
120
121my $options = { 'name' => "MetadataXMLPlugin",
122 'desc' => "{MetadataXMLPlugin.desc}",
123 'abstract' => "no",
124 'inherits' => "yes",
125 'args' => $arguments };
126
127sub new {
128 my ($class) = shift (@_);
129 my ($pluginlist,$inputargs,$hashArgOptLists) = @_;
130 push(@$pluginlist, $class);
131
132 push(@{$hashArgOptLists->{"ArgList"}},@{$arguments});
133 push(@{$hashArgOptLists->{"OptList"}},$options);
134
135 my $self = new BasePlugin($pluginlist, $inputargs, $hashArgOptLists);
136
137 if ($self->{'info_only'}) {
138 # don't worry about any options or initialisations etc
139 return bless $self, $class;
140 }
141
142 # The following used to be passed in as a parameter to XML::Parser,
143 # if the version of perl was greater than or equal to 5.8.
144 # The svn commit comment explaining the reason for adding this was
145 # not very clear and also said that it was quick fix and hadn't
146 # been tested under windows.
147 # More recent work has been to make strings in Perl "Unicode-aware"
148 # and so this line might actually be potentially harmful, however
149 # it is not the case that we encountered an actual error leading to
150 # its removal, rather it has been eliminated in an attempt to tighten
151 # up the code. For example, this protocol encoding is not used in
152 # ReadXMLFile.
153 # 'ProtocolEncoding' => 'ISO-8859-1',
154
155 # create XML::Parser object for parsing metadata.xml files
156 my $parser = new XML::Parser('Style' => 'Stream',
157 'Pkg' => 'MetadataXMLPlugin',
158 'PluginObj' => $self,
159 'Handlers' => {'Char' => \&Char,
160 'Doctype' => \&Doctype
161 });
162
163 $self->{'parser'} = $parser;
164 $self->{'in_filename'} = 0;
165
166
167 return bless $self, $class;
168}
169
170
171sub get_default_process_exp
172{
173 return q^metadata\.xml$^;
174}
175
176sub get_doctype {
177 my $self = shift(@_);
178
179 return "(Greenstone)?DirectoryMetadata"
180}
181
182sub can_process_this_file {
183 my $self = shift(@_);
184 my ($filename) = @_;
185
186 if (-f $filename && $self->SUPER::can_process_this_file($filename) && $self->check_doctype($filename)) {
187 return 1; # its a file for us
188 }
189 return 0;
190}
191
192sub check_doctype {
193 my $self = shift (@_);
194
195 my ($filename) = @_;
196
197 if (open(XMLIN,"<$filename")) {
198 my $doctype = $self->get_doctype();
199 ## check whether the doctype has the same name as the root element tag
200 while (defined (my $line = <XMLIN>)) {
201 ## find the root element
202 if ($line =~ /<([\w\d:]+)[\s>]/){
203 my $root = $1;
204 if ($root !~ $doctype){
205 close(XMLIN);
206 return 0;
207 }
208 else {
209 close(XMLIN);
210 return 1;
211 }
212 }
213 }
214 close(XMLIN);
215 }
216
217 return undef; # haven't found a valid line
218
219}
220
221sub file_block_read {
222 my $self = shift (@_);
223 my ($pluginfo, $base_dir, $file, $block_hash, $metadata, $gli) = @_;
224
225 my $filename_full_path = &util::filename_cat($base_dir, $file);
226 return undef unless $self->can_process_this_file($filename_full_path);
227
228 if ($ENV{'GSDLOS'} =~ m/^windows$/) {
229
230 my $lower_drive = $filename_full_path;
231 $lower_drive =~ s/^([A-Z]):/\l$1:/i;
232
233 my $upper_drive = $filename_full_path;
234 $upper_drive =~ s/^([A-Z]):/\u$1:/i;
235
236 $block_hash->{'metadata_files'}->{$lower_drive} = 1;
237 $block_hash->{'metadata_files'}->{$upper_drive} = 1;
238 }
239 else {
240 $block_hash->{'metadata_files'}->{$filename_full_path} = 1;
241 }
242
243 return 1;
244}
245
246sub metadata_read
247{
248 my $self = shift (@_);
249 my ($pluginfo, $base_dir, $file, $block_hash,
250 $extrametakeys, $extrametadata,$extrametafile,
251 $processor, $gli, $aux) = @_;
252
253 my $filename = &util::filename_cat($base_dir, $file);
254 return undef unless $self->can_process_this_file($filename);
255
256 $self->{'metadata-file'} = $file;
257 $self->{'metadata-filename'} = $filename;
258
259 my $outhandle = $self->{'outhandle'};
260
261 print STDERR "\n<Processing n='$file' p='MetadataXMLPlugin'>\n" if ($gli);
262 print $outhandle "MetadataXMLPlugin: processing $file\n" if ($self->{'verbosity'})> 1;
263 # add the file to the block list so that it won't be processed in read, as we will do all we can with it here
264 &util::block_filename($block_hash,$filename);
265
266 $self->{'metadataref'} = $extrametadata;
267 $self->{'metafileref'} = $extrametafile;
268 $self->{'metakeysref'} = $extrametakeys;
269
270 eval {
271 $self->{'parser'}->parsefile($filename);
272 };
273
274 if ($@) {
275 print STDERR "**** Error is: $@\n";
276 my $plugin_name = ref ($self);
277 my $failhandle = $self->{'failhandle'};
278 print $outhandle "$plugin_name failed to process $file ($@)\n";
279 print $failhandle "$plugin_name failed to process $file ($@)\n";
280 print STDERR "<ProcessingError n='$file'>\n" if ($gli);
281 return -1; #error
282 }
283
284 return 1;
285
286}
287
288
289# Updated by Jeffrey 2010/04/16 @ DL Consulting Ltd.
290# Get rid off the global $self as it cause problems when there are 2+ MetadataXMLPlugin in your collect.cfg...
291# For example when you have an OAIMetadataXMLPlugin that is a child of MetadataXMLPlugin
292sub Doctype {$_[0]->{'PluginObj'}->xml_doctype(@_);}
293sub StartTag {$_[0]->{'PluginObj'}->xml_start_tag(@_);}
294sub EndTag {$_[0]->{'PluginObj'}->xml_end_tag(@_);}
295sub Text {$_[0]->{'PluginObj'}->xml_text(@_);}
296
297
298sub xml_doctype {
299 my $self = shift(@_);
300 my ($expat, $name, $sysid, $pubid, $internal) = @_;
301
302 # allow the short-lived and badly named "GreenstoneDirectoryMetadata" files
303 # to be processed as well as the "DirectoryMetadata" files which should now
304 # be created by import.pl
305 die if ($name !~ /^(Greenstone)?DirectoryMetadata$/);
306}
307
308sub xml_start_tag {
309 my $self = shift(@_);
310 my ($expat, $element) = @_;
311
312 if ($element eq "FileSet") {
313 $self->{'saved_targets'} = [];
314 $self->{'saved_metadata'} = {};
315 }
316 elsif ($element eq "FileName") {
317 $self->{'in_filename'} = 1;
318 }
319 elsif ($element eq "Metadata") {
320 $self->{'metadata_name'} = $_{'name'};
321 $self->{'metadata_value'} = "";
322 if ((defined $_{'mode'}) && ($_{'mode'} eq "accumulate")) {
323 $self->{'metadata_accumulate'} = 1;
324 } else {
325 $self->{'metadata_accumulate'} = 0;
326 }
327 }
328}
329
330sub xml_end_tag {
331 my $self = shift(@_);
332 my ($expat, $element) = @_;
333
334 if ($element eq "FileSet") {
335 foreach my $target (@{$self->{'saved_targets'}}) {
336 my $file_metadata = $self->{'metadataref'}->{$target};
337 my $saved_metadata = $self->{'saved_metadata'};
338
339 if (!defined $file_metadata) {
340 $self->{'metadataref'}->{$target} = $saved_metadata;
341
342 # not had target before
343 push (@{$self->{'metakeysref'}}, $target);
344 }
345 else {
346 &metadatautil::combine_metadata_structures($file_metadata,$saved_metadata);
347 }
348
349
350 # now record which metadata.xml file it came from
351
352 my $file = $self->{'metadata-file'};
353 my $filename = $self->{'metadata-filename'};
354
355 if (!defined $self->{'metafileref'}->{$target}) {
356 $self->{'metafileref'}->{$target} = {};
357 }
358
359 $self->{'metafileref'}->{$target}->{$file} = $filename
360 }
361 }
362 elsif ($element eq "FileName") {
363 $self->{'in_filename'} = 0;
364 }
365 elsif ($element eq "Metadata") {
366 # text read in by XML::Parser is in Perl's binary byte value
367 # form ... need to explicitly make it UTF-8
368
369 my $metadata_name = decode("utf-8",$self->{'metadata_name'});
370 my $metadata_value = decode("utf-8",$self->{'metadata_value'});
371
372 &metadatautil::store_saved_metadata($self,
373 $metadata_name, $metadata_value,
374 $self->{'metadata_accumulate'});
375 $self->{'metadata_name'} = "";
376 }
377
378}
379
380sub xml_text {
381 my $self = shift(@_);
382
383 if ($self->{'in_filename'}) {
384 # $_ == FileName content
385 push (@{$self->{'saved_targets'}}, $_);
386 }
387 elsif (defined ($self->{'metadata_name'}) && $self->{'metadata_name'} ne "") {
388 # $_ == Metadata content
389 $self->{'metadata_value'} = $_;
390 }
391}
392
393# This Char function overrides the one in XML::Parser::Stream to overcome a
394# problem where $expat->{Text} is treated as the return value, slowing
395# things down significantly in some cases.
396sub Char {
397 use bytes; # Necessary to prevent encoding issues with XML::Parser 2.31+
398
399# if ($]<5.008) {
400# use bytes; # Necessary to prevent encoding issues with XML::Parser 2.31+ and Perl 5.6
401# }
402 $_[0]->{'Text'} .= $_[1];
403 return undef;
404}
405
406
407
4081;
Note: See TracBrowser for help on using the repository browser.