Search in sources :

Example 81 with UriComponentsBuilder

use of org.springframework.web.util.UriComponentsBuilder in project connectors-workspace-one by vmware.

the class SalesforceControllerTest method testAddContact.

@Test
void testAddContact() throws Exception {
    UriComponentsBuilder addContactReqBuilder = fromHttpUrl(SERVER_URL).path(ADD_CONTACT_PATH);
    UriComponentsBuilder addOppToContactReqBuilder = fromHttpUrl(SERVER_URL).path(LINK_OPPORTUNITY_PATH);
    mockSF.expect(requestTo(addContactReqBuilder.build().toUri())).andExpect(method(HttpMethod.POST)).andExpect(MockRestRequestMatchers.header(HttpHeaders.AUTHORIZATION, "Bearer abc")).andRespond(withSuccess(sfResponseContactCreated, APPLICATION_JSON));
    mockSF.expect(requestTo(addOppToContactReqBuilder.build().toUri())).andExpect(method(HttpMethod.POST)).andExpect(MockRestRequestMatchers.header(HttpHeaders.AUTHORIZATION, "Bearer abc")).andRespond(withSuccess());
    perform(requestAddContact("abc", TRAVIS_ACCOUNT_ID, "/salesforce/request/contact.txt")).andExpect(status().isOk());
    mockSF.verify();
}
Also used : UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 82 with UriComponentsBuilder

use of org.springframework.web.util.UriComponentsBuilder in project ma-modules-public by infiniteautomation.

the class PointValueRestController method firstAndLastPointValues.

@ApiOperation(value = "First and last point values", notes = "Retrieves the first and last point values within a time range, used to read accumulators")
@RequestMapping(method = RequestMethod.GET, value = "/{xid}/first-last", produces = { "application/json", "text/csv" })
public ResponseEntity<List<PointValueTimeModel>> firstAndLastPointValues(HttpServletRequest request, @ApiParam(value = "Point xid", required = true, allowMultiple = false) @PathVariable String xid, @ApiParam(value = "Return rendered value as String", required = false, defaultValue = "false", allowMultiple = false) @RequestParam(required = false, defaultValue = "false") boolean useRendered, @ApiParam(value = "Return converted value using displayed unit", required = false, defaultValue = "false", allowMultiple = false) @RequestParam(required = false, defaultValue = "false") boolean unitConversion, @ApiParam(value = "From time", required = false, allowMultiple = false) @RequestParam(value = "from", required = false) @DateTimeFormat(iso = ISO.DATE_TIME) DateTime from, @ApiParam(value = "To time", required = false, allowMultiple = false) @RequestParam(value = "to", required = false) @DateTimeFormat(iso = ISO.DATE_TIME) DateTime to, @ApiParam(value = "Time zone of output, used if formatted times are returned", required = false, allowMultiple = false) @RequestParam(value = "timezone", required = false) String timezone) {
    RestProcessResult<List<PointValueTimeModel>> result = new RestProcessResult<List<PointValueTimeModel>>(HttpStatus.OK);
    User user = this.checkUser(request, result);
    if (result.isOk()) {
        if (timezone != null) {
            try {
                ZoneId.of(timezone);
            } catch (Exception e) {
                RestValidationResult vr = new RestValidationResult();
                vr.addError("validate.invalidValue", "timezone");
                throw new ValidationFailedRestException(vr);
            }
        }
        DataPointVO vo = DataPointDao.instance.getByXid(xid);
        if (vo == null) {
            result.addRestMessage(getDoesNotExistMessage());
            return result.createResponseEntity();
        }
        try {
            if (Permissions.hasDataPointReadPermission(user, vo)) {
                long current = Common.timer.currentTimeMillis();
                if (from == null)
                    from = new DateTime(current);
                if (to == null)
                    to = new DateTime(current);
                // better not to for RESTfulness
                if (timezone != null) {
                    DateTimeZone zone = DateTimeZone.forID(timezone);
                    from = from.withZone(zone);
                    to = to.withZone(zone);
                }
                PointValueFacade pointValueFacade = new PointValueFacade(vo.getId(), false);
                PointValueTime first = pointValueFacade.getPointValueAfter(from.getMillis());
                PointValueTime last = pointValueFacade.getPointValueBefore(to.getMillis());
                List<PointValueTimeModel> models = new ArrayList<PointValueTimeModel>(2);
                if (useRendered) {
                    if (first != null) {
                        PointValueTimeModel model = new PointValueTimeModel();
                        model.setType(DataTypeEnum.convertTo(first.getValue().getDataType()));
                        model.setValue(Functions.getRenderedText(vo, first));
                        model.setTimestamp(first.getTime());
                        if (first.isAnnotated())
                            model.setAnnotation(((AnnotatedPointValueTime) first).getAnnotation(Common.getTranslations()));
                        models.add(model);
                    }
                    if (last != null) {
                        PointValueTimeModel model = new PointValueTimeModel();
                        model.setType(DataTypeEnum.convertTo(last.getValue().getDataType()));
                        model.setValue(Functions.getRenderedText(vo, last));
                        model.setTimestamp(last.getTime());
                        if (last.isAnnotated())
                            model.setAnnotation(((AnnotatedPointValueTime) last).getAnnotation(Common.getTranslations()));
                        models.add(model);
                    }
                } else if (unitConversion) {
                    if (first != null) {
                        PointValueTimeModel model = new PointValueTimeModel();
                        model.setType(DataTypeEnum.convertTo(first.getValue().getDataType()));
                        model.setValue(vo.getUnit().getConverterTo(vo.getRenderedUnit()).convert(first.getValue().getDoubleValue()));
                        model.setTimestamp(first.getTime());
                        if (first.isAnnotated())
                            model.setAnnotation(((AnnotatedPointValueTime) first).getAnnotation(Common.getTranslations()));
                        models.add(model);
                    }
                    if (last != null) {
                        PointValueTimeModel model = new PointValueTimeModel();
                        model.setType(DataTypeEnum.convertTo(last.getValue().getDataType()));
                        model.setValue(vo.getUnit().getConverterTo(vo.getRenderedUnit()).convert(last.getValue().getDoubleValue()));
                        model.setTimestamp(last.getTime());
                        if (last.isAnnotated())
                            model.setAnnotation(((AnnotatedPointValueTime) last).getAnnotation(Common.getTranslations()));
                        models.add(model);
                    }
                } else {
                    models.add(first == null ? null : new PointValueTimeModel(first));
                    models.add(last == null ? null : new PointValueTimeModel(last));
                }
                if (vo.getPointLocator().getDataTypeId() == DataTypes.IMAGE) {
                    // If we are an image type we should build the URLS
                    UriComponentsBuilder imageServletBuilder = UriComponentsBuilder.fromPath("/imageValue/hst{ts}_{id}.jpg");
                    for (PointValueTimeModel model : models) {
                        model.setValue(imageServletBuilder.buildAndExpand(model.getTimestamp(), vo.getId()).toUri());
                    }
                }
                return result.createResponseEntity(models);
            } else {
                result.addRestMessage(getUnauthorizedMessage());
                return result.createResponseEntity();
            }
        } catch (PermissionException e) {
            LOG.error(e.getMessage(), e);
            result.addRestMessage(getUnauthorizedMessage());
            return result.createResponseEntity();
        }
    } else {
        return result.createResponseEntity();
    }
}
Also used : RestValidationResult(com.infiniteautomation.mango.rest.v2.model.RestValidationResult) DataPointVO(com.serotonin.m2m2.vo.DataPointVO) PermissionException(com.serotonin.m2m2.vo.permission.PermissionException) PointValueFacade(com.serotonin.m2m2.rt.dataImage.PointValueFacade) User(com.serotonin.m2m2.vo.User) XidPointValueTimeModel(com.serotonin.m2m2.web.mvc.rest.v1.model.pointValue.XidPointValueTimeModel) RecentPointValueTimeModel(com.serotonin.m2m2.web.mvc.rest.v1.model.pointValue.RecentPointValueTimeModel) PointValueTimeModel(com.serotonin.m2m2.web.mvc.rest.v1.model.pointValue.PointValueTimeModel) ValidationFailedRestException(com.infiniteautomation.mango.rest.v2.exception.ValidationFailedRestException) ArrayList(java.util.ArrayList) RestValidationFailedException(com.serotonin.m2m2.web.mvc.rest.v1.exception.RestValidationFailedException) ValidationFailedRestException(com.infiniteautomation.mango.rest.v2.exception.ValidationFailedRestException) RTException(com.serotonin.m2m2.rt.RTException) NotFoundRestException(com.infiniteautomation.mango.rest.v2.exception.NotFoundRestException) PermissionException(com.serotonin.m2m2.vo.permission.PermissionException) DateTime(org.joda.time.DateTime) DateTimeZone(org.joda.time.DateTimeZone) RestProcessResult(com.serotonin.m2m2.web.mvc.rest.v1.message.RestProcessResult) UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) ServletUriComponentsBuilder(org.springframework.web.servlet.support.ServletUriComponentsBuilder) AnnotatedPointValueTime(com.serotonin.m2m2.rt.dataImage.AnnotatedPointValueTime) PointValueTime(com.serotonin.m2m2.rt.dataImage.PointValueTime) AnnotatedPointValueTime(com.serotonin.m2m2.rt.dataImage.AnnotatedPointValueTime) List(java.util.List) ArrayList(java.util.ArrayList) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 83 with UriComponentsBuilder

use of org.springframework.web.util.UriComponentsBuilder in project ma-modules-public by infiniteautomation.

the class PointValueRestController method getLatestPointValues.

/**
 * Get the latest point values for a point
 *
 * @param xid
 * @param limit
 * @return
 */
@ApiOperation(value = "Get Latest Point Values Directly from the Runtime Manager, this makes Cached and Intra-Interval data available.", notes = "Default limit 100, time descending order, Default to return cached data. For the most efficient use of this endpoint " + " the data point's default cache size should be the size that you will typically query the latest values of.")
@RequestMapping(method = RequestMethod.GET, value = "/{xid}/latest", produces = { "application/json", "text/csv" })
public ResponseEntity<List<RecentPointValueTimeModel>> getLatestPointValues(HttpServletRequest request, @ApiParam(value = "Point xid", required = true, allowMultiple = false) @PathVariable String xid, @ApiParam(value = "Return rendered value as String", required = false, defaultValue = "false", allowMultiple = false) @RequestParam(required = false, defaultValue = "false") boolean useRendered, @ApiParam(value = "Return converted value using displayed unit", required = false, defaultValue = "false", allowMultiple = false) @RequestParam(required = false, defaultValue = "false") boolean unitConversion, @ApiParam(value = "Limit results", allowMultiple = false, defaultValue = "100") @RequestParam(value = "limit", defaultValue = "100") int limit, @ApiParam(value = "Return cached data?", allowMultiple = false, defaultValue = "true") @RequestParam(value = "useCache", defaultValue = "true") boolean useCache) {
    RestProcessResult<List<RecentPointValueTimeModel>> result = new RestProcessResult<List<RecentPointValueTimeModel>>(HttpStatus.OK);
    User user = this.checkUser(request, result);
    if (result.isOk()) {
        DataPointVO vo = DataPointDao.instance.getByXid(xid);
        if (vo == null) {
            result.addRestMessage(getDoesNotExistMessage());
            return result.createResponseEntity();
        }
        try {
            if (Permissions.hasDataPointReadPermission(user, vo)) {
                // Check to see if we can convert (Must be a Numeric Value)
                if (unitConversion && (vo.getPointLocator().getDataTypeId() != DataTypes.NUMERIC)) {
                    result.addRestMessage(HttpStatus.NOT_ACCEPTABLE, new TranslatableMessage("common.default", "Can't convert non-numeric types."));
                    return result.createResponseEntity();
                }
                // If we are an image type we should build the URLS
                UriComponentsBuilder imageServletBuilder = UriComponentsBuilder.fromPath("/imageValue/hst{ts}_{id}.jpg");
                List<RecentPointValueTimeModel> models;
                if (useCache) {
                    // In an effort not to expand the PointValueCache we avoid the
                    // PointValueFacade
                    DataPointRT rt = Common.runtimeManager.getDataPoint(vo.getId());
                    if (rt != null) {
                        List<PointValueTime> cache = rt.getCacheCopy();
                        if (limit < cache.size()) {
                            List<PointValueTime> pvts = cache.subList(0, limit);
                            models = new ArrayList<>(limit);
                            for (PointValueTime pvt : pvts) models.add(createRecentPointValueTimeModel(vo, pvt, imageServletBuilder, useRendered, unitConversion, true));
                        } else {
                            // We need to merge 2 lists
                            List<PointValueTime> disk = Common.databaseProxy.newPointValueDao().getLatestPointValues(vo.getId(), limit);
                            Set<RecentPointValueTimeModel> all = new HashSet<RecentPointValueTimeModel>(limit);
                            for (PointValueTime pvt : cache) all.add(createRecentPointValueTimeModel(vo, pvt, imageServletBuilder, useRendered, unitConversion, true));
                            for (PointValueTime pvt : disk) {
                                if (all.size() >= limit)
                                    break;
                                else
                                    all.add(createRecentPointValueTimeModel(vo, pvt, imageServletBuilder, useRendered, unitConversion, false));
                            }
                            models = new ArrayList<>(all);
                            // Override the comparison method
                            Collections.sort(models, new Comparator<RecentPointValueTimeModel>() {

                                // Compare such that data sets are returned in time
                                // descending order
                                // which turns out is opposite of compare to method for
                                // PointValueTime objects
                                @Override
                                public int compare(RecentPointValueTimeModel o1, RecentPointValueTimeModel o2) {
                                    if (o1.getTimestamp() < o2.getTimestamp())
                                        return 1;
                                    if (o1.getTimestamp() > o2.getTimestamp())
                                        return -1;
                                    return 0;
                                }
                            });
                        }
                    } else {
                        List<PointValueTime> pvts = Common.databaseProxy.newPointValueDao().getLatestPointValues(vo.getId(), limit);
                        models = new ArrayList<>(limit);
                        for (PointValueTime pvt : pvts) models.add(createRecentPointValueTimeModel(vo, pvt, imageServletBuilder, useRendered, unitConversion, false));
                    }
                } else {
                    models = new ArrayList<>(limit);
                    List<PointValueTime> pvts = Common.databaseProxy.newPointValueDao().getLatestPointValues(vo.getId(), limit);
                    for (PointValueTime pvt : pvts) models.add(createRecentPointValueTimeModel(vo, pvt, imageServletBuilder, useRendered, unitConversion, false));
                }
                return result.createResponseEntity(models);
            } else {
                result.addRestMessage(getUnauthorizedMessage());
                return result.createResponseEntity();
            }
        } catch (PermissionException e) {
            LOG.error(e.getMessage(), e);
            result.addRestMessage(getUnauthorizedMessage());
            return result.createResponseEntity();
        }
    } else {
        return result.createResponseEntity();
    }
}
Also used : DataPointVO(com.serotonin.m2m2.vo.DataPointVO) PermissionException(com.serotonin.m2m2.vo.permission.PermissionException) User(com.serotonin.m2m2.vo.User) RestProcessResult(com.serotonin.m2m2.web.mvc.rest.v1.message.RestProcessResult) RecentPointValueTimeModel(com.serotonin.m2m2.web.mvc.rest.v1.model.pointValue.RecentPointValueTimeModel) UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) ServletUriComponentsBuilder(org.springframework.web.servlet.support.ServletUriComponentsBuilder) DataPointRT(com.serotonin.m2m2.rt.dataImage.DataPointRT) AnnotatedPointValueTime(com.serotonin.m2m2.rt.dataImage.AnnotatedPointValueTime) PointValueTime(com.serotonin.m2m2.rt.dataImage.PointValueTime) List(java.util.List) ArrayList(java.util.ArrayList) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) HashSet(java.util.HashSet) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 84 with UriComponentsBuilder

use of org.springframework.web.util.UriComponentsBuilder in project ma-modules-public by infiniteautomation.

the class RealTimeDataRestController method query.

/**
 * Query the User's Real Time Data
 * @param request
 * @param limit
 * @return
 */
@ApiOperation(value = "Query realtime values", notes = "Check the status member to ensure the point is OK not DISABLED or UNRELIABLE")
@RequestMapping(method = RequestMethod.GET, produces = { "application/json" })
public ResponseEntity<List<RealTimeModel>> query(HttpServletRequest request) {
    RestProcessResult<List<RealTimeModel>> result = new RestProcessResult<List<RealTimeModel>>(HttpStatus.OK);
    User user = this.checkUser(request, result);
    if (result.isOk()) {
        ASTNode model;
        try {
            model = parseRQLtoAST(request.getQueryString());
            if (model == null) {
                result.addRestMessage(new RestMessage(HttpStatus.NOT_ACCEPTABLE, new TranslatableMessage("common.default", "Query Required")));
                return result.createResponseEntity();
            }
            List<RealTimeDataPointValue> values = RealTimeDataPointValueCache.instance.getUserView(user);
            values = model.accept(new RQLToObjectListQuery<RealTimeDataPointValue>(), values);
            List<RealTimeModel> models = new ArrayList<RealTimeModel>();
            UriComponentsBuilder imageServletBuilder = UriComponentsBuilder.fromPath("/imageValue/{ts}_{id}.jpg");
            for (RealTimeDataPointValue value : values) {
                if (value.getDataTypeId() == DataTypes.IMAGE) {
                    models.add(new RealTimeModel(value, imageServletBuilder.buildAndExpand(value.getTimestamp(), value.getDataPointId()).toUri()));
                } else {
                    models.add(new RealTimeModel(value, value.getValue()));
                }
            }
            return result.createResponseEntity(models);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            result.addRestMessage(getInternalServerErrorMessage(e.getMessage()));
            return result.createResponseEntity();
        }
    }
    return result.createResponseEntity();
}
Also used : User(com.serotonin.m2m2.vo.User) RealTimeDataPointValue(com.serotonin.m2m2.rt.dataImage.RealTimeDataPointValue) ArrayList(java.util.ArrayList) RealTimeModel(com.serotonin.m2m2.web.mvc.rest.v1.model.RealTimeModel) RQLToObjectListQuery(com.infiniteautomation.mango.db.query.pojo.RQLToObjectListQuery) RestProcessResult(com.serotonin.m2m2.web.mvc.rest.v1.message.RestProcessResult) RestMessage(com.serotonin.m2m2.web.mvc.rest.v1.message.RestMessage) UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) ASTNode(net.jazdw.rql.parser.ASTNode) ArrayList(java.util.ArrayList) List(java.util.List) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 85 with UriComponentsBuilder

use of org.springframework.web.util.UriComponentsBuilder in project ma-modules-public by infiniteautomation.

the class RealTimeDataRestController method get.

@ApiOperation(value = "Get realtime value of point based on XID", notes = "Check the status member to ensure the point is OK not DISABLED or UNRELIABLE")
@RequestMapping(method = RequestMethod.GET, value = "/by-xid/{xid}", produces = { "application/json" })
public ResponseEntity<RealTimeModel> get(@PathVariable String xid, HttpServletRequest request) {
    RestProcessResult<RealTimeModel> result = new RestProcessResult<RealTimeModel>(HttpStatus.OK);
    // Check the user
    User user = checkUser(request, result);
    // If no messages then go for it
    if (result.isOk()) {
        List<RealTimeDataPointValue> values = RealTimeDataPointValueCache.instance.getUserView(user);
        ASTNode root = new ASTNode("eq", "xid", xid);
        values = root.accept(new RQLToObjectListQuery<RealTimeDataPointValue>(), values);
        if (values.size() == 0) {
            LOG.debug("Attempted access of Real time point that DNE.");
            result.addRestMessage(HttpStatus.NOT_FOUND, new TranslatableMessage("common.default", "Point doesn't exist or is not enabled."));
            return result.createResponseEntity();
        }
        RealTimeModel model;
        RealTimeDataPointValue value = values.get(0);
        if (value.getDataTypeId() != DataTypes.IMAGE)
            model = new RealTimeModel(value, value.getValue());
        else {
            UriComponentsBuilder imageServletBuilder = UriComponentsBuilder.fromPath("/imageValue/{ts}_{id}.jpg");
            model = new RealTimeModel(value, imageServletBuilder.buildAndExpand(value.getTimestamp(), value.getDataPointId()).toUri());
        }
        return result.createResponseEntity(model);
    } else {
        return result.createResponseEntity();
    }
}
Also used : RestProcessResult(com.serotonin.m2m2.web.mvc.rest.v1.message.RestProcessResult) User(com.serotonin.m2m2.vo.User) RealTimeDataPointValue(com.serotonin.m2m2.rt.dataImage.RealTimeDataPointValue) UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) ASTNode(net.jazdw.rql.parser.ASTNode) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) RealTimeModel(com.serotonin.m2m2.web.mvc.rest.v1.model.RealTimeModel) RQLToObjectListQuery(com.infiniteautomation.mango.db.query.pojo.RQLToObjectListQuery) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

UriComponentsBuilder (org.springframework.web.util.UriComponentsBuilder)131 Test (org.junit.Test)34 UriComponents (org.springframework.web.util.UriComponents)23 ServletUriComponentsBuilder (org.springframework.web.servlet.support.ServletUriComponentsBuilder)12 URI (java.net.URI)9 Test (org.junit.jupiter.api.Test)9 SearchRequest (org.nzbhydra.searching.searchrequests.SearchRequest)8 MvcUriComponentsBuilder (org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder)8 ArrayList (java.util.ArrayList)7 LinkedMultiValueMap (org.springframework.util.LinkedMultiValueMap)7 List (java.util.List)6 User (com.serotonin.m2m2.vo.User)5 RestProcessResult (com.serotonin.m2m2.web.mvc.rest.v1.message.RestProcessResult)5 ApiOperation (com.wordnik.swagger.annotations.ApiOperation)5 HashMap (java.util.HashMap)5 HttpEntity (org.springframework.http.HttpEntity)5 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)5 HttpClientErrorException (org.springframework.web.client.HttpClientErrorException)5 IOException (java.io.IOException)4 Map (java.util.Map)4