1 /* 2 * Copyright 2017 Google Inc. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * https://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package trebuchet.task 18 19 import trebuchet.extractors.ExtractorRegistry 20 import trebuchet.importers.ImportFeedback 21 import trebuchet.importers.ImporterRegistry 22 import trebuchet.io.BufferProducer 23 import trebuchet.io.StreamingReader 24 import trebuchet.model.Model 25 import trebuchet.model.fragments.ModelFragment 26 import kotlin.system.measureTimeMillis 27 28 class ImportTask(private val importFeedback: ImportFeedback) { 29 private val fragments = mutableListOf<ModelFragment>() 30 31 // TODO: Java doesn't like this since it collides with the 32 @JvmName("importTrace") importnull33 fun import(source: BufferProducer): Model { 34 extractOrImport(source) 35 return finish() 36 } 37 extractOrImportnull38 private fun extractOrImport(stream: BufferProducer) { 39 try { 40 val reader = StreamingReader(stream) 41 reader.loadIndex(reader.keepLoadedSize.toLong()) 42 val extractor = ExtractorRegistry.extractorFor(reader, importFeedback) 43 if (extractor != null) { 44 extractor.extract(reader, this::extractOrImport) 45 } else { 46 addImporterSource(reader) 47 } 48 } catch (ex: Throwable) { 49 importFeedback.reportImportException(ex) 50 } finally { 51 stream.close() 52 } 53 } 54 addImporterSourcenull55 private fun addImporterSource(reader: StreamingReader) { 56 val importer = ImporterRegistry.importerFor(reader, importFeedback) 57 if (importer != null) { 58 val result = importer.import(reader) 59 if (result != null) { 60 fragments.add(result) 61 } 62 } 63 } 64 finishnull65 private fun finish(): Model { 66 val model = Model(fragments) 67 fragments.clear() 68 return model 69 } 70 }