Commit 19cb562e authored by Claudia Martens's avatar Claudia Martens
Browse files
parents b09485be 0b22795c
......@@ -19,9 +19,18 @@ import traceback
import os, sys, io, time
import argparse
import timeout_decorator
import urllib2, urllib, socket
import socket
import json, pprint
PY2 = sys.version_info[0] == 2
if PY2:
from urllib import quote
from urllib2 import urlopen, Request
from urllib2 import HTTPError,URLError
else:
from urllib import parse
from urllib.request import urlopen, Request
from urllib.error import HTTPError,URLError
def check_url(url):
# Checks and validates a url via urllib module
......@@ -38,12 +47,13 @@ def check_url(url):
resplen='--'
try:
start=time.time()
if (urllib2.urlopen(url, timeout=1).getcode() < 501):
request = Request(url)
if (urlopen(request, timeout=1).getcode() < 501):
msg='[OK]'
retcode=0
rta=time.time()-start
except urllib2.URLError as e:
except URLError as e:
## msg=" %s and %s" % (e,traceback.format_exc())
msg=" [URLError] %s" % e
retcode = 2 #catched
......@@ -65,9 +75,6 @@ def check_url(url):
return (retcode,msg,resplen,rta)
def check_ckan_action(actionreq,data,rows):
# Checks and validates a request or action submitted to CKAN
#
......@@ -83,45 +90,55 @@ def check_ckan_action(actionreq,data,rows):
rta=0
try:
start=time.time()
request = urllib2.Request(actionreq)
##HEW-D request = Request(actionreq)
if data :
data_string = urllib.quote(json.dumps(data))
response = urllib2.urlopen(request,data_string)
if PY2 :
data_string = quote(json.dumps(data))
else :
data_string = parse.quote(json.dumps(data)).encode('utf-8')
request = Request(actionreq,data_string)
response = urlopen(request)
else :
response = urllib2.urlopen(request)
request = Request(actionreq)
response = urlopen(request)
rta=time.time()-start
assert response.code == 200
response_dict = json.loads(response.read())
# Check the contents of the response.
assert response_dict['success'] is True
result = response_dict['result']
if actionreq.endswith('group_show') :
resplen=result['package_count']
else:
resplen=len(result)
except urllib2.URLError as e:
msg = " [URLERROR] %s " % e
except URLError as e:
msg = " [URLERROR] %s " % e
retcode = 2
except socket.timeout as e:
msg = " [IOERROR] %s " % e
msg = " [TIMEOUT] %s " % e
retcode = 2
except IOError as e:
msg = " [IOERROR] %s " % e
msg = " [IOError] %s " % e
retcode = 1
except ValueError as e:
msg = " [IOERROR] %s " % e
msg = " [ValueError] %s " % e
retcode = 1 #catched
except Exception as e:
msg = " [IOERROR] %s " % e
msg = " [Error] %s " % e
retcode = 3 #catched
else:
msg = '[OK]'
retcode = 0
assert response.code == 200
###print('response %s' % response.read())
if PY2 :
response_dict = json.loads(response.read())
else:
response_dict = response.read()
# Check the contents of the response.
if type(response_dict) is dict and 'success' in response_dict :
assert response_dict['success'] is True
## print('response.code %s' % response.code)
if type(response_dict) is dict and 'result' in response_dict :
result = response_dict['result']
if actionreq.endswith('group_show') :
resplen=result['package_count']
else:
resplen=len(result)
return (retcode,msg,resplen,rta)
def main():
......
# -*- coding: utf-8 -*-
"""converting.py - class for B2FIND converting :
- Converter maps harvested and specific MD records onto B2FIND schema
Copyright (c) 2013 Heinrich Widmann (DKRZ)
Further contributions by
2013 John Mrziglod (DKRZ)
2014 Mikael Karlsson (CSC)
2017 Claudia Martens (DKRZ)
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
# from future
from __future__ import absolute_import
from __future__ import print_function
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
__author__ = "Heinrich Widmann"
# system relevant modules:
import os, glob, sys
import time, datetime, subprocess
# program relevant modules:
import logging
import traceback
import re
# needed for MAPPER :
import codecs
import xml.etree.ElementTree as ET
import simplejson as json
import io
from pyparsing import *
import Levenshtein as lvs
import iso639
from collections import OrderedDict, Iterable
PY2 = sys.version_info[0] == 2
if PY2:
from urllib2 import urlopen
from urllib2 import HTTPError,URLError
else:
from urllib.request import urlopen
from urllib.error import HTTPError,URLError
class Converter(object):
"""
### CONVERTER - class
# Parameters:
# -----------
# Public Methods:
# ---------------
# convert(request) - converts records according to request on target schema (e.g. CERA) XMLs
# using templates and stores resulting files in subdirectory ' ...-<targetschema>/xml'
#
"""
def __init__ (self, OUT, base_outdir,fromdate):
##HEW-D logging = logging.getLogger()
self.base_outdir = base_outdir
self.OUT = OUT
self.fromdate = fromdate
self.logger = OUT.logger
# Read in B2FIND metadata schema and fields
schemafile = '%s/mapfiles/b2find_schema.json' % (os.getcwd())
with open(schemafile, 'r') as f:
self.b2findfields=json.loads(f.read(), object_pairs_hook=OrderedDict)
def json2xml(self,json_obj, line_padding="", mdftag="", mapdict="b2findfields"):
result_list = list()
json_obj_type = type(json_obj)
if json_obj_type is list:
for sub_elem in json_obj:
result_list.append(json2xml(sub_elem, line_padding, mdftag, mapdict))
return "\n".join(result_list)
if json_obj_type is dict:
for tag_name in json_obj:
sub_obj = json_obj[tag_name]
if tag_name in mapdict :
tag_name=mapdict[tag_name]
if not isinstance(tag_name,list) : tag_name=[tag_name]
for key in tag_name:
result_list.append("%s<%s%s>" % (line_padding, mdftag, key))
if type(sub_obj) is list:
for nv in sub_obj:
if tag_name == 'tags' or tag_name == 'KEY_CONNECT.GENERAL_KEY':
result_list.append("%s%s" % (line_padding, nv["name"].strip()))
else:
result_list.append("%s%s" % (line_padding, nv.strip()))
else:
result_list.append(self.json2xml(sub_obj, "\t" + line_padding, mdftag, mapdict))
result_list.append("%s</%s%s>" % (line_padding, mdftag, key))
else:
self.logger.debug ('[WARNING] : Field %s can not mapped to B2FIND schema' % tag_name)
continue
return "\n".join(result_list)
return "%s%s" % (line_padding, json_obj)
def convert(self,request):
# Converts JSON files to XML files formatted in target format, e.g. 'CERA' (exp_ and ds2_ files)
results = {
'count':0,
'tcount':0,
'ecount':0,
'time':0
}
# set processing parameters
community=request[0]
mdprefix=request[3]
mdsubset=request[4] if len(request)>4 else None
target_mdschema=request[5] if len(request)>5 else None
# set subset:
if (not mdsubset):
subset = 'SET_1' ## or 2,...
elif mdsubset.endswith('_'): # no OAI subsets, but store in sub dirs
subset = mdsubset+'1' ## or 2,...
elif mdsubset[-1].isdigit() and mdsubset[-2] == '_' :
subset = mdsubset
else:
subset = mdsubset+'_1'
self.logger.info(' |- Subset: \t%s' % subset )
# check for target_mdschema and set subset and path
if (target_mdschema):
# data subset dir :
outpath = '/'.join([self.base_outdir,community+'-'+mdprefix+'-'+target_mdschema,subset,'xml'])
self.logger.info('\t|- Data out path:\t%s' % outpath)
else:
self.logger.critical('For OAI converter processing target metaschema must be given!')
sys.exit()
inpath = '/'.join([self.base_outdir,community+'-'+mdprefix,subset])
# check data in and out path
if not os.path.exists(inpath+'/json') or not os.listdir(inpath + '/json'):
self.logger.error('[ERROR] Can not access input data path %s' % (inpath+'/json') )
return results
elif not os.path.exists(outpath) :
self.logger.warning('[ERROR] Create not existing output data path %s' % (outpath) )
os.makedirs(outpath)
# run oai-converting
# find all .json files in inpath/json:
files = list(filter(lambda x: x.endswith('.json'), os.listdir(inpath+'/json')))
results['tcount'] = len(files)
##oaiset=path.split(target_mdschema)[0].split('_')[0].strip('/')
##oaiset=os.path.basename(path)
## outpath=path.split(community)[0]+'/b2find-oai_b2find/'+community+'/'+mdprefix +'/'+path.split(mdprefix)[1].split('_')[0]+'/xml'
##HEW-D outpath=path.split(community)[0]+'b2find-oai_b2find/'+community+'/'+mdprefix +'/xml'
self.logger.debug(' %s Converting of files in %s' % (time.strftime("%H:%M:%S"),inpath))
self.logger.debug(' | %-4s | %-40s | %-40s |\n |%s|' % ('#','infile','outfile',"-" * 53))
fcount = 0
oldperc = 0
start = time.time()
# Read in B2FIND metadata schema and fields
schemafile = '%s/mapfiles/b2find_schema.json' % (os.getcwd())
with open(schemafile, 'r') as f:
b2findfields=json.loads(f.read())
for filename in files:
## counter and progress bar
fcount+=1
self.logger.debug('Next file to convert : %s' % inpath+'/json/'+filename)
perc=int(fcount*100/int(len(files)))
bartags=int(perc/5)
if perc%10 == 0 and perc != oldperc :
oldperc=perc
print ("\r\t[%-20s] %d / %d%% in %d sec" % ('='*bartags, fcount, perc, time.time()-start ))
sys.stdout.flush()
createdate = str(datetime.datetime.utcnow())
jsondata = dict()
self.logger.debug(' |- %s INFO JSON2XML - Processing: %s/%s' % (time.strftime("%H:%M:%S"),os.path.basename(inpath),filename))
if ( os.path.getsize(inpath+'/json/'+filename) > 0 ):
self.logger.debug('Read json file %s' % inpath+'/json/'+filename)
with open(inpath+'/json/'+filename, 'r') as f:
try:
jsondata=json.loads(f.read())
except:
self.logger.error(' | [ERROR] Can not access json file %s' % inpath+'/json/'+filename)
results['ecount'] += 1
continue
else:
self.logger.critical('Can not access json file %s' % inpath+'/json/'+filename)
results['ecount'] += 1
continue
### oai-convert !!
if target_mdschema == 'cera':
##HEW-T print('JJJJJJJJ %s' % jsondata['oai_identifier'])
if 'oai_identifier' in jsondata :
identifier=jsondata['oai_identifier'][0]
else:
identifier=os.path.splitext(filename)[0]
convertfile='%s/mapfiles/%s%s.%s' % (os.getcwd(),'json2',target_mdschema,'json')
with open(convertfile, 'r') as f:
try:
mapdict=json.loads(f.read())
except:
self.logger.error(' | [ERROR] Cannot load the convert file %s' % convertfile)
sys.exit()
for filetype in ['ds2','exp']:
outfile=outpath+'/'+filetype+'_'+community+'_'+identifier+'.xml'
### load xml template
templatefile='%s/mapfiles/%s_%s_%s.%s' % (os.getcwd(),target_mdschema,filetype,'template','xml')
with open(templatefile, 'r') as f:
try:
dsdata= f.read() ##HEW-D ET.parse(templatefile).getroot()
except Exception :
self.logger.error(' | Cannot load tempalte file %s' % (templatefile))
data=dict()
jsondata['community']=community
##HEW-D dsdata = Template(dsdata)
for facetdict in b2findfields.values() :
facet=facetdict["ckanName"]
##HEW-T print ('facet %s ' % facet)
if facet in jsondata:
if isinstance(jsondata[facet],list) and len(jsondata[facet])>0 :
if facet == 'tags':
data[facet]=''
for tagndict in jsondata[facet]:
data[facet]+=tagndict['name']
else:
data[facet]=' '.join(jsondata[facet]).strip('\n ')
else :
data[facet]=jsondata[facet]
## outdata = dsdata.substitute(key=data[key])
##HEW-T print('KKKK key %s\t data %s' % (key,data[key]))
else:
data[facet]=''
data['identifier']=identifier
try:
outdata=dsdata%data
except KeyError as err :
self.logger.error("[ERROR] %s\n" % err )
pass
outfile=outpath+'/'+filetype+'_'+identifier+'.xml'
try :
f = open(outfile, 'w')
f.write(outdata) ### .encode('utf-8'))
f.write("\n")
f.close
except IOError :
self.logger.error("[ERROR] Cannot write data in xml file '%s': %s\n" % (outfile))
return(False, outfile , outpath, fcount)
else:
identifier=jsondata["oai_identifier"]
outfile=outpath+'/'+filetype+'/'+community+'_'+identifier+'.xml'
mapdict=self.b2findfields ##HEW-D ??? ckanfields ???
header="""<record xmlns="http://www.openarchives.org/OAI/2.0/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<header>
<identifier>"""+identifier+"""</identifier>
<datestamp>"""+createdate+"""</datestamp>
<setSpec>"""+oaiset+"""</setSpec>
</header>
<metadata>
<oai_b2find:b2find xmlns:b2find="http://purl.org/b2find/elements/1.1/" xmlns:oai_b2find="http://www.openarchives.org/OAI/2.0/oai_b2find/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://b2find.eudat.eu/schema http://b2find.eudat.eu/schema/oai_b2find.xsd">
"""
footer="""
</oai_b2find:b2find>
</metadata>
</record>"""
xmlprefix='b2find'
xmldata=header+self.json2xml(jsondata,'\t',xmlprefix,mapdict)+footer
try:
f = open(outfile, 'w')
f.write(xmldata.encode('utf-8'))
f.write("\n")
f.close
except IOError :
self.logger.error("[ERROR] Cannot write data in xml file '%s': %s\n" % (outfile))
return(False, outfile , outpath, fcount)
self.logger.debug(' | o | %-4d | %-45s | %-45s |' % (fcount,os.path.basename(filename),os.path.basename(outfile)))
self.logger.info('%s INFO B2FIND : %d records converted; %d records caused error(s).' % (time.strftime("%H:%M:%S"),fcount,results['ecount']))
# count ... all .xml files in path/b2find
results['count'] = len(list(filter(lambda x: x.endswith('.xml'), os.listdir(outpath))))
print (' \t|- %-10s |@ %-10s |\n\t| Provided | Converted | Failed |\n\t| %8d | %6d | %6d |' % ( 'Finished',time.strftime("%H:%M:%S"),
results['tcount'],
fcount,
results['ecount']
))
return results
......@@ -20,6 +20,8 @@ http://capsella.madgik.di.uoa.gr:8081/oaipmh-publisher ListRecords oai_dc
getit http://getit.lifewatch.unisalento.it/catalogue/csw csw iso19139 full
## DataverseNO
dataverseno https://dataverse.no/oai ListRecords oai_dc HarvesterDataverseNO
dataverseno https://dataverse.no/oai ListRecords oai_dc nmdc
dataverseno https://dataverse.no/oai ListRecords oai_dc trolling
##Herbadrop
herbadrop https://www.cines.fr/en/herbadrop-project-honored ListRecords oai_dc
herbadrop https://www.cines.fr/en/herbadrop-project-honored works json
......@@ -52,13 +54,14 @@ epos http://epos-tcs-uni-utr??? ListRecords iso19139 SET_1
##epos https://trng-b2share.eudat.eu/api/oai2d ListRecords marcxml EPOS
## SLKS
### slks https://www.kulturarv.dk/repox/OAIHandler ListRecords lido
slks https://www.kulturarv.dk/repox/OAIHandler ListRecords fbb test
##slks https://www.kulturarv.dk/repox/OAIHandler ListRecords fbb test
slks https://www.kulturarv.dk/repox/OAIHandler ListRecords fbb SAVE
slks https://www.kulturarv.dk/repox/OAIHandler ListRecords fbb Objects
##??NO fbb??? slks https://www.kulturarv.dk/repox/OAIHandler ListRecords fbb Objects
slks https://www.kulturarv.dk/repox/OAIHandler ListRecords fbb Listed
slks https://www.kulturarv.dk/repox/OAIHandler ListRecords fbb KID
##??NO fbb??? slks https://www.kulturarv.dk/repox/OAIHandler ListRecords fbb KID
slks https://www.kulturarv.dk/repox/OAIHandler ListRecords fbb Preservation
slks https://www.kulturarv.dk/repox/OAIHandler ListRecords fbb Foto
##??NO fbb??? slks https://www.kulturarv.dk/repox/OAIHandler ListRecords fbb Foto
##??NO OAI set ??? slks https://www.kulturarv.dk/repox/OAIHandler ListRecords fbb sites
## HZG
hzg http://???? ListRecords iso19139 coastmap
## Aston university
......
......@@ -30,6 +30,7 @@ Modified by c/o DKRZ 2018 Heinrich Widmann
from generating import Generator
from harvesting import Harvester
from mapping import Mapper
from converting import Converter
from validating import Validator
from uploading import Uploader, CKAN_CLIENT
from output import Output
......@@ -57,7 +58,7 @@ def main():
settings.init()
# parse command line options and arguments:
modes=['a','g','generate','h','harvest','c','convert','m','map','v','validate','o','oaiconvert','u','upload','h-c','c-u','h-u', 'h-d', 'd','delete']
modes=['a','g','generate','h','harvest','m','map','v','validate','c','convert','u','upload','h-m','m-u','h-u', 'h-d', 'd','delete']
p = options_parser(modes)
global options
options,arguments = p.parse_args()
......@@ -218,11 +219,11 @@ def process(options,pstat,OUT):
VD = Validator(OUT,options.outdir,options.fromdate)
process_validate(VD,reqlist)
## OAI-CONVERTING - Mode:
if (pstat['status']['o'] == 'tbd'):
logger.info('\n|- OAI-Converting started : %s' % time.strftime("%Y-%m-%d %H:%M:%S"))
MP = Mapper(OUT,options.outdir,options.fromdate)
process_oaiconvert(MP, reqlist)
## CONVERTING - Mode:
if (pstat['status']['c'] == 'tbd'):
logger.info('\n|- Converting started : %s' % time.strftime("%Y-%m-%d %H:%M:%S"))
CV = Converter(OUT,options.outdir,options.fromdate)
process_convert(CV, reqlist)
## UPLOADING - Mode:
if (pstat['status']['u'] == 'tbd'):
......@@ -449,7 +450,7 @@ def process_upload(UP, rlist):
UP.OUT.save_stats(request[0]+'-'+request[3],'SET_1','u',results)
def process_oaiconvert(MP, rlist):
def process_convert(CV, rlist):
ir=0
for request in rlist:
......@@ -457,13 +458,13 @@ def process_oaiconvert(MP, rlist):
print (' |# %-4d : %-10s\t%-20s --> %-10s\n\t|- %-10s |@ %-10s |' % (ir,request[0],request[2:5],request[5],'Started',time.strftime("%H:%M:%S")))
rcstart = time.time()
results = MP.oaiconvert(request)
results = CV.convert(request)
rctime=time.time()-rcstart
results['time'] = rctime
# save stats:
MP.OUT.save_stats(request[0]+'-'+ request[3],request[4],'o',results)
CV.OUT.save_stats(request[0]+'-'+ request[3],request[4],'c',results)
def process_delete(OUT, dir, options):
......@@ -731,7 +732,7 @@ def pstat_init (p,modes,mode,source,iphost):
mode = 'h-u'
# initialize status, count and timing of processes
plist=['g','h','m','v','u','c','o','d']
plist=['g','h','m','v','u','c','d']
pstat = {
'status' : {},
'text' : {},
......@@ -759,20 +760,18 @@ def pstat_init (p,modes,mode,source,iphost):
pstat['text']['g']='Generate XML files from ' + stext
pstat['text']['h']='Harvest XML files from ' + stext
pstat['text']['c']='Convert XML to B2FIND JSON'
pstat['text']['m']='Map community XML to B2FIND JSON and do semantic mapping'
pstat['text']['v']='Validate JSON records against B2FIND schema'
pstat['text']['o']='OAI-Convert B2FIND JSON to B2FIND XML'
pstat['text']['c']='Convert JSON to (e.g. CERA) XML'
pstat['text']['u']='Upload JSON records as datasets into B2FIND %s' % iphost
pstat['text']['d']='Delete B2FIND datasets from %s' % iphost
pstat['short']['h-u']='TotalIngestion'
pstat['short']['g']='Generating'
pstat['short']['h']='Harvesting'
pstat['short']['c']='Converting'
pstat['short']['m']='Mapping'
pstat['short']['v']='Validating'
pstat['short']['o']='OAIconverting'
pstat['short']['c']='Converting'
pstat['short']['u']='Uploading'
pstat['short']['d']='Deletion'
......
......@@ -21,6 +21,9 @@
<field name="url">
<xpath>//dc:identifier</xpath>
</field>
<field name="MetadataAccess">
<xpath>//h:header/h:identifier</xpath>
</field>
<!-- Provenance information -->
<field name="author">
<xpath>//dc:creator</xpath>
......
......@@ -16,37 +16,32 @@
<field name="tags">
<xpath>//dc:subject</xpath>
</field>
<!-- Access data -->
<!-- Identifier -->
<field name="url">
<xpath>//dc:identifier</xpath>
</field>
<field name="Checksum">
</field>
<field name="Rights">
<xpath>//dc:rights</xpath>
</field>
<!-- Provenance data -->
<field name="Discipline">
<xpath>//dc:subject</xpath>
<field name="MetadataAccess">
<xpath>//h:header/h:identifier</xpath>
</field>
<!-- Provenance information -->
<field name="author">
<xpath>//dc:creator</xpath>
</field>
<field name="Publisher">
<xpath>//dc:publisher</xpath>
<xpath>//dc:source</xpath>
</field>
<field name="PublicationYear">
<xpath>//dc:date[0]</xpath>
<xpath>//r:datestamp</xpath>
</field>
<!-- Formal data -->
<field name="Language">
<xpath>//dc:language</xpath>
<field name="Rights">
<xpath>//dc:rights</xpath>
</field>
<field name="SpatialCoverage">
<xpath>//dc:coverage</xpath>
<field name="Contact">
<xpath>//dc:creator</xpath>
</field>
<field name="TemporalCoverage">
<xpath>//dc:coverage</xpath>
<!-- Representation Information -->
<field name="Language">