Example usage for java.sql SQLException toString

List of usage examples for java.sql SQLException toString

Introduction

In this page you can find the example usage for java.sql SQLException toString.

Prototype

public String toString() 

Source Link

Document

Returns a short description of this throwable.

Usage

From source file:org.artifactory.storage.db.build.dao.BuildsDao.java

/**
 * get Module Artifact diff with paging//from   ww w  .j  av a2 s  . c o m
 *
 * @param offset - row offset
 * @param limit  - row limit
 * @return
 */
public List<ModuleDependency> getModuleDependencyForDiffWithPaging(BuildParams buildParams, String offset,
        String limit) {
    ResultSet rs = null;
    ResultSet rsDep = null;
    ResultSet rsDepCompared = null;
    List<ModuleDependency> dependencies = new ArrayList<>();
    Map<String, ModuleDependency> moduleDependencyMap = new HashMap<>();
    try {
        StringBuilder builder = new StringBuilder(getBaseDependencyQuery(buildParams));
        Object[] diffParams = getBuildDependencyParams(buildParams);
        /// update query with specific conditions
        updateQueryWithSpecificConditions(buildParams, builder);
        String buildQuery = builder.toString();
        rs = jdbcHelper.executeSelect(buildQuery, diffParams);
        Map<String, String> tempDependencyMap = new HashMap<>();
        StringBuilder inClauseBuilder = new StringBuilder();
        inClauseBuilder.append("(");
        while (rs.next()) {
            String sha1 = rs.getString(3);
            if (tempDependencyMap.get(sha1) == null) {
                tempDependencyMap.put(sha1, sha1);
                ModuleDependency dependency = new ModuleDependency(null, null, rs.getString(1), rs.getString(2),
                        rs.getString(4), sha1);
                dependency.setStatus(rs.getString(5));
                if (buildParams.isAllArtifact()) {
                    dependency.setModule(rs.getString(6));
                }
                dependencies.add(dependency);
            }
            inClauseBuilder.append("'" + sha1 + "'").append(",");
        }
        String inClause = inClauseBuilder.toString();
        inClause = inClause.substring(0, inClause.length() - 1);
        inClause = inClause + ")";
        // update dependencies repo path data
        if (!dependencies.isEmpty()) {
            rsDep = getModuleDependencyNodes(moduleDependencyMap, inClause);
            if (buildParams.isAllArtifact()) {
                rsDepCompared = getModuleDependencyNodes(moduleDependencyMap, inClause);
            }
            dependencies.forEach(dependency -> {
                ModuleDependency moduleDependency = moduleDependencyMap.get(dependency.getSha1());
                if (moduleDependency != null) {
                    dependency.setRepoKey(moduleDependency.getRepoKey());
                    String path = moduleDependency.getPath();
                    String name = moduleDependency.getName();
                    if (path != null) {
                        dependency.setPath(path.equals(".") ? name : path + "/" + name);
                    }
                }
            });
        }
    } catch (SQLException e) {
        log.error(e.toString());
    } finally {
        DbUtils.close(rsDep);
        DbUtils.close(rsDepCompared);
        DbUtils.close(rs);
    }
    return dependencies;
}

From source file:org.codehaus.mojo.sql.SqlExecMojo.java

/**
 * Exec the sql statement./*from   w  w  w  . ja v  a 2  s. c o m*/
 * 
 * @param sql query to execute 
 * @param out the outputstream
 */
private void execSQL(String sql, PrintStream out) throws SQLException {
    // Check and ignore empty statements
    if ("".equals(sql.trim())) {
        return;
    }

    ResultSet resultSet = null;
    try {
        totalStatements++;
        getLog().debug("SQL: " + sql);

        boolean ret;
        int updateCountTotal = 0;

        ret = statement.execute(sql);
        do {
            if (!ret) {
                int updateCount = statement.getUpdateCount();
                if (updateCount != -1) {
                    updateCountTotal += updateCount;
                }
            } else {
                resultSet = statement.getResultSet();
                if (printResultSet) {
                    printResultSet(resultSet, out);
                }
            }
            ret = statement.getMoreResults();
        } while (ret);

        getLog().debug(updateCountTotal + " rows affected");

        if (printResultSet) {
            StringBuffer line = new StringBuffer();
            line.append(updateCountTotal).append(" rows affected");
            out.println(line);
        }

        SQLWarning warning = conn.getWarnings();
        while (warning != null) {
            getLog().debug(warning + " sql warning");
            warning = warning.getNextWarning();
        }
        conn.clearWarnings();
        successfulStatements++;
    } catch (SQLException e) {
        getLog().error("Failed to execute: " + sql);
        if (ON_ERROR_ABORT.equalsIgnoreCase(getOnError())) {
            throw e;
        }
        getLog().error(e.toString());
    } finally {
        if (resultSet != null) {
            resultSet.close();
        }
    }
}

From source file:org.archiviststoolkit.mydomain.DomainAccessObjectImpl.java

/**
 * Find an instance by its identifier./* w  w w. java 2  s  .  c  om*/
 *
 * @param identifier the identifier we are looking for
 * @return the domain object with the required identifier
 * @throws LookupException fails if we cannot execute the lookup
 */

public DomainObject findByPrimaryKeyCommon(final Long identifier, Session session) throws LookupException {

    DomainObject domainObject;

    try {

        //         try {
        if (getPersistentClass() == Names.class) {
            Criteria criteria = session.createCriteria(Names.class);
            criteria.setFetchMode("contactNotes", FetchMode.JOIN);
            criteria.setFetchMode("nonPreferredNames", FetchMode.JOIN);
            criteria.setFetchMode("archDescriptionNames", FetchMode.JOIN);
            criteria.add(Restrictions.idEq(identifier));
            domainObject = (DomainObject) criteria.uniqueResult();

        } else if (getPersistentClass() == Accessions.class) {
            Criteria criteria = session.createCriteria(Accessions.class);
            criteria.setFetchMode("names", FetchMode.JOIN);
            criteria.setFetchMode("repeatingData", FetchMode.JOIN);
            criteria.setFetchMode("resources", FetchMode.JOIN);
            criteria.setFetchMode("subjects", FetchMode.JOIN);
            criteria.setFetchMode("locations", FetchMode.JOIN);
            criteria.setFetchMode("deaccessions", FetchMode.JOIN);
            criteria.add(Restrictions.idEq(identifier));
            domainObject = (DomainObject) criteria.uniqueResult();

        } else if (getPersistentClass() == Subjects.class) {
            Criteria criteria = session.createCriteria(Subjects.class);
            criteria.setFetchMode("archDescriptionSubjects", FetchMode.JOIN);
            criteria.add(Restrictions.idEq(identifier));
            domainObject = (DomainObject) criteria.uniqueResult();

        } else if (getPersistentClass() == Resources.class) {
            Criteria criteria = session.createCriteria(Resources.class);
            criteria.setFetchMode("names", FetchMode.JOIN);
            criteria.setFetchMode("accessions", FetchMode.JOIN);
            criteria.setFetchMode("subjects", FetchMode.JOIN);
            //               criteria.setFetchMode("repeatingData", FetchMode.JOIN);
            //               criteria.setFetchMode("instances", FetchMode.JOIN);
            //               criteria.setFetchMode("resourcesComponents", FetchMode.JOIN);
            criteria.add(Restrictions.idEq(identifier));
            domainObject = (DomainObject) criteria.uniqueResult();

        } else if (getPersistentClass() == ResourcesComponents.class) {
            Criteria criteria = session.createCriteria(ResourcesComponents.class);
            criteria.setFetchMode("names", FetchMode.JOIN);
            criteria.setFetchMode("instances", FetchMode.JOIN);
            criteria.setFetchMode("subjects", FetchMode.JOIN);
            criteria.setFetchMode("repeatingData", FetchMode.JOIN);
            criteria.add(Restrictions.idEq(identifier));
            domainObject = (DomainObject) criteria.uniqueResult();

        } else if (getPersistentClass() == Locations.class) {
            Criteria criteria = session.createCriteria(Locations.class);
            criteria.setFetchMode("repository", FetchMode.JOIN);
            criteria.add(Restrictions.idEq(identifier));
            domainObject = (DomainObject) criteria.uniqueResult();

        } else if (getPersistentClass() == DigitalObjects.class) {
            Criteria criteria = session.createCriteria(DigitalObjects.class);
            //               criteria.setFetchMode("names", FetchMode.JOIN);
            //               criteria.setFetchMode("repeatingData", FetchMode.JOIN);
            //               criteria.setFetchMode("subjects", FetchMode.JOIN);
            //               criteria.setFetchMode("fileVersions", FetchMode.JOIN);
            criteria.add(Restrictions.idEq(identifier));
            domainObject = (DomainObject) criteria.uniqueResult();

        } else {
            domainObject = (DomainObject) session.load(getPersistentClass(), identifier);
        }

        //         } catch (ObjectNotFoundException objectNotFoundException) {
        //            new ErrorDialog("", StringHelper.getStackTrace(e)).showDialog();
        //            domainObject = null;
        //            logger.log(Level.INFO, "Object could not be found by key " + identifier);
        //         }

        session.flush();
        session.connection().commit();

    } catch (ObjectNotFoundException objectNotFoundException) {
        throw new LookupException("failed to findbyprimarykey: " + objectNotFoundException.toString(),
                objectNotFoundException);
    } catch (HibernateException hibernateException) {
        throw new LookupException("failed to findbyprimarykey: " + hibernateException.toString(),
                hibernateException);
    } catch (SQLException sqlException) {
        throw new LookupException("failed to findbyprimarykey: " + sqlException.toString(), sqlException);
    }

    return (domainObject);
}

From source file:org.metis.pull.WdsResourceBean.java

/**
 * Called by Spring after all of this bean's properties have been set.
 *//*from  www .  jav  a  2  s  .  c  o  m*/
public void afterPropertiesSet() throws Exception {

    // log info for the jdbc driver being used
    // this will also attempt to open connection
    // with jdbc driver
    try {
        Connection con = getDataSource().getConnection();
        if (con != null) {
            DatabaseMetaData dbmd = con.getMetaData();
            setDbConnectionAcquired(true);
            if (dbmd != null) {
                setDriverName(dbmd.getDriverName().trim().toLowerCase());
                isOracle = (getDriverName() != null && getDriverName().indexOf(ORACLE_STR) >= 0) ? true : false;
                LOG.info(getBeanName() + ":Is Oracle JDBC Driver = " + isOracle);
                LOG.info(getBeanName() + ":JDBC Driver name = " + getDriverName());
                LOG.info(getBeanName() + ":JDBC Driver version = " + dbmd.getDriverVersion().trim());
                LOG.info(getBeanName() + ":JDBC Driver product name = " + dbmd.getDatabaseProductName().trim());
                LOG.info(getBeanName() + ":JDBC Driver database product version = "
                        + dbmd.getDatabaseProductVersion().trim());
                con.close();
            } else {
                LOG.info(getBeanName() + ": Unable to get JDBC driver meta data");
            }
        } else {
            LOG.info(getBeanName() + ": Unable to get JDBC connection");
        }
    } catch (SQLException exc) {
        LOG.error(getBeanName() + ": got this exception when trying to " + "get driver meta data: "
                + exc.toString());
        LOG.error(getBeanName() + ": exception stack trace follows:");
        dumpStackTrace(exc.getStackTrace());
        LOG.error(getBeanName() + ": Caused by " + exc.getCause().toString());
        LOG.error(getBeanName() + ": causing exception stack trace follows:");
        dumpStackTrace(exc.getCause().getStackTrace());
    }

    // bean must be assigned a JDBC DataSource
    if (getDataSource() == null) {
        throw new Exception(
                getBeanName() + ".afterPropertiesSet: this bean has not been " + "assigned a JDBC DataSource");
    }

    // do some validation
    if (getSqls4Get() == null && getSqls4Put() == null && getSqls4Post() == null && getSqls4Delete() == null) {
        throw new Exception("At least one of the WdsResourceBean's http methods has "
                + "not been assigned a SQL statement");
    }

    // create and validate the different SQL statements
    if (getSqls4Get() != null) {
        sqlStmnts4Get = new ArrayList<SqlStmnt>();
        for (String sql : getSqls4Get()) {
            SqlStmnt stmt = getSQLStmnt(this, sql, getJdbcTemplate());
            if (stmt.isEqual(sqlStmnts4Get)) {
                throw new Exception("Injected SQL statements for GET are not distinct");
            }
            sqlStmnts4Get.add(stmt);
        }
        if (LOG.isDebugEnabled()) {
            for (SqlStmnt sqlstmnt : sqlStmnts4Get) {
                LOG.debug(getBeanName() + ": SQL for GET = " + sqlstmnt.getOriginal());
                LOG.debug(getBeanName() + ": Parameterized SQL for GET = " + sqlstmnt.getPrepared());
            }
        }
        allowedMethodsRsp += "GET ";
    }

    if (getSqls4Put() != null) {
        sqlStmnts4Put = new ArrayList<SqlStmnt>();
        for (String sql : getSqls4Put()) {
            SqlStmnt stmt = getSQLStmnt(this, sql, getJdbcTemplate());
            if (stmt.isEqual(sqlStmnts4Put)) {
                throw new Exception("Injected SQL statements for PUT are not distinct");
            }
            sqlStmnts4Put.add(stmt);
        }
        if (LOG.isDebugEnabled()) {
            for (SqlStmnt sqlstmnt : sqlStmnts4Put) {
                LOG.debug(getBeanName() + ": SQL for PUT = " + sqlstmnt.getOriginal());
                LOG.debug(getBeanName() + ": Parameterized SQL for PUT = " + sqlstmnt.getPrepared());
            }
        }
        allowedMethodsRsp += "PUT ";
    }

    if (getSqls4Post() != null) {
        sqlStmnts4Post = new ArrayList<SqlStmnt>();
        for (String sql : getSqls4Post()) {
            SqlStmnt stmt = getSQLStmnt(this, sql, getJdbcTemplate());
            if (stmt.isEqual(sqlStmnts4Post)) {
                throw new Exception("Injected SQL statements for POST are not distinct");
            }
            sqlStmnts4Post.add(stmt);
        }
        if (LOG.isDebugEnabled()) {
            for (SqlStmnt sqlstmnt : sqlStmnts4Post) {
                LOG.debug(getBeanName() + ": SQL for POST = " + sqlstmnt.getOriginal());
                LOG.debug(getBeanName() + ": Parameterized SQL for POST = " + sqlstmnt.getPrepared());
            }
        }
        allowedMethodsRsp += "POST ";
    }

    if (getSqls4Delete() != null) {
        sqlStmnts4Delete = new ArrayList<SqlStmnt>();
        for (String sql : getSqls4Delete()) {
            SqlStmnt stmt = getSQLStmnt(this, sql, getJdbcTemplate());
            if (stmt.isEqual(sqlStmnts4Delete)) {
                throw new Exception("Injected SQL statements for DELETE are not distinct");
            }
            sqlStmnts4Delete.add(stmt);
        }
        if (LOG.isDebugEnabled()) {
            for (SqlStmnt sqlstmnt : sqlStmnts4Delete) {
                LOG.debug(getBeanName() + ": SQL for DELETE = " + sqlstmnt.getOriginal());
                LOG.debug(getBeanName() + ": Parameterized SQL for DELETE = " + sqlstmnt.getPrepared());
            }
        }
        allowedMethodsRsp += "DELETE";
    }

    LOG.debug(getBeanName() + ": allowedMethodsRsp string = " + allowedMethodsRsp);

    // tell our parent what methods this RDB will support
    setSupportedMethods(allowedMethodsRsp.split(SPACE_CHR_STR));

    if (LOG.isDebugEnabled() && getAllowedAgents() != null) {
        if (!getAllowedAgents().isEmpty()) {
            LOG.debug(getBeanName() + ": agents allowed =  " + getAllowedAgents());
        } else {
            LOG.debug(getBeanName() + ": agents not allowed =  " + getNotAllowedAgents());
        }
    }

}

From source file:fi.helsinki.lib.simplerest.ItemsResource.java

@Post
public Representation addItem(InputRepresentation rep)
        throws AuthorizeException, SQLException, IdentifierException {
    Collection collection = null;
    Context addItemContext = null;
    try {/*  w  w  w. j a v  a 2 s  .  com*/
        //Get Context and make sure the user has the rights to add items.
        addItemContext = getAuthenticatedContext();
        collection = Collection.find(addItemContext, this.collectionId);
        if (collection == null) {
            addItemContext.abort();
            return errorNotFound(addItemContext, "Could not find the collection.");
        }
    } catch (SQLException e) {
        log.log(Priority.ERROR, e);
        return errorInternal(addItemContext, "SQLException");
    } catch (NullPointerException e) {
        log.log(Priority.ERROR, e);
        return errorInternal(addItemContext, "NullPointerException");
    }
    String title = null;
    String lang = null;

    try {
        RestletFileUpload rfu = new RestletFileUpload(new DiskFileItemFactory());
        FileItemIterator iter = rfu.getItemIterator(rep);

        while (iter.hasNext()) {
            FileItemStream fileItemStream = iter.next();
            if (fileItemStream.isFormField()) {
                String key = fileItemStream.getFieldName();
                String value = IOUtils.toString(fileItemStream.openStream(), "UTF-8");

                if (key.equals("title")) {
                    title = value;
                } else if (key.equals("lang")) {
                    lang = value;
                } else if (key.equals("in_archive")) {
                    ;
                } else if (key.equals("withdrawn")) {
                    ;
                } else {
                    return error(addItemContext, "Unexpected attribute: " + key,
                            Status.CLIENT_ERROR_BAD_REQUEST);
                }
            }
        }
    } catch (FileUploadException e) {
        return errorInternal(addItemContext, e.toString());
    } catch (NullPointerException e) {
        log.log(Priority.INFO, e);
        return errorInternal(context, e.toString());
    } catch (IOException e) {
        return errorInternal(context, e.toString());
    }

    if (title == null) {
        return error(addItemContext, "There was no title given.", Status.CLIENT_ERROR_BAD_REQUEST);
    }

    Item item = null;
    try {
        WorkspaceItem wsi = WorkspaceItem.create(addItemContext, collection, false);
        item = InstallItem.installItem(addItemContext, wsi);
        item.addMetadata("dc", "title", null, lang, title);
        item.update();
    } catch (AuthorizeException ae) {
        return error(addItemContext, "Unauthorized", Status.CLIENT_ERROR_UNAUTHORIZED);
    } catch (SQLException e) {
        log.log(Priority.FATAL, e, e);
        return errorInternal(addItemContext, e.toString());
    } catch (IOException e) {
        log.log(Priority.FATAL, e, e);
        return errorInternal(addItemContext, e.toString());
    } finally {
        if (addItemContext != null) {
            addItemContext.complete();
        }
    }

    return successCreated("Created a new item.", baseUrl() + ItemResource.relativeUrl(item.getID()));
}

From source file:org.cerberus.crud.dao.impl.TestCaseExecutionInQueueDAO.java

@Override
public List<TestCaseExecutionInQueue> findTestCaseExecutionInQueuebyTag(String tag) throws CerberusException {
    boolean throwEx = false;
    final StringBuilder query = new StringBuilder("select exq.*, tec.*, app.* from ( select exq.* ")
            .append("from testcaseexecutionqueue exq ").append("where exq.tag = ? ")
            .append(" order by exq.test, exq.testcase, exq.ID desc) as exq ")
            .append("LEFT JOIN testcase tec on exq.Test = tec.Test and exq.TestCase = tec.TestCase ")
            .append("LEFT JOIN application app ON tec.application = app.application ")
            .append("GROUP BY exq.test, exq.testcase, exq.Environment, exq.Browser, exq.Country ");

    List<TestCaseExecutionInQueue> testCaseExecutionInQueueList = new ArrayList<TestCaseExecutionInQueue>();
    Connection connection = this.databaseSpring.connect();
    try {/* www  .  j av a 2s .  c  o m*/
        PreparedStatement preStat = connection.prepareStatement(query.toString());

        preStat.setString(1, tag);

        try {
            ResultSet resultSet = preStat.executeQuery();
            try {
                while (resultSet.next()) {
                    testCaseExecutionInQueueList.add(this.loadWithDependenciesFromResultSet(resultSet));
                }
            } catch (SQLException exception) {
                LOG.error("Unable to execute query : " + exception.toString());
                testCaseExecutionInQueueList = null;
            } catch (FactoryCreationException ex) {
                LOG.error("Unable to execute query : " + ex.toString());
            } finally {
                resultSet.close();
            }
        } catch (SQLException exception) {
            LOG.error("Unable to execute query : " + exception.toString());
            testCaseExecutionInQueueList = null;
        } finally {
            preStat.close();
        }
    } catch (SQLException exception) {
        LOG.error("Unable to execute query : " + exception.toString());
        testCaseExecutionInQueueList = null;
    } finally {
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            LOG.warn(e.toString());
        }
    }
    if (throwEx) {
        throw new CerberusException(new MessageGeneral(MessageGeneralEnum.NO_DATA_FOUND));
    }
    return testCaseExecutionInQueueList;
}

From source file:org.cerberus.crud.dao.impl.TestCaseExecutionInQueueDAO.java

@Override
public AnswerList findTagList(int tagnumber) {
    AnswerList response = new AnswerList();
    MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_OK);
    List<String> list = null;
    StringBuilder query = new StringBuilder();

    query.append("SELECT DISTINCT tag FROM testcaseexecutionqueue WHERE tag != ''");

    if (tagnumber != 0) {
        query.append("ORDER BY id desc LIMIT ");
        query.append(tagnumber);//from w  w w .  ja va2  s.c  om
    }

    query.append(";");
    Connection connection = this.databaseSpring.connect();
    try {
        PreparedStatement preStat = connection.prepareStatement(query.toString());
        try {
            ResultSet resultSet = preStat.executeQuery();
            try {
                list = new ArrayList<String>();

                while (resultSet.next()) {
                    list.add(resultSet.getString("tag"));
                }
                msg.setDescription(
                        msg.getDescription().replace("%ITEM%", "TagList").replace("%OPERATION%", "SELECT"));
            } catch (SQLException exception) {
                LOG.error("Unable to execute query : " + exception.toString());
                msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
                msg.setDescription(msg.getDescription().replace("%DESCRIPTION%",
                        "Unable to retrieve the list of entries!"));
            } finally {
                resultSet.close();
            }
        } catch (SQLException exception) {
            LOG.error("Unable to execute query : " + exception.toString());
            msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
            msg.setDescription(
                    msg.getDescription().replace("%DESCRIPTION%", "Unable to retrieve the list of entries!"));
        } finally {
            preStat.close();
        }
    } catch (SQLException exception) {
        LOG.error("Unable to execute query : " + exception.toString());
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
        msg.setDescription(
                msg.getDescription().replace("%DESCRIPTION%", "Unable to retrieve the list of entries!"));
    } finally {
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            LOG.warn(e.toString());
        }
    }

    response.setResultMessage(msg);
    response.setDataList(list);
    return response;
}

From source file:org.cerberus.crud.dao.impl.TestCaseExecutionDAO.java

@Override
public void setTagToExecution(long id, String tag) throws CerberusException {
    boolean throwEx = false;
    final String query = "UPDATE testcaseexecution exe SET exe.tag = ? WHERE exe.id = ?";

    Connection connection = this.databaseSpring.connect();
    try {//from  w ww.  java2 s  . c  o  m
        PreparedStatement preStat = connection.prepareStatement(query);
        try {
            preStat.setString(1, tag);
            preStat.setLong(2, id);

            preStat.executeUpdate();
        } catch (SQLException exception) {
            LOG.error("Unable to execute query : " + exception.toString());
            throwEx = true;
        } finally {
            preStat.close();
        }
    } catch (SQLException exception) {
        LOG.error("Unable to execute query : " + exception.toString());
    } finally {
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            LOG.warn(e.toString());
        }
    }
    if (throwEx) {
        throw new CerberusException(new MessageGeneral(MessageGeneralEnum.CANNOT_UPDATE_TABLE));
    }
}

From source file:org.cerberus.crud.dao.impl.TestCaseExecutionInQueueDAO.java

@Override
public AnswerList readByTagByCriteria(String tag, int start, int amount, String sort, String searchTerm,
        Map<String, List<String>> individualSearch) throws CerberusException {
    MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_OK);
    AnswerList answer = new AnswerList();
    List<String> individalColumnSearchValues = new ArrayList<String>();

    final StringBuilder query = new StringBuilder();

    query.append("SELECT * FROM testcaseexecutionqueue exq ");
    query.append("left join testcase tec on exq.Test = tec.Test and exq.TestCase = tec.TestCase ");
    query.append("left join application app on tec.application = app.application ");
    query.append("where exq.ID IN ");
    query.append("(select MAX(exq.ID) from testcaseexecutionqueue exq ");

    query.append("where 1=1 ");
    if (!StringUtil.isNullOrEmpty(tag)) {
        query.append("and exq.tag = ? ");
    }//from w  w  w.  j  a  v a  2s  .  c o m

    query.append("group by exq.test, exq.testcase, exq.Environment, exq.Browser, exq.Country) ");
    if (!StringUtil.isNullOrEmpty(searchTerm)) {
        query.append("and (exq.`test` like ? ");
        query.append(" or exq.`testCase` like ? ");
        query.append(" or tec.`application` like ? ");
        query.append(" or tec.`bugid` like ? ");
        query.append(" or tec.`priority` like ? ");
        query.append(" or tec.`description` like ? )");
    }
    if (individualSearch != null && !individualSearch.isEmpty()) {
        query.append(" and ( 1=1 ");
        for (Map.Entry<String, List<String>> entry : individualSearch.entrySet()) {
            query.append(" and ");
            query.append(SqlUtil.getInSQLClauseForPreparedStatement(entry.getKey(), entry.getValue()));
            individalColumnSearchValues.addAll(entry.getValue());
        }
        query.append(" ) ");
    }

    if (!StringUtil.isNullOrEmpty(sort)) {
        query.append(" order by ").append(sort);
    }

    if ((amount <= 0) || (amount >= MAX_ROW_SELECTED)) {
        query.append(" limit ").append(start).append(" , ").append(MAX_ROW_SELECTED);
    } else {
        query.append(" limit ").append(start).append(" , ").append(amount);
    }

    // Debug message on SQL.
    if (LOG.isDebugEnabled()) {
        LOG.debug("SQL : " + query.toString());
    }

    List<TestCaseExecutionInQueue> testCaseExecutionInQueueList = new ArrayList<TestCaseExecutionInQueue>();
    Connection connection = this.databaseSpring.connect();
    try {
        PreparedStatement preStat = connection.prepareStatement(query.toString());

        int i = 1;
        if (!StringUtil.isNullOrEmpty(tag)) {
            preStat.setString(i++, tag);
        }
        if (!Strings.isNullOrEmpty(searchTerm)) {
            preStat.setString(i++, "%" + searchTerm + "%");
            preStat.setString(i++, "%" + searchTerm + "%");
            preStat.setString(i++, "%" + searchTerm + "%");
            preStat.setString(i++, "%" + searchTerm + "%");
            preStat.setString(i++, "%" + searchTerm + "%");
            preStat.setString(i++, "%" + searchTerm + "%");
        }
        for (String individualColumnSearchValue : individalColumnSearchValues) {
            preStat.setString(i++, individualColumnSearchValue);
        }

        try {
            ResultSet resultSet = preStat.executeQuery();
            try {
                while (resultSet.next()) {
                    testCaseExecutionInQueueList.add(this.loadWithDependenciesFromResultSet(resultSet));
                }

                msg.setDescription(msg.getDescription().replace("%ITEM%", "TestCaseExecutionInQueue")
                        .replace("%OPERATION%", "SELECT"));
                answer = new AnswerList(testCaseExecutionInQueueList, testCaseExecutionInQueueList.size());
            } catch (SQLException exception) {
                LOG.error("Unable to execute query : " + exception.toString());
                msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
                msg.setDescription(msg.getDescription().replace("%DESCRIPTION%",
                        "Unable to retrieve the list of entries!"));
                testCaseExecutionInQueueList = null;
            } catch (FactoryCreationException ex) {
                LOG.error("Unable to execute query : " + ex.toString());
                msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
                msg.setDescription(msg.getDescription().replace("%DESCRIPTION%",
                        "Unable to retrieve the list of entries!"));
            } finally {
                resultSet.close();
            }
        } catch (SQLException exception) {
            LOG.error("Unable to execute query : " + exception.toString());
            msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
            msg.setDescription(
                    msg.getDescription().replace("%DESCRIPTION%", "Unable to retrieve the list of entries!"));
            testCaseExecutionInQueueList = null;
        } finally {
            preStat.close();
        }
    } catch (SQLException exception) {
        LOG.error("Unable to execute query : " + exception.toString());
        msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
        msg.setDescription(
                msg.getDescription().replace("%DESCRIPTION%", "Unable to retrieve the list of entries!"));
        testCaseExecutionInQueueList = null;
    } finally {
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            LOG.warn(e.toString());
            msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
            msg.setDescription(
                    msg.getDescription().replace("%DESCRIPTION%", "Unable to retrieve the list of entries!"));
        }
    }
    answer.setResultMessage(msg);
    return answer;
}