Example usage for javax.persistence NoResultException getMessage

List of usage examples for javax.persistence NoResultException getMessage

Introduction

In this page you can find the example usage for javax.persistence NoResultException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:com.exp.tracker.services.impl.JpaUserService.java

@Transactional
public int deleteUser(Long id, String currentUserName, RequestContext ctx) {
    int result = 1;

    boolean expenseRecordsExist = true;
    boolean settlementRecordsExist = true;
    UserEntity ue = em.find(UserEntity.class, id);

    if (currentUserName.equalsIgnoreCase(ue.getUsername())) {
        ctx.getMessageContext()//from  w  w  w  .  j  a v  a2s. co  m
                .addMessage(new MessageBuilder().error().defaultText("You can not delete yourself.").build());
        return 2;
    }
    // any expense?
    Query getExpensesQuery = em.createNamedQuery("anyExpensesForUser");
    getExpensesQuery.setParameter("userName", ue.getUsername());
    try {
        Collection<?> results = getExpensesQuery.getResultList();
        if (null == results) {
            expenseRecordsExist = false;
        } else {
            if (results.size() == 0) {
                expenseRecordsExist = false;
            }
        }
    } catch (NoResultException nre) {
        if (logger.isDebugEnabled()) {
            logger.debug("No expenses exists for this user - " + currentUserName + " - " + nre.getMessage());
        }
        expenseRecordsExist = false;
    }
    // any settlements?
    settlementRecordsExist = true;
    Query getAllSettlementsForUserQuery = em.createNamedQuery("getAllSettlementsForUser");
    getAllSettlementsForUserQuery.setParameter("userName", ue.getUsername());
    try {
        Collection<?> results = getAllSettlementsForUserQuery.getResultList();
        if (null == results) {
            settlementRecordsExist = false;
        } else {
            if (results.size() == 0) {
                settlementRecordsExist = false;
            }
        }
    } catch (NoResultException nre) {
        if (logger.isDebugEnabled()) {
            logger.debug("No settlement record exists " + nre.getMessage());
        }
        settlementRecordsExist = false;
    }

    if ((!settlementRecordsExist) && (!expenseRecordsExist)) {
        try {
            UserEntity ue1 = em.find(UserEntity.class, id);
            em.remove(ue1);
            result = 0;
            ctx.getMessageContext()
                    .addMessage(new MessageBuilder().info().defaultText("User deleted successfuly.").build());
        } catch (Exception e) {
            logger.error("User deletion failed.", e);
            result = 1;
            ctx.getMessageContext()
                    .addMessage(new MessageBuilder().error().defaultText("User deletion failed.").build());
        }
    } else {
        ctx.getMessageContext()
                .addMessage(new MessageBuilder().error()
                        .defaultText(
                                "Can not delete user. " + "Participatory expenses" + " or settlements exist.")
                        .build());
    }
    return result;
}

From source file:se.nrm.dina.data.jpa.impl.DinaDaoImpl.java

@Override
public T getEntityByJPQL(String jpql) {

    //        logger.info("getEntityByJPQL - jpql: {}", jpql);
    query = entityManager.createQuery(jpql);
    try {//w  w  w. j  a  v  a  2  s  .c o m
        return (T) query.getSingleResult();
    } catch (javax.persistence.NoResultException ex) {
        return null;
    } catch (javax.persistence.NonUniqueResultException ex) {
        throw new DinaDatabaseException(ex.getMessage(), ErrorMsg.getInstance().getNonUniqueErrorCode());
    }
}

From source file:se.nrm.dina.data.jpa.impl.DinaDaoImpl.java

@Override
public List<T> getEntitiesByNamedQuery(String namedQuery, Map<String, Object> map) {

    //        logger.info("getEntitiesByNamedQuery - namedQuery: {} -- {}", namedQuery, map);

    query = entityManager.createNamedQuery(namedQuery);

    setQueryParameter(map);/*from  w w w . j  a  v  a 2  s . c  o  m*/

    try {
        List<T> list = (List<T>) query.getResultList();
        //            entityManager.clear();
        return list;
    } catch (javax.persistence.NoResultException ex) {
        logger.error("No result");
        return null;
    } catch (javax.persistence.NonUniqueResultException ex) {
        throw new DinaDatabaseException(ex.getMessage(), ErrorMsg.getInstance().getNonUniqueErrorCode());
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:nl.npcf.eav.web.EAVController.java

@RequestMapping(value = "/edit/**")
public ModelAndView edit(@RequestParam(value = DELETE_PARAMETER, required = false) String deleteParameter,
        HttpServletRequest request, HttpServletResponse response) throws IOException, EAVException {
    if (!eavStore.initialize()) {
        response.sendRedirect(request.getContextPath() + "/service/meta");
        return null;
    }// w ww.ja va2s. c  om
    String baseUrl = request.getContextPath() + "/service/edit";
    EAVStore.Entity entity = null;
    EAVStore.Path path = null;
    String error = null;
    try {
        String key = getFirstPathNode("/edit", request);
        path = getPath("/edit", true, request);
        if (key.isEmpty()) {
            entity = eavStore.createTransientEntity(null);
        } else {
            boolean delete = Boolean.parseBoolean(deleteParameter);
            Map<EAVStore.Path, String> values = getValues(request);
            try {
                entity = eavStore.findByKey(key);
                if (delete) {
                    if (path.isEmpty()) {
                        eavStore.remove(entity);
                        response.sendRedirect(baseUrl);
                    } else {
                        entity = eavStore.remove(entity, path);
                        response.sendRedirect(baseUrl + EAVStore.PATH_SEPARATOR + key + EAVStore.PATH_SEPARATOR
                                + path.getParent());
                    }
                } else {
                    entity = eavStore.setValues(key, values, getPrincipal());
                }
            } catch (NoResultException e) {
                if (delete) {
                    throw e;
                }
                entity = eavStore.createTransientEntity(key);
                for (Map.Entry<EAVStore.Path, String> entry : values.entrySet()) {
                    entity.setTransientValue(entry.getKey(), entry.getValue(), getPrincipal());
                }
                eavStore.persist(entity);
            }
        }
    } catch (EAVValidationException e) {
        if (e.getValue() == null) {
            error = "Validation problem setting " + e.getAttribute().getPrompt() + ": \"" + e.getMessage()
                    + "\".";
        } else {
            error = "Validation problem setting " + e.getAttribute().getPrompt() + "=[" + e.getValue() + "]: \""
                    + e.getMessage() + "\".";
        }
    } catch (EAVPathException e) {
        error = "Path problem using [" + e.getPathString() + "]: \"" + e.getMessage() + "\".";
    } catch (Throwable t) {
        logger.error("Unhandled exception", t);
        error = "Internal problem. It has been logged.";
    }
    ModelAndView modelAndView = new ModelAndView("edit");
    modelAndView.addObject("entity", entity);
    modelAndView.addObject("path", path);
    modelAndView.addObject("baseUrl", baseUrl);
    modelAndView.addObject("error", error);
    return modelAndView;
}

From source file:war.controller.WorkboardController.java

@RequestMapping(value = "/delete", method = RequestMethod.GET)
public ModelAndView deleteWorkboard(@RequestParam(value = "id", required = true) Integer userStoryId,
        Model model) {//from w w w.  ja  va  2 s .c o  m
    logger.debug("Inside deleteWorkboard");

    try {
        model.addAttribute("user", userDao.find(SecurityHelper.getCurrentlyLoggedInUsername()));

        UserStory userStory = userStoryDao.find(userStoryId);

        if (!(SecurityHelper.IsCurrentUserAllowedToAccess(userStory))) // Security: ownership check
            throw new AccessDeniedException(ERR_ACCESS_DENIED);

        User user = userStory.getOwner();
        userStoryDao.delete(userStory); // Deletes the Workboard
        return ModelForWorkboardCreation(model, user); // Starts the creation of a new workboard
    } catch (NoResultException e) {
        model.addAttribute("errorMessage", e.getMessage());
    }
    return new ModelAndView("workboard");
}

From source file:war.controller.WorkboardController.java

@RequestMapping(value = "/deletedataelement", method = RequestMethod.GET)
public String deleteDataElement(@RequestParam(value = "dataelementid", required = true) Integer dataElementId,
        RedirectAttributes attributes, Model model) {
    logger.info("Inside deleteDataElement");

    try {// ww w.j a  v a2s.  c  om
        DataElement dataElement = dataElementDao.find(dataElementId);
        UserStory userStory = dataElement.getUserStory();

        if (!(SecurityHelper.IsCurrentUserAllowedToAccess(userStory))) // Security: ownership check
            throw new AccessDeniedException(ERR_ACCESS_DENIED);

        // Delete the Data Element if it belongs to the user's workboard
        if (userStory.getMode().equals("active")) {
            dataElementDao.delete(dataElement);
            userStory.getDataElements().remove(dataElement);
            attributes.addFlashAttribute("successMessage", MSG_DATA_ELEMENT_DELETED);
        } else { // If the Data Element belongs to a User Story and not the Workboard, don't delete
            attributes.addFlashAttribute("errorMessage", ERR_DELETE_DATA_ELEMENT);
        }
        // Redirects to the right tab of the workboard after deletion based on the data element type
        return "redirect:" + redirectToCategory(dataElement);
    } catch (NoResultException e) {
        attributes.addFlashAttribute("errorMessage", e.getMessage());
    }
    return ("redirect:/auth/my-workboard");
}

From source file:war.controller.WorkboardController.java

@RequestMapping(value = "/addPastData", method = RequestMethod.POST)
public String addPastDataToWorkboard(@RequestParam(value = "userstoryid", required = true) Integer userStoryId,
        @RequestParam(value = "pastDataId", required = true) Integer pastDataId,
        RedirectAttributes attributes) {
    logger.info("Inside addPastDataToWorkboard");

    UserStory userStory = null;//from   ww w .java2  s.  c  o m
    try {
        userStory = userStoryDao.find(userStoryId);

        if (!(SecurityHelper.IsCurrentUserAllowedToAccess(userStory))) // Security: ownership check
            throw new AccessDeniedException(ERR_ACCESS_DENIED);

        List<PastData> pastDataList = new ArrayList<PastData>();
        pastDataList.add(pastDataDao.find(pastDataId));

        DataElementPast dataElement = new DataElementPast(new Date(), "National climate and marine trends",
                true, 0, DisplayType.PICTURE, userStory, pastDataList);
        dataElementDao.save(dataElement);

        userStory.getDataElements().add(dataElement);

        attributes.addFlashAttribute("successMessage", WorkboardController.MSG_PAST_DATA_ADDED);
    } catch (NoResultException e) {
        attributes.addFlashAttribute("warningMessage", e.getMessage());
    }

    return "redirect:/auth/workboard?user=" + SecurityHelper.getCurrentlyLoggedInUsername()
            + "#tabs-observed-climate";
}

From source file:war.controller.WorkboardController.java

@RequestMapping(value = "/addAbsData", method = RequestMethod.POST)
public String addAbsDataToWorkboard(@RequestParam(value = "userstoryid", required = true) Integer userStoryId,
        @RequestParam(value = "variable", required = true) Integer variableId,
        @RequestParam(value = "seaport", required = true) String seaportCode,
        @RequestParam(value = "displayType", required = true) String displayTypeString,
        RedirectAttributes attributes) {
    logger.info("Inside addAbsDataToWorkboard");

    UserStory userStory = null;//from  w  w w  . j a  va2  s  . c  o  m
    try {
        userStory = userStoryDao.find(userStoryId);

        if (!(SecurityHelper.IsCurrentUserAllowedToAccess(userStory))) // Security: ownership check
            throw new AccessDeniedException(ERR_ACCESS_DENIED);

        AbsVariable variable = absVariableDao.find(variableId);
        Seaport seaport = seaportDao.find(seaportCode);
        List<AbsData> absDataList = absDataDao.getAllInSeaportForVariable(seaport, variable);
        DataElement.DisplayType displayType = DataElement.DisplayType.fromString(displayTypeString);

        DataElementAbs dataElement = new DataElementAbs(new Date(), "ABS Data - " + variable.getName(), true, 0,
                displayType, userStory, absDataList);
        dataElementDao.save(dataElement);

        userStory.getDataElements().add(dataElement);

        attributes.addFlashAttribute("successMessage", WorkboardController.MSG_ABS_DATA_ADDED);
    } catch (NoResultException e) {
        attributes.addFlashAttribute("warningMessage", e.getMessage());
    }

    return "redirect:/auth/workboard?user=" + SecurityHelper.getCurrentlyLoggedInUsername()
            + "#tabs-non-climate-context";
}

From source file:war.controller.WorkboardController.java

@RequestMapping(value = "/addBitreData", method = RequestMethod.POST)
public String addBitreDataToWorkboard(@RequestParam(value = "userstoryid", required = true) Integer userStoryId,
        @RequestParam(value = "variableCategory", required = true) Integer variableCategoryId,
        @RequestParam(value = "seaport", required = true) String seaportCode,
        @RequestParam(value = "displayType", required = true) String displayTypeString,
        RedirectAttributes attributes) {
    logger.info("Inside addBitreDataToWorkboard");

    UserStory userStory = null;/*w  w  w  . j a va2  s . c  o m*/
    try {
        userStory = userStoryDao.find(userStoryId);

        if (!(SecurityHelper.IsCurrentUserAllowedToAccess(userStory))) // Security: ownership check
            throw new AccessDeniedException(ERR_ACCESS_DENIED);

        BitreVariableCategory category = bitreVariableCategoryDao.find(variableCategoryId);
        Seaport seaport = seaportDao.find(seaportCode);
        List<BitreData> bitreDataList = bitreDataDao.find(seaport, category);
        DataElement.DisplayType displayType = DataElement.DisplayType.fromString(displayTypeString);

        DataElementBitre dataElement = new DataElementBitre(new Date(),
                "Ports Australia Data - " + category.getName(), true, 0, displayType, userStory, bitreDataList);
        dataElementDao.save(dataElement);

        userStory.getDataElements().add(dataElement);

        attributes.addFlashAttribute("successMessage", WorkboardController.MSG_BITRE_DATA_ADDED);
    } catch (NoResultException e) {
        attributes.addFlashAttribute("warningMessage", e.getMessage());
    }

    return "redirect:/auth/workboard?user=" + SecurityHelper.getCurrentlyLoggedInUsername()
            + "#tabs-non-climate-context";
}

From source file:war.controller.WorkboardController.java

@RequestMapping(value = "/addCmarData", method = RequestMethod.POST)
public String addCmarDataToWorkboard(@RequestParam(value = "userstoryid", required = true) Integer userStoryId,
        @RequestParam(value = "year", required = true) String year,
        @RequestParam(value = "includePictures", required = false) String includePictures,
        RedirectAttributes attributes) {
    logger.info("Inside addCmarDataToWorkboard");

    UserStory userStory = null;//w  ww .ja v  a2 s .c  o m
    try {
        userStory = userStoryDao.find(userStoryId);

        if (!(SecurityHelper.IsCurrentUserAllowedToAccess(userStory))) // Security: ownership check
            throw new AccessDeniedException(ERR_ACCESS_DENIED);

        // Retrieve data using static Climate Model, Emission scenario and Variable since it is fixed
        // Refer to the method "addCsiroDataToWorkBoard" to see how to enable dynamic data
        List<CmarData> cmarDataList = new ArrayList<CmarData>();
        cmarDataList.add(cmarDataDao.find(userStory.getSeaport().getRegion().getName(), "A1B", "Most Likely",
                Integer.valueOf(year), "Sea Level Rise"));

        Boolean picturesIncluded = (includePictures != null && includePictures.equals("on")) ? true : false;

        DataElementCmar dataElement = new DataElementCmar(new Date(), "CSIRO - CMAR Data", true, 0,
                DisplayType.TABLE, userStory, cmarDataList, picturesIncluded);
        dataElementDao.save(dataElement);

        userStory.getDataElements().add(dataElement);

        attributes.addFlashAttribute("successMessage", WorkboardController.MSG_CMAR_DATA_ADDED);
    } catch (NoResultException e) {
        attributes.addFlashAttribute("warningMessage", e.getMessage());
    }

    return "redirect:/auth/workboard?user=" + SecurityHelper.getCurrentlyLoggedInUsername()
            + "#tabs-future-climate";
}