How do I include Xtext generator in my Maven project? - java

I am currently building a framework which would benefit from having a DSL for creating a configuration file, so I created one using Xtext.
Now I want to add a dependency to the classes that I have created so that I can generate configurations at runtime, but on Xtext's site it looks like the only two cases for integration are:
When I want CI for the language itself;
When I want to include a plugin that would generate code at build time.
How can I use the generator that I wrote in Xtext at runtime in my Maven project?

For CI for Xtext itself simpy use the new project wizard and select Maven as build system on the second page of the project. To build your model files have a look that the xtext-maven-plugin e.g. as used here https://github.com/xtext/maven-xtext-example/blob/master/example-project/pom.xml or here https://github.com/cdietrich/xtext-maven-example/blob/master/org.xtext.example.mydsl.model/pom.xml
If you simply want to read a model file and call the generator
package org.eclipse.xtext.example.domainmodel;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.xtext.generator.GeneratorContext;
import org.eclipse.xtext.generator.GeneratorDelegate;
import org.eclipse.xtext.generator.IGeneratorContext;
import org.eclipse.xtext.generator.JavaIoFileSystemAccess;
import org.eclipse.xtext.util.CancelIndicator;
import org.eclipse.xtext.validation.CheckMode;
import org.eclipse.xtext.validation.IResourceValidator;
import org.eclipse.xtext.validation.Issue;
import com.google.common.collect.Lists;
import com.google.inject.Injector;
/**
* #author dietrich - Initial contribution and API
*/
public class Main {
public static void main(String[] args) {
// TODO traverse directory
List<String> files = Lists.newArrayList("model/a.dmodel", "model/b.dmodel");
Injector injector = new DomainmodelStandaloneSetup().createInjectorAndDoEMFRegistration();
ResourceSet rs = injector.getInstance(ResourceSet.class);
ArrayList<Resource> resources = Lists.newArrayList();
for (String file : files) {
Resource r = rs.getResource(URI.createFileURI(file), true);
resources.add(r);
}
IResourceValidator validator = injector.getInstance(IResourceValidator.class);
for (Resource r : resources) {
List<Issue> issues = validator.validate(r, CheckMode.ALL, CancelIndicator.NullImpl);
for (Issue i : issues) {
System.out.println(i);
}
}
GeneratorDelegate generator = injector.getInstance(GeneratorDelegate.class);
JavaIoFileSystemAccess fsa = injector.getInstance(JavaIoFileSystemAccess.class);
fsa.setOutputPath("src-gen-code/");
GeneratorContext context = new GeneratorContext();
context.setCancelIndicator(CancelIndicator.NullImpl);
for (Resource r : resources) {
generator.generate(r, fsa, context);
}
}
}

Related

How to Run Java Code from Gradle at Build Time

I'm using jsonschema-generator to generate a JSON schema file based on my POJOs. Currently I'm doing it via a test that is run during the gradle build step. This works fine but it doesn't feel right as really what I'm doing is not testing anything.
I've also found this answer which details how to run it on gradle run but this is not ideal either as it will pointlessly execute this every time the application comes up but not when I build.
Therefore, is there a way to tell gradle (in build.gradle) to run a piece of Java code at build time?
For completeness, here the code I'm looking to run:
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.victools.jsonschema.generator.Option;
import com.github.victools.jsonschema.generator.OptionPreset;
import com.github.victools.jsonschema.generator.SchemaGenerator;
import com.github.victools.jsonschema.generator.SchemaGeneratorConfig;
import com.github.victools.jsonschema.generator.SchemaGeneratorConfigBuilder;
import com.mypackage.MyClass;
import org.junit.jupiter.api.Test;
import java.io.PrintWriter;
import java.util.Map;
#SuppressWarnings({"FieldCanBeLocal", "rawtypes"})
public class JsonSchemaGenerator {
private final String SCHEMA_FOLDER = "schemas/";
private final Map<Class, String> schemaToGenerate = Map.of(
MyClass.class, "my-class.schema"
);
#Test
public void generateJsonSchema() throws Exception {
SchemaGeneratorConfigBuilder configBuilder = new SchemaGeneratorConfigBuilder(new ObjectMapper(), OptionPreset.PLAIN_JSON);
SchemaGeneratorConfig config = configBuilder.with(Option.DEFINITIONS_FOR_ALL_OBJECTS).build();
SchemaGenerator generator = new SchemaGenerator(config);
for (var entry : schemaToGenerate.entrySet()) {
JsonNode jsonSchema = generator.generateSchema(entry.getKey());
PrintWriter out = new PrintWriter(SCHEMA_FOLDER + entry.getValue());
out.println(jsonSchema.toPrettyString());
out.close();
}
}
}
The JavaExec Plugin seems to meet your requirements.
This allows you to run a main() method and thereby any Java Code you want – including whatever JSON Schema generation you like.
This other answer also describes pretty much what you want to do.
Adapted from the linked documentation:
apply plugin: 'java'
task generateJsonSchema(type: JavaExec) {
classpath = sourceSets.main.runtimeClasspath
main = 'package.Main'
// arguments to pass to the application
args 'appArg1'
}
As per Jorn's comment below:
You can depend the build task on your custom task: build.dependsOn generateJsonSchema if your custom task is defined as task generateJsonSchema(type: JavaExec) { ... }

Loading classes for Reflections library outside Netbeans

I'm trying to use the Reflections library to give me a list of all the classes in a specific package in an external jar file. This works in Netbeans, but not when running the jar file from the command line. It looks like Netbeans finds and loads the classes I need, whereas the command line run doesn't. How should I set this up so it works everywhere?
I've tried both the usage example on the Reflections readme, as well as the response to this issue. Both methods have the same result.
Here's the test code I've been working with to reproduce the issue:
package javaapplication1;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import org.reflections.Reflections;
import org.reflections.util.ConfigurationBuilder;
import org.reflections.util.ClasspathHelper;
import org.reflections.scanners.SubTypesScanner;
import org.reflections.scanners.ResourcesScanner;
import java.util.Set;
import org.externaljar.package.*;
public class JavaApplication1
{
private static Reflections reflections;
public static void main(String[] args)
{
final String myPkg = "org.externaljar.package";
URL[] urlPath = new URL[1];
try{
urlPath[0] = new URL("jar:file:/path/to/external.jar!/");
}catch(MalformedURLException ex){
ex.printStackTrace();
}
URLClassLoader urlLoader = URLClassLoader.newInstance(urlPath);
final ConfigurationBuilder config = new ConfigurationBuilder()
.addClassLoader(urlLoader)
.setScanners(new ResourcesScanner(), new SubTypesScanner(false))
.setUrls(ClasspathHelper.forPackage(myPkg));
reflections = new Reflections(config, new SubTypesScanner(false));
Set<Class<? extends ObjectBase>> objects = reflections.getSubTypesOf(ObjectBase.class);
System.out.println("\n\nFound " + objects.size() + " Objects\n\n");
}
}
Running the project in Netbeans gives a non-zero value for objects.size(), but running java -jar JavaApplication1.jar prints "Found 0 Objects". Adding -verbose:class to each shows that Netbeans loads all the classes I'm looking for, but those aren't loaded when run from the command line.

Cucumber Reporting getting Error

I am using a Cucumber reporting api for better reporting. My project is not a maven project and cannot change the project structure now. So I add all the dependency on my project but still now it is getting error like "java.lang.IllegalArgumentException: File 'target/cucumber.json' does not contan features!"
All added jars and version showing below.
I also added my runner class here which may help for debugging.
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.junit.AfterClass;
import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.SnippetType;
import cucumber.api.junit.Cucumber;
import net.masterthought.cucumber.Configuration;
import net.masterthought.cucumber.ReportBuilder;
#RunWith(Cucumber.class)
#CucumberOptions(
plugin = {
"html:target/cucumber-html-report",
"json:target/cucumber.json"
},features ={"./sample.feature"},
glue ={"com/automation/steps"},strict = true,
dryRun= false,monochrome = true, snippets= SnippetType.CAMELCASE)
/*public class Runner extends AbstractTestNGCucumberTests{
}*/
public class Runner {
#AfterClass
public static void generateReport(){
File reportOutputDirectory = new File("target");
List<String> jsonFiles = new ArrayList<>();
jsonFiles.add("target/cucumber.json");
String jenkinsBasePath = "";
String buildNumber = "1";
String projectName = "cucumber-jvm";
boolean skippedFails = true;
boolean pendingFails = false;
boolean undefinedFails = true;
boolean missingFails = true;
boolean runWithJenkins = false;
boolean parallelTesting = false;
Configuration configuration = new Configuration(reportOutputDirectory, projectName);
// optionally only if you need
configuration.setStatusFlags(skippedFails, pendingFails, undefinedFails, missingFails);
configuration.setParallelTesting(parallelTesting);
configuration.setJenkinsBasePath(jenkinsBasePath);
configuration.setRunWithJenkins(runWithJenkins);
configuration.setBuildNumber(buildNumber);
ReportBuilder reportBuilder = new ReportBuilder(jsonFiles, configuration);
reportBuilder.generateReports();
}
}
I also attached the project structure image.
I observed that feature-overview.html was generated under the folder structure but it was corrupted when I opened this file it was showing this error on this file.
Can any one please help me on this error?
Your cukes runner is not able to identify path to feature file..
Try giving full path of your feature file in feature option..like src/test/java/sample.feature

DeepLearning4j‘s example compiled error

I got a few problems while programming with DeepLearning4j.
When I open and compile the example MnistMultiThreadedExample in Eclipse, these problems occured.
import org.deeplearning4j.datasets.iterator.impl.MnistDataSetIterator;
import org.deeplearning4j.datasets.test.TestDataSetIterator;
import org.deeplearning4j.iterativereduce.actor.multilayer.ActorNetworkRunner;**(error)**
import org.deeplearning4j.models.classifiers.dbn.DBN;**(error)**
import org.deeplearning4j.nn.conf.NeuralNetConfiguration;
import org.deeplearning4j.scaleout.conf.Conf;**(error)**
It is saying these package are not in the target package. And I couldn't find these modules in the package and couldn't find it in Maven Center Repository while I couldn't find the Class in Source Code.
Now I want to know how I get these modules and what should I do before creating a AutoEncoder which could running on Spark.
The example code is shown below:
import org.deeplearning4j.datasets.iterator.impl.MnistDataSetIterator;
import org.deeplearning4j.datasets.test.TestDataSetIterator;
import org.deeplearning4j.iterativereduce.actor.multilayer.ActorNetworkRunner;
import org.deeplearning4j.models.classifiers.dbn.DBN;
import org.deeplearning4j.nn.conf.NeuralNetConfiguration;
import org.deeplearning4j.scaleout.conf.Conf;
public class MnistMultiThreadedExample {
public static void main(String[] args) throws Exception {
//5 batches of 100: 20 each
MnistDataSetIterator mnist = new MnistDataSetIterator(20, 60000);
TestDataSetIterator iter = new TestDataSetIterator(mnist);
ActorNetworkRunner runner = new ActorNetworkRunner(iter);
NeuralNetConfiguration conf2 = new NeuralNetConfiguration.Builder()
.nIn(784).nOut(10).build();
Conf conf = new Conf();
conf.setConf(conf2);
conf.getConf().setFinetuneEpochs(1000);
conf.setLayerSizes(new int[]{500,250,100});
conf.setMultiLayerClazz(DBN.class);
conf.getConf().setnOut(10);
conf.getConf().setFinetuneLearningRate(0.0001f);
conf.getConf().setnIn(784);
conf.getConf().setL2(0.001f);
conf.getConf().setMomentum(0.5f);
conf.setSplit(10);
conf.getConf().setUseRegularization(false);
conf.setDeepLearningParams(new Object[]{1,0.0001,1000});
runner.setup(conf);
runner.train();
}
}
You should add the following dependency to your POM:
<dependency>
<groupId>org.deeplearning4j</groupId>
<artifactId>deeplearning4j-scaleout-akka</artifactId>
<version>0.0.3.3</version>
</dependency>
This will add as transitive dependencies deeplearning4j-scaleout-api and deeplearning4j-core. Those three dependencies will provide you the imports you are missing.

Cannot instantiate the type configuration Mirror API

I recently purchased the Book "Programming Google Glass - The Mirror API" By Eric Redmond and in the 2nd chapter we install Freemarker GRE .jar file into the project. There is a part when we have to create a method that renders a template file. I keep getting an error when trying to make a Configuration.
package com.leetinsider.leetfoodfinder;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;
import java.util.Random;
import javax.security.auth.login.Configuration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import com.sun.org.apache.xalan.internal.xsltc.compiler.Template;
public class LeetFoodFinder {
public static String getRandomCuisine()
{
String[] lunchOptions = {
"American", "Chineese", "French", "Italian", "Japenese", "Thai"
};
int choice = new Random().nextInt(lunchOptions.length);
return lunchOptions[choice];
}
public static String render(ServletContext ctx, String template, Map<String, Object> data)
throws IOException, ServletException{
Configuration config = new Configuration();
config.setServletContextForTemplateLoading(ctx, "WEB-INF/views");
config.setDefaultEncoding("UTF-8");
Template ftl = config.getTemplate(template);
try{
//use the data to render the template to the servlet output
StringWriter writer = new StringWriter();
ftl.process(data, writer);
return writer.toString();
}
catch (TemplateException e){
throw new ServletException("Problem while processing template", e);
}
}
}
It tells me that Configuration() cannot be instaniated. Is there an import that I am missing? I put the freemarker-gae2.3.2.0.jar file in the war/WEB-INF/lib directory but am not sure if there is something else I am missing.
Trying to follow along with the book but this is holding me back :/
If you look at your import statement, they're referring to non freemarker classes of the same name.
The jar isn't actually in your build path. Right click the project and choose "Properties", then "Java Build Path". If freemarker isn't in the Libraries list, select Add JARs and find the jar in your project.
Delete the "import javax.security.auth.login.Configuration" line. You need to choose the Freemarker configuration.
Hope that helps.

Categories

Resources