Search in sources :

Example 1 with Blob

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

the class DatabaseBlobField method readFromObject.

public void readFromObject(Object obj) {
    super.readFromObject(obj);
    if (obj == null) {
        forgetBlob();
    } else {
        byte[] value = (byte[]) accessor.get(obj);
        if (value == null) {
            forgetBlob();
        } else {
            blob = new Blob(null);
            blob.setSize(value.length);
            blob.setInputStream(new ByteArrayInputStream(value));
            if (fileNameAccessor != null) {
                blob.setFilename((String) fileNameAccessor.get(obj));
            } else {
                blob.setFilename("binary.blob");
            }
            if (contentTypeAccessor != null) {
                blob.setContentType((String) contentTypeAccessor.get(obj));
            } else {
                blob.setContentType("application/octet-stream");
            }
            if (timestampAccessor != null) {
                DateTime dt = OgnlUtils.convertValue(timestampAccessor.get(obj), DateTime.class);
                blob.setCreateTimestamp(dt != null ? dt : new DateTime());
            } else {
                blob.setCreateTimestamp(new DateTime());
            }
        }
    }
}
Also used : Blob(com.manydesigns.elements.blobs.Blob) DatabaseBlob(com.manydesigns.elements.annotations.DatabaseBlob) ByteArrayInputStream(java.io.ByteArrayInputStream) DateTime(org.joda.time.DateTime)

Example 2 with Blob

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

the class AbstractCrudAction method refreshBlobDownloadHref.

// --------------------------------------------------------------------------
// Blob management
// --------------------------------------------------------------------------
protected void refreshBlobDownloadHref() {
    for (FieldSet fieldSet : form) {
        for (Field field : fieldSet.fields()) {
            if (field instanceof AbstractBlobField) {
                AbstractBlobField fileBlobField = (AbstractBlobField) field;
                Blob blob = fileBlobField.getValue();
                if (blob != null) {
                    String url = getBlobDownloadUrl(fileBlobField);
                    field.setHref(url);
                }
            }
        }
    }
}
Also used : Blob(com.manydesigns.elements.blobs.Blob) FileBlob(com.manydesigns.elements.annotations.FileBlob)

Example 3 with Blob

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

the class AbstractCrudAction method deleteOldBlobs.

protected void deleteOldBlobs(List<Blob> blobsBefore, List<Blob> blobsAfter) {
    List<Blob> toDelete = new ArrayList<>(blobsBefore);
    toDelete.removeAll(blobsAfter);
    for (Blob blob : toDelete) {
        try {
            getBlobManager().delete(blob);
        } catch (IOException e) {
            logger.warn("Could not delete blob: " + blob.getCode(), e);
        }
    }
}
Also used : Blob(com.manydesigns.elements.blobs.Blob) FileBlob(com.manydesigns.elements.annotations.FileBlob) IOException(java.io.IOException)

Example 4 with Blob

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

the class CrudActionTest method testBlobs.

public void testBlobs() throws Exception {
    MutableHttpServletRequest req = new MutableHttpServletRequest();
    ElementsThreadLocals.setMultipart(req);
    req.getServletContext().setInitParameter("portofino.api.root", "http://fake");
    req.makeMultipart();
    Column column = DatabaseLogic.findColumnByName(persistence.getModel(), "jpetstore", "PUBLIC", "PRODUCT", "DESCN");
    Annotation ann = new Annotation(column, FileBlob.class.getName());
    column.getAnnotations().add(ann);
    persistence.initModel();
    CrudAction crudAction = new CrudAction() {

        public void commitTransaction() {
            super.commitTransaction();
            session.beginTransaction();
        }

        @NotNull
        @Override
        protected ClassAccessor filterAccordingToPermissions(ClassAccessor classAccessor) {
            // Let's ignore Shiro
            return classAccessor;
        }

        @Override
        protected String getUrlEncoding() {
            return PortofinoProperties.URL_ENCODING_DEFAULT;
        }
    };
    CrudConfiguration configuration = new CrudConfiguration();
    configuration.setDatabase("jpetstore");
    configuration.setQuery("from product");
    String metaFilenamePattern = "blob-{0}.properties";
    String dataFilenamePattern = "blob-{0}.data";
    crudAction.blobManager = new HierarchicalBlobManager(new File(System.getProperty("java.io.tmpdir")), metaFilenamePattern, dataFilenamePattern);
    CrudProperty property = new CrudProperty();
    property.setName("productid");
    property.setEnabled(true);
    property.setInsertable(true);
    property.setUpdatable(true);
    configuration.getProperties().add(property);
    property = new CrudProperty();
    property.setName("category");
    property.setEnabled(true);
    property.setInsertable(true);
    property.setUpdatable(true);
    configuration.getProperties().add(property);
    property = new CrudProperty();
    property.setName("descn");
    property.setEnabled(true);
    property.setInsertable(true);
    property.setUpdatable(true);
    configuration.getProperties().add(property);
    property = new CrudProperty();
    property.setName("name");
    property.setEnabled(true);
    property.setInsertable(true);
    property.setUpdatable(true);
    ann = new Annotation(column, Required.class.getName());
    ann.getProperties().add(new Property("value", "true"));
    property.getAnnotations().add(ann);
    configuration.getProperties().add(property);
    configuration.persistence = persistence;
    configuration.init();
    ActionInstance actionInstance = new ActionInstance(null, null, new ActionDescriptor(), CrudAction.class);
    actionInstance.setConfiguration(configuration);
    actionInstance.getParameters().add("1");
    ActionContext actionContext = new ActionContext();
    actionContext.setRequest(req);
    actionContext.setActionPath("");
    actionContext.setServletContext(req.getServletContext());
    req.setParameter("productid", "1");
    Map category = (Map) persistence.getSession("jpetstore").createQuery("from category").list().get(0);
    req.setParameter("category", (String) category.get("catid"));
    crudAction.persistence = persistence;
    crudAction.setContext(actionContext);
    crudAction.setActionInstance(actionInstance);
    crudAction.init();
    crudAction.setupForm(Mode.CREATE);
    Field descnField = crudAction.getForm().findFieldByPropertyName("descn");
    assertNotNull(descnField);
    assertTrue(descnField instanceof FileBlobField);
    File tmpFile = File.createTempFile("blob", "blob");
    DiskFileItem fileItem = new DiskFileItem("descn", "application/octet-stream", false, tmpFile.getName(), 0, tmpFile.getParentFile()) {

        @Override
        public void delete() {
        // Do nothing as we want to reuse this
        }
    };
    OutputStream os = fileItem.getOutputStream();
    IOUtils.write("some test data", os, req.getCharacterEncoding());
    req.addFileItem("descn", fileItem);
    req.setParameter("descn_operation", AbstractBlobField.UPLOAD_MODIFY);
    crudAction.httpPostMultipart();
    assertFalse(crudAction.form.validate());
    AbstractBlobField blobField = (AbstractBlobField) crudAction.form.findFieldByPropertyName("descn");
    assertNotNull(blobField.getValue());
    assertEquals(tmpFile.getName(), blobField.getValue().getFilename());
    assertEquals(fileItem.getSize(), blobField.getValue().getSize());
    try {
        crudAction.getBlobManager().loadMetadata(new Blob(blobField.getValue().getCode()));
        fail("The blob was saved despite validation failing");
    } catch (Exception e) {
    }
    crudAction.object = null;
    req.setParameter(blobField.getCodeInputName(), blobField.getValue().getCode());
    req.setParameter("name", "name");
    req.setParameter("productid", "1");
    req.setParameter("category", "BIRDS");
    crudAction.httpPostMultipart();
    assertTrue(crudAction.form.validate());
    blobField = (FileBlobField) crudAction.form.findFieldByPropertyName("descn");
    assertNotNull(blobField.getValue());
    // This is necessary because the crud might reload the form
    crudAction.blobManager.loadMetadata(blobField.getValue());
    assertEquals(tmpFile.getName(), blobField.getValue().getFilename());
    assertEquals(fileItem.getSize(), blobField.getValue().getSize());
    try {
        crudAction.blobManager.loadMetadata(new Blob(blobField.getValue().getCode()));
    } catch (IOException e) {
        e.printStackTrace();
        fail("The blob was not saved");
    }
    crudAction.httpPutMultipart();
    assertTrue(crudAction.form.validate());
    blobField = (FileBlobField) crudAction.form.findFieldByPropertyName("descn");
    assertNotNull(blobField.getValue());
    // This is necessary because the crud might reload the form
    crudAction.blobManager.loadMetadata(blobField.getValue());
    assertEquals(tmpFile.getName(), blobField.getValue().getFilename());
    String oldBlobCode = blobField.getValue().getCode();
    assertEquals(fileItem.getSize(), blobField.getValue().getSize());
    req.setParameter("descn_operation", FileBlobField.UPLOAD_MODIFY);
    req.setFileItem("descn", fileItem);
    crudAction.httpPutMultipart();
    assertTrue(crudAction.form.validate());
    blobField = (FileBlobField) crudAction.form.findFieldByPropertyName("descn");
    assertNotNull(blobField.getValue());
    // This is necessary because the crud might reload the form
    crudAction.blobManager.loadMetadata(blobField.getValue());
    assertEquals(tmpFile.getName(), blobField.getValue().getFilename());
    String newBlobCode = blobField.getValue().getCode();
    assertNotEquals(oldBlobCode, newBlobCode);
    crudAction.blobManager.loadMetadata(new Blob(newBlobCode));
    try {
        crudAction.blobManager.loadMetadata(new Blob(oldBlobCode));
        fail("The blob " + oldBlobCode + " should have been deleted");
    } catch (IOException e) {
    // Ok
    }
    Session session = persistence.getSession("jpetstore");
    session.flush();
    Object id = ((Map) crudAction.object).get("productid");
    int qres = session.createSQLQuery("update product set descn = 'illegal' where productid = :id").setParameter("id", id).executeUpdate();
    assertEquals(1, qres);
    session.flush();
    session.getTransaction().commit();
    session.clear();
    session.beginTransaction();
    // Force loading the object from the DB
    crudAction.getParameters().add(id.toString());
    crudAction.parametersAcquired();
    crudAction.setupForm(Mode.VIEW);
    crudAction.form.readFromObject(crudAction.object);
    BlobUtils.loadBlobs(crudAction.form, crudAction.getBlobManager(), false);
    blobField = (FileBlobField) crudAction.form.findFieldByPropertyName("descn");
    assertNotNull(blobField.getValue());
    assertNotNull(blobField.getBlobError());
    assertNull(blobField.getValue().getFilename());
    qres = session.createSQLQuery("update product set descn = :blobCode where productid = :id").setParameter("id", id).setParameter("blobCode", newBlobCode).executeUpdate();
    assertEquals(1, qres);
    session.flush();
    session.getTransaction().commit();
    session.clear();
    session.beginTransaction();
    // Force reload
    crudAction.parametersAcquired();
    crudAction.httpDelete(Collections.emptyList());
    try {
        crudAction.blobManager.loadMetadata(new Blob(newBlobCode));
        fail("The blob " + newBlobCode + " should have been deleted");
    } catch (IOException e) {
    // Ok
    }
}
Also used : FileBlobField(com.manydesigns.elements.fields.FileBlobField) ActionDescriptor(com.manydesigns.portofino.actions.ActionDescriptor) OutputStream(java.io.OutputStream) Field(com.manydesigns.elements.fields.Field) FileBlobField(com.manydesigns.elements.fields.FileBlobField) AbstractBlobField(com.manydesigns.elements.fields.AbstractBlobField) Column(com.manydesigns.portofino.model.database.Column) CrudProperty(com.manydesigns.portofino.resourceactions.crud.configuration.CrudProperty) AbstractBlobField(com.manydesigns.elements.fields.AbstractBlobField) Property(com.manydesigns.portofino.model.Property) CrudProperty(com.manydesigns.portofino.resourceactions.crud.configuration.CrudProperty) CrudConfiguration(com.manydesigns.portofino.resourceactions.crud.configuration.database.CrudConfiguration) DiskFileItem(org.apache.commons.fileupload.disk.DiskFileItem) Blob(com.manydesigns.elements.blobs.Blob) FileBlob(com.manydesigns.elements.annotations.FileBlob) FileBlob(com.manydesigns.elements.annotations.FileBlob) MutableHttpServletRequest(com.manydesigns.elements.servlet.MutableHttpServletRequest) IOException(java.io.IOException) ActionContext(com.manydesigns.portofino.resourceactions.ActionContext) Annotation(com.manydesigns.portofino.model.Annotation) SQLException(java.sql.SQLException) IOException(java.io.IOException) ActionInstance(com.manydesigns.portofino.resourceactions.ActionInstance) ClassAccessor(com.manydesigns.elements.reflection.ClassAccessor) HierarchicalBlobManager(com.manydesigns.elements.blobs.HierarchicalBlobManager) FileObject(org.apache.commons.vfs2.FileObject) File(java.io.File) Map(java.util.Map) Session(org.hibernate.Session)

Example 5 with Blob

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

the class Utilities method downloadBlob.

public static Response downloadBlob(Blob blob, BlobManager blobManager, HttpServletRequest request, Logger logger) {
    if (blob == null) {
        return Response.status(Response.Status.NOT_FOUND).build();
    }
    if (blob.getInputStream() == null) {
        try {
            blobManager.loadMetadata(blob);
        } catch (IOException e) {
            logger.error("Could not load blob", e);
            return Response.status(Response.Status.NOT_FOUND).build();
        }
    }
    long contentLength = blob.getSize();
    String contentType = blob.getContentType();
    String fileName = blob.getFilename();
    long lastModified = blob.getCreateTimestamp().getMillis();
    if (request.getHeader("If-Modified-Since") != null) {
        long ifModifiedSince = request.getDateHeader("If-Modified-Since");
        if (ifModifiedSince >= lastModified) {
            return Response.status(Response.Status.NOT_MODIFIED).build();
        }
    }
    final InputStream inputStream;
    if (blob.getInputStream() == null) {
        try {
            inputStream = blobManager.openStream(blob);
        } catch (IOException e) {
            logger.error("Could not load blob", e);
            return Response.status(Response.Status.NOT_FOUND).build();
        }
    } else {
        inputStream = blob.getInputStream();
    }
    StreamingOutput streamingOutput = output -> {
        try (InputStream i = inputStream) {
            IOUtils.copyLarge(i, output);
        }
    };
    Response.ResponseBuilder responseBuilder = Response.ok(streamingOutput).type(contentType).lastModified(new Date(lastModified)).header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName);
    if (contentLength > 0) {
        responseBuilder.header(HttpHeaders.CONTENT_LENGTH, contentLength);
    }
    return responseBuilder.build();
}
Also used : IOUtils(org.apache.commons.io.IOUtils) BlobManager(com.manydesigns.elements.blobs.BlobManager) HttpServletRequest(javax.servlet.http.HttpServletRequest) Logger(org.slf4j.Logger) HttpHeaders(javax.ws.rs.core.HttpHeaders) Response(javax.ws.rs.core.Response) Date(java.util.Date) StreamingOutput(javax.ws.rs.core.StreamingOutput) IOException(java.io.IOException) Blob(com.manydesigns.elements.blobs.Blob) InputStream(java.io.InputStream) Response(javax.ws.rs.core.Response) InputStream(java.io.InputStream) StreamingOutput(javax.ws.rs.core.StreamingOutput) IOException(java.io.IOException) Date(java.util.Date)

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