Checker.java 30 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/*-
 *  Copyright 2020 Beuth Hochschule für Technik Berlin, Hochschule für Technik Stuttgart
 * 
 *  This file is part of CityDoctor2.
 *
 *  CityDoctor2 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 3 of the License, or
 *  (at your option) any later version.
 *
 *  CityDoctor2 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 Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public License
 *  along with CityDoctor2.  If not, see <https://www.gnu.org/licenses/>.
 */
package de.hft.stuttgart.citydoctor2.check;

import java.io.BufferedOutputStream;
import java.io.File;
23
import java.io.FileInputStream;
24
25
26
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
27
28
import java.io.InputStream;
import java.io.UncheckedIOException;
29
30
31
32
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
Matthias Betz's avatar
Matthias Betz committed
33
import java.util.Iterator;
34
35
36
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
Matthias Betz's avatar
Matthias Betz committed
37
import java.util.Set;
38
39
40
import java.util.stream.Stream;

import javax.xml.XMLConstants;
41
import javax.xml.transform.Result;
42
import javax.xml.transform.Source;
43
import javax.xml.transform.Transformer;
44
import javax.xml.transform.TransformerException;
45
import javax.xml.transform.TransformerFactory;
46
import javax.xml.transform.URIResolver;
47
import javax.xml.transform.dom.DOMResult;
48
import javax.xml.transform.dom.DOMSource;
49
import javax.xml.transform.sax.SAXResult;
50
51
52
53
54
import javax.xml.transform.stream.StreamSource;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

Matthias Betz's avatar
Matthias Betz committed
55
import de.hft.stuttgart.citydoctor2.check.error.AttributeInvalidError;
56
57
import de.hft.stuttgart.citydoctor2.check.error.AttributeMissingError;
import de.hft.stuttgart.citydoctor2.check.error.AttributeValueWrongError;
58
59
import de.hft.stuttgart.citydoctor2.check.error.SchematronError;
import de.hft.stuttgart.citydoctor2.checkresult.utility.CheckReportWriteException;
60
import de.hft.stuttgart.citydoctor2.checks.CheckContainer;
61
import de.hft.stuttgart.citydoctor2.checks.CheckPrototype;
62
63
64
65
66
67
import de.hft.stuttgart.citydoctor2.checks.Checks;
import de.hft.stuttgart.citydoctor2.checks.SvrlContentHandler;
import de.hft.stuttgart.citydoctor2.checks.util.FeatureCheckedListener;
import de.hft.stuttgart.citydoctor2.datastructure.CityDoctorModel;
import de.hft.stuttgart.citydoctor2.datastructure.CityObject;
import de.hft.stuttgart.citydoctor2.datastructure.FeatureType;
68
69
70
import de.hft.stuttgart.citydoctor2.parser.CityGmlConsumer;
import de.hft.stuttgart.citydoctor2.parser.CityGmlParseException;
import de.hft.stuttgart.citydoctor2.parser.CityGmlParser;
71
72
73
74
75
76
77
78
import de.hft.stuttgart.citydoctor2.parser.ParserConfiguration;
import de.hft.stuttgart.citydoctor2.parser.ProgressListener;
import de.hft.stuttgart.citydoctor2.reporting.Reporter;
import de.hft.stuttgart.citydoctor2.reporting.StreamReporter;
import de.hft.stuttgart.citydoctor2.reporting.XmlStreamReporter;
import de.hft.stuttgart.citydoctor2.reporting.XmlValidationReporter;
import de.hft.stuttgart.citydoctor2.reporting.pdf.PdfReporter;
import de.hft.stuttgart.citydoctor2.reporting.pdf.PdfStreamReporter;
Matthias Betz's avatar
Matthias Betz committed
79
import de.hft.stuttgart.citydoctor2.utils.Localization;
Matthias Betz's avatar
Matthias Betz committed
80
81
82
83
84
85
86
87
88
89
import de.hft.stuttgart.quality.model.enums.RequirementId;
import de.hft.stuttgart.quality.model.enums.TopLevelFeatureType;
import de.hft.stuttgart.quality.model.properties.CheckingProperty;
import de.hft.stuttgart.quality.model.properties.FilterProperty;
import de.hft.stuttgart.quality.model.properties.GlobalParametersProperty;
import de.hft.stuttgart.quality.model.properties.ParameterProperty;
import de.hft.stuttgart.quality.model.properties.RequirementProperty;
import de.hft.stuttgart.quality.model.types.Checking;
import de.hft.stuttgart.quality.model.types.Parameter;
import de.hft.stuttgart.quality.model.types.ValidationPlan;
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

/**
 * The main container class for checking. It contains the logic for validation,
 * as well as contains the state of the checks performed.
 * 
 * @author Matthias Betz
 *
 */
public class Checker {

	private static final Logger logger = LogManager.getLogger(Checker.class);

	private ValidationConfiguration config;
	private List<List<Check>> execLayers;

	private List<Filter> includeFilters;
	private List<Filter> excludeFilters;

	private Checks checkConfig;
	private CityDoctorModel model;

	public Checker(CityDoctorModel model) {
		this(ValidationConfiguration.loadStandardValidationConfig(), model);
	}

	public Checker(ValidationConfiguration config, CityDoctorModel model) {
		this.model = model;
		checkConfig = new Checks();
		setValidationConfig(config);
	}

	public Checks getChecks() {
		return checkConfig;
	}
124

125
126
127
128
129
130
131
132
133
134
135
136
	public CityDoctorModel getModel() {
		return model;
	}

	/**
	 * Write the xml report for the given CityDoctorModel. If no report location is
	 * given or this checker has not validated anything, nothing is done.
	 * 
	 * @param xmlOutput the output file location for the XML report. Can be null.
	 * @param model     the model for which the report is written.
	 */
	public void writeXmlReport(String xmlOutput) {
137
		if (!model.isValidated() || xmlOutput == null) {
138
139
140
			return;
		}
		File xmlFile = new File(xmlOutput);
141
		if (xmlFile.getParentFile() != null) {
142
143
144
145
146
147
			xmlFile.getParentFile().mkdirs();
		}
		Reporter reporter = new XmlValidationReporter();
		try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(xmlFile.getAbsolutePath()))) {
			reporter.writeReport(checkConfig, bos, model, config);
		} catch (CheckReportWriteException | IOException e) {
Matthias Betz's avatar
Matthias Betz committed
148
			logger.error(Localization.getText("Checker.failXml"), e);
149
150
151
152
		}
	}

	public void writePdfReport(String pdfOutput) {
153
		if (!model.isValidated() || pdfOutput == null) {
154
155
156
			return;
		}
		File pdfFile = new File(pdfOutput);
157
		if (pdfFile.getParentFile() != null) {
158
159
			pdfFile.getParentFile().mkdirs();
		}
Matthias Betz's avatar
Matthias Betz committed
160
		Reporter reporter = new PdfReporter();
161
162
163
		try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(pdfFile.getAbsolutePath()))) {
			reporter.writeReport(checkConfig, bos, model, config);
		} catch (IOException | CheckReportWriteException e) {
Matthias Betz's avatar
Matthias Betz committed
164
			logger.error(Localization.getText("Checker.failPdf"), e);
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
		}
	}

	public void runChecks() {
		runChecks((ProgressListener) null);
	}

	public void runChecks(String xmlOutput) {
		runChecks();
		writeXmlReport(xmlOutput);
	}

	public void runChecks(String xmlOutput, String pdfOutput) {
		runChecks();
		writeXmlReport(xmlOutput);
		writePdfReport(pdfOutput);
	}

	public void runChecks(String xmlOutput, String pdfOutput, ProgressListener l) {
		runChecks(l);
		writeXmlReport(xmlOutput);
		writePdfReport(pdfOutput);
	}

	public void runChecks(ProgressListener l) {
		if (config == null) {
			config = ValidationConfiguration.loadStandardValidationConfig();
		}
		checkCityModel(model, l);
Matthias Betz's avatar
Matthias Betz committed
194
195
196
		if (logger.isInfoEnabled()) {
			logger.info(Localization.getText("Checker.checksFinished"));
		}
197
198
		SvrlContentHandler handler = executeSchematronValidationIfAvailable(config, model.getFile());
		if (handler != null) {
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
			handleSchematronResults(handler);
		}
		model.setValidated(createValidationPlan());
	}

	private void handleSchematronResults(SvrlContentHandler handler) {
		model.addGlobalErrors(handler.getGeneralErrors());
		Map<String, CityObject> featureMap = new HashMap<>();
		model.createFeatureStream().forEach(f -> featureMap.put(f.getGmlId().getGmlString(), f));
		handler.getFeatureErrors().forEach((k, v) -> {
			if (k.trim().isEmpty()) {
				// missing gml id, ignore?
				return;
			}
			CityObject co = featureMap.get(k);
			if (co == null) {
				// gml id reported by schematron was not found, add to general errors
				for (SchematronError se : v) {
					model.addGlobalError(se);
218
				}
219
220
221
222
223
224
			} else {
				handleSchematronErrorsForCityObject(v, co);
			}
		});
	}

225
	public static void handleSchematronErrorsForCityObject(List<SchematronError> v, CityObject co) {
226
227
228
229
		int count = 0;
		for (SchematronError se : v) {
			CheckError err;
			if (AttributeMissingError.ID.getIdString().equals(se.getErrorIdString())) {
Matthias Betz's avatar
Matthias Betz committed
230
				err = new AttributeMissingError(co, se.getChildId(), se.getNameOfAttribute());
231
			} else if (AttributeValueWrongError.ID.getIdString().equals(se.getErrorIdString())) {
Matthias Betz's avatar
Matthias Betz committed
232
233
234
				err = new AttributeValueWrongError(co, se.getChildId(), se.getNameOfAttribute());
			} else if (AttributeInvalidError.ID.getIdString().equals(se.getErrorIdString())) {
				err = new AttributeInvalidError(co, se.getChildId(), se.getNameOfAttribute());
235
236
237
238
			} else {
				throw new IllegalStateException(
						"Unknown error ID was given in schematron file: " + se.getErrorIdString());
			}
239
			co.addCheckResult(new CheckResult(new CheckId("SchematronCheck " + count), ResultStatus.ERROR, err));
240
241
242
243
			count++;
		}
	}

Matthias Betz's avatar
Matthias Betz committed
244
	ValidationPlan createValidationPlan() {
245
		ValidationPlan plan = new ValidationPlan();
Matthias Betz's avatar
Matthias Betz committed
246
247
		de.hft.stuttgart.quality.model.types.Filter filter = createFilter();
		plan.setFilter(new FilterProperty(filter));
248

249
		Map<String, de.hft.stuttgart.citydoctor2.check.Requirement> reqs = Checks.getAvailableRequirements();
250
		for (Entry<String, RequirementConfiguration> e : config.getRequirements().entrySet()) {
251
252
253
254
			RequirementId reqId = mapToRequirement(e.getKey());
			if (reqId == null) {
				continue;
			}
Matthias Betz's avatar
Matthias Betz committed
255
256
			de.hft.stuttgart.quality.model.types.Requirement req = new de.hft.stuttgart.quality.model.types.Requirement();
			req.setRequirementType(reqId);
257
			req.setEnabled(e.getValue().isEnabled());
Matthias Betz's avatar
Matthias Betz committed
258
			plan.getRequirements().add(new RequirementProperty(req));
259
260
261
262
			Map<String, String> parameters = e.getValue().getParameters();
			if (parameters != null) {
				for (Entry<String, String> param : parameters.entrySet()) {
					Parameter p = new Parameter();
263
					DefaultParameter defaultP = getDefaultParameter(e.getKey(), reqs, param.getKey());
264
265
					if (defaultP != null) {
						p.setUom(defaultP.getUnitType().getGmlRepresentation());
266
					}
267
268
					p.setName(param.getKey());
					p.setValue(param.getValue());
Matthias Betz's avatar
Matthias Betz committed
269
					req.getParameters().add(new ParameterProperty(p));
270
271
272
273
				}
			}
		}

Matthias Betz's avatar
Matthias Betz committed
274
275
276
277
		de.hft.stuttgart.quality.model.types.Requirement missing = new de.hft.stuttgart.quality.model.types.Requirement();
		missing.setRequirementType(RequirementId.R_SE_ATTRIBUTES_EXISTING);
		de.hft.stuttgart.quality.model.types.Requirement correct = new de.hft.stuttgart.quality.model.types.Requirement();
		correct.setRequirementType(RequirementId.R_SE_ATTRIBUTES_CORRECT);
278
279
		missing.setEnabled(config.getSchematronFilePath() != null);
		correct.setEnabled(config.getSchematronFilePath() != null);
Matthias Betz's avatar
Matthias Betz committed
280
281
		plan.getRequirements().add(new RequirementProperty(missing));
		plan.getRequirements().add(new RequirementProperty(correct));
282
283
284
285
286
287
288
289
290
291
292

		Parameter numRounding = new Parameter();
		numRounding.setName("numberOfRoundingPlaces");
		numRounding.setValue("" + config.getNumberOfRoundingPlaces());
		Parameter minVertexDistance = new Parameter();
		minVertexDistance.setName("minVertexDistance");
		minVertexDistance.setUom("m");
		minVertexDistance.setValue("" + config.getMinVertexDistance());
		Parameter schematronFile = new Parameter();
		schematronFile.setName("schematronFile");
		schematronFile.setValue(config.getSchematronFilePath());
Matthias Betz's avatar
Matthias Betz committed
293
294
295
296
297
		de.hft.stuttgart.quality.model.types.GlobalParameters globParams = new de.hft.stuttgart.quality.model.types.GlobalParameters();
		plan.setGlobalParameters(new GlobalParametersProperty(globParams));
		globParams.getParameters().add(new ParameterProperty(numRounding));
		globParams.getParameters().add(new ParameterProperty(minVertexDistance));
		globParams.getParameters().add(new ParameterProperty(schematronFile));
298
299
300
		return plan;
	}

301
302
303
	private DefaultParameter getDefaultParameter(String reqKey,
			Map<String, de.hft.stuttgart.citydoctor2.check.Requirement> reqs, String paramName) {
		de.hft.stuttgart.citydoctor2.check.Requirement requirement = reqs.get(reqKey);
304
305
		if (requirement != null) {
			for (DefaultParameter param : requirement.getDefaultParameter()) {
306
				if (param.getName().equals(paramName)) {
307
308
					return param;
				}
309
310
311
312
313
			}
		}
		return null;
	}

Matthias Betz's avatar
Matthias Betz committed
314
	private de.hft.stuttgart.quality.model.types.Filter createFilter() {
Matthias Betz's avatar
Matthias Betz committed
315
		var filter = new de.hft.stuttgart.quality.model.types.Filter();
316
317
318
319
320
321
322
323
324
		handleInputFilter(filter);
		if (excludeFilters != null) {
			for (Filter f : excludeFilters) {
				if (f instanceof TypeFilter) {
					TypeFilter tf = (TypeFilter) f;
					FeatureType type = tf.getType();
					TopLevelFeatureType tlft = mapToTopLevelFeatureType(type);
					if (tlft == null) {
						continue;
325
					}
326
					removeFilter(tlft, filter);
327
				}
328
329
330
331
332
			}
		}
		return filter;
	}

Matthias Betz's avatar
Matthias Betz committed
333
	private void handleInputFilter(de.hft.stuttgart.quality.model.types.Filter filter) {
334
335
336
337
338
		if (includeFilters == null || includeFilters.isEmpty()) {
			// no filter means, use all
			addAllFilters(filter);
		} else {
			for (Filter f : includeFilters) {
Matthias Betz's avatar
Matthias Betz committed
339
				if (f instanceof TypeFilter tf) {
340
341
342
343
344
					FeatureType type = tf.getType();
					TopLevelFeatureType tlft = mapToTopLevelFeatureType(type);
					if (tlft == null) {
						continue;
					}
Matthias Betz's avatar
Matthias Betz committed
345
346
347
					Checking c = new Checking();
					c.setFeatureType(tlft);
					filter.getChecking().add(new CheckingProperty(c));
348
349
				}
			}
Matthias Betz's avatar
Matthias Betz committed
350
			if (filter.getChecking().isEmpty()) {
351
352
353
354
355
356
357
358
				// this happens if no type include filter was used
				// it is possible only single objects were tested then
				// so include everything
				addAllFilters(filter);
			}
		}
	}

Matthias Betz's avatar
Matthias Betz committed
359
360
361
362
	private void addAllFilters(de.hft.stuttgart.quality.model.types.Filter filter) {
		Checking buildingChecking = new Checking();
		buildingChecking.setFeatureType(TopLevelFeatureType.BUILDING);
		filter.getChecking().add(new CheckingProperty(buildingChecking));
Matthias Betz's avatar
Matthias Betz committed
363

Matthias Betz's avatar
Matthias Betz committed
364
365
366
		Checking bridgeChecking = new Checking();
		bridgeChecking.setFeatureType(TopLevelFeatureType.BRIDGE);
		filter.getChecking().add(new CheckingProperty(bridgeChecking));
Matthias Betz's avatar
Matthias Betz committed
367

Matthias Betz's avatar
Matthias Betz committed
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
		Checking landChecking = new Checking();
		landChecking.setFeatureType(TopLevelFeatureType.LAND);
		filter.getChecking().add(new CheckingProperty(landChecking));

		Checking transportationChecking = new Checking();
		transportationChecking.setFeatureType(TopLevelFeatureType.TRANSPORTATION);
		filter.getChecking().add(new CheckingProperty(transportationChecking));

		Checking vegetationChecking = new Checking();
		vegetationChecking.setFeatureType(TopLevelFeatureType.VEGETATION);
		filter.getChecking().add(new CheckingProperty(vegetationChecking));

		Checking waterChecking = new Checking();
		waterChecking.setFeatureType(TopLevelFeatureType.WATER);
		filter.getChecking().add(new CheckingProperty(waterChecking));
383
384
	}

Matthias Betz's avatar
Matthias Betz committed
385
386
387
388
	private void removeFilter(TopLevelFeatureType tlft, de.hft.stuttgart.quality.model.types.Filter filter) {
		for (CheckingProperty c : filter.getChecking()) {
			if (c.getObject().getFeatureType().equals(tlft)) {
				filter.getChecking().remove(c);
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
				return;
			}
		}
	}

	private TopLevelFeatureType mapToTopLevelFeatureType(FeatureType type) {
		switch (type) {
		case BRIDGE:
			return TopLevelFeatureType.BRIDGE;
		case BUILDING:
			return TopLevelFeatureType.BUILDING;
		case LAND:
			return TopLevelFeatureType.LAND;
		case TRANSPORTATION:
			return TopLevelFeatureType.TRANSPORTATION;
		case VEGETATION:
			return TopLevelFeatureType.VEGETATION;
		case WATER:
			return TopLevelFeatureType.WATER;
		default:
			return null;
		}
	}

413
414
415
416
	private RequirementId mapToRequirement(String requirementName) {
		try {
			return RequirementId.valueOf(requirementName);
		} catch (IllegalArgumentException e) {
417
			return null;
418
419
		}
	}
420

421
422
423
	public ValidationConfiguration getConfig() {
		return config;
	}
424

425
	public static SvrlContentHandler executeSchematronValidationIfAvailable(ValidationConfiguration config, File file) {
426
427
428
429
430
431
432
433
434
435
436
437
		if (file == null || !file.exists()) {
			return null;
		}
		try {
			return executeSchematronValidationIfAvailable(config, new FileInputStream(file));
		} catch (FileNotFoundException e) {
			throw new UncheckedIOException(e);
		}
	}

	public static SvrlContentHandler executeSchematronValidationIfAvailable(ValidationConfiguration config,
			InputStream in) {
438
		if (config.getSchematronFilePath() != null && !config.getSchematronFilePath().isEmpty()) {
Matthias Betz's avatar
Matthias Betz committed
439
440
441
			if (logger.isInfoEnabled()) {
				logger.info(Localization.getText("Checker.schematronValidation"));
			}
442
443

			try {
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
				TransformerFactory transformerFactory = TransformerFactory.newInstance("net.sf.saxon.TransformerFactoryImpl", Checker.class.getClassLoader());
				transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
				transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);

				transformerFactory.setURIResolver(new URIResolver() {
					
					@Override
					public Source resolve(String href, String base) throws TransformerException {
						return new StreamSource(Checker.class.getResourceAsStream(href));
					}
				});
				
				Source dsdlXslSource = new StreamSource(Checker.class.getResourceAsStream("iso_dsdl_include.xsl"));
				Transformer dsdlXslTransformer = transformerFactory.newTransformer(dsdlXslSource);
				
				DOMResult dsdlXslResult = new DOMResult();
				dsdlXslTransformer.transform(new StreamSource(new File(config.getSchematronFilePath())), dsdlXslResult);
			
				Source abstractExpandXsl = new StreamSource(Checker.class.getResourceAsStream("iso_abstract_expand.xsl"));
				Transformer abstractExpandTransformer = transformerFactory.newTransformer(abstractExpandXsl);
				
				DOMResult abstractExpandResult = new DOMResult();
				abstractExpandTransformer.transform(new DOMSource(dsdlXslResult.getNode()), abstractExpandResult);
				
				Source svrlXslSource = new StreamSource(Checker.class.getResourceAsStream("iso_svrl_for_xslt2.xsl"));
				Transformer svrlTransformer = transformerFactory.newTransformer(svrlXslSource);
				
				DOMResult schematronXsltResult = new DOMResult();
				svrlTransformer.transform(new DOMSource(abstractExpandResult.getNode()), schematronXsltResult);

				Transformer schematronTransformer = transformerFactory.newTransformer(new DOMSource(schematronXsltResult.getNode()));
				Source cityGmlSource = new StreamSource(in);
				
477
				SvrlContentHandler handler = new SvrlContentHandler();
478
479
480
				Result finalResult = new SAXResult(handler);
				
				schematronTransformer.transform(cityGmlSource, finalResult);
481
				return handler;
482
			} catch (TransformerException e) {
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
				logger.catching(e);
			}
		}
		return null;
	}

	private void buildFilters() {
		FilterConfiguration filterConfig = config.getFilter();
		if (filterConfig == null) {
			includeFilters = Collections.emptyList();
			excludeFilters = Collections.emptyList();
			return;
		}
		excludeFilters = buildExcludeFilters(filterConfig);
		includeFilters = buildIncludeFilters(filterConfig);
	}

	private List<Filter> buildExcludeFilters(FilterConfiguration filterConfig) {
		if (filterConfig == null) {
			return Collections.emptyList();
		}
		ExcludeFilterConfiguration excludeConfig = filterConfig.getExclude();
		if (excludeConfig == null) {
			return Collections.emptyList();
		} else {
			List<Filter> filters = new ArrayList<>();
			if (excludeConfig.getTypes() != null) {
				for (FeatureType excludeType : excludeConfig.getTypes()) {
					filters.add(new TypeFilter(excludeType));
				}
			}
			if (excludeConfig.getIds() != null) {
				for (String excludePattern : excludeConfig.getIds()) {
					Filter f = new EqualsIgnoreCaseFilter(excludePattern);
					filters.add(f);
				}
			}
			return filters;
		}
	}

	private List<Filter> buildIncludeFilters(FilterConfiguration filterConfig) {
		if (filterConfig == null) {
			return Collections.emptyList();
		}
		IncludeFilterConfiguration includeConfig = filterConfig.getInclude();
		if (includeConfig == null) {
			return Collections.emptyList();
		} else {
			List<Filter> filters = new ArrayList<>();
			if (includeConfig.getTypes() != null) {
				for (FeatureType includeType : includeConfig.getTypes()) {
					filters.add(new TypeFilter(includeType));
				}
			}
			if (includeConfig.getIds() != null) {
				for (String includePattern : includeConfig.getIds()) {
					Filter f = new EqualsIgnoreCaseFilter(includePattern);
					filters.add(f);
				}
			}
			return filters;
		}
	}

	private void setValidationConfig(ValidationConfiguration config) {
		if (config == null) {
			throw new IllegalArgumentException("Validation configuration may not be null");
		}
		this.config = config;
		buildFilters();
		ParserConfiguration parserConfig = config.getParserConfiguration();
		List<Check> checks = collectEnabledChecksAndInit(parserConfig, config);
		execLayers = buildExecutionLayers(checks);
	}

	private List<Check> collectEnabledChecksAndInit(ParserConfiguration parserConfig, ValidationConfiguration config) {
560
561
562
563
564
565
566
567
568
569
		Set<CheckId> enabledCheck = new HashSet<>();
		Map<CheckId, Map<String, String>> parameterMap = new HashMap<>();
		for (Entry<String, RequirementConfiguration> e : config.getRequirements().entrySet()) {
			de.hft.stuttgart.citydoctor2.check.Requirement req = Checks.getAvailableRequirements().get(e.getKey());
			if (req == null) {
				logger.warn("Could not find any check that satisfies requirement {}, it will not be checked",
						e.getKey());
			} else {
				if (e.getValue().isEnabled()) {
					// this requirement is enabled
570
					insertGlobalParameters(config, enabledCheck, parameterMap, e, req);
571
572
573
574
575
576
577
578
579
580
581
582
583
				}
			}
		}
		fillParameterMapsWithDefaultParameter(enabledCheck, parameterMap);
		ArrayList<Check> checkList = new ArrayList<>();
		for (CheckId id : enabledCheck) {
			Check c = checkConfig.getCheckForId(id);
			c.init(parameterMap.get(id), parserConfig);
			checkList.add(c);
		}
		return checkList;
	}

584
585
586
587
588
589
590
591
592
593
	private void insertGlobalParameters(ValidationConfiguration config, Set<CheckId> enabledCheck,
			Map<CheckId, Map<String, String>> parameterMap, Entry<String, RequirementConfiguration> e,
			de.hft.stuttgart.citydoctor2.check.Requirement req) {
		for (CheckPrototype proto : Checks.getCheckPrototypes()) {
			if (proto.checksRequirements().contains(req)) {
				// this requirement is checked by this check
				// put all requirement parameter in the map
				parameterMap.compute(proto.getCheckId(), (k, v) -> {
					if (v == null) {
						v = new HashMap<>();
Matthias Betz's avatar
Matthias Betz committed
594
						v.put(GlobalParameters.NUMBER_OF_ROUNDING_PLACES, config.getNumberOfRoundingPlacesAsString());
595
596
597
598
599
600
601
602
603
604
605
						v.put(GlobalParameters.MIN_VERTEX_DISTANCE, config.getMinVertexDistanceAsString());
					}
					v.putAll(e.getValue().getParameters());
					return v;
				});
				enabledCheck.add(proto.getCheckId());
				collectDependencyChecks(proto, enabledCheck);
			}
		}
	}

606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
	private void fillParameterMapsWithDefaultParameter(Set<CheckId> enabledCheck,
			Map<CheckId, Map<String, String>> parameterMap) {
		for (CheckId id : enabledCheck) {
			CheckPrototype proto = Checks.getCheckPrototypeForId(id);
			Map<String, String> map = parameterMap.computeIfAbsent(id, k -> new HashMap<>());
			for (de.hft.stuttgart.citydoctor2.check.Requirement req : proto.checksRequirements()) {
				if (proto.checksRequirements().contains(req)) {
					for (DefaultParameter param : req.getDefaultParameter()) {
						map.computeIfAbsent(param.getName(), k -> param.getValue());
					}
				}
			}
		}
	}

	private void collectDependencyChecks(CheckPrototype proto, Set<CheckId> enabledChecks) {
		enabledChecks.addAll(proto.getDependencies());
		for (CheckId id : proto.getDependencies()) {
			if (enabledChecks.contains(id)) {
				continue;
626
			}
627
628
			CheckPrototype depProto = Checks.getCheckPrototypeForId(id);
			collectDependencyChecks(depProto, enabledChecks);
629
630
631
632
633
634
635
636
637
		}
	}

	private void checkCityModel(CityDoctorModel model, ProgressListener l) {
		Stream<CityObject> features = model.createFeatureStream();
		float featureSum = model.getNumberOfFeatures();
		// stupid lamda with final variable restrictions
		int[] currentFeature = new int[1];
		features.forEach(co -> {
638
639
640
641
			if (config.getParserConfiguration().useLowMemoryConsumption()) {
				// no edges have been created yet, create them
				co.prepareForChecking();
			}
642
643
			// check every feature
			executeChecksForCityObject(co);
644

645
646
647
648
			if (config.getParserConfiguration().useLowMemoryConsumption()) {
				// low memory consumption, remove edges again
				co.clearMetaInformation();
			}
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
			if (l != null) {
				currentFeature[0]++;
				l.updateProgress(currentFeature[0] / featureSum);
			}
		});
	}

	private boolean filterObject(CityObject co) {
		return isObjectIncluded(co, includeFilters, excludeFilters);
	}

	private boolean isObjectIncluded(CityObject co, List<Filter> includeFilters, List<Filter> excludeFilters) {
		if (!includeFilters.isEmpty()) {
			boolean include = false;
			for (Filter f : includeFilters) {
				if (f.matches(co)) {
					include = true;
					break;
				}
			}
			if (!include) {
				// not included, ignore
				return false;
			}
		}
		// check if object is excluded
		for (Filter f : excludeFilters) {
			if (f.matches(co)) {
				// exclude object
				return false;
			}
		}
		return true;
	}

	/**
	 * Checks the city object if it has not been removed by the filters. The check
	 * result are stored into the city object itself.
	 * 
	 * @param co the city object that is going to be checked
	 */
	private void executeChecksForCityObject(CityObject co) {
		if (!filterObject(co)) {
			return;
		}
		executeChecksForCheckable(co);
	}

	/**
Matthias Betz's avatar
Matthias Betz committed
698
699
	 * Executes all checks for the checkable. This will bypass the filters. This
	 * will clear the old check results
700
701
702
703
704
705
	 * 
	 * @param co the checkable.
	 */
	public void executeChecksForCheckable(Checkable co) {
		// throw away old results
		co.clearAllContainedCheckResults();
Matthias Betz's avatar
Matthias Betz committed
706
707
708
		if (logger.isDebugEnabled()) {
			logger.debug(Localization.getText("Checker.checkFeature"), co);
		}
709
710
		for (int i = 0; i < execLayers.size(); i++) {
			for (Check check : execLayers.get(i)) {
Matthias Betz's avatar
Matthias Betz committed
711
712
713
				if (logger.isTraceEnabled()) {
					logger.trace(Localization.getText("Checker.executeCheck"), check.getCheckId());
				}
714
715
716
717
718
				co.accept(check);
			}
		}
	}

Matthias Betz's avatar
Matthias Betz committed
719
	public static List<List<Check>> buildExecutionLayers(List<Check> checks) {
720
		List<List<Check>> result = new ArrayList<>();
721

Matthias Betz's avatar
Matthias Betz committed
722
723
		Set<Check> availableChecks = new HashSet<>(checks);
		Set<CheckId> usedChecks = new HashSet<>();
724

Matthias Betz's avatar
Matthias Betz committed
725
726
727
728
729
730
731
732
		while (!availableChecks.isEmpty()) {
			List<Check> layer = new ArrayList<>();
			Iterator<Check> iterator = availableChecks.iterator();
			while (iterator.hasNext()) {
				Check c = iterator.next();
				boolean hasUnusedDependency = searchForUnusedDependency(usedChecks, c);
				if (!hasUnusedDependency) {
					iterator.remove();
733
					layer.add(new CheckContainer(c));
Matthias Betz's avatar
Matthias Betz committed
734
735
736
				}
			}
			if (layer.isEmpty()) {
737
				throw new IllegalStateException(
Matthias Betz's avatar
Matthias Betz committed
738
						"There are checks that have dependencies that are not executed or are unknown, aborting");
Matthias Betz's avatar
Matthias Betz committed
739
740
741
742
			}
			result.add(layer);
			for (Check c : layer) {
				usedChecks.add(c.getCheckId());
743
744
745
746
747
			}
		}
		return result;
	}

Matthias Betz's avatar
Matthias Betz committed
748
749
750
751
752
753
754
	private static boolean searchForUnusedDependency(Set<CheckId> usedChecks, Check c) {
		boolean hasUnusedDependency = false;
		for (CheckId id : c.getDependencies()) {
			if (!usedChecks.contains(id)) {
				hasUnusedDependency = true;
				break;
			}
755
		}
Matthias Betz's avatar
Matthias Betz committed
756
		return hasUnusedDependency;
757
758
	}

759
760
	public static void streamCheck(File inputFile, String xmlOutput, String pdfOutput, ValidationConfiguration config,
			String outputFile) throws IOException, CityGmlParseException {
Matthias Betz's avatar
Matthias Betz committed
761
		streamCheck(inputFile, xmlOutput, pdfOutput, config, null, outputFile);
762
763
	}

764
	public static void streamCheck(File inputFile, String xmlOutput, String pdfOutput, ValidationConfiguration config,
Matthias Betz's avatar
Matthias Betz committed
765
			FeatureCheckedListener l, String outputFile) throws IOException, CityGmlParseException {
766
767
		try (BufferedOutputStream xmlBos = getXmlOutputMaybe(xmlOutput);
				BufferedOutputStream pdfBos = getPdfOutputMaybe(pdfOutput)) {
768
769
			Checker c = new Checker(config, null);
			String fileName = inputFile.getName();
Matthias Betz's avatar
Matthias Betz committed
770

771
772
			// create reporter if available
			XmlStreamReporter xmlReporter = getXmlReporter(config, xmlBos, fileName);
Matthias Betz's avatar
Matthias Betz committed
773
			PdfStreamReporter pdfReporter = getPdfReporter(config, pdfBos, fileName);
Matthias Betz's avatar
Matthias Betz committed
774

775
776
			// execute schematron first
			SvrlContentHandler handler = executeSchematronValidationIfAvailable(config, inputFile);
Matthias Betz's avatar
Matthias Betz committed
777
			CityGmlConsumer con = new StreamCityGmlConsumer(c, xmlReporter, pdfReporter, handler, config, l);
778
			// parse and validate
Matthias Betz's avatar
Matthias Betz committed
779
			CityGmlParser.streamCityGml(inputFile.getAbsolutePath(), config.getParserConfiguration(), con, outputFile);
Matthias Betz's avatar
Matthias Betz committed
780

781
			// write reports if available
782
783
			writeReport(xmlReporter);
			writeReport(pdfReporter);
784
		} catch (CheckReportWriteException e) {
Matthias Betz's avatar
Matthias Betz committed
785
			logger.error(Localization.getText("Checker.failReports"), e);
786
787
		}
	}
788
789
790
791
792
793
794
795
796
797
798
799

	private static XmlStreamReporter getXmlReporter(ValidationConfiguration config, BufferedOutputStream xmlBos,
			String fileName) {
		XmlStreamReporter xmlReporter;
		if (xmlBos != null) {
			xmlReporter = new XmlStreamReporter(xmlBos, fileName, config);
		} else {
			xmlReporter = null;
		}
		return xmlReporter;
	}

Matthias Betz's avatar
Matthias Betz committed
800
801
	private static PdfStreamReporter getPdfReporter(ValidationConfiguration config, BufferedOutputStream pdfBos,
			String fileName) {
802
803
		PdfStreamReporter pdfReporter;
		if (pdfBos != null) {
Matthias Betz's avatar
Matthias Betz committed
804
			pdfReporter = new PdfStreamReporter(pdfBos, fileName, config);
805
806
807
808
809
		} else {
			pdfReporter = null;
		}
		return pdfReporter;
	}
810

Matthias Betz's avatar
Matthias Betz committed
811
	public static void writeReport(StreamReporter reporter) throws CheckReportWriteException {
812
813
814
815
816
		if (reporter != null) {
			reporter.finishReport();
		}
	}

817
	public static BufferedOutputStream getPdfOutputMaybe(String pdfOutput) throws FileNotFoundException {
818
819
820
		return pdfOutput != null ? new BufferedOutputStream(new FileOutputStream(pdfOutput)) : null;
	}

821
	public static BufferedOutputStream getXmlOutputMaybe(String xmlOutput) throws FileNotFoundException {
822
823
824
		return xmlOutput != null ? new BufferedOutputStream(new FileOutputStream(xmlOutput)) : null;
	}

Matthias Betz's avatar
Matthias Betz committed
825
826
827
828
829
830
831
832
833
	/**
	 * Checks the city object and writes report information into reporters. Clears
	 * old check results. If the city object would be filtered by the configured
	 * filters it is ignored and old check results are not cleared.
	 * 
	 * @param xmlReporter a xml reporter
	 * @param pdfReporter a pdf reporter
	 * @param co          the city object to be checked
	 */
834
	public void checkFeature(XmlStreamReporter xmlReporter, PdfStreamReporter pdfReporter, CityObject co) {
Matthias Betz's avatar
Matthias Betz committed
835
836
837
		if (logger.isDebugEnabled()) {
			logger.debug(Localization.getText("Checker.checkFeature"), co);
		}
838
839
840
841
842
843
844
845
846
		executeChecksForCityObject(co);
		if (xmlReporter != null) {
			xmlReporter.report(co);
		}
		if (pdfReporter != null) {
			pdfReporter.report(co);
		}
	}
}