org.eclipse.emf.ecore.resource.URIConverter Java Examples

The following examples show how to use org.eclipse.emf.ecore.resource.URIConverter. 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
Source File: DefaultSimulationEngineFactory.java    From statecharts with Eclipse Public License 1.0 6 votes vote down vote up
protected ExecutionContext restore(String context, Statechart statechart) {
	try {
		ResourceSet set = new ResourceSetImpl();
		Resource resource = set.createResource(URI.createURI("snapshot.xmi"));
		if (resource == null)
			return null;
		set.getResources().add(resource);
		resource.load(new URIConverter.ReadableInputStream(context, "UTF_8"), Collections.emptyMap());
		IDomain domain = DomainRegistry.getDomain(statechart);
		Injector injector = domain.getInjector(IDomain.FEATURE_SIMULATION);
		ITypeSystem typeSystem = injector.getInstance(ITypeSystem.class);
		if (typeSystem instanceof AbstractTypeSystem) {
			set.getResources().add(((AbstractTypeSystem) typeSystem).getResource());
		}
		EcoreUtil.resolveAll(resource);
		ExecutionContext result = (ExecutionContext) resource.getContents().get(0);
		result.setSnapshot(true);
		return result;
	} catch (Exception e) {
		e.printStackTrace();
	}
	return null;
}
 
Example #2
Source File: SerializationUtil.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
public static String getCompleteContent(XtextResource xr) throws IOException, UnsupportedEncodingException {
	XtextResourceSet resourceSet = (XtextResourceSet) xr.getResourceSet();
	URIConverter uriConverter = resourceSet.getURIConverter();
	URI uri = xr.getURI();
	String encoding = xr.getEncoding();

	InputStream inputStream = null;

	try {
		inputStream = uriConverter.createInputStream(uri);

		return getCompleteContent(encoding, inputStream);
	} finally {
		tryClose(inputStream, null);
	}
}
 
Example #3
Source File: RegisteredGenmodelTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Ignore @Test public void testCanResolveGenmodelURIs() {
	String declaringPlugin = "org.eclipse.emf.ecore";
	String pointId = "generated_package";
	IExtensionPoint point = registry.getExtensionPoint(declaringPlugin + "." + pointId);
	IExtension[] extensions = point.getExtensions();
	for(IExtension extension: extensions) {
		IConfigurationElement[] configurationElements = extension.getConfigurationElements();
		for(IConfigurationElement configurationElement: configurationElements) {
			String attribute = configurationElement.getAttribute("genModel");
			if (attribute != null && attribute.length() != 0) {
				String name = extension.getContributor().getName();
				String uriAsString = "platform:/plugin/" + name + "/" + attribute;
				URI uri = URI.createURI(uriAsString);
				boolean exists = URIConverter.INSTANCE.exists(uri, Collections.emptyMap());
				if (!exists) {
						fail(uriAsString + " does not exist");
				}
			}
		}
	}
}
 
Example #4
Source File: NewGenerationWizard.java    From M2Doc with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Initializes the {@link Generation#getDefinitions() variable definition} for the given {@link Generation}.
 * 
 * @param gen
 *            the {@link Generation}
 */
private void initializeVariableDefinition(Generation gen) {
    final IQueryEnvironment queryEnvironment = Query.newEnvironment();
    try {
        final TemplateCustomProperties properties = POIServices.getInstance().getTemplateCustomProperties(
                URIConverter.INSTANCE, URI.createURI(gen.getTemplateFileName()).resolve(gen.eResource().getURI()));
        ((IQueryEnvironment) queryEnvironment).registerEPackage(EcorePackage.eINSTANCE);
        ((IQueryEnvironment) queryEnvironment).registerCustomClassMapping(
                EcorePackage.eINSTANCE.getEStringToStringMapEntry(), EStringToStringMapEntryImpl.class);
        properties.configureQueryEnvironmentWithResult((IQueryEnvironment) queryEnvironment);
        final ResourceSetImpl defaultResourceSet = new ResourceSetImpl();
        defaultResourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("*",
                new XMIResourceFactoryImpl());
        final ResourceSet resourceSetForModel = M2DocUtils.createResourceSetForModels(new ArrayList<Exception>(),
                queryEnvironment, defaultResourceSet, GenconfUtils.getOptions(gen));
        final List<Definition> newDefinitions = GenconfUtils.getNewDefinitions(gen, properties);
        gen.getDefinitions().addAll(newDefinitions);
        GenconfUtils.initializeVariableDefinition(gen, queryEnvironment, properties, resourceSetForModel);
        M2DocUtils.cleanResourceSetForModels(queryEnvironment, resourceSetForModel);
        // CHECKSTYLE:OFF
    } catch (Exception e) {
        // CHECKSTYLE:ON
        // no initialization if it fails no big deal
    }
}
 
Example #5
Source File: AbstractResourceDescription.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
protected URI getNormalizedURI(Resource resource) {
	URI uri = resource.getURI();
	URIConverter uriConverter = resource.getResourceSet()!=null?resource.getResourceSet().getURIConverter():null;
	if (uri != null && uriConverter != null) {
		if (!uri.isPlatform()) {
			return uriConverter.normalize(uri);
		}
		// This is a fix for resources which have been loaded using a platform:/plugin URI
		// This happens when one resource has absolute references using a platform:/plugin uri and the corresponding
		// ResourceDescriptionManager resolves references in the first phase, i.e. during EObjectDecription computation.
		// EMF's GenModelResourceDescriptionStrategy does so as it needs to call GenModel.reconcile() eagerly.
		if (uri.isPlatformPlugin()) {
			URI resourceURI = uri.replacePrefix(URI.createURI("platform:/plugin/"), URI.createURI("platform:/resource/"));
			if (uriConverter.normalize(uri).equals(uriConverter.normalize(resourceURI)))
				return resourceURI;
		}
	}
	return uri;
}
 
Example #6
Source File: XStatefulIncrementalBuilder.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
private void removeGeneratedFiles(URI source, XSource2GeneratedMapping source2GeneratedMapping) {
	Map<URI, String> outputConfigMap = source2GeneratedMapping.deleteSourceAndGetOutputConfigs(source);
	IResourceServiceProvider serviceProvider = context.getResourceServiceProvider(source);
	IContextualOutputConfigurationProvider2 outputConfigurationProvider = serviceProvider
			.get(IContextualOutputConfigurationProvider2.class);
	XtextResourceSet resourceSet = request.getResourceSet();
	Set<OutputConfiguration> outputConfigs = outputConfigurationProvider.getOutputConfigurations(resourceSet);
	Map<String, OutputConfiguration> outputConfigsMap = Maps.uniqueIndex(outputConfigs,
			OutputConfiguration::getName);
	URIConverter uriConverter = resourceSet.getURIConverter();
	for (URI generated : outputConfigMap.keySet()) {
		OutputConfiguration config = outputConfigsMap.get(outputConfigMap.get(generated));
		if (config != null && config.isCleanUpDerivedResources()) {
			try {
				uriConverter.delete(generated, CollectionLiterals.emptyMap());
				request.setResultDeleteFile(generated);
			} catch (IOException e) {
				Exceptions.sneakyThrow(e);
			}
		}
	}
}
 
Example #7
Source File: EMFGeneratorFragment2.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
private void registerUsedGenModel(final URIConverter converter, final Grammar grammar) {
  final URI genModelUri = this.getGenModelUri(grammar);
  boolean _exists = converter.exists(genModelUri, null);
  if (_exists) {
    try {
      GenModelHelper _genModelHelper = new GenModelHelper();
      XtextResourceSet _xtextResourceSet = new XtextResourceSet();
      _genModelHelper.registerGenModel(_xtextResourceSet, genModelUri);
    } catch (final Throwable _t) {
      if (_t instanceof Exception) {
        final Exception e = (Exception)_t;
        EMFGeneratorFragment2.LOG.error("Failed to register GenModel", e);
      } else {
        throw Exceptions.sneakyThrow(_t);
      }
    }
  }
}
 
Example #8
Source File: XtextDocumentProvider.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * @since 2.3
 */
protected void updateCache(IURIEditorInput input) throws CoreException {
	URIInfo info= (URIInfo) getElementInfo(input);
	if (info != null) {
		URI emfURI = toEmfUri(input.getURI());
		if (emfURI != null) {
			boolean readOnly = true;
			if (emfURI.isFile() && !emfURI.isArchive()) {
				// TODO: Should we use the ResourceSet somehow to obtain the URIConverter for the file protocol?
				// see also todo below, but don't run into a stackoverflow ;-)
				Map<String, ?> attributes = URIConverter.INSTANCE.getAttributes(emfURI, null);
				readOnly = Boolean.TRUE.equals(attributes.get(URIConverter.ATTRIBUTE_READ_ONLY));
			}
			info.isReadOnly=  readOnly;
			info.isModifiable= !readOnly;
		}
		info.updateCache= false;
	}
}
 
Example #9
Source File: FlatResourceSetBasedAllContainersState.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public Collection<URI> getContainedURIs(String containerHandle) {
	if (!HANDLE.equals(containerHandle))
		return Collections.emptySet();
	if (resourceSet instanceof XtextResourceSet) {
		ResourceDescriptionsData descriptionsData = findResourceDescriptionsData(resourceSet);
		if (descriptionsData != null) {
			return descriptionsData.getAllURIs();
		}
		return newArrayList(((XtextResourceSet) resourceSet).getNormalizationMap().values());
	}
	List<URI> uris = Lists.newArrayListWithCapacity(resourceSet.getResources().size());
	URIConverter uriConverter = resourceSet.getURIConverter();
	for (Resource r : resourceSet.getResources())
		uris.add(uriConverter.normalize(r.getURI()));
	return uris;
}
 
Example #10
Source File: MImageImpl.java    From M2Doc with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Constructor with enforced image type.
 * 
 * @param uriConverter
 *            the {@link URIConverter uri converter} to use
 * @param uri
 *            the {@link URI}
 * @param type
 *            the picture {@link PictureType type}
 */
public MImageImpl(URIConverter uriConverter, URI uri, PictureType type) {
    this.uriConverter = uriConverter;
    this.uri = uri;
    this.type = type;
    try (InputStream input = getInputStream()) {
        final BufferedImage image = ImageIO.read(input);
        if (image != null) {
            width = image.getWidth();
            height = image.getHeight();
            conserveRatio = true;
            ratio = ((double) width) / ((double) height);
        } else {
            conserveRatio = false;
            ratio = -1;
        }
    } catch (IOException e) {
        // will continue with out ratio and width x height preset
        ratio = -1;
    }
}
 
Example #11
Source File: CustomClassEcoreGeneratorFragment.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Generates a stub for a custom class (e.g. FooImplCustom) into the {@link CustomClassEcoreGeneratorFragment#javaModelSrcDirectories specified SRC folder}.
 *
 * @param from
 *          qualified name of default implementation class (e.g. FooImpl) to extend
 * @param customClassName
 *          qualified name of custom class to generate
 * @param path
 *          URI for resource to generate into
 */
@SuppressWarnings({"nls", "PMD.InsufficientStringBufferDeclaration"})
protected void generateCustomClassStub(final String from, final String customClassName, final URI path) {
  StringBuilder sb = new StringBuilder();
  // sb.append(copyright()).append("\n");
  int lastIndexOfDot = customClassName.lastIndexOf('.');
  sb.append("package ").append(customClassName.substring(0, lastIndexOfDot)).append(";\n\n\n");
  sb.append("public class ").append(customClassName.substring(lastIndexOfDot + 1)).append(" extends ").append(from).append(" {\n\n");
  sb.append("}\n");

  try {
    OutputStream stream = URIConverter.INSTANCE.createOutputStream(path);
    stream.write(sb.toString().getBytes());
    stream.close();
  } catch (IOException e) {
    throw new WrappedException(e);
  }
}
 
Example #12
Source File: TemplateCustomPropertiesTests.java    From M2Doc with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void getMissingVariablesInFooter() throws IOException, InvalidFormatException {
    try (XWPFDocument document = POIServices.getInstance().getXWPFDocument(URIConverter.INSTANCE,
            URI.createFileURI("resources/document/properties/missingVariablesInFooter.docx"));) {
        final TemplateCustomProperties properties = new TemplateCustomProperties(document);
        final List<String> missingVariables = properties.getMissingVariables();

        assertEquals(16, missingVariables.size());
        assertEquals("linkNamelinkText", missingVariables.get(0));
        assertEquals("bookmarkName", missingVariables.get(1));
        assertEquals("queryInBookmark", missingVariables.get(2));
        assertEquals("ifCondition", missingVariables.get(3));
        assertEquals("queryInIf", missingVariables.get(4));
        assertEquals("elseIfCondition", missingVariables.get(5));
        assertEquals("queryInElseIf", missingVariables.get(6));
        assertEquals("queryInElse", missingVariables.get(7));
        assertEquals("letExpression", missingVariables.get(8));
        assertEquals("queryInLet", missingVariables.get(9));
        assertEquals("forExpression", missingVariables.get(10));
        assertEquals("queryInFor", missingVariables.get(11));
        assertEquals("queryExpression", missingVariables.get(12));
        assertEquals("aqlInSelect", missingVariables.get(13));
        assertEquals("aqlLetExpression", missingVariables.get(14));
        assertEquals("aqlLetBody", missingVariables.get(15));
    }
}
 
Example #13
Source File: TemplateCustomPropertiesTests.java    From M2Doc with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void getMissingVariablesInHeader() throws IOException, InvalidFormatException {
    try (XWPFDocument document = POIServices.getInstance().getXWPFDocument(URIConverter.INSTANCE,
            URI.createFileURI("resources/document/properties/missingVariablesInHeader.docx"));) {
        final TemplateCustomProperties properties = new TemplateCustomProperties(document);
        final List<String> missingVariables = properties.getMissingVariables();

        assertEquals(16, missingVariables.size());
        assertEquals("linkNamelinkText", missingVariables.get(0));
        assertEquals("bookmarkName", missingVariables.get(1));
        assertEquals("queryInBookmark", missingVariables.get(2));
        assertEquals("ifCondition", missingVariables.get(3));
        assertEquals("queryInIf", missingVariables.get(4));
        assertEquals("elseIfCondition", missingVariables.get(5));
        assertEquals("queryInElseIf", missingVariables.get(6));
        assertEquals("queryInElse", missingVariables.get(7));
        assertEquals("letExpression", missingVariables.get(8));
        assertEquals("queryInLet", missingVariables.get(9));
        assertEquals("forExpression", missingVariables.get(10));
        assertEquals("queryInFor", missingVariables.get(11));
        assertEquals("queryExpression", missingVariables.get(12));
        assertEquals("aqlInSelect", missingVariables.get(13));
        assertEquals("aqlLetExpression", missingVariables.get(14));
        assertEquals("aqlLetBody", missingVariables.get(15));
    }
}
 
Example #14
Source File: TemplateCustomPropertiesTests.java    From M2Doc with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void getMissingVariables() throws IOException, InvalidFormatException {
    try (XWPFDocument document = POIServices.getInstance().getXWPFDocument(URIConverter.INSTANCE,
            URI.createFileURI("resources/document/properties/missingVariables.docx"));) {
        final TemplateCustomProperties properties = new TemplateCustomProperties(document);
        final List<String> missingVariables = properties.getMissingVariables();

        assertEquals(16, missingVariables.size());
        assertEquals("linkNamelinkText", missingVariables.get(0));
        assertEquals("bookmarkName", missingVariables.get(1));
        assertEquals("queryInBookmark", missingVariables.get(2));
        assertEquals("ifCondition", missingVariables.get(3));
        assertEquals("queryInIf", missingVariables.get(4));
        assertEquals("elseIfCondition", missingVariables.get(5));
        assertEquals("queryInElseIf", missingVariables.get(6));
        assertEquals("queryInElse", missingVariables.get(7));
        assertEquals("letExpression", missingVariables.get(8));
        assertEquals("queryInLet", missingVariables.get(9));
        assertEquals("forExpression", missingVariables.get(10));
        assertEquals("queryInFor", missingVariables.get(11));
        assertEquals("queryExpression", missingVariables.get(12));
        assertEquals("aqlInSelect", missingVariables.get(13));
        assertEquals("aqlLetExpression", missingVariables.get(14));
        assertEquals("aqlLetBody", missingVariables.get(15));
    }
}
 
Example #15
Source File: CheckGenModelUtil.java    From dsl-devkit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Given an array of {@link IContainers}, searches through all *.genmodel files in all {@link IFolders}, ignoring nested folders, trying to find a
 * {@link GenModel} for the given {@link EPackage}.
 *
 * @param containers
 *          To search, may be empty, but must not be {@code null}
 * @param baseURI
 *          of these containers; must not be {@code null}
 * @param ePackage
 *          to find a genmodel for; must not be {@code null}
 * @param resourceSet
 *          to use for resource loading; must not be {@code null}
 * @return the genmodel, if found, or {@code null} if not.
 * @throws CoreException
 *           if enumerating folder contents does so
 */
private static GenModel findGenModelInContainers(final IContainer[] containers, final URI baseURI, final EPackage ePackage, final ResourceSet resourceSet) throws CoreException {
  Preconditions.checkNotNull(containers);
  Preconditions.checkNotNull(baseURI);
  Preconditions.checkNotNull(ePackage);
  Preconditions.checkNotNull(resourceSet);
  final URIConverter uriConverter = resourceSet.getURIConverter();
  for (IContainer container : containers) {
    if (!(container instanceof IFolder)) {
      continue;
    }
    IResource[] resources = container.members();
    for (IResource r : resources) {
      if (r.exists() && r instanceof IFile && GENMODEL_EXTENSION.equals(r.getFileExtension())) {
        URI uriToTry = uriConverter.normalize(baseURI.appendSegment(URI.encodeSegment(r.getName(), false)));
        GenModel result = loadGenModel(uriToTry, ePackage, resourceSet);
        if (result != null) {
          return result;
        }
      }
    }
  }
  return null;
}
 
Example #16
Source File: EcoreUtil2.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * checks whether the given URI can be loaded given the context. I.e. there's a resource set with a corresponding
 * resource factory and the physical resource exists.
 */
public static boolean isValidUri(Resource resource, URI uri) {
	if (uri == null || uri.isEmpty()) {
		return false;
	}
	URI newURI = getResolvedImportUri(resource, uri);
	try {
		ResourceSet resourceSet = resource.getResourceSet();
		if (resourceSet.getResource(uri, false) != null)
			return true;
		URIConverter uriConverter = resourceSet.getURIConverter();
		URI normalized = uriConverter.normalize(newURI);
		if (normalized != null)
			// fix for https://bugs.eclipse.org/bugs/show_bug.cgi?id=326760
			if("platform".equals(normalized.scheme()) && !normalized.isPlatform()) 
				return false;
			return uriConverter.exists(normalized, Collections.emptyMap());
	} catch (RuntimeException e) { // thrown by org.eclipse.emf.ecore.resource.ResourceSet#getResource(URI, boolean)
		log.trace("Cannot load resource: " + newURI, e);
	}
	return false;
}
 
Example #17
Source File: TemplateCustomPropertiesTests.java    From M2Doc with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void getUnusedVariables() throws IOException, InvalidFormatException {
    try (XWPFDocument document = POIServices.getInstance().getXWPFDocument(URIConverter.INSTANCE,
            URI.createFileURI("resources/document/properties/unusedVariables.docx"));) {
        final TemplateCustomProperties properties = new TemplateCustomProperties(document);
        final List<String> unusedVariables = properties.getUnusedDeclarations();

        assertEquals(1, unusedVariables.size());
        assertEquals("unusedVariable", unusedVariables.get(0));
    }
}
 
Example #18
Source File: FindingsTemplateService.java    From elexis-3-core with Eclipse Public License 1.0 5 votes vote down vote up
public FindingsTemplates getFindingsTemplates(String templateId){
	Assert.isNotNull(templateId);
	templateId = templateId.replaceAll(" ", "_");
	Optional<IBlob> blob =
		coreModelService.load(FINDINGS_TEMPLATE_ID_PREFIX + templateId, IBlob.class);
	if (blob.isPresent()) {
		String stringContent = blob.get().getStringContent();
		if (stringContent != null && !stringContent.isEmpty()) {
			try {
				Resource.Factory.Registry reg = Resource.Factory.Registry.INSTANCE;
				Map<String, Object> m = reg.getExtensionToFactoryMap();
				m.put("xmi", new XMIResourceFactoryImpl());
				// Obtain a new resource set
				ResourceSet resSet = new ResourceSetImpl();
				
				// Get the resource
				Resource resource =
					resSet.createResource(URI.createURI("findingsTemplate.xml"));
				resource.load(new URIConverter.ReadableInputStream(stringContent), null);
				return (FindingsTemplates) resource.getContents().get(0);
			} catch (IOException e) {
				LoggerFactory.getLogger(FindingsTemplateService.class)
					.error("read findings templates error", e);
			}
		}
	}
	
	ModelFactory factory = ModelFactory.eINSTANCE;
	FindingsTemplates findingsTemplates = factory.createFindingsTemplates();
	findingsTemplates.setId(FINDINGS_TEMPLATE_ID_PREFIX + templateId);
	findingsTemplates.setTitle("Standard Vorlagen");
	return findingsTemplates;
}
 
Example #19
Source File: TemplateCustomPropertiesTests.java    From M2Doc with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void deleteProperties() throws IOException {
    final File tempFile = File.createTempFile("properties", "-add.docx");
    final URI tempFileURI = URI.createURI(tempFile.toURI().toString(), false);
    tempFile.deleteOnExit();
    try (XWPFDocument document = POIServices.getInstance().getXWPFDocument(URIConverter.INSTANCE,
            URI.createFileURI("resources/document/properties/properties-template.docx"));) {
        final TemplateCustomProperties properties = new TemplateCustomProperties(document);

        assertEquals(2, properties.getPackagesURIs().size());
        properties.getPackagesURIs().clear();

        assertEquals(2, properties.getServiceClasses().size());
        properties.getServiceClasses().clear();

        assertEquals(3, properties.getVariables().size());
        properties.getVariables().clear();

        properties.save();
        POIServices.getInstance().saveFile(URIConverter.INSTANCE, document, tempFileURI);
    }

    try (XWPFDocument document = POIServices.getInstance().getXWPFDocument(URIConverter.INSTANCE, tempFileURI);) {
        final TemplateCustomProperties info = new TemplateCustomProperties(document);

        assertEquals(0, info.getPackagesURIs().size());

        assertEquals(0, info.getServiceClasses().size());

        assertEquals(0, info.getVariables().size());
    }
}
 
Example #20
Source File: XtextValidationTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testBug322875_02() throws Exception {
	URIConverter.URI_MAP.put(URI.createURI("platform:/plugin/org.eclipse.emf.ecore/model/Ecore.ecore"), URI.createURI(getClass().getResource("/model/Ecore.ecore").toExternalForm()));
	String testGrammar = "grammar foo.Bar with org.eclipse.xtext.common.Terminals\n " +
			" import 'platform:/plugin/org.eclipse.emf.ecore/model/Ecore.ecore'  " +
			"Model returns EClass: name=ID;";
	XtextResource resource = getResourceFromString(testGrammar);
	Diagnostic diag = Diagnostician.INSTANCE.validate(resource.getContents().get(0));
	assertNotNull("diag", diag);
	assertEquals(diag.toString(), 0, diag.getChildren().size());
	assertEquals("diag.isOk", Diagnostic.OK, diag.getSeverity());
}
 
Example #21
Source File: AbstractLibraryGlobalScopeProvider.java    From statecharts with Eclipse Public License 1.0 5 votes vote down vote up
protected Iterable<URI> getValidLibraries(Resource context) {
	return Iterables.filter(getLibraries(context), new Predicate<URI>() {
		@Override
		public boolean apply(URI input) {
			return URIConverter.INSTANCE.exists(input, Collections.EMPTY_MAP);
		}
	});
}
 
Example #22
Source File: UserContentManager.java    From M2Doc with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Constructor.
 * 
 * @param uriConverter
 *            the {@link URIConverter uri converter} to use.
 * @param sourceURI
 *            the source {@link URI}
 * @param destinationURI
 *            the destination {@link URI}
 */
public UserContentManager(URIConverter uriConverter, URI sourceURI, URI destinationURI) {
    this.uriConverter = uriConverter;
    this.sourceURI = sourceURI;
    this.destinationURI = destinationURI;
    if (uriConverter != null && destinationURI != null
        && uriConverter.exists(destinationURI, Collections.EMPTY_MAP)) {
        // Copy file
        uriConverter.getURIHandlers().add(0, uriHandler);
        memoryCopy = memoryCopy(destinationURI);
    } else {
        memoryCopy = null;
    }
}
 
Example #23
Source File: TemplateCustomPropertiesTests.java    From M2Doc with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void getM2DocVersion() throws IOException {
    try (XWPFDocument document = POIServices.getInstance().getXWPFDocument(URIConverter.INSTANCE,
            URI.createFileURI("resources/document/properties/properties-template-m2docVersion.docx"));) {
        final TemplateCustomProperties properties = new TemplateCustomProperties(document);

        assertEquals("2.0.0", properties.getM2DocVersion());
    }
}
 
Example #24
Source File: TemplateCustomPropertiesTests.java    From M2Doc with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Check that reading a blank metamodel URI from a docx file does not fail (throw an exception for instance) but that no MM URI is
 * returned.
 * 
 * @throws IOException
 *             If IO problem
 * @throws InvalidFormatException
 *             If format problem
 */
@Test
public void testReadBlankMMUri() throws IOException, InvalidFormatException {
    try (XWPFDocument document = POIServices.getInstance().getXWPFDocument(URIConverter.INSTANCE,
            URI.createFileURI("resources/document/properties/noUri.docx"));) {
        final TemplateCustomProperties properties = new TemplateCustomProperties(document);
        final List<String> uris = properties.getPackagesURIs();
        assertTrue(uris.isEmpty());
    }
}
 
Example #25
Source File: TemplateCustomPropertiesTests.java    From M2Doc with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Check that reading invalid variables from a docx file does not fail (throw an exception for instance) but that invalid variables are
 * simply ignored.
 * 
 * @throws IOException
 *             If IO problem
 * @throws InvalidFormatException
 *             If format problem
 */
@Test
public void parseInvalidVariables() throws IOException, InvalidFormatException {
    try (XWPFDocument document = POIServices.getInstance().getXWPFDocument(URIConverter.INSTANCE,
            URI.createFileURI("resources/document/properties/emptyVar.docx"));) {
        final TemplateCustomProperties properties = new TemplateCustomProperties(document);
        final Map<String, String> variables = properties.getVariables();
        assertTrue(variables.isEmpty());
    }
}
 
Example #26
Source File: AbstractFileSystemSupport.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
protected Boolean isFolder(final URI uri) {
  Boolean _xblockexpression = null;
  {
    final Object directory = this.getAttribute(uri, URIConverter.ATTRIBUTE_DIRECTORY);
    Boolean _xifexpression = null;
    if ((directory instanceof Boolean)) {
      _xifexpression = ((Boolean)directory);
    } else {
      _xifexpression = Boolean.valueOf(false);
    }
    _xblockexpression = _xifexpression;
  }
  return _xblockexpression;
}
 
Example #27
Source File: AddInServlet.java    From M2Doc with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Gets the validation.
 * 
 * @param queryEnvironment
 *            the {@link IReadOnlyQueryEnvironment}
 * @param uriConverter
 *            the {@link URIConverter}
 * @param templateURI
 *            the template {@link URI}
 * @param req
 *            the {@link HttpServletRequest}
 * @param resp
 *            the {@link HttpServletResponse}
 * @throws IOException
 *             if the response can't be written
 */
private void getValidation(IReadOnlyQueryEnvironment queryEnvironment, URIConverter uriConverter, URI templateURI,
        HttpServletRequest req, HttpServletResponse resp) throws IOException {
    final String expression = req.getParameter(EXPRESSION_PARAMETER);
    if (expression != null) {
        try (XWPFDocument document = POIServices.getInstance().getXWPFDocument(uriConverter, templateURI)) {
            final TemplateCustomProperties properties = new TemplateCustomProperties(document);
            final AstValidator validator = new AstValidator(new ValidationServices(queryEnvironment));
            final Map<String, Set<IType>> variableTypes = properties.getVariableTypes(validator, queryEnvironment);
            variableTypes.putAll(
                    parseVariableTypes(queryEnvironment, validator, variableTypes, uriConverter, templateURI));
            IQueryValidationEngine engine = new QueryValidationEngine(queryEnvironment);
            final IValidationResult result = engine.validate(expression, variableTypes);
            resp.setStatus(HttpServletResponse.SC_OK);
            resp.setContentType(MimeTypes.Type.APPLICATION_JSON_UTF_8.toString());
            final List<Map<String, Object>> messages = new ArrayList<>();
            for (IValidationMessage message : result.getMessages()) {
                final Map<String, Object> map = new HashMap<>();
                messages.add(map);
                map.put("level", message.getLevel());
                map.put("start", message.getStartPosition());
                map.put("end", message.getEndPosition());
                map.put("message", message.getMessage());
            }
            resp.getWriter().print(JSON.toString(messages));
        } catch (IOException e) {
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            resp.setContentType(MimeTypes.Type.TEXT_PLAIN_UTF_8.toString());
            resp.getWriter().print(String.format(CAN_T_LOAD_TEMPLATE, e.getMessage()));
        }
    } else {
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        resp.setContentType(MimeTypes.Type.TEXT_PLAIN_UTF_8.toString());
        resp.getWriter().print(String.format(PARAMETER_IS_MANDATORY, EXPRESSION_PARAMETER));
    }
}
 
Example #28
Source File: AbstractFileSystemSupport.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
protected Long getLastModification(final URI uri) {
  Long _xblockexpression = null;
  {
    final Object timeStamp = this.getAttribute(uri, URIConverter.ATTRIBUTE_TIME_STAMP);
    Long _xifexpression = null;
    if ((timeStamp instanceof Long)) {
      _xifexpression = ((Long)timeStamp);
    } else {
      _xifexpression = Long.valueOf(0L);
    }
    _xblockexpression = _xifexpression;
  }
  return _xblockexpression;
}
 
Example #29
Source File: TemplateCustomPropertiesTests.java    From M2Doc with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void parseVariable() throws IOException, InvalidFormatException {
    try (XWPFDocument document = POIServices.getInstance().getXWPFDocument(URIConverter.INSTANCE,
            URI.createFileURI("resources/document/properties/properties-template.docx"));) {
        final TemplateCustomProperties properties = new TemplateCustomProperties(document);
        final Map<String, String> variables = properties.getVariables();
        assertEquals(3, variables.size());
        assertEquals("ecore::EPackage", variables.get("variable1"));
        assertEquals("ecore::EClass", variables.get("variable2"));
        assertEquals(null, variables.get("variable3"));
    }
}
 
Example #30
Source File: AddInServlet.java    From M2Doc with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Gets the evaluation in a HTML format.
 * 
 * @param queryEnvironment
 *            the {@link IReadOnlyQueryEnvironment}
 * @param uriConverter
 *            the {@link URIConverter}
 * @param templateURI
 *            the template {@link URI}
 * @param variables
 *            the declared variable values
 * @param req
 *            the {@link HttpServletRequest}
 * @param resp
 *            the {@link HttpServletResponse}
 * @throws IOException
 *             if the response can't be written
 */
private void getEvaluation(IReadOnlyQueryEnvironment queryEnvironment, URIConverter uriConverter, URI templateURI,
        Map<String, Object> variables, HttpServletRequest req, HttpServletResponse resp) throws IOException {
    final String expression = req.getParameter(EXPRESSION_PARAMETER);
    if (expression != null) {
        try (XWPFDocument document = POIServices.getInstance().getXWPFDocument(uriConverter, templateURI)) {
            final QueryEvaluationEngine engine = new QueryEvaluationEngine((IQueryEnvironment) queryEnvironment);
            final Map<String, Object> allVariables = new HashMap<>(variables);
            allVariables
                    .putAll(parseVariableValues(queryEnvironment, engine, allVariables, uriConverter, templateURI));
            final IQueryBuilderEngine builder = new QueryBuilderEngine(queryEnvironment);
            final AstResult build = builder.build(expression);
            final EvaluationResult result = engine.eval(build, allVariables);

            resp.setStatus(HttpServletResponse.SC_OK);
            resp.setContentType(MimeTypes.Type.TEXT_HTML_UTF_8.toString());
            resp.getWriter().print(HTML_SERIALIZER.serialize(result.getResult()));
        } catch (IOException e) {
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            resp.setContentType(MimeTypes.Type.TEXT_PLAIN_UTF_8.toString());
            resp.getWriter().print(String.format(CAN_T_LOAD_TEMPLATE, e.getMessage()));
        }
    } else {
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        resp.setContentType(MimeTypes.Type.TEXT_PLAIN_UTF_8.toString());
        resp.getWriter().print(String.format(PARAMETER_IS_MANDATORY, EXPRESSION_PARAMETER));
    }
}