blob: 935d51082aff319095a8d3c2b799a69210c839f6 [file] [log] [blame]
/*******************************************************************************
* Copyright (c) 2016 Fundación Tecnalia Research & Innovation.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v2.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/org/documents/epl-2.0/EPL-2.0.html
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Huascar Espinoza - initial API and implementation
* Alejandra Ruíz - initial API and implementation
* Idoya Del Río - initial API and implementation
* Mari Carmen Palacios - initial API and implementation
* Angel López - initial API and implementation
*******************************************************************************/
package org.eclipse.opencert.apm.assurproj.wizards.ui.wizards.Etl;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.operations.OperationHistoryFactory;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Platform;
import org.eclipse.emf.cdo.dawn.util.connection.CDOConnectionUtil;
import org.eclipse.emf.cdo.eresource.CDOResource;
import org.eclipse.emf.cdo.eresource.CDOResourceFolder;
import org.eclipse.emf.cdo.transaction.CDOTransaction;
import org.eclipse.emf.common.EMFPlugin;
import org.eclipse.emf.common.util.BasicEList;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.Enumerator;
import org.eclipse.emf.common.util.TreeIterator;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EEnum;
import org.eclipse.emf.ecore.EEnumLiteral;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.ecore.impl.DynamicEObjectImpl;
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.util.BasicExtendedMetaData;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.emf.ecore.util.ExtendedMetaData;
import org.eclipse.emf.ecore.xmi.XMLResource;
import org.eclipse.emf.ecore.xmi.impl.EcoreResourceFactoryImpl;
import org.eclipse.emf.ecore.impl.EEnumLiteralImpl;
import org.eclipse.emf.transaction.TransactionalEditingDomain;
import org.eclipse.emf.workspace.util.WorkspaceSynchronizer;
import org.eclipse.gmf.runtime.common.core.command.CommandResult;
import org.eclipse.gmf.runtime.emf.commands.core.command.AbstractTransactionalCommand;
import org.eclipse.gmf.runtime.emf.core.GMFEditingDomainFactory;
import org.eclipse.gmf.runtime.emf.core.resources.GMFResourceFactory;
import org.eclipse.opencert.apm.assurproj.assuranceproject.provider.AssuranceprojectEditPlugin;
import org.eclipse.opencert.apm.assurproj.wizards.Activator;
import org.eclipse.opencert.apm.baseline.baseline.BaseFramework;
import org.eclipse.opencert.apm.baseline.baseline.BaselineFactory;
import org.eclipse.opencert.apm.baseline.baseline.BaselinePackage;
import org.eclipse.opencert.apm.baseline.baseline.impl.BaseFrameworkImpl;
import org.eclipse.opencert.sam.arg.arg.ArgFactory;
import org.eclipse.opencert.sam.arg.arg.ArgPackage;
import org.eclipse.opencert.sam.arg.arg.Case;
import org.eclipse.opencert.sam.arg.arg.InformationElementType;
import org.eclipse.opencert.sam.arg.arg.impl.CaseImpl;
import org.osgi.framework.Bundle;
public class CDOTransformHandler {
// configuration params
// coming from class AssurProjInitializationHelper
private static final String UTF_8 = "UTF-8";
private static final String ARGUMENTATION = "Argumentation";
private static final String BASELINE = "baseline";
private static final String ARG = "arg";
private static String etlFile = "epsilon/Baseline2Arg.etl";
// ahora en dir HOME
//private static String modelIURI = "epsilon/model.baseline";
//private static String modelOURI = "epsilon/model.arg";
private static String modelIURI = "model.baseline";
private static String modelOURI = "model.arg";
private static String fileIURI = "model/baseline.ecore";
private static String fileOURI = "model/arg.ecore";
//private static String pluginInWorkSpace = "Dev-Workspace20140505";
//private static String pluginPath = "D:/Personal/Carmen/Proassurance/trabajo/" + pluginInWorkSpace + "/org.eclipse.opencert.apm.assurproj.wizards";
private static String pluginInWorkSpace = "";
private static String pluginPath = "";
private static String metamodelFiles = "";
private static String targetmetamodelFiles = "";
//CRF problem
private static String ArgPack = "org.eclipse.opencert.sam.arg.arg";
private static String ArgBundle = "org.eclipse.opencert.sam.arg";
//private static Object oldEPackage = null;
private static Object IoldEPackage = null;
private static Object OoldEPackage = null;
//CRF problem
// CDO
//private URI sourceModelURI;
private CDOResource targetModel;
private CDOResourceFolder project;
private EMFPlugin pluginProject;
private CDOTransaction transaction;
// files
private String sourceModelFile;
private String targetModelFile;
private Resource targetModelResource = null;
private static Map<EObject, EObject> map = new HashMap<EObject, EObject>();
private Object setUp(String fileURI) throws Exception {
Object oldEPackage = null;
// Register the metamodels
Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().put(
"ecore", new EcoreResourceFactoryImpl());
ResourceSet rs = new ResourceSetImpl();
// enable extended metadata
final ExtendedMetaData extendedMetaData = new BasicExtendedMetaData(rs.getPackageRegistry());
rs.getLoadOptions().put(XMLResource.OPTION_EXTENDED_META_DATA,
extendedMetaData);
Resource r = rs.getResource(URI.createURI(fileURI), true);
EObject eObject = r.getContents().get(0);
if (eObject instanceof EPackage) {
EPackage p = (EPackage)eObject;
Object oldEPackage2 = EPackage.Registry.INSTANCE.get(p.getNsURI());
if(oldEPackage2 != null)
{
oldEPackage = oldEPackage2;
}
EPackage.Registry.INSTANCE.put(p.getNsURI(), p);
}
//CRF problem
return oldEPackage;
}
//public CDOTransformHandler(CDOResourceFolder project, URI sourceModelURI, URI targetModelURI) {
public CDOTransformHandler(CDOResourceFolder project, CDOResource sourceModel, CDOResource targetModel, CDOTransaction transaction) {
try {
//RedirectSystemErr.init("D:\\Personal\\Carmen\\Proassurance\\trabajo\\runtime-201406\\.metadata\\err.txt");
this.project = project; // MCP: proyecto creado por el usuario
this.pluginProject = AssuranceprojectEditPlugin.INSTANCE; //getResourceLocator().getImage("full/obj16/AssuranceProject");// MCP: proyecto del plugin org.eclipse.opencert.apm.assurproj.wizards???!!!!
//this.sourceModelURI = sourceModelURI;
this.targetModel = targetModel;
this.transaction = transaction;
URL entry = null;
URL fileURL = null;
String file ="";
try {
// init config data
String spluginPath = Platform.getBundle(Activator.PLUGIN_ID).getLocation();
RedirectSystemErr.out("spluginPath:= ." + spluginPath + ".");
if(spluginPath.contains("plugins")) // si estoy en modo jar
{
//pluginPath = spluginPath.substring(0, spluginPath.indexOf("plugins"))+ "/configuration";
entry = Platform.getBundle(Activator.PLUGIN_ID).getEntry(fileIURI);
fileURL = FileLocator.resolve(entry);
file = fileURL.getFile();
//CRF file = file.replace(" ", "%20");// reemplazar caracter blanco
RedirectSystemErr.out("file:= ." + file + ".");
pluginPath = file.substring("file:/".length(), file.indexOf("plugins"))+ "configuration";
RedirectSystemErr.out("pluginPath:= ." + pluginPath + ".");
String sname = Platform.getBundle(Activator.PLUGIN_ID).getSymbolicName();
RedirectSystemErr.out("sname:= ." + sname + ".");
pluginInWorkSpace = "";
}
else
{
pluginPath = spluginPath.substring("reference:file:/".length(), spluginPath.length()-1); // eliminar ultimo caracter "/"
RedirectSystemErr.out("pluginPath:= ." + pluginPath + ".");
String sname = Platform.getBundle(Activator.PLUGIN_ID).getSymbolicName();
int index0 = pluginPath.lastIndexOf("/", pluginPath.length()-(sname.length()+2));
pluginInWorkSpace = pluginPath.substring(index0+1, pluginPath.lastIndexOf("/"));
}
RedirectSystemErr.out("pluginInWorkSpace:= ." + pluginInWorkSpace + ".");
String OS = System.getProperty("os.name").toLowerCase();
//In linux add the starting / to find the models
if ((OS.indexOf("nix") >= 0 || OS.indexOf("nux") >= 0 || OS.indexOf("aix") > 0 )){
pluginPath = "/" + pluginPath;
}
metamodelFiles=
pluginPath + "/model/general.ecore, " +
pluginPath + "/model/property.ecore, " +
pluginPath + "/model/Mapping.ecore, " +
pluginPath + "/model/refframework.ecore, " +
pluginPath + "/model/assuranceasset.ecore, " +
pluginPath + "/model/evidence.ecore, " +
pluginPath + "/model/baseline.ecore";
RedirectSystemErr.out("metamodelFiles:= ." + metamodelFiles + ".");
// metamodelo input
if(spluginPath.contains("plugins")) // si estoy en modo jar
{
entry = Platform.getBundle(Activator.PLUGIN_ID).getEntry(fileIURI);
fileURL = FileLocator.resolve(entry);
file = fileURL.getFile();
//CRF file = file.replace(" ", "%20");// reemplazar caracter blanco
RedirectSystemErr.out("metamodelo input0:= ." + file + ".");
String wrong = file.substring(file.indexOf("plugins"), file.indexOf("/"+fileIURI));
String file2 = file.replace(wrong, "configuration");
file = file2;
}
else
{
entry = Platform.getBundle(Activator.PLUGIN_ID).getEntry(fileIURI);
fileURL = FileLocator.resolve(entry);
file = "file:" + fileURL.getFile();
//CRF file = file.replace(" ", "%20");// reemplazar caracter blanco
}
RedirectSystemErr.out("metamodelo input:= ." + file + ".");
setUp(file);
//CRF problem
RedirectSystemErr.out("version CRF");
targetmetamodelFiles=
pluginPath + "/model/general.ecore, " +
pluginPath + "/model/property.ecore, " +
pluginPath + "/model/Mapping.ecore, " +
pluginPath + "/model/assuranceasset.ecore, " +
pluginPath + "/model/evidence.ecore, " +
pluginPath + "/model/arg.ecore";
RedirectSystemErr.out("targetmetamodelFiles:= ." + targetmetamodelFiles + ".");
//CRF problem
// metamodelo output
if(spluginPath.contains("plugins")) // si estoy en modo jar
{
entry = Platform.getBundle(Activator.PLUGIN_ID).getEntry(fileOURI);
fileURL = FileLocator.resolve(entry);
file = fileURL.getFile();
//CRF file = file.replace(" ", "%20");// reemplazar caracter blanco
RedirectSystemErr.out("metamodelo output0:= ." + file + ".");
String wrong = file.substring(file.indexOf("plugins"), file.indexOf("/"+fileOURI));
String file2 = file.replace(wrong, "configuration");
file = file2;
}
else
{
entry = Platform.getBundle(Activator.PLUGIN_ID).getEntry(fileOURI);
fileURL = FileLocator.resolve(entry);
file = "file:" + fileURL.getFile();
//CRF file = file.replace(" ", "%20");// reemplazar caracter blanco
}
RedirectSystemErr.out("metamodelo output:= ." + file + ".");
setUp(file);
// path ficheros temporales de modelo input y modelo output
String modelsPath = System.getProperty("user.home");
RedirectSystemErr.out("modelsPath:= ." + modelsPath + ".");
// modelo input (ahora en dir HOME)
//sourceModelFile = pluginPath + IPath.SEPARATOR + modelIURI;
sourceModelFile = modelsPath + IPath.SEPARATOR + modelIURI;
RedirectSystemErr.out("sourceModelFile:= ." + sourceModelFile + ".");
URI modelILocalURI = URI.createFileURI(sourceModelFile);
createBaselineModel(modelILocalURI, sourceModel);
// modelo output (ahora en dir HOME)
//targetModelFile = pluginPath + IPath.SEPARATOR + modelOURI;
targetModelFile = modelsPath + IPath.SEPARATOR + modelOURI;
RedirectSystemErr.out("targetModelFile:= ." + targetModelFile + ".");
URI modelOLocalURI = URI.createFileURI(targetModelFile);
targetModelResource = createArgModel(modelOLocalURI, null);
RedirectSystemErr.out(" created Arg model ");
} catch (IOException e) {
e.printStackTrace();
RedirectSystemErr.out("CDOTransformHandler Exception 1 ." + e.toString());
} catch (URISyntaxException e) {
e.printStackTrace();
RedirectSystemErr.out("CDOTransformHandler Exception 2 ." + e.toString());
}
Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().put(
//"baseline", new XMIResourceFactoryImpl());
BASELINE, new GMFResourceFactory());
Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().put(
//"arg", new XMIResourceFactoryImpl());
ARG, new GMFResourceFactory());
}
catch (Exception e)
{
e.printStackTrace();
RedirectSystemErr.out("CDOTransformHandler Exception 3 ." + e.toString());
}
}
/* copied from BaselineDiagramEditorUtil */
private void attachModelToResource(EObject model,
Resource resource) {
resource.getContents().add(model);
}
/* copied from BaselineDiagramEditorUtil */
private void setCharset(IFile file) {
if (file == null) {
return;
}
try {
file.setCharset("UTF-8", new NullProgressMonitor()); //$NON-NLS-1$
} catch (CoreException e) {
e.printStackTrace();
}
}
/* copied from BaselineDiagramEditorUtil */
private BaseFramework createBaselineInitialModel() {
return BaselineFactory.eINSTANCE.createBaseFramework();
}
private Resource createBaselineModel(URI modelURI, final CDOResource modelCDO) {
TransactionalEditingDomain editingDomain = GMFEditingDomainFactory.INSTANCE
.createEditingDomain();
/*
progressMonitor
.beginTask(
org.eclipse.opencert.apm.baseline.baseline.diagram.part.Messages.BaselineDiagramEditorUtil_CreateDiagramProgressTask,
3);
*/
final Resource modelResource = editingDomain.getResourceSet().createResource(modelURI);
AbstractTransactionalCommand command = new AbstractTransactionalCommand(
editingDomain,
"Create Baseline Model File",
Collections.EMPTY_LIST) {
protected CommandResult doExecuteWithResult(
IProgressMonitor monitor, IAdaptable info)
throws ExecutionException {
RedirectSystemErr.out("createBaselineModel before createBaselineInitialModel");
BaseFrameworkImpl model = (BaseFrameworkImpl)createBaselineInitialModel();
if(modelCDO != null)
{
RedirectSystemErr.out("createBaselineModel before map.clear");
//model.eContents().addAll(modelCDO.eContents());
//model.eResource().getContents().addAll(modelCDO.eContents());
/* CDO Native problema macheque baseline
model = (BaseFrameworkImpl) modelCDO.getContents().get(0);
*/
// CDO me obliga a duplicar el modelo
map.clear();
for (EObject aEObject : modelCDO.getContents()) {
EObject bEObject = getCorrespondingEObject(aEObject, "BaselinePackage");
if (bEObject != null) modelResource.getContents().add(bEObject);
}
RedirectSystemErr.out("createBaselineModel before iterator");
// Copy EObjects, containment in the resource is done automatically since we have
// already attached the corresponding root EObject to the target resource
for (Iterator<EObject> iterator = modelCDO.getAllContents(); iterator.hasNext();) {
EObject aEObject = iterator.next();
EObject bEObject = getCorrespondingEObject(aEObject, "BaselinePackage");
if (bEObject != null) copyAEObjectToBEObject(aEObject, bEObject, "BaselinePackage");
}
}
RedirectSystemErr.out("createBaselineModel before attachModelToResource");
attachModelToResource(model, modelResource);
try {
RedirectSystemErr.out("createBaselineModel before modelResource.save");
modelResource
.save(org.eclipse.opencert.apm.baseline.baseline.diagram.part.BaselineDiagramEditorUtil
.getSaveOptions());
} catch (IOException e) {
e.printStackTrace();
RedirectSystemErr.out("createBaselineModel exception e.=" + e.toString());
}
return CommandResult.newOKCommandResult();
}
};
try {
OperationHistoryFactory.getOperationHistory().execute(command, null, null);
} catch (ExecutionException e) {
e.printStackTrace();
RedirectSystemErr.out("createBaselineModel exception e.=" + e.toString());
}
setCharset(WorkspaceSynchronizer.getFile(modelResource));
return modelResource;
}
private Case createArgInitialModel() {
return ArgFactory.eINSTANCE.createCase();
}
private Resource createArgModel(URI modelURI, final CDOResource modelCDO) {
TransactionalEditingDomain editingDomain = GMFEditingDomainFactory.INSTANCE
.createEditingDomain();
final Resource modelResource = editingDomain.getResourceSet()
.createResource(modelURI);
AbstractTransactionalCommand command = new AbstractTransactionalCommand(
editingDomain,
"Create Argumentation Model File",
Collections.EMPTY_LIST) {
protected CommandResult doExecuteWithResult(
IProgressMonitor monitor, IAdaptable info)
throws ExecutionException {
CaseImpl model = (CaseImpl)createArgInitialModel();
if(modelCDO != null)
{
model = (CaseImpl) modelCDO.getContents().get(0);
}
attachModelToResource(model, modelResource);
try {
modelResource
.save(org.eclipse.opencert.sam.arg.arg.diagram.part.ArgDiagramEditorUtil
.getSaveOptions());
} catch (IOException e) {
e.printStackTrace();
}
return CommandResult.newOKCommandResult();
}
};
try {
OperationHistoryFactory.getOperationHistory().execute(command, null, null);
} catch (ExecutionException e) {
e.printStackTrace();
}
setCharset(WorkspaceSynchronizer.getFile(modelResource));
return modelResource;
}
// MCP
public Object execute() throws ExecutionException, IOException {
Object res = null;
EtlTransformParameters parameters = createTransformParameters(new EtlTransformParameters());
String sourceModelFilePath = sourceModelFile;
parameters.setSourceModelFilePath(sourceModelFilePath);
parameters.setTargetModelFilePath(targetModelFile);
//CRF problem
//parameters.setOldEPackages(oldEPackage);
parameters.setIOldEPackages(IoldEPackage);
parameters.setOOldEPackages(OoldEPackage);
//CRF problem
EtlTransformation service = new EtlTransformation(null);
service.createJob(parameters);
try {
// Modificar source baseline model para eliminar http://baseline/1.0
try {
// ahora en dir HOME
//URL entry = Platform.getBundle(Activator.PLUGIN_ID).getEntry(IPath.SEPARATOR + modelIURI);
//InputStream fileStream = entry.openStream();
String modelsPath = System.getProperty("user.home");
RedirectSystemErr.out("fileStream name:=." + modelsPath + IPath.SEPARATOR + modelIURI + ".");
FileInputStream fileStream = new FileInputStream(modelsPath + IPath.SEPARATOR + modelIURI);
RedirectSystemErr.out("fileStream:=." + fileStream.toString() + ".");
String fileContentI = new Scanner(fileStream,UTF_8).useDelimiter("\\A").next();
fileStream.close();
if(fileContentI.contains("xmlns:baseline=\"http://baseline/1.0\"")){
//String newfileContent = fileContentI.replaceAll("xmlns:baseline=\"http://baseline/1.0\"", "xmlns:baseline=\"baseline\"");
// Save the contents of the resource to the file system.
// ahora en dir HOME
//FileOutputStream fileOutStream = new FileOutputStream(pluginPath + IPath.SEPARATOR + modelIURI);
FileOutputStream fileOutStream = new FileOutputStream(modelsPath + IPath.SEPARATOR + modelIURI);
BufferedOutputStream outStream = new BufferedOutputStream(fileOutStream);
outStream.write(fileContentI.getBytes(UTF_8));
// Se fuerza el volcado del buffer a disco
outStream.flush();
outStream.close();
fileOutStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
RedirectSystemErr.out(" before service.execute() ");
// ejecutar transformacion
service.execute();
res = service.getResult();
RedirectSystemErr.out(" res :=." + res +".");
RedirectSystemErr.out(" before removing schema from arg model ");
// Modificar target arg model para eliminar esquema.
try {
RedirectSystemErr.out(" targetModelFile:=. " + targetModelFile + ".");
FileInputStream fileInStream = new FileInputStream(targetModelFile);
String fileContentO = new Scanner(fileInStream,UTF_8).useDelimiter("\\A").next();
fileInStream.close();
if(fileContentO.contains("xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"")){
String newfileContent = fileContentO.replaceAll("xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"", "");
newfileContent = newfileContent.replaceAll("xsi:schemaLocation=\"arg ../../../" + pluginInWorkSpace + "/org.eclipse.opencert.apm.assurproj.wizards/model/arg.ecore\"", "");
// Save the contents of the resource to the file system.
FileOutputStream fileOutStream = new FileOutputStream(targetModelFile);
BufferedOutputStream outStream = new BufferedOutputStream(fileOutStream);
outStream.write(newfileContent.getBytes(UTF_8));
// Se fuerza el volcado del buffer a disco
outStream.flush();
outStream.close();
fileOutStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
RedirectSystemErr.out(" before updating arg package ");
// restaurar paquete "arg"
//CRF problem
//EPackage p = (EPackage)oldEPackage;
EPackage p = (EPackage)OoldEPackage;
//CRF problem
if(p != null)
{
EPackage.Registry.INSTANCE.put(p.getNsURI(), p);
}
RedirectSystemErr.out(" before refreshing file content ");
// guardar el modelo transformado y disponible en fichero en CDO
// primero refrescar contenido creado por rules
if (targetModelResource.isLoaded()) {
targetModelResource.unload();
try {
targetModelResource.load(Collections.EMPTY_MAP);
}
catch (IOException exception) {
exception.printStackTrace();
}
}
ResourceSet resourceSet = new ResourceSetImpl();
URI resourceURI = targetModel.getURI();
RedirectSystemErr.out(" before creating CDO Arg model ");
/*
CDOTransaction transaction = CDOConnectionUtil.instance
.openCurrentTransaction(resourceSet,
resourceURI.toString());
*/
String diagramResourceStr = resourceURI.toString().substring("cdo://opencert".length(), resourceURI.toString().length());
CDOResource resource = transaction.getOrCreateResource(resourceURI.path());
EObject rootObject = createArgInitialModel();
//CRF problem
//CaseImpl argModel = (CaseImpl) targetModelResource.getContents().get(0);
EObject argModel = targetModelResource.getContents().get(0);
//CRF problem
if(argModel != null)
{
RedirectSystemErr.out(" argModel = ." + argModel.toString() + ".");
//rootObject = (EObject) argModel;
// CDO me obliga a duplicar el modelo
map.clear();
for (EObject aEObject : targetModelResource.getContents()) {
EObject bEObject = getCorrespondingEObject(aEObject, "ArgPackage");
if (bEObject != null) resource.getContents().add(bEObject);
}
// Copy EObjects, containment in the resource is done automatically since we have
// already attached the corresponding root EObject to the target resource
for (Iterator<EObject> iterator = targetModelResource.getAllContents(); iterator.hasNext();) {
EObject aEObject = iterator.next();
EObject bEObject = getCorrespondingEObject(aEObject, "ArgPackage");
if(bEObject != null) copyAEObjectToBEObject(aEObject, bEObject, "ArgPackage");
}
} else if (rootObject != null) {
resource.getContents().add(rootObject);
}
RedirectSystemErr.out(" before saving CDO Diagram Arg model ");
resource.save(Collections.EMPTY_MAP);
transaction.commit();
//transaction.close();
} catch (Exception e) {
e.printStackTrace();
}
RedirectSystemErr.end();
return res;
}
private Object getTypeProperty(EObject item) {
Object result = null;
for (EAttribute attribute : item.eClass().getEAllAttributes()) {
if (attribute.getName().equalsIgnoreCase("type")) {
result = (Object) item.eGet((EStructuralFeature) attribute);
break;
}
}
return result;
}
//CRF problem
Enumerator getEnum(String clase, String name)
{
Enumerator ret = null;
if(clase.contains("InformationElementCitation"))
{
//int value = ((EEnumLiteral)aEObject.eGet(aFeature)).getInstance(). getValue();
//String name = ((EEnumLiteral)aEObject.eGet(aFeature)).getInstance().getName();
//String literal = ((EEnumLiteral)aEObject.eGet(aFeature)).getInstance(). getLiteral();
InformationElementType tipo = InformationElementType.getByName(name);
ret = tipo;
}
return ret;
}
Enumerator getEnumByName(String myclass, Object whatInstance, String name)
{
Enumerator returnValue = null;
try {
// Step 2: Define a class to be loaded.
String classNameToBeLoaded = myclass;
/*
ClassLoader myClassLoader = ClassLoader.getSystemClassLoader();
// Step 3: Load the class
Class myClass = myClassLoader.loadClass(classNameToBeLoaded);
*/
String bundleStr = ArgBundle;
Bundle bundle = Platform.getBundle(bundleStr);
Class myClass = bundle.loadClass(classNameToBeLoaded);
// Step 5: get the method, with proper parameter signature.
// The second parameter is the parameter type.
// There can be multiple parameters for the method we are trying to call,
// hence the use of array.
Method myMethod = myClass.getMethod("getByName", new Class[] { String.class });
// Step 6:
// Calling the real method. Passing methodParameter as
// parameter. You can pass multiple parameters based on
// the signature of the method you are calling. Hence
// there is an array.
returnValue = (Enumerator) myMethod.invoke(whatInstance, new Object[] { name });
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return returnValue;
}
//CRF problem
/**
* Copies an {@link EObject} instance of a class of {@link APackage} to
* an {@link EObject} instance of a class of {@link BPackage} considering
* the well-known correspondences between both {@link EPackage}s
*
* @param aEObject source EObject
* @param bEObject target EObject
*/
private void copyAEObjectToBEObject(EObject aEObject, EObject bEObject, String type) {
for (EStructuralFeature aFeature : aEObject.eClass().getEAllStructuralFeatures()) {
if (aEObject.eIsSet(aFeature)) {
// Get the corresponding feature in the target EClass.
// Get simply the feature with the same name
EStructuralFeature bFeature = bEObject.eClass().getEStructuralFeature(aFeature.getName());
if(bFeature != null){
if (aFeature instanceof EAttribute) {
try {
//CRF problem
//bEObject.eSet(bFeature, aEObject.eGet(aFeature));
if (aEObject.eGet(aFeature).getClass().toString().contains("EEnumLiteralImpl"))
{
/* NO FUNCIONA!!!
EEnumLiteralImpl enumeration = (EEnumLiteralImpl) aEObject.eGet(aFeature);
bEObject.eSet(bFeature, enumeration.getInstance());
*/
/* NO FUNCIONA!!!
List<Enumerator> enumerators = new ArrayList<Enumerator> ();
EEnumLiteral enumeration = (EEnumLiteral) aEObject.eGet(aFeature);
enumerators.add(enumeration.getInstance());
bEObject.eSet(bFeature, enumerators.get(0));
*/
/* NO FUNCIONA!!!
TreeIterator<EObject> iterator = aEObject.eAllContents();
while (iterator.hasNext()) {
EObject item = iterator.next();
Object obj = getTypeProperty(item);
if(obj != null)
{
bEObject.eSet(bFeature, obj);
}
}
*/
/* FUNCIONA!!!
if(aEObject.eClass().getName().contains("InformationElementCitation"))
{
int value = ((EEnumLiteral)aEObject.eGet(aFeature)).getInstance(). getValue();
String name = ((EEnumLiteral)aEObject.eGet(aFeature)).getInstance().getName();
String literal = ((EEnumLiteral)aEObject.eGet(aFeature)).getInstance(). getLiteral();
InformationElementType tipo = InformationElementType.getByName(name);
bEObject.eSet(bFeature, tipo);
}
*/
/* FUNCIONA!!!
Enumerator newValue = getEnum(aEObject.eClass().getName(), ((EEnumLiteral)aEObject.eGet(aFeature)).getInstance().getName());
bEObject.eSet(bFeature, newValue);
*/
String name = ((EEnumLiteral)aEObject.eGet(aFeature)).getInstance().getName();
//Class clase = ((EEnumLiteral)aEObject.eGet(aFeature)).getInstance().getClass();
//Class clase = ((EObject)aEObject.eGet(aFeature)).eContainer().getClass();
EEnum objeto = (EEnum)((EObject)aEObject.eGet(aFeature)).eContainer();
String clase = objeto.getName();
Enumerator newValue = getEnumByName(ArgPack+"."+clase, objeto, name);
bEObject.eSet(bFeature, newValue);
}
else
{
bEObject.eSet(bFeature, aEObject.eGet(aFeature));
}
//CRF problem
} catch (Exception e) {
RedirectSystemErr.out(" exception aFeature=." + aFeature.toString() + ". bFeature=." + bFeature.toString() + ". value=." + aEObject.eGet(aFeature).toString() + ".");
e.printStackTrace();
}
} else { // EReference
@SuppressWarnings({ "unchecked" })
EList<EObject> aList = new BasicEList<EObject>();
if(aEObject.eGet(aFeature) instanceof EList)
{
aList = (EList<EObject>)aEObject.eGet(aFeature);
EList<EObject> bList = new BasicEList<EObject>();
for (int i = 0; i < aList.size(); i++) {
EObject objTemp = getCorrespondingEObject(aList.get(i), type);
if (objTemp != null) bList.add(objTemp);
}
bEObject.eSet(bFeature, bList);
}
else
{
EObject objTemp = getCorrespondingEObject((EObject)aEObject.eGet(aFeature), type);
if (objTemp != null) bEObject.eSet(bFeature, objTemp);
}
}
}
}
}
}
/**
* Returns the {@link EObject} an {@link EObject} instance of a class of
* {@link BPackage} that corresponds to an {@link EObject} instance of a
* class of {@link APackage}
*
* @param eObject
* @return
*/
private EObject getCorrespondingEObject(EObject aEObject, String type) {
EObject bEObject = map.get(aEObject);
if (bEObject == null) {
EClass aEClass = aEObject.eClass();
// We know that all class names of APackage start with "Prefix"
// APackage.PrefixA <--> Bpackage.B
// First change the prefix
String bClassName = aEClass.getName();
// Second search the corresponding EClass in BPackage
EClass bEClass = null;
if(type.contains("ArgPackage"))
bEClass = (EClass) ArgPackage.eINSTANCE.getEClassifier(bClassName);
else if(type.contains("BaselinePackage"))
bEClass = (EClass) BaselinePackage.eINSTANCE.getEClassifier(bClassName);
if(bEClass == null)
{
System.out.println("getCorrespondingEObject error: type =." + type +". & bClassName =." + bClassName + ".");
return null;
}
// Create a new empty instance and register to avoid dups
bEObject = EcoreUtil.create(bEClass);
map.put(aEObject, bEObject);
}
return bEObject;
}
// MCP
public EtlTransformParameters createTransformParameters(EtlTransformParameters etlTransformParameters)
{
etlTransformParameters.setPluginID(Activator.PLUGIN_ID);
// reglas
etlTransformParameters.setEtlTransform(etlFile);
//metamodelos input
etlTransformParameters.setSourceMetaModelFilePath(metamodelFiles);
etlTransformParameters.setSourceName("Baseline");
etlTransformParameters.setSourceReadOnLoad(true);
etlTransformParameters.setSourceStoreOnDisposal(false);
//modelo output
//CRF problem
//etlTransformParameters.setTargetMetaModelURI(ARG);
etlTransformParameters.setTargetMetaModelFilePath(targetmetamodelFiles);
//CRF problem
etlTransformParameters.setTargetName("Arg");
etlTransformParameters.setTargetReadOnLoad(false);
etlTransformParameters.setTargetStoreOnDisposal(true);
return etlTransformParameters;
}
}