Search in sources :

Example 1 with GenericRestException

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);
    }
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) DataValue(com.serotonin.m2m2.rt.dataImage.types.DataValue) URI(java.net.URI) AnnotatedPointValueTime(com.serotonin.m2m2.rt.dataImage.AnnotatedPointValueTime) PointValueTime(com.serotonin.m2m2.rt.dataImage.PointValueTime) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) DataPointVO(com.serotonin.m2m2.vo.DataPointVO) BinaryValue(com.serotonin.m2m2.rt.dataImage.types.BinaryValue) SetPointSource(com.serotonin.m2m2.rt.dataImage.SetPointSource) BadRequestException(com.infiniteautomation.mango.rest.latest.exception.BadRequestException) GenericRestException(com.infiniteautomation.mango.rest.latest.exception.GenericRestException) NotFoundRestException(com.infiniteautomation.mango.rest.latest.exception.NotFoundRestException) NotFoundException(com.infiniteautomation.mango.util.exception.NotFoundException) ServerErrorException(com.infiniteautomation.mango.rest.latest.exception.ServerErrorException) RTException(com.serotonin.m2m2.rt.RTException) AbstractRestException(com.infiniteautomation.mango.rest.latest.exception.AbstractRestException) PermissionException(com.serotonin.m2m2.vo.permission.PermissionException) MultistateValue(com.serotonin.m2m2.rt.dataImage.types.MultistateValue) RTException(com.serotonin.m2m2.rt.RTException) ResponseEntity(org.springframework.http.ResponseEntity) AlphanumericValue(com.serotonin.m2m2.rt.dataImage.types.AlphanumericValue) AnnotatedPointValueTime(com.serotonin.m2m2.rt.dataImage.AnnotatedPointValueTime) ServerErrorException(com.infiniteautomation.mango.rest.latest.exception.ServerErrorException) NumericValue(com.serotonin.m2m2.rt.dataImage.types.NumericValue) GenericRestException(com.infiniteautomation.mango.rest.latest.exception.GenericRestException) ApiOperation(io.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 2 with GenericRestException

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);
            }
        });
    }
}
Also used : JsonException(com.serotonin.json.JsonException) IOException(java.io.IOException) GenericRestException(com.infiniteautomation.mango.rest.latest.exception.GenericRestException)

Example 3 with GenericRestException

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);
    }
}
Also used : MangoStoreClient(com.infiniteautomation.mango.rest.latest.util.MangoStoreClient) ResponseEntity(org.springframework.http.ResponseEntity) JsonString(com.serotonin.json.type.JsonString) ICoreLicense(com.serotonin.m2m2.ICoreLicense) JsonException(com.serotonin.json.JsonException) FeatureDisabledException(com.infiniteautomation.mango.util.exception.FeatureDisabledException) HttpException(org.apache.http.HttpException) SocketTimeoutException(java.net.SocketTimeoutException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) BadRequestException(com.infiniteautomation.mango.rest.latest.exception.BadRequestException) GenericRestException(com.infiniteautomation.mango.rest.latest.exception.GenericRestException) FileNotFoundException(java.io.FileNotFoundException) ModuleRestException(com.infiniteautomation.mango.rest.latest.exception.ModuleRestException) NotFoundException(com.infiniteautomation.mango.util.exception.NotFoundException) ServerErrorException(com.infiniteautomation.mango.rest.latest.exception.ServerErrorException) ValidationFailedRestException(com.infiniteautomation.mango.rest.latest.exception.ValidationFailedRestException) GenericRestException(com.infiniteautomation.mango.rest.latest.exception.GenericRestException) ApiOperation(io.swagger.annotations.ApiOperation) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 4 with GenericRestException

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"));
    }
}
Also used : JsonObject(com.serotonin.json.type.JsonObject) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) URI(java.net.URI) GenericRestException(com.infiniteautomation.mango.rest.latest.exception.GenericRestException) ApiOperation(io.swagger.annotations.ApiOperation) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 5 with GenericRestException

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);
            }
        });
    }
}
Also used : IOException(java.io.IOException) GenericRestException(com.infiniteautomation.mango.rest.latest.exception.GenericRestException)

Aggregations

GenericRestException (com.infiniteautomation.mango.rest.latest.exception.GenericRestException)5 ApiOperation (io.swagger.annotations.ApiOperation)3 IOException (java.io.IOException)3 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)3 BadRequestException (com.infiniteautomation.mango.rest.latest.exception.BadRequestException)2 ServerErrorException (com.infiniteautomation.mango.rest.latest.exception.ServerErrorException)2 NotFoundException (com.infiniteautomation.mango.util.exception.NotFoundException)2 JsonException (com.serotonin.json.JsonException)2 TranslatableMessage (com.serotonin.m2m2.i18n.TranslatableMessage)2 URI (java.net.URI)2 ResponseEntity (org.springframework.http.ResponseEntity)2 PreAuthorize (org.springframework.security.access.prepost.PreAuthorize)2 AbstractRestException (com.infiniteautomation.mango.rest.latest.exception.AbstractRestException)1 ModuleRestException (com.infiniteautomation.mango.rest.latest.exception.ModuleRestException)1 NotFoundRestException (com.infiniteautomation.mango.rest.latest.exception.NotFoundRestException)1 ValidationFailedRestException (com.infiniteautomation.mango.rest.latest.exception.ValidationFailedRestException)1 MangoStoreClient (com.infiniteautomation.mango.rest.latest.util.MangoStoreClient)1 FeatureDisabledException (com.infiniteautomation.mango.util.exception.FeatureDisabledException)1 JsonObject (com.serotonin.json.type.JsonObject)1 JsonString (com.serotonin.json.type.JsonString)1