Java Code Examples for org.eclipse.emf.common.util.URI#resolve()

The following examples show how to use org.eclipse.emf.common.util.URI#resolve() . 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: SafeURI.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
private U appendRelativeURI(URI relativeURI) {
	String[] segments = relativeURI.segments();
	if (segments.length == 0) {
		throw new IllegalArgumentException("Cannot append empty URI.");
	}
	if (!URI.validSegments(segments)) {
		throw new IllegalArgumentException(String.valueOf(relativeURI));
	}
	if (segments.length == 1 && segments[0].isEmpty()) {
		throw new IllegalArgumentException("Use withTrailingPathDelimiter instead");
	}
	for (int i = 0; i < segments.length - 1; i++) {
		if (segments[i].isEmpty()) {
			throw new IllegalArgumentException("Cannot add intermediate empty segments");
		}
	}
	URI base = withTrailingPathDelimiter().toURI();
	URI result = relativeURI.resolve(base);
	return createFrom(result);
}
 
Example 2
Source File: M2DocHTMLServices.java    From M2Doc with Eclipse Public License 1.0 6 votes vote down vote up
@Documentation(
    value = "Returns a Sequence of MElement corresponding to the given web page.",
    params = {
        @Param(name = "uriStr", value = "The URI."),
    },
    result = "The Sequence of MElement corresponding to the given web page.",
    examples = {
        @Example(
            expression = "'http://www.m2doc.org/'.fromHTMLURI()",
            result = "The Sequence of MElement corresponding to the given web page."
        )
    }
)
// @formatter:on
public List<MElement> fromHTMLURI(String uriStr) throws IOException {
    final URI htmlURI = URI.createURI(uriStr, false);
    final URI uri = htmlURI.resolve(templateURI);

    try (InputStream input = uriConverter.createInputStream(uri);) {
        final String htmlString = new String(IOUtils.toByteArray(input));

        return parser.parse(uri, htmlString);
    }
}
 
Example 3
Source File: SiriusServiceConfigurator.java    From M2Doc with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public Set<IService> getServices(IReadOnlyQueryEnvironment queryEnvironment, ResourceSet resourceSetForModels,
        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 boolean forceRefresh = Boolean.valueOf(options.get(M2DocSiriusUtils.SIRIUS_FORCE_REFRESH));
            final M2DocSiriusServices serviceInstance = new M2DocSiriusServices(session, forceRefresh);
            res.addAll(ServiceUtils.getServices(queryEnvironment, serviceInstance));
            services.put(queryEnvironment, serviceInstance);
        }
    }

    return res;
}
 
Example 4
Source File: PackageJsonValidatorExtension.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Converts the given {@code relativePath} to an absolute URI by resolving it based on the location of
 * {@code resource}.
 */
private URI getResourceRelativeURI(Resource resource, String relativePath) {
	final String normalizedStringPath = FileUtils.normalize(relativePath);
	final URI relativeLocation = URI.createURI(normalizedStringPath);
	// obtain URI of resource container (including trailing slash)
	final URI resourceContainerLocation = resource.getURI().trimSegments(1).appendSegment("");
	return relativeLocation.resolve(resourceContainerLocation);
}
 
Example 5
Source File: GenconfUtils.java    From M2Doc with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Gets the {@link URI#resolve(URI) resolved URI} from the given {@link Generation}.
 * 
 * @param generation
 *            the {@link Generation}
 * @param uri
 *            the {@link URI} to resolve
 * @return the {@link URI#resolve(URI) resolved URI} from the given {@link Generation}
 */
public static URI getResolvedURI(Generation generation, URI uri) {
    final URI res;

    if (generation.eResource() != null && generation.eResource().getURI() != null) {
        res = uri.resolve(generation.eResource().getURI());
    } else {
        res = uri;
    }

    return res;
}
 
Example 6
Source File: FileUtils.java    From gama with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns a best guess URI based on the target string and an optional URI specifying from where the relative URI
 * should be run. If existingResource is null, then the root of the workspace is used as the relative URI
 *
 * @param target
 *            a String giving the path
 * @param existingResource
 *            the URI of the resource from which relative URIs should be interpreted
 * @author Alexis Drogoul, July 2018
 * @return an URI or null if it cannot be determined.
 */
public static URI getURI(final String target, final URI existingResource) {
	if (target == null) { return null; }
	try {
		final IPath path = Path.fromOSString(target);
		final IFileStore file = EFS.getLocalFileSystem().getStore(path);
		final IFileInfo info = file.fetchInfo();
		if (info.exists()) {
			// We have an absolute file
			final URI fileURI = URI.createFileURI(target);
			return fileURI;
		} else {
			final URI first = URI.createURI(target, false);
			URI root;
			if (!existingResource.isPlatformResource()) {
				root = URI.createPlatformResourceURI(existingResource.toString(), false);
			} else {
				root = existingResource;
			}
			if (root == null) {
				root = WORKSPACE_URI;
			}
			final URI iu = first.resolve(root);
			if (isFileExistingInWorkspace(iu)) { return iu; }
			return null;
		}
	} catch (final Exception e) {
		return null;
	}
}
 
Example 7
Source File: EcoreUtil2.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
private static URI getResolvedImportUri(Resource context, URI uri) {
	URI contextURI = context.getURI();
	if (contextURI.isHierarchical() && !contextURI.isRelative() && (uri.isRelative() && !uri.isEmpty())) {
		uri = uri.resolve(contextURI);
	}
	return uri;
}
 
Example 8
Source File: URIBasedFileSystemAccess.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public URI getURI(String path, String outputConfiguration) {
	String outlet = getPathes().get(outputConfiguration);
	if (outlet == null) {
		throw new IllegalArgumentException(
				"A slot with name \'" + outputConfiguration + "\' has not been configured.");
	}
	URI uri = URI.createFileURI(outlet + File.separator + path);
	return baseDir != null ? uri.resolve(baseDir) : uri;
}
 
Example 9
Source File: AbstractFileSystemSupport.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
protected URI getURI(final Path path) {
  if (((path == null) || Objects.equal(path, Path.ROOT))) {
    return null;
  }
  final IProjectConfig projectConfig = this.projectConfigProvider.getProjectConfig(this.context);
  if ((projectConfig == null)) {
    return null;
  }
  final URI projectURI = projectConfig.getPath();
  final String projectName = IterableExtensions.<String>head(path.getSegments());
  String _name = projectConfig.getName();
  boolean _notEquals = (!Objects.equal(projectName, _name));
  if (_notEquals) {
    return null;
  }
  final Iterable<String> segments = IterableExtensions.<String>tail(path.getSegments());
  boolean _isEmpty = IterableExtensions.isEmpty(segments);
  if (_isEmpty) {
    return projectURI;
  }
  final URI relativeURI = URI.createURI(IterableExtensions.<String>head(segments)).appendSegments(((String[])Conversions.unwrapArray(IterableExtensions.<String>tail(segments), String.class)));
  final URI uri = relativeURI.resolve(projectURI);
  Boolean _isFolder = this.isFolder(uri);
  if ((_isFolder).booleanValue()) {
    return UriUtil.toFolderURI(uri);
  }
  return uri;
}
 
Example 10
Source File: SiriusServiceConfigurator.java    From M2Doc with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public ResourceSet createResourceSetForModels(Object context, Map<String, String> options) {
    ResourceSet created = null;
    final String sessionURIStr = options.get(M2DocSiriusUtils.SIRIUS_SESSION_OPTION);
    if (sessionURIStr != null && !sessionURIStr.isEmpty()) {
        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())) {
            try {
                final Session session = SessionManager.INSTANCE.getSession(sessionURI, new NullProgressMonitor());
                sessions.put(context, session);
                if (!session.isOpen()) {
                    session.open(new NullProgressMonitor());
                    sessionToClose.add(session);
                }
                created = session.getTransactionalEditingDomain().getResourceSet();
                SessionTransientAttachment transiantAttachment = new SessionTransientAttachment(session);
                created.eAdapters().add(transiantAttachment);
                transientAttachments.put(session, transiantAttachment);
                // CHECKSTYLE:OFF
            } catch (Exception e) {
                // CHECKSTYLE:ON
                // TODO remove this workaround see https://support.jira.obeo.fr/browse/VP-5389
                if (PlatformUI.isWorkbenchRunning()) {
                    MessageDialog.openWarning(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
                            "Unable to open Sirius Session",
                            "Check the " + M2DocSiriusUtils.SIRIUS_SESSION_OPTION
                                + " option or try to open the session manually by double clicking the .aird file:\n"
                                + e.getMessage());
                }
            }
        } else {
            throw new IllegalArgumentException("The Sirius session doesn't exist: " + sessionURI);
        }
    }
    return created;
}
 
Example 11
Source File: Repository.java    From textuml with Eclipse Public License 1.0 4 votes vote down vote up
private boolean isManaged(Resource resource) {
    URI resourceURI = resource.getURI();
    if (resourceURI.isRelative())
        resourceURI = resourceURI.resolve(baseURI);
    return resourceURI.toString().startsWith(baseURI.toString());
}
 
Example 12
Source File: ExcelServices.java    From M2Doc with Eclipse Public License 1.0 4 votes vote down vote up
@Documentation(
    value = "Insert a table from an Excel .xlsx file.",
    params = {
        @Param(name = "uri", value = "The Excel .xlsx file uri, it can be relative to the template"),
        @Param(name = "sheetName", value = "The sheet name"),
        @Param(name = "topLeftCellAdress", value = "The top left cell address"),
        @Param(name = "bottomRightCellAdress", value = "The bottom right cell address"),
        @Param(name = "languageTag", value = "The language tag for the locale"),
    },
    result = "insert the table",
    examples = {
        @Example(expression = "'excel.xlsx'.asTable('Feuil1', 'C3', 'F7', 'fr-FR')", result = "insert the table from 'excel.xlsx'"),
    }
)
// @formatter:on
public MTable asTable(String uriStr, String sheetName, String topLeftCellAdress, String bottomRightCellAdress,
        String languageTag) throws IOException {
    final MTable res = new MTableImpl();

    final URI xlsxURI = URI.createURI(uriStr, false);
    final URI uri = xlsxURI.resolve(templateURI);

    try (XSSFWorkbook workbook = new XSSFWorkbook(uriConverter.createInputStream(uri));) {
        final FormulaEvaluator evaluator = new XSSFFormulaEvaluator(workbook);
        final XSSFSheet sheet = workbook.getSheet(sheetName);
        if (sheet == null) {
            throw new IllegalArgumentException(String.format("The sheet %s doesn't exist in %s.", sheetName, uri));
        } else {
            final Locale locale;
            if (languageTag != null) {
                locale = Locale.forLanguageTag(languageTag);
            } else {
                locale = Locale.getDefault();
            }
            final DataFormatter dataFormatter = new DataFormatter(locale);
            final CellAddress start = new CellAddress(topLeftCellAdress);
            final CellAddress end = new CellAddress(bottomRightCellAdress);
            int rowIndex = start.getRow();
            while (rowIndex <= end.getRow()) {
                final XSSFRow row = sheet.getRow(rowIndex++);
                if (row != null) {
                    final MRow mRow = new MRowImpl();
                    int cellIndex = start.getColumn();
                    while (cellIndex <= end.getColumn()) {
                        final XSSFCell cell = row.getCell(cellIndex++);
                        if (cell != null) {
                            final MStyle style = getStyle(cell);
                            final MElement text = new MTextImpl(dataFormatter.formatCellValue(cell, evaluator),
                                    style);
                            final Color background = getColor(cell.getCellStyle().getFillForegroundColorColor());
                            final MCell mCell = new MCellImpl(text, background);
                            mRow.getCells().add(mCell);
                        } else {
                            mRow.getCells().add(createEmptyCell());
                        }
                    }
                    res.getRows().add(mRow);
                } else {
                    final int length = end.getColumn() - start.getColumn() + 1;
                    res.getRows().add(createEmptyRow(length));
                }
            }

        }
    }

    return res;
}
 
Example 13
Source File: GenerationFileNamesPage.java    From M2Doc with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Validates the page and gets the {@link TemplateCustomProperties} if any.
 * 
 * @param gen
 *            the {@link Generation}
 * @param templateURI
 *            the template {@link URI}
 * @return the {@link TemplateCustomProperties} if any, <code>null</code> otherwise
 */
private TemplateCustomProperties validatePage(Generation gen, URI templateURI) {
    TemplateCustomProperties res;

    final EditingDomain editingDomain = TransactionUtil.getEditingDomain(gen);

    final URI absoluteURI = templateURI.resolve(gen.eResource().getURI());
    if (URIConverter.INSTANCE.exists(absoluteURI, null)) {
        try {
            res = POIServices.getInstance().getTemplateCustomProperties(URIConverter.INSTANCE, absoluteURI);
            final List<Definition> oldDefinitions = GenconfUtils.getOldDefinitions(gen, res);
            final Command removeCommand = RemoveCommand.create(editingDomain, gen,
                    GenconfPackage.GENERATION__DEFINITIONS, oldDefinitions);
            editingDomain.getCommandStack().execute(removeCommand);

            final List<Definition> newDefinitions = GenconfUtils.getNewDefinitions(gen, res);
            final Command addCommand = AddCommand.create(editingDomain, gen, GenconfPackage.GENERATION__DEFINITIONS,
                    newDefinitions);
            editingDomain.getCommandStack().execute(addCommand);
            // CHECKSTYLE:OFF
        } catch (Exception e) {
            // CHECKSTYLE:ON
            setErrorMessage("Invalid template: " + e.getMessage());
            res = null;
        }
    } else {
        res = null;
        setErrorMessage("Template " + absoluteURI + " doesn't exist.");
    }

    if (res != null) {
        setPageComplete(true);
        if (!M2DocUtils.VERSION.equals(res.getM2DocVersion())) {
            setMessage("M2Doc version mismatch: template version is " + res.getM2DocVersion()
                + " and current M2Doc version is " + M2DocUtils.VERSION, IMessageProvider.WARNING);
        } else {
            setErrorMessage(null);
        }
    } else {
        setPageComplete(false);
    }

    return res;
}
 
Example 14
Source File: Postgres.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
public URL makeURL ( final String uriString ) throws MalformedURLException
{
    URI uri = URI.createURI ( uriString );
    uri = uri.resolve ( this.postgres.eResource ().getURI () );
    return new URL ( uri.toString () );
}
 
Example 15
Source File: ImageServices.java    From M2Doc with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * Gets the {@link MImage} corresponding to the given path.
 * 
 * @param uriStr
 *            the uri.
 * @param type
 *            the picture {@link PictureType type}.
 * @return the {@link MImage} corresponding to the given path
 */
private MImage asImage(String uriStr, PictureType type) {
    final URI imageURI = URI.createURI(uriStr, false);
    final URI uri = imageURI.resolve(templateURI);

    return new MImageImpl(uriConverter, uri, type);
}
 
Example 16
Source File: M2DocWikiTextServices.java    From M2Doc with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * Parses the given markup contents with at the given {@link URI}.
 * 
 * @param parser
 *            the {@link MarkupParser}
 * @param baseURI
 *            the base {@link URI}
 * @param srcURI
 *            the source {@link URI}
 * @return the {@link List} of parsed {@link MElement}
 * @throws IOException
 *             if the source {@link URI} can't be read
 */
protected List<MElement> parse(MarkupParser parser, URI baseURI, URI markupURI) throws IOException {
    builder.setBaseURI(baseURI);
    final URI uri = markupURI.resolve(templateURI);

    try (InputStream input = uriConverter.createInputStream(uri);) {
        final String markupContents = new String(IOUtils.toByteArray(input));
        parser.parse(markupContents);
    }

    return builder.getResult();
}
 
Example 17
Source File: UserContentManager.java    From M2Doc with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * Gets the lost {@link UserContent} {@link URI} for the given destination {@link URI} and {@link UserContent#getId() user content ID}.
 * 
 * @param dest
 *            the destination {@link URI}
 * @param id
 *            the {@link UserContent#getId() user content ID}
 * @return the lost {@link UserContent} {@link URI} for the given destination {@link URI} and {@link UserContent#getId() user content
 *         ID}
 */
protected URI getLostUserContentURI(URI dest, String id) {
    final URI res = URI.createURI("./" + dest.lastSegment() + "-" + id + "-lost.docx", false);

    return res.resolve(dest);
}