Example usage for org.springframework.http ResponseEntity status

List of usage examples for org.springframework.http ResponseEntity status

Introduction

In this page you can find the example usage for org.springframework.http ResponseEntity status.

Prototype

Object status

To view the source code for org.springframework.http ResponseEntity status.

Click Source Link

Usage

From source file:org.springframework.cloud.function.web.RequestProcessor.java

private Mono<ResponseEntity<?>> response(FunctionWrapper wrapper, Object body, boolean stream) {

    Function<Publisher<?>, Publisher<?>> function = wrapper.function();
    Consumer<Publisher<?>> consumer = wrapper.consumer();

    Flux<?> flux;//from www .jav  a 2s.  c om
    if (body != null) {
        if (Collection.class.isAssignableFrom(this.inspector.getInputType(wrapper.handler()))) {
            flux = Flux.just(body);
        } else {
            Iterable<?> iterable = body instanceof Collection ? (Collection<?>) body
                    : (body instanceof Set ? Collections.singleton(body) : Collections.singletonList(body));
            flux = Flux.fromIterable(iterable);
        }
    } else if (MultiValueMap.class.isAssignableFrom(this.inspector.getInputType(wrapper.handler()))) {
        flux = Flux.just(wrapper.params());
    } else {
        throw new IllegalStateException("Failed to determine input for function call with parameters: '"
                + wrapper.params + "' and headers: `" + wrapper.headers + "`");
    }

    if (this.inspector.isMessage(function)) {
        flux = messages(wrapper, function == null ? consumer : function, flux);
    }
    Mono<ResponseEntity<?>> responseEntityMono = null;

    if (function instanceof FluxedConsumer || function instanceof FluxConsumer) {
        ((Mono<?>) function.apply(flux)).subscribe();
        logger.debug("Handled POST with consumer");
        responseEntityMono = Mono.just(ResponseEntity.status(HttpStatus.ACCEPTED).build());
    } else {
        Flux<?> result = Flux.from(function.apply(flux));
        logger.debug("Handled POST with function");
        if (stream) {
            responseEntityMono = stream(wrapper, result);
        } else {
            responseEntityMono = response(wrapper, function, result,
                    body == null ? null : !(body instanceof Collection), false);
        }
    }
    return responseEntityMono;
}

From source file:org.springframework.cloud.gateway.test.HttpBinCompatibleController.java

@RequestMapping("/status/{status}")
public ResponseEntity<String> status(@PathVariable int status) {
    return ResponseEntity.status(status).body("Failed with " + status);
}

From source file:org.springframework.cloud.netflix.turbine.stream.TurbineStreamTests.java

private ResponseEntity<String> extract(ClientHttpResponse response) throws IOException {
    // The message has to be sent after the endpoint is activated, so this is a
    // convenient place to put it
    stubTrigger.trigger("metrics");
    byte[] bytes = new byte[1024];
    StringBuilder builder = new StringBuilder();
    int read = 0;
    while (read >= 0 && StringUtils.countOccurrencesOf(builder.toString(), "\n") < 2) {
        read = response.getBody().read(bytes, 0, bytes.length);
        if (read > 0) {
            latch.countDown();/*w w  w .  ja v  a  2  s  .co m*/
            builder.append(new String(bytes, 0, read));
        }
        log.debug("Building: " + builder);
    }
    log.debug("Done: " + builder);
    return ResponseEntity.status(response.getStatusCode()).headers(response.getHeaders())
            .body(builder.toString());
}

From source file:org.tightblog.ui.restapi.UserController.java

@PostMapping(value = "/tb-ui/authoring/rest/weblog/{weblogId}/user/{userId}/role/{role}/attach", produces = "text/plain")
public ResponseEntity addUserToWeblog(@PathVariable String weblogId, @PathVariable String userId,
        @PathVariable WeblogRole role, Principal p, Locale locale) {

    User requestor = userRepository.findEnabledByUserName(p.getName());
    User newMember = userRepository.findByIdOrNull(userId);
    Weblog weblog = weblogRepository.findById(weblogId).orElse(null);

    if (weblog != null && newMember != null && requestor != null
            && requestor.hasEffectiveGlobalRole(GlobalRole.ADMIN)) {

        UserWeblogRole roleChk = userWeblogRoleRepository.findByUserAndWeblog(newMember, weblog);
        if (roleChk != null) {
            return ResponseEntity.badRequest()
                    .body(messages.getMessage("members.userAlreadyMember", null, locale));
        }//from  w  w  w .ja v  a2  s .  c  om
        userManager.grantWeblogRole(newMember, weblog, role);
        return ResponseEntity.ok(messages.getMessage("members.userAdded", null, locale));
    } else {
        return ResponseEntity.status(HttpServletResponse.SC_FORBIDDEN).build();
    }
}

From source file:org.tightblog.ui.restapi.UserController.java

private ResponseEntity saveUser(User user, UserData newData, Principal p, HttpServletResponse response,
        boolean add) throws ServletException {
    try {/*from  w  w  w.jav  a  2 s .c o m*/
        if (user != null) {
            user.setScreenName(newData.user.getScreenName().trim());
            user.setEmailAddress(newData.user.getEmailAddress().trim());

            if (!UserStatus.ENABLED.equals(user.getStatus())
                    && StringUtils.isNotEmpty(newData.user.getActivationCode())) {
                user.setActivationCode(newData.user.getActivationCode());
            }

            if (add) {
                user.setStatus(newData.user.getStatus());
                if (userRepository.count() == 0) {
                    // first person in is always an admin
                    user.setGlobalRole(GlobalRole.ADMIN);
                } else {
                    user.setGlobalRole(webloggerPropertiesRepository.findOrNull().isUsersCreateBlogs()
                            ? GlobalRole.BLOGCREATOR
                            : GlobalRole.BLOGGER);
                }
            } else {
                // users can't alter own roles or status
                if (!user.getUserName().equals(p.getName())) {
                    user.setGlobalRole(newData.user.getGlobalRole());
                    user.setStatus(newData.user.getStatus());
                }
            }

            try {
                userRepository.saveAndFlush(user);
                userRepository.evictUser(user);
                // reset password if set
                if (newData.credentials != null) {
                    if (!StringUtils.isEmpty(newData.credentials.getPasswordText())) {
                        userManager.updateCredentials(user.getId(), newData.credentials.getPasswordText());
                    }
                    // reset MFA secret if requested
                    if (newData.credentials.isEraseMfaSecret()) {
                        userCredentialsRepository.eraseMfaCode(user.getId());
                    }
                }
                response.setStatus(HttpServletResponse.SC_OK);
            } catch (RollbackException e) {
                return ResponseEntity.status(HttpServletResponse.SC_CONFLICT).body("Persistence Problem");
            }
        } else {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        UserData data = new UserData();
        data.setUser(user);
        UserCredentials creds = userCredentialsRepository.findByUserName(user.getUserName());
        data.setCredentials(creds);
        return ResponseEntity.ok(data);
    } catch (Exception e) {
        log.error("Error updating user", e);
        throw new ServletException(e);
    }
}

From source file:org.tightblog.ui.restapi.WeblogController.java

@PostMapping(value = "/tb-ui/authoring/rest/weblogs")
public ResponseEntity addWeblog(@Valid @RequestBody Weblog newData, Principal p) throws ServletException {

    User user = userRepository.findEnabledByUserName(p.getName());

    if (!user.hasEffectiveGlobalRole(GlobalRole.BLOGCREATOR)) {
        return ResponseEntity.status(403)
                .body(messages.getMessage("weblogConfig.createNotAuthorized", null, Locale.getDefault()));
    }//from  w w w.  j  a  va 2s  . co m

    ValidationError maybeError = advancedValidate(newData, true);
    if (maybeError != null) {
        return ResponseEntity.badRequest().body(maybeError);
    }

    Weblog weblog = new Weblog(newData.getHandle().trim(), user, newData.getName().trim(), newData.getTheme());

    return saveWeblog(weblog, newData, true);
}

From source file:org.tightblog.ui.restapi.WeblogEntryController.java

@PostMapping(value = "/{weblogId}/entries")
public ResponseEntity postEntry(@PathVariable String weblogId, @Valid @RequestBody WeblogEntry entryData,
        Locale locale, Principal p) throws ServletException {

    try {/*from   w  w  w .  ja  va 2s  .  c  om*/

        boolean createNew = false;
        WeblogEntry entry = null;

        if (entryData.getId() != null) {
            entry = weblogEntryRepository.findByIdOrNull(entryData.getId());
        }

        // Check user permissions
        User user = userRepository.findEnabledByUserName(p.getName());
        Weblog weblog = (entry == null) ? weblogRepository.findById(weblogId).orElse(null) : entry.getWeblog();

        WeblogRole necessaryRole = (PubStatus.PENDING.equals(entryData.getStatus())
                || PubStatus.DRAFT.equals(entryData.getStatus())) ? WeblogRole.EDIT_DRAFT : WeblogRole.POST;
        if (weblog != null && userManager.checkWeblogRole(user, weblog, necessaryRole)) {

            // create new?
            if (entry == null) {
                createNew = true;
                entry = new WeblogEntry();
                entry.setCreator(user);
                entry.setWeblog(weblog);
                entry.setEditFormat(entryData.getEditFormat());
                entryData.setWeblog(weblog);
            }

            entry.setUpdateTime(Instant.now());
            Instant pubTime = calculatePubTime(entryData);
            entry.setPubTime((pubTime != null) ? pubTime : entry.getUpdateTime());

            if (PubStatus.PUBLISHED.equals(entryData.getStatus())
                    && entry.getPubTime().isAfter(Instant.now().plus(1, ChronoUnit.MINUTES))) {
                entryData.setStatus(PubStatus.SCHEDULED);
            }

            entry.setStatus(entryData.getStatus());
            entry.setTitle(entryData.getTitle());
            entry.setText(entryData.getText());
            entry.setSummary(entryData.getSummary());
            entry.setNotes(entryData.getNotes());
            if (!StringUtils.isEmpty(entryData.getTagsAsString())) {
                entry.updateTags(
                        new HashSet<>(Arrays.asList(entryData.getTagsAsString().trim().split("\\s+"))));
            } else {
                entry.updateTags(new HashSet<>());
            }
            entry.setSearchDescription(entryData.getSearchDescription());
            entry.setEnclosureUrl(entryData.getEnclosureUrl());
            WeblogCategory category = weblogCategoryRepository.findById(entryData.getCategory().getId())
                    .orElse(null);
            if (category != null) {
                entry.setCategory(category);
            } else {
                throw new IllegalArgumentException("Category is invalid.");
            }

            entry.setCommentDays(entryData.getCommentDays());

            if (!StringUtils.isEmpty(entry.getEnclosureUrl())) {
                // Fetch MediaCast resource
                log.debug("Checking MediaCast attributes");
                AtomEnclosure enclosure;

                try {
                    enclosure = weblogEntryManager.generateEnclosure(entry.getEnclosureUrl());
                } catch (IllegalArgumentException e) {
                    BindException be = new BindException(entry, "new data object");
                    be.addError(new ObjectError("Enclosure URL",
                            messages.getMessage(e.getMessage(), null, locale)));
                    return ResponseEntity.badRequest().body(ValidationError.fromBindingErrors(be));
                }

                // set enclosure attributes
                entry.setEnclosureUrl(enclosure.getUrl());
                entry.setEnclosureType(enclosure.getContentType());
                entry.setEnclosureLength(enclosure.getLength());
            }

            weblogEntryManager.saveWeblogEntry(entry);
            dp.updateLastSitewideChange();

            // notify search of the new entry
            if (entry.isPublished()) {
                luceneIndexer.updateIndex(entry, false);
            } else if (!createNew) {
                luceneIndexer.updateIndex(entry, true);
            }

            if (PubStatus.PENDING.equals(entry.getStatus())) {
                emailService.sendPendingEntryNotice(entry);
            }

            SuccessfulSaveResponse ssr = new SuccessfulSaveResponse();
            ssr.entryId = entry.getId();

            switch (entry.getStatus()) {
            case DRAFT:
                ssr.message = messages.getMessage("entryEdit.draftSaved", null, locale);
                break;
            case PUBLISHED:
                ssr.message = messages.getMessage("entryEdit.publishedEntry", null, locale);
                break;
            case SCHEDULED:
                ssr.message = messages.getMessage(
                        "entryEdit.scheduledEntry", new Object[] { DateTimeFormatter.ISO_DATE_TIME
                                .withZone(entry.getWeblog().getZoneId()).format(entry.getPubTime()) },
                        null, locale);
                break;
            case PENDING:
                ssr.message = messages.getMessage("entryEdit.submittedForReview", null, locale);
                break;
            default:
            }

            return ResponseEntity.ok(ssr);
        } else {
            return ResponseEntity.status(403).body(messages.getMessage("error.title.403", null, locale));
        }
    } catch (Exception e) {
        throw new ServletException(e.getMessage());
    }
}

From source file:sg.ncl.DataController.java

/**
 * References://from ww w  .  j a  v a  2  s .c om
 * [1] https://github.com/23/resumable.js/blob/master/samples/java/src/main/java/resumable/js/upload/UploadServlet.java
 */
@RequestMapping(value = "{datasetId}/resources/upload", method = RequestMethod.GET)
public ResponseEntity<String> checkChunk(@PathVariable String datasetId, HttpServletRequest request) {
    int resumableChunkNumber = getResumableChunkNumber(request);
    ResumableInfo info = getResumableInfo(request);

    String url = properties.checkUploadChunk(datasetId, resumableChunkNumber, info.resumableIdentifier);
    log.debug("URL: {}", url);
    HttpEntity<String> httpEntity = createHttpEntityHeaderOnly();
    ResponseEntity responseEntity = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);
    String body = responseEntity.getBody().toString();
    log.debug(body);
    if (body.equals("Not found")) {
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body(body);
    }
    return ResponseEntity.ok(body);
}

From source file:sg.ncl.DataController.java

@RequestMapping(value = "{datasetId}/resources/upload", method = RequestMethod.POST)
public ResponseEntity<String> uploadChunk(@PathVariable String datasetId, HttpServletRequest request) {
    int resumableChunkNumber = getResumableChunkNumber(request);
    ResumableInfo info = getResumableInfo(request);

    try {/*from w  w w .java 2  s . com*/
        InputStream is = request.getInputStream();
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        long readed = 0;
        long content_length = request.getContentLength();
        byte[] bytes = new byte[1024 * 100];
        while (readed < content_length) {
            int r = is.read(bytes);
            if (r < 0) {
                break;
            }
            os.write(bytes, 0, r);
            readed += r;
        }

        JSONObject resumableObject = new JSONObject();
        resumableObject.put("resumableChunkSize", info.resumableChunkSize);
        resumableObject.put("resumableTotalSize", info.resumableTotalSize);
        resumableObject.put("resumableIdentifier", info.resumableIdentifier);
        resumableObject.put("resumableFilename", info.resumableFilename);
        resumableObject.put("resumableRelativePath", info.resumableRelativePath);

        String resumableChunk = Base64.encodeBase64String(os.toByteArray());
        log.debug(resumableChunk);
        resumableObject.put("resumableChunk", resumableChunk);

        String url = properties.sendUploadChunk(datasetId, resumableChunkNumber);
        log.debug("URL: {}", url);
        HttpEntity<String> httpEntity = createHttpEntityWithBody(resumableObject.toString());
        restTemplate.setErrorHandler(new MyResponseErrorHandler());
        ResponseEntity responseEntity = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
        String body = responseEntity.getBody().toString();

        if (RestUtil.isError(responseEntity.getStatusCode())) {
            MyErrorResource error = objectMapper.readValue(body, MyErrorResource.class);
            ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());

            return getStringResponseEntity(exceptionState);
        } else if (body.equals("All finished.")) {
            log.info("Data resource uploaded.");
        }
        return ResponseEntity.ok(body);
    } catch (Exception e) {
        log.error("Error sending upload chunk: {}", e);
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error sending upload chunk");
    }
}

From source file:sg.ncl.DataController.java

private ResponseEntity<String> getStringResponseEntity(ExceptionState exceptionState) {
    switch (exceptionState) {
    case DATA_NOT_FOUND_EXCEPTION:
        log.warn("Dataset not found for uploading resource.");
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Dataset not found for uploading resource.");
    case DATA_RESOURCE_ALREADY_EXISTS_EXCEPTION:
        log.warn("Data resource already exist.");
        return ResponseEntity.status(HttpStatus.CONFLICT).body("Data resource already exist");
    case FORBIDDEN_EXCEPTION:
        log.warn("Uploading of dataset resource forbidden.");
        return ResponseEntity.status(HttpStatus.FORBIDDEN).body("Uploading of dataset resource forbidden.");
    case UPLOAD_ALREADY_EXISTS_EXCEPTION:
        log.warn("Upload of data resource already exist.");
        return ResponseEntity.status(HttpStatus.CONFLICT).body("Upload of data resource already exist.");
    default:/*from   ww  w  . ja va  2s .  c  o m*/
        log.warn("Unknown exception while uploading resource.");
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body("Unknown exception while uploading resource.");
    }
}