use of com.infiniteautomation.mango.rest.latest.exception.ServerErrorException in project ma-modules-public by infiniteautomation.
the class PointValueRestController method putPointValue.
/**
* Update a point value in the system
*/
@ApiOperation(value = "Update an existing data point's value", notes = "Data point must exist and be enabled")
@RequestMapping(method = RequestMethod.PUT, value = "/{xid}")
public ResponseEntity<LegacyPointValueTimeModel> putPointValue(@RequestBody() LegacyPointValueTimeModel model, @PathVariable String xid, @ApiParam(value = "Return converted value using displayed unit", defaultValue = "false") @RequestParam(required = false, defaultValue = "false") boolean unitConversion, @AuthenticationPrincipal PermissionHolder user, UriComponentsBuilder builder) {
DataPointVO vo = this.dataPointService.get(xid);
this.dataPointService.ensureSetPermission(user, vo);
// Set the time to now if it is not present
if (model.getTimestamp() == 0) {
model.setTimestamp(Common.timer.currentTimeMillis());
}
// Validate the model's data type for compatibility
if (model.getDataType() != vo.getPointLocator().getDataType()) {
throw new GenericRestException(HttpStatus.NOT_ACCEPTABLE, new TranslatableMessage("event.ds.dataType"));
}
// Validate the timestamp for future dated
if (model.getTimestamp() > Common.timer.currentTimeMillis() + SystemSettingsDao.getInstance().getFutureDateLimit()) {
throw new GenericRestException(HttpStatus.NOT_ACCEPTABLE, new TranslatableMessage("common.default", "Future dated points not acceptable."));
}
// Are we converting from the rendered Unit?
if (unitConversion) {
if ((model.getDataType() == DataType.NUMERIC) && (model.getValue() instanceof Number)) {
double value;
if (model.getValue() instanceof Integer) {
value = ((Integer) model.getValue());
} else {
value = ((Double) model.getValue());
}
model.setValue(vo.getRenderedUnit().getConverterTo(vo.getUnit()).convert(value));
} else {
throw new GenericRestException(HttpStatus.NOT_ACCEPTABLE, new TranslatableMessage("common.default", "[" + xid + "]Cannot perform unit conversion on Non Numeric data types."));
}
}
// to convert it
if ((model.getDataType() == DataType.MULTISTATE || model.getDataType() == DataType.NUMERIC) && (model.getValue() instanceof String)) {
try {
DataValue value = vo.getTextRenderer().parseText((String) model.getValue(), vo.getPointLocator().getDataType());
model.setValue(value.getObjectValue());
} catch (Exception e) {
// Lots can go wrong here so let the user know
throw new GenericRestException(HttpStatus.NOT_ACCEPTABLE, new TranslatableMessage("common.default", "[" + xid + "]Unable to convert String representation to any known value."));
}
}
final PointValueTime pvt;
try {
DataValue dataValue;
switch(model.getDataType()) {
case ALPHANUMERIC:
dataValue = new AlphanumericValue((String) model.getValue());
break;
case BINARY:
dataValue = new BinaryValue((Boolean) model.getValue());
break;
case MULTISTATE:
dataValue = new MultistateValue(((Number) model.getValue()).intValue());
break;
case NUMERIC:
dataValue = new NumericValue(((Number) model.getValue()).doubleValue());
break;
default:
throw new UnsupportedOperationException("Setting image values not supported");
}
if (model.getAnnotation() != null)
pvt = new AnnotatedPointValueTime(dataValue, model.getTimestamp(), new TranslatableMessage("common.default", model.getAnnotation()));
else
pvt = new PointValueTime(dataValue, model.getTimestamp());
} catch (Exception e) {
throw new GenericRestException(HttpStatus.NOT_ACCEPTABLE, new TranslatableMessage("common.default", "[" + xid + "]Invalid Format"));
}
// one last check to ensure we are inserting the correct data type
if (pvt.getValue().getDataType() != vo.getPointLocator().getDataType()) {
throw new GenericRestException(HttpStatus.NOT_ACCEPTABLE, new TranslatableMessage("event.ds.dataType"));
}
final int dataSourceId = vo.getDataSourceId();
SetPointSource source = null;
if (model.getAnnotation() != null) {
source = new SetPointSource() {
@Override
public String getSetPointSourceType() {
return "REST";
}
@Override
public int getSetPointSourceId() {
return dataSourceId;
}
@Override
public TranslatableMessage getSetPointSourceMessage() {
return ((AnnotatedPointValueTime) pvt).getSourceMessage();
}
@Override
public void raiseRecursionFailureEvent() {
log.error("Recursive failure while setting point via REST");
}
};
}
try {
Common.runtimeManager.setDataPointValue(vo.getId(), pvt, source);
// This URI may not always be accurate if the Data Source doesn't use the
// provided time...
URI location = builder.path("/point-values/{xid}/{time}").buildAndExpand(xid, pvt.getTime()).toUri();
HttpHeaders headers = new HttpHeaders();
headers.setLocation(location);
return new ResponseEntity<>(model, headers, HttpStatus.CREATED);
} catch (RTException e) {
// Ok its probably not enabled or settable
throw new GenericRestException(HttpStatus.NOT_ACCEPTABLE, new TranslatableMessage("common.default", "[" + xid + "]" + e.getMessage()));
} catch (Exception e) {
log.error(e.getMessage(), e);
throw new ServerErrorException(e);
}
}
use of com.infiniteautomation.mango.rest.latest.exception.ServerErrorException in project ma-modules-public by infiniteautomation.
the class MangoTaskTemporaryResourceManager method scheduleTask.
private void scheduleTask(TemporaryResource<T, AbstractRestException> resource) {
TaskData tasks = (TaskData) resource.getData();
// high priority task will start with user that calls this method in the SecurityContext
tasks.mainTask = new HighPriorityTask("Temporary resource " + resource.getResourceType() + " " + resource.getId()) {
@Override
public void run(long runtime) {
try {
resource.runTask();
} catch (Exception e) {
AbstractRestException error = MangoTaskTemporaryResourceManager.this.mapException(e);
resource.safeError(error);
}
}
@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);
AbstractRestException error = MangoTaskTemporaryResourceManager.this.mapException(ex);
resource.safeError(error);
}
};
Common.backgroundProcessing.execute(tasks.mainTask);
this.scheduleTimeout(resource);
}
use of com.infiniteautomation.mango.rest.latest.exception.ServerErrorException in project ma-modules-public by infiniteautomation.
the class WatchListService method getPointEvents.
/**
*/
public void getPointEvents(WatchListVO vo, Integer limit, Integer offset, Consumer<EventInstanceVO> callback) {
PermissionHolder user = Common.getUser();
List<Object> args = new ArrayList<>();
args.add("typeRef1");
switch(vo.getType()) {
case STATIC:
this.dao.getPoints(vo.getId(), (dp) -> {
if (dataPointService.hasReadPermission(user, dp)) {
args.add(Integer.toString(dp.getId()));
}
});
break;
case QUERY:
if (vo.getParams().size() > 0)
throw new ServerErrorException(new TranslatableMessage("watchList.queryParametersNotSupported"));
ASTNode conditions = RQLUtils.parseRQLtoAST(vo.getQuery());
dataPointService.customizedQuery(conditions, (dp) -> {
if (dataPointService.hasReadPermission(user, dp)) {
args.add(Integer.toString(dp.getId()));
}
});
break;
case TAGS:
throw new ServerErrorException(new TranslatableMessage("watchList.queryParametersNotSupported"));
default:
throw new ServerErrorException(new TranslatableMessage("common.default", "unknown watchlist type: " + vo.getType()));
}
// Create Event Query for these Points
if (args.size() > 1) {
ASTNode query = new ASTNode("in", args);
if (user.getUser() != null) {
query = addAndRestriction(query, new ASTNode("eq", "userId", user.getUser().getId()));
}
query = addAndRestriction(query, new ASTNode("eq", "typeName", EventTypeNames.DATA_POINT));
if (limit != null) {
if (offset == null) {
offset = 0;
}
query = addAndRestriction(query, new ASTNode("limit", limit, offset));
}
eventService.customizedQuery(query, (event) -> {
if (eventService.hasReadPermission(user, event)) {
callback.accept(event);
}
});
}
}
use of com.infiniteautomation.mango.rest.latest.exception.ServerErrorException in project ma-modules-public by infiniteautomation.
the class WatchListService method getDataPoints.
/**
* Get the full data points for a list (TAG_TYPE not supported)
*/
public void getDataPoints(WatchListVO vo, Consumer<DataPointVO> callback) {
PermissionHolder user = Common.getUser();
switch(vo.getType()) {
case STATIC:
this.dao.getPoints(vo.getId(), (dp) -> {
if (dataPointService.hasReadPermission(user, dp)) {
callback.accept(dp);
}
});
break;
case QUERY:
if (vo.getParams().size() > 0)
throw new ServerErrorException(new TranslatableMessage("watchList.queryParametersNotSupported"));
ASTNode rql = RQLUtils.parseRQLtoAST(vo.getQuery());
ConditionSortLimit conditions = dataPointService.rqlToCondition(rql, null, null, null);
dataPointService.customizedQuery(conditions, callback);
break;
case TAGS:
throw new ServerErrorException(new TranslatableMessage("watchList.queryParametersNotSupported"));
default:
throw new ServerErrorException(new TranslatableMessage("common.default", "unknown watchlist type: " + vo.getType()));
}
}
use of com.infiniteautomation.mango.rest.latest.exception.ServerErrorException in project ma-modules-public by infiniteautomation.
the class VirtualSerialPortConfigDeserializer method deserialize.
@Override
public VirtualSerialPortConfig deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
ObjectMapper mapper = (ObjectMapper) jp.getCodec();
JsonNode tree = jp.readValueAsTree();
String typeName = tree.get("portType").asText();
Class<?> clazz;
switch(typeName) {
case "SERIAL_SOCKET_BRIDGE":
clazz = SerialSocketBridgeConfig.class;
break;
case "SERIAL_SERVER_SOCKET_BRIDGE":
clazz = SerialServerSocketBridgeConfig.class;
break;
default:
throw new ServerErrorException(new TranslatableMessage("rest.missingModelMapping", VirtualSerialPortConfig.class.getSimpleName(), typeName));
}
VirtualSerialPortConfig model = (VirtualSerialPortConfig) mapper.treeToValue(tree, clazz);
return model;
}
Aggregations