Applying Eclipse Papyrus Designer stereotypes programmatically - eclipse

I have created a java program that uses Eclipse UML2 to load a .uml file and perform a model translation that (amongst other things) applies Papyrus Designer stereotypes (Codegen and C_Cpp profiles). Papyrus Designer can then be used to load the resulting model and generate cpp. I have successfully used the plugin jars as libraries in a standard java project, but I'm having problems transitioning to an Eclipse plugin project. The pertinent code is:
Profile codegenProfile = loadProfile(codegenProfileUri); // loads the profile resource from its plugin jar and returns the org.eclipse.uml2.uml.Profile
codegenProfile.define();
...
model.applyProfile(codegenProfile);
...
final Stereotype listHint = codegenProfile.getOwnedStereotype("ListHint");
model.applyStereotype(listHint);
// etc
I have to define() the profile to avoid an exception when applying the profile:
java.lang.IllegalArgumentException: profile "C_Cpp" has no Ecore definition
In my plugin version of the project I load the profile ok but get an exception when applying the stereotype:
java.lang.IllegalArgumentException: org.eclipse.uml2.uml.internal.impl.StereotypeImpl#540dcfba (name: ListHint, visibility: <unset>) (isLeaf: false, isAbstract: false, isFinalSpecialization: false) (isActive: false)
at org.eclipse.uml2.uml.internal.operations.ElementOperations.setValue(ElementOperations.java:667)
at org.eclipse.uml2.uml.internal.impl.ElementImpl.setValue(ElementImpl.java:307)
Looking at ElementOperations, the problem is in:
EObject eObject = element.getStereotypeApplication(stereotype);
if (eObject == null) {
throw new IllegalArgumentException(String.valueOf(stereotype));
}
which suggests the profile has not been properly initialised

Related

UIMA Ruta Workbench with Maven and DKPro Core

I'm trying to use DKPro Core components within the RUTA workbench, as in the following example with the german novel: https://github.com/pkluegl/ruta
IMPORT PACKAGE de.tudarmstadt.ukp.dkpro.core.api.lexmorph.type.pos FROM desc.type.POS AS pos;
IMPORT de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Lemma FROM desc.type.LexicalUnits;
Maven properly get the dependencies from DKPro Core. While I'm able to execute the main ruta script within Eclipse and to get the xmi file in the output directory, I'm unable to open this xmi file in the annotation browser:
Caused by: XCASParsingException: Error parsing XCAS or XMI-CAS from source <unknown> at line <unknown>, column <unknown>: unknown type: de.tudarmstadt.ukp.dkpro.core.api.metadata.type.TagsetDescription.
I guess the typesystems of DKPro Core imports are not accessible to the Workbench, and I have no idea on how to solve this issue. I tried upgrading the parent project to the current ruta version (2.6.1, same as my ruta workbench) without any better result.
There are different options to solve this problem. You could import the DKPRo Core type system containing TagsetDescription in your Ruta script so that the generated type system description also provides the type, in case that type system description is used to open the XMI in the CAS Editor.
I often generate a type system description containing all type system descriptions available in the classpath of the project (uimaFIT types.txt) in order to open XMIs in the CAS Editor. For example with the following code:
protected void storeTypeSystem() {
File tsFile = new File("TypeSystem.xml");
try {
TypeSystemDescription typeSystemDescription = TypeSystemDescriptionFactory.createTypeSystemDescription();
try (OutputStream os = new FileOutputStream(tsFile)) {
typeSystemDescription.toXML(os);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
You can specify the type system description that should be used for all files within a project in the properties of that project: Properties -> UIMA Type System. By default, it points to the file created by the sample code above.
DISCLAIMER: I am a developer of UIMA Ruta

OpenCV Exporting Runnable JAR in Eclipse

While Exporting Runnable JAR in Eclipse, Got error as no open cv in java.library.path.
Included Steps :-
Created User Library (ex OpenCV320) in eclipse and added in project build path also dll (as my system is 64 bit "C:\OpenCV\opencv\build\java\x64") opencv_java320.dll is set as Native library Location.
While exporting runnable jar selected "Extract required libraries into generated jar".
Here is the solution
No need to create separate user library.
Add below code.
String libraryPath = "C:\OpenCV\opencv\build\java\x64";
System.setProperty("java.library.path", libraryPath);
Field sysPath = ClassLoader.class.getDeclaredField("sys_paths");
sysPath.setAccessible(true);
sysPath.set(null, null);
3.And export the runnable jar.

Instanciate a JPA EntityManager in an Eclipse RCP (Java SE) environment

Context :
Eclipse RCP project, divided into plugins, each one devoted to a task (eg : HMI management, communications, ...)
Necessity to persist some data in a database
- ORM : hibernate's JPA (JPA 2.1, Hibernate 5.2.1 used throught an org.hibernate.core plugin as constructed [here (page 8)][1]
- database : in mysql
- constraint : Java SE environment, so the only way to obtain an EntityManager (for the persistence operations) is to create it through an EntityManagerFactory
First step (that works!) :
Plugin that manages the database operations, its structure :
com.plugin.name
JRE System Library
Plug-in Dependencies
Referenced Libraries (contains the mysql connector jar)
src/
com.plugin.name (package containing the plugin activator)
com.plugin.name.entities (package containing all my entities)
com.plugin.name.utils (package containing my access functions and a main)
META-INF/
persistence.xml
META-INF/
MANIFEST.MF
In com.plugin.name.utils I have my classes performing all the persistence functions.
In these classes, I create an EntityManagerFactory this way :
private static final EntityManagerFactory ENTITY_MANAGER_FACTORY = Persistence.createEntityManagerFactory("com.plugin.name");
where "com.plugin.name" is the persistence unit name defined in my persistence.xml
In one of those classes, I have a main running some database-related functions.
When I run this main as java application, everything works fine.
(to prevent future questions : my persistence.xml file was originally generated in the MANIFEST.MF META-INF folder but when running this main, it couldn't be found, so I moved it. I checked both configurations when calling the persistence functions from another plugin)
The problem :
I need to access my persistence functions from another plugin, let's call him com.plugin.other
So I added com.plugin.name as a dependency of this plugin.
But when I try to run the application, I get the following error :
javax.persistence.PersistenceException: No Persistence provider for EntityManager named com.plugin.name
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:61)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:39)
When i run the main as standalone application, if there's any problem with the persistence.xml file (not found, incomplete, etc) it gets at least mentionned... Here I'm really stuck with no clue to understand where the problem comes from.
I finally made it without the persistence.xml by using the createContainerEntityManagerFactory(PersistenceUnitInfo info, Map map) method in the PersistenceProvider.
Code :
Activator a = Activator.getDefault();
Bundle b = a.getBundle();
URL url = b.getResource("META-INF/persistence.xml");
List<PersistenceProvider> providers = PersistenceProviderResolverHolder.getPersistenceProviderResolver().getPersistenceProviders();
for (PersistenceProvider pp : providers) {
PersistenceUnitInfoImpl pui = new PersistenceUnitInfoImpl();
pui.setPersistenceUnitName("persistenceUnitName");
pui.setTransactionType(PersistenceUnitTransactionType.RESOURCE_LOCAL);
pui.setPersistenceUnitRootUrl(url);
Properties prop = pui.getProperties();
if (prop == null) {
prop = new Properties();
}
prop.setProperty("javax.persistence.jdbc.url", "jdbc:mysql://ip:port/dbName");
prop.setProperty("javax.persistence.jdbc.user", "dbUser");
prop.setProperty("javax.persistence.jdbc.password", "dbPass");
prop.setProperty("javax.persistence.jdbc.driver", "com.mysql.jdbc.Driver");
pui.setProperties(prop);
pui.setClassLoader(com.mysql.jdbc.Driver.class.getClassLoader());
emFactory = pp.createContainerEntityManagerFactory(pui, null);
}
}

Use webapp classpath using JavaCompiler in Tomcat within Eclipse with Maven

I have an existing "Example Webapp" that references "Example Library" using Maven. I'm running Tomcat 7 inside Eclipse 4.3RC3 with the m2e plugin. When I launch Example Webapp on Tomcat inside Eclipse, I have verified that the example-library.jar is probably getting deployed in the Tomcat instance's WEB-INF/lib folder.
The Example Webapp has code that compiles certain classes on the fly using JavaCompiler.CompilationTask. These dynamically generated classes reference classes in example-library.jar. Unfortunately the compile task is failing because the referenced classes cannot be found.
I understand that I can set the JavaCompiler classpath, but System.getProperty("java.class.path") only returns me the Tomcat classpath, not the webapp classpath:
C:\bin\tomcat\bin\bootstrap.jar;C:\bin\tomcat\bin\tomcat-juli.jar;C:\bin\jdk6\lib\tools.jar
Other have said that I need to get the real path of WEB-INF/lib from the servlet context, but the class generation code doesn't know anything about a servlet context --- it is written to be agnostic of whether it is used on the client or on the server.
In another question, one answer indicated I could enumerate the classloader URLs, and sure enough this provides me with the jars in WEB-INF/lib, but when I provide this as a -classpath option to compiler.getTask(), the task still fails because it can't find the referenced classes.
How can I simply provide the classpath of the currently executing code to the JavaCompiler instance so that it will find the classes from the libraries in WEB-INF/lib? (A similar question was raised but never answered regarding referencing jars within ear files using JavaCompiler.)
Example: In an attempt to get things working at any cost, I even tried to hard-code the classpath. For example, I have foobar.lib in my webapp lib directory, so I used the following code, modified from the answers I indicated above:
List<String> options = new ArrayList<String>();
options.add("-classpath");
options.add("C:\\work\\.metadata\\.plugins\\org.eclipse.wst.server.core\\tmp0\\wtpwebapps\\FooBar\\WEB-INF\\lib\\foobar.jar");
JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, options, null, compilationUnits);
boolean success = task.call();
In the end success is false, and my diaognostics indicates package com.example.foo.bar does not exist..., even though that package is in foobar.jar.
Put example-library.jar somewhere in your file system and pass that location to the code that runs JavaCompiler (the -classpath option). If you use an exploded WAR file to deploy, you can of course point it to the physical location within the WEB-INF/lib folder. The point is that you only need one configurable parameter in your webapp to do this, which can be a properties file entry, -D system property, database row or something else entirely.
Sample code (tested in Tomcat 7 and OpenJDK 1.7 on Fedora 18 x64):
private File compile(File javaFile, String classpath) throws IOException {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
Iterable<? extends JavaFileObject> compilationUnit = fileManager.getJavaFileObjects(javaFile);
List<String> options = classpath != null ? Arrays.asList("-classpath", classpath) : null;
StringWriter output = new StringWriter();
try {
boolean successful = compiler.getTask(output, fileManager, null, options, null, compilationUnit).call();
if (!successful) {
throw new CompilationException("Failed to compile: " + javaFile, output.toString());
}
return firstClassFileFrom(javaFile.getParentFile());
} finally {
fileManager.close();
}
}
private File firstClassFileFrom(File directory) {
return directory.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
return name.endsWith(".class");
}
})[0];
}
See https://github.com/jpalomaki/compiler for a runnable sample webapp.
i met the same question. The reason is not "-classpath" .
my code :
String classpath ="xx/WEB-INF/clases ";
List<String> options = classpath != null ? Arrays.asList("-d", classpath,"-cp",classpath) : null;
CompilationTask task = compiler.getTask(null, javaDinamicoManager, diagnostics,
options, null, Arrays.asList(sourceObj));
boolean result = task.call();
the “result” will return true .
You could follow the answer provided for the even more specific question of how to load dependencies of compiled code from within a web app running directly from an unexpanded WAR file (there are no JAR files to reference - only the container's class loder knows how to access the classes): https://stackoverflow.com/a/45038007/2546679

Programmatically adding a library to an Eclipse project

How can I create a new build path entry for any *.jar file and add this classpath entry to the build path of an Eclipse project.
I have a plugin that should automatically setup my target project. So this project needs to have some library imports and I want to add this imports automatically using a wizard. The user just selects the location of a certain SDK and then some libraries have to be linked with the target project.
However, I found some references:
Importing libraries in Eclipse programmatically
How to add a folder to java build path as library, having multiple jars or entries in it?
Unfortunately, I failed to implement the second solution as I cannot find the classes IClasspathContainer, JavaCore and IJavaProject.
I'm using Eclipse Helios and JDK. Do I need any additional libraries to make changes to the build path or is there a simpler solution to import a jar library programmatically?
Regards,
Florian
I'm assuming that you are creating a plugin and need your plugin to manage the extra jars added to the classpath.
As you mention, you need to create a custom classpath container. First, create the classpath container extension by exending this extension point:
org.eclipse.jdt.core.classpathContainerInitializer
Then, you create a class that implements org.eclipse.jdt.core.IClasspathContainer and associate it with the extension point you just created.
You mention that you cannot find the org.eclipse.jdt.core.IClasspathContainer interface. You need to make sure that your plugin references the org.eclipse.jdt.core plugin in its MANIFEST.MF.
Here you can find some examples, how to define new classpath entries and classpath containers to java projects. I think it would handy for someone reading this question.
In order to get access to IJavaProject etc, goto your plugin.xml and add org.eclipse.jdt.core to the classpath. Thereafter you can import those packages into your project.
String projectName = "MyProject"; // project to add a library to
IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
IJavaProject jProject = JavaCore.create(project);
for(File file : new File("path-to-some-directory-of-libraries-to-add").listFiles()){
if(file.isFile() && file.getName().endsWith(".jar")){
addProjectLibrary(jProject, file);
}
}
private static void addProjectLibrary(IJavaProject jProject, File jarLibrary) throws IOException, URISyntaxException, MalformedURLException, CoreException {
// copy the jar file into the project
InputStream jarLibraryInputStream = new BufferedInputStream(new FileInputStream(jarLibrary));
IFile libFile = jProject.getProject().getFile(jarLibrary.getName());
libFile.create(jarLibraryInputStream, false, null);
// create a classpath entry for the library
IClasspathEntry relativeLibraryEntry = new org.eclipse.jdt.internal.core.ClasspathEntry(
IPackageFragmentRoot.K_BINARY,
IClasspathEntry.CPE_LIBRARY, libFile.getLocation(),
ClasspathEntry.INCLUDE_ALL, // inclusion patterns
ClasspathEntry.EXCLUDE_NONE, // exclusion patterns
null, null, null, // specific output folder
false, // exported
ClasspathEntry.NO_ACCESS_RULES, false, // no access rules to combine
ClasspathEntry.NO_EXTRA_ATTRIBUTES);
// add the new classpath entry to the project's existing entries
IClasspathEntry[] oldEntries = jProject.getRawClasspath();
IClasspathEntry[] newEntries = new IClasspathEntry[oldEntries.length + 1];
System.arraycopy(oldEntries, 0, newEntries, 0, oldEntries.length);
newEntries[oldEntries.length] = relativeLibraryEntry;
jProject.setRawClasspath(newEntries, null);
}
Note that as Andrew Eisenberg mentioned, you need to include the org.eclipse.jdt.core plugin dependency in your plugin's MANIFEST.MF.
Note that you may also need to programmatically refresh the project too.