Example usage for org.hibernate ObjectNotFoundException ObjectNotFoundException

List of usage examples for org.hibernate ObjectNotFoundException ObjectNotFoundException

Introduction

In this page you can find the example usage for org.hibernate ObjectNotFoundException ObjectNotFoundException.

Prototype

public ObjectNotFoundException(Serializable identifier, String entityName) 

Source Link

Document

Constructs a ObjectNotFoundException using the given information.

Usage

From source file:com.maven.dealers.controller.DealerController.java

/**
 * Function to get a dealer by id to be updated
 *
 * @param id of the dealer to be updated
 * @return Dealers ModelAndView/*from   w  ww. j  a  v  a 2  s .c o  m*/
 * @throws ObjectNotFoundException
 */
@RequestMapping({ "/editDealer/{id}" })
public ModelAndView editDealer(@PathVariable("id") int id) throws ObjectNotFoundException {
    logger.info(new Date() + " called function to populate form for editing a dealer");
    Dealer dealer = this.dealerService.getDealerById(id);
    if (dealer == null) {
        logger.error(new Date() + " Exception happened while getting dealer with id = " + id);
        throw new ObjectNotFoundException(dealer, " Dealer with id : " + id + " Not Found");
    }
    logger.debug(new Date() + " Editing Dealer with id = " + id + " , Dealer = " + dealer);
    List<Country> countryList = countryService.listCountries();
    ModelAndView mv = new ModelAndView("admin/dealers");
    mv.addObject("countryList", countryList);
    mv.addObject("dealer", dealer);
    mv.addObject("listDealers", this.dealerService.listDealers());
    return mv;
}

From source file:com.redhat.rhn.domain.action.ActionChainFactory.java

License:Open Source License

/**
 * Gets an Action Chain by id.//  w  ww  .j  a  v a 2s.  c  o m
 * @param requestor the user whose chain we're looking for
 * @param id the id
 * @return the Action Chain
 * @throws ObjectNotFoundException if there is no such id accessible to the requestor
 */
public static ActionChain getActionChain(User requestor, Long id) throws ObjectNotFoundException {
    log.debug("Looking up Action Chain with id " + id);
    if (id == null) {
        return null;
    }
    ActionChain ac = (ActionChain) getSession().createCriteria(ActionChain.class).add(Restrictions.eq("id", id))
            .add(Restrictions.eq("user", requestor)).uniqueResult();
    if (ac == null) {
        throw new ObjectNotFoundException(ActionChain.class,
                "ActionChain Id " + id + " not found for User " + requestor.getLogin());
    }
    return ac;
}

From source file:com.redhat.rhn.domain.action.ActionChainFactory.java

License:Open Source License

/**
 * Gets an Action Chain Entry by id.//www  .  ja  v  a  2 s .  c o m
 * @param requestor the user whose entry we're looking for
 * @param id the action chain entry id
 * @return the Action Chain Entry
 * @throws ObjectNotFoundException if there is no such id accessible to the requestor
 */
public static ActionChainEntry getActionChainEntry(User requestor, Long id) throws ObjectNotFoundException {
    if (id == null) {
        return null;
    }
    ActionChainEntry ace = (ActionChainEntry) getSession().load(ActionChainEntry.class, id);

    if (ace.getActionChain().getUser().getId().longValue() == requestor.getId().longValue()) {
        return ace;
    }
    throw new ObjectNotFoundException(ActionChainEntry.class,
            "ActionChainEntry Id " + id + " not found for User " + requestor.getLogin());
}

From source file:mockit.emulation.hibernate3.SessionEmul.java

License:Open Source License

@SuppressWarnings({ "RawUseOfParameterizedType" })
public Object load(Class theClass, Serializable id) throws ObjectNotFoundException {
    Object entity = get(theClass, id);

    if (entity == null) {
        throw new ObjectNotFoundException(id, theClass.getName());
    }/* ww w. j a  va  2s . co  m*/

    return entity;
}

From source file:no.abmu.organisationregister.service.hibernate3.OrganisationUnitServiceH3Impl.java

License:Open Source License

public OrganisationUnit getByOrganisationTypeAndId(String orgType, String orgId) {

    String query;//  w  ww  .j  a va2s  .c om
    query = "SELECT orgUnit " + "FROM " + OrganisationUnit.class.getName() + " AS orgUnit "
            + "join orgUnit.organisationTypeRelations as orgTypeRelation "
            + "join orgTypeRelation.organisationType as orgType " + "WHERE " + " orgType.name.reference" + "='"
            + orgType + "' " + " AND " + " orgTypeRelation.organisationId='" + orgId + "'";

    Object[] matches = find(query);
    if (matches.length > 1) {
        logger.warn("Id " + orgId + " for organisation type " + orgType + " is not unique, found "
                + matches.length + " matches");
    } else if (matches.length == 0) {
        logger.warn("Could not find OrganisationType with name '" + orgType + "' and orgId '" + orgId + "'");
        Long id = Long.valueOf(orgId);
        throw new ObjectNotFoundException(id, OrganisationUnit.class.getName());
    }

    return (OrganisationUnit) matches[0];
}

From source file:org.hyperic.hq.api.transfer.impl.MeasurementTransferImpl.java

License:Open Source License

protected List<Measurement> getMeasurements(final String rscId, final List<MeasurementTemplate> tmps,
        final AuthzSubject authzSubject) throws PermissionException {
    // get measurements
    Map<Integer, List<Integer>> resIdsToTmpIds = new HashMap<Integer, List<Integer>>();
    List<Integer> tmpIds = new ArrayList<Integer>();
    for (MeasurementTemplate tmp : tmps) {
        tmpIds.add(tmp.getId());//from  www . j a  v a2 s.  co m
    }
    resIdsToTmpIds.put(Integer.valueOf(rscId), tmpIds);
    Map<Resource, List<Measurement>> rscTohqMsmts = null;
    rscTohqMsmts = this.measurementMgr.findMeasurements(authzSubject, resIdsToTmpIds);
    if (rscTohqMsmts == null || rscTohqMsmts.size() == 0 || rscTohqMsmts.values().isEmpty()) {
        throw new ObjectNotFoundException(tmps.toString(), Measurement.class.getName());
    }
    // there should be only one list of measurements for one resource
    List<Measurement> hqMsmts = rscTohqMsmts.values().iterator().next();
    if (hqMsmts == null || hqMsmts.isEmpty()) {
        throw new ObjectNotFoundException(tmps.toString(), Measurement.class.getName());
    }
    return hqMsmts;
}

From source file:org.hyperic.hq.api.transfer.impl.MeasurementTransferImpl.java

License:Open Source License

public MetricResponse getMetrics(ApiMessageContext apiMessageContext, List<String> templateNames,
        final String rscId, final Date begin, final Date end)
        throws ParseException, PermissionException, UnsupportedOperationException, ObjectNotFoundException,
        TimeframeBoundriesException, TimeframeSizeException {
    MetricResponse res = new MetricResponse();
    if (templateNames.isEmpty()) {
        throw new UnsupportedOperationException("message body is missing or corrupted");
    }//from  ww w.j  ava  2  s  .  com
    validateTimeFrame(begin, end);
    if (rscId == null || "".equals(rscId)) {
        throw new UnsupportedOperationException("The request URL is missing the resource ID");
    }
    AuthzSubject authzSubject = apiMessageContext.getAuthzSubject();
    // extract all input measurement templates
    List<MeasurementTemplate> tmps = tmpltMgr.findTemplatesByName(templateNames);
    if (tmps == null || tmps.isEmpty()) {
        throw new ObjectNotFoundException(templateNames.toString(), MeasurementTemplate.class.getName());
    }
    List<Measurement> hqMsmts = getMeasurements(rscId, tmps, authzSubject);
    // get metrics
    for (Measurement hqMsmt : hqMsmts) {
        org.hyperic.hq.api.model.measurements.Measurement msmt = mapper.toMeasurement(hqMsmt);
        List<HighLowMetricValue> hqMetrics = dataMgr.getHistoricalData(hqMsmt, begin.getTime(), end.getTime(),
                true, MAX_DTPS);
        if (hqMetrics != null && !hqMetrics.isEmpty()) {
            List<org.hyperic.hq.api.model.measurements.Metric> metrics = mapper.toMetrics(hqMetrics);
            msmt.setMetrics(metrics);
        }
        res.add(msmt);
    }
    return res;
}

From source file:org.hyperic.hq.api.transfer.impl.MeasurementTransferImpl.java

License:Open Source License

@Transactional(readOnly = true)
public ResourceMeasurementBatchResponse getAggregatedMetricData(ApiMessageContext apiMessageContext,
        ResourceMeasurementRequests requests, Date begin, Date end) throws TimeframeBoundriesException,
        PermissionException, SQLException, UnsupportedOperationException, ObjectNotFoundException {
    ResourceMeasurementBatchResponse res = new ResourceMeasurementBatchResponse(this.errorHandler);
    List<ResourceMeasurementRequest> measRequests;
    if (requests == null || (measRequests = requests.getMeasurementRequests()) == null
            || measRequests.isEmpty()) {
        throw new UnsupportedOperationException("failed parsing the supplied filter");
    }//from   w  w  w  .  j a v  a  2  s.c om
    validateTimeFrame(begin, end);
    AuthzSubject authzSubject = apiMessageContext.getAuthzSubject();
    // extract all input measurement templates
    Map<String, List<String>> tmpNameToRscs = new HashMap<String, List<String>>();
    List<String> tmpNames = null;
    String rscId = null;
    for (ResourceMeasurementRequest request : requests.getMeasurementRequests()) {
        rscId = request.getRscId();
        if (rscId == null || "".equals(rscId)) {
            throw new ObjectNotFoundException("no resource ID supplied", Resource.class.getName());
        }
        tmpNames = request.getMeasurementTemplateNames();
        for (String tmpName : tmpNames) {
            List<String> rscs = tmpNameToRscs.get(tmpName);
            if (rscs == null) {
                rscs = new ArrayList<String>();
                tmpNameToRscs.put(tmpName, rscs);
            }
            rscs.add(rscId);
        }
    }
    // extract tmp Ids per rsc
    List<MeasurementTemplate> tmps = tmpltMgr
            .findTemplatesByName(new ArrayList<String>(tmpNameToRscs.keySet()));
    // will contain all the resources for which at least one of the templates requested for them exists
    Map<Integer, List<Integer>> rscIdsToTmpIds = new HashMap<Integer, List<Integer>>();
    List<String> rscIds = null;
    for (MeasurementTemplate tmp : tmps) {
        rscIds = tmpNameToRscs.get(tmp.getAlias());
        if (rscIds == null) {
            continue;
        }
        for (String _rscId : rscIds) {
            Integer rscIdInt = Integer.valueOf(_rscId);
            List<Integer> tmpIds = rscIdsToTmpIds.get(rscIdInt);
            if (tmpIds == null) {
                tmpIds = new ArrayList<Integer>();
                rscIdsToTmpIds.put(rscIdInt, tmpIds);
            }
            tmpIds.add(tmp.getId());
        }
    }
    // mark resources for which no measurements were found
    final String TEMPLATE_NOT_FOUND_ERR_CODE = ExceptionToErrorCodeMapper.ErrorCode.TEMPLATE_NOT_FOUND
            .getErrorCode();
    rscId = null;
    for (ResourceMeasurementRequest hqMsmtReq : requests.getMeasurementRequests()) {
        // by now we know that all reqs are with valid rscs, o/w we wouldn't get here
        rscId = hqMsmtReq.getRscId();
        // if the requested rsc is not in the map of rscs for which at least one template was found, mark it as a failed rsc
        if (!rscIdsToTmpIds.keySet().contains(Integer.valueOf(rscId))) {
            res.addFailedResource(rscId, TEMPLATE_NOT_FOUND_ERR_CODE, null, new Object[] { "" });
        }
    }
    Map<Integer, Exception> failedRscs = new HashMap<Integer, Exception>();
    Map<Resource, List<Measurement>> rscToHqMsmts = this.measurementMgr.findBulkMeasurements(authzSubject,
            rscIdsToTmpIds, failedRscs);
    if (rscToHqMsmts == null) {
        throw new ObjectNotFoundException(tmps.toString(), Measurement.class.getName());
    }
    final String MEASUREMENT_NOT_FOUND = ExceptionToErrorCodeMapper.ErrorCode.MEASUREMENT_NOT_FOUND
            .getErrorCode();
    for (Map.Entry<Integer, Exception> failedRscEntry : failedRscs.entrySet()) {
        Integer failedRscId = failedRscEntry.getKey();
        Exception e = failedRscEntry.getValue();
        if (e == null) {
            res.addFailedResource(String.valueOf(failedRscId), MEASUREMENT_NOT_FOUND, null,
                    new Object[] { "" });
        } else {
            res.addFailedResource(String.valueOf(failedRscId), e.getMessage(), null, new Object[] { "" });
        }
    }
    // validate that all rscs have msmts, and map msmt names to rscs
    Map<Integer, Resource> msmtIdToRsc = new HashMap<Integer, Resource>();
    Set<Measurement> allMsmts = new HashSet<Measurement>();
    List<Measurement> msmts = null;
    for (Map.Entry<Resource, List<Measurement>> rscToHqMsmtsEntry : rscToHqMsmts.entrySet()) {
        Resource rsc = rscToHqMsmtsEntry.getKey();
        msmts = rscToHqMsmtsEntry.getValue();
        if (msmts == null || msmts.size() == 0) {
            res.addFailedResource(String.valueOf(rsc.getId()), TEMPLATE_NOT_FOUND_ERR_CODE, null,
                    new Object[] { "" });
        } else {
            for (Measurement msmt : msmts) {
                msmtIdToRsc.put(msmt.getId(), rsc);
            }
            allMsmts.addAll(msmts);
        }
    }
    // sort msmts as per their IDs
    Map<Integer, Measurement> msmtIdToMsmt = new HashMap<Integer, Measurement>();
    for (Measurement msmt : allMsmts) {
        msmtIdToMsmt.put(msmt.getId(), msmt);
    }
    Map<Integer, double[]> msmtIdToAgg = dataMgr.getAggregateDataAndAvailUpByMetric(
            new ArrayList<Measurement>(allMsmts), begin.getTime(), end.getTime());
    Map<Integer, ResourceMeasurementResponse> rscIdToRes = new HashMap<Integer, ResourceMeasurementResponse>();
    Resource rsc = null;
    for (Map.Entry<Integer, double[]> msmtIdToAggEntry : msmtIdToAgg.entrySet()) {
        Integer msmtId = msmtIdToAggEntry.getKey();
        rsc = msmtIdToRsc.get(msmtId);
        double[] agg = msmtIdToAggEntry.getValue();
        // no val for that msmt
        if (agg == null || agg.length <= MeasurementConstants.IND_AVG) {
            continue;
        }
        double avg = agg[MeasurementConstants.IND_AVG];
        Measurement hqMsmt = msmtIdToMsmt.get(msmtId);
        // ignore tmps which were not requested (should not happen)
        if (hqMsmt == null) {
            continue;
        }
        org.hyperic.hq.api.model.measurements.Measurement msmt = this.mapper.toMeasurement(hqMsmt, avg);
        ResourceMeasurementResponse rscRes = rscIdToRes.get(rsc.getId());
        if (rscRes == null) {
            rscRes = new ResourceMeasurementResponse(String.valueOf(rsc.getId()));
            rscIdToRes.put(rsc.getId(), rscRes);
            res.addResponse(rscRes);
        }
        rscRes.add(msmt);
    }
    return res;
}

From source file:org.hyperic.hq.appdef.server.session.AIQueueManagerImpl.java

License:Open Source License

private List<AppdefResource> _processQueue(AuthzSubject subject, List<Integer> platformList,
        List<Integer> serverList, List<Integer> ipList, int action, boolean verifyLiveAgent)
        throws PermissionException, ValidationException, AIQApprovalException {
    boolean isApproveAction = (action == AIQueueConstants.Q_DECISION_APPROVE);
    boolean isPurgeAction = (action == AIQueueConstants.Q_DECISION_PURGE);
    int i;//  w w w.j a  v a  2s  . c  o  m

    log.debug("start _processQueue()");

    Map<Integer, Object> aiplatformsToResync = new HashMap<Integer, Object>();
    Map<String, AIServer> aiserversToRemove = new HashMap<String, AIServer>();
    Object marker = new Object();

    AIPlatform aiplatform = null;
    List<AppdefResource> createdResources = new ArrayList<AppdefResource>();

    // Create our visitor based on the action
    AIQResourceVisitor visitor = aiqResourceVisitorFactory.getVisitor(action);

    if (platformList != null) {
        for (i = 0; i < platformList.size(); i++) {
            final Integer id = platformList.get(i);
            if (log.isDebugEnabled()) {
                log.debug("_processQueue(): platform id = [" + id + "]");
            }
            if (id == null) {
                log.error("_processQueue(): platform with ID=null");
                continue;
            }

            aiplatform = aiPlatformDAO.get(id);

            if (aiplatform == null) {
                if (isPurgeAction) {
                    continue;
                } else {
                    throw new ObjectNotFoundException(id, AIPlatform.class.getName());
                }
            }

            // Before processing platforms, ensure the agent is up since
            // the approval process depends on being able to schedule
            // runtime discovery and enable metrics.
            if (isApproveAction && verifyLiveAgent) {
                try {
                    AgentCommandsClient client = agentCommandsClientFactory
                            .getClient(agentManager.getAgent(aiplatform.getAgentToken()));
                    long pingTime = client.ping();
                    if (log.isDebugEnabled()) {
                        log.debug("_processQueue(): The time of ping = [" + pingTime + "]");
                    }

                } catch (AgentNotFoundException e) {
                    // In this case we just want to
                    // remove the AIPlatform from the AIQ since the
                    // agent does not exist anyway
                    // JIRA bug http://jira.hyperic.com/browse/HHQ-2394
                    removeFromQueue(aiplatform);
                    continue;
                } catch (AgentRemoteException e) {
                    log.error("_processQueue(): Error AgentRemoteException- " + e.getMessage());
                    throw new AIQApprovalException("Error invoking remote method on agent " + e.getMessage(),
                            e);
                } catch (AgentConnectionException e) {
                    // [HHQ-3249] if the IP is being updated then ping may
                    // fail but that is expected so ignore
                    // [HHQ-5955] if the IP is being updated and the old IP was removed from ipList
                    // then ping may fail but that is expected so ignore
                    if (ipIsUpdated(aiplatform, ipList)) {
                        log.warn(
                                "_processQueue(): AgentConnectionException catch while IP is updated so ignoring. "
                                        + e.getMessage());
                    } else {
                        log.error("_processQueue(): Error connecting or communicating with agent.  "
                                + e.getMessage());
                        throw new AIQApprovalException(
                                "Error connecting or communicating with agent " + e.getMessage(), e);
                    }
                }
            }

            visitor.visitPlatform(aiplatform, subject, createdResources);
            if (!isPurgeAction)
                aiplatformsToResync.put(id, marker);
        }
    }
    if (ipList != null) {
        for (i = 0; i < ipList.size(); i++) {
            final Integer id = (Integer) ipList.get(i);
            if (id == null) {
                log.error("processQueue: " + aiplatform.getName() + " has an IP with ID=null");
                continue;
            }

            final AIIp aiip = aiIpDAO.get(id);

            if (aiip == null) {
                if (isPurgeAction)
                    continue;
                else
                    throw new ObjectNotFoundException(id, AIIp.class.getName());
            }
            visitor.visitIp(aiip, subject);
            if (!isPurgeAction) {
                Integer pk = aiip.getAIPlatform().getId();
                aiplatformsToResync.put(pk, marker);
            }
        }
    }
    if (serverList != null) {
        for (i = 0; i < serverList.size(); i++) {
            final Integer id = (Integer) serverList.get(i);
            if (id == null) {
                String name = aiplatform == null ? "" : aiplatform.getName();
                log.error("processQueue: " + name + " has a Server with ID=null");
                continue;
            }
            final AIServer aiserver = aIServerDAO.get(id);
            if (aiserver == null) {
                if (isPurgeAction) {
                    continue;
                } else {
                    throw new ObjectNotFoundException(id, AIServer.class.getName());
                }
            }

            visitor.visitServer(aiserver, subject, createdResources);
            if (isApproveAction) {
                // Approved servers are removed from the queue
                String aiid = aiserver.getAutoinventoryIdentifier();
                aiserversToRemove.put(aiid, aiserver);
            } else if (!isPurgeAction) {
                Integer pk = aiserver.getAIPlatform().getId();
                aiplatformsToResync.put(pk, marker);
            }
        }
    }

    // If the action was "approve" or "ignore", then resync queued platforms
    // to appdef, now that appdef may have been updated.

    if (!isPurgeAction) {

        for (Integer id : aiplatformsToResync.keySet()) {

            aiplatform = aiPlatformDAO.get(id);
            syncQueue(aiplatform, isApproveAction);
        }

        if (aiplatform != null) {
            // See above note, now we remove approved servers from the queue
            Collection<AIServer> servers = aiplatform.getAIServers();
            if (servers != null) {
                for (Iterator<AIServer> it = servers.iterator(); it.hasNext();) {
                    AIServer aiServer = it.next();
                    String aiid = aiServer.getAutoinventoryIdentifier();
                    if (aiserversToRemove.containsKey(aiid)) {
                        it.remove();
                    }
                }
            }
        }
    }
    return createdResources;
}

From source file:org.infoglue.calendar.actions.ViewEventAction.java

License:Open Source License

/**
 * This is the entry point for the main listing.
 *///  w w  w.ja  v  a2  s  .co m

public String execute() throws Exception {
    try {
        log.info("this.eventId:" + eventId);

        Session session = getSession(true);

        String requestEventId = ServletActionContext.getRequest().getParameter("eventId");
        String forceRequestEventIdString = ServletActionContext.getRequest()
                .getParameter("forceRequestEventId");
        if (forceRequestEventIdString != null && forceRequestEventIdString.length() > 0)
            this.forceRequestEventId = new Boolean(forceRequestEventIdString);

        String requestEventCopy = ServletActionContext.getRequest().getParameter("eventCopy");
        if (forceRequestEventIdString != null && forceRequestEventIdString.length() > 0)
            this.eventCopy = new Boolean(requestEventCopy);

        if ((this.eventId == null || this.forceRequestEventId.booleanValue()) && requestEventId != null
                && !requestEventId.equalsIgnoreCase(""))
            this.eventId = new Long(requestEventId);

        this.availableLanguages = LanguageController.getController().getLanguageList(session);
        if (this.versionLanguageId == null && this.availableLanguages.size() > 0) {
            this.versionLanguageId = ((Language) this.availableLanguages.get(0)).getId();
        }

        if (this.eventId != null) {
            this.event = EventController.getController().getEvent(eventId, session);
            Iterator eventVersionsIterator = this.event.getVersions().iterator();
            while (eventVersionsIterator.hasNext()) {
                EventVersion currentEventVersion = (EventVersion) eventVersionsIterator.next();
                if (currentEventVersion.getVersionLanguageId().equals(versionLanguageId)) {
                    this.eventVersion = currentEventVersion;
                    break;
                } else if (alternativeEventVersion == null) //Setting the alternative version if none set before and it's not the current.
                {
                    alternativeEventVersion = currentEventVersion;
                }
            }

            if (this.event.getOwningCalendar() != null)
                this.calendarId = this.event.getOwningCalendar().getId();

            this.locations = LocationController.getController().getLocationList(session);
            this.categories = CategoryController.getController().getRootCategoryList(session);
            //this.infogluePrincipals = UserControllerProxy.getController().getAllUsers();
            this.entryFormEventTypes = EventTypeController.getController()
                    .getEventTypeList(EventType.ENTRY_DEFINITION, session);
            this.entryFormEventType = EventTypeController.getController().getEventType(event.getEntryFormId(),
                    session);

            EventType eventType = this.event.getOwningCalendar().getEventType();
            if (eventType != null)
                this.attributes = ContentTypeDefinitionController.getController()
                        .getContentTypeAttributes(eventType.getSchemaValue());

            this.yesOrNo = new ArrayList();
            this.yesOrNo.add("true");

            return Action.SUCCESS;
        } else {
            throw new ObjectNotFoundException("EventId was empty", "");
        }
    } catch (ObjectNotFoundException o) {
        log.warn("Det fanns inget evenemang med id " + this.eventId + ":" + o.getMessage());
        setError("Det fanns inget evenemang med id " + this.eventId, o);
    } catch (Exception e) {
        log.error("Ett fel uppstod nr evenemang med id " + this.eventId + " skulle visas:" + e.getMessage(),
                e);
        setError("Ett fel uppstod nr evenemang med id " + this.eventId + " skulle visas.", e);
    }

    return Action.ERROR;
}