Example usage for java.sql Connection rollback

List of usage examples for java.sql Connection rollback

Introduction

In this page you can find the example usage for java.sql Connection rollback.

Prototype

void rollback() throws SQLException;

Source Link

Document

Undoes all changes made in the current transaction and releases any database locks currently held by this Connection object.

Usage

From source file:com.alfaariss.oa.engine.tgt.jdbc.JDBCTGTFactory.java

/**
 * Uses a batch update to persist all supplied tgts.
 * @param tgts The TGTs to persist.//from w w w .j a  va2  s  . com
 * @throws PersistenceException If persistance fails.
 * 
 * @see IEntityManager#persist(IEntity[])
 * @see PreparedStatement#addBatch()
 */
public void persist(JDBCTGT[] tgts) throws PersistenceException {
    if (tgts == null)
        throw new IllegalArgumentException("Suplied tgt array is empty or invalid");

    List<TGTEventError> listTGTEventErrors = new Vector<TGTEventError>();

    Connection connection = null;
    PreparedStatement psInsert = null;
    PreparedStatement psDelete = null;
    PreparedStatement psDeleteAliasR = null;
    PreparedStatement psDeleteAliasF = null;
    PreparedStatement psUpdate = null;
    try {
        connection = _oDataSource.getConnection(); //Manage connection
        connection.setAutoCommit(false);

        if (_aliasStoreSP != null)
            psDeleteAliasR = connection.prepareStatement(_aliasStoreSP.getQueryAliasRemove());

        if (_aliasStoreIDP != null)
            psDeleteAliasF = connection.prepareStatement(_aliasStoreIDP.getQueryAliasRemove());

        psInsert = connection.prepareStatement(_sInsertQuery);
        psDelete = connection.prepareStatement(_sRemoveQuery);
        psUpdate = connection.prepareStatement(_sUpdateQuery);

        Vector<ITGT> vCreate = new Vector<ITGT>();
        Vector<ITGT> vUpdate = new Vector<ITGT>();
        Vector<ITGT> vRemove = new Vector<ITGT>();

        for (JDBCTGT tgt : tgts) //For all tgts
        {
            String id = tgt.getId();
            if (id == null) //New TGT
            {
                byte[] baId = new byte[ITGT.TGT_LENGTH];
                do {
                    _random.nextBytes(baId);
                    try {
                        id = ModifiedBase64.encode(baId);
                    } catch (UnsupportedEncodingException e) {
                        _logger.error("Could not create tgt id for byte[]: " + baId, e);
                        throw new PersistenceException(SystemErrors.ERROR_INTERNAL);
                    }
                } while (exists(id)); //Key allready exists   

                tgt.setId(id);
                //Update expiration time
                long expiration = System.currentTimeMillis() + _lExpiration;
                tgt.setTgtExpTime(expiration);
                psInsert.setString(1, id);
                psInsert.setTimestamp(2, new Timestamp(expiration));
                psInsert.setBytes(3, Serialize.encode(tgt.getUser()));
                psInsert.setBytes(4, Serialize.encode(tgt.getAuthenticationProfile()));
                psInsert.setBytes(5, Serialize.encode(tgt.getModifiableAuthNProfileIDs()));
                psInsert.setBytes(6, Serialize.encode(tgt.getModifiableRequestorIDs()));
                psInsert.setBytes(7, Serialize.encode(tgt.getAttributes()));
                psInsert.addBatch();

                vCreate.add(tgt);
            } else if (tgt.isExpired()) //Expired
            {
                _logger.debug("TGT Expired: " + id);

                if (psDeleteAliasR != null) {
                    psDeleteAliasR.setString(1, id);
                    psDeleteAliasR.addBatch();
                }

                if (psDeleteAliasF != null) {
                    psDeleteAliasF.setString(1, id);
                    psDeleteAliasF.addBatch();
                }

                vRemove.add(tgt);
            } else //Update
            {
                //Update expiration time
                long expiration = System.currentTimeMillis() + _lExpiration;
                tgt.setTgtExpTime(expiration);
                //Update tgt
                psUpdate.setTimestamp(1, new Timestamp(expiration));
                psUpdate.setBytes(2, Serialize.encode(tgt.getUser()));
                psUpdate.setBytes(3, Serialize.encode(tgt.getAuthenticationProfile()));
                psUpdate.setBytes(4, Serialize.encode(tgt.getModifiableAuthNProfileIDs()));
                psUpdate.setBytes(5, Serialize.encode(tgt.getModifiableRequestorIDs()));
                psUpdate.setBytes(6, Serialize.encode(tgt.getAttributes()));
                psUpdate.setString(7, id);
                psUpdate.addBatch();

                vUpdate.add(tgt);
            }
        }

        try {
            int iTotalAdded = 0;
            for (int i : psInsert.executeBatch()) {
                iTotalAdded += i;
            }
            _logger.debug(iTotalAdded + " new TGT(s) added by batch");

            for (ITGT tgt : vCreate) {
                try {
                    processEvent(TGTListenerEvent.ON_CREATE, tgt);
                } catch (TGTListenerException e) {
                    listTGTEventErrors.addAll(e.getErrors());
                }
            }
        } catch (SQLException e) {
            _logger.error("Could not execute insert batch", e);
            throw new PersistenceException(SystemErrors.ERROR_RESOURCE_INSERT);
        }

        try {
            for (ITGT tgt : vRemove) {
                IUser tgtUser = tgt.getUser();
                _eventLogger.info(new UserEventLogItem(null, tgt.getId(), null, UserEvent.TGT_EXPIRED,
                        tgtUser.getID(), tgtUser.getOrganization(), null, null, this, null));

                try {
                    processEvent(TGTListenerEvent.ON_REMOVE, tgt);
                } catch (TGTListenerException e) {
                    listTGTEventErrors.addAll(e.getErrors());
                }
            }

            int iTotalDeleted = 0;
            for (int i : psDelete.executeBatch()) {
                iTotalDeleted += i;
            }
            _logger.debug(iTotalDeleted + " TGT(s) deleted by batch");
        } catch (SQLException e) {
            _logger.error("Could not execute delete batch", e);
            throw new PersistenceException(SystemErrors.ERROR_RESOURCE_REMOVE);
        }

        if (psDeleteAliasR != null) {
            try {
                int iTotalAliasDeleted = 0;
                for (int i : psDeleteAliasR.executeBatch()) {
                    iTotalAliasDeleted += i;
                }
                _logger.debug(iTotalAliasDeleted + " (requestor based) alias(es) deleted by batch");
            } catch (SQLException e) {
                _logger.error("Could not execute delete (requestor based) alias batch", e);
                throw new PersistenceException(SystemErrors.ERROR_RESOURCE_REMOVE);
            }
        }

        if (psDeleteAliasF != null) {
            try {
                int iTotalAliasDeleted = 0;
                for (int i : psDeleteAliasF.executeBatch()) {
                    iTotalAliasDeleted += i;
                }
                _logger.debug(iTotalAliasDeleted + " (remote enitity based) alias(es) deleted by batch");
            } catch (SQLException e) {
                _logger.error("Could not execute delete (remote enitity based) alias batch", e);
                throw new PersistenceException(SystemErrors.ERROR_RESOURCE_REMOVE);
            }
        }

        try {
            int iTotalUpdated = 0;
            for (int i : psUpdate.executeBatch()) {
                iTotalUpdated += i;
            }
            _logger.debug(iTotalUpdated + " TGT(s) updated by batch");

            for (ITGT tgt : vUpdate) {
                try {
                    processEvent(TGTListenerEvent.ON_UPDATE, tgt);
                } catch (TGTListenerException e) {
                    listTGTEventErrors.addAll(e.getErrors());
                }
            }
        } catch (SQLException e) {
            _logger.error("Could not execute update batch", e);
            throw new PersistenceException(SystemErrors.ERROR_RESOURCE_UPDATE);
        }

        connection.commit();

        if (listTGTEventErrors != null) {//TGT Event processing failed, error has been logged already
            throw new TGTListenerException(listTGTEventErrors);
        }
    } catch (SQLException e) {
        _logger.error("Could not execute Batch", e);
        try {
            if (connection != null)
                connection.rollback();
        } catch (SQLException e1) {
            _logger.warn("Could not rollback batch", e);
        }

        throw new PersistenceException(SystemErrors.ERROR_INTERNAL);
    } catch (PersistenceException e) {
        try {
            if (connection != null)
                connection.rollback();
        } catch (SQLException e1) {
            _logger.warn("Could not rollback batch", e);
        }
        throw e;
    } catch (Exception e) {
        _logger.error("Could not connect to JDBC resource", e);
        throw new PersistenceException(SystemErrors.ERROR_RESOURCE_CONNECT);
    } finally {
        try {
            if (psInsert != null)
                psInsert.close();
        } catch (SQLException e) {
            _logger.debug("Could not close insert statement", e);
        }

        try {
            if (psDelete != null)
                psDelete.close();
        } catch (SQLException e) {
            _logger.debug("Could not close delete statement", e);
        }

        try {
            if (psDeleteAliasR != null)
                psDeleteAliasR.close();
        } catch (SQLException e) {
            _logger.debug("Could not close delete (requestor based) alias statement", e);
        }

        try {
            if (psDeleteAliasF != null)
                psDeleteAliasF.close();
        } catch (SQLException e) {
            _logger.debug("Could not close delete (remote entity based) alias statement", e);
        }

        try {
            if (psUpdate != null)
                psUpdate.close();
        } catch (SQLException e) {
            _logger.debug("Could not close update statement", e);
        }

        try {
            if (connection != null)
                connection.close();
        } catch (SQLException e) {
            _logger.debug("Could not close connection", e);
        }
    }
}

From source file:com.stratelia.webactiv.beans.admin.Admin.java

/**
 * Add the given component instance in Silverpeas.
 *
 * @param userId/*  ww w.j  a v  a 2  s .  c  o  m*/
 * @param componentInst
 * @param startNewTransaction
 * @return
 * @throws com.stratelia.webactiv.beans.admin.AdminException
 */
public String addComponentInst(String userId, ComponentInst componentInst, boolean startNewTransaction)
        throws AdminException, QuotaException {
    Connection connectionProd = null;
    DomainDriverManager domainDriverManager = DomainDriverManagerFactory.getFactory().getDomainDriverManager();
    try {
        connectionProd = openConnection(false);

        if (startNewTransaction) {
            // Open the connections with auto-commit to false
            domainDriverManager.startTransaction(false);
        }

        // Get the father space inst
        SpaceInst spaceInstFather = getSpaceInstById(componentInst.getDomainFatherId());

        // Verify the component space quota
        SpaceServiceFactory.getComponentSpaceQuotaService()
                .verify(ComponentSpaceQuotaKey.from(spaceInstFather));

        // Create the component instance
        String driverComponentId = componentManager.createComponentInst(componentInst, domainDriverManager,
                getDriverSpaceId(spaceInstFather.getId()));

        // Add the component to the space
        spaceInstFather.addComponentInst(componentInst);

        // Put the new Id for client
        componentInst.setId(driverComponentId);

        // Instantiate the component
        String componentName = componentInst.getName();
        String componentId = componentName + componentInst.getId();

        String[] asCompoNames = { componentName };
        String[] asCompoIds = { componentId };
        instantiateComponents(userId, asCompoIds, asCompoNames, spaceInstFather.getId(), connectionProd);

        if (isContentManagedComponent(componentName)) {
            // Create the manager objects
            ContainerManager containerManager = new ContainerManager();
            ContentManager contentManager = new ContentManager();

            // Call the register functions
            containerManager.registerNewContainerInstance(connectionProd, componentId, "containerPDC",
                    componentName);
            contentManager.registerNewContentInstance(connectionProd, componentId, "containerPDC",
                    componentName);
        }

        if (useProfileInheritance && !componentInst.isInheritanceBlocked()) {
            // inherits profiles from space
            setSpaceProfilesToComponent(componentInst, spaceInstFather);
        }

        // commit the transactions
        if (startNewTransaction) {
            domainDriverManager.commit();
        }
        connectionProd.commit();
        cache.opAddComponent(componentInst);

        ComponentInstLight component = getComponentInstLight(componentId);
        TreeCache.addComponent(driverComponentId, component, getDriverSpaceId(spaceInstFather.getId()));

        // indexation du composant
        createComponentIndex(component);

        return componentId;
    } catch (Exception e) {
        try {
            if (startNewTransaction) {
                domainDriverManager.rollback();
            }
            connectionProd.rollback();
        } catch (Exception e1) {
            SilverTrace.error(MODULE_ADMIN, "Admin.addComponentInst", "root.EX_ERR_ROLLBACK", e1);
        }
        if (e instanceof QuotaException) {
            throw (QuotaException) e;
        }
        throw new AdminException("Admin.addComponentInst", SilverpeasException.ERROR,
                "admin.EX_ERR_ADD_COMPONENT", "component name: '" + componentInst.getName() + "'", e);
    } finally {
        if (startNewTransaction) {
            domainDriverManager.releaseOrganizationSchema();
        }
        DBUtil.close(connectionProd);
    }
}

From source file:dao.DirectoryDaoDb.java

/**
 * Deletes directory//from  www .j  ava2  s  . c  o  m
 * If the directory contains subdirectories or children or collabrum or urls, then
 * this directory is not deleted.
 * User permissions are checked before the user is allowed to delete directory.
 * If the user is the userid or admin, delete directory.
 * If the user has permission to delete in the permission directory, delete directory.
 * Returns parentId of this directory for controller
 * @param directoryId - the directoryid 
 * @param userId - the user id
 * @param userLogin - user login
 * @return List -> has the parentid used by the controller to throw the viewDirectory
 * @throws BaseDaoException If we have a problem interpreting the data or the data is missing or incorrect
 */
public List deleteDirectory(String directoryId, String userId, String userLogin) throws BaseDaoException {

    if (RegexStrUtil.isNull(directoryId) || RegexStrUtil.isNull(userId) || RegexStrUtil.isNull(userLogin)) {
        throw new BaseDaoException("params are null");
    }

    //logger.info("deleteDirectory" + directoryId);

    if (!WebUtil.isHomeDirDeleteEnabled()) {
        if (WebUtil.isSanEnabled()) {
            if (isHomeDirectory(directoryId, userLogin, userId)) {
                throw new BaseDaoException("Cannot delete, home directory, directoryId " + directoryId
                        + " userLogin = " + userLogin);
            }
        }
    }

    /**
    * allow files, collabrums to be deleted
    */
    if (!WebUtil.isDirTreeDeleteEnabled()) {
        if (isChildASubDir(directoryId)) {
            throw new BaseDaoException(
                    "Cannot delete, subdirs exist, userId = " + userId + " directoryId = " + directoryId);
        }
    }

    /**
     *  check authority to delete: isDiaryAdmin, isAuthor
     *  We donot check for global scope as the author who has added this entry 
     *  is added as diradmin
     */
    if ((!diaryAdmin.isDiaryAdmin(userLogin)) && (!isAuthor(directoryId, userId))) {
        throw new BaseDaoException("User does not have permission to delete this directory, user = " + userId
                + " directoryId " + directoryId);
    }

    /**
     *  Get scalability datasource for directory - not partitioned
     */
    String sourceName = scalabilityManager.getWriteZeroScalability();
    ds = scalabilityManager.getSource(sourceName);
    if (ds == null) {
        throw new BaseDaoException("ds null, deleteDirectory() " + sourceName);
    }

    /**
     *  gets the parentid of the directoryid and the result is returned
     */
    List dResult = null;
    try {
        Object[] params = { (Object) directoryId };
        dResult = directoryParentQuery.execute(params);
    } catch (Exception e) {
        throw new BaseDaoException("directoryparentQuery() exception " + directoryParentQuery.getSql(), e);
    }

    Connection conn = null;
    HashSet dirSet = null;
    try {
        conn = ds.getConnection();
        dirSet = listAuthorQuery.run(conn, directoryId);
    } catch (Exception e) {
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (Exception e1) {
            throw new BaseDaoException("conn.close() exception " + directoryId, e1);
        }
        throw new BaseDaoException("listAuthorQuery, exception " + directoryId, e);
    }

    if (WebUtil.isSanEnabled()) {
        Directory currentDir = viewDirectory(directoryId, userId, userLogin, DbConstants.READ_FROM_SLAVE,
                DbConstants.BLOB_READ_FROM_SLAVE, DbConstants.READ_FROM_SLAVE);

        if (currentDir != null) {
            try {
                getSanUtils();
                //logger.info("commenting deleteAllSanDir for the time being");
                sanUtils.deleteAllSanDir(currentDir.getValue(DbConstants.DIRPATH),
                        currentDir.getValue(DbConstants.DIRNAME), SanConstants.sanPath);
            } catch (SanException e) {
                throw new BaseDaoException("deleteSanDir() deleteDirectory() error, " + directoryId
                        + " error message " + e.getMessage(), e);
            }
        }
    }

    try {
        if (conn == null) {
            conn = ds.getConnection();
        }
        conn.setAutoCommit(false);

        /** delete all children, subdirs */
        if (isChildASubDir(directoryId)) {
            //logger.info("calling deleteNode()");
            deleteNode(directoryId, conn);
        }

        /** 
         * the userId is not required to be checked 
         * as long as the user either the diaryAdmin or is author 
         */
        deleteAllDirectory(directoryId, conn);
        //logger.info("deleteAllDirectory called " + directoryId);

        /*
              directoryDeleteQuery.run(conn, directoryId);
              scopeDeleteQuery.run(conn, directoryId);
              deleteChildQuery.run(conn, directoryId);
              deleteAdminQuery.run(conn, directoryId);
              deleteDirCopyQuery.run(conn, directoryId);
              deleteDirBlockAllQuery.run(conn, directoryId);
              deleteDirAllowUsersAllQuery.run(conn, directoryId);
        */
        //logger.info("completed deleteDirectory queries ");
        /**
         * delete collabrum, delete websites coming soon!
         */
    } catch (Exception e) {
        try {
            conn.rollback();
        } catch (Exception e1) {
            try {
                if (conn != null) {
                    conn.setAutoCommit(true);
                    conn.close();
                }
            } catch (Exception e2) {
                throw new BaseDaoException(
                        "connection close() exception for rollback, delete directory/dirscope/diradmin tables  "
                                + " params (2) " + " directoryId = " + directoryId + " userId = " + userId,
                        e2);
            }
            throw new BaseDaoException("rollback() exception for delete directory/dirscope/diradmin tables  "
                    + " params (2) " + " directoryId = " + directoryId + " userId = " + userId, e1);
        }
    }

    // connection commit
    try {
        conn.commit();
    } catch (Exception e3) {
        throw new BaseDaoException("commit() exception for delete, directory/dirscope/diradmin tables  "
                + " params (2) " + " directoryId = " + directoryId + " userId = " + userId, e3);
    }
    try {
        if (conn != null) {
            conn.setAutoCommit(true);
            conn.close();
        }
    } catch (Exception e4) {
        throw new BaseDaoException(
                "connection close() exception for commit, delete directory/dirscope/diradmin tables  "
                        + " params (2) " + " directoryId = " + directoryId + " userId = " + userId,
                e4);
    }

    /**
     * remove this directory from cache
     */
    Fqn fqn = cacheUtil.fqn(DbConstants.DIRECTORY);
    if (treeCache.exists(fqn, directoryId)) {
        treeCache.remove(fqn, directoryId);
    }

    // check for each parent and remove the parent from cache
    if ((dResult != null) && (dResult.size() > 0)) {
        String parentId = ((Directory) dResult.get(0)).getValue(DbConstants.PARENT_ID);
        if (treeCache.exists(fqn, parentId)) {
            treeCache.remove(fqn, parentId);
        }
    }

    fqn = cacheUtil.fqn(DbConstants.DIR_COBRAND);
    if (treeCache.exists(fqn, directoryId)) {
        treeCache.remove(fqn, directoryId);
    }

    fqn = cacheUtil.fqn(DbConstants.DIR_SCOPE);
    if (treeCache.exists(fqn, directoryId)) {
        treeCache.remove(fqn, directoryId);
    }

    fqn = cacheUtil.fqn(DbConstants.DIR_CAT);
    StringBuffer sb = new StringBuffer(directoryId);
    sb.append("-");
    sb.append(DbConstants.PHOTO_CATEGORY);
    if (treeCache.exists(fqn, sb.toString())) {
        treeCache.remove(fqn, sb.toString());
    }

    sb.delete(0, sb.length());
    sb.append(directoryId);
    sb.append("-");
    sb.append(DbConstants.FILE_CATEGORY);
    if (treeCache.exists(fqn, sb.toString())) {
        treeCache.remove(fqn, sb.toString());
    }

    /*
            fqn = cacheUtil.fqn(DbConstants.DIRECTORY_STREAM_BLOBS);
            if (treeCache.exists(fqn, directoryId)) {
          Object obj = treeCache.get(fqn, directoryId);
          if (obj != null) {
             List entries = (List)obj;
      Fqn streamFqn = cacheUtil.fqn(DbConstants.DIR_STREAM_BLOB);
             //StringBuffer sb = new StringBuffer();
             for (int i = 0; i < entries.size(); i++) {
     String entryId = ((Photo)entries.get(i)).getValue(DbConstants.ENTRYID);
            if (!RegexStrUtil.isNull(entryId)) {
               sb.delete(0, sb.length());        
               sb.append(directoryId);
               sb.append("-");
               sb.append(entryId);
               if (treeCache.exists(streamFqn, sb.toString())) {
      treeCache.remove(streamFqn, sb.toString());
               }
            }
             }
          }
               treeCache.remove(fqn, directoryId);
       }
    */
    if (dirSet != null) {
        Iterator it = dirSet.iterator();
        while (it.hasNext()) {
            Directory directory = (Directory) it.next();
            String adminUser = directory.getValue(DbConstants.LOGIN);
            if (!RegexStrUtil.isNull(adminUser)) {

                fqn = cacheUtil.fqn(DbConstants.USER_PAGE);
                if (treeCache.exists(fqn, adminUser)) {
                    treeCache.remove(fqn, adminUser);
                }

                fqn = cacheUtil.fqn(DbConstants.AUTHORS_LIST);
                if (treeCache.exists(fqn, adminUser)) {
                    treeCache.remove(fqn, adminUser);
                }

                fqn = cacheUtil.fqn(DbConstants.AUTHORS_DIRECTORIES);
                if (treeCache.exists(fqn, adminUser)) {
                    treeCache.remove(fqn, adminUser);
                }

                String adminId = directory.getValue(DbConstants.LOGIN_ID);
                fqn = cacheUtil.fqn(DbConstants.AUTHOR_BLOCKED_DIRS);
                if (treeCache.exists(fqn, adminId)) {
                    treeCache.remove(fqn, adminId);
                }

                fqn = cacheUtil.fqn(DbConstants.DIR_COPY);
                if (treeCache.exists(fqn, adminId)) {
                    treeCache.remove(fqn, adminId);
                }

                fqn = cacheUtil.fqn(DbConstants.DIR_MOVE);
                if (treeCache.exists(fqn, adminId)) {
                    treeCache.remove(fqn, adminId);
                }

                sb.delete(0, sb.length());
                sb.append(directoryId);
                sb.append("-");
                sb.append(adminId);
                String key = sb.toString();
                fqn = cacheUtil.fqn(DbConstants.DIR_AUTHOR);
                if (treeCache.exists(fqn, key)) {
                    treeCache.remove(fqn, key);
                }
            }
        }
    }
    removeUsersFromDirAuthorsCache(directoryId);
    return dResult;
}

From source file:com.stratelia.webactiv.beans.admin.Admin.java

/**
 * Deletes the given component instance in Silverpeas
 *
 * @param userId the unique identifier of the user requesting the deletion.
 * @param componentId the client identifier of the component instance (for a kmelia instance of id
 * 666, the client identifier of the instance is kmelia666)
 * @param definitive is the component instance deletion is definitive? If not, the component
 * instance is moved into the bin./*from w w w. j a v  a 2 s.co  m*/
 * @param startNewTransaction is the deletion has to occur within a new transaction?
 * @return the client component instance identifier.
 * @throws com.stratelia.webactiv.beans.admin.AdminException if an error occurs while deleting the
 * component instance.
 */
public String deleteComponentInst(String userId, String componentId, boolean definitive,
        boolean startNewTransaction) throws AdminException {
    Connection connectionProd = null;
    SilverTrace.spy(MODULE_ADMIN, "Admin.deleteComponentInst()", "ACP", componentId, "", userId,
            SilverTrace.SPY_ACTION_DELETE);
    DomainDriverManager domainDriverManager = DomainDriverManagerFactory.getFactory().getDomainDriverManager();
    try {
        if (startNewTransaction) {
            // Open the connections with auto-commit to false
            domainDriverManager.startTransaction(false);
        }

        // Convert the client id in driver id
        String sDriverComponentId = getDriverComponentId(componentId);

        // Get the component to delete
        ComponentInst componentInst = getComponentInst(sDriverComponentId, true, null);

        // Get the father id
        String sFatherClientId = componentInst.getDomainFatherId();

        if (!definitive) {
            // delete the profiles instance
            for (int nI = 0; nI < componentInst.getNumProfileInst(); nI++) {
                deleteProfileInst(componentInst.getProfileInst(nI).getId(), false);
            }

            componentManager.sendComponentToBasket(domainDriverManager, sDriverComponentId,
                    componentInst.getLabel() + Admin.basketSuffix, userId);
        } else {
            connectionProd = openConnection(false);

            // Uninstantiate the components
            String componentName = componentInst.getName();
            String[] asCompoName = { componentName };
            String[] asCompoId = { componentId };
            unInstantiateComponents(userId, asCompoId, asCompoName, getClientSpaceId(sFatherClientId),
                    connectionProd);

            // delete the profiles instance
            for (int nI = 0; nI < componentInst.getNumProfileInst(); nI++) {
                deleteProfileInst(componentInst.getProfileInst(nI).getId(), false);
            }

            // Delete the component
            componentManager.deleteComponentInst(componentInst, domainDriverManager);

            if (isContentManagedComponent(componentName)) {
                // Create the manager objects
                ContainerManager containerManager = new ContainerManager();
                ContentManager contentManager = new ContentManager();

                // Call the unregister functions
                containerManager.unregisterNewContainerInstance(connectionProd, componentId, "containerPDC",
                        componentName);
                contentManager.unregisterNewContentInstance(connectionProd, componentId, "containerPDC",
                        componentName);
            }

            // commit the transactions
            connectionProd.commit();
        }
        if (startNewTransaction) {
            domainDriverManager.commit();
        }
        cache.opRemoveComponent(componentInst);
        TreeCache.removeComponent(getDriverSpaceId(sFatherClientId), componentId);

        // unindex component
        deleteComponentIndex(componentId);

        deleteComponentData(componentId);

        return componentId;
    } catch (Exception e) {
        try {
            // Roll back the transactions
            if (startNewTransaction) {
                domainDriverManager.rollback();
            }
            if (connectionProd != null) {
                connectionProd.rollback();
            }
        } catch (Exception e1) {
            SilverTrace.error(MODULE_ADMIN, "Admin.deleteComponentInst", "root.EX_ERR_ROLLBACK", e1);
        }
        throw new AdminException("Admin.deleteComponentInst", SilverpeasException.ERROR,
                "admin.EX_ERR_DELETE_COMPONENT", "component Id: '" + componentId + "'", e);
    } finally {
        if (startNewTransaction) {
            domainDriverManager.releaseOrganizationSchema();
        }
        DBUtil.close(connectionProd);
    }
}

From source file:com.concursive.connect.web.modules.profile.utils.ProjectCopier.java

public static Project clone(CloneBean bean, Connection db, int groupId, int userId) throws SQLException {
    Project project = null;/*from  w  ww  . j a va  2s  .  com*/
    try {
        db.setAutoCommit(false);

        int oldProjectId = bean.getProjectId();

        // Load permissions and resources for this member
        LOG.debug("ProjectCopier-> ProjectId: " + oldProjectId);
        LOG.debug("ProjectCopier-> UserId: " + userId);

        User user = UserUtils.loadUser(userId);

        LookupList roleList = new LookupList(db, "lookup_project_role");

        // Load old project, change some values, save as new project
        project = new Project(db, oldProjectId);

        TeamMember member = null;
        if (!project.getPortal()) {
            member = new TeamMember(db, oldProjectId, userId);
        }

        // Offset in days
        long offset = 0;
        if (bean.getResetActivityDates() && bean.getRequestDate() != null && project.getRequestDate() != null) {
            offset = bean.getRequestDate().getTime() - project.getRequestDate().getTime();
        }
        project.setId(-1);
        project.setUniqueId(null);
        project.setGroupId(groupId);
        project.setEnteredBy(userId);
        project.setModifiedBy(userId);
        project.setEntered((Timestamp) null);
        project.setModified((Timestamp) null);
        if (bean.getTitle() != null) {
            project.setTitle(bean.getTitle());
        } else {
            project.setTitle(project.getTitle() + " (copy)");
        }
        if (!hasPermission(db, project, user, member, "project-details-view", roleList)) {
            project.setRequestedBy("");
            project.setRequestedByDept("");
            project.setBudget(0);
        }
        if (bean.getRequestDate() != null) {
            project.setRequestDate(bean.getRequestDate());
        } else {
            project.setRequestDate(new Timestamp(System.currentTimeMillis()));
        }
        project.setClosed(false);
        project.setCloseDate((Timestamp) null);
        project.setEstimatedCloseDate((Timestamp) null);
        project.setApprovalDate((Timestamp) null);
        project.setApproved(false);
        project.setClone(true);
        project.buildPermissionList(db);
        project.insert(db);
        if (project.getId() == -1) {
            throw new SQLException("Project object validation failed");
        }
        project.updateFeatures(db);

        // Permissions
        PermissionList permissions = new PermissionList();
        permissions.setProjectId(oldProjectId);
        permissions.buildList(db);
        permissions.setProjectId(project.getId());
        permissions.insert(db);

        // Team
        if (bean.getCloneTeam() && hasPermission(db, project, user, member, "project-team-view", roleList)) {
            TeamMemberList team = new TeamMemberList();
            team.setProjectId(oldProjectId);
            team.buildList(db);
            team.setProjectId(project.getId());
            team.setEnteredBy(userId);
            team.setModifiedBy(userId);
            team.removeTeamMember(userId);
            team.insert(db);
        }
        // Add the current user to the team as Project Lead
        int roleUserLevel = roleList.getIdFromLevel(TeamMember.PROJECT_ADMIN);
        TeamMember thisMember = new TeamMember();
        thisMember.setProjectId(project.getId());
        thisMember.setUserId(userId);
        thisMember.setUserLevel(roleUserLevel);
        thisMember.setEnteredBy(userId);
        thisMember.setModifiedBy(userId);
        thisMember.insert(db);

        // News
        if (bean.getCloneNewsCategories() || bean.getCloneNews()) {
            HashMap categoryMap = new HashMap();
            if (bean.getCloneNewsCategories()
                    && hasPermission(db, project, user, member, "project-news-view", roleList)) {
                // Copy the news categories
                BlogPostCategoryList categoryList = new BlogPostCategoryList();
                categoryList.setProjectId(oldProjectId);
                categoryList.buildList(db);
                categoryList.setProjectId(project.getId());
                categoryList.insert(db, categoryMap);
            }

            if (bean.getCloneNews()
                    && hasPermission(db, project, user, member, "project-news-view", roleList)) {
                // Copy the news
                BlogPostList news = new BlogPostList();
                news.setProjectId(oldProjectId);
                news.buildList(db);
                news.setProjectId(project.getId());
                news.setEnteredBy(userId);
                news.setModifiedBy(userId);
                news.remapCategories(categoryMap);
                // TODO: Adjust startDate and endDate based on today?
                news.insert(db);
                // TODO: Need to copy the news image library
            }
        }

        // Discussion Forums
        if (bean.getCloneForums()
                && hasPermission(db, project, user, member, "project-discussion-forums-view", roleList)) {
            ForumList forums = new ForumList();
            forums.setProjectId(oldProjectId);
            forums.buildList(db);
            // TODO: Discussion Topics
            forums.setProjectId(project.getId());
            forums.setEnteredBy(userId);
            forums.setModifiedBy(userId);
            forums.insert(db);
        }

        // Document Folders
        if (bean.getCloneDocumentFolders()
                && hasPermission(db, project, user, member, "project-documents-view", roleList)) {
            FileFolderHierarchy hierarchy = new FileFolderHierarchy();
            hierarchy.setLinkModuleId(Constants.PROJECTS_FILES);
            hierarchy.setLinkItemId(oldProjectId);
            hierarchy.build(db);
            FileFolderList folders = hierarchy.getHierarchy();
            folders.setLinkItemId(project.getId());
            folders.setEnteredBy(userId);
            folders.setModifiedBy(userId);
            folders.insert(db);
        }

        // Lists
        if (bean.getCloneLists() && hasPermission(db, project, user, member, "project-lists-view", roleList)) {
            TaskCategoryList lists = new TaskCategoryList();
            lists.setProjectId(oldProjectId);
            lists.buildList(db);
            lists.setProjectId(project.getId());
            lists.setEnteredBy(userId);
            lists.setModifiedBy(userId);
            lists.setOwner(userId);
            if (bean.getCloneListItems()) {
                lists.insert(db, true);
            } else {
                lists.insert(db, false);
            }
        }

        if (System.getProperty("DEBUG") != null) {
            System.out.println("ProjectCopier-> before wiki");
        }
        // Wiki
        if (bean.getCloneWiki() && hasPermission(db, project, user, member, "project-wiki-view", roleList)) {
            LOG.debug("ProjectCopier-> Inserting wiki");

            // The wiki items
            WikiList wikiList = new WikiList();
            wikiList.setProjectId(oldProjectId);
            wikiList.buildList(db);
            wikiList.setEnteredBy(userId);
            wikiList.setModifiedBy(userId);
            wikiList.setProjectId(project.getId());
            wikiList.insert(db);
            wikiList = null;
            // TODO: The wiki images -- references and files
            /*FileItemList wikiImages = new FileItemList();
            wikiImages.setLinkModuleId(Constants.PROJECT_WIKI_FILES);
            wikiImages.setLinkItemId(oldProjectId);
            wikiImages.buildList(db);
            wikiImages.setLinkItemId(project.getId());
            wikiImages.copyTo(newPath);
            wikiImages.insert(db);
            wikiImages = null;*/
        }

        // Ticket Configuration
        if (bean.getCloneTicketConfig()
                && hasPermission(db, project, user, member, "project-tickets-view", roleList)) {
            // Ticket Categories
            HashMap categoryMap = new HashMap();
            TicketCategoryList categoryList = new TicketCategoryList();
            categoryList.setProjectId(oldProjectId);
            categoryList.buildList(db);
            categoryList.setProjectId(project.getId());
            categoryList.insert(db, categoryMap);
            // Ticket Defect Lookup
            ProjectItemList defectList = new ProjectItemList();
            defectList.setProjectId(oldProjectId);
            defectList.setEnabled(Constants.TRUE);
            defectList.buildList(db, ProjectItemList.TICKET_DEFECT);
            defectList.setProjectId(project.getId());
            defectList.insert(db, null, ProjectItemList.TICKET_DEFECT);
            // Ticket States Lookup
            ProjectItemList stateList = new ProjectItemList();
            stateList.setProjectId(oldProjectId);
            stateList.setEnabled(Constants.TRUE);
            stateList.buildList(db, ProjectItemList.TICKET_STATE);
            stateList.setProjectId(project.getId());
            stateList.insert(db, null, ProjectItemList.TICKET_STATE);
            // Ticket Causes Lookup
            ProjectItemList causeList = new ProjectItemList();
            causeList.setProjectId(oldProjectId);
            causeList.setEnabled(Constants.TRUE);
            causeList.buildList(db, ProjectItemList.TICKET_CAUSE);
            causeList.setProjectId(project.getId());
            causeList.insert(db, null, ProjectItemList.TICKET_CAUSE);
            // Ticket Resolution Lookup
            ProjectItemList resolutionList = new ProjectItemList();
            resolutionList.setProjectId(oldProjectId);
            resolutionList.setEnabled(Constants.TRUE);
            resolutionList.buildList(db, ProjectItemList.TICKET_RESOLUTION);
            resolutionList.setProjectId(project.getId());
            resolutionList.insert(db, null, ProjectItemList.TICKET_RESOLUTION);
            // Ticket Escalation Lookup
            ProjectItemList escalationList = new ProjectItemList();
            escalationList.setProjectId(oldProjectId);
            escalationList.setEnabled(Constants.TRUE);
            escalationList.buildList(db, ProjectItemList.TICKET_ESCALATION);
            escalationList.setProjectId(project.getId());
            escalationList.insert(db, null, ProjectItemList.TICKET_ESCALATION);
        }

        // Outlines, Activities, Activity Folders (no notes yet)
        if (bean.getCloneActivities()
                && hasPermission(db, project, user, member, "project-plan-view", roleList)) {
            RequirementList outlines = new RequirementList();
            outlines.setProjectId(oldProjectId);
            outlines.buildList(db);
            outlines.setProjectId(project.getId());
            outlines.setEnteredBy(userId);
            outlines.setModifiedBy(userId);
            outlines.setOffset(offset);
            if (bean.getResetActivityStatus()) {
                outlines.setResetStatus(true);
            }
            outlines.insert(db, oldProjectId);
        }
        db.commit();
    } catch (Exception e) {
        LOG.error("clone", e);
        db.rollback();
    } finally {
        db.setAutoCommit(true);
    }
    return project;
}

From source file:dao.DirectoryDaoDb.java

/**
  * Update an existing in a directory./*from  www .j  a  va2 s .  c o m*/
  * User permissions are checked before the user is allowed to update it.
  * If the user is the userid or admin, update directory.
  * if the user has permission to rename or modify in the permission directory, update directory.
  * @param directoryId - directory id
  * @param dirname - directory name (destination directory name)
  * @param keywords - keywords
  * @param scopeid - scope id
  * @param desc - description
  * @param operations - operations allowed in this directory
  * @param authorid - author id or login id of this author
  * @param dirPath - directory path
  * @param srcDirName - original or source directory name
  * @throws BaseDaoException If we have a problem interpreting the data or the data is missing or incorrect
 */
public void updateDirectory(String directoryId, String dirname, String keywords, String scopeid, String desc,
        String operations, String authorid, String userLogin, String dirPath, String srcDirName)
        throws BaseDaoException {

    /**
    *  check only dirname and owner. others can be null.
    */
    if (RegexStrUtil.isNull(authorid) || RegexStrUtil.isNull(directoryId) || RegexStrUtil.isNull(dirname)) {
        throw new BaseDaoException("params are null");
    }

    /**
     *  isDiaryAdmin or isAuthor
     */
    if ((!diaryAdmin.isDiaryAdmin(userLogin)) && (!isAuthor(directoryId, authorid))) {
        throw new BaseDaoException("User is neither a diaryAdmin nor author to update directory = "
                + directoryId + " authorid =" + authorid);
    }

    /**
     *  Get scalability datasource for directory - not partitioned
     */
    String sourceName = scalabilityManager.getWriteZeroScalability();
    ds = scalabilityManager.getSource(sourceName);
    if (ds == null) {
        throw new BaseDaoException("ds null, updateDirectory() " + sourceName);
    }

    /**
    * children do not exist then, rename the dirname
    * isDirTreeRenameEnabled(), rename the dirname
    */
    if (!childrenExist(directoryId) || WebUtil.isDirTreeRenameEnabled()) {
        if (WebUtil.isSanEnabled() && !RegexStrUtil.isNull(dirname)) {
            if (!RegexStrUtil.isNull(srcDirName) && !srcDirName.equals(dirname)) {
                try {
                    getSanUtils();
                    /** 
                          * renames the directory from srcDirName to dirname 
                          */
                    sanUtils.renameSanDir(dirPath, srcDirName, SanConstants.sanPath, dirname);
                } catch (SanException e) {
                    throw new BaseDaoException("error in renameSanDir(), updateDirectory()" + directoryId
                            + " srcDirName " + srcDirName + " dirname = " + dirname + " dirPath = " + dirPath
                            + " error message = " + e.getMessage(), e);
                }
            }
        }
    }

    // where do we get the stateid from ?
    String stateid = "null";
    Connection conn = null;
    try {
        conn = ds.getConnection();
        conn.setAutoCommit(false);
        /**
        *  1) isDirTreeRenameEnabled() is true, rename the directory 
             *  2) if children do not exist, rename the directory
        */
        if (childrenExist(directoryId)) {
            if (!WebUtil.isDirTreeRenameEnabled()) {
                directoryupdateQuery.run(conn, directoryId, keywords, desc);
            } else {
                /* 
                * update the dirname
                     */
                directoryrenameQuery.run(conn, directoryId, dirname, keywords, desc);
                /*
                 * update the dirname in the dirpath for the children
                * subdirectories
                *
                 * directoryId is the mainDir that is being renamed
                 * so set it to true
                 */
                StringBuffer oldPath = new StringBuffer(srcDirName);
                oldPath.append(DbConstants.DIRPATH_PIPE);
                oldPath.append(directoryId);

                StringBuffer newPath = new StringBuffer(dirname);
                newPath.append(DbConstants.DIRPATH_PIPE);
                newPath.append(directoryId);
                //logger.info("params to updatePath(), oldPath = " + oldPath + " newPath=" + newPath + " directoryId=" + directoryId);

                updatePath(directoryId, newPath.toString(), oldPath.toString(), conn, true);

                /** create new segment of dirpath **/
                /*
                            List subDirs = getListOfSubDirs(directoryId, DbConstants.READ_FROM_MASTER);
                       if (subDirs != null && subDirs.size() > 0) {
                          StringBuffer sb = new StringBuffer();
                                    sb.append(DbConstants.DIRPATH_COLON);
                                    sb.append(dirname);
                                    sb.append(DbConstants.DIRPATH_PIPE);
                                    sb.append(directoryId);
                                    String replaceDirNamePath = sb.toString();
                        
                               sb.delete(0, sb.length());
                          sb.append(DbConstants.DIRPATH_COLON);
                          sb.append(srcDirName);
                          sb.append(DbConstants.DIRPATH_PIPE);
                          sb.append(directoryId);
                          String oldDirNamePath = sb.toString();
                        
                               for (int i = 0; i < subDirs.size(); i++) {
                             if (subDirs.get(i) != null) {
                                 String subDirId = ((Directory)subDirs.get(i)).getValue(DbConstants.DIRECTORY_ID);
                                 Directory subDirWhole = getDirectory(subDirId, authorid);
                                if (subDirWhole != null) {
                                   String subDirPath = subDirWhole.getValue(DbConstants.DIRPATH);
                logger.info("oldDirNamePath = " + oldDirNamePath + " newDirNamePath = " + replaceDirNamePath);
                              subDirPath = RegexStrUtil.replaceString(subDirPath, oldDirNamePath, replaceDirNamePath);
                                   dirPasteQuery.run(conn, subDirId, subDirPath);
                           }
                             }
                          }
                       }
                */
            }
        } else {

            /* 
            * Children do not exist 
            */
            if (RegexStrUtil.isNull(dirname)) {
                throw new BaseDaoException(
                        "dirname is null for update " + directoryId + " authorid = " + authorid);
            }
            directoryrenameQuery.run(conn, directoryId, dirname, keywords, desc);
        }
        scopeupdateQuery.run(conn, directoryId, scopeid, operations);
    } catch (Exception e) {
        try {
            conn.rollback();
        } catch (Exception e1) {
            try {
                if (conn != null) {
                    conn.setAutoCommit(true);
                    conn.close();
                }
            } catch (Exception e2) {
                throw new BaseDaoException(
                        "conn.close() exception for rollback(), for update directory/scope tables params (6) "
                                + " dirname = " + dirname + " keywords = " + keywords + " desc = " + desc
                                + " dirid = " + directoryId,
                        e2);
            }
            throw new BaseDaoException("rollback() exception,  for update directory/scope" + " dirname = "
                    + dirname + " keywords = " + keywords + " desc = " + desc + " dirId = " + directoryId, e1);
        }
        throw new BaseDaoException("for update directory/scope tables params " + " dirname = " + dirname
                + " keywords = " + keywords + " desc = " + desc + " directoryId = " + directoryId, e);
    }

    // connection commit
    try {
        conn.commit();
    } catch (Exception e3) {
        throw new BaseDaoException("commit() exception, for update directory" + " dirname = " + dirname
                + " keywords = " + keywords + " desc = " + desc + " directoryId = " + directoryId, e3);
    }

    try {
        if (conn != null) {
            conn.setAutoCommit(true);
            conn.close();
        }
    } catch (Exception e4) {
        throw new BaseDaoException("conn.close() exception for commit(), updateDirectory" + " dirname = "
                + dirname + " keywords = " + keywords + " desc = " + desc + " directoryId = " + directoryId,
                e4);
    }

    /**
     * remove directory from cache
     */
    Fqn fqn = cacheUtil.fqn(DbConstants.DIRECTORY);
    if (treeCache.exists(fqn, directoryId)) {
        treeCache.remove(fqn, directoryId);
    }

    fqn = cacheUtil.fqn(DbConstants.DIR_SCOPE);
    if (treeCache.exists(fqn, directoryId)) {
        treeCache.remove(fqn, directoryId);
    }

    /**
    * check for parent and remove the parent from cache
    */
    String parentId = getParentId(directoryId);
    fqn = cacheUtil.fqn(DbConstants.DIRECTORY);
    if (treeCache.exists(fqn, parentId)) {
        treeCache.remove(fqn, parentId);
    }
}

From source file:com.iana.boesc.dao.BOESCDaoImpl.java

@Override
public boolean getPopulatedDataAndInsert(EDI322Bean eb, String boescUserId, String userType, File file,
        List<String> finalErrorList, Map<Integer, Object> fileTransStatus) throws Exception {
    logger.info("----- getPopulatedDataAndInsert ............" + " boescUserId ::" + boescUserId
            + " userType ::" + userType);
    String status = "";
    logger.info("----- ISA  ............");
    String gsHeader = "";
    String gsControl = "";
    String st_control = "";
    String n7Header = "";
    String q5Header = "";
    String equip_prefix = "";
    String equip_number = "";
    String w2Header = "";
    String r4Header = "";
    String r13Header = "";
    String n9Header = "";
    String eventType = "";
    String port_qual = "";
    String iana_splc = "";

    QueryRunner qrun = new QueryRunner(getDataSource());
    logger.info("----- GE  ............");
    for (int i = 0; i < eb.getListGSDetails().size(); i++) {
        gsHeader = eb.getListGSDetails().get(i).getHeaderDetails();
        gsControl = eb.getListGSDetails().get(i).getGroupControlNumber();
        logger.info("gsControl ::" + gsControl + " gsHeader ::" + gsHeader);
        int startIndex = i + 1;
        logger.info("----- ST & SE  ............");
        for (int a = 0; a < eb.getSTDetailsMap().get(startIndex).size(); a++) {

            Connection conn = getConnection();
            conn.setAutoCommit(false);//from   w  w w  .  ja  v  a  2 s . c o m
            PreparedStatement pstmt = null;
            ResultSet rs = null;
            StringBuilder sbQuery = new StringBuilder(
                    "INSERT INTO BOESC_TRAN_SET (ISA_HEADER, GS_HEADER, INPUT_TYPE, SENDER_ID, SENDER_TYPE, ");
            sbQuery.append(
                    " ISA_DATETIME, GS_CONTROL, ST_CONTROL, EVENT_TYPE, EQ_PREFIX, EQ_NUMBER, CHASSIS_ID, IEP_SCAC, IEP_DOT, PORT_QUAL, IANA_SPLC, ");
            sbQuery.append(" POOL_ID, POOL_NAME, Q5_SEG, N7_SEG, W2_SEG, R4_SEG, N9_SEG, R13_SEG, ");

            if (userType.equalsIgnoreCase(GlobalVariables.USER_TYPE_IEP)) {
                sbQuery.append(" RECEIVER_ID, REC_STATUS   ");
            } else if (userType.equalsIgnoreCase(GlobalVariables.USER_TYPE_MRV)) {
                sbQuery.append(" MRV_ID, MRV_STATUS   ");
            } else if (userType.equalsIgnoreCase(GlobalVariables.USER_TYPE_FO)) {
                sbQuery.append(" FO_ID, FO_STATUS ");

            } else if (userType.equalsIgnoreCase(GlobalVariables.USER_TYPE_SU)) {

            }

            try {
                status = "";
                int changedIndex = a + 1; //very important Variable
                if (fileTransStatus != null && fileTransStatus.size() > 0) {
                    logger.info("-------------------- changedIndex ::" + changedIndex
                            + " fileTransStatus.get(startIndex)  ::" + fileTransStatus.get(changedIndex));
                    if (fileTransStatus.get(changedIndex) == null) {
                        status = GlobalVariables.STATUS_PENDING;
                    } else {
                        status = GlobalVariables.STATUS_REJECTED;
                    }
                } else {
                    status = GlobalVariables.STATUS_PENDING;
                }

                r13Header = "";
                r4Header = "";
                n9Header = "";
                port_qual = "";
                iana_splc = "";
                GIERInfoDetails gierInfo = null;

                st_control = eb.getSTDetailsMap().get(startIndex).get(a).getTransactionSetControlNumber();
                logger.info("  st_control :" + st_control);

                /*String transactionControlNumberSE  = eb.getSEDetailsMap().get(startIndex).get(a).getTransactionSetControlNumber();
                logger.info("  transactionControlNumberSE :"+transactionControlNumberSE );*/

                logger.info("----- N7  ............");

                for (int q = 0; q < eb.getN7DetailsMap().get(startIndex).get(changedIndex).size(); q++) {
                    n7Header = eb.getN7DetailsMap().get(startIndex).get(changedIndex).get(q).getHeaderDetails();
                    logger.info("n7Header ::" + n7Header);
                    equip_prefix = eb.getN7DetailsMap().get(startIndex).get(changedIndex).get(q)
                            .getEquipmentInitial();
                    equip_number = eb.getN7DetailsMap().get(startIndex).get(changedIndex).get(q)
                            .getEquipmentNumber();

                    logger.info("equip_prefix ::" + equip_prefix);
                    logger.info("equip_number ::" + equip_number);
                    equip_prefix = equip_prefix == null || equip_prefix.trim().length() == 0 ? ""
                            : equip_prefix;
                    equip_number = equip_number == null || equip_number.trim().length() == 0 ? ""
                            : equip_number;
                    gierInfo = getDVIRAdditionaldetails(equip_prefix, equip_number);
                    //logger.info("gierInfo ::"+gierInfo);

                }

                logger.info("----- Q5  ............");
                for (int q = 0; q < eb.getQ5DetailsMap().get(startIndex).get(changedIndex).size(); q++) {
                    q5Header = eb.getQ5DetailsMap().get(startIndex).get(changedIndex).get(q).getHeaderDetails();
                    eventType = eb.getQ5DetailsMap().get(startIndex).get(changedIndex).get(q).getStatusCode();
                    logger.info("q5Header ::" + q5Header + " eventType ::" + eventType);
                }

                logger.info("----- W2  ............");
                for (int q = 0; q < eb.getW2DetailsMap().get(startIndex).get(changedIndex).size(); q++) {
                    w2Header = eb.getW2DetailsMap().get(startIndex).get(changedIndex).get(q).getHeaderDetails();
                    logger.info("w2Header ::" + w2Header);
                }

                logger.info("----- R4  ............");
                String tempR4Header = "";
                String tempPort_qual = "";
                String tempIana_splc = "";
                for (int q = 0; q < eb.getR4DetailsMap().get(startIndex).get(changedIndex).size(); q++) {
                    tempR4Header = eb.getR4DetailsMap().get(startIndex).get(changedIndex).get(q)
                            .getHeaderDetails();
                    tempPort_qual = eb.getR4DetailsMap().get(startIndex).get(changedIndex).get(q)
                            .getLocationQualifier();
                    tempIana_splc = eb.getR4DetailsMap().get(startIndex).get(changedIndex).get(q)
                            .getLocationIdentifier();
                    r4Header = r4Header + GlobalVariables.FIELD_SEPARATOR + tempR4Header;
                    port_qual = port_qual + GlobalVariables.FIELD_SEPARATOR + tempPort_qual;
                    iana_splc = iana_splc + GlobalVariables.FIELD_SEPARATOR + tempIana_splc;
                    logger.info("r4Header ::" + r4Header + " port_qual:: " + port_qual + " iana_splc ::"
                            + iana_splc);

                }
                r4Header = r4Header.startsWith(GlobalVariables.FIELD_SEPARATOR) == true ? r4Header.substring(1)
                        : r4Header;
                port_qual = port_qual.startsWith(GlobalVariables.FIELD_SEPARATOR) == true
                        ? port_qual.substring(1)
                        : port_qual;
                iana_splc = iana_splc.startsWith(GlobalVariables.FIELD_SEPARATOR) == true
                        ? iana_splc.substring(1)
                        : iana_splc;

                logger.info("----- R13  ............");
                String tempR13Header = "";
                for (int q = 0; q < eb.getR13DetailsMap().get(startIndex).get(changedIndex).size(); q++) {
                    tempR13Header = eb.getR13DetailsMap().get(startIndex).get(changedIndex).get(q)
                            .getHeaderDetails();
                    r13Header = r13Header + GlobalVariables.FIELD_SEPARATOR + tempR13Header;
                    logger.info("r13Header ::" + r13Header);
                }
                r13Header = r13Header.startsWith(GlobalVariables.FIELD_SEPARATOR) == true
                        ? r13Header.substring(1)
                        : r13Header;

                logger.info("----- N9  ............");
                String tempN9Header = "";
                for (int q = 0; q < eb.getN9DetailsMap().get(startIndex).get(changedIndex).size(); q++) {
                    tempN9Header = eb.getN9DetailsMap().get(startIndex).get(changedIndex).get(q)
                            .getHeaderDetails();
                    n9Header = n9Header + GlobalVariables.FIELD_SEPARATOR + tempN9Header;
                    logger.info("n9Header ::" + n9Header);
                }
                n9Header = n9Header.startsWith(GlobalVariables.FIELD_SEPARATOR) == true ? n9Header.substring(1)
                        : n9Header;

                sbQuery.append(
                        " , CREATED_DATE) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");

                if (gierInfo == null) {
                    gierInfo = new GIERInfoDetails(); //this situation happen when all segment are missing except : ISA,SE,ST,GE,GS,IEA
                }

                equip_prefix = equip_prefix == null || equip_prefix.trim().length() == 0 ? "" : equip_prefix;
                equip_number = equip_number == null || equip_number.trim().length() == 0 ? "" : equip_number;

                pstmt = conn.prepareStatement(sbQuery.toString(), Statement.RETURN_GENERATED_KEYS);
                pstmt.setString(1, eb.getISADetails().getHeaderDetails());
                pstmt.setString(2, gsHeader);
                pstmt.setString(3, GlobalVariables.INPUT_TYPE_BOESC_322);
                pstmt.setString(4, eb.getISADetails().getInterchangeSenderId());
                pstmt.setString(5, userType);
                pstmt.setString(6, eb.getISADetails().getInterchangeDate());
                pstmt.setString(7, gsControl);
                pstmt.setString(8, st_control);
                pstmt.setString(9, eventType);
                pstmt.setString(10, equip_prefix);
                pstmt.setString(11, equip_number);
                pstmt.setString(12, equip_prefix + equip_number);
                pstmt.setString(13, gierInfo.getCompanySCACCode() == null ? "" : gierInfo.getCompanySCACCode());
                pstmt.setString(14, gierInfo.getUsDotNumber() == null ? "" : gierInfo.getUsDotNumber());
                pstmt.setString(15, port_qual);
                pstmt.setString(16, iana_splc);
                pstmt.setString(17, gierInfo.getChassisPoolId() == null ? "" : gierInfo.getChassisPoolId());
                pstmt.setString(18, gierInfo.getChassisPoolName() == null ? "" : gierInfo.getChassisPoolName());
                pstmt.setString(19, q5Header);
                pstmt.setString(20, n7Header);
                pstmt.setString(21, w2Header);
                pstmt.setString(22, r4Header);
                pstmt.setString(23, n9Header);
                pstmt.setString(24, r13Header);
                pstmt.setString(25, boescUserId);
                pstmt.setString(26, status);
                pstmt.setObject(27, DateTimeFormater.getSqlSysTimestamp());

                logger.info("query :: " + sbQuery.toString());
                int dbStat = 0;
                int boescKey = 0;
                dbStat = pstmt.executeUpdate();
                rs = pstmt.getGeneratedKeys();
                if (dbStat != 0) {
                    if (rs != null) {
                        while (rs.next()) {
                            boescKey = rs.getInt(1);
                            logger.info("boescKey: " + boescKey);
                        }
                    }

                    conn.commit();
                } else {
                    conn.rollback();
                }
                if (boescKey != 0) {
                    //Update BOESC_UNIQUE_NO : using business logic
                    String sql = "UPDATE BOESC_TRAN_SET SET BOESC_UNIQUE_NO = ? WHERE BOESC_TRAN_ID = ? ";
                    qrun.update(sql, new Object[] { Utility.addPadToUniqueNum(boescKey, "BOESC-"), boescKey });
                    logger.info("Record Inserted successfully for BOESC..." + file.getName());
                    return true;
                } else {
                    logger.error("Failure Data insertion in BOESC..");
                }
            } finally {
                try {
                    if (rs != null) {
                        rs.close();
                    }
                    if (pstmt != null) {
                        pstmt.close();
                    }
                    if (conn != null) {
                        conn.close();
                    }
                } catch (SQLException ex1) {
                    logger.error("Caught SQL exception while closing prepared statement /resultset "
                            + ex1.getMessage());
                    ex1.printStackTrace();
                    throw ex1;
                } catch (Exception e) {
                    logger.error("Caught SQL exception in finally block " + e.getMessage());
                    e.printStackTrace();
                    throw e;
                }
            }
        }
    }

    return false;
}

From source file:com.pari.nm.utils.db.InventoryDBHelper.java

public static boolean updateDeviceDetails(NetworkNode device, boolean manage, String deviceKnownIp,
        boolean updatevirtualDevice, int updateDeviceId, boolean discoveryJob) {
    PreparedStatement ps = null;/*w  w  w. j a v  a  2s .  c o m*/
    Connection c = null;
    int deviceId = updateDeviceId;
    try {
        c = DBHelper.getConnection();
        c.setAutoCommit(false);
        boolean insert = true;

        if (updatevirtualDevice) {
            insert = false;
            ps = c.prepareStatement(DBHelperConstants.NODE_UPDATE);
        } else {
            ps = c.prepareStatement(DBHelperConstants.NODE_INSERT);
        }
        Timestamp ts = null;
        // CSCtr59009 -Bug fix - Fix for timestamp issue of discovered
        // devices.
        if (device.getDiscoveredTime() > 0) {
            ts = new Timestamp(device.getDiscoveredTime());
        } else {
            synchronized (lock) {
                // Even though synchronization here looks unnecessary, all
                // we are trying to do
                // is to gaurantee a distinct timestamp value across
                // multiple threads in which
                // updateDeviceDetails() method is invoked
                ts = new Timestamp(System.currentTimeMillis());
                Thread.sleep(1);
            }
        }
        if (insert) {
            // logger.debug("Before inserting before device: " +
            // deviceKnownIp);
            ps.setString(1, deviceKnownIp);
            // ps.setInt(2, device.getVersion().getVersionType().typeInt);
            ps.setInt(2, device.getVersion().getOsTypeDetails().getOsId());
            // ps.setString(3, device.getVersion().getDeviceType());

            // Setting Device Family as family
            ps.setString(3, device.getVersion().getDeviceFamily());
            ps.setString(4, device.getVendorName());
            ps.setString(5, manage ? "m" : "u");

            ps.setTimestamp(6, ts);
            ps.setInt(7, device.getDeviceMode());
            ps.setString(8, device.getSysObjectID());
            // Setting ShowFamilyAs as Product_Family
            ps.setString(9, device.getVersion().getShowFamilyAs());
            ps.setString(10, device.getVersion().getOsTypeDetails().getOsAlias());
            ps.setString(11, device.getProductId());
        } else {
            // ps.setString(1, device.getVersion().getDeviceType());

            // Setting Device Family as family
            ps.setString(1, device.getVersion().getDeviceFamily());
            ps.setString(2, device.getVendorName());
            ps.setString(3, manage ? "m" : "u");
            // ps.setInt(4, device.getVersion().getVersionType().typeInt);
            ps.setInt(4, device.getVersion().getOsTypeDetails().getOsId());
            ps.setInt(5, device.getDeviceMode());
            ps.setTimestamp(6, ts); // CSCtr59009 - updating timestamp also
            if (device.getSysObjectID() != null && !device.getSysObjectID().isEmpty()) {
                ps.setString(7, device.getSysObjectID());
            } else {
                ps.setString(7, null);
            }
            // Setting ShowFamilyAs as Product_Family
            ps.setString(8, device.getVersion().getShowFamilyAs());
            ps.setString(9, device.getVersion().getOsTypeDetails().getOsAlias());
            ps.setString(10, device.getProductId());
            ps.setInt(11, deviceId);

        }
        int id = -1;
        if (insert) {
            synchronized (lock) {
                ps.executeUpdate();
                id = getCurrentMaxNodeId(c, device);
            }
        } else {
            ps.executeUpdate();
        }

        if (insert) {
            // logger.debug("Just inserted device: " + deviceKnownIp);
            if (id >= 0) {
                logger.debug("Setting nodeId: " + id + " for device: " + deviceKnownIp);
                device.setNodeId(id);
                /*
                 * DeviceWeightage weightage = DeviceWeightageManager.getInstance ().getWeightage(device);
                 * device.setWeightageObj(weightage);
                 */
                if (!discoveryJob) {
                    BackupSoftwareImageRequestProcessor.getInstance().processRequest(id);
                    // logger.debug("Device :"+id+" is added to Automatic Backup Job.... ");
                }
            } else {
                throw new Exception("Unable to get new device ID for device: " + deviceKnownIp);
            }
            /*
             * try {
             *
             * PreparedStatement ps1 = null; // rs = DBHelper.executeQueryNoCommit(c,
             * "select max(id) as id from nodes"); ps1 = c.prepareStatement(DBHelperConstants.NODE_DISOVERED);
             * ps1.setTimestamp(1, ts); rs = ps1.executeQuery();
             *
             * if ((rs != null) && rs.next()) { int id = rs.getInt("ID");
             *
             * device.setNodeId(id); } } catch (Exception ex) { ex.printStackTrace(); } finally { try { ps1.close();
             * } catch (Exception ex) {} }
             */
        } else {
            device.setNodeId(deviceId);
        }
        c.commit();
    } catch (Exception ee) {
        ee.printStackTrace();
        logger.warn("Error while updating deviceDetails for the deviceId " + updateDeviceId, ee);
        try {
            if (c != null) {
                c.rollback();
            }
        } catch (Exception e) {
        }
        return false;
    } finally {
        try {
            if (ps != null) {
                ps.close();
            }
        } catch (Exception ee) {
        }

        try {
            if (c != null) {
                c.setAutoCommit(true);
            }
        } catch (Exception e) {
        }

        try {
            DBHelper.releaseConnection(c);
        } catch (Exception ee) {
        }
    }
    return true;
}

From source file:com.att.pirates.controller.ProjectController.java

private void processProjectAppOwnersByArtifactName(List<ProjectAppOwnerModel> existingOwners,
        List<ProjectAppOwnerModel> userSelectedOwners, String artifactName, String dueDateForArtifact,
        String UUID, int impactId) {
    if (impactId == 4 && artifactName.equalsIgnoreCase(PiratesConstants.ISTExec)) {
        return;//from   w  ww. jav a  2 s . co m
    }

    Connection con = null;
    PreparedStatement updateRow = null;
    PreparedStatement deleteRow = null;
    PreparedStatement insertRow = null;
    PreparedStatement syncRow = null;
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String today = format.format(Calendar.getInstance().getTime());

    String insertSQL = " INSERT INTO [AppProjectArtifactOwners] " + "           ([UUID] "
            + "           ,[DueDate] " + "           ,[ArtifactName] " + "           ,[PRISMId] "
            + "           ,[ApplicationName] " + "           ,[ModuleId] " + "           ,[IsPrimaryOwner] "
            + "           ,[MileStoneId] " + "           ,[DateCreated] " + "           ,[UpdatedByUUID] "
            + "           ,[SystemNote]) " + "     VALUES " + "           ( ?,?,?,?,?,?,?,?,?,?,?)  ";

    String updateSQL = " UPDATE AppProjectArtifactOwners " + "   SET DueDate = ? " + "      ,UpdatedByUUID = ? "
            + "      ,SystemNote = ? " + "       WHERE  "
            + "   UUID = ? and ArtifactName = ? and PRISMId = ? and ApplicationName = ? and ModuleId = ? and MileStoneId = ? ";

    String deleteSQL = " DELETE FROM AppProjectArtifactOwners " + "       WHERE  "
            + "   UUID = ? and ArtifactName = ? and PRISMId = ? and ApplicationName = ? and ModuleId = ? and MileStoneId = ? ";

    // we need to make sure duedates for each artifact for all applications in this project
    // to be in sync
    String syncSQL = " Update a " + " Set a.duedate = t.duedate " + " from AppProjectArtifactOwners a "
            + " join " + " ( " + " select prismid, applicationname, artifactname, duedate "
            + " from AppProjectArtifactOwners " + " Where artifactname = ? and prismid = ? "
            + " And applicationname = ? " + " and isprimaryowner = 1 " + " ) t "
            + " on a.prismid=t.prismid and a.artifactname=t.artifactname "
            + " and a.applicationname <> t.applicationname " + " where a.isprimaryowner = 1 ";

    try {
        List<String> artifactNames = new ArrayList<String>();
        String prismId = "";
        String applicationName = "";

        con = DBUtility.getDBConnection();
        con.setAutoCommit(false);
        insertRow = con.prepareStatement(insertSQL);
        // inserts
        boolean isAdd = false;
        for (ProjectAppOwnerModel o : userSelectedOwners) {
            if (o.getIsNew()) {
                if (!isAdd)
                    isAdd = true;
                logger.error(msgHeader + " userSelectedOwners " + artifactName + " " + o.getUUID()
                        + " is being added..");
                insertRow.setString(1, o.getUUID());
                insertRow.setString(2, o.getDueDate());
                insertRow.setString(3, o.getArtifactName());
                insertRow.setString(4, o.getPrismId());
                insertRow.setString(5, o.getApplicationName());
                insertRow.setInt(6, Integer.valueOf(o.getModuleId()));
                insertRow.setInt(7, 1);
                insertRow.setInt(8, Integer.valueOf(o.getMileStoneId()));
                insertRow.setString(9, today);
                insertRow.setString(10, o.getUpdatedByUUID());
                insertRow.setString(11,
                        "Record created by " + o.getUpdatedByUUID() + " on " + o.getDateCreated());
                insertRow.addBatch();

                // update artifactNames list
                if (!artifactNames.contains(o.getArtifactName())) {
                    artifactNames.add(o.getArtifactName());
                }
                if (prismId.isEmpty()) {
                    prismId = o.getPrismId();
                }
                if (applicationName.isEmpty()) {
                    applicationName = o.getApplicationName();
                }
            }
        }
        if (isAdd)
            insertRow.executeBatch();
        if (!isAdd)
            logger.error(msgHeader + " processProjectAppOwnersByArtifactName.. nothing to insert");

        // updates
        boolean isUpdate = false;
        updateRow = con.prepareStatement(updateSQL);
        for (ProjectAppOwnerModel o : existingOwners) {
            if (o.getIsNew()) {
                // do nothing here... 
            } else {
                SimpleDateFormat yFormat = new SimpleDateFormat("MM/dd/yyyy");
                Date userSelected = yFormat.parse(dueDateForArtifact);
                Date existing = yFormat.parse(o.getDueDate());
                if (existing.compareTo(userSelected) == 0) {
                    logger.error(msgHeader + " new duedate: " + dueDateForArtifact
                            + " is the same as existing duedate " + o.getDueDate()
                            + " , nothing to do here...");
                } else {
                    if (!isUpdate)
                        isUpdate = true;
                    logger.error(msgHeader + " existingOwners " + artifactName + " " + o.getUUID()
                            + " is being updated..");
                    updateRow.setString(1, dueDateForArtifact);
                    updateRow.setString(2, UUID);
                    updateRow.setString(3, "Record updated by " + UUID + " on " + today);
                    updateRow.setString(4, o.getUUID());
                    updateRow.setString(5, o.getArtifactName());
                    updateRow.setString(6, o.getPrismId());
                    updateRow.setString(7, o.getApplicationName());
                    updateRow.setInt(8, Integer.valueOf(o.getModuleId()));
                    updateRow.setInt(9, Integer.valueOf(o.getMileStoneId()));
                    updateRow.addBatch();

                    // update artifactNames list
                    if (!artifactNames.contains(o.getArtifactName())) {
                        artifactNames.add(o.getArtifactName());
                    }
                    if (prismId.isEmpty()) {
                        prismId = o.getPrismId();
                    }
                    if (applicationName.isEmpty()) {
                        applicationName = o.getApplicationName();
                    }
                }
            }
        }
        if (isUpdate)
            updateRow.executeBatch();
        if (!isUpdate)
            logger.error(msgHeader + " processProjectAppOwnersByArtifactName.. nothing to update");

        // deletes
        boolean isDelete = false;
        deleteRow = con.prepareStatement(deleteSQL);
        for (ProjectAppOwnerModel o : existingOwners) {
            if (o.getIsNew()) {
                if (!isDelete)
                    isDelete = true;
                logger.error(msgHeader + " existingOwners " + artifactName + " " + o.getUUID()
                        + " is being deleted..");
                deleteRow.setString(1, o.getUUID());
                deleteRow.setString(2, o.getArtifactName());
                deleteRow.setString(3, o.getPrismId());
                deleteRow.setString(4, o.getApplicationName());
                deleteRow.setInt(5, Integer.valueOf(o.getModuleId()));
                deleteRow.setInt(6, Integer.valueOf(o.getMileStoneId()));

                deleteRow.addBatch();
            } else {
                // do nothing here
            }
        }
        if (isDelete)
            deleteRow.executeBatch();
        if (!isDelete)
            logger.error(msgHeader + " processProjectAppOwnersByArtifactName.. nothing to delete");

        if (isAdd || isUpdate || isDelete) {
            // sync up same artifact, same project different application's due dates
            if (!artifactNames.isEmpty()) {
                syncRow = con.prepareStatement(syncSQL);
                for (String a : artifactNames) {
                    logger.error("Setting syncup parameters.. artifactname: " + a + ", prismId: " + prismId
                            + ", applicationName: " + applicationName);
                    syncRow.setString(1, a);
                    syncRow.setString(2, prismId);
                    syncRow.setString(3, applicationName);
                    syncRow.addBatch();
                }
                syncRow.executeBatch();
            }

            con.commit();
        } else {
            logger.error(msgHeader + " processProjectAppOwnersByArtifactName.. nothing to commit");
        }

    } catch (SQLException e) {
        if (con != null) {
            try {
                logger.error(e.getMessage()
                        + ", processProjectAppOwnersByArtifactName.. Transaction is being rolled back.. "
                        + e.getMessage());
                con.rollback();
            } catch (SQLException excep) {
                logger.error(excep.getMessage()
                        + ", processProjectAppOwnersByArtifactName.. Transaction is being rolled back.."
                        + excep.getMessage());
                try {
                    con.rollback();
                } catch (SQLException logOrIgnore) {
                }
            }
        }
    } catch (Exception ex) {
        logger.error(ex + ", processProjectAppOwnersByArtifactName.. Transaction is being rolled back.."
                + ex.getMessage());
        try {
            con.rollback();
        } catch (SQLException logOrIgnore) {
        }
    } finally {
        if (updateRow != null) {
            try {
                updateRow.close();
            } catch (SQLException e) {
            }
        }
        if (deleteRow != null) {
            try {
                deleteRow.close();
            } catch (SQLException e) {
            }
        }
        if (insertRow != null) {
            try {
                insertRow.close();
            } catch (SQLException e) {
            }
        }
        if (con != null) {
            try {
                con.setAutoCommit(true);
                con.close();
            } catch (SQLException logOrIgnore) {
            }
        }
    }
}

From source file:org.apache.hadoop.hive.metastore.MyXid.java

@Override
public List<String> getDatabases() throws MetaException {
    Connection con;
    Statement stmt = null;//ww  w  . j av  a 2 s  . c  o  m

    List<String> dbNameList = new ArrayList<String>();

    try {
        con = getGlobalConnection();
    } catch (MetaStoreConnectException e1) {
        LOG.error("get databases error msg=" + e1.getMessage());
        throw new MetaException(e1.getMessage());
    } catch (SQLException e1) {
        LOG.error("get databases error msg=" + e1.getMessage());
        throw new MetaException(e1.getMessage());
    }

    try {
        con.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);

        stmt = con.createStatement();
        String sql = "select db_name, owner from router";
        ResultSet ret = stmt.executeQuery(sql);

        dbNameList = new ArrayList<String>();

        while (ret.next()) {
            dbNameList.add(ret.getString(1));
        }
        ret.close();
    } catch (SQLException x) {
        x.printStackTrace();
        try {
            con.rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        LOG.error("get databases error msg=" + x.getMessage());
        throw new MetaException(x.getMessage());
    } finally {
        closeStatement(stmt);
        closeConnection(con);
    }

    return dbNameList;
}