Search in sources :

Example 91 with MediaType

use of org.springframework.http.MediaType in project nextprot-api by calipho-sib.

the class EntryAccessionController method writeEntries.

private void writeEntries(Collection<String> entries, NextprotMediaType mediaType, HttpServletResponse response) throws IOException {
    if (mediaType == NextprotMediaType.JSON) {
        JSONObjectsWriter<String> writer = new JSONObjectsWriter<>(response.getOutputStream());
        writer.write(entries);
    } else if (mediaType == NextprotMediaType.TXT) {
        PrintWriter writer = new PrintWriter(response.getOutputStream());
        entries.forEach(entryAccession -> {
            writer.write(entryAccession);
            writer.write("\n");
        });
        writer.close();
    }
}
Also used : PrintWriter(java.io.PrintWriter) ApiVerb(org.jsondoc.core.pojo.ApiVerb) PathVariable(org.springframework.web.bind.annotation.PathVariable) RequestParam(org.springframework.web.bind.annotation.RequestParam) MediaType(org.springframework.http.MediaType) Collection(java.util.Collection) HttpServletResponse(javax.servlet.http.HttpServletResponse) NextProtException(org.nextprot.api.commons.exception.NextProtException) Autowired(org.springframework.beans.factory.annotation.Autowired) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) RequestMethod(org.springframework.web.bind.annotation.RequestMethod) IOException(java.io.IOException) Controller(org.springframework.stereotype.Controller) NextprotMediaType(org.nextprot.api.core.service.export.format.NextprotMediaType) ApiQueryParam(org.jsondoc.core.annotation.ApiQueryParam) ProteinExistence(org.nextprot.api.core.domain.ProteinExistence) HttpServletRequest(javax.servlet.http.HttpServletRequest) ApiMethod(org.jsondoc.core.annotation.ApiMethod) JSONObjectsWriter(org.nextprot.api.web.service.impl.writer.JSONObjectsWriter) Api(org.jsondoc.core.annotation.Api) MasterIdentifierService(org.nextprot.api.core.service.MasterIdentifierService) ApiPathParam(org.jsondoc.core.annotation.ApiPathParam) JSONObjectsWriter(org.nextprot.api.web.service.impl.writer.JSONObjectsWriter) PrintWriter(java.io.PrintWriter)

Example 92 with MediaType

use of org.springframework.http.MediaType in project ma-modules-public by infiniteautomation.

the class FileStoreRestV2Controller method listStoreContents.

protected ResponseEntity<List<FileModel>> listStoreContents(File directory, File root, HttpServletRequest request) throws IOException {
    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
    if (directory.equals(root) && !root.exists())
        return new ResponseEntity<>(Collections.emptyList(), responseHeaders, HttpStatus.OK);
    if (!directory.exists()) {
        throw new ResourceNotFoundException(relativePath(root, directory));
    }
    Collection<File> files = Arrays.asList(directory.listFiles());
    List<FileModel> found = new ArrayList<>(files.size());
    for (File file : files) found.add(fileToModel(file, root, request.getServletContext()));
    Set<MediaType> mediaTypes = Sets.newHashSet(MediaType.APPLICATION_JSON_UTF8);
    request.setAttribute(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE, mediaTypes);
    return new ResponseEntity<>(found, responseHeaders, HttpStatus.OK);
}
Also used : FileModel(com.infiniteautomation.mango.rest.v2.model.filestore.FileModel) HttpHeaders(org.springframework.http.HttpHeaders) ResponseEntity(org.springframework.http.ResponseEntity) ArrayList(java.util.ArrayList) MediaType(org.springframework.http.MediaType) ResourceNotFoundException(com.infiniteautomation.mango.rest.v2.exception.ResourceNotFoundException) File(java.io.File) CommonsMultipartFile(org.springframework.web.multipart.commons.CommonsMultipartFile) MultipartFile(org.springframework.web.multipart.MultipartFile)

Example 93 with MediaType

use of org.springframework.http.MediaType in project ma-modules-public by infiniteautomation.

the class FileStoreRestV2Controller method getFile.

protected ResponseEntity<FileSystemResource> getFile(File file, boolean download, HttpServletRequest request, HttpServletResponse response) throws HttpMediaTypeNotAcceptableException {
    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.set(HttpHeaders.CONTENT_DISPOSITION, download ? "attachment" : "inline");
    MediaType mediaType = null;
    Set<MediaType> mediaTypes = Sets.newHashSet(MediaType.APPLICATION_OCTET_STREAM);
    request.setAttribute(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE, mediaTypes);
    // ResourceHttpMessageConverter uses ActivationMediaTypeFactory.getMediaType(resource) but this is not visible
    String mimeType = request.getServletContext().getMimeType(file.getName());
    if (StringUtils.hasText(mimeType)) {
        try {
            mediaType = MediaType.parseMediaType(mimeType);
        } catch (InvalidMediaTypeException e) {
        // Shouldn't happen - ServletContext.getMimeType() should return valid mime types
        }
    }
    // to whatever the Accept header was
    if (mediaType == null) {
        mediaTypes.add(MediaType.ALL);
        responseHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    } else {
        mediaTypes.add(mediaType);
        responseHeaders.setContentType(mediaType);
    }
    // this doesn't work as a header from ResponseEntity wont be set if it is already set in the response
    // responseHeaders.setCacheControl(cacheControlHeader);
    response.setHeader(HttpHeaders.CACHE_CONTROL, cacheControlHeader);
    return new ResponseEntity<>(new FileSystemResource(file), responseHeaders, HttpStatus.OK);
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) ResponseEntity(org.springframework.http.ResponseEntity) MediaType(org.springframework.http.MediaType) FileSystemResource(org.springframework.core.io.FileSystemResource) InvalidMediaTypeException(org.springframework.http.InvalidMediaTypeException)

Example 94 with MediaType

use of org.springframework.http.MediaType in project ma-modules-public by infiniteautomation.

the class PointValueTimeStreamCsvMessageConverter method writeInternal.

@Override
protected void writeInternal(Object object, Type type, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
    MediaType contentType = outputMessage.getHeaders().getContentType();
    JsonEncoding encoding = getJsonEncoding(contentType);
    try {
        PointValueTimeStream<?, ?> stream = (PointValueTimeStream<?, ?>) object;
        stream.setContentType(StreamContentType.CSV);
        JsonGenerator generator = this.objectMapper.getFactory().createGenerator(outputMessage.getBody(), encoding);
        // Set the schema
        CsvSchema.Builder builder = CsvSchema.builder();
        builder.setUseHeader(true);
        // Setup our rendering parameters
        LatestQueryInfo info = stream.getQueryInfo();
        if (stream instanceof MultiPointTimeRangeDatabaseStream || stream instanceof MultiPointLatestDatabaseStream) {
            if (info.isSingleArray()) {
                if (info.isMultiplePointsPerArray()) {
                    Map<Integer, DataPointVO> voMap = stream.getVoMap();
                    Iterator<Integer> it = voMap.keySet().iterator();
                    boolean firstTimestamp = true;
                    while (it.hasNext()) {
                        String xid = voMap.get(it.next()).getXid();
                        for (PointValueField field : info.getFields()) {
                            if (field == PointValueField.TIMESTAMP) {
                                if (firstTimestamp)
                                    field.createColumn(builder, xid);
                                firstTimestamp = false;
                            } else
                                field.createColumn(builder, xid);
                        }
                    }
                } else {
                    for (PointValueField field : info.getFields()) field.createColumn(builder, null);
                }
            } else {
                for (PointValueField field : info.getFields()) field.createColumn(builder, null);
            }
        } else if (stream instanceof MultiDataPointStatisticsQuantizerStream) {
            if (stream.getQueryInfo().isSingleArray()) {
                if (stream.getQueryInfo().isMultiplePointsPerArray()) {
                    Map<Integer, DataPointVO> voMap = stream.getVoMap();
                    Iterator<Integer> it = voMap.keySet().iterator();
                    boolean firstTimestamp = true;
                    while (it.hasNext()) {
                        String xid = voMap.get(it.next()).getXid();
                        for (PointValueField field : info.getFields()) {
                            if (field == PointValueField.TIMESTAMP) {
                                if (firstTimestamp)
                                    field.createColumn(builder, xid);
                                firstTimestamp = false;
                            } else if (field == PointValueField.VALUE) {
                                if (info.getRollup() == RollupEnum.ALL) {
                                    for (RollupEnum rollup : getAllRollups()) {
                                        builder.addColumn(xid + PointValueTimeWriter.DOT + rollup.name(), ColumnType.NUMBER_OR_STRING);
                                    }
                                } else {
                                    field.createColumn(builder, xid);
                                }
                            } else {
                                field.createColumn(builder, xid);
                            }
                        }
                    }
                } else {
                    // Single array
                    if (info.getRollup() == RollupEnum.ALL) {
                        for (RollupEnum rollup : getAllRollups()) {
                            builder.addColumn(rollup.name(), ColumnType.NUMBER_OR_STRING);
                        }
                        for (PointValueField field : info.getFields()) {
                            if (field == PointValueField.VALUE)
                                continue;
                            field.createColumn(builder, null);
                        }
                    } else {
                        for (PointValueField field : info.getFields()) field.createColumn(builder, null);
                    }
                }
            } else {
                if (info.getRollup() == RollupEnum.ALL) {
                    for (RollupEnum rollup : getAllRollups()) {
                        builder.addColumn(rollup.name(), ColumnType.NUMBER_OR_STRING);
                    }
                    for (PointValueField field : info.getFields()) {
                        if (field == PointValueField.VALUE)
                            continue;
                        field.createColumn(builder, null);
                    }
                } else {
                    for (PointValueField field : info.getFields()) field.createColumn(builder, null);
                }
            }
        }
        generator.setSchema(builder.build());
        PointValueTimeWriter writer = new PointValueTimeCsvWriter(stream.getQueryInfo(), stream.getVoMap().size(), generator);
        stream.start(writer);
        stream.streamData(writer);
        stream.finish(writer);
        generator.flush();
    } catch (JsonProcessingException ex) {
        throw new HttpMessageNotWritableException("Could not write content: " + ex.getMessage(), ex);
    }
}
Also used : PointValueTimeStream(com.infiniteautomation.mango.rest.v2.model.pointValue.PointValueTimeStream) MultiDataPointStatisticsQuantizerStream(com.infiniteautomation.mango.rest.v2.model.pointValue.quantize.MultiDataPointStatisticsQuantizerStream) LatestQueryInfo(com.infiniteautomation.mango.rest.v2.model.pointValue.query.LatestQueryInfo) CsvSchema(com.fasterxml.jackson.dataformat.csv.CsvSchema) PointValueTimeCsvWriter(com.infiniteautomation.mango.rest.v2.model.pointValue.PointValueTimeCsvWriter) JsonEncoding(com.fasterxml.jackson.core.JsonEncoding) MultiPointTimeRangeDatabaseStream(com.infiniteautomation.mango.rest.v2.model.pointValue.query.MultiPointTimeRangeDatabaseStream) Iterator(java.util.Iterator) MediaType(org.springframework.http.MediaType) JsonGenerator(com.fasterxml.jackson.core.JsonGenerator) RollupEnum(com.serotonin.m2m2.web.mvc.rest.v1.model.time.RollupEnum) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) MultiPointLatestDatabaseStream(com.infiniteautomation.mango.rest.v2.model.pointValue.query.MultiPointLatestDatabaseStream) DataPointVO(com.serotonin.m2m2.vo.DataPointVO) HttpMessageNotWritableException(org.springframework.http.converter.HttpMessageNotWritableException) PointValueTimeWriter(com.infiniteautomation.mango.rest.v2.model.pointValue.PointValueTimeWriter) Map(java.util.Map) PointValueField(com.infiniteautomation.mango.rest.v2.model.pointValue.PointValueField)

Example 95 with MediaType

use of org.springframework.http.MediaType in project commons by craftercms.

the class HttpMessageConvertingResponseWriter method writeWithMessageConverters.

@SuppressWarnings("unchecked")
public <T> void writeWithMessageConverters(T returnValue, HttpServletRequest request, HttpServletResponse response) throws IOException, HttpMediaTypeNotAcceptableException {
    Class<?> returnValueClass = returnValue.getClass();
    List<MediaType> requestedMediaTypes = getAcceptableMediaTypes(request);
    List<MediaType> producibleMediaTypes = getProducibleMediaTypes(returnValueClass);
    Set<MediaType> compatibleMediaTypes = new LinkedHashSet<MediaType>();
    for (MediaType r : requestedMediaTypes) {
        for (MediaType p : producibleMediaTypes) {
            if (r.isCompatibleWith(p)) {
                compatibleMediaTypes.add(getMostSpecificMediaType(r, p));
            }
        }
    }
    if (compatibleMediaTypes.isEmpty()) {
        throw new HttpMediaTypeNotAcceptableException(producibleMediaTypes);
    }
    List<MediaType> mediaTypes = new ArrayList<MediaType>(compatibleMediaTypes);
    MediaType.sortBySpecificityAndQuality(mediaTypes);
    MediaType selectedMediaType = null;
    for (MediaType mediaType : mediaTypes) {
        if (mediaType.isConcrete()) {
            selectedMediaType = mediaType;
            break;
        } else if (mediaType.equals(MediaType.ALL) || mediaType.equals(MEDIA_TYPE_APPLICATION)) {
            selectedMediaType = MediaType.APPLICATION_OCTET_STREAM;
            break;
        }
    }
    if (selectedMediaType != null) {
        selectedMediaType = selectedMediaType.removeQualityValue();
        for (HttpMessageConverter<?> messageConverter : messageConverters) {
            if (messageConverter.canWrite(returnValueClass, selectedMediaType)) {
                ((HttpMessageConverter<T>) messageConverter).write(returnValue, selectedMediaType, new ServletServerHttpResponse(response));
                logger.debug(LOG_KEY_WRITTEN_WITH_MESSAGE_CONVERTER, returnValue, selectedMediaType, messageConverter);
                return;
            }
        }
    }
    throw new HttpMediaTypeNotAcceptableException(allSupportedMediaTypes);
}
Also used : LinkedHashSet(java.util.LinkedHashSet) HttpMediaTypeNotAcceptableException(org.springframework.web.HttpMediaTypeNotAcceptableException) ArrayList(java.util.ArrayList) HttpMessageConverter(org.springframework.http.converter.HttpMessageConverter) MediaType(org.springframework.http.MediaType) ServletServerHttpResponse(org.springframework.http.server.ServletServerHttpResponse)

Aggregations

MediaType (org.springframework.http.MediaType)477 Test (org.junit.jupiter.api.Test)177 HttpHeaders (org.springframework.http.HttpHeaders)97 Test (org.junit.Test)61 ArrayList (java.util.ArrayList)58 Charset (java.nio.charset.Charset)42 MockHttpOutputMessage (org.springframework.http.MockHttpOutputMessage)34 List (java.util.List)33 MockHttpInputMessage (org.springframework.http.MockHttpInputMessage)33 LinkedMultiValueMap (org.springframework.util.LinkedMultiValueMap)33 HashMap (java.util.HashMap)30 ParameterizedTypeReference (org.springframework.core.ParameterizedTypeReference)30 IOException (java.io.IOException)26 Resource (org.springframework.core.io.Resource)23 ResolvableType (org.springframework.core.ResolvableType)22 HttpEntity (org.springframework.http.HttpEntity)21 ServerWebExchange (org.springframework.web.server.ServerWebExchange)20 MockServerWebExchange (org.springframework.web.testfixture.server.MockServerWebExchange)20 Nullable (org.springframework.lang.Nullable)18 HttpClientErrorException (org.springframework.web.client.HttpClientErrorException)18