Search in sources :

Example 6 with Blob

use of com.manydesigns.elements.blobs.Blob in project Portofino by ManyDesigns.

the class FileBlobFieldTest method testField1.

public void testField1() throws Exception {
    buildForm();
    assertNull(field.getValue());
    assertEquals(20, field.blobCodeGenerator.call().length());
    InputStream is = new ByteArrayInputStream(sampleContent.getBytes());
    FileItem fileItem = new DiskFileItem(field.getInputName(), "text/plain", false, sampleFilename, 0, RandomUtil.getTempDir());
    OutputStream os = fileItem.getOutputStream();
    IOUtils.copy(is, os);
    req.setFileItem(field.getInputName(), fileItem);
    req.setParameter(field.getOperationInputName(), FileBlobField.UPLOAD_MODIFY);
    form.readFromRequest(req);
    Blob blob = field.getValue();
    assertNotNull(blob);
    assertNotNull(blob.getCode());
    assertEquals(sampleFilename, blob.getFilename());
    blobManager.save(blob);
    assertNotNull(blob.getCode());
    // Test keep
    req.setParameter(field.getCodeInputName(), blob.getCode());
    req.setParameter(field.getOperationInputName(), FileBlobField.UPLOAD_KEEP);
    buildForm();
    form.readFromRequest(req);
    assertTrue(form.validate());
    blob = field.getValue();
    BlobUtils.loadBlob(field, blobManager, true);
    // Remove old one
    blobManager.delete(blob);
    blobManager.save(blob);
    assertNotNull(blob);
    assertEquals(sampleFilename, blob.getFilename());
    assertEquals(sampleContent.length(), blob.getSize());
    // Test that modify with null content keeps the old content
    req.setParameter(field.getOperationInputName(), FileBlobField.UPLOAD_MODIFY);
    req.setFileItem(field.getInputName(), null);
    req.setParameter(field.getCodeInputName(), blob.getCode());
    buildForm();
    form.readFromRequest(req);
    assertTrue(form.validate());
    blob = field.getValue();
    assertNotNull(blob);
    assertEquals(req.getParameter(field.getCodeInputName()), blob.getCode());
    buildForm();
    field.setRequired(true);
    form.readFromRequest(req);
    assertTrue(form.validate());
    // Test delete
    req.setParameter(field.getOperationInputName(), FileBlobField.UPLOAD_DELETE);
    req.setFileItem(field.getInputName(), null);
    buildForm();
    form.readFromRequest(req);
    assertTrue(form.validate());
    blob = field.getValue();
    assertNull(blob);
    buildForm();
    field.setRequired(true);
    form.readFromRequest(req);
    assertFalse(form.validate());
    field.setRequired(false);
}
Also used : FileItem(org.apache.commons.fileupload.FileItem) DiskFileItem(org.apache.commons.fileupload.disk.DiskFileItem) Blob(com.manydesigns.elements.blobs.Blob) FileBlob(com.manydesigns.elements.annotations.FileBlob) ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) DiskFileItem(org.apache.commons.fileupload.disk.DiskFileItem)

Example 7 with Blob

use of com.manydesigns.elements.blobs.Blob in project Portofino by ManyDesigns.

the class FormUtil method fieldsToJson.

/**
 * Writes a collection of fields as properties of a JSON object.
 * @param js the JSONStringer to write to. Must have a JSON object open for writing.
 * @param fields the fields to output
 * @throws org.json.JSONException if the JSON can not be generated.
 */
public static void fieldsToJson(JSONStringer js, Collection<Field> fields) throws JSONException {
    for (Field field : fields) {
        Object value = field.getValue();
        if (value instanceof Date) {
            value = ((Date) value).getTime();
        }
        if (value instanceof DateTime) {
            value = ((DateTime) value).getMillis();
        }
        String displayValue = field.getDisplayValue();
        String href = field.getHref();
        List<String> errors = field.getErrors();
        js.key(field.getPropertyAccessor().getName());
        JSONWriter json = js.object().key(JSON_VALUE);
        if (value instanceof Blob) {
            json.object();
            Blob blob = (Blob) value;
            json.key(JSON_TYPE).value(Blob.class.getName());
            json.key("code").value(blob.getCode());
            json.key("filename").value(blob.getFilename());
            json.key("contentType").value(blob.getContentType());
            json.key("size").value(blob.getSize());
            json.endObject();
        } else {
            json.value(value);
        }
        if (displayValue != null && !ObjectUtils.equals(displayValue, value)) {
            json.key("displayValue").value(displayValue);
        }
        if (href != null) {
            json.key("href").value(href);
        }
        if (!errors.isEmpty()) {
            json.key("errors").array();
            for (String error : errors) {
                json.value(error);
            }
            json.endArray();
        }
        json.endObject();
    }
}
Also used : JSONWriter(org.json.JSONWriter) TextField(com.manydesigns.elements.fields.TextField) Field(com.manydesigns.elements.fields.Field) Blob(com.manydesigns.elements.blobs.Blob) JSONObject(org.json.JSONObject) Date(java.util.Date) DateTime(org.joda.time.DateTime)

Example 8 with Blob

use of com.manydesigns.elements.blobs.Blob in project Portofino by ManyDesigns.

the class AbstractCrudAction method uploadBlob.

@PUT
@Path(":blob/{propertyName}")
@RequiresPermissions(permissions = PERMISSION_EDIT)
@Guard(test = "isEditEnabled()", type = GuardType.VISIBLE)
@Operation(summary = "Upload a blob property")
public Response uploadBlob(@Parameter(description = "The name of the property", required = true) @PathParam("propertyName") String propertyName, @Parameter(description = "The name of uploaded file") @QueryParam("filename") String filename, InputStream inputStream) throws IOException {
    if (object == null) {
        return Response.status(Response.Status.BAD_REQUEST).entity("Object can not be null (this method can only be called with /objectKey)").build();
    }
    checkAccessorPermissions(new String[] { PERMISSION_EDIT });
    setupForm(Mode.EDIT);
    form.readFromObject(object);
    AbstractBlobField field = (AbstractBlobField) form.findFieldByPropertyName(propertyName);
    if (field == null) {
        return Response.status(Response.Status.NOT_FOUND).build();
    }
    if (!field.isUpdatable()) {
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("Property not writable").build();
    }
    Blob blob = new Blob(field.generateNewCode());
    blob.setFilename(filename);
    blob.setSize(context.getRequest().getContentLength());
    blob.setContentType(context.getRequest().getContentType());
    blob.setCharacterEncoding(context.getRequest().getCharacterEncoding());
    blob.setCreateTimestamp(new DateTime());
    blob.setInputStream(inputStream);
    Blob oldBlob = field.getValue();
    field.setValue(blob);
    field.writeToObject(object);
    if (!field.isSaveBlobOnObject()) {
        BlobManager blobManager = getBlobManager();
        blobManager.save(blob);
        if (oldBlob != null) {
            try {
                blobManager.delete(oldBlob);
            } catch (IOException e) {
                logger.warn("Could not delete old blob (code: " + oldBlob.getCode() + ")", e);
            }
        }
    }
    commitTransaction();
    return Response.ok().build();
}
Also used : Blob(com.manydesigns.elements.blobs.Blob) FileBlob(com.manydesigns.elements.annotations.FileBlob) BlobManager(com.manydesigns.elements.blobs.BlobManager) IOException(java.io.IOException) DateTime(org.joda.time.DateTime) Guard(com.manydesigns.portofino.operations.annotations.Guard) Operation(io.swagger.v3.oas.annotations.Operation)

Example 9 with Blob

use of com.manydesigns.elements.blobs.Blob in project Portofino by ManyDesigns.

the class AbstractCrudAction method refreshTableBlobDownloadHref.

protected void refreshTableBlobDownloadHref() {
    Iterator<?> objIterator = objects.iterator();
    for (TableForm.Row row : tableForm.getRows()) {
        Iterator<Field> fieldIterator = row.iterator();
        Object obj = objIterator.next();
        String baseUrl = null;
        while (fieldIterator.hasNext()) {
            Field field = fieldIterator.next();
            if (field instanceof AbstractBlobField) {
                if (baseUrl == null) {
                    OgnlTextFormat hrefFormat = getReadURLFormat();
                    baseUrl = hrefFormat.format(obj);
                }
                Blob blob = ((AbstractBlobField) field).getValue();
                if (blob != null) {
                    field.setHref(getBlobDownloadUrl(field, baseUrl));
                }
            }
        }
    }
}
Also used : Blob(com.manydesigns.elements.blobs.Blob) FileBlob(com.manydesigns.elements.annotations.FileBlob) JSONObject(org.json.JSONObject) OgnlTextFormat(com.manydesigns.elements.text.OgnlTextFormat)

Example 10 with Blob

use of com.manydesigns.elements.blobs.Blob in project Portofino by ManyDesigns.

the class AbstractCrudAction method deleteBlob.

@DELETE
@Path(":blob/{propertyName}")
@RequiresPermissions(permissions = PERMISSION_EDIT)
@Operation(summary = "Delete the contents of a blob property")
public Response deleteBlob(@Parameter(description = "The name of the property", required = true) @PathParam("propertyName") String propertyName) throws IOException {
    if (object == null) {
        return Response.status(Response.Status.BAD_REQUEST).entity("Object can not be null (this method can only be called with /objectKey)").build();
    }
    checkAccessorPermissions(new String[] { PERMISSION_EDIT });
    setupForm(Mode.EDIT);
    form.readFromObject(object);
    AbstractBlobField field = (AbstractBlobField) form.findFieldByPropertyName(propertyName);
    if (!field.isUpdatable() || field.isRequired()) {
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("Property not writable").build();
    }
    Blob blob = field.getValue();
    field.setValue(null);
    field.writeToObject(object);
    if (!field.isSaveBlobOnObject() && blob != null) {
        BlobManager blobManager = getBlobManager();
        blobManager.delete(blob);
    }
    commitTransaction();
    return Response.ok().build();
}
Also used : Blob(com.manydesigns.elements.blobs.Blob) FileBlob(com.manydesigns.elements.annotations.FileBlob) BlobManager(com.manydesigns.elements.blobs.BlobManager) Operation(io.swagger.v3.oas.annotations.Operation)

Aggregations

Blob (com.manydesigns.elements.blobs.Blob)13 FileBlob (com.manydesigns.elements.annotations.FileBlob)7 IOException (java.io.IOException)6 DateTime (org.joda.time.DateTime)4 BlobManager (com.manydesigns.elements.blobs.BlobManager)3 Field (com.manydesigns.elements.fields.Field)2 Operation (io.swagger.v3.oas.annotations.Operation)2 ByteArrayInputStream (java.io.ByteArrayInputStream)2 InputStream (java.io.InputStream)2 OutputStream (java.io.OutputStream)2 Date (java.util.Date)2 DiskFileItem (org.apache.commons.fileupload.disk.DiskFileItem)2 JSONObject (org.json.JSONObject)2 DatabaseBlob (com.manydesigns.elements.annotations.DatabaseBlob)1 HierarchicalBlobManager (com.manydesigns.elements.blobs.HierarchicalBlobManager)1 AbstractBlobField (com.manydesigns.elements.fields.AbstractBlobField)1 FileBlobField (com.manydesigns.elements.fields.FileBlobField)1 TextField (com.manydesigns.elements.fields.TextField)1 ClassAccessor (com.manydesigns.elements.reflection.ClassAccessor)1 MutableHttpServletRequest (com.manydesigns.elements.servlet.MutableHttpServletRequest)1