Error on load EMF model dynamically - java

I am following the article http://www.ibm.com/developerworks/library/os-eclipse-dynamicemf/ to load dynamically metamodels.
I load the model instanced document using this
ResourceSet load_resourceSet = new ResourceSetImpl();
// ResourceSet load_resourceSet2 = new ResourceSetImpl();
/*
* Register XMI Factory impl ementation using DEFAULT_EXTENSION
*/
load_resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("*", //$NON-NLS-1$
new XMIResourceFactoryImpl());
/*
* Add bookStoreEPackage to package registry
*/
load_resourceSet.getPackageRegistry().put("http:///com.ibm.dynamic.example.bookstore.ecore",
bookStoreEPackage);
// load_resourceSet2.getResourceFactoryRegistry().getExtensionToFactoryMap().put("*", //$NON-NLS-1$
// new XMIResourceFactoryImpl());
/*
* Load the resources using the URI
*/
Resource modelo_esquerda = load_resourceSet
.getResource(URI.createURI("./BookStore.xmi"), true);
But, I´ve got this error message
Exception in thread "main" org.eclipse.emf.ecore.resource.impl.ResourceSetImpl$1DiagnosticWrappedException: org.eclipse.emf.ecore.xmi.ClassNotFoundException: Class 'BookStore' is not found or is abstract. (.\BookStore.xmi, 9, 34)
The XMI file already exists on directory.
What I can do?
Thank you

You can try the following, it worked well for me:
XMIResourceImpl resource = new XMIResourceImpl();
File source = new File(xmlName.xml);
resource.load(new FileInputStream(source), new HashMap<Object,Object>());
Data data = (Data) resource.getContents().get(0);
Where Data is your model.

Related

Implementation of JAXB-API has not been found on module path or classpath

I am using JAXB to convert between classes and XML and save and read to an XML document. I am working in Eclipse Oxygen.1a Release (4.7.1a) and I have included the jaxb-api-2.3.0.jar file to the project from here: https://mvnrepository.com/artifact/javax.xml.bind/jaxb-api/2.3.0 It looks like my implementation of the JAXB-API in Eclipse has not been done correctly. I am not sure how to do that. I just included the jar file hoping it will work.
Now my code throws an expectation Implementation of JAXB-API has not been found on module path or classpath.
/**
* Saves the current person data to the specified file.
*
* #param file
*/
public void savePersonDataToFile(File file) {
try {
JAXBContext context = JAXBContext
.newInstance(PersonListWrapper.class);
Marshaller m = (Marshaller) context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
// Wrapping our person data.
PersonListWrapper wrapper = new PersonListWrapper();
wrapper.setPersons(personData);
// Marshalling and saving XML to the file.
((Marshaller) m).marshal(wrapper, file);
// Save the file path to the registry.
setPersonFilePath(file);
} catch (Exception e) { // catches ANY exception
Alert alert = new Alert(AlertType.ERROR);
alert.setTitle("Error");
alert.setHeaderText("Could not save data");
//alert.setContentText("Could not save data to file:\n" + file.getPath());
alert.setContentText(e.getMessage());
alert.showAndWait();
}
}
I must be missing configurations.

Reading JSON-String using EMFJson

I am using EMFJson for serializing EMF Ecore Models. I am able to create a JSON String from an existing model. However, the way back is not working for me. I tried the following two snippets:
First Attempt:
ObjectMapper objectMapper = EMFModule.setupDefaultMapper();
objectMapper.reader().forType(MyClass.class).readValue(string);
Second Attempt:
ObjectMapper objectMapper = EMFModule.setupDefaultMapper();
ResourceSet resourceSet = new ResourceSetImpl();
resourceSet.getResourceFactoryRegistry()
.getExtensionToFactoryMap()
.put("json", new JsonResourceFactory());
try {
Resource resource = objectMapper
.reader()
.withAttribute(EMFContext.Attributes.RESOURCE_SET, resourceSet)
.withAttribute(EMFContext.Attributes.RESOURCE_URI, null)
.forType(Resource.class)
.readValue(string);
} catch (IOException e1) {
e1.printStackTrace();
}
For both attempts I am getting the following exception: java.lang.RuntimeException: Cannot create resource for uri default
I guess that the second approach cannot work at all as I do not know what to provide as RESOURCE_URI. The example here I took as foundation for attempt two reads a file rather than a string. Does somebody have an idea how to make this work? Thanks!
I managed to handle it using the answer given here: Parse XML in string format using EMF
The method with my changes looks like this:
private EObject loadEObjectFromString(String model, EPackage ePackage) throws IOException {
ResourceSet resourceSet = new ResourceSetImpl();
resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(Resource.Factory.Registry.DEFAULT_EXTENSION, new JsonResourceFactory());
resourceSet.getPackageRegistry().put(ePackage.getNsURI(), ePackage);
Resource resource = resourceSet.createResource(URI.createURI("*.extension"));
InputStream stream = new ByteArrayInputStream(model.getBytes(StandardCharsets.UTF_8));
resource.load(stream, null);
return resource.getContents().get(0);
}
Now I can call it like this:
EObject test = this.loadEObjectFromString(jsonString, MyPackage.eINSTANCE);

Error loading TTF file - Libgdx

I have created a android project with LibgdGdx where i create a AssetManager class, where I load all the assets I need, but when I run the project i have an error when a ttf file is loading. The code of the AssetManager:
public AssetManager manager;
public AssetsManager(){
manager = new AssetManager();
loadAssets();
}
public void loadAssets(){
loadTtf("assets/Birds.TTF");
}
void loadTtf(String path){
FileHandleResolver resolver = new InternalFileHandleResolver();
manager.setLoader(FreeTypeFontGenerator.class, new FreeTypeFontGeneratorLoader(resolver));
manager.setLoader(BitmapFont.class, "assets/Birds.TTF", new FreetypeFontLoader(resolver));
FreetypeFontLoader.FreeTypeFontLoaderParameter font = new FreetypeFontLoader.FreeTypeFontLoaderParameter();
font.fontFileName = path;
font.fontParameters.size = 20;
manager.load(path , BitmapFont.class, font);
}
I try to load the ttf file through this code
BitmapFont font = manager.manager.get("assets/Birds.TTF",BitmapFont.class);
Part of the error I have:
com.badlogic.gdx.utils.GdxRuntimeException: com.badlogic.gdx.utils.GdxRuntimeException: Error reading file: assets/Birds.TTF (Internal)
at com.badlogic.gdx.assets.AssetManager.handleTaskError(AssetManager.java:579)
at com.badlogic.gdx.assets.AssetManager.update(AssetManager.java:380)
at com.poum.game.Main.render(Main.java:33)
at com.badlogic.gdx.backends.android.AndroidGraphics.onDrawFrame(AndroidGraphics.java:459)
at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1649)
at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1354)
As i have said, the project is run on Android
Thank you for everything
String path="Birds.TTF"; //can be inside nested folder
String fileName = "Birds.TTF" ; // it can be any name with extension, will use to load and retrieve
Load in this way :
manager=new AssetManager();
FileHandleResolver resolver = new InternalFileHandleResolver();
manager.setLoader(FreeTypeFontGenerator.class, new FreeTypeFontGeneratorLoader(resolver));
manager.setLoader(BitmapFont.class, ".TTF", new FreetypeFontLoader(resolver));
FreetypeFontLoader.FreeTypeFontLoaderParameter parms = new FreetypeFontLoader.FreeTypeFontLoaderParameter();
parms.fontFileName = path; // path of .TTF file where that exist
parms.fontParameters.size = 20;
manager.load(fileName, BitmapFont.class, parms); // fileName with extension, sameName will use to get from manager
manager.finishLoading(); //or use update() inside render() method
Retrieve font from AssetManager
BitmapFont font=manager.get(fileName,BitmapFont.class);
EDIT
From your screenshot, I got your file name Birds.ttf not Birds.TTF
so change
String path = "Birds.ttf";
String fileName = "Birds.ttf"
Android file-system is case sensitive.
Run Configuration for desktop module should be like this :

Database driver-class dynamic loading

I want to develop a DB-Agnostic application in java. I have chosen hibernate as ORM. The problem with jdbc is that , it is just an interface and we need the driver class of the db in the class path. Since the database should be configurable i have to go for loading the driver class of DB dynamically. (User should keep the driver class in a folder and it should be loaded dynamically )
Below is my code.
File driverJar = new File("E:\\Jomon\\backup_2017_05_25\\2.2\\WS\\2.2_1\\lib\\Drivers\\postgresql-42.1.1.jar");
URL[] urls = new URL[] { driverJar.toURL() };
URLClassLoader classLoader = new URLClassLoader(urls,DBUtils.class.getClassLoader());
Class.forName("org.postgresql.Driver", true, classLoader);
No error till now.
But after this, while initializing hibernate connection, I am getting error java.lang.ClassNotFoundException: org.postgresql.Driver.
May I know what is the problem here.
Finally I got the solution by myself,
The problem here is , I have created a new classloader and loaded the jar into it.
The hibernate is searching for driver class in system class loader , not in the user defined class loaders.
The problem here can be solved by load the jar into system class loader as below.
File driverJar = new File("E:\\Jomon\\backup_2017_05_25\\2.2\\WS\\2.2_1\\lib\\Drivers\\postgresql-42.1.1.jar");
URL myJarFile = new URL("jar", "", "file:" + driverJar.getAbsolutePath() + "!/");
URLClassLoader sysLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
Class sysClass = URLClassLoader.class;
Method sysMethod = sysClass.getDeclaredMethod("addURL", new Class[] { URL.class });
sysMethod.setAccessible(true);
sysMethod.invoke(sysLoader, new Object[] { myJarFile });
Class.forName("org.postgresql.Driver", true, classLoader); // Now no error in this line.
Hibernate will always to attempt the load the driver from the current thread classloader and in your case, it doesn't have the driver.
You own class loader works fine and just before you initialize sessionFactory ,set your custom loader into contextClassLoader like this.
File f = new File( "E:\\Jomon\\backup_2017_05_25\\2.2\\WS\\2.2_1\\lib\\Drivers\\postgresql-42.1.1.jar" );
URLClassLoader urlCl = new URLClassLoader( new URL[] { f.toURL() }, System.class.getClassLoader() );
Class postGreDriver = urlCl.loadClass( "org.postgresql.Driver" );
System.out.println( postGreDriver.newInstance() );
Thread.currentThread().setContextClassLoader(postGreDriver);
//Hibernate can start
//you should restore your old classloader when hibernate services end
This may not be the best solution. Have got this snippet from this discussion
Hope this helps!!!

LibGDX - Couldn't load dependencies of FreetypeFont asset

Hi I'm currently stuck on trying to load a .ttf font, I'm getting a GdxRuntimeException with the message: Couldn't load dependencies of asset: coastershadowfont
FileHandleResolver resolver = new InternalFileHandleResolver();
assetManager.setLoader(FreeTypeFontGenerator.class, new FreeTypeFontGeneratorLoader(resolver));
assetManager.setLoader(BitmapFont.class, ".ttf", new FreetypeFontLoader(resolver));
FreetypeFontLoader.FreeTypeFontLoaderParameter params = new FreetypeFontLoader.FreeTypeFontLoaderParameter();
params.fontFileName = "fonts/coastershadow.ttf";
params.fontParameters.size = 30;
assetManager.load("coastershadowfont", BitmapFont.class, params);
try {
assetManager.finishLoadingAssets();
} catch (Exception exception) {
System.out.println(exception.toString());
}
Pass fileName with extension, when you call load(...) method on AssetManager. FileName should be anything with extension.
assetManager.load("coastershadowfont.ttf", BitmapFont.class, params); //Adds the given asset to the loading queue of the AssetManager.
assetManager.finishLoading(); // triggered to execute task
And get BitmapFont with fileName that you specified at loading time.
font= assetManager.get("coastershadowfont.ttf",BitmapFont.class);

Categories

Resources