Example usage for javax.persistence NoResultException NoResultException

List of usage examples for javax.persistence NoResultException NoResultException

Introduction

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

Prototype

public NoResultException(String message) 

Source Link

Document

Constructs a new NoResultException exception with the specified detail message.

Usage

From source file:org.broadleafcommerce.openadmin.server.service.AdminEntityServiceImpl.java

@Override
public PersistenceResponse getAdvancedCollectionRecord(ClassMetadata containingClassMetadata,
        Entity containingEntity, Property collectionProperty, String collectionItemId,
        List<SectionCrumb> sectionCrumbs, String alternateId) throws ServiceException {
    PersistencePackageRequest ppr = PersistencePackageRequest.fromMetadata(collectionProperty.getMetadata(),
            sectionCrumbs);//w w  w  .  j av  a  2  s.  c  o  m

    FieldMetadata md = collectionProperty.getMetadata();
    String containingEntityId = getContextSpecificRelationshipId(containingClassMetadata, containingEntity,
            collectionProperty.getName());
    ppr.setSectionEntityField(collectionProperty.getName());

    PersistenceResponse response;

    if (md instanceof AdornedTargetCollectionMetadata) {
        FilterAndSortCriteria fasc = new FilterAndSortCriteria(ppr.getAdornedList().getCollectionFieldName());
        fasc.setFilterValue(containingEntityId);
        ppr.addFilterAndSortCriteria(fasc);

        fasc = new FilterAndSortCriteria(ppr.getAdornedList().getCollectionFieldName() + "Target");
        fasc.setFilterValue(collectionItemId);
        ppr.addFilterAndSortCriteria(fasc);

        if (!StringUtils.isEmpty(alternateId)) {
            fasc = new FilterAndSortCriteria(ppr.getAdornedList().getIdProperty());
            fasc.setFilterValue(alternateId);
            ppr.addFilterAndSortCriteria(fasc);
        }

        response = fetch(ppr);
        Entity[] entities = response.getDynamicResultSet().getRecords();
        Assert.isTrue(entities != null && entities.length == 1, "Entity not found");
    } else if (md instanceof MapMetadata) {
        MapMetadata mmd = (MapMetadata) md;
        FilterAndSortCriteria fasc = new FilterAndSortCriteria(ppr.getForeignKey().getManyToField());
        fasc.setFilterValue(containingEntityId);
        ppr.addFilterAndSortCriteria(fasc);

        response = fetch(ppr);
        Entity[] entities = response.getDynamicResultSet().getRecords();
        for (Entity e : entities) {
            String idProperty = getIdProperty(containingClassMetadata);
            if (mmd.isSimpleValue()) {
                idProperty = "key";
            }
            Property p = e.getPMap().get(idProperty);
            if (p.getValue().equals(collectionItemId)) {
                response.setEntity(e);
                break;
            }
        }
    } else {
        throw new IllegalArgumentException(String.format(
                "The specified field [%s] for class [%s] was not an " + "advanced collection field.",
                collectionProperty.getName(), containingClassMetadata.getCeilingType()));
    }

    if (response == null) {
        throw new NoResultException(String.format(
                "Could not find record for class [%s], field [%s], main entity id "
                        + "[%s], collection entity id [%s]",
                containingClassMetadata.getCeilingType(), collectionProperty.getName(), containingEntityId,
                collectionItemId));
    }

    return response;
}

From source file:nl.b3p.kaartenbalie.service.servlet.CallScriptingServlet.java

/**
 * Checks the login session or credentials
 *
 * @param request The incoming request//from  w  w w. ja va2s  .  co  m
 * @param em The entityManager
 * @param pcode
 * @return The user Principal
 * @throws AccessDeniedException if the user can not be authenticated
 */
protected User checkLogin(HttpServletRequest request, EntityManager em, String pcode)
        throws AccessDeniedException {
    User user = (User) request.getUserPrincipal();

    if (user != null) {
        log.info("Cookie accepted for login, username: " + user.getName());

        return user;
    }

    // Try preemptive basic login
    // attempt to dig out authentication info only if the user has not yet been authenticated
    String authorizationHeader = request.getHeader("Authorization");
    if (authorizationHeader != null) {
        String decoded = decodeBasicAuthorizationString(authorizationHeader);
        String username = parseUsername(decoded);
        String password = parsePassword(decoded);

        String encpw = null;
        try {
            encpw = KBCrypter.encryptText(password);
        } catch (Exception ex) {
            log.error("error encrypting password: ", ex);
        }
        try {
            user = (User) em
                    .createQuery("from User " + "where lower(username) = lower(:username) "
                            + "and password = :password ")
                    .setParameter("username", username).setParameter("password", encpw).getSingleResult();
            em.flush();
        } catch (NonUniqueResultException nue) {
            log.error(
                    "More than one person found for these credentials (to be fixed in database), trying next method.");
            user = null;
        } catch (NoResultException nre) {
            user = null;
            log.debug("No results using encrypted password, trying next method");
        }

        // extra check voor oude non-encrypted passwords
        if (user == null) {
            try {
                user = (User) em
                        .createQuery("from User " + "where lower(username) = lower(:username) "
                                + "and password = :password ")
                        .setParameter("username", username).setParameter("password", encpw).getSingleResult();

                // Volgende keer dus wel encrypted
                user.setPassword(encpw);
                em.merge(user);
                em.flush();

                if (!user.checkRole("beheerder")) {
                    throw new NoResultException("Not a admin");
                }
                log.debug("Cleartext password now encrypted!");
            } catch (NonUniqueResultException nue) {
                log.error(
                        "More than one person found for these (cleartext) credentials (to be fixed in database), trying next method.");
                user = null;
            } catch (NoResultException nre) {
                log.debug("No results using cleartext password, trying next method.");
            }
        }
    }
    if (user != null && user.checkRole("beheerder")) {
        log.info("Basic authentication accepted for login, username: " + user.getName());
        return user;
    } else {
        throw new AccessDeniedException(
                "Authorisation required for this service! No credentials found in Personal url, Authentication header or Cookie, Giving up! ");
    }
}

From source file:de.micromata.genome.jpa.Emgr.java

/**
 * Select attached by pk.//ww w.  ja va  2  s. com
 *
 * @param <R> the generic type
 * @param cls the cls
 * @param pk the pk
 * @return the r
 * @throws NoResultException if not found
 */
@Override
public <R, PK extends Serializable> R selectByPkAttached(final Class<R> cls, final PK pk) {

    R r = findByPkAttached(cls, pk);
    if (r == null) {
        throw new NoResultException("Cannot find " + cls.getSimpleName() + " by pk " + pk);
    }
    return r;

}

From source file:org.rhq.enterprise.server.configuration.ConfigurationManagerBean.java

public @XmlJavaTypeAdapter(ConfigurationAdapter.class) Configuration getResourceConfiguration(Subject subject,
        int resourceId) {
    Resource resource = entityManager.find(Resource.class, resourceId);

    if (resource == null) {
        throw new NoResultException("Cannot get live configuration for unknown resource [" + resourceId + "]");
    }/*  www . ja v  a2  s  .  c  om*/

    if (!authorizationManager.hasResourcePermission(subject, Permission.CONFIGURE_READ, resource.getId())) {
        throw new PermissionException("User [" + subject.getName()
                + "] does not have permission to view resource configuration for [" + resource + "]");
    }

    Configuration result = configurationManager.getResourceConfiguration(resourceId);

    return result;
}

From source file:org.rhq.enterprise.server.configuration.ConfigurationManagerBean.java

public ResourceConfigurationUpdate getLatestResourceConfigurationUpdate(Subject subject, int resourceId,
        boolean fromStructured) {
    log.debug("Getting current Resource configuration for Resource [" + resourceId + "]...");

    Resource resource = entityManager.getReference(Resource.class, resourceId);
    if (resource == null) {
        throw new NoResultException(
                "Cannot get latest resource configuration for unknown Resource [" + resourceId + "].");
    }/*from  www  .  jav a2  s .co  m*/

    if (!authorizationManager.hasResourcePermission(subject, Permission.CONFIGURE_READ, resource.getId())) {
        throw new PermissionException("User [" + subject.getName()
                + "] does not have permission to view Resource configuration for [" + resource + "].");
    }

    ResourceConfigurationUpdate current;
    // Get the latest configuration as known to the server (i.e. persisted in the DB).
    try {
        Query query = entityManager
                .createNamedQuery(ResourceConfigurationUpdate.QUERY_FIND_CURRENTLY_ACTIVE_CONFIG);
        query.setParameter("resourceId", resourceId);
        current = (ResourceConfigurationUpdate) query.getSingleResult();
        resource = current.getResource();
    } catch (NoResultException nre) {
        // The Resource hasn't been successfully configured yet - return null.
        current = null;
    }

    // Check whether or not a resource configuration update is currently in progress.
    ResourceConfigurationUpdate latest;
    try {
        Query query = entityManager
                .createNamedQuery(ResourceConfigurationUpdate.QUERY_FIND_LATEST_BY_RESOURCE_ID);
        query.setParameter("resourceId", resourceId);
        latest = (ResourceConfigurationUpdate) query.getSingleResult();
        if (latest.getStatus() == ConfigurationUpdateStatus.INPROGRESS) {
            // The agent is in the process of a config update, so we do not want to ask it for the live config.
            // Instead, simply return the most recent persisted config w/ a SUCCESS status (possibly null).
            if (current != null) {
                // Fetch and mask the configuration before returning the update.
                Configuration configuration = current.getConfiguration();
                configuration.getMap().size();
                ConfigurationDefinition configurationDefinition = getResourceConfigurationDefinitionForResourceType(
                        subjectManager.getOverlord(), resource.getResourceType().getId());
                // We do not want the masked configuration persisted, so detach all entities before masking the configuration.
                entityManager.clear();
                ConfigurationMaskingUtility.maskConfiguration(configuration, configurationDefinition);
            }
            return current;
        }
    } catch (NoResultException nre) {
        // The resource hasn't been successfully configured yet - not a problem, we'll ask the agent for the live
        // config...
    }

    // ask the agent to get us the live, most up-to-date configuration for the resource,
    // then compare it to make sure what we think is the latest configuration is really the latest
    Configuration liveConfig = getLiveResourceConfiguration(resource, true, fromStructured);

    if (liveConfig != null) {
        Configuration currentConfig = (current != null) ? current.getConfiguration() : null;
        // Compare the live values and, if there is a difference with the current, store the live config as a new
        // update. Note that, if there is no current configuration stored, the live config is stored as the first
        // update.
        boolean theSame = (currentConfig != null && currentConfig.equals(liveConfig));

        // Someone dorked with the configuration on the agent side - save the live config as a new update.
        if (!theSame) {
            try {
                current = persistNewAgentReportedResourceConfiguration(resource, liveConfig);
            } catch (ConfigurationUpdateStillInProgressException e) {
                // This means a config update is INPROGRESS.
                // Return the current in this case since it is our latest committed active config.
                // Note that even though this application exception specifies "rollback=true", it will
                // not effect our current transaction since the persist call was made with REQUIRES_NEW
                // and thus only that new tx was rolled back
                log.debug("Resource is currently in progress of changing its resource configuration - "
                        + "since it hasn't finished yet, will use the last successful resource configuration: "
                        + e);
            }
        }
    } else {
        log.warn("Could not get live resource configuration for resource [" + resource
                + "]; will assume latest resource configuration update is the current resource configuration.");
    }

    if (current != null) {
        // Mask the configuration before returning the update.
        Configuration configuration = current.getConfiguration();
        configuration.getMap().size();
        ConfigurationDefinition configurationDefinition = getResourceConfigurationDefinitionForResourceType(
                subjectManager.getOverlord(), resource.getResourceType().getId());
        // We do not want the masked configuration persisted, so detach all entities before masking the configuration.
        entityManager.clear();
        ConfigurationMaskingUtility.maskConfiguration(configuration, configurationDefinition);
    }
    return current;
}

From source file:com.enioka.jqm.api.HibernateClient.java

@Override
public void killJob(int idJob) {
    // First try to cancel the JI (works if it is not already running)
    try {/*from   www.  j  ava2 s .  c o m*/
        cancelJob(idJob);
        return;
    } catch (JqmClientException e) {
        // Nothing to do - this is thrown if already running. Just go on, this is a standard kill.
    }

    EntityManager em = null;
    try {
        em = getEm();
        em.getTransaction().begin();
        JobInstance j = em.find(JobInstance.class, idJob, LockModeType.PESSIMISTIC_READ);
        if (j == null) {
            throw new NoResultException("Job instance does not exist or has already finished");
        }
        jqmlogger.trace("The " + j.getState() + " job (ID: " + idJob + ")" + " will be marked for kill");

        j.setState(State.KILLED);

        Message m = new Message();
        m.setJi(idJob);
        m.setTextMessage("Kill attempt on the job");
        em.persist(m);
        em.getTransaction().commit();
    } catch (NoResultException e) {
        throw new JqmInvalidRequestException("An attempt was made to kill a job instance that did not exist.");
    } catch (Exception e) {
        throw new JqmClientException("Could not kill a job (internal error)", e);
    } finally {
        closeQuietly(em);
    }
}

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;/*from www  .  ja va2s  .co  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:org.rhq.enterprise.server.configuration.ConfigurationManagerBean.java

public PluginConfigurationUpdate getLatestPluginConfigurationUpdate(Subject subject, int resourceId) {
    log.debug("Getting current plugin configuration for resource [" + resourceId + "]...");

    Resource resource = entityManager.getReference(Resource.class, resourceId);
    if (resource == null) {
        throw new NoResultException(
                "Cannot get latest plugin configuration for unknown Resource [" + resourceId + "].");
    }/* w  ww  .java2  s.  c  o m*/

    if (!authorizationManager.canViewResource(subject, resource.getId())) {
        throw new PermissionException("User [" + subject.getName()
                + "] does not have permission to view plugin configuration for [" + resource + "].");
    }

    PluginConfigurationUpdate current;
    // Get the latest configuration as known to the server (i.e. persisted in the DB).
    try {
        Query query = entityManager
                .createNamedQuery(PluginConfigurationUpdate.QUERY_FIND_CURRENTLY_ACTIVE_CONFIG);
        query.setParameter("resourceId", resourceId);
        current = (PluginConfigurationUpdate) query.getSingleResult();

        resource = current.getResource();

        // Mask the configuration before returning the update.
        Configuration configuration = current.getConfiguration();
        configuration.getMap().size();
        ConfigurationDefinition configurationDefinition = getPluginConfigurationDefinitionForResourceType(
                subjectManager.getOverlord(), resource.getResourceType().getId());
        // We do not want the masked configuration persisted, so detach all entities before masking the configuration.
        entityManager.clear();
        ConfigurationMaskingUtility.maskConfiguration(configuration, configurationDefinition);
    } catch (NoResultException nre) {
        // The resource hasn't been successfully configured yet - return null.
        current = null;
    }

    return current;
}

From source file:org.rhq.enterprise.server.configuration.ConfigurationManagerBean.java

public Configuration getLiveResourceConfiguration(Subject subject, int resourceId, boolean pingAgentFirst,
        boolean fromStructured) throws Exception {
    Resource resource = entityManager.find(Resource.class, resourceId);

    if (resource == null) {
        throw new NoResultException("Cannot get live configuration for unknown resource [" + resourceId + "]");
    }//from   w  ww  .ja v a 2s . co  m

    if (!authorizationManager.canViewResource(subject, resource.getId())) {
        throw new PermissionException("User [" + subject.getName()
                + "] does not have permission to view resource configuration for [" + resource + "]");
    }

    // ask the agent to get us the live, most up-to-date configuration for the resource
    Configuration liveConfig = getLiveResourceConfiguration(resource, pingAgentFirst, fromStructured);

    return liveConfig;
}

From source file:com.enioka.jqm.api.HibernateClient.java

private InputStream getJobLog(int jobId, String extension, String param) {
    // 1: retrieve node to address
    EntityManager em = null;//from ww  w  . j a  v  a2  s .  com
    Node n = null;
    try {
        em = getEm();
        History h = em.find(History.class, jobId);
        if (h != null) {
            n = h.getNode();
        } else {
            JobInstance ji = em.find(JobInstance.class, jobId);
            if (ji != null) {
                n = ji.getNode();
            } else {
                throw new NoResultException("No history or running instance for this jobId.");
            }
        }
    } catch (Exception e) {
        closeQuietly(em);
        throw new JqmInvalidRequestException("No job found with the job ID " + jobId, e);
    }

    if (n == null) {
        throw new JqmInvalidRequestException("cannot retrieve a file from a deleted node");
    }

    // 2: build URL
    URL url = null;
    try {
        url = new URL(
                getFileProtocol(em) + n.getDns() + ":" + n.getPort() + "/ws/simple/" + param + "?id=" + jobId);
        jqmlogger.trace("URL: " + url.toString());
    } catch (MalformedURLException e) {
        throw new JqmClientException("URL is not valid " + url, e);
    } finally {
        em.close();
    }

    return getFile(url.toString());
}