Search in sources :

Example 16 with SiteFeed

use of org.craftercms.studio.api.v1.dal.SiteFeed in project studio by craftercms.

the class ContentServiceImpl method updateDatabaseOnMove.

protected void updateDatabaseOnMove(String site, String fromPath, String movePath) throws SiteNotFoundException {
    logger.debug("updateDatabaseOnMove FROM {0} TO {1}  ", fromPath, movePath);
    String user = securityService.getCurrentUser();
    Map<String, String> params = new HashMap<>();
    params.put(DmConstants.KEY_SOURCE_PATH, fromPath);
    params.put(DmConstants.KEY_TARGET_PATH, movePath);
    // These do not exist in 3.0, note some extensions may be using it
    // params.put(DmConstants.KEY_SOURCE_FULL_PATH, expandRelativeSitePath(site, fromPath));
    // params.put(DmConstants.KEY_TARGET_FULL_PATH, expandRelativeSitePath(site, movePath));
    ContentItemTO renamedItem = getContentItem(site, movePath, 0);
    String contentType = renamedItem.getContentType();
    if (!renamedItem.isFolder()) {
        dmContentLifeCycleService.process(site, user, movePath, contentType, DmContentLifeCycleService.ContentLifeCycleOperation.RENAME, params);
        // change the path of this object in the object state database
        objectStateService.updateObjectPath(site, fromPath, movePath);
        objectStateService.transition(site, renamedItem, SAVE);
        renamedItem = getContentItem(site, movePath, 0);
    }
    // update metadata
    if (!objectMetadataManager.isRenamed(site, fromPath)) {
        // if an item was previously moved, we do not track intermediate moves because it will
        // ultimately orphan deployed content.  Old Path is always the OLDEST DEPLOYED PATH
        ItemMetadata metadata = objectMetadataManager.getProperties(site, fromPath);
        if (metadata == null && !renamedItem.isFolder()) {
            if (!objectMetadataManager.metadataExist(site, fromPath)) {
                objectMetadataManager.insertNewObjectMetadata(site, fromPath);
            }
            metadata = objectMetadataManager.getProperties(site, fromPath);
        }
        if (!renamedItem.isNew() && !renamedItem.isFolder()) {
            // if the item is not new, we need to track the old URL for deployment
            logger.debug("item is not new, and has not previously been moved. Track the old URL {0}", fromPath);
            Map<String, Object> objMetadataProps = new HashMap<String, Object>();
            objMetadataProps.put(ItemMetadata.PROP_RENAMED, 1);
            objMetadataProps.put(ItemMetadata.PROP_OLD_URL, fromPath);
            objectMetadataManager.setObjectMetadata(site, fromPath, objMetadataProps);
        }
    }
    if (!renamedItem.isFolder()) {
        if (objectMetadataManager.metadataExist(site, movePath)) {
            if (!StringUtils.equalsIgnoreCase(fromPath, movePath)) {
                objectMetadataManager.deleteObjectMetadata(site, movePath);
            }
        }
        objectMetadataManager.updateObjectPath(site, fromPath, movePath);
    }
    // write activity stream
    SiteFeed siteFeed = siteService.getSite(site);
    AuditLog auditLog = auditServiceInternal.createAuditLogEntry();
    auditLog.setOperation(OPERATION_MOVE);
    auditLog.setSiteId(siteFeed.getId());
    auditLog.setActorId(user);
    auditLog.setPrimaryTargetId(site + ":" + movePath);
    if (renamedItem.isFolder()) {
        auditLog.setPrimaryTargetType(TARGET_TYPE_FOLDER);
    } else {
        auditLog.setPrimaryTargetType(TARGET_TYPE_CONTENT_ITEM);
    }
    auditLog.setPrimaryTargetValue(movePath);
    auditLog.setPrimaryTargetSubtype(getContentTypeClass(site, movePath));
    auditServiceInternal.insertAuditLog(auditLog);
    updateDependenciesOnMove(site, fromPath, movePath);
}
Also used : ContentItemTO(org.craftercms.studio.api.v1.to.ContentItemTO) HashMap(java.util.HashMap) SiteFeed(org.craftercms.studio.api.v1.dal.SiteFeed) AuditLog(org.craftercms.studio.api.v2.dal.AuditLog) ItemMetadata(org.craftercms.studio.api.v1.dal.ItemMetadata)

Example 17 with SiteFeed

use of org.craftercms.studio.api.v1.dal.SiteFeed in project studio by craftercms.

the class PostActivityProcessor method process.

public void process(PipelineContent content, ResultTO result) throws SiteNotFoundException {
    if (result.getCommitId() != null) {
        String site = content.getProperty(DmConstants.KEY_SITE);
        boolean skipAuditLogInsert = ContentFormatUtils.getBooleanValue(content.getProperty(DmConstants.KEY_SKIP_AUDIT_LOG_INSERT));
        if (!skipAuditLogInsert) {
            String type = content.getProperty(DmConstants.KEY_ACTIVITY_TYPE);
            String user = content.getProperty(DmConstants.KEY_USER);
            String activityType = OPERATION_CREATE.equals(type) ? OPERATION_CREATE : OPERATION_UPDATE;
            String folderPath = content.getProperty(DmConstants.KEY_FOLDER_PATH);
            String fileName = content.getProperty(DmConstants.KEY_FILE_NAME);
            boolean isSystemAsset = ContentFormatUtils.getBooleanValue(content.getProperty(DmConstants.KEY_SYSTEM_ASSET));
            if (isSystemAsset) {
                ContentAssetInfoTO assetInfoTO = (ContentAssetInfoTO) result.getItem();
                fileName = assetInfoTO.getFileName();
            }
            String uri = (folderPath.endsWith(FILE_SEPARATOR)) ? folderPath + fileName : folderPath + FILE_SEPARATOR + fileName;
            SiteFeed siteFeed = siteService.getSite(site);
            AuditLog auditLog = auditServiceInternal.createAuditLogEntry();
            auditLog.setOperation(activityType);
            auditLog.setActorId(user);
            auditLog.setSiteId(siteFeed.getId());
            auditLog.setPrimaryTargetId(site + ":" + uri);
            auditLog.setPrimaryTargetType(TARGET_TYPE_CONTENT_ITEM);
            auditLog.setPrimaryTargetValue(uri);
            auditLog.setPrimaryTargetSubtype(contentService.getContentTypeClass(site, uri));
            auditServiceInternal.insertAuditLog(auditLog);
        }
        contentRepository.markGitLogAudited(site, result.getCommitId());
    }
}
Also used : ContentAssetInfoTO(org.craftercms.studio.api.v1.to.ContentAssetInfoTO) SiteFeed(org.craftercms.studio.api.v1.dal.SiteFeed) AuditLog(org.craftercms.studio.api.v2.dal.AuditLog)

Example 18 with SiteFeed

use of org.craftercms.studio.api.v1.dal.SiteFeed in project studio by craftercms.

the class WorkflowServiceImpl method submitForApproval.

@SuppressWarnings("unchecked")
protected ResultTO submitForApproval(final String site, String submittedBy, final String request, final boolean delete) throws ServiceLayerException {
    RequestContext requestContext = RequestContextBuilder.buildSubmitContext(site, submittedBy);
    ResultTO result = new ResultTO();
    try {
        SimpleDateFormat format = new SimpleDateFormat(StudioConstants.DATE_PATTERN_WORKFLOW_WITH_TZ);
        JSONObject requestObject = JSONObject.fromObject(request);
        JSONArray items = requestObject.getJSONArray(JSON_KEY_ITEMS);
        int length = items.size();
        if (length > 0) {
            for (int index = 0; index < length; index++) {
                objectStateService.setSystemProcessing(site, items.optString(index), true);
            }
        }
        boolean isNow = (requestObject.containsKey(JSON_KEY_SCHEDULE)) ? StringUtils.equalsIgnoreCase(requestObject.getString(JSON_KEY_SCHEDULE), JSON_KEY_IS_NOW) : false;
        ZonedDateTime scheduledDate = null;
        if (!isNow) {
            scheduledDate = (requestObject.containsKey(JSON_KEY_SCHEDULED_DATE)) ? getScheduledDate(site, format, requestObject.getString(JSON_KEY_SCHEDULED_DATE)) : null;
        }
        boolean sendEmail = (requestObject.containsKey(JSON_KEY_SEND_EMAIL)) ? requestObject.getBoolean(JSON_KEY_SEND_EMAIL) : false;
        String environment = (requestObject != null && requestObject.containsKey(JSON_KEY_ENVIRONMENT)) ? requestObject.getString(JSON_KEY_ENVIRONMENT) : null;
        String submissionComment = (requestObject != null && requestObject.containsKey(JSON_KEY_SUBMISSION_COMMENT)) ? requestObject.getString(JSON_KEY_SUBMISSION_COMMENT) : null;
        // TODO: check scheduled date to make sure it is not null when isNow
        // = true and also it is not past
        String schDate = null;
        if (requestObject.containsKey(JSON_KEY_SCHEDULED_DATE)) {
            schDate = requestObject.getString(JSON_KEY_SCHEDULED_DATE);
        }
        if (length > 0) {
            List<DmDependencyTO> submittedItems = new ArrayList<DmDependencyTO>();
            for (int index = 0; index < length; index++) {
                String stringItem = items.optString(index);
                DmDependencyTO submittedItem = getSubmittedItem(site, stringItem, format, schDate, null);
                String user = submittedBy;
                submittedItems.add(submittedItem);
                if (delete) {
                    submittedItem.setSubmittedForDeletion(true);
                }
            }
            submittedItems.addAll(addDependenciesForSubmitForApproval(site, submittedItems, format, schDate));
            List<String> submittedPaths = new ArrayList<String>();
            for (DmDependencyTO goLiveItem : submittedItems) {
                submittedPaths.add(goLiveItem.getUri());
                objectStateService.setSystemProcessing(site, goLiveItem.getUri(), true);
                DependencyRules rule = new DependencyRules(site);
                rule.setObjectStateService(objectStateService);
                rule.setContentService(contentService);
                Set<DmDependencyTO> depSet = rule.applySubmitRule(goLiveItem);
                for (DmDependencyTO dep : depSet) {
                    submittedPaths.add(dep.getUri());
                    objectStateService.setSystemProcessing(site, dep.getUri(), true);
                }
            }
            List<DmError> errors = submitToGoLive(submittedItems, scheduledDate, sendEmail, delete, requestContext, submissionComment, environment);
            SiteFeed siteFeed = siteService.getSite(site);
            AuditLog auditLog = auditServiceInternal.createAuditLogEntry();
            auditLog.setOperation(OPERATION_REQUEST_PUBLISH);
            auditLog.setActorId(submittedBy);
            auditLog.setSiteId(siteFeed.getId());
            auditLog.setPrimaryTargetId(site);
            auditLog.setPrimaryTargetType(TARGET_TYPE_CONTENT_ITEM);
            auditLog.setPrimaryTargetValue(site);
            auditServiceInternal.insertAuditLog(auditLog);
            result.setSuccess(true);
            result.setStatus(200);
            result.setMessage(notificationService.getNotificationMessage(site, NotificationMessageType.CompleteMessages, COMPLETE_SUBMIT_TO_GO_LIVE_MSG, Locale.ENGLISH));
            for (String relativePath : submittedPaths) {
                objectStateService.setSystemProcessing(site, relativePath, false);
            }
        }
    } catch (Exception e) {
        result.setSuccess(false);
        result.setMessage(e.getMessage());
        logger.error("Error while submitting content for approval.", e);
    }
    return result;
}
Also used : JSONArray(net.sf.json.JSONArray) ArrayList(java.util.ArrayList) DependencyRules(org.craftercms.studio.api.v1.service.dependency.DependencyRules) DmDependencyTO(org.craftercms.studio.api.v1.to.DmDependencyTO) ResultTO(org.craftercms.studio.api.v1.to.ResultTO) AuditLog(org.craftercms.studio.api.v2.dal.AuditLog) ServiceLayerException(org.craftercms.studio.api.v1.exception.ServiceLayerException) ContentNotFoundException(org.craftercms.studio.api.v1.exception.ContentNotFoundException) JSONException(net.sf.json.JSONException) DeploymentException(org.craftercms.studio.api.v1.service.deployment.DeploymentException) JSONObject(net.sf.json.JSONObject) ZonedDateTime(java.time.ZonedDateTime) DmError(org.craftercms.studio.api.v1.to.DmError) SiteFeed(org.craftercms.studio.api.v1.dal.SiteFeed) RequestContext(org.craftercms.studio.api.v1.service.workflow.context.RequestContext) SimpleDateFormat(java.text.SimpleDateFormat)

Example 19 with SiteFeed

use of org.craftercms.studio.api.v1.dal.SiteFeed in project studio by craftercms.

the class WorkflowServiceImpl method approve_new.

/**
 * approve workflows and schedule them as specified in the request
 *
 * @param site
 * @param request
 * @return call result
 * @throws ServiceLayerException
 */
@SuppressWarnings("unchecked")
protected ResultTO approve_new(String site, String request, Operation operation) {
    String approver = securityService.getCurrentUser();
    ResultTO result = new ResultTO();
    try {
        JSONObject requestObject = JSONObject.fromObject(request);
        JSONArray items = requestObject.getJSONArray(JSON_KEY_ITEMS);
        String scheduledDate = null;
        if (requestObject.containsKey(JSON_KEY_SCHEDULED_DATE)) {
            scheduledDate = requestObject.getString(JSON_KEY_SCHEDULED_DATE);
        }
        boolean isNow = (requestObject.containsKey(JSON_KEY_IS_NOW)) ? requestObject.getBoolean(JSON_KEY_IS_NOW) : false;
        String publishChannelGroupName = (requestObject.containsKey(JSON_KEY_PUBLISH_CHANNEL)) ? requestObject.getString(JSON_KEY_PUBLISH_CHANNEL) : null;
        JSONObject jsonObjectStatus = requestObject.getJSONObject(JSON_KEY_STATUS_SET);
        String statusMessage = (jsonObjectStatus != null && jsonObjectStatus.containsKey(JSON_KEY_STATUS_MESSAGE)) ? jsonObjectStatus.getString(JSON_KEY_STATUS_MESSAGE) : null;
        String submissionComment = (requestObject != null && requestObject.containsKey(JSON_KEY_SUBMISSION_COMMENT)) ? requestObject.getString(JSON_KEY_SUBMISSION_COMMENT) : "Test Go Live";
        MultiChannelPublishingContext mcpContext = new MultiChannelPublishingContext(publishChannelGroupName, statusMessage, submissionComment);
        int length = items.size();
        if (length == 0) {
            throw new ServiceLayerException("No items provided to go live.");
        }
        List<String> submittedPaths = new ArrayList<String>();
        String responseMessageKey = null;
        SimpleDateFormat format = new SimpleDateFormat(StudioConstants.DATE_PATTERN_WORKFLOW_WITH_TZ);
        List<DmDependencyTO> submittedItems = new ArrayList<>();
        for (int index = 0; index < length; index++) {
            String stringItem = items.optString(index);
            submittedPaths.add(stringItem);
            DmDependencyTO submittedItem = null;
            submittedItem = getSubmittedItem_new(site, stringItem, format, scheduledDate);
            List<DmDependencyTO> submitForDeleteChildren = removeSubmitToDeleteChildrenForGoLive(submittedItem, operation);
            if (submittedItem.isReference()) {
                submittedItem.setReference(false);
            }
            submittedItems.add(submittedItem);
            submittedItems.addAll(submitForDeleteChildren);
        }
        switch(operation) {
            case GO_LIVE:
                if (scheduledDate != null && !isNow) {
                    responseMessageKey = NotificationService.COMPLETE_SCHEDULE_GO_LIVE;
                } else {
                    responseMessageKey = NotificationService.COMPLETE_GO_LIVE;
                }
                List<DmDependencyTO> submitToDeleteItems = new ArrayList<>();
                List<DmDependencyTO> goLiveItems = new ArrayList<>();
                List<DmDependencyTO> renameItems = new ArrayList<>();
                for (DmDependencyTO item : submittedItems) {
                    if (item.isSubmittedForDeletion()) {
                        submitToDeleteItems.add(item);
                    } else {
                        if (!isItemRenamed(site, item)) {
                            goLiveItems.add(item);
                        } else {
                            renameItems.add(item);
                        }
                    }
                }
                if (!submitToDeleteItems.isEmpty()) {
                    doDelete(site, submitToDeleteItems, approver);
                }
                if (!goLiveItems.isEmpty()) {
                    List<DmDependencyTO> references = getRefAndChildOfDiffDateFromParent_new(site, goLiveItems, true);
                    List<DmDependencyTO> children = getRefAndChildOfDiffDateFromParent_new(site, goLiveItems, false);
                    goLiveItems.addAll(references);
                    goLiveItems.addAll(children);
                    List<DmDependencyTO> dependencies = addDependenciesForSubmittedItems(site, submittedItems, format, scheduledDate);
                    goLiveItems.addAll(dependencies);
                    List<String> goLivePaths = new ArrayList<>();
                    List<AuditLogParameter> auditLogParameters = new ArrayList<AuditLogParameter>();
                    for (DmDependencyTO goLiveItem : goLiveItems) {
                        goLivePaths.add(goLiveItem.getUri());
                        AuditLogParameter auditLogParameter = new AuditLogParameter();
                        auditLogParameter.setTargetId(site + ":" + goLiveItem.getUri());
                        auditLogParameter.setTargetType(TARGET_TYPE_CONTENT_ITEM);
                        auditLogParameter.setTargetValue(goLiveItem.getUri());
                        auditLogParameters.add(auditLogParameter);
                    }
                    goLive(site, goLiveItems, approver, mcpContext);
                    SiteFeed siteFeed = siteService.getSite(site);
                    AuditLog auditLog = auditServiceInternal.createAuditLogEntry();
                    auditLog.setActorId(approver);
                    auditLog.setSiteId(siteFeed.getId());
                    auditLog.setPrimaryTargetId(site);
                    auditLog.setPrimaryTargetType(TARGET_TYPE_SITE);
                    auditLog.setPrimaryTargetValue(site);
                    auditLog.setParameters(auditLogParameters);
                    if (scheduledDate != null && !isNow) {
                        auditLog.setOperation(OPERATION_APPROVE_SCHEDULED);
                    } else {
                        auditLog.setOperation(OPERATION_APPROVE);
                    }
                    auditServiceInternal.insertAuditLog(auditLog);
                }
                if (!renameItems.isEmpty()) {
                    List<String> renamePaths = new ArrayList<>();
                    List<DmDependencyTO> renamedChildren = new ArrayList<>();
                    for (DmDependencyTO renameItem : renameItems) {
                        renamedChildren.addAll(getChildrenForRenamedItem(site, renameItem));
                        renamePaths.add(renameItem.getUri());
                        objectStateService.setSystemProcessing(site, renameItem.getUri(), true);
                    }
                    for (DmDependencyTO renamedChild : renamedChildren) {
                        renamePaths.add(renamedChild.getUri());
                        objectStateService.setSystemProcessing(site, renamedChild.getUri(), true);
                    }
                    renameItems.addAll(renamedChildren);
                    // Set proper information of all renameItems before send them to GoLive
                    for (int i = 0; i < renameItems.size(); i++) {
                        DmDependencyTO renamedItem = renameItems.get(i);
                        if (renamedItem.getScheduledDate() != null && renamedItem.getScheduledDate().isAfter(ZonedDateTime.now(ZoneOffset.UTC))) {
                            renamedItem.setNow(false);
                        } else {
                            renamedItem.setNow(true);
                        }
                        renameItems.set(i, renamedItem);
                    }
                    goLive(site, renameItems, approver, mcpContext);
                }
                break;
            case DELETE:
                responseMessageKey = NotificationService.COMPLETE_DELETE;
                List<String> deletePaths = new ArrayList<>();
                List<String> nodeRefs = new ArrayList<String>();
                List<AuditLogParameter> auditLogParameters = new ArrayList<AuditLogParameter>();
                for (DmDependencyTO deletedItem : submittedItems) {
                    // deletedItem.setScheduledDate(getScheduledDate(site, format, scheduledDate));
                    deletePaths.add(deletedItem.getUri());
                    AuditLogParameter auditLogParameter = new AuditLogParameter();
                    auditLogParameter.setTargetId(site + ":" + deletedItem.getUri());
                    auditLogParameter.setTargetType(TARGET_TYPE_CONTENT_ITEM);
                    auditLogParameter.setTargetValue(deletedItem.getUri());
                    auditLogParameters.add(auditLogParameter);
                }
                doDelete(site, submittedItems, approver);
                SiteFeed siteFeed = siteService.getSite(site);
                AuditLog auditLog = auditServiceInternal.createAuditLogEntry();
                auditLog.setOperation(OPERATION_APPROVE);
                auditLog.setActorId(approver);
                auditLog.setSiteId(siteFeed.getId());
                auditLog.setPrimaryTargetId(site);
                auditLog.setPrimaryTargetType(TARGET_TYPE_SITE);
                auditLog.setPrimaryTargetValue(site);
                auditLog.setParameters(auditLogParameters);
                auditServiceInternal.insertAuditLog(auditLog);
        }
        result.setSuccess(true);
        result.setStatus(200);
        result.setMessage(notificationService.getNotificationMessage(site, NotificationMessageType.CompleteMessages, responseMessageKey, Locale.ENGLISH));
    } catch (JSONException e) {
        logger.error("error performing operation " + operation + " " + e);
        result.setSuccess(false);
        result.setMessage(e.getMessage());
    } catch (ServiceLayerException e) {
        logger.error("error performing operation " + operation + " " + e);
        result.setSuccess(false);
        result.setMessage(e.getMessage());
    }
    return result;
}
Also used : JSONArray(net.sf.json.JSONArray) ArrayList(java.util.ArrayList) ServiceLayerException(org.craftercms.studio.api.v1.exception.ServiceLayerException) JSONException(net.sf.json.JSONException) DmDependencyTO(org.craftercms.studio.api.v1.to.DmDependencyTO) ResultTO(org.craftercms.studio.api.v1.to.ResultTO) AuditLog(org.craftercms.studio.api.v2.dal.AuditLog) MultiChannelPublishingContext(org.craftercms.studio.api.v1.service.workflow.context.MultiChannelPublishingContext) JSONObject(net.sf.json.JSONObject) SiteFeed(org.craftercms.studio.api.v1.dal.SiteFeed) AuditLogParameter(org.craftercms.studio.api.v2.dal.AuditLogParameter) SimpleDateFormat(java.text.SimpleDateFormat)

Example 20 with SiteFeed

use of org.craftercms.studio.api.v1.dal.SiteFeed in project studio by craftercms.

the class SiteServiceImpl method createSiteCloneRemote.

@SuppressWarnings("deprecation")
private void createSiteCloneRemote(String siteId, String sandboxBranch, String description, String remoteName, String remoteUrl, String remoteBranch, boolean singleBranch, String authenticationType, String remoteUsername, String remotePassword, String remoteToken, String remotePrivateKey, Map<String, String> params, boolean createAsOrphan) throws ServiceLayerException, InvalidRemoteRepositoryException, InvalidRemoteRepositoryCredentialsException, RemoteRepositoryNotFoundException, InvalidRemoteUrlException {
    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) git repo, 2) deployer target, 3) database, 4) kick deployer
    String siteUuid = UUID.randomUUID().toString();
    try {
        // create site by cloning remote git repo
        logger.info("Creating site " + siteId + " by cloning remote repository " + remoteName + " (" + remoteUrl + ")");
        success = contentRepositoryV2.createSiteCloneRemote(siteId, sandboxBranch, remoteName, remoteUrl, remoteBranch, singleBranch, authenticationType, remoteUsername, remotePassword, remoteToken, remotePrivateKey, params, createAsOrphan);
    } catch (InvalidRemoteRepositoryException | InvalidRemoteRepositoryCredentialsException | RemoteRepositoryNotFoundException | InvalidRemoteUrlException | ServiceLayerException e) {
        contentRepository.deleteSite(siteId);
        logger.error("Error while creating site: " + siteId + " ID: " + siteId + " as clone from " + "remote repository: " + remoteName + " (" + remoteUrl + "). Rolling back.", e);
        throw e;
    }
    if (!success) {
        contentRepository.removeRemoteRepositoriesForSite(siteId);
        contentRepository.deleteSite(siteId);
        throw new ServiceLayerException("Failed to create site: " + siteId + " ID: " + siteId + " as clone from " + "remote repository: " + remoteName + " (" + remoteUrl + ")");
    }
    // try to get the search engine from the blueprint descriptor file
    String searchEngine = studioConfiguration.getProperty(StudioConfiguration.PREVIEW_SEARCH_ENGINE);
    PluginDescriptor descriptor = sitesServiceInternal.getSiteBlueprintDescriptor(siteId);
    if (Objects.nonNull(descriptor) && Objects.nonNull(descriptor.getPlugin())) {
        searchEngine = descriptor.getPlugin().getSearchEngine();
        logger.info("Using search engine {0} from plugin descriptor", searchEngine);
    } else if (Objects.nonNull(descriptor) && Objects.nonNull(descriptor.getBlueprint())) {
        searchEngine = descriptor.getBlueprint().getSearchEngine();
        logger.info("Using search engine {0} from blueprint descriptor", searchEngine);
    } else {
        logger.info("Missing descriptor, using default search engine {0}", searchEngine);
    }
    if (success) {
        // Create the site in the preview deployer
        try {
            logger.info("Creating Deployer targets for site " + siteId);
            deployer.createTargets(siteId, searchEngine);
        } catch (Exception e) {
            logger.error("Error while creating site: " + siteId + " ID: " + siteId + " as clone from" + " remote repository: " + remoteName + " (" + remoteUrl + "). Rolling back...", e);
            contentRepositoryV2.removeRemote(siteId, remoteName);
            boolean deleted = contentRepository.deleteSite(siteId);
            if (!deleted) {
                logger.error("Error while rolling back site: " + siteId);
            }
            throw new DeployerTargetException("Error while creating site: " + siteId + " ID: " + siteId + " as clone from remote repository: " + remoteName + " (" + remoteUrl + "). The required Deployer targets couldn't " + "be created", e);
        }
    }
    if (success) {
        ZonedDateTime now = ZonedDateTime.now();
        String creator = securityService.getCurrentUser();
        try {
            logger.debug("Adding site UUID.");
            addSiteUuidFile(siteId, siteUuid);
            // insert database records
            logger.info("Adding site record to database for site " + siteId);
            SiteFeed siteFeed = new SiteFeed();
            siteFeed.setName(siteId);
            siteFeed.setSiteId(siteId);
            siteFeed.setSiteUuid(siteUuid);
            siteFeed.setDescription(description);
            siteFeed.setPublishingStatus(READY);
            siteFeed.setPublishingStatusMessage(studioConfiguration.getProperty(JOB_DEPLOY_CONTENT_TO_ENVIRONMENT_STATUS_MESSAGE_DEFAULT));
            siteFeed.setSandboxBranch(sandboxBranch);
            siteFeed.setSearchEngine(searchEngine);
            siteFeedMapper.createSite(siteFeed);
            upgradeManager.upgradeSite(siteId);
            // Add default groups
            logger.info("Adding default groups for site " + siteId);
            addDefaultGroupsForNewSite(siteId);
            String lastCommitId = contentRepositoryV2.getRepoLastCommitId(siteId);
            String firstCommitId = contentRepositoryV2.getRepoFirstCommitId(siteId);
            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");
            }
            insertCreateSiteAuditLog(siteId, siteId, createdFiles);
            contentRepositoryV2.insertGitLog(siteId, firstCommitId, 1, 1);
            processCreatedFiles(siteId, createdFiles, creator, now, lastCommitId);
            updateLastCommitId(siteId, lastCommitId);
            updateLastVerifiedGitlogCommitId(siteId, lastCommitId);
            updateLastSyncedGitlogCommitId(siteId, firstCommitId);
            logger.info("Loading configuration for site " + siteId);
            reloadSiteConfiguration(siteId);
        } catch (Exception e) {
            success = false;
            logger.error("Error while creating site: " + siteId + " ID: " + siteId + " as clone from " + "remote repository: " + remoteName + " (" + remoteUrl + "). Rolling back.", e);
            deleteSite(siteId);
            throw new SiteCreationException("Error while creating site: " + siteId + " ID: " + siteId + " as clone from remote repository: " + remoteName + " (" + remoteUrl + "). Rolling back.");
        }
    }
    if (success) {
        // Now that everything is created, we can sync the preview deployer with the new content
        logger.info("Sync all site content to preview for " + siteId);
        try {
            deploymentService.syncAllContentToPreview(siteId, true);
        } catch (ServiceLayerException e) {
            logger.error("Error while syncing site: " + siteId + " ID: " + siteId + " to preview. Site was " + "successfully created otherwise. Ignoring.", e);
            throw new SiteCreationException("Error while syncing site: " + siteId + " 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: " + siteId + " ID: " + siteId + ".");
    }
    logger.info("Finished creating site " + siteId);
}
Also used : InvalidRemoteRepositoryCredentialsException(org.craftercms.studio.api.v1.exception.repository.InvalidRemoteRepositoryCredentialsException) DeployerTargetException(org.craftercms.studio.api.v1.exception.DeployerTargetException) InvalidRemoteRepositoryException(org.craftercms.studio.api.v1.exception.repository.InvalidRemoteRepositoryException) ServiceLayerException(org.craftercms.studio.api.v1.exception.ServiceLayerException) InvalidRemoteUrlException(org.craftercms.studio.api.v1.exception.repository.InvalidRemoteUrlException) 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) ZonedDateTime(java.time.ZonedDateTime) RemoteRepositoryNotFoundException(org.craftercms.studio.api.v1.exception.repository.RemoteRepositoryNotFoundException) SiteFeed(org.craftercms.studio.api.v1.dal.SiteFeed) SiteCreationException(org.craftercms.studio.api.v1.exception.SiteCreationException)

Aggregations

SiteFeed (org.craftercms.studio.api.v1.dal.SiteFeed)58 AuditLog (org.craftercms.studio.api.v2.dal.AuditLog)39 ServiceLayerException (org.craftercms.studio.api.v1.exception.ServiceLayerException)21 SiteNotFoundException (org.craftercms.studio.api.v1.exception.SiteNotFoundException)18 ArrayList (java.util.ArrayList)16 HashMap (java.util.HashMap)15 AuditLogParameter (org.craftercms.studio.api.v2.dal.AuditLogParameter)12 Group (org.craftercms.studio.api.v2.dal.Group)12 HasPermission (org.craftercms.commons.security.permissions.annotations.HasPermission)11 UserNotFoundException (org.craftercms.studio.api.v1.exception.security.UserNotFoundException)11 User (org.craftercms.studio.api.v2.dal.User)10 IOException (java.io.IOException)9 ClusterMember (org.craftercms.studio.api.v2.dal.ClusterMember)9 CryptoException (org.craftercms.commons.crypto.CryptoException)8 ValidateParams (org.craftercms.commons.validation.annotations.param.ValidateParams)8 EntitlementException (org.craftercms.commons.entitlements.exception.EntitlementException)6 ZonedDateTime (java.time.ZonedDateTime)5 AuthenticationSystemException (org.craftercms.studio.api.v1.exception.security.AuthenticationSystemException)5 UserAlreadyExistsException (org.craftercms.studio.api.v1.exception.security.UserAlreadyExistsException)5 SiteService (org.craftercms.studio.api.v1.service.site.SiteService)5