Skip to content
75 changes: 40 additions & 35 deletions sdm/src/main/java/com/sap/cds/sdm/constants/SDMConstants.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
package com.sap.cds.sdm.constants;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class SDMConstants {
private SDMConstants() {
Expand All @@ -23,7 +26,6 @@ private SDMConstants() {
"The following files could not be renamed as they already exist:\n%s\n";
public static final String COULD_NOT_UPDATE_THE_ATTACHMENT = "Could not update the attachment";
public static final String ATTACHMENT_NOT_FOUND = "Attachment not found";
public static final String DUPLICATE_FILES_ERROR = "%s already exists.";
public static final String GENERIC_ERROR = "Could not %s the document.";
public static final String VERSIONED_REPO_ERROR =
"Upload not supported for versioned repositories.";
Expand Down Expand Up @@ -140,45 +142,46 @@ private SDMConstants() {
"Failed to parse repository response";
public static final String ERROR_IN_SETTING_TIMEOUT_MESSAGE = "Error in setting timeout";
public static final String FAILED_TO_CREATE_FOLDER = "Failed to create folder";
public static final String FILENAME_WHITESPACE_ERROR_MESSAGE =
"The object name cannot be empty or consist entirely of space characters. Enter a value.";
public static final String SINGLE_RESTRICTED_CHARACTER_IN_FILE =
"\"%s\" contains unsupported characters (‘/’ or ‘\\’). Rename and try again.";
public static final String SINGLE_DUPLICATE_FILENAME =
"An object named \"%s\" already exists. Rename the object and try again.";

public static String nameConstraintMessage(
List<String> fileNameWithRestrictedCharacters, String operation) {
// Create the base message
String prefixMessage =
"%s unsuccessful. The following filename(s) contain unsupported characters (/, \\). \n\n";

// Create the formatted prefix message
String formattedPrefixMessage = String.format(prefixMessage, operation);

// Initialize the StringBuilder with the formatted message prefix
StringBuilder bulletPoints = new StringBuilder(formattedPrefixMessage);

// Append each unsupported file name to the StringBuilder
for (String file : fileNameWithRestrictedCharacters) {
bulletPoints.append(String.format("\t• %s%n", file));
// Helper Methods to create error/warning messages
public static String buildErrorMessage(
Collection<String> filenames, StringBuilder prefixTemplate, String closingRemark) {
for (String file : filenames) {
prefixTemplate.append(String.format("\t• %s%n", file));
}
bulletPoints.append("\nRename the files and try again.");
return bulletPoints.toString();
if (closingRemark != null && !closingRemark.isEmpty())
prefixTemplate.append("\n ").append(closingRemark);
return prefixTemplate.toString();
}

public static String linkNameConstraintMessage(
List<String> fileNameWithRestrictedCharacters, String operation) {
// Create the base message
String prefixMessage =
"Link could not be %s. The following name(s) contain unsupported characters (/, \\). \n\n";

// Create the formatted prefix message
String formattedPrefixMessage = String.format(prefixMessage, operation);

// Initialize the StringBuilder with the formatted message prefix
StringBuilder bulletPoints = new StringBuilder(formattedPrefixMessage);
// Restricted characters: / and \
public static String nameConstraintMessage(List<String> invalidFileNames) {
// if only 1 restricted character is there in file, so different error will throw
if (invalidFileNames.size() == 1) {
return String.format(SINGLE_RESTRICTED_CHARACTER_IN_FILE, invalidFileNames.iterator().next());
}
StringBuilder prefix = new StringBuilder();
prefix.append(
"The following names contain unsupported characters (‘/’ or ‘\\’). Rename and try again:\n\n");
return buildErrorMessage(invalidFileNames, prefix, null);
}

// Append each unsupported file name to the StringBuilder
for (String file : fileNameWithRestrictedCharacters) {
bulletPoints.append(String.format("\t• %s%n", file));
// Duplicate file names error message
public static String duplicateFilenameFormat(Set<String> duplicateFileNames) {
// if only 1 duplicate file, so different error will throw
if (duplicateFileNames.size() == 1) {
return String.format(SINGLE_DUPLICATE_FILENAME, duplicateFileNames.iterator().next());
}
bulletPoints.append("\nRename the link and try again.");
return bulletPoints.toString();
StringBuilder prefix = new StringBuilder();
prefix.append("Objects with the following names already exist:\n\n");
String closingRemark = "Rename the objects and try again";
return buildErrorMessage(duplicateFileNames, prefix, closingRemark);
}

public static String fileNotFound(List<String> fileNameNotFound) {
Expand Down Expand Up @@ -253,7 +256,9 @@ public static String unsupportedPropertiesMessage(List<String> propertiesList) {
}

public static String getDuplicateFilesError(String filename) {
return String.format(DUPLICATE_FILES_ERROR, filename);
Set<String> filenames = new HashSet<>();
filenames.add(filename);
return duplicateFilenameFormat(filenames);
}

public static String getGenericError(String event) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,13 +74,9 @@ public void updateName(
Map<String, String> propertyTitles = new HashMap<>();
Map<String, String> secondaryPropertiesWithInvalidDefinitions = new HashMap<>();
String targetEntity = context.getTarget().getQualifiedName();
Set<String> duplicateFilenames =
SDMUtils.isFileNameDuplicateInDrafts(data, attachmentCompositionName, targetEntity);
if (!duplicateFilenames.isEmpty()) {
handleDuplicateFilenames(context, duplicateFilenames);
} else {
List<String> fileNameWithRestrictedCharacters = new ArrayList<>();
List<String> duplicateFileNameList = new ArrayList<>();
Boolean isError = false;
isError = SDMUtils.validateFileNames(context, data, attachmentCompositionName);
if (!isError) {
List<String> filesNotFound = new ArrayList<>();
List<String> filesWithUnsupportedProperties = new ArrayList<>();
Map<String, String> badRequest = new HashMap<>();
Expand All @@ -89,19 +85,22 @@ public void updateName(
List<Map<String, Object>> attachments =
AttachmentsHandlerUtils.fetchAttachments(
targetEntity, entity, attachmentCompositionName);
if (attachments == null || attachments.isEmpty()) {
logger.info(
"No attachments found for composition [{}] in entity [{}]. Skipping processing.",
attachmentCompositionName,
targetEntity);
continue;
}
Optional<CdsEntity> attachmentEntity =
context.getModel().findEntity(attachmentCompositionDefinition);
if (attachments != null && !attachments.isEmpty()) {
propertyTitles = SDMUtils.getPropertyTitles(attachmentEntity, attachments.get(0));
secondaryPropertiesWithInvalidDefinitions =
SDMUtils.getSecondaryPropertiesWithInvalidDefinition(
attachmentEntity, attachments.get(0));
}
propertyTitles = SDMUtils.getPropertyTitles(attachmentEntity, attachments.get(0));
secondaryPropertiesWithInvalidDefinitions =
SDMUtils.getSecondaryPropertiesWithInvalidDefinition(
attachmentEntity, attachments.get(0));
processEntity(
context,
entity,
fileNameWithRestrictedCharacters,
duplicateFileNameList,
filesNotFound,
filesWithUnsupportedProperties,
badRequest,
Expand All @@ -112,8 +111,6 @@ public void updateName(
attachmentCompositionName);
handleWarnings(
context,
fileNameWithRestrictedCharacters,
duplicateFileNameList,
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As this parameter is removed, are we still handling duplicate case in SDM repository (not UI check)

filesNotFound,
filesWithUnsupportedProperties,
badRequest,
Expand All @@ -123,21 +120,9 @@ public void updateName(
}
}

private void handleDuplicateFilenames(
CdsCreateEventContext context, Set<String> duplicateFilenames) {
context
.getMessages()
.error(
String.format(
SDMConstants.DUPLICATE_FILE_IN_DRAFT_ERROR_MESSAGE,
String.join(", ", duplicateFilenames)));
}

private void processEntity(
CdsCreateEventContext context,
Map<String, Object> entity,
List<String> fileNameWithRestrictedCharacters,
List<String> duplicateFileNameList,
List<String> filesNotFound,
List<String> filesWithUnsupportedProperties,
Map<String, String> badRequest,
Expand All @@ -155,8 +140,6 @@ private void processEntity(
processAttachment(
context,
attachment,
fileNameWithRestrictedCharacters,
duplicateFileNameList,
filesNotFound,
filesWithUnsupportedProperties,
badRequest,
Expand All @@ -175,8 +158,6 @@ private void processEntity(
private void processAttachment(
CdsCreateEventContext context,
Map<String, Object> attachment,
List<String> fileNameWithRestrictedCharacters,
List<String> duplicateFileNameList,
List<String> filesNotFound,
List<String> filesWithUnsupportedProperties,
Map<String, String> badRequest,
Expand Down Expand Up @@ -226,81 +207,53 @@ private void processAttachment(
secondaryTypeProperties,
propertiesInDB);

if (Boolean.TRUE.equals(SDMUtils.isRestrictedCharactersInName(filenameInRequest))) {
fileNameWithRestrictedCharacters.add(filenameInRequest);
replacePropertiesInAttachment(
attachment,
fileNameInSDM,
propertiesInDB,
secondaryTypeProperties); // In this case we immediately stop the processing (Request
// isn't sent to SDM)
} else {
CmisDocument cmisDocument = new CmisDocument();
cmisDocument.setFileName(filenameInRequest);
cmisDocument.setObjectId(objectId);
if (fileNameInDB
== null) { // If the file name in DB is null, it means that the file is being created for
// the first time
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)) { // If the file name in DB is not equal to the file name in
// request, it means that the file name has been modified
updatedSecondaryProperties.put("filename", filenameInRequest);
}
}
try {
int responseCode =
sdmService.updateAttachments(
sdmCredentials,
cmisDocument,
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 409:
duplicateFileNameList.add(filenameInRequest);
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;
CmisDocument cmisDocument = new CmisDocument();
cmisDocument.setFileName(filenameInRequest);
cmisDocument.setObjectId(objectId);
if (fileNameInDB == null || !fileNameInDB.equals(filenameInRequest)) {
updatedSecondaryProperties.put("filename", filenameInRequest);
}

default:
throw new ServiceException(SDMConstants.SDM_ROLES_ERROR_MESSAGE, 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);
try {
int responseCode =
sdmService.updateAttachments(
sdmCredentials,
cmisDocument,
updatedSecondaryProperties,
secondaryPropertiesWithInvalidDefinitions,
context.getUserInfo().isSystemUser());
switch (responseCode) {
case 403:
// SDM Roles for user are missing
noSDMRoles.add(fileNameInSDM);
replacePropertiesInAttachment(
attachment, fileNameInSDM, propertiesInDB, secondaryTypeProperties);
} else {
badRequest.put(filenameInRequest, e.getMessage());
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);
}
} 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);
}
}
}
Expand Down Expand Up @@ -333,26 +286,11 @@ private void replacePropertiesInAttachment(

private void handleWarnings(
CdsCreateEventContext context,
List<String> fileNameWithRestrictedCharacters,
List<String> duplicateFileNameList,
List<String> filesNotFound,
List<String> filesWithUnsupportedProperties,
Map<String, String> badRequest,
Map<String, String> propertyTitles,
List<String> noSDMRoles) {
if (!fileNameWithRestrictedCharacters.isEmpty()) {
context
.getMessages()
.warn(SDMConstants.nameConstraintMessage(fileNameWithRestrictedCharacters, "Rename"));
}
if (!duplicateFileNameList.isEmpty()) {
context
.getMessages()
.warn(
String.format(
SDMConstants.FILES_RENAME_WARNING_MESSAGE,
String.join(", ", duplicateFileNameList)));
}
if (!filesNotFound.isEmpty()) {
context.getMessages().warn(SDMConstants.fileNotFound(filesNotFound));
}
Expand Down
Loading
Loading