@SuppressWarnings("unchecked") @Override @Transactional(TxType.REQUIRED) public E create(final E transientInstance) throws MessageLabelException { log.trace("Create a new entity {}", getModelClass().getName()); if (transientInstance == null) { log.warn("Try to create a null object !"); throw new NullDataException(); } validateEntity((IEntity<Serializable>) transientInstance); mapsId(transientInstance); reSet(transientInstance); getEntityManager().persist(transientInstance); // rebuild Set fields because they are hashed with null entity pk. reSet(transientInstance); log.trace("New entity {} created", transientInstance); return transientInstance; }
@Override @Transactional(TxType.REQUIRED) public boolean delete(final E detachedInstance) throws MessageLabelException { log.trace("Delete one entity {}", getModelClass().getName()); if (detachedInstance == null) { log.warn("Try to delete a null object !"); throw new NullDataException(); } final E persistedInstance = findByPk(detachedInstance.getPrimaryKey()); if (persistedInstance == null) { log.trace("Entity {} {} doesn't exist for deletion", getModelClass().getName(), detachedInstance.getPrimaryKey()); return false; } getEntityManager().remove(persistedInstance); log.trace("Entity {} {} deleted", getModelClass().getName(), persistedInstance.getPrimaryKey()); return true; }
@Override @Transactional(TxType.NEVER) public void updateStatus(Long stackId, StatusRequest statusRequest) { Stack stack = stackService.getByIdWithLists(stackId); Cluster cluster = stack.getCluster(); if (cluster == null) { throw new BadRequestException(String.format("There is no cluster installed on stack '%s'.", stack.getName())); } switch (statusRequest) { case SYNC: sync(stack); break; case STOPPED: stop(stack, cluster); break; case STARTED: start(stack, cluster); break; default: throw new BadRequestException("Cannot update the status of cluster because status request not valid"); } }
@Override @Transactional(TxType.NEVER) public Cluster updateClusterStatusByStackId(Long stackId, Status status, String statusReason) { LOGGER.debug("Updating cluster status. stackId: {}, status: {}, statusReason: {}", stackId, status, statusReason); StackStatus stackStatus = stackService.getCurrentStatusByStackId(stackId); Cluster cluster = retrieveClusterByStackId(stackId); if (cluster != null) { cluster.setStatus(status); cluster.setStatusReason(statusReason); cluster = clusterRepository.save(cluster); if (status.isRemovableStatus()) { InMemoryStateStore.deleteCluster(cluster.getId()); if (stackStatus.getStatus().isRemovableStatus()) { InMemoryStateStore.deleteStack(stackId); } } else { InMemoryStateStore.putCluster(cluster.getId(), statusToPollGroupConverter.convert(status)); if (InMemoryStateStore.getStack(stackId) == null) { InMemoryStateStore.putStack(stackId, statusToPollGroupConverter.convert(stackStatus.getStatus())); } } } return cluster; }
@Override @Transactional(value = TxType.NOT_SUPPORTED) public String getKey() { return KEY; }
@Override @Transactional(TxType.REQUIRED) public <S extends Office> S save(S entity) { logger.info("Transaction should be started by Blueprint interceptor"); if (entity.isNew()) { em.persist(entity); } else { em.merge(entity); } return entity; }
@Override @Transactional(value = TxType.SUPPORTS) public E read(final E transientInstance) throws MessageLabelException { log.trace("Read entity {}", transientInstance); if (transientInstance == null || transientInstance.getPrimaryKey() == null) { throw new NullPrimaryKeyException(); } return findByPk(transientInstance.getPrimaryKey()); }
@Override @Transactional(TxType.SUPPORTS) public E findByPk(final P pk) throws MessageLabelException { log.trace("Get entity {} for pk {}", getModelClass().getName(), pk); if (pk == null) { throw new NullPrimaryKeyException(); } final E entity = getEntityManager().find(getModelClass(), pk); if (entity == null) { log.trace("Object {} is not found for pk {}", getModelClass().getName(), pk); } else { log.trace("Object {} is found for pk {}", getModelClass().getName(), pk); } return entity; }
@Override @Transactional(TxType.SUPPORTS) public E findByPk(final P pk, final E eagerLoading) throws MessageLabelException { if (eagerLoading == null) { return findByPk(pk); } if (pk == null) { throw new NullPrimaryKeyException(); } log.trace("Get entity {} for pk {}", getModelClass().getName(), pk); final JpqlEntityQueryBuilder<E> queryBuilder = getQueryBuilder(eagerLoading); queryBuilder.getWhere() .equals(queryBuilder.getAlias(eagerLoading) + StringUtil.DOT + EntityUtil.getPrimaryKeyField(getModelClass()).getName(), pk); if (queryBuilder.getSingleResult() == null) { log.trace("Object {} is not found for pk {}", getModelClass().getName(), pk); return null; } else { log.trace("Object {} is found for pk {}", getModelClass().getName(), pk); return getEntityManager().find(getModelClass(), pk); } }
@Override @SuppressWarnings("unchecked") @Transactional(TxType.SUPPORTS) public Collection<E> findAllByPk(final Collection<P> primaryKeys, final E eagerLoading) throws MessageLabelException { if (primaryKeys == null) { return null; } E eager = eagerLoading; if (eagerLoading == null) { eager = ObjectUtil.newInstance(getModelClass()); } if (CollectionUtil.isEmpty(primaryKeys)) { return ObjectUtil.newInstance(primaryKeys.getClass()); } if (primaryKeys.size() >= MAX_ELEMENTS) { throw new TooMuchDataException(MAX_ELEMENTS); } log.trace("Get entities {} for {} pk with eager loading ", getModelClass().getName(), primaryKeys.size()); final JpqlEntityQueryBuilder<E> queryBuilder = getQueryBuilder(eager); queryBuilder.getWhere().in(queryBuilder.getAlias(eager) + StringUtil.DOT + EntityUtil.getPrimaryKeyField(getModelClass()).getName(), primaryKeys); final List<E> entities = queryBuilder.getResultList(); log.trace("Found {} entities {}", entities.size(), getModelClass().getName()); if (primaryKeys.getClass().equals(entities.getClass())) { return entities; } else { return CollectionUtil.toCollection(entities, primaryKeys.getClass()); } }
@Override @Transactional(TxType.SUPPORTS) public List<E> findAll() throws MessageLabelException { log.trace("Find all entities {}", getModelClass().getName()); final JpqlEntityQueryBuilder<E> queryBuilder = getQueryBuilder(null); final List<E> entities = queryBuilder.getResultList(); log.trace("Found {} elements for entities {}", entities.size(), getModelClass().getName()); return entities; }
@Override @Transactional(TxType.SUPPORTS) public List<E> findAll(final E criteria, final E eagerLoading, final List<IOrderBy> orderBy) throws MessageLabelException { log.trace("Find all entities {}", getModelClass().getName()); E eager = eagerLoading; if (eager == null) { eager = ObjectUtil.newInstance(getModelClass()); } final JpqlEntityQueryBuilder<E> queryBuilder = getQueryBuilder(eager); queryBuilder.getWhere().and(criteria); orderBy(queryBuilder, orderBy); final List<E> list = queryBuilder.getResultList(); log.trace("Found {} elements for entities {}", list.size(), getModelClass().getName()); return list; }
@SuppressWarnings("unchecked") @Override @Transactional(TxType.REQUIRED) public E update(final E detachedInstance) throws MessageLabelException { log.trace("Update one entity {}", getModelClass().getName()); if (detachedInstance == null) { log.warn("Try to update a null object !"); throw new NullDataException(); } validateEntity((IEntity<Serializable>) detachedInstance); mapsId(detachedInstance); reSet(detachedInstance); // Clear xxxToMany relationship before merging entity, and add their // after merged. final Map<Field, Collection<IEntity<?>>> map = oneToMany(detachedInstance); // Merge the entity. final E entity = getEntityManager().merge(detachedInstance); // Recollection oneToMany relationship in the entity. oneToMany(entity, map); oneToMany(detachedInstance, map); // Flush and reset Set object. getEntityManager().flush(); reSet(detachedInstance); reSet(entity); log.trace("Entity {} updated", entity); return entity; }
@Override @Transactional(TxType.REQUIRED) public void delete(final Collection<E> detachedInstance) throws MessageLabelException { if (CollectionUtil.isEmpty(detachedInstance)) { log.warn("Try to delete a null or empty objects !"); throw new NullDataException(); } for (final E entity : detachedInstance) { delete(entity); } }
@Override @Transactional(TxType.REQUIRED) public <C extends Collection<E>> C create(final C transientInstance) throws MessageLabelException { final C created = newInstance(transientInstance); for (final E entity : transientInstance) { created.add(create(entity)); } return created; }
@SuppressWarnings("unchecked") @Override @Transactional(TxType.SUPPORTS) public <C extends Collection<E>> C read(final C detachedInstance) throws MessageLabelException { final Collection<P> primaryKeys = EntityUtil.getPrimaryKeys(detachedInstance); return (C) findAllByPk(primaryKeys); }
@Override @Transactional(TxType.REQUIRED) public <C extends Collection<E>> C update(final C detachedInstance) throws MessageLabelException { final C updated = newInstance(detachedInstance); for (final E entity : detachedInstance) { updated.add(update(entity)); } return updated; }
@Override @Transactional(TxType.REQUIRED) public E save(final E detachedInstance) throws MessageLabelException { if (EntityUtil.isNullPk(detachedInstance)) { return create(detachedInstance); } else { return update(detachedInstance); } }
@Override @Transactional(TxType.REQUIRED) public <C extends Collection<E>> C save(final C transientInstance) throws MessageLabelException { final C saved = newInstance(transientInstance); for (final E one : transientInstance) { saved.add(save(one)); } return saved; }
@GET @Produces(MediaType.APPLICATION_JSON) @Path("/{id}") @Transactional(value=TxType.REQUIRED) public Event getConcert(@PathParam("id") long id) { System.out.println("ConcertResource.getConcert(" + id + ")"); return emf.createEntityManager().find(Event.class, id); }
@GET @Produces(MediaType.APPLICATION_JSON) @Path("/{id}") @Transactional(value=TxType.REQUIRED) public Event getSportsEvent(@PathParam("id") long id) { System.out.println("ConcertResource.getConcert(" + id + ")"); return emf.createEntityManager().find(Event.class, id); }
@GET @Produces(MediaType.APPLICATION_JSON) @Path("/{id}") @Transactional(value=TxType.REQUIRED) public Venue getItem(@PathParam("id") long id) { System.out.println("VenueResource.getItem(" + id + ")"); return emf.createEntityManager().find(Venue.class, id); }
@Transactional(TxType.NEVER) public Long subscribe(Subscription subscription) { List<Subscription> clientSubscriptions = subscriptionRepository.findByClientIdAndEndpoint(subscription.getClientId(), subscription.getEndpoint()); if (!clientSubscriptions.isEmpty()) { LOGGER.info(String.format("Subscription already exists for this client with the same endpoint [client: '%s', endpoint: '%s']", subscription.getClientId(), subscription.getEndpoint())); return clientSubscriptions.get(0).getId(); } return subscriptionRepository.save(subscription).getId(); }
@Transactional(TxType.NEVER) public Network create(IdentityUser user, Network network) { LOGGER.info("Creating network: [User: '{}', Account: '{}']", user.getUsername(), user.getAccount()); network.setOwner(user.getUserId()); network.setAccount(user.getAccount()); try { return networkRepository.save(network); } catch (DataIntegrityViolationException ex) { String msg = String.format("Error with resource [%s], error: [%s]", APIResourceType.NETWORK, getProperSqlErrorMessage(ex)); throw new BadRequestException(msg); } }
@Transactional(TxType.NEVER) public LdapConfig create(IdentityUser user, LdapConfig ldapConfig) { ldapConfig.setOwner(user.getUserId()); ldapConfig.setAccount(user.getAccount()); try { return ldapConfigRepository.save(ldapConfig); } catch (DataIntegrityViolationException ex) { String msg = String.format("Error with resource [%s], error: [%s]", APIResourceType.LDAP_CONFIG, getProperSqlErrorMessage(ex)); throw new BadRequestException(msg); } }
@Transactional(TxType.NEVER) public Set<StackResponse> retrieveAccountStacks(IdentityUser user) { if (user.getRoles().contains(IdentityUserRole.ADMIN)) { return convertStacks(stackRepository.findAllInAccountWithLists(user.getAccount())); } else { return convertStacks(stackRepository.findPublicInAccountForUser(user.getUserId(), user.getAccount())); } }
@Transactional(TxType.NEVER) public StackResponse getJsonById(Long id, Set<String> entry) { Stack stack = getByIdWithLists(id); authorizationService.hasReadPermission(stack); StackResponse stackResponse = conversionService.convert(stack, StackResponse.class); stackResponse = stackResponseDecorator.decorate(stackResponse, stack, entry); return stackResponse; }
@Transactional(TxType.NEVER) public void updateStatus(Long stackId, StatusRequest status, boolean updateCluster) { Stack stack = getByIdWithLists(stackId); Cluster cluster = null; if (stack.getCluster() != null) { cluster = clusterRepository.findOneWithLists(stack.getCluster().getId()); } switch (status) { case SYNC: sync(stack, false); break; case FULL_SYNC: sync(stack, true); break; case REPAIR_FAILED_NODES: repairFailedNodes(stack); break; case STOPPED: stop(stack, cluster, updateCluster); break; case STARTED: start(stack, cluster, updateCluster); break; default: throw new BadRequestException("Cannot update the status of stack because status request not valid."); } }
@Transactional(TxType.NEVER) public Template create(IdentityUser user, Template template) { LOGGER.debug("Creating template: [User: '{}', Account: '{}']", user.getUsername(), user.getAccount()); Template savedTemplate; template.setOwner(user.getUserId()); template.setAccount(user.getAccount()); try { savedTemplate = templateRepository.save(template); } catch (Exception ex) { throw new DuplicateKeyValueException(APIResourceType.TEMPLATE, template.getName(), ex); } return savedTemplate; }
@Transactional(TxType.NEVER) public Recipe create(IdentityUser user, Recipe recipe) { recipe.setOwner(user.getUserId()); recipe.setAccount(user.getAccount()); try { return recipeRepository.save(recipe); } catch (DataIntegrityViolationException ex) { String msg = String.format("Error with resource [%s], error: [%s]", APIResourceType.RECIPE, getProperSqlErrorMessage(ex)); throw new BadRequestException(msg); } }
@Override @Transactional(TxType.NEVER) public Cluster updateAmbariClientConfig(Long clusterId, HttpClientConfig ambariClientConfig) { Cluster cluster = clusterRepository.findById(clusterId); cluster.setAmbariIp(ambariClientConfig.getApiAddress()); cluster = clusterRepository.save(cluster); LOGGER.info("Updated cluster: [ambariIp: '{}'].", ambariClientConfig.getApiAddress()); return cluster; }
@Override @Transactional(TxType.NEVER) public Cluster updateCluster(Cluster cluster) { LOGGER.debug("Updating cluster. clusterId: {}", cluster.getId()); cluster = clusterRepository.save(cluster); return cluster; }
@Override @Transactional(TxType.NEVER) public Cluster updateClusterMetadata(Long stackId) { Stack stack = stackService.getById(stackId); try { AmbariClient ambariClient = getAmbariClient(stack); Map<String, Integer> hostGroupCounter = new HashMap<>(); Set<HostMetadata> hosts = hostMetadataRepository.findHostsInCluster(stack.getCluster().getId()); Map<String, String> hostStatuses = ambariClient.getHostStatuses(); for (HostMetadata host : hosts) { if (hostStatuses.containsKey(host.getHostName())) { String hgName = host.getHostGroup().getName(); Integer hgCounter = hostGroupCounter.getOrDefault(hgName, 0) + 1; hostGroupCounter.put(hgName, hgCounter); HostMetadataState newState = HostMetadataState.HEALTHY.name().equals(hostStatuses.get(host.getHostName())) ? HostMetadataState.HEALTHY : HostMetadataState.UNHEALTHY; boolean stateChanged = updateHostMetadataByHostState(stack, host.getHostName(), newState); if (stateChanged && HostMetadataState.HEALTHY == newState) { updateInstanceMetadataStateToRegistered(stackId, host); } } } hostGroupCounter(stack.getCluster().getId(), hostGroupCounter); } catch (CloudbreakSecuritySetupException e) { throw new CloudbreakServiceException(e); } return stack.getCluster(); }
@Transactional(TxType.NEVER) public Blueprint create(IdentityUser user, Blueprint blueprint, List<Map<String, Map<String, String>>> properties) { LOGGER.debug("Creating blueprint: [User: '{}', Account: '{}']", user.getUsername(), user.getAccount()); Blueprint savedBlueprint; blueprint.setOwner(user.getUserId()); blueprint.setAccount(user.getAccount()); if (properties != null && !properties.isEmpty()) { LOGGER.info("Extend blueprint with the following properties: {}", properties); Map<String, Map<String, String>> configs = new HashMap<>(properties.size()); for (Map<String, Map<String, String>> property : properties) { for (Entry<String, Map<String, String>> entry : property.entrySet()) { Map<String, String> configValues = configs.get(entry.getKey()); if (configValues != null) { configValues.putAll(entry.getValue()); } else { configs.put(entry.getKey(), entry.getValue()); } } } String extendedBlueprint = new AmbariClient().extendBlueprintGlobalConfiguration(blueprint.getBlueprintText(), configs); LOGGER.info("Extended blueprint result: {}", extendedBlueprint); blueprint.setBlueprintText(extendedBlueprint); } try { savedBlueprint = blueprintRepository.save(blueprint); } catch (DataIntegrityViolationException ex) { String msg = String.format("Error with resource [%s], error: [%s]", APIResourceType.BLUEPRINT, getProperSqlErrorMessage(ex)); throw new BadRequestException(msg); } return savedBlueprint; }
@Transactional(TxType.NEVER) public ClusterTemplate create(IdentityUser user, ClusterTemplate clusterTemplate) { LOGGER.debug("Creating clusterTemplate: [User: '{}', Account: '{}']", user.getUsername(), user.getAccount()); ClusterTemplate savedClusterTemplate; clusterTemplate.setOwner(user.getUserId()); clusterTemplate.setAccount(user.getAccount()); try { savedClusterTemplate = clusterTemplateRepository.save(clusterTemplate); } catch (DataIntegrityViolationException ex) { String msg = String.format("Error with resource [%s], error: [%s]", APIResourceType.CLUSTER_TEMPLATE, getProperSqlErrorMessage(ex)); throw new BadRequestException(msg); } return savedClusterTemplate; }
@Transactional(TxType.NEVER) public Topology create(IdentityUser user, Topology topology) { LOGGER.debug("Creating topology: [User: '{}', Account: '{}']", user.getUsername(), user.getAccount()); Topology savedTopology; topology.setOwner(user.getUserId()); topology.setAccount(user.getAccount()); try { savedTopology = topologyRepository.save(topology); } catch (DataIntegrityViolationException ex) { String msg = String.format("Error with resource [%s], error: [%s]", APIResourceType.TOPOLOGY, getProperSqlErrorMessage(ex)); throw new BadRequestException(msg); } return savedTopology; }
@Transactional(TxType.NEVER) public Map<String, String> interactiveLogin(IdentityUser user, Credential credential) { LOGGER.debug("Interactive login: [User: '{}', Account: '{}']", user.getUsername(), user.getAccount()); credential.setOwner(user.getUserId()); credential.setAccount(user.getAccount()); return credentialAdapter.interactiveLogin(credential); }
@Transactional(TxType.NEVER) public Credential create(IdentityUser user, Credential credential) { LOGGER.debug("Creating credential: [User: '{}', Account: '{}']", user.getUsername(), user.getAccount()); credential.setOwner(user.getUserId()); credential.setAccount(user.getAccount()); return saveCredential(credential); }
@Transactional(TxType.NEVER) public Credential create(String userId, String account, Credential credential) { LOGGER.debug("Creating credential: [UserId: '{}', Account: '{}']", userId, account); credential.setOwner(userId); credential.setAccount(account); return saveCredential(credential); }