-
Notifications
You must be signed in to change notification settings - Fork 219
/
Process.java
1853 lines (1635 loc) · 59.5 KB
/
Process.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
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
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Copyright (C) 2001-2018 by RapidMiner and the contributors
*
* Complete list of developers available at our web site:
*
* http://rapidminer.com
*
* This program is free software: you can redistribute it and/or modify it under the terms of the
* GNU Affero General Public License as published by the Free Software Foundation, either version 3
* 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
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program.
* If not, see http://www.gnu.org/licenses/.
*/
package com.rapidminer;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.charset.IllegalCharsetNameException;
import java.nio.charset.UnsupportedCharsetException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
import javax.swing.event.EventListenerList;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import com.rapidminer.core.license.LicenseViolationException;
import com.rapidminer.core.license.ProductConstraintManager;
import com.rapidminer.datatable.DataTable;
import com.rapidminer.datatable.SimpleDataTable;
import com.rapidminer.example.table.AttributeFactory;
import com.rapidminer.gui.tools.ProgressThread;
import com.rapidminer.gui.tools.ProgressThreadStoppedException;
import com.rapidminer.io.process.XMLImporter;
import com.rapidminer.io.process.XMLTools;
import com.rapidminer.license.violation.LicenseViolation;
import com.rapidminer.operator.Annotations;
import com.rapidminer.operator.DebugMode;
import com.rapidminer.operator.DummyOperator;
import com.rapidminer.operator.ExecutionMode;
import com.rapidminer.operator.ExecutionUnit;
import com.rapidminer.operator.IOContainer;
import com.rapidminer.operator.IOObject;
import com.rapidminer.operator.IOObjectMap;
import com.rapidminer.operator.Operator;
import com.rapidminer.operator.OperatorException;
import com.rapidminer.operator.PortUserError;
import com.rapidminer.operator.ProcessRootOperator;
import com.rapidminer.operator.ProcessStoppedException;
import com.rapidminer.operator.UnknownParameterInformation;
import com.rapidminer.operator.UserError;
import com.rapidminer.operator.execution.FlowData;
import com.rapidminer.operator.execution.ProcessFlowFilter;
import com.rapidminer.operator.nio.file.RepositoryBlobObject;
import com.rapidminer.operator.ports.InputPort;
import com.rapidminer.operator.ports.OutputPort;
import com.rapidminer.operator.ports.Port;
import com.rapidminer.parameter.UndefinedParameterError;
import com.rapidminer.report.ReportStream;
import com.rapidminer.repository.BlobEntry;
import com.rapidminer.repository.Entry;
import com.rapidminer.repository.IOObjectEntry;
import com.rapidminer.repository.MalformedRepositoryLocationException;
import com.rapidminer.repository.RepositoryAccessor;
import com.rapidminer.repository.RepositoryException;
import com.rapidminer.repository.RepositoryLocation;
import com.rapidminer.repository.RepositoryManager;
import com.rapidminer.studio.internal.ProcessFlowFilterRegistry;
import com.rapidminer.tools.AbstractObservable;
import com.rapidminer.tools.LogService;
import com.rapidminer.tools.LoggingHandler;
import com.rapidminer.tools.Observable;
import com.rapidminer.tools.Observer;
import com.rapidminer.tools.OperatorService;
import com.rapidminer.tools.ParameterService;
import com.rapidminer.tools.ProgressListener;
import com.rapidminer.tools.RandomGenerator;
import com.rapidminer.tools.ResultService;
import com.rapidminer.tools.Tools;
import com.rapidminer.tools.WebServiceTools;
import com.rapidminer.tools.WrapperLoggingHandler;
import com.rapidminer.tools.XMLException;
import com.rapidminer.tools.XMLParserException;
import com.rapidminer.tools.container.Pair;
import com.rapidminer.tools.usagestats.ActionStatisticsCollector;
/**
* <p>
* This class was introduced to avoid confusing handling of operator maps and other stuff when a new
* process definition is created. It is also necessary for file name resolving and breakpoint
* handling.
* </p>
*
* <p>
* If you want to use RapidMiner from your own application the best way is often to create a process
* definition from scratch (by adding the complete operator tree to the process' root operator) or
* from a file (for example created with the GUI beforehand) and start it by invoking the
* {@link #run()} method.
* </p>
*
* <p>
* Observers can listen to changes of the associated file, repository location, and context.
* </p>
* TODO: Add reasonable class comment
*
* @author Ingo Mierswa
*/
public class Process extends AbstractObservable<Process> implements Cloneable {
public static final int PROCESS_STATE_UNKNOWN = -1;
public static final int PROCESS_STATE_STOPPED = 0;
public static final int PROCESS_STATE_PAUSED = 1;
public static final int PROCESS_STATE_RUNNING = 2;
/** The root operator of the process. */
private ProcessRootOperator rootOperator = null;
/** This is the operator which is currently applied. */
private Operator currentOperator;
/**
* The process might be connected to this file or repository location which is then used to
* resolve relative file names which might be defined as parameters.
*/
private ProcessLocation processLocation;
/**
* Indicates if the original process file has been changed by import rules. If this happens,
* overwriting will destroy the backward compatibility. This flag indicates that this would
* happen during saving.
*/
private boolean isProcessConverted = false;
/**
* Indicates how deeply nested the current process is. The original process itself has a depth
* of {@code 0}. If that process spawns a new one via an Execute Process operator, the depth of
* the new one will be {@code 1}. If the new process also contains an Execute Process operator,
* the depth will be {@code 2} and so on. Used to prevent {@link StackOverflowError} when
* recursion is too deep (mostly to prevent accidents).
*/
private int nestingDepth = 0;
/**
* This list contains all unknown parameter information which existed during the loading of the
* process.
*/
private final List<UnknownParameterInformation> unknownParameterInformation = new LinkedList<>();
/** The listeners for breakpoints. */
private final List<BreakpointListener> breakpointListeners = Collections.synchronizedList(new LinkedList<>());
/** The list of filters called between each operator */
private final CopyOnWriteArrayList<ProcessFlowFilter> processFlowFilters = new CopyOnWriteArrayList<>();
/** The listeners for logging (data tables). */
private final List<LoggingListener> loggingListeners = Collections.synchronizedList(new LinkedList<>());
private final List<ProcessStateListener> processStateListeners = Collections.synchronizedList(new LinkedList<>());
/** The macro handler can be used to replace (user defined) macro strings. */
private final MacroHandler macroHandler = new MacroHandler(this);
/**
* This map holds the names of all operators in the process. Operators are automatically
* registered during adding and unregistered after removal.
*/
private Map<String, Operator> operatorNameMap = new HashMap<>();
/**
* Maps names of ProcessLog operators to Objects, that these Operators use for collecting
* statistics (objects of type {@link DataTable}).
*/
private final Map<String, DataTable> dataTableMap = new HashMap<>();
/**
* Maps names of report streams to reportStream objects
*/
private final Map<String, ReportStream> reportStreamMap = new HashMap<>();
/**
* Stores IOObjects according to a specified name for the runtime of the process.
*/
private final Map<String, IOObject> storageMap = new HashMap<>();
/**
* Stores IOObjects according to a specified name for a long-term scope like the session of
* RapidMiner or a RapidMiner Server app session
*/
private IOObjectMap ioObjectCache = RapidMiner.getGlobalIOObjectCache();
/** Indicates the current process state. */
private int processState = PROCESS_STATE_STOPPED;
/** Indicates whether operators should be executed always or only when dirty. */
private transient ExecutionMode executionMode = ExecutionMode.ALWAYS;
/** Indicates whether we are updating meta data. */
private transient DebugMode debugMode = DebugMode.DEBUG_OFF;
private transient final Logger logger = makeLogger();
/** @deprecated Use {@link #getLogger()} */
@Deprecated
private transient final LoggingHandler logService = new WrapperLoggingHandler(logger);
private ProcessContext context = new ProcessContext();
/** Message generated during import by {@link XMLImporter}. */
private String importMessage;
private final Annotations annotations = new Annotations();
private RepositoryAccessor repositoryAccessor;
/**
* Indicates whether the {@link IOContainer} returned by {@link #run()} might contain
* <code>null</code> values for empty results.
*/
private boolean omitNullResults = true;
// -------------------
// Constructors
// -------------------
/** Constructs an process consisting only of a SimpleOperatorChain. */
public Process() {
try {
ProcessRootOperator root = OperatorService.createOperator(ProcessRootOperator.class);
root.rename(root.getOperatorDescription().getName());
setRootOperator(root);
} catch (Exception e) {
throw new RuntimeException("Cannot initialize root operator of the process: " + e.getMessage(), e);
}
initContext();
}
public Process(final File file) throws IOException, XMLException {
this(file, null);
}
/**
* Creates a new process from the given process file. This might have been created with the GUI
* beforehand.
*/
public Process(final File file, final ProgressListener progressListener) throws IOException, XMLException {
this.processLocation = new FileProcessLocation(file);
initContext();
try (FileInputStream fis = new FileInputStream(file); Reader in = new InputStreamReader(fis, "UTF-8")) {
readProcess(in, progressListener);
}
}
/**
* Creates a new process from the given XML copying state information not covered by the XML
* from the parameter process.
*/
public Process(final String xml, final Process process) throws IOException, XMLException {
this(xml);
this.processLocation = process.processLocation;
}
/** Reads an process configuration from an XML String. */
public Process(final String xmlString) throws IOException, XMLException {
initContext();
StringReader in = new StringReader(xmlString);
readProcess(in);
in.close();
}
/** Reads an process configuration from the given reader. */
public Process(final Reader in) throws IOException, XMLException {
initContext();
readProcess(in);
}
/** Reads an process configuration from the given stream. */
public Process(final InputStream in) throws IOException, XMLException {
initContext();
readProcess(new InputStreamReader(in, XMLImporter.PROCESS_FILE_CHARSET));
}
/** Reads an process configuration from the given URL. */
public Process(final URL url) throws IOException, XMLException {
initContext();
try (Reader in = new InputStreamReader(WebServiceTools.openStreamFromURL(url), getEncoding(null))) {
readProcess(in);
}
}
protected Logger makeLogger() {
return Logger.getLogger(Process.class.getName());
}
private void initContext() {
getContext().addObserver(delegatingContextObserver, false);
}
/**
* Clone constructor. Makes a deep clone of the operator tree and the process file. The same
* applies for the operatorNameMap. The breakpoint listeners are copied by reference and all
* other fields are initialized like for a fresh process.
*/
private Process(final Process other) {
this();
setRootOperator((ProcessRootOperator) other.rootOperator.cloneOperator(other.rootOperator.getName(), false));
this.currentOperator = null;
if (other.processLocation != null) {
this.processLocation = other.processLocation;
} else {
this.processLocation = null;
}
}
private void initLogging(final int logVerbosity) {
if (logVerbosity >= 0) {
logger.setLevel(WrapperLoggingHandler.LEVELS[logVerbosity]);
} else {
logger.setLevel(Level.INFO);
}
}
@Override
public Object clone() {
return new Process(this);
}
/**
* @deprecated Use {@link #setProcessState(int)} instead
*/
@Deprecated
public synchronized void setExperimentState(final int state) {
setProcessState(state);
}
private void setProcessState(final int state) {
int oldState = this.processState;
this.processState = state;
fireProcessStateChanged(oldState, state);
}
/**
* @deprecated Use {@link #getProcessState()} instead
*/
@Deprecated
public synchronized int getExperimentState() {
return getProcessState();
}
public int getProcessState() {
return this.processState;
}
// -------------------------
// User initiated state changes
// ---------------------------
/** Adds the given process state listener. */
public void addProcessStateListener(ProcessStateListener processStateListener) {
this.processStateListeners.add(processStateListener);
}
/** Removes the given process state listener. */
public void removeProcessStateListener(ProcessStateListener processStateListener) {
this.processStateListeners.remove(processStateListener);
}
private void fireProcessStateChanged(int stateBefore, int newState) {
// sanity check
if (stateBefore == newState) {
return;
}
List<ProcessStateListener> listeners;
synchronized (processStateListeners) {
listeners = new LinkedList<>(processStateListeners);
}
for (ProcessStateListener listener : listeners) {
switch (newState) {
case PROCESS_STATE_PAUSED:
listener.paused(this);
break;
case PROCESS_STATE_STOPPED:
listener.stopped(this);
break;
default:
if (stateBefore == PROCESS_STATE_STOPPED) {
listener.started(this);
} else {
listener.resumed(this);
}
break;
}
}
}
// -------------------------
// Logging
// -------------------------
/**
* @deprecated use {@link #getLogger()} instead
*/
@Deprecated
public LoggingHandler getLog() {
return this.logService;
}
public Logger getLogger() {
return this.logger;
}
// -------------------------
// Macro Handler
// -------------------------
/** Returns the macro handler. */
public MacroHandler getMacroHandler() {
return this.macroHandler;
}
/** Clears all macros. */
public void clearMacros() {
this.getMacroHandler().clear();
}
// -------------------------
// IOObject Storage
// -------------------------
/** Stores the object with the given name. */
public void store(final String name, final IOObject object) {
this.storageMap.put(name, object);
}
/** Retrieves the stored object. */
public IOObject retrieve(final String name, final boolean remove) {
if (remove) {
return this.storageMap.remove(name);
} else {
return this.storageMap.get(name);
}
}
/** Clears all macros. */
public void clearStorage() {
this.storageMap.clear();
}
// -------------------------
// State storage
// -------------------------
/**
* Injects another {@link IOObject} cache (to remember and recall {@link IOObject}s during a
* long-term scope)
*
* If {@link #ioObjectCache} is null, the setter does not have any effect
*/
public void setIOObjectCache(IOObjectMap ioObjectCache) {
if (ioObjectCache != null) {
this.ioObjectCache = ioObjectCache;
}
}
/**
* Returns the {@link IOObject} cache (to remember and recall {@link IOObject}s during a
* long-term scope), designed to be manipulated by operators in the process
*
* @return the IOObjectCache of the process
*/
public IOObjectMap getIOObjectCache() {
return ioObjectCache;
}
// -------------------------
// Data Tables (Logging)
// -------------------------
/** Adds the given logging listener. */
public void addLoggingListener(final LoggingListener loggingListener) {
this.loggingListeners.add(loggingListener);
}
/** Removes the given logging listener. */
public void removeLoggingListener(final LoggingListener loggingListener) {
this.loggingListeners.remove(loggingListener);
}
/** Returns true if a data table object with the given name exists. */
public boolean dataTableExists(final String name) {
return dataTableMap.get(name) != null;
}
/**
* Adds the given data table.
*/
public void addDataTable(final DataTable table) {
dataTableMap.put(table.getName(), table);
synchronized (loggingListeners) {
for (LoggingListener listener : loggingListeners) {
listener.addDataTable(table);
}
}
}
/** Clears a single data table, i.e. removes all entries. */
public void clearDataTable(final String name) {
DataTable table = getDataTable(name);
if (table != null) {
if (table instanceof SimpleDataTable) {
((SimpleDataTable) table).clear();
}
}
}
/** Deletes a single data table. */
public void deleteDataTable(final String name) {
if (dataTableExists(name)) {
DataTable table = dataTableMap.remove(name);
synchronized (loggingListeners) {
for (LoggingListener listener : loggingListeners) {
listener.removeDataTable(table);
}
}
}
}
/**
* Returns the data table associated with the given name. If the name was not used yet, an empty
* DataTable object is created with the given columnNames.
*/
public DataTable getDataTable(final String name) {
return dataTableMap.get(name);
}
/** Returns all data tables. */
public Collection<DataTable> getDataTables() {
return dataTableMap.values();
}
/** Removes all data tables before running a new process. */
private void clearDataTables() {
dataTableMap.clear();
}
// ------------------------------
// Report Streams
// ------------------------------
/**
* This method adds a new report stream with the given name
*/
public void addReportStream(final ReportStream stream) {
reportStreamMap.put(stream.getName(), stream);
}
/**
* Returns the reportStream with given name
*/
public ReportStream getReportStream(final String name) {
if (name == null || name.length() == 0) {
if (reportStreamMap.size() == 1) {
return reportStreamMap.values().iterator().next();
} else {
return null;
}
} else {
return reportStreamMap.get(name);
}
}
/**
* Removes this reportStream from process. This report Stream will not be notified about new
* report items.
*
* @param name
* of the report stream given in the ReportGenerator operator
*/
public void removeReportStream(final String name) {
reportStreamMap.remove(name);
}
public void clearReportStreams() {
reportStreamMap.clear();
}
// ----------------------
// Operator Handling
// ----------------------
/** Sets the current root operator. This might lead to a new registering of operator names. */
public void setRootOperator(final ProcessRootOperator root) {
if (this.rootOperator != null) {
this.rootOperator.removeObserver(delegatingOperatorObserver);
}
this.rootOperator = root;
this.rootOperator.addObserver(delegatingOperatorObserver, false);
this.operatorNameMap.clear();
this.rootOperator.setProcess(this);
}
/** Delivers the current root operator. */
public ProcessRootOperator getRootOperator() {
return rootOperator;
}
/** Returns the operator with the given name. */
public Operator getOperator(final String name) {
return operatorNameMap.get(name);
}
/** Returns the operator that is currently being executed. */
public Operator getCurrentOperator() {
return currentOperator;
}
/** Returns a Collection view of all operators. */
public Collection<Operator> getAllOperators() {
List<Operator> result = rootOperator.getAllInnerOperators();
result.add(0, rootOperator);
return result;
}
/** Returns a Set view of all operator names (i.e. Strings). */
public Collection<String> getAllOperatorNames() {
Collection<String> allNames = new LinkedList<>();
for (Operator o : getAllOperators()) {
allNames.add(o.getName());
}
return allNames;
}
/** Sets the operator that is currently being executed. */
public void setCurrentOperator(final Operator operator) {
this.currentOperator = operator;
}
// -------------------------------------
// start, stop, resume, breakpoints
// -------------------------------------
/** We synchronize on this object to wait and resume operation. */
private final Object breakpointLock = new Object();
/** Pauses the process at a breakpoint. */
public void pause(final Operator operator, final IOContainer iocontainer, final int breakpointType) {
setProcessState(PROCESS_STATE_PAUSED);
fireBreakpointEvent(operator, iocontainer, breakpointType);
while (getProcessState() == Process.PROCESS_STATE_PAUSED) {
synchronized (breakpointLock) {
try {
breakpointLock.wait();
} catch (InterruptedException e) {
}
}
}
}
/** Resumes the process after it has been paused. */
public void resume() {
setProcessState(PROCESS_STATE_RUNNING);
synchronized (breakpointLock) {
breakpointLock.notifyAll();
}
fireResumeEvent();
}
/** Stops the process as soon as possible. */
public void stop() {
this.setProcessState(PROCESS_STATE_STOPPED);
synchronized (breakpointLock) {
breakpointLock.notifyAll();
}
}
/** Stops the process as soon as possible. */
public void pause() {
this.setProcessState(PROCESS_STATE_PAUSED);
}
/** Returns true iff the process should be stopped. */
public boolean shouldStop() {
return getProcessState() == PROCESS_STATE_STOPPED;
}
/** Returns true iff the process should be stopped. */
public boolean shouldPause() {
return getProcessState() == PROCESS_STATE_PAUSED;
}
// --------------------
// Filters between operators handling
// --------------------
/**
* Add a new {@link ProcessFlowFilter} to this process. The filter will be called directly
* before and after each operator. Refer to {@link ProcessFlowFilter} for more information.
* <p>
* If the given filter instance is already registered, it will not be added a second time.
* </p>
*
* @param filter
* the filter instance to add
*/
public void addProcessFlowFilter(ProcessFlowFilter filter) {
if (filter == null) {
throw new IllegalArgumentException("filter must not be null!");
}
processFlowFilters.addIfAbsent(filter);
}
/**
* Remove a {@link ProcessFlowFilter} from this process. Does nothing if the filter is unknown.
*
* @param filter
* the filter instance to remove
*/
public void removeProcessFlowFilter(ProcessFlowFilter filter) {
if (filter == null) {
throw new IllegalArgumentException("filter must not be null!");
}
processFlowFilters.remove(filter);
}
/**
* Notifies all registered {@link ProcessFlowFilter}s that the next operator in the process is
* about to be executed.
*
* @param previousOperator
* the previous operator; may be {@code null} for the first operator in a subprocess
* @param nextOperator
* the next operator to be called, never {@code null}
* @param input
* the list of all input data for the next operator. If {@code null}, an empty list
* will be used
*/
public void fireProcessFlowBeforeOperator(Operator previousOperator, Operator nextOperator, List<FlowData> input)
throws OperatorException {
if (nextOperator == null) {
throw new IllegalArgumentException("nextOperator must not be null!");
}
if (input == null) {
input = Collections.emptyList();
}
for (ProcessFlowFilter filter : processFlowFilters) {
try {
filter.preOperator(previousOperator, nextOperator, input);
} catch (OperatorException oe) {
throw oe;
} catch (Exception e) {
getLogger().log(Level.WARNING, "com.rapidminer.Process.process_flow_filter_failed", e);
}
}
}
/**
* Notifies all registered {@link ProcessFlowFilter}s that an operator in the process has just
* finished execution.
*
* @param previousOperator
* the operator which just finished, never {@code null}
* @param nextOperator
* the next operator to be called; may be {@code null} if this was the last operator
* in a subprocess
* @param output
* the list of all output data from the previous operator. If {@code null}, an empty
* list will be used
*/
public void fireProcessFlowAfterOperator(Operator previousOperator, Operator nextOperator, List<FlowData> output)
throws OperatorException {
if (previousOperator == null) {
throw new IllegalArgumentException("previousOperator must not be null!");
}
if (output == null) {
output = Collections.emptyList();
}
for (ProcessFlowFilter filter : processFlowFilters) {
try {
filter.postOperator(previousOperator, nextOperator, output);
} catch (OperatorException oe) {
throw oe;
} catch (Exception e) {
getLogger().log(Level.WARNING, "com.rapidminer.Process.process_flow_filter_failed", e);
}
}
}
/**
* Copies the registered {@link ProcessFlowFilter}s of this process to the given process
* instance.
*
* @param otherProcess
* the process who should get all process flow listeners which are registered to this
* process instance
*/
public void copyProcessFlowListenersToOtherProcess(Process otherProcess) {
if (otherProcess == null) {
throw new IllegalArgumentException("otherProcess must not be null!");
}
for (ProcessFlowFilter filter : processFlowFilters) {
otherProcess.addProcessFlowFilter(filter);
}
}
// --------------------
// Breakpoint Handling
// --------------------
/** Adds a breakpoint listener. */
public void addBreakpointListener(final BreakpointListener listener) {
breakpointListeners.add(listener);
}
/** Removes a breakpoint listener. */
public void removeBreakpointListener(final BreakpointListener listener) {
breakpointListeners.remove(listener);
}
/** Fires the event that the process was paused. */
private void fireBreakpointEvent(final Operator operator, final IOContainer ioContainer, final int location) {
synchronized (breakpointListeners) {
for (BreakpointListener l : breakpointListeners) {
l.breakpointReached(this, operator, ioContainer, location);
}
}
}
/** Fires the event that the process was resumed. */
public void fireResumeEvent() {
LinkedList<BreakpointListener> l;
synchronized (breakpointListeners) {
l = new LinkedList<>(breakpointListeners);
}
for (BreakpointListener listener : l) {
listener.resume();
}
}
// -----------------
// Checks
// -----------------
/**
* Delivers the information about unknown parameter types which occurred during process creation
* (from streams or files).
*/
public List<UnknownParameterInformation> getUnknownParameters() {
return this.unknownParameterInformation;
}
/**
* Clears the information about unknown parameter types which occurred during process creation
* (from streams or files).
*/
public void clearUnknownParameters() {
this.unknownParameterInformation.clear();
}
/**
* Checks for correct number of inner operators, properties, and io.
*
* @deprecated Use {@link #checkProcess(IOContainer)} instead
*/
@Deprecated
public boolean checkExperiment(final IOContainer inputContainer) {
return checkProcess(inputContainer);
}
/** Checks for correct number of inner operators, properties, and io. */
public boolean checkProcess(final IOContainer inputContainer) {
rootOperator.checkAll();
return true;
}
// ------------------
// Running
// ------------------
/**
* This method initializes the process, the operators, and the services and must be invoked at
* the beginning of run. It also resets all apply counts.
*/
private final void prepareRun(final int logVerbosity) throws OperatorException {
initLogging(logVerbosity);
setProcessState(PROCESS_STATE_RUNNING);
getLogger().fine("Initialising process setup.");
RandomGenerator.init(this);
ResultService.init(this);
clearDataTables();
clearReportStreams();
clearMacros();
clearStorage();
if (getExecutionMode() != ExecutionMode.ONLY_DIRTY) {
getRootOperator().clear(Port.CLEAR_DATA);
}
AttributeFactory.resetNameCounters();
getLogger().fine("Process initialised.");
// add process start macro value here already to have it available for root parameters
// can be overwritten if it is passed to the run() method via the macro map
getMacroHandler().addMacro(MacroHandler.PROCESS_START,
MacroHandler.DATE_FORMAT.get().format(new Date(System.currentTimeMillis())));
}
/**
* Checks whether input data was specified in the process context. Will return true if at least
* one input port has specified data.
*
* @param firstPort
* The first port to check
* @return true if at least one input port has specified data.
*/
private boolean checkForInitialData(int firstPort) {
for (int i = firstPort; i < context.getInputRepositoryLocations().size(); i++) {
String location = context.getInputRepositoryLocations().get(i);
if (location == null || location.length() == 0) {
continue;
}
if (i >= rootOperator.getSubprocess(0).getInnerSources().getNumberOfPorts()) {
break;
}
return true;
}
return false;
}
/**
* Loads results from the repository if specified in the {@link ProcessContext}.
*
* @param firstPort
* Specifies the first port which is read from the ProcessContext. This enables the
* possibility to skip ports for which input is already specified via the input
* parameter of the run() method.
*/
protected void loadInitialData(final int firstPort) throws UserError {
loadInitialData(firstPort, null);
}
/**
* Loads results from the repository if specified in the {@link ProcessContext}. Will also show
* the progress of loading if a {@link ProgressListener} is specified.
*
* @param firstPort
* Specifies the first port which is read from the ProcessContext. This enables the
* possibility to skip ports for which input is already specified via the input
* parameter of the run() method.
* @param progressListener
* The progress listener for loading the data. Can be null.
*/
protected void loadInitialData(final int firstPort, ProgressListener progressListener) throws UserError {
ProcessContext context = getContext();
if (context.getInputRepositoryLocations().isEmpty()) {
if (progressListener != null) {
progressListener.complete();
}
return;
}
if (progressListener != null) {
progressListener.setTotal(context.getInputRepositoryLocations().size() - firstPort - 1);
progressListener.setCompleted(0);
}
getLogger()
.info("Loading initial data" + (firstPort > 0 ? " (starting at port " + (firstPort + 1) + ")" : "") + ".");
for (int i = firstPort; i < context.getInputRepositoryLocations().size(); i++) {
if (shouldStop()) {
return;
}
String location = context.getInputRepositoryLocations().get(i);
if (location == null || location.length() == 0) {
getLogger().fine("Input #" + (i + 1) + " not specified.");