Search in sources :

Example 16 with BadRequestException

use of com.netflix.spinnaker.front50.exception.BadRequestException in project ma-modules-public by infiniteautomation.

the class DataPointTagsRestController method bulkDataPointTagOperation.

@ApiOperation(value = "Bulk get/set/add data point tags for a list of XIDs", notes = "User must have read/edit permission for the data point")
@RequestMapping(method = RequestMethod.POST, value = "/bulk")
public ResponseEntity<TemporaryResource<TagBulkResponse, AbstractRestV2Exception>> bulkDataPointTagOperation(@RequestBody TagBulkRequest requestBody, @AuthenticationPrincipal User user, UriComponentsBuilder builder) {
    BulkTagAction defaultAction = requestBody.getAction();
    Map<String, String> defaultBody = requestBody.getBody();
    List<TagIndividualRequest> 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<TagBulkResponse, AbstractRestV2Exception> responseBody = bulkResourceManager.newTemporaryResource(RESOURCE_TYPE_BULK_DATA_POINT_TAGS, resourceId, user.getId(), expiration, timeout, (resource) -> {
        TagBulkResponse bulkResponse = new TagBulkResponse();
        int i = 0;
        resource.progress(bulkResponse, i++, requests.size());
        for (TagIndividualRequest request : requests) {
            TagIndividualResponse individualResponse = doIndividualRequest(request, defaultAction, defaultBody, user);
            bulkResponse.addResponse(individualResponse);
            resource.progressOrSuccess(bulkResponse, i++, requests.size());
        }
    });
    HttpHeaders headers = new HttpHeaders();
    headers.setLocation(builder.path("/v2/data-point-tags/bulk/{id}").buildAndExpand(responseBody.getId()).toUri());
    return new ResponseEntity<TemporaryResource<TagBulkResponse, AbstractRestV2Exception>>(responseBody, headers, HttpStatus.CREATED);
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) AbstractRestV2Exception(com.infiniteautomation.mango.rest.v2.exception.AbstractRestV2Exception) ResponseEntity(org.springframework.http.ResponseEntity) 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 17 with BadRequestException

use of com.netflix.spinnaker.front50.exception.BadRequestException in project ma-modules-public by infiniteautomation.

the class ModulesRestController method uploadUpgrades.

@PreAuthorize("isAdmin()")
@ApiOperation(value = "Upload upgrade zip bundle, to be installed on restart", notes = "The bundle can be downloaded from the Mango Store")
@RequestMapping(method = RequestMethod.POST, value = "/upload-upgrades")
public void uploadUpgrades(@ApiParam(value = "Restart after upload completes", required = false, defaultValue = "false", allowMultiple = false) @RequestParam(required = false, defaultValue = "false") boolean restart, MultipartHttpServletRequest multipartRequest) throws IOException {
    synchronized (UPLOAD_UPGRADE_LOCK) {
        if (UPLOAD_UPGRADE_IN_PROGRESS == null) {
            UPLOAD_UPGRADE_IN_PROGRESS = new Object();
        } else {
            throw new BadRequestException(new TranslatableMessage("rest.error.upgradeUploadInProgress"));
        }
    }
    try {
        List<MultipartFile> files = new ArrayList<>();
        MultiValueMap<String, MultipartFile> filemap = multipartRequest.getMultiFileMap();
        for (String nameField : filemap.keySet()) {
            files.addAll(filemap.get(nameField));
        }
        // Validate the zip
        if (files.size() == 0)
            throw new BadRequestException(new TranslatableMessage("rest.error.noFileProvided"));
        // Create the temp directory into which to download, if necessary.
        File tempDir = new File(Common.MA_HOME, ModuleUtils.DOWNLOAD_DIR);
        if (!tempDir.exists())
            tempDir.mkdirs();
        // Delete anything that is currently the temp directory.
        FileUtils.cleanDirectory(tempDir);
        try {
            // Save the upload(s) to the temp dir
            for (MultipartFile file : files) {
                File newFile = new File(tempDir, file.getOriginalFilename());
                try (FileOutputStream fos = new FileOutputStream(newFile)) {
                    org.springframework.util.StreamUtils.copy(file.getInputStream(), fos);
                }
            }
            String[] potentialUpgrades = tempDir.list(new FilenameFilter() {

                public boolean accept(File dir, String name) {
                    if (name.endsWith(".zip"))
                        return true;
                    else
                        return false;
                }
            });
            boolean didUpgrade = false;
            for (String potentialUpgrade : potentialUpgrades) {
                File file = new File(tempDir, potentialUpgrade);
                boolean core = false;
                boolean hasWebModules = false;
                try (FileInputStream fis = new FileInputStream(file)) {
                    // Test to see if it is a core or a bundle of only zips or many zip files
                    try (ZipInputStream is = new ZipInputStream(fis)) {
                        ZipEntry entry = is.getNextEntry();
                        if (entry == null) {
                            // Not a zip file or empty, either way we don't care
                            throw new BadRequestException(new TranslatableMessage("rest.error.badUpgradeFile"));
                        } else {
                            do {
                                if ("release.signed".equals(entry.getName())) {
                                    core = true;
                                    break;
                                } else if (entry.getName().startsWith(WEB_MODULE_PREFIX)) {
                                    hasWebModules = true;
                                }
                            } while ((entry = is.getNextEntry()) != null);
                        }
                    }
                }
                if (core) {
                    // move file to core directory
                    Files.move(file, new File(coreDir, "m2m2-core-upgrade.zip"));
                    didUpgrade = true;
                } else if (hasWebModules) {
                    // This is a zip with modules in web/modules move them all out into the MA_HOME/web/modules dir
                    try (FileInputStream fis = new FileInputStream(file)) {
                        try (ZipInputStream is = new ZipInputStream(fis)) {
                            ZipEntry entry;
                            while ((entry = is.getNextEntry()) != null) {
                                if (entry.getName().startsWith(WEB_MODULE_PREFIX)) {
                                    File newModule = new File(coreDir, entry.getName());
                                    try (FileOutputStream fos = new FileOutputStream(newModule)) {
                                        org.springframework.util.StreamUtils.copy(is, fos);
                                    }
                                    didUpgrade = true;
                                }
                            }
                        }
                    }
                } else {
                    // if its a module move it to the modules folder
                    if (potentialUpgrade.startsWith(ModuleUtils.Constants.MODULE_PREFIX)) {
                        // Its extra work but we better check that it is a module from the store:
                        didUpgrade = maybeCopyModule(file);
                    } else {
                        // Is this a zip of modules?
                        try (FileInputStream fis = new FileInputStream(file)) {
                            try (ZipInputStream is = new ZipInputStream(fis)) {
                                ZipEntry entry;
                                while ((entry = is.getNextEntry()) != null) {
                                    if (entry.getName().startsWith(ModuleUtils.Constants.MODULE_PREFIX)) {
                                        // Extract it and confirm it is a module
                                        File newModule = new File(tempDir, entry.getName());
                                        try (FileOutputStream fos = new FileOutputStream(newModule)) {
                                            org.springframework.util.StreamUtils.copy(is, fos);
                                        }
                                        didUpgrade = maybeCopyModule(newModule);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            // Ensure we have some upgrades
            if (!didUpgrade)
                throw new BadRequestException(new TranslatableMessage("rest.error.invalidUpgradeFile"));
        } finally {
            FileUtils.deleteDirectory(tempDir);
        }
    } finally {
        // Release the lock
        synchronized (UPLOAD_UPGRADE_LOCK) {
            UPLOAD_UPGRADE_IN_PROGRESS = null;
        }
    }
    if (restart)
        ModulesDwr.scheduleRestart();
}
Also used : ZipEntry(java.util.zip.ZipEntry) ArrayList(java.util.ArrayList) JsonString(com.serotonin.json.type.JsonString) FileInputStream(java.io.FileInputStream) FilenameFilter(java.io.FilenameFilter) MultipartFile(org.springframework.web.multipart.MultipartFile) ZipInputStream(java.util.zip.ZipInputStream) FileOutputStream(java.io.FileOutputStream) BadRequestException(com.infiniteautomation.mango.rest.v2.exception.BadRequestException) JsonObject(com.serotonin.json.type.JsonObject) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) File(java.io.File) MultipartFile(org.springframework.web.multipart.MultipartFile) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 18 with BadRequestException

use of com.netflix.spinnaker.front50.exception.BadRequestException in project ma-modules-public by infiniteautomation.

the class JsonDataRestController method mergeNode.

JsonNode mergeNode(final JsonNode existingData, final String[] dataPath, final JsonNode newData) {
    JsonNode destination = getNode(existingData, dataPath);
    JsonNode mergedNode;
    if (destination.isObject()) {
        // object merge
        if (!newData.isObject()) {
            throw new BadRequestException(new TranslatableMessage("rest.error.cantMergeNodeTypeIntoObject", newData.getNodeType()));
        }
        ObjectNode destinationObject = (ObjectNode) destination;
        Iterator<Entry<String, JsonNode>> it = newData.fields();
        while (it.hasNext()) {
            Entry<String, JsonNode> entry = it.next();
            destinationObject.set(entry.getKey(), entry.getValue());
        }
        mergedNode = destinationObject;
    } else if (destination.isArray()) {
        // append operation
        ArrayNode destinationArray = (ArrayNode) destination;
        destinationArray.add(newData);
        mergedNode = destinationArray;
    } else {
        throw new BadRequestException(new TranslatableMessage("rest.error.cantMergeIntoX", destination.getNodeType()));
    }
    return mergedNode;
}
Also used : Entry(java.util.Map.Entry) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) BadRequestException(com.infiniteautomation.mango.rest.v2.exception.BadRequestException) JsonNode(com.fasterxml.jackson.databind.JsonNode) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode)

Example 19 with BadRequestException

use of com.netflix.spinnaker.front50.exception.BadRequestException in project front50 by spinnaker.

the class EntityTagsController method delete.

@RequestMapping(method = RequestMethod.DELETE, value = "/**")
public void delete(HttpServletRequest request, HttpServletResponse response) {
    String pattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
    String tagId = new AntPathMatcher().extractPathWithinPattern(pattern, request.getServletPath());
    if (!taggedEntityDAO.isPresent()) {
        throw new BadRequestException("Tagging is not supported");
    }
    taggedEntityDAO.get().delete(tagId);
    response.setStatus(HttpStatus.NO_CONTENT.value());
}
Also used : BadRequestException(com.netflix.spinnaker.front50.exception.BadRequestException) AntPathMatcher(org.springframework.util.AntPathMatcher)

Aggregations

BadRequestException (com.infiniteautomation.mango.rest.v2.exception.BadRequestException)17 TranslatableMessage (com.serotonin.m2m2.i18n.TranslatableMessage)17 ApiOperation (com.wordnik.swagger.annotations.ApiOperation)10 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)10 NotFoundRestException (com.infiniteautomation.mango.rest.v2.exception.NotFoundRestException)6 ResponseEntity (org.springframework.http.ResponseEntity)6 AccessDeniedException (com.infiniteautomation.mango.rest.v2.exception.AccessDeniedException)5 JsonNode (com.fasterxml.jackson.databind.JsonNode)4 ArrayNode (com.fasterxml.jackson.databind.node.ArrayNode)4 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)4 AbstractRestV2Exception (com.infiniteautomation.mango.rest.v2.exception.AbstractRestV2Exception)4 DataPointModel (com.infiniteautomation.mango.rest.v2.model.dataPoint.DataPointModel)4 HttpHeaders (org.springframework.http.HttpHeaders)4 PreAuthorize (org.springframework.security.access.prepost.PreAuthorize)4 DataPointVO (com.serotonin.m2m2.vo.DataPointVO)3 User (com.serotonin.m2m2.vo.User)3 URI (java.net.URI)3 VoAction (com.infiniteautomation.mango.rest.v2.bulk.VoAction)2 BadRequestException (com.netflix.spinnaker.front50.exception.BadRequestException)2 JsonObject (com.serotonin.json.type.JsonObject)2