Java源码示例:org.glassfish.jersey.uri.UriTemplate

示例1
private static RequestEvent event(Integer status, Exception exception, String baseUri, String... uriTemplateStrings) {
    Builder builder = new RequestEventImpl.Builder();

    ContainerRequest containerRequest = mock(ContainerRequest.class);
    when(containerRequest.getMethod()).thenReturn("GET");
    builder.setContainerRequest(containerRequest);

    ContainerResponse containerResponse = mock(ContainerResponse.class);
    when(containerResponse.getStatus()).thenReturn(status);
    builder.setContainerResponse(containerResponse);

    builder.setException(exception, null);

    ExtendedUriInfo extendedUriInfo = mock(ExtendedUriInfo.class);
    when(extendedUriInfo.getBaseUri()).thenReturn(
        URI.create("http://localhost:8080" + (baseUri == null ? "/" : baseUri)));
    List<UriTemplate> uriTemplates = uriTemplateStrings == null ? Collections.emptyList()
        : Arrays.stream(uriTemplateStrings).map(uri -> new UriTemplate(uri))
        .collect(Collectors.toList());
    // UriTemplate are returned in reverse order
    Collections.reverse(uriTemplates);
    when(extendedUriInfo.getMatchedTemplates()).thenReturn(uriTemplates);
    builder.setExtendedUriInfo(extendedUriInfo);

    return builder.build(Type.FINISHED);
}
 
示例2
private void setupUriInfoWithBasePathAndUriTemplates(
    ExtendedUriInfo uriInfoMock,
    URI basePath,
    String ... templateStrings
) {
    doReturn(basePath).when(uriInfoMock).getBaseUri();

    List<UriTemplate> templates = new ArrayList<>();
    if (templateStrings != null) {
        for (String templateString : templateStrings) {
            templates.add(new UriTemplate(templateString));
        }
    }

    doReturn(templates).when(uriInfoMock).getMatchedTemplates();
}
 
示例3
private String getTemplatePath(ExtendedUriInfo uriInfo) {
    StringBuilder builder = new StringBuilder();

    for (UriTemplate template : uriInfo.getMatchedTemplates()) {
        List<String> variables = template.getTemplateVariables();
        String[] args = new String[variables.size()];
        for (int i = 0; i < args.length; i++) {
            args[i] = "{" + variables.get(i) + "}";
        }
        String uri = template.createURI(args);
        if (!uri.equals("/") && !uri.equals(""))
            builder.insert(0, uri);
    }

    return builder.toString();
}
 
示例4
/**
 * This returns the matched template as defined by a base URL and path expressions.
 *
 * <p>Matched templates are pairs of (resource path, method path) added with
 * {@link org.glassfish.jersey.server.internal.routing.RoutingContext#pushTemplates(UriTemplate,
 * UriTemplate)}. This code skips redundant slashes from either source caused by Path("/") or
 * Path("").
 */
@Nullable static String route(ContainerRequest request) {
  ExtendedUriInfo uriInfo = request.getUriInfo();
  List<UriTemplate> templates = uriInfo.getMatchedTemplates();
  int templateCount = templates.size();
  if (templateCount == 0) return "";
  StringBuilder builder = null; // don't allocate unless you need it!
  String basePath = uriInfo.getBaseUri().getPath();
  String result = null;
  if (!"/" .equals(basePath)) { // skip empty base paths
    result = basePath;
  }
  for (int i = templateCount - 1; i >= 0; i--) {
    String template = templates.get(i).getTemplate();
    if ("/" .equals(template)) continue; // skip allocation
    if (builder != null) {
      builder.append(template);
    } else if (result != null) {
      builder = new StringBuilder(result).append(template);
      result = null;
    } else {
      result = template;
    }
  }
  return result != null ? result : builder != null ? builder.toString() : "";
}
 
示例5
public String newClient(String name, String email) {
  ObjectNode clientDto = resourcesDtos.clientDto(name, email);
  Response response = resourcesClient.postClient(clientDto);
  response.close();
  assertThat(response.getStatus(), equalTo(201));
  Map<String, String> params = new HashMap<>();
  UriTemplate clientUriTemplate = resourcesClient.getResourcesUrls().clientUriTemplate();
  assertTrue(clientUriTemplate.match(response.getHeaderString("Location"), params));
  return params.get("id");
}
 
示例6
public String newAccount(String clientId) {
  Response response = resourcesClient.postAccount(resourcesDtos.accountDto(clientId));
  response.close();
  assertThat(response.getStatus(), equalTo(201));
  Map<String, String> params = new HashMap<>();
  UriTemplate accountUriTemplate = resourcesClient.getResourcesUrls().accountUriTemplate();
  assertTrue(accountUriTemplate.match(response.getHeaderString("Location"), params));
  return params.get("id");
}
 
示例7
@Test
void newAccount() {
  String clientId = stateSetup.newClient("John", "[email protected]");
  Response response = resourcesClient.postAccount(resourcesDtos.accountDto(clientId));
  response.close();
  assertThat(response.getStatus(), equalTo(201));
  UriTemplate accountUriTemplate = resourcesClient.getResourcesUrls().accountUriTemplate();
  assertTrue(accountUriTemplate.match(response.getHeaderString("Location"), new ArrayList<>()));
}
 
示例8
@Test
void newClient() {
  ObjectNode clientDto = resourcesDtos.clientDto("John", "[email protected]");
  Response response = resourcesClient.postClient(clientDto);
  response.close();
  assertThat(response.getStatus(), equalTo(201));
  UriTemplate clientUriTemplate = resourcesClient.getResourcesUrls().clientUriTemplate();
  assertTrue(clientUriTemplate.match(response.getHeaderString("Location"), new ArrayList<>()));
}
 
示例9
private static String getMatchingPattern(RequestEvent event) {
    ExtendedUriInfo uriInfo = event.getUriInfo();
    List<UriTemplate> templates = uriInfo.getMatchedTemplates();

    StringBuilder sb = new StringBuilder();
    sb.append(uriInfo.getBaseUri().getPath());
    for (int i = templates.size() - 1; i >= 0; i--) {
        sb.append(templates.get(i).getTemplate());
    }
    String multipleSlashCleaned = MULTIPLE_SLASH_PATTERN.matcher(sb.toString()).replaceAll("/");
    if (multipleSlashCleaned.equals("/")) {
        return multipleSlashCleaned;
    }
    return TRAILING_SLASH_PATTERN.matcher(multipleSlashCleaned).replaceAll("");
}
 
示例10
@Override
public boolean isMatching(Request request, ResourceMethod resourceMethod) {
    Resource resource = resourceMethod.getParent();

    try {
        return new UriTemplate(resource.getPath()).match(request.getPathTemplate(), new HashMap<>());
    } catch (NullPointerException e) {
        return false;
    }
}
 
示例11
/**
 * This returns the matched template as defined by a base URL and path expressions.
 *
 * <p>Matched templates are pairs of (resource path, method path) added with
 * {@link RoutingContext#pushTemplates(UriTemplate, UriTemplate)}.
 * This code skips redundant slashes from either source caused by Path("/") or Path("").
 */
protected String route(ContainerRequest request) {
    ExtendedUriInfo uriInfo = request.getUriInfo();
    List<UriTemplate> templates = uriInfo.getMatchedTemplates();
    int templateCount = templates.size();
    if (templateCount == 0) {
        return "";
    }
    StringBuilder builder = null; // don't allocate unless you need it!
    String basePath = uriInfo.getBaseUri().getPath();
    String result = null;

    if (!"/".equals(basePath)) { // skip empty base paths
        result = basePath;
    }
    for (int i = templateCount - 1; i >= 0; i--) {
        String template = templates.get(i).getTemplate();
        if ("/".equals(template)) {
            continue; // skip allocation
        }
        if (builder != null) {
            builder.append(template);
        }
        else if (result != null) {
            builder = new StringBuilder(result).append(template);
            result = null;
        }
        else {
            result = template;
        }
    }

    return (result != null)
           ? result
           : (builder != null)
             ? builder.toString()
             : "";
}
 
示例12
/**
 * Merges all path patterns and and creates a single string value which will be equal with service methods path
 * annotation value and HTTP method type. Generated string will be used for permission checks.
 *
 * @param token            for checking permission list
 * @param matchedTemplates matched templates of context. They will be merged with reverse order
 * @param method           HTTP Method of the request. Will be merged with
 * @return true if user is Authorized.
 */
private boolean isAuthorized(BasicToken token, List<UriTemplate> matchedTemplates, String method) {
    StringBuilder path = new StringBuilder();
    // Merge all path templates and generate a path.
    for (UriTemplate template : matchedTemplates) {
        path.insert(0, template.getTemplate());
    }
    path.append(":").append(method);

    //Look at user permissions to see if the service is permitted.
    return token.getPermissions().contains(path.toString());
}
 
示例13
/**
 * returns path arguments of the http path.
 */
public static Set<ArgumentName> pathArgs(String httpPath) {
    UriTemplate uriTemplate = new UriTemplate(httpPath);
    return uriTemplate.getTemplateVariables().stream().map(ArgumentName::of).collect(Collectors.toSet());
}
 
示例14
public UriTemplate clientUriTemplate() {
  return new UriTemplate(format("http://localhost:%d/clients/{id}", port));
}
 
示例15
public UriTemplate accountUriTemplate() {
  return new UriTemplate(format("http://localhost:%d/accounts/{id}", port));
}
 
示例16
FakeExtendedUriInfo(URI baseURI, List<UriTemplate> matchedTemplates) {
  this.baseURI = baseURI;
  this.matchedTemplates = matchedTemplates;
}
 
示例17
@Override public List<UriTemplate> getMatchedTemplates() {
  return matchedTemplates;
}