blob: 7eaecab5eb24c205ec473c5393beca0847e7431a [file] [log] [blame]
/*******************************************************************************
* Copyright (c) 2017 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:
* Alejandra Ruiz - initial development and documentation
* Huascar Espinoza - initial API
* 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.sam.arg.export.exportWizards;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
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.IAdaptable;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Platform;
import org.eclipse.emf.cdo.dawn.preferences.PreferenceConstants;
import org.eclipse.emf.cdo.dawn.util.connection.CDOConnectionUtil;
import org.eclipse.emf.cdo.eresource.CDOResource;
import org.eclipse.emf.cdo.eresource.impl.CDOResourceImpl;
import org.eclipse.emf.cdo.session.CDOSession;
import org.eclipse.emf.cdo.view.CDOView;
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.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.EStructuralFeature;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.util.EcoreUtil;
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.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.opencert.apm.baseline.baseline.BaselinePackage;
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.diagram.part.ArgDiagramEditorUtil;
import org.eclipse.opencert.sam.arg.arg.impl.CaseImpl;
import org.eclipse.ui.IExportWizard;
import org.eclipse.ui.IWorkbench;
import org.osgi.framework.Bundle;
public class ExportWizard extends Wizard implements IExportWizard {
ExportWizardPage mainPage;
private static Map<EObject, EObject> map = new HashMap<EObject, EObject>();
private static String ArgPack = "org.eclipse.opencert.sam.arg.arg";
private static String ArgBundle = "org.eclipse.opencert.sam.arg";
public ExportWizard() {
super();
}
/* (non-Javadoc)
* @see org.eclipse.jface.wizard.Wizard#performFinish()
*/
public boolean performFinish() {
//Now we create a new file
System.out.println("Modelo seleccionado: "+mainPage.selectedSource);
CDOConnectionUtil.instance.init(
PreferenceConstants.getRepositoryName(),
PreferenceConstants.getProtocol(),
PreferenceConstants.getServerName());
CDOSession sessionCDO = CDOConnectionUtil.instance.getCurrentSession();
CDOView viewCDO = CDOConnectionUtil.instance.openView(sessionCDO);
CDOResourceImpl resource = (CDOResourceImpl) viewCDO.getResource(mainPage.selectedSource.getPath());
String targetModelFile = mainPage.newFile;
System.out.println("targetModelFile:= ." + targetModelFile + ".");
URI modelOLocalURI = URI.createFileURI(mainPage.newFile);
createArgModel(modelOLocalURI, resource);
Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().put(
"arg", new GMFResourceFactory());
return true;
}
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){
System.out.println("createArgumentModel before map.clear");
map.clear();
for (EObject aEObject : modelCDO.getContents()) {
EObject bEObject = getCorrespondingEObject(aEObject, "ArgPackage");
if (bEObject != null)
modelResource.getContents().add(bEObject);
if(bEObject instanceof Case)
model=(CaseImpl) bEObject;
}
System.out.println("createArgumentModel 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, "ArgPackage");
if (bEObject != null)
copyAEObjectToBEObject(aEObject, bEObject, "ArgPackage");
}
}
attachModelToResource(model, modelResource);
try {
modelResource
.save(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;
}
private void attachModelToResource(EObject model,
Resource resource) {
resource.getContents().add(model);
}
private void setCharset(IFile file) {
if (file == null) {
return;
}
try {
file.setCharset("UTF-8", new NullProgressMonitor()); //$NON-NLS-1$
} catch (CoreException e) {
e.printStackTrace();
}
}
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;
}
@SuppressWarnings("unchecked")
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"))
{
String name = ((EEnumLiteral)aEObject.eGet(aFeature)).getInstance().getName();
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) {
System.out.println(" exception aFeature=." + aFeature.toString() + ". bFeature=." + bFeature.toString() + ". value=." + aEObject.eGet(aFeature).toString() + ".");
e.printStackTrace();
}
} else { // EReference
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);
}
}
}
}
}
}
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;
}
/* (non-Javadoc)
* @see org.eclipse.ui.IWorkbenchWizard#init(org.eclipse.ui.IWorkbench, org.eclipse.jface.viewers.IStructuredSelection)
*/
public void init(IWorkbench workbench, IStructuredSelection selection) {
setWindowTitle("Argumentation Model Export Wizard"); //NON-NLS-1
setNeedsProgressMonitor(true);
mainPage = new ExportWizardPage("Export as ARG File",selection); //NON-NLS-1
}
/* (non-Javadoc)
* @see org.eclipse.jface.wizard.IWizard#addPages()
*/
public void addPages() {
super.addPages();
addPage(mainPage);
}
}