use of io.gravitee.definition.model.Path in project gravitee-management-rest-api by gravitee-io.
the class ApiServiceImpl method createOrUpdateWithDefinition.
@Override
public ApiEntity createOrUpdateWithDefinition(final ApiEntity apiEntity, String apiDefinition, String userId) {
try {
final UpdateApiEntity importedApi = objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false).readValue(apiDefinition, UpdateApiEntity.class);
// Initialize with a default path
if (importedApi.getPaths() == null || importedApi.getPaths().isEmpty()) {
Path path = new Path();
path.setPath("/");
importedApi.setPaths(Collections.singletonMap("/", path));
}
// create group if not exist & replace groupName by groupId
if (importedApi.getGroups() != null) {
Set<String> groupNames = new HashSet<>(importedApi.getGroups());
importedApi.getGroups().clear();
for (String name : groupNames) {
List<GroupEntity> groupEntities = groupService.findByName(name);
GroupEntity group;
if (groupEntities.isEmpty()) {
NewGroupEntity newGroupEntity = new NewGroupEntity();
newGroupEntity.setName(name);
group = groupService.create(newGroupEntity);
} else {
group = groupEntities.get(0);
}
importedApi.getGroups().add(group.getId());
}
}
ApiEntity createdOrUpdatedApiEntity;
Set<MemberToImport> members;
if (apiEntity == null || apiEntity.getId() == null) {
createdOrUpdatedApiEntity = create0(importedApi, userId);
members = Collections.emptySet();
} else {
createdOrUpdatedApiEntity = update(apiEntity.getId(), importedApi);
members = membershipService.getMembers(MembershipReferenceType.API, apiEntity.getId(), RoleScope.API).stream().map(member -> new MemberToImport(member.getUsername(), member.getRole())).collect(Collectors.toSet());
}
// Read the whole definition
final JsonNode jsonNode = objectMapper.readTree(apiDefinition);
// Members
final JsonNode membersDefinition = jsonNode.path("members");
if (membersDefinition != null && membersDefinition.isArray()) {
MemberEntity memberAsPrimaryOwner = null;
for (final JsonNode memberNode : membersDefinition) {
MemberToImport memberEntity = objectMapper.readValue(memberNode.toString(), MemberToImport.class);
Collection<SearchableUser> idpUsers = identityService.search(memberEntity.getUsername());
if (!idpUsers.isEmpty()) {
SearchableUser user = idpUsers.iterator().next();
if (!members.contains(memberEntity) || members.stream().anyMatch(m -> m.getUsername().equals(memberEntity.getUsername()) && !m.getRole().equals(memberEntity.getRole()))) {
MemberEntity membership = membershipService.addOrUpdateMember(new MembershipService.MembershipReference(MembershipReferenceType.API, createdOrUpdatedApiEntity.getId()), new MembershipService.MembershipUser(user.getId(), user.getReference()), new MembershipService.MembershipRole(RoleScope.API, memberEntity.getRole()));
if (SystemRole.PRIMARY_OWNER.name().equals(memberEntity.getRole())) {
// Get the identifier of the primary owner
memberAsPrimaryOwner = membership;
}
}
}
}
// Transfer ownership if necessary
if (memberAsPrimaryOwner != null && !userId.equals(memberAsPrimaryOwner.getId())) {
membershipService.transferApiOwnership(createdOrUpdatedApiEntity.getId(), new MembershipService.MembershipUser(memberAsPrimaryOwner.getId(), null), null);
}
}
// Pages
final JsonNode pagesDefinition = jsonNode.path("pages");
if (pagesDefinition != null && pagesDefinition.isArray()) {
for (final JsonNode pageNode : pagesDefinition) {
PageQuery query = new PageQuery.Builder().api(createdOrUpdatedApiEntity.getId()).name(pageNode.get("name").asText()).type(PageType.valueOf(pageNode.get("type").asText())).build();
List<PageEntity> pageEntities = pageService.search(query);
if (pageEntities == null || pageEntities.isEmpty()) {
pageService.createApiPage(createdOrUpdatedApiEntity.getId(), objectMapper.readValue(pageNode.toString(), NewPageEntity.class));
} else if (pageEntities.size() == 1) {
UpdatePageEntity updatePageEntity = objectMapper.readValue(pageNode.toString(), UpdatePageEntity.class);
pageService.update(pageEntities.get(0).getId(), updatePageEntity);
} else {
LOGGER.error("Not able to identify the page to update: {}. Too much page with the same name", pageNode.get("name").asText());
throw new TechnicalManagementException("Not able to identify the page to update: " + pageNode.get("name").asText() + ". Too much page with the same name");
}
}
}
// Plans
final JsonNode plansDefinition = jsonNode.path("plans");
if (plansDefinition != null && plansDefinition.isArray()) {
for (JsonNode planNode : plansDefinition) {
PlanQuery query = new PlanQuery.Builder().api(createdOrUpdatedApiEntity.getId()).name(planNode.get("name").asText()).security(PlanSecurityType.valueOf(planNode.get("security").asText())).build();
List<PlanEntity> planEntities = planService.search(query);
if (planEntities == null || planEntities.isEmpty()) {
NewPlanEntity newPlanEntity = objectMapper.readValue(planNode.toString(), NewPlanEntity.class);
newPlanEntity.setApi(createdOrUpdatedApiEntity.getId());
planService.create(newPlanEntity);
} else if (planEntities.size() == 1) {
UpdatePlanEntity updatePlanEntity = objectMapper.readValue(planNode.toString(), UpdatePlanEntity.class);
planService.update(updatePlanEntity);
} else {
LOGGER.error("Not able to identify the plan to update: {}. Too much plan with the same name", planNode.get("name").asText());
throw new TechnicalManagementException("Not able to identify the plan to update: " + planNode.get("name").asText() + ". Too much plan with the same name");
}
}
}
return createdOrUpdatedApiEntity;
} catch (final IOException e) {
LOGGER.error("An error occurs while trying to JSON deserialize the API {}", apiDefinition, e);
}
return null;
}
use of io.gravitee.definition.model.Path in project gravitee-management-rest-api by gravitee-io.
the class ApiServiceImpl method create.
@Override
public ApiEntity create(NewApiEntity newApiEntity, String userId) throws ApiAlreadyExistsException {
UpdateApiEntity apiEntity = new UpdateApiEntity();
apiEntity.setName(newApiEntity.getName());
apiEntity.setDescription(newApiEntity.getDescription());
apiEntity.setVersion(newApiEntity.getVersion());
// check the existence of groups
if (newApiEntity.getGroups() != null && !newApiEntity.getGroups().isEmpty()) {
try {
groupService.findByIds(newApiEntity.getGroups());
} catch (GroupsNotFoundException gnfe) {
throw new InvalidDataException("Groups [" + newApiEntity.getGroups() + "] does not exist");
}
}
apiEntity.setGroups(newApiEntity.getGroups());
Proxy proxy = new Proxy();
proxy.setContextPath(newApiEntity.getContextPath());
proxy.setEndpoints(new LinkedHashSet<>());
proxy.getEndpoints().add(new HttpEndpoint("default", newApiEntity.getEndpoint()));
apiEntity.setProxy(proxy);
List<String> declaredPaths = (newApiEntity.getPaths() != null) ? newApiEntity.getPaths() : new ArrayList<>();
if (!declaredPaths.contains("/")) {
declaredPaths.add(0, "/");
}
// Initialize with a default path and provided paths
Map<String, Path> paths = declaredPaths.stream().map(sPath -> {
Path path = new Path();
path.setPath(sPath);
return path;
}).collect(Collectors.toMap(Path::getPath, path -> path));
apiEntity.setPaths(paths);
return create0(apiEntity, userId);
}
use of io.gravitee.definition.model.Path in project gravitee-management-rest-api by gravitee-io.
the class ApiService_ExportAsJsonTest method setUp.
@Before
public void setUp() throws TechnicalException {
PropertyFilter apiMembershipTypeFilter = new ApiPermissionFilter();
objectMapper.setFilterProvider(new SimpleFilterProvider(Collections.singletonMap("apiMembershipTypeFilter", apiMembershipTypeFilter)));
Api api = new Api();
api.setId(API_ID);
api.setDescription("Gravitee.io");
when(apiRepository.findById(API_ID)).thenReturn(Optional.of(api));
PageEntity page = new PageEntity();
page.setName("My Title");
page.setOrder(1);
page.setType(PageType.MARKDOWN.toString());
page.setContent("Read the doc");
when(pageService.findApiPagesByApi(API_ID)).thenReturn(Collections.singletonList(new PageListItem()));
when(pageService.findById(any())).thenReturn(page);
Membership membership = new Membership();
membership.setUserId("johndoe");
membership.setReferenceId(API_ID);
membership.setReferenceType(MembershipReferenceType.API);
membership.setRoles(Collections.singletonMap(RoleScope.API.getId(), SystemRole.PRIMARY_OWNER.name()));
when(membershipRepository.findByReferenceAndRole(eq(MembershipReferenceType.API), eq(API_ID), any(), any())).thenReturn(Collections.singleton(membership));
MemberEntity memberEntity = new MemberEntity();
memberEntity.setUsername(membership.getUserId());
memberEntity.setRole(SystemRole.PRIMARY_OWNER.name());
when(membershipService.getMembers(eq(MembershipReferenceType.API), eq(API_ID), eq(RoleScope.API))).thenReturn(Collections.singleton(memberEntity));
UserEntity userEntity = new UserEntity();
userEntity.setUsername(memberEntity.getId());
when(userService.findByUsername(memberEntity.getId(), false)).thenReturn(userEntity);
api.setGroups(Collections.singleton("my-group"));
GroupEntity groupEntity = new GroupEntity();
groupEntity.setId("my-group");
groupEntity.setName("My Group");
when(groupService.findByIds(api.getGroups())).thenReturn(Collections.singleton(groupEntity));
PlanEntity publishedPlan = new PlanEntity();
publishedPlan.setId("plan-id");
publishedPlan.setApis(Collections.singleton(API_ID));
publishedPlan.setDescription("free plan");
publishedPlan.setType(PlanType.API);
publishedPlan.setSecurity(PlanSecurityType.API_KEY);
publishedPlan.setValidation(PlanValidationType.AUTO);
publishedPlan.setStatus(PlanStatus.PUBLISHED);
Map<String, Path> paths = new HashMap<>();
Path path = new Path();
path.setPath("/");
io.gravitee.definition.model.Rule rule = new io.gravitee.definition.model.Rule();
rule.setEnabled(true);
rule.setMethods(Collections.singletonList(HttpMethod.GET));
Policy policy = new Policy();
policy.setName("rate-limit");
String ls = System.lineSeparator();
policy.setConfiguration("{" + ls + " \"rate\": {" + ls + " \"limit\": 1," + ls + " \"periodTime\": 1," + ls + " \"periodTimeUnit\": \"SECONDS\"" + ls + " }" + ls + " }");
rule.setPolicy(policy);
path.setRules(Collections.singletonList(rule));
paths.put("/", path);
publishedPlan.setPaths(paths);
PlanEntity closedPlan = new PlanEntity();
closedPlan.setId("closedPlan-id");
closedPlan.setApis(Collections.singleton(API_ID));
closedPlan.setDescription("free closedPlan");
closedPlan.setType(PlanType.API);
closedPlan.setSecurity(PlanSecurityType.API_KEY);
closedPlan.setValidation(PlanValidationType.AUTO);
closedPlan.setStatus(PlanStatus.CLOSED);
closedPlan.setPaths(paths);
Set<PlanEntity> set = new HashSet<>();
set.add(publishedPlan);
set.add(closedPlan);
when(planService.findByApi(API_ID)).thenReturn(set);
}
use of io.gravitee.definition.model.Path in project gravitee-gateway by gravitee-io.
the class ApiPathResolverTest method setUp.
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
final Map<String, Path> paths = new HashMap<>();
paths.putAll(new HashMap<String, Path>() {
{
Path p1 = new Path();
p1.setPath("/");
put(p1.getPath(), p1);
Path p2 = new Path();
p2.setPath("/products");
put(p2.getPath(), p2);
Path p3 = new Path();
p3.setPath("/stores");
put(p3.getPath(), p3);
Path p4 = new Path();
p4.setPath("/stores/:storeId");
put(p4.getPath(), p4);
Path p5 = new Path();
p5.setPath("/[0-9,;]+");
put(p5.getPath(), p5);
Path p6 = new Path();
p6.setPath("/Stores/:storeId");
put(p6.getPath(), p6);
}
});
// API 1
Proxy proxy = new Proxy();
proxy.setContextPath("/");
when(api.getProxy()).thenReturn(proxy);
when(api.getPaths()).thenReturn(paths);
pathResolver = new ApiPathResolverImpl(api);
// API 2
Proxy proxy2 = new Proxy();
proxy2.setContextPath("/v1/products");
when(api2.getProxy()).thenReturn(proxy2);
when(api2.getPaths()).thenReturn(paths);
pathResolver2 = new ApiPathResolverImpl(api2);
}
use of io.gravitee.definition.model.Path in project gravitee-gateway by gravitee-io.
the class PlanPolicyChainResolver method calculate.
@Override
protected List<Policy> calculate(StreamType streamType, Request request, Response response, ExecutionContext executionContext) {
if (streamType == StreamType.ON_REQUEST) {
String plan = (String) executionContext.getAttribute(ExecutionContext.ATTR_PLAN);
String application = (String) executionContext.getAttribute(ExecutionContext.ATTR_APPLICATION);
// String user = (String) executionContext.getAttribute(ExecutionContext.ATTR_USER_ID);
// request.metrics().setUserId(user);
request.metrics().setPlan(plan);
request.metrics().setApplication(application);
Plan apiPlan = api.getPlan(plan);
// The call is probably not relative to the same API.
if (plan != null && apiPlan != null) {
Map<String, Path> paths = api.getPlan(plan).getPaths();
if (paths != null && !paths.isEmpty()) {
// For 1.0.0, there is only a single root path defined
// Must be reconsidered when user will be able to manage policies at the plan level by himself
Path rootPath = paths.values().iterator().next();
return rootPath.getRules().stream().filter(rule -> rule.isEnabled() && rule.getMethods().contains(request.method())).map(rule -> create(streamType, rule.getPolicy().getName(), rule.getPolicy().getConfiguration())).filter(Objects::nonNull).collect(Collectors.toList());
}
} else {
logger.warn("No plan has been selected to process request {}. Returning an unauthorized HTTP status (401)", request.id());
return null;
}
}
return Collections.emptyList();
}
Aggregations