cross-file reference in xtext - grammar

I created a new DSL by using xtext as follows.
(Actually I will access the DSL on RCP application.)
grammar org.xtext.example.mydsl.MyDsl with org.eclipse.xtext.common.Terminals
generate myDsl "http://www.xtext.org/example/mydsl/MyDsl"
Configuration:
components+=(Component)*;
Component:
'Component' name=ID
'{'
(('display' display=STRING) &
('dependency' dependency=[Component|ID])?)
'}'
;
I have two files:
sample1.mydsl
Component comp1 {
display "comp1"
dependency comp2
}
sampl2.mydsl
Component comp2 {
display "comp2"
}
To check the reference from another file,
I tried to run a test code as standalone but I couldn't get the eobject exactly.
test code
public static final void main(String arg[]) {
new org.eclipse.emf.mwe.utils.StandaloneSetup().setPlatformUri("../");
Injector injector = new MyDslStandaloneSetup().createInjectorAndDoEMFRegistration();
XtextResourceSet resourceSet = injector.getInstance(XtextResourceSet.class);
resourceSet.addLoadOption(XtextResource.OPTION_RESOLVE_ALL, Boolean.TRUE);
File file=new File("/Users/nuckee/Work/temp/mydsl/sample1.mydsl");
Resource resource = resourceSet.getResource(
URI.createURI(file.toURI().toString()), true);
Configuration config = (Configuration) resource.getContents().get(0);
Component comp1 = config.getComponents().get(0);
if (comp1 != null) {
System.out.println("configuration displayed name : " + comp1.getDisplay());
Component dep = comp1.getDependency() ;
if (dep != null) {
System.out.println("dep : " + dep);
System.out.println("dep displayed name : " + dep.getDisplay());
}
}
}
result
configuration displayed name : comp1
dep : org.xtext.example.mydsl.myDsl.impl.ComponentImpl#61544ae6 (eProxyURI: file:/Users/nuckee/Work/temp/mydsl/sample1.mydsl#|0)
dep displayed name : null
How can exactly I get the display of "comp2" from another file?
I Hope someone can help me solve it. Thanks.

You have to load all model files into the resourceset. Xtext does not do auto file discovery

Related

Migrate CRUD Plugin from Play 1.2.4 to 2.5.x : views compilation errors

i'm new on Playframework and i need to migrate the CRUD Plugin from Play-1.2.4 to a module on Play-2.5.x. I'm facing some strange problems with the views. For example the form.scala.html component have the following errors :
app\views\tags\crud\form.scala.html:28: not found: type fieldName
app\views\tags\crud\form.scala.html:28: variable fieldsHandler of type Array[String] does not take type parameters.
app\views\tags\crud\form.scala.html:31: not found: value field
Here is a piece of code of the form file :
#(fields: List[String], obj: Object, typ: controllers.CRUD.ObjectType)(body: Html)
#import scala.Predef; var currentObject: Object = null; var currentType: controllers.CRUD.ObjectType = null; var fieldsHandler = new Array[String](10);
#for(fieldName <- fields) {
var am : String = "";
var field = #currentType.getField(fieldName);
#if(field == null){
throw new play.exceptions.TagInternalException("Field not found -> " + #fieldName)
}
#if(field.typ == "text") {
#tags.crud.textField(fieldName, currentObject[fieldName])
}
#if(field.typ == "password") {
#tags.crud.passwordField(fieldName, currentObject[fieldName])
}
#if(field.typ == "binary"){
#tags.crud.fileField(fieldName, currentObject[fieldName], currentObject.id )
}
}
--> 80% of the compile errors are related to variable recognition !
A piece from build.sbt file:
scalaVersion := "2.11.7"
lazy val root = (project in file(".")).enablePlugins(PlayJava, PlayEbean, SbtTwirl)
fork in run := true
Any idea ? Your help will be appreciated. Thanks.
I understood that the principle of the crud plugin is in contradiction with the new logic of compiling scala templates. So I started on a new generic implementation of crud.
Thank you

declare ITD static method on multiple types

I would like to declare a static method (like void main(String..args)) on every subtype of my App class.
public aspect Aspects pertypewithin(App+) {
protected Class appClass;
after() : staticinitialization(App+) && !staticinitialization(App) {
StaticPart point = thisJoinPointStaticPart;
Signature signature = point.getSignature();
Class declaringType = signature.getDeclaringType();
this.appClass = declaringType;
}
public static void App.main(String...args) {
// how do i make this appear on every subtype of App, not just App
}
}
Is this possible with AspectJ?
The usual pattern for adding a set of non-static methods to multiple classes is to define an interface + implementing methods within an aspect and use declare parents in order to make the target classes implement the interface.
Unfortunately this does not work for static methods like main because static methods cannot be defined via an interface. On the other hand, if you have a class MyApp extends App you can call java -cp ... MyApp, i.e. its parent main method will automatically be used.
Now let us assume that for some reason you want the contents of the generated main methods to be somehow different. In this case you really need to generate one method per class. For that purpose you can use a new feature introduced in AspectJ 1.8.2 and described in the release notes: annotation processing support. Here is some self-consistent sample code. I compiled it from the command line because from Eclipse I failed to get it running according to AspectJ maintainer Andy Clement's description.
Okay, let's say we have two project directories somewhere in a base directory called java-src. The directory layout be like this:
java-src
SO_AJ_ITD_AddMainMethodToAllSubclasses_AJ
src\de\scrum_master\app\App.java
src\de\scrum_master\app\BarApp.java
src\de\scrum_master\app\FooApp.java
compile_run.bat
SO_AJ_ITD_AddMainMethodToAllSubclasses_APT
src\de\scrum_master\app\EntryPoint.java
src\de\scrum_master\aspect\EntryPointProcessor.java
src\META-INF\services\javax.annotation.processing.Processor
In project SO_AJ_ITD_AddMainMethodToAllSubclasses_AJ we have our Java classes:
package de.scrum_master.app;
#EntryPoint
public class App {
public void doSomething() {
System.out.println("Doing something");
}
}
package de.scrum_master.app;
public class FooApp extends App {
public void doFoo() {
System.out.println("Doing foo");
}
public int add(int a, int b) {
return a + b;
}
}
package de.scrum_master.app;
public class BarApp extends App {
public void doBar() {
System.out.println("Doing bar");
}
public int multiply(int a, int b) {
return a * b;
}
}
In project SO_AJ_ITD_AddMainMethodToAllSubclasses_APT we have our marker annotation, the annotation processor and processor description file for the META-INF directory of our processor.jar:
Please note: The annotation is #Inherited when applied to classes. This is important in order to make the annotation processor find it.
package de.scrum_master.app;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.TYPE)
#Inherited
public #interface EntryPoint {}
The annotation processor creates one aspect per annotated class. Each aspect does the following:
Add a main method which
instantiates an object of the target class,
always calls the base method doSomething() upon the target instance,
searches the target class for other simple non-static methods without parameters and calls these methods, just so as to show some fancy and dynamic stuff and make the resulting aspects look a bit different.
package de.scrum_master.aspect;
import java.io.*;
import javax.tools.*;
import java.util.*;
import javax.annotation.processing.*;
import javax.lang.model.*;
import javax.lang.model.element.*;
import de.scrum_master.app.EntryPoint;
#SupportedAnnotationTypes(value = { "*" })
#SupportedSourceVersion(SourceVersion.RELEASE_7)
public class EntryPointProcessor extends AbstractProcessor {
private Filer filer;
#Override
public void init(ProcessingEnvironment env) {
filer = env.getFiler();
}
#Override
public boolean process(Set<? extends TypeElement> elements, RoundEnvironment env) {
// Discover elements marked with #EntryPoint
for (Element element : env.getElementsAnnotatedWith(EntryPoint.class)) {
// Skip non-class elements
if (element.getKind() != ElementKind.CLASS)
continue;
String packageName = element.getEnclosingElement().toString().substring(8);
String className = element.getSimpleName().toString();
String aspectName = "MainMethodAspect_" + className;
// For each marked class, create an aspect adding a 'main' method
String aspectSource = createAspectSource(element, packageName, className, aspectName);
writeAspectSourceToDisk(element, packageName, aspectName, aspectSource);
}
return true;
}
private String createAspectSource(Element element, String packageName, String className, String aspectName) {
String variableName = className.substring(0, 1).toLowerCase() + className.substring(1);
StringBuilder aspectSource = new StringBuilder()
.append("package " + packageName + ";\n\n")
.append("public aspect " + aspectName + " {\n")
.append(" public static void " + className + ".main(String[] args) {\n")
.append(" " + className + " " + variableName + " = new " + className + "();\n")
.append(" " + variableName + ".doSomething();\n");
for (Element childElement : element.getEnclosedElements()) {
// Skip everything which is not a non-static method
if (childElement.getKind() != ElementKind.METHOD || childElement.getModifiers().contains(Modifier.STATIC))
continue;
ExecutableElement method = (ExecutableElement) childElement;
// Skip methods with parameters or named 'doSomething'
if (!method.getParameters().isEmpty() || method.getSimpleName().toString().equals("doSomething"))
continue;
// Add call to found method
aspectSource.append(" " + variableName + "." + method.getSimpleName() + "();\n");
}
aspectSource
.append(" }\n")
.append("}\n");
return aspectSource.toString();
}
private void writeAspectSourceToDisk(Element element, String packageName, String aspectName, String aspectSource) {
try {
JavaFileObject file = filer.createSourceFile(packageName + "." + aspectName, element);
file.openWriter().append(aspectSource).close();
System.out.println("Generated aspect " + packageName + "." + aspectName + " to advise " + element);
} catch (IOException ioe) {
// Message "already created" can appear if processor runs more than once
if (!ioe.getMessage().contains("already created"))
ioe.printStackTrace();
}
}
}
The processor description file src\META-INF\services\javax.annotation.processing.Processor for APT looks like this:
de.scrum_master.aspect.EntryPointProcessor
How to compile and run: Last, but not least here is a (Windows) batch file SO_AJ_ITD_AddMainMethodToAllSubclasses_AJ\compile_run.bat which
compiles the APT project and packages it into a JAR,
compiles the other project including APM aspect code generation and finally
runs each of the three Java classes, testing if their main methods actually work as expected:
#echo off
set SRC_PATH=C:\Users\Alexander\Documents\java-src
set ASPECTJ_HOME=C:\Program Files\Java\AspectJ
echo Building annotation processor
cd "%SRC_PATH%\SO_AJ_ITD_AddMainMethodToAllSubclasses_APT"
rmdir /s /q bin
del /q processor.jar
call "%ASPECTJ_HOME%\bin\ajc.bat" -8 -sourceroots src -d bin -cp "c:\Program Files\Java\AspectJ\lib\aspectjrt.jar"
jar -cvf processor.jar -C src META-INF -C bin .
echo.
echo Generating aspects and building project
cd "%SRC_PATH%\SO_AJ_ITD_AddMainMethodToAllSubclasses_AJ"
rmdir /s /q bin .apt_generated
call "%ASPECTJ_HOME%\bin\ajc.bat" -8 -sourceroots src -d bin -s .apt_generated -cp "c:\Program Files\Java\AspectJ\lib\aspectjrt.jar";..\SO_AJ_ITD_AddMainMethodToAllSubclasses_APT\processor.jar
echo.
echo Running de.scrum_master.app.App
java -cp bin;"c:\Program Files\Java\AspectJ\lib\aspectjrt.jar" de.scrum_master.app.App
echo.
echo Running de.scrum_master.app.FooApp
java -cp bin;"c:\Program Files\Java\AspectJ\lib\aspectjrt.jar" de.scrum_master.app.FooApp
echo.
echo Running de.scrum_master.app.BarApp
java -cp bin;"c:\Program Files\Java\AspectJ\lib\aspectjrt.jar" de.scrum_master.app.BarApp
Console output: If you run the batch file, the output should look as follows:
Building annotation processor
Manifest wurde hinzugefügt
Eintrag META-INF/ wird ignoriert
META-INF/services/ wird hinzugefügt(ein = 0) (aus = 0)(0 % gespeichert)
META-INF/services/javax.annotation.processing.Processor wird hinzugefügt(ein = 43) (aus = 45)(-4 % verkleinert)
de/ wird hinzugefügt(ein = 0) (aus = 0)(0 % gespeichert)
de/scrum_master/ wird hinzugefügt(ein = 0) (aus = 0)(0 % gespeichert)
de/scrum_master/app/ wird hinzugefügt(ein = 0) (aus = 0)(0 % gespeichert)
de/scrum_master/app/EntryPoint.class wird hinzugefügt(ein = 430) (aus = 253)(41 % verkleinert)
de/scrum_master/aspect/ wird hinzugefügt(ein = 0) (aus = 0)(0 % gespeichert)
de/scrum_master/aspect/EntryPointProcessor.class wird hinzugefügt(ein = 5782) (aus = 2617)(54 % verkleinert)
Generating aspects and building project
Generated aspect de.scrum_master.app.MainMethodAspect_App to advise de.scrum_master.app.App
Generated aspect de.scrum_master.app.MainMethodAspect_BarApp to advise de.scrum_master.app.BarApp
Generated aspect de.scrum_master.app.MainMethodAspect_FooApp to advise de.scrum_master.app.FooApp
Running de.scrum_master.app.App
Doing something
Running de.scrum_master.app.FooApp
Doing something
Doing foo
Running de.scrum_master.app.BarApp
Doing something
Doing bar
If you look at the files generated by the annotation processor under SO_AJ_ITD_AddMainMethodToAllSubclasses_AJ\.apt_generated, you will find three classes looking like this (I am showing just one of them as a sample):
package de.scrum_master.app;
public aspect MainMethodAspect_FooApp {
public static void FooApp.main(String[] args) {
FooApp fooApp = new FooApp();
fooApp.doSomething();
fooApp.doFoo();
}
}
Sorry for this lenghty answer, but other than creating a GitHub repo and just pointing there, I had to mention it all in order to make it reproducible.
Enjoy!

yii2 fixtures doesn't work properly

I have a problem with fixtures in yii2 , I just created all required file according to this document but it's not working.
let me explain , I have a module called Authyii and inside this module I have a model named User .
this is my directory structure :
my fixture file is like this :
namespace app\modules\Authyii\tests\fixtures;
use app\modules\Authyii\models;
use yii\test\ActiveFixture;
use yii\test\Fixture;
class UserFixture extends ActiveFixture
{
public $modelClass = 'app\modules\Aythyii\models\User';
public $tableName = 'authyii_user';
}
this is my command line :
but after I type 'yes' and command line says :
but when I check my database there is not new record inside authyii_user tables .
what I missed ?
File User.php id data dir must have table name authyii_user.php. In framework source code in file ActiveFixture.php line with code:
$dataFile = dirname($class->getFileName()) . '/data/'
. $this->getTableSchema()->fullName . '.php';
Best regards.
There is method getFixturesConfig() in \vendor\yiisoft\yii2\console\controllers\FixtureController.php
private function getFixturesConfig($fixtures)
{
$config = [];
foreach ($fixtures as $fixture) {
$isNamespaced = (strpos($fixture, '\\') !== false);
$fullClassName = $isNamespaced ? $fixture . 'Fixture' : $this->namespace . '\\' . $fixture . 'Fixture';
if (class_exists($fullClassName)) { // <<< I think you lose your UserFixture here
$config[] = $fullClassName;
}
}
return $config;
}
You should check what $fullClassName Yii expects it to be (for example logging or echoing it) and tweak your UserFixture's namespace accordingly.

eclipse JDT setting the project

I am a beginner to Eclipse JDT. I was going through some tutorial and found one good example for creating the java file. In this below example in which project they will create the package and java file. I could not see any code pointing to any of the project name. Please make me understand if I am wrong. I just run the below example. I could not see any output..
AST ast = AST.newAST(AST.JLS3);
CompilationUnit unit = ast.newCompilationUnit();
PackageDeclaration packageDeclaration = ast.newPackageDeclaration();
packageDeclaration.setName(ast.newSimpleName("example"));
unit.setPackage(packageDeclaration);
ImportDeclaration importDeclaration = ast.newImportDeclaration();
QualifiedName name =
ast.newQualifiedName(
ast.newSimpleName("java"),
ast.newSimpleName("util"));
importDeclaration.setName(name);
importDeclaration.setOnDemand(true);
unit.imports().add(importDeclaration);
TypeDeclaration type = ast.newTypeDeclaration();
type.setInterface(false);
type.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD));
type.setName(ast.newSimpleName("HelloWorld"));
MethodDeclaration methodDeclaration = ast.newMethodDeclaration();
methodDeclaration.setConstructor(false);
List modifiers = methodDeclaration.modifiers();
modifiers.add(ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD));
modifiers.add(ast.newModifier(Modifier.ModifierKeyword.STATIC_KEYWORD));
methodDeclaration.setName(ast.newSimpleName("main"));
methodDeclaration.setReturnType2(ast.newPrimitiveType(PrimitiveType.VOID));
SingleVariableDeclaration variableDeclaration = ast.newSingleVariableDeclaration();
variableDeclaration.setType(ast.newArrayType(ast.newSimpleType(ast.newSimpleName("String"))));
variableDeclaration.setName(ast.newSimpleName("args"));
methodDeclaration.parameters().add(variableDeclaration);
org.eclipse.jdt.core.dom.Block block = ast.newBlock();
MethodInvocation methodInvocation = ast.newMethodInvocation();
name =
ast.newQualifiedName(
ast.newSimpleName("System"),
ast.newSimpleName("out"));
methodInvocation.setExpression(name);
methodInvocation.setName(ast.newSimpleName("println"));
InfixExpression infixExpression = ast.newInfixExpression();
infixExpression.setOperator(InfixExpression.Operator.PLUS);
StringLiteral literal = ast.newStringLiteral();
literal.setLiteralValue("Hello");
infixExpression.setLeftOperand(literal);
literal = ast.newStringLiteral();
literal.setLiteralValue(" world");
infixExpression.setRightOperand(literal);
methodInvocation.arguments().add(infixExpression);
ExpressionStatement expressionStatement = ast.newExpressionStatement(methodInvocation);
block.statements().add(expressionStatement);
methodDeclaration.setBody(block);
type.bodyDeclarations().add(methodDeclaration);
unit.types().add(type);
You may take a look at this. It uses Java Model, which means you will need to create a plug-in to make it work.
// create a project with name "TESTJDT"
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
IProject project = root.getProject("TESTJDT");
project.create(null);
project.open(null);
//set the Java nature
IProjectDescription description = project.getDescription();
description.setNatureIds(new String[] { JavaCore.NATURE_ID });
//create the project
project.setDescription(description, null);
IJavaProject javaProject = JavaCore.create(project);
//set the build path
IClasspathEntry[] buildPath = {
JavaCore.newSourceEntry(project.getFullPath().append("src")),
JavaRuntime.getDefaultJREContainerEntry() };
javaProject.setRawClasspath(buildPath, project.getFullPath().append(
"bin"), null);
//create folder by using resources package
IFolder folder = project.getFolder("src");
folder.create(true, true, null);
//Add folder to Java element
IPackageFragmentRoot srcFolder = javaProject
.getPackageFragmentRoot(folder);
//create package fragment
IPackageFragment fragment = srcFolder.createPackageFragment(
"com.programcreek", true, null);
//init code string and create compilation unit
String str = "package com.programcreek;" + "\n"
+ "public class Test {" + "\n" + " private String name;"
+ "\n" + "}";
ICompilationUnit cu = fragment.createCompilationUnit("Test.java", str,
false, null);
//create a field
IType type = cu.getType("Test");
type.createField("private String age;", null, true, null);

[Zend_Form][1.11.1] Error Message Fatal error: Class 'Admin_Form_Login' not found in ...\modules\default\controllers\IndexController.php

I don't speak english fluently (i'm french) so i will be
i followed the tutorial here and i got this structure
Application
--Modules
------admin
---------controller
---------views
------etat
---------controller
---------views
------default
---------controller
---------views
--configs
bootstrap.php
My problem is that, when i created my first form and tried to view it in my browser, i got the following error:
Fatal error: Class 'Admin_Form_Login' not found in C:\wamp\www\get\application\modules\default\controllers\IndexController.php on line 14.
Here is my code:
My controller : /modules/etat/controller/IndexController.php
class Etat_IndexController extends Zend_Controller_Action
{
public function init()
{
/* Initialize action controller here */
}
public function indexAction()
{
// action body
$form = new Etat_Form_InfoAgent();
$this->view->form = $form;
}
}
My form : /modules/etat/forms/InfoAgent.php
class Etat_Form_InfoAgent extends Zend_Form
{
public function init()
{
/* Form Elements & Other Definitions Here ... */
$this->setName('infoagent');
$this->setMethod('post');
$login = new Zend_Form_Element_Text('matricule');
$login->setLabel('Matricule:');
$login->setRequired(true);
$login->addFilter('StripTags');
$login->addFilter('StringTrim');
$this->addElement($login);
$password = new Zend_Form_Element_Password('agence');
$password->setLabel('Code agence:');
$password->setRequired(true);
$password->addFilter('StripTags');
$password->addFilter('StringTrim');
$this->addElement($password);
$submit = new Zend_Form_Element_Submit('submit');
$submit->setLabel('Valider');
//$submit->style = array('float: right');
$this->addElement($submit);
}
}
My view : /modules/etat/view/script/index.phtml
<br /><br />
<div id="view-content">
<?php echo $this->form; ?>
</div>
Configuration file : configs/application.ini
[production]
phpSettings.display_startup_errors = 0
phpSettings.display_errors = 0
includePaths.library = APPLICATION_PATH "/../library"
bootstrap.path = APPLICATION_PATH "/Bootstrap.php"
bootstrap.class = "Bootstrap"
appnamespace = "Application"
resources.frontController.controllerDirectory = APPLICATION_PATH "/controllers"
resources.frontController.params.displayExceptions = 0
;Modular structure
resources.modules[] =
resources.frontController.moduleDirectory = APPLICATION_PATH "/modules"
resources.frontController.params.prefixDefaultModule = "1"
;database ressources
resources.db.adapter = PDO_MYSQL
resources.db.params.host = localhost
resources.db.params.username = root
resources.db.params.password =
resources.db.params.dbname = bd_test
[staging : production]
[testing : production]
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1
[development : production]
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1
resources.frontController.params.displayExceptions = 1
I have searched the web for solution but i didn't get it. I saw a post about the same problem on your website (stackoverflow) and i tried to aplly your instructions without solving my problem.
i precise that i haven't change the code on my bootstrap and my public/index.php file
I hope you could help me soon.
thx
Make sure you have created a Bootstrap.php in each module directory, which looks like:
class Admin_Bootstrap extends Zend_Application_Module_Bootstrap
{}
In which Admin is the name of the module.
Also, make sure there is actually a file Login.php inside directory modules/admin/forms with a class Admin_Form_Login