Search in sources :

Example 1 with ServerErrorException

use of com.infiniteautomation.mango.rest.v2.exception.ServerErrorException in project ma-modules-public by infiniteautomation.

the class EventDetectorRestV2Controller method update.

@ApiOperation(value = "Update an Event Detector", notes = "")
@RequestMapping(method = RequestMethod.PUT, value = { "/{xid}" })
public ResponseEntity<AbstractEventDetectorModel<?>> update(@ApiParam(value = "Valid Event Detector XID", required = true, allowMultiple = false) @PathVariable String xid, @ApiParam(value = "Event Detector", required = true) @RequestBody(required = true) AbstractEventDetectorModel<?> model, @AuthenticationPrincipal User user, UriComponentsBuilder builder, HttpServletRequest request) {
    AbstractEventDetectorVO<?> vo = model.getData();
    // Check to see if it already exists
    AbstractEventDetectorVO<?> existing = this.dao.getByXid(xid);
    if (existing == null) {
        throw new NotFoundRestException();
    } else {
        // Set the ID
        vo.setId(existing.getId());
    }
    // Check permission
    DataPointVO dp = DataPointDao.instance.get(vo.getSourceId());
    if (dp == null)
        throw new NotFoundRestException();
    Permissions.ensureDataSourcePermission(user, dp.getDataSourceId());
    // TODO Fix this when we have other types of detectors
    AbstractPointEventDetectorVO<?> ped = (AbstractPointEventDetectorVO<?>) vo;
    ped.njbSetDataPoint(dp);
    // Validate
    ped.ensureValid();
    // Replace it on the data point, if it isn't replaced we fail.
    boolean replaced = false;
    DataPointDao.instance.setEventDetectors(dp);
    ListIterator<AbstractPointEventDetectorVO<?>> it = dp.getEventDetectors().listIterator();
    while (it.hasNext()) {
        AbstractPointEventDetectorVO<?> ed = it.next();
        if (ed.getId() == ped.getId()) {
            it.set(ped);
            replaced = true;
            break;
        }
    }
    if (!replaced)
        throw new ServerErrorException(new TranslatableMessage("rest.error.eventDetectorNotAssignedToThisPoint"));
    // Save the data point
    Common.runtimeManager.saveDataPoint(dp);
    URI location = builder.path("/v2/event-detectors/{xid}").buildAndExpand(vo.getXid()).toUri();
    return getResourceUpdated(vo.asModel(), location);
}
Also used : DataPointVO(com.serotonin.m2m2.vo.DataPointVO) NotFoundRestException(com.infiniteautomation.mango.rest.v2.exception.NotFoundRestException) AbstractPointEventDetectorVO(com.serotonin.m2m2.vo.event.detector.AbstractPointEventDetectorVO) ServerErrorException(com.infiniteautomation.mango.rest.v2.exception.ServerErrorException) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) URI(java.net.URI) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 2 with ServerErrorException

use of com.infiniteautomation.mango.rest.v2.exception.ServerErrorException in project ma-modules-public by infiniteautomation.

the class SessionExceptionRestV2Controller method clearLatest.

@ApiOperation(value = "Clear Last Exception for your session", notes = "")
@ApiResponses({ @ApiResponse(code = 401, message = "Unauthorized user access", response = ResponseEntity.class), @ApiResponse(code = 404, message = "No Exception exists", response = ResponseEntity.class), @ApiResponse(code = 500, message = "Error processing request", response = ResponseEntity.class) })
@RequestMapping(method = { RequestMethod.PUT }, value = { "/latest" }, produces = { "application/json" })
public ResponseEntity<Map<String, Exception>> clearLatest(HttpServletRequest request) {
    RestProcessResult<Map<String, Exception>> result = new RestProcessResult<>(HttpStatus.OK);
    // Get latest Session Exception
    HttpSession session = request.getSession(false);
    if (session == null)
        throw new ServerErrorException(new TranslatableMessage("rest.error.noSession"));
    Map<String, Exception> exceptionMap = new HashMap<String, Exception>();
    for (String key : exceptionKeys) {
        exceptionMap.put(key, (Exception) session.getAttribute(key));
        session.removeAttribute(key);
    }
    return result.createResponseEntity(exceptionMap);
}
Also used : RestProcessResult(com.serotonin.m2m2.web.mvc.rest.v1.message.RestProcessResult) HashMap(java.util.HashMap) HttpSession(javax.servlet.http.HttpSession) ServerErrorException(com.infiniteautomation.mango.rest.v2.exception.ServerErrorException) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) HashMap(java.util.HashMap) Map(java.util.Map) ServerErrorException(com.infiniteautomation.mango.rest.v2.exception.ServerErrorException) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) ApiResponses(com.wordnik.swagger.annotations.ApiResponses) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 3 with ServerErrorException

use of com.infiniteautomation.mango.rest.v2.exception.ServerErrorException in project ma-modules-public by infiniteautomation.

the class SessionExceptionRestV2Controller method getLatest.

@ApiOperation(value = "Get Last Exception for your session", notes = "")
@ApiResponses({ @ApiResponse(code = 401, message = "Unauthorized user access", response = ResponseEntity.class), @ApiResponse(code = 404, message = "No Exception exists", response = ResponseEntity.class), @ApiResponse(code = 500, message = "Error processing request", response = ResponseEntity.class) })
@RequestMapping(method = { RequestMethod.GET }, value = { "/latest" }, produces = { "application/json" })
public ResponseEntity<Map<String, Exception>> getLatest(HttpServletRequest request) {
    RestProcessResult<Map<String, Exception>> result = new RestProcessResult<>(HttpStatus.OK);
    // Get latest Session Exception
    HttpSession session = request.getSession(false);
    if (session == null)
        throw new ServerErrorException(new TranslatableMessage("rest.error.noSession"));
    Map<String, Exception> exceptionMap = new HashMap<String, Exception>();
    for (String key : exceptionKeys) {
        exceptionMap.put(key, (Exception) session.getAttribute(key));
    }
    return result.createResponseEntity(exceptionMap);
}
Also used : RestProcessResult(com.serotonin.m2m2.web.mvc.rest.v1.message.RestProcessResult) HashMap(java.util.HashMap) HttpSession(javax.servlet.http.HttpSession) ServerErrorException(com.infiniteautomation.mango.rest.v2.exception.ServerErrorException) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) HashMap(java.util.HashMap) Map(java.util.Map) ServerErrorException(com.infiniteautomation.mango.rest.v2.exception.ServerErrorException) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) ApiResponses(com.wordnik.swagger.annotations.ApiResponses) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 4 with ServerErrorException

use of com.infiniteautomation.mango.rest.v2.exception.ServerErrorException in project ma-modules-public by infiniteautomation.

the class EventDetectorRestV2Controller method delete.

@ApiOperation(value = "Delete an Event Detector", notes = "")
@RequestMapping(method = RequestMethod.DELETE, value = { "/{xid}" })
public ResponseEntity<AbstractEventDetectorModel<?>> delete(@ApiParam(value = "Valid Event Detector XID", required = true, allowMultiple = false) @PathVariable String xid, @AuthenticationPrincipal User user, UriComponentsBuilder builder, HttpServletRequest request) {
    // Check to see if it already exists
    AbstractEventDetectorVO<?> existing = this.dao.getByXid(xid);
    if (existing == null) {
        throw new NotFoundRestException();
    }
    // Check permission
    DataPointVO dp = DataPointDao.instance.get(existing.getSourceId());
    Permissions.ensureDataSourcePermission(user, dp.getDataSourceId());
    // TODO Fix this when we have other types of detectors
    AbstractPointEventDetectorVO<?> ped = (AbstractPointEventDetectorVO<?>) existing;
    ped.njbSetDataPoint(dp);
    // Remove it from the data point, if it isn't replaced we fail.
    boolean removed = false;
    DataPointDao.instance.setEventDetectors(dp);
    ListIterator<AbstractPointEventDetectorVO<?>> it = dp.getEventDetectors().listIterator();
    while (it.hasNext()) {
        AbstractPointEventDetectorVO<?> ed = it.next();
        if (ed.getId() == ped.getId()) {
            it.remove();
            removed = true;
            break;
        }
    }
    if (!removed)
        throw new ServerErrorException(new TranslatableMessage("rest.error.eventDetectorNotAssignedToThisPoint"));
    // Save the data point
    Common.runtimeManager.saveDataPoint(dp);
    return new ResponseEntity<>(existing.asModel(), HttpStatus.OK);
}
Also used : DataPointVO(com.serotonin.m2m2.vo.DataPointVO) NotFoundRestException(com.infiniteautomation.mango.rest.v2.exception.NotFoundRestException) ResponseEntity(org.springframework.http.ResponseEntity) AbstractPointEventDetectorVO(com.serotonin.m2m2.vo.event.detector.AbstractPointEventDetectorVO) ServerErrorException(com.infiniteautomation.mango.rest.v2.exception.ServerErrorException) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 5 with ServerErrorException

use of com.infiniteautomation.mango.rest.v2.exception.ServerErrorException in project ma-modules-public by infiniteautomation.

the class MangoTaskTemporaryResourceManager method scheduleTask.

private void scheduleTask(TemporaryResource<T, AbstractRestV2Exception> resource) {
    TaskData tasks = (TaskData) resource.getData();
    // TODO Mango 3.4 keep user inside the resource isntead of user id?
    // maybe change the user inside DataPointRestController bulk operation lambda function to get user from background context
    User user = UserDao.instance.get(resource.getUserId());
    if (user == null) {
        AccessDeniedException error = new AccessDeniedException();
        resource.safeError(error);
        return;
    }
    tasks.mainTask = new HighPriorityTask("Temporary resource " + resource.getResourceType() + " " + resource.getId()) {

        @Override
        public void run(long runtime) {
            try {
                BackgroundContext.set(user);
                resource.getTask().run(resource);
            } catch (Exception e) {
                AbstractRestV2Exception error = MangoTaskTemporaryResourceManager.this.mapException(e);
                resource.safeError(error);
            } finally {
                BackgroundContext.remove();
            }
        }

        @Override
        public void rejected(RejectedTaskReason reason) {
            super.rejected(reason);
            TranslatableMessage msg = null;
            switch(reason.getCode()) {
                case RejectedTaskReason.POOL_FULL:
                    msg = new TranslatableMessage("rest.error.rejectedTaskPoolFull");
                    break;
                case RejectedTaskReason.TASK_QUEUE_FULL:
                    msg = new TranslatableMessage("rest.error.rejectedTaskQueueFull");
                    break;
                case RejectedTaskReason.CURRENTLY_RUNNING:
                    msg = new TranslatableMessage("rest.error.rejectedTaskAlreadyRunning");
                    break;
            }
            ServerErrorException ex = msg == null ? new ServerErrorException() : new ServerErrorException(msg);
            AbstractRestV2Exception error = MangoTaskTemporaryResourceManager.this.mapException(ex);
            resource.safeError(error);
        }
    };
    Common.backgroundProcessing.execute(tasks.mainTask);
    this.scheduleTimeout(resource);
}
Also used : AccessDeniedException(com.infiniteautomation.mango.rest.v2.exception.AccessDeniedException) HighPriorityTask(com.serotonin.m2m2.util.timeout.HighPriorityTask) User(com.serotonin.m2m2.vo.User) AbstractRestV2Exception(com.infiniteautomation.mango.rest.v2.exception.AbstractRestV2Exception) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) ServerErrorException(com.infiniteautomation.mango.rest.v2.exception.ServerErrorException) AbstractRestV2Exception(com.infiniteautomation.mango.rest.v2.exception.AbstractRestV2Exception) ServerErrorException(com.infiniteautomation.mango.rest.v2.exception.ServerErrorException) AccessDeniedException(com.infiniteautomation.mango.rest.v2.exception.AccessDeniedException) RejectedTaskReason(com.serotonin.timer.RejectedTaskReason)

Aggregations

ServerErrorException (com.infiniteautomation.mango.rest.v2.exception.ServerErrorException)6 TranslatableMessage (com.serotonin.m2m2.i18n.TranslatableMessage)5 ApiOperation (com.wordnik.swagger.annotations.ApiOperation)4 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)4 NotFoundRestException (com.infiniteautomation.mango.rest.v2.exception.NotFoundRestException)3 AbstractRestV2Exception (com.infiniteautomation.mango.rest.v2.exception.AbstractRestV2Exception)2 AccessDeniedException (com.infiniteautomation.mango.rest.v2.exception.AccessDeniedException)2 DataPointVO (com.serotonin.m2m2.vo.DataPointVO)2 User (com.serotonin.m2m2.vo.User)2 AbstractPointEventDetectorVO (com.serotonin.m2m2.vo.event.detector.AbstractPointEventDetectorVO)2 RestProcessResult (com.serotonin.m2m2.web.mvc.rest.v1.message.RestProcessResult)2 ApiResponses (com.wordnik.swagger.annotations.ApiResponses)2 HashMap (java.util.HashMap)2 Map (java.util.Map)2 HttpSession (javax.servlet.http.HttpSession)2 ResponseEntity (org.springframework.http.ResponseEntity)2 GenericRestException (com.infiniteautomation.mango.rest.v2.exception.GenericRestException)1 ResourceNotFoundException (com.infiniteautomation.mango.rest.v2.exception.ResourceNotFoundException)1 ValidationFailedRestException (com.infiniteautomation.mango.rest.v2.exception.ValidationFailedRestException)1 HighPriorityTask (com.serotonin.m2m2.util.timeout.HighPriorityTask)1