com.damnhandy.uri.template.UriTemplate Java Examples

The following examples show how to use com.damnhandy.uri.template.UriTemplate. 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: ResourceScanner.java    From seed with Mozilla Public License 2.0 6 votes vote down vote up
private void buildHalLink() {
    for (Map.Entry<String, List<Method>> entry : resourceByRel.entrySet()) {
        String rel = entry.getKey();
        List<Method> methodsByRel = entry.getValue();

        String path = RESTReflect.findPath(methodsByRel.get(0));
        if (path == null) {
            throw new IllegalStateException("Path not found for rel: " + rel);
        }
        UriTemplateBuilder uriTemplateBuilder = UriTemplate.buildFromTemplate(path);

        Set<String> queryParams = findAllQueryParamsForRel(methodsByRel);
        if (!queryParams.isEmpty()) {
            uriTemplateBuilder.query(queryParams.toArray(new String[queryParams.size()]));
        }

        String absolutePath = UriBuilder.uri(servletContextPath, restConfig.getPath(),
                uriTemplateBuilder.build().getTemplate());

        halLinks.put(rel, new Link(absolutePath));
    }
}
 
Example #2
Source File: GitLabAvatarCache.java    From gitlab-branch-source-plugin with MIT License 6 votes vote down vote up
/**
 * Builds the URL for the cached avatar image of the required size.
 *
 * @param url  the URL of the source avatar image.
 * @param size the size of the image.
 * @return the URL of the cached image.
 */
public static String buildUrl(String url, String size) {
    Jenkins j = Jenkins.get();
    GitLabAvatarCache instance = j.getExtensionList(RootAction.class).get(GitLabAvatarCache.class);
    if (instance == null) {
        throw new AssertionError();
    }
    String key = Util.getDigestOf(GitLabAvatarCache.class.getName() + url);
    // seed the cache
    instance.getCacheEntry(key, url);
    return UriTemplate.buildFromTemplate(j.getRootUrlFromRequest())
        .literal(instance.getUrlName())
        .path("key")
        .query("size")
        .build()
        .set("key", key)
        .set("size", size)
        .expand();
}
 
Example #3
Source File: GiteaSCMSource.java    From gitea-plugin with MIT License 6 votes vote down vote up
@NonNull
@Override
protected List<Action> retrieveActions(SCMSourceEvent event, @NonNull TaskListener listener)
        throws IOException, InterruptedException {
    if (giteaRepository == null) {
        try (GiteaConnection c = gitea().open()) {
            listener.getLogger().format("Looking up repository %s/%s%n", repoOwner, repository);
            giteaRepository = c.fetchRepository(repoOwner, repository);
        }
    }
    List<Action> result = new ArrayList<>();
    result.add(new ObjectMetadataAction(null, giteaRepository.getDescription(), giteaRepository.getWebsite()));
    result.add(new GiteaLink("icon-gitea-repo", UriTemplate.buildFromTemplate(serverUrl)
            .path(UriTemplateBuilder.var("owner"))
            .path(UriTemplateBuilder.var("repository"))
            .build()
            .set("owner", repoOwner)
            .set("repository", repository)
            .expand()
    ));
    return result;
}
 
Example #4
Source File: GitLabHookCreator.java    From gitlab-branch-source-plugin with MIT License 6 votes vote down vote up
/**
 * @param server the {@code GitLabServer} for which the hooks URL would be created. If not {@code null} and it
 *        has a {@link GitLabServer#getHooksRootUrl()}, then the hook URL will be based on this root URL.
 *        Otherwise, the hook URL will be based on {@link Jenkins#getRootUrl()}.
 * @param isWebHook {@code true} to get the webhook URL, {@code false} for the systemhook URL
 * @return a webhook or systemhook URL
 */
public static String getHookUrl(GitLabServer server, boolean isWebHook) {
    String rootUrl = (server == null || server.getHooksRootUrl() == null)
            ? Jenkins.get().getRootUrl()
            : server.getHooksRootUrl();
    if (StringUtils.isBlank(rootUrl)) {
        return "";
    }
    checkURL(rootUrl);
    UriTemplateBuilder templateBuilder = UriTemplate.buildFromTemplate(rootUrl);
    if (isWebHook) {
        templateBuilder.literal("gitlab-webhook");
    } else {
        templateBuilder.literal("gitlab-systemhook");
    }
    return templateBuilder.literal("/post").build().expand();
}
 
Example #5
Source File: GiteaBrowser.java    From gitea-plugin with MIT License 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public URL getFileLink(Path path) throws IOException {
    if (path.getEditType().equals(EditType.DELETE)) {
        return diffLink(path);
    } else {
        return new URL(
                UriTemplate.buildFromTemplate(getRepoUrl())
                        .literal("/src")
                        .path(UriTemplateBuilder.var("changeSet"))
                        .path(UriTemplateBuilder.var("path", true))
                        .build()
                        .set("changeSet", path.getChangeSet().getId())
                        .set("path", StringUtils.split(path.getPath(), '/'))
                        .expand()
        );
    }
}
 
Example #6
Source File: DefaultGiteaConnection.java    From gitea-plugin with MIT License 6 votes vote down vote up
private <T> List<T> getList(UriTemplate template, final Class<T> modelClass)
        throws IOException, InterruptedException {
    HttpURLConnection connection = openConnection(template);
    withAuthentication(connection);
    try {
        connection.connect();
        int status = connection.getResponseCode();
        if (status / 100 == 2) {
            try (InputStream is = connection.getInputStream()) {
                List<T> list = mapper.readerFor(mapper.getTypeFactory()
                        .constructCollectionType(List.class, modelClass))
                        .readValue(is);
                // strip null values from the list
                for (Iterator<T> iterator = list.iterator(); iterator.hasNext(); ) {
                    if (iterator.next() == null) {
                        iterator.remove();
                    }
                }
                return list;
            }
        }
        throw new GiteaHttpStatusException(status, connection.getResponseMessage());
    } finally {
        connection.disconnect();
    }
}
 
Example #7
Source File: DefaultGiteaConnection.java    From gitea-plugin with MIT License 6 votes vote down vote up
private <T> T getObject(UriTemplate template, final Class<T> modelClass) throws IOException, InterruptedException {
    HttpURLConnection connection = openConnection(template);
    withAuthentication(connection);
    try {
        connection.connect();
        int status = connection.getResponseCode();
        if (status == 200) {
            try (InputStream is = connection.getInputStream()) {
                return mapper.readerFor(modelClass).readValue(is);
            }
        }
        throw new GiteaHttpStatusException(status, connection.getResponseMessage());
    } finally {
        connection.disconnect();
    }
}
 
Example #8
Source File: DefaultGiteaConnection.java    From gitea-plugin with MIT License 5 votes vote down vote up
private int status(UriTemplate template) throws IOException, InterruptedException {
    HttpURLConnection connection = openConnection(template);
    withAuthentication(connection);
    try {
        connection.connect();
        return connection.getResponseCode();
    } finally {
        connection.disconnect();
    }
}
 
Example #9
Source File: OCNWhisperService.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public ListenableFuture<Whisper> forReply(PlayerId user) {
    final String uri = UriTemplate.fromTemplate("/{model}/reply/{user}")
                                  .set("model", "whispers")
                                  .set("user", user._id())
                                  .expand();
    return client().get(uri, Whisper.class, HttpOption.INFINITE_RETRY);
}
 
Example #10
Source File: OCNTournamentService.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
private ListenableFuture<Entrant> entrantSearch(String tournamentId, String param, String value) {
    return client().get(UriTemplate.fromTemplate("/tournaments/{id}/entrants?{param}={value}")
                                   .set("id", tournamentId)
                                   .set("param", param)
                                   .set("value", value)
                                   .expand(),
                        Entrant.class);
}
 
Example #11
Source File: OCNTournamentService.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public ListenableFuture<Entrant> entrant(String tournamentId, String teamId) {
    return client().get(UriTemplate.fromTemplate("/tournaments/{id}/entrants/{team_id}")
                                   .set("id", tournamentId)
                                   .set("team_id", teamId)
                                   .expand(),
                        Entrant.class);
}
 
Example #12
Source File: HttpQueryService.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
protected String memberUri(String id, String action) {
    return UriTemplate.fromTemplate("/{model}/{id}/{action}")
                      .set("model", meta.pluralName())
                      .set("id", id)
                      .set("action", action)
                      .expand();
}
 
Example #13
Source File: GiteaSCMBuilder.java    From gitea-plugin with MIT License 5 votes vote down vote up
public final String repositoryUrl(String owner, String repository) {
    return UriTemplate.buildFromTemplate(serverUrl)
            .path(UriTemplateBuilder.var("owner"))
            .path(UriTemplateBuilder.var("repository"))
            .build()
            .set("owner", owner)
            .set("repository", repository)
            .expand();
}
 
Example #14
Source File: DefaultGiteaConnection.java    From gitea-plugin with MIT License 5 votes vote down vote up
@Restricted(NoExternalUse.class)
protected HttpURLConnection openConnection(UriTemplate template) throws IOException {
    URL url = new URL(template.expand());
    Jenkins jenkins = Jenkins.get();
    if (jenkins.proxy == null) {
        return (HttpURLConnection) url.openConnection();
    }
    return (HttpURLConnection) url.openConnection(jenkins.proxy.createProxy(url.getHost()));
}
 
Example #15
Source File: DefaultGiteaConnection.java    From gitea-plugin with MIT License 5 votes vote down vote up
private int delete(UriTemplate template) throws IOException, InterruptedException {
    HttpURLConnection connection = openConnection(template);
    withAuthentication(connection);
    connection.setRequestMethod("DELETE");
    try {
        connection.connect();
        return connection.getResponseCode();
    } finally {
        connection.disconnect();
    }
}
 
Example #16
Source File: StateRepositoryRestController.java    From synapse with Apache License 2.0 5 votes vote down vote up
private List<Link> entityItemLinks(final UriTemplate uriTemplate,
                                   final List<String> entityIds) {

    return entityIds
            .stream()
            .map(key -> item(uriTemplate.set("entityId", key).expand()))
            .collect(toList());
}
 
Example #17
Source File: URITemplateFormatValidator.java    From json-schema with Apache License 2.0 5 votes vote down vote up
@Override public Optional<String> validate(String subject) {
    try {
        UriTemplate.fromTemplate(subject);
        return Optional.empty();
    } catch (MalformedUriTemplateException e) {
        return Optional.of(format("[%s] is not a valid URI template", subject));
    }
}
 
Example #18
Source File: TemplateUriTest.java    From zendesk-java-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testUriTempateConstructor() {
    UriTemplate uriTemplate = UriTemplate.fromTemplate("/{foo:1}{/foo}");
    TemplateUri templateUri = new TemplateUri(uriTemplate);
    templateUri.set("foo", "test");

    assertEquals("/t/test", templateUri.toString());
}
 
Example #19
Source File: Resource.java    From seed with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Return the href template. It's empty unless the path is templated.
 *
 * @return hrefTemplate
 */
public String hrefTemplate() {
    UriTemplateBuilder uriTemplateBuilder = UriTemplate.buildFromTemplate(hrefTemplate);
    if (!queryParams.isEmpty()) {
        uriTemplateBuilder = uriTemplateBuilder.query(
                queryParams.keySet().toArray(new String[queryParams.keySet().size()]));
    }
    return uriTemplateBuilder.build().getTemplate();
}
 
Example #20
Source File: Link.java    From seed with Mozilla Public License 2.0 5 votes vote down vote up
public String getHref() {
    if (isTemplated()) {
        return href;
    } else {
        return Optional.ofNullable(href)
                .map(UriTemplate::fromTemplate)
                .map(uriTemplate -> uriTemplate.expand(hrefVars))
                .orElse(null);
    }
}
 
Example #21
Source File: UriTemplates.java    From jolie with GNU Lesser General Public License v2.1 5 votes vote down vote up
public Value match( Value request ) {
	UriTemplate t = UriTemplate.fromTemplate( request.getFirstChild( "template" ).strValue() );
	Pattern p = UriTemplateMatcherFactory.getReverseMatchPattern( t );
	Matcher m = p.matcher( request.getFirstChild( "uri" ).strValue() );
	Value response = Value.create();
	boolean matches = m.matches();
	response.setValue( matches );
	if( matches ) {
		for( String param : t.getVariables() ) {
			response.setFirstChild( param, m.group( param ) );
		}
	}
	return response;
}
 
Example #22
Source File: GiteaBrowser.java    From gitea-plugin with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public URL getChangeSetLink(GitChangeSet changeSet) throws IOException {
    return new URL(
            UriTemplate.buildFromTemplate(getRepoUrl())
                    .literal("/commit")
                    .path(UriTemplateBuilder.var("changeSet"))
                    .build()
                    .set("changeSet", changeSet.getId())
                    .expand()
    );
}
 
Example #23
Source File: GiteaBrowser.java    From gitea-plugin with MIT License 5 votes vote down vote up
/**
 * Generates a diff link for the supplied path.
 * @param path the path.
 * @return the diff link.
 * @throws IOException if there was an error parsing the index of the path from the changeset.
 */
private URL diffLink(Path path) throws IOException {
    return new URL(
            UriTemplate.buildFromTemplate(getRepoUrl())
                    .literal("/commit")
                    .path(UriTemplateBuilder.var("changeSet"))
                    .fragment(UriTemplateBuilder.var("diff"))
                    .build()
                    .set("changeSet", path.getChangeSet().getId())
                    .set("diff", "diff-" + (getIndexOfPath(path) + 1))
                    .expand()
    );
}
 
Example #24
Source File: GiteaSCMNavigator.java    From gitea-plugin with MIT License 5 votes vote down vote up
@NonNull
@Override
protected List<Action> retrieveActions(@NonNull SCMNavigatorOwner owner, SCMNavigatorEvent event,
                                       @NonNull TaskListener listener) throws IOException, InterruptedException {
    if (this.giteaOwner == null) {
        try (GiteaConnection c = gitea(owner).open()) {
            this.giteaOwner = c.fetchUser(repoOwner);
            if (StringUtils.isBlank(giteaOwner.getEmail())) {
                this.giteaOwner = c.fetchOrganization(repoOwner);
            }
        }
    }
    List<Action> result = new ArrayList<>();
    String objectUrl = UriTemplate.buildFromTemplate(serverUrl)
            .path("owner")
            .build()
            .set("owner", repoOwner)
            .expand();
    result.add(new ObjectMetadataAction(
            Util.fixEmpty(giteaOwner.getFullName()),
            null,
            objectUrl)
    );
    if (StringUtils.isNotBlank(giteaOwner.getAvatarUrl())) {
        result.add(new GiteaAvatar(giteaOwner.getAvatarUrl()));
    }
    result.add(new GiteaLink("icon-gitea-org", objectUrl));
    if (giteaOwner instanceof GiteaOrganization) {
        String website = ((GiteaOrganization) giteaOwner).getWebsite();
        if (StringUtils.isBlank(website)) {
            listener.getLogger().println("Organization website: unspecified");
        } else {
            listener.getLogger().printf("Organization website: %s%n",
                    HyperlinkNote.encodeTo(website, StringUtils.defaultIfBlank(giteaOwner.getFullName(), website)));
        }
    }
    return result;
}
 
Example #25
Source File: UriTemplates.java    From jolie with GNU Lesser General Public License v2.1 5 votes vote down vote up
public String expand( Value request ) {
	UriTemplate t = UriTemplate.fromTemplate( request.getFirstChild( "template" ).strValue() );
	if( request.hasChildren( "params" ) ) {
		for( final Map.Entry< String, ValueVector > entry : request.getFirstChild( "params" ).children()
			.entrySet() ) {
			t.set( entry.getKey(), entry.getValue().first().valueObject() );
		}
	}
	return t.expand();
}
 
Example #26
Source File: StateRepositoryUiController.java    From synapse with Apache License 2.0 4 votes vote down vote up
@GetMapping(
        path = "${edison.application.management.base-path:internal}/staterepositories/{repositoryName}",
        produces = "text/html"
)
public ModelAndView getStateRepositoryHtml(final @PathVariable String repositoryName,
                                           final @RequestParam(defaultValue = "0") int page,
                                           final @RequestParam(defaultValue = "100") int pageSize,
                                           final UriComponentsBuilder uriComponentsBuilder) {
    if (stateRepositories.containsKey(repositoryName)) {

        final StateRepository<?> stateRepository = stateRepositories
                .get(repositoryName);
        final Set<String> allEntityIds = stateRepository
                .keySet();
        final List<String> entityPageIds = allEntityIds
                .stream()
                .skip(page * pageSize)
                .limit(pageSize)
                .collect(Collectors.toList());

        final UriComponentsBuilder baseUriBuilder = uriComponentsBuilder
                .pathSegment(managementBasePath)
                .path("/staterepositories");

        final UriTemplate repositoryUri = fromTemplate(baseUriBuilder.toUriString() + "/" + repositoryName + "{?page,pageSize}");

        final PagerModel pagerModel = toPagerModel(pageSize > 0
                ? zeroBasedNumberedPaging(page, pageSize, (int)stateRepository.size()).links(repositoryUri, allOf(PagingRel.class))
                : emptyLinks());

        final List<ImmutableMap<String, String>> entitiesModel = entityPageIds
                .stream()
                .map(entityId -> toEntityModel(entityId, stateRepository.get(entityId)))
                .collect(toList());
        return new ModelAndView(
                "staterepository",
                ImmutableMap.<String,Object>builder()
                        .put("basePath", managementBasePath)
                        .put("singleEntity", false)
                        .put("journaled", journals.hasJournal(repositoryName))
                        .put("repositoryName", repositoryName)
                        .put("entities", entitiesModel)
                        .put("pager", pagerModel)
                        .build()
        );
    } else {
        throw new ResponseStatusException(NOT_FOUND, "No such StateRepository " + repositoryName);
    }
}
 
Example #27
Source File: TemplateUri.java    From scava with Eclipse Public License 2.0 4 votes vote down vote up
public TemplateUri(String uri) {
    this.uri = UriTemplate.fromTemplate(uri);
}
 
Example #28
Source File: StateRepositoryRestController.java    From synapse with Apache License 2.0 4 votes vote down vote up
/**
 * Returns an application/hal+json representation of a {@link StateRepository}, containing a pageable collection
 * resource with links to the event-sourced entities stored in the repository.
 *
 * @param repositoryName the name of the StateRepository
 * @param page the zero-based page number
 * @param pageSize the number of entities to return
 * @param uriComponentsBuilder builder used to create hrefs
 *
 * @return HalRepresentation of the paged collection resource
 */
@GetMapping(
        path = "${edison.application.management.base-path:internal}/staterepositories/{repositoryName}",
        produces = {"application/hal+json", "application/json"}
)
@ResponseBody
public HalRepresentation getStateRepository(final @PathVariable String repositoryName,
                                            final @RequestParam(defaultValue = "0") int page,
                                            final @RequestParam(defaultValue = "100") int pageSize,
                                            final UriComponentsBuilder uriComponentsBuilder) {
    if (stateRepositories.containsKey(repositoryName)) {

        final UriComponentsBuilder baseUriBuilder = uriComponentsBuilder
                .pathSegment(managementBasePath)
                .path("/staterepositories");
        final UriTemplate repositoriesUri = fromTemplate(baseUriBuilder.toUriString());
        final UriTemplate repositoryUri = fromTemplate(baseUriBuilder.toUriString() + "/" + repositoryName + "{?page,pageSize}");
        final UriTemplate entityUri = fromTemplate(baseUriBuilder.toUriString() + "/" + repositoryName + "/{entityId}");

        final StateRepository<?> stateRepository = stateRepositories
                .get(repositoryName);

        final Set<String> allEntityIds = stateRepository.keySet();
        final List<String> entityPageIds = allEntityIds
                .stream()
                .skip(page * pageSize)
                .limit(pageSize)
                .collect(toList());

        final Links pagingLinks = pageSize > 0
                ? zeroBasedNumberedPaging(page, pageSize, (int)stateRepository.size()).links(repositoryUri, allOf(PagingRel.class))
                : emptyLinks();

        final List<Link> itemLinks = entityItemLinks(entityUri, entityPageIds);

        return new HalRepresentation(
                linkingTo()
                        .with(pagingLinks)
                        .single(collection(repositoriesUri.expand()))
                        .array(itemLinks).build()
        );
    } else {
        throw new ResponseStatusException(NOT_FOUND, "No such StateRepository " + repositoryName);
    }
}
 
Example #29
Source File: TemplateUri.java    From scava with Eclipse Public License 2.0 4 votes vote down vote up
public TemplateUri(UriTemplate uri) {
    this.uri = uri;
}
 
Example #30
Source File: ResourceScanner.java    From seed with Mozilla Public License 2.0 4 votes vote down vote up
private boolean isTemplated(String path) {
    return UriTemplate.fromTemplate(path).expressionCount() > 0;
}