
com.xlrit.gears.engine.form.SubmitContext Maven / Gradle / Ivy
package com.xlrit.gears.engine.form;
import java.util.List;
import java.util.function.Predicate;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xlrit.gears.base.content.ContentRef;
import com.xlrit.gears.base.content.ContentStore;
import com.xlrit.gears.base.exception.NotFoundException;
import com.xlrit.gears.engine.util.EngineUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.web.multipart.MultipartFile;
@RequiredArgsConstructor
public class SubmitContext {
public static final String NAME_PREFIX = "name:";
public static final String FILENAME_PREFIX = "filename:";
private final ObjectMapper objectMapper;
private final ContentStore contentStore;
private final JsonNode formValues;
private final List files;
public ObjectMapper getObjectMapper() {
return objectMapper;
}
public JsonNode getFormValues() {
return formValues;
}
public MultipartFile getUploadedFile(String id) {
if (id == null || id.isBlank())
throw new IllegalArgumentException("Invalid id: " + id);
if (files == null || files.isEmpty())
throw new NotFoundException("upload", "id", id);
return files.stream()
.filter(createPartPredicate(id))
.findFirst()
.orElseThrow(() -> new NotFoundException("upload", "id", id));
}
public ContentRef getContentRef(String id) {
if (contentStore == null) throw new IllegalStateException("contentStore not set");
MultipartFile part = getUploadedFile(id);
return contentStore.putContent(part.getOriginalFilename(), part.getContentType(), EngineUtils.getUploadedFileData(part));
}
private static Predicate createPartPredicate(String value) {
if (value.startsWith(NAME_PREFIX)) {
String name = value.substring(NAME_PREFIX.length());
return file -> name.equals(file.getName());
}
if (value.startsWith(FILENAME_PREFIX)) {
String filename = value.substring(FILENAME_PREFIX.length());
return file -> filename.equals(file.getOriginalFilename());
}
return file -> value.equals(file.getOriginalFilename());
}
public static SubmitContext empty(ObjectMapper objectMapper) {
return new SubmitContext(objectMapper, null, null, null);
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy