Skip to main content
summaryrefslogtreecommitdiffstats
blob: c43f387663133b303badaedb0b5721f66cb4fd9f (plain) (blame)
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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
/**
 *                                                                            
 *  Copyright (c) 2011, 2016 - Loetz GmbH&Co.KG (69115 Heidelberg, Germany) 
 *                                                                            
 *  All rights reserved. This program and the accompanying materials           
 *  are made available under the terms of the Eclipse Public License 2.0        
 *  which accompanies this distribution, and is available at                  
 *  https://www.eclipse.org/legal/epl-2.0/                                 
 *                                 
 *  SPDX-License-Identifier: EPL-2.0                                 
 *                                                                            
 *  Contributors:                                                      
 * 	   Christophe Loetz (Loetz GmbH&Co.KG) - initial implementation
 * 
 */
package org.eclipse.osbp.xtext.datainterchange.common;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Locale;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IPath;
import org.eclipse.osbp.core.api.persistence.IPersistenceService;
import org.eclipse.osbp.datainterchange.api.IDataInterchangeExecutionEvent;
import org.eclipse.osbp.datainterchange.api.IDataInterchangeExecutionEventListener;
import org.eclipse.osbp.runtime.common.event.IEventDispatcher;
import org.eclipse.osbp.ui.api.customfields.IBlobService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.ProgressBar;
import com.vaadin.ui.UI;

public abstract class WorkerThreadRunnable implements Runnable, IDataInterchangeExecutionEventListener {

	static final Logger log = LoggerFactory.getLogger("dataInterchange");
	private String name = null;
	private String status = null;
	private IEventDispatcher eventDispatcher;
	private ProgressBar progressBar;
	private HorizontalLayout progressBarArea;
	private IPersistenceService persistenceService;
	private long counter = 0;
	private long length = 0;
	private long avgElementSize = 0;
	private float previousValue = 0.0f;
	private UI ui = null;
	private URL fileURL;
	private SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddhhmmssa", Locale.US);

	public enum Direction {
		IMPORT, EXPORT
	}

	private Direction direction = Direction.IMPORT;
	private IBlobService blobService;

	private boolean deleteFileAfterImport = false;
	private boolean failedExecution = false;
	private boolean executionDone = false;
	private boolean actionFilterExecutionNeeded = false; 
	private float progress;

	private final String ERROR_MESSAGE = "The directory you've chosen does not exist or is not accessible. Please adapt the url.";

	private HashMap<String, Parameter> filterParameters;

	public WorkerThreadRunnable() {
		progressBarArea = new HorizontalLayout();
		progressBar = new ProgressBar();
		progressBarArea.addComponent(progressBar);
	}

	public void setLength(long length) {
		this.length = length;
	}

	public void setAvgElementSize(long avgElementSize) {
		this.avgElementSize = avgElementSize;
	}

	public void setProgressBarStyleName(String styleName) {
		progressBar.addStyleName(styleName);
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
		progressBar.setDescription(name);
	}

	public String getStatus() {
		return status;
	}

	public void setStatus(String status) {
		this.status = status;
	}

	public IEventDispatcher getEventDispatcher() {
		return eventDispatcher;
	}

	public void setEventDispatcher(IEventDispatcher eventDispatcher) {
		this.eventDispatcher = eventDispatcher;
	}

	public void setBlobService(IBlobService blobService) {
		this.blobService = blobService;
	}

	public IBlobService getBlobService() {
		return blobService;
	}

	public IPersistenceService getPersistenceService() {
		return persistenceService;
	}

	public void setPersistenceService(IPersistenceService persistenceService) {
		this.persistenceService = persistenceService;
	}

	public ProgressBar getProgressBar() {
		return progressBar;
	}

	public HorizontalLayout getProgressBarArea() {
		return progressBarArea;
	}

	public Direction getDirection() {
		return direction;
	}

	public void setDirection(Direction direction) {
		this.direction = direction;
	}

	public UI getUi() {
		return ui;
	}

	public void setUi(UI ui) {
		this.ui = ui;
	}

	public void setProgressBarEnabled(final boolean enable) {
		if (ui != null) {
			ui.access(() -> progressBar.setEnabled(enable));
		}
	}

	public void setProgressIndeterminated(final boolean indeterminate) {
		if (ui != null) {
			ui.access(() -> progressBar.setIndeterminate(indeterminate));
		}
	}

	@Override
	public void onEvent(IDataInterchangeExecutionEvent event) {
		if (ui != null) {
			switch (event.getType()) {
			case STARTED:
				ui.access(() -> {
					progressBar.setValue(0.0f);
					progressBar.setEnabled(false);
				});
				break;
			case FINISHED:
				ui.access(() -> {
					progressBar.setValue(1.0f);
					progressBar.setIndeterminate(true);
				});
				break;
			case ELEMENT:
				counter++;
				if (length != 0) {
					progress = ((float) counter * avgElementSize) / length;
					if (Math.abs(progress - previousValue) > 0.01) {
						ui.access(() -> {
							log.debug("progress {}", progress);
							progressBar.setValue(progress);
							previousValue = progress;
						});
					}
				}
				break;
			}
		}
	}

	/**
	 * Sets the {@link #fileURL}.
	 * 
	 * @param filepath
	 *            the file URl
	 */
	public void setFileURL(String filepath) {
		fileURL = null;
		try {
			fileURL = new URL(filepath);
		} catch (MalformedURLException e1) {
			if (e1.getMessage().startsWith("unknown protocol") || e1.getMessage().startsWith("no protocol")) {
				try {
					fileURL = Paths.get(filepath).toUri().toURL();
				} catch (MalformedURLException e2) {
					StringWriter sw = new StringWriter();
					e2.printStackTrace(new PrintWriter(sw));
					log.error("{}", sw);
				}
			}
		}
		// fileURL = produceAppropiateInterchangeURL(filepath);
	}

	/**
	 * Gives the {@link #fileURL}.
	 * 
	 * @return {@link URL} the file url
	 */
	public URL getFileURL() {
		return this.fileURL;
	}

	/**
	 * Checks whether the import file has to be deleted at the end of the
	 * process.
	 * 
	 * @return true if yes, false if not
	 */
	public boolean isDeleteFileAfterImport() {
		return deleteFileAfterImport;
	}

	/**
	 * Sets whether the import file has to be deleted at the end of the process.
	 * 
	 * @param deleteFileAfterImport
	 */
	public void setDeleteFileAfterImport(boolean deleteFileAfterImport) {
		this.deleteFileAfterImport = deleteFileAfterImport;
	}

	/**
	 * Make sure that the given file is deleted.
	 * 
	 * @param file
	 *            the file to rename
	 * @param logidinfo
	 *            log information from the caller.
	 */
	public void deleteFile(final Path file, String logidinfo) {
		try {
			if (Files.deleteIfExists(file)) {
				log.info("{} [{}] successfuly removed.", logidinfo, file);
			} else {
				log.info("{} [{}] doesn't exist and could not be removed.", logidinfo, file);
			}
		} catch (IOException e) {
			log.error("{} [{}] could not be deleted.\n{}", logidinfo, file, e.getMessage());
		}
	}

	/**
	 * Renames the given file with the given new name. If a file with the given
	 * new name already exists then a number offset will be added to it.
	 * 
	 * @param file
	 *            the file to rename
	 * @param newname
	 *            the new file name
	 */
	public void renameFile(final Path file, String newname) {
		try {
			if (Files.exists(file)) {
				String filename = file.getFileName().toString();
				if (newname == null || newname.isEmpty()) {
					log.info("file [{}] has not been renamed!", filename);
				} else {
					int renameTry = 0;
					boolean done = false;
					String tempname = newname;
					String extension = newname.substring(newname.length() - 4);
					do {
						try {
							Files.move(file, file.resolveSibling(tempname));
							done = true;
						} catch (FileAlreadyExistsException ae) {
							renameTry++;
							tempname = newname.replace(extension, renameTry + extension);
						}
					} while (!done);
					log.info("file [{}] renamed to {}.", filename, tempname);
				}
			} else {
				log.info("file [{}] doesn't exist and could not be renamed.", file);
			}
		} catch (IOException e) {
			log.error("file [{}] could not be renamed.\n{}", file, e.getMessage());
		}
	}

	/**
	 * Checks whether the import or export execution is done.
	 * 
	 * @return true if yes, false if not
	 */
	public boolean isExecutionDone() {
		return executionDone;
	}

	/**
	 * Sets whether the import or export execution is done.
	 * 
	 * @param executionDone
	 *            the execution state
	 */
	public void setExecutionDone(boolean executionDone) {
		this.executionDone = executionDone;
	}

	/**
	 * Checks whether the import or export execution has failed.
	 * 
	 * @return true if yes, false if not
	 */
	public boolean hasExecutionFailed() {
		return failedExecution;
	}

	/**
	 * Sets whether the import or export execution has failed.
	 * 
	 * @param failedExecution
	 *            the new state
	 */
	public void setExecutionFailed(boolean failedExecution) {
		this.failedExecution = failedExecution;
	}

	/**
	 * Gives the {@link #formatter}.
	 * 
	 * @return {@link SimpleDateFormat}
	 */
	public SimpleDateFormat getFormatter() {
		return formatter;
	}

	/**
	 * Generates the right directory url depending on whether the given file
	 * path is relative or absolute.
	 * 
	 * @return the URL
	 */
	public URL produceAppropiateInterchangeURL(String filepath) {
		URL url = null;
		String filename = null;
		String directory = null;

		if (filepath != null && !filepath.isEmpty()) {

			int index = filepath.lastIndexOf("/");
			if (index != -1) {
				directory = filepath.substring(0, index + 1);
				filename = filepath.substring(index + 1, filepath.length());
			} else {
				index = filepath.lastIndexOf("\\");
				if (index != -1) {
					directory = filepath.substring(0, index + 1);
					filename = filepath.substring(index + 1, filepath.length());
				}
			}
			// TODO for relative path check if directory is valid
			// check most needed for configuration file entries
			if (directory != null && !directory.isEmpty() && filename != null && !filename.isEmpty()) {
				try {
					url = new URL(filepath);
					if (url.getProtocol().equals("file")) {
						// do nothing for now
					}
				} catch (InvalidPathException | MalformedURLException e1) {
					if (e1.getMessage().startsWith("unknown protocol") || e1.getMessage().startsWith("no protocol")) {
						try {
							if (!Paths.get(filepath).isAbsolute()) { // check
																		// for
																		// relative
																		// path
								IPath folderlocation = null;
								// check if WITHIN all projects a directory
								// exists corresponding to the relative path
								for (IProject prj : ResourcesPlugin.getWorkspace().getRoot().getProjects()) {
									IPath templocation = prj.getFolder(directory).getLocation();
									Path folder = Paths.get(templocation.toString());
									if (folder != null && folder.toFile() != null) {
										// find the first folder
										folderlocation = templocation;
										break;
									}
									// else 1. in the base projects for ../..
									// else 2. outside the base project
								}

								File file = Paths.get(folderlocation.append(filename).toOSString()).toFile();
								if (file != null && file.exists() && file.isDirectory()) {
									url = Paths.get(folderlocation.append(filename).toString()).toUri().toURL();
								} else {
									// TODO to be cleared with Joerg, if fale
									// safe is needed
									// if the folder doesn't exist then use the
									// base directory as main location for all
									// interchanges
									// url =
									// Paths.get(ResourcesPlugin.getWorkspace().getRoot().getProjectRelativePath().append(filename).toString()).toUri().toURL();
									throw new InvalidPathException(ERROR_MESSAGE, filepath);
								}
							} else { // for absolute paths that were malformed
										// or else
								url = Paths.get(filepath).toUri().toURL();
							}
						} catch (InvalidPathException | MalformedURLException e2) {
							StringWriter sw = new StringWriter();
							e2.printStackTrace(new PrintWriter(sw));
							log.error("{}", sw);
						}
					}
				}
			}
		}
		// if the path is absolute or from another protocol like http, ftp ...
		// just return
		return url;
	}

	/**
	 * Returns the path of the given file name or directory name.
	 */
	public IPath findProjectFileOrFolderLocation(String projectname, String fname, boolean isFile) {
		if (projectname != null && !projectname.isEmpty() && fname != null && !fname.isEmpty()) {
			IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectname);
			if (isFile) {
				return project.getFile(fname).getLocation();
			}
			return project.getFolder(fname).getLocation();
		}
		return null;
	}

	public void setFilter(HashMap<String, Parameter> param) {
		this.filterParameters = param;
	}

	public HashMap<String, Parameter> getFilter() {
		return this.filterParameters;
	}

	public boolean hasFilter() {
		return (this.filterParameters != null && !this.filterParameters.isEmpty());
	}
	
	public boolean isActionFilterExecutionNeeded() {
		return actionFilterExecutionNeeded;
	}

	public void setActionFilterExecutionNeeded(boolean actionFilterExecutionNeeded) {
		this.actionFilterExecutionNeeded = actionFilterExecutionNeeded;
	}

	static public class Parameter {
		private String name;
		private Object value;

		public Parameter(String name, Object value) {
			super();
			this.name = name;
			this.value = value;
		}
		
		public String getName() {
			return name;
		}
		
		public String getValue() {
			String result = "";
			if(value != null){
				log.debug("VALUE TYPE is ", value.getClass().getSimpleName());
				result = value.getClass().cast(value).toString();
			}
			return result;
		}
		
		/**
		 * Returns the raw saved object
		 * @return Object the saved object value
		 */
		public Object getRawValue(){
			return value;
		}
	}
}

Back to the top