Example usage for org.springframework.jdbc.core JdbcTemplate update

List of usage examples for org.springframework.jdbc.core JdbcTemplate update

Introduction

In this page you can find the example usage for org.springframework.jdbc.core JdbcTemplate update.

Prototype

@Override
    public int update(PreparedStatementCreator psc) throws DataAccessException 

Source Link

Usage

From source file:ca.nrc.cadc.vos.server.NodeDAOTest.java

@Test
public void testDeleteDelta() {

    log.debug("testDeleteDelta - START");
    try {//from   www  .j  av  a 2s. c  o  m
        DBConfig dbConfig = new DBConfig();
        ConnectionConfig connConfig = dbConfig.getConnectionConfig(SERVER, DATABASE);
        this.dataSource = DBUtil.getDataSource(connConfig);
        NodeSchema ns = new NodeSchema("Node", "NodeProperty", true); // TOP
        this.nodeDAO = new NodeDAO(dataSource, ns, VOS_AUTHORITY, new X500IdentityManager(), DELETED_NODES);

        ContainerNode rootContainer = (ContainerNode) nodeDAO.getPath(HOME_CONTAINER);
        log.debug("ROOT: " + rootContainer);
        Assert.assertNotNull(rootContainer);

        String basePath = "/" + HOME_CONTAINER + "/";

        // Create a container node
        String containerPath = basePath + getNodeName("delta-test2");
        ContainerNode containerNode = this.getCommonContainerNode(containerPath);
        containerNode.setParent(rootContainer);
        containerNode = (ContainerNode) nodeDAO.put(containerNode, owner);

        // Create a data node
        String dataPath = containerNode.getUri().getPath() + "/" + "dataNode" + System.currentTimeMillis();
        DataNode dataNode = getCommonDataNode(dataPath);
        dataNode.setParent(containerNode);
        nodeDAO.put(dataNode, owner);

        // manually set the nodeSize
        JdbcTemplate jdbc = new JdbcTemplate(dataSource);
        String sql = "update Node set contentLength=2 where name='" + dataNode.getName() + "'";
        jdbc.update(sql);

        // manually set the delta
        sql = "update Node set delta=7 where name='" + containerNode.getName() + "'";
        jdbc.update(sql);

        nodeDAO.delete(dataNode);

        int delta = jdbc.queryForInt("select delta from Node where name='" + containerNode.getName() + "'");
        // delta should now be 7-2
        Assert.assertEquals("Wrong delta", 5, delta);
    } catch (Exception unexpected) {
        log.error("unexpected exception", unexpected);
        Assert.fail("unexpected exception: " + unexpected);
    } finally {
        log.debug("testDeleteDelta - DONE");
    }
}

From source file:ca.nrc.cadc.vos.server.NodeDAOTest.java

@Test
public void testGetOutstandingSizePropagations() {
    log.debug("testGetOutstandingSizePropagations - START");
    try {// ww w. j av  a2  s .co m
        DBConfig dbConfig = new DBConfig();
        ConnectionConfig connConfig = dbConfig.getConnectionConfig(SERVER, DATABASE);
        this.dataSource = DBUtil.getDataSource(connConfig);
        NodeSchema ns = new NodeSchema("Node", "NodeProperty", true); // TOP
        this.nodeDAO = new NodeDAO(dataSource, ns, VOS_AUTHORITY, new X500IdentityManager(), DELETED_NODES);

        ContainerNode rootContainer = (ContainerNode) nodeDAO.getPath(HOME_CONTAINER);
        log.debug("ROOT: " + rootContainer);
        Assert.assertNotNull(rootContainer);

        String basePath = "/" + HOME_CONTAINER + "/";

        // Create a container node
        String containerPath = basePath + getNodeName("trickle-test1");
        ContainerNode containerNode = this.getCommonContainerNode(containerPath);
        containerNode.setParent(rootContainer);
        containerNode = (ContainerNode) nodeDAO.put(containerNode, owner);

        // Create a data node
        String dataPath = containerNode.getUri().getPath() + "/" + "dataNode" + System.currentTimeMillis();
        DataNode dataNode = getCommonDataNode(dataPath);
        dataNode.setParent(containerNode);
        nodeDAO.put(dataNode, owner);

        // manually set the deltas
        JdbcTemplate jdbc = new JdbcTemplate(dataSource);
        String sql = "update Node set delta=11 where name='" + dataNode.getName() + "'";
        jdbc.update(sql);
        sql = "update Node set delta=3 where name='" + containerNode.getName() + "'";
        jdbc.update(sql);

        // grab the nodeIDs for assertion
        sql = "select nodeID from Node where name='" + dataNode.getName() + "'";
        Long dataNodeID = jdbc.queryForLong(sql);
        sql = "select nodeID from Node where name='" + containerNode.getName() + "'";
        Long containerNodeID = jdbc.queryForLong(sql);
        sql = "select nodeID from Node where name='" + rootContainer.getName() + "'";
        Long rootNodeID = jdbc.queryForLong(sql);

        List<NodeSizePropagation> propagations = nodeDAO.getOutstandingPropagations(100, false);
        Assert.assertTrue("Wrong number of oustanding propagations", propagations.size() == 2);

        // sort them for assertion
        Collections.sort(propagations, new Comparator<NodeSizePropagation>() {
            @Override
            public int compare(NodeSizePropagation n1, NodeSizePropagation n2) {
                return -1 * n1.getChildType().compareTo(n2.getChildType());
            }
        });

        Assert.assertEquals("Wrong data node ID", dataNodeID, (Long) propagations.get(0).getChildID());
        Assert.assertEquals("Wrong data node ID", containerNodeID, propagations.get(0).getParentID());
        Assert.assertEquals("Wrong data node ID", containerNodeID, (Long) propagations.get(1).getChildID());
        Assert.assertEquals("Wrong data node ID", rootNodeID, propagations.get(1).getParentID());

    } catch (Exception unexpected) {
        log.error("unexpected exception", unexpected);
        Assert.fail("unexpected exception: " + unexpected);
    } finally {
        log.debug("testGetOutstandingSizePropagations - DONE");
    }
}

From source file:ca.nrc.cadc.vos.server.NodeDAOTest.java

@Test
public void testMoveDelta() {

    log.debug("testMoveDelta - START");
    try {//from w  ww  .j av a  2  s . c o m
        DBConfig dbConfig = new DBConfig();
        ConnectionConfig connConfig = dbConfig.getConnectionConfig(SERVER, DATABASE);
        this.dataSource = DBUtil.getDataSource(connConfig);
        NodeSchema ns = new NodeSchema("Node", "NodeProperty", true); // TOP
        this.nodeDAO = new NodeDAO(dataSource, ns, VOS_AUTHORITY, new X500IdentityManager(), DELETED_NODES);

        ContainerNode rootContainer = (ContainerNode) nodeDAO.getPath(HOME_CONTAINER);
        log.debug("ROOT: " + rootContainer);
        Assert.assertNotNull(rootContainer);

        String basePath = "/" + HOME_CONTAINER + "/";

        // Create a container node
        String containerPath = basePath + getNodeName("delta-test3");
        ContainerNode containerNode = this.getCommonContainerNode(containerPath);
        containerNode.setParent(rootContainer);
        containerNode = (ContainerNode) nodeDAO.put(containerNode, owner);

        // Create another container node
        String containerPath2 = basePath + getNodeName("delta-test4");
        ContainerNode containerNode2 = this.getCommonContainerNode(containerPath2);
        containerNode2.setParent(rootContainer);
        containerNode2 = (ContainerNode) nodeDAO.put(containerNode2, owner);

        // Create a data node
        String dataPath = containerNode.getUri().getPath() + "/" + "dataNode" + System.currentTimeMillis();
        DataNode dataNode = getCommonDataNode(dataPath);
        dataNode.setParent(containerNode);
        nodeDAO.put(dataNode, owner);

        // manually set the nodeSize
        JdbcTemplate jdbc = new JdbcTemplate(dataSource);
        String sql = "update Node set contentLength=9 where name='" + dataNode.getName() + "'";
        jdbc.update(sql);

        // manually set the deltas
        sql = "update Node set delta=11 where name='" + containerNode.getName() + "'";
        jdbc.update(sql);
        sql = "update Node set delta=13 where name='" + containerNode2.getName() + "'";
        jdbc.update(sql);

        nodeDAO.move(dataNode, containerNode2);

        int delta = jdbc.queryForInt("select delta from Node where name='" + containerNode.getName() + "'");
        Assert.assertEquals("Wrong delta", 2, delta);

        delta = jdbc.queryForInt("select delta from Node where name='" + containerNode2.getName() + "'");
        Assert.assertEquals("Wrong delta", 22, delta);
    } catch (Exception unexpected) {
        log.error("unexpected exception", unexpected);
        Assert.fail("unexpected exception: " + unexpected);
    } finally {
        log.debug("testMoveDelta - DONE");
    }
}

From source file:ca.nrc.cadc.vos.server.NodeDAOTest.java

@Test
public void testDatabaseDateRoundTrip() {
    log.debug("testDatabaseDateRoundTrip - START");
    try {// w ww  . j a  v a  2 s .c o m
        DBConfig dbConfig = new DBConfig();
        ConnectionConfig connConfig = dbConfig.getConnectionConfig(SERVER, DATABASE);
        this.dataSource = DBUtil.getDataSource(connConfig);
        NodeSchema ns = new NodeSchema("Node", "NodeProperty", true); // TOP
        this.nodeDAO = new NodeDAO(dataSource, ns, VOS_AUTHORITY, new X500IdentityManager(), DELETED_NODES);

        ContainerNode rootContainer = (ContainerNode) nodeDAO.getPath(HOME_CONTAINER);
        log.debug("ROOT: " + rootContainer);
        Assert.assertNotNull(rootContainer);

        String basePath = "/" + HOME_CONTAINER + "/";

        // Create a container node
        String containerPath = basePath + getNodeName("trickle-test2");
        ContainerNode containerNode = this.getCommonContainerNode(containerPath);
        containerNode.setParent(rootContainer);
        containerNode = (ContainerNode) nodeDAO.put(containerNode, owner);

        // Create a data node
        String dataPath = containerNode.getUri().getPath() + "/" + "dataNode" + System.currentTimeMillis();
        DataNode dataNode = getCommonDataNode(dataPath);
        dataNode.setParent(containerNode);
        nodeDAO.put(dataNode, owner);

        // manually set the busy state
        JdbcTemplate jdbc = new JdbcTemplate(dataSource);
        String sql = "update Node set busyState='W' where name='" + dataNode.getName() + "'";
        jdbc.update(sql);

        // update the metadata, using the strict option
        nodeDAO.updateNodeMetadata(dataNode, new FileMetadata(), true);

        // ensure the state is back to normal
        sql = "select busyState from Node where name='" + dataNode.getName() + "'";
        String curState = (String) jdbc.queryForObject(sql, String.class);
        Assert.assertEquals("Wrong busy state", "N", curState);

        // manually reset the busy state
        sql = "update Node set busyState='W' where name='" + dataNode.getName() + "'";
        jdbc.update(sql);

        // modify some metadata (this will tweak the date)
        List<NodeProperty> properties = new ArrayList<NodeProperty>();
        properties.add(new NodeProperty(VOS.PROPERTY_URI_ISLOCKED, "true"));
        nodeDAO.updateProperties(dataNode, properties);

        // update the metadata again (should get illegal argument exception)
        try {
            nodeDAO.updateNodeMetadata(dataNode, new FileMetadata(), true);
            Assert.fail("Strict option failed.");
        } catch (IllegalStateException e) {
            // expected
        }
    } catch (Exception unexpected) {
        unexpected.printStackTrace();
        log.error("unexpected exception", unexpected);
        Assert.fail("unexpected exception: " + unexpected);
    } finally {
        log.debug("testDatabaseDateRoundTrip - DONE");
    }
}

From source file:ca.nrc.cadc.vos.server.NodeDAOTest.java

@Test
public void testUpdateMetadataDelta() {

    log.debug("testUpdateMetadataDelta - START");
    try {/*from   www.j  a v a2 s.com*/
        DBConfig dbConfig = new DBConfig();
        ConnectionConfig connConfig = dbConfig.getConnectionConfig(SERVER, DATABASE);
        this.dataSource = DBUtil.getDataSource(connConfig);
        NodeSchema ns = new NodeSchema("Node", "NodeProperty", true); // TOP
        this.nodeDAO = new NodeDAO(dataSource, ns, VOS_AUTHORITY, new X500IdentityManager(), DELETED_NODES);

        ContainerNode rootContainer = (ContainerNode) nodeDAO.getPath(HOME_CONTAINER);
        log.debug("ROOT: " + rootContainer);
        Assert.assertNotNull(rootContainer);

        String basePath = "/" + HOME_CONTAINER + "/";

        // Create a container node
        String containerPath = basePath + getNodeName("delta-test");
        ContainerNode containerNode = this.getCommonContainerNode(containerPath);
        containerNode.setParent(rootContainer);
        containerNode = (ContainerNode) nodeDAO.put(containerNode, owner);

        // Create a data node
        String dataPath = containerNode.getUri().getPath() + "/" + "dataNode" + System.currentTimeMillis();
        DataNode dataNode = getCommonDataNode(dataPath);
        dataNode.setParent(containerNode);
        nodeDAO.put(dataNode, owner);

        // manually set the content length & nodeSize
        JdbcTemplate jdbc = new JdbcTemplate(dataSource);
        String sql = "update Node set contentLength=4, busyState='W' where name='" + dataNode.getName() + "'";
        jdbc.update(sql);

        FileMetadata meta = new FileMetadata();
        meta.setContentLength(10L);

        // perform the metadata update
        nodeDAO.updateNodeMetadata(dataNode, meta, true);

        int delta = jdbc.queryForInt("select delta from Node where name='" + dataNode.getName() + "'");
        Assert.assertEquals("Wrong delta", 6, delta);
    } catch (Exception unexpected) {
        log.error("unexpected exception", unexpected);
        Assert.fail("unexpected exception: " + unexpected);
    } finally {
        log.debug("testUpdateMetadataDelta - DONE");
    }
}

From source file:ca.nrc.cadc.vos.server.NodeDAOTest.java

@Test
public void testApplyNodeSizePropagation() {
    log.debug("testApplyNodeSizePropagation - START");
    try {/*from   w w  w. j av  a 2  s .  c  o m*/
        DBConfig dbConfig = new DBConfig();
        ConnectionConfig connConfig = dbConfig.getConnectionConfig(SERVER, DATABASE);
        this.dataSource = DBUtil.getDataSource(connConfig);
        NodeSchema ns = new NodeSchema("Node", "NodeProperty", true); // TOP
        this.nodeDAO = new NodeDAO(dataSource, ns, VOS_AUTHORITY, new X500IdentityManager(), DELETED_NODES);

        ContainerNode rootContainer = (ContainerNode) nodeDAO.getPath(HOME_CONTAINER);
        log.debug("ROOT: " + rootContainer);
        Assert.assertNotNull(rootContainer);

        String basePath = "/" + HOME_CONTAINER + "/";

        // Create a container node
        String containerPath = basePath + getNodeName("trickle-test2");
        ContainerNode containerNode = this.getCommonContainerNode(containerPath);
        containerNode.setParent(rootContainer);
        containerNode = (ContainerNode) nodeDAO.put(containerNode, owner);

        // Create a data node
        String dataPath = containerNode.getUri().getPath() + "/" + "dataNode" + System.currentTimeMillis();
        DataNode dataNode = getCommonDataNode(dataPath);
        dataNode.setParent(containerNode);
        nodeDAO.put(dataNode, owner);

        // manually set the deltas
        JdbcTemplate jdbc = new JdbcTemplate(dataSource);
        String sql = "update Node set delta=11 where name='" + dataNode.getName() + "'";
        jdbc.update(sql);
        sql = "update Node set delta=3 where name='" + containerNode.getName() + "'";
        jdbc.update(sql);

        List<NodeSizePropagation> propagations = nodeDAO.getOutstandingPropagations(100, true);
        // sort them
        Collections.sort(propagations, new Comparator<NodeSizePropagation>() {
            @Override
            public int compare(NodeSizePropagation n1, NodeSizePropagation n2) {
                return -1 * n1.getChildType().compareTo(n2.getChildType());
            }
        });
        Assert.assertTrue("Wrong number of outstanding propagations", propagations.size() == 1);

        // get them again
        propagations = nodeDAO.getOutstandingPropagations(100, false);

        // sort them
        Collections.sort(propagations, new Comparator<NodeSizePropagation>() {
            @Override
            public int compare(NodeSizePropagation n1, NodeSizePropagation n2) {
                return -1 * n1.getChildType().compareTo(n2.getChildType());
            }
        });
        Assert.assertTrue("Wrong number of outstanding propagations", propagations.size() == 2);
        nodeDAO.applyPropagation(propagations.get(0));

        propagations = nodeDAO.getOutstandingPropagations(100, false);
        Assert.assertTrue("Wrong number of outstanding propagations", propagations.size() == 1);
        nodeDAO.applyPropagation(propagations.get(0));

        propagations = nodeDAO.getOutstandingPropagations(100, false);
        Assert.assertTrue("Wrong number of outstanding propagations", propagations.size() == 1);
        nodeDAO.applyPropagation(propagations.get(0));

        propagations = nodeDAO.getOutstandingPropagations(100, false);
        Assert.assertTrue("Wrong number of outstanding propagations", propagations.size() == 0);
    } catch (Exception unexpected) {
        unexpected.printStackTrace();
        log.error("unexpected exception", unexpected);
        Assert.fail("unexpected exception: " + unexpected);
    } finally {
        log.debug("testApplyNodeSizePropagation - DONE");
    }
}

From source file:ca.nrc.cadc.vos.server.NodeDAOTest.java

@Test
public void testPropagationNewThenApply() {
    log.debug("testPropagationNewThenApply - START");
    try {/*from  ww  w . ja  v  a2 s .  com*/
        DBConfig dbConfig = new DBConfig();
        ConnectionConfig connConfig = dbConfig.getConnectionConfig(SERVER, DATABASE);
        this.dataSource = DBUtil.getDataSource(connConfig);
        NodeSchema ns = new NodeSchema("Node", "NodeProperty", true); // TOP
        this.nodeDAO = new NodeDAO(dataSource, ns, VOS_AUTHORITY, new X500IdentityManager(), DELETED_NODES);

        ContainerNode rootContainer = (ContainerNode) nodeDAO.getPath(HOME_CONTAINER);
        log.debug("ROOT: " + rootContainer);
        Assert.assertNotNull(rootContainer);

        String basePath = "/" + HOME_CONTAINER + "/";

        // Create a container node
        String containerName = getNodeName("trickle-test3");
        String containerPath = basePath + containerName;
        ContainerNode containerNode = this.getCommonContainerNode(containerPath);
        containerNode.setParent(rootContainer);
        containerNode = (ContainerNode) nodeDAO.put(containerNode, owner);

        // create a data node
        String dataPath = containerNode.getUri().getPath() + "/" + "dataNode" + System.currentTimeMillis();
        DataNode dataNode = getCommonDataNode(dataPath);
        dataNode.setParent(containerNode);
        nodeDAO.put(dataNode, owner);

        JdbcTemplate jdbc = new JdbcTemplate(dataSource);

        // ensure the contentLength is zero to start
        String sql = "select contentLength from Node where name='" + dataNode.getName() + "'";
        Long contentLength = jdbc.queryForLong(sql);
        Assert.assertEquals("Wrong content length", Long.valueOf(0L), contentLength);

        // ensure the data node delta is zero to start
        sql = "select delta from Node where name='" + dataNode.getName() + "'";
        Long delta = jdbc.queryForLong(sql);
        Assert.assertEquals("Wrong delta", Long.valueOf(0L), delta);

        // manually set the busy state
        sql = "update Node set busyState='W' where name='" + dataNode.getName() + "'";
        jdbc.update(sql);

        // update the metadata, using the strict option
        FileMetadata metadata = new FileMetadata();
        metadata.setContentLength(10L);
        metadata.setMd5Sum("a94fc20c049422af7c591e2984f1f82d");
        nodeDAO.updateNodeMetadata(dataNode, metadata, true);

        // ensure the state is back to normal
        sql = "select busyState from Node where name='" + dataNode.getName() + "'";
        String curState = (String) jdbc.queryForObject(sql, String.class);
        Assert.assertEquals("Wrong busy state", "N", curState);

        // ensure the contentLength is correct
        sql = "select contentLength from Node where name='" + dataNode.getName() + "'";
        contentLength = jdbc.queryForLong(sql);
        Assert.assertEquals("Wrong content length", Long.valueOf(10L), contentLength);

        // ensure the data node delta is correct
        sql = "select delta from Node where name='" + dataNode.getName() + "'";
        delta = jdbc.queryForLong(sql);
        Assert.assertEquals("Wrong delta", Long.valueOf(10L), delta);

        // ensure the md5sum is correct
        sql = "select contentMD5 from Node where name='" + dataNode.getName() + "'";
        String md5sum = (String) jdbc.queryForObject(sql, String.class);
        Assert.assertEquals("Wrong md5 sum", "a94fc20c049422af7c591e2984f1f82d".toUpperCase(),
                md5sum.toUpperCase());

        // get the nodeID
        sql = "select nodeID from Node where name='" + dataNode.getName() + "'";
        long nodeID = jdbc.queryForLong(sql);
        log.debug("nodeID is " + nodeID);

        // get the propagation
        List<NodeSizePropagation> propagations = nodeDAO.getOutstandingPropagations(100, false);
        NodeSizePropagation propagation = null;
        for (NodeSizePropagation next : propagations) {
            log.debug("Looking at propgation with nodeID: " + next.getChildID());
            if (next.getChildID() == nodeID)
                propagation = next;
        }
        Assert.assertNotNull("Null propagation", propagation);

        // apply the propagation
        nodeDAO.applyPropagation(propagation);

        // ensure the data node content length is correct
        sql = "select contentLength from Node where name='" + dataNode.getName() + "'";
        contentLength = jdbc.queryForLong(sql);
        Assert.assertEquals("Wrong content length", Long.valueOf(10L), contentLength);

        // ensure the data node delta is correct
        sql = "select delta from Node where name='" + dataNode.getName() + "'";
        delta = jdbc.queryForLong(sql);
        Assert.assertEquals("Wrong delta", Long.valueOf(0L), delta);

        // ensure the container node content length is correct
        sql = "select contentLength from Node where name='" + containerName + "'";
        contentLength = jdbc.queryForLong(sql);
        Assert.assertEquals("Wrong container content length", Long.valueOf(0L), contentLength);

        // ensure the container node delta is correct
        sql = "select delta from Node where name='" + containerName + "'";
        delta = jdbc.queryForLong(sql);
        Assert.assertEquals("Wrong container delta", Long.valueOf(10L), delta);

    } catch (Exception unexpected) {
        unexpected.printStackTrace();
        log.error("unexpected exception", unexpected);
        Assert.fail("unexpected exception: " + unexpected);
    } finally {
        log.debug("testPropagationNewThenApply - DONE");
    }
}

From source file:ca.nrc.cadc.vos.server.NodeDAOTest.java

@Test
public void testPropagationNewReplaceThenApply() {
    log.debug("testPropagationNewReplaceThenApply - START");
    try {// w w w  .ja v  a 2 s  .c o m
        DBConfig dbConfig = new DBConfig();
        ConnectionConfig connConfig = dbConfig.getConnectionConfig(SERVER, DATABASE);
        this.dataSource = DBUtil.getDataSource(connConfig);
        NodeSchema ns = new NodeSchema("Node", "NodeProperty", true); // TOP
        this.nodeDAO = new NodeDAO(dataSource, ns, VOS_AUTHORITY, new X500IdentityManager(), DELETED_NODES);

        ContainerNode rootContainer = (ContainerNode) nodeDAO.getPath(HOME_CONTAINER);
        log.debug("ROOT: " + rootContainer);
        Assert.assertNotNull(rootContainer);

        String basePath = "/" + HOME_CONTAINER + "/";

        // Create a container node
        String containerName = getNodeName("trickle-test4");
        String containerPath = basePath + containerName;
        ContainerNode containerNode = this.getCommonContainerNode(containerPath);
        containerNode.setParent(rootContainer);
        containerNode = (ContainerNode) nodeDAO.put(containerNode, owner);

        // create a data node
        String dataPath = containerNode.getUri().getPath() + "/" + "dataNode" + System.currentTimeMillis();
        DataNode dataNode = getCommonDataNode(dataPath);
        dataNode.setParent(containerNode);
        nodeDAO.put(dataNode, owner);

        JdbcTemplate jdbc = new JdbcTemplate(dataSource);

        // ensure the contentLength is zero to start
        String sql = "select contentLength from Node where name='" + dataNode.getName() + "'";
        Long contentLength = jdbc.queryForLong(sql);
        Assert.assertEquals("Wrong content length", Long.valueOf(0L), contentLength);

        // ensure the data node delta is zero to start
        sql = "select delta from Node where name='" + dataNode.getName() + "'";
        Long delta = jdbc.queryForLong(sql);
        Assert.assertEquals("Wrong delta", Long.valueOf(0L), delta);

        // manually set the busy state
        sql = "update Node set busyState='W' where name='" + dataNode.getName() + "'";
        jdbc.update(sql);

        // update the metadata, using the strict option
        FileMetadata metadata = new FileMetadata();
        metadata.setContentLength(10L);
        metadata.setMd5Sum("a94fc20c049422af7c591e2984f1f82d");
        nodeDAO.updateNodeMetadata(dataNode, metadata, true);

        // ensure the state is back to normal
        sql = "select busyState from Node where name='" + dataNode.getName() + "'";
        String curState = (String) jdbc.queryForObject(sql, String.class);
        Assert.assertEquals("Wrong busy state", "N", curState);

        // ensure the contentLength is correct
        sql = "select contentLength from Node where name='" + dataNode.getName() + "'";
        contentLength = jdbc.queryForLong(sql);
        Assert.assertEquals("Wrong content length", Long.valueOf(10L), contentLength);

        // ensure the md5sum is correct
        sql = "select contentMD5 from Node where name='" + dataNode.getName() + "'";
        String md5sum = (String) jdbc.queryForObject(sql, String.class);
        Assert.assertEquals("Wrong md5 sum", "a94fc20c049422af7c591e2984f1f82d".toUpperCase(),
                md5sum.toUpperCase());

        // ensure the data node delta is correct
        sql = "select delta from Node where name='" + dataNode.getName() + "'";
        delta = jdbc.queryForLong(sql);
        Assert.assertEquals("Wrong delta", Long.valueOf(10L), delta);

        // start the replace--manually set the busy state
        sql = "update Node set busyState='W' where name='" + dataNode.getName() + "'";
        jdbc.update(sql);

        // update the metadata, using the strict option
        metadata = new FileMetadata();
        metadata.setContentLength(15L);
        metadata.setMd5Sum("c2831384aae9c2e175c255797c2cfca5");
        nodeDAO.updateNodeMetadata(dataNode, metadata, true);

        // ensure the state is back to normal
        sql = "select busyState from Node where name='" + dataNode.getName() + "'";
        curState = (String) jdbc.queryForObject(sql, String.class);
        Assert.assertEquals("Wrong busy state", "N", curState);

        // ensure the contentLength is correct
        sql = "select contentLength from Node where name='" + dataNode.getName() + "'";
        contentLength = jdbc.queryForLong(sql);
        Assert.assertEquals("Wrong content length", Long.valueOf(15L), contentLength);

        // ensure the md5sum is correct
        sql = "select contentMD5 from Node where name='" + dataNode.getName() + "'";
        md5sum = (String) jdbc.queryForObject(sql, String.class);
        Assert.assertEquals("Wrong md5 sum", "c2831384aae9c2e175c255797c2cfca5".toUpperCase(),
                md5sum.toUpperCase());

        // ensure the data node delta is correct
        sql = "select delta from Node where name='" + dataNode.getName() + "'";
        delta = jdbc.queryForLong(sql);
        Assert.assertEquals("Wrong delta", Long.valueOf(15L), delta);

        // get the nodeID
        sql = "select nodeID from Node where name='" + dataNode.getName() + "'";
        long nodeID = jdbc.queryForLong(sql);

        // get the propagation
        List<NodeSizePropagation> propagations = nodeDAO.getOutstandingPropagations(100, false);
        NodeSizePropagation propagation = null;
        for (NodeSizePropagation next : propagations) {
            if (next.getChildID() == nodeID)
                propagation = next;
        }
        Assert.assertNotNull("Null propagation", propagation);

        // apply the propagation
        nodeDAO.applyPropagation(propagation);

        // ensure the data node content length is correct
        sql = "select contentLength from Node where name='" + dataNode.getName() + "'";
        contentLength = jdbc.queryForLong(sql);
        Assert.assertEquals("Wrong content length", Long.valueOf(15L), contentLength);

        // ensure the data node delta is correct
        sql = "select delta from Node where name='" + dataNode.getName() + "'";
        delta = jdbc.queryForLong(sql);
        Assert.assertEquals("Wrong delta", Long.valueOf(0L), delta);

        // ensure the container node content length is correct
        sql = "select contentLength from Node where name='" + containerName + "'";
        contentLength = jdbc.queryForLong(sql);
        Assert.assertEquals("Wrong container content length", Long.valueOf(0L), contentLength);

        // ensure the container node delta is correct
        sql = "select delta from Node where name='" + containerName + "'";
        delta = jdbc.queryForLong(sql);
        Assert.assertEquals("Wrong container delta", Long.valueOf(15L), delta);

    } catch (Exception unexpected) {
        unexpected.printStackTrace();
        log.error("unexpected exception", unexpected);
        Assert.fail("unexpected exception: " + unexpected);
    } finally {
        log.debug("testPropagationNewReplaceThenApply - DONE");
    }
}

From source file:org.agnitas.dao.impl.ImportRecipientsDaoImpl.java

@Override
public Map<Integer, Integer> assiggnToMailingLists(List<Integer> mailingLists, int companyID, int datasourceId,
        int mode, int adminId, NewImportWizardService importWizardHelper) {
    Map<Integer, Integer> mailinglistStat = new HashMap<Integer, Integer>();
    if (mailingLists == null || mailingLists.isEmpty() || mode == ImportMode.TO_BLACKLIST.getIntValue()) {
        return mailinglistStat;
    }/*from  w  w  w  .  j  av  a 2 s  .  c om*/

    JdbcTemplate jdbc = createJdbcTemplate();
    String currentTimestamp = AgnUtils.getHibernateDialect().getCurrentTimestampSQLFunctionName();
    String sql = null;
    importWizardHelper.setCompletedPercent(0);
    double count = 0;
    double diffComplete = 0;
    int newRecipientsCount = jdbc.queryForInt(
            "SELECT COUNT(*) FROM customer_" + companyID + "_tbl WHERE datasource_id = " + datasourceId);
    if (mode != ImportMode.ADD.getIntValue()) {
        count = newRecipientsCount != 0
                ? (newRecipientsCount / NewImportWizardService.BLOCK_SIZE) * mailingLists.size()
                : 1;
        Integer[] types = { NewImportWizardService.RECIPIENT_TYPE_DUPLICATE_RECIPIENT };
        final int updatedRecipients = getRecipientsCountByType(types, adminId, datasourceId);
        if (updatedRecipients > 0) {
            diffComplete = MAX_WRITE_PROGRESS_HALF / (count != 0 ? count : 1);
        } else {
            diffComplete = MAX_WRITE_PROGRESS / (count != 0 ? count : 1);
        }
    } else {
        count = newRecipientsCount != 0
                ? (newRecipientsCount / NewImportWizardService.BLOCK_SIZE) * mailingLists.size()
                : 1;
        diffComplete = MAX_WRITE_PROGRESS / (count != 0 ? count : 1);
    }
    double intNumber = 0;
    // assign new recipients to mailing lists
    for (Integer mailingList : mailingLists) {
        mailinglistStat.put(mailingList, 0);
        if (mode == ImportMode.ADD.getIntValue() || mode == ImportMode.ADD_AND_UPDATE.getIntValue()) {
            int position = 1;
            int recipientIterator = newRecipientsCount;
            int added = 0;
            while (recipientIterator > 0 || (position == 1 && newRecipientsCount > 0)) {
                final ImportProfile importProfile = importWizardHelper.getImportProfile();
                if (importProfile != null) {
                    if (logger.isInfoEnabled()) {
                        logger.info("Import ID: " + importProfile.getImportId()
                                + " Assigning new recipients to mailinglist with ID " + mailingList
                                + ", datasourceID: " + datasourceId);
                    }
                } else {
                    if (logger.isInfoEnabled()) {
                        logger.info("Import ID is undefined");
                    }
                }
                if (AgnUtils.isMySQLDB()) {
                    sql = "INSERT INTO customer_" + companyID
                            + "_binding_tbl (customer_id, user_type, user_status, user_remark, creation_date, exit_mailing_id, mailinglist_id) "
                            + "(SELECT customer_id, 'W', 1, 'CSV File Upload', " + currentTimestamp + ", 0,"
                            + mailingList + " FROM customer_" + companyID + "_tbl " + "WHERE datasource_id = "
                            + datasourceId + " LIMIT " + (position - 1) * NewImportWizardService.BLOCK_SIZE
                            + "," + NewImportWizardService.BLOCK_SIZE + " )";
                }
                if (AgnUtils.isOracleDB()) {
                    sql = "INSERT INTO customer_" + companyID
                            + "_binding_tbl (customer_id, user_type, user_status, user_remark, creation_date, exit_mailing_id, mailinglist_id) "
                            + "(SELECT customer_id, 'W', 1, 'CSV File Upload', " + currentTimestamp + ", 0,"
                            + mailingList + " FROM (SELECT customer_id, datasource_id, rownum r FROM customer_"
                            + companyID + "_tbl WHERE datasource_id = " + datasourceId + " AND 1=1) "
                            + " WHERE r BETWEEN " + (((position - 1) * NewImportWizardService.BLOCK_SIZE) + 1)
                            + " AND " + (((position - 1) * NewImportWizardService.BLOCK_SIZE)
                                    + NewImportWizardService.BLOCK_SIZE)
                            + " )";
                }
                added = added + jdbc.update(sql);
                mailinglistStat.put(mailingList, added);
                intNumber = intNumber + diffComplete;
                if (intNumber >= 1) {
                    importWizardHelper.setCompletedPercent(
                            (int) (importWizardHelper.getCompletedPercent() + Math.floor(intNumber)));
                    intNumber = intNumber - Math.floor(intNumber);
                }
                position++;
                recipientIterator = recipientIterator - NewImportWizardService.BLOCK_SIZE;
            }
        }
    }

    if (mode != ImportMode.ADD.getIntValue()) {
        Integer[] types = { NewImportWizardService.RECIPIENT_TYPE_DUPLICATE_RECIPIENT };
        final int updatedRecipients = getRecipientsCountByType(types, adminId, datasourceId);

        count = count + updatedRecipients != 0 ? updatedRecipients / NewImportWizardService.BLOCK_SIZE : 1;
        if (newRecipientsCount > 0) {
            diffComplete = MAX_WRITE_PROGRESS_HALF / (count != 0 ? count : 1);
        } else {
            diffComplete = MAX_WRITE_PROGRESS / (count != 0 ? count : 1);
        }

    }
    // assign updated recipients to mailing lists
    if (mode != ImportMode.ADD.getIntValue()) {
        Integer[] types = { NewImportWizardService.RECIPIENT_TYPE_DUPLICATE_RECIPIENT };
        int page = 0;
        int rowNum = NewImportWizardService.BLOCK_SIZE;
        HashMap<ProfileRecipientFields, ValidatorResults> recipients = null;
        while (recipients == null || recipients.size() >= rowNum) {
            recipients = getRecipientsByTypePaginated(types, page, rowNum, adminId, datasourceId);
            List<Integer> updatedRecipients = new ArrayList<Integer>();
            for (ProfileRecipientFields recipient : recipients.keySet()) {
                if (recipient.getUpdatedIds() != null && !recipient.getUpdatedIds().isEmpty()) {
                    updatedRecipients.addAll(recipient.getUpdatedIds());
                }
            }
            updateMailinglists(mailingLists, companyID, datasourceId, mode, mailinglistStat, jdbc,
                    currentTimestamp, updatedRecipients);
            page++;
            importWizardHelper
                    .setCompletedPercent((int) (importWizardHelper.getCompletedPercent() + diffComplete));
        }
    }
    importWizardHelper.setCompletedPercent(MAX_WRITE_PROGRESS);
    return mailinglistStat;
}

From source file:org.agnitas.dao.impl.ImportRecipientsDaoImpl.java

private void updateMailinglists(List<Integer> mailingLists, int companyID, int datasourceId, int mode,
        Map<Integer, Integer> mailinglistStat, JdbcTemplate jdbc, String currentTimestamp,
        List<Integer> updatedRecipients) {
    String sql;/*from  w w w  .  java 2s.  co  m*/
    for (Integer mailinglistId : mailingLists) {
        try {
            if (mode == ImportMode.ADD.getIntValue() || mode == ImportMode.ADD_AND_UPDATE.getIntValue()
                    || mode == ImportMode.UPDATE.getIntValue()) {
                int added = 0;
                createRecipientBindTemporaryTable(companyID, datasourceId, updatedRecipients, jdbc);
                sql = "DELETE FROM cust_" + companyID + "_exist1_tmp" + datasourceId
                        + "_tbl WHERE customer_id IN (SELECT customer_id FROM customer_" + companyID
                        + "_binding_tbl WHERE mailinglist_id=" + mailinglistId + ")";
                jdbc.execute(sql);
                sql = "INSERT INTO customer_" + companyID
                        + "_binding_tbl (customer_id, user_type, user_status, user_remark, creation_date, exit_mailing_id, mailinglist_id) (SELECT customer_id, 'W', 1, 'CSV File Upload', "
                        + currentTimestamp + ", 0," + mailinglistId + " FROM cust_" + companyID + "_exist1_tmp"
                        + datasourceId + "_tbl)";
                added += jdbc.update(sql);
                mailinglistStat.put(mailinglistId, mailinglistStat.get(mailinglistId) + added);
            } else if (mode == ImportMode.MARK_OPT_OUT.getIntValue()) {
                int changed = changeStatusInMailingList(companyID, updatedRecipients, jdbc, mailinglistId,
                        BindingEntry.USER_STATUS_OPTOUT, "Mass Opt-Out by Admin", currentTimestamp);
                mailinglistStat.put(mailinglistId, mailinglistStat.get(mailinglistId) + changed);
            } else if (mode == ImportMode.MARK_BOUNCED.getIntValue()) {
                int changed = changeStatusInMailingList(companyID, updatedRecipients, jdbc, mailinglistId,
                        BindingEntry.USER_STATUS_BOUNCED, "Mass Bounce by Admin", currentTimestamp);
                mailinglistStat.put(mailinglistId, mailinglistStat.get(mailinglistId) + changed);
            }
        } catch (Exception e) {
            logger.error("writeContent: " + e.getMessage(), e);
        } finally {
            removeBindTemporaryTable(companyID, datasourceId, jdbc);
        }
    }
}