Example usage for org.springframework.http HttpStatus NOT_ACCEPTABLE

List of usage examples for org.springframework.http HttpStatus NOT_ACCEPTABLE

Introduction

In this page you can find the example usage for org.springframework.http HttpStatus NOT_ACCEPTABLE.

Prototype

HttpStatus NOT_ACCEPTABLE

To view the source code for org.springframework.http HttpStatus NOT_ACCEPTABLE.

Click Source Link

Document

406 Not Acceptable .

Usage

From source file:com.sms.server.controller.AdminController.java

@RequestMapping(value = "/media/folder", method = RequestMethod.POST, headers = {
        "Content-type=application/json" })
@ResponseBody/*from  w ww  .java2  s  . c om*/
public ResponseEntity<String> createMediaFolder(@RequestBody MediaFolder mediaFolder) {
    // Check mandatory fields.
    if (mediaFolder.getName() == null || mediaFolder.getType() == null || mediaFolder.getPath() == null) {
        return new ResponseEntity<>("Missing required parameter.", HttpStatus.BAD_REQUEST);
    }

    // Check unique fields
    if (settingsDao.getMediaFolderByPath(mediaFolder.getPath()) != null) {
        return new ResponseEntity<>("Media folder path already exists.", HttpStatus.NOT_ACCEPTABLE);
    }

    // Check path is readable
    if (!new File(mediaFolder.getPath()).isDirectory()) {
        return new ResponseEntity<>("Media folder path does not exist or is not readable.",
                HttpStatus.FAILED_DEPENDENCY);
    }

    // Add Media Folder to the database.
    if (!settingsDao.createMediaFolder(mediaFolder)) {
        LogService.getInstance().addLogEntry(Level.ERROR, CLASS_NAME,
                "Error adding media folder with path '" + mediaFolder.getPath() + "' to database.", null);
        return new ResponseEntity<>("Error adding media folder to database.", HttpStatus.INTERNAL_SERVER_ERROR);
    }

    LogService.getInstance().addLogEntry(Level.INFO, CLASS_NAME,
            "Media folder with path '" + mediaFolder.getPath() + "' added successfully.", null);
    return new ResponseEntity<>("Media Folder added successfully.", HttpStatus.CREATED);
}

From source file:hr.softwarecity.osijek.controllers.PersonController.java

/**
 * Method for user image upload//w ww  .  j av a 2  s.co m
 * @param id
 * @param file
 * @return HTTP OK or HTTP
 */
@RequestMapping(value = "/{id}/image", method = RequestMethod.POST)
public ResponseEntity<HashMap<String, String>> setUserImage(@PathVariable("id") long id,
        @RequestParam("file") MultipartFile file) {
    String path = null;
    try {
        path = Multimedia.handleFileUpload("/var/www/html/app/img", file);
    } catch (IOException ex) {
        Logger.getLogger("PersonController.java").log(Logger.Level.ERROR,
                "File failed to upload, cannot write to path");
    }
    if (path != null) {
        path = "/app/img/" + file.getOriginalFilename();
        Person person = personRepository.findById(id);
        person.setImage(path);
        personRepository.save(person);
        Logger.getLogger("PersonController.java").log(Logger.Level.INFO, "New user image saved");
        HashMap<String, String> map = new HashMap<>();
        map.put("path", path);
        return new ResponseEntity<>(map, HttpStatus.OK);
    } else {
        return new ResponseEntity<>(HttpStatus.NOT_ACCEPTABLE);
    }
}

From source file:org.spring.data.gemfire.rest.GemFireRestInterfaceTest.java

@SuppressWarnings("deprecation")
private RestTemplate setErrorHandler(final RestTemplate restTemplate) {
    restTemplate.setErrorHandler(new ResponseErrorHandler() {
        private final Set<HttpStatus> errorStatuses = new HashSet<>();

        /* non-static */ {
            errorStatuses.add(HttpStatus.BAD_REQUEST);
            errorStatuses.add(HttpStatus.UNAUTHORIZED);
            errorStatuses.add(HttpStatus.FORBIDDEN);
            errorStatuses.add(HttpStatus.NOT_FOUND);
            errorStatuses.add(HttpStatus.METHOD_NOT_ALLOWED);
            errorStatuses.add(HttpStatus.NOT_ACCEPTABLE);
            errorStatuses.add(HttpStatus.REQUEST_TIMEOUT);
            errorStatuses.add(HttpStatus.CONFLICT);
            errorStatuses.add(HttpStatus.REQUEST_ENTITY_TOO_LARGE);
            errorStatuses.add(HttpStatus.REQUEST_URI_TOO_LONG);
            errorStatuses.add(HttpStatus.UNSUPPORTED_MEDIA_TYPE);
            errorStatuses.add(HttpStatus.TOO_MANY_REQUESTS);
            errorStatuses.add(HttpStatus.INTERNAL_SERVER_ERROR);
            errorStatuses.add(HttpStatus.NOT_IMPLEMENTED);
            errorStatuses.add(HttpStatus.BAD_GATEWAY);
            errorStatuses.add(HttpStatus.SERVICE_UNAVAILABLE);
        }/*from   w w  w .  j a v  a  2s  .  c om*/

        @Override
        public boolean hasError(final ClientHttpResponse response) throws IOException {
            return errorStatuses.contains(response.getStatusCode());
        }

        @Override
        public void handleError(final ClientHttpResponse response) throws IOException {
            System.err.printf("%1$d - %2$s%n", response.getRawStatusCode(), response.getStatusText());
            System.err.println(readBody(response));
        }

        private String readBody(final ClientHttpResponse response) throws IOException {
            BufferedReader responseBodyReader = null;

            try {
                responseBodyReader = new BufferedReader(new InputStreamReader(response.getBody()));

                StringBuilder buffer = new StringBuilder();
                String line;

                while ((line = responseBodyReader.readLine()) != null) {
                    buffer.append(line).append(System.getProperty("line.separator"));
                }

                return buffer.toString().trim();
            } finally {
                FileSystemUtils.close(responseBodyReader);
            }
        }
    });

    return restTemplate;
}

From source file:com.sms.server.controller.AdminController.java

@RequestMapping(value = "/media/folder", method = RequestMethod.PUT, headers = {
        "Content-type=application/json" })
@ResponseBody//from  www  . j a v  a 2s.  co  m
public ResponseEntity<String> updateMediaFolder(@RequestBody MediaFolder update) {
    MediaFolder mediaFolder = settingsDao.getMediaFolderByID(update.getID());

    if (mediaFolder == null) {
        return new ResponseEntity<>("Media folder does not exist.", HttpStatus.BAD_REQUEST);
    }

    if (update.getName() != null) {
        mediaFolder.setName(update.getName());
    }

    if (update.getType() != null) {
        mediaFolder.setType(update.getType());
    }

    if (update.getPath() != null) {
        // Check unique fields
        if (settingsDao.getMediaFolderByPath(update.getPath()) != null) {
            return new ResponseEntity<>("New media folder path already exists.", HttpStatus.NOT_ACCEPTABLE);
        }

        // Check path is readable
        if (!new File(update.getPath()).isDirectory()) {
            return new ResponseEntity<>("New media folder path does not exist or is not readable.",
                    HttpStatus.FAILED_DEPENDENCY);
        }

        mediaFolder.setPath(update.getPath());
    }

    if (update.getEnabled() != null) {
        mediaFolder.setEnabled(update.getEnabled());
    }

    // Update database
    if (!settingsDao.updateMediaFolder(mediaFolder)) {
        LogService.getInstance().addLogEntry(Level.ERROR, CLASS_NAME,
                "Error updating media folder with ID '" + mediaFolder.getID() + "'.", null);
        return new ResponseEntity<>("Error updating media folder.", HttpStatus.INTERNAL_SERVER_ERROR);
    }

    LogService.getInstance().addLogEntry(Level.INFO, CLASS_NAME,
            "Media folder with ID '" + mediaFolder.getID() + "' updated successfully.", null);
    return new ResponseEntity<>("Media folder updated successfully.", HttpStatus.ACCEPTED);
}

From source file:com.sms.server.controller.AdminController.java

@RequestMapping(value = "/media/scan", method = RequestMethod.GET)
public ResponseEntity<String> scanMedia() {
    if (mediaScannerService.isScanning()) {
        return new ResponseEntity<>("Media is already being scanned.", HttpStatus.NOT_ACCEPTABLE);
    }//from  w w w. j a  v  a 2  s . c  om

    // Start scanning media
    mediaScannerService.startScanning();

    return new ResponseEntity<>("Media scanning started.", HttpStatus.OK);
}

From source file:com.athena.peacock.controller.common.component.RHEVMRestTemplate.java

/**
 * <pre>/*from w  w  w .ja v  a2s .c om*/
 * RHEV Manager  API   .
 * </pre>
 * @param api RHEV Manager API (/api, /api/vms )
 * @param body xml contents
 * @param clazz ? Target Object Class
 * @return
 * @throws RestClientException
 * @throws Exception
 */
public synchronized <T> T submit(String api, HttpMethod method, Object body, String rootElementName,
        Class<T> clazz) throws RestClientException, Exception {
    Assert.isTrue(StringUtils.isNotEmpty(api), "api must not be null");
    Assert.notNull(clazz, "clazz must not be null.");

    // Multi RHEV Manager        ? ?? HostnameVerifier ??,
    // ??    ? ?.(java.io.IOException: HTTPS hostname wrong:  should be <{host}>)
    //init();

    try {
        RestTemplate rt = new RestTemplate();

        ResponseEntity<?> response = rt.exchange(new URI(getUrl(api)), method,
                setHTTPEntity(body, rootElementName), clazz);

        logger.debug("[Request URL] : {}", getUrl(api));
        logger.debug("[Response] : {}", response);

        if (response.getStatusCode().equals(HttpStatus.BAD_REQUEST)
                || response.getStatusCode().equals(HttpStatus.UNAUTHORIZED)
                || response.getStatusCode().equals(HttpStatus.PAYMENT_REQUIRED)
                || response.getStatusCode().equals(HttpStatus.FORBIDDEN)
                || response.getStatusCode().equals(HttpStatus.METHOD_NOT_ALLOWED)
                || response.getStatusCode().equals(HttpStatus.NOT_ACCEPTABLE)
                || response.getStatusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR)
                || response.getStatusCode().equals(HttpStatus.NOT_IMPLEMENTED)
                || response.getStatusCode().equals(HttpStatus.BAD_GATEWAY)
                || response.getStatusCode().equals(HttpStatus.SERVICE_UNAVAILABLE)
                || response.getStatusCode().equals(HttpStatus.GATEWAY_TIMEOUT)) {
            throw new Exception(response.getStatusCode().value() + " " + response.getStatusCode().toString());
        }

        return clazz.cast(response.getBody());
    } catch (RestClientException e) {
        logger.error("RestClientException has occurred.", e);
        throw e;
    } catch (Exception e) {
        logger.error("Unhandled Exception has occurred.", e);
        throw e;
    }
}

From source file:net.navasoft.madcoin.backend.services.controller.WorkRequestController.java

@ExceptionHandler(AlreadyAcceptedException.class)
@ResponseStatus(value = HttpStatus.NOT_ACCEPTABLE)
private @ResponseBody FailedResponseVO handleAlreadyAccepted(AlreadyAcceptedException e) {
    FailedResponseVO value = new BusinessFailedResponseVO();
    value.setErrorMessage(e.getMessage());
    value.setCauses("La orden fue aceptada por otro proveedor antes de que ud la aceptara.");
    String tips[] = new String[] { "Solicite la asignacion manual de ordenes a su usuario proveedor",
            "Comuniquese con un administrador si desea que se le asignen manualmente las ordenes." };
    value.setTip(tips);/* w  ww  .j av  a  2  s .  c om*/
    return value;
}

From source file:ph.fingra.statisticsweb.controller.ComponentsController.java

@ExceptionHandler(Exception.class)
@ResponseStatus(value = HttpStatus.NOT_ACCEPTABLE, reason = "Invalid Component/Component Group Name")
public @ResponseBody String handleAllExceptions(Exception ex) {
    Map<String, String> model = new HashMap<String, String>();
    model.put("error", ex.getMessage());
    return (new Gson()).toJson(model);
}

From source file:com.orange.ngsi2.server.Ngsi2BaseController.java

@ExceptionHandler({ NotAcceptableException.class })
public ResponseEntity<Object> notAcceptable(NotAcceptableException exception, HttpServletRequest request) {
    logger.error("Not Acceptable: {}", exception.getMessage());
    HttpStatus httpStatus = HttpStatus.NOT_ACCEPTABLE;
    if (request.getHeader("Accept").contains(MediaType.TEXT_PLAIN_VALUE)) {
        return new ResponseEntity<>(exception.getError().toString(), httpStatus);
    }/*from w w  w .ja  va 2s.c om*/
    return new ResponseEntity<>(exception.getError(), httpStatus);
}

From source file:com.scooter1556.sms.server.controller.MediaController.java

@RequestMapping(value = "/{id}/contents", method = RequestMethod.GET)
public ResponseEntity<List<MediaElement>> getMediaElementsByID(@PathVariable("id") UUID id) {
    MediaElement element = mediaDao.getMediaElementByID(id);

    if (element == null) {
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }//from  ww  w  .j  a v a2s .c  o  m

    String parentPath;
    Byte type = element.getType();

    switch (element.getType()) {
    case MediaElementType.DIRECTORY:
        parentPath = element.getPath();
        type = null;
        break;

    case MediaElementType.AUDIO:
    case MediaElementType.VIDEO:
        parentPath = element.getParentPath();
        break;

    default:
        return new ResponseEntity<>(HttpStatus.NOT_ACCEPTABLE);
    }

    List<MediaElement> mediaElements = mediaDao.getMediaElementsByParentPath(parentPath, type);

    if (mediaElements == null) {
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    return new ResponseEntity<>(mediaElements, HttpStatus.OK);
}