Search in sources :

Example 21 with RowMapper

use of com.ramussoft.jdbc.RowMapper in project ramus by Vitaliy-Yakovchuk.

the class StandardAttributesPlugin method init.

@SuppressWarnings("deprecation")
@Override
public void init(final Engine engine, final AccessRules accessor) {
    super.init(engine, accessor);
    engine.setPluginProperty(getName(), STANDARD_ATTRIBUTES_PLUGIN, this);
    if ((attributes != null) || (qualifiers != null)) {
        throw new RuntimeException("Plugin has already been inted");
    }
    qualifiers = engine.getSystemQualifier(QUALIFIERS_QUALIFIER);
    attributes = engine.getSystemQualifier(ATTRIBUTES_QUALIFIER);
    iconsQualifier = engine.getSystemQualifier(ICONS_QUALIFIER);
    historyQualifier = engine.getSystemQualifier(QUALIFIER_HISTORY);
    if (historyQualifier == null) {
        historyQualifier = engine.createSystemQualifier();
        historyQualifier.setName(QUALIFIER_HISTORY);
        historyElement = engine.createSystemAttribute(new AttributeType("Core", "Long", true));
        historyElement.setName(ATTRIBUTE_HISTORY_ELEMENT);
        engine.updateAttribute(historyElement);
        historyAttribute = engine.createSystemAttribute(new AttributeType("Core", "Long", true));
        historyAttribute.setName(ATTRIBUTE_HISTORY_ATTRIBUTE);
        engine.updateAttribute(historyAttribute);
        historyTime = engine.createSystemAttribute(new AttributeType("Core", "Date", true));
        historyTime.setName(ATTRIBUTE_HISTORY_TIME);
        engine.updateAttribute(historyTime);
        historyQualifier.getSystemAttributes().add(historyElement);
        historyQualifier.getSystemAttributes().add(historyAttribute);
        historyQualifier.getSystemAttributes().add(historyTime);
        engine.updateQualifier(historyQualifier);
    } else {
        historyElement = engine.getSystemAttribute(ATTRIBUTE_HISTORY_ELEMENT);
        historyAttribute = engine.getSystemAttribute(ATTRIBUTE_HISTORY_ATTRIBUTE);
        historyTime = engine.getSystemAttribute(ATTRIBUTE_HISTORY_TIME);
    }
    for (Qualifier qualifier : engine.getSystemQualifiers()) {
        if (qualifier.getName().startsWith(TABLE_QUALIFIER))
            tableQualifierIds.add(qualifier.getId());
    }
    if (((qualifiers == null) && (attributes != null)) || ((qualifiers != null) && (attributes == null))) {
        throw new RuntimeException("Attributes and qualifiers must inited both in the same time.");
    }
    if (qualifiers == null) {
        initQualifiers(engine);
    } else {
        loadAttributes();
    }
    iconsAttribute = engine.getSystemAttribute(ICONS_ATTRIBUTE);
    iconsQualifierLeafs = engine.getSystemAttribute(ICONS_QUALIFIER_LEAFS);
    iconsQualifierOpenFolders = engine.getSystemAttribute(ICONS_QUALIFIER_OPEN_FOLDERS);
    iconsQualifierClosedFolders = engine.getSystemAttribute(ICONS_QUALIFIER_CLOSED_FOLDERS);
    tableElementIdAttribute = engine.getSystemAttribute(TABLE_ELEMENT_ID_ATTRIBUTE);
    if (iconsQualifier == null) {
        createIconsQualifier(engine);
    }
    if (tableElementIdAttribute == null) {
        createTableElementIdAttribute(engine);
    }
    engine.setPluginProperty(getName(), ATTRIBUTES_QUALIFIER, attributes);
    engine.setPluginProperty(getName(), QUALIFIERS_QUALIFIER, qualifiers);
    engine.setPluginProperty(getName(), ATTRIBUTE_NAME, nameAttribute);
    engine.setPluginProperty(getName(), QUALIFIER_ID, aQualifierId);
    engine.setPluginProperty(getName(), ATTRIBUTE_TYPE_NAME, attributeTypeName);
    engine.setPluginProperty(getName(), ATTRIBUTE_ID, aAttributeId);
    engine.setPluginProperty(getName(), QUALIFIER_ATTRIBUTES, aList);
    engine.setPluginProperty(getName(), ICONS_QUALIFIER, iconsQualifier);
    engine.setPluginProperty(getName(), ICONS_ATTRIBUTE, iconsAttribute);
    engine.setPluginProperty(getName(), ICONS_QUALIFIER_LEAFS, iconsQualifierLeafs);
    engine.setPluginProperty(getName(), ICONS_QUALIFIER_OPEN_FOLDERS, iconsQualifierOpenFolders);
    engine.setPluginProperty(getName(), ICONS_QUALIFIER_CLOSED_FOLDERS, iconsQualifierClosedFolders);
    engine.addQualifierListener(new QualifierAdapter() {

        @Override
        public void qualifierCreated(QualifierEvent event) {
            if (!autocreateFromQualifiers)
                return;
            if (disableAutoupdate)
                return;
            if (event.isJournaled())
                return;
            synchronized (threadLocker) {
                if (Thread.currentThread() == currentThread)
                    return;
            }
            try {
                synchronized (threadLocker) {
                    currentThread = Thread.currentThread();
                }
                Engine e = event.getEngine();
                Element element = e.createElement(qualifiers.getId());
                e.setAttribute(element, aQualifierId, event.getNewQualifier().getId());
                e.setAttribute(element, nameAttribute, "");
            } finally {
                synchronized (threadLocker) {
                    currentThread = null;
                }
            }
        }

        @Override
        public void qualifierDeleted(QualifierEvent event) {
            Qualifier qualifier = event.getOldQualifier();
            if ((qualifier.isSystem()) && (qualifier.getName().startsWith(TABLE_QUALIFIER))) {
                tableQualifierIds.remove(new Long(qualifier.getId()));
            }
            if (event.isJournaled())
                return;
            if (disableAutoupdate)
                return;
            synchronized (threadLocker) {
                if (Thread.currentThread() == currentThread)
                    return;
            }
            try {
                synchronized (threadLocker) {
                    currentThread = Thread.currentThread();
                }
                Engine e = event.getEngine();
                List<Element> elements = e.findElements(qualifiers.getId(), aQualifierId, event.getOldQualifier().getId());
                if (elements.size() != 1) {
                    return;
                }
                e.deleteElement(elements.get(0).getId());
            } finally {
                synchronized (threadLocker) {
                    currentThread = null;
                }
            }
        }

        @Override
        public void qualifierUpdated(QualifierEvent event) {
            Qualifier qualifier = event.getNewQualifier();
            if ((qualifier.isSystem()) && (qualifier.getName().startsWith(TABLE_QUALIFIER)))
                tableQualifierIds.add(qualifier.getId());
            if (event.isJournaled())
                return;
            if (disableAutoupdate)
                return;
            List<Attribute> attributesToRemove = getAttributesToRemove(event);
            List<Element> allElements = null;
            for (Attribute attribute : attributesToRemove) {
                if (attribute.getAttributeType().toString().equals("Core.Table")) {
                    if (allElements == null) {
                        allElements = engine.getElements(event.getNewQualifier().getId());
                    }
                    for (Element element : allElements) {
                        for (Element element2 : getTableElements(engine, attribute, element)) {
                            engine.deleteElement(element2.getId());
                        }
                    }
                }
            }
            if (event.getNewQualifier().isSystem())
                return;
            synchronized (threadLocker) {
                if (Thread.currentThread() == currentThread)
                    return;
            }
            try {
                synchronized (threadLocker) {
                    currentThread = Thread.currentThread();
                }
                Engine e = event.getEngine();
                List<Element> elements = e.findElements(qualifiers.getId(), aQualifierId, event.getNewQualifier().getId());
                if (elements.size() != 1) {
                    // .println("Not regidtered qualifier was updated, or data integrity wrong.");
                    return;
                }
                e.setAttribute(elements.get(0), nameAttribute, event.getNewQualifier().getName());
                List<Attribute> list = event.getNewQualifier().getAttributes();
                List<ElementListPersistent> pList = new ArrayList<ElementListPersistent>();
                for (Attribute a : list) {
                    if (isSystem(a.getAttributeType()))
                        continue;
                    List<Element> ems = e.findElements(attributes.getId(), aAttributeId, a.getId());
                    if (ems.size() != 1) {
                        throw new RuntimeException("Fatal error, not registered attribute was removed, or data integrity wrong.");
                    }
                    pList.add(new ElementListPersistent(elements.get(0).getId(), ems.get(0).getId()));
                }
                e.setAttribute(elements.get(0), aList, pList);
            } finally {
                synchronized (threadLocker) {
                    currentThread = null;
                }
            }
        }

        private List<Attribute> getAttributesToRemove(QualifierEvent event) {
            List<Attribute> res = new ArrayList<Attribute>(0);
            diff(event.getOldQualifier().getAttributes(), event.getNewQualifier().getAttributes(), res);
            diff(event.getOldQualifier().getSystemAttributes(), event.getNewQualifier().getSystemAttributes(), res);
            return res;
        }

        private void diff(List<Attribute> attributes, List<Attribute> attributes2, List<Attribute> res) {
            for (Attribute attribute : attributes) if (attributes2.indexOf(attribute) < 0) {
                res.add(attribute);
            }
        }
    });
    engine.addAttributeListener(new AttributeAdapter() {

        @Override
        public void attributeCreated(AttributeEvent event) {
            if (event.isJournaled())
                return;
            if (disableAutoupdate)
                return;
            if (isSystem(event.getAttribute().getAttributeType()))
                return;
            synchronized (threadLocker) {
                if (Thread.currentThread() == currentThread)
                    return;
            }
            try {
                synchronized (threadLocker) {
                    currentThread = Thread.currentThread();
                }
                long lastId = getLastId();
                HierarchicalPersistent hp = new HierarchicalPersistent();
                hp.setIconId(-1l);
                hp.setParentElementId(-1l);
                hp.setPreviousElementId(lastId);
                Engine e = event.getEngine();
                Element element = e.createElement(attributes.getId());
                e.setAttribute(element, aAttributeId, event.getAttribute().getId());
                e.setAttribute(element, getHierarchicalAttribute(engine), hp);
                e.setAttribute(element, nameAttribute, "");
                e.setAttribute(element, attributeTypeName, event.getAttribute().getAttributeType().toString());
            } finally {
                synchronized (threadLocker) {
                    currentThread = null;
                }
            }
        }

        private long getLastId() {
            try {
                if (engine.getDeligate() instanceof IEngineImpl) {
                    IEngineImpl impl = ((IEngineImpl) engine.getDeligate());
                    String prefix = impl.getPrefix();
                    String sql = "SELECT element_id FROM " + prefix + "elements WHERE element_id NOT IN (SELECT previous_element_id FROM " + prefix + "attribute_hierarchicals) AND qualifier_id=?";
                    JDBCTemplate template = impl.getTemplate();
                    Object res = template.queryForObject(sql, new RowMapper() {

                        @Override
                        public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
                            return rs.getLong(1);
                        }
                    }, attributes.getId(), true);
                    if (res != null)
                        return ((Long) res).longValue();
                    return -1l;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            List<Attribute> attrs = new ArrayList<Attribute>();
            attrs.add(getHierarchicalAttribute(engine));
            Hashtable<Element, Object[]> hash = engine.getElements(attributes, attrs);
            Element element = null;
            for (Element e1 : hash.keySet()) {
                element = e1;
                for (Object[] objects : hash.values()) {
                    HierarchicalPersistent hp = (HierarchicalPersistent) objects[0];
                    if (hp != null) {
                        if (hp.getPreviousElementId() == element.getId()) {
                            element = null;
                            break;
                        }
                    }
                }
                if (element != null)
                    break;
            }
            if (element == null)
                return -1l;
            return element.getId();
        }

        @Override
        public void attributeDeleted(AttributeEvent event) {
            if (event.isJournaled())
                return;
            if (disableAutoupdate)
                return;
            if (((Attribute) event.getOldValue()).getAttributeType().toString().equals("Core.Table")) {
                Qualifier qualifier = getTableQualifierForAttribute(engine, (Attribute) event.getOldValue());
                engine.deleteQualifier(qualifier.getId());
            }
            if (isSystem(((Attribute) event.getOldValue()).getAttributeType()))
                return;
            synchronized (threadLocker) {
                if (Thread.currentThread() == currentThread)
                    return;
            }
            try {
                synchronized (threadLocker) {
                    currentThread = Thread.currentThread();
                }
                Engine e = event.getEngine();
                List<Element> elements = e.findElements(attributes.getId(), aAttributeId, event.getAttribute().getId());
                if (elements.size() != 1) {
                    throw new RuntimeException("Fatal error, not registered qualifier was removed, or data integrity wrong.");
                }
                e.deleteElement(elements.get(0).getId());
            } finally {
                synchronized (threadLocker) {
                    currentThread = null;
                }
            }
        }

        @Override
        public void attributeUpdated(AttributeEvent event) {
            if (event.isJournaled())
                return;
            if (disableAutoupdate)
                return;
            if (isSystem(event.getAttribute().getAttributeType()))
                return;
            synchronized (threadLocker) {
                if (Thread.currentThread() == currentThread)
                    return;
            }
            try {
                synchronized (threadLocker) {
                    currentThread = Thread.currentThread();
                }
                Engine e = event.getEngine();
                List<Element> elements = e.findElements(attributes.getId(), aAttributeId, event.getAttribute().getId());
                if (elements.size() != 1) {
                    return;
                // throw new RuntimeException(
                // "Fatal error, not registered attribute was removed, or data integrity wrong.");
                }
                e.setAttribute(elements.get(0), nameAttribute, event.getAttribute().getName());
            } finally {
                synchronized (threadLocker) {
                    currentThread = null;
                }
            }
        }

        @Override
        public void beforeAttributeDeleted(AttributeEvent event) {
            if (event.isJournaled())
                return;
            if (disableAutoupdate)
                return;
            Attribute attribute = event.getAttribute();
            Engine engine = event.getEngine();
            if (attribute.getAttributeType().toString().equals("Core.Table")) {
                Qualifier qualifier = getTableQualifierForAttribute(engine, attribute);
                if (qualifier != null) {
                    for (Element element : engine.getElements(qualifier.getId())) {
                        engine.deleteElement(element.getId());
                    }
                }
            }
        }
    });
    engine.addElementAttributeListener(qualifiers, new ElementAttributeListener() {

        @SuppressWarnings("unchecked")
        @Override
        public void attributeChanged(AttributeEvent event) {
            if (event.isJournaled())
                return;
            if (disableAutoupdate)
                return;
            if (event.getAttribute().equals(aQualifierId)) {
                Engine e = event.getEngine();
                Qualifier q = e.getQualifier((Long) event.getNewValue());
                List<Element> elements = e.findElements(qualifiers.getId(), aQualifierId, q.getId());
                if (elements.size() != 1) {
                    // .println("Not regidtered qualifier was updated, or data integrity wrong.");
                    return;
                }
                List<Attribute> list = q.getAttributes();
                List<ElementListPersistent> pList = new ArrayList<ElementListPersistent>();
                for (Attribute a : list) {
                    List<Element> ems = e.findElements(attributes.getId(), aAttributeId, a.getId());
                    if (ems.size() != 1) {
                        throw new RuntimeException("Fatal error, not registered attribute was removed, or data integrity wrong.");
                    }
                    pList.add(new ElementListPersistent(elements.get(0).getId(), ems.get(0).getId()));
                }
                Element element = elements.get(0);
                element.setQualifierId(qualifiers.getId());
                e.setAttribute(element, aList, pList);
            }
            synchronized (threadLocker) {
                if (Thread.currentThread() == currentThread)
                    return;
            }
            Engine e = event.getEngine();
            try {
                synchronized (threadLocker) {
                    currentThread = Thread.currentThread();
                }
                if (event.getAttribute().equals(nameAttribute)) {
                    Qualifier qualifier = e.getQualifier((Long) e.getAttribute(event.getElement(), aQualifierId));
                    qualifier.setName((String) event.getNewValue());
                    e.updateQualifier(qualifier);
                } else if (event.getAttribute().equals(aList)) {
                    Long attribute = (Long) e.getAttribute(event.getElement(), aQualifierId);
                    if (attribute == null)
                        return;
                    Qualifier qualifier = e.getQualifier(attribute);
                    List<ElementListPersistent> list = (List<ElementListPersistent>) e.getAttribute(event.getElement(), aList);
                    List<Attribute> attrs = new ArrayList<Attribute>();
                    for (ElementListPersistent p : list) {
                        Element attr = e.getElement(p.getElement2Id());
                        Attribute a = e.getAttribute(((Long) e.getAttribute(attr, aAttributeId)));
                        attrs.add(a);
                    }
                    List<Attribute> al = qualifier.getAttributes();
                    for (int i = al.size() - 1; i >= 0; i--) {
                        if (attrs.indexOf(al.get(i)) < 0) {
                            al.remove(i);
                        }
                    }
                    for (Attribute a : attrs) {
                        if (al.indexOf(a) < 0)
                            al.add(a);
                    }
                    e.updateQualifier(qualifier);
                }
            } finally {
                synchronized (threadLocker) {
                    currentThread = null;
                }
            }
        }
    });
    engine.addElementAttributeListener(attributes, new ElementAttributeListener() {

        @Override
        public void attributeChanged(AttributeEvent event) {
            if (event.isJournaled())
                return;
            if (disableAutoupdate)
                return;
            synchronized (threadLocker) {
                if (Thread.currentThread() == currentThread)
                    return;
            }
            Engine e = event.getEngine();
            try {
                synchronized (threadLocker) {
                    currentThread = Thread.currentThread();
                }
                if (event.getAttribute().equals(nameAttribute)) {
                    Attribute attribute = e.getAttribute((Long) e.getAttribute(event.getElement(), aAttributeId));
                    attribute.setName((String) event.getNewValue());
                    e.updateAttribute(attribute);
                }
            } finally {
                synchronized (threadLocker) {
                    currentThread = null;
                }
            }
        }
    });
    engine.addElementAttributeListener(null, new ElementAttributeListener() {

        @Override
        public void attributeChanged(AttributeEvent event) {
            if (disableAutoupdate)
                return;
            Element element = event.getElement();
            if (element == null)
                return;
            try {
                if (tableQualifierIds.indexOf(new Long(element.getQualifierId())) >= 0) {
                    Object parentElementId;
                    if (event.getAttribute().equals(tableElementIdAttribute))
                        parentElementId = event.getNewValue();
                    else
                        parentElementId = engine.getAttribute(element, tableElementIdAttribute);
                    if (parentElementId != null) {
                        Qualifier table = engine.getQualifier(element.getQualifierId());
                        Attribute attribute = getAttributeForTable(engine, table);
                        Element parent = engine.getElement((Long) parentElementId);
                        AttributeEvent event2 = new AttributeEvent(engine, parent, attribute, null, null, event.isJournaled());
                        for (ElementAttributeListener listener : engine.getElementAttributeListeners(-1)) listener.attributeChanged(event2);
                        for (ElementAttributeListener listener : engine.getElementAttributeListeners(parent.getQualifierId())) listener.attributeChanged(event2);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (event.isJournaled())
                return;
            List<Long> attrs = historyQualifiers.get(element.getQualifierId());
            if (attrs != null)
                if (attrs.indexOf(event.getAttribute().getId()) >= 0) {
                    Element data = engine.createElement(historyQualifier.getId());
                    engine.setAttribute(data, event.getAttribute(), event.getNewValue());
                    engine.setAttribute(data, historyElement, element.getId());
                    engine.setAttribute(data, historyAttribute, event.getAttribute().getId());
                    engine.setAttribute(data, historyTime, new Date());
                }
        }
    });
    engine.addElementListener(qualifiers, new ElementAdapter() {

        @Override
        public void elementCreated(ElementEvent event) {
            if (event.isJournaled())
                return;
            if (disableAutoupdate)
                return;
            synchronized (threadLocker) {
                if (Thread.currentThread() == currentThread)
                    return;
            }
            Engine e = event.getEngine();
            try {
                synchronized (threadLocker) {
                    currentThread = Thread.currentThread();
                }
                Qualifier qualifier = e.createQualifier();
                e.setAttribute(event.getNewElement(), aQualifierId, qualifier.getId());
            } finally {
                synchronized (threadLocker) {
                    currentThread = null;
                }
            }
        }

        @Override
        public void beforeElementDeleted(ElementEvent event) {
            if (event.isJournaled())
                return;
            if (disableAutoupdate)
                return;
            synchronized (threadLocker) {
                if (Thread.currentThread() == currentThread)
                    return;
            }
            Engine e = event.getEngine();
            long qualifierId = event.getOldElement().getQualifierId();
            if ((qualifierId != qualifiers.getId()) && (qualifierId != attributes.getId()))
                return;
            try {
                synchronized (threadLocker) {
                    currentThread = Thread.currentThread();
                }
                if (qualifierId == qualifiers.getId()) {
                    Object attribute = e.getAttribute(event.getOldElement(), aQualifierId);
                    if (attribute != null)
                        e.deleteQualifier((Long) attribute);
                } else {
                    throw new RuntimeException("Element for attribute can not be deleted");
                }
            } finally {
                synchronized (threadLocker) {
                    currentThread = null;
                }
            }
        }
    });
    engine.addElementListener(null, new ElementAdapter() {

        @Override
        public void beforeElementDeleted(ElementEvent event) {
            if (disableAutoupdate)
                return;
            Element element = event.getOldElement();
            if (element == null)
                return;
            try {
                if (tableQualifierIds.indexOf(new Long(element.getQualifierId())) >= 0) {
                    Object parentElementId;
                    parentElementId = engine.getAttribute(element, tableElementIdAttribute);
                    if (parentElementId != null) {
                        Qualifier table = engine.getQualifier(element.getQualifierId());
                        Attribute attribute = getAttributeForTable(engine, table);
                        Element parent = engine.getElement((Long) parentElementId);
                        AttributeEvent event2 = new AttributeEvent(engine, parent, attribute, null, null, event.isJournaled());
                        for (ElementAttributeListener listener : engine.getElementAttributeListeners(-1)) listener.attributeChanged(event2);
                        for (ElementAttributeListener listener : engine.getElementAttributeListeners(parent.getQualifierId())) listener.attributeChanged(event2);
                    }
                } else {
                    Qualifier qualifier = engine.getQualifier(element.getQualifierId());
                    for (Attribute attribute : qualifier.getAttributes()) {
                        if (attribute.getAttributeType().toString().equals("Core.Table")) {
                            for (Element element2 : getTableElements(engine, attribute, element)) {
                                engine.deleteElement(element2.getId());
                            }
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            List<Long> attrs = historyQualifiers.get(element.getQualifierId());
            if (attrs != null) {
                List<Element> list = engine.findElements(historyQualifier.getId(), historyElement, element.getId());
                for (Element element2 : list) engine.deleteElement(element2.getId());
            }
        }
    });
    engine.addStreamListener(new StreamAdapter() {

        @Override
        public void streamUpdated(StreamEvent event) {
            if (event.isJournaled())
                return;
            String path = event.getPath();
            if (path.equals(PROPERTIES)) {
                loadHistoryQualifiers((!disableAutoupdate) && (!event.isJournaled()));
            }
        }
    });
    loadHistoryQualifiers(false);
}
Also used : ElementAdapter(com.ramussoft.common.event.ElementAdapter) ElementListPersistent(com.ramussoft.core.attribute.simple.ElementListPersistent) Attribute(com.ramussoft.common.Attribute) ElementAttributeListener(com.ramussoft.common.event.ElementAttributeListener) Element(com.ramussoft.common.Element) ArrayList(java.util.ArrayList) QualifierEvent(com.ramussoft.common.event.QualifierEvent) AttributeEvent(com.ramussoft.common.event.AttributeEvent) JDBCTemplate(com.ramussoft.jdbc.JDBCTemplate) AttributeType(com.ramussoft.common.AttributeType) ResultSet(java.sql.ResultSet) Qualifier(com.ramussoft.common.Qualifier) ArrayList(java.util.ArrayList) List(java.util.List) Engine(com.ramussoft.common.Engine) IEngine(com.ramussoft.common.IEngine) RowMapper(com.ramussoft.jdbc.RowMapper) QualifierAdapter(com.ramussoft.common.event.QualifierAdapter) Hashtable(java.util.Hashtable) StreamEvent(com.ramussoft.common.event.StreamEvent) ElementEvent(com.ramussoft.common.event.ElementEvent) SQLException(java.sql.SQLException) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Date(java.util.Date) StreamAdapter(com.ramussoft.common.event.StreamAdapter) IEngineImpl(com.ramussoft.core.impl.IEngineImpl) HierarchicalPersistent(com.ramussoft.core.attribute.simple.HierarchicalPersistent) AttributeAdapter(com.ramussoft.common.event.AttributeAdapter)

Example 22 with RowMapper

use of com.ramussoft.jdbc.RowMapper in project ramus by Vitaliy-Yakovchuk.

the class FileIEngineImpl method setStream.

@SuppressWarnings("unchecked")
@Override
public void setStream(String path, byte[] bytes) {
    if (!path.startsWith("/"))
        throw new RuntimeException("Path should start with / symbol.");
    long branchId = getActiveBranchId();
    if (branchId == 0l || !path.startsWith("/elements/")) {
        if (bytes == null) {
            if (deleteStreamBytes(path))
                template.update("DELETE FROM " + prefix + "streams WHERE STREAM_ID=?", new Object[] { path }, true);
            return;
        }
        writeStream(path, bytes);
        List<String> list = template.query("SELECT * FROM " + prefix + "streams WHERE STREAM_ID=?", new RowMapper() {

            @Override
            public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
                return rs.getString("STREAM_ID");
            }
        }, new Object[] { path }, true);
        if (list.size() == 0) {
            template.update("INSERT INTO " + prefix + "streams (STREAM_ID) VALUES (?)", new Object[] { path }, true);
        }
    } else {
        List<Long> list = template.query("SELECT * FROM " + prefix + "streams WHERE STREAM_ID=? AND created_branch_id IN " + "(SELECT MAX(created_branch_id) FROM " + prefix + "streams WHERE STREAM_ID=? AND created_branch_id <=? AND removed_branch_id>?", new RowMapper() {

            @Override
            public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
                return rs.getLong("created_branch_id");
            }
        }, new Object[] { path, path, branchId, branchId }, false);
        if (list.size() > 0) {
            long storedBranchId = list.get(0);
            if (storedBranchId == branchId) {
                if (bytes == null) {
                    template.update("DELETE FROM " + prefix + "streams WHERE STREAM_ID=? AND created_branch_id=?", new Object[] { path, branchId }, false);
                    deleteStreamBytes("/branches/" + branchId + path);
                } else
                    writeStream("/branches/" + branchId + path, bytes);
            } else {
                template.update("UPDATE " + prefix + "streams SET removed_branch_id=? WHERE STREAM_ID=? AND created_branch_id=?", new Object[] { branchId, path, storedBranchId }, false);
                if (bytes != null) {
                    template.update("INSERT INTO " + prefix + "streams (STREAM_ID, created_branch_id) VALUES (?, ?)", new Object[] { path, branchId }, true);
                    writeStream("/branches/" + branchId + path, bytes);
                }
            }
        } else {
            if (bytes != null) {
                template.update("INSERT INTO " + prefix + "streams (STREAM_ID, created_branch_id) VALUES (?, ?)", new Object[] { path, branchId }, true);
                writeStream("/branches/" + branchId + path, bytes);
            }
        }
    }
}
Also used : SQLException(java.sql.SQLException) ResultSet(java.sql.ResultSet) RowMapper(com.ramussoft.jdbc.RowMapper)

Example 23 with RowMapper

use of com.ramussoft.jdbc.RowMapper in project ramus by Vitaliy-Yakovchuk.

the class FileIEngineImpl method getPluginNames.

@SuppressWarnings("unchecked")
private PluginName[] getPluginNames(List<Plugin> plugins) {
    List<PluginName> data = new ArrayList<PluginName>(plugins.size());
    List<AttributeType> types = template.query("SELECT attribute_type_plugin_name, attribute_type_name from " + prefix + "attributes GROUP BY attribute_type_plugin_name, attribute_type_name", new RowMapper() {

        @Override
        public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
            return new AttributeType(rs.getString(1).trim(), rs.getString(2).trim());
        }
    });
    for (int i = 0; i < plugins.size(); i++) {
        Plugin plugin = plugins.get(i);
        String name = plugin.getName();
        if (plugin instanceof AttributePlugin) {
            AttributePlugin attributePlugin = (AttributePlugin) plugin;
            AttributeType type = new AttributeType(attributePlugin.getName(), attributePlugin.getTypeName());
            if (types.indexOf(type) >= 0) {
                name = "Attribute." + name + "." + attributePlugin.getTypeName();
                data.add(new PluginName(plugin, name));
            }
        } else {
            data.add(new PluginName(plugin, name));
        }
    }
    return data.toArray(new PluginName[data.size()]);
}
Also used : AttributePlugin(com.ramussoft.common.attribute.AttributePlugin) SQLException(java.sql.SQLException) ResultSet(java.sql.ResultSet) RowMapper(com.ramussoft.jdbc.RowMapper) AttributePlugin(com.ramussoft.common.attribute.AttributePlugin)

Example 24 with RowMapper

use of com.ramussoft.jdbc.RowMapper in project ramus by Vitaliy-Yakovchuk.

the class FileIEngineImpl method deleteStream.

@Override
public boolean deleteStream(String path) {
    long branchId = getActiveBranch();
    List<Long> list = template.query("SELECT * FROM " + prefix + "streams WHERE STREAM_ID=? AND created_branch_id IN " + "(SELECT MAX(created_branch_id) FROM " + prefix + "streams WHERE STREAM_ID=? AND created_branch_id<=?) AND removed_branch_id>?", new RowMapper() {

        @Override
        public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
            return rs.getLong("created_branch_id");
        }
    }, new Object[] { path, path, branchId, branchId }, false);
    if (list.size() > 0) {
        long storedBranchId = list.get(0);
        if (storedBranchId == branchId) {
            try {
                return deleteStreamBytes(path);
            } finally {
                template.update("DELETE FROM " + prefix + "streams WHERE STREAM_ID=? AND created_branch_id=?", new Object[] { path, branchId }, false);
            }
        } else {
            template.update("UPDATE " + prefix + "streams SET removed_branch_id=? WHERE STREAM_ID=? AND created_branch_id=?", new Object[] { branchId, path, storedBranchId }, false);
        }
    }
    return false;
}
Also used : SQLException(java.sql.SQLException) ResultSet(java.sql.ResultSet) RowMapper(com.ramussoft.jdbc.RowMapper)

Example 25 with RowMapper

use of com.ramussoft.jdbc.RowMapper in project ramus by Vitaliy-Yakovchuk.

the class IEngineImpl method getEListFixed.

private List<Persistent>[] getEListFixed(final PersistentRow row, final Class<? extends Persistent> clazz, final PersistentWrapper wrapper, ArrayList<String> paramFields, ArrayList<Object> params, long branchId) {
    String sqlBranchCondition = " AND value_branch_id<=? " + "AND (removed_branch_id > ? OR removed_branch_id is NULL)";
    StringBuffer sb = new StringBuffer("SELECT * FROM " + row.getTableName());
    if (params.size() > 0) {
        sb.append(" WHERE ");
    }
    boolean first = true;
    for (int j = 0; j < params.size(); j++) {
        if (first) {
            first = false;
        } else {
            sb.append(" AND ");
        }
        sb.append(paramFields.get(j));
        sb.append("=?");
    }
    sb.append(sqlBranchCondition);
    params.add(branchId);
    params.add(branchId);
    return new List[] { template.query(sb.toString(), new RowMapper() {

        @Override
        public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
            try {
                Persistent persistent = clazz.newInstance();
                for (PersistentField field : row.getFields()) {
                    wrapper.setDatabaseField(persistent, field, rs);
                }
                return persistent;
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            throw new RuntimeException();
        }
    }, params.toArray(), true) };
}
Also used : PersistentField(com.ramussoft.common.persistent.PersistentField) SQLException(java.sql.SQLException) Persistent(com.ramussoft.common.persistent.Persistent) ResultSet(java.sql.ResultSet) ArrayList(java.util.ArrayList) List(java.util.List) FindObject(com.ramussoft.common.attribute.FindObject) RowMapper(com.ramussoft.jdbc.RowMapper)

Aggregations

RowMapper (com.ramussoft.jdbc.RowMapper)30 ResultSet (java.sql.ResultSet)30 SQLException (java.sql.SQLException)22 FindObject (com.ramussoft.common.attribute.FindObject)14 ArrayList (java.util.ArrayList)14 Attribute (com.ramussoft.common.Attribute)11 List (java.util.List)11 Qualifier (com.ramussoft.common.Qualifier)7 JDBCTemplate (com.ramussoft.jdbc.JDBCTemplate)7 Element (com.ramussoft.common.Element)6 PersistentRow (com.ramussoft.common.persistent.PersistentRow)6 IEngineImpl (com.ramussoft.core.impl.IEngineImpl)6 Hashtable (java.util.Hashtable)6 Engine (com.ramussoft.common.Engine)5 AttributePlugin (com.ramussoft.common.attribute.AttributePlugin)5 Persistent (com.ramussoft.common.persistent.Persistent)5 PersistentField (com.ramussoft.common.persistent.PersistentField)5 PersistentWrapper (com.ramussoft.common.persistent.PersistentWrapper)4 DeleteStatus (com.ramussoft.common.DeleteStatus)3 IEngine (com.ramussoft.common.IEngine)3