Epsilon Model Migration (Flock) - Full Copy - eclipse

in the webpage of Epsilon Model Migration Language (https://www.eclipse.org/epsilon/doc/flock/) there is the description of the "Full Copy" primitive. I want to use it to copy a model in the simplest possible way, generating a new model with another name (but essentially is a full copy of the first one). Can you show me some pieces of code? Is my first time with Epsilon. Thanks.

Below is a minimal example that demonstrates running Flock from Java to migrate an EMF-based tree model. The complete Maven project is in Epsilon's Git repo.
package org.eclipse.epsilon.examples.standalone.flock;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.eclipse.epsilon.emc.emf.EmfModel;
import org.eclipse.epsilon.flock.FlockModule;
public class FlockStandaloneExample {
public static void main(String[] args) throws Exception {
Path root = Paths.get(FlockStandaloneExample.class.getResource("").toURI()),
modelsRoot = root.getParent().resolve("models");
// Set up the original model
EmfModel original = new EmfModel();
original.setName("Source");
original.setReadOnLoad(true);
original.setStoredOnDisposal(false);
original.setMetamodelFile(modelsRoot.resolve("Tree.ecore").toAbsolutePath().toString());
original.setModelFile(modelsRoot.resolve("Tree.xmi").toAbsolutePath().toString());
original.load();
// Set up the migrated model
EmfModel migrated = new EmfModel();
migrated.setName("Migrated");
migrated.setReadOnLoad(false);
migrated.setStoredOnDisposal(true);
migrated.setMetamodelFile(modelsRoot.resolve("Tree.ecore").toAbsolutePath().toString());
migrated.setModelFile(modelsRoot.resolve("Tree.migrated.xmi").toAbsolutePath().toString().replace("/target/classes/", "/src/"));
migrated.load();
// Run the migration transformation
FlockModule module = new FlockModule();
module.parse(root.resolve("tree2tree.mig"));
module.getContext().getModelRepository().addModel(original);
module.getContext().getModelRepository().addModel(migrated);
module.getContext().setOriginalModel(original);
module.getContext().setMigratedModel(migrated);
module.execute();
// Save the migrated model
module.getContext().getModelRepository().dispose();
}
}

Related

Can we customize mapping file names in Wiremock?

I am recording the application through Wiremock using JAVA DSL, Do we have the option to customize the mapping file names? instead of getting the filename which is generated from wiremock..
Example: searchpanel_arrivalairport_th-72f9b8b7-076f-4102-b6a8-aa38710fde1b.json (Generated form wiremock using java )
I am expecting the above file name with my desired naming convention like
seacrpanel_airport_LGW.json
Custom filenames can be added by customizing StubMappingJsonRecorder.
I added CustomStubMappingJsonRecorder and override writeToMappingAndBodyFile method.
if(fileName!=null && !fileName.equals("")){
mappingFileName=fileName+"-mapping.json";
bodyFileName=fileName+"-body.json";
}else {
mappingFileName = UniqueFilenameGenerator.generate(request.getUrl(),
"mapping", filed);
bodyFileName = UniqueFilenameGenerator.generate(request.getUrl(), "body",
fileId, ContentTypes.determineFileExtension(request.getUrl(),
response.getHeaders().getContentTypeHeader(), body));
}
There's no easy way to do this at the moment. It is however possible. As #santhiya-ps says you need to write your own implementation of RequestListener, probably using StubMappingJsonRecorder as a template.
You can't extend it and override writeToMappingAndBodyFile as that method is private, but that is the method you probably want to change.
import com.github.tomakehurst.wiremock.common.*;
import com.github.tomakehurst.wiremock.core.*;
import com.github.tomakehurst.wiremock.http.*;
import java.util.List;
import static com.github.tomakehurst.wiremock.core.WireMockApp.*;
class NameTemplateStubMappingJsonRecorder implements RequestListener {
private final FileSource mappingsFileSource;
private final FileSource filesFileSource;
private final Admin admin;
private final List<CaseInsensitiveKey> headersToMatch;
private final IdGenerator idGenerator = new VeryShortIdGenerator();
public NameTemplateStubMappingJsonRecorder(Admin admin) {
this.mappingsFileSource = admin.getOptions().filesRoot().child(MAPPINGS_ROOT);
this.filesFileSource = admin.getOptions().filesRoot().child(FILES_ROOT);
this.admin = admin;
this.headersToMatch = admin.getOptions().matchingHeaders();
}
#Override
public void requestReceived(Request request, Response response) {
// TODO copy StubMappingJsonRecorder changing as required...
}
}
You can then register your RequestListener as so:
WireMockServer wireMockServer = new WireMockServer();
wireMockServer.addMockServiceRequestListener(
new NameTemplateStubMappingJsonRecorder(wireMockServer)
);
wireMockServer.start();
So long as you still store the mapping files in the expected directory (stored in FileSource mappingsFileSource above, which will be ${rootDir}/mappings, where rootDir is configured as explained in Configuration - File Locations) they should be loaded successfully as all files with extension json in that dir are loaded as mappings.
It would be much easier if StubMappingJsonRecorder took a strategy for generating these names - it might be worth creating an issue on the WireMock repo asking for an easier way to do this. I'd suggest getting an agreement on a basic design before raising a PR though.

de.hybris.eventtracking.model.events.AbstractTrackingEvent cannot be resolved to a type

I just finished configuring hybris and tried to set up the eclipse project. As per guidelines in the wiki.hybris, I imported all the extensions into the eclipse project. When I try into build and clean, I get more than 3000 compiler errors. One of the errors is the class AbstractTrackingEvent cannot be resolved to a type. I looked for the particular class in the project folder. I could not find the folder events under de.hybris.eventtracking.model, which is the cause of the issue.
Am I missing anything while importing the project? There are many such type of issues in my eclipse project. Please let me know how to fix it. I have attached the screenshot for reference.
Note: I am using hybris-commerce-suite 5.7.0.8
As requested, I am adding the source code.
package de.hybris.eventtracking.services.populators;
import de.hybris.eventtracking.model.events.AbstractTrackingEvent;
import de.hybris.eventtracking.services.constants.TrackingEventJsonFields;
import de.hybris.platform.servicelayer.dto.converter.ConversionException;
import java.io.IOException;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* #author stevo.slavic
*
*/
public abstract class AbstractTrackingEventGenericPopulator implements
GenericPopulator<Map<String, Object>, AbstractTrackingEvent>
{
private final ObjectMapper mapper;
public AbstractTrackingEventGenericPopulator(final ObjectMapper mapper)
{
this.mapper = mapper;
}
public ObjectMapper getMapper()
{
return mapper;
}
protected Map<String, Object> getPageScopedCvar(final Map<String, Object> trackingEventData)
{
final String cvar = (String) trackingEventData.get(TrackingEventJsonFields.COMMON_CVAR_PAGE.getKey());
Map<String, Object> customVariablesPageScoped = null;
if (StringUtils.isNotBlank(cvar))
{
try
{
customVariablesPageScoped = getMapper().readValue(cvar, Map.class);
}
catch (final IOException e)
{
throw new ConversionException("Error extracting custom page scoped variables from: " + cvar, e);
}
}
return customVariablesPageScoped;
}
}
"As per guidelines in the wiki.hybris, I imported all the extensions into the eclipse project."
I don't think the guidelines tell you this. Basically, you want the projects loaded to be the same as those defined in your localextensions.xml and their dependencies. The reason you can't see those is they are not built.
Ensure you have run 'ant build' successfully, refresh the platform project, remove any extensions from your workspace that are not needed for your project, and clean and build in eclipse.
Make sure you have provided the project dependencies in each project by checking their individual extensioninfo.xml files as shown in below image.
Also sometimes dependent libraries are not imported properly check for those too.

Manipulate owl file using Protege-OWL API.(delete classes,delete properties)

I need to manipulate owl file using the Protege-Owl API. You know, creating classes and properties isn't too difficult.But I don't know how to delete a class or property.If we treat the owl file as a graph, deleting an class means deleting an node and its direct edge.For exemple:
<owl:unionOf rdf:parseType="Collection">
<rdf:Description rdf:about="&data;DataBundle"/>
<rdf:Description rdf:about="&data;DataItem"/>
</owl:unionOf>
if I want to delete the class DataItem,
how should I do it using Protege-OWL API? Does RDFResource.delete()can achieve this? I have tried it,but I can't achieve this,maybe there is something wrong.
what will I get after I delete the DataItem?
If DataItem is the domain of an property, what will I get after I delete it?
I hope to get your answer.
Edit: the Protege OWL API is the api described here, not the OWL API described here.
#Joshua Taylor,Thank you for your answer!I'm a new user and I make a mistake for posting this problem twice.Sorry for that.I make some mistakes in my code at first and today I tried to fix it.The following codes can delete a class or property.
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URI;
import edu.stanford.smi.protegex.owl.ProtegeOWL;
import edu.stanford.smi.protegex.owl.jena.JenaOWLModel;
import edu.stanford.smi.protegex.owl.model.RDFResource;
public class DeleteClass {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
//get model from an owl file
String filePath = "D:\\ss.owl";
FileInputStream inFile= new FileInputStream(filePath);
Reader in = new InputStreamReader(inFile,"UTF-8");
JenaOWLModel jenaOwlModel = ProtegeOWL.createJenaOWLModelFromReader(in);
//get an class from the model
RDFResource oneClass=jenaOwlModel.getRDFResource("Person");
RDFResource oneDataProperty=jenaOwlModel.getRDFResource("age");
//delete the resource
oneClass.delete();
oneDataProperty.delete();
//save the model to another owl file
URI file=URI.create("file:///D:/ssChange.owl");
System.out.println(file);
jenaOwlModel.save(file);
//System.out.println(oneClass);
}
}

MEF Composition .NET 4.0

Thanks in advance for your assistance. I have the following exported part:
[Export (typeof(INewComponent))] // orignally tried just [Export} here and importing NewComponent below
public class NewComponent : INewComponent
{
// does stuff including an import
}
The Console test program imports the above:
public class Program
{
[Import] // have tried variations on importing "NewComponent NewComponent" etc
public INewComponent NewComponent
{
get;
set;
}
public static void Main(string[] args)
{
var p = new Program();
var catalog = new AssemblyCatalog(typeof(Program).Assembly);
var container = new CompositionContainer(catalog);
container.ComposeParts(p);
}
The Composition fails with these CompositionExceptions (I removed the namespace to protect the guilty :)):
1) No valid exports were found that match the constraint
'((exportDefinition.ContractName == "INewComponent") AndAlso
(exportDefinition.Metadata.ContainsKey("ExportTypeIdentity") AndAlso
"INewComponent".Equals(exportDefinition.Metadata.get_Item("ExportTypeIdentity"))))',
invalid exports may have been rejected.
The Composition works successfully if I do the composition in the main program like this:
public class Program
{
public static void Main(string[] args)
{
INewComponent newComponent = new NewComponent();
var catalog = new AssemblyCatalog(typeof(Program).Assembly);
var container = new CompositionContainer(catalog);
container.ComposeParts(newComponent);
}
}
Thank You
Is your Exported part contained in the same Assembly as Program? If it is in a separate DLL, you need to include that Assembly in your catalog as well, like this:
var aggregateCatalog = new AggregateCatalog();
aggregateCatalog.Catalogs.Add(new AssemblyCatalog(typeof(Program).Assembly));
aggregateCatalog.Catalogs.Add(new AssemblyCatalog(typeof(NewComponent).Assembly));
var container = new CompositionContainer(aggregateCatalog);
// etc...
If that's doesn't work, then there is a nice open source tool called Visual MEFx that can help you analyze your catalog. Here is a short article about setting it up:
Getting Started With Visual MEFx
In your NewComponent class you wrote this:
// does stuff including an import
If there is a problem with that unshown import, then MEF will complain about the Program.NewComponent import instead of the actual deeper cause. This is called "stable composition". Stable composition can be useful, but it also complicates the debugging of a failed composition.
You can follow the instructions in the MEF documentation about Diagnosing Composition Errors to home in on the actual cause.
In a small program, you can also try to call container.GetExportedValue<ISomeExport>() for a few exports until you find the one that is causing problems.

MEF: how to import from an exported object?

I have created a MEF plugin control that I import into my app. Now, I want the plugin to be able to import parts from the app. I can't figure how setup the catalog in the plugin, so that it can find the exports from the app. Can somebody tell me how this is done? Below is my code which doesn't work when I try to create an AssemblyCatalog with the current executing assembly.
[Export(typeof(IPluginControl))]
public partial class MyPluginControl : UserControl, IPluginControl
[Import]
public string Message { get; set; }
public MyPluginControl()
{
InitializeComponent();
Initialize();
}
private void Initialize()
{
AggregateCatalog catalog = new AggregateCatalog();
catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
CompositionContainer container = new CompositionContainer(catalog);
try
{
container.ComposeParts(this);
}
catch (CompositionException ex)
{
Console.WriteLine(ex.ToString());
}
}
}
You don't need to do this.
Just make sure that the catalog you're using when you import this plugin includes the main application's assembly.
When MEF constructs your type in order to export it (to fulfill the IPluginControl import elsewhere), it'll already compose this part for you - and at that point, will import the "Message" string (though, you most likely should assign a name to that "message", or a custom type of some sort - otherwise, it'll just import a string, and you can only use a single "string" export anywhere in your application).
When MEF composes parts, it finds all types matching the specified type (in this case IPluginControl), instantiates a single object, fills any [Import] requirements for that object (which is why you don't need to compose this in your constructor), then assigns it to any objects importing the type.