diff --git a/pom.xml b/pom.xml index fdec1f3c..d5a84cfb 100644 --- a/pom.xml +++ b/pom.xml @@ -23,7 +23,7 @@ - 1.6.2-SNAPSHOT + 1.0.0-RC1 17 ${java.version} ${java.version} diff --git a/sdm/src/main/java/com/sap/cds/sdm/handler/applicationservice/SDMCreateAttachmentsHandler.java b/sdm/src/main/java/com/sap/cds/sdm/handler/applicationservice/SDMCreateAttachmentsHandler.java index b1f79db0..469a87ef 100644 --- a/sdm/src/main/java/com/sap/cds/sdm/handler/applicationservice/SDMCreateAttachmentsHandler.java +++ b/sdm/src/main/java/com/sap/cds/sdm/handler/applicationservice/SDMCreateAttachmentsHandler.java @@ -63,7 +63,6 @@ public void processBefore(CdsCreateEventContext context, List data) thr context.getTarget().getQualifiedName(), entityData); logger.info("Attachment compositions present in CDS Model : " + attachmentCompositionDetails); - updateName(context, data, attachmentCompositionDetails); } } @@ -202,38 +201,27 @@ private void processAttachment( List noSDMRoles) throws IOException { String id = (String) attachment.get("ID"); - String fileNameInDB; - fileNameInDB = - dbQuery.getAttachmentForID( - attachmentEntity.get(), - persistenceService, - id); // Fetching the name of the file from DB - String filenameInRequest = - (String) attachment.get("fileName"); // Fetching the name of the file from request + String filenameInRequest = (String) attachment.get("fileName"); + String descriptionInRequest = (String) attachment.get("note"); String objectId = (String) attachment.get("objectId"); + + // Fetch original data from DB and SDM + String fileNameInDB = + dbQuery.getAttachmentForID(attachmentEntity.get(), persistenceService, id); SDMCredentials sdmCredentials = tokenHandler.getSDMCredentials(); - String fileNameInSDM = - sdmService.getObject( - objectId, - sdmCredentials, - context - .getUserInfo() - .isSystemUser()); // Fetch original filename from SDM since it's null in attachments - // table until save; needed to revert UI-modified names on error. + List sdmAttachmentData = + AttachmentsHandlerUtils.fetchAttachmentDataFromSDM( + sdmService, objectId, sdmCredentials, context.getUserInfo().isSystemUser()); + String fileNameInSDM = sdmAttachmentData.get(0); + String descriptionInSDM = sdmAttachmentData.get(1); Map secondaryTypeProperties = - SDMUtils.getSecondaryTypeProperties( - attachmentEntity, - attachment); // Fetching the secondary type properties from the attachment entity - Map propertiesInDB; - propertiesInDB = + SDMUtils.getSecondaryTypeProperties(attachmentEntity, attachment); + Map propertiesInDB = dbQuery.getPropertiesForID( - attachmentEntity.get(), - persistenceService, - id, - secondaryTypeProperties); // Fetching the values of the properties from the DB + attachmentEntity.get(), persistenceService, id, secondaryTypeProperties); - // Get the updated secondary properties + // Prepare document and updated properties Map updatedSecondaryProperties = SDMUtils.getUpdatedSecondaryProperties( attachmentEntity, @@ -241,16 +229,17 @@ private void processAttachment( persistenceService, secondaryTypeProperties, propertiesInDB); - if (SDMUtils.hasRestrictedCharactersInName(filenameInRequest)) { - fileNameWithRestrictedCharacters.add(filenameInRequest); - } - CmisDocument cmisDocument = new CmisDocument(); - cmisDocument.setFileName(filenameInRequest); - cmisDocument.setObjectId(objectId); - if (fileNameInDB == null || !fileNameInDB.equals(filenameInRequest)) { - updatedSecondaryProperties.put("filename", filenameInRequest); - } + CmisDocument cmisDocument = + AttachmentsHandlerUtils.prepareCmisDocument( + filenameInRequest, descriptionInRequest, objectId); + + // Update filename and description properties + AttachmentsHandlerUtils.updateFilenameProperty( + fileNameInDB, filenameInRequest, updatedSecondaryProperties); + AttachmentsHandlerUtils.updateDescriptionProperty( + descriptionInSDM, descriptionInRequest, updatedSecondaryProperties); + // Send update to SDM and handle response try { int responseCode = sdmService.updateAttachments( @@ -259,66 +248,29 @@ private void processAttachment( updatedSecondaryProperties, secondaryPropertiesWithInvalidDefinitions, context.getUserInfo().isSystemUser()); - switch (responseCode) { - case 403: - // SDM Roles for user are missing - noSDMRoles.add(fileNameInSDM); - replacePropertiesInAttachment( - attachment, fileNameInSDM, propertiesInDB, secondaryTypeProperties); - break; - case 404: - filesNotFound.add(filenameInRequest); - replacePropertiesInAttachment( - attachment, filenameInRequest, propertiesInDB, secondaryTypeProperties); - break; - case 200: - case 201: - // Success cases, do nothing - break; - - default: - throw new ServiceException(SDMConstants.SDM_ROLES_ERROR_MESSAGE, null); - } + AttachmentsHandlerUtils.handleSDMUpdateResponse( + responseCode, + attachment, + fileNameInSDM, + filenameInRequest, + propertiesInDB, + secondaryTypeProperties, + descriptionInSDM, + noSDMRoles, + duplicateFileNameList, + filesNotFound); } catch (ServiceException e) { - // This exception is thrown when there are unsupported properties in the request - if (e.getMessage().startsWith(SDMConstants.UNSUPPORTED_PROPERTIES)) { - String unsupportedDetails = - e.getMessage().substring(SDMConstants.UNSUPPORTED_PROPERTIES.length()).trim(); - filesWithUnsupportedProperties.add(unsupportedDetails); - replacePropertiesInAttachment( - attachment, fileNameInSDM, propertiesInDB, secondaryTypeProperties); - } else { - badRequest.put(filenameInRequest, e.getMessage()); - replacePropertiesInAttachment( - attachment, filenameInRequest, propertiesInDB, secondaryTypeProperties); - } - } - } - - private void replacePropertiesInAttachment( - Map attachment, - String fileName, - Map propertiesInDB, - Map secondaryTypeProperties) { - if (propertiesInDB != null) { - for (Map.Entry entry : propertiesInDB.entrySet()) { - String dbKey = entry.getKey(); - String dbValue = entry.getValue(); - - // Find the key in secondaryTypeProperties where the value matches dbKey - String secondaryKey = - secondaryTypeProperties.entrySet().stream() - .filter(e -> e.getValue().equals(dbKey)) - .map(Map.Entry::getKey) - .findFirst() - .orElse(null); - - if (secondaryKey != null) { - attachment.replace(secondaryKey, dbValue); - } - } + AttachmentsHandlerUtils.handleSDMServiceException( + e, + attachment, + fileNameInSDM, + filenameInRequest, + propertiesInDB, + secondaryTypeProperties, + descriptionInSDM, + filesWithUnsupportedProperties, + badRequest); } - attachment.replace("fileName", fileName); } private void handleWarnings( diff --git a/sdm/src/main/java/com/sap/cds/sdm/handler/applicationservice/SDMUpdateAttachmentsHandler.java b/sdm/src/main/java/com/sap/cds/sdm/handler/applicationservice/SDMUpdateAttachmentsHandler.java index 88ddcadb..61585bd7 100644 --- a/sdm/src/main/java/com/sap/cds/sdm/handler/applicationservice/SDMUpdateAttachmentsHandler.java +++ b/sdm/src/main/java/com/sap/cds/sdm/handler/applicationservice/SDMUpdateAttachmentsHandler.java @@ -211,28 +211,36 @@ public void processAttachment( List noSDMRoles) throws IOException { String id = (String) attachment.get("ID"); + String filenameInRequest = (String) attachment.get("fileName"); + String descriptionInRequest = (String) attachment.get("note"); + String objectId = (String) attachment.get("objectId"); + Map secondaryTypeProperties = - SDMUtils.getSecondaryTypeProperties( - attachmentEntity, - attachment); // Fetching the secondary type properties from the attachment entity - String fileNameInDB; - fileNameInDB = dbQuery.getAttachmentForID(attachmentEntity.get(), persistenceService, id); - if (fileNameInDB - == null) { // On entity UPDATE, fetch original attachment name from SDM to revert property - // values if needed. - String objectId = (String) attachment.get("objectId"); - SDMCredentials sdmCredentials = tokenHandler.getSDMCredentials(); - fileNameInDB = - sdmService.getObject(objectId, sdmCredentials, context.getUserInfo().isSystemUser()); + SDMUtils.getSecondaryTypeProperties(attachmentEntity, attachment); + String fileNameInDB = + dbQuery.getAttachmentForID(attachmentEntity.get(), persistenceService, id); + SDMCredentials sdmCredentials = tokenHandler.getSDMCredentials(); + + // Fetch from SDM if not in DB + String descriptionInDB = null; + if (fileNameInDB == null) { + List sdmAttachmentData = + AttachmentsHandlerUtils.fetchAttachmentDataFromSDM( + sdmService, objectId, sdmCredentials, context.getUserInfo().isSystemUser()); + fileNameInDB = sdmAttachmentData.get(0); + descriptionInDB = sdmAttachmentData.get(1); } - Map propertiesInDB; - propertiesInDB = + + Map propertiesInDB = dbQuery.getPropertiesForID( - attachmentEntity.get(), - persistenceService, - id, - secondaryTypeProperties); // Fetching the values of the properties from the DB + attachmentEntity.get(), persistenceService, id, secondaryTypeProperties); + // Extract note (description) from DB if it exists + if (propertiesInDB != null && propertiesInDB.containsKey("note")) { + descriptionInDB = propertiesInDB.get("note"); + } + + // Prepare document and updated properties Map updatedSecondaryProperties = SDMUtils.getUpdatedSecondaryProperties( attachmentEntity, @@ -240,109 +248,52 @@ public void processAttachment( persistenceService, secondaryTypeProperties, propertiesInDB); - String filenameInRequest = (String) attachment.get("fileName"); + CmisDocument cmisDocument = + AttachmentsHandlerUtils.prepareCmisDocument( + filenameInRequest, descriptionInRequest, objectId); - String objectId = (String) attachment.get("objectId"); - if (Boolean.TRUE.equals( - SDMUtils.hasRestrictedCharactersInName( - filenameInRequest))) { // Check if the filename contains restricted characters and stop - // further processing if it does (Request not sent to SDM) - fileNameWithRestrictedCharacters.add(filenameInRequest); - replacePropertiesInAttachment( - attachment, fileNameInDB, propertiesInDB, secondaryTypeProperties); - return; - } - CmisDocument cmisDocument = new CmisDocument(); - cmisDocument.setFileName(filenameInRequest); - cmisDocument.setObjectId(objectId); - if (fileNameInDB == null) { - if (filenameInRequest != null) { - updatedSecondaryProperties.put("filename", filenameInRequest); - } else { - throw new ServiceException("Filename cannot be empty"); - } - } else { - if (filenameInRequest == null) { - throw new ServiceException("Filename cannot be empty"); - } else if (!fileNameInDB.equals(filenameInRequest)) { - updatedSecondaryProperties.put("filename", filenameInRequest); - } - } - if (!updatedSecondaryProperties.isEmpty()) { - try { - int responseCode = - sdmService.updateAttachments( - tokenHandler.getSDMCredentials(), - cmisDocument, - updatedSecondaryProperties, - secondaryPropertiesWithInvalidDefinitions, - context.getUserInfo().isSystemUser()); - switch (responseCode) { - case 403: - // SDM Roles for user are missing - noSDMRoles.add(fileNameInDB); - replacePropertiesInAttachment( - attachment, fileNameInDB, propertiesInDB, secondaryTypeProperties); - break; - case 409: - duplicateFileNameList.add(filenameInRequest); - replacePropertiesInAttachment( - attachment, fileNameInDB, propertiesInDB, secondaryTypeProperties); - break; - case 404: - filesNotFound.add(fileNameInDB); - replacePropertiesInAttachment( - attachment, fileNameInDB, propertiesInDB, secondaryTypeProperties); - break; - case 200: - case 201: - // Success cases, do nothing - break; + // Update filename and description properties + AttachmentsHandlerUtils.updateFilenameProperty( + fileNameInDB, filenameInRequest, updatedSecondaryProperties); + AttachmentsHandlerUtils.updateDescriptionProperty( + descriptionInDB, descriptionInRequest, updatedSecondaryProperties); - default: - throw new ServiceException(SDMConstants.SDM_ROLES_ERROR_MESSAGE, (Object[]) null); - } - } catch (ServiceException e) { - // This exception is thrown when there are unsupported properties in the request - if (e.getMessage().startsWith(SDMConstants.UNSUPPORTED_PROPERTIES)) { - String unsupportedDetails = - e.getMessage().substring(SDMConstants.UNSUPPORTED_PROPERTIES.length()).trim(); - filesWithUnsupportedProperties.add(unsupportedDetails); - replacePropertiesInAttachment( - attachment, fileNameInDB, propertiesInDB, secondaryTypeProperties); - } else { - badRequest.put(fileNameInDB, e.getMessage()); - replacePropertiesInAttachment( - attachment, fileNameInDB, propertiesInDB, secondaryTypeProperties); - } - } + // Send update to SDM only if there are changes + if (updatedSecondaryProperties.isEmpty()) { + return; } - } - - private void replacePropertiesInAttachment( - Map attachment, - String fileName, - Map propertiesInDB, - Map secondaryTypeProperties) { - if (propertiesInDB != null) { - for (Map.Entry entry : propertiesInDB.entrySet()) { - String dbKey = entry.getKey(); - String dbValue = entry.getValue(); - - // Find the key in secondaryTypeProperties where the value matches dbKey - String secondaryKey = - secondaryTypeProperties.entrySet().stream() - .filter(e -> e.getValue().equals(dbKey)) - .map(Map.Entry::getKey) - .findFirst() - .orElse(null); - if (secondaryKey != null) { - attachment.replace(secondaryKey, dbValue); - } - } + try { + int responseCode = + sdmService.updateAttachments( + tokenHandler.getSDMCredentials(), + cmisDocument, + updatedSecondaryProperties, + secondaryPropertiesWithInvalidDefinitions, + context.getUserInfo().isSystemUser()); + AttachmentsHandlerUtils.handleSDMUpdateResponse( + responseCode, + attachment, + fileNameInDB, + filenameInRequest, + propertiesInDB, + secondaryTypeProperties, + descriptionInDB, + noSDMRoles, + duplicateFileNameList, + filesNotFound); + } catch (ServiceException e) { + AttachmentsHandlerUtils.handleSDMServiceException( + e, + attachment, + fileNameInDB, + filenameInRequest, + propertiesInDB, + secondaryTypeProperties, + descriptionInDB, + filesWithUnsupportedProperties, + badRequest); } - attachment.replace("fileName", fileName); } private void handleWarnings( diff --git a/sdm/src/main/java/com/sap/cds/sdm/handler/applicationservice/helper/AttachmentsHandlerUtils.java b/sdm/src/main/java/com/sap/cds/sdm/handler/applicationservice/helper/AttachmentsHandlerUtils.java index a55a3e5f..71fb582d 100644 --- a/sdm/src/main/java/com/sap/cds/sdm/handler/applicationservice/helper/AttachmentsHandlerUtils.java +++ b/sdm/src/main/java/com/sap/cds/sdm/handler/applicationservice/helper/AttachmentsHandlerUtils.java @@ -7,9 +7,14 @@ import com.sap.cds.sdm.constants.SDMConstants; import com.sap.cds.sdm.handler.common.SDMAssociationCascader; import com.sap.cds.sdm.handler.common.SDMAttachmentsReader; +import com.sap.cds.sdm.model.CmisDocument; +import com.sap.cds.sdm.model.SDMCredentials; +import com.sap.cds.sdm.service.SDMService; import com.sap.cds.sdm.utilities.SDMUtils; import com.sap.cds.services.EventContext; +import com.sap.cds.services.ServiceException; import com.sap.cds.services.persistence.PersistenceService; +import java.io.IOException; import java.util.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -587,4 +592,207 @@ public static Boolean validateFileNames( // returning the error message return isError; } + + /** + * Fetches attachment data (filename and description) from SDM. + * + * @param sdmService the SDM service to fetch data from + * @param objectId the object ID in SDM + * @param sdmCredentials the credentials for SDM access + * @param isSystemUser whether the request is from a system user + * @return a list containing [filename, description] + * @throws IOException if there's an error fetching from SDM + */ + public static List fetchAttachmentDataFromSDM( + SDMService sdmService, String objectId, SDMCredentials sdmCredentials, boolean isSystemUser) + throws IOException { + return sdmService.getObject(objectId, sdmCredentials, isSystemUser); + } + + /** + * Updates the filename property in the secondary properties map if needed. + * + * @param fileNameInDB the filename currently in the database + * @param filenameInRequest the filename from the request + * @param updatedSecondaryProperties the map to update + * @throws ServiceException if filename validation fails + */ + public static void updateFilenameProperty( + String fileNameInDB, String filenameInRequest, Map updatedSecondaryProperties) + throws ServiceException { + if (fileNameInDB == null) { + if (filenameInRequest != null) { + updatedSecondaryProperties.put("filename", filenameInRequest); + } else { + throw new ServiceException("Filename cannot be empty"); + } + } else { + if (filenameInRequest == null) { + throw new ServiceException("Filename cannot be empty"); + } else if (!fileNameInDB.equals(filenameInRequest)) { + updatedSecondaryProperties.put("filename", filenameInRequest); + } + } + } + + /** + * Updates the description property in the secondary properties map if needed. + * + * @param descriptionInDB the description currently in the database + * @param descriptionInRequest the description from the request + * @param updatedSecondaryProperties the map to update + */ + public static void updateDescriptionProperty( + String descriptionInDB, + String descriptionInRequest, + Map updatedSecondaryProperties) { + if (descriptionInDB == null) { + if (descriptionInRequest != null) { + updatedSecondaryProperties.put("description", descriptionInRequest); + } + } else { + if (descriptionInRequest != null && !descriptionInDB.equals(descriptionInRequest)) { + updatedSecondaryProperties.put("description", descriptionInRequest); + } + } + } + + /** + * Handles the SDM service response and adds to appropriate error/warning lists. + * + * @param responseCode the HTTP response code from SDM + * @param attachment the attachment map to potentially revert + * @param fileNameInSDM the original filename in SDM + * @param filenameInRequest the filename from the request + * @param propertiesInDB the properties from the database + * @param secondaryTypeProperties the secondary type properties + * @param descriptionInSDM the original description in SDM + * @param noSDMRoles list to add to if 403 error + * @param duplicateFileNameList list to add to if 409 error + * @param filesNotFound list to add to if 404 error + */ + public static void handleSDMUpdateResponse( + int responseCode, + Map attachment, + String fileNameInSDM, + String filenameInRequest, + Map propertiesInDB, + Map secondaryTypeProperties, + String descriptionInSDM, + List noSDMRoles, + List duplicateFileNameList, + List filesNotFound) { + switch (responseCode) { + case 403: + noSDMRoles.add(fileNameInSDM); + revertAttachmentProperties( + attachment, fileNameInSDM, propertiesInDB, secondaryTypeProperties, descriptionInSDM); + break; + case 409: + duplicateFileNameList.add(filenameInRequest); + revertAttachmentProperties( + attachment, fileNameInSDM, propertiesInDB, secondaryTypeProperties, descriptionInSDM); + break; + case 404: + filesNotFound.add(fileNameInSDM); + revertAttachmentProperties( + attachment, fileNameInSDM, propertiesInDB, secondaryTypeProperties, descriptionInSDM); + break; + case 200: + case 201: + // Success cases, do nothing + break; + default: + throw new ServiceException(SDMConstants.SDM_ROLES_ERROR_MESSAGE, (Object[]) null); + } + } + + /** + * Handles exceptions from SDM service calls. + * + * @param e the service exception + * @param attachment the attachment map to potentially revert + * @param fileNameInSDM the original filename in SDM + * @param filenameInRequest the filename from the request + * @param propertiesInDB the properties from the database + * @param secondaryTypeProperties the secondary type properties + * @param descriptionInSDM the original description in SDM + * @param filesWithUnsupportedProperties list to add to if unsupported properties error + * @param badRequest map to add to for other errors + */ + public static void handleSDMServiceException( + ServiceException e, + Map attachment, + String fileNameInSDM, + String filenameInRequest, + Map propertiesInDB, + Map secondaryTypeProperties, + String descriptionInSDM, + List filesWithUnsupportedProperties, + Map badRequest) { + if (e.getMessage().startsWith(SDMConstants.UNSUPPORTED_PROPERTIES)) { + String unsupportedDetails = + e.getMessage().substring(SDMConstants.UNSUPPORTED_PROPERTIES.length()).trim(); + filesWithUnsupportedProperties.add(unsupportedDetails); + revertAttachmentProperties( + attachment, fileNameInSDM, propertiesInDB, secondaryTypeProperties, descriptionInSDM); + } else { + badRequest.put(filenameInRequest, e.getMessage()); + revertAttachmentProperties( + attachment, filenameInRequest, propertiesInDB, secondaryTypeProperties, descriptionInSDM); + } + } + + /** + * Reverts attachment properties to their original values from the database. + * + * @param attachment the attachment map to update + * @param fileName the filename to restore + * @param propertiesInDB the properties from the database + * @param secondaryTypeProperties the secondary type properties mapping + * @param descriptionInSDM the description to restore + */ + public static void revertAttachmentProperties( + Map attachment, + String fileName, + Map propertiesInDB, + Map secondaryTypeProperties, + String descriptionInSDM) { + if (propertiesInDB != null) { + for (Map.Entry entry : propertiesInDB.entrySet()) { + String dbKey = entry.getKey(); + String dbValue = entry.getValue(); + + String secondaryKey = + secondaryTypeProperties.entrySet().stream() + .filter(e -> e.getValue().equals(dbKey)) + .map(Map.Entry::getKey) + .findFirst() + .orElse(null); + + if (secondaryKey != null) { + attachment.replace(secondaryKey, dbValue); + } + } + } + attachment.replace("fileName", fileName); + attachment.replace("note", descriptionInSDM); + } + + /** + * Prepares a CmisDocument with the provided attachment data. + * + * @param filenameInRequest the filename from the request + * @param descriptionInRequest the description from the request + * @param objectId the object ID in SDM + * @return a configured CmisDocument + */ + public static CmisDocument prepareCmisDocument( + String filenameInRequest, String descriptionInRequest, String objectId) { + CmisDocument cmisDocument = new CmisDocument(); + cmisDocument.setFileName(filenameInRequest); + cmisDocument.setDescription(descriptionInRequest); + cmisDocument.setObjectId(objectId); + return cmisDocument; + } } diff --git a/sdm/src/main/java/com/sap/cds/sdm/model/CmisDocument.java b/sdm/src/main/java/com/sap/cds/sdm/model/CmisDocument.java index 88c9d04f..dc6c1994 100644 --- a/sdm/src/main/java/com/sap/cds/sdm/model/CmisDocument.java +++ b/sdm/src/main/java/com/sap/cds/sdm/model/CmisDocument.java @@ -27,4 +27,5 @@ public class CmisDocument { private String url; private String contentId; private String type; + private String description; } diff --git a/sdm/src/main/java/com/sap/cds/sdm/model/CreateDraftEntriesRequest.java b/sdm/src/main/java/com/sap/cds/sdm/model/CreateDraftEntriesRequest.java index 3f8bded5..a6cdc370 100644 --- a/sdm/src/main/java/com/sap/cds/sdm/model/CreateDraftEntriesRequest.java +++ b/sdm/src/main/java/com/sap/cds/sdm/model/CreateDraftEntriesRequest.java @@ -1,13 +1,14 @@ package com.sap.cds.sdm.model; import java.util.List; +import java.util.Map; /** * Parameter object for createDraftEntries method to reduce parameter count and improve code * maintainability. */ public class CreateDraftEntriesRequest { - private final List> attachmentsMetadata; + private final List> attachmentsMetadata; private final List populatedDocuments; private final String parentEntity; private final String compositionName; @@ -15,6 +16,7 @@ public class CreateDraftEntriesRequest { private final String upIdKey; private final String repositoryId; private final String folderId; + private final Map customPropertyValues; private CreateDraftEntriesRequest(Builder builder) { this.attachmentsMetadata = builder.attachmentsMetadata; @@ -25,10 +27,11 @@ private CreateDraftEntriesRequest(Builder builder) { this.upIdKey = builder.upIdKey; this.repositoryId = builder.repositoryId; this.folderId = builder.folderId; + this.customPropertyValues = builder.customPropertyValues; } // Getters - public List> getAttachmentsMetadata() { + public List> getAttachmentsMetadata() { return attachmentsMetadata; } @@ -60,12 +63,16 @@ public String getFolderId() { return folderId; } + public Map getCustomPropertyValues() { + return customPropertyValues; + } + public static Builder builder() { return new Builder(); } public static class Builder { - private List> attachmentsMetadata; + private List> attachmentsMetadata; private List populatedDocuments; private String parentEntity; private String compositionName; @@ -73,8 +80,9 @@ public static class Builder { private String upIdKey; private String repositoryId; private String folderId; + private Map customPropertyValues; - public Builder attachmentsMetadata(List> attachmentsMetadata) { + public Builder attachmentsMetadata(List> attachmentsMetadata) { this.attachmentsMetadata = attachmentsMetadata; return this; } @@ -114,6 +122,11 @@ public Builder folderId(String folderId) { return this; } + public Builder customPropertyValues(Map customPropertyValues) { + this.customPropertyValues = customPropertyValues; + return this; + } + public CreateDraftEntriesRequest build() { return new CreateDraftEntriesRequest(this); } diff --git a/sdm/src/main/java/com/sap/cds/sdm/service/SDMService.java b/sdm/src/main/java/com/sap/cds/sdm/service/SDMService.java index 605309dc..6ab9f602 100644 --- a/sdm/src/main/java/com/sap/cds/sdm/service/SDMService.java +++ b/sdm/src/main/java/com/sap/cds/sdm/service/SDMService.java @@ -10,6 +10,7 @@ import java.io.IOException; import java.util.List; import java.util.Map; +import java.util.Set; import org.json.JSONObject; public interface SDMService { @@ -46,8 +47,8 @@ public int updateAttachments( boolean isSystemUser) throws ServiceException; - public String getObject(String objectId, SDMCredentials sdmCredentials, boolean isSystemUser) - throws IOException; + public List getObject( + String objectId, SDMCredentials sdmCredentials, boolean isSystemUser) throws IOException; public List getSecondaryTypes( String repositoryId, SDMCredentials sdmCredentials, boolean isSystemUser) throws IOException; @@ -59,8 +60,11 @@ public List getValidSecondaryProperties( boolean isSystemUser) throws IOException; - public List copyAttachment( - CmisDocument cmisDocument, SDMCredentials sdmCredentials, boolean isSystemUser) + public Map copyAttachment( + CmisDocument cmisDocument, + SDMCredentials sdmCredentials, + boolean isSystemUser, + Set customPropertiesInSDM) throws IOException; public JSONObject editLink( diff --git a/sdm/src/main/java/com/sap/cds/sdm/service/SDMServiceImpl.java b/sdm/src/main/java/com/sap/cds/sdm/service/SDMServiceImpl.java index f1c76502..9cf18329 100644 --- a/sdm/src/main/java/com/sap/cds/sdm/service/SDMServiceImpl.java +++ b/sdm/src/main/java/com/sap/cds/sdm/service/SDMServiceImpl.java @@ -196,7 +196,6 @@ public int updateAttachments( logger.info("This is a :" + grantType + " flow"); var httpClient = tokenHandler.getHttpClient(binding, connectionPool, null, grantType); String objectId = cmisDocument.getObjectId(); - String fileName = cmisDocument.getFileName(); List secondaryTypes; try { secondaryTypes = @@ -243,7 +242,11 @@ public int updateAttachments( Set keysToRemove = secondaryProperties.keySet().stream() - .filter(key -> !key.equals("filename") && !validSecondaryProperties.contains(key)) + .filter( + key -> + !key.equals("filename") + && !key.equals("description") + && !validSecondaryProperties.contains(key)) .collect( Collectors .toSet()); // Adding the properties which are unsupported to a list so that @@ -284,7 +287,7 @@ public int updateAttachments( secondaryTypes.get(index)); // Adding Secondary Types to the request body } - SDMUtils.prepareSecondaryProperties(updateRequestBody, secondaryProperties, fileName); + SDMUtils.prepareSecondaryProperties(updateRequestBody, secondaryProperties); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); SDMUtils.assembleRequestBodySecondaryTypes( builder, updateRequestBody, objectId); // Adding Secondary Properties to the request body @@ -306,8 +309,8 @@ public int updateAttachments( } @Override - public String getObject(String objectId, SDMCredentials sdmCredentials, boolean isSystemUser) - throws IOException { + public List getObject( + String objectId, SDMCredentials sdmCredentials, boolean isSystemUser) throws IOException { String grantType = isSystemUser ? TECHNICAL_USER_FLOW : NAMED_USER_FLOW; logger.info("This is a :" + grantType + " flow"); var httpClient = tokenHandler.getHttpClient(binding, connectionPool, null, grantType); @@ -328,7 +331,9 @@ public String getObject(String objectId, SDMCredentials sdmCredentials, boolean String responseString = EntityUtils.toString(response.getEntity()); JSONObject jsonObject = new JSONObject(responseString); JSONObject succinctProperties = jsonObject.getJSONObject("succinctProperties"); - return succinctProperties.getString("cmis:name"); + String cmisName = succinctProperties.optString("cmis:name", ""); + String cmisDescription = succinctProperties.optString("cmis:description", ""); + return List.of(cmisName, cmisDescription); } catch (IOException e) { throw new ServiceException(SDMConstants.ATTACHMENT_NOT_FOUND, e); } @@ -393,7 +398,8 @@ public String getFolderId( for (Map attachment : resultList) { if (attachment.get("folderId") != null) { repositoryId = attachment.get("repositoryId").toString(); - // check if folderId exists for the repositoryId if not then make folderId null else + // check if folderId exists for the repositoryId if not then make folderId null + // else // continue if (repoId.equalsIgnoreCase(repositoryId)) { folderId = attachment.get("folderId").toString(); @@ -657,8 +663,11 @@ public List getValidSecondaryProperties( } @Override - public List copyAttachment( - CmisDocument cmisDocument, SDMCredentials sdmCredentials, boolean isSystemUser) + public Map copyAttachment( + CmisDocument cmisDocument, + SDMCredentials sdmCredentials, + boolean isSystemUser, + Set customPropertiesInSDM) throws IOException { String grantType = isSystemUser ? TECHNICAL_USER_FLOW : NAMED_USER_FLOW; @@ -683,14 +692,7 @@ public List copyAttachment( entity != null ? EntityUtils.toString(entity, StandardCharsets.UTF_8) : ""; if (response.getStatusLine().getStatusCode() == 201) { - // Process successful response - - JSONObject jsonObject = new JSONObject(responseBody); - JSONObject props = jsonObject.getJSONObject("succinctProperties"); - String fileName = props.optString("cmis:name"); - String mimeType = props.optString("cmis:contentStreamMimeType"); - String objectId = props.optString("cmis:objectId"); - return List.of(fileName, mimeType, objectId); + return processCopyAttachmentResponse(responseBody, customPropertiesInSDM); } // On error, throw exception with error information @@ -702,4 +704,40 @@ public List copyAttachment( throw new ServiceException(SDMConstants.FAILED_TO_COPY_ATTACHMENT, e); } } + + private Map processCopyAttachmentResponse( + String responseBody, Set customPropertiesInSDM) { + Map resultMap = new HashMap<>(); + JSONObject jsonObject = new JSONObject(responseBody); + JSONObject props = jsonObject.optJSONObject("succinctProperties"); + + // Extract standard CMIS properties + resultMap.put("cmis:name", extractProperty(props, jsonObject, "cmis:name")); + resultMap.put( + "cmis:contentStreamMimeType", + extractProperty(props, jsonObject, "cmis:contentStreamMimeType")); + resultMap.put("cmis:description", extractProperty(props, jsonObject, "cmis:description")); + resultMap.put("cmis:objectId", extractProperty(props, jsonObject, "cmis:objectId")); + + // Extract custom properties from SDM response + extractCustomProperties(props, customPropertiesInSDM, resultMap); + + return resultMap; + } + + private String extractProperty(JSONObject props, JSONObject jsonObject, String propertyName) { + return props != null ? props.optString(propertyName) : jsonObject.optString(propertyName); + } + + private void extractCustomProperties( + JSONObject props, Set customPropertiesInSDM, Map resultMap) { + if (props != null && customPropertiesInSDM != null && !customPropertiesInSDM.isEmpty()) { + for (String customProperty : customPropertiesInSDM) { + if (props.has(customProperty)) { + Object value = props.get(customProperty); + resultMap.put(customProperty, value != null ? value.toString() : ""); + } + } + } + } } diff --git a/sdm/src/main/java/com/sap/cds/sdm/service/handler/SDMCustomServiceHandler.java b/sdm/src/main/java/com/sap/cds/sdm/service/handler/SDMCustomServiceHandler.java index fd8df12a..25fbdd25 100644 --- a/sdm/src/main/java/com/sap/cds/sdm/service/handler/SDMCustomServiceHandler.java +++ b/sdm/src/main/java/com/sap/cds/sdm/service/handler/SDMCustomServiceHandler.java @@ -22,9 +22,12 @@ import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; +import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; import org.json.JSONObject; @ServiceName(value = "*", type = RegisterService.class) @@ -37,16 +40,16 @@ public class SDMCustomServiceHandler { // Result class for copyAttachmentsToSDM method private static class CopyAttachmentsResult { - private final List> attachmentsMetadata; + private final List> attachmentsMetadata; private final List populatedDocuments; public CopyAttachmentsResult( - List> attachmentsMetadata, List populatedDocuments) { + List> attachmentsMetadata, List populatedDocuments) { this.attachmentsMetadata = attachmentsMetadata; this.populatedDocuments = populatedDocuments; } - public List> getAttachmentsMetadata() { + public List> getAttachmentsMetadata() { return attachmentsMetadata; } @@ -72,6 +75,36 @@ public SDMCustomServiceHandler( public void copyAttachments(AttachmentCopyEventContext context) throws IOException { String parentEntity = context.getParentEntity(); String compositionName = context.getCompositionName(); + Optional entity = + context.getModel().findEntity(parentEntity + "." + compositionName); + + Map customPropertyDefinitions = new HashMap<>(); + if (entity.isPresent()) { + CdsEntity cdsEntity = entity.get(); + + // Get columns with @SDM.Attachments.AdditionalProperty annotation and their name values + // Filter out associations - only include actual database columns + customPropertyDefinitions = + cdsEntity + .elements() + .filter( + element -> + element + .findAnnotation(SDMConstants.SDM_ANNOTATION_ADDITIONALPROPERTY_NAME) + .isPresent() + && !element.getType().isAssociation()) + .collect( + Collectors.toMap( + CdsElement::getName, + element -> + element + .findAnnotation(SDMConstants.SDM_ANNOTATION_ADDITIONALPROPERTY_NAME) + .get() + .getValue() + .toString())); + } + + Set customPropertiesInSDM = new HashSet<>(customPropertyDefinitions.values()); String upID = context.getUpId(); String folderName = upID + "__" + compositionName; String repositoryId = SDMConstants.REPOSITORY_ID; @@ -97,9 +130,9 @@ public void copyAttachments(AttachmentCopyEventContext context) throws IOExcepti .folderExists(folderExists) .build(); - CopyAttachmentsResult copyResult = copyAttachmentsToSDM(request); + CopyAttachmentsResult copyResult = copyAttachmentsToSDM(request, customPropertiesInSDM); - List> attachmentsMetadata = copyResult.getAttachmentsMetadata(); + List> attachmentsMetadata = copyResult.getAttachmentsMetadata(); List populatedDocuments = copyResult.getPopulatedDocuments(); String upIdKey = resolveUpIdKey(context, parentEntity, compositionName); @@ -114,9 +147,10 @@ public void copyAttachments(AttachmentCopyEventContext context) throws IOExcepti .upIdKey(upIdKey) .repositoryId(repositoryId) .folderId(folderId) + .customPropertyValues(null) .build(); - createDraftEntries(draftRequest); + createDraftEntries(draftRequest, customPropertyDefinitions); context.setCompleted(); } @@ -137,9 +171,9 @@ private String ensureFolderExists( return folderId; } - private CopyAttachmentsResult copyAttachmentsToSDM(CopyAttachmentsRequest request) - throws IOException { - List> attachmentsMetadata = new ArrayList<>(); + private CopyAttachmentsResult copyAttachmentsToSDM( + CopyAttachmentsRequest request, Set customPropertiesInSDM) throws IOException { + List> attachmentsMetadata = new ArrayList<>(); List populatedDocuments = new ArrayList<>(); for (String objectId : request.getObjectIds()) { @@ -156,9 +190,14 @@ private CopyAttachmentsResult copyAttachmentsToSDM(CopyAttachmentsRequest reques populatedDocuments.add(populatedDocument); try { - attachmentsMetadata.add( + Map attachmentData = sdmService.copyAttachment( - cmisDocument, request.getSdmCredentials(), request.getIsSystemUser())); + cmisDocument, + request.getSdmCredentials(), + request.getIsSystemUser(), + customPropertiesInSDM); + + attachmentsMetadata.add(attachmentData); } catch (ServiceException e) { handleCopyFailure( request.getContext(), @@ -176,15 +215,15 @@ private void handleCopyFailure( AttachmentCopyEventContext context, String folderId, boolean folderExists, - List> attachmentsMetadata, + List> attachmentsMetadata, ServiceException e) throws IOException { if (!folderExists) { sdmService.deleteDocument("deleteTree", folderId, context.getUserInfo().getName()); } else { - for (List attachmentMetadata : attachmentsMetadata) { + for (Map attachmentMetadata : attachmentsMetadata) { sdmService.deleteDocument( - "delete", attachmentMetadata.get(2), context.getUserInfo().getName()); + "delete", attachmentMetadata.get("cmis:objectId"), context.getUserInfo().getName()); } } throw new ServiceException(e.getMessage()); @@ -222,16 +261,18 @@ private String resolveUpIdKey( return null; } - private void createDraftEntries(CreateDraftEntriesRequest request) { + private void createDraftEntries( + CreateDraftEntriesRequest request, Map customPropertyDefinitions) { for (int i = 0; i < request.getAttachmentsMetadata().size(); i++) { - List attachmentMetadata = request.getAttachmentsMetadata().get(i); + Map attachmentMetadata = request.getAttachmentsMetadata().get(i); CmisDocument cmisDocument = request.getPopulatedDocuments().get(i); Map updatedFields = new HashMap<>(); - String fileName = attachmentMetadata.get(0); - String mimeType = attachmentMetadata.get(1); - String newObjectId = attachmentMetadata.get(2); + String fileName = attachmentMetadata.get("cmis:name"); + String mimeType = attachmentMetadata.get("cmis:contentStreamMimeType"); + String description = attachmentMetadata.get("cmis:description"); + String newObjectId = attachmentMetadata.get("cmis:objectId"); updatedFields.put("objectId", newObjectId); updatedFields.put("repositoryId", request.getRepositoryId()); @@ -240,6 +281,7 @@ private void createDraftEntries(CreateDraftEntriesRequest request) { updatedFields.put("mimeType", mimeType); updatedFields.put("type", cmisDocument.getType()); // Individual type for each attachment updatedFields.put("fileName", fileName); + updatedFields.put("note", description); // Map cmis:description to note field updatedFields.put("HasDraftEntity", false); updatedFields.put("HasActiveEntity", false); updatedFields.put("linkUrl", cmisDocument.getUrl()); // Individual linkUrl for each attachment @@ -256,6 +298,19 @@ private void createDraftEntries(CreateDraftEntriesRequest request) { + mimeType); updatedFields.put(request.getUpIdKey(), request.getUpID()); + // Extract custom properties from the attachmentMetadata using customPropertyDefinitions + if (customPropertyDefinitions != null && !customPropertyDefinitions.isEmpty()) { + for (Map.Entry customProperty : customPropertyDefinitions.entrySet()) { + String columnName = customProperty.getKey(); // CDS column name + String sdmPropertyName = customProperty.getValue(); // SDM property name + + if (attachmentMetadata.containsKey(sdmPropertyName)) { + String value = attachmentMetadata.get(sdmPropertyName); + updatedFields.put(columnName, value); + } + } + } + String baseKeyField = request.getUpIdKey() != null ? request.getUpIdKey().replace("up__", "") : "ID"; var insert = diff --git a/sdm/src/main/java/com/sap/cds/sdm/utilities/SDMUtils.java b/sdm/src/main/java/com/sap/cds/sdm/utilities/SDMUtils.java index 339cc3ff..52cd52c9 100644 --- a/sdm/src/main/java/com/sap/cds/sdm/utilities/SDMUtils.java +++ b/sdm/src/main/java/com/sap/cds/sdm/utilities/SDMUtils.java @@ -109,7 +109,7 @@ public static boolean hasRestrictedCharactersInName(String cmisName) { } public static void prepareSecondaryProperties( - Map requestBody, Map secondaryProperties, String fileName) { + Map requestBody, Map secondaryProperties) { Iterator> iterator = secondaryProperties.entrySet().iterator(); int index = 1; @@ -118,6 +118,9 @@ public static void prepareSecondaryProperties( if ("filename".equals(entry.getKey())) { requestBody.put("propertyId[" + index + "]", "cmis:name"); requestBody.put("propertyValue[" + index + "]", entry.getValue()); + } else if ("description".equals(entry.getKey())) { + requestBody.put("propertyId[" + index + "]", "cmis:description"); + requestBody.put("propertyValue[" + index + "]", entry.getValue()); } else { requestBody.put("propertyId[" + index + "]", entry.getKey()); requestBody.put("propertyValue[" + index + "]", entry.getValue()); @@ -190,7 +193,10 @@ public static void extractSecondaryTypeIds(JSONArray jsonArray, List res } } - /* Create a map of property names to their UI titles for intuitive error messages. */ + /* + * Create a map of property names to their UI titles for intuitive error + * messages. + */ public static Map getPropertyTitles( Optional attachmentEntity, Map attachment) { Map titleMap = new HashMap<>(); @@ -215,7 +221,10 @@ public static Map getPropertyTitles( } private static String extractPropertyName(CdsElement element) { - /* Check both old and new SDM annotations to track titles for properties needing error handling. */ + /* + * Check both old and new SDM annotations to track titles for properties needing + * error handling. + */ if (element.findAnnotation(SDMConstants.SDM_ANNOTATION_ADDITIONALPROPERTY_NAME).isPresent()) { return element .findAnnotation(SDMConstants.SDM_ANNOTATION_ADDITIONALPROPERTY_NAME) @@ -235,7 +244,10 @@ private static String extractTitle(CdsElement element) { .orElse(element.getName()); } - /* Identify incorrectly defined properties in the CDS file to group them with unsupported ones where "MCM" is not true. */ + /* + * Identify incorrectly defined properties in the CDS file to group them with + * unsupported ones where "MCM" is not true. + */ public static Map getSecondaryPropertiesWithInvalidDefinition( Optional attachmentEntity, Map attachment) { List keysList = new ArrayList<>(attachment.keySet()); @@ -257,9 +269,10 @@ public static Map getSecondaryPropertiesWithInvalidDefinition( if (titleAnnotation.isPresent()) { title = titleAnnotation.get().getValue().toString(); } else { - title = - element - .getName(); /* This is in case the user has not specified a title for the column in the cds file (which is optional) */ + title = element.getName(); /* + * This is in case the user has not specified a title for the column in the cds + * file (which is optional) + */ } invalidProperties.put(key, title); } @@ -282,18 +295,21 @@ public static Map getSecondaryTypeProperties( } CdsElement element = entity.getElement(key); if (element != null) { - // Checking the SDM Annotation, both the old (outdated method) and the correct method. + // Checking the SDM Annotation, both the old (outdated method) and the correct + // method. Optional> annotation = element.findAnnotation(SDMConstants.SDM_ANNOTATION_ADDITIONALPROPERTY); Optional> nameAnnotation = element.findAnnotation(SDMConstants.SDM_ANNOTATION_ADDITIONALPROPERTY_NAME); if (annotation.isPresent()) { - // If the property was defined using the old method, we will use the actual name of the + // If the property was defined using the old method, we will use the actual name + // of the // property secondaryTypeProperties.put(element.getName(), element.getName()); } if (nameAnnotation.isPresent()) { - // If the property was defined using the new method, we will use the name specified in + // If the property was defined using the new method, we will use the name + // specified in // the annotation secondaryTypeProperties.put( element.getName(), nameAnnotation.get().getValue().toString()); diff --git a/sdm/src/main/resources/cds/com.sap.cds/sdm/attachments.cds b/sdm/src/main/resources/cds/com.sap.cds/sdm/attachments.cds index e26b9bb6..9d131062 100644 --- a/sdm/src/main/resources/cds/com.sap.cds/sdm/attachments.cds +++ b/sdm/src/main/resources/cds/com.sap.cds/sdm/attachments.cds @@ -22,7 +22,7 @@ annotate Attachments with @UI: { {Value: note, @HTML5.CssDefaults: {width: '20%'}} ] } { - note @(title: '{i18n>Note}'); + note @(title: '{i18n>Description}'); fileName @(title: '{i18n>Filename}'); modifiedAt @(odata.etag: null); content diff --git a/sdm/src/test/java/unit/com/sap/cds/sdm/handler/applicationservice/SDMCreateAttachmentsHandlerTest.java b/sdm/src/test/java/unit/com/sap/cds/sdm/handler/applicationservice/SDMCreateAttachmentsHandlerTest.java index 6ec0cc9e..62bbdeac 100644 --- a/sdm/src/test/java/unit/com/sap/cds/sdm/handler/applicationservice/SDMCreateAttachmentsHandlerTest.java +++ b/sdm/src/test/java/unit/com/sap/cds/sdm/handler/applicationservice/SDMCreateAttachmentsHandlerTest.java @@ -515,7 +515,7 @@ public void testUpdateNameWithEmptyFilename() throws IOException { // Mock getObject when(sdmService.getObject("test-object-id", mockCredentials, false)) - .thenReturn("fileInSDM.txt"); + .thenReturn(Arrays.asList("fileInSDM.txt", "descriptionInSDM")); // Mock getSecondaryTypeProperties Map secondaryTypeProperties = new HashMap<>(); diff --git a/sdm/src/test/java/unit/com/sap/cds/sdm/handler/applicationservice/SDMUpdateAttachmentsHandlerTest.java b/sdm/src/test/java/unit/com/sap/cds/sdm/handler/applicationservice/SDMUpdateAttachmentsHandlerTest.java index 60fe5260..54a7392e 100644 --- a/sdm/src/test/java/unit/com/sap/cds/sdm/handler/applicationservice/SDMUpdateAttachmentsHandlerTest.java +++ b/sdm/src/test/java/unit/com/sap/cds/sdm/handler/applicationservice/SDMUpdateAttachmentsHandlerTest.java @@ -93,7 +93,8 @@ public void testProcessBefore() throws IOException { when(context.getModel()).thenReturn(model); when(model.findEntity(anyString())).thenReturn(Optional.of(targetEntity)); - // Mock AttachmentsHandlerUtils.getAttachmentCompositionDetails to return the expected mapping + // Mock AttachmentsHandlerUtils.getAttachmentCompositionDetails to return the + // expected mapping Map> expectedCompositionMapping2 = new HashMap<>(); Map compositionInfo1 = new HashMap<>(); compositionInfo1.put("name", "Name1"); @@ -155,7 +156,8 @@ public void testRenameWithDuplicateFilenames() throws IOException { when(targetEntity.getQualifiedName()).thenReturn("TestEntity"); when(context.getTarget()).thenReturn(targetEntity); - // Make AttachmentsHandlerUtils.fetchAttachments return our attachments for any entity + // Make AttachmentsHandlerUtils.fetchAttachments return our attachments for any + // entity attachmentsMockedStatic .when( () -> @@ -206,93 +208,95 @@ public void testRenameWithDuplicateFilenames() throws IOException { } } - // @Test - // public void testRenameWithUniqueFilenames() throws IOException { - // List data = prepareMockAttachmentData("file1.txt"); - // CdsEntity attachmentDraftEntity = mock(CdsEntity.class); - // Map secondaryProperties = new HashMap<>(); - // CmisDocument document = new CmisDocument(); - // document.setFileName("file1.txt"); - // when(context.getTarget()).thenReturn(attachmentDraftEntity); - // when(context.getModel()).thenReturn(model); - // when(attachmentDraftEntity.getQualifiedName()).thenReturn("some.qualified.Name"); - // when(model.findEntity("some.qualified.Name.attachments")) - // .thenReturn(Optional.of(attachmentDraftEntity)); - // dbQueryMockedStatic = mockStatic(DBQuery.class); - // dbQueryMockedStatic - // .when( - // () -> - // getAttachmentForID( - // any(CdsEntity.class), any(PersistenceService.class), anyString())) - // .thenReturn("file1.txt"); - - // handler.updateName(context, data); - // verify(sdmService, never()) - // .updateAttachments("token", mockCredentials, document, secondaryProperties); - // } - - // @Test - // public void testRenameWithConflictResponseCode() throws IOException { - // // Mock the data structure to simulate the attachments - // List data = new ArrayList<>(); - // Map entity = new HashMap<>(); - // List> attachments = new ArrayList<>(); - // Map attachment = spy(new HashMap<>()); - // Map secondaryProperties = new HashMap<>(); - // secondaryProperties.put("filename", "file1.txt"); - // CmisDocument document = new CmisDocument(); - // document.setFileName("file1.txt"); - // attachment.put("fileName", "file1.txt"); - // attachment.put("url", "objectId"); - // attachment.put("ID", "test-id"); // assuming there's an ID field - // attachments.add(attachment); - // entity.put("attachments", attachments); - // CdsData mockCdsData = mock(CdsData.class); - // when(mockCdsData.get("attachments")).thenReturn(attachments); - // data.add(mockCdsData); - - // CdsEntity attachmentDraftEntity = mock(CdsEntity.class); - // when(context.getTarget()).thenReturn(attachmentDraftEntity); - // when(context.getModel()).thenReturn(model); - // when(attachmentDraftEntity.getQualifiedName()).thenReturn("some.qualified.Name"); - // when(model.findEntity("some.qualified.Name.attachments")) - // .thenReturn(Optional.of(attachmentDraftEntity)); - - // // Mock the authentication context - // when(context.getAuthenticationInfo()).thenReturn(authInfo); - // when(authInfo.as(JwtTokenAuthenticationInfo.class)).thenReturn(jwtTokenInfo); - // when(jwtTokenInfo.getToken()).thenReturn("jwtToken"); - - // // Mock the static TokenHandler - // when(TokenHandler.getSDMCredentials()).thenReturn(mockCredentials); - - // // Mock the SDM service responses - // dbQueryMockedStatic = mockStatic(DBQuery.class); - // dbQueryMockedStatic - // .when( - // () -> - // getAttachmentForID( - // any(CdsEntity.class), any(PersistenceService.class), anyString())) - // .thenReturn("file123.txt"); // Mock a different file name in SDM to trigger renaming - - // when(sdmService.updateAttachments("jwtToken", mockCredentials, document, + // @Test + // public void testRenameWithUniqueFilenames() throws IOException { + // List data = prepareMockAttachmentData("file1.txt"); + // CdsEntity attachmentDraftEntity = mock(CdsEntity.class); + // Map secondaryProperties = new HashMap<>(); + // CmisDocument document = new CmisDocument(); + // document.setFileName("file1.txt"); + // when(context.getTarget()).thenReturn(attachmentDraftEntity); + // when(context.getModel()).thenReturn(model); + // when(attachmentDraftEntity.getQualifiedName()).thenReturn("some.qualified.Name"); + // when(model.findEntity("some.qualified.Name.attachments")) + // .thenReturn(Optional.of(attachmentDraftEntity)); + // dbQueryMockedStatic = mockStatic(DBQuery.class); + // dbQueryMockedStatic + // .when( + // () -> + // getAttachmentForID( + // any(CdsEntity.class), any(PersistenceService.class), anyString())) + // .thenReturn("file1.txt"); + + // handler.updateName(context, data); + // verify(sdmService, never()) + // .updateAttachments("token", mockCredentials, document, secondaryProperties); + // } + + // @Test + // public void testRenameWithConflictResponseCode() throws IOException { + // // Mock the data structure to simulate the attachments + // List data = new ArrayList<>(); + // Map entity = new HashMap<>(); + // List> attachments = new ArrayList<>(); + // Map attachment = spy(new HashMap<>()); + // Map secondaryProperties = new HashMap<>(); + // secondaryProperties.put("filename", "file1.txt"); + // CmisDocument document = new CmisDocument(); + // document.setFileName("file1.txt"); + // attachment.put("fileName", "file1.txt"); + // attachment.put("url", "objectId"); + // attachment.put("ID", "test-id"); // assuming there's an ID field + // attachments.add(attachment); + // entity.put("attachments", attachments); + // CdsData mockCdsData = mock(CdsData.class); + // when(mockCdsData.get("attachments")).thenReturn(attachments); + // data.add(mockCdsData); + + // CdsEntity attachmentDraftEntity = mock(CdsEntity.class); + // when(context.getTarget()).thenReturn(attachmentDraftEntity); + // when(context.getModel()).thenReturn(model); + // when(attachmentDraftEntity.getQualifiedName()).thenReturn("some.qualified.Name"); + // when(model.findEntity("some.qualified.Name.attachments")) + // .thenReturn(Optional.of(attachmentDraftEntity)); + + // // Mock the authentication context + // when(context.getAuthenticationInfo()).thenReturn(authInfo); + // when(authInfo.as(JwtTokenAuthenticationInfo.class)).thenReturn(jwtTokenInfo); + // when(jwtTokenInfo.getToken()).thenReturn("jwtToken"); + + // // Mock the static TokenHandler + // when(TokenHandler.getSDMCredentials()).thenReturn(mockCredentials); + + // // Mock the SDM service responses + // dbQueryMockedStatic = mockStatic(DBQuery.class); + // dbQueryMockedStatic + // .when( + // () -> + // getAttachmentForID( + // any(CdsEntity.class), any(PersistenceService.class), anyString())) + // .thenReturn("file123.txt"); // Mock a different file name in SDM to trigger + // renaming + + // when(sdmService.updateAttachments("jwtToken", mockCredentials, document, // secondaryProperties)) - // .thenReturn(409); // Mock conflict response code + // .thenReturn(409); // Mock conflict response code - // // Mock the returned messages - // when(context.getMessages()).thenReturn(messages); + // // Mock the returned messages + // when(context.getMessages()).thenReturn(messages); - // // Execute the method under test - // handler.updateName(context, data); + // // Execute the method under test + // handler.updateName(context, data); - // // Verify the attachment's file name was attempted to be replaced with "file-sdm.txt" - // verify(attachment).put("fileName", "file1.txt"); + // // Verify the attachment's file name was attempted to be replaced with + // "file-sdm.txt" + // verify(attachment).put("fileName", "file1.txt"); - // // Verify that a warning message was added to the context - // verify(messages, times(1)) - // .warn("The following files could not be renamed as they already + // // Verify that a warning message was added to the context + // verify(messages, times(1)) + // .warn("The following files could not be renamed as they already // exist:\nfile1.txt\n"); - // } + // } @Test public void testRenameWithNoSDMRoles() throws IOException { @@ -311,11 +315,8 @@ public void testRenameWithNoSDMRoles() throws IOException { Map secondaryPropertiesWithInvalidDefinitions = new HashMap<>(); secondaryProperties.put("filename", "file1.txt"); - CmisDocument document = new CmisDocument(); - document.setFileName("file1.txt"); - attachment.put("fileName", "file1.txt"); - attachment.put("url", "objectId"); + attachment.put("objectId", "test-object-id"); attachment.put("ID", "test-id"); attachments.add(attachment); @@ -338,13 +339,18 @@ public void testRenameWithNoSDMRoles() throws IOException { any(CdsEntity.class), any(PersistenceService.class), anyString())) .thenReturn("file123.txt"); - when(sdmService.updateAttachments( - mockCredentials, - document, - secondaryProperties, - secondaryPropertiesWithInvalidDefinitions, - false)) - .thenReturn(403); // Forbidden + when(dbQuery.getPropertiesForID( + any(CdsEntity.class), any(PersistenceService.class), anyString(), any(Map.class))) + .thenReturn(new HashMap<>()); + + doReturn(403) + .when(sdmService) + .updateAttachments( + any(SDMCredentials.class), + any(CmisDocument.class), + any(Map.class), + any(Map.class), + anyBoolean()); // Mock AttachmentsHandlerUtils.fetchAttachments attachmentsMockStatic @@ -354,6 +360,51 @@ public void testRenameWithNoSDMRoles() throws IOException { anyString(), any(Map.class), eq("compositionName"))) .thenReturn(attachments); + // Mock prepareCmisDocument + CmisDocument mockCmisDocument = new CmisDocument(); + mockCmisDocument.setFileName("file1.txt"); + mockCmisDocument.setObjectId("test-object-id"); + attachmentsMockStatic + .when(() -> AttachmentsHandlerUtils.prepareCmisDocument(any(), any(), any())) + .thenReturn(mockCmisDocument); + + // Mock updateFilenameProperty and updateDescriptionProperty + attachmentsMockStatic + .when( + () -> + AttachmentsHandlerUtils.updateFilenameProperty( + anyString(), anyString(), any(Map.class))) + .thenAnswer(invocation -> null); + + attachmentsMockStatic + .when( + () -> + AttachmentsHandlerUtils.updateDescriptionProperty( + anyString(), anyString(), any(Map.class))) + .thenAnswer(invocation -> null); + + // Mock handleSDMUpdateResponse + attachmentsMockStatic + .when( + () -> + AttachmentsHandlerUtils.handleSDMUpdateResponse( + anyInt(), + any(Map.class), + anyString(), + anyString(), + any(Map.class), + any(Map.class), + nullable(String.class), + any(List.class), + any(List.class), + any(List.class))) + .thenAnswer( + invocation -> { + List noSDMRolesList = invocation.getArgument(7); + noSDMRolesList.add("file123.txt"); + return null; + }); + // Mock SDMUtils methods try (MockedStatic sdmUtilsMock = mockStatic(SDMUtils.class)) { sdmUtilsMock @@ -414,122 +465,124 @@ public void testRenameWithNoSDMRoles() throws IOException { } } - // @Test - // public void testRenameWith500Error() throws IOException { - // // Mock the data structure to simulate the attachments - // List data = new ArrayList<>(); - // Map entity = new HashMap<>(); - // List> attachments = new ArrayList<>(); - // Map attachment = spy(new HashMap<>()); - // Map secondaryProperties = new HashMap<>(); - // secondaryProperties.put("filename", "file1.txt"); - // CmisDocument document = new CmisDocument(); - // document.setFileName("file1.txt"); - // attachment.put("fileName", "file1.txt"); - // attachment.put("url", "objectId"); - // attachment.put("ID", "test-id"); // assuming there's an ID field - // attachments.add(attachment); - // entity.put("attachments", attachments); - // CdsData mockCdsData = mock(CdsData.class); - // when(mockCdsData.get("attachments")).thenReturn(attachments); - // data.add(mockCdsData); - - // CdsEntity attachmentDraftEntity = mock(CdsEntity.class); - // when(context.getTarget()).thenReturn(attachmentDraftEntity); - // when(context.getModel()).thenReturn(model); - // when(attachmentDraftEntity.getQualifiedName()).thenReturn("some.qualified.Name"); - // when(model.findEntity("some.qualified.Name.attachments")) - // .thenReturn(Optional.of(attachmentDraftEntity)); - - // // Mock the authentication context - // when(context.getAuthenticationInfo()).thenReturn(authInfo); - // when(authInfo.as(JwtTokenAuthenticationInfo.class)).thenReturn(jwtTokenInfo); - // when(jwtTokenInfo.getToken()).thenReturn("jwtToken"); - - // // Mock the static TokenHandler - // when(TokenHandler.getSDMCredentials()).thenReturn(mockCredentials); - - // // Mock the SDM service responses - // dbQueryMockedStatic = mockStatic(DBQuery.class); - // dbQueryMockedStatic - // .when( - // () -> - // getAttachmentForID( - // any(CdsEntity.class), any(PersistenceService.class), anyString())) - // .thenReturn("file123.txt"); // Mock a different file name in SDM to trigger renaming - - // when(sdmService.updateAttachments("jwtToken", mockCredentials, document, + // @Test + // public void testRenameWith500Error() throws IOException { + // // Mock the data structure to simulate the attachments + // List data = new ArrayList<>(); + // Map entity = new HashMap<>(); + // List> attachments = new ArrayList<>(); + // Map attachment = spy(new HashMap<>()); + // Map secondaryProperties = new HashMap<>(); + // secondaryProperties.put("filename", "file1.txt"); + // CmisDocument document = new CmisDocument(); + // document.setFileName("file1.txt"); + // attachment.put("fileName", "file1.txt"); + // attachment.put("url", "objectId"); + // attachment.put("ID", "test-id"); // assuming there's an ID field + // attachments.add(attachment); + // entity.put("attachments", attachments); + // CdsData mockCdsData = mock(CdsData.class); + // when(mockCdsData.get("attachments")).thenReturn(attachments); + // data.add(mockCdsData); + + // CdsEntity attachmentDraftEntity = mock(CdsEntity.class); + // when(context.getTarget()).thenReturn(attachmentDraftEntity); + // when(context.getModel()).thenReturn(model); + // when(attachmentDraftEntity.getQualifiedName()).thenReturn("some.qualified.Name"); + // when(model.findEntity("some.qualified.Name.attachments")) + // .thenReturn(Optional.of(attachmentDraftEntity)); + + // // Mock the authentication context + // when(context.getAuthenticationInfo()).thenReturn(authInfo); + // when(authInfo.as(JwtTokenAuthenticationInfo.class)).thenReturn(jwtTokenInfo); + // when(jwtTokenInfo.getToken()).thenReturn("jwtToken"); + + // // Mock the static TokenHandler + // when(TokenHandler.getSDMCredentials()).thenReturn(mockCredentials); + + // // Mock the SDM service responses + // dbQueryMockedStatic = mockStatic(DBQuery.class); + // dbQueryMockedStatic + // .when( + // () -> + // getAttachmentForID( + // any(CdsEntity.class), any(PersistenceService.class), anyString())) + // .thenReturn("file123.txt"); // Mock a different file name in SDM to trigger + // renaming + + // when(sdmService.updateAttachments("jwtToken", mockCredentials, document, // secondaryProperties)) - // .thenReturn(500); // Mock conflict response code - - // ServiceException exception = - // assertThrows( - // ServiceException.class, - // () -> { - // handler.updateName(context, data); - // }); - - // assertEquals(SDMConstants.SDM_ROLES_ERROR_MESSAGE, exception.getMessage()); - // } - - // @Test - // public void testRenameWith200ResponseCode() throws IOException { - // // Mock the data structure to simulate the attachments - // List data = new ArrayList<>(); - // Map entity = new HashMap<>(); - // List> attachments = new ArrayList<>(); - // Map attachment = spy(new HashMap<>()); - // Map secondaryProperties = new HashMap<>(); - // secondaryProperties.put("filename", "file1.txt"); - // CmisDocument document = new CmisDocument(); - // document.setFileName("file1.txt"); - // attachment.put("fileName", "file1.txt"); - // attachment.put("url", "objectId"); - // attachment.put("ID", "test-id"); // assuming there's an ID field - // attachments.add(attachment); - // entity.put("attachments", attachments); - // CdsData mockCdsData = mock(CdsData.class); - // when(mockCdsData.get("attachments")).thenReturn(attachments); - // data.add(mockCdsData); - - // CdsEntity attachmentDraftEntity = mock(CdsEntity.class); - // when(context.getTarget()).thenReturn(attachmentDraftEntity); - // when(context.getModel()).thenReturn(model); - // when(attachmentDraftEntity.getQualifiedName()).thenReturn("some.qualified.Name"); - // when(model.findEntity("some.qualified.Name.attachments")) - // .thenReturn(Optional.of(attachmentDraftEntity)); - - // // Mock the authentication context - // when(context.getAuthenticationInfo()).thenReturn(authInfo); - // when(authInfo.as(JwtTokenAuthenticationInfo.class)).thenReturn(jwtTokenInfo); - // when(jwtTokenInfo.getToken()).thenReturn("jwtToken"); - - // // Mock the static TokenHandler - // when(TokenHandler.getSDMCredentials()).thenReturn(mockCredentials); - - // // Mock the SDM service responses - // dbQueryMockedStatic = mockStatic(DBQuery.class); - // dbQueryMockedStatic - // .when( - // () -> - // getAttachmentForID( - // any(CdsEntity.class), any(PersistenceService.class), anyString())) - // .thenReturn("file123.txt"); // Mock a different file name in SDM to trigger renaming - - // when(sdmService.updateAttachments("jwtToken", mockCredentials, document, + // .thenReturn(500); // Mock conflict response code + + // ServiceException exception = + // assertThrows( + // ServiceException.class, + // () -> { + // handler.updateName(context, data); + // }); + + // assertEquals(SDMConstants.SDM_ROLES_ERROR_MESSAGE, exception.getMessage()); + // } + + // @Test + // public void testRenameWith200ResponseCode() throws IOException { + // // Mock the data structure to simulate the attachments + // List data = new ArrayList<>(); + // Map entity = new HashMap<>(); + // List> attachments = new ArrayList<>(); + // Map attachment = spy(new HashMap<>()); + // Map secondaryProperties = new HashMap<>(); + // secondaryProperties.put("filename", "file1.txt"); + // CmisDocument document = new CmisDocument(); + // document.setFileName("file1.txt"); + // attachment.put("fileName", "file1.txt"); + // attachment.put("url", "objectId"); + // attachment.put("ID", "test-id"); // assuming there's an ID field + // attachments.add(attachment); + // entity.put("attachments", attachments); + // CdsData mockCdsData = mock(CdsData.class); + // when(mockCdsData.get("attachments")).thenReturn(attachments); + // data.add(mockCdsData); + + // CdsEntity attachmentDraftEntity = mock(CdsEntity.class); + // when(context.getTarget()).thenReturn(attachmentDraftEntity); + // when(context.getModel()).thenReturn(model); + // when(attachmentDraftEntity.getQualifiedName()).thenReturn("some.qualified.Name"); + // when(model.findEntity("some.qualified.Name.attachments")) + // .thenReturn(Optional.of(attachmentDraftEntity)); + + // // Mock the authentication context + // when(context.getAuthenticationInfo()).thenReturn(authInfo); + // when(authInfo.as(JwtTokenAuthenticationInfo.class)).thenReturn(jwtTokenInfo); + // when(jwtTokenInfo.getToken()).thenReturn("jwtToken"); + + // // Mock the static TokenHandler + // when(TokenHandler.getSDMCredentials()).thenReturn(mockCredentials); + + // // Mock the SDM service responses + // dbQueryMockedStatic = mockStatic(DBQuery.class); + // dbQueryMockedStatic + // .when( + // () -> + // getAttachmentForID( + // any(CdsEntity.class), any(PersistenceService.class), anyString())) + // .thenReturn("file123.txt"); // Mock a different file name in SDM to trigger + // renaming + + // when(sdmService.updateAttachments("jwtToken", mockCredentials, document, // secondaryProperties)) - // .thenReturn(200); + // .thenReturn(200); - // // Execute the method under test - // handler.updateName(context, data); + // // Execute the method under test + // handler.updateName(context, data); - // verify(attachment, never()).replace("fileName", "file-sdm.txt"); + // verify(attachment, never()).replace("fileName", "file-sdm.txt"); - // // Verify that a warning message was added to the context - // verify(messages, times(0)) - // .warn("The following files could not be renamed as they already + // // Verify that a warning message was added to the context + // verify(messages, times(0)) + // .warn("The following files could not be renamed as they already // exist:\nfile1.txt\n"); - // } + // } @Test public void testRenameWithoutFileInSDM() throws IOException { @@ -595,263 +648,267 @@ public void testRenameWithNoAttachments() throws IOException { } } - // @Test - // public void testRenameWithRestrictedFilenames() throws IOException { - // List data = prepareMockAttachmentData("file1.txt", "file2/abc.txt", + // @Test + // public void testRenameWithRestrictedFilenames() throws IOException { + // List data = prepareMockAttachmentData("file1.txt", "file2/abc.txt", // "file3\\abc.txt"); - // Map secondaryProperties = new HashMap<>(); - // secondaryProperties.put("filename", "file1.txt"); - // CmisDocument document = new CmisDocument(); - // document.setFileName("file1.txt"); - // List fileNameWithRestrictedChars = new ArrayList<>(); - // fileNameWithRestrictedChars.add("file2/abc.txt"); - // fileNameWithRestrictedChars.add("file3\\abc.txt"); - - // CdsEntity attachmentDraftEntity = mock(CdsEntity.class); - // when(context.getTarget()).thenReturn(attachmentDraftEntity); - // when(context.getModel()).thenReturn(model); - // when(attachmentDraftEntity.getQualifiedName()).thenReturn("some.qualified.Name"); - // when(model.findEntity("some.qualified.Name.attachments")) - // .thenReturn(Optional.of(attachmentDraftEntity)); - // when(context.getAuthenticationInfo()).thenReturn(authInfo); - // when(authInfo.as(JwtTokenAuthenticationInfo.class)).thenReturn(jwtTokenInfo); - // when(jwtTokenInfo.getToken()).thenReturn("jwtToken"); - - // when(context.getMessages()).thenReturn(messages); - - // sdmUtilsMockedStatic = mockStatic(SDMUtils.class); - // sdmUtilsMockedStatic - // .when(() -> SDMUtils.isRestrictedCharactersInName(anyString())) - // .thenAnswer( - // invocation -> { - // String filename = invocation.getArgument(0); - // return filename.contains("/") || filename.contains("\\"); - // }); - - // when(sdmService.updateAttachments("jwtToken", mockCredentials, document, + // Map secondaryProperties = new HashMap<>(); + // secondaryProperties.put("filename", "file1.txt"); + // CmisDocument document = new CmisDocument(); + // document.setFileName("file1.txt"); + // List fileNameWithRestrictedChars = new ArrayList<>(); + // fileNameWithRestrictedChars.add("file2/abc.txt"); + // fileNameWithRestrictedChars.add("file3\\abc.txt"); + + // CdsEntity attachmentDraftEntity = mock(CdsEntity.class); + // when(context.getTarget()).thenReturn(attachmentDraftEntity); + // when(context.getModel()).thenReturn(model); + // when(attachmentDraftEntity.getQualifiedName()).thenReturn("some.qualified.Name"); + // when(model.findEntity("some.qualified.Name.attachments")) + // .thenReturn(Optional.of(attachmentDraftEntity)); + // when(context.getAuthenticationInfo()).thenReturn(authInfo); + // when(authInfo.as(JwtTokenAuthenticationInfo.class)).thenReturn(jwtTokenInfo); + // when(jwtTokenInfo.getToken()).thenReturn("jwtToken"); + + // when(context.getMessages()).thenReturn(messages); + + // sdmUtilsMockedStatic = mockStatic(SDMUtils.class); + // sdmUtilsMockedStatic + // .when(() -> SDMUtils.isRestrictedCharactersInName(anyString())) + // .thenAnswer( + // invocation -> { + // String filename = invocation.getArgument(0); + // return filename.contains("/") || filename.contains("\\"); + // }); + + // when(sdmService.updateAttachments("jwtToken", mockCredentials, document, // secondaryProperties)) - // .thenReturn(409); // Mock conflict response code - - // dbQueryMockedStatic = mockStatic(DBQuery.class); - // dbQueryMockedStatic - // .when( - // () -> - // getAttachmentForID( - // any(CdsEntity.class), any(PersistenceService.class), anyString())) - // .thenReturn("file-in-sdm.txt"); - - // handler.updateName(context, data); - - // verify(messages, times(1)) - // .warn(SDMConstants.nameConstraintMessage(fileNameWithRestrictedChars, "Rename")); - - // verify(messages, never()).error(anyString()); - // } - - // @Test - // public void testRenameWithValidRestrictedNames() throws IOException { - // List data = new ArrayList<>(); - // Map entity = new HashMap<>(); - // List> attachments = new ArrayList<>(); - // Map attachment = spy(new HashMap<>()); - // List fileNameWithRestrictedChars = new ArrayList<>(); - // fileNameWithRestrictedChars.add("file2/abc.txt"); - // attachment.put("fileName", "file2/abc.txt"); - // attachment.put("objectId", "objectId-123"); - // attachment.put("ID", "id-123"); - // attachments.add(attachment); - // entity.put("attachments", attachments); - // CdsData mockCdsData = mock(CdsData.class); - // when(mockCdsData.get("attachments")).thenReturn(attachments); - // data.add(mockCdsData); - - // CdsEntity attachmentDraftEntity = mock(CdsEntity.class); - // when(context.getTarget()).thenReturn(attachmentDraftEntity); - // when(context.getModel()).thenReturn(model); - // when(attachmentDraftEntity.getQualifiedName()).thenReturn("some.qualified.Name"); - // when(model.findEntity("some.qualified.Name.attachments")) - // .thenReturn(Optional.of(attachmentDraftEntity)); - - // when(context.getMessages()).thenReturn(messages); - - // sdmUtilsMockedStatic = mockStatic(SDMUtils.class); - // sdmUtilsMockedStatic - // .when(() -> SDMUtils.isRestrictedCharactersInName(anyString())) - // .thenAnswer( - // invocation -> { - // String filename = invocation.getArgument(0); - // return filename.contains("/") || filename.contains("\\"); - // }); - - // dbQueryMockedStatic = mockStatic(DBQuery.class); - // dbQueryMockedStatic - // .when( - // () -> - // getAttachmentForID( - // any(CdsEntity.class), any(PersistenceService.class), anyString())) - // .thenReturn("file3/abc.txt"); - - // // Call the method under test - // handler.updateName(context, data); - - // // Verify the attachment's file name was replaced with the name in SDM - // // Now use `put` to verify the change was made instead of `replace` - // verify(attachment).put("fileName", "file2/abc.txt"); - - // // Verify that a warning message is correct - // verify(messages, times(1)) - // .warn( - // String.format( - // SDMConstants.nameConstraintMessage(fileNameWithRestrictedChars, "Rename"))); - // } - - // @Test - // public void testProcessAttachment_PopulateSecondaryTypeProperties() throws IOException { - // // Arrange - // List data = new ArrayList<>(); - // Map entity = new HashMap<>(); - // List> attachments = new ArrayList<>(); - - // // Create a spy for the attachment map - // Map attachment = spy(new HashMap<>()); - - // // Prepare attachment with test data - // attachment.put("ID", "test-id"); - // attachment.put("fileName", "test-file.txt"); - // attachment.put("objectId", "test-object-id"); - - // // Add secondary type properties - // attachment.put("category", "document"); - // attachment.put("description", "Test document"); - - // attachments.add(attachment); - // entity.put("attachments", attachments); - - // // Mock necessary dependencies - // CdsData mockCdsData = mock(CdsData.class); - // data.add(mockCdsData); - - // CdsEntity attachmentDraftEntity = mock(CdsEntity.class); - - // // Prepare lists for restricted characters and duplicate files - // List fileNameWithRestrictedCharacters = new ArrayList<>(); - // List duplicateFileNameList = new ArrayList<>(); - - // // Mock static methods - // try (MockedStatic sdmUtilsMockedStatic = mockStatic(SDMUtils.class); - // MockedStatic dbQueryMockedStatic = mockStatic(DBQuery.class)) { - - // // Setup mocking for secondary type properties - - // when(sdmUtilsMock.getSecondaryTypeProperties( - // eq(Optional.of(attachmentDraftEntity)), eq(attachment))) - // .thenReturn(Arrays.asList("category", "description")); - - // Map propertiesInDB = new HashMap<>(); - - // // Setup mocking for updated secondary properties - // when(sdmUtilsMock.getUpdatedSecondaryProperties( - // eq(Optional.of(attachmentDraftEntity)), - // eq(attachment), - // eq(persistenceService), - // eq(propertiesInDB)) - // .thenReturn(new HashMap<>()); - - // // Mock restricted characters check - // when(sdmUtilsMock.isRestrictedCharactersInName(anyString())).thenReturn(false); - - // // Mock DB query for attachment - - // when(dbQueryMock.getAttachmentForID( - // eq(attachmentDraftEntity), eq(persistenceService), eq("test-id"))) - // .thenReturn("test-file.txt"); - - // handler.processAttachment( - // Optional.of(attachmentDraftEntity), - // context, - // attachment, - // duplicateFileNameList, - // fileNameWithRestrictedCharacters); - - // // Assert - // verify(attachment).get("category"); - // verify(attachment).get("description"); - // } - // } - - // @Test - // public void testProcessAttachment_EmptyFilename_ThrowsServiceException() { - // // Arrange - // List data = new ArrayList<>(); - // Map entity = new HashMap<>(); - // List> attachments = new ArrayList<>(); - - // // Create a spy for the attachment map - // Map attachment = spy(new HashMap<>()); - - // // Prepare attachment with test data - set filename to null - // attachment.put("ID", "test-id"); - // attachment.put("fileName", null); - // attachment.put("objectId", "test-object-id"); - - // attachments.add(attachment); - // entity.put("attachments", attachments); - - // // Mock necessary dependencies - // CdsData mockCdsData = mock(CdsData.class); - // data.add(mockCdsData); - - // CdsEntity attachmentDraftEntity = mock(CdsEntity.class); - - // // Prepare lists for restricted characters and duplicate files - // List fileNameWithRestrictedCharacters = new ArrayList<>(); - // List duplicateFileNameList = new ArrayList<>(); - - // // Mock static methods - // try (MockedStatic sdmUtilsMockedStatic = mockStatic(SDMUtils.class); - // MockedStatic dbQueryMockedStatic = mockStatic(DBQuery.class)) { - - // // Setup mocking for secondary type properties - // when(sdmUtilsMock.getSecondaryTypeProperties( - // eq(Optional.of(attachmentDraftEntity)), eq(attachment))) - // .thenReturn(Collections.emptyList()); - - // // Setup mocking for updated secondary properties - // when(sdmUtilsMock.getUpdatedSecondaryProperties( - // eq(Optional.of(attachmentDraftEntity)), - // eq(attachment), - // eq(persistenceService), - // eq(Collections.emptyList()))) - // .thenReturn(new HashMap<>()); - // // Mock restricted characters check - // when(sdmUtilsMock.isRestrictedCharactersInName(anyString())).thenReturn(false); - - // // Mock DB query for attachment - // when(dbQueryMock.getAttachmentForID( - // eq(attachmentDraftEntity), eq(persistenceService), eq("test-id"))) - // .thenReturn("existing-filename.txt"); - // // Act & Assert - // ServiceException thrown = - // assertThrows( - // ServiceException.class, - // () -> { - // handler.processAttachment( - // Optional.of(attachmentDraftEntity), - // context, - // attachment, - // duplicateFileNameList, - // fileNameWithRestrictedCharacters); - // }); - - // // Verify the exception message - // assertEquals("Filename cannot be empty", thrown.getMessage()); - - // // Verify interactions - // verify(attachment).get("fileName"); - // assertTrue(fileNameWithRestrictedCharacters.isEmpty()); - // assertTrue(duplicateFileNameList.isEmpty()); - // } - // } + // .thenReturn(409); // Mock conflict response code + + // dbQueryMockedStatic = mockStatic(DBQuery.class); + // dbQueryMockedStatic + // .when( + // () -> + // getAttachmentForID( + // any(CdsEntity.class), any(PersistenceService.class), anyString())) + // .thenReturn("file-in-sdm.txt"); + + // handler.updateName(context, data); + + // verify(messages, times(1)) + // .warn(SDMConstants.nameConstraintMessage(fileNameWithRestrictedChars, + // "Rename")); + + // verify(messages, never()).error(anyString()); + // } + + // @Test + // public void testRenameWithValidRestrictedNames() throws IOException { + // List data = new ArrayList<>(); + // Map entity = new HashMap<>(); + // List> attachments = new ArrayList<>(); + // Map attachment = spy(new HashMap<>()); + // List fileNameWithRestrictedChars = new ArrayList<>(); + // fileNameWithRestrictedChars.add("file2/abc.txt"); + // attachment.put("fileName", "file2/abc.txt"); + // attachment.put("objectId", "objectId-123"); + // attachment.put("ID", "id-123"); + // attachments.add(attachment); + // entity.put("attachments", attachments); + // CdsData mockCdsData = mock(CdsData.class); + // when(mockCdsData.get("attachments")).thenReturn(attachments); + // data.add(mockCdsData); + + // CdsEntity attachmentDraftEntity = mock(CdsEntity.class); + // when(context.getTarget()).thenReturn(attachmentDraftEntity); + // when(context.getModel()).thenReturn(model); + // when(attachmentDraftEntity.getQualifiedName()).thenReturn("some.qualified.Name"); + // when(model.findEntity("some.qualified.Name.attachments")) + // .thenReturn(Optional.of(attachmentDraftEntity)); + + // when(context.getMessages()).thenReturn(messages); + + // sdmUtilsMockedStatic = mockStatic(SDMUtils.class); + // sdmUtilsMockedStatic + // .when(() -> SDMUtils.isRestrictedCharactersInName(anyString())) + // .thenAnswer( + // invocation -> { + // String filename = invocation.getArgument(0); + // return filename.contains("/") || filename.contains("\\"); + // }); + + // dbQueryMockedStatic = mockStatic(DBQuery.class); + // dbQueryMockedStatic + // .when( + // () -> + // getAttachmentForID( + // any(CdsEntity.class), any(PersistenceService.class), anyString())) + // .thenReturn("file3/abc.txt"); + + // // Call the method under test + // handler.updateName(context, data); + + // // Verify the attachment's file name was replaced with the name in SDM + // // Now use `put` to verify the change was made instead of `replace` + // verify(attachment).put("fileName", "file2/abc.txt"); + + // // Verify that a warning message is correct + // verify(messages, times(1)) + // .warn( + // String.format( + // SDMConstants.nameConstraintMessage(fileNameWithRestrictedChars, "Rename"))); + // } + + // @Test + // public void testProcessAttachment_PopulateSecondaryTypeProperties() throws + // IOException { + // // Arrange + // List data = new ArrayList<>(); + // Map entity = new HashMap<>(); + // List> attachments = new ArrayList<>(); + + // // Create a spy for the attachment map + // Map attachment = spy(new HashMap<>()); + + // // Prepare attachment with test data + // attachment.put("ID", "test-id"); + // attachment.put("fileName", "test-file.txt"); + // attachment.put("objectId", "test-object-id"); + + // // Add secondary type properties + // attachment.put("category", "document"); + // attachment.put("description", "Test document"); + + // attachments.add(attachment); + // entity.put("attachments", attachments); + + // // Mock necessary dependencies + // CdsData mockCdsData = mock(CdsData.class); + // data.add(mockCdsData); + + // CdsEntity attachmentDraftEntity = mock(CdsEntity.class); + + // // Prepare lists for restricted characters and duplicate files + // List fileNameWithRestrictedCharacters = new ArrayList<>(); + // List duplicateFileNameList = new ArrayList<>(); + + // // Mock static methods + // try (MockedStatic sdmUtilsMockedStatic = + // mockStatic(SDMUtils.class); + // MockedStatic dbQueryMockedStatic = mockStatic(DBQuery.class)) { + + // // Setup mocking for secondary type properties + + // when(sdmUtilsMock.getSecondaryTypeProperties( + // eq(Optional.of(attachmentDraftEntity)), eq(attachment))) + // .thenReturn(Arrays.asList("category", "description")); + + // Map propertiesInDB = new HashMap<>(); + + // // Setup mocking for updated secondary properties + // when(sdmUtilsMock.getUpdatedSecondaryProperties( + // eq(Optional.of(attachmentDraftEntity)), + // eq(attachment), + // eq(persistenceService), + // eq(propertiesInDB)) + // .thenReturn(new HashMap<>()); + + // // Mock restricted characters check + // when(sdmUtilsMock.isRestrictedCharactersInName(anyString())).thenReturn(false); + + // // Mock DB query for attachment + + // when(dbQueryMock.getAttachmentForID( + // eq(attachmentDraftEntity), eq(persistenceService), eq("test-id"))) + // .thenReturn("test-file.txt"); + + // handler.processAttachment( + // Optional.of(attachmentDraftEntity), + // context, + // attachment, + // duplicateFileNameList, + // fileNameWithRestrictedCharacters); + + // // Assert + // verify(attachment).get("category"); + // verify(attachment).get("description"); + // } + // } + + // @Test + // public void testProcessAttachment_EmptyFilename_ThrowsServiceException() { + // // Arrange + // List data = new ArrayList<>(); + // Map entity = new HashMap<>(); + // List> attachments = new ArrayList<>(); + + // // Create a spy for the attachment map + // Map attachment = spy(new HashMap<>()); + + // // Prepare attachment with test data - set filename to null + // attachment.put("ID", "test-id"); + // attachment.put("fileName", null); + // attachment.put("objectId", "test-object-id"); + + // attachments.add(attachment); + // entity.put("attachments", attachments); + + // // Mock necessary dependencies + // CdsData mockCdsData = mock(CdsData.class); + // data.add(mockCdsData); + + // CdsEntity attachmentDraftEntity = mock(CdsEntity.class); + + // // Prepare lists for restricted characters and duplicate files + // List fileNameWithRestrictedCharacters = new ArrayList<>(); + // List duplicateFileNameList = new ArrayList<>(); + + // // Mock static methods + // try (MockedStatic sdmUtilsMockedStatic = + // mockStatic(SDMUtils.class); + // MockedStatic dbQueryMockedStatic = mockStatic(DBQuery.class)) { + + // // Setup mocking for secondary type properties + // when(sdmUtilsMock.getSecondaryTypeProperties( + // eq(Optional.of(attachmentDraftEntity)), eq(attachment))) + // .thenReturn(Collections.emptyList()); + + // // Setup mocking for updated secondary properties + // when(sdmUtilsMock.getUpdatedSecondaryProperties( + // eq(Optional.of(attachmentDraftEntity)), + // eq(attachment), + // eq(persistenceService), + // eq(Collections.emptyList()))) + // .thenReturn(new HashMap<>()); + // // Mock restricted characters check + // when(sdmUtilsMock.isRestrictedCharactersInName(anyString())).thenReturn(false); + + // // Mock DB query for attachment + // when(dbQueryMock.getAttachmentForID( + // eq(attachmentDraftEntity), eq(persistenceService), eq("test-id"))) + // .thenReturn("existing-filename.txt"); + // // Act & Assert + // ServiceException thrown = + // assertThrows( + // ServiceException.class, + // () -> { + // handler.processAttachment( + // Optional.of(attachmentDraftEntity), + // context, + // attachment, + // duplicateFileNameList, + // fileNameWithRestrictedCharacters); + // }); + + // // Verify the exception message + // assertEquals("Filename cannot be empty", thrown.getMessage()); + + // // Verify interactions + // verify(attachment).get("fileName"); + // assertTrue(fileNameWithRestrictedCharacters.isEmpty()); + // assertTrue(duplicateFileNameList.isEmpty()); + // } + // } private List prepareMockAttachmentData(String... fileNames) { List data = new ArrayList<>(); diff --git a/sdm/src/test/java/unit/com/sap/cds/sdm/service/SDMServiceImplTest.java b/sdm/src/test/java/unit/com/sap/cds/sdm/service/SDMServiceImplTest.java index 1f60e33a..ddab5535 100644 --- a/sdm/src/test/java/unit/com/sap/cds/sdm/service/SDMServiceImplTest.java +++ b/sdm/src/test/java/unit/com/sap/cds/sdm/service/SDMServiceImplTest.java @@ -638,7 +638,6 @@ public void testCreateDocumentFailDuplicate() throws IOException { public void testCreateDocumentFailVirus() throws IOException { String mockResponseBody = "{\"succinctProperties\": {\"cmis:objectId\": \"objectId\"}, \"message\": \"Malware Service Exception: Virus found in the file!\"}"; - CmisDocument cmisDocument = new CmisDocument(); cmisDocument.setFileName("sample.pdf"); cmisDocument.setAttachmentId("attachmentId"); @@ -1419,8 +1418,8 @@ public void testGetObject_Success() throws IOException { InputStream inputStream = new ByteArrayInputStream(mockResponseBody.getBytes()); when(entity.getContent()).thenReturn(inputStream); - String objectName = sdmServiceImpl.getObject(objectId, sdmCredentials, false); - assertEquals("desiredObjectName", objectName); + List objectInfo = sdmServiceImpl.getObject(objectId, sdmCredentials, false); + assertEquals("desiredObjectName", objectInfo.get(0)); } @Test @@ -1439,8 +1438,8 @@ public void testGetObject_Failure() throws IOException { InputStream inputStream = new ByteArrayInputStream("".getBytes()); when(entity.getContent()).thenReturn(inputStream); - String objectName = sdmServiceImpl.getObject(objectId, sdmCredentials, false); - assertNull(objectName); + List objectInfo = sdmServiceImpl.getObject(objectId, sdmCredentials, false); + assertNull(objectInfo); } @Test @@ -1527,9 +1526,12 @@ public void testCopyAttachment_Success() throws Exception { .thenReturn(responseBody); SDMServiceImpl sdmServiceImpl = new SDMServiceImpl(binding, connectionPool, tokenHandler); - List result = sdmServiceImpl.copyAttachment(cmisDocument, sdmCredentials, true); + Map result = + sdmServiceImpl.copyAttachment(cmisDocument, sdmCredentials, true, new HashSet<>()); - assertEquals(List.of("file1.pdf", "application/pdf", "obj123"), result); + assertEquals("file1.pdf", result.get("cmis:name")); + assertEquals("application/pdf", result.get("cmis:contentStreamMimeType")); + assertEquals("obj123", result.get("cmis:objectId")); } } @@ -1565,7 +1567,9 @@ public void testCopyAttachment_ErrorResponse() throws Exception { ServiceException ex = assertThrows( ServiceException.class, - () -> sdmServiceImpl.copyAttachment(cmisDocument, sdmCredentials, true)); + () -> + sdmServiceImpl.copyAttachment( + cmisDocument, sdmCredentials, true, new HashSet<>())); assertTrue(ex.getMessage().contains("SomeException")); assertTrue(ex.getMessage().contains("Something went wrong")); } @@ -1588,7 +1592,8 @@ public void testCopyAttachment_IOException() throws Exception { ServiceException ex = assertThrows( ServiceException.class, - () -> sdmServiceImpl.copyAttachment(cmisDocument, sdmCredentials, true)); + () -> + sdmServiceImpl.copyAttachment(cmisDocument, sdmCredentials, true, new HashSet<>())); assertTrue(ex.getMessage().contains(SDMConstants.FAILED_TO_COPY_ATTACHMENT)); assertTrue(ex.getCause() instanceof IOException); } diff --git a/sdm/src/test/java/unit/com/sap/cds/sdm/service/handler/SDMCustomServiceHandlerTest.java b/sdm/src/test/java/unit/com/sap/cds/sdm/service/handler/SDMCustomServiceHandlerTest.java index 9ca075e2..0c4336ef 100644 --- a/sdm/src/test/java/unit/com/sap/cds/sdm/service/handler/SDMCustomServiceHandlerTest.java +++ b/sdm/src/test/java/unit/com/sap/cds/sdm/service/handler/SDMCustomServiceHandlerTest.java @@ -25,7 +25,9 @@ import com.sap.cds.services.request.UserInfo; import com.sap.cds.services.runtime.CdsRuntime; import java.io.IOException; +import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.Optional; import java.util.stream.Stream; import org.junit.jupiter.api.BeforeEach; @@ -77,8 +79,12 @@ void testCopyAttachments_HappyPath() throws IOException { .thenReturn(FOLDER_ID); // Mock attachment copy - when(sdmService.copyAttachment(any(), any(SDMCredentials.class), any(Boolean.class))) - .thenReturn(List.of("fileName.url", "application/internet-shortcut", OBJECT_ID)); + Map attachmentData = new HashMap<>(); + attachmentData.put("cmis:name", "fileName.url"); + attachmentData.put("cmis:contentStreamMimeType", "application/internet-shortcut"); + attachmentData.put("cmis:objectId", OBJECT_ID); + when(sdmService.copyAttachment(any(), any(SDMCredentials.class), any(Boolean.class), any())) + .thenReturn(attachmentData); CmisDocument cmisDocument = new CmisDocument(); cmisDocument.setType("sap-icon://internet-browser"); cmisDocument.setUrl("https://example.com"); @@ -93,7 +99,7 @@ void testCopyAttachments_HappyPath() throws IOException { // Assert verify(sdmService, times(1)) - .copyAttachment(any(), any(SDMCredentials.class), any(Boolean.class)); + .copyAttachment(any(), any(SDMCredentials.class), any(Boolean.class), any()); verify(draftService, times(1)).newDraft(any()); verify(context, times(1)).setCompleted(); } @@ -110,8 +116,12 @@ void testCopyAttachments_HappyPathNonLink() throws IOException { .thenReturn(FOLDER_ID); // Mock attachment copy - when(sdmService.copyAttachment(any(), any(SDMCredentials.class), any(Boolean.class))) - .thenReturn(List.of("fileName", "mimeType", OBJECT_ID)); + Map attachmentData = new HashMap<>(); + attachmentData.put("cmis:name", "fileName"); + attachmentData.put("cmis:contentStreamMimeType", "mimeType"); + attachmentData.put("cmis:objectId", OBJECT_ID); + when(sdmService.copyAttachment(any(), any(SDMCredentials.class), any(Boolean.class), any())) + .thenReturn(attachmentData); CmisDocument cmisDocument = new CmisDocument(); cmisDocument.setType("sap-icon://document"); when(dbQuery.getAttachmentForObjectID(any(), any(), any())).thenReturn(cmisDocument); @@ -125,7 +135,7 @@ void testCopyAttachments_HappyPathNonLink() throws IOException { // Assert verify(sdmService, times(1)) - .copyAttachment(any(), any(SDMCredentials.class), any(Boolean.class)); + .copyAttachment(any(), any(SDMCredentials.class), any(Boolean.class), any()); verify(draftService, times(1)).newDraft(any()); verify(context, times(1)).setCompleted(); } @@ -147,8 +157,12 @@ void testCopyAttachments_FolderDoesNotExist() throws IOException { .thenReturn("{\"succinctProperties\": {\"cmis:objectId\": \"" + FOLDER_ID + "\"}}"); // Mock attachment copy - when(sdmService.copyAttachment(any(), any(SDMCredentials.class), any(Boolean.class))) - .thenReturn(List.of("fileName", "mimeType", OBJECT_ID)); + Map attachmentData = new HashMap<>(); + attachmentData.put("cmis:name", "fileName"); + attachmentData.put("cmis:contentStreamMimeType", "mimeType"); + attachmentData.put("cmis:objectId", OBJECT_ID); + when(sdmService.copyAttachment(any(), any(SDMCredentials.class), any(Boolean.class), any())) + .thenReturn(attachmentData); CmisDocument cmisDocument = new CmisDocument(); cmisDocument.setType("sap-icon://internet-browser"); cmisDocument.setUrl("https://example.com"); @@ -167,7 +181,7 @@ void testCopyAttachments_FolderDoesNotExist() throws IOException { .createFolder( any(String.class), any(String.class), any(SDMCredentials.class), any(Boolean.class)); verify(sdmService, times(1)) - .copyAttachment(any(), any(SDMCredentials.class), any(Boolean.class)); + .copyAttachment(any(), any(SDMCredentials.class), any(Boolean.class), any()); } @Test @@ -182,8 +196,12 @@ void testCopyAttachments_AttachmentCopyFails() throws IOException { .thenReturn(FOLDER_ID); // Mock attachment copy failure - when(sdmService.copyAttachment(any(), any(SDMCredentials.class), any(Boolean.class))) - .thenReturn(List.of("fileName", "mimeType", OBJECT_ID)) + Map attachmentData = new HashMap<>(); + attachmentData.put("cmis:name", "fileName"); + attachmentData.put("cmis:contentStreamMimeType", "mimeType"); + attachmentData.put("cmis:objectId", OBJECT_ID); + when(sdmService.copyAttachment(any(), any(SDMCredentials.class), any(Boolean.class), any())) + .thenReturn(attachmentData) .thenThrow(new ServiceException("Copy failed")); CmisDocument cmisDocument = new CmisDocument(); cmisDocument.setType("sap-icon://internet-browser"); @@ -224,7 +242,7 @@ void testCopyAttachments_AttachmentCopyFails_FolderDoesNotExist() throws IOExcep .thenReturn("{\"succinctProperties\": {\"cmis:objectId\": \"" + FOLDER_ID + "\"}}"); // Simulate copyAttachment throws ServiceException on first call - when(sdmService.copyAttachment(any(), any(), anyBoolean())) + when(sdmService.copyAttachment(any(), any(), anyBoolean(), any())) .thenThrow(new ServiceException("Copy failed")); AttachmentCopyEventContext context = createMockContext(); @@ -259,8 +277,12 @@ void testCopyAttachments_AttachmentCopyFails_FolderExists_AttachmentsDeleted() when(sdmService.getFolderIdByPath(any(), any(), any(), anyBoolean())).thenReturn(FOLDER_ID); // First call succeeds, second call fails - when(sdmService.copyAttachment(any(), any(), anyBoolean())) - .thenReturn(List.of("fileName", "mimeType", OBJECT_ID)) + Map attachmentData = new HashMap<>(); + attachmentData.put("cmis:name", "fileName"); + attachmentData.put("cmis:contentStreamMimeType", "mimeType"); + attachmentData.put("cmis:objectId", OBJECT_ID); + when(sdmService.copyAttachment(any(), any(), anyBoolean(), any())) + .thenReturn(attachmentData) .thenThrow(new ServiceException("Copy failed")); AttachmentCopyEventContext context = createMockContext(); diff --git a/sdm/src/test/java/unit/com/sap/cds/sdm/utilities/SDMUtilsTest.java b/sdm/src/test/java/unit/com/sap/cds/sdm/utilities/SDMUtilsTest.java index 6d839397..dc8d11ba 100644 --- a/sdm/src/test/java/unit/com/sap/cds/sdm/utilities/SDMUtilsTest.java +++ b/sdm/src/test/java/unit/com/sap/cds/sdm/utilities/SDMUtilsTest.java @@ -155,7 +155,7 @@ public void prepareSecondaryPropertiesTest_withFilenameKey() { Map secondaryProperties = new HashMap<>(); secondaryProperties.put("filename", "myfile.txt"); - SDMUtils.prepareSecondaryProperties(requestBody, secondaryProperties, "myfile.txt"); + SDMUtils.prepareSecondaryProperties(requestBody, secondaryProperties); assertEquals("cmis:name", requestBody.get("propertyId[1]")); assertEquals("myfile.txt", requestBody.get("propertyValue[1]")); @@ -168,7 +168,7 @@ public void testPrepareSecondaryProperties_withOtherKeys() { secondaryProperties.put("author", "test user"); secondaryProperties.put("subject", "JUnit Testing"); - SDMUtils.prepareSecondaryProperties(requestBody, secondaryProperties, "testfile.txt"); + SDMUtils.prepareSecondaryProperties(requestBody, secondaryProperties); assertEquals("author", requestBody.get("propertyId[1]")); assertEquals("test user", requestBody.get("propertyValue[1]")); @@ -181,7 +181,7 @@ public void testPrepareSecondaryProperties_emptySecondaryProperties() { Map requestBody = new HashMap<>(); Map secondaryProperties = new HashMap<>(); - SDMUtils.prepareSecondaryProperties(requestBody, secondaryProperties, "emptyfile.txt"); + SDMUtils.prepareSecondaryProperties(requestBody, secondaryProperties); assertTrue(requestBody.isEmpty()); } @@ -238,23 +238,26 @@ public void testCheckMCM_withMissingPropertyDefinitions() throws IOException { // @Test // public void testCheckMCM_withPropertyDefinitionNull() throws IOException { - // // Create a mock response entity with valid propertyDefinitions but not part of the table - // String jsonResponse = "{\"propertyDefinitions\": null}"; - // HttpEntity responseEntity = new StringEntity(jsonResponse, StandardCharsets.UTF_8); + // // Create a mock response entity with valid propertyDefinitions but not part + // of the table + // String jsonResponse = "{\"propertyDefinitions\": null}"; + // HttpEntity responseEntity = new StringEntity(jsonResponse, + // StandardCharsets.UTF_8); - // List secondaryPropertyIds = new ArrayList<>(); + // List secondaryPropertyIds = new ArrayList<>(); - // // Call the method to test - // Boolean result = SDMUtils.checkMCM(responseEntity, secondaryPropertyIds); + // // Call the method to test + // Boolean result = SDMUtils.checkMCM(responseEntity, secondaryPropertyIds); - // // Assertions - // assertFalse(result); - // assertTrue(secondaryPropertyIds.isEmpty()); + // // Assertions + // assertFalse(result); + // assertTrue(secondaryPropertyIds.isEmpty()); // } @Test public void testCheckMCM_withPropertyDefinitionsNotPartOfTable() throws IOException { - // Create a mock response entity with valid propertyDefinitions but not part of the table + // Create a mock response entity with valid propertyDefinitions but not part of + // the table String jsonResponse = "{\"propertyDefinitions\": {" + "\"propertyA\": {\"mcm:miscellaneous\": {\"isPartOfTable\": \"false\"}}" @@ -274,7 +277,8 @@ public void testCheckMCM_withPropertyDefinitionsNotPartOfTable() throws IOExcept @Test public void testCheckMCM_withMCMMiscellanousNotPartOfTable() throws IOException { - // Create a mock response entity with valid propertyDefinitions but not part of the table + // Create a mock response entity with valid propertyDefinitions but not part of + // the table String jsonResponse = "{\"propertyDefinitions\": {" + "\"propertyA\": {\"mcm:miscellaneous\": {\"isQueryableInUi\": \"false\"}}" @@ -372,164 +376,168 @@ public void testExtractSecondaryTypeIds_withEmptyJSONArray() { // @Test // public void testGetUpdatedSecondaryProperties_withModifiedValues() { - // // Mock the necessary components - // CdsEntity mockEntity = mock(CdsEntity.class); - // PersistenceService mockPersistenceService = mock(PersistenceService.class); - - // // Prepare attachment and secondaryTypeProperties - // Map attachment = new HashMap<>(); - // attachment.put("ID", "123"); - // attachment.put("property1", "newValue1"); - // attachment.put("property2", "newValue2"); - - // List secondaryTypeProperties = Arrays.asList("property1", "property2"); - - // // Mock DBQuery class behavior - // List propertiesInDB = Arrays.asList("oldValue1", "newValue2"); - // mockedDbQuery - // .when( - // () -> - // DBQuery.getpropertiesForID( - // mockEntity, mockPersistenceService, "123", secondaryTypeProperties)) - // .thenReturn(propertiesInDB); - - // Map result = - // SDMUtils.getUpdatedSecondaryProperties( - // Optional.of(mockEntity), attachment, mockPersistenceService, + // // Mock the necessary components + // CdsEntity mockEntity = mock(CdsEntity.class); + // PersistenceService mockPersistenceService = mock(PersistenceService.class); + + // // Prepare attachment and secondaryTypeProperties + // Map attachment = new HashMap<>(); + // attachment.put("ID", "123"); + // attachment.put("property1", "newValue1"); + // attachment.put("property2", "newValue2"); + + // List secondaryTypeProperties = Arrays.asList("property1", + // "property2"); + + // // Mock DBQuery class behavior + // List propertiesInDB = Arrays.asList("oldValue1", "newValue2"); + // mockedDbQuery + // .when( + // () -> + // DBQuery.getpropertiesForID( + // mockEntity, mockPersistenceService, "123", secondaryTypeProperties)) + // .thenReturn(propertiesInDB); + + // Map result = + // SDMUtils.getUpdatedSecondaryProperties( + // Optional.of(mockEntity), attachment, mockPersistenceService, // secondaryTypeProperties); - // assertEquals(1, result.size()); - // assertEquals("newValue1", result.get("property1")); - // assertNull(result.get("property2")); + // assertEquals(1, result.size()); + // assertEquals("newValue1", result.get("property1")); + // assertNull(result.get("property2")); // } // @Test - // public void testGetUpdatedSecondaryProperties_withSecondaryTypePropertiesNull() { - // // Mock the necessary components - // CdsEntity mockEntity = mock(CdsEntity.class); - // PersistenceService mockPersistenceService = mock(PersistenceService.class); - - // // Prepare attachment and secondaryTypeProperties - // Map attachment = new HashMap<>(); - // attachment.put("ID", "123"); - // attachment.put("property1", "newValue1"); - // attachment.put("property2", "newValue2"); - - // List secondaryTypeProperties = new ArrayList<>(); - - // // Mock DBQuery class behavior - // List propertiesInDB = new ArrayList<>(); - // mockedDbQuery - // .when( - // () -> - // DBQuery.getpropertiesForID( - // mockEntity, mockPersistenceService, "123", secondaryTypeProperties)) - // .thenReturn(propertiesInDB); - - // Map result = - // SDMUtils.getUpdatedSecondaryProperties( - // Optional.of(mockEntity), attachment, mockPersistenceService, + // public void + // testGetUpdatedSecondaryProperties_withSecondaryTypePropertiesNull() { + // // Mock the necessary components + // CdsEntity mockEntity = mock(CdsEntity.class); + // PersistenceService mockPersistenceService = mock(PersistenceService.class); + + // // Prepare attachment and secondaryTypeProperties + // Map attachment = new HashMap<>(); + // attachment.put("ID", "123"); + // attachment.put("property1", "newValue1"); + // attachment.put("property2", "newValue2"); + + // List secondaryTypeProperties = new ArrayList<>(); + + // // Mock DBQuery class behavior + // List propertiesInDB = new ArrayList<>(); + // mockedDbQuery + // .when( + // () -> + // DBQuery.getpropertiesForID( + // mockEntity, mockPersistenceService, "123", secondaryTypeProperties)) + // .thenReturn(propertiesInDB); + + // Map result = + // SDMUtils.getUpdatedSecondaryProperties( + // Optional.of(mockEntity), attachment, mockPersistenceService, // secondaryTypeProperties); - // assertEquals(0, result.size()); - // assertEquals(null, result.get("property1")); - // assertEquals(null, result.get("property2")); + // assertEquals(0, result.size()); + // assertEquals(null, result.get("property1")); + // assertEquals(null, result.get("property2")); // } // @Test // public void testGetUpdatedSecondaryProperties_withPropertiesMapNull() { - // // Mock the necessary components - // CdsEntity mockEntity = mock(CdsEntity.class); - // PersistenceService mockPersistenceService = mock(PersistenceService.class); - - // // Prepare attachment and secondaryTypeProperties - // Map attachment = new HashMap<>(); - // attachment.put("ID", "123"); - - // List secondaryTypeProperties = new ArrayList<>(); - - // // Mock DBQuery class behavior - // List propertiesInDB = new ArrayList<>(); - // mockedDbQuery - // .when( - // () -> - // DBQuery.getpropertiesForID( - // mockEntity, mockPersistenceService, "123", secondaryTypeProperties)) - // .thenReturn(propertiesInDB); - - // Map result = - // SDMUtils.getUpdatedSecondaryProperties( - // Optional.of(mockEntity), attachment, mockPersistenceService, + // // Mock the necessary components + // CdsEntity mockEntity = mock(CdsEntity.class); + // PersistenceService mockPersistenceService = mock(PersistenceService.class); + + // // Prepare attachment and secondaryTypeProperties + // Map attachment = new HashMap<>(); + // attachment.put("ID", "123"); + + // List secondaryTypeProperties = new ArrayList<>(); + + // // Mock DBQuery class behavior + // List propertiesInDB = new ArrayList<>(); + // mockedDbQuery + // .when( + // () -> + // DBQuery.getpropertiesForID( + // mockEntity, mockPersistenceService, "123", secondaryTypeProperties)) + // .thenReturn(propertiesInDB); + + // Map result = + // SDMUtils.getUpdatedSecondaryProperties( + // Optional.of(mockEntity), attachment, mockPersistenceService, // secondaryTypeProperties); - // assertEquals(0, result.size()); - // assertEquals(null, result.get("property1")); - // assertEquals(null, result.get("property2")); + // assertEquals(0, result.size()); + // assertEquals(null, result.get("property1")); + // assertEquals(null, result.get("property2")); // } // @Test // public void testGetUpdatedSecondaryProperties_DBPropertiesNull() { - // // Mock the necessary components - // CdsEntity mockEntity = mock(CdsEntity.class); - // PersistenceService mockPersistenceService = mock(PersistenceService.class); - - // // Prepare attachment and secondaryTypeProperties - // Map attachment = new HashMap<>(); - // attachment.put("ID", "123"); - // attachment.put("property1", "newValue1"); - // attachment.put("property2", "newValue2"); - - // List secondaryTypeProperties = Arrays.asList("property1", "property2"); - - // // Mock DBQuery class behavior - // List propertiesInDB = null; - // mockedDbQuery - // .when( - // () -> - // DBQuery.getpropertiesForID( - // mockEntity, mockPersistenceService, "123", secondaryTypeProperties)) - // .thenReturn(propertiesInDB); - - // Map result = - // SDMUtils.getUpdatedSecondaryProperties( - // Optional.of(mockEntity), attachment, mockPersistenceService, + // // Mock the necessary components + // CdsEntity mockEntity = mock(CdsEntity.class); + // PersistenceService mockPersistenceService = mock(PersistenceService.class); + + // // Prepare attachment and secondaryTypeProperties + // Map attachment = new HashMap<>(); + // attachment.put("ID", "123"); + // attachment.put("property1", "newValue1"); + // attachment.put("property2", "newValue2"); + + // List secondaryTypeProperties = Arrays.asList("property1", + // "property2"); + + // // Mock DBQuery class behavior + // List propertiesInDB = null; + // mockedDbQuery + // .when( + // () -> + // DBQuery.getpropertiesForID( + // mockEntity, mockPersistenceService, "123", secondaryTypeProperties)) + // .thenReturn(propertiesInDB); + + // Map result = + // SDMUtils.getUpdatedSecondaryProperties( + // Optional.of(mockEntity), attachment, mockPersistenceService, // secondaryTypeProperties); - // assertEquals(2, result.size()); - // assertEquals("newValue1", result.get("property1")); - // assertEquals("newValue2", result.get("property2")); + // assertEquals(2, result.size()); + // assertEquals("newValue1", result.get("property1")); + // assertEquals("newValue2", result.get("property2")); // } // @Test // public void testGetUpdatedSecondaryProperties_withNoChanges() { - // // Mock the necessary components - // PersistenceService mockPersistenceService = mock(PersistenceService.class); - - // // Prepare attachment and secondaryTypeProperties - // Map attachment = new HashMap<>(); - // attachment.put("ID", "123"); - // attachment.put("property1", "sameValue1"); - // attachment.put("property2", "sameValue2"); - - // List secondaryTypeProperties = Arrays.asList("property1", "property2"); - - // // Mock DBQuery static method behavior using try-with-resources - // List propertiesInDB = Arrays.asList("sameValue1", "sameValue2"); - // mockedDbQuery - // .when( - // () -> - // DBQuery.getpropertiesForID( - // mockEntity, mockPersistenceService, "123", secondaryTypeProperties)) - // .thenReturn(propertiesInDB); - - // // Call the method under test - // Map result = - // SDMUtils.getUpdatedSecondaryProperties( - // Optional.of(mockEntity), attachment, mockPersistenceService, + // // Mock the necessary components + // PersistenceService mockPersistenceService = mock(PersistenceService.class); + + // // Prepare attachment and secondaryTypeProperties + // Map attachment = new HashMap<>(); + // attachment.put("ID", "123"); + // attachment.put("property1", "sameValue1"); + // attachment.put("property2", "sameValue2"); + + // List secondaryTypeProperties = Arrays.asList("property1", + // "property2"); + + // // Mock DBQuery static method behavior using try-with-resources + // List propertiesInDB = Arrays.asList("sameValue1", "sameValue2"); + // mockedDbQuery + // .when( + // () -> + // DBQuery.getpropertiesForID( + // mockEntity, mockPersistenceService, "123", secondaryTypeProperties)) + // .thenReturn(propertiesInDB); + + // // Call the method under test + // Map result = + // SDMUtils.getUpdatedSecondaryProperties( + // Optional.of(mockEntity), attachment, mockPersistenceService, // secondaryTypeProperties); - // // Validate results - // assertTrue(result.isEmpty()); + // // Validate results + // assertTrue(result.isEmpty()); // } @Test @@ -558,7 +566,8 @@ public void testPropertyNullOrMissingMiscellaneous() throws IOException { HttpEntity mockResponseEntity = mock(HttpEntity.class); List secondaryPropertyIds = new ArrayList<>(); - // Simulate response string with "propertyDefinitions" but no "mcm:miscellaneous" + // Simulate response string with "propertyDefinitions" but no + // "mcm:miscellaneous" String responseString = "{\"propertyDefinitions\": {\"key1\": {}}}"; when(mockResponseEntity.getContent()) .thenReturn(new java.io.ByteArrayInputStream(responseString.getBytes())); @@ -573,38 +582,42 @@ public void testPropertyNullOrMissingMiscellaneous() throws IOException { // @Test // public void testPropertyValueIsNullInMapAndNotNullInDB() { - // // Arrange - // Map attachment = new HashMap<>(); - // attachment.put("ID", "12345"); // Sample ID + // // Arrange + // Map attachment = new HashMap<>(); + // attachment.put("ID", "12345"); // Sample ID - // // Simulating that "property1" has a null value in attachment map - // attachment.put("property1", null); + // // Simulating that "property1" has a null value in attachment map + // attachment.put("property1", null); - // // Secondary type properties to check - // List secondaryTypeProperties = Arrays.asList("property1", "property2"); + // // Secondary type properties to check + // List secondaryTypeProperties = Arrays.asList("property1", + // "property2"); - // // Simulate the database response where "property1" has a value in the DB - // List propertiesInDB = Arrays.asList("DBValueForProperty1", "DBValueForProperty2"); + // // Simulate the database response where "property1" has a value in the DB + // List propertiesInDB = Arrays.asList("DBValueForProperty1", + // "DBValueForProperty2"); - // // Mocking the DBQuery call to return propertiesInDB for "property1" - // when(DBQuery.getpropertiesForID( - // any(), eq(mockPersistenceService), eq("12345"), eq(secondaryTypeProperties))) - // .thenReturn(propertiesInDB); + // // Mocking the DBQuery call to return propertiesInDB for "property1" + // when(DBQuery.getpropertiesForID( + // any(), eq(mockPersistenceService), eq("12345"), eq(secondaryTypeProperties))) + // .thenReturn(propertiesInDB); - // Optional attachmentEntity = Optional.of(mock(CdsEntity.class)); + // Optional attachmentEntity = Optional.of(mock(CdsEntity.class)); - // // Act - // Map result = - // SDMUtils.getUpdatedSecondaryProperties( - // attachmentEntity, attachment, mockPersistenceService, secondaryTypeProperties); + // // Act + // Map result = + // SDMUtils.getUpdatedSecondaryProperties( + // attachmentEntity, attachment, mockPersistenceService, + // secondaryTypeProperties); - // // Assert - // assertTrue(result.containsKey("property1")); - // assertNull( - // result.get( - // "property1")); // Since property1 is null in attachment and non-null in DB, it should + // // Assert + // assertTrue(result.containsKey("property1")); + // assertNull( + // result.get( + // "property1")); // Since property1 is null in attachment and non-null in DB, + // it should // be - // // set to null + // // set to null // } @Test