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:mom.trd.opentheso.bdd.helper.ConceptHelper.java

/**
 * Cette fonction permet de supprimer un Concept avec ses relations et
 * traductions// w ww  .j a  v a  2  s.c om
 *
 * @param ds
 * @param idConcept
 * @param idThesaurus
 * @param idUser
 * @return boolean
 */
public boolean deleteConcept(HikariDataSource ds, String idConcept, String idThesaurus, int idUser) {

    TermHelper termHelper = new TermHelper();
    RelationsHelper relationsHelper = new RelationsHelper();
    NoteHelper noteHelper = new NoteHelper();
    AlignmentHelper alignmentHelper = new AlignmentHelper();

    // controle si le Concept a des fils avant de le supprimer
    if (relationsHelper.isRelationNTExist(ds, idConcept, idThesaurus)) {
        return false;
    }

    String idTerm = new TermHelper().getIdTermOfConcept(ds, idConcept, idThesaurus);
    if (idTerm == null) {
        return false;
    }

    // suppression du term avec les traductions et les synonymes
    // gestion du Rollback en cas d'erreur
    Connection conn = null;
    try {
        conn = ds.getConnection();
        conn.setAutoCommit(false);

        if (!termHelper.deleteTerm(conn, idTerm, idThesaurus, idUser)) {
            conn.rollback();
            conn.close();
            return false;
        }

        if (!relationsHelper.deleteAllRelationOfConcept(conn, idConcept, idThesaurus, idUser)) {
            conn.rollback();
            conn.close();
            return false;
        }

        if (!noteHelper.deleteNotesOfConcept(conn, idConcept, idThesaurus)) {
            conn.rollback();
            conn.close();
            return false;
        }

        if (!noteHelper.deleteNotesOfTerm(conn, idTerm, idThesaurus)) {
            conn.rollback();
            conn.close();
            return false;
        }

        if (!alignmentHelper.deleteAlignmentOfConcept(conn, idConcept, idThesaurus)) {
            conn.rollback();
            conn.close();
            return false;
        }

        if (!deleteConceptFromTable(conn, idConcept, idThesaurus, idUser)) {
            conn.rollback();
            conn.close();
            return false;
        }
        conn.commit();
        conn.close();
        return true;

    } catch (SQLException ex) {
        Logger.getLogger(ConceptHelper.class.getName()).log(Level.SEVERE, null, ex);
        if (conn != null) {
            try {
                conn.rollback();
                conn.close();
            } catch (SQLException ex1) {
                Logger.getLogger(ConceptHelper.class.getName()).log(Level.SEVERE, null, ex1);
            }
        }
        return false;
    }
}

From source file:mom.trd.opentheso.bdd.helper.ConceptHelper.java

/**
 * Cette fonction permet de dplacer une Branche vers un concept d'un autre
 * Groupe/*from   www.j a  v  a2s  .  c om*/
 *
 * @param conn
 * @param idConcept
 * @param idOldConceptBT
 * @param idNewConceptBT
 * @param idThesaurus
 * @param idUser
 * @return true or false
 */
public boolean moveBranchToConceptOtherGroup(Connection conn, String idConcept, String idOldConceptBT,
        String idNewConceptBT, String idThesaurus, int idUser) {
    try {
        if (!new RelationsHelper().deleteRelationBT(conn, idConcept, idThesaurus, idOldConceptBT, idUser)) {
            conn.rollback();
            conn.close();
            return false;
        }
        if (!new RelationsHelper().addRelationBT(conn, idConcept, idThesaurus, idNewConceptBT, idUser)) {
            conn.rollback();
            conn.close();
            return false;
        }
        return true;

    } catch (SQLException ex) {
        Logger.getLogger(ConceptHelper.class.getName()).log(Level.SEVERE, null, ex);

    }
    return false;
}

From source file:com.concursive.connect.web.modules.documents.dao.FileItem.java

/**
 * Description of the Method/* w w  w. j a  v a  2  s. c  om*/
 *
 * @param db Description of Parameter
 * @return Description of the Returned Value
 * @throws SQLException Description of Exception
 */
public boolean insertVersion(Connection db) throws SQLException {
    if (!isValid()) {
        return false;
    }
    boolean result = false;
    boolean doCommit = false;
    try {
        if (doCommit = db.getAutoCommit()) {
            db.setAutoCommit(false);
        }
        //Insert a new version of an existing file
        FileItemVersion thisVersion = new FileItemVersion();
        thisVersion.setId(this.getId());
        thisVersion.setSubject(subject);
        thisVersion.setClientFilename(clientFilename);
        thisVersion.setFilename(filename);
        thisVersion.setVersion(version);
        thisVersion.setSize(size);
        thisVersion.setEnteredBy(enteredBy);
        thisVersion.setModifiedBy(modifiedBy);
        thisVersion.setImageWidth(imageWidth);
        thisVersion.setImageHeight(imageHeight);
        thisVersion.setComment(comment);
        thisVersion.insert(db);

        //Update the master record
        int i = 0;
        PreparedStatement pst = db.prepareStatement("UPDATE project_files "
                + "SET subject = ?, client_filename = ?, filename = ?, version = ?, "
                + "size = ?, modifiedby = ?, modified = CURRENT_TIMESTAMP, comment = ?, image_width = ?, image_height = ? , featured_file = ? "
                + "WHERE item_id = ? ");
        pst.setString(++i, subject);
        pst.setString(++i, clientFilename);
        pst.setString(++i, filename);
        pst.setDouble(++i, version);
        pst.setInt(++i, size);
        pst.setInt(++i, modifiedBy);
        pst.setString(++i, comment);
        pst.setInt(++i, imageWidth);
        pst.setInt(++i, imageHeight);
        pst.setBoolean(++i, featuredFile);
        pst.setInt(++i, this.getId());
        pst.execute();
        pst.close();
        logUpload(db);
        if (doCommit) {
            db.commit();
        }
        result = true;
    } catch (Exception e) {
        LOG.error("Could not insert version", e);
        if (doCommit) {
            db.rollback();
        }
        throw new SQLException(e.getMessage());
    } finally {
        if (doCommit) {
            db.setAutoCommit(true);
        }
    }
    return result;
}

From source file:dao.ContactDaoDb.java

/**
 * This method updates an existing contact
 * @param contactId - the contact id /*from  w  w  w  .  j a va 2 s.c  o  m*/
 * @param loginId - the loginid
 * @param dob
 * @param title
 * @param industry
 * @param company
 * @param pwebsite
 * @param cwebsite
 * @param blogsite
 * @param city
 * @param state
 * @param country
 * @param description
 * @param zipcode
 * @param fname
 * @param lname
 * @param mname
 * @param email
 * @param gender
 * @param nickname
 * @param designation
 * @param bcity
 * @param bstate
 * @param bcountry
 * @param bzipcode
 * @param hphone
 * @param cphone
 * @param bphone
 * @param yim
 * @param aim
 * @param msn
 * @param icq
 * @param fax
 * @param netphone
 * @param relation
 * @param published
 * @param usertags
 * @param alphabet - the first letter of firstname or lastname
 */
public void updateContact(String contactId, String loginId, String dob, String title, String industry,
        String company, String pwebsite, String cwebsite, String blogsite, String city, String state,
        String country, String description, String zipcode, String fname, String lname, String mname,
        String email, String gender, String nickname, String designation, String bcity, String bstate,
        String bcountry, String bzipcode, String hphone, String cphone, String bphone, String yim, String aim,
        String msn, String icq, String fax, String netphone, String relation, String published, String usertags,
        String alphabet, String street, String bstreet) throws BaseDaoException {

    /**
     *  Get scalability datasource for hdcontacts
     */
    String sourceName = scalabilityManager.getWriteZeroScalability();
    ds = scalabilityManager.getSource(sourceName);
    if (ds == null) {
        throw new BaseDaoException("ds null, updateContact() " + sourceName);
    }

    Connection conn = null;
    try {
        conn = ds.getConnection();
        if (conn == null) {
            throw new BaseDaoException("conn null, updateContact() ");
        }
        conn.setAutoCommit(false);
        Object[] params = { (Object) contactId };
        List result = contactTagExistsQuery.execute(params);
        boolean contactTagExists = false;
        if ((result != null) && (result.size() > 0)) {
            contactTagExists = true;
        }

        if (!RegexStrUtil.isNull(published)) {
            if (published.equals("1")) {
                if (contactTagExists) {
                    updateTagQuery.run(conn, contactId, usertags);
                } else {
                    addTagQuery.run(conn, contactId, usertags);
                }
                updateQuery.run(conn, fname, lname, mname, dob, title, industry, company, pwebsite, cwebsite,
                        blogsite, city, state, country, description, zipcode, gender, nickname, designation,
                        bcity, bstate, bcountry, bzipcode, hphone, cphone, bphone, yim, aim, msn, icq, loginId,
                        fax, netphone, relation, email, published, "", contactId, street, bstreet);
            } else {
                if (contactTagExists) {
                    deleteTagQuery.run(conn, contactId);
                }
                updateQuery.run(conn, fname, lname, mname, dob, title, industry, company, pwebsite, cwebsite,
                        blogsite, city, state, country, description, zipcode, gender, nickname, designation,
                        bcity, bstate, bcountry, bzipcode, hphone, cphone, bphone, yim, aim, msn, icq, loginId,
                        fax, netphone, relation, email, published, usertags, contactId, street, bstreet);
            }
        }
    } 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/autocommit(true) updateContact() loginid = " + loginId, e2);
            }
            throw new BaseDaoException("connection rollback exception in updateContact() loginId =" + loginId,
                    e1);
        }
        throw new BaseDaoException("connection exception in updateContact() loginId =" + loginId, e);
    }

    // conn commit
    try {
        conn.commit();
    } catch (Exception e3) {
        throw new BaseDaoException("conn.commit() in updateContact loginid=" + loginId, e3);
    }

    try {
        if (conn != null) {
            conn.setAutoCommit(true);
            conn.close();
        }
    } catch (Exception e4) {
        throw new BaseDaoException("connection close/autocommit(true), updateContact() loginId = " + loginId,
                e4);
    }

    Fqn fqn = cacheUtil.fqn(DbConstants.CONTACTS);
    if (treeCache.exists(fqn, loginId)) {
        treeCache.remove(fqn, loginId);
    }

    fqn = cacheUtil.fqn(DbConstants.SHARED_PUBLISHED_CONTACTS);
    if (treeCache.exists(fqn, loginId)) {
        treeCache.remove(fqn, loginId);
    }

    fqn = cacheUtil.fqn(DbConstants.PUBLISHED_CONTACTS);
    if (treeCache.exists(fqn, loginId)) {
        treeCache.remove(fqn, loginId);
    }

    fqn = cacheUtil.fqn(DbConstants.CONTACTS_ALPHABET);
    StringBuffer sb = new StringBuffer(alphabet);
    sb.append("-");
    sb.append(loginId);
    if (treeCache.exists(fqn, sb.toString())) {
        treeCache.remove(fqn, sb.toString());
    }

    fqn = cacheUtil.fqn(DbConstants.CONTACT);
    if (treeCache.exists(fqn, contactId)) {
        treeCache.remove(fqn, contactId);
    }
}

From source file:dao.DirectoryAbstractDao.java

/**
 * Add a new blob to a directory of blobs
 * Adds an empty tag entry into tag directory
 * Adds an entry in the images directory that is not split
 * (used for searching)/* w  w w .j  a  v a 2  s . co m*/
 * User permissions are checked before the user is allowed to add it.
 * If the user is the author of this directory or diaryadmin, allow this user to add it.
 * @param List  - files list
 * @param directoryId - directoryId
 * @param userLogin - userLogin
 * @param userId - userId
 * @throws BaseDaoException If we have a problem interpreting the data or 
 *  the data is missing or incorrect
*/
public void addStreamBlobs(List files, String directoryId, String userLogin, String userId)
        throws BaseDaoException {

    // String usertags, 
    if ((files == null) || (RegexStrUtil.isNull(directoryId)) || (userLogin == null) || (userId == null)) {
        throw new BaseDaoException("params are null");
    }

    /**
     *  Get scalability datasource for dirblob - partitioned on directoryId
     */
    String sourceName = scalabilityManager.getWriteBlobScalability(directoryId);
    ds = scalabilityManager.getSource(sourceName);
    if (ds == null) {
        throw new BaseDaoException("ds null, addStreamBlob " + sourceName);
    }

    if (!isAuthor(directoryId, userId) && !diaryAdmin.isDiaryAdmin(userLogin)) {
        throw new BaseDaoException("user does not have permission to add streamblobs in directory "
                + directoryId + " userId " + userId);
    }

    Connection conn = null;
    String entryId = null;
    for (int i = 0; i < files.size(); i++) {
        if (files.get(i) == null) {
            logger.info("files.get(" + i + ") is null");
            continue;
        }

        logger.info("photo file is not null, i=" + i);

        long bsize = 0;
        int blobtype = 0;
        int zoom = 0;

        String bsizeStr = ((Photo) files.get(i)).getValue(DbConstants.BSIZE);
        if (!RegexStrUtil.isNull(bsizeStr)) {
            bsize = new Long(bsizeStr).longValue();
        }
        String blobtypeStr = ((Photo) files.get(i)).getValue(DbConstants.BLOBTYPE);
        if (!RegexStrUtil.isNull(blobtypeStr)) {
            blobtype = new Integer(blobtypeStr).intValue();
        }
        String mtype = ((Photo) files.get(i)).getValue(DbConstants.MIMETYPE);
        String btitle = ((Photo) files.get(i)).getValue(DbConstants.BTITLE);
        byte[] blob = ((Photo) files.get(i)).getBlob();

        String zoomStr = ((Photo) files.get(i)).getValue(DbConstants.ZOOM);
        if (!RegexStrUtil.isNull(zoomStr)) {
            zoom = new Integer(zoomStr).intValue();
        }
        String caption = ((Photo) files.get(i)).getValue(DbConstants.CAPTION);
        if ((bsize <= 0) || RegexStrUtil.isNull(mtype) || RegexStrUtil.isNull(btitle)) {
            throw new BaseDaoException("params are null");
        }

        logger.info("bsize=" + bsize + " mtype=" + mtype + " btitle=" + btitle);

        if (RegexStrUtil.isNull(caption)) {
            caption = btitle;
        }

        try {
            conn = ds.getConnection();
            if (conn == null) {
                throw new BaseDaoException("conn is null");
            }
            conn.setAutoCommit(false);

            if (WebUtil.isSanEnabled()) {
                byte[] noBlobData = { ' ' };
                logger.info("noblobdata " + directoryId + " userId=" + userId);
                addStreamBlobQuery.run(conn, noBlobData, blobtype, mtype, btitle, bsize, zoom, directoryId,
                        userId, caption);
            } else {
                logger.info("blobdata");
                addStreamBlobQuery.run(conn, blob, blobtype, mtype, btitle, bsize, zoom, directoryId, userId,
                        caption);
            }
            logger.info("came here addTagQuery");

            addTagQuery.run(conn, directoryId, "", "LAST_INSERT_ID()");
            logger.info("completed addTagQuery");
            boolean convertEntryId = false;
            addImageQuery.run(conn, "", blobtype, mtype, btitle, bsize, zoom, directoryId, userId, caption,
                    convertEntryId);
            logger.info("completed addImageQuery");

        } catch (Exception e) {
            logger.info("errorMsg=" + e.getMessage());
            try {
                conn.rollback();
            } catch (Exception e1) {
                logger.info("errorMsg e1=" + e1.getMessage());
                try {
                    if (conn != null) {
                        conn.setAutoCommit(true);
                        conn.close();
                    }
                } catch (Exception e2) {
                    throw new BaseDaoException(
                            "conn.close() error, addStreamBlob()/addTagQuery/addImageQuery, userId=" + userId
                                    + " ErrorMsg=" + e2.getMessage(),
                            e2);
                }
                throw new BaseDaoException(
                        " rollback() exception, for addStreamBlob()/addTagQuery()/addImageQuery(),  userId = "
                                + userId + " ErrorMsg=" + e1.getMessage(),
                        e1);
            }
            throw new BaseDaoException("addStreamBlob()/addTagQuery()/addImageQuery exception,  userId = "
                    + userId + " ErrorMsg=" + e.getMessage(), e);
        }

        /* 
        * connection commit
        */
        try {
            conn.commit();
        } catch (Exception e3) {
            throw new BaseDaoException(
                    " commit() exception, for addStreamBlob()/addImageQuery/addTagQuery, userId = " + userId
                            + " ErrorMsg = " + e3.getMessage(),
                    e3);
        }
        try {
            if (conn != null) {
                conn.setAutoCommit(true);
                conn.close();
            }
        } catch (Exception e4) {
            throw new BaseDaoException(
                    " conn.close() exception, for commit(), addStreamBlob()/addTagQuery/addImageQuery userId = "
                            + userId + " ErrorMsg = " + e4.getMessage(),
                    e4);
        }

        /**
         * get stream blobs for a directory from cache, if it exists
         */
        Fqn fqn = cacheUtil.fqn(DbConstants.DIRECTORY_STREAM_BLOBS);
        if (treeCache.exists(fqn, directoryId)) {
            treeCache.remove(fqn, directoryId);
        }

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

        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);
        fqn = cacheUtil.fqn(DbConstants.DIR_CAT);
        if (treeCache.exists(fqn, sb.toString())) {
            treeCache.remove(fqn, sb.toString());
        }

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

From source file:com.tremolosecurity.provisioning.core.providers.BasicDB.java

@Override

public void deleteUser(User user, Map<String, Object> request) throws ProvisioningException {
    Connection con = null;

    int approvalID = 0;

    Workflow workflow = (Workflow) request.get("WORKFLOW");

    if (request.containsKey("APPROVAL_ID")) {
        approvalID = (Integer) request.get("APPROVAL_ID");
    }/*  w  w  w.j av a  2s. co  m*/

    try {
        con = this.ds.getConnection();
        StringBuffer select = new StringBuffer();

        if (this.userSQL != null) {
            select.append(this.userSQL.replaceAll("\\%S", this.userPrimaryKey).replaceAll("\\%L", "?"));
        } else {
            select.append("SELECT ");
            this.getFieldName(this.userPrimaryKey, select).append(" FROM ").append(this.userTable)
                    .append(" WHERE ");
            this.getFieldName(this.userName, select).append("=?");
        }

        PreparedStatement ps = con.prepareStatement(select.toString());
        ps.setString(1, user.getUserID());
        ResultSet rs = ps.executeQuery();

        if (!rs.next()) {
            throw new ProvisioningException("User not found " + user.getUserID());
        }

        int id = rs.getInt(this.userPrimaryKey);

        rs.close();
        ps.close();

        con.setAutoCommit(false);

        if (this.customDBProvider != null) {
            this.customDBProvider.deleteUser(con, id);
        } else {
            select.setLength(0);
            select.append("DELETE FROM ").append(this.userTable).append(" WHERE ");
            this.getFieldName(this.userPrimaryKey, select).append("=?");
            ps = con.prepareStatement(select.toString());
            ps.setInt(1, id);
            ps.executeUpdate();

            switch (this.groupMode) {
            case None:
                break;
            case One2Many:
                select.setLength(0);
                select.append("DELETE FROM ").append(this.groupTable).append(" WHERE ");
                this.getFieldName(this.groupUserKey, select).append("=?");
                ps = con.prepareStatement(select.toString());
                ps.setInt(1, id);
                ps.executeUpdate();
                break;
            case Many2Many:
                many2manyDeleteGroups(con, select, id);
                break;
            }
        }

        con.commit();

        this.cfgMgr.getProvisioningEngine().logAction(this.name, true, ActionType.Delete, approvalID, workflow,
                "userName", user.getUserID());
    } catch (Exception e) {
        try {
            con.rollback();
        } catch (SQLException e1) {

        }

        throw new ProvisioningException("Could not delete user " + user.getUserID(), e);
    } finally {
        if (con != null) {

            try {
                con.close();
            } catch (SQLException e) {

            }
        }
    }

}

From source file:de.whs.poodle.repositories.ExerciseRepository.java

public void save(Exercise exercise) {
    if (exercise.getTitle().trim().isEmpty())
        throw new BadRequestException("noTitleSpecified");
    if (exercise.getText().trim().isEmpty())
        throw new BadRequestException("noExerciseTextSpecified");

    jdbc.execute(new ConnectionCallback<Void>() {

        @Override//w w w  . j a  va  2  s  .com
        public Void doInConnection(Connection con) throws SQLException, DataAccessException {
            try (CallableStatement exercisePs = con
                    .prepareCall("{ ? = CALL create_exercise(?,?,?::exercise_visibility,?,?,?,?,?,?,?,?,?) }");

                    PreparedStatement tagsPs = con
                            .prepareStatement("INSERT INTO exercise_to_tag(exercise_id,tag_id) VALUES(?,?)");) {
                con.setAutoCommit(false);

                // inner try for rollback
                try {
                    // create exercise
                    exercisePs.registerOutParameter(1, Types.INTEGER); // new_id

                    exercisePs.setString(2, exercise.getText());

                    /*
                     * The root id is always the ID of the first revision. If this
                     * is a new exercise, this ID obviously doesn't exist yet. We set
                     * NULL in this case, but a trigger in the DB will automatically
                     * set the root_id to the generated id.
                     */
                    if (exercise.getRootId() == 0)
                        exercisePs.setNull(3, Types.INTEGER);
                    else
                        exercisePs.setInt(3, exercise.getRootId());

                    exercisePs.setString(4, exercise.getVisibility().toString());
                    exercisePs.setString(5, exercise.getTitle());
                    exercisePs.setInt(6, exercise.getChangedBy().getId());
                    exercisePs.setString(7, exercise.getHint1());
                    exercisePs.setString(8, exercise.getHint2());

                    // sample solution
                    SampleSolutionType sampleSolutionType = exercise.getSampleSolutionType();

                    if (sampleSolutionType == SampleSolutionType.NONE) {
                        exercisePs.setNull(9, Types.INTEGER);
                        exercisePs.setNull(10, Types.VARCHAR);
                    } else if (sampleSolutionType == SampleSolutionType.FILE) {
                        exercisePs.setInt(9, exercise.getSampleSolution().getFile().getId());
                        exercisePs.setNull(10, Types.VARCHAR);
                    } else { // must be text
                        exercisePs.setNull(9, Types.INTEGER);
                        exercisePs.setString(10, exercise.getSampleSolution().getText());
                    }

                    // attachments
                    List<Integer> attachmentIds = exercise.getAttachments().stream().map(a -> a.getId())
                            .collect(Collectors.toList());

                    Array anhaengeIdsArray = con.createArrayOf("int4", attachmentIds.toArray());
                    exercisePs.setArray(11, anhaengeIdsArray);

                    exercisePs.setInt(12, exercise.getCourseId());

                    exercisePs.setString(13, exercise.getComment());

                    exercisePs.executeUpdate();

                    /* Set the generated ID so the calling function can read it. */
                    exercise.setId(exercisePs.getInt(1));

                    // create relation to tags
                    tagsPs.setInt(1, exercise.getId());

                    for (Tag t : exercise.getTags()) {
                        tagsPs.setInt(2, t.getId());
                        tagsPs.addBatch();
                    }

                    tagsPs.executeBatch();

                    con.commit();
                } catch (SQLException e) {
                    con.rollback();
                    throw e;
                } finally {
                    con.setAutoCommit(true);
                }
            }

            return null;
        }
    });
}

From source file:mom.trd.opentheso.bdd.helper.ConceptHelper.java

/**
 * Cette fonction permet d'ajouter un domaine  un Concept dans la table
 * Concept, en paramtre un objet Classe Concept
 *
 * @param conn//from w  w  w .  ja  va2 s .com
 * @param concept
 * @param idUser
 * @return true or false
 */
public boolean addNewGroupOfConcept(Connection conn, Concept concept, int idUser) {

    Statement stmt;
    boolean status = false;
    try {
        try {
            conn.setAutoCommit(false);
            stmt = conn.createStatement();
            try {

                if (!addConceptHistorique(conn, concept, idUser)) {
                    conn.rollback();
                    conn.close();
                    return false;
                }

                String query = "Insert into concept "
                        + "(id_concept, id_thesaurus, id_ark, status, notation, top_concept, id_group)"
                        + " values (" + "'" + concept.getIdConcept() + "'" + ",'" + concept.getIdThesaurus()
                        + "'" + ",'" + concept.getIdArk() + "'" + ",'" + concept.getStatus() + "'" + ",'"
                        + concept.getNotation() + "'" + "," + concept.isTopConcept() + ",'"
                        + concept.getIdGroup() + "')";

                stmt.executeUpdate(query);
                status = true;
                conn.commit();
            } finally {
                stmt.close();
            }
        } finally {
            //         conn.close();
        }
    } catch (SQLException sqle) {
        // Log exception
        if (!sqle.getMessage().contains("duplicate key value violates unique constraint")) {
            log.error("Error while adding Concept : " + concept.getIdConcept(), sqle);
        }
    }
    return status;
}

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

public static final void saveApplicationPreferences(String app_name, String preference_name, String preference)
        throws Exception {
    Connection c = null;
    PreparedStatement ps = null;/*w  ww  .j av a  2 s .c o  m*/

    String deleteSql = "delete from app_preferences where application_name ='" + app_name
            + "' and preference_name ='" + preference_name + "'";
    String insertSql = "insert into app_preferences (application_name, preference_name, preference_value) values (?, ?, ?)";

    try {
        c = DBHelper.getConnection();
        c.setAutoCommit(false);

        DBHelper.executeUpdateNoCommit(c, deleteSql);

        ps = c.prepareStatement(insertSql);

        ps.setString(1, app_name);
        ps.setString(2, preference_name);
        ps.setString(3, preference);
        ps.executeUpdate();

        c.commit();
    } catch (Exception ee) {
        try {
            c.rollback();
        } catch (Exception sqlEx) {
            logger.debug("Error while rollingback the data", sqlEx);
        }
        logger.warn("Error while saving Application Preferences", ee);
        throw new PariException(-1, "Error while saving Application Preferences");
    } finally {
        try {
            c.setAutoCommit(true);
        } catch (Exception e) {
            logger.debug("Error while Setting auto commit", e);
        }
        if (ps != null) {
            try {
                ps.close();
            } catch (SQLException e) {
                logger.error("Exception while closing Statement:", e);
            }
        }

        DBConnectionFactory.getInstance().releaseConnection(c);
    }
}

From source file:mom.trd.opentheso.bdd.helper.ConceptHelper.java

/**
 * Cette fonction permet de fusionner deux concepts. Le premier concept
 * reste, le second passe en tat 'fusionn'.
 *
 * @param ds//from  w  w w.ja  va  2s .c o m
 * @param idConcept1
 * @param idConcept2
 * @param idTheso
 * @param idUser
 * @return
 */
public boolean addConceptFusion(HikariDataSource ds, String idConcept1, String idConcept2, String idTheso,
        int idUser) {
    boolean status = false;
    String idArk = "";
    Connection conn;
    Statement stmt;

    try {
        // Get connection from pool
        conn = ds.getConnection();
        conn.setAutoCommit(false);
        Concept concept = getThisConcept(ds, idConcept2, idTheso);
        concept.setStatus("hidden");

        if (!addConceptHistorique(conn, concept, idUser)) {
            conn.rollback();
            conn.close();
            return false;
        } else if (!updateStatusConcept(ds, idConcept2, idTheso, "hidden")) {
            conn.rollback();
            conn.close();
            return false;
        }
        try {
            stmt = conn.createStatement();
            try {
                String query = "Insert into concept_fusion "
                        + "(id_concept1, id_concept2, id_thesaurus, id_user)" + " values (" + "'" + idConcept1
                        + "'" + ",'" + idConcept2 + "'" + ",'" + idTheso + "'" + ",'" + idUser + "')";
                stmt.executeUpdate(query);
                status = true;
                conn.commit();
            } finally {
                stmt.close();
            }
        } finally {
            conn.close();
        }
    } catch (SQLException sqle) {
        // Log exception
        log.error("Error while melting Concept : " + idConcept1 + " and " + idConcept2, sqle);
    }
    return status;
}