Search in sources :

Example 11 with RequestBody

use of org.springframework.web.bind.annotation.RequestBody in project alien4cloud by alien4cloud.

the class AbstractLocationResourcesSecurityController method updateAuthorizedEnvironmentsAndEnvTypePerApplication.

/**
 * Update applications,environments and environment types authorized to access the location resource.
 */
@ApiOperation(value = "Update applications,environments and environment types authorized to access the location resource", notes = "Only user with ADMIN role can update authorized applications,environments and environment types for the location.")
@RequestMapping(value = "/environmentsPerApplication", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
@PreAuthorize("hasAuthority('ADMIN')")
public synchronized RestResponse<Void> updateAuthorizedEnvironmentsAndEnvTypePerApplication(@PathVariable String orchestratorId, @PathVariable String locationId, @PathVariable String resourceId, @RequestBody ApplicationEnvironmentAuthorizationUpdateRequest request) {
    Location location = locationService.getLocation(orchestratorId, locationId);
    locationSecurityService.grantAuthorizationOnLocationIfNecessary(request.getApplicationsToAdd(), request.getEnvironmentsToAdd(), request.getEnvironmentTypesToAdd(), location);
    AbstractLocationResourceTemplate resourceTemplate = locationResourceService.getOrFail(resourceId);
    if (ArrayUtils.isNotEmpty(request.getApplicationsToDelete())) {
        resourcePermissionService.revokePermission(resourceTemplate, (resource -> locationResourceService.saveResource(location, (AbstractLocationResourceTemplate) resource)), Subject.APPLICATION, request.getApplicationsToDelete());
    }
    if (ArrayUtils.isNotEmpty(request.getEnvironmentsToDelete())) {
        resourcePermissionService.revokePermission(resourceTemplate, (resource -> locationResourceService.saveResource(location, (AbstractLocationResourceTemplate) resource)), Subject.ENVIRONMENT, request.getEnvironmentsToDelete());
    }
    if (ArrayUtils.isNotEmpty(request.getEnvironmentTypesToDelete())) {
        resourcePermissionService.revokePermission(resourceTemplate, (resource -> locationResourceService.saveResource(location, (AbstractLocationResourceTemplate) resource)), Subject.ENVIRONMENT_TYPE, request.getEnvironmentTypesToDelete());
    }
    Set<String> envIds = Sets.newHashSet();
    if (ArrayUtils.isNotEmpty(request.getApplicationsToAdd())) {
        resourcePermissionService.grantPermission(resourceTemplate, (resource -> locationResourceService.saveResource(location, (AbstractLocationResourceTemplate) resource)), Subject.APPLICATION, request.getApplicationsToAdd());
        // when an app is added, all eventual existing env authorizations are removed
        for (String applicationToAddId : request.getApplicationsToAdd()) {
            ApplicationEnvironment[] aes = applicationEnvironmentService.getByApplicationId(applicationToAddId);
            for (ApplicationEnvironment ae : aes) {
                envIds.add(ae.getId());
            }
        }
        if (!envIds.isEmpty()) {
            resourcePermissionService.revokePermission(resourceTemplate, (resource -> locationResourceService.saveResource(location, (AbstractLocationResourceTemplate) resource)), Subject.ENVIRONMENT, envIds.toArray(new String[envIds.size()]));
        }
    }
    if (ArrayUtils.isNotEmpty(request.getEnvironmentsToAdd())) {
        List<String> envToAddSet = Arrays.stream(request.getEnvironmentsToAdd()).filter(env -> !envIds.contains(env)).collect(Collectors.toList());
        resourcePermissionService.grantPermission(resourceTemplate, (resource -> locationResourceService.saveResource(location, (AbstractLocationResourceTemplate) resource)), Subject.ENVIRONMENT, envToAddSet.toArray(new String[envToAddSet.size()]));
    }
    if (ArrayUtils.isNotEmpty(request.getEnvironmentTypesToAdd())) {
        resourcePermissionService.grantPermission(resourceTemplate, (resource -> locationResourceService.saveResource(location, (AbstractLocationResourceTemplate) resource)), Subject.ENVIRONMENT_TYPE, request.getEnvironmentTypesToAdd());
    }
    return RestResponseBuilder.<Void>builder().build();
}
Also used : PathVariable(org.springframework.web.bind.annotation.PathVariable) Lists(org.elasticsearch.common.collect.Lists) Arrays(java.util.Arrays) ApplicationEnvironmentService(alien4cloud.application.ApplicationEnvironmentService) Subject(alien4cloud.security.Subject) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) LocationService(alien4cloud.orchestrators.locations.services.LocationService) ResourcePermissionService(alien4cloud.authorization.ResourcePermissionService) ApplicationEnvironmentAuthorizationDTO(alien4cloud.rest.orchestrator.model.ApplicationEnvironmentAuthorizationDTO) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ArrayUtils(org.apache.commons.lang3.ArrayUtils) LocationSecurityService(alien4cloud.orchestrators.locations.services.LocationSecurityService) AlienUtils.safe(alien4cloud.utils.AlienUtils.safe) Location(alien4cloud.model.orchestrators.locations.Location) RequestBody(org.springframework.web.bind.annotation.RequestBody) ApiOperation(io.swagger.annotations.ApiOperation) Audit(alien4cloud.audit.annotation.Audit) RestResponseBuilder(alien4cloud.rest.model.RestResponseBuilder) RestResponse(alien4cloud.rest.model.RestResponse) Application(alien4cloud.model.application.Application) ILocationResourceService(alien4cloud.orchestrators.locations.services.ILocationResourceService) MapUtils(org.apache.commons.collections4.MapUtils) ApplicationEnvironment(alien4cloud.model.application.ApplicationEnvironment) MediaType(org.springframework.http.MediaType) Resource(javax.annotation.Resource) RequestMethod(org.springframework.web.bind.annotation.RequestMethod) Set(java.util.Set) IGenericSearchDAO(alien4cloud.dao.IGenericSearchDAO) Collectors(java.util.stream.Collectors) Sets(com.google.common.collect.Sets) List(java.util.List) GroupDTO(alien4cloud.rest.orchestrator.model.GroupDTO) UserDTO(alien4cloud.rest.orchestrator.model.UserDTO) AbstractLocationResourceTemplate(alien4cloud.model.orchestrators.locations.AbstractLocationResourceTemplate) ApplicationEnvironmentAuthorizationUpdateRequest(alien4cloud.rest.orchestrator.model.ApplicationEnvironmentAuthorizationUpdateRequest) AbstractLocationResourceTemplate(alien4cloud.model.orchestrators.locations.AbstractLocationResourceTemplate) ApplicationEnvironment(alien4cloud.model.application.ApplicationEnvironment) Location(alien4cloud.model.orchestrators.locations.Location) ApiOperation(io.swagger.annotations.ApiOperation) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 12 with RequestBody

use of org.springframework.web.bind.annotation.RequestBody in project cas by apereo.

the class OidcDynamicClientRegistrationEndpointController method handleRequestInternal.

/**
 * Handle request.
 *
 * @param jsonInput the json input
 * @param request   the request
 * @param response  the response
 * @return the model and view
 * @throws Exception the exception
 */
@PostMapping(value = { '/' + OidcConstants.BASE_OIDC_URL + '/' + OidcConstants.REGISTRATION_URL, "/**/" + OidcConstants.REGISTRATION_URL }, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity handleRequestInternal(@RequestBody final String jsonInput, final HttpServletRequest request, final HttpServletResponse response) throws Exception {
    val webContext = new JEEContext(request, response);
    if (!getConfigurationContext().getOidcRequestSupport().isValidIssuerForEndpoint(webContext, OidcConstants.REGISTRATION_URL)) {
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }
    try {
        val registrationRequest = (OidcClientRegistrationRequest) getConfigurationContext().getClientRegistrationRequestSerializer().from(jsonInput);
        LOGGER.debug("Received client registration request [{}]", registrationRequest);
        val containsFragment = registrationRequest.getRedirectUris().stream().anyMatch(uri -> uri.contains("#"));
        if (containsFragment) {
            throw new IllegalArgumentException("Redirect URI cannot contain a fragment");
        }
        val servicesManager = getConfigurationContext().getServicesManager();
        val registeredService = registrationRequest.getRedirectUris().stream().map(uri -> (OidcRegisteredService) OAuth20Utils.getRegisteredOAuthServiceByRedirectUri(servicesManager, uri)).filter(Objects::nonNull).findFirst().orElseGet(OidcRegisteredService::new);
        if (StringUtils.isNotBlank(registrationRequest.getClientName())) {
            registeredService.setName(registrationRequest.getClientName());
        } else if (StringUtils.isBlank(registeredService.getName())) {
            registeredService.setName(RandomUtils.randomAlphabetic(GENERATED_CLIENT_NAME_LENGTH));
        }
        val serviceId = String.join("|", registrationRequest.getRedirectUris());
        registeredService.setServiceId(serviceId);
        registeredService.setSectorIdentifierUri(registrationRequest.getSectorIdentifierUri());
        registeredService.setSubjectType(registrationRequest.getSubjectType());
        if (StringUtils.equalsIgnoreCase(OidcSubjectTypes.PAIRWISE.getType(), registeredService.getSubjectType())) {
            registeredService.setUsernameAttributeProvider(new PairwiseOidcRegisteredServiceUsernameAttributeProvider());
        }
        if (StringUtils.isNotBlank(registrationRequest.getJwksUri())) {
            registeredService.setJwks(registrationRequest.getJwksUri());
        } else {
            val jwks = registrationRequest.getJwks();
            if (jwks != null && !jwks.getJsonWebKeys().isEmpty()) {
                jwks.getJsonWebKeys().stream().filter(key -> StringUtils.isBlank(key.getKeyId())).forEach(key -> key.setKeyId(RandomUtils.randomAlphabetic(6)));
                registeredService.setJwks(jwks.toJson());
            }
        }
        if (StringUtils.isNotBlank(registrationRequest.getTokenEndpointAuthMethod())) {
            registeredService.setTokenEndpointAuthenticationMethod(registrationRequest.getTokenEndpointAuthMethod());
        }
        registeredService.setClientId(getConfigurationContext().getClientIdGenerator().getNewString());
        registeredService.setClientSecret(getConfigurationContext().getClientSecretGenerator().getNewString());
        registeredService.setEvaluationOrder(0);
        val urls = org.springframework.util.StringUtils.collectionToCommaDelimitedString(registrationRequest.getPostLogoutRedirectUris());
        registeredService.setLogoutUrl(urls);
        if (StringUtils.isNotBlank(registrationRequest.getLogo())) {
            registeredService.setLogo(registrationRequest.getLogo());
        }
        if (StringUtils.isNotBlank(registrationRequest.getPolicyUri())) {
            registeredService.setInformationUrl(registrationRequest.getPolicyUri());
        }
        if (StringUtils.isNotBlank(registrationRequest.getTermsOfUseUri())) {
            registeredService.setPrivacyUrl(registrationRequest.getTermsOfUseUri());
        }
        if (!StringUtils.equalsIgnoreCase("none", registrationRequest.getUserInfoSignedReponseAlg())) {
            registeredService.setUserInfoSigningAlg(registrationRequest.getUserInfoSignedReponseAlg());
        }
        registeredService.setUserInfoEncryptedResponseAlg(registrationRequest.getUserInfoEncryptedResponseAlg());
        if (StringUtils.isNotBlank(registeredService.getUserInfoEncryptedResponseAlg())) {
            if (StringUtils.isBlank(registrationRequest.getUserInfoEncryptedResponseEncoding())) {
                registeredService.setUserInfoEncryptedResponseEncoding(OidcUserProfileSigningAndEncryptionService.USER_INFO_RESPONSE_ENCRYPTION_ENCODING_DEFAULT);
            } else {
                registeredService.setUserInfoEncryptedResponseEncoding(registrationRequest.getUserInfoEncryptedResponseEncoding());
            }
        }
        val properties = getConfigurationContext().getCasProperties();
        val supportedScopes = new HashSet<>(properties.getAuthn().getOidc().getDiscovery().getScopes());
        val prefix = properties.getServer().getPrefix();
        val clientResponse = OidcClientRegistrationUtils.getClientRegistrationResponse(registeredService, prefix);
        clientResponse.setClientSecretExpiresAt(0);
        val accessToken = generateRegistrationAccessToken(request, response, registeredService, registrationRequest);
        val encodedAccessToken = OAuth20JwtAccessTokenEncoder.builder().accessToken(accessToken).registeredService(registeredService).service(accessToken.getService()).accessTokenJwtBuilder(getConfigurationContext().getAccessTokenJwtBuilder()).casProperties(getConfigurationContext().getCasProperties()).build().encode();
        clientResponse.setRegistrationAccessToken(encodedAccessToken);
        registeredService.setScopes(supportedScopes);
        val processedScopes = new LinkedHashSet<>(supportedScopes);
        registeredService.setScopes(processedScopes);
        if (!registrationRequest.getDefaultAcrValues().isEmpty()) {
            val multifactorPolicy = new DefaultRegisteredServiceMultifactorPolicy();
            multifactorPolicy.setMultifactorAuthenticationProviders(new HashSet<>(registrationRequest.getDefaultAcrValues()));
            registeredService.setMultifactorPolicy(multifactorPolicy);
        }
        if (StringUtils.isNotBlank(registrationRequest.getIdTokenSignedResponseAlg())) {
            registeredService.setIdTokenSigningAlg(registrationRequest.getIdTokenSignedResponseAlg());
            registeredService.setSignIdToken(true);
        }
        if (StringUtils.isNotBlank(registrationRequest.getIdTokenEncryptedResponseAlg())) {
            registeredService.setIdTokenEncryptionAlg(registrationRequest.getIdTokenEncryptedResponseAlg());
            registeredService.setEncryptIdToken(true);
        }
        if (StringUtils.isNotBlank(registrationRequest.getIdTokenEncryptedResponseEncoding())) {
            registeredService.setIdTokenEncryptionEncoding(registrationRequest.getIdTokenEncryptedResponseEncoding());
            registeredService.setEncryptIdToken(true);
        }
        registrationRequest.getContacts().forEach(c -> {
            val contact = new DefaultRegisteredServiceContact();
            if (c.contains("@")) {
                contact.setEmail(c);
                contact.setName(c.substring(0, c.indexOf('@')));
            } else {
                contact.setName(c);
            }
            registeredService.getContacts().add(contact);
        });
        registeredService.setDescription("Registered service ".concat(registeredService.getName()));
        registeredService.setDynamicallyRegistered(true);
        validate(registrationRequest, registeredService);
        getConfigurationContext().getServicesManager().save(registeredService);
        return new ResponseEntity<>(clientResponse, HttpStatus.CREATED);
    } catch (final Exception e) {
        LoggingUtils.error(LOGGER, e);
        val map = new HashMap<String, String>();
        map.put("error", "invalid_client_metadata");
        map.put("error_description", StringUtils.defaultString(e.getMessage(), "None"));
        return new ResponseEntity<>(map, HttpStatus.BAD_REQUEST);
    }
}
Also used : lombok.val(lombok.val) OidcUserProfileSigningAndEncryptionService(org.apereo.cas.oidc.profile.OidcUserProfileSigningAndEncryptionService) DefaultRegisteredServiceContact(org.apereo.cas.services.DefaultRegisteredServiceContact) RandomUtils(org.apereo.cas.util.RandomUtils) DefaultAuthenticationBuilder(org.apereo.cas.authentication.DefaultAuthenticationBuilder) HashMap(java.util.HashMap) StringUtils(org.apache.commons.lang3.StringUtils) RequestBody(org.springframework.web.bind.annotation.RequestBody) HashSet(java.util.HashSet) LoggingUtils(org.apereo.cas.util.LoggingUtils) HttpServletRequest(javax.servlet.http.HttpServletRequest) BaseOidcController(org.apereo.cas.oidc.web.controllers.BaseOidcController) OAuth20AccessTokenFactory(org.apereo.cas.ticket.accesstoken.OAuth20AccessTokenFactory) JEEContext(org.pac4j.core.context.JEEContext) LinkedHashSet(java.util.LinkedHashSet) OAuth20JwtAccessTokenEncoder(org.apereo.cas.support.oauth.web.response.accesstoken.response.OAuth20JwtAccessTokenEncoder) PostMapping(org.springframework.web.bind.annotation.PostMapping) OidcClientRegistrationRequest(org.apereo.cas.oidc.dynareg.OidcClientRegistrationRequest) OAuth20ResponseTypes(org.apereo.cas.support.oauth.OAuth20ResponseTypes) OAuth20Utils(org.apereo.cas.support.oauth.util.OAuth20Utils) OAuth20GrantTypes(org.apereo.cas.support.oauth.OAuth20GrantTypes) PrincipalFactoryUtils(org.apereo.cas.authentication.principal.PrincipalFactoryUtils) OidcConstants(org.apereo.cas.oidc.OidcConstants) MediaType(org.springframework.http.MediaType) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) lombok.val(lombok.val) HttpMethod(org.springframework.http.HttpMethod) HttpServletResponse(javax.servlet.http.HttpServletResponse) HttpUtils(org.apereo.cas.util.HttpUtils) StandardCharsets(java.nio.charset.StandardCharsets) OidcSubjectTypes(org.apereo.cas.services.OidcSubjectTypes) OAuth20AccessToken(org.apereo.cas.ticket.accesstoken.OAuth20AccessToken) OidcConfigurationContext(org.apereo.cas.oidc.OidcConfigurationContext) Objects(java.util.Objects) IOUtils(org.apache.commons.io.IOUtils) HttpStatus(org.springframework.http.HttpStatus) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) OidcRegisteredService(org.apereo.cas.services.OidcRegisteredService) JacksonObjectMapperFactory(org.apereo.cas.util.serialization.JacksonObjectMapperFactory) JsonValue(org.hjson.JsonValue) PairwiseOidcRegisteredServiceUsernameAttributeProvider(org.apereo.cas.services.PairwiseOidcRegisteredServiceUsernameAttributeProvider) HttpResponse(org.apache.http.HttpResponse) ResponseEntity(org.springframework.http.ResponseEntity) DefaultRegisteredServiceMultifactorPolicy(org.apereo.cas.services.DefaultRegisteredServiceMultifactorPolicy) LinkedHashSet(java.util.LinkedHashSet) OidcRegisteredService(org.apereo.cas.services.OidcRegisteredService) JEEContext(org.pac4j.core.context.JEEContext) PairwiseOidcRegisteredServiceUsernameAttributeProvider(org.apereo.cas.services.PairwiseOidcRegisteredServiceUsernameAttributeProvider) DefaultRegisteredServiceMultifactorPolicy(org.apereo.cas.services.DefaultRegisteredServiceMultifactorPolicy) ResponseEntity(org.springframework.http.ResponseEntity) OidcClientRegistrationRequest(org.apereo.cas.oidc.dynareg.OidcClientRegistrationRequest) Objects(java.util.Objects) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) DefaultRegisteredServiceContact(org.apereo.cas.services.DefaultRegisteredServiceContact) PostMapping(org.springframework.web.bind.annotation.PostMapping)

Example 13 with RequestBody

use of org.springframework.web.bind.annotation.RequestBody in project cas by apereo.

the class UmaUpdatePolicyForResourceSetEndpointController method updatePoliciesForResourceSet.

/**
 * Update policy for resource set.
 *
 * @param resourceId the resource id
 * @param policyId   the policy id
 * @param body       the body
 * @param request    the request
 * @param response   the response
 * @return the policy for resource set
 */
@PutMapping(value = '/' + OAuth20Constants.BASE_OAUTH20_URL + "/{resourceId}/" + OAuth20Constants.UMA_POLICY_URL + "/{policyId}", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity updatePoliciesForResourceSet(@PathVariable(value = "resourceId") final long resourceId, @PathVariable(value = "policyId") final long policyId, @RequestBody final String body, final HttpServletRequest request, final HttpServletResponse response) {
    try {
        val profileResult = getAuthenticatedProfile(request, response, OAuth20Constants.UMA_PROTECTION_SCOPE);
        val resourceSetResult = getUmaConfigurationContext().getUmaResourceSetRepository().getById(resourceId);
        if (resourceSetResult.isEmpty()) {
            val model = buildResponseEntityErrorModel(HttpStatus.NOT_FOUND, "Requested resource-set cannot be found");
            return new ResponseEntity(model, model, HttpStatus.BAD_REQUEST);
        }
        val resourceSet = resourceSetResult.get();
        resourceSet.validate(profileResult);
        val umaRequest = MAPPER.readValue(JsonValue.readHjson(body).toString(), ResourceSetPolicy.class);
        val policyResult = resourceSet.getPolicies().stream().filter(p -> p.getId() == policyId).findFirst();
        if (policyResult.isPresent()) {
            val policy = policyResult.get();
            policy.setPermissions(umaRequest.getPermissions());
            val currentPolicies = resourceSet.getPolicies().stream().filter(p -> p.getId() != policyId).collect(Collectors.toSet());
            currentPolicies.add(policy);
            resourceSet.setPolicies(new HashSet<>(currentPolicies));
            getUmaConfigurationContext().getUmaResourceSetRepository().save(resourceSet);
            val model = CollectionUtils.wrap("entity", resourceSet, "code", HttpStatus.FOUND);
            return new ResponseEntity(model, HttpStatus.OK);
        }
        val model = CollectionUtils.wrap("code", HttpStatus.NOT_FOUND);
        return new ResponseEntity(model, HttpStatus.OK);
    } catch (final Exception e) {
        LoggingUtils.error(LOGGER, e);
    }
    return new ResponseEntity("Unable to locate resource-set.", HttpStatus.BAD_REQUEST);
}
Also used : lombok.val(lombok.val) PathVariable(org.springframework.web.bind.annotation.PathVariable) OAuth20Constants(org.apereo.cas.support.oauth.OAuth20Constants) UmaConfigurationContext(org.apereo.cas.uma.UmaConfigurationContext) MediaType(org.springframework.http.MediaType) lombok.val(lombok.val) HttpServletResponse(javax.servlet.http.HttpServletResponse) ResourceSetPolicy(org.apereo.cas.uma.ticket.resource.ResourceSetPolicy) Controller(org.springframework.stereotype.Controller) Collectors(java.util.stream.Collectors) RequestBody(org.springframework.web.bind.annotation.RequestBody) HashSet(java.util.HashSet) HttpStatus(org.springframework.http.HttpStatus) LoggingUtils(org.apereo.cas.util.LoggingUtils) Slf4j(lombok.extern.slf4j.Slf4j) HttpServletRequest(javax.servlet.http.HttpServletRequest) PutMapping(org.springframework.web.bind.annotation.PutMapping) CollectionUtils(org.apereo.cas.util.CollectionUtils) JsonValue(org.hjson.JsonValue) ResponseEntity(org.springframework.http.ResponseEntity) BaseUmaEndpointController(org.apereo.cas.uma.web.controllers.BaseUmaEndpointController) ResponseEntity(org.springframework.http.ResponseEntity) PutMapping(org.springframework.web.bind.annotation.PutMapping)

Example 14 with RequestBody

use of org.springframework.web.bind.annotation.RequestBody in project proxyee-down by monkeyWie.

the class HttpDownController method bdyUnzip.

@RequestMapping("/bdyUnzip")
public ResultInfo bdyUnzip(@RequestParam String id, @RequestParam boolean ignore, @RequestBody UnzipForm unzipForm) throws IOException {
    ResultInfo resultInfo = new ResultInfo();
    File file = new File(unzipForm.getFilePath());
    if (file.exists() && file.isFile()) {
        if (!unzipForm.getFilePath().equalsIgnoreCase(unzipForm.getToPath())) {
            if (ignore || BdyZip.isBdyZip(unzipForm.getFilePath())) {
                UnzipInfo unzipInfo = new UnzipInfo().setId(id);
                if (!FileUtil.exists(unzipForm.getToPath())) {
                    FileUtil.createDirSmart(unzipForm.getToPath());
                }
                if (!FileUtil.canWrite(unzipForm.getToPath())) {
                    resultInfo.setStatus(ResultStatus.BAD.getCode()).setMsg("无权访问解压路径,请修改路径或开放目录写入权限");
                    return resultInfo;
                }
                new Thread(() -> {
                    try {
                        BdyZip.unzip(unzipForm.getFilePath(), unzipForm.getToPath(), new BdyUnzipCallback() {

                            @Override
                            public void onStart() {
                                unzipInfo.setType(BdyZip.ON_START).setStartTime(System.currentTimeMillis());
                                ContentManager.WS.sendMsg(new WsForm(WsDataType.UNZIP_ING, unzipInfo));
                            }

                            @Override
                            public void onFix(long totalSize, long fixSize) {
                                unzipInfo.setType(BdyZip.ON_FIX).setTotalFixSize(totalSize).setFixSize(fixSize);
                                ContentManager.WS.sendMsg(new WsForm(WsDataType.UNZIP_ING, unzipInfo));
                            }

                            @Override
                            public void onFixDone(List<BdyZipEntry> list) {
                                unzipInfo.setType(BdyZip.ON_FIX_DONE).setTotalFileSize(list.stream().map(entry -> entry.getCompressedSize()).reduce((s1, s2) -> s1 + s2).get());
                            }

                            @Override
                            public void onEntryStart(BdyZipEntry entry) {
                                unzipInfo.setType(BdyZip.ON_ENTRY_START).setEntry(entry).setCurrFileSize(entry.getCompressedSize()).setCurrWriteSize(0);
                                ContentManager.WS.sendMsg(new WsForm(WsDataType.UNZIP_ING, unzipInfo));
                            }

                            @Override
                            public void onEntryWrite(long totalSize, long writeSize) {
                                unzipInfo.setType(BdyZip.ON_ENTRY_WRITE).setCurrWriteSize(unzipInfo.getCurrWriteSize() + writeSize).setTotalWriteSize(unzipInfo.getTotalWriteSize() + writeSize);
                                ContentManager.WS.sendMsg(new WsForm(WsDataType.UNZIP_ING, unzipInfo));
                            }

                            @Override
                            public void onDone() {
                                unzipInfo.setType(BdyZip.ON_DONE).setEndTime(System.currentTimeMillis());
                                ContentManager.WS.sendMsg(new WsForm(WsDataType.UNZIP_ING, unzipInfo));
                            }

                            @Override
                            public void onError(Exception e) {
                                unzipInfo.setType(BdyZip.ON_ERROR).setErrorMsg(e.toString());
                                ContentManager.WS.sendMsg(new WsForm(WsDataType.UNZIP_ING, unzipInfo));
                            }
                        });
                    } catch (Exception e) {
                        LOGGER.error("unzip error:", e);
                    }
                }).start();
            } else {
                resultInfo.setStatus(ResultStatus.BAD.getCode());
                resultInfo.setMsg("解压失败,请确认是否为百度云批量下载zip文件");
            }
        } else {
            resultInfo.setStatus(ResultStatus.BAD.getCode());
            resultInfo.setMsg("解压失败,文件路径与解压路径相同");
        }
    } else {
        resultInfo.setStatus(ResultStatus.BAD.getCode());
        resultInfo.setMsg("解压失败,文件不存在");
    }
    return resultInfo;
}
Also used : Arrays(java.util.Arrays) HttpDownConstant(lee.study.down.constant.HttpDownConstant) BdyZip(lee.study.down.io.BdyZip) BdyZipEntry(lee.study.down.io.BdyZip.BdyZipEntry) RequestParam(org.springframework.web.bind.annotation.RequestParam) ContentManager(lee.study.down.content.ContentManager) LoggerFactory(org.slf4j.LoggerFactory) TimeoutException(java.util.concurrent.TimeoutException) ResultStatus(lee.study.down.model.ResultInfo.ResultStatus) FileUtil(lee.study.down.util.FileUtil) TaskInfo(lee.study.down.model.TaskInfo) UpdateService(lee.study.down.update.UpdateService) DirInfo(lee.study.down.model.DirInfo) DirForm(lee.study.down.mvc.form.DirForm) HttpDownApplication(lee.study.down.gui.HttpDownApplication) Map(java.util.Map) GithubUpdateService(lee.study.down.update.GithubUpdateService) HttpDownCallback(lee.study.down.dispatch.HttpDownCallback) Collectors(java.util.stream.Collectors) UnzipForm(lee.study.down.mvc.form.UnzipForm) RestController(org.springframework.web.bind.annotation.RestController) UpdateInfo(lee.study.down.model.UpdateInfo) List(java.util.List) WsForm(lee.study.down.mvc.form.WsForm) BootstrapException(lee.study.down.exception.BootstrapException) ProxyConfig(lee.study.proxyee.proxy.ProxyConfig) HttpDownStatus(lee.study.down.constant.HttpDownStatus) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Value(org.springframework.beans.factory.annotation.Value) RequestBody(org.springframework.web.bind.annotation.RequestBody) AbstractHttpDownBootstrap(lee.study.down.boot.AbstractHttpDownBootstrap) BdyUnzipCallback(lee.study.down.io.BdyZip.BdyUnzipCallback) ConfigInfo(lee.study.down.model.ConfigInfo) LinkedList(java.util.LinkedList) BuildTaskForm(lee.study.down.mvc.form.BuildTaskForm) Desktop(java.awt.Desktop) NewTaskForm(lee.study.down.mvc.form.NewTaskForm) Logger(org.slf4j.Logger) MalformedURLException(java.net.MalformedURLException) Files(java.nio.file.Files) HttpRequestInfo(lee.study.down.model.HttpRequestInfo) WsDataType(lee.study.down.mvc.ws.WsDataType) ResultInfo(lee.study.down.model.ResultInfo) IOException(java.io.IOException) File(java.io.File) UnzipInfo(lee.study.down.model.UnzipInfo) OsUtil(lee.study.down.util.OsUtil) DownContent(lee.study.down.content.DownContent) HttpDownInfo(lee.study.down.model.HttpDownInfo) Paths(java.nio.file.Paths) ConfigForm(lee.study.down.mvc.form.ConfigForm) HttpDownUtil(lee.study.down.util.HttpDownUtil) StringUtils(org.springframework.util.StringUtils) BdyUnzipCallback(lee.study.down.io.BdyZip.BdyUnzipCallback) UnzipInfo(lee.study.down.model.UnzipInfo) List(java.util.List) LinkedList(java.util.LinkedList) WsForm(lee.study.down.mvc.form.WsForm) ResultInfo(lee.study.down.model.ResultInfo) File(java.io.File) BdyZipEntry(lee.study.down.io.BdyZip.BdyZipEntry) TimeoutException(java.util.concurrent.TimeoutException) BootstrapException(lee.study.down.exception.BootstrapException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 15 with RequestBody

use of org.springframework.web.bind.annotation.RequestBody in project spring-framework by spring-projects.

the class RequestBodyMethodArgumentResolver method resolveArgument.

@Override
public Mono<Object> resolveArgument(MethodParameter param, BindingContext bindingContext, ServerWebExchange exchange) {
    RequestBody ann = param.getParameterAnnotation(RequestBody.class);
    Assert.state(ann != null, "No RequestBody annotation");
    return readBody(param, ann.required(), bindingContext, exchange);
}
Also used : RequestBody(org.springframework.web.bind.annotation.RequestBody)

Aggregations

RequestBody (org.springframework.web.bind.annotation.RequestBody)19 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)14 List (java.util.List)13 Collectors (java.util.stream.Collectors)13 PathVariable (org.springframework.web.bind.annotation.PathVariable)10 HttpStatus (org.springframework.http.HttpStatus)9 MediaType (org.springframework.http.MediaType)9 RequestMethod (org.springframework.web.bind.annotation.RequestMethod)9 Set (java.util.Set)8 RequestParam (org.springframework.web.bind.annotation.RequestParam)8 ApiOperation (io.swagger.annotations.ApiOperation)7 Arrays (java.util.Arrays)7 Map (java.util.Map)7 ResponseEntity (org.springframework.http.ResponseEntity)7 RestController (org.springframework.web.bind.annotation.RestController)7 IOException (java.io.IOException)6 ArrayList (java.util.ArrayList)5 HashSet (java.util.HashSet)5 PreAuthorize (org.springframework.security.access.prepost.PreAuthorize)5 ApplicationEnvironmentService (alien4cloud.application.ApplicationEnvironmentService)4