forked from agmoyano/node-jasper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
395 lines (362 loc) · 11.5 KB
/
index.js
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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
var java=null,
fs = require('fs'),
path = require('path'),
extend = require('extend'),
util = require('util'),
temp = require('temp'),
async = require('async');
var defaults = {reports:{}, drivers:{}, conns:{}, tmpPath: '/tmp'};
function walk(dir, done) {
var results = [];
fs.readdir(dir, function(err, list) {
if (err) return done(err);
var pending = list.length;
if (!pending) return done(null, results);
list.forEach(function(file) {
file = path.join(dir, file);
fs.stat(file, function(err, stat) {
if (stat && stat.isDirectory()) {
walk(file, function(err, res) {
results = results.concat(res);
if (!--pending) done(null, results);
});
} else {
results.push(file);
if (!--pending) done(null, results);
}
});
});
});
};
/*
* options: {
* path: , //Path to jasperreports-x.x.x-project directory
* tmpPath: '/tmp', // Path to a folder for storing compiled report files
* reports: {
* // Report Definition
* "name": {
* jasper: , //Path to jasper file,
* jrxml: , //Path to jrxml file,
* conn: , //Connection name, definition object or false (if false defaultConn won't apply)
* }
* },
* drivers: {
* // Driver Definition
* "name": {
path: , //Path to jdbc driver jar
class: , //Class name of the driver (what you would tipically place in "Class.forName()" in java)
type: //Type of database (mysql, postgres)
}
* },
* conns: {
* // Connection Definition
* "name": {
* host: , //Database hostname or IP
* port: , //Database Port
* dbname: , //Database Name
* user: , //User Name
* pass: , //User Password
* jdbc: , //jdbc connection string
* driver: //name or definition of the driver for this conn
* }
* },
* defaultConn: , //Default Connection name
java: //Array of java options, for example ["-Djava.awt.headless=true"]
* }
*/
function jasper(options) {
if(options.javaInstance) {
java = options.javaInstance
} else {
java = require('java')
}
this.java = java;
if(options.java) {
if(util.isArray(options.java)) {
options.java.forEach(function(javaOption) {
java.options.push(javaOption);
});
}
if(typeof options.java == 'string') {
java.options.push(options.java);
}
}
var self = this;
self.parentPath = path.dirname(module.parent.filename);
var jrPath = path.resolve(self.parentPath, options.path||'.');
async.auto({
jrJars: function(cb) {
if(fs.statSync(path.join(jrPath, 'lib')).isDirectory() && fs.statSync(path.join(jrPath, 'dist')).isDirectory()) {
async.parallel([
function(cb) {
walk(path.join(jrPath, 'dist'), function(err, results) {
cb(err, results);
});
},
function(cb) {
walk(path.join(jrPath, 'lib'), function(err, results) {
cb(err, results);
});
}
], function(err, results) {
if(err) return cb(err);
var r = results.shift();
results.forEach(function(item) {
r = r.concat(item);
});
cb(null, r);
})
} else {
walk(jrPath, function(err, results) {
cb(err, results);
});
}
},
dirverJars: function(cb) {
var results = [];
if(options.drivers) {
for(var i in options.drivers) {
results.push(path.resolve(self.parentPath, options.drivers[i].path));
}
}
cb(null, results);
},
loadJars: ['jrJars', 'dirverJars', function(cb, jars) {
jars.jrJars.concat(jars.dirverJars).forEach(function(file) {
if(path.extname(file) == '.jar') {
java.classpath.push(file)
}
});
cb();
}],
debug: ['loadJars', function(cb) {
if(!options.debug) options.debug = 'off';
var levels = ['ALL', 'TRACE', 'DEBUG', 'INFO', 'WARN', 'ERROR', 'FATAL', 'OFF'];
if(levels.indexOf((options.debug+'').toUpperCase()) == -1) options.debug = 'DEBUG';
var appender = java.newInstanceSync('org.apache.log4j.ConsoleAppender');
var pattern = java.newInstanceSync('org.apache.log4j.PatternLayout', "%d [%p|%c|%C{1}] %m%n");
appender.setLayout(pattern);
appender.setThreshold(java.getStaticFieldValue("org.apache.log4j.Level", (options.debug+'').toUpperCase()));
appender.activateOptions();
var root = java.callStaticMethodSync("org.apache.log4j.Logger", "getRootLogger");
root.addAppender(appender);
cb();
}],
loadClass: ['loadJars', function(cb) {
var cl = java.callStaticMethodSync("java.lang.ClassLoader","getSystemClassLoader")
for(var i in options.drivers) {
cl.loadClassSync(options.drivers[i].class).newInstanceSync();
}
cb();
}],
imports: ['loadClass', function(cb) {
self.dm = java.import('java.sql.DriverManager');
self.jreds = java.import('net.sf.jasperreports.engine.JREmptyDataSource');
self.jrjsonef = java.import('net.sf.jasperreports.engine.data.JsonDataSource');
self.jbais = java.import('java.io.ByteArrayInputStream');
self.jcm = java.import('net.sf.jasperreports.engine.JasperCompileManager');
self.hm = java.import('java.util.HashMap');
self.jfm = java.import('net.sf.jasperreports.engine.JasperFillManager');
self.jem = java.import('net.sf.jasperreports.engine.JasperExportManager');
self.loc = java.import('java.util.Locale');
cb();
}]
}, function() {
if(self.ready) {
self.ready();
}
});
delete options.path;
extend(self, defaults, options);
}
jasper.prototype.ready = function(f) {
var self = this;
self.ready = f;
};
/*
* name = Report Name
* def = Report Definition
*/
jasper.prototype.add = function(name, def) {
this.reports[name] = def;
}
jasper.prototype.pdf = function(report) {
return this.export(report, 'pdf');
}
/*
* report can be of any of the following types:
* _ A string that represents report's name. No data is supplied.. defaultConn will be applied to get data with reports internal query.
* _ An object that represents report's definition. No data is supplied.. defaultConn will be applied to get data with reports internal query.
* _ An object that represents reports, data and properties to override for this specific method call.
*
* {
* report: , //name, definition or an array with any combination of both
* data: {}, //Data to be applied to the report. If there is an array of reports, data will be applied to each.
* override: {} //properties of report to override for this specific method call.
* }
* _ An array with any combination of the three posibilities described before.
* _ A function returning any combination of the four posibilities described before.
*/
var validConnections = {};
jasper.prototype.export = function(report, type, callback) {
var self = this;
if(!type) return;
type = type.charAt(0).toUpperCase()+type.toLowerCase().slice(1);
var processReport = function(report) {
if(typeof report == 'string') {
return [extend({},self.reports[report])];
} else if(util.isArray(report)) {
var ret = [];
report.forEach(function(i) {
ret = ret.concat(processReport(i));
});
return ret;
} else if(typeof report == 'function') {
return processReport(report());
} else if(typeof report == 'object') {
if(report.data||report.override) {
var reps = processReport(report.report);
return reps.map(function(i) {
if(report.override) {
extend(i, report.override);
}
i.data = report.data;
i.dataset = report.dataset;
return i;
})
} else {
return [report];
}
}
};
var processConn = function(conn, item) {
if(conn == 'in_memory_json') {
var jsonString = JSON.stringify(item.dataset);
var byteArray = java.newArray('byte', jsonString.split('').map(function(c, i) {
return java.newByte(jsonString.charCodeAt(i));
}));
return new self.jrjsonef(new self.jbais(byteArray));
}else if(typeof conn == 'string') {
conn = self.conns[conn];
} else if (typeof conn == 'function') {
conn = conn();
} else if(conn !== false && self.defaultConn) {
conn = self.conns[self.defaultConn];
}
if(conn) {
if(typeof conn.driver == 'string') {
conn.driver = self.drivers[conn.driver];
}
var connStr = conn.jdbc?conn.jdbc:'jdbc:'+conn.driver.type+'://'+conn.host+':'+conn.port+'/'+conn.dbname;
if(!validConnections[connStr] || !validConnections[connStr].isValidSync(conn.validationTimeout || 1)){
validConnections[connStr] = self.dm.getConnectionSync(connStr, conn.user, conn.pass);
}
return validConnections[connStr];
} else {
return new self.jreds();
}
};
var parseLocale = function (localeString) {
var tokens = localeString.split(/[_|-]/);
if (tokens.length > 1) {
return self.loc(tokens[0], tokens[1]);
}
else {
return self.loc(tokens[0]);
}
}
var reports = processReport(report);
var prints = [];
reports.forEach(function(item) {
if(!item.jasper && item.jrxml) {
item.jasper = self.compileSync(item.jrxml, self.tmpPath);
}
if(item.jasper) {
var data = null;
if(item.data) {
data = new self.hm();
for(var j in item.data) {
if (j === 'REPORT_LOCALE') {
item.data[j] = parseLocale(item.data[j]);
}
data.putSync(j, item.data[j])
}
}
var conn = processConn(item.conn, item);
var pathToRpt = path.resolve(self.parentPath,item.jasper);
console.log(new Date(), `Filling report ${pathToRpt} with data ${data}`);
if(callback){
self.jfm.fillReport(pathToRpt, data, conn, function(err,master) {
if(err){
console.log('ERROR in fillReport: err ->', err, 'result ->', master);
callback(null, err);
}else if(!master){
console.log('ERROR in fillReport: no result ->', master);
callback(null, null);
}else{
var tempName = temp.path({suffix: '.pdf'});
self.jem['exportReportTo'+type+'FileSync'](master, tempName);
var exp = fs.readFileSync(tempName);
fs.unlinkSync(tempName);
callback(exp);
}
});
}else{
var p = self.jfm.fillReportSync(pathToRpt, data, conn);
prints.push(p);
}
}
});
if(prints.length) {
var master = prints.shift();
prints.forEach(function(p) {
var s = p.getPagesSync().sizeSync();
for(var j = 0; j < s; j++) {
master.addPageSync(p.getPagesSync().getSync(j));
}
});
var tempName = temp.path({suffix: '.pdf'});
self.jem['exportReportTo'+type+'FileSync'](master, tempName);
var exp = fs.readFileSync(tempName);
fs.unlinkSync(tempName);
return exp;
}
return '';
}
/*
* compiles all reports added to the reports definition collection with a jrxml file specified
*
* dstFolder = destination folder path where the compiled report files will be placed. If not specified, will use the options tmpPath or the defaults tmpPath value.
*
*/
jasper.prototype.compileAllSync = function (dstFolder) {
var self = this;
for (var name in self.reports) {
var report = self.reports[name];
if (report.jrxml) {
report.jasper = self.compileSync(report.jrxml, dstFolder || self.tmpPath);
}
}
}
/*
* compiles a jrxml report file to a jasper file with the same name
*
* dstFolder = destination folder path where the compiled report files will be placed. If not specified, will use the options tmpPath or the defaults tmpPath value.
*
* returns the full path of the created jasper file
*
*/
jasper.prototype.compileSync = function (jrxmlFile, dstFolder) {
var self = this;
var name = path.basename(jrxmlFile, '.jrxml');
var file = path.join(dstFolder || self.tmpPath, name + '.jasper');
java.callStaticMethodSync(
"net.sf.jasperreports.engine.JasperCompileManager",
"compileReportToFile",
path.resolve(self.parentPath, jrxmlFile), file
);
return file;
};
module.exports = function(options) {
return new jasper(options)
};