Example usage for org.springframework.dao DataAccessException getMessage

List of usage examples for org.springframework.dao DataAccessException getMessage

Introduction

In this page you can find the example usage for org.springframework.dao DataAccessException getMessage.

Prototype

@Override
@Nullable
public String getMessage() 

Source Link

Document

Return the detail message, including the message from the nested exception if there is one.

Usage

From source file:edu.hm.muse.controller.Logincontroller.java

@RequestMapping(value = "/login.secu", method = RequestMethod.POST)
public ModelAndView doSomeLogin(@RequestParam(value = "mname", required = false) String mname,
        @RequestParam(value = "mpwd", required = false) String mpwd, HttpSession session) {
    if (null == mname || null == mpwd || mname.isEmpty() || mpwd.isEmpty()) {
        throw new SuperFatalAndReallyAnnoyingException(
                "I can not process, because the requestparam mname or mpwd is empty or null or something like this");
    }//  w  w w  .ja v a2s.  c o m

    //This is the sql statement
    String sql = String.format("select count(*) from M_USER where muname = '%s' and mpwd = '%s'", mname, mpwd);

    int res = 0;
    try {
        //Here is the sql magic
        //TODO:Possibly this is unsecure, but I am only a low paid code scripter...perhaps there is a option to bring prepared
        //statements into this sql-query.
        //But I found a possible solution here http://static.springsource.org/spring/docs/3.0.x/reference/html/jdbc.html#jdbc-JdbcTemplate-idioms
        //I think the easiest way is to build the sql statements with ? instead of concatenation
        res = jdbcTemplate.queryForInt(sql);
    } catch (DataAccessException e) {
        throw new SuperFatalAndReallyAnnoyingException(
                String.format("Sorry but %sis a bad grammar or has following problem %s", sql, e.getMessage()));
    }

    //If there are any results, than the username and password is correct
    if (res > 0) {
        session.setAttribute("user", mname);
        session.setAttribute("login", true);
        return new ModelAndView("redirect:intern.secu");
    }
    //Ohhhhh not correct try again
    ModelAndView mv = returnToLogin(session);
    return mv;
}

From source file:cherry.foundation.etl.LoaderImpl.java

/**
 * ?/*  w  w w .j a v a2  s.  com*/
 * 
 * @param dataSource 
 * @param sql SQL
 * @param provider ??
 * @param limit ???
 * @return ????
 * @throws LimiterException ????
 * @throws IOException ??
 */
@Override
public LoadResult load(DataSource dataSource, String sql, Provider provider, Limiter limiter)
        throws LimiterException, IOException {

    NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate(dataSource);

    limiter.start();
    try {

        provider.begin();

        long totalCount = 0;
        long successCount = 0;
        long failedCount = 0;
        Map<String, ?> data;
        while ((data = provider.provide()) != null) {

            totalCount += 1;

            try {
                template.update(sql, data);
                successCount += 1;
            } catch (DataAccessException ex) {
                if (allowedFailCount <= 0) {
                    throw ex;
                }

                failedCount += 1;
                logger.warn("SQL failed: count={}, message={}", failedCount, ex.getMessage());
                if (allowedFailCount < failedCount) {
                    throw ex;
                }
            }

            if (batchCount > 0 && batchCount <= totalCount) {
                break;
            }

            limiter.tick();
        }

        provider.end();

        LoadResult result = new LoadResult();
        result.setTotalCount(totalCount);
        result.setSuccessCount(successCount);
        result.setFailedCount(failedCount);
        return result;

    } finally {
        limiter.stop();
    }
}

From source file:pe.gob.mef.gescon.hibernate.impl.ContenidoDaoImpl.java

@Override
public List<HashMap> getConcimientosDisponibles(HashMap filters) {
    String ntipoconocimientoid = ((BigDecimal) filters.get("ntipoconocimientoid")).toString();
    String nconocimientovinc = (String) filters.get("nconocimientovinc");
    final StringBuilder sql = new StringBuilder();
    Object object = null;/*from   www . jav a  2  s .  c o m*/
    try {
        if (StringUtils.isNotBlank(ntipoconocimientoid) && ntipoconocimientoid.equals("1")) {
            sql.append("SELECT ");
            sql.append(
                    "    a.nbaselegalid AS ID, a.vnumero AS NUMERO, a.vnombre AS NOMBRE, a.vsumilla AS SUMILLA, ");
            sql.append(
                    "    a.ncategoriaid AS IDCATEGORIA, b.vnombre AS CATEGORIA, a.dfechapublicacion AS FECHA, ");
            sql.append(
                    "    1 AS IDTIPOCONOCIMIENTO, 'Base Legal' AS TIPOCONOCIMIENTO, a.nestadoid AS IDESTADO, c.vnombre AS ESTADO ");
            sql.append("FROM TBASELEGAL a ");
            sql.append("    INNER JOIN MTCATEGORIA b ON a.ncategoriaid = b.ncategoriaid ");
            sql.append("    INNER JOIN MTESTADO_BASELEGAL c ON a.nestadoid = c.nestadoid ");
            sql.append("WHERE a.nactivo = :ACTIVO ");
            sql.append("AND a.nestadoid IN (3,5,6) "); // Publicada, Concordada y Modificada.
            if (StringUtils.isNotBlank(nconocimientovinc)) {
                sql.append("AND a.nbaselegalid NOT IN (").append(nconocimientovinc).append(") ");
            }
        }
        if (StringUtils.isNotBlank(ntipoconocimientoid) && ntipoconocimientoid.equals("2")) {
            sql.append("SELECT ");
            sql.append("    a.npreguntaid AS ID, '' AS NUMERO, a.vasunto AS NOMBRE, a.vrespuesta AS SUMILLA, ");
            sql.append(
                    "    a.ncategoriaid AS IDCATEGORIA, b.vnombre AS CATEGORIA, a.dfechacreacion AS FECHA, ");
            sql.append("    2 AS IDTIPOCONOCIMIENTO, 'Preguntas y Respuestas' AS TIPOCONOCIMIENTO, ");
            sql.append("    a.nsituacionid AS IDESTADO, c.vnombre AS ESTADO ");
            sql.append("FROM TPREGUNTA a ");
            sql.append("    INNER JOIN MTCATEGORIA b ON a.ncategoriaid = b.ncategoriaid ");
            sql.append("    INNER JOIN MTSITUACION c ON a.nsituacionid = c.nsituacionid ");
            sql.append("WHERE a.nactivo = :ACTIVO ");
            sql.append("AND a.nsituacionid = 6 "); // Publicado
            if (StringUtils.isNotBlank(nconocimientovinc)) {
                sql.append("AND a.npreguntaid NOT IN (").append(nconocimientovinc).append(") ");
            }
        }
        if (StringUtils.isNotBlank(ntipoconocimientoid)
                && (ntipoconocimientoid.equals("3") || ntipoconocimientoid.equals("4")
                        || ntipoconocimientoid.equals("5") || ntipoconocimientoid.equals("6"))) {
            sql.append("SELECT ");
            sql.append(
                    "    a.nconocimientoid AS ID, '' AS NUMERO, a.vtitulo AS NOMBRE, a.vdescripcion AS SUMILLA, ");
            sql.append(
                    "    a.ncategoriaid AS IDCATEGORIA, b.vnombre AS CATEGORIA, a.dfechacreacion AS FECHA, ");
            sql.append("    a.ntpoconocimientoid AS IDTIPOCONOCIMIENTO, d.vnombre AS TIPOCONOCIMIENTO, ");
            sql.append("    a.nsituacionid AS IDESTADO, c.vnombre AS ESTADO ");
            sql.append("FROM TCONOCIMIENTO a ");
            sql.append("    INNER JOIN MTCATEGORIA b ON a.ncategoriaid = b.ncategoriaid ");
            sql.append("    INNER JOIN MTSITUACION c ON a.nsituacionid = c.nsituacionid ");
            sql.append("    INNER JOIN MTTIPO_CONOCIMIENTO d ON a.ntpoconocimientoid = d.ntpoconocimientoid ");
            sql.append("WHERE a.nactivo = :ACTIVO ");
            sql.append("AND a.nsituacionid = 6 AND a.NTPOCONOCIMIENTOID = ").append(ntipoconocimientoid)
                    .append(" "); // Publicado
            if (StringUtils.isNotBlank(nconocimientovinc)) {
                sql.append(" AND a.nconocimientoid NOT IN (").append(nconocimientovinc).append(") ");
            }
        }
        sql.append("ORDER BY 5, 7 DESC ");

        object = getHibernateTemplate().execute(new HibernateCallback() {
            @Override
            public Object doInHibernate(Session session) throws HibernateException {
                Query query = session.createSQLQuery(sql.toString());
                query.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
                if (StringUtils.isNotBlank(sql.toString())) {
                    query.setParameter("ACTIVO", BigDecimal.ONE);
                }
                return query.list();
            }
        });
    } catch (DataAccessException e) {
        e.getMessage();
        e.printStackTrace();
    }
    return (List<HashMap>) object;
}

From source file:com.sfs.whichdoctor.dao.PhoneDAOImpl.java

/**
 * Gets the country code based on the supplied country string.
 *
 * @param country the country//from w  w w  . j av a  2s  .c  o  m
 * @return the country code
 */
public final int getCountryCode(final String country) {

    int countryCode = 0;

    if (StringUtils.isNotBlank(country)) {
        try {
            countryCode = this.getJdbcTemplateReader()
                    .queryForInt(this.getSQL().getValue("phone/findCountryCode"), new Object[] { country });
        } catch (DataAccessException dae) {
            dataLogger.error("Error loading country code: " + dae.getMessage());
        }
    }

    return countryCode;
}

From source file:pe.gob.mef.gescon.hibernate.impl.ConocimientoDaoImpl.java

@Override
public List<HashMap> getConcimientosByVinculoBaseLegalId(final BigDecimal id) {
    final StringBuilder sql = new StringBuilder();
    Object object = null;/* w ww  .  java2 s. co  m*/
    try {
        sql.append("SELECT t.nconocimientoid AS ID ");
        sql.append("FROM tconocimiento t ");
        sql.append("INNER JOIN tvinculo x ");
        sql.append("ON x.nconocimientoid = t.nconocimientoid ");
        sql.append("AND x.nconocimientovinc = :IDCONOCIMIENTO ");
        sql.append("AND x.ntipoconocimientovinc = :TIPO ");
        object = getHibernateTemplate().execute(new HibernateCallback() {
            @Override
            public Object doInHibernate(Session session) throws HibernateException {
                Query query = session.createSQLQuery(sql.toString());
                query.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
                query.setParameter("IDCONOCIMIENTO", id);
                query.setParameter("TIPO", BigDecimal.ONE);
                return query.list();
            }
        });
    } catch (DataAccessException e) {
        e.getMessage();
        e.printStackTrace();
    }
    return (List<HashMap>) object;
}

From source file:com.sfs.dao.GadgetDAOImpl.java

/**
 * Search for a list of Gadgets based on the supplied GadgetListBean parameters.
 *
 * @param gadgetList the gadget list//www . ja v a2 s.  co m
 *
 * @return the gadget list bean
 *
 * @throws SFSDaoException the SFS dao exception
 */
@SuppressWarnings("unchecked")
public final GadgetListBean search(final GadgetListBean gadgetList) throws SFSDaoException {
    GadgetListBean results = gadgetList.clone();

    results.setCategories(this.getCategories());

    String category = "";
    if (gadgetList.getCategory().compareToIgnoreCase("All") != 0
            && gadgetList.getCategory().compareToIgnoreCase("Latest") != 0) {
        category = gadgetList.getCategory();
    }
    category += "%";

    String searchSQL = getSQL().getValue("gadget/search");
    if (gadgetList.getCategory().compareToIgnoreCase("Latest") == 0) {
        searchSQL += " ORDER BY gadgets.Created DESC LIMIT ?, ?";
    } else {
        searchSQL += " ORDER BY gadgets.Title ASC LIMIT ?, ?";
    }

    final String searchString = "%" + gadgetList.getSearchString() + "%";

    try {
        final int totalResults = this.getJdbcTemplateReader().queryForInt(getSQL().getValue("gadget/count"),
                new Object[] { searchString, searchString, category });

        results.setTotalResults(totalResults);

    } catch (DataAccessException de) {
        dataLogger.error("Error getting count: " + de.getMessage());
    }

    try {
        Collection<GadgetBean> gadgets = this
                .getJdbcTemplateReader().query(
                        searchSQL, new Object[] { searchString, searchString, category,
                                gadgetList.getCurrentRecord(), gadgetList.getResultsPerPage() },
                        new RowMapper() {
                            public Object mapRow(final ResultSet rs, final int rowNum) throws SQLException {
                                return loadGadget(rs);
                            }
                        });

        results.setResults(gadgets);

    } catch (IncorrectResultSizeDataAccessException ie) {
        dataLogger.debug("No results found for this search: " + ie.getMessage());
    }
    return results;
}

From source file:org.itracker.services.authentication.DefaultAuthenticator.java

/**
 * The DefaultAuthenticator returns a list of user permissions from the database.
 *
 * @param user      a User object that contains the user to retrieve permissions for
 * @param reqSource the source of the request (eg web, api)
 * @return an array of PermissionModels//from w  w w.  j av  a2  s  .c  om
 * @throws AuthenticatorException an error occurs
 */
public List<Permission> getUserPermissions(User user, int reqSource) throws AuthenticatorException {
    if (user == null || user.getId() == null) {
        throw new AuthenticatorException(AuthenticatorException.INVALID_DATA);
    }

    List<Permission> permissionList;
    try {
        permissionList = getUserService().getUserPermissionsLocal(user);
    } catch (DataAccessException e) {
        throw new AuthenticatorException(e.getMessage(), reqSource);
    }

    if (user.isSuperUser()) {
        List<Permission> augmentedPermissions = new ArrayList<Permission>();

        // Super user has access to all projects (represented by the "null" project). 
        Permission permission = new Permission(PermissionType.USER_ADMIN, user, null);
        augmentedPermissions.add(permission);
        augmentedPermissions.addAll(permissionList);
        return augmentedPermissions;

    } else {
        return permissionList;
    }

}

From source file:com.sfs.whichdoctor.dao.SavedSearchDAOImpl.java

/**
 * Delete the saved search.//from   w w w . j a v a  2  s  .  com
 *
 * @param search the search
 * @return true, if successful
 * @throws WhichDoctorDaoException the which doctor dao exception
 */
public final boolean delete(final SearchBean search) throws WhichDoctorDaoException {

    if (search.getId() == 0) {
        throw new WhichDoctorDaoException("Search requires a vaild SearchId number");
    }

    boolean success = false;

    try {
        final int deleteCount = this.getJdbcTemplateWriter().update(this.getSQL().getValue("search/delete"),
                new Object[] { search.getId() });

        if (deleteCount > 0) {
            dataLogger.info("Sccessfully deleted SearchId: " + search.getId());
            success = true;
        }
    } catch (DataAccessException de) {
        dataLogger.error("Error deleting search: " + de.getMessage());
        throw new WhichDoctorDaoException("Error deleting search: " + de.getMessage());
    }
    return success;
}

From source file:com.sfs.whichdoctor.dao.SavedSearchDAOImpl.java

/**
 * Modify the saved search.//  w w w. j  a va  2 s  . c  o  m
 *
 * @param search the search
 * @return true, if successful
 * @throws WhichDoctorDaoException the which doctor dao exception
 */
public final boolean modify(final SearchBean search) throws WhichDoctorDaoException {

    /* Modify search requires all the neccessary information */
    if (StringUtils.isBlank(search.getName())) {
        throw new WhichDoctorDaoException("Saved search description " + "field cannot be an empty string");
    }
    if (search.getId() == 0) {
        throw new WhichDoctorDaoException("A valid SearchId value is required");
    }

    boolean success = false;

    try {
        final int updateCount = this.getJdbcTemplateWriter().update(this.getSQL().getValue("search/modify"),
                new Object[] { search.getName(), search.getPublicSearch(), search.getFavourite(),
                        search.getDescription(), search.getId() });

        if (updateCount > 0) {
            dataLogger.info("Sccessfully updated SearchId: " + search.getId());
            success = true;
        }
    } catch (DataAccessException de) {
        dataLogger.error("Error updating search: " + de.getMessage());
        throw new WhichDoctorDaoException("Error updating search: " + de.getMessage());
    }
    return success;
}

From source file:pe.gob.mef.gescon.hibernate.impl.ConocimientoDaoImpl.java

@Override
public List<HashMap> getConcimientosDisponibles(HashMap filters) {
    String ntipoconocimientoid = ((BigDecimal) filters.get("ntipoconocimientoid")).toString();
    String nconocimientovinc = (String) filters.get("nconocimientovinc");
    final StringBuilder sql = new StringBuilder();
    Object object = null;//w  w w  . j  a v a  2 s  . c om
    try {
        if (StringUtils.isNotBlank(ntipoconocimientoid) && ntipoconocimientoid.equals("1")) {
            sql.append("SELECT ");
            sql.append(
                    "    a.nbaselegalid AS ID, a.vnumero AS NUMERO, a.vnombre AS NOMBRE, a.vsumilla AS SUMILLA, ");
            sql.append(
                    "    a.ncategoriaid AS IDCATEGORIA, b.vnombre AS CATEGORIA, a.dfechapublicacion AS FECHA, ");
            sql.append(
                    "    1 AS IDTIPOCONOCIMIENTO, 'Base Legal' AS TIPOCONOCIMIENTO, a.nestadoid AS IDESTADO, c.vnombre AS ESTADO ");
            sql.append("FROM TBASELEGAL a ");
            sql.append("    INNER JOIN MTCATEGORIA b ON a.ncategoriaid = b.ncategoriaid ");
            sql.append("    INNER JOIN MTESTADO_BASELEGAL c ON a.nestadoid = c.nestadoid ");
            sql.append("WHERE a.nactivo = :ACTIVO ");
            sql.append("AND a.nestadoid IN (3,5,6) "); // Publicada, Concordada y Modificada.
            if (StringUtils.isNotBlank(nconocimientovinc)) {
                sql.append("AND a.nbaselegalid NOT IN (").append(nconocimientovinc).append(") ");
            }
        }
        if (StringUtils.isNotBlank(ntipoconocimientoid) && ntipoconocimientoid.equals("2")) {
            sql.append("SELECT ");
            sql.append("    a.npreguntaid AS ID, '' AS NUMERO, a.vasunto AS NOMBRE, a.vdetalle AS SUMILLA, ");
            sql.append(
                    "    a.ncategoriaid AS IDCATEGORIA, b.vnombre AS CATEGORIA, a.dfechapublicacion AS FECHA, ");
            sql.append("    2 AS IDTIPOCONOCIMIENTO, 'Preguntas y Respuestas' AS TIPOCONOCIMIENTO, ");
            sql.append("    a.nsituacionid AS IDESTADO, c.vnombre AS ESTADO ");
            sql.append("FROM TPREGUNTA a ");
            sql.append("    INNER JOIN MTCATEGORIA b ON a.ncategoriaid = b.ncategoriaid ");
            sql.append("    INNER JOIN MTSITUACION c ON a.nsituacionid = c.nsituacionid ");
            sql.append("WHERE a.nactivo = :ACTIVO ");
            sql.append("AND a.nsituacionid = 6 "); // Publicado
            if (StringUtils.isNotBlank(nconocimientovinc)) {
                sql.append("AND a.npreguntaid NOT IN (").append(nconocimientovinc).append(") ");
            }
        }
        if (StringUtils.isNotBlank(ntipoconocimientoid)
                && (ntipoconocimientoid.equals("3") || ntipoconocimientoid.equals("4")
                        || ntipoconocimientoid.equals("5") || ntipoconocimientoid.equals("6"))) {
            sql.append("SELECT ");
            sql.append(
                    "    a.nconocimientoid AS ID, '' AS NUMERO, a.vtitulo AS NOMBRE, a.vdescripcion AS SUMILLA, ");
            sql.append(
                    "    a.ncategoriaid AS IDCATEGORIA, b.vnombre AS CATEGORIA, a.dfechapublicacion AS FECHA, ");
            sql.append("    a.ntpoconocimientoid AS IDTIPOCONOCIMIENTO, d.vnombre AS TIPOCONOCIMIENTO, ");
            sql.append("    a.nsituacionid AS IDESTADO, c.vnombre AS ESTADO ");
            sql.append("FROM TCONOCIMIENTO a ");
            sql.append("    INNER JOIN MTCATEGORIA b ON a.ncategoriaid = b.ncategoriaid ");
            sql.append("    INNER JOIN MTSITUACION c ON a.nsituacionid = c.nsituacionid ");
            sql.append("    INNER JOIN MTTIPO_CONOCIMIENTO d ON a.ntpoconocimientoid = d.ntpoconocimientoid ");
            sql.append("WHERE a.nactivo = :ACTIVO ");
            sql.append("AND a.nsituacionid = 6 "); // Publicado
            sql.append("AND a.ntpoconocimientoid = ").append(ntipoconocimientoid).append(" ");
            if (StringUtils.isNotBlank(nconocimientovinc)) {
                sql.append("AND a.nconocimientoid NOT IN (").append(nconocimientovinc).append(") ");
            }
        }
        sql.append("ORDER BY 5, 7 DESC ");

        object = getHibernateTemplate().execute(new HibernateCallback() {
            @Override
            public Object doInHibernate(Session session) throws HibernateException {
                Query query = session.createSQLQuery(sql.toString());
                query.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
                if (StringUtils.isNotBlank(sql.toString())) {
                    query.setParameter("ACTIVO", BigDecimal.ONE);
                }
                return query.list();
            }
        });
    } catch (DataAccessException e) {
        e.getMessage();
        e.printStackTrace();
    }
    return (List<HashMap>) object;
}