Search in sources :

Example 6 with ResultTO

use of org.craftercms.studio.api.v1.to.ResultTO in project studio by craftercms.

the class WorkflowServiceImpl method approveWithoutDependencies.

/**
 * approve workflows and schedule them as specified in the request
 *
 * @param site
 * @param request
 * @return call result
 * @throws ServiceLayerException
 */
@SuppressWarnings("unchecked")
protected ResultTO approveWithoutDependencies(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 = getSubmittedItemApproveWithoutDependencies(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 == false) {
                    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<String> goLivePaths = new ArrayList<>();
                    Set<String> processedPaths = new HashSet<String>();
                    for (DmDependencyTO goLiveItem : goLiveItems) {
                        resolveSubmittedPaths(site, goLiveItem, goLivePaths, processedPaths);
                    }
                    goLive(site, goLiveItems, approver, mcpContext);
                }
                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>();
                for (DmDependencyTO deletedItem : submittedItems) {
                    deletePaths.add(deletedItem.getUri());
                    ContentItemTO contentItem = contentService.getContentItem(site, deletedItem.getUri());
                    if (contentItem != null) {
                    // nodeRefs.add(nodeRef.getId());
                    }
                }
                doDelete(site, submittedItems, approver);
        }
        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) ContentItemTO(org.craftercms.studio.api.v1.to.ContentItemTO) MultiChannelPublishingContext(org.craftercms.studio.api.v1.service.workflow.context.MultiChannelPublishingContext) JSONObject(net.sf.json.JSONObject) SimpleDateFormat(java.text.SimpleDateFormat) HashSet(java.util.HashSet)

Example 7 with ResultTO

use of org.craftercms.studio.api.v1.to.ResultTO 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 8 with ResultTO

use of org.craftercms.studio.api.v1.to.ResultTO 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 9 with ResultTO

use of org.craftercms.studio.api.v1.to.ResultTO in project studio by craftercms.

the class AssetDmContentProcessor method process.

public void process(PipelineContent content, ResultTO result) throws ContentProcessException {
    String site = content.getProperty(DmConstants.KEY_SITE);
    String user = content.getProperty(DmConstants.KEY_USER);
    String path = content.getProperty(DmConstants.KEY_PATH);
    String fileName = content.getProperty(DmConstants.KEY_FILE_NAME);
    String widthStr = content.getProperty(DmConstants.KEY_WIDTH);
    String heightStr = content.getProperty(DmConstants.KEY_HEIGHT);
    int width = (widthStr != null) ? Integer.parseInt(widthStr) : -1;
    int height = (heightStr != null) ? Integer.parseInt(heightStr) : -1;
    String unlockValue = content.getProperty(DmConstants.KEY_UNLOCK);
    // default is true for unlocking on save
    boolean unlock = (!StringUtils.isEmpty(unlockValue) && unlockValue.equalsIgnoreCase("false")) ? false : true;
    boolean isPreview = ContentFormatUtils.getBooleanValue(content.getProperty(DmConstants.KEY_IS_PREVIEW));
    boolean isSystemAsset = ContentFormatUtils.getBooleanValue(content.getProperty(DmConstants.KEY_SYSTEM_ASSET));
    boolean createFolders = ContentFormatUtils.getBooleanValue(content.getProperty(DmConstants.KEY_CREATE_FOLDERS));
    try {
        ContentAssetInfoTO oldAssetInfo = (ContentAssetInfoTO) result.getItem();
        ContentAssetInfoTO assetInfo = writeContentAsset(content, site, user, path, fileName, content.getContentStream(), width, height, createFolders, isPreview, unlock, isSystemAsset, result);
        if (oldAssetInfo != null) {
            oldAssetInfo.setFileExtension(assetInfo.getFileExtension());
            oldAssetInfo.setFileName(assetInfo.getFileName());
            oldAssetInfo.setSize(assetInfo.getSize());
            oldAssetInfo.setSizeUnit(assetInfo.getSizeUnit());
            result.setItem(oldAssetInfo);
        } else {
            result.setItem(assetInfo);
        }
    } catch (ServiceLayerException e) {
        throw new ContentProcessException("Failed to write " + content.getId() + ", " + e, e);
    } finally {
        content.closeContentStream();
    }
}
Also used : ContentAssetInfoTO(org.craftercms.studio.api.v1.to.ContentAssetInfoTO) ContentProcessException(org.craftercms.studio.api.v1.exception.ContentProcessException) ServiceLayerException(org.craftercms.studio.api.v1.exception.ServiceLayerException)

Example 10 with ResultTO

use of org.craftercms.studio.api.v1.to.ResultTO in project studio by craftercms.

the class AssetDmContentProcessor method writeContentAsset.

/**
 * upload content asset to the given path
 *
 * @param site
 * @param path
 * @param assetName
 * @param in
 *            input stream to read the asset from
 * @param width
 * @param height
 * @param createFolders
 * 				create missing folders?
 * @param isPreview
 * @param unlock
 * 			unlock the content upon update?
 * @return asset information
 * @throws ServiceLayerException
 */
protected ContentAssetInfoTO writeContentAsset(PipelineContent content, String site, String user, String path, String assetName, InputStream in, int width, int height, boolean createFolders, boolean isPreview, boolean unlock, boolean isSystemAsset, ResultTO result) throws ServiceLayerException {
    logger.debug("Writing content asset: [site: " + site + ", path: " + path + ", assetName: " + assetName + ", createFolders: " + createFolders);
    String ext = null;
    int index = assetName.lastIndexOf(".");
    if (index > 0 && (index + 1) < assetName.length()) {
        ext = assetName.substring(index + 1).toUpperCase();
    }
    String contentPath = path + FILE_SEPARATOR + assetName;
    try {
        // look up the path content first
        ContentItemTO parentContentItem = contentService.getContentItem(site, path, 0);
        boolean parentExists = contentService.contentExists(site, path);
        if (!parentExists && createFolders) {
            parentContentItem = createMissingFoldersInPath(site, path, isPreview);
            parentExists = contentService.contentExists(site, path);
        }
        if (parentExists && parentContentItem.isFolder()) {
            boolean exists = contentService.contentExists(site, path + FILE_SEPARATOR + assetName);
            ContentItemTO contentItem = null;
            if (exists) {
                contentItem = contentService.getContentItem(site, path + FILE_SEPARATOR + assetName, 0);
                updateFile(site, contentItem, contentPath, in, user, isPreview, unlock, result);
                content.addProperty(DmConstants.KEY_ACTIVITY_TYPE, OPERATION_UPDATE);
            } else {
                // TODO: define content type
                contentItem = createNewFile(site, parentContentItem, assetName, null, in, user, unlock, result);
                content.addProperty(DmConstants.KEY_ACTIVITY_TYPE, OPERATION_CREATE);
                objectStateService.insertNewEntry(site, contentItem);
            }
            ContentAssetInfoTO assetInfo = new ContentAssetInfoTO();
            assetInfo.setFileName(assetName);
            long sizeInBytes = contentService.getContentSize(site, path + FILE_SEPARATOR + assetName);
            double convertedSize = 0;
            if (sizeInBytes > 0) {
                convertedSize = sizeInBytes / 1024d;
                if (convertedSize >= 1024) {
                    assetInfo.setSizeUnit(FILE_SIZE_MB);
                    assetInfo.setSize(convertedSize / 1024d);
                } else {
                    if (convertedSize > 0 && convertedSize < 1) {
                        assetInfo.setSize(1);
                    } else {
                        assetInfo.setSize(Math.round(convertedSize));
                    }
                    assetInfo.setSizeUnit(FILE_SIZE_KB);
                }
            }
            assetInfo.setFileExtension(ext);
            return assetInfo;
        } else {
            throw new ServiceLayerException(path + " does not exist or not a directory.");
        }
    } finally {
        ContentUtils.release(in);
    }
}
Also used : ContentAssetInfoTO(org.craftercms.studio.api.v1.to.ContentAssetInfoTO) ContentItemTO(org.craftercms.studio.api.v1.to.ContentItemTO) ServiceLayerException(org.craftercms.studio.api.v1.exception.ServiceLayerException)

Aggregations

ServiceLayerException (org.craftercms.studio.api.v1.exception.ServiceLayerException)12 ResultTO (org.craftercms.studio.api.v1.to.ResultTO)8 ContentProcessException (org.craftercms.studio.api.v1.exception.ContentProcessException)6 ContentItemTO (org.craftercms.studio.api.v1.to.ContentItemTO)6 SimpleDateFormat (java.text.SimpleDateFormat)5 ArrayList (java.util.ArrayList)5 JSONArray (net.sf.json.JSONArray)5 JSONException (net.sf.json.JSONException)5 JSONObject (net.sf.json.JSONObject)5 ContentAssetInfoTO (org.craftercms.studio.api.v1.to.ContentAssetInfoTO)5 DmDependencyTO (org.craftercms.studio.api.v1.to.DmDependencyTO)5 SiteFeed (org.craftercms.studio.api.v1.dal.SiteFeed)4 ContentNotFoundException (org.craftercms.studio.api.v1.exception.ContentNotFoundException)4 AuditLog (org.craftercms.studio.api.v2.dal.AuditLog)4 HashSet (java.util.HashSet)3 ValidateParams (org.craftercms.commons.validation.annotations.param.ValidateParams)3 SiteNotFoundException (org.craftercms.studio.api.v1.exception.SiteNotFoundException)3 MultiChannelPublishingContext (org.craftercms.studio.api.v1.service.workflow.context.MultiChannelPublishingContext)3 InputStream (java.io.InputStream)2 HashMap (java.util.HashMap)2