Skip to content

Commit 29b2e8d

Browse files
Merge pull request #356 from cap-java/ValidateNames
Validation for Whitespace, Restricted and Duplicate
2 parents 878cd04 + 3eb7681 commit 29b2e8d

File tree

14 files changed

+828
-486
lines changed

14 files changed

+828
-486
lines changed

sdm/src/main/java/com/sap/cds/sdm/constants/SDMConstants.java

Lines changed: 40 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
11
package com.sap.cds.sdm.constants;
22

3+
import java.util.Collection;
4+
import java.util.HashSet;
35
import java.util.List;
46
import java.util.Map;
7+
import java.util.Set;
58

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

144-
public static String nameConstraintMessage(
145-
List<String> fileNameWithRestrictedCharacters, String operation) {
146-
// Create the base message
147-
String prefixMessage =
148-
"%s unsuccessful. The following filename(s) contain unsupported characters (/, \\). \n\n";
149-
150-
// Create the formatted prefix message
151-
String formattedPrefixMessage = String.format(prefixMessage, operation);
152-
153-
// Initialize the StringBuilder with the formatted message prefix
154-
StringBuilder bulletPoints = new StringBuilder(formattedPrefixMessage);
155-
156-
// Append each unsupported file name to the StringBuilder
157-
for (String file : fileNameWithRestrictedCharacters) {
158-
bulletPoints.append(String.format("\t• %s%n", file));
152+
// Helper Methods to create error/warning messages
153+
public static String buildErrorMessage(
154+
Collection<String> filenames, StringBuilder prefixTemplate, String closingRemark) {
155+
for (String file : filenames) {
156+
prefixTemplate.append(String.format("\t• %s%n", file));
159157
}
160-
bulletPoints.append("\nRename the files and try again.");
161-
return bulletPoints.toString();
158+
if (closingRemark != null && !closingRemark.isEmpty())
159+
prefixTemplate.append("\n ").append(closingRemark);
160+
return prefixTemplate.toString();
162161
}
163162

164-
public static String linkNameConstraintMessage(
165-
List<String> fileNameWithRestrictedCharacters, String operation) {
166-
// Create the base message
167-
String prefixMessage =
168-
"Link could not be %s. The following name(s) contain unsupported characters (/, \\). \n\n";
169-
170-
// Create the formatted prefix message
171-
String formattedPrefixMessage = String.format(prefixMessage, operation);
172-
173-
// Initialize the StringBuilder with the formatted message prefix
174-
StringBuilder bulletPoints = new StringBuilder(formattedPrefixMessage);
163+
// Restricted characters: / and \
164+
public static String nameConstraintMessage(List<String> invalidFileNames) {
165+
// if only 1 restricted character is there in file, so different error will throw
166+
if (invalidFileNames.size() == 1) {
167+
return String.format(SINGLE_RESTRICTED_CHARACTER_IN_FILE, invalidFileNames.iterator().next());
168+
}
169+
StringBuilder prefix = new StringBuilder();
170+
prefix.append(
171+
"The following names contain unsupported characters (‘/’ or ‘\\’). Rename and try again:\n\n");
172+
return buildErrorMessage(invalidFileNames, prefix, null);
173+
}
175174

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

184187
public static String fileNotFound(List<String> fileNameNotFound) {
@@ -253,7 +256,9 @@ public static String unsupportedPropertiesMessage(List<String> propertiesList) {
253256
}
254257

255258
public static String getDuplicateFilesError(String filename) {
256-
return String.format(DUPLICATE_FILES_ERROR, filename);
259+
Set<String> filenames = new HashSet<>();
260+
filenames.add(filename);
261+
return duplicateFilenameFormat(filenames);
257262
}
258263

259264
public static String getGenericError(String event) {

sdm/src/main/java/com/sap/cds/sdm/handler/applicationservice/SDMCreateAttachmentsHandler.java

Lines changed: 60 additions & 96 deletions
Original file line numberDiff line numberDiff line change
@@ -74,11 +74,9 @@ public void updateName(
7474
Map<String, String> propertyTitles = new HashMap<>();
7575
Map<String, String> secondaryPropertiesWithInvalidDefinitions = new HashMap<>();
7676
String targetEntity = context.getTarget().getQualifiedName();
77-
Set<String> duplicateFilenames =
78-
SDMUtils.isFileNameDuplicateInDrafts(data, attachmentCompositionName, targetEntity);
79-
if (!duplicateFilenames.isEmpty()) {
80-
handleDuplicateFilenames(context, duplicateFilenames);
81-
} else {
77+
Boolean isError = false;
78+
isError = AttachmentsHandlerUtils.validateFileNames(context, data, attachmentCompositionName);
79+
if (!isError) {
8280
List<String> fileNameWithRestrictedCharacters = new ArrayList<>();
8381
List<String> duplicateFileNameList = new ArrayList<>();
8482
List<String> filesNotFound = new ArrayList<>();
@@ -89,14 +87,19 @@ public void updateName(
8987
List<Map<String, Object>> attachments =
9088
AttachmentsHandlerUtils.fetchAttachments(
9189
targetEntity, entity, attachmentCompositionName);
90+
if (attachments == null || attachments.isEmpty()) {
91+
logger.info(
92+
"No attachments found for composition [{}] in entity [{}]. Skipping processing.",
93+
attachmentCompositionName,
94+
targetEntity);
95+
continue;
96+
}
9297
Optional<CdsEntity> attachmentEntity =
9398
context.getModel().findEntity(attachmentCompositionDefinition);
94-
if (attachments != null && !attachments.isEmpty()) {
95-
propertyTitles = SDMUtils.getPropertyTitles(attachmentEntity, attachments.get(0));
96-
secondaryPropertiesWithInvalidDefinitions =
97-
SDMUtils.getSecondaryPropertiesWithInvalidDefinition(
98-
attachmentEntity, attachments.get(0));
99-
}
99+
propertyTitles = SDMUtils.getPropertyTitles(attachmentEntity, attachments.get(0));
100+
secondaryPropertiesWithInvalidDefinitions =
101+
SDMUtils.getSecondaryPropertiesWithInvalidDefinition(
102+
attachmentEntity, attachments.get(0));
100103
processEntity(
101104
context,
102105
entity,
@@ -123,16 +126,6 @@ public void updateName(
123126
}
124127
}
125128

126-
private void handleDuplicateFilenames(
127-
CdsCreateEventContext context, Set<String> duplicateFilenames) {
128-
context
129-
.getMessages()
130-
.error(
131-
String.format(
132-
SDMConstants.DUPLICATE_FILE_IN_DRAFT_ERROR_MESSAGE,
133-
String.join(", ", duplicateFilenames)));
134-
}
135-
136129
private void processEntity(
137130
CdsCreateEventContext context,
138131
Map<String, Object> entity,
@@ -225,82 +218,56 @@ private void processAttachment(
225218
persistenceService,
226219
secondaryTypeProperties,
227220
propertiesInDB);
228-
229-
if (Boolean.TRUE.equals(SDMUtils.isRestrictedCharactersInName(filenameInRequest))) {
221+
if (SDMUtils.hasRestrictedCharactersInName(filenameInRequest)) {
230222
fileNameWithRestrictedCharacters.add(filenameInRequest);
231-
replacePropertiesInAttachment(
232-
attachment,
233-
fileNameInSDM,
234-
propertiesInDB,
235-
secondaryTypeProperties); // In this case we immediately stop the processing (Request
236-
// isn't sent to SDM)
237-
} else {
238-
CmisDocument cmisDocument = new CmisDocument();
239-
cmisDocument.setFileName(filenameInRequest);
240-
cmisDocument.setObjectId(objectId);
241-
if (fileNameInDB
242-
== null) { // If the file name in DB is null, it means that the file is being created for
243-
// the first time
244-
if (filenameInRequest != null) {
245-
updatedSecondaryProperties.put("filename", filenameInRequest);
246-
} else {
247-
throw new ServiceException("Filename cannot be empty");
248-
}
249-
} else {
250-
if (filenameInRequest == null) {
251-
throw new ServiceException("Filename cannot be empty");
252-
} else if (!fileNameInDB.equals(
253-
filenameInRequest)) { // If the file name in DB is not equal to the file name in
254-
// request, it means that the file name has been modified
255-
updatedSecondaryProperties.put("filename", filenameInRequest);
256-
}
257-
}
258-
try {
259-
int responseCode =
260-
sdmService.updateAttachments(
261-
sdmCredentials,
262-
cmisDocument,
263-
updatedSecondaryProperties,
264-
secondaryPropertiesWithInvalidDefinitions,
265-
context.getUserInfo().isSystemUser());
266-
switch (responseCode) {
267-
case 403:
268-
// SDM Roles for user are missing
269-
noSDMRoles.add(fileNameInSDM);
270-
replacePropertiesInAttachment(
271-
attachment, fileNameInSDM, propertiesInDB, secondaryTypeProperties);
272-
break;
273-
case 409:
274-
duplicateFileNameList.add(filenameInRequest);
275-
replacePropertiesInAttachment(
276-
attachment, fileNameInSDM, propertiesInDB, secondaryTypeProperties);
277-
break;
278-
case 404:
279-
filesNotFound.add(filenameInRequest);
280-
replacePropertiesInAttachment(
281-
attachment, filenameInRequest, propertiesInDB, secondaryTypeProperties);
282-
break;
283-
case 200:
284-
case 201:
285-
// Success cases, do nothing
286-
break;
223+
}
224+
CmisDocument cmisDocument = new CmisDocument();
225+
cmisDocument.setFileName(filenameInRequest);
226+
cmisDocument.setObjectId(objectId);
227+
if (fileNameInDB == null || !fileNameInDB.equals(filenameInRequest)) {
228+
updatedSecondaryProperties.put("filename", filenameInRequest);
229+
}
287230

288-
default:
289-
throw new ServiceException(SDMConstants.SDM_ROLES_ERROR_MESSAGE, null);
290-
}
291-
} catch (ServiceException e) {
292-
// This exception is thrown when there are unsupported properties in the request
293-
if (e.getMessage().startsWith(SDMConstants.UNSUPPORTED_PROPERTIES)) {
294-
String unsupportedDetails =
295-
e.getMessage().substring(SDMConstants.UNSUPPORTED_PROPERTIES.length()).trim();
296-
filesWithUnsupportedProperties.add(unsupportedDetails);
231+
try {
232+
int responseCode =
233+
sdmService.updateAttachments(
234+
sdmCredentials,
235+
cmisDocument,
236+
updatedSecondaryProperties,
237+
secondaryPropertiesWithInvalidDefinitions,
238+
context.getUserInfo().isSystemUser());
239+
switch (responseCode) {
240+
case 403:
241+
// SDM Roles for user are missing
242+
noSDMRoles.add(fileNameInSDM);
297243
replacePropertiesInAttachment(
298244
attachment, fileNameInSDM, propertiesInDB, secondaryTypeProperties);
299-
} else {
300-
badRequest.put(filenameInRequest, e.getMessage());
245+
break;
246+
case 404:
247+
filesNotFound.add(filenameInRequest);
301248
replacePropertiesInAttachment(
302249
attachment, filenameInRequest, propertiesInDB, secondaryTypeProperties);
303-
}
250+
break;
251+
case 200:
252+
case 201:
253+
// Success cases, do nothing
254+
break;
255+
256+
default:
257+
throw new ServiceException(SDMConstants.SDM_ROLES_ERROR_MESSAGE, null);
258+
}
259+
} catch (ServiceException e) {
260+
// This exception is thrown when there are unsupported properties in the request
261+
if (e.getMessage().startsWith(SDMConstants.UNSUPPORTED_PROPERTIES)) {
262+
String unsupportedDetails =
263+
e.getMessage().substring(SDMConstants.UNSUPPORTED_PROPERTIES.length()).trim();
264+
filesWithUnsupportedProperties.add(unsupportedDetails);
265+
replacePropertiesInAttachment(
266+
attachment, fileNameInSDM, propertiesInDB, secondaryTypeProperties);
267+
} else {
268+
badRequest.put(filenameInRequest, e.getMessage());
269+
replacePropertiesInAttachment(
270+
attachment, filenameInRequest, propertiesInDB, secondaryTypeProperties);
304271
}
305272
}
306273
}
@@ -343,15 +310,12 @@ private void handleWarnings(
343310
if (!fileNameWithRestrictedCharacters.isEmpty()) {
344311
context
345312
.getMessages()
346-
.warn(SDMConstants.nameConstraintMessage(fileNameWithRestrictedCharacters, "Rename"));
313+
.warn(SDMConstants.nameConstraintMessage(fileNameWithRestrictedCharacters));
347314
}
348315
if (!duplicateFileNameList.isEmpty()) {
349316
context
350317
.getMessages()
351-
.warn(
352-
String.format(
353-
SDMConstants.FILES_RENAME_WARNING_MESSAGE,
354-
String.join(", ", duplicateFileNameList)));
318+
.warn(String.format(SDMConstants.duplicateFilenameFormat(duplicateFileNameList)));
355319
}
356320
if (!filesNotFound.isEmpty()) {
357321
context.getMessages().warn(SDMConstants.fileNotFound(filesNotFound));

sdm/src/main/java/com/sap/cds/sdm/handler/applicationservice/SDMUpdateAttachmentsHandler.java

Lines changed: 6 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -65,17 +65,9 @@ public void updateName(
6565
String attachmentCompositionDefinition,
6666
String attachmentCompositionName)
6767
throws IOException {
68-
String targetEntity = context.getTarget().getQualifiedName();
69-
Set<String> duplicateFilenames =
70-
SDMUtils.isFileNameDuplicateInDrafts(data, attachmentCompositionName, targetEntity);
71-
if (!duplicateFilenames.isEmpty()) {
72-
context
73-
.getMessages()
74-
.error(
75-
String.format(
76-
SDMConstants.DUPLICATE_FILE_IN_DRAFT_ERROR_MESSAGE,
77-
String.join(", ", duplicateFilenames)));
78-
} else {
68+
Boolean isError = false;
69+
isError = AttachmentsHandlerUtils.validateFileNames(context, data, attachmentCompositionName);
70+
if (!isError) {
7971
Optional<CdsEntity> attachmentEntity =
8072
context.getModel().findEntity(attachmentCompositionDefinition);
8173
renameDocument(
@@ -226,7 +218,7 @@ public void processAttachment(
226218

227219
String objectId = (String) attachment.get("objectId");
228220
if (Boolean.TRUE.equals(
229-
SDMUtils.isRestrictedCharactersInName(
221+
SDMUtils.hasRestrictedCharactersInName(
230222
filenameInRequest))) { // Check if the filename contains restricted characters and stop
231223
// further processing if it does (Request not sent to SDM)
232224
fileNameWithRestrictedCharacters.add(filenameInRequest);
@@ -339,15 +331,12 @@ private void handleWarnings(
339331
if (!fileNameWithRestrictedCharacters.isEmpty()) {
340332
context
341333
.getMessages()
342-
.warn(SDMConstants.nameConstraintMessage(fileNameWithRestrictedCharacters, "Rename"));
334+
.warn(SDMConstants.nameConstraintMessage(fileNameWithRestrictedCharacters));
343335
}
344336
if (!duplicateFileNameList.isEmpty()) {
345337
context
346338
.getMessages()
347-
.warn(
348-
String.format(
349-
SDMConstants.FILES_RENAME_WARNING_MESSAGE,
350-
String.join(", ", duplicateFileNameList)));
339+
.warn(String.format(SDMConstants.duplicateFilenameFormat(duplicateFileNameList)));
351340
}
352341
if (!filesNotFound.isEmpty()) {
353342
context.getMessages().warn(SDMConstants.fileNotFound(filesNotFound));

0 commit comments

Comments
 (0)