Java Code Examples for org.eclipse.xtext.generator.IFileSystemAccess

The following examples show how to use org.eclipse.xtext.generator.IFileSystemAccess. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
public String generate(final Resource res, final JvmDeclaredType type) {
  String _xblockexpression = null;
  {
    res.eSetDeliver(false);
    EList<EObject> _contents = res.getContents();
    this.builder.<JvmDeclaredType>operator_add(_contents, type);
    res.eSetDeliver(true);
    final InMemoryFileSystemAccess fsa = new InMemoryFileSystemAccess();
    this.generator.doGenerate(res, fsa);
    Map<String, CharSequence> _textFiles = fsa.getTextFiles();
    String _replace = type.getIdentifier().replace(".", "/");
    String _plus = (IFileSystemAccess.DEFAULT_OUTPUT + _replace);
    String _plus_1 = (_plus + ".java");
    _xblockexpression = _textFiles.get(_plus_1).toString();
  }
  return _xblockexpression;
}
 
Example 2
Source Project: xtext-eclipse   Source File: MyGenerator.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void doGenerate(Resource input, IFileSystemAccess fsa) {
	TreeIterator<EObject> allContents = input.getAllContents();
	while (allContents.hasNext()) {
		EObject next = allContents.next();
		if (next instanceof Element) {
			Element ele = (Element) next;
			String fileName = ele.getName() + ".txt";
			if (fsa instanceof IFileSystemAccess2) {
				IFileSystemAccess2 fileSystemAccess2 = (IFileSystemAccess2) fsa;
				if (fileSystemAccess2.isFile(fileName)) {
					fileSystemAccess2.readTextFile(fileName);
				}
			}
			fsa.generateFile(fileName, "object " + ele.getName());
		}
	}
}
 
Example 3
Source Project: sarl   Source File: SARLPreferences.java    License: Apache License 2.0 6 votes vote down vote up
/** Replies the SARL output path in the global preferences.
 *
 * @return the output path for SARL compiler in the global preferences.
 */
public static IPath getGlobalSARLOutputPath() {
	final Injector injector = LangActivator.getInstance().getInjector(LangActivator.IO_SARL_LANG_SARL);
	final IOutputConfigurationProvider configurationProvider =
			injector.getInstance(IOutputConfigurationProvider.class);
	final OutputConfiguration config = Iterables.find(
		configurationProvider.getOutputConfigurations(),
		it -> Objects.equals(it.getName(), IFileSystemAccess.DEFAULT_OUTPUT));
	if (config != null) {
		final String path = config.getOutputDirectory();
		if (!Strings.isNullOrEmpty(path)) {
			final IPath pathObject = Path.fromOSString(path);
			if (pathObject != null) {
				return pathObject;
			}
		}
	}
	throw new IllegalStateException("No global preferences found for SARL."); //$NON-NLS-1$
}
 
Example 4
Source Project: sarl   Source File: SARLJvmGenerator.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void _internalDoGenerate(JvmDeclaredType type, IFileSystemAccess fsa) {
	if (DisableCodeGenerationAdapter.isDisabled(type)) {
		return;
	}
	final String qn = type.getQualifiedName();
	if (!Strings.isEmpty(qn)) {
		final String fn = qn.replace('.', '/') + ".java"; //$NON-NLS-1$
		final CharSequence content = generateType(type, this.generatorConfigProvider.get(type));
		final String outputConfigurationName;
		final Boolean isTest = this.resourceTypeDetector.isTestResource(type.eResource());
		if (isTest != null && isTest.booleanValue()) {
			outputConfigurationName = SARLConfig.TEST_OUTPUT_CONFIGURATION;
		} else {
			outputConfigurationName = IFileSystemAccess.DEFAULT_OUTPUT;
		}
		fsa.generateFile(fn, outputConfigurationName, content);
	}
}
 
Example 5
Source Project: n4js   Source File: XSource2GeneratedMapping.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Add a source to gen mapping.
 */
public void addSource2Generated(URI source, URI generated, String outputCfgName) {
	this.source2generated.put(source, generated);
	this.generated2source.put(generated, source);
	this.generated2OutputConfigName.put(generated,
			outputCfgName == null ? IFileSystemAccess.DEFAULT_OUTPUT : outputCfgName);
}
 
Example 6
Source Project: n4js   Source File: N4JSCompositeGenerator.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void doGenerate(Resource input, IFileSystemAccess fsa) {
	if (isApplicableTo(input)) {
		String fileExtension = xpectAwareFileExtensionCalculator.getXpectAwareFileExtension(input.getURI());
		for (ISubGenerator subgenerator : getSubGenerators(fileExtension)) {
			subgenerator.doGenerate(input, fsa);
		}
	}
}
 
Example 7
Source Project: xtext-extras   Source File: JvmModelGenerator.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void doGenerate(final Resource input, final IFileSystemAccess fsa) {
  EList<EObject> _contents = input.getContents();
  for (final EObject obj : _contents) {
    this.internalDoGenerate(obj, fsa);
  }
}
 
Example 8
Source Project: xtext-extras   Source File: JvmModelGenerator.java    License: Eclipse Public License 2.0 5 votes vote down vote up
protected void _internalDoGenerate(final JvmDeclaredType type, final IFileSystemAccess fsa) {
  boolean _isDisabled = DisableCodeGenerationAdapter.isDisabled(type);
  if (_isDisabled) {
    return;
  }
  String _qualifiedName = type.getQualifiedName();
  boolean _tripleNotEquals = (_qualifiedName != null);
  if (_tripleNotEquals) {
    String _replace = type.getQualifiedName().replace(".", "/");
    String _plus = (_replace + ".java");
    fsa.generateFile(_plus, this.generateType(type, this.generatorConfigProvider.get(type)));
  }
}
 
Example 9
Source Project: xtext-extras   Source File: JvmModelGenerator.java    License: Eclipse Public License 2.0 5 votes vote down vote up
public void internalDoGenerate(final EObject type, final IFileSystemAccess fsa) {
  if (type instanceof JvmDeclaredType) {
    _internalDoGenerate((JvmDeclaredType)type, fsa);
    return;
  } else if (type != null) {
    _internalDoGenerate(type, fsa);
    return;
  } else {
    throw new IllegalArgumentException("Unhandled parameter types: " +
      Arrays.<Object>asList(type, fsa).toString());
  }
}
 
Example 10
@Override
public void doGenerate(Resource input, IFileSystemAccess fsa) {
	if (input.getContents().isEmpty())
		return;
	EObject root = input.getContents().get(0);
	if (!(root instanceof Model))
		return;
	GenerateDirective generateDirective = ((Model) root).getGenerateDirective();
	if (generateDirective != null) {
		fsa.generateFile(generateFileName(generateDirective), generateFileContents(generateDirective));
	}
}
 
Example 11
@Override
public Set<OutputConfiguration> getOutputConfigurations() {
	OutputConfiguration config = new OutputConfiguration(IFileSystemAccess.DEFAULT_OUTPUT);
	config.setOutputDirectory("src-gen");
	if (useOutputPerSource) {
		SourceMapping sourceMapping = new OutputConfiguration.SourceMapping("src2");
		sourceMapping.setOutputDirectory("src2-gen");
		config.getSourceMappings().add(sourceMapping);
		config.setUseOutputPerSourceFolder(true);
	}
	return ImmutableSet.of(config);
}
 
Example 12
Source Project: xtext-extras   Source File: MyGenerator.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void doGenerate(Resource input, IFileSystemAccess fsa) {
	for (Element ele : Iterables.filter(IteratorExtensions.toIterable(input.getAllContents()),
			Element.class)) {
		String fileName = ele.getName() + ".txt";
		if (fsa instanceof IFileSystemAccess2) {
			if (((IFileSystemAccess2) fsa).isFile(fileName)) {
				((IFileSystemAccess2) fsa).readTextFile(fileName);
			}
		}
		fsa.generateFile(fileName, "object " + ele.getName());
	}
}
 
Example 13
@Override
public void doGenerateStubs(IFileSystemAccess access, IResourceDescription description) {
	for (IEObjectDescription objectDesc : description.getExportedObjects()) {
		String javaStubSource = getJavaStubSource(objectDesc, description);
		if(javaStubSource != null) {
			String javaFileName = getJavaFileName(objectDesc);
			access.generateFile(javaFileName, javaStubSource);
		}
	}
}
 
Example 14
@Override
public void doGenerate(Resource input, IFileSystemAccess fsa) {
	if (input.getContents().isEmpty())
		return;
	EObject root = input.getContents().get(0);
	if (!(root instanceof Model))
		return;
	GenerateDirective generateDirective = ((Model) root).getGenerateDirective();
	if (generateDirective != null) {
		fsa.generateFile(generateFileName(generateDirective), generateFileContents(generateDirective));
	}
}
 
Example 15
@Before
public void setUp () throws Exception {
	project = workspace.createProject();
	fsa.setProject(project);
	fsa.setOutputPath("src-gen");
	fsa.getOutputConfigurations().get(IFileSystemAccess.DEFAULT_OUTPUT).setCreateOutputDirectory(true);
	fsa.setMonitor(new NullProgressMonitor());
}
 
Example 16
@Override
public Set<OutputConfiguration> getOutputConfigurations() {
	OutputConfiguration config = new OutputConfiguration(IFileSystemAccess.DEFAULT_OUTPUT);
	config.setOutputDirectory("src-gen");
	if (useOutputPerSource) {
		SourceMapping sourceMapping = new OutputConfiguration.SourceMapping("src2");
		sourceMapping.setOutputDirectory("src2-gen");
		config.getSourceMappings().add(sourceMapping);
		config.setUseOutputPerSourceFolder(true);
	}
	return ImmutableSet.of(config);
}
 
Example 17
protected void handleChangedContents(Delta delta, IBuildContext context, IFileSystemAccess fileSystemAccess) {
	if (!resourceServiceProvider.canHandle(delta.getUri()))
		return;
	Resource resource = context.getResourceSet().getResource(delta.getUri(), true);
	if (shouldGenerate(resource, context)) {
		CancelIndicator cancelIndicator = CancelIndicator.NullImpl;
		if (fileSystemAccess instanceof EclipseResourceFileSystemAccess2) {
			cancelIndicator = new MonitorBasedCancelIndicator(((EclipseResourceFileSystemAccess2) fileSystemAccess).getMonitor());
		}
		GeneratorContext generatorContext = new GeneratorContext();
		generatorContext.setCancelIndicator(cancelIndicator);
		generator.generate(resource, (IFileSystemAccess2) fileSystemAccess, generatorContext);
		context.needRebuild();
	}
}
 
Example 18
Source Project: xtext-eclipse   Source File: BuilderParticipant.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @since 2.8
 */
protected void saveResourceStorage(Resource resource, IFileSystemAccess access) {
	if (resource instanceof StorageAwareResource && access instanceof IFileSystemAccessExtension3) {
		IResourceStorageFacade storageFacade = ((StorageAwareResource) resource).getResourceStorageFacade();
		if (storageFacade != null) {
			storageFacade.saveResource((StorageAwareResource)resource, (IFileSystemAccessExtension3)access);
		}
	}
}
 
Example 19
Source Project: xtext-xtend   Source File: KeepLocalHistoryTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
public String getKey(final String preferenceName) {
  StringConcatenation _builder = new StringConcatenation();
  _builder.append(EclipseOutputConfigurationProvider.OUTPUT_PREFERENCE_TAG);
  _builder.append(PreferenceConstants.SEPARATOR);
  _builder.append(IFileSystemAccess.DEFAULT_OUTPUT);
  _builder.append(PreferenceConstants.SEPARATOR);
  _builder.append(preferenceName);
  return _builder.toString();
}
 
Example 20
@Override
public Set<OutputConfiguration> getOutputConfigurations() {
	OutputConfiguration defaultOutput = new OutputConfiguration(IFileSystemAccess.DEFAULT_OUTPUT);
	defaultOutput.setDescription("Output folder for generated Java files");
	defaultOutput.setOutputDirectory("xtend-gen");
	defaultOutput.setOverrideExistingResources(true);
	defaultOutput.setCreateOutputDirectory(true);
	defaultOutput.setCanClearOutputDirectory(false);
	defaultOutput.setCleanUpDerivedResources(true);
	defaultOutput.setSetDerivedProperty(true);
	defaultOutput.setKeepLocalHistory(false);
	return newHashSet(defaultOutput);
}
 
Example 21
@Before
public void before() throws Exception {
	Path tmpPath = Paths.get(StandardSystemProperty.JAVA_IO_TMPDIR.value());
	Path output = Files.createTempDirectory(tmpPath, "tempFolder_" + UUID.randomUUID());
	Path resource = Files.createFile(output.resolve(URIBasedFileSystemAccessTest.EXISTING_RESOURCE_NAME));
	resource.toFile().deleteOnExit();
	output.toFile().deleteOnExit();
	OutputConfiguration config = configProvider.getOutputConfigurations().iterator().next();
	config.setOutputDirectory(output.toString());
	Map<String, OutputConfiguration> cfgMap = new HashMap<>();
	cfgMap.put(IFileSystemAccess.DEFAULT_OUTPUT, config);
	fsa.setOutputConfigurations(cfgMap);
	fsa.setConverter(uriConverter);
}
 
Example 22
/**
 * Creates output configuration for regular generated files.
 *
 * @return output configuration
 */
private OutputConfiguration getDefaultConfig() {
  OutputConfiguration config = new OutputConfiguration(IFileSystemAccess.DEFAULT_OUTPUT);
  config.setDescription("Output configuration for generated classes"); //$NON-NLS-1$
  config.setOverrideExistingResources(true);
  config.setOutputDirectory("src-gen"); //$NON-NLS-1$
  return config;
}
 
Example 23
/**
 * If the resource contains errors, any existing storage will be deleted.
 */
@Override
public void saveResource(final StorageAwareResource resource, final IFileSystemAccessExtension3 fsa) {
  // delete storage first in case saving fails
  deleteStorage(resource.getURI(), (IFileSystemAccess) fsa);
  if (resource.getErrors().isEmpty()) {
    super.saveResource(resource, fsa);
  }
}
 
Example 24
Source Project: sarl   Source File: SarlOutputConfigurationProvider.java    License: Apache License 2.0 5 votes vote down vote up
/** Create the standard output configuration.
 *
 * @return the configuration, never {@code null}.
 * @since 0.8
 */
@SuppressWarnings("static-method")
protected OutputConfiguration createStandardOutputConfiguration() {
	final OutputConfiguration defaultOutput = new OutputConfiguration(IFileSystemAccess.DEFAULT_OUTPUT);
	defaultOutput.setDescription(Messages.SarlOutputConfigurationProvider_0);
	defaultOutput.setOutputDirectory(SARLConfig.FOLDER_SOURCE_GENERATED);
	defaultOutput.setOverrideExistingResources(true);
	defaultOutput.setCreateOutputDirectory(true);
	defaultOutput.setCanClearOutputDirectory(false);
	defaultOutput.setCleanUpDerivedResources(true);
	defaultOutput.setSetDerivedProperty(true);
	defaultOutput.setKeepLocalHistory(false);
	return defaultOutput;
}
 
Example 25
Source Project: sarl   Source File: ExtraLanguageGeneratorSupport.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public final void doGenerate(Resource input, IFileSystemAccess fsa) {
	final IFileSystemAccess2 casted = (IFileSystemAccess2) fsa;
	final GeneratorContext context = new GeneratorContext();
	try {
		beforeGenerate(input, casted, context);
		doGenerate(input, casted, context);
	} finally {
		afterGenerate(input, casted, context);
	}
}
 
Example 26
Source Project: sarl   Source File: AbstractExtraLanguageGeneratorTest.java    License: Apache License 2.0 5 votes vote down vote up
protected OutputConfiguration getOutputConfiguration() {
	Iterable<? extends OutputConfiguration> configurations = this.outputConfigurationProvider.getOutputConfigurations();
	OutputConfiguration defaultConfiguration = null;
	for (final OutputConfiguration configuration : configurations) {
		if (Strings.equal(IFileSystemAccess.DEFAULT_OUTPUT, configuration.getName())) {
			defaultConfiguration = configuration;
		} else if (Strings.equal(getOutputConfigurationName(), configuration.getName())) {
			return configuration;
		}
	}
	return defaultConfiguration;
}
 
Example 27
Source Project: joynr   Source File: AbstractJoynrTSGeneratorTest.java    License: Apache License 2.0 5 votes vote down vote up
public void setup(boolean generateProxy, boolean generateProvider) throws Exception {
    temporaryOutputDirectory = Files.createTempDirectory(null).toFile();
    temporaryOutputDirectory.deleteOnExit();
    InvocationArguments arguments = new InvocationArguments();
    arguments.setGenerationLanguage("javascript");
    arguments.setModelPath("src/test/resources");
    arguments.setOutputPath(temporaryOutputDirectory.getAbsolutePath());
    if (generateProxy && !generateProvider) {
        arguments.setTarget("proxy");
    } else if (!generateProxy && generateProvider) {
        arguments.setTarget("provider");
    }

    Injector francaInjector = new FrancaIDLStandaloneSetup().createInjectorAndDoEMFRegistration()
                                                            .createChildInjector(new AbstractModule() {

                                                                @Override
                                                                protected void configure() {
                                                                    bindConstant().annotatedWith(Names.named(JoynrGeneratorExtensions.JOYNR_GENERATOR_CLEAN))
                                                                                  .to(false);
                                                                    bindConstant().annotatedWith(Names.named(JoynrGeneratorExtensions.JOYNR_GENERATOR_GENERATE))
                                                                                  .to(true);
                                                                    bindConstant().annotatedWith(Names.named(NamingUtil.JOYNR_GENERATOR_PACKAGEWITHVERSION))
                                                                                  .to(false);
                                                                    bindConstant().annotatedWith(Names.named(NamingUtil.JOYNR_GENERATOR_NAMEWITHVERSION))
                                                                                  .to(false);
                                                                    bindConstant().annotatedWith(Names.named("generateProxyCode"))
                                                                                  .to(arguments.getGenerateProxyCode());
                                                                    bindConstant().annotatedWith(Names.named("generateProviderCode"))
                                                                                  .to(arguments.getGenerateProviderCode());
                                                                    bind(IFileSystemAccess.class).to(JavaIoFileSystemAccess.class);
                                                                }
                                                            });
    francaInjector.injectMembers(this);
    generator = new JoynrJSGenerator();
    Injector injector = francaInjector.createChildInjector(generator.getGeneratorModule());
    injector.injectMembers(this);
    injector.injectMembers(generator);
    FileSystemAccessUtil.createFileSystemAccess(outputFileSystem, arguments.getOutputPath());
}
 
Example 28
Source Project: joynr   Source File: AbstractJoynrJavaGeneratorTest.java    License: Apache License 2.0 5 votes vote down vote up
public void setup(boolean generateProxy, boolean generateProvider) throws Exception {
    temporaryOutputDirectory = Files.createTempDirectory(null).toFile();
    temporaryOutputDirectory.deleteOnExit();
    InvocationArguments arguments = new InvocationArguments();
    arguments.setGenerationLanguage("java");
    arguments.setModelPath("src/test/resources");
    arguments.setOutputPath(temporaryOutputDirectory.getAbsolutePath());
    if (generateProxy && !generateProvider) {
        arguments.setTarget("proxy");
    } else if (!generateProxy && generateProvider) {
        arguments.setTarget("provider");
    }

    Injector francaInjector = new FrancaIDLStandaloneSetup().createInjectorAndDoEMFRegistration()
                                                            .createChildInjector(new AbstractModule() {

                                                                @Override
                                                                protected void configure() {
                                                                    bindConstant().annotatedWith(Names.named(JoynrGeneratorExtensions.JOYNR_GENERATOR_CLEAN))
                                                                                  .to(false);
                                                                    bindConstant().annotatedWith(Names.named(JoynrGeneratorExtensions.JOYNR_GENERATOR_GENERATE))
                                                                                  .to(true);
                                                                    bindConstant().annotatedWith(Names.named(NamingUtil.JOYNR_GENERATOR_PACKAGEWITHVERSION))
                                                                                  .to(false);
                                                                    bindConstant().annotatedWith(Names.named(NamingUtil.JOYNR_GENERATOR_NAMEWITHVERSION))
                                                                                  .to(false);
                                                                    bindConstant().annotatedWith(Names.named("generateProxyCode"))
                                                                                  .to(arguments.getGenerateProxyCode());
                                                                    bindConstant().annotatedWith(Names.named("generateProviderCode"))
                                                                                  .to(arguments.getGenerateProviderCode());
                                                                    bind(IFileSystemAccess.class).to(JavaIoFileSystemAccess.class);
                                                                }
                                                            });
    francaInjector.injectMembers(this);
    generator = new JoynrJavaGenerator();
    Injector injector = francaInjector.createChildInjector(generator.getGeneratorModule());
    injector.injectMembers(this);
    injector.injectMembers(generator);
    FileSystemAccessUtil.createFileSystemAccess(outputFileSystem, arguments.getOutputPath());
}
 
Example 29
Source Project: joynr   Source File: Executor.java    License: Apache License 2.0 5 votes vote down vote up
public Executor(final InvocationArguments arguments) throws ClassNotFoundException,
                                                     InstantiationException,
                                                     IllegalAccessException {
    arguments.checkArguments();
    this.arguments = arguments;

    // Get an injector and inject into the current instance
    Injector francaInjector = new FrancaIDLStandaloneSetup().createInjectorAndDoEMFRegistration();

    // Use a child injector that contains configuration parameters passed to this Executor
    Injector injector = francaInjector.createChildInjector(new AbstractModule() {
        @Override
        protected void configure() {
            bind(IFileSystemAccess.class).to(JavaIoFileSystemAccess.class);
            String generationId = arguments.getGenerationId();
            if (generationId != null) {
                bindConstant().annotatedWith(Names.named("generationId")).to(generationId);
            } else {
                // Guice does not allow null binding - use an empty string to show there is no generationId
                bindConstant().annotatedWith(Names.named("generationId")).to("");
            }
            bindConstant().annotatedWith(Names.named("generateProxyCode")).to(arguments.getGenerateProxyCode());
            bindConstant().annotatedWith(Names.named("generateProviderCode"))
                          .to(arguments.getGenerateProviderCode());

            bind(Boolean.class).annotatedWith(Names.named(JoynrGeneratorExtensions.JOYNR_GENERATOR_GENERATE))
                               .toInstance(arguments.generate());
            bind(Boolean.class).annotatedWith(Names.named(JoynrGeneratorExtensions.JOYNR_GENERATOR_CLEAN))
                               .toInstance(arguments.clean());
            bind(Boolean.class).annotatedWith(Names.named(NamingUtil.JOYNR_GENERATOR_PACKAGEWITHVERSION))
                               .toInstance(arguments.addVersionToPackage());
            bind(Boolean.class).annotatedWith(Names.named(NamingUtil.JOYNR_GENERATOR_NAMEWITHVERSION))
                               .toInstance(arguments.addVersionToName());
        }
    });
    this.outputFileSystem = injector.getInstance(IFileSystemAccess.class);
    this.generator = createGenerator(injector);
}
 
Example 30
Source Project: joynr   Source File: FileSystemAccessUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static void createFileSystemAccess(IFileSystemAccess fileSystemAccess, String outputDirectory) {

        if (!(fileSystemAccess instanceof AbstractFileSystemAccess)) {
            throw new IllegalStateException("Guice Module configuration wrong: IFileSystemAccess.class shall be binded to a sub type of org.eclipse.xtext.generator.AbstractFileSystemAccess");
        }
        ((AbstractFileSystemAccess) fileSystemAccess).setOutputPath(outputDirectory);
        ((AbstractFileSystemAccess) fileSystemAccess).getOutputConfigurations()
                                                     .get(IFileSystemAccess.DEFAULT_OUTPUT)
                                                     .setCreateOutputDirectory(true);
    }