This repository has been archived by the owner on May 31, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjasper_reports.php
executable file
·284 lines (213 loc) · 7.4 KB
/
jasper_reports.php
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
#!/usr/bin/env php
<?php
/**
* Import jasper reports
*
* @author Rob Caiger <[email protected]>
*/
class Runner
{
private $args;
private $options = array();
private $destination;
private $requiredOptions = array('s', 'd');
private $optionalOptions = array('u', 'p');
private $ignoreFiles = array('.', '..', '.DS_Store');
private $defaultUsername = 'jasperadmin';
private $defaultPassword = 'jasperadmin';
private $colors = array(
'default' => "\e[0m",
'error' => "\e[0;31m",
'success' => "\e[0;32m",
'warning' => "\e[0;33m"
);
const ERROR_MISSING_ARGS = 'Please ensure you have a -s [source] and -d [destination] argument set';
const ERROR_MISSING_SOURCE = 'Unable to find the given source directory';
const ERROR_CANNOT_CREATE_ZIP = 'Unable to create zip';
const ERROR_INVALID_RESPONSE = 'Invalid response returned from Jasper';
const MESSAGE_HELP_TEXT = 'Usage:
jasper_reports -s /path/to/resources/directory -d http://jasper-host-name';
public function __construct($args)
{
$this->args = $args;
$this->checkForHelp();
$this->checkForMissingArgs();
}
public function run()
{
$source = $this->findSource();
$this->setDestination();
$pathToZip = $this->zipSource($source);
$this->importResources($pathToZip);
$this->removeZip($pathToZip);
$this->exitResponse('All done!', 'success');
}
private function getOptions()
{
if (empty($this->options)) {
$this->options = getopt(implode(':', array_merge($this->requiredOptions, $this->optionalOptions)) . ':');
}
return $this->options;
}
private function getDestination()
{
return $this->destination;
}
private function setDestination()
{
$options = $this->getOptions();
$this->destination = rtrim($options['d'], '/') . '/jasperserver/rest_v2';
}
private function checkForHelp()
{
if (in_array('--help', $this->args)) {
$this->exitResponse(self::MESSAGE_HELP_TEXT);
}
}
private function checkForMissingArgs()
{
if ($this->isMissingRequiredOptions()) {
$this->exitResponse(self::ERROR_MISSING_ARGS, 'error');
}
}
private function getUsername()
{
return isset($this->getOptions()['u']) ? $this->getOptions()['u'] : $this->defaultUsername;
}
private function getPassword()
{
return isset($this->getOptions()['p']) ? $this->getOptions()['p'] : $this->defaultPassword;
}
private function importResources($zip)
{
$this->respond('Importing resources into jasper: ' . $this->getDestination());
$response = $this->makeRequest('/import', array('Content-Type: application/zip'), file_get_contents($zip), true);
if (isset($response['phase']) && $response['phase'] == 'inprogress') {
while (isset($response['phase']) && $response['phase'] == 'inprogress') {
sleep(1);
$response = $this->checkProgress($response['id']);
}
}
if (
isset($response['phase'])
&& $response['phase'] == 'finished'
&& $response['message'] == 'Import succeeded.'
) {
$this->respond('Successfully imported', 'success');
} else {
$this->respond('Import failed', 'error');
}
return $response;
}
private function checkProgress($id)
{
$this->respond('Checking progress...', 'warning');
return $this->makeRequest('/export/' . $id . '/state', array());
}
private function makeRequest($destination, $headers, $data = array(), $post = false)
{
$username = $this->getUsername();
$password = $this->getPassword();
$ch = curl_init();
$headers[] = 'Authorization: Basic ' . base64_encode($username . ':' . $password);
$headers[] = 'Accept: application/json';
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_URL, $this->getDestination() . $destination);
curl_setopt($ch, CURLOPT_POST, $post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
curl_close($ch);
$arrayResult = json_decode($result, true);
if (json_last_error() == JSON_ERROR_NONE) {
return $arrayResult;
}
switch (true) {
case strstr($result, 'HTTP Status 401 - Bad credentials'):
$extra = 'Bad credentials';
break;
default:
$extra = $result;
break;
}
$this->exitResponse(self::ERROR_INVALID_RESPONSE . ': ' . $extra, 'error');
}
private function zipSource($source)
{
$this->respond('Zipping resources in ' . $source);
$outputZip = __DIR__ . '/jasper_reports_' . time() . '.zip';
$zipArchive = new ZipArchive();
$zipArchive->open($outputZip, ZipArchive::CREATE);
$this->addFilesToZip($source, $zipArchive);
$zipArchive->close();
if (file_exists($outputZip)) {
$this->respond('Resources successfully zipped!', 'success');
return $outputZip;
}
$this->exitResponse(self::ERROR_CANNOT_CREATE_ZIP, 'error');
}
private function addFilesToZip($source, $zipArchive)
{
$files = $this->getFilesFromSource($source);
foreach ($files as $file) {
if (in_array($file->getFilename(), $this->ignoreFiles)) {
continue;
}
if ($file->isDir()) {
$zipArchive->addEmptyDir(str_replace($source . '/', '', $file . '/'));
} else if ($file->isFile()) {
$zipArchive->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
}
}
}
private function removeZip($zip)
{
$this->respond('Removing zip');
unlink($zip);
if (!file_exists($zip)) {
$this->respond('Zip removed', 'success');
return;
}
$this->respond('Zip was not removed: ' . $zip, 'warning');
}
private function getFilesFromSource($source)
{
return new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($source),
RecursiveIteratorIterator::SELF_FIRST
);
}
private function findSource()
{
$options = $this->getOptions();
if (file_exists(realpath($options['s']))) {
return realpath($options['s']);
}
$this->exitResponse(self::ERROR_MISSING_SOURCE, 'error');
}
private function isMissingRequiredOptions()
{
$options = $this->getOptions();
foreach ($this->requiredOptions as $opt) {
if (!isset($options[$opt]) || empty($options[$opt])) {
return true;
}
}
return false;
}
private function respond($message, $type = 'default')
{
echo $this->colors[$type];
if ($type != 'default') {
echo ucwords($type) . ': ';
}
echo $message . $this->colors['default'] . "\n";
}
private function exitResponse($message, $type = 'default')
{
$this->respond($message, $type);
exit;
}
}
$runner = new Runner($argv);
$runner->run();