| /** |
| * ******************************************************************************* |
| * Copyright (c) 2020 Robert Bosch GmbH. |
| * |
| * This program and the accompanying materials are made |
| * available under the terms of the Eclipse Public License 2.0 |
| * which is available at https://www.eclipse.org/legal/epl-2.0/ |
| * |
| * SPDX-License-Identifier: EPL-2.0 |
| * |
| * Contributors: |
| * Robert Bosch GmbH - initial API and implementation |
| * ******************************************************************************* |
| */ |
| |
| package org.eclipse.app4mc.slg.config.util; |
| |
| import java.io.File; |
| import java.io.IOException; |
| |
| import org.eclipse.app4mc.slg.config.ConfigModel; |
| import org.eclipse.app4mc.slg.config.ConfigurationPackage; |
| import org.eclipse.emf.common.util.EList; |
| import org.eclipse.emf.common.util.URI; |
| import org.eclipse.emf.ecore.EObject; |
| import org.eclipse.emf.ecore.resource.Resource; |
| import org.eclipse.emf.ecore.resource.ResourceSet; |
| import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl; |
| import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl; |
| import org.slf4j.Logger; |
| import org.slf4j.LoggerFactory; |
| |
| public class ConfigurationFileLoader { |
| |
| private static final Logger LOG = LoggerFactory.getLogger(ConfigurationFileLoader.class); |
| |
| public ConfigModel loadConfigurationFile(String filePath) { |
| |
| ResourceSet resourceSet = new ResourceSetImpl(); |
| resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap() |
| .put(Resource.Factory.Registry.DEFAULT_EXTENSION, new XMIResourceFactoryImpl()); |
| |
| resourceSet.getPackageRegistry().put(ConfigurationPackage.eNS_URI, ConfigurationPackage.eINSTANCE); |
| |
| File file = new File(filePath); |
| |
| try { |
| String path = file.getCanonicalPath(); |
| URI uri = file.isFile() ? URI.createFileURI(path) : URI.createURI(path); |
| Resource resource = resourceSet.getResource(uri, true); |
| LOG.info("Loaded {}", uri); |
| |
| // Validate the contents of the loaded resource. |
| // |
| EList<EObject> contents = resource.getContents(); |
| |
| if (! contents.isEmpty()) { |
| EObject eObject = contents.get(0); |
| if (eObject instanceof ConfigModel) { |
| return (ConfigModel) eObject; |
| } |
| } |
| } catch (RuntimeException | IOException exception) { |
| LOG.error("Error loading configuration file : {}", exception.getMessage()); |
| } |
| |
| return null; |
| } |
| |
| } |