blob: bdca3a8c0bf450559805ffc82f2f4ff7f829f838 [file] [log] [blame]
/**
* *******************************************************************************
* Copyright (c) 2020, 2021 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;
public final class ConfigurationFileLoader {
public static 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);
// 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) {
throw new IllegalStateException("Error on loading configuration file", exception);
}
return null;
}
}