-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnationalLicences.py
315 lines (220 loc) · 12 KB
/
nationalLicences.py
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
# -*- coding: utf-8 -*-
import os
import uuid
from swissbibMongoHarvesting import MongoDBHarvestingWrapper
from swissbibHarvestingConfigs import HarvestingFilesConfigs
from argparse import ArgumentParser
from Context import ApplicationContext, NLApplicationContext
from swissbibUtilities import ResultCollector, SwissbibUtilities
from datetime import datetime, timedelta
from harvestingTasks import PersistNLMongo
from FileProcessorImpl import FileProcessor, SingleImportFileProvider,FileWebdavWriteContext
from harvestingTasks import PersistRecordMongo, PersistNLMongo, WriteModsForCBS
from Context import TaskContext, StoreNativeRecordContext, StoreNativeNLRecordContext
from lxml import etree
import re
import StringIO
class NLFileProvider(SingleImportFileProvider):
def __init__(self,context):
SingleImportFileProvider.__init__(self,context)
def getFileContent(self, path, filename):
fileHandle = open("".join([path,'/',filename]),"r")
content = fileHandle.read()
return content
def createGenerator(self):
processedDataDir = self.context.getConfiguration().getNlProcessedDataDir()
for root, dirs, files in os.walk(processedDataDir):
for file in files:
if file.lower().endswith('.xml') or file.lower().endswith('.xml.meta'):
yield [self.getFileContent(root, file), root+'/'+file]
class NationalLicencesProcessor(FileProcessor):
def __init__(self,context):
FileProcessor.__init__(self,context)
def _getRecordIdFromMods(self, modsRecord):
recordTree = etree.fromstring(modsRecord)
# Get id from XML
xpathGetIdentifier = "//ns:identifier[@type='swissbib']"
result = recordTree.xpath(xpathGetIdentifier, namespaces={'ns': 'http://www.loc.gov/mods/v3'})
if len(result) > 0:
id = result[0].text
else: # almost never the case, but just to make sure
id = str(uuid.uuid4())
return id
def _getModsStructure(self, sourceRecord, filename):
f = StringIO.StringIO(sourceRecord)
xml = etree.parse(f)
plain_string_filename = etree.XSLT.strparam(filename)
#filename is passed as a stylesheet parameter
mods = self.context.getModsTransformation()(xml, filename=plain_string_filename)
return etree.tostring(mods)
def lookUpContent(self):
#lookup raw content deliverd by publisher
#FTP lookup ? not done by now
#actually we have to put the raw content manually at the rightt place
pass
def preProcessContent(self):
pass
#start xslt transformation process created by Lionel
#launch shell scripts (lionel)
def initialize(self):
pass
#do we have to do some kind of initialization
#e.g. creation or deletion of directories??
def postProcessContent(self):
pass
#move the collected content (which should be aggregated into one single file)
#into the proper directory for CBS
#perhaps we can use at least part of the implementations available for other pipes
def process(self):
nlFileProvider = NLFileProvider(self.context)
try:
for recordAndFilename in nlFileProvider.createGenerator():
contentSingleRecord = recordAndFilename[0]
filename = recordAndFilename[1]
try:
mods = self._getModsStructure(contentSingleRecord, filename)
recordId = self._getRecordIdFromMods(mods)
#print contentSingleRecord
for taskName, task in self.context.getConfiguration().getDedicatedTasks().items():
#write record into file which is going to be sent to CBS later
#open question: what do we do with DTD?
try:
#do we have to do any additional validation of the record?
if isinstance(task, PersistNLMongo) or isinstance(task, WriteModsForCBS) :
#extract id from swissbib-jats
#extract year from swissbib-jats (pyear, eyear or others)
taskContext = StoreNativeNLRecordContext(appContext=self.context,
rID=recordId, jatsRecord=contentSingleRecord,
deleted=False,modsRecord=mods)
else:
taskContext = TaskContext(appContext=self.context)
task.processRecord(taskContext)
except Exception as pythonBaseException:
#write Exception into log
continue
except Exception as BaseException:
#make some kind of error handling
continue
except Exception as processExcepion:
print processExcepion
if __name__ == '__main__':
__author__ = 'swissbib - UB Basel, Switzerland, Guenter Hipler'
__copyright__ = "Copyright 2016, swissbib project"
__license__ = "??"
__version__ = "0.1"
__maintainer__ = "Guenter Hipler"
__email__ = "[email protected]"
__status__ = "in development"
__description__ = """
"""
oParser = None
args = None
sConfigs = None
mongoWrapper = None
rCollector = None
startTime = None
nebisClient = None
appContext = None
try:
#print sys.version_info
oParser = ArgumentParser()
oParser.add_argument("-c", "--config", dest="confFile")
args = oParser.parse_args()
sConfigs = HarvestingFilesConfigs(args.confFile)
sConfigs.setApplicationDir(os.getcwd())
rCollector = ResultCollector()
startTime = datetime.now()
appContext = NLApplicationContext()
appContext.setConfiguration(sConfigs)
appContext.setResultCollector(rCollector)
data = open(sConfigs.getJats2modsxsl(),'r')
xslt_content = data.read()
data.close()
xslt_root = etree.XML(xslt_content)
transform = etree.XSLT(xslt_root)
appContext.setModsTransformation(transform)
mongoWrapper = MongoDBHarvestingWrapper(applicationContext=appContext)
appContext.setMongoWrapper(mongoWrapper)
aggregatonFile = "".join([str(appContext.getConfiguration().getPrefixSummaryFile()),'-','{:%Y%m%d%H%M%S}'.format(datetime.now()), "-", 'nl.all.xml'])
wC = FileWebdavWriteContext(appContext)
appContext.setWriteContext(wC)
wC.setOutFileName(aggregatonFile)
client = globals()[sConfigs.getFileProcessorType()](appContext)
client.initialize()
client.lookUpContent()
client.preProcessContent()
client.process()
client.postProcessContent()
except Exception as exception:
if not appContext is None and not appContext.getWriteContext() is None:
procMess=["Exception in FileProcessorImpl.py"]
if not appContext.getConfiguration() is None:
procMess = SwissbibUtilities.addBlockedMessageToLogSummary(procMess,appContext.getConfiguration())
appContext.getWriteContext().handleOperationAfterError(exType=exception,
message="\n".join(procMess) )
elif not appContext is None and not appContext.getConfiguration() is None:
logfile = open(appContext.getConfiguration().getErrorLogDir() + os.sep + appContext.getConfiguration().getErrorLogFile(),"a")
message = ["no WriteContext after Error: Exception Handler",
str(exception)]
message = SwissbibUtilities.addBlockedMessageToLogSummary(message,appContext.getConfiguration())
logfile.write("\n".join(message))
logfile.flush()
logfile.close()
else:
print "no WriteContext after Error and Configuration is None: Exception Handler"
print str(exception) + "\n"
else:
if not appContext.getWriteContext() is None:
appContext.getWriteContext().setAndWriteConfigAfterSuccess()
procMess = ["start time: " + str( startTime),
"end time: " + str(datetime.now()),
"Nebis file(s) processed: " + "##".join(rCollector.getProcessedFile()),
"logged skipped records (if true): " + sConfigs.getSummaryContentFileSkipped(),
"records deleted: " + str(rCollector.getRecordsDeleted()) ,
"records skipped: " + str(rCollector.getRecordsSkipped()) ,
"records parse error: " + str(rCollector.getRecordsparseError()) ,
"records to cbs inserted: " + str(rCollector.getRecordsToCBSInserted()) ,
"records to cbs updated: " + str(rCollector.getRecordsToCBSUpdated()) ,
"records to cbs (without skip mechanism - configuration!): " + str(rCollector.getRecordsToCBSNoSkip()),
"\n"]
if not appContext.getConfiguration() is None:
procMess = SwissbibUtilities.addBlockedMessageToLogSummary(procMess,appContext.getConfiguration())
appContext.getWriteContext().writeLog(header="Import file (push or webdav) summary",message=procMess )
elif not appContext is None and not appContext.getConfiguration() is None:
procMess = ["WriteContext is None - after process finished regularly",
"start time: " + str( startTime),
"end time: " + str(datetime.now()),
"Nebis file(s) processed: " + "##".join(rCollector.getProcessedFile()),
"logged skipped records (if true): " + sConfigs.getSummaryContentFileSkipped(),
"records deleted: " + str(rCollector.getRecordsDeleted()) ,
"records skipped: " + str(rCollector.getRecordsSkipped()) ,
"records parse error: " + str(rCollector.getRecordsparseError()) ,
"records to cbs inserted: " + str(rCollector.getRecordsToCBSInserted()) ,
"records to cbs updated: " + str(rCollector.getRecordsToCBSUpdated()) ,
"records to cbs (without skip mechanism - configuration!): " + str(rCollector.getRecordsToCBSNoSkip()),
"\n"]
if not appContext.getConfiguration() is None:
procMess = SwissbibUtilities.addBlockedMessageToLogSummary(procMess,appContext.getConfiguration())
logfile = open(appContext.getConfiguration().getProcessLogDir() + os.sep + appContext.getConfiguration().getProcessLogFile(),"a")
logfile.write("\n".join(procMess))
logfile.flush()
logfile.close()
else:
procMess = ["WriteContext is None and Configuration is None after process finished regularly",
"going cto use logfile channel directly",
"start time: " + str( startTime),
"end time: " + str(datetime.now()),
"Nebis file(s) processed: " + "##".join(rCollector.getProcessedFile()),
"logged skipped records (if true): " + sConfigs.getSummaryContentFileSkipped(),
"records deleted: " + str(rCollector.getRecordsDeleted()) ,
"records skipped: " + str(rCollector.getRecordsSkipped()) ,
"records parse error: " + str(rCollector.getRecordsparseError()) ,
"records to cbs inserted: " + str(rCollector.getRecordsToCBSInserted()) ,
"records to cbs updated: " + str(rCollector.getRecordsToCBSUpdated()) ,
"records to cbs (without skip mechanism - configuration!): " + str(rCollector.getRecordsToCBSNoSkip()),
"\n"]
print "\n".join(procMess)
#appContext.getWriteContext().writeErrorLog(message= "ResultCollector was None - Why?")
#appContext.getWriteContext().writeLog(message= "ResultCollector was None - Why?")
if not mongoWrapper is None:
mongoWrapper.closeResources()