use of io.gravitee.definition.model.Plan in project gravitee-management-rest-api by gravitee-io.
the class ApiServiceImpl method isSynchronized.
@Override
public boolean isSynchronized(String apiId) {
try {
// 1_ First, check the API state
ApiEntity api = findById(apiId);
Map<String, Object> properties = new HashMap<>();
properties.put(Event.EventProperties.API_ID.getValue(), apiId);
io.gravitee.common.data.domain.Page<EventEntity> events = eventService.search(Arrays.asList(PUBLISH_API, EventType.UNPUBLISH_API), properties, 0, 0, 0, 1);
if (!events.getContent().isEmpty()) {
// According to page size, we know that we have only one element in the list
EventEntity lastEvent = events.getContent().get(0);
// TODO: Done only for backward compatibility with 0.x. Must be removed later (1.1.x ?)
boolean enabled = objectMapper.getDeserializationConfig().isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
Api payloadEntity = objectMapper.readValue(lastEvent.getPayload(), Api.class);
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, enabled);
final ApiEntity deployedApi = convert(payloadEntity);
// Remove policy description from sync check
removeDescriptionFromPolicies(api);
removeDescriptionFromPolicies(deployedApi);
boolean sync = apiSynchronizationProcessor.processCheckSynchronization(deployedApi, api);
// but only for published or closed plan
if (sync) {
Set<PlanEntity> plans = planService.findByApi(api.getId());
sync = plans.stream().filter(plan -> (plan.getStatus() != PlanStatus.STAGING)).filter(plan -> plan.getNeedRedeployAt().after(api.getDeployedAt())).count() == 0;
}
return sync;
}
} catch (Exception e) {
LOGGER.error("An error occurs while trying to check API synchronization state {}", apiId, e);
}
return false;
}
use of io.gravitee.definition.model.Plan in project gravitee-management-rest-api by gravitee-io.
the class ApiPlansResourceTest method getApi.
private ApiEntity getApi(DefinitionVersion version) {
ApiEntity api = new ApiEntity();
api.setId(API);
api.setGraviteeDefinitionVersion(version.getLabel());
if (DefinitionVersion.V2.equals(version)) {
Plan plan1 = new Plan();
plan1.setId(PLAN);
Plan plan2 = new Plan();
plan2.setId("plan-2");
api.setPlans(Arrays.asList(plan1, plan2));
}
return api;
}
use of io.gravitee.definition.model.Plan in project gravitee-management-rest-api by gravitee-io.
the class ApiServiceImpl method update.
@Override
public ApiEntity update(String apiId, UpdateApiEntity updateApiEntity, boolean checkPlans) {
try {
LOGGER.debug("Update API {}", apiId);
Optional<Api> optApiToUpdate = apiRepository.findById(apiId);
if (!optApiToUpdate.isPresent()) {
throw new ApiNotFoundException(apiId);
}
// check if entrypoints are unique
final Collection<VirtualHost> sanitizedVirtualHosts = virtualHostService.sanitizeAndValidate(updateApiEntity.getProxy().getVirtualHosts(), apiId);
updateApiEntity.getProxy().setVirtualHosts(new ArrayList<>(sanitizedVirtualHosts));
// check endpoints presence
checkEndpointsExists(updateApiEntity);
// check endpoints name
checkEndpointsName(updateApiEntity);
// check HC inheritance
checkHealthcheckInheritance(updateApiEntity);
// validate HC cron schedule
validateHealtcheckSchedule(updateApiEntity);
// check CORS Allow-origin format
checkAllowOriginFormat(updateApiEntity);
addLoggingMaxDuration(updateApiEntity.getProxy().getLogging());
// check if there is regex errors in plaintext fields
validateRegexfields(updateApiEntity);
// check policy configurations.
checkPolicyConfigurations(updateApiEntity);
final ApiEntity apiToCheck = convert(optApiToUpdate.get());
// if user changes sharding tags, then check if he is allowed to do it
checkShardingTags(updateApiEntity, apiToCheck);
// if lifecycle state not provided, set the saved one
if (updateApiEntity.getLifecycleState() == null) {
updateApiEntity.setLifecycleState(apiToCheck.getLifecycleState());
}
// check lifecycle state
checkLifecycleState(updateApiEntity, apiToCheck);
Set<String> groups = updateApiEntity.getGroups();
if (groups != null && !groups.isEmpty()) {
// check the existence of groups
checkGroupExistence(groups);
// remove PO group if exists
groups = removePOGroups(groups, apiId);
updateApiEntity.setGroups(groups);
}
// add a default path, if version is v1
if (Objects.equals(updateApiEntity.getGraviteeDefinitionVersion(), DefinitionVersion.V1.getLabel()) && (updateApiEntity.getPaths() == null || updateApiEntity.getPaths().isEmpty())) {
updateApiEntity.setPaths(singletonMap("/", new ArrayList<>()));
}
if (updateApiEntity.getPlans() == null) {
updateApiEntity.setPlans(new ArrayList<>());
} else if (checkPlans) {
List<Plan> existingPlans = apiToCheck.getPlans();
Map<String, String> planStatuses = new HashMap<>();
if (existingPlans != null && !existingPlans.isEmpty()) {
planStatuses.putAll(existingPlans.stream().collect(toMap(Plan::getId, Plan::getStatus)));
}
updateApiEntity.getPlans().forEach(planToUpdate -> {
if (!planStatuses.containsKey(planToUpdate.getId()) || (planStatuses.containsKey(planToUpdate.getId()) && planStatuses.get(planToUpdate.getId()).equalsIgnoreCase(PlanStatus.CLOSED.name()) && !planStatuses.get(planToUpdate.getId()).equalsIgnoreCase(planToUpdate.getStatus()))) {
throw new InvalidDataException("Invalid status for plan '" + planToUpdate.getName() + "'");
}
});
}
Api apiToUpdate = optApiToUpdate.get();
if (io.gravitee.rest.api.model.api.ApiLifecycleState.DEPRECATED.equals(updateApiEntity.getLifecycleState())) {
planService.findByApi(apiId).forEach(plan -> {
if (PlanStatus.PUBLISHED.equals(plan.getStatus()) || PlanStatus.STAGING.equals(plan.getStatus())) {
planService.deprecate(plan.getId(), true);
updateApiEntity.getPlans().stream().filter(p -> p.getId().equals(plan.getId())).forEach(p -> p.setStatus(PlanStatus.DEPRECATED.name()));
}
});
}
Api api = convert(apiId, updateApiEntity, apiToUpdate.getDefinition());
if (api != null) {
api.setId(apiId.trim());
api.setUpdatedAt(new Date());
// Copy fields from existing values
api.setEnvironmentId(apiToUpdate.getEnvironmentId());
api.setDeployedAt(apiToUpdate.getDeployedAt());
api.setCreatedAt(apiToUpdate.getCreatedAt());
api.setLifecycleState(apiToUpdate.getLifecycleState());
// If no new picture and the current picture url is not the default one, keep the current picture
if (updateApiEntity.getPicture() == null && updateApiEntity.getPictureUrl() != null && updateApiEntity.getPictureUrl().indexOf("?hash") > 0) {
api.setPicture(apiToUpdate.getPicture());
}
if (updateApiEntity.getBackground() == null && updateApiEntity.getBackgroundUrl() != null && updateApiEntity.getBackgroundUrl().indexOf("?hash") > 0) {
api.setBackground(apiToUpdate.getBackground());
}
if (updateApiEntity.getGroups() == null) {
api.setGroups(apiToUpdate.getGroups());
}
if (updateApiEntity.getLabels() == null && apiToUpdate.getLabels() != null) {
api.setLabels(new ArrayList<>(new HashSet<>(apiToUpdate.getLabels())));
}
if (updateApiEntity.getCategories() == null) {
api.setCategories(apiToUpdate.getCategories());
}
if (ApiLifecycleState.DEPRECATED.equals(api.getApiLifecycleState())) {
notifierService.trigger(ApiHook.API_DEPRECATED, apiId, new NotificationParamsBuilder().api(apiToCheck).user(userService.findById(getAuthenticatedUsername())).build());
}
Api updatedApi = apiRepository.update(api);
// Audit
auditService.createApiAuditLog(updatedApi.getId(), Collections.emptyMap(), API_UPDATED, updatedApi.getUpdatedAt(), apiToUpdate, updatedApi);
if (parameterService.findAsBoolean(Key.LOGGING_AUDIT_TRAIL_ENABLED, ParameterReferenceType.ENVIRONMENT)) {
// Audit API logging if option is enabled
auditApiLogging(apiToUpdate, updatedApi);
}
ApiEntity apiEntity = convert(singletonList(updatedApi)).iterator().next();
ApiEntity apiWithMetadata = fetchMetadataForApi(apiEntity);
searchEngineService.index(apiWithMetadata, false);
return apiEntity;
} else {
LOGGER.error("Unable to update API {} because of previous error.", apiId);
throw new TechnicalManagementException("Unable to update API " + apiId);
}
} catch (TechnicalException ex) {
LOGGER.error("An error occurs while trying to update API {}", apiId, ex);
throw new TechnicalManagementException("An error occurs while trying to update API " + apiId, ex);
}
}
Aggregations