Checker.java 31.6 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
23
24
25
/*-
 *  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;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
26
import java.time.ZonedDateTime;
27
28
29
30
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
Matthias Betz's avatar
Matthias Betz committed
31
import java.util.Iterator;
32
33
34
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
Matthias Betz's avatar
Matthias Betz committed
35
import java.util.Set;
36
import java.util.concurrent.atomic.AtomicInteger;
37
38
39
40
41
42
43
44
45
46
47
48
49
import java.util.stream.Stream;

import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Source;
import javax.xml.transform.TransformerException;
import javax.xml.transform.URIResolver;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamSource;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
50
51
import org.citygml4j.factory.GMLGeometryFactory;
import org.citygml4j.model.citygml.core.CityModel;
52
53
import org.w3c.dom.Document;

54
55
import de.hft.stuttgart.citydoctor2.check.error.AttributeMissingError;
import de.hft.stuttgart.citydoctor2.check.error.AttributeValueWrongError;
56
57
import de.hft.stuttgart.citydoctor2.check.error.SchematronError;
import de.hft.stuttgart.citydoctor2.checkresult.utility.CheckReportWriteException;
58
import de.hft.stuttgart.citydoctor2.checks.CheckPrototype;
59
60
61
import de.hft.stuttgart.citydoctor2.checks.Checks;
import de.hft.stuttgart.citydoctor2.checks.SvrlContentHandler;
import de.hft.stuttgart.citydoctor2.checks.util.FeatureCheckedListener;
62
63
import de.hft.stuttgart.citydoctor2.datastructure.BridgeObject;
import de.hft.stuttgart.citydoctor2.datastructure.Building;
64
65
66
import de.hft.stuttgart.citydoctor2.datastructure.CityDoctorModel;
import de.hft.stuttgart.citydoctor2.datastructure.CityObject;
import de.hft.stuttgart.citydoctor2.datastructure.FeatureType;
67
68
69
70
71
72
73
import de.hft.stuttgart.citydoctor2.datastructure.LandObject;
import de.hft.stuttgart.citydoctor2.datastructure.TransportationObject;
import de.hft.stuttgart.citydoctor2.datastructure.Vegetation;
import de.hft.stuttgart.citydoctor2.datastructure.WaterObject;
import de.hft.stuttgart.citydoctor2.parser.CityGmlConsumer;
import de.hft.stuttgart.citydoctor2.parser.CityGmlParseException;
import de.hft.stuttgart.citydoctor2.parser.CityGmlParser;
74
75
76
77
78
79
80
81
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
82
import de.hft.stuttgart.citydoctor2.utils.Localization;
83
84
85
86
87
88
89
90
91
92
93
import de.hft.stuttgart.citydoctor2.utils.QualityADEUtils;
import de.hft.stuttgart.quality.model.Validation;
import de.hft.stuttgart.quality.model.jaxb.Checking;
import de.hft.stuttgart.quality.model.jaxb.ErrorStatistics;
import de.hft.stuttgart.quality.model.jaxb.FeatureStatistics;
import de.hft.stuttgart.quality.model.jaxb.Parameter;
import de.hft.stuttgart.quality.model.jaxb.Requirement;
import de.hft.stuttgart.quality.model.jaxb.RequirementId;
import de.hft.stuttgart.quality.model.jaxb.Statistics;
import de.hft.stuttgart.quality.model.jaxb.TopLevelFeatureType;
import de.hft.stuttgart.quality.model.jaxb.ValidationPlan;
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
import net.sf.saxon.s9api.DOMDestination;
import net.sf.saxon.s9api.Destination;
import net.sf.saxon.s9api.Processor;
import net.sf.saxon.s9api.SAXDestination;
import net.sf.saxon.s9api.SaxonApiException;
import net.sf.saxon.s9api.XsltCompiler;
import net.sf.saxon.s9api.XsltExecutable;
import net.sf.saxon.s9api.XsltTransformer;

/**
 * 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;
	}
136

137
138
139
140
141
142
143
144
145
146
147
148
	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) {
149
		if (!model.isValidated() || xmlOutput == null) {
150
151
152
			return;
		}
		File xmlFile = new File(xmlOutput);
153
		if (xmlFile.getParentFile() == null) {
154
155
156
157
158
159
			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
160
			logger.error(Localization.getText("Checker.failXml"), e);
161
162
163
164
		}
	}

	public void writePdfReport(String pdfOutput) {
165
		if (!model.isValidated() || pdfOutput == null) {
166
167
168
			return;
		}
		File pdfFile = new File(pdfOutput);
169
		if (pdfFile.getParentFile() == null) {
170
171
172
173
174
175
			pdfFile.getParentFile().mkdirs();
		}
		Reporter reporter = new PdfReporter("assets/Logo.png");
		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
176
			logger.error(Localization.getText("Checker.failPdf"), e);
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
		}
	}

	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
206
207
208
		if (logger.isInfoEnabled()) {
			logger.info(Localization.getText("Checker.checksFinished"));
		}
209
210
		SvrlContentHandler handler = executeSchematronValidationIfAvailable(config, model.getFile());
		if (handler != null) {
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
			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);
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
			} else {
				handleSchematronErrorsForCityObject(v, co);
			}
		});
	}

	private static void handleSchematronErrorsForCityObject(List<SchematronError> v, CityObject co) {
		int count = 0;
		for (SchematronError se : v) {
			CheckError err;
			if (AttributeMissingError.ID.getIdString().equals(se.getErrorIdString())) {
				err = new AttributeMissingError(co, se.getChildId(), se.getNameOfAttribute(), se.isGeneric());
			} else if (AttributeValueWrongError.ID.getIdString().equals(se.getErrorIdString())) {
				err = new AttributeValueWrongError(co, se.getChildId(), se.getNameOfAttribute(), se.isGeneric());
			} else {
				throw new IllegalStateException(
						"Unknown error ID was given in schematron file: " + se.getErrorIdString());
			}
			co.addCheckResult(new CheckResult(new CheckId("" + count), ResultStatus.ERROR, err));
			count++;
		}
	}

	private ValidationPlan createValidationPlan() {
		ValidationPlan plan = new ValidationPlan();
		List<Checking> filter = createFilter();

		for (Entry<CheckId, CheckConfiguration> e : config.getChecks().entrySet()) {
			RequirementId reqId = mapToRequirement(e.getKey());
			if (reqId == null) {
				continue;
			}
			Requirement req = new Requirement();
			req.setName(reqId);
			req.setEnabled(e.getValue().isEnabled());
			plan.getRequirements().add(req);
			CheckPrototype proto = Checks.getCheckPrototypeForId(e.getKey());
			Map<String, String> parameters = e.getValue().getParameters();
			if (parameters != null) {
				for (Entry<String, String> param : parameters.entrySet()) {
					Parameter p = new Parameter();
					DefaultParameter defaultP = getDefaultParameter(param.getKey(), proto);
					if (defaultP != null) {
						p.setUom(defaultP.getUnitType().getGmlRepresentation());
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
					p.setName(param.getKey());
					p.setValue(param.getValue());
					req.getParameters().add(p);
				}
			}
		}

		Requirement missing = new Requirement();
		missing.setName(RequirementId.R_SEM_ATTRIBUTES_EXISTING);
		Requirement correct = new Requirement();
		correct.setName(RequirementId.R_SEM_ATTRIBUTES_CORRECT);
		missing.setEnabled(config.getSchematronFilePath() != null);
		correct.setEnabled(config.getSchematronFilePath() != null);
		plan.getRequirements().add(missing);
		plan.getRequirements().add(correct);

		plan.getFilter().addAll(filter);
		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());
		plan.getGlobalParameters().add(numRounding);
		plan.getGlobalParameters().add(minVertexDistance);
		plan.getGlobalParameters().add(schematronFile);
		return plan;
	}

	private DefaultParameter getDefaultParameter(String key, CheckPrototype proto) {
		for (DefaultParameter param : proto.getDefaultParameter()) {
			if (param.getName().equals(key)) {
				return param;
			}
		}
		return null;
	}

	private List<Checking> createFilter() {
		List<Checking> filter = new ArrayList<>();
		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;
329
					}
330
					removeFilter(tlft, filter);
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
			}
		}
		return filter;
	}

	private void handleInputFilter(List<Checking> filter) {
		if (includeFilters == null || includeFilters.isEmpty()) {
			// no filter means, use all
			addAllFilters(filter);
		} else {
			for (Filter f : includeFilters) {
				if (f instanceof TypeFilter) {
					TypeFilter tf = (TypeFilter) f;
					FeatureType type = tf.getType();
					TopLevelFeatureType tlft = mapToTopLevelFeatureType(type);
					if (tlft == null) {
						continue;
					}
					filter.add(new Checking(tlft));
				}
			}
			if (filter.isEmpty()) {
				// this happens if no type include filter was used
				// it is possible only single objects were tested then
				// so include everything
				addAllFilters(filter);
			}
		}
	}

	private void addAllFilters(List<Checking> filter) {
		filter.add(new Checking(TopLevelFeatureType.BUILDING));
		filter.add(new Checking(TopLevelFeatureType.BRIDGE));
		filter.add(new Checking(TopLevelFeatureType.LAND));
		filter.add(new Checking(TopLevelFeatureType.TRANSPORTATION));
		filter.add(new Checking(TopLevelFeatureType.VEGETATION));
		filter.add(new Checking(TopLevelFeatureType.WATER));
	}

	private void removeFilter(TopLevelFeatureType tlft, List<Checking> filter) {
		for (Checking c : filter) {
			if (c.getValue().equals(tlft)) {
				filter.remove(c);
				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;
		}
	}

	private RequirementId mapToRequirement(CheckId key) {
		switch (key.getName()) {
		case "C_GE_R_TOO_FEW_POINTS":
			return RequirementId.R_GE_R_TOO_FEW_POINTS;
		case "C_GE_R_NOT_CLOSED":
			return RequirementId.R_GE_R_NOT_CLOSED;
		case "C_GE_R_DUPLICATE_POINT":
			return RequirementId.R_GE_R_CONSECUTIVE_POINTS_SAME;
		case "C_GE_R_SELF_INTERSECTION":
			return RequirementId.R_GE_R_SELF_INTERSECTION;
		case "C_GE_P_INTERIOR_DISCONNECTED":
			return RequirementId.R_GE_P_INTERIOR_DISCONNECTED;
		case "C_GE_P_INTERSECTING_RINGS":
			return RequirementId.R_GE_P_INTERSECTING_RINGS;
		case "C_GE_P_NON_PLANAR":
			return RequirementId.R_GE_P_NON_PLANAR;
		case "C_GE_S_TOO_FEW_POLYGONS":
			return RequirementId.R_GE_S_TOO_FEW_POLYGONS;
		case "C_GE_S_NON_MANIFOLD_EDGE":
			return RequirementId.R_GE_S_NON_MANIFOLD_EDGE;
		case "C_GE_S_POLYGON_WRONG_ORIENTATION":
			return RequirementId.R_GE_S_POLYGON_WRONG_ORIENTATION;
		case "C_GE_S_ALL_POLYGONS_WRONG_ORIENTATION":
			return RequirementId.R_GE_S_ALL_POLYGONS_WRONG_ORIENTATION;
		case "C_GE_S_NON_MANIFOLD_VERTEX":
			return RequirementId.R_GE_S_NON_MANIFOLD_VERTEX;
		case "C_GE_S_SELF_INTERSECTION":
			return RequirementId.R_GE_S_SELF_INTERSECTION;
		case "C_GE_P_HOLE_OUTSIDE":
			return RequirementId.R_GE_P_HOLE_OUTSIDE;
		case "C_GE_P_INNER_RINGS_NESTED":
			return RequirementId.R_GE_P_INNER_RINGS_NESTED;
		case "C_GE_S_NOT_CLOSED":
			return RequirementId.R_GE_S_NOT_CLOSED;
		case "C_GE_S_MULTIPLE_CONNECTED_COMPONENTS":
			return RequirementId.R_GE_S_MULTIPLE_CONNECTED_COMPONENTS;
		default:
			return null;
437
438
		}
	}
439

440
441
442
	public ValidationConfiguration getConfig() {
		return config;
	}
443

444
	public static SvrlContentHandler executeSchematronValidationIfAvailable(ValidationConfiguration config, File file) {
445
		if (config.getSchematronFilePath() != null && !config.getSchematronFilePath().isEmpty()) {
Matthias Betz's avatar
Matthias Betz committed
446
447
448
			if (logger.isInfoEnabled()) {
				logger.info(Localization.getText("Checker.schematronValidation"));
			}
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
			Processor processor = new Processor(false);
			XsltCompiler xsltCompiler = processor.newXsltCompiler();
			xsltCompiler.setURIResolver(new URIResolver() {

				@Override
				public Source resolve(String href, String base) throws TransformerException {
					return new StreamSource(Checker.class.getResourceAsStream(href));
				}

			});
			try {
				XsltExecutable includeExecutable = xsltCompiler
						.compile(new StreamSource(Checker.class.getResourceAsStream("iso_dsdl_include.xsl")));
				XsltTransformer includeTransformer = includeExecutable.load();
				includeTransformer.setSource(new StreamSource(new File(config.getSchematronFilePath())));

				XsltExecutable expandExecutable = xsltCompiler
						.compile(new StreamSource(Checker.class.getResourceAsStream("iso_abstract_expand.xsl")));
				XsltTransformer expandTransformer = expandExecutable.load();
				includeTransformer.setDestination(expandTransformer);

				XsltExecutable xslt2Executable = xsltCompiler
						.compile(new StreamSource(Checker.class.getResourceAsStream("iso_svrl_for_xslt2.xsl")));

				XsltTransformer xslt2Transformer = xslt2Executable.load();
				expandTransformer.setDestination(xslt2Transformer);

				DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
				factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
				Document doc = factory.newDocumentBuilder().newDocument();
				DOMDestination domDestination = new DOMDestination(doc);
				xslt2Transformer.setDestination(domDestination);
				includeTransformer.transform();

				XsltExecutable schematronExecutable = xsltCompiler.compile(new DOMSource(doc));
				XsltTransformer schematronTransformer = schematronExecutable.load();
				schematronTransformer.setSource(new StreamSource(file));
				SvrlContentHandler handler = new SvrlContentHandler();
				Destination dest = new SAXDestination(handler);
				schematronTransformer.setDestination(dest);
				schematronTransformer.transform();
Matthias Betz's avatar
Matthias Betz committed
490
491
492
				if (logger.isInfoEnabled()) {
					logger.info(Localization.getText("Checker.finishedSchematron"));
				}
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
				return handler;
			} catch (SaxonApiException | ParserConfigurationException e) {
				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) {
		List<Check> checks = new ArrayList<>();
		for (Entry<CheckId, CheckConfiguration> e : config.getChecks().entrySet()) {
			if (e.getValue().isEnabled()) {
				Check c = checkConfig.getCheckForId(e.getKey());
576
577
				Map<String, String> parameters = new HashMap<>();
				parameters.putAll(e.getValue().getParameters());
578
				parameters.put("numberOfRoundingPlaces", "" + config.getNumberOfRoundingPlaces());
579
				parameters.put("minVertexDistance", "" + config.getMinVertexDistance());
580
				// initialize checks with parameters
581
				c.init(parameters, parserConfig);
582
583
584
585
586
587
588
589
590
591
592
593
				checks.add(c);
			}
		}
		return checks;
	}

	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 -> {
594
595
596
597
			if (config.getParserConfiguration().useLowMemoryConsumption()) {
				// no edges have been created yet, create them
				co.prepareForChecking();
			}
598
599
			// check every feature
			executeChecksForCityObject(co);
600

601
602
603
604
			if (config.getParserConfiguration().useLowMemoryConsumption()) {
				// low memory consumption, remove edges again
				co.clearMetaInformation();
			}
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
			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);
	}

	/**
	 * Executes all checks for the checkable. This will bypass the filters.
	 * 
	 * @param co the checkable.
	 */
	public void executeChecksForCheckable(Checkable co) {
		// throw away old results
		co.clearAllContainedCheckResults();
Matthias Betz's avatar
Matthias Betz committed
661
662
663
		if (logger.isDebugEnabled()) {
			logger.debug(Localization.getText("Checker.checkFeature"), co);
		}
664
665
		for (int i = 0; i < execLayers.size(); i++) {
			for (Check check : execLayers.get(i)) {
Matthias Betz's avatar
Matthias Betz committed
666
667
668
				if (logger.isTraceEnabled()) {
					logger.trace(Localization.getText("Checker.executeCheck"), check.getCheckId());
				}
669
670
671
672
673
				co.accept(check);
			}
		}
	}

Matthias Betz's avatar
Matthias Betz committed
674
	public static List<List<Check>> buildExecutionLayers(List<Check> checks) {
675
		List<List<Check>> result = new ArrayList<>();
676

Matthias Betz's avatar
Matthias Betz committed
677
678
		Set<Check> availableChecks = new HashSet<>(checks);
		Set<CheckId> usedChecks = new HashSet<>();
679

Matthias Betz's avatar
Matthias Betz committed
680
681
682
683
684
685
686
687
688
689
690
691
		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();
					layer.add(c);
				}
			}
			if (layer.isEmpty()) {
692
693
				throw new IllegalStateException(
						"There are checks that have dependencies that are not executed or are unknown");
Matthias Betz's avatar
Matthias Betz committed
694
695
696
697
			}
			result.add(layer);
			for (Check c : layer) {
				usedChecks.add(c.getCheckId());
698
699
700
701
702
			}
		}
		return result;
	}

Matthias Betz's avatar
Matthias Betz committed
703
704
705
706
707
708
709
	private static boolean searchForUnusedDependency(Set<CheckId> usedChecks, Check c) {
		boolean hasUnusedDependency = false;
		for (CheckId id : c.getDependencies()) {
			if (!usedChecks.contains(id)) {
				hasUnusedDependency = true;
				break;
			}
710
		}
Matthias Betz's avatar
Matthias Betz committed
711
		return hasUnusedDependency;
712
713
	}

714
715
716
	public static void streamCheck(File inputFile, String xmlOutput, String pdfOutput, ValidationConfiguration config,
			String outputFile) throws IOException, CityGmlParseException {
		streamCheck(inputFile, xmlOutput, pdfOutput, config, "assets/Logo.png", null, outputFile);
717
718
	}

719
720
721
	public static void streamCheck(File inputFile, String xmlOutput, String pdfOutput, ValidationConfiguration config,
			String logoLocation, FeatureCheckedListener l, String outputFile)
			throws IOException, CityGmlParseException {
722
723
		try (BufferedOutputStream xmlBos = getXmlOutputMaybe(xmlOutput);
				BufferedOutputStream pdfBos = getPdfOutputMaybe(pdfOutput)) {
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
			Checker c = new Checker(config, null);
			String fileName = inputFile.getName();
			
			// create reporter if available
			XmlStreamReporter xmlReporter = getXmlReporter(config, xmlBos, fileName);
			PdfStreamReporter pdfReporter = getPdfReporter(config, logoLocation, pdfBos, fileName);
			
			// create quality ade structures
			Validation val = new Validation();
			val.setValidationDate(ZonedDateTime.now());
			val.setValidationSoftware("CityDoctor " + Localization.getText(Localization.VERSION));
			Statistics statistics = new Statistics();
			FeatureStatistics buildingStatistics = new FeatureStatistics();
			statistics.setNumErrorBuildings(buildingStatistics);
			FeatureStatistics bridgeStatistics = new FeatureStatistics();
			statistics.setNumErrorBridgeObjects(bridgeStatistics);
			FeatureStatistics transportationStatistics = new FeatureStatistics();
			statistics.setNumErrorTransportation(transportationStatistics);
			FeatureStatistics vegetationStatistics = new FeatureStatistics();
			statistics.setNumErrorVegetation(vegetationStatistics);
			FeatureStatistics landStatistics = new FeatureStatistics();
			statistics.setNumErrorLandObjects(landStatistics);
			FeatureStatistics waterStatistics = new FeatureStatistics();
			statistics.setNumErrorWaterObjects(waterStatistics);
			
			// map for counting individual error counts
			Map<ErrorId, AtomicInteger> errorCount = new HashMap<>();
			GMLGeometryFactory gmlFactory = new GMLGeometryFactory();
			
			// execute schematron first
			SvrlContentHandler handler = executeSchematronValidationIfAvailable(config, inputFile);
			
			CityGmlConsumer con = new CityGmlConsumer() {
				@Override
				public void accept(CityObject co) {
					c.checkFeature(xmlReporter, pdfReporter, co);
					
					if (handler != null) {
						List<SchematronError> errors = handler.getFeatureErrors().get(co.getGmlId().getGmlString());
						if (errors != null) {
							handleSchematronErrorsForCityObject(errors, co);
						}
					}
					
					// remove existing quality ade datastructure if existing
					QualityADEUtils.removeValidationResult(co);
					// store quality ade datastructures in cityobject
					QualityADEUtils.writeQualityAde(co);
					// recreate geometry
					co.reCreateGeometries(gmlFactory, config.getParserConfiguration());
					
					// store result in statistics
					applyToStatistics(buildingStatistics, bridgeStatistics, transportationStatistics,
							vegetationStatistics, landStatistics, waterStatistics, co);

					// add errors to statistics
					List<CheckError> errorList = new ArrayList<>();
					co.collectContainedErrors(errorList);
					Set<CheckError> errors = new HashSet<>(errorList);
					for (CheckError e : errors) {
						errorCount.compute(e.getErrorId(), (k, v) -> {
							if (v == null) {
								return new AtomicInteger(1);
							}
							v.incrementAndGet();
							return v;
						});
					}

					if (l != null) {
						l.featureChecked(co);
					}
796
				}
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817

				@Override
				public void accept(CityModel cm) {
					QualityADEUtils.removeValidation(cm);
					for (Entry<ErrorId, AtomicInteger> e : errorCount.entrySet()) {
						ErrorStatistics stats = new ErrorStatistics();
						stats.setAmount(e.getValue().get());
						stats.setName(QualityADEUtils.mapErrorIdToAdeId(e.getKey()));
						statistics.getErrorStatistics().add(stats);
					}
					val.setStatistics(statistics);
					val.setValidationPlan(c.createValidationPlan());

					cm.addGenericApplicationPropertyOfCityModel(val);
				}
			};
			
			// parse and validate
			CityGmlParser.streamCityGml(inputFile, config.getParserConfiguration(), con, outputFile);
			
			// write reports if available
818
819
820
			writeReport(xmlReporter, handler);
			writeReport(pdfReporter, handler);
		} catch (CheckReportWriteException e) {
Matthias Betz's avatar
Matthias Betz committed
821
			logger.error(Localization.getText("Checker.failReports"), e);
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
	
	private static void applyToStatistics(FeatureStatistics buildingStatistics, FeatureStatistics bridgeStatistics,
			FeatureStatistics transportationStatistics, FeatureStatistics vegetationStatistics,
			FeatureStatistics landStatistics, FeatureStatistics waterStatistics, CityObject co) {
		if (co.isValidated()) {
			if (co instanceof Building) {
				countForFeatureStatistics(buildingStatistics, co);
			} else if (co instanceof TransportationObject) {
				countForFeatureStatistics(transportationStatistics, co);
			} else if (co instanceof BridgeObject) {
				countForFeatureStatistics(bridgeStatistics, co);
			} else if (co instanceof WaterObject) {
				countForFeatureStatistics(waterStatistics, co);
			} else if (co instanceof LandObject) {
				countForFeatureStatistics(landStatistics, co);
			} else if (co instanceof Vegetation) {
				countForFeatureStatistics(vegetationStatistics, co);
			}
		}
	}
	
	private static void countForFeatureStatistics(FeatureStatistics featureStatistics, CityObject co) {
		featureStatistics.setNumChecked(featureStatistics.getNumChecked() + 1);
		if (co.containsAnyError()) {
			featureStatistics.setNumErrors(featureStatistics.getNumErrors() + 1);
		}
	}

	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;
	}

	private static PdfStreamReporter getPdfReporter(ValidationConfiguration config, String logoLocation,
			BufferedOutputStream pdfBos, String fileName) {
		PdfStreamReporter pdfReporter;
		if (pdfBos != null) {
			pdfReporter = new PdfStreamReporter(pdfBos, fileName, config, logoLocation);
		} else {
			pdfReporter = null;
		}
		return pdfReporter;
	}
873

874
	public static void writeReport(StreamReporter reporter, SvrlContentHandler handler)
875
876
877
878
879
880
			throws CheckReportWriteException {
		if (reporter != null) {
			if (handler != null) {
				for (SchematronError err : handler.getGeneralErrors()) {
					reporter.reportGlobalError(err);
				}
881
882
883
884
				for (Entry<String, List<SchematronError>> e : handler.getFeatureErrors().entrySet()) {
					for (SchematronError se : e.getValue()) {
						reporter.addError(e.getKey(), se);
					}
885
886
887
888
889
890
				}
			}
			reporter.finishReport();
		}
	}

891
	public static BufferedOutputStream getPdfOutputMaybe(String pdfOutput) throws FileNotFoundException {
892
893
894
		return pdfOutput != null ? new BufferedOutputStream(new FileOutputStream(pdfOutput)) : null;
	}

895
	public static BufferedOutputStream getXmlOutputMaybe(String xmlOutput) throws FileNotFoundException {
896
897
898
		return xmlOutput != null ? new BufferedOutputStream(new FileOutputStream(xmlOutput)) : null;
	}

899
	public void checkFeature(XmlStreamReporter xmlReporter, PdfStreamReporter pdfReporter, CityObject co) {
Matthias Betz's avatar
Matthias Betz committed
900
901
902
		if (logger.isDebugEnabled()) {
			logger.debug(Localization.getText("Checker.checkFeature"), co);
		}
903
904
905
906
907
908
909
910
911
		executeChecksForCityObject(co);
		if (xmlReporter != null) {
			xmlReporter.report(co);
		}
		if (pdfReporter != null) {
			pdfReporter.report(co);
		}
	}
}