If not mapped, content-type is application/octet-stream for binary and test/plain otherwise.
TODO: extensibility
161549
public static String getContentType(String ext) {
        String ct = extToContentType.get(ext);
        if (ct == null)
            ct = isBinary(ext) ? "application/octet-stream" : "text/plain";
        return ct;
    }
620304
@Override
    public void setContentType(String type) {

        if (LOG.isDebugEnabled()) {
            LOG.debug(Messages.get().getBundle().key(Messages.LOG_FLEXRESPONSE_SETTING_CONTENTTYPE_1, type));
        }
        // only if this is the "Top-Level" element, do set the content type
        // otherwise an included JSP could reset the type with some unwanted defaults
        if (!m_typeSet && m_isTopElement) {
            // type must be set only once, otherwise some Servlet containers (not Tomcat) generate errors
            m_typeSet = true;
            super.setContentType(type);
            return;
        }
    }
331409
private MediaType findContentType(final String url) {
        if (url == null) {
            return null;
        }

        if (url.startsWith("file")) {
            return APPLICATION_OCTET_STREAM_TYPE;
        } else if (url.startsWith("http")) {
            try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
                final HttpHead httpHead = new HttpHead(url);
                try (CloseableHttpResponse response = httpClient.execute(httpHead)) {
                    if (response.getStatusLine().getStatusCode() == SC_OK) {
                        final Header contentType = response.getFirstHeader(CONTENT_TYPE);
                        if (contentType != null) {
                            return MediaType.valueOf(contentType.getValue());
                        }
                    }
                }
            } catch (final IOException e) {
                LOGGER.warn("Unable to retrieve external content from {} due to {}", url, e.getMessage());
            } catch (final Exception e) {
                throw new RepositoryRuntimeException(e);
            }
        }
        LOGGER.debug("Defaulting to octet stream for media type");
        return APPLICATION_OCTET_STREAM_TYPE;
    }
1300674
public final B contentType(CharSequence contentType) {
        requireNonNull(contentType, "contentType");
        autoDetectedContentType(false);
        return setHeader(HttpHeaderNames.CONTENT_TYPE, contentType);
    }
414913
protected String getContentType(Resource resource, @SuppressWarnings("unused") SlingHttpServletRequest request) {
    String mimeType = JcrBinary.getMimeType(resource);
    if (StringUtils.isEmpty(mimeType)) {
      mimeType = ContentType.OCTET_STREAM;
    }
    return mimeType;
  }
133186
public static Map<String,Object> toMetaDatas(String contentType, String fileName){
        Map<String,Object> metadatas = new HashMap<String, Object>();
        putMetaDatas(metadatas, contentType, fileName);
        return metadatas;
    }
610896
public static boolean isGrpcContentType(String contentType) {
    if (contentType == null) {
      return false;
    }

    if (CONTENT_TYPE_GRPC.length() > contentType.length()) {
      return false;
    }

    contentType = contentType.toLowerCase();
    if (!contentType.startsWith(CONTENT_TYPE_GRPC)) {
      // Not a gRPC content-type.
      return false;
    }

    if (contentType.length() == CONTENT_TYPE_GRPC.length()) {
      // The strings match exactly.
      return true;
    }

    // The contentType matches, but is longer than the expected string.
    // We need to support variations on the content-type (e.g. +proto, +json) as defined by the
    // gRPC wire spec.
    char nextChar = contentType.charAt(CONTENT_TYPE_GRPC.length());
    return nextChar == '+' || nextChar == ';';
  }
250362
public boolean isTextContentType(String contentType) {
        if (contentType != null) {
            String lowerContentType = contentType.toLowerCase();
            for (String textContentType : this.parsableContentTypes) {
                if (lowerContentType.startsWith(textContentType)) {
                    return true;
                }
            }
        }
        return false;
    }
313614
protected void sendBinaryData(byte[] binaryData, String contentType,
      SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException {

    // set content type and length
    response.setContentType(contentType);
    response.setContentLength(binaryData.length);

    // Handling of the "force download" selector
    if (RequestPath.hasSelector(request, SELECTOR_DOWNLOAD)) {
      // Overwrite MIME type with one suited for downloads
      response.setContentType(ContentType.DOWNLOAD);

      // Construct disposition header
      StringBuilder dispositionHeader = new StringBuilder("attachment;");
      String suffix = request.getRequestPathInfo().getSuffix();
      suffix = StringUtils.stripStart(suffix, "/");
      if (StringUtils.isNotEmpty(suffix)) {
        dispositionHeader.append("filename=\"").append(suffix).append('\"');
      }

      response.setHeader(HEADER_CONTENT_DISPOSITION, dispositionHeader.toString());
    }

    // write binary data
    OutputStream out = response.getOutputStream();
    out.write(binaryData);
    out.flush();

  }
859455
def wrap_content_as_binary_if_needed(func_, *args, **kwargs):
    
    assert isinstance(args[0], dict)
    try:
        args[0][CONTENT_FIELD] = BINARY(args[0].get(CONTENT_FIELD, b""))
    except (r.errors.ReqlDriverCompileError, AttributeError):  # pragma: no cover
        pass  # toss in the object as string
    return func_(*args, **kwargs)
418201
@SuppressWarnings("rawtypes")
    @Override
    public long sizeInputStreamData(Map isd) throws UnsupportedEncodingException, IllegalStateException {
        validateInputStreamData(isd);
        // The length of IMPUT_STREAM_CONTENT_TYPE won't exceed Integer.MAX_VALUE
        long size = LENGTH_INT + LENGTH_LONG;
        String type = (String)isd.get(INPUT_STREAM_CONTENT_TYPE);
        if (type != null) {
            size += type.getBytes("UTF-8").length;
        } else {
            size +=1; // if the size is zero, one byte data will be used for placeholder.
        }
        byte [] data = (byte [])isd.get(INPUT_STREAM_CONTENT_DATA);
        if (data != null) {
            size += data.length;
        }
        if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))
            logger.logp(Level.FINE, CLASS_NAME,"sizeInputStreamData", Long.toString(size));
        return size;
    }
71694
function validateContentType(cb) {
        if (!_.isUndefined(kontx.args.meta) && !_.isUndefined(kontx.args.meta.type)) {
            db.contentTypes.getById(kontx.args.meta.type.toString()).then(
                function(contentType) {
                    cb(null, contentType);
                },
                function() {
                    cb(createError(400, messages.invalid_content_type));
                });
        } else {
            cb(createError(400, messages.invalid_content_type));
        }

    }
609730
protected BodyPart handleBinaryPart(MimePart mediaPart, String contentType) throws IOException, MessagingException {
        String contentId = mediaPart.getContentID() != null ? "(" + mediaPart.getContentID() + ")" : "";
        return new BodyPart(mediaPart.getFileName() + contentId, contentType);
    }
923893
@Override
    public long getContentSize(Context ctx) throws StreamIOException {
        try {
            // For new or modified datastreams, the new bytestream hasn't yet been
            // committed. However, we need to access it in order to compute
            // the datastream checksum
            if (DSLocation.startsWith(UPLOADED_SCHEME)) {
                // TODO: refactor to use proper temp file management - FCREPO-718
                // for now, just get the file directly (see also DefaultManagement.getTempStream(...))
                String internalId = DSLocation.substring(UPLOADED_SCHEME.length());
                File uploadedFile = new File(getTempUploadDir(), internalId);
                // check it has not been automatically purged (see DefaultManagement.purgeUploadedFiles())
                if (uploadedFile.exists()) {
                    return uploadedFile.length();
                } else {
                    throw new StreamIOException("Uploaded file " + DSLocation + " no longer exists.");
                }

            } else if (DSLocation.startsWith(TEMP_SCHEME)) {
                // TODO: refactor to use proper temp file management - FCREPO-718
                String fileName = DSLocation.substring(TEMP_SCHEME.length());
                File tempFile = new File(fileName);
                // check it has not been removed elsewhere (should not happen)
                if (tempFile.exists()) {
                    return tempFile.length();
                } else {
                    throw new StreamIOException("Temp file " + DSLocation + " no longer exists.");
                }
            } else if (Datastream.DS_LOCATION_TYPE_INTERNAL.equals(DSLocationType)) {
                ILowlevelStorage llstore = getLLStore();
                if (s_llsizable) {
                    return ((ISizable)llstore).getDatastreamSize(DSLocation);
                } else {
                    return 0;
                }
            } else if (Datastream.DS_LOCATION_TYPE_URL.equals(DSLocationType)) {
                // Managed content can have URL dsLocation on ingest
                ValidationUtility.validateURL(DSLocation, this.DSControlGrp);
                // If validation has succeeded, assume an external resource.
                // Fetch it, store it locally, update DSLocation
                if (ctx == null) {
                    ctx = ReadOnlyContext.getContext(null, null, "", false);
                    // changed from below, which sets noOp to true, seems to cause an AuthZ permitted exception
                    // in PolicyEnforcementPoint.enforce(...)
                    // ctx = ReadOnlyContext.EMPTY;
                }
               ContentManagerParams params = new ContentManagerParams(DSLocation);
                params.setContext(ctx);
                MIMETypedStream stream = getExternalContentManager()
                        .getExternalContent(params);

                // TODO: refactor temp file management - see FCREPO-718; for now create temp file and write to it
                // note - don't use temp upload directory, use (container's) temp dir (upload dir is for uploads)
                File tempFile = File.createTempFile("managedcontentupdate", null);
                OutputStream os = new FileOutputStream(tempFile);
                StreamUtility.pipeStream(stream.getStream(), os, 32768);
                DSLocation = TEMP_SCHEME + tempFile.getAbsolutePath();
                return tempFile.length();
            }
        } catch (Throwable th) {
            throw new StreamIOException("[DatastreamManagedContent] returned "
                    + " the error: \"" + th.getClass().getName()
                    + "\". Reason: " + th.getMessage(), th);
        }
        throw new StreamIOException("[DatastreamManagedContent] could not resolve dsLocation " + DSLocation + " dsLocationType " + DSLocationType);
    }
1035289
function getContentType(url: string): string {
  url = trimUrlQuery(url);
  const dot = url.lastIndexOf(".");
  if (dot >= 0) {
    const name = url.substring(dot + 1);
    if (name in contentMap) {
      return contentMap[name];
    }
  }
  return "text/plain";
}
497724
def get_content_type(self):
        
        mime_type, encoding = mimetypes.guess_type(self.filepath)
        if encoding == "gzip":
            return "application/gzip"
        elif encoding is not None:
            return "application/octet-stream"
        elif mime_type is not None:
            return mime_type
        # if mime_type not detected, use application/octet-stream
        else:
            return "application/octet-stream"
827715
@Override
    public void setContent(final InputStream content, final String contentType,
            final Collection<URI> checksums, final String originalFileName,
            final StoragePolicyDecisionPoint storagePolicyDecisionPoint)
            throws InvalidChecksumException {

        try {


            final Node dsNode = getNode();

            LOGGER.debug("Created content node at path: {}", dsNode.getPath());

            String hint = null;

            if (storagePolicyDecisionPoint != null) {
                hint = storagePolicyDecisionPoint.evaluatePolicies(this);
            }
            final ValueFactory modevf =
                    (ValueFactory) node.getSession().getValueFactory();
            final Binary binary = modevf.createBinary(content, hint);

        /*
         * This next line of code deserves explanation. If we chose for the
         * simpler line: Property dataProperty =
         * contentNode.setProperty(JCR_DATA, requestBodyStream); then the JCR
         * would not block on the stream's completion, and we would return to
         * the requester before the mutation to the repo had actually completed.
         * So instead we use createBinary(requestBodyStream), because its
         * contract specifies: "The passed InputStream is closed before this
         * method returns either normally or because of an exception." which
         * lets us block and not return until the job is done! The simpler code
         * may still be useful to us for an asynchronous method that we develop
         * later.
         */
            final Property dataProperty = dsNode.setProperty(JCR_DATA, binary);

            // Ensure provided checksums are valid
            final Collection<URI> nonNullChecksums = (null == checksums) ? new HashSet<>() : checksums;
            verifyChecksums(nonNullChecksums, dataProperty);

            final Node descNode = getDescriptionNodeOrNull();

            decorateContentNode(dsNode, descNode, nonNullChecksums);
            FedoraTypesUtils.touch(dsNode);

            if (descNode != null) {
                descNode.setProperty(HAS_MIME_TYPE, contentType);

                if (originalFileName != null) {
                    descNode.setProperty(FILENAME, originalFileName);
                }

                FedoraTypesUtils.touch(descNode);
            }

            LOGGER.debug("Created data property at path: {}", dataProperty.getPath());

        } catch (final RepositoryException e) {
            throw new RepositoryRuntimeException(e);
        }
    }