use of com.infiniteautomation.mango.rest.latest.exception.GenericRestException 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.GenericRestException in project ma-modules-public by infiniteautomation.
the class StreamedSeroJsonBasicVORqlQuery method writeArrayValues.
@Override
public void writeArrayValues(JsonWriter writer) throws IOException {
if (filter != null) {
// Using memory filter
Integer offset = conditions.getOffset();
Integer limit = conditions.getLimit();
service.customizedQuery(conditions.withNullLimitOffset(), (T item) -> {
if (filter.test(item)) {
if ((offset == null || count >= offset) && (limit == null || offsetCount < limit)) {
try {
if (count > 0)
writer.append(',');
writer.indent();
writer.writeObject(item);
} catch (IOException | JsonException e) {
// the exception if we don't cancel it.
throw new GenericRestException(HttpStatus.INTERNAL_SERVER_ERROR, e);
}
offsetCount++;
}
count++;
}
});
} else {
// No filter just run query
service.customizedQuery(conditions, (T item) -> {
try {
if (count > 0)
writer.append(',');
writer.indent();
writer.writeObject(item);
count++;
} catch (IOException | JsonException e) {
// the exception if we don't cancel it.
throw new GenericRestException(HttpStatus.INTERNAL_SERVER_ERROR, e);
}
});
}
}
use of com.infiniteautomation.mango.rest.latest.exception.GenericRestException in project ma-modules-public by infiniteautomation.
the class ModulesRestController method downloadLicense.
@PreAuthorize("isAdmin()")
@ApiOperation(value = "Download your license from the store", notes = "Admin Only")
@RequestMapping(method = RequestMethod.PUT, value = "/download-license")
public ResponseEntity<Void> downloadLicense(@ApiParam(value = "Connection retries", required = false, defaultValue = "0", allowMultiple = false) @RequestParam(required = false, defaultValue = "0") int retries, @ApiParam(value = "User Credentials", required = true) @RequestBody(required = true) CredentialsModel model, HttpServletRequest request) {
try {
String storeUrl = Common.envProps.getString("store.url");
// Login to the store
MangoStoreClient client = new MangoStoreClient(storeUrl);
client.login(model.getUsername(), model.getPassword(), retries);
// Send the token request
String guid = Providers.get(ICoreLicense.class).getGuid();
String distributor = Common.envProps.getString("distributor");
String token = client.getLicenseToken(guid, distributor, retries);
// With the token we can make the request to download the file
String license = client.getLicense(token, retries);
saveLicense(license);
return new ResponseEntity<Void>(HttpStatus.OK);
} catch (Exception e) {
throw new GenericRestException(HttpStatus.INTERNAL_SERVER_ERROR, e);
}
}
use of com.infiniteautomation.mango.rest.latest.exception.GenericRestException in project ma-modules-public by infiniteautomation.
the class JsonEmportController method importConfiguration.
@PreAuthorize("isAdmin()")
@ApiOperation(value = "Import Configuration", notes = "Submit the request and get a URL for the results")
@RequestMapping(method = { RequestMethod.POST })
public ResponseEntity<ImportStatusProvider> importConfiguration(HttpServletRequest request, UriComponentsBuilder builder, @ApiParam(value = "Optional timeout for resource to expire, defaults to 5 minutes", required = false, allowMultiple = false) @RequestParam(value = "timeout", required = false) Long timeout, @RequestBody(required = true) JsonValue config, @AuthenticationPrincipal PermissionHolder user) {
if (config instanceof JsonObject) {
// Setup the Temporary Resource
String resourceId = importStatusResources.generateResourceId();
ImportStatusProvider statusProvider = new ImportStatusProvider(importStatusResources, resourceId, websocket, timeout, user, config.toJsonObject());
this.importStatusResources.put(resourceId, statusProvider);
URI location = builder.path("/json-emport/import/{id}").buildAndExpand(resourceId).toUri();
return getResourceCreated(statusProvider, location);
} else {
throw new GenericRestException(HttpStatus.NOT_ACCEPTABLE, new TranslatableMessage("emport.invalidImportData"));
}
}
use of com.infiniteautomation.mango.rest.latest.exception.GenericRestException in project ma-modules-public by infiniteautomation.
the class StreamedBasicVORqlQuery method writeArrayValues.
@Override
public void writeArrayValues(JsonGenerator jgen) throws IOException {
if (filter != null) {
// Using memory filter
Integer offset = conditions.getOffset();
Integer limit = conditions.getLimit();
service.customizedQuery(conditions.withNullLimitOffset(), (T item) -> {
if (filter.test(item)) {
if ((offset == null || count >= offset) && (limit == null || offsetCount < limit)) {
try {
jgen.writeObject(item);
} catch (IOException e) {
// the exception if we don't cancel it.
throw new GenericRestException(HttpStatus.INTERNAL_SERVER_ERROR, e);
}
offsetCount++;
}
count++;
}
});
} else {
// No filter just run query
service.customizedQuery(conditions, (T item) -> {
try {
jgen.writeObject(item);
} catch (IOException e) {
// the exception if we don't cancel it.
throw new GenericRestException(HttpStatus.INTERNAL_SERVER_ERROR, e);
}
});
}
}
Aggregations