/
LoadableFileBatchJob.java
201 lines (182 loc) · 7.5 KB
/
LoadableFileBatchJob.java
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
/*
* #%L
* Netarchivesuite - common
* %%
* Copyright (C) 2005 - 2018 The Royal Danish Library,
* the National Library of France and the Austrian National Library.
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
package dk.netarkivet.common.utils.batch;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import dk.netarkivet.common.exceptions.ArgumentNotValid;
import dk.netarkivet.common.exceptions.IOFailure;
import dk.netarkivet.common.utils.FileUtils;
/**
* This implementation of FileBatchJob is a bridge to a class file given as a File object. The given class will be
* loaded and used to perform the actions of the FileBatchJob class.
*/
@SuppressWarnings({"unchecked", "rawtypes", "serial"})
public class LoadableFileBatchJob extends FileBatchJob {
/** The class logger. */
private static final transient Logger log = LoggerFactory.getLogger(LoadableFileBatchJob.class);
/** The job loaded from file. */
transient FileBatchJob loadedJob;
/** The binary contents of the file before they are turned into a class. */
byte[] fileContents;
/** The name of the file before they are turned into a class. */
String fileName;
/** The arguments for instantiating the batchjob. */
private List<String> args;
/**
* Create a new batch job that runs the loaded class.
*
* @param classFile the classfile for the batch job we want to run.
* @param arguments The arguments for the batchjobs. This can be null.
* @throws ArgumentNotValid If the classfile is null.
*/
public LoadableFileBatchJob(File classFile, List<String> arguments) throws ArgumentNotValid {
ArgumentNotValid.checkNotNull(classFile, "File classFile");
fileContents = FileUtils.readBinaryFile(classFile);
fileName = classFile.getName();
if (arguments == null) {
this.args = new ArrayList<String>();
} else {
this.args = arguments;
}
loadBatchJob();
}
/**
* Override of the default toString to include name of loaded class.
*
* @return string representation of this class.
*/
public String toString() {
return this.getClass().getName() + " processing " + fileName;
}
/**
* Override of the default way to serialize this class.
*
* @param out Stream that the object will be written to.
* @throws IOException In case there is an error from the underlying stream, or this object cannot be serialized.
*/
private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
}
/**
* Override of the default way to unserialize an object of this class.
*
* @param in Stream that the object can be read from.
* @throws IOException If there is an error reading from the stream, or the serialized object cannot be deserialized
* due to errors in the serialized form.
* @throws ClassNotFoundException If the class definition of the serialized object cannot be found.
*/
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
}
/**
* Initialize the job before runnning. This is called before the processFile() calls.
*
* @param os the OutputStream to which output should be written
*/
public void initialize(OutputStream os) {
ArgumentNotValid.checkNotNull(os, "OutputStream os");
loadBatchJob();
loadedJob.initialize(os);
}
/**
* Method for initializing the loaded batchjob.
*
* @throws IOFailure If the batchjob cannot be loaded.
*/
protected void loadBatchJob() throws IOFailure {
ByteClassLoader singleClassLoader = new ByteClassLoader(fileContents);
try {
Class batchClass = singleClassLoader.defineClass();
if (args.size() == 0) {
loadedJob = (FileBatchJob) batchClass.newInstance();
} else {
// get argument classes (string only).
Class[] argClasses = new Class[args.size()];
for (int i = 0; i < args.size(); i++) {
argClasses[i] = String.class;
}
// extract the constructor and instantiate the batchjob.
Constructor con = batchClass.getConstructor(argClasses);
loadedJob = (FileBatchJob) con.newInstance(args.toArray());
log.debug("Loaded batchjob with arguments: '{}'.", args);
}
} catch (InvocationTargetException e) {
final String msg = "Not allowed to invoke the batchjob '" + fileName + "'.";
log.warn(msg, e);
throw new IOFailure(msg, e);
} catch (NoSuchMethodException e) {
final String msg = "No constructor for the arguments '" + args + "' can be found for the batchjob '"
+ fileName + "'.";
log.warn(msg, e);
throw new IOFailure(msg, e);
} catch (InstantiationException e) {
String errMsg = "Cannot instantiate batchjob from byte array";
log.warn(errMsg, e);
throw new IOFailure(errMsg, e);
} catch (IllegalAccessException e) {
String errMsg = "Cannot access loaded job from byte array";
log.warn(errMsg, e);
throw new IOFailure(errMsg, e);
}
}
/**
* Process one file stored in the bit archive.
*
* @param file the file to be processed.
* @param os the OutputStream to which output should be written
* @return true if the file was successfully processed, false otherwise
*/
public boolean processFile(File file, OutputStream os) {
log.trace("Started processing of file '{}'.", file.getAbsolutePath());
ArgumentNotValid.checkNotNull(file, "File file");
ArgumentNotValid.checkNotNull(os, "OutputStream os");
return loadedJob.processFile(file, os);
}
/**
* Finish up the job. This is called after the last process() call.
*
* @param os the OutputStream to which output should be written
*/
public void finish(OutputStream os) {
ArgumentNotValid.checkNotNull(os, "OutputStream os");
loadedJob.finish(os);
}
@Override
public boolean postProcess(InputStream input, OutputStream output) {
ArgumentNotValid.checkNotNull(input, "InputStream input");
ArgumentNotValid.checkNotNull(output, "OutputStream output");
// Let the loaded job handle the post processing.
loadBatchJob();
return loadedJob.postProcess(input, output);
}
}