use of io.gravitee.repository.exceptions.TechnicalException in project gravitee-management-rest-api by gravitee-io.
the class ApiServiceImpl method convert.
private Set<ApiEntity> convert(Set<Api> apis, boolean readDefinition) throws TechnicalException {
if (apis == null || apis.isEmpty()) {
return Collections.emptySet();
}
// find primary owners usernames of each apis
Set<Membership> memberships = membershipRepository.findByReferencesAndRole(MembershipReferenceType.API, apis.stream().map(Api::getId).collect(Collectors.toList()), RoleScope.API, SystemRole.PRIMARY_OWNER.name());
int poMissing = apis.size() - memberships.size();
if (poMissing > 0) {
Set<String> apiIds = apis.stream().map(Api::getId).collect(Collectors.toSet());
Set<String> apiMembershipsIds = memberships.stream().map(Membership::getReferenceId).collect(Collectors.toSet());
apiIds.removeAll(apiMembershipsIds);
Optional<String> optionalApisAsString = apiIds.stream().reduce((a, b) -> a + " / " + b);
String apisAsString = "?";
if (optionalApisAsString.isPresent())
apisAsString = optionalApisAsString.get();
LOGGER.error("{} apis has no identified primary owners in this list {}.", poMissing, apisAsString);
throw new TechnicalManagementException(poMissing + " apis has no identified primary owners in this list " + apisAsString + ".");
}
Map<String, String> apiToUser = new HashMap<>(memberships.size());
memberships.forEach(membership -> apiToUser.put(membership.getReferenceId(), membership.getUserId()));
Map<String, UserEntity> userIdToUserEntity = new HashMap<>(memberships.size());
userService.findByIds(memberships.stream().map(Membership::getUserId).collect(Collectors.toList())).forEach(userEntity -> userIdToUserEntity.put(userEntity.getId(), userEntity));
return apis.stream().map(publicApi -> this.convert(publicApi, userIdToUserEntity.get(apiToUser.get(publicApi.getId())), readDefinition)).collect(Collectors.toSet());
}
use of io.gravitee.repository.exceptions.TechnicalException in project gravitee-management-rest-api by gravitee-io.
the class ApiServiceImpl method checkContextPath.
private void checkContextPath(String newContextPath, final String apiId) throws TechnicalException {
if (newContextPath.charAt(newContextPath.length() - 1) == '/') {
newContextPath = newContextPath.substring(0, newContextPath.length() - 1);
}
final int indexOfEndOfNewSubContextPath = newContextPath.lastIndexOf('/', 1);
final String newSubContextPath = newContextPath.substring(0, indexOfEndOfNewSubContextPath <= 0 ? newContextPath.length() : indexOfEndOfNewSubContextPath) + '/';
final boolean contextPathExists = apiRepository.findAll().stream().filter(api -> !api.getId().equals(apiId)).anyMatch(api -> {
final String contextPath = convert(api, null, true).getProxy().getContextPath();
final int indexOfEndOfSubContextPath = contextPath.lastIndexOf('/', 1);
final String subContextPath = contextPath.substring(0, indexOfEndOfSubContextPath <= 0 ? contextPath.length() : indexOfEndOfSubContextPath) + '/';
return subContextPath.startsWith(newSubContextPath) || newSubContextPath.startsWith(subContextPath);
});
if (contextPathExists) {
throw new ApiContextPathAlreadyExistsException(newSubContextPath);
}
}
use of io.gravitee.repository.exceptions.TechnicalException in project gravitee-management-rest-api by gravitee-io.
the class ApiServiceImpl method deployLastPublishedAPI.
private ApiEntity deployLastPublishedAPI(String apiId, String userId, EventType eventType) throws TechnicalException {
Set<EventEntity> events = eventService.findByApi(apiId);
Optional<EventEntity> optEvent = events.stream().filter(event -> EventType.PUBLISH_API.equals(event.getType())).sorted((e1, e2) -> e2.getCreatedAt().compareTo(e1.getCreatedAt())).findFirst();
try {
if (optEvent.isPresent()) {
EventEntity event = optEvent.get();
JsonNode node = objectMapper.readTree(event.getPayload());
Api lastPublishedAPI = objectMapper.convertValue(node, Api.class);
lastPublishedAPI.setLifecycleState(convert(eventType));
lastPublishedAPI.setUpdatedAt(new Date());
lastPublishedAPI.setDeployedAt(new Date());
Map<String, String> properties = new HashMap<>();
properties.put(Event.EventProperties.API_ID.getValue(), lastPublishedAPI.getId());
properties.put(Event.EventProperties.USER.getValue(), userId);
// Clear useless field for history
lastPublishedAPI.setPicture(null);
// And create event
eventService.create(eventType, objectMapper.writeValueAsString(lastPublishedAPI), properties);
return convert(Collections.singleton(lastPublishedAPI), true).iterator().next();
} else {
if (events.size() == 0) {
// this is the first time we start the api without previously deployed id.
// let's do it.
this.deploy(apiId, userId, EventType.PUBLISH_API);
return deployLastPublishedAPI(apiId, userId, eventType);
}
throw new TechnicalException("No event found for API " + apiId);
}
} catch (Exception e) {
LOGGER.error("An error occurs while trying to deploy last published API {}", apiId, e);
throw new TechnicalException("An error occurs while trying to deploy last published API " + apiId, e);
}
}
use of io.gravitee.repository.exceptions.TechnicalException in project gravitee-management-rest-api by gravitee-io.
the class ApiServiceImpl method create0.
private ApiEntity create0(UpdateApiEntity api, String userId) throws ApiAlreadyExistsException {
try {
LOGGER.debug("Create {} for user {}", api, userId);
String id = UUID.toString(UUID.random());
Optional<Api> checkApi = apiRepository.findById(id);
if (checkApi.isPresent()) {
throw new ApiAlreadyExistsException(id);
}
// Format context-path and check if context path is unique
checkContextPath(api.getProxy().getContextPath());
Api repoApi = convert(id, api);
if (repoApi != null) {
repoApi.setId(id);
// Set date fields
repoApi.setCreatedAt(new Date());
repoApi.setUpdatedAt(repoApi.getCreatedAt());
// Be sure that lifecycle is set to STOPPED by default and visibility is private
repoApi.setLifecycleState(LifecycleState.STOPPED);
repoApi.setVisibility(Visibility.PRIVATE);
// Add Default groups
Set<String> defaultGroups = groupService.findByEvent(GroupEvent.API_CREATE).stream().map(GroupEntity::getId).collect(Collectors.toSet());
if (!defaultGroups.isEmpty() && repoApi.getGroups() == null) {
repoApi.setGroups(defaultGroups);
} else if (!defaultGroups.isEmpty()) {
repoApi.getGroups().addAll(defaultGroups);
}
Api createdApi = apiRepository.create(repoApi);
// Audit
auditService.createApiAuditLog(createdApi.getId(), Collections.emptyMap(), API_CREATED, createdApi.getCreatedAt(), null, createdApi);
// Add the primary owner of the newly created API
UserEntity primaryOwner = userService.findById(userId);
Membership membership = new Membership(primaryOwner.getId(), createdApi.getId(), MembershipReferenceType.API);
membership.setRoles(Collections.singletonMap(RoleScope.API.getId(), SystemRole.PRIMARY_OWNER.name()));
membership.setCreatedAt(repoApi.getCreatedAt());
membership.setUpdatedAt(repoApi.getCreatedAt());
membershipRepository.create(membership);
// create the default mail notification
if (primaryOwner.getEmail() != null && !primaryOwner.getEmail().isEmpty()) {
GenericNotificationConfigEntity notificationConfigEntity = new GenericNotificationConfigEntity();
notificationConfigEntity.setName("Default Mail Notifications");
notificationConfigEntity.setReferenceType(HookScope.API.name());
notificationConfigEntity.setReferenceId(createdApi.getId());
notificationConfigEntity.setHooks(Arrays.stream(ApiHook.values()).map(Enum::name).collect(Collectors.toList()));
notificationConfigEntity.setNotifier(NotifierServiceImpl.DEFAULT_EMAIL_NOTIFIER_ID);
notificationConfigEntity.setConfig(primaryOwner.getEmail());
genericNotificationConfigService.create(notificationConfigEntity);
}
// TODO add membership log
return convert(createdApi, primaryOwner, true);
} else {
LOGGER.error("Unable to create API {} because of previous error.");
throw new TechnicalManagementException("Unable to create API " + id);
}
} catch (TechnicalException ex) {
LOGGER.error("An error occurs while trying to create {} for user {}", api, userId, ex);
throw new TechnicalManagementException("An error occurs while trying create " + api + " for user " + userId, ex);
}
}
use of io.gravitee.repository.exceptions.TechnicalException in project gravitee-management-rest-api by gravitee-io.
the class ApplicationServiceImpl method update.
@Override
public ApplicationEntity update(String applicationId, UpdateApplicationEntity updateApplicationEntity) {
try {
LOGGER.debug("Update application {}", applicationId);
if (updateApplicationEntity.getGroups() != null && !updateApplicationEntity.getGroups().isEmpty()) {
// throw a NotFoundException if the group doesn't exist
groupService.findByIds(updateApplicationEntity.getGroups());
}
Optional<Application> optApplicationToUpdate = applicationRepository.findById(applicationId);
if (!optApplicationToUpdate.isPresent()) {
throw new ApplicationNotFoundException(applicationId);
}
// If clientId is set, check for uniqueness
String clientId = updateApplicationEntity.getClientId();
if (clientId != null && !clientId.trim().isEmpty()) {
LOGGER.debug("Check that client_id is unique among all applications");
final Set<Application> applications = applicationRepository.findAll(ApplicationStatus.ACTIVE);
final Optional<Application> byClientId = applications.stream().filter(application -> clientId.equals(application.getClientId())).findAny();
if (byClientId.isPresent() && !byClientId.get().getId().equals(optApplicationToUpdate.get().getId())) {
LOGGER.error("An application already exists with the same client_id");
throw new ClientIdAlreadyExistsException(clientId);
}
}
Application application = convert(updateApplicationEntity);
application.setId(applicationId);
application.setStatus(ApplicationStatus.ACTIVE);
application.setCreatedAt(optApplicationToUpdate.get().getCreatedAt());
application.setUpdatedAt(new Date());
Application updatedApplication = applicationRepository.update(application);
// Audit
auditService.createApplicationAuditLog(updatedApplication.getId(), Collections.emptyMap(), APPLICATION_CREATED, updatedApplication.getUpdatedAt(), optApplicationToUpdate.get(), updatedApplication);
// Set correct client_id for all subscriptions
SubscriptionQuery subQuery = new SubscriptionQuery();
subQuery.setApplication(applicationId);
subQuery.setStatuses(Collections.singleton(SubscriptionStatus.ACCEPTED));
subscriptionService.search(subQuery).forEach(new Consumer<SubscriptionEntity>() {
@Override
public void accept(SubscriptionEntity subscriptionEntity) {
UpdateSubscriptionEntity updateSubscriptionEntity = new UpdateSubscriptionEntity();
updateSubscriptionEntity.setId(subscriptionEntity.getId());
updateSubscriptionEntity.setStartingAt(subscriptionEntity.getStartingAt());
updateSubscriptionEntity.setEndingAt(subscriptionEntity.getEndingAt());
subscriptionService.update(updateSubscriptionEntity, application.getClientId());
}
});
return convert(Collections.singleton(updatedApplication)).iterator().next();
} catch (TechnicalException ex) {
LOGGER.error("An error occurs while trying to update application {}", applicationId, ex);
throw new TechnicalManagementException(String.format("An error occurs while trying to update application %s", applicationId), ex);
}
}
Aggregations