Skip to content

Commit

Permalink
update
Browse files Browse the repository at this point in the history
  • Loading branch information
mfriesen committed Jun 7, 2024
1 parent 7c43aa2 commit c2d6a87
Show file tree
Hide file tree
Showing 4 changed files with 426 additions and 175 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Stream;

import com.amazonaws.services.lambda.runtime.LambdaLogger;
import com.formkiq.aws.dynamodb.PaginationResult;
import com.formkiq.aws.dynamodb.SiteIdKeyGenerator;
Expand All @@ -55,9 +57,12 @@
import com.formkiq.aws.services.lambda.exceptions.DocumentNotFoundException;
import com.formkiq.aws.services.lambda.exceptions.NotFoundException;
import com.formkiq.aws.services.lambda.services.CacheService;
import com.formkiq.module.actions.Action;
import com.formkiq.module.actions.services.ActionsService;
import com.formkiq.module.lambdaservices.AwsServiceCache;
import com.formkiq.stacks.api.transformers.AddDocumentRequestToDocumentItem;
import com.formkiq.stacks.api.transformers.AddDocumentRequestToPresignedUrls;
import com.formkiq.stacks.api.transformers.DocumentAttributeSchema;
import com.formkiq.stacks.api.transformers.DocumentAttributeToDocumentAttributeRecord;
import com.formkiq.stacks.api.transformers.PresignedUrlsToS3Bucket;
import com.formkiq.stacks.api.validators.DocumentEntityValidator;
Expand All @@ -69,6 +74,8 @@
import com.formkiq.stacks.dynamodb.SaveDocumentOptions;
import com.formkiq.stacks.dynamodb.attributes.AttributeValidationAccess;
import com.formkiq.stacks.dynamodb.attributes.DocumentAttributeRecord;
import com.formkiq.stacks.dynamodb.schemas.Schema;
import com.formkiq.stacks.dynamodb.schemas.SchemaService;
import com.formkiq.validation.ValidationError;
import com.formkiq.validation.ValidationException;
import software.amazon.awssdk.services.s3.model.S3Exception;
Expand All @@ -77,13 +84,10 @@
public class DocumentIdRequestHandler
implements ApiGatewayRequestHandler, ApiGatewayRequestEventUtil {

/** Extension for FormKiQ config file. */
public static final String FORMKIQ_DOC_EXT = ".fkb64";

/** {@link DocumentEntityValidator}. */
private DocumentEntityValidator documentEntityValidator = new DocumentEntityValidatorImpl();
private final DocumentEntityValidator documentEntityValidator = new DocumentEntityValidatorImpl();
/** {@link DocumentValidator}. */
private DocumentValidator documentValidator = new DocumentValidatorImpl();
private final DocumentValidator documentValidator = new DocumentValidatorImpl();

/**
* constructor.
Expand Down Expand Up @@ -173,13 +177,6 @@ public ApiRequestHandlerResponse get(final LambdaLogger logger,
return new ApiRequestHandlerResponse(SC_OK, new ApiMapResponse(ditem));
}

private AttributeValidationAccess getAttributeValidationAccess(
final ApiAuthorization authorization, final String siteId) {

boolean isAdmin = authorization.getPermissions(siteId).contains(ApiPermission.ADMIN);
return isAdmin ? AttributeValidationAccess.ADMIN_UPDATE : AttributeValidationAccess.UPDATE;
}

@Override
public String getRequestUrl() {
return "/documents/{documentId}";
Expand Down Expand Up @@ -215,12 +212,8 @@ public ApiRequestHandlerResponse patch(final LambdaLogger logger,

DocumentService service = awsservice.getExtension(DocumentService.class);

DocumentAttributeToDocumentAttributeRecord tr =
new DocumentAttributeToDocumentAttributeRecord(request.getDocumentId());

List<DocumentAttribute> attributes = notNull(request.getAttributes());
List<DocumentAttributeRecord> documentAttributes =
attributes.stream().flatMap(a -> tr.apply(a).stream()).toList();
getDocumentAttributeRecords(awsservice, request, siteId, documentId);

SaveDocumentOptions options = new SaveDocumentOptions()
.validationAccess(getAttributeValidationAccess(authorization, siteId));
Expand All @@ -232,13 +225,20 @@ public ApiRequestHandlerResponse patch(final LambdaLogger logger,
Map<String, Object> uploadUrls = addDocumentRequestToPresignedUrls.apply(request);
new PresignedUrlsToS3Bucket(request).apply(uploadUrls);

uploadUrls.put("siteId", siteId != null ? siteId : null);
List<Action> actions = request.getActions();
if (!notNull(actions).isEmpty()) {
ActionsService actionsService = awsservice.getExtension(ActionsService.class);
actions.forEach(a -> a.userId(authorization.getUsername()));
actionsService.saveNewActions(siteId, documentId, actions);
}

uploadUrls.put("siteId", siteId);
return new ApiRequestHandlerResponse(SC_OK, new ApiMapResponse(uploadUrls));
}

/**
* Validate Patch Request.
*
*
* @param awsservice {@link AwsServiceCache}
* @param event {@link ApiGatewayRequestEvent}
* @param siteId {@link String}
Expand All @@ -264,4 +264,39 @@ private void validatePatch(final AwsServiceCache awsservice, final ApiGatewayReq
throw new ValidationException(errors);
}
}

/**
* Get Document Attribute Records.
*
* @param awsservice {@link AwsServiceCache}
* @param request {@link AddDocumentRequest}
* @param siteId {@link String}
* @param documentId {@link String}
* @return {@link List} {@link DocumentAttributeRecord}
*/
private List<DocumentAttributeRecord> getDocumentAttributeRecords(
final AwsServiceCache awsservice, final AddDocumentRequest request, final String siteId,
final String documentId) {

DocumentAttributeToDocumentAttributeRecord tr =
new DocumentAttributeToDocumentAttributeRecord(request.getDocumentId());

List<DocumentAttribute> attributes = notNull(request.getAttributes());
List<DocumentAttributeRecord> documentAttributes =
attributes.stream().flatMap(a -> tr.apply(a).stream()).toList();

SchemaService schemaService = awsservice.getExtension(SchemaService.class);
Schema schema = schemaService.getSitesSchema(siteId, null);

Collection<DocumentAttributeRecord> compositeKeys =
new DocumentAttributeSchema(schema, documentId).apply(documentAttributes);
return Stream.concat(documentAttributes.stream(), compositeKeys.stream()).toList();
}

private AttributeValidationAccess getAttributeValidationAccess(
final ApiAuthorization authorization, final String siteId) {

boolean isAdmin = authorization.getPermissions(siteId).contains(ApiPermission.ADMIN);
return isAdmin ? AttributeValidationAccess.ADMIN_UPDATE : AttributeValidationAccess.UPDATE;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -113,40 +113,20 @@ private ApiRequestHandlerResponse buildPresignedResponse(final ApiGatewayRequest
final Collection<DocumentAttributeRecord> searchAttributes)
throws UnsupportedEncodingException, BadException, ValidationException {

// Date date = item.getInsertedDate();
String documentId = request.getDocumentId();
// String username = item.getUserId();

// List<DocumentTag> tags = new ArrayList<>();
// if (item.containsKey("tags")) {
// tags = item.getList("tags").stream().map(new DynamicObjectToDocumentTag(null))
// .map(t -> t.setInsertedDate(date)).collect(Collectors.toList());
// }

if (tags.isEmpty()) {
tags.add(new DocumentTag(documentId, "untagged", "true", new Date(),
authorization.getUsername(), DocumentTagType.SYSTEMDEFINED));
}

// validateTagSchema(siteId, request, tags, username, tags);

AddDocumentRequestToPresignedUrls addDocumentRequestToPresignedUrls =
new AddDocumentRequestToPresignedUrls(awsservice, siteId,
caculateDuration(event.getQueryStringParameters()),
calculateContentLength(awsservice, event.getQueryStringParameters(), siteId));

Map<String, Object> map = addDocumentRequestToPresignedUrls.apply(request);

// Map<String, Object> map = generatePresignedUrl(event, awsservice, siteId, request);

// if (awsservice.debug()) {
// logger.log("generated presign url: " + urlstring + " for document " + documentId);
// }

// String value = this.restrictionMaxDocuments.getValue(awsservice, siteId);

// if (!this.restrictionMaxDocuments.enforced(awsservice, siteId, value)) {

DocumentService service = awsservice.getExtension(DocumentService.class);

DocumentItem item =
Expand All @@ -155,38 +135,13 @@ private ApiRequestHandlerResponse buildPresignedResponse(final ApiGatewayRequest
SaveDocumentOptions options = new SaveDocumentOptions().saveDocumentDate(true);
service.saveDocument(siteId, item, tags, searchAttributes, options);

// for (DocumentItem childDoc : item.getDocuments()) {
// childDoc.setBelongsToDocumentId(item.getDocumentId());
// options = new SaveDocumentOptions().saveDocumentDate(false);
// // service.saveDocument(request, childDoc, null, null, options);
// // TODO cleanup
// }

//// List<DynamicObject> documents = tags.getList("documents");
//// for (DynamicObject o : notNull(documents)) {
//// options = new SaveDocumentOptions().saveDocumentDate(false);
// service.saveDocument(request, o, tags, searchAttributes, options);
// }

List<Action> actions = request.getActions();
if (!notNull(actions).isEmpty()) {
ActionsService actionsService = awsservice.getExtension(ActionsService.class);
// List<Action> actions = tags.getList("actions").stream().map(new DynamicObjectToAction())
// .collect(Collectors.toList());
actions.forEach(a -> a.userId(authorization.getUsername()));
actionsService.saveNewActions(siteId, documentId, actions);
}

// if (value != null) {
//
// DocumentCountService countService = awsservice.getExtension(DocumentCountService.class);
// countService.incrementDocumentCount(siteId);
// }

// } else {
// throw new BadException("Max Number of Documents reached");
// }

return new ApiRequestHandlerResponse(SC_OK, new ApiMapResponse(map));
}

Expand Down Expand Up @@ -352,26 +307,13 @@ public ApiRequestHandlerResponse post(final LambdaLogger logger,

notNull(request.getDocuments()).forEach(d -> d.setDocumentId(UUID.randomUUID().toString()));

// DynamicDocumentItem item = new DynamicDocumentItem(fromBodyToMap(event));
// item.setDocumentId(UUID.randomUUID().toString());
// item.setUserId(authorization.getUsername());
// item.setInsertedDate(new Date());

// List<DynamicObject> documents = item.getList("documents");
// for (DynamicObject o : notNull(documents)) {
// o.put("documentId", UUID.randomUUID().toString());
// o.put("userId", authorization.getUsername());
// }


SchemaService schemaService = awsservice.getExtension(SchemaService.class);

String siteId = authorization.getSiteId();
String documentId = request.getDocumentId();
Schema schema = schemaService.getSitesSchema(siteId, null);

AttributeService attributeService = awsservice.getExtension(AttributeService.class);
// attributeService.getAttributes(siteId, attributeKeys);

List<DocumentAttribute> attributes = notNull(request.getAttributes());

Expand All @@ -393,19 +335,11 @@ public ApiRequestHandlerResponse post(final LambdaLogger logger,

String maxDocumentCount = validatePost(awsservice, siteId, request);

// List<DynamicObject> list = item.getList("attributes");


Collection<DocumentAttributeRecord> compositeKeys =
new DocumentAttributeSchema(schema, documentId).apply(searchAttributes);

searchAttributes = Stream.concat(searchAttributes.stream(), compositeKeys.stream()).toList();

// List<DocumentAttributeRecord> compositeKeys = searchAttributes.stream()
// .flatMap(new DocumentAttributeSchema(schema, documentId).stream()).toList();
// Collection<DocumentAttributeRecord> searchAttributes =
// new DynamicObjectToDocumentAttributeRecord(item.getDocumentId(), schema).apply(list);

ApiRequestHandlerResponse response = buildPresignedResponse(event, authorization, awsservice,
siteId, request, tags, searchAttributes);

Expand All @@ -421,17 +355,6 @@ public ApiRequestHandlerResponse post(final LambdaLogger logger,
private String validatePost(final AwsServiceCache awsservice, final String siteId,
final AddDocumentRequest item) throws BadException, ValidationException {

// boolean isFolder = isFolder(item);
//
// Collection<ValidationError> errors = Collections.emptyList();
// if (!isFolder && !item.hasString("content") && item.getList("documents").isEmpty()
// && isEmpty(item.getDeepLinkPath())) {
//
// errors = Arrays.asList(new ValidationErrorImpl()
// .error("either 'content', 'documents', or 'deepLinkPath' are required"));
// throw new ValidationException(errors);
// }

Collection<ValidationError> errors = this.documentValidator.validate(item.getMetadata());
if (!errors.isEmpty()) {
throw new ValidationException(errors);
Expand All @@ -450,62 +373,4 @@ private String validateMaxDocuments(final AwsServiceCache awsservice, final Stri

return maxDocumentCount;
}

// /**
// * Validate Document Tags.
// *
// * @param tags {@link List} {@link DynamicObject}
// * @throws ValidationException ValidationException
// */
// private void validateTags(final List<DynamicObject> tags) throws ValidationException {
//
// List<String> tagKeys = tags.stream().map(t -> t.getString("key")).collect(Collectors.toList());
//
// DocumentTagValidator validator = new DocumentTagValidatorImpl();
// Collection<ValidationError> errors = validator.validateKeys(tagKeys);
//
// if (!errors.isEmpty()) {
// throw new ValidationException(errors);
// }
// }

// /**
// * Validate {@link DynamicDocumentItem} against a TagSchema.
// *
// * @param cacheService {@link AwsServiceCache}
// * @param siteId {@link String}
// * @param item {@link DynamicDocumentItem}
// * @param userId {@link String}
// * @param tags {@link List} {@link DocumentTag}
// * @throws ValidationException ValidationException
// * @throws BadException BadException
// */
// private void validateTagSchema(final AwsServiceCache cacheService, final String siteId,
// final DynamicDocumentItem item, final String userId, final List<DocumentTag> tags)
// throws ValidationException, BadException {
//
// DocumentTagSchemaPlugin plugin = cacheService.getExtension(DocumentTagSchemaPlugin.class);
//
// if (item.getTagSchemaId() != null) {
//
// TagSchemaInterface tagSchema = plugin.getTagSchema(siteId, item.getTagSchemaId());
//
// if (tagSchema == null) {
// throw new BadException("TagschemaId " + item.getTagSchemaId() + " not found");
// }
//
// plugin.updateInUse(siteId, tagSchema);
//
// Collection<ValidationError> errors = new ArrayList<>();
// List<DocumentTag> compositeTags = plugin
// .addCompositeKeys(tagSchema, siteId, item.getDocumentId(), tags, userId, true, errors)
// .stream().map(t -> t).collect(Collectors.toList());
//
// if (!errors.isEmpty()) {
// throw new ValidationException(errors);
// }
//
// tags.addAll(compositeTags);
// }
// }
}
Loading

0 comments on commit c2d6a87

Please sign in to comment.