Return the list of acceptable {@linkplain MediaType media types},
as specified by the {@code Accept} header.
<p>Returns an empty list when the acceptable media types are unspecified.
321599
public List<MediaType> getAccept() {
		String value = getFirst(ACCEPT);
		List<MediaType> result = (value != null ? MediaType.parseMediaTypes(value) : Collections.<MediaType>emptyList());

		// Some containers parse 'Accept' into multiple values
		if (result.size() == 1) {
			List<String> acceptHeader = get(ACCEPT);
			if (acceptHeader.size() > 1) {
				value = StringUtils.collectionToCommaDelimitedString(acceptHeader);
				result = MediaType.parseMediaTypes(value);
			}
		}

		return result;
	}
1064503
@SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
    private static MediaTypes getType(final Request req) throws IOException {
        MediaTypes list = new MediaTypes();
        final Iterable<String> headers = new RqHeaders.Base(req)
            .header("Content-Type");
        for (final String hdr : headers) {
            list = list.merge(new MediaTypes(hdr));
        }
        if (list.isEmpty()) {
            list = new MediaTypes("*/*");
        }
        return list;
    }
1269905
public static Map<MediaType, QualityValue> getMediaTypeQualityValues(String header)
   {
      if (header == null)
         return null;
      header = header.trim();
      if (header.length() == 0)
         return null;
      Map<MediaType, QualityValue> result = new LinkedHashMap<MediaType, QualityValue>();

      int offset = 0;
      while (offset >= 0)
      {
         int slashIndex = header.indexOf('/', offset);
         if (slashIndex < 0)
            throw new IllegalArgumentException("Malformed media type: " + header);
         String type = header.substring(offset, slashIndex);
         String subtype;
         Map<String, String> parameters = null;
         QualityValue qualityValue = QualityValue.DEFAULT;

         offset = slashIndex + 1;
         int parameterStartIndex = header.indexOf(';', offset);
         int itemEndIndex = header.indexOf(',', offset);
         if (parameterStartIndex == itemEndIndex)
         {
            assert itemEndIndex == -1;
            subtype = header.substring(offset);
            offset = -1;
         }
         else if (itemEndIndex < 0 || (parameterStartIndex >= 0 && parameterStartIndex < itemEndIndex))
         {
            subtype = header.substring(offset, parameterStartIndex);
            offset = parameterStartIndex + 1;
            parameters = new LinkedHashMap<String, String>();
            offset = parseParameters(parameters, header, offset);
            qualityValue = evaluateAcceptParameters(parameters);
         }
         else
         {
            subtype = header.substring(offset, itemEndIndex);
            offset = itemEndIndex + 1;
         }
         result.put(new MediaType(type.trim(), subtype.trim(), parameters), qualityValue);
      }

      if (logger.isDebugEnabled())
         logger.debug(result.toString());
      return result;
   }
1193733
@SuppressWarnings({ "null", "unused" })
  @NotNull
  Media processRequest(@NotNull final MediaRequest mediaRequest) {

    // detect media source
    MediaSource mediaSource = null;
    List<Class<? extends MediaSource>> mediaSources = mediaHandlerConfig.getSources();
    if (mediaSources == null || mediaSources.isEmpty()) {
      throw new RuntimeException("No media sources defined.");
    }
    MediaSource firstMediaSource = null;
    for (Class<? extends MediaSource> candidateMediaSourceClass : mediaSources) {
      MediaSource candidateMediaSource = AdaptTo.notNull(adaptable, candidateMediaSourceClass);
      if (candidateMediaSource.accepts(mediaRequest)) {
        mediaSource = candidateMediaSource;
        break;
      }
      else if (firstMediaSource == null) {
        firstMediaSource = candidateMediaSource;
      }
    }
    // if no media source was detected use first media resource defined
    if (mediaSource == null) {
      mediaSource = firstMediaSource;
    }
    Media media = new Media(mediaSource, mediaRequest);

    // resolve media format names to media formats
    MediaFormatResolver mediaFormatResolver = new MediaFormatResolver(mediaFormatHandler);
    if (!mediaFormatResolver.resolve(mediaRequest.getMediaArgs())) {
      media.setMediaInvalidReason(MediaInvalidReason.INVALID_MEDIA_FORMAT);
      return media;
    }

    // if only downloads are accepted prepare media format filter set which only contains download media formats
    if (!resolveDownloadMediaFormats(mediaRequest.getMediaArgs())) {
      media.setMediaInvalidReason(MediaInvalidReason.INVALID_MEDIA_FORMAT);
      return media;
    }

    // apply defaults to media args
    if (mediaRequest.getMediaArgs().isIncludeAssetWebRenditions() == null) {
      mediaRequest.getMediaArgs().includeAssetWebRenditions(mediaHandlerConfig.includeAssetWebRenditionsByDefault());
    }

    // preprocess media request before resolving
    List<Class<? extends MediaProcessor>> mediaPreProcessors = mediaHandlerConfig.getPreProcessors();
    if (mediaPreProcessors != null) {
      for (Class<? extends MediaProcessor> processorClass : mediaPreProcessors) {
        MediaProcessor processor = AdaptTo.notNull(adaptable, processorClass);
        media = processor.process(media);
        if (media == null) {
          throw new RuntimeException("MediaPreProcessor '" + processor + "' returned null, request: " + mediaRequest);
        }
      }
    }

    // resolve media request
    media = mediaSource.resolveMedia(media);
    if (media == null) {
      throw new RuntimeException("MediaType '" + mediaSource + "' returned null, request: " + mediaRequest);
    }

    // generate markup (if markup builder is available) - first accepting wins
    List<Class<? extends MediaMarkupBuilder>> mediaMarkupBuilders = mediaHandlerConfig.getMarkupBuilders();
    if (mediaMarkupBuilders != null) {
      for (Class<? extends MediaMarkupBuilder> mediaMarkupBuilderClass : mediaMarkupBuilders) {
        MediaMarkupBuilder mediaMarkupBuilder = AdaptTo.notNull(adaptable, mediaMarkupBuilderClass);
        if (mediaMarkupBuilder.accepts(media)) {
          media.setElement(mediaMarkupBuilder.build(media));
          break;
        }
      }
    }

    // postprocess media request after resolving
    List<Class<? extends MediaProcessor>> mediaPostProcessors = mediaHandlerConfig.getPostProcessors();
    if (mediaPostProcessors != null) {
      for (Class<? extends MediaProcessor> processorClass : mediaPostProcessors) {
        MediaProcessor processor = AdaptTo.notNull(adaptable, processorClass);
        media = processor.process(media);
        if (media == null) {
          throw new RuntimeException("MediaPostProcessor '" + processor + "' returned null, request: " + mediaRequest);
        }
      }
    }

    return media;
  }
1297521
public static String getSupportPatchMediaTypes() {
        if (SUPPORT_PATCH_MEDIA_TYPES == null) {
            synchronized (HttpPatchProperties.SUPPORT_PATCH_MEDIA_TYPES) {
                if (SUPPORT_PATCH_MEDIA_TYPES == null) {
                    SUPPORT_PATCH_MEDIA_TYPES = StringUtils.join(HttpPatchProperties.SUPPORT_PATCH_MEDIA_TYPES, ",");
                }
            }
        }
        return SUPPORT_PATCH_MEDIA_TYPES;
    }
1129525
function getMLinePayloadTypes (mediaLine, mediaType) {
      var mLineSelector = new RegExp('^m=' + mediaType +
                            ' \\d+(/\\d+)? [a-zA-Z0-9/]+(( [a-zA-Z0-9/]+)+)$', 'i');

      // Get all payload types that the line supports
      var payloadTypes = mediaLine.match(mLineSelector);
      if (!payloadTypes || payloadTypes.length < 2) {
        // Error, invalid M line?
        return [];
      }

      return OT.$.trim(payloadTypes[2]).split(' ');
    }
1155575
def parse_accept_header(accept):
    

    def parse_media_range(accept_item):
        """ Parse media range and subtype """

        return accept_item.split('/', 1)

    def comparator(a, b):
        """ Compare accept items a and b """

        # first compare q values
        result = -cmp(a[2], b[2])
        if result is not 0:
            # q values differ, no need to compare media types
            return result

        # parse media types and compare them (asterisks are lower in precedence)
        mtype_a, subtype_a = parse_media_range(a[0])
        mtype_b, subtype_b = parse_media_range(b[0])
        if mtype_a == '*' and subtype_a == '*':
            return 1
        if mtype_b == '*' and subtype_b == '*':
            return -1
        if subtype_a == '*':
            return 1
        if subtype_b == '*':
            return -1
        return 0

    if not accept:
        return []

    result = []
    for media_range in accept.split(","):
        parts = media_range.split(";")
        media_type = parts.pop(0).strip()
        media_params = []
        q = 1.0
        for part in parts:
            (key, value) = part.lstrip().split("=", 1)
            if key == "q":
                q = float(value)
            else:
                media_params.append((key, value))
        result.append((media_type, tuple(media_params), q))
    result.sort(comparator)
    return result
715898
private ContentType getAcceptType() {
        // If the format header is present, it overrides the ACCEPT header.
        String format = m_variableMap.get("format");
        if (format != null) {
            return new ContentType(format);
        }
        String acceptParts = m_request.getHeader(HttpDefs.ACCEPT);
        if (!Utils.isEmpty(acceptParts)) {
	        for (String acceptPart : acceptParts.split(",")) {
	            ContentType acceptType = new ContentType(acceptPart);
	            if (acceptType.isJSON() || acceptType.isXML() || acceptType.isPlainText()) {
	                return acceptType;
	            }
	        }
        }
        return getContentType();
    }
948694
@Override
	public boolean supports(@NonNull MediaType delimiter) {

		return this.mediaTypes.stream() //
				.anyMatch(mediaType -> mediaType.isCompatibleWith(delimiter));
	}
31839
def select_header_accept(self, accepts):
        
        if not accepts:
            return

        accepts = [x.lower() for x in accepts]

        if 'application/json' in accepts:
            return 'application/json'
        else:
            return ', '.join(accepts)
718563
public static MediaType valueOf(String type) throws IllegalArgumentException {
        if (type == null || type.trim().isEmpty() || type.startsWith(SUBTYPE_SEPARATOR) || type.endsWith(SUBTYPE_SEPARATOR)) {
            throw new IllegalArgumentException("Invalid mime type '" + type + "'");
        }
        String[] splitType = type.split(SUBTYPE_SEPARATOR);
        if (splitType.length == 2) {
            nonEmpty(type, splitType[0]);
            nonEmpty(type, splitType[1]);
            Map<String, String> parameters = new HashMap<>();
            String subType = splitType[1];
            if (splitType[1].contains(PARAMETERS_SEPARATOR)) {
                String[] subTypeWithparameter = splitType[1].split(PARAMETERS_SEPARATOR);
                String paramString = subTypeWithparameter[1].trim();
                subType = subTypeWithparameter[0];
                parameters = parseParameters(paramString);
            }
            return new MediaType(splitType[0].trim(), subType.trim(), parameters);
        }
        if (!type.contains(SUBTYPE_SEPARATOR)) {
            String mimeType = mimeMappings.getMimeType(type);
            if (mimeType != null) {
                return valueOf(mimeType);
            }
        }
        throw new IllegalArgumentException("Invalid mime type '" + type + "'");
    }
652904
public function getAcceptableContentTypes()
    {
        if (null !== $this->acceptableContentTypes) {
            return $this->acceptableContentTypes;
        }

        return $this->acceptableContentTypes = array_keys(AcceptHeader::fromString($this->headers->get('Accept'))->all());
    }
528315
public HttpEntity<byte[]> getMetadata(HttpServletRequest request, @RequestHeader(name = "Accept", required = false) String acceptHeader) {

    logger.debug("Request to download metadata from {}", request.getRemoteAddr());

    try {

      // Check if the metadata is up-to-date according to how the container was configured.
      //
      if (this.metadataContainer.updateRequired(true)) {
        logger.debug("Metadata needs to be updated ...");
        this.metadataContainer.update(true);
        logger.debug("Metadata was updated and signed");
      }
      else {
        logger.debug("Metadata is up-to-date, using cached metadata");
      }

      // Get the DOM for the metadata and serialize it.
      //
      Element dom = this.metadataContainer.marshall();

      ByteArrayOutputStream stream = new ByteArrayOutputStream();
      SerializeSupport.writeNode(dom, stream);

      // Assign the HTTP headers.
      //
      HttpHeaders header = new HttpHeaders();
      if (acceptHeader != null && !acceptHeader.contains(APPLICATION_SAML_METADATA)) {
        header.setContentType(MediaType.APPLICATION_XML);
      }
      else {
        header.setContentType(MediaType.valueOf(APPLICATION_SAML_METADATA));
      }
      // TODO: turn off caching

      byte[] documentBody = stream.toByteArray();
      header.setContentLength(documentBody.length);
      return new HttpEntity<byte[]>(documentBody, header);
    }
    catch (SignatureException | MarshallingException e) {
      logger.error("Failed to return valid metadata", e);
      return new ResponseEntity<byte[]>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }
796334
private Map<String, RouteEntry> getAcceptedMimeTypes(List<RouteEntry> routes) {
        Map<String, RouteEntry> acceptedTypes = new HashMap<>();

        for (RouteEntry routeEntry : routes) {
            if (!acceptedTypes.containsKey(routeEntry.acceptedType)) {
                acceptedTypes.put(routeEntry.acceptedType, routeEntry);
            }
        }

        return acceptedTypes;
    }
1140247
def _response_mimetype_based_on_accept_header(self):
        
        response_mimetype = None

        if not request.accept_mimetypes:
            response_mimetype = self.default_mimetype
        else:
            all_media_types_wildcard = '*/*'

            for mimetype, q in request.accept_mimetypes:
                if mimetype == all_media_types_wildcard:
                    response_mimetype = self.default_mimetype
                    break
                if mimetype in self.response_formatters:
                    response_mimetype = mimetype
                    break

        return response_mimetype
1267653
public MediaType getContentType() {
        if (isNull(this.contentType)) {
            contentType = getHeader(HeaderName.CONTENT_TYPE)
                .map(MediaType::of)
                .orElse(WILDCARD);
        }

        return contentType;
    }
840032
public function getAcceptedContentTypes()
    {
        if (empty($this->acceptedContentTypes)) {
            // Values will be stored in this array
            $this->acceptedContentTypes = array();

            // Accept header is case insensitive, and whitespace isn’t important.
            $acceptHeader = strtolower(str_replace(' ', '', @$_SERVER['HTTP_ACCEPT'] ?: '*/*'));
            // Extract the content types from the header.
            $acceptHeaderItems = explode(',', $acceptHeader);
            foreach ($acceptHeaderItems as $contentType) {
                // The default quality is 1.
                $quality = 1;
                // Check whether a quality is specified.
                if (strpos($contentType, ';q=')) {
                    list($contentType, $quality) = explode(';q=', $contentType);
                }

                $this->acceptedContentTypes[$contentType] = $quality;
            }
            // Sort the content types by relevance.
            arsort($this->acceptedContentTypes);
        }

        return $this->acceptedContentTypes;
    }