Search in sources :

Example 1 with ClassAccessor

use of com.manydesigns.elements.reflection.ClassAccessor in project Portofino by ManyDesigns.

the class QueryUtils method getRelatedObjects.

/**
 * Navigates a ...-to-many relationship returning the list of objects associated with a given entity.
 * @param persistence the persistence object
 * @param databaseName the name of the database (connection provider)
 * @param entityName the type (entity name) of the master object
 * @param obj the master object
 * @param oneToManyRelationshipName the name of the relationship to navigate
 * @return the list of associated objects
 */
@SuppressWarnings({ "unchecked" })
public static List<Object> getRelatedObjects(Persistence persistence, String databaseName, String entityName, Object obj, String oneToManyRelationshipName) {
    Model model = persistence.getModel();
    ForeignKey relationship = DatabaseLogic.findOneToManyRelationship(model, databaseName, entityName, oneToManyRelationshipName);
    if (relationship == null) {
        throw new IllegalArgumentException("Relationship not defined: " + oneToManyRelationshipName);
    }
    Table fromTable = relationship.getFromTable();
    Session session = persistence.getSession(fromTable.getDatabaseName());
    ClassAccessor toAccessor = persistence.getTableAccessor(databaseName, entityName);
    try {
        CriteriaDefinition criteria = createCriteria(session, fromTable);
        List<Predicate> where = new ArrayList<>();
        for (Reference reference : relationship.getReferences()) {
            Column fromColumn = reference.getActualFromColumn();
            Column toColumn = reference.getActualToColumn();
            PropertyAccessor toPropertyAccessor = toAccessor.getProperty(toColumn.getActualPropertyName());
            Object toValue = toPropertyAccessor.get(obj);
            where.add(criteria.builder.equal(criteria.root.get(fromColumn.getActualPropertyName()), toValue));
        }
        return session.createQuery(criteria.query.where(where.toArray(new Predicate[0]))).list();
    } catch (Throwable e) {
        String msg = String.format("Cannot access relationship %s on entity %s.%s", oneToManyRelationshipName, databaseName, entityName);
        logger.warn(msg, e);
    }
    return null;
}
Also used : PropertyAccessor(com.manydesigns.elements.reflection.PropertyAccessor) Predicate(javax.persistence.criteria.Predicate) ClassAccessor(com.manydesigns.elements.reflection.ClassAccessor) Model(com.manydesigns.portofino.model.Model) Session(org.hibernate.Session)

Example 2 with ClassAccessor

use of com.manydesigns.elements.reflection.ClassAccessor 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 3 with ClassAccessor

use of com.manydesigns.elements.reflection.ClassAccessor in project Portofino by ManyDesigns.

the class SelectionProviderLogic method createSelectionProvider.

public static DefaultSelectionProvider createSelectionProvider(String name, Collection objects, Class objectClass, @Nullable TextFormat[] textFormats, String[] propertyNames) {
    ClassAccessor classAccessor = JavaClassAccessor.getClassAccessor(objectClass);
    PropertyAccessor[] propertyAccessors = new PropertyAccessor[propertyNames.length];
    for (int i = 0; i < propertyNames.length; i++) {
        String currentName = propertyNames[i];
        try {
            PropertyAccessor propertyAccessor = classAccessor.getProperty(currentName);
            propertyAccessors[i] = propertyAccessor;
        } catch (Throwable e) {
            String msg = MessageFormat.format("Could not access property: {0}", currentName);
            logger.warn(msg, e);
            throw new IllegalArgumentException(msg, e);
        }
    }
    return createSelectionProvider(name, objects, propertyAccessors, textFormats);
}
Also used : PropertyAccessor(com.manydesigns.elements.reflection.PropertyAccessor) JavaClassAccessor(com.manydesigns.elements.reflection.JavaClassAccessor) ClassAccessor(com.manydesigns.elements.reflection.ClassAccessor)

Example 4 with ClassAccessor

use of com.manydesigns.elements.reflection.ClassAccessor in project Portofino by ManyDesigns.

the class ManyToManyAction method jsonAssociations.

public Response jsonAssociations() throws JSONException {
    JSONObject response = new JSONObject();
    JSONArray enumList = new JSONArray();
    JSONObject model = new JSONObject();
    JSONObject titleMap = new JSONObject();
    JSONArray trueRelations = new JSONArray();
    JSONArray form = new JSONArray();
    JSONObject schema = new JSONObject();
    if (onePk != null) {
        try {
            loadAssociations();
            if (potentiallyAvailableAssociations == null) {
                return resourceActionNotConfigured();
            }
        } catch (NoSuchFieldException e) {
            return resourceActionNotConfigured();
        }
        booleanRelation = new LinkedHashMap<>();
        ClassAccessor ca = getManyTableAccessor();
        PkHelper pkHelper = new PkHelper(ca);
        for (Object obj : potentiallyAvailableAssociations) {
            String pk = StringUtils.join(pkHelper.generatePkStringArray(obj), "/");
            enumList.put(pk);
            titleMap.put(pk, ShortNameUtils.getName(ca, obj));
            if (!availableAssociations.contains(obj)) {
                trueRelations.put(pk);
            }
        }
        model.put(onePk.toString(), trueRelations);
        JSONObject items = new JSONObject();
        items.put("type", "string");
        items.put("enum", enumList);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type", "array");
        jsonObject.put("title", "");
        jsonObject.put("items", items);
        JSONObject properties = new JSONObject();
        properties.put(onePk.toString(), jsonObject);
        schema.put("type", "object");
        schema.put("title", "Many to many");
        schema.put("properties", properties);
        JSONObject checkboxes = new JSONObject();
        checkboxes.put("key", onePk.toString());
        checkboxes.put("titleMap", titleMap);
        checkboxes.put("notitle", true);
        form.put(checkboxes);
    }
    if (!security.hasPermissions(getPortofinoConfiguration(), getActionInstance(), AccessLevel.VIEW, ManyToManyAction.PERMISSION_UPDATE)) {
        schema.put("readonly", true);
    }
    response.put("model", model);
    response.put("schema", schema);
    response.put("form", form);
    String jsonText = response.toString(2);
    return Response.ok(jsonText).type(MediaType.APPLICATION_JSON_TYPE).encoding("UTF-8").build();
}
Also used : JSONObject(org.json.JSONObject) JavaClassAccessor(com.manydesigns.elements.reflection.JavaClassAccessor) ClassAccessor(com.manydesigns.elements.reflection.ClassAccessor) JSONArray(org.json.JSONArray) JSONObject(org.json.JSONObject) PkHelper(com.manydesigns.portofino.util.PkHelper)

Example 5 with ClassAccessor

use of com.manydesigns.elements.reflection.ClassAccessor in project Portofino by ManyDesigns.

the class DateSearchFieldTest method setupFields.

private void setupFields() {
    ClassAccessor classAccessor = JavaClassAccessor.getClassAccessor(this.getClass());
    try {
        PropertyAccessor myPropertyAccessor = classAccessor.getProperty("date");
        dateField = new DateSearchField(myPropertyAccessor);
    } catch (NoSuchFieldException e) {
        fail(e.getMessage(), e);
    }
}
Also used : PropertyAccessor(com.manydesigns.elements.reflection.PropertyAccessor) DateSearchField(com.manydesigns.elements.fields.search.DateSearchField) JavaClassAccessor(com.manydesigns.elements.reflection.JavaClassAccessor) ClassAccessor(com.manydesigns.elements.reflection.ClassAccessor)

Aggregations

ClassAccessor (com.manydesigns.elements.reflection.ClassAccessor)18 JavaClassAccessor (com.manydesigns.elements.reflection.JavaClassAccessor)14 PropertyAccessor (com.manydesigns.elements.reflection.PropertyAccessor)13 FilteredClassAccessor (com.manydesigns.elements.reflection.FilteredClassAccessor)2 BigDecimal (java.math.BigDecimal)2 FileObject (org.apache.commons.vfs2.FileObject)2 Session (org.hibernate.Session)2 JSONStringer (org.json.JSONStringer)2 FileBlob (com.manydesigns.elements.annotations.FileBlob)1 Blob (com.manydesigns.elements.blobs.Blob)1 HierarchicalBlobManager (com.manydesigns.elements.blobs.HierarchicalBlobManager)1 AbstractBlobField (com.manydesigns.elements.fields.AbstractBlobField)1 Field (com.manydesigns.elements.fields.Field)1 FileBlobField (com.manydesigns.elements.fields.FileBlobField)1 DateSearchField (com.manydesigns.elements.fields.search.DateSearchField)1 MutableHttpServletRequest (com.manydesigns.elements.servlet.MutableHttpServletRequest)1 ActionDescriptor (com.manydesigns.portofino.actions.ActionDescriptor)1 Annotation (com.manydesigns.portofino.model.Annotation)1 Model (com.manydesigns.portofino.model.Model)1 Property (com.manydesigns.portofino.model.Property)1