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:war.controller.WorkboardController.java

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

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

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

        Region region = regionDao.find(userStory.getSeaport().getRegion().getName());
        List<AcornSatStation> stations = acornSatStationDao.find(region);

        Boolean extreme = acornSatExtremeData.equals("extreme");

        List<AcornSatData> acornSatDataList = new ArrayList<AcornSatData>();
        for (AcornSatStation station : stations) {
            acornSatDataList.addAll(acornSatDataDao.find(station, extreme));
        }

        DataElementAcornSat dataElement = new DataElementAcornSat(new Date(), "BoM - ACORN-SAT measurements",
                true, 0, DisplayType.TABLE, userStory, acornSatDataList);
        dataElementDao.save(dataElement);

        userStory.getDataElements().add(dataElement);

        attributes.addFlashAttribute("successMessage", WorkboardController.MSG_ACORNSAT_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 = "/addCsiroData", method = RequestMethod.POST)
public String addCsiroDataToWorkboard(@RequestParam(value = "userstoryid", required = true) Integer userStoryId,
        @RequestParam(value = "climateVariable", required = true) String climateVariable,
        @RequestParam(value = "climateEmissionScenario", required = true) String climateEmissionScenario,
        @RequestParam(value = "climateModel", required = true) String climateModel,
        @RequestParam(value = "year", required = true) String year,
        @RequestParam(value = "displayType", required = false) String displayTypeString,
        RedirectAttributes attributes) {
    logger.info("Inside addCsiroDataToWorkboard");

    UserStory userStory = null;// www .  jav  a2 s . c  om
    try {
        userStory = userStoryDao.find(userStoryId);

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

        List<CsiroData> csiroDataList = null;
        if (climateVariable.equals("All"))
            csiroDataList = csiroDataDao.find(userStory.getSeaport().getRegion().getName(),
                    climateEmissionScenario, climateModel, Integer.valueOf(year));
        else {
            csiroDataList = new ArrayList<CsiroData>();
            csiroDataList.add(csiroDataDao.find(userStory.getSeaport().getRegion().getName(),
                    climateEmissionScenario, climateModel, Integer.valueOf(year), climateVariable));
        }

        DataElement.DisplayType displayType = DataElement.DisplayType.fromString(displayTypeString);

        DataElementCsiro dataElement = new DataElementCsiro(new Date(), "Future Climate Change Data", true, 0,
                displayType, userStory, csiroDataList);
        dataElementDao.save(dataElement);

        userStory.getDataElements().add(dataElement);

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

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

From source file:war.controller.WorkboardController.java

@RequestMapping(value = "/addEngineeringData", method = RequestMethod.POST)
public String addEngineeringDataToWorkboard(
        @RequestParam(value = "file", required = true) MultipartFile uploadfile,
        @RequestParam(value = "sourceType", required = true) String sourceType,
        @RequestParam(value = "engVariable", required = true) String engVariableName,
        @RequestParam(value = "engVariableCategory", required = true) String engVariableCategory,
        @RequestParam(value = "id", required = true) Integer userStoryId,
        @RequestParam(value = "displayType", required = true) String displayTypeString,
        RedirectAttributes attributes) {
    logger.info("Inside addEngineeringDataToWorkBoard");

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

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

        EngineeringModelVariable engVariable = null;
        try {
            engVariable = engineeringModelVariableDao.find(engVariableName, engVariableCategory);
        } catch (NoResultException e) {
            logger.info(e.getMessage() + "(" + engVariableName + ")");
            throw (e);
        }

        DataElement.DisplayType displayType = DataElement.DisplayType.fromString(displayTypeString);

        if (sourceType.equals("upload")) {
            logger.info("Excel File Upload");

            int lastIndex = uploadfile.getOriginalFilename().lastIndexOf('.');
            //String fileName = uploadfile.getOriginalFilename().substring(0, lastIndex);
            String fileExtension = uploadfile.getOriginalFilename().substring(lastIndex + 1);
            String fileType = uploadfile.getContentType();

            // Checks the file extension & MIME type
            if (uploadfile.getSize() == 0) {
                throw new IllegalArgumentException(WorkboardController.ERR_UPLOAD_NO_FILE);
            } else if (!(fileType.equals("application/vnd.ms-excel")
                    || fileType.equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
                    || !(fileExtension.equals("xls") || fileExtension.equals("xlsx"))) {
                throw new InvalidFormatException(WorkboardController.ERR_INVALID_FILE_FORMAT);
            }

            ByteArrayInputStream bis = new ByteArrayInputStream(uploadfile.getBytes());
            // HSSFWorkbook and HSSFSheet for XLS, XSSFWorkbook and XSSFSheet for XLSX
            HSSFWorkbook workbook = new HSSFWorkbook(bis);

            // Extract & save Engineering Model Asset
            EngineeringModelAsset asset = extractEngineeringOutputAsset(workbook);
            asset = engineeringModelAssetDao.save(asset);

            // Extract and save Engineering Model Data
            List<EngineeringModelData> extractedDataList = extractEngineeringOutputData(workbook, userStory,
                    engVariable, asset);

            // Create a data element using the extracted data if there is some
            if (extractedDataList != null && extractedDataList.size() > 0) {

                for (EngineeringModelData data : extractedDataList) {
                    engineeringModelDataDao.save(data);
                }

                DataElementEngineeringModel de = new DataElementEngineeringModel(new Date(),
                        "Concrete deterioration for " + asset.getAssetCode(), true, 0, displayType, userStory,
                        extractedDataList);
                dataElementDao.save(de);

                userStory = userStoryDao.find(userStoryId);
                attributes.addFlashAttribute("successMessage", WorkboardController.MSG_ENG_DATA_ADDED);
            } else {
                throw new NoResultException(WorkboardController.ERR_NO_DATA_ENG_MODEL);
            }
        } else if (sourceType.equals("example")) {
            logger.info("Example selected");

            //Find the Data
            List<EngineeringModelData> engineeringModelDataList = engineeringModelDataDao
                    .find(userStory.getSeaport().getRegion(), engVariable);

            // Create the data element
            if (engineeringModelDataList != null && engineeringModelDataList.size() > 0) {
                String dataElementTitle = "Concrete deterioration for "
                        + engineeringModelDataList.get(0).getAsset().getAssetCode();
                DataElementEngineeringModel de = new DataElementEngineeringModel(new Date(), dataElementTitle,
                        true, 0, displayType, userStory, engineeringModelDataList);
                dataElementDao.save(de);

                userStory = userStoryDao.find(userStoryId);
                attributes.addFlashAttribute("successMessage", WorkboardController.MSG_ENG_DATA_ADDED);
            } else {
                throw new NoResultException(WorkboardController.ERR_NO_DATA_ENG_MODEL_EXAMPLE);
            }
        }
    } catch (NoResultException e) {
        attributes.addFlashAttribute("warningMessage", e.getMessage());
    } catch (InvalidFormatException e) {
        attributes.addFlashAttribute("warningMessage", e.getMessage());
    } catch (IllegalArgumentException e) {
        attributes.addFlashAttribute("warningMessage", e.getMessage());
    } catch (IOException e) {
        attributes.addFlashAttribute("errorMessage", e.getMessage());
    }

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

From source file:com.haulmont.cuba.core.app.RdbmsStore.java

@SuppressWarnings("unchecked")
protected <E extends Entity> List<E> executeQuery(Query query, boolean singleResult) {
    List<E> list;/*from  w w  w .j ava  2 s. c o m*/
    try {
        if (singleResult) {
            try {
                E result = (E) query.getSingleResult();
                list = new ArrayList<>(1);
                list.add(result);
            } catch (NoResultException e) {
                list = Collections.emptyList();
            }
        } else {
            list = query.getResultList();
        }
    } catch (javax.persistence.PersistenceException e) {
        if (e.getCause() instanceof org.eclipse.persistence.exceptions.QueryException && e.getMessage() != null
                && e.getMessage().contains("Fetch group cannot be set on report query")) {
            throw new DevelopmentException("DataManager cannot execute query for single attributes");
        } else {
            throw e;
        }
    }
    return list;
}

From source file:mx.edu.ittepic.AEEcommerce.ejbs.OperationCommerce.java

public String deleteCompany(String CompanyId) {
    Message m = new Message();
    GsonBuilder builder = new GsonBuilder();
    Gson gson = builder.create();/*from w ww  .  j a va2s. c  o m*/
    try {
        Company r = new Company();
        Query q = entity.createNamedQuery("Company.findByCompanyid").setParameter("companyid",
                Integer.parseInt(CompanyId));
        r = (Company) q.getSingleResult();
        if (r == null) {
            m.setCode(404);
            m.setMsg("No se encontro");
            m.setDetail(":(");
        } else {
            entity.remove(r);
            m.setCode(200);
            m.setMsg("Todo bien");
            m.setDetail("OK");
        }
        return gson.toJson(m);

    } catch (IllegalArgumentException e) {
        m.setCode(404);
        m.setMsg(e.getMessage());
        m.setDetail("error");
        return gson.toJson(m);
    } catch (NoResultException ex) {
        m.setCode(404);
        m.setMsg(ex.getMessage());
        m.setDetail("error");
        return gson.toJson(m);
    } catch (IllegalStateException exx) {
        m.setCode(404);
        m.setMsg(exx.getMessage());
        m.setDetail("error");
        return gson.toJson(m);
    } catch (TransactionRequiredException exxx) {
        m.setCode(404);
        m.setMsg(exxx.getMessage());
        m.setDetail("error");
        return gson.toJson(m);
    }
}

From source file:mx.edu.ittepic.AEEcommerce.ejbs.OperationCommerce.java

public String deleteUsers(String userid) {
    Message m = new Message();
    GsonBuilder builder = new GsonBuilder();
    Gson gson = builder.create();//from w  w  w  .  j a v  a 2 s . c om
    try {
        Users r = new Users();
        Query q = entity.createNamedQuery("Users.findByUserid").setParameter("userid",
                Integer.parseInt(userid));
        r = (Users) q.getSingleResult();
        if (r == null) {
            m.setCode(404);
            m.setMsg("No se encontro");
            m.setDetail(":(");
        } else {
            entity.remove(r);
            m.setCode(200);
            m.setMsg("Todo bien");
            m.setDetail("OK");
        }
        return gson.toJson(m);

    } catch (IllegalArgumentException e) {
        m.setCode(404);
        m.setMsg(e.getMessage());
        m.setDetail("error");
        return gson.toJson(m);
    } catch (NoResultException ex) {
        m.setCode(404);
        m.setMsg(ex.getMessage());
        m.setDetail("error");
        return gson.toJson(m);
    } catch (IllegalStateException exx) {
        m.setCode(404);
        m.setMsg(exx.getMessage());
        m.setDetail("error");
        return gson.toJson(m);
    } catch (TransactionRequiredException exxx) {
        m.setCode(404);
        m.setMsg(exxx.getMessage());
        m.setDetail("error");
        return gson.toJson(m);
    }
}

From source file:mx.edu.ittepic.AEEcommerce.ejbs.OperationCommerce.java

public String deleteCategory(String categoryid) {
    Message m = new Message();
    GsonBuilder builder = new GsonBuilder();
    Gson gson = builder.create();//from www .j  av a 2 s  .co  m
    try {
        Category r = new Category();
        Query q = entity.createNamedQuery("Category.findByCategoryid").setParameter("categoryid",
                Integer.parseInt(categoryid));
        r = (Category) q.getSingleResult();
        if (r == null) {
            m.setCode(404);
            m.setMsg("No se encontro");
            m.setDetail(":(");
        } else {
            entity.remove(r);
            m.setCode(200);
            m.setMsg("Todo bien");
            m.setDetail("OK");
        }
        return gson.toJson(m);

    } catch (IllegalArgumentException e) {
        m.setCode(404);
        m.setMsg(e.getMessage());
        m.setDetail("error");
        return gson.toJson(m);
    } catch (NoResultException ex) {
        m.setCode(404);
        m.setMsg(ex.getMessage());
        m.setDetail("error");
        return gson.toJson(m);
    } catch (IllegalStateException exx) {
        m.setCode(404);
        m.setMsg(exx.getMessage());
        m.setDetail("error");
        return gson.toJson(m);
    } catch (TransactionRequiredException exxx) {
        m.setCode(404);
        m.setMsg(exxx.getMessage());
        m.setDetail("error");
        return gson.toJson(m);
    }
}

From source file:org.rhq.enterprise.server.measurement.AvailabilityManagerBean.java

@SuppressWarnings("unchecked")
public boolean mergeAvailabilityReport(AvailabilityReport report) {
    int reportSize = report.getResourceAvailability().size();
    String agentName = report.getAgentName();
    StopWatch watch = new StopWatch();

    if (reportSize == 0) {
        log.error("Agent [" + agentName
                + "] sent an empty availability report.  This is a bug, please report it");
        return true; // even though this report is bogus, do not ask for an immediate full report to avoid unusual infinite recursion due to this error condition
    }/*from  www  . jav a 2  s .  c om*/

    if (log.isDebugEnabled()) {
        if (reportSize > 1) {
            log.debug("Agent [" + agentName + "]: processing availability report of size: " + reportSize);
        }
    }

    // translate data into Availability objects for downstream processing
    List<Availability> availabilities = new ArrayList<Availability>(report.getResourceAvailability().size());
    for (AvailabilityReport.Datum datum : report.getResourceAvailability()) {
        availabilities.add(new Availability(new Resource(datum.getResourceId()), datum.getStartTime(),
                datum.getAvailabilityType()));
    }

    // We will alert only on the avails for enabled resources. Keep track of any that are disabled. 
    List<Availability> disabledAvailabilities = new ArrayList<Availability>();

    boolean askForFullReport = false;
    Integer agentToUpdate = agentManager.getAgentIdByName(agentName);

    // if this report is from an agent update the lastAvailreport time
    if (!report.isEnablementReport() && agentToUpdate != null) {
        // do this now, before we might clear() the entity manager
        availabilityManager.updateLastAvailabilityReport(agentToUpdate.intValue());
    }

    int numInserted = 0;

    // if this report is from an agent, and is a changes-only report, and the agent appears backfilled,
    // then we need to skip this report so as not to waste our time> Then, immediately request and process
    // a full report because, obviously, the agent is no longer down but the server thinks
    // it still is down - we need to know the availabilities for all the resources on that agent
    if (!report.isEnablementReport() && report.isChangesOnlyReport()
            && agentManager.isAgentBackfilled(agentToUpdate.intValue())) {
        askForFullReport = true;

    } else {
        Query q = entityManager.createNamedQuery(Availability.FIND_CURRENT_BY_RESOURCE);
        q.setFlushMode(FlushModeType.COMMIT);

        int count = 0;
        for (Availability reported : availabilities) {
            if ((++count % 100) == 0) {
                entityManager.flush();
                entityManager.clear();
            }

            // availability reports only tell us the current state at the start time; end time is ignored/must be null
            reported.setEndTime(null);

            try {
                q.setParameter("resourceId", reported.getResource().getId());
                Availability latest = (Availability) q.getSingleResult();
                AvailabilityType latestType = latest.getAvailabilityType();
                AvailabilityType reportedType = reported.getAvailabilityType();

                // If the current avail is DISABLED, and this report is not trying to re-enable the resource,
                // Then ignore the reported avail.
                if (AvailabilityType.DISABLED == latestType) {
                    if (!(report.isEnablementReport() && (AvailabilityType.UNKNOWN == reportedType))) {
                        disabledAvailabilities.add(reported);
                        continue;
                    }
                }

                if (reported.getStartTime() >= latest.getStartTime()) {
                    //log.info( "new avail (latest/reported)-->" + latest + "/" + reported );

                    // the new availability data is for a time after our last known state change
                    // we are runlength encoded, so only persist data if the availability changed                        
                    if (latest.getAvailabilityType() != reported.getAvailabilityType()) {
                        entityManager.persist(reported);
                        numInserted++;

                        latest.setEndTime(reported.getStartTime());
                        latest = entityManager.merge(latest);

                        updateResourceAvailability(reported);
                    }

                    // our last known state was unknown, ask for a full report to ensure we are in sync with agent
                    if (latest.getAvailabilityType() == AvailabilityType.UNKNOWN) {
                        askForFullReport = true;
                    }
                } else {
                    //log.info( "past avail (latest/reported)==>" + latest + "/" + reported );

                    // The new data is for a time in the past, probably an agent sending a report after
                    // a network outage has been corrected but after we have already backfilled.
                    // We need to insert it into our past timeline.
                    insertAvailability(reported);
                    numInserted++;

                    // this is an unusual report - ask the agent for a full report so as to ensure we are in sync with agent
                    askForFullReport = true;
                }
            } catch (NoResultException nre) {
                // This condition should never happen. An initial, unknown, Availability/ResourceAvailability
                // are created at resource persist time. But, just in case, handle it...
                log.warn("Resource [" + reported.getResource() + "] has no availability without an endtime ["
                        + nre.getMessage() + "] - will attempt to create one\n" + report.toString(false));

                entityManager.persist(reported);
                updateResourceAvailability(reported);
                numInserted++;

            } catch (NonUniqueResultException nure) {
                // This condition should never happen.  In my world of la-la land, I've done everything
                // correctly so this never happens.  But, due to the asynchronous nature of things,
                // I have to believe that this still might happen (albeit rarely).  If it does happen,
                // and we do nothing about it - bad things arise.  So, if we find that a resource
                // has 2 or more availabilities with endTime of null, we need to delete all but the
                // latest one (the one whose start time is the latest).  This should correct the
                // problem and allow us to continue processing availability reports for that resource
                log.warn("Resource [" + reported.getResource()
                        + "] has multiple availabilities without an endtime [" + nure.getMessage()
                        + "] - will attempt to remove the extra ones\n" + report.toString(false));

                q.setParameter("resourceId", reported.getResource().getId());
                List<Availability> latest = q.getResultList();

                // delete all but the last one (our query sorts in ASC start time order)
                int latestCount = latest.size();
                for (int i = 0; i < (latestCount - 1); i++) {
                    entityManager.remove(latest.get(i));
                }
                updateResourceAvailability(latest.get(latestCount - 1));

                // this is an unusual report - ask the agent for a full report so as to ensure we are in sync with agent
                askForFullReport = true;
            }
        }

        MeasurementMonitor.getMBean().incrementAvailabilityReports(report.isChangesOnlyReport());
        MeasurementMonitor.getMBean().incrementAvailabilitiesInserted(numInserted);
        MeasurementMonitor.getMBean().incrementAvailabilityInsertTime(watch.getElapsed());
        watch.reset();
    }

    // notify alert condition cache manager for all reported avails for for enabled resources
    availabilities.removeAll(disabledAvailabilities);
    notifyAlertConditionCacheManager("mergeAvailabilityReport",
            availabilities.toArray(new Availability[availabilities.size()]));

    if (!report.isEnablementReport()) {
        // a single report comes from a single agent - update the agent's last availability report timestamp
        if (agentToUpdate != null) {
            // don't bother asking for a full report if the one we are currently processing is already full
            if (askForFullReport && report.isChangesOnlyReport()) {
                log.debug("The server is unsure that it has up-to-date availabilities for agent [" + agentName
                        + "]; asking for a full report to be sent");
                return false;
            }
        } else {
            log.error("Could not figure out which agent sent availability report. "
                    + "This error is harmless and should stop appearing after a short while if the platform of the agent ["
                    + agentName + "] was recently removed. In any other case this is a bug." + report);
        }
    }

    return true; // everything is OK and things look to be in sync
}

From source file:com.tasktop.c2c.server.tasks.tests.service.TaskServiceTest.java

License:asdf

@Test
public void testWorkflowTaskUpdate()
        throws EntityNotFoundException, ConcurrentUpdateException, ValidationException {
    int updateTestCount = 0;
    for (com.tasktop.c2c.server.tasks.domain.TaskStatus status : getRepositoryConfiguration().getStatuses()) {
        for (com.tasktop.c2c.server.tasks.domain.TaskStatus status2 : getRepositoryConfiguration()
                .getStatuses()) {//ww  w  .j a v a2  s .c o m
            System.out.println("Test " + status + " -> " + status2);
            ++updateTestCount;
            boolean transitionAllowed = false;
            boolean commentRequired = false;
            if (status.equals(status2)) {
                transitionAllowed = true;
            } else {
                try {
                    commentRequired = (Boolean) entityManager
                            .createQuery(
                                    "select sw.id.requireComment from " + StatusWorkflow.class.getSimpleName()
                                            + " sw where sw.oldStatus.value = '" + status.getValue()
                                            + "' and sw.newStatus.value = '" + status2.getValue() + "'")
                            .getSingleResult();
                    transitionAllowed = true;
                } catch (NoResultException e) {
                    // expected
                }
            }
            com.tasktop.c2c.server.tasks.domain.Task toCreate = getMockTask("test " + status.getValue());
            com.tasktop.c2c.server.tasks.domain.Task task = taskService.createTask(toCreate);

            // create the initial state, bypassing workflow
            Task itask = entityManager.find(Task.class, task.getId());
            itask.setStatus(status.getValue());

            task.setStatus(status2);
            if (commentRequired) {
                Comment comment = new Comment();
                comment.setAuthor(task.getReporter());
                comment.setCommentText("a comment");
                task.getComments().add(comment);
            }
            ensureValidResolutionForStatus(task);

            try {
                taskService.updateTask(task);
                if (transitionAllowed) {
                    // expected
                } else {
                    fail("Should not be able to transition a task with status from " + status + " to "
                            + status2);
                }
            } catch (ValidationException e) {
                if (transitionAllowed) {
                    fail("Should be able to transition a task with status from " + status + " to " + status2
                            + ": " + e.getMessage());
                }
            }
        }
    }
    // sanity
    assertTrue(updateTestCount > 0);
}