Search in sources :

Example 1 with EntitlementException

use of org.craftercms.commons.entitlements.exception.EntitlementException in project studio by craftercms.

the class UserServiceImpl method createUser.

@Override
@HasPermission(type = DefaultPermission.class, action = "create_users")
public User createUser(User user) throws UserAlreadyExistsException, ServiceLayerException, AuthenticationException {
    try {
        entitlementValidator.validateEntitlement(EntitlementType.USER, 1);
    } catch (EntitlementException e) {
        throw new ServiceLayerException("Unable to complete request due to entitlement limits. Please contact " + "your system administrator.", e);
    }
    User toRet = userServiceInternal.createUser(user);
    SiteFeed siteFeed = siteService.getSite(studioConfiguration.getProperty(CONFIGURATION_GLOBAL_SYSTEM_SITE));
    AuditLog auditLog = auditServiceInternal.createAuditLogEntry();
    auditLog.setOperation(OPERATION_CREATE);
    auditLog.setSiteId(siteFeed.getId());
    auditLog.setActorId(getCurrentUser().getUsername());
    auditLog.setPrimaryTargetId(user.getUsername());
    auditLog.setPrimaryTargetType(TARGET_TYPE_USER);
    auditLog.setPrimaryTargetValue(user.getUsername());
    auditServiceInternal.insertAuditLog(auditLog);
    return toRet;
}
Also used : EntitlementException(org.craftercms.commons.entitlements.exception.EntitlementException) User(org.craftercms.studio.api.v2.dal.User) AuthenticatedUser(org.craftercms.studio.model.AuthenticatedUser) SiteFeed(org.craftercms.studio.api.v1.dal.SiteFeed) ServiceLayerException(org.craftercms.studio.api.v1.exception.ServiceLayerException) AuditLog(org.craftercms.studio.api.v2.dal.AuditLog) HasPermission(org.craftercms.commons.security.permissions.annotations.HasPermission)

Example 2 with EntitlementException

use of org.craftercms.commons.entitlements.exception.EntitlementException in project studio by craftercms.

the class SiteServiceImpl method createSiteWithRemoteOption.

@Override
@ValidateParams
public void createSiteWithRemoteOption(@ValidateStringParam(name = "siteId", maxLength = 50, whitelistedPatterns = "[a-z0-9\\-]*") String siteId, @ValidateStringParam(name = "sandboxBranch") String sandboxBranch, @ValidateNoTagsParam(name = "description") String description, String blueprintName, @ValidateStringParam(name = "remoteName") String remoteName, @ValidateStringParam(name = "remoteUrl") String remoteUrl, String remoteBranch, boolean singleBranch, String authenticationType, String remoteUsername, String remotePassword, String remoteToken, String remotePrivateKey, @ValidateStringParam(name = "createOption") String createOption, Map<String, String> params, boolean createAsOrphan) throws ServiceLayerException, InvalidRemoteRepositoryException, InvalidRemoteRepositoryCredentialsException, RemoteRepositoryNotFoundException, RemoteRepositoryNotBareException, InvalidRemoteUrlException {
    if (exists(siteId)) {
        throw new SiteAlreadyExistsException();
    }
    logger.debug("Validate site entitlements");
    try {
        entitlementValidator.validateEntitlement(EntitlementType.SITE, 1);
    } catch (EntitlementException e) {
        throw new SiteCreationException("Unable to complete request due to entitlement limits. Please contact your " + "system administrator.", e);
    }
    switch(createOption) {
        case REMOTE_REPOSITORY_CREATE_OPTION_CLONE:
            logger.info("Clone from remote repository create option selected");
            createSiteCloneRemote(siteId, sandboxBranch, description, remoteName, remoteUrl, remoteBranch, singleBranch, authenticationType, remoteUsername, remotePassword, remoteToken, remotePrivateKey, params, createAsOrphan);
            break;
        case REMOTE_REPOSITORY_CREATE_OPTION_PUSH:
            logger.info("Push to remote repository create option selected");
            createSitePushToRemote(siteId, sandboxBranch, description, blueprintName, remoteName, remoteUrl, remoteBranch, authenticationType, remoteUsername, remotePassword, remoteToken, remotePrivateKey, params, createAsOrphan);
            break;
        default:
            logger.error("Invalid create option for create site using remote repository: " + createOption + "\nAvailable options: [" + REMOTE_REPOSITORY_CREATE_OPTION_CLONE + ", " + REMOTE_REPOSITORY_CREATE_OPTION_PUSH + "]");
            break;
    }
}
Also used : EntitlementException(org.craftercms.commons.entitlements.exception.EntitlementException) SiteAlreadyExistsException(org.craftercms.studio.api.v1.exception.SiteAlreadyExistsException) SiteCreationException(org.craftercms.studio.api.v1.exception.SiteCreationException) ValidateParams(org.craftercms.commons.validation.annotations.param.ValidateParams)

Example 3 with EntitlementException

use of org.craftercms.commons.entitlements.exception.EntitlementException in project commons by craftercms.

the class DefaultDbIntegrityValidatorImpl method validate.

/**
 * {@inheritDoc}
 */
@Override
public void validate(final Connection connection) throws EntitlementException, SQLException {
    try (Statement statement = connection.createStatement()) {
        ResultSet result = statement.executeQuery(QUERY);
        if (result.next()) {
            long stored = result.getLong(1);
            result = statement.executeQuery(query.replace(SCHEMA, connection.getCatalog()));
            if (result.next()) {
                long actual = result.getLong(1);
                if (stored != actual) {
                    result = statement.executeQuery(UPGRADE_DBMS_INTEGRITY_FAIL_CHECK_QUERY.replace(SCHEMA, connection.getCatalog()));
                    if (result.next()) {
                        actual = result.getLong(1);
                        if (stored == actual) {
                            return;
                        } else {
                            result = statement.executeQuery(oldquery.replace(SCHEMA, connection.getCatalog()));
                            if (result.next()) {
                                actual = result.getLong(1);
                                if (stored == actual) {
                                    return;
                                }
                            }
                        }
                    }
                    throw new EntitlementException("Incompatible database detected, unable to start");
                }
            }
        }
    }
}
Also used : EntitlementException(org.craftercms.commons.entitlements.exception.EntitlementException) Statement(java.sql.Statement) PreparedStatement(java.sql.PreparedStatement) ResultSet(java.sql.ResultSet)

Example 4 with EntitlementException

use of org.craftercms.commons.entitlements.exception.EntitlementException in project studio by craftercms.

the class SiteServiceImpl method createSiteFromBlueprint.

@Override
@ValidateParams
public void createSiteFromBlueprint(@ValidateStringParam(name = "blueprintId") String blueprintId, @ValidateNoTagsParam(name = "siteName") String siteName, @ValidateStringParam(name = "siteId", maxLength = 50, whitelistedPatterns = "[a-z0-9\\-]*") String siteId, @ValidateStringParam(name = "sandboxBranch") String sandboxBranch, @ValidateNoTagsParam(name = "desc") String desc, Map<String, String> params, boolean createAsOrphan) throws SiteAlreadyExistsException, SiteCreationException, DeployerTargetException, BlueprintNotFoundException, MissingPluginParameterException {
    if (exists(siteId)) {
        throw new SiteAlreadyExistsException();
    }
    logger.debug("Get blueprint descriptor for: " + blueprintId);
    PluginDescriptor descriptor = sitesServiceInternal.getBlueprintDescriptor(blueprintId);
    if (Objects.isNull(descriptor)) {
        throw new BlueprintNotFoundException();
    }
    logger.debug("Validating blueprint parameters");
    sitesServiceInternal.validateBlueprintParameters(descriptor, params);
    String blueprintLocation = sitesServiceInternal.getBlueprintLocation(blueprintId);
    String searchEngine = descriptor.getPlugin().getSearchEngine();
    logger.debug("Validate site entitlements");
    try {
        entitlementValidator.validateEntitlement(EntitlementType.SITE, 1);
    } catch (EntitlementException e) {
        throw new SiteCreationException("Unable to complete request due to entitlement limits. Please contact " + "your system administrator.", e);
    }
    logger.info("Starting site creation process for site " + siteName + " from " + blueprintId + " blueprint.");
    boolean success = true;
    // We must fail site creation if any of the site creations steps fail and rollback
    // For example: Create site => create Deployer Target (fail) = fail
    // and rollback the whole thing.
    // What we need to do for site creation and the order of execution:
    // 1) deployer target, 2) git repo, 3) database, 4) kick deployer
    String siteUuid = UUID.randomUUID().toString();
    // Create the site in the preview deployer
    logger.info("Creating deployer targets.");
    try {
        deployer.createTargets(siteId, searchEngine);
    } catch (Exception e) {
        success = false;
        String msg = "Error while creating site: " + siteName + " ID: " + siteId + " from blueprint: " + blueprintId + ". The required Deployer targets couldn't be created";
        logger.error(msg, e);
        throw new DeployerTargetException(msg, e);
    }
    if (success) {
        try {
            logger.info("Copying site content from blueprint.");
            success = createSiteFromBlueprintGit(blueprintLocation, siteName, siteId, sandboxBranch, desc, params);
            ZonedDateTime now = ZonedDateTime.now();
            logger.debug("Adding site UUID.");
            addSiteUuidFile(siteId, siteUuid);
            logger.info("Adding site record to database for site " + siteId);
            // insert database records
            SiteFeed siteFeed = new SiteFeed();
            siteFeed.setName(siteName);
            siteFeed.setSiteId(siteId);
            siteFeed.setSiteUuid(siteUuid);
            siteFeed.setDescription(desc);
            siteFeed.setPublishingStatus(READY);
            siteFeed.setPublishingStatusMessage(studioConfiguration.getProperty(JOB_DEPLOY_CONTENT_TO_ENVIRONMENT_STATUS_MESSAGE_DEFAULT));
            siteFeed.setSandboxBranch(sandboxBranch);
            siteFeed.setSearchEngine(searchEngine);
            siteFeedMapper.createSite(siteFeed);
            String localeAddress = studioClusterUtils.getClusterNodeLocalAddress();
            ClusterMember cm = clusterDao.getMemberByLocalAddress(localeAddress);
            if (Objects.nonNull(cm)) {
                SiteFeed s = getSite(siteId);
                clusterDao.insertClusterSiteSyncRepo(cm.getId(), s.getId(), null, null, null);
            }
            logger.info("Upgrading site.");
            upgradeManager.upgradeSite(siteId);
            // Add default groups
            logger.info("Adding default groups");
            addDefaultGroupsForNewSite(siteId);
            String lastCommitId = contentRepositoryV2.getRepoLastCommitId(siteId);
            String creator = securityService.getCurrentUser();
            long startGetChangeSetCreatedFilesMark = logger.isDebugEnabled() ? System.currentTimeMillis() : 0;
            Map<String, String> createdFiles = contentRepositoryV2.getChangeSetPathsFromDelta(siteId, null, lastCommitId);
            if (logger.isDebugEnabled()) {
                logger.debug("Get change set created files finished in " + (System.currentTimeMillis() - startGetChangeSetCreatedFilesMark) + " milliseconds");
            }
            logger.info("Adding audit log");
            insertCreateSiteAuditLog(siteId, siteName, createdFiles);
            processCreatedFiles(siteId, createdFiles, creator, now, lastCommitId);
            contentRepositoryV2.insertGitLog(siteId, lastCommitId, 1, 1);
            updateLastCommitId(siteId, lastCommitId);
            updateLastVerifiedGitlogCommitId(siteId, lastCommitId);
            updateLastSyncedGitlogCommitId(siteId, lastCommitId);
            logger.info("Reload site configuration");
            reloadSiteConfiguration(siteId);
        } catch (Exception e) {
            success = false;
            logger.error("Error while creating site: " + siteName + " ID: " + siteId + " from blueprint: " + blueprintId + ". Rolling back.", e);
            deleteSite(siteId);
            throw new SiteCreationException("Error while creating site: " + siteName + " ID: " + siteId + " from blueprint: " + blueprintId + ". Rolling back.");
        }
    }
    if (success) {
        logger.info("Syncing all content to preview.");
        // Now that everything is created, we can sync the preview deployer with the new content
        try {
            deploymentService.syncAllContentToPreview(siteId, true);
        } catch (ServiceLayerException e) {
            logger.error("Error while syncing site: " + siteName + " ID: " + siteId + " to preview. Site was " + "successfully created otherwise. Ignoring.", e);
            throw new SiteCreationException("Error while syncing site: " + siteName + " ID: " + siteId + " to preview. Site was successfully created, but it won't be preview-able until the Preview " + "Deployer is reachable.");
        }
        setSiteState(siteId, STATE_CREATED);
    } else {
        throw new SiteCreationException("Error while creating site: " + siteName + " ID: " + siteId + ".");
    }
    logger.info("Finished creating site " + siteId);
}
Also used : BlueprintNotFoundException(org.craftercms.studio.api.v1.exception.BlueprintNotFoundException) DeployerTargetException(org.craftercms.studio.api.v1.exception.DeployerTargetException) SiteAlreadyExistsException(org.craftercms.studio.api.v1.exception.SiteAlreadyExistsException) ServiceLayerException(org.craftercms.studio.api.v1.exception.ServiceLayerException) SiteConfigNotFoundException(org.craftercms.studio.api.v1.service.site.SiteConfigNotFoundException) ServiceLayerException(org.craftercms.studio.api.v1.exception.ServiceLayerException) SiteCreationException(org.craftercms.studio.api.v1.exception.SiteCreationException) MissingPluginParameterException(org.craftercms.studio.api.v2.exception.MissingPluginParameterException) IOException(java.io.IOException) RemoteRepositoryNotFoundException(org.craftercms.studio.api.v1.exception.repository.RemoteRepositoryNotFoundException) UserNotFoundException(org.craftercms.studio.api.v1.exception.security.UserNotFoundException) InvalidRemoteUrlException(org.craftercms.studio.api.v1.exception.repository.InvalidRemoteUrlException) DeployerTargetException(org.craftercms.studio.api.v1.exception.DeployerTargetException) RestServiceException(org.craftercms.commons.rest.RestServiceException) SiteAlreadyExistsException(org.craftercms.studio.api.v1.exception.SiteAlreadyExistsException) GroupAlreadyExistsException(org.craftercms.studio.api.v1.exception.security.GroupAlreadyExistsException) DocumentException(org.dom4j.DocumentException) EntitlementException(org.craftercms.commons.entitlements.exception.EntitlementException) BlueprintNotFoundException(org.craftercms.studio.api.v1.exception.BlueprintNotFoundException) SiteNotFoundException(org.craftercms.studio.api.v1.exception.SiteNotFoundException) CryptoException(org.craftercms.commons.crypto.CryptoException) RemoteRepositoryNotBareException(org.craftercms.studio.api.v1.exception.repository.RemoteRepositoryNotBareException) InvalidRemoteRepositoryCredentialsException(org.craftercms.studio.api.v1.exception.repository.InvalidRemoteRepositoryCredentialsException) InvalidRemoteRepositoryException(org.craftercms.studio.api.v1.exception.repository.InvalidRemoteRepositoryException) PluginDescriptor(org.craftercms.commons.plugin.model.PluginDescriptor) EntitlementException(org.craftercms.commons.entitlements.exception.EntitlementException) ClusterMember(org.craftercms.studio.api.v2.dal.ClusterMember) ZonedDateTime(java.time.ZonedDateTime) SiteFeed(org.craftercms.studio.api.v1.dal.SiteFeed) SiteCreationException(org.craftercms.studio.api.v1.exception.SiteCreationException) ValidateParams(org.craftercms.commons.validation.annotations.param.ValidateParams)

Example 5 with EntitlementException

use of org.craftercms.commons.entitlements.exception.EntitlementException in project studio by craftercms.

the class ContentServiceImpl method writeContentAsset.

/**
 * write content asset
 *
 * @param site
 * @param path
 * @param assetName
 * @param in
 * @param isImage
 * 			is this asset an image?
 * @param allowedWidth
 * 			specifies the allowed image width in pixel if the asset is an image
 * @param allowedHeight
 * 			specifies the allowed image height in pixel if the asset is an image
 * @param unlock
 * 			unlock the content upon edit?
 * @return content asset info
 * @throws ServiceLayerException
 */
@Override
@ValidateParams
public Map<String, Object> writeContentAsset(@ValidateStringParam(name = "site") String site, @ValidateSecurePathParam(name = "path") String path, @ValidateStringParam(name = "assetName") String assetName, InputStream in, String isImage, String allowedWidth, String allowedHeight, String allowLessSize, String draft, String unlock, String systemAsset) throws ServiceLayerException {
    try {
        entitlementValidator.validateEntitlement(EntitlementType.ITEM, 1);
    } catch (EntitlementException e) {
        throw new ServiceLayerException("Unable to complete request due to entitlement limits. Please contact your " + "system administrator.");
    }
    boolean isSystemAsset = Boolean.valueOf(systemAsset);
    Map<String, String> params = new HashMap<String, String>();
    params.put(DmConstants.KEY_SITE, site);
    params.put(DmConstants.KEY_PATH, path);
    params.put(DmConstants.KEY_FILE_NAME, assetName);
    params.put(DmConstants.KEY_IS_IMAGE, isImage);
    params.put(DmConstants.KEY_ALLOW_LESS_SIZE, allowLessSize);
    params.put(DmConstants.KEY_ALLOWED_WIDTH, allowedWidth);
    params.put(DmConstants.KEY_ALLOWED_HEIGHT, allowedHeight);
    params.put(DmConstants.KEY_CONTENT_TYPE, "");
    params.put(DmConstants.KEY_CREATE_FOLDERS, "true");
    params.put(DmConstants.KEY_UNLOCK, unlock);
    params.put(DmConstants.KEY_SYSTEM_ASSET, String.valueOf(isSystemAsset));
    boolean exists = contentExists(site, path + FILE_SEPARATOR + assetName);
    params.put(DmConstants.KEY_ACTIVITY_TYPE, (exists ? OPERATION_UPDATE : OPERATION_CREATE));
    String id = site + ":" + path + ":" + assetName + ":" + "";
    // processContent will close the input stream
    ContentItemTO item = null;
    try {
        path = path + FILE_SEPARATOR + assetName;
        item = getContentItem(site, path);
        if (item != null) {
            ItemState itemState = objectStateService.getObjectState(site, path);
            if (itemState != null) {
                if (itemState.getSystemProcessing() != 0) {
                    logger.error(String.format("Error Content %s is being processed " + "(Object State is SYSTEM_PROCESSING);", path));
                    throw new RuntimeException(String.format("Content \"%s\" is being processed", path));
                }
                objectStateService.setSystemProcessing(site, path, true);
            }
        }
        if (objectStateService.deletedPathExists(site, path) || objectMetadataManager.movedPathExists(site, path)) {
            throw new ServiceLayerException("Content " + path + " for site " + site + ", cannot be created because" + " this name/URL was in use by another content item that has been moved or deleted by " + "not yet published.");
        }
        ResultTO result = processContent(id, in, false, params, DmConstants.CONTENT_CHAIN_ASSET);
        ContentAssetInfoTO assetInfoTO = (ContentAssetInfoTO) result.getItem();
        if (isSystemAsset) {
            path = path.replace(assetName, assetInfoTO.getFileName());
        }
        item = getContentItem(site, path);
        item.setSize(assetInfoTO.getSize());
        item.setSizeUnit(assetInfoTO.getSizeUnit());
        if (item != null) {
            if (result.getCommitId() != null) {
                objectStateService.transition(site, item, SAVE);
            } else {
                objectStateService.transition(site, item, TransitionEvent.CANCEL_EDIT);
            }
        }
        PreviewEventContext context = new PreviewEventContext();
        context.setSite(site);
        eventService.publish(EVENT_PREVIEW_SYNC, context);
        Map<String, Object> toRet = new HashMap<String, Object>();
        toRet.put("success", true);
        toRet.put("message", item);
        return toRet;
    } catch (Exception e) {
        logger.error("Error processing content", e);
        Map<String, Object> toRet = new HashMap<String, Object>();
        toRet.put("success", true);
        toRet.put("message", e.getMessage());
        toRet.put("error", e);
        return toRet;
    } finally {
        if (item != null) {
            objectStateService.setSystemProcessing(site, path, false);
        }
    }
}
Also used : ContentAssetInfoTO(org.craftercms.studio.api.v1.to.ContentAssetInfoTO) HashMap(java.util.HashMap) ServiceLayerException(org.craftercms.studio.api.v1.exception.ServiceLayerException) ResultTO(org.craftercms.studio.api.v1.to.ResultTO) ServiceLayerException(org.craftercms.studio.api.v1.exception.ServiceLayerException) IOException(java.io.IOException) AuthenticationException(org.craftercms.studio.api.v1.exception.security.AuthenticationException) InvalidRemoteUrlException(org.craftercms.studio.api.v1.exception.repository.InvalidRemoteUrlException) SAXException(org.xml.sax.SAXException) ContentNotFoundException(org.craftercms.studio.api.v1.exception.ContentNotFoundException) DocumentException(org.dom4j.DocumentException) EntitlementException(org.craftercms.commons.entitlements.exception.EntitlementException) SiteNotFoundException(org.craftercms.studio.api.v1.exception.SiteNotFoundException) CryptoException(org.craftercms.commons.crypto.CryptoException) EntitlementException(org.craftercms.commons.entitlements.exception.EntitlementException) ContentItemTO(org.craftercms.studio.api.v1.to.ContentItemTO) ItemState(org.craftercms.studio.api.v1.dal.ItemState) Map(java.util.Map) HashMap(java.util.HashMap) MimetypesFileTypeMap(javax.activation.MimetypesFileTypeMap) PreviewEventContext(org.craftercms.studio.api.v1.ebus.PreviewEventContext) ValidateParams(org.craftercms.commons.validation.annotations.param.ValidateParams)

Aggregations

EntitlementException (org.craftercms.commons.entitlements.exception.EntitlementException)6 ValidateParams (org.craftercms.commons.validation.annotations.param.ValidateParams)4 ServiceLayerException (org.craftercms.studio.api.v1.exception.ServiceLayerException)4 IOException (java.io.IOException)2 HashMap (java.util.HashMap)2 CryptoException (org.craftercms.commons.crypto.CryptoException)2 ItemState (org.craftercms.studio.api.v1.dal.ItemState)2 SiteFeed (org.craftercms.studio.api.v1.dal.SiteFeed)2 PreviewEventContext (org.craftercms.studio.api.v1.ebus.PreviewEventContext)2 SiteAlreadyExistsException (org.craftercms.studio.api.v1.exception.SiteAlreadyExistsException)2 SiteCreationException (org.craftercms.studio.api.v1.exception.SiteCreationException)2 SiteNotFoundException (org.craftercms.studio.api.v1.exception.SiteNotFoundException)2 InvalidRemoteUrlException (org.craftercms.studio.api.v1.exception.repository.InvalidRemoteUrlException)2 ContentItemTO (org.craftercms.studio.api.v1.to.ContentItemTO)2 DocumentException (org.dom4j.DocumentException)2 PreparedStatement (java.sql.PreparedStatement)1 ResultSet (java.sql.ResultSet)1 Statement (java.sql.Statement)1 ZonedDateTime (java.time.ZonedDateTime)1 Map (java.util.Map)1