Example usage for org.springframework.http MediaType valueOf

List of usage examples for org.springframework.http MediaType valueOf

Introduction

In this page you can find the example usage for org.springframework.http MediaType valueOf.

Prototype

public static MediaType valueOf(String value) 

Source Link

Document

Parse the given String value into a MediaType object, with this method name following the 'valueOf' naming convention (as supported by org.springframework.core.convert.ConversionService .

Usage

From source file:org.ff4j.spring.boot.resources.AbstractStepDef.java

protected void constructRequestBuilder(String path, String httpMethod, String contentType) {
    switch (HttpMethod.getHttpMethod(httpMethod)) {
    case GET:/*  w ww  . ja v a  2 s. co  m*/
        requestBuilder = MockMvcRequestBuilders.get(path).contentType(MediaType.valueOf(contentType));
        break;
    case PUT:
        requestBuilder = MockMvcRequestBuilders.put(path).contentType(MediaType.valueOf(contentType));
        break;
    case DELETE:
        requestBuilder = MockMvcRequestBuilders.delete(path).contentType(MediaType.valueOf(contentType));
        break;
    case POST:
        requestBuilder = MockMvcRequestBuilders.post(path).contentType(MediaType.valueOf(contentType));
        break;
    default:
        throw new AssertionError("http method not found");
    }
}

From source file:com.fredhopper.core.connector.index.upload.impl.RestPublishingStrategy.java

@Override
public String uploadDataSet(final InstanceConfig config, final File file) throws ResponseStatusException {
    Preconditions.checkArgument(config != null);
    Preconditions.checkArgument(file != null);

    final RestTemplate restTemplate = restTemplateProvider.createTemplate(config.getHost(), config.getPort(),
            config.getUsername(), config.getPassword());
    final String checkSum = createCheckSum(file);

    final List<NameValuePair> params = Arrays
            .asList(new NameValuePair[] { new BasicNameValuePair("checksum", checkSum) });
    final URI url = createUri(config.getScheme(), config.getHost(), config.getPort(), config.getServername(),
            UPLOAD_PATH, params);/*w  w  w .ja  v  a  2 s.  c o m*/

    final HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.valueOf("application/zip"));
    final HttpEntity<Resource> httpEntity = new HttpEntity<>(new FileSystemResource(file), headers);

    final ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.PUT, httpEntity,
            String.class);

    final HttpStatus status = response.getStatusCode();
    if (status.equals(HttpStatus.CREATED)) {
        return response.getBody().trim();
    } else {
        throw new ResponseStatusException(
                "HttpStatus " + status.toString() + " response received. File upload failed.");
    }
}

From source file:com.github.alexfalappa.nbspringboot.projects.initializr.InitializrService.java

public JsonNode getMetadata() throws Exception {
    if (metadata == null) {
        // set connection timeouts
        timeoutFromPrefs();/*from   w  w  w .j  av a2  s  .  co  m*/
        // prepare request
        final String serviceUrl = NbPreferences.forModule(PrefConstants.class).get(PREF_INITIALIZR_URL,
                "http://start.spring.io");
        RequestEntity<Void> req = RequestEntity.get(new URI(serviceUrl))
                .accept(MediaType.valueOf("application/vnd.initializr.v2.1+json"))
                .header("User-Agent", REST_USER_AGENT).build();
        // connect
        logger.log(INFO, "Getting Spring Initializr metadata from: {0}", serviceUrl);
        logger.log(INFO, "Asking metadata as: {0}", REST_USER_AGENT);
        long start = System.currentTimeMillis();
        ResponseEntity<String> respEntity = rt.exchange(req, String.class);
        // analyze response
        final HttpStatus statusCode = respEntity.getStatusCode();
        if (statusCode == OK) {
            ObjectMapper mapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
            metadata = mapper.readTree(respEntity.getBody());
            logger.log(INFO, "Retrieved Spring Initializr service metadata. Took {0} msec",
                    System.currentTimeMillis() - start);
            if (logger.isLoggable(FINE)) {
                logger.fine(mapper.writeValueAsString(metadata));
            }
        } else {
            // log status code
            final String errMessage = String.format(
                    "Spring initializr service connection problem. HTTP status code: %s",
                    statusCode.toString());
            logger.severe(errMessage);
            // throw exception in order to set error message
            throw new RuntimeException(errMessage);
        }
    }
    return metadata;
}

From source file:ca.intelliware.ihtsdo.mlds.web.rest.MemberResource.java

private ResponseEntity<?> downloadFile(HttpServletRequest request, File file) throws SQLException, IOException {
    if (file == null) {
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    } else if (file.getLastUpdated() != null) {
        long ifModifiedSince = request.getDateHeader("If-Modified-Since");
        long lastUpdatedSecondsFloor = file.getLastUpdated().getMillis() / 1000 * 1000;
        if (ifModifiedSince != -1 && lastUpdatedSecondsFloor <= ifModifiedSince) {
            return new ResponseEntity<>(HttpStatus.NOT_MODIFIED);
        }/* ww w  . j a v  a2 s .  com*/
    }

    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setContentType(MediaType.valueOf(file.getMimetype()));
    httpHeaders.setContentLength(file.getContent().length());
    httpHeaders.setContentDispositionFormData("file", file.getFilename());
    if (file.getLastUpdated() != null) {
        httpHeaders.setLastModified(file.getLastUpdated().getMillis());
    }

    byte[] byteArray = IOUtils.toByteArray(file.getContent().getBinaryStream());
    org.springframework.core.io.Resource contents = new ByteArrayResource(byteArray);
    return new ResponseEntity<org.springframework.core.io.Resource>(contents, httpHeaders, HttpStatus.OK);
}

From source file:business.services.FileService.java

public File uploadPart(User user, String name, File.AttachmentType type, MultipartFile file, Integer chunk,
        Integer chunks, String flowIdentifier) {
    try {//  w  w w .  j  ava 2  s.c om
        String identifier = user.getId().toString() + "_" + flowIdentifier;
        String contentType = MediaType.APPLICATION_OCTET_STREAM_VALUE;
        log.info("File content-type: " + file.getContentType());
        try {
            contentType = MediaType.valueOf(file.getContentType()).toString();
            log.info("Media type: " + contentType);
        } catch (InvalidMediaTypeException e) {
            log.warn("Invalid content type: " + e.getMediaType());
            //throw new FileUploadError("Invalid content type: " + e.getMediaType());
        }
        InputStream input = file.getInputStream();

        // Create temporary file for chunk
        Path path = fileSystem.getPath(uploadPath).normalize();
        if (!path.toFile().exists()) {
            Files.createDirectory(path);
        }
        name = URLEncoder.encode(name, "utf-8");

        String prefix = getBasename(name);
        String suffix = getExtension(name);
        Path f = Files.createTempFile(path, prefix, suffix + "." + chunk + ".chunk").normalize();
        // filter path names that point to places outside the upload path.
        // E.g., to prevent that in cases where clients use '../' in the filename
        // arbitrary locations are reachable.
        if (!Files.isSameFile(path, f.getParent())) {
            // Path f is not in the upload path. Maybe 'name' contains '..'?
            throw new FileUploadError("Invalid file name");
        }
        log.info("Copying file to " + f.toString());

        // Copy chunk to temporary file
        Files.copy(input, f, StandardCopyOption.REPLACE_EXISTING);

        // Save chunk location in chunk map
        SortedMap<Integer, Path> chunkMap;
        synchronized (uploadChunks) {
            // FIXME: perhaps use a better identifier? Not sure if this one 
            // is unique enough...
            chunkMap = uploadChunks.get(identifier);
            if (chunkMap == null) {
                chunkMap = new TreeMap<Integer, Path>();
                uploadChunks.put(identifier, chunkMap);
            }
        }
        chunkMap.put(chunk, f);
        log.info("Chunk " + chunk + " saved to " + f.toString());

        // Assemble complete file if all chunks have been received
        if (chunkMap.size() == chunks.intValue()) {
            uploadChunks.remove(identifier);
            Path assembly = Files.createTempFile(path, prefix, suffix).normalize();
            // filter path names that point to places outside the upload path.
            // E.g., to prevent that in cases where clients use '../' in the filename
            // arbitrary locations are reachable.
            if (!Files.isSameFile(path, assembly.getParent())) {
                // Path assembly is not in the upload path. Maybe 'name' contains '..'?
                throw new FileUploadError("Invalid file name");
            }
            log.info("Assembling file " + assembly.toString() + " from " + chunks + " chunks...");
            OutputStream out = Files.newOutputStream(assembly, StandardOpenOption.CREATE,
                    StandardOpenOption.APPEND);

            // Copy chunks to assembly file, delete chunk files
            for (int i = 1; i <= chunks; i++) {
                //log.info("Copying chunk " + i + "...");
                Path source = chunkMap.get(new Integer(i));
                if (source == null) {
                    log.error("Cannot find chunk " + i);
                    throw new FileUploadError("Cannot find chunk " + i);
                }
                Files.copy(source, out);
                Files.delete(source);
            }

            // Save assembled file name to database
            log.info("Saving attachment to database...");
            File attachment = new File();
            attachment.setName(URLDecoder.decode(name, "utf-8"));
            attachment.setType(type);
            attachment.setMimeType(contentType);
            attachment.setDate(new Date());
            attachment.setUploader(user);
            attachment.setFilename(assembly.getFileName().toString());
            attachment = fileRepository.save(attachment);
            return attachment;
        }
        return null;
    } catch (IOException e) {
        log.error(e);
        throw new FileUploadError(e.getMessage());
    }
}

From source file:org.devefx.httpmapper.binding.MapperMethod.java

@SuppressWarnings("unchecked")
public Object execute(RestTemplate restTemplate, Object[] args) throws Exception {
    Object result = null;//w ww  .  j  a va  2  s  .com

    do {
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.valueOf(command.getContentType()));

        Map<String, Object> paramMap = null;
        Object param = method.convertArgsToCommandParam(args);
        if (param instanceof Map) {
            paramMap = (Map<String, Object>) param;
            body.setAll(paramMap);
        }

        URI uri = expandURI(command.getUrl(), args);

        RequestEntity requestEntity = new RequestEntity(body, headers, command.getHttpMethod(), uri,
                method.getReturnType());

        mappedHandler.onRequest(requestEntity);

        // FIXME: application/x-www-form-urlencoded
        if (headers.getContentType().includes(MediaType.APPLICATION_FORM_URLENCODED)) {
            if (paramMap != null) {
                for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
                    Object value = entry.getValue();
                    if (value != null && !ReflectUtils.isUserType(value)) {
                        entry.setValue(String.valueOf(value));
                    }
                }
                body.setAll(paramMap);
            } else if (param != null && ReflectUtils.isUserType(param)) {
                body.setAll(mapper.<Map<String, Object>>convertValue(param, mapType));
            }
        }

        if (requestEntity.getMethod() == HttpMethod.GET) {
            uri = appendUrlParams(requestEntity.getUrl(), body);
            requestEntity.setUrl(uri);
        }

        if (logger.isInfoEnabled()) {
            String preStr = command.getName() + " ====> ";
            logger.info(preStr + "Request: " + requestEntity.getUrl());
            logger.info(preStr + "Parameters: " + requestEntity.getBody());
            logger.info(preStr + "Headers: " + requestEntity.getHeaders());
        }

        ResponseEntity<JsonNode> responseEntity = restTemplate.exchange(requestEntity.getUrl(),
                requestEntity.getMethod(),
                new HttpEntity<>(requestEntity.getBody(), requestEntity.getHeaders()), JsonNode.class);

        if (logger.isInfoEnabled()) {
            StringBuffer buf = new StringBuffer();
            buf.append(command.getName() + " ====> ");
            buf.append("Response: [status=").append(responseEntity.getStatusCode()).append("] ");
            if (responseEntity.hasBody()) {
                buf.append(responseEntity.getBody());
            }
            logger.info(buf.toString());
        }

        if (responseEntity != null) {
            org.devefx.httpmapper.http.ResponseEntity entity = new org.devefx.httpmapper.http.ResponseEntity(
                    responseEntity.getBody(), responseEntity.getHeaders(), responseEntity.getStatusCode());

            mappedHandler.onResponse(requestEntity, entity);

            if (entity.hasBody()) {
                Object responseBody = entity.getBody();
                if (method.getRawType().isInstance(responseBody)) {
                    result = responseBody;
                    break;
                }

                JavaType valueType = mapper.getTypeFactory().constructType(method.getReturnType());
                if (responseBody instanceof String) {
                    result = mapper.readValue((String) responseBody, valueType);
                } else {
                    result = mapper.convertValue(responseBody, valueType);
                }
            }
        }

    } while (false);

    if (result == null && method.returnsPrimitive() && !method.returnsVoid()) {
        throw new BindingException("Mapper method '" + command.getUrl()
                + " attempted to return null from a method with a primitive return type ("
                + method.getReturnType() + ").");
    }
    return result;
}

From source file:jp.go.aist.six.util.core.web.spring.SpringHttpClientImpl.java

/**
 */
public void setObjectMediaType(final String media_type) {
    _object_media_type = MediaType.valueOf(media_type);
}

From source file:business.services.PaNumberService.java

public HttpEntity<InputStreamResource> writeAllPaNumbers(List<LabRequestRepresentation> labRequests)
        throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    Writer writer = new OutputStreamWriter(out, PA_NUMBERS_DOWNLOAD_CHARACTER_ENCODING);
    CSVWriter csvwriter = new CSVWriter(writer, ',', '"');
    csvwriter.writeNext(PA_NUMBERS_HEADER);
    for (LabRequestRepresentation labRequest : labRequests) {
        String labRequestCode = labRequest.getLabRequestCode();
        String status = labRequest.getStatus().toString();
        String labName = labRequest.getLab().getName();
        String requesterName = labRequest.getRequesterName();
        String requesterEmail = labRequest.getRequesterEmail();
        String requesterTelephone = labRequest.getRequesterTelephone();
        String labRequestSentDate = labRequest.getSendDate() == null ? "" : labRequest.getSendDate().toString();
        for (PathologyRepresentation item : labRequest.getPathologyList()) {
            csvwriter.writeNext(new String[] { labRequestCode, status, item.getPaNumber(), labName,
                    requesterName, requesterEmail, requesterTelephone, labRequestSentDate });
        }/*  www .  j  av  a 2s .  c  o  m*/
    }
    csvwriter.flush();
    writer.flush();
    out.flush();
    InputStream in = new ByteArrayInputStream(out.toByteArray());
    csvwriter.close();
    writer.close();
    out.close();
    InputStreamResource resource = new InputStreamResource(in);
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.valueOf("text/csv;charset=" + PA_NUMBERS_DOWNLOAD_CHARACTER_ENCODING));
    String filename = "pa_numbers.csv";
    headers.set("Content-Disposition", "attachment; filename=" + filename);
    HttpEntity<InputStreamResource> response = new HttpEntity<InputStreamResource>(resource, headers);
    return response;
}

From source file:com.btmatthews.leabharlann.view.FileContentMessageConverter.java

/**
 * Set the HTTP headers on the servlet response and stream the file contents to the servlet response's output stream.
 *
 * @param fileContent   Describes the file content.
 * @param outputMessage Used to access the servlet response headers and output stream.
 * @throws IOException                     If there was an error streaming the file content.
 * @throws HttpMessageNotWritableException If there was problem retrieving the file content from the Java Content Repository.
 *//*  w  w w . j av a 2  s  . c om*/
@Override
protected void writeInternal(final FileContent fileContent, final HttpOutputMessage outputMessage)
        throws IOException, HttpMessageNotWritableException {
    try {
        jcrAccessor.withNodeId(fileContent.getWorkspace(), fileContent.getId(), new NodeCallback() {
            @Override
            public Object doInSessionWithNode(Session session, Node node) throws Exception {
                final Node resourceNode = node.getNode(Node.JCR_CONTENT);
                final String mimeType = jcrAccessor.getStringProperty(resourceNode, Property.JCR_MIMETYPE);
                final Calendar lastModified = jcrAccessor.getCalendarProperty(resourceNode,
                        Property.JCR_LAST_MODIFIED);
                final Binary data = jcrAccessor.getBinaryProperty(resourceNode, Property.JCR_DATA);
                if (jcrAccessor.hasProperty(resourceNode, Property.JCR_ENCODING)) {
                    final String encoding = jcrAccessor.getStringProperty(resourceNode, Property.JCR_ENCODING);
                    outputMessage.getHeaders().setContentType(new MediaType(MediaType.valueOf(mimeType),
                            Collections.singletonMap("charset", encoding)));
                } else {
                    outputMessage.getHeaders().setContentType(MediaType.valueOf(mimeType));
                }
                outputMessage.getHeaders().setContentLength(data.getSize());
                if (lastModified != null) {
                    outputMessage.getHeaders().setLastModified(lastModified.getTimeInMillis());
                }
                outputMessage.getHeaders().set("Content-Disposition", "attachment;filename=" + node.getName());
                IOUtils.copy(data.getStream(), outputMessage.getBody());
                return null;
            }
        });
    } catch (final RepositoryAccessException e) {
        throw new HttpMessageNotWritableException(e.getLocalizedMessage());
    }
}

From source file:com.github.alexfalappa.nbspringboot.projects.initializr.InitializrService.java

public JsonNode getDependencies(String bootVersion) throws Exception {
    if (!dependencyMetaMap.containsKey(bootVersion)) {
        // set connection timeouts
        timeoutFromPrefs();//from w  w w  .java2  s . c  o  m
        // prepare request
        final String serviceUrl = NbPreferences.forModule(PrefConstants.class).get(PREF_INITIALIZR_URL,
                "http://start.spring.io");
        UriTemplate template = new UriTemplate(serviceUrl.concat("/dependencies?{bootVersion}"));
        RequestEntity<Void> req = RequestEntity.get(template.expand(bootVersion))
                .accept(MediaType.valueOf("application/vnd.initializr.v2.1+json"))
                .header("User-Agent", REST_USER_AGENT).build();
        // connect
        logger.log(INFO, "Getting Spring Initializr dependencies metadata from: {0}", template);
        logger.log(INFO, "Asking metadata as: {0}", REST_USER_AGENT);
        long start = System.currentTimeMillis();
        ResponseEntity<String> respEntity = rt.exchange(req, String.class);
        // analyze response
        final HttpStatus statusCode = respEntity.getStatusCode();
        if (statusCode == OK) {
            ObjectMapper mapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
            final JsonNode depMeta = mapper.readTree(respEntity.getBody());
            logger.log(INFO,
                    "Retrieved Spring Initializr dependencies metadata for boot version {0}. Took {1} msec",
                    new Object[] { bootVersion, System.currentTimeMillis() - start });
            if (logger.isLoggable(FINE)) {
                logger.fine(mapper.writeValueAsString(depMeta));
            }
            dependencyMetaMap.put(bootVersion, depMeta);
        } else {
            // log status code
            final String errMessage = String.format(
                    "Spring initializr service connection problem. HTTP status code: %s",
                    statusCode.toString());
            logger.severe(errMessage);
            // throw exception in order to set error message
            throw new RuntimeException(errMessage);
        }
    }
    return dependencyMetaMap.get(bootVersion);
}