Search in sources :

Example 41 with TranslatableMessage

use of com.serotonin.m2m2.i18n.TranslatableMessage in project ma-modules-public by infiniteautomation.

the class DataPointRestController method bulkDataPointOperation.

@ApiOperation(value = "Bulk get/create/update/delete data points", notes = "User must have read/edit permission for the data point")
@RequestMapping(method = RequestMethod.POST, value = "/bulk")
public ResponseEntity<TemporaryResource<DataPointBulkResponse, AbstractRestV2Exception>> bulkDataPointOperation(@RequestBody DataPointBulkRequest requestBody, @AuthenticationPrincipal User user, UriComponentsBuilder builder) {
    VoAction defaultAction = requestBody.getAction();
    DataPointModel defaultBody = requestBody.getBody();
    List<DataPointIndividualRequest> requests = requestBody.getRequests();
    if (requests == null) {
        throw new BadRequestException(new TranslatableMessage("rest.error.mustNotBeNull", "requests"));
    }
    String resourceId = requestBody.getId();
    Long expiration = requestBody.getExpiration();
    Long timeout = requestBody.getTimeout();
    TemporaryResource<DataPointBulkResponse, AbstractRestV2Exception> responseBody = bulkResourceManager.newTemporaryResource(RESOURCE_TYPE_BULK_DATA_POINT, resourceId, user.getId(), expiration, timeout, (resource) -> {
        DataPointBulkResponse bulkResponse = new DataPointBulkResponse();
        int i = 0;
        resource.progress(bulkResponse, i++, requests.size());
        for (DataPointIndividualRequest request : requests) {
            UriComponentsBuilder reqBuilder = UriComponentsBuilder.newInstance();
            DataPointIndividualResponse individualResponse = doIndividualRequest(request, defaultAction, defaultBody, user, reqBuilder);
            bulkResponse.addResponse(individualResponse);
            resource.progressOrSuccess(bulkResponse, i++, requests.size());
        }
    });
    HttpHeaders headers = new HttpHeaders();
    headers.setLocation(builder.path("/v2/data-points/bulk/{id}").buildAndExpand(responseBody.getId()).toUri());
    return new ResponseEntity<TemporaryResource<DataPointBulkResponse, AbstractRestV2Exception>>(responseBody, headers, HttpStatus.CREATED);
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) VoAction(com.infiniteautomation.mango.rest.v2.bulk.VoAction) DataPointModel(com.infiniteautomation.mango.rest.v2.model.dataPoint.DataPointModel) AbstractRestV2Exception(com.infiniteautomation.mango.rest.v2.exception.AbstractRestV2Exception) ResponseEntity(org.springframework.http.ResponseEntity) UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) BadRequestException(com.infiniteautomation.mango.rest.v2.exception.BadRequestException) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 42 with TranslatableMessage

use of com.serotonin.m2m2.i18n.TranslatableMessage 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 43 with TranslatableMessage

use of com.serotonin.m2m2.i18n.TranslatableMessage in project ma-modules-public by infiniteautomation.

the class FileStoreRestV2Controller method createNewFolder.

@ApiOperation(value = "Create a folder or copy/move/rename an existing file or folder", notes = "Must have write access to the store")
@RequestMapping(method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, value = "/{fileStoreName}/**")
public ResponseEntity<FileModel> createNewFolder(@ApiParam(value = "Valid File Store name", required = true, allowMultiple = false) @PathVariable("fileStoreName") String fileStoreName, @ApiParam(value = "Move file/folder to", required = false, allowMultiple = false) @RequestParam(required = false) String moveTo, @ApiParam(value = "Copy file/folder to", required = false, allowMultiple = false) @RequestParam(required = false) String copyTo, @AuthenticationPrincipal User user, HttpServletRequest request) throws IOException, URISyntaxException {
    FileStoreDefinition def = ModuleRegistry.getFileStoreDefinition(fileStoreName);
    if (def == null)
        throw new NotFoundRestException();
    // Check Permissions
    def.ensureStoreWritePermission(user);
    String pathInStore = parsePath(request);
    File root = def.getRoot().getCanonicalFile();
    File fileOrFolder = new File(root, pathInStore).getCanonicalFile();
    if (!fileOrFolder.toPath().startsWith(root.toPath())) {
        throw new GenericRestException(HttpStatus.FORBIDDEN, new TranslatableMessage("filestore.belowRoot", pathInStore));
    }
    if (copyTo != null) {
        return copyFileOrFolder(request, fileStoreName, root, fileOrFolder, copyTo);
    } else if (moveTo != null) {
        return moveFileOrFolder(request, fileStoreName, root, fileOrFolder, moveTo);
    } else {
        return createFolder(request, fileStoreName, root, fileOrFolder);
    }
}
Also used : NotFoundRestException(com.infiniteautomation.mango.rest.v2.exception.NotFoundRestException) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) File(java.io.File) CommonsMultipartFile(org.springframework.web.multipart.commons.CommonsMultipartFile) MultipartFile(org.springframework.web.multipart.MultipartFile) FileStoreDefinition(com.serotonin.m2m2.module.FileStoreDefinition) GenericRestException(com.infiniteautomation.mango.rest.v2.exception.GenericRestException) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 44 with TranslatableMessage

use of com.serotonin.m2m2.i18n.TranslatableMessage in project ma-modules-public by infiniteautomation.

the class FileStoreRestV2Controller method uploadWithPath.

@ApiOperation(value = "Upload a file to a store with a path", notes = "Must have write access to the store")
@RequestMapping(method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, value = "/{name}/**")
public ResponseEntity<List<FileModel>> uploadWithPath(@ApiParam(value = "Valid File Store name", required = true, allowMultiple = false) @PathVariable("name") String name, @AuthenticationPrincipal User user, @RequestParam(required = false, defaultValue = "false") boolean overwrite, MultipartHttpServletRequest multipartRequest, HttpServletRequest request) throws IOException {
    FileStoreDefinition def = ModuleRegistry.getFileStoreDefinition(name);
    if (def == null)
        throw new NotFoundRestException();
    // Check Permissions
    def.ensureStoreWritePermission(user);
    String pathInStore = parsePath(request);
    File root = def.getRoot().getCanonicalFile();
    Path rootPath = root.toPath();
    File outputDirectory = new File(root, pathInStore).getCanonicalFile();
    if (!outputDirectory.toPath().startsWith(rootPath)) {
        throw new GenericRestException(HttpStatus.FORBIDDEN, new TranslatableMessage("filestore.belowRoot", pathInStore));
    }
    if (outputDirectory.exists() && !outputDirectory.isDirectory()) {
        throw new GenericRestException(HttpStatus.INTERNAL_SERVER_ERROR, new TranslatableMessage("filestore.cannotCreateDir", removeToRoot(root, outputDirectory), name));
    }
    if (!outputDirectory.exists()) {
        if (!outputDirectory.mkdirs())
            throw new GenericRestException(HttpStatus.INTERNAL_SERVER_ERROR, new TranslatableMessage("filestore.cannotCreateDir", removeToRoot(root, outputDirectory), name));
    }
    // Put the file where it belongs
    List<FileModel> fileModels = new ArrayList<>();
    MultiValueMap<String, MultipartFile> filemap = multipartRequest.getMultiFileMap();
    for (String nameField : filemap.keySet()) {
        for (MultipartFile file : filemap.get(nameField)) {
            String filename;
            if (file instanceof CommonsMultipartFile) {
                FileItem fileItem = ((CommonsMultipartFile) file).getFileItem();
                filename = fileItem.getName();
            } else {
                filename = file.getName();
            }
            File newFile = findUniqueFileName(outputDirectory, filename, overwrite);
            File parent = newFile.getParentFile();
            if (!parent.exists()) {
                parent.mkdirs();
            }
            try (OutputStream output = new FileOutputStream(newFile, false)) {
                try (InputStream input = file.getInputStream()) {
                    StreamUtils.copy(input, output);
                }
            }
            fileModels.add(fileToModel(newFile, root, request.getServletContext()));
        }
    }
    return new ResponseEntity<>(fileModels, HttpStatus.OK);
}
Also used : Path(java.nio.file.Path) NotFoundRestException(com.infiniteautomation.mango.rest.v2.exception.NotFoundRestException) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) ArrayList(java.util.ArrayList) CommonsMultipartFile(org.springframework.web.multipart.commons.CommonsMultipartFile) FileModel(com.infiniteautomation.mango.rest.v2.model.filestore.FileModel) FileItem(org.apache.commons.fileupload.FileItem) CommonsMultipartFile(org.springframework.web.multipart.commons.CommonsMultipartFile) MultipartFile(org.springframework.web.multipart.MultipartFile) ResponseEntity(org.springframework.http.ResponseEntity) FileOutputStream(java.io.FileOutputStream) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) File(java.io.File) CommonsMultipartFile(org.springframework.web.multipart.commons.CommonsMultipartFile) MultipartFile(org.springframework.web.multipart.MultipartFile) FileStoreDefinition(com.serotonin.m2m2.module.FileStoreDefinition) GenericRestException(com.infiniteautomation.mango.rest.v2.exception.GenericRestException) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 45 with TranslatableMessage

use of com.serotonin.m2m2.i18n.TranslatableMessage in project ma-modules-public by infiniteautomation.

the class FileStoreRestV2Controller method moveFileOrFolder.

private ResponseEntity<FileModel> moveFileOrFolder(HttpServletRequest request, String fileStoreName, File root, File fileOrFolder, String moveTo) throws IOException, URISyntaxException {
    if (!fileOrFolder.exists()) {
        throw new NotFoundRestException();
    }
    Path srcPath = fileOrFolder.toPath();
    File dstFile = new File(fileOrFolder.getParentFile(), moveTo).getCanonicalFile();
    Path dstPath = dstFile.toPath();
    if (!dstPath.startsWith(root.toPath())) {
        throw new GenericRestException(HttpStatus.FORBIDDEN, new TranslatableMessage("filestore.belowRoot", moveTo));
    }
    if (dstFile.isDirectory()) {
        dstPath = dstPath.resolve(srcPath.getFileName());
    }
    Path movedPath;
    try {
        movedPath = java.nio.file.Files.move(srcPath, dstPath);
    } catch (FileAlreadyExistsException e) {
        throw new GenericRestException(HttpStatus.CONFLICT, new TranslatableMessage("filestore.fileExists", dstPath.getFileName()));
    }
    File movedFile = new File(movedPath.toUri());
    FileModel fileModel = fileToModel(movedFile, root, request.getServletContext());
    return new ResponseEntity<>(fileModel, HttpStatus.OK);
}
Also used : Path(java.nio.file.Path) FileModel(com.infiniteautomation.mango.rest.v2.model.filestore.FileModel) NotFoundRestException(com.infiniteautomation.mango.rest.v2.exception.NotFoundRestException) FileAlreadyExistsException(java.nio.file.FileAlreadyExistsException) ResponseEntity(org.springframework.http.ResponseEntity) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) File(java.io.File) CommonsMultipartFile(org.springframework.web.multipart.commons.CommonsMultipartFile) MultipartFile(org.springframework.web.multipart.MultipartFile) GenericRestException(com.infiniteautomation.mango.rest.v2.exception.GenericRestException)

Aggregations

TranslatableMessage (com.serotonin.m2m2.i18n.TranslatableMessage)180 User (com.serotonin.m2m2.vo.User)53 ApiOperation (com.wordnik.swagger.annotations.ApiOperation)52 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)52 DataPointVO (com.serotonin.m2m2.vo.DataPointVO)33 RestProcessResult (com.serotonin.m2m2.web.mvc.rest.v1.message.RestProcessResult)33 IOException (java.io.IOException)28 HashMap (java.util.HashMap)27 DwrPermission (com.serotonin.m2m2.web.dwr.util.DwrPermission)24 ProcessResult (com.serotonin.m2m2.i18n.ProcessResult)22 ArrayList (java.util.ArrayList)22 DataPointRT (com.serotonin.m2m2.rt.dataImage.DataPointRT)20 PointValueTime (com.serotonin.m2m2.rt.dataImage.PointValueTime)20 ShouldNeverHappenException (com.serotonin.ShouldNeverHappenException)19 BadRequestException (com.infiniteautomation.mango.rest.v2.exception.BadRequestException)18 NotFoundRestException (com.infiniteautomation.mango.rest.v2.exception.NotFoundRestException)17 File (java.io.File)16 URI (java.net.URI)16 PermissionException (com.serotonin.m2m2.vo.permission.PermissionException)12 ResponseEntity (org.springframework.http.ResponseEntity)11