Search in sources :

Example 1 with TableAccessor

use of com.manydesigns.portofino.reflection.TableAccessor in project Portofino by ManyDesigns.

the class PersistenceTest method testAutoIncrementGenerator.

public void testAutoIncrementGenerator() {
    Map<String, Object> supplierData = new HashMap<>();
    supplierData.put("status", "99");
    supplierData.put("name", "Giampiero");
    Object supplier = makeEntity("jpetstore.public.Supplier", supplierData);
    Session session = persistence.getSession("jpetstore");
    session.save("supplier", supplier);
    session.getTransaction().commit();
    Table table = DatabaseLogic.findTableByName(persistence.getModel(), "jpetstore", "PUBLIC", "SUPPLIER");
    assertNotNull(table);
    TableAccessor tableAccessor = new TableAccessor(table);
    TableCriteria criteria = new TableCriteria(table);
    final BigInteger expectedId = new BigInteger("3");
    try {
        criteria.eq(tableAccessor.getProperty("suppid"), expectedId);
        List<?> listObjs = QueryUtils.getObjects(session, criteria, null, null);
        assertEquals(1, listObjs.size());
        Object supp = listObjs.get(0);
        String name = get(supp, "name");
        assertEquals("Giampiero", name);
    } catch (NoSuchFieldException e) {
        fail(e.getMessage(), e);
    }
}
Also used : TableAccessor(com.manydesigns.portofino.reflection.TableAccessor) TableCriteria(com.manydesigns.portofino.persistence.TableCriteria) BigInteger(java.math.BigInteger) FileObject(org.apache.commons.vfs2.FileObject) Session(org.hibernate.Session)

Example 2 with TableAccessor

use of com.manydesigns.portofino.reflection.TableAccessor in project Portofino by ManyDesigns.

the class PersistenceTest method testSearchAndUpdateCategorie.

public void testSearchAndUpdateCategorie() {
    Table table = DatabaseLogic.findTableByName(persistence.getModel(), "jpetstore", "PUBLIC", "CATEGORY");
    assertNotNull(table);
    TableAccessor tableAccessor = new TableAccessor(table);
    TableCriteria tableCriteria = new TableCriteria(table);
    Session session = persistence.getSession("jpetstore");
    CriteriaQuery<Object> criteria = QueryUtils.createCriteria(session, "category").query;
    List<Object> resultCat = new ArrayList<>(session.createQuery(criteria).list());
    int sizeCat = resultCat.size();
    assertEquals("categorie", 5, sizeCat);
    Object categoria0 = findCategory(tableAccessor, tableCriteria);
    assertEquals("Fish", get(categoria0, "name"));
    set(categoria0, "name", "Pesciu");
    session.update("category", categoria0);
    session.getTransaction().commit();
    persistence.closeSessions();
    // Controllo l'aggiornamento e riporto le cose come stavano
    tableCriteria = new TableCriteria(table);
    categoria0 = findCategory(tableAccessor, tableCriteria);
    assertEquals("Pesciu", get(categoria0, "name"));
    set(categoria0, "name", "Fish");
    session = persistence.getSession("jpetstore");
    session.update("category", categoria0);
    session.getTransaction().commit();
    persistence.closeSessions();
}
Also used : TableAccessor(com.manydesigns.portofino.reflection.TableAccessor) TableCriteria(com.manydesigns.portofino.persistence.TableCriteria) FileObject(org.apache.commons.vfs2.FileObject) Session(org.hibernate.Session)

Example 3 with TableAccessor

use of com.manydesigns.portofino.reflection.TableAccessor in project Portofino by ManyDesigns.

the class ModelBasedRealm method saveSelfRegisteredUser.

public String[] saveSelfRegisteredUser(Object user) throws RegistrationException {
    if (StringUtils.isEmpty(userTokenProperty)) {
        throw new UnsupportedOperationException("Token property not configured.");
    }
    User theUser = (User) user;
    Session session = persistence.getSession(usersTable.getDatabaseName());
    TableAccessor accessor = persistence.getTableAccessor(usersTable);
    Object persistentUser = accessor.newInstance();
    setUserProperty(persistentUser, userNameProperty, theUser.username);
    setUserProperty(persistentUser, userPasswordProperty, encryptPassword(theUser.password));
    if (!StringUtils.isEmpty(userEmailProperty)) {
        setUserProperty(persistentUser, userEmailProperty, theUser.email);
    }
    String token = RandomUtil.createRandomId(20);
    setUserProperty(persistentUser, userTokenProperty, token);
    try {
        session.save(usersTable.getActualEntityName(), persistentUser);
        session.flush();
    } catch (ConstraintViolationException e) {
        throw new ExistingUserException(e);
    }
    session.getTransaction().commit();
    return new String[] { token, theUser.email };
}
Also used : TableAccessor(com.manydesigns.portofino.reflection.TableAccessor) ConstraintViolationException(org.hibernate.exception.ConstraintViolationException) Session(org.hibernate.Session)

Example 4 with TableAccessor

use of com.manydesigns.portofino.reflection.TableAccessor in project Portofino by ManyDesigns.

the class ModelBasedRealm method getUserById.

public Serializable getUserById(String encodedId) {
    TableAccessor accessor = persistence.getTableAccessor(usersTable);
    Serializable id = (Serializable) accessor.getIdStrategy().getPrimaryKey(encodedId);
    Session session = persistence.getSession(usersTable.getActualEntityName());
    return (Serializable) QueryUtils.getObjectByPk(session, accessor, id);
}
Also used : Serializable(java.io.Serializable) TableAccessor(com.manydesigns.portofino.reflection.TableAccessor) Session(org.hibernate.Session)

Example 5 with TableAccessor

use of com.manydesigns.portofino.reflection.TableAccessor in project Portofino by ManyDesigns.

the class ModelSelectionProviderSupport method createHQLOptionProvider.

protected OptionProvider createHQLOptionProvider(DatabaseSelectionProvider selectionProvider, String name, String databaseName, String hql) {
    Database database = DatabaseLogic.findDatabaseByName(persistence.getModel(), databaseName);
    Table table = QueryUtils.getTableFromQueryString(database, hql);
    if (table == null) {
        logger.error("Selection provider {} has a HQL query that " + "refers to an entity that does not exist ({})", name, hql);
        return null;
    }
    return new MemoizingOptionProvider(() -> {
        String entityName = table.getActualEntityName();
        Session session = persistence.getSession(databaseName);
        QueryStringWithParameters queryWithParameters = QueryUtils.mergeQuery(hql, null, this);
        Collection<Object> objects = getFromQueryCache(selectionProvider, queryWithParameters);
        if (objects == null) {
            String queryString = queryWithParameters.getQueryString();
            Object[] parameters = queryWithParameters.getParameters();
            logger.debug("Query not in cache: {}", queryString);
            try {
                objects = QueryUtils.runHqlQuery(session, queryString, parameters);
            } catch (Exception e) {
                logger.error("Exception in populating selection provider " + name, e);
                return null;
            }
            putInQueryCache(selectionProvider, queryWithParameters, objects);
        }
        TableAccessor tableAccessor = persistence.getTableAccessor(databaseName, entityName);
        ShortName shortNameAnnotation = tableAccessor.getAnnotation(ShortName.class);
        TextFormat[] textFormats = null;
        // L'ordinamento e' usato solo in caso di chiave singola
        if (shortNameAnnotation != null && tableAccessor.getKeyProperties().length == 1) {
            textFormats = new TextFormat[] { OgnlTextFormat.create(shortNameAnnotation.value()) };
        }
        final TextFormat[] actualTextFormats = textFormats;
        Stream<OptionProvider.Option> optionStream = objects.stream().map(o -> SelectionProviderLogic.getOption(name, tableAccessor.getKeyProperties(), actualTextFormats, o));
        if (selectionProvider instanceof ForeignKey) {
            optionStream = optionStream.sorted(DefaultSelectionProvider.OPTION_COMPARATOR_BY_LABEL);
        }
        return optionStream.collect(Collectors.toList());
    });
}
Also used : ShortName(com.manydesigns.elements.annotations.ShortName) QueryStringWithParameters(com.manydesigns.elements.text.QueryStringWithParameters) TableAccessor(com.manydesigns.portofino.reflection.TableAccessor) TextFormat(com.manydesigns.elements.text.TextFormat) OgnlTextFormat(com.manydesigns.elements.text.OgnlTextFormat) Session(org.hibernate.Session)

Aggregations

TableAccessor (com.manydesigns.portofino.reflection.TableAccessor)12 Session (org.hibernate.Session)9 TableCriteria (com.manydesigns.portofino.persistence.TableCriteria)4 PropertyAccessor (com.manydesigns.elements.reflection.PropertyAccessor)3 FileObject (org.apache.commons.vfs2.FileObject)3 ShortName (com.manydesigns.elements.annotations.ShortName)2 OgnlTextFormat (com.manydesigns.elements.text.OgnlTextFormat)2 QueryStringWithParameters (com.manydesigns.elements.text.QueryStringWithParameters)2 TextFormat (com.manydesigns.elements.text.TextFormat)2 JSONObject (org.json.JSONObject)2 SelectField (com.manydesigns.elements.fields.SelectField)1 OgnlHqlFormat (com.manydesigns.elements.text.OgnlHqlFormat)1 Model (com.manydesigns.portofino.model.Model)1 ConfigurationClass (com.manydesigns.portofino.resourceactions.annotations.ConfigurationClass)1 SelectionProviderReference (com.manydesigns.portofino.resourceactions.m2m.configuration.SelectionProviderReference)1 Serializable (java.io.Serializable)1 BigInteger (java.math.BigInteger)1 CriteriaQuery (javax.persistence.criteria.CriteriaQuery)1 JSQLParserException (net.sf.jsqlparser.JSQLParserException)1 Alias (net.sf.jsqlparser.expression.Alias)1