Java 类org.eclipse.emf.ecore.resource.URIConverter 实例源码

项目:gemoc-studio-modeldebugging    文件:DebugPermissionProvider.java   
@Override
public boolean provides(ResourceSet set) {
    final boolean res;

    if (set != null && set.getURIConverter() != null) {
        URIConverter converter = set.getURIConverter();
        if (converter.getURIHandlers().size() > 0) {
            res = converter.getURIHandlers().get(0) instanceof DebugURIHandler;
        } else {
            res = false;
        }
    } else {
        res = false;
    }

    return res;
}
项目:rest-modeling-framework    文件:TypeDeclarationResolverTest.java   
@Ignore
@Test
public void api() {
    final File apiFile = new File("/Users/mkoester/Development/commercetools-api-reference/api.raml");
    assumeTrue(apiFile.exists());

    final URI apiUri = URI.createURI(apiFile.toURI().toString());
    final URIConverter uriConverter = new RamlResourceSet().getURIConverter();
    final RAMLCustomLexer lexer = new RAMLCustomLexer(apiUri, uriConverter);
    final TokenStream tokenStream = new CommonTokenStream(lexer);

    final RAMLParser parser = new RAMLParser(tokenStream);
    final Resource resource = new RamlResourceSet().createResource(apiUri);

    final Scope scope = Scope.of(resource);
    final TypeDeclarationResolver resolver = new TypeDeclarationResolver();
    resolver.resolve(parser.api(), scope);

    assertThat(resource.getErrors()).isEmpty();
}
项目:M2Doc    文件:M2DocTestUtils.java   
/**
 * Gets the textual element of the .docx at the given {@link URI}.
 * 
 * @param uriConverter
 *            the {@link URIConverter}
 * @param uri
 *            the .docx {@link URI}
 * @return the textual element of the .docx at the given {@link URI}
 */
public static String getTextContent(URIConverter uriConverter, URI uri) {
    String result = "";

    try (InputStream is = uriConverter.createInputStream(uri);
            OPCPackage oPackage = OPCPackage.open(is);
            XWPFDocument document = new XWPFDocument(oPackage);
            XWPFWordExtractor ex = new XWPFWordExtractor(document);) {

        result += "===== Document Text ====\n";
        result += ex.getText();
        // CHECKSTYLE:OFF
    } catch (Throwable e) {
        // CHECKSTYLE:ON
        /*
         * if for some reason we can't use POI to get the text content then move along, we'll still get the XML and hashs
         */
    }
    return result;
}
项目:M2Doc    文件:TemplateCustomPropertiesTests.java   
@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));
    }
}
项目:M2Doc    文件:CustomGenconfEditor.java   
/**
 * Updates {@link TemplateCustomProperties}.
 * 
 * @param uri
 *            the template {@link URI}
 */
private void updateTemplateCustomProperties(URI uri) {
    final URI absoluteURI = uri.resolve(getGenconfResource().getURI());
    if (URIConverter.INSTANCE.exists(absoluteURI, null)) {
        try {
            templateCustomProperties = POIServices.getInstance().getTemplateCustomProperties(absoluteURI);
            final Generation generation = getGeneration();
            final List<Definition> newDefinitions = GenconfUtils.getNewDefinitions(generation,
                    templateCustomProperties);
            editingDomain.getCommandStack().execute(AddCommand.create(editingDomain, generation,
                    GenconfPackage.GENERATION__DEFINITIONS, newDefinitions));
            // CHECKSTYLE:OFF
        } catch (Exception e) {
            // CHECKSTYLE:ON
            templateCustomProperties = null;
        }
    }
}
项目:M2Doc    文件:MImageImpl.java   
/**
 * 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 {
        final BufferedImage image = ImageIO.read(getInputStream());
        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;
    }
}
项目:M2Doc    文件:M2DocUtils.java   
/**
 * Prepares the given {@link IQueryEnvironment} for M2Doc services.
 * 
 * @param queryEnvironment
 *            the {@link IQueryEnvironment}
 * @param uriConverter
 *            the {@link URIConverter uri converter} to use.
 * @param templateURI
 *            the template {@link URI}
 * @param options
 *            the {@link Map} of options
 */
public static void prepareEnvironmentServices(IQueryEnvironment queryEnvironment, URIConverter uriConverter,
        URI templateURI, Map<String, String> options) {

    Set<IService> services = ServiceUtils.getServices(queryEnvironment, BooleanServices.class);
    ServiceUtils.registerServices(queryEnvironment, services);
    services = ServiceUtils.getServices(queryEnvironment, LinkServices.class);
    ServiceUtils.registerServices(queryEnvironment, services);
    services = ServiceUtils.getServices(queryEnvironment, PaginationServices.class);
    ServiceUtils.registerServices(queryEnvironment, services);
    services = ServiceUtils.getServices(queryEnvironment, new ImageServices(uriConverter, templateURI));
    ServiceUtils.registerServices(queryEnvironment, services);
    services = ServiceUtils.getServices(queryEnvironment, new ExcelServices(uriConverter, templateURI));
    ServiceUtils.registerServices(queryEnvironment, services);
    for (IServicesConfigurator configurator : getConfigurators()) {
        ServiceUtils.registerServices(queryEnvironment, configurator.getServices(queryEnvironment, options));
    }
}
项目:M2Doc    文件:SiriusServiceConfigurator.java   
/**
 * Gets the {@link Session} option from the generation URI string.
 * 
 * @param genConfURIStr
 *            the generation URI string
 * @return the {@link Session} option from the generation URI string
 */
protected String getSessionString(final String genConfURIStr) {
    final String res;

    if (genConfURIStr != null) {
        final URI genConfURI = URI.createURI(genConfURIStr, false);
        if (URIConverter.INSTANCE.exists(genConfURI, Collections.emptyMap()) && genConfURI.isPlatformResource()) {
            res = getSessionFromPlatformResource(genConfURI);
        } else {
            res = null;
        }
    } else {
        res = null;
    }

    return res;
}
项目:M2Doc    文件:SiriusServiceConfigurator.java   
@Override
public Set<IService> getServices(IReadOnlyQueryEnvironment queryEnvironment, Map<String, String> options) {
    final Set<IService> res = new LinkedHashSet<>();

    final String sessionURIStr = options.get(M2DocSiriusUtils.SIRIUS_SESSION_OPTION);
    if (sessionURIStr != null) {
        URI sessionURI = URI.createURI(sessionURIStr, false);
        final String genconfURIStr = options.get(GenconfUtils.GENCONF_URI_OPTION);
        if (genconfURIStr != null) {
            sessionURI = sessionURI.resolve(URI.createURI(genconfURIStr));
        }
        if (URIConverter.INSTANCE.exists(sessionURI, Collections.emptyMap())) {
            final Session session = SessionManager.INSTANCE.getSession(sessionURI, new NullProgressMonitor());
            final M2DocSiriusServices serviceInstance = new M2DocSiriusServices(session);
            res.addAll(ServiceUtils.getServices(queryEnvironment, serviceInstance));
            services.put(queryEnvironment, serviceInstance);
        }
    }

    return res;
}
项目:M2Doc    文件:SiriusServiceConfigurator.java   
@Override
public Map<String, List<Diagnostic>> validate(IReadOnlyQueryEnvironment queryEnvironment,
        Map<String, String> options) {
    final Map<String, List<Diagnostic>> res = new HashMap<>();

    final String sessionURIStr = options.get(M2DocSiriusUtils.SIRIUS_SESSION_OPTION);
    if (sessionURIStr != null) {
        URI sessionURI = URI.createURI(sessionURIStr, false);
        final String genconfURIStr = options.get(GenconfUtils.GENCONF_URI_OPTION);
        if (genconfURIStr != null) {
            sessionURI = sessionURI.resolve(URI.createURI(genconfURIStr, false));
        }
        if (!URIConverter.INSTANCE.exists(sessionURI, Collections.emptyMap())) {
            final List<Diagnostic> diagnostics = new ArrayList<>();
            res.put(M2DocSiriusUtils.SIRIUS_SESSION_OPTION, diagnostics);
            diagnostics.add(new BasicDiagnostic(Diagnostic.ERROR, M2DocSiriusUtils.PLUGIN_ID, 0,
                    "The Sirius session doesn't exist: " + sessionURI.toString(), new Object[] {sessionURI}));
        }
    }

    return res;
}
项目:xtext-core    文件:SerializationUtil.java   
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);
    }
}
项目:xtext-core    文件:FlatResourceSetBasedAllContainersState.java   
@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;
}
项目:xtext-core    文件:FlatResourceSetBasedAllContainersState.java   
@Override
public boolean containsURI(String containerHandle, URI candidateURI) {
    if (!HANDLE.equals(containerHandle))
        return false;
    if (resourceSet instanceof XtextResourceSet) {
        ResourceDescriptionsData descriptionsData = findResourceDescriptionsData(resourceSet);
        if (descriptionsData != null) {
            return descriptionsData.getResourceDescription(candidateURI) != null;
        }
        Collection<URI> allUris = ((XtextResourceSet) resourceSet).getNormalizationMap().values();
        for (URI uri : allUris) {
            if (uri.equals(candidateURI)) {
                return true;
            }
        }
        return false;
    }
    URIConverter uriConverter = resourceSet.getURIConverter();
    for (Resource r : resourceSet.getResources()) {
        URI normalized = uriConverter.normalize(r.getURI());
        if (normalized.equals(candidateURI)) {
            return true;
        }
    }
    return false;
}
项目:xtext-core    文件:AbstractResourceDescription.java   
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;
}
项目:xtext-core    文件:EcoreUtil2.java   
/**
 * 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;
}
项目:xtext-core    文件:EMFGeneratorFragment2.java   
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);
      }
    }
  }
}
项目:dsl-devkit    文件:FormatScopeUtil.java   
/**
 * Find URI of extended FormatConfiguration.
 * The following heuristic is used to find the URI: extract grammar name from the extensionName (path name) and then replace the file name segment of the
 * context's URI with the extracted grammar name.
 *
 * @param context
 *          the context
 * @param extensionName
 *          the extension name
 * @return the URI if found, otherwise null
 */
private URI findExtensionURI(final Resource context, final String extensionName) {
  URI uri = context.getURI().trimFileExtension();
  String name = convertPathNameToShortName(extensionName);
  final URI extensionURI = uri.trimSegments(1).appendSegment(name).appendFileExtension(FormatConstants.FILE_EXTENSION);
  final ResourceSet resourceSet = context.getResourceSet();
  final URIConverter uriConverter = resourceSet.getURIConverter();
  try {
    if (resourceSet.getResource(extensionURI, false) != null || uriConverter.exists(extensionURI, null)) {
      return extensionURI;
    }
    // CHECKSTYLE:OFF
  } catch (Exception e) {// NOPMD
    // no resource found - return null
    // CHECKSTYLE:ON
  }
  return null;
}
项目:dsl-devkit    文件:CheckGenModelUtil.java   
/**
 * 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;
}
项目:dsl-devkit    文件:CustomClassEcoreGeneratorFragment.java   
/** {@inheritDoc} */
@Override
@SuppressWarnings("nls")
public String apply(final String from) {
  if (from.startsWith("org.eclipse.emf.ecore")) {
    return null;
  }
  for (String dir : baseDirs) {
    URI createURI = URI.createURI(dir + "/" + from.replace('.', '/') + "Custom.java");
    String customClassName = from + "Custom";
    if (URIConverter.INSTANCE.exists(createURI, null)) {
      return customClassName;
    }
    if (from.endsWith("Impl") && isGenerateCustomClasses()) {
      generateCustomClassStub(from, customClassName, createURI);
      return customClassName;
    }
  }
  return null;
}
项目:dsl-devkit    文件:CustomClassEcoreGeneratorFragment.java   
/**
 * 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);
  }
}
项目:dsl-devkit    文件:CustomClassAwareEcoreGenerator.java   
@Override
public String apply(final String from) {
  if (from.startsWith("org.eclipse.emf.ecore")) {
    return null;
  }
  String customClassName = from + "Custom";
  String fromPath = from.replace('.', '/');
  for (String srcPath : srcPaths) {
    URI createURI = URI.createURI(srcPath + "/" + fromPath + "Custom.java");
    if (URIConverter.INSTANCE.exists(createURI, null)) {
      return customClassName;
    }
    if (from.endsWith("Impl") && generateCustomClasses) {
      generate(from, customClassName, createURI);
      return customClassName;
    }
  }
  if (getClass().getClassLoader().getResourceAsStream(fromPath + "Custom.class") != null) {
    return customClassName;
  }
  return null;
}
项目:bts    文件:XtextDocumentProvider.java   
/**
 * @since 2.3
 */
protected void updateCache(IURIEditorInput input) throws CoreException {
    URIInfo info= (URIInfo) getElementInfo(input);
    if (info != null) {
        java.net.URI uri= input.getURI();
        if (uri != null) {
            boolean readOnly = true;
            String uriAsString = uri.toString();
            URI emfURI = URI.createURI(uriAsString);
            if (emfURI.isFile() && !emfURI.isArchive()) {
                // TODO: Should we use the resource set 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;
    }
}
项目:bts    文件:DirtyStateEditorSupport.java   
protected Collection<Resource> collectAffectedResources(XtextResource resource, IResourceDescription.Event event) {
    List<Resource> result = Lists.newArrayListWithExpectedSize(4);
    ResourceSet resourceSet = resource.getResourceSet();
    URIConverter converter = resourceSet.getURIConverter();
    Set<URI> normalizedURIs = Sets.newHashSetWithExpectedSize(event.getDeltas().size());
    for(IResourceDescription.Delta delta: event.getDeltas()) {
        normalizedURIs.add(converter.normalize(delta.getUri()));
    }
    List<Resource> resources = resourceSet.getResources();
    for(int i = 0; i< resources.size(); i++) {
        Resource res = resources.get(i);
        if (res != resource && res != null) {
            URI uri = res.getURI();
            try {
                uri = converter.normalize(uri);
            } catch (org.eclipse.xtext.resource.ClasspathUriResolutionException e) {
                // ignore, since the classpath might be broken.
            }
            if (normalizedURIs.contains(uri))
                result.add(res);
        }
    }
    return result;
}
项目:statecharts    文件:DefaultSimulationEngineFactory.java   
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;
}
项目:tug_qt_unit_testing_fw    文件:MyGenerator.java   
public void registerLibraries() {
    System.out.println("@MyGenerator::registerLibraries");
    CodeSource acceleoModel = MtlPackage.class.getProtectionDomain().getCodeSource();
    if (acceleoModel != null) {
        String libraryLocation = acceleoModel.getLocation().toString();
        if (libraryLocation.endsWith(".jar")) {
            libraryLocation = "jar:" + libraryLocation + '!';
        }

        URIConverter.URI_MAP.put(URI.createURI("http://www.eclipse.org/acceleo/mtl/3.0/mtlstdlib.ecore"),
                URI.createURI(libraryLocation + "/model/mtlstdlib.ecore"));
        URIConverter.URI_MAP.put(URI.createURI("http://www.eclipse.org/acceleo/mtl/3.0/mtlnonstdlib.ecore"),
                URI.createURI(libraryLocation + "/model/mtlnonstdlib.ecore"));
    } else {
        System.err.println("Coudln't retrieve location of plugin 'org.eclipse.acceleo.model'.");
    }
}
项目:slr-toolkit    文件:BibtexTests.java   
@Test
public void storeSingleDimensionWithoutSubTerms() throws Exception {

    Model model = TaxonomyFactory.eINSTANCE.createModel();
    Term term = TaxonomyFactory.eINSTANCE.createTerm();

    term.setName("test");
    model.getDimensions().add(term);

    Document document = BibtexFactory.eINSTANCE.createDocument();
    document.setTaxonomy(model);
    document.setKey("test02");
    document.setType("article");

    StringWriter writer = new StringWriter();
    resource.getContents().add(document);
    resource.save(new URIConverter.WriteableOutputStream(writer, "UTF-8"),
            Collections.EMPTY_MAP);

    String bib = writer.toString();
    assertThat(bib, containsString("test02"));
}
项目:slr-toolkit    文件:BibtexTests.java   
@Test
public void loadChangeAndStoreABibtexResource() throws Exception {
    final String bibIn = "@INPROCEEDINGS{Test01, classes = {test}}";
    StringWriter writer = new StringWriter();
    resource.load(new URIConverter.ReadableInputStream(bibIn, "UTF-8"),
            Collections.EMPTY_MAP);

    Term subTerm1 = TaxonomyFactory.eINSTANCE.createTerm();
    subTerm1.setName("sub-test1");
    Term subTerm2 = TaxonomyFactory.eINSTANCE.createTerm();
    subTerm2.setName("sub-test2");

    Document document = (Document) resource.getContents().get(0);
    Term term = document.getTaxonomy().getDimensions().get(0);
    term.getSubclasses().add(subTerm1);
    term.getSubclasses().add(subTerm2);

    resource.save(new URIConverter.WriteableOutputStream(writer, "UTF-8"),
            Collections.EMPTY_MAP);
    final String bibOut = writer.toString();
    final String expected = "@INPROCEEDINGS{Test01,\n\tclasses = {test{sub-test1, sub-test2}}\n}";
    assertThat(bibOut, is(expected));
}
项目:slr-toolkit    文件:BibtexTests.java   
@Test
public void loadSingleDimensionWithSubTerms() throws Exception {
    final String bib = "@INPROCEEDINGS{Test01, classes = {dimension{sub{subsub}}}}";

    resource.load(new URIConverter.ReadableInputStream(bib, "UTF-8"),
            Collections.EMPTY_MAP);

    assertThat(resource.getContents().get(0), instanceOf(Document.class));

    Document document = (Document) resource.getContents().get(0);
    Term dimension = document.getTaxonomy().getDimensions().get(0);
    Term subDimension = dimension.getSubclasses().get(0);
    Term subSubDimension = subDimension.getSubclasses().get(0);

    assertThat(dimension.getName(), is("dimension"));
    assertThat(subDimension.getName(), is("sub"));
    assertThat(subSubDimension.getName(), is("subsub"));
}
项目:slr-toolkit    文件:BibtexTests.java   
@Test
public void loadTwoDimensions() throws Exception {
    final String bib = "@INPROCEEDINGS{Test01, classes = {dimension1{subterm1} dimension2{subterm2}}}";

    resource.load(new URIConverter.ReadableInputStream(bib, "UTF-8"),
            Collections.EMPTY_MAP);

    assertThat(resource.getContents().get(0), instanceOf(Document.class));

    Document document = (Document) resource.getContents().get(0);
    Term dimension1 = document.getTaxonomy().getDimensions().get(0);
    Term dimension2 = document.getTaxonomy().getDimensions().get(1);

    assertThat(dimension1.getName(), is("dimension1"));
    assertThat(dimension2.getName(), is("dimension2"));
}
项目:ModelDebugging    文件:DebugPermissionProvider.java   
@Override
public boolean provides(ResourceSet set) {
    final boolean res;

    if (set != null && set.getURIConverter() != null) {
        URIConverter converter = set.getURIConverter();
        if (converter.getURIHandlers().size() > 0) {
            res = converter.getURIHandlers().get(0) instanceof DebugURIHandler;
        } else {
            res = false;
        }
    } else {
        res = false;
    }

    return res;
}
项目:OpenSPIFe    文件:FixedTransactionEditingDomain.java   
@Override
public boolean isReadOnly(Resource resource) {
    if (resourceToReadOnlyMap == null) {
        return false;
    }
    Boolean result = resourceToReadOnlyMap.get(resource);
    if (result == null && resource != null) {
        ResourceSet set = (resource.getResourceSet() != null ? resource.getResourceSet() : resourceSet);
        URIConverter uriConverter = set.getURIConverter();
        URI uri = resource.getURI();
        if (uriConverter != null && uri != null) {
            Map<String, ?> attributes = uriConverter.getAttributes(uri, null);
            result = Boolean.TRUE.equals(attributes.get(URIConverter.ATTRIBUTE_READ_ONLY));
            resourceToReadOnlyMap.put(resource, result);
        }
    }
    return Boolean.TRUE.equals(result);
}
项目:OpenSPIFe    文件:TestColumnConfigurationResource.java   
/**
 * Does a comparison of the contents of the two URIs,
 * ignoring comments in the contents.  Will compare line-by-line.
 * 
 * @param uri
 * @param uri2
 * @throws IOException
 */
private void assertEqualContents(URI uri, URI uri2) throws IOException {
    URIConverter converter = new ExtensibleURIConverterImpl();
    InputStream inputStream1 = converter.createInputStream(uri);
    BufferedReader reader1 = new BufferedReader(new InputStreamReader(inputStream1));
    InputStream inputStream2 = converter.createInputStream(uri2);
    BufferedReader reader2 = new BufferedReader(new InputStreamReader(inputStream2));
    while (true) {
        String line1 = readUncommentedLine(reader1);
        String line2 = readUncommentedLine(reader2);
        assertEquals(line1, line2);
        if (line1 == null) {
            break;
        }
    }
}
项目:OpenSPIFe    文件:EuropaServerManagerConfig.java   
public static EuropaServerManagerConfig fromEsmConfig(String uriString, Map<String, String> configReplacements) {
    URI uri = URI.createURI(uriString);
    EuropaServerManagerConfig cfg = null;
    Resource resource = null;
    if(URIConverter.INSTANCE.exists(uri, null)) {
        resource = s_resourceSet.getResource(uri, true); //exception here: org.xml.sax.XAXParseException: Premature end of file
        DocumentRoot root = (DocumentRoot) resource.getContents().get(0);
        cfg = fromEsmConfig(root.getEuropaServerManager(), configReplacements);
    } else {
        resource = s_resourceSet.createResource(uri);
        cfg = new EuropaServerManagerConfig();
    }

    cfg.setFile(resource);

    return cfg;
}
项目:OpenSPIFe    文件:EuropaServerManager.java   
private static boolean isFileWritable(String file) {
    org.eclipse.emf.common.util.URI uri = org.eclipse.emf.common.util.URI.createURI(file);
    if(URIConverter.INSTANCE.exists(uri, null)) {
        Map<String, Set<String>> options = new TreeMap<String, Set<String>>();
        Set<String> attributes = new TreeSet<String>();
        attributes.add(URIConverter.ATTRIBUTE_READ_ONLY);
        options.put(URIConverter.OPTION_REQUESTED_ATTRIBUTES, attributes);

        Map<String, ?> readOnly = URIConverter.INSTANCE.getAttributes(uri, options);
        return !((Boolean) readOnly.get(URIConverter.ATTRIBUTE_READ_ONLY));
    }
    else {
        File foo = new File(file);
        return foo.canWrite();
    }
}
项目:pnmlframework    文件:NUPNReader.java   
private static EObject extractNUPNToolInfo(String nupnXmlToolInfo) throws IOException {
    // create a ResourceSet
    ResourceSet resourceSet = new ResourceSetImpl();
    // register NupnResourceFactoryIml
    NupnResourceFactoryImpl npnrf = new NupnResourceFactoryImpl();
    resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put
    (Resource.Factory.Registry.DEFAULT_EXTENSION, 
     npnrf);
     // register your NupnPackage to the resource set so it has a reference to Nupn.ecore
    NupnPackage ePackage = NupnPackage.eINSTANCE;
    resourceSet.getPackageRegistry().put(ePackage.getNsURI(), ePackage);
    // create resource using PNML namespace URI
    Resource resource = npnrf.createResource(URI.createURI(PNML_NS_URI));
    resource.load(new URIConverter.ReadableInputStream(nupnXmlToolInfo), null);
    // return the root model object and there you have it, all you need is to
    // cast it to the right EObject based on your model 
    return resource.getContents().get(0);
}
项目:sadlos2    文件:SadlDirtyStateEditorSupport.java   
protected URI getOwlURI(URIConverter conv, URI sadlURI) {
    URI norm = conv.normalize(sadlURI);
    if (norm.isPlatformResource()) {
        List<String> seg = Lists.newArrayList(norm.trimFileExtension()
                .appendFileExtension(ResourceManager.getOwlFileExtension()).segmentsList()); // "owl").segmentsList());
        seg.remove(0);
        seg.add(1, "OwlModels");
        norm = URI.createPlatformResourceURI(Joiner.on("/").join(seg), false);
        for (Pair<IStorage,IProject> storages: mapper.getStorages(norm)) {
            IStorage s = storages.getFirst();
            if (s instanceof IResource) {
                norm = URI.createURI(((IResource) s).getLocationURI()
                        .toString());
            }
        }
    }
    return norm;
}
项目:sadlos2    文件:SadlDirtyStateEditorSupport.java   
protected Collection<Resource> collectAffectedResources(
        XtextResource resource, IResourceDescription.Event event) {
    List<Resource> result = Lists.newArrayListWithExpectedSize(4);
    ResourceSet resourceSet = resource.getResourceSet();
    URIConverter converter = resourceSet.getURIConverter();
    Set<URI> norm = Sets.newHashSetWithExpectedSize(event.getDeltas()
            .size());
    for (IResourceDescription.Delta delta : event.getDeltas()) {
        if (delta.getNew() != null) {
            norm.add(converter.normalize(delta.getNew().getURI()));
            norm.add(getOwlURI(converter, delta.getNew().getURI()));
        } else if (delta.getOld() != null) {
            norm.add(converter.normalize(delta.getOld().getURI()));
            norm.add(getOwlURI(converter, delta.getOld().getURI()));
        }
    }
    for (Resource res : resourceSet.getResources()) {
        if (res != resource && res != null) {
            URI normalized = converter.normalize(res.getURI());
            if (norm.contains(normalized))
                result.add(res);
        }
    }
    return result;
}
项目:emfstore-rest    文件:ModelUtil.java   
/**
 * Converts the given {@link EObject} to a string.
 * 
 * @param copy The copied {@link EObject}.
 * @param resource The resource for the {@link EObject}.
 * @return The string representing the {@link EObject}.
 * @throws SerializationException If a serialization problem occurs.
 */
public static String copiedEObjectToString(EObject copy, XMIResource resource) throws SerializationException {
    final int step = 200;
    final int initialSize = step;
    resource.getContents().add(copy);

    final StringWriter stringWriter = new StringWriter(initialSize);
    final URIConverter.WriteableOutputStream uws = new URIConverter.WriteableOutputStream(stringWriter, "UTF-8");

    final String lineSeparator = System.getProperty("line.separator");
    try {
        System.setProperty("line.separator", "\r\n");
        resource.save(uws, getResourceSaveOptions());
    } catch (final IOException e) {
        throw new SerializationException(e);
    } finally {
        System.setProperty("line.separator", lineSeparator);
    }

    return stringWriter.toString();
}
项目:eclipse-avro    文件:PlatformResourceURIHandlerImpl.java   
/**
 * Creates an output stream for the given {@link IFile} path.
 * <p>
 * This implementation uses a {@link PlatformResourceURIHandlerImpl.PlatformResourceOutputStream}.
 * </p>
 * @return an open output stream.
 * @exception IOException if there is a problem obtaining an open output stream.
 * @see IWorkspaceRoot#getFile(org.eclipse.core.runtime.IPath)
 * @see PlatformResourceURIHandlerImpl.PlatformResourceOutputStream
 * @see IFile#setContents(InputStream, boolean, boolean, IProgressMonitor)
 */
public static OutputStream createPlatformResourceOutputStream(String platformResourcePath, Map<?, ?> options) throws IOException
{
  IFile file = workspaceRoot.getFile(new Path(platformResourcePath));
  @SuppressWarnings("unchecked")
  final Map<Object, Object> response = options == null ? null : (Map<Object, Object>)options.get(URIConverter.OPTION_RESPONSE);
  return
    new PlatformResourceOutputStream(file, false, true, null)
    {
      @Override
      public void close() throws IOException
      {
        try
        {
          super.close();
        }
        finally
        {
          if (response != null)
          {
            response.put(URIConverter.RESPONSE_TIME_STAMP_PROPERTY, file.getLocalTimeStamp());
          }
        }
      }
    };
}
项目:eclipse-avro    文件:PlatformResourceURIHandlerImpl.java   
/**
 * Creates an output stream for the platform resource path and returns it.
 * <p>
 * This implementation does one of two things, depending on the runtime environment.
 * If there is an Eclipse workspace, it delegates to
 * {@link WorkbenchHelper#createPlatformResourceOutputStream WorkbenchHelper.createPlatformResourceOutputStream},
 * which gives the expected Eclipse behaviour.
 * Otherwise, the {@link EcorePlugin#resolvePlatformResourcePath resolved} URI
 * is delegated to {@link #createOutputStream createOutputStream}
 * for recursive processing.
 * @return an open output stream.
 * @exception IOException if there is a problem obtaining an open output stream or a valid interpretation of the path.
 * @see EcorePlugin#resolvePlatformResourcePath(String)
 */
@Override
public OutputStream createOutputStream(URI uri, Map<?, ?> options) throws IOException
{
  String platformResourcePath = uri.toPlatformString(true);
  if (workspaceRoot != null)
  {
    return WorkbenchHelper.createPlatformResourceOutputStream(platformResourcePath, options);
  }
  else
  {
    URI resolvedLocation = EcorePlugin.resolvePlatformResourcePath(platformResourcePath);
    if (resolvedLocation != null)
    {
      return ((URIConverter)options.get(URIConverter.OPTION_URI_CONVERTER)).createOutputStream(resolvedLocation, options);
    }

    throw new IOException("The path '" + platformResourcePath + "' is unmapped");
  }
}