List of usage examples for org.springframework.http ResponseEntity status
Object status
To view the source code for org.springframework.http ResponseEntity status.
Click Source Link
From source file:com.yunmel.syncretic.core.BaseController.java
/** * * * @param e * @return */ protected ResponseEntity<Result> refuse(Result result) { return ResponseEntity.status(HttpStatus.FORBIDDEN).body(result); }
From source file:com.yunmel.syncretic.core.BaseController.java
/** * ?//from www .j ava2 s. co m * * @param e * @return */ protected ResponseEntity<Result> unauthorized(Result result) { return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(result); }
From source file:objective.taskboard.controller.FollowUpController.java
@RequestMapping public ResponseEntity<Object> download(@RequestParam("project") String projectKey, @RequestParam("template") String template, @RequestParam("date") Optional<LocalDate> date, @RequestParam("timezone") String zoneId) { if (ObjectUtils.isEmpty(projectKey)) return new ResponseEntity<>("You must provide the project", BAD_REQUEST); if (ObjectUtils.isEmpty(template)) return new ResponseEntity<>("Template not selected", BAD_REQUEST); Template templateFollowup = templateService.getTemplate(template); if (templateFollowup == null || !authorizer.hasAnyRoleInProjects(templateFollowup.getRoles(), asList(projectKey))) return new ResponseEntity<>("Template or project doesn't exist", HttpStatus.NOT_FOUND); ZoneId timezone = determineTimeZoneId(zoneId); try {/*from ww w. ja v a2 s . c o m*/ Resource resource = followUpFacade.generateReport(template, date, timezone, projectKey); String filename = "Followup_" + template + "_" + projectKey + "_" + templateDate(date, timezone) + ".xlsm"; return ResponseEntity.ok().contentLength(resource.contentLength()) .header("Content-Disposition", "attachment; filename=\"" + filename + "\"") .header("Set-Cookie", "fileDownload=true; path=/").body(resource); } catch (InvalidTableRangeException e) {//NOSONAR return ResponseEntity.badRequest().body(format( "The selected template is invalid. The range of table %s? in sheet %s? is smaller than the available data. " + "Please increase the range to cover at least row %s.", e.getTableName(), e.getSheetName(), e.getMinRows())); } catch (ClusterNotConfiguredException e) {//NOSONAR return ResponseEntity.badRequest() .body("No cluster configuration found for project " + projectKey + "."); } catch (ProjectDatesNotConfiguredException e) {//NOSONAR return ResponseEntity.badRequest() .body("The project " + projectKey + " has no start or delivery date."); } catch (Exception e) { log.warn("Error generating followup spreadsheet", e); return ResponseEntity.status(INTERNAL_SERVER_ERROR).header("Content-Type", "text/html; charset=utf-8") .body(StringUtils.defaultIfEmpty(e.getMessage(), e.toString())); } }
From source file:org.apereo.portal.rest.oauth.OidcUserInfoController.java
/** * Obtain an OIDC Id token for the specified <code>client_id</code>. At least one bean of type * {@link OAuthClient} is required to use this endpoint. * * <p>This token strategy supports Spring's <code>OAuth2RestTemplate</code> for accessing * uPortal REST APIs from external systems. Use a <code>ClientCredentialsResourceDetails</code> * with <code>clientAuthenticationScheme=AuthenticationScheme.form</code>, together with a * <code>ClientCredentialsAccessTokenProvider</code>. * * @since 5.5// w w w . j av a 2 s . c om */ @PostMapping(value = TOKEN_ENDPOINT_URI, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity oauthToken(@RequestParam(value = "client_id") String clientId, @RequestParam(value = "client_secret") String clientSecret, @RequestParam(value = "grant_type", required = false, defaultValue = "client_credentials") String grantType, @RequestParam(value = "scope", required = false, defaultValue = "/all") String scope, @RequestParam(value = "claims", required = false) String claims, @RequestParam(value = "groups", required = false) String groups) { /* * NB: Several of this method's parameters are not consumed (yet) in any way. They are * defined to match a two-legged OAuth strategy and for future use. */ final String msg = "Processing request for OAuth access token; client_id='{}', client_secret='{}', " + "grant_type='{}', scope='{}', claims='{}', groups='{}'"; logger.debug(msg, clientId, StringUtils.repeat("*", clientSecret.length()), grantType, scope, claims, groups); // STEP 1: identify the client final OAuthClient oAuthClient = clientMap.get(clientId); if (oAuthClient == null) { return ResponseEntity.status(HttpStatus.FORBIDDEN) .body(Collections.singletonMap("message", "client_id not found")); } logger.debug("Selected known OAuthClient with client_id='{}' for access token request", oAuthClient.getClientId()); // STEP 2: validate the client_secret if (!oAuthClient.getClientSecret().equals(clientSecret)) { return ResponseEntity.status(HttpStatus.FORBIDDEN) .body(Collections.singletonMap("message", "authentication failed")); } // STEP 3: obtain the specified user final IPerson person = personService.getPerson(oAuthClient.getPortalUserAccount()); if (person == null) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Collections.singletonMap("message", "portal user account not found: " + oAuthClient.getPortalUserAccount())); } logger.debug("Selected portal Person with username='{}' for client_id='{}'", person.getUserName(), oAuthClient.getClientId()); // STEP 4: build a standard OAuth2 access token response final String token = createToken(person, claims, groups); final Map<String, Object> rslt = new HashMap<>(); rslt.put("access_token", token); rslt.put("token_type", "bearer"); rslt.put("expires_in", timeoutSeconds > 2 ? timeoutSeconds - 2L /* fudge factor */ : timeoutSeconds); rslt.put("scope", scope); logger.debug("Produced the following access token for client_id='{}': {}", oAuthClient.getClientId(), rslt); return ResponseEntity.ok(rslt); }
From source file:org.craftercms.deployer.impl.rest.TargetController.java
/** * Deploys the {@link Target} with the specified environment and site name. * * @param env the target's environment * @param siteName the target's site name * @param params any additional parameters that can be used by the {@link org.craftercms.deployer.api.DeploymentProcessor}s, for * example {@code reprocess_all_files} * * @return the response entity with a 200 OK status * * @throws DeployerException if an error occurred *///from w w w. j a v a 2 s. c om @RequestMapping(value = DEPLOY_TARGET_URL, method = RequestMethod.POST) public ResponseEntity<Result> deployTarget(@PathVariable(ENV_PATH_VAR_NAME) String env, @PathVariable(SITE_NAME_PATH_VAR_NAME) String siteName, @RequestBody(required = false) Map<String, Object> params) throws DeployerException, ExecutionException, InterruptedException { if (params == null) { params = new HashMap<>(); } boolean waitTillDone = false; if (MapUtils.isNotEmpty(params)) { waitTillDone = BooleanUtils.toBoolean(params.remove(WAIT_TILL_DONE_PARAM_NAME)); } deploymentService.deployTarget(env, siteName, waitTillDone, params); return ResponseEntity.status(HttpStatus.ACCEPTED).body(Result.OK); }
From source file:org.craftercms.deployer.impl.rest.TargetController.java
/** * Deploys all current {@link Target}s.//www .ja v a 2 s .c o m * * @param params any additional parameters that can be used by the {@link org.craftercms.deployer.api.DeploymentProcessor}s, for * example {@code reprocess_all_files} * * @return the response entity with a 200 OK status * * @throws DeployerException if an error occurred */ @RequestMapping(value = DEPLOY_ALL_TARGETS_URL, method = RequestMethod.POST) public ResponseEntity<Result> deployAllTargets(@RequestBody(required = false) Map<String, Object> params) throws DeployerException { if (params == null) { params = new HashMap<>(); } boolean waitTillDone = false; if (MapUtils.isNotEmpty(params)) { waitTillDone = BooleanUtils.toBoolean(params.remove(WAIT_TILL_DONE_PARAM_NAME)); } deploymentService.deployAllTargets(waitTillDone, params); return ResponseEntity.status(HttpStatus.ACCEPTED).body(Result.OK); }
From source file:org.eclipse.hawkbit.mgmt.rest.resource.MgmtDownloadResource.java
/** * Handles the GET request for downloading an artifact. * //from www .j a v a 2s.c om * @param downloadId * the generated download id * @return {@link ResponseEntity} with status {@link HttpStatus#OK} if * successful */ @Override @ResponseBody public ResponseEntity<Void> downloadArtifactByDownloadId(@PathVariable("downloadId") final String downloadId) { try { final ValueWrapper cacheWrapper = cache.get(downloadId); if (cacheWrapper == null) { LOGGER.warn("Download Id {} could not be found", downloadId); return new ResponseEntity<>(HttpStatus.NOT_FOUND); } final DownloadArtifactCache artifactCache = (DownloadArtifactCache) cacheWrapper.get(); DbArtifact artifact = null; if (DownloadType.BY_SHA1.equals(artifactCache.getDownloadType())) { artifact = artifactRepository.getArtifactBySha1(artifactCache.getId()); } else { LOGGER.warn("Download Type {} not supported", artifactCache.getDownloadType()); } if (artifact == null) { LOGGER.warn("Artifact with cached id {} and download type {} could not be found.", artifactCache.getId(), artifactCache.getDownloadType()); return new ResponseEntity<>(HttpStatus.NOT_FOUND); } try { IOUtils.copy(artifact.getFileInputStream(), requestResponseContextHolder.getHttpServletResponse().getOutputStream()); } catch (final IOException e) { LOGGER.error("Cannot copy streams", e); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); } } finally { cache.evict(downloadId); } return ResponseEntity.ok().build(); }
From source file:org.esupportail.publisher.web.rest.FileResource.java
@RequestMapping(value = "/file/{entityId}/{isPublic}/{fileUri:.*}", method = RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_VALUE) @PreAuthorize(SecurityConstants.IS_ROLE_ADMIN + " || " + SecurityConstants.IS_ROLE_USER + " && hasPermission(#entityId, '" + SecurityConstants.CTX_ORGANIZATION + "', '" + SecurityConstants.PERM_LOOKOVER + "')") @Timed//w w w . ja v a 2 s. c om public ResponseEntity<Void> delete(@PathVariable Long entityId, @PathVariable boolean isPublic, @PathVariable("fileUri") String fileUri) throws URIException { log.debug("REST request to delete File : {}", fileUri); boolean result; if (isPublic) { result = fileService.deleteInternalResource(StringUtils.newStringUtf8(decoder.decode(fileUri))); } else { result = fileService.deletePrivateResource(StringUtils.newStringUtf8(decoder.decode(fileUri))); } if (result) return ResponseEntity.ok().build(); return ResponseEntity.status(HttpStatus.NO_CONTENT).build(); }
From source file:org.geowebcache.sqlite.OperationsRest.java
@RequestMapping(value = "/replace", method = RequestMethod.POST) public @ResponseBody ResponseEntity<String> replace(@RequestParam(value = "layer") String layer, @RequestParam(value = "destination", required = false) String destination, @RequestParam(value = "source", required = false) String source, @RequestParam(value = "file", required = false) MultipartFile uploadedFile) { // we need to close this resources at the end File workingDirectory = null; File file = null;/* w w w . j av a 2s .co m*/ try { // create a temporary working directory (may not be used) workingDirectory = Files.createTempDirectory("replace-operation-").toFile(); // finding the blobstore associated t our layer SqliteBlobStore blobStore = getBlobStoreForLayer(layer); if (blobStore == null) { return ResponseEntity.status(HttpStatus.BAD_REQUEST) .body("No SQLite store could be associated with provided layer."); } // finding the file or the directory that will be used to replace if (uploadedFile != null && !uploadedFile.isEmpty()) { // it was an upload file file = handleFileUpload(uploadedFile, workingDirectory); } else if (source != null) { // the file is already present file = new File(source); } if (file == null || !file.exists()) { return ResponseEntity.status(HttpStatus.BAD_REQUEST) .body("Provided file is NULL or doesn't exists."); } // if we have a zip file we need to unzip it file = unzipFileIfNeeded(file, workingDirectory); if (file.isDirectory()) { // we invoke the replace directory variant blobStore.replace(file); } else { if (destination == null) { return ResponseEntity.status(HttpStatus.BAD_REQUEST) .body("Destination is required for single files."); } // we replace the single file blobStore.replace(file, destination); } } catch (Exception exception) { if (LOGGER.isErrorEnabled()) { LOGGER.error("Error executing the replace operation.", exception); } return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(exception.getMessage()); } finally { // cleaning everything FileUtils.deleteQuietly(workingDirectory); } return ResponseEntity.status(HttpStatus.OK).body(null); }
From source file:org.springframework.cloud.function.web.flux.FunctionController.java
@PostMapping(path = "/**") @ResponseBody//from w ww . j av a 2 s . co m public ResponseEntity<Flux<?>> post( @RequestAttribute(required = false, name = "org.springframework.cloud.function.web.flux.constants.WebRequestConstants.function") Function<Flux<?>, Flux<?>> function, @RequestAttribute(required = false, name = "org.springframework.cloud.function.web.flux.constants.WebRequestConstants.consumer") Consumer<Flux<?>> consumer, @RequestAttribute(required = false, name = "org.springframework.cloud.function.web.flux.constants.WebRequestConstants.input_single") Boolean single, @RequestBody FluxRequest<?> body) { if (function != null) { Flux<?> result = (Flux<?>) function.apply(body.flux()); if (logger.isDebugEnabled()) { logger.debug("Handled POST with function"); } return ResponseEntity.ok().body(debug ? result.log() : result); } if (consumer != null) { Flux<?> flux = body.flux().cache(); // send a copy back to the caller consumer.accept(flux); if (logger.isDebugEnabled()) { logger.debug("Handled POST with consumer"); } return ResponseEntity.status(HttpStatus.ACCEPTED).body(flux); } throw new IllegalArgumentException("no such function"); }