ballerina/mime module

Module Overview

This module provides functions to encapsulate multiple body parts, such as attachments in a single message. The communication of such messages follow the MIME (Multipurpose Internet Mail Extensions) specification as specified in the RFC 2045 standard.

MIME specific terms

The following terms are MIME specific and are extracted from the MIME specification.

Entity

This refers to the header fields and the content of a message, or a part of the body in a multipart entity.

Body Part

This refers to an entity that is inside a multipart entity.

Body

This is the body of an entity, which can be a body of a message or the body of a multipart entity.

Header Fields

Content-Type, Content-Transfer-Encoding, Content-ID, Content-Description, and Content-Disposition are some of the MIME header fields. These headers exist along with the other headers in the Entity.

Content-Type: image/jpeg
Content-Disposition: attachment; filename=genome.jpeg;
Content-Description: a complete map of the human genome

Modify and retrieve the data in an entity

The module provides functions to set and get an entity body from different kinds of message types, such as XML, text, JSON, blob, and body parts. Headers can be modified through functions such as addHeader(), setHeader(), removeHeader(), etc.

Samples

Handle multipart request

The sample service given below handles a multipart request. It extracts the body content from each part, converts it to a string, and sends a response.

import ballerina/http;
import ballerina/io;
import ballerina/log;
import ballerina/mime;

@http:ServiceConfig {
    basePath: "/test"
}
service test on new http:Listener(9090) {

    @http:ResourceConfig {
        methods: ["POST"],
        path: "/multipleparts"
    }
    // The resource that handles multipart requests.
    resource function multipartResource(http:Caller caller, http:Request request) {
        http:Response response = new;

        // Get the body parts from the request.
        var bodyParts = request.getBodyParts();
        if (bodyParts is mime:Entity[]) {
            string content = "";
            // Iterate through each body part and handle the content.
            foreach var part in bodyParts {
                content = content + " -- " + handleContent(part);
            }
            response.setPayload(untaint content);
        } else {
            // If there is an error while getting the body parts, set the response code as 500 and
            // set the error message as the response message.
            response.statusCode = 500;
            response.setPayload(untaint bodyParts.reason());
        }

        var result = caller->respond(response);
        if (result is error) {
            log:printError("Error in responding", err = result);
        }
    }
}

// The function that handles the content based on the body part type.
function handleContent(mime:Entity bodyPart) returns string {
    var mediaType = mime:getMediaType(bodyPart.getContentType());
    if (mediaType is mime:MediaType) {
        // Get the base type of the specific body part.
        string baseType = mediaType.getBaseType();
        // If the base type is ‘application/xml’ or ‘text/xml’, get the XML content from body part.
        if (mime:APPLICATION_XML == baseType || mime:TEXT_XML == baseType) {
            var payload = bodyPart.getXml();
            if (payload is xml) {
                return payload.getTextValue();
            } else {
                return "Error in parsing xml payload";
            }
        } else if (mime:APPLICATION_JSON == baseType) {
            // If the base type is ‘application/json’, get the JSON content from body part.
            var payload = bodyPart.getJson();
            if (payload is json) {
                return payload.toString();
            } else {
                return "Error in parsing json payload";
            }
        }
    } else {
        return mediaType.reason();
    }
    return "";
}

The sample request that is sent to the above service is shown below.

curl -v -F "request={\"param1\": \"value1\"};type=application/json" -F "language=ballerina;type=text/plain" -F "upload=@/home/path-to-file/encode.txt;type=application/octet-stream"  http://localhost:9090/test/multipleparts -H "Expect:"

Create a multipart request

The sample given below creates a multipart request. It includes two body parts with application/json and application/xml content type.

// Create a JSON body part.
mime:Entity bodyPart1 = new;
// Set the JSON content.
bodyPart1.setJson({"bodyPart": "jsonPart"});

// Create another body part using an XML file.
mime:Entity bodyPart2 = new;
bodyPart2.setFileAsEntityBody("ballerina/mime/file.xml", contentType = mime:APPLICATION_XML);

//Create an array to hold all the body parts.
mime:Entity[] bodyParts = [bodyPart1, bodyPart2];

// Set the body parts to the outbound response.
http:Request outRequest = new;
// Set the content type as ‘multipart/mixed’ and set the body parts.
outRequest.setBodyParts(bodyParts, contentType = mime:MULTIPART_MIXED);

Module Detail

Objects

Object Description
ContentDisposition

Represents values in Content-Disposition header.

Entity

Represents the headers and body of a message. This can be used to represent both the entity of a top level message and an entity(body part) inside of a multipart entity.

MediaType

Describes the nature of the data in the body of a MIME entity.

Functions

Function Description
base64DecodeBlob

Decodes a given byte[] with Base64 encoding scheme.

base64DecodeByteArray

Decode a given byte[] with Base64 encoding scheme.

base64DecodeByteChannel

Decodes a given ByteChannel with Base64 encoding scheme.

base64DecodeString

Decodes a given string with Base64 encoding scheme.

base64EncodeBlob

Encodes a given byte[] with Base64 encoding scheme.

base64EncodeByteArray

Encode a given byte[] with Base64 encoding scheme.

base64EncodeByteChannel

Encodes a given ByteChannel with Base64 encoding scheme.

base64EncodeString

Encodes a given string with Base64 encoding scheme.

byteArrayToString

Converts given byte[] to a string.

getContentDispositionObject

Given the Content-Disposition as a string, gets the ContentDisposition object with it.

getMediaType

Given the Content-Type in string, gets the MediaType object populated with it.

public function base64DecodeBlob(byte[] valueToBeDecoded) returns (byte[]|error<>)

Decodes a given byte[] with Base64 encoding scheme.

Parameter Name Data Type Default Value Description
valueToBeDecoded byte[]

Content that needs to be decoded

Return Type Description
byte[]|error<>

A decoded byte[]. In case of errors, an error record is returned

public function base64DecodeByteArray(byte[] b) returns (byte[])

Decode a given byte[] with Base64 encoding scheme.

Parameter Name Data Type Default Value Description
b byte[]
Return Type Description
byte[]

Return a decoded byte[]

public function base64DecodeByteChannel(io:ReadableByteChannel valueToBeDecoded) returns (io:ReadableByteChannel|error<>)

Decodes a given ByteChannel with Base64 encoding scheme.

Parameter Name Data Type Default Value Description
valueToBeDecoded io:ReadableByteChannel

Content that needs to be decoded

Return Type Description
io:ReadableByteChannel|error<>

A decoded io:ReadableByteChannel. In case of errors, an error record is returned

public function base64DecodeString(string valueToBeDecoded, string charset) returns (string|error<>)

Decodes a given string with Base64 encoding scheme.

Parameter Name Data Type Default Value Description
valueToBeDecoded string

Content that needs to be decoded

charset string utf-8

Charset to be used

Return Type Description
string|error<>

A decoded string. In case of errors, an error record is returned

public function base64EncodeBlob(byte[] valueToBeEncoded) returns (byte[]|error<>)

Encodes a given byte[] with Base64 encoding scheme.

Parameter Name Data Type Default Value Description
valueToBeEncoded byte[]

Content that needs to be encoded

Return Type Description
byte[]|error<>

An encoded byte[]. In case of errors, an error record is returned

public function base64EncodeByteArray(byte[] b) returns (byte[])

Encode a given byte[] with Base64 encoding scheme.

Parameter Name Data Type Default Value Description
b byte[]
Return Type Description
byte[]

Return an encoded byte[]

public function base64EncodeByteChannel(io:ReadableByteChannel valueToBeEncoded) returns (io:ReadableByteChannel|error<>)

Encodes a given ByteChannel with Base64 encoding scheme.

Parameter Name Data Type Default Value Description
valueToBeEncoded io:ReadableByteChannel

Content that needs to be encoded

Return Type Description
io:ReadableByteChannel|error<>

An encoded io:ReadableByteChannel. In case of errors, an error record is returned

public function base64EncodeString(string valueToBeEncoded, string charset) returns (string|error<>)

Encodes a given string with Base64 encoding scheme.

Parameter Name Data Type Default Value Description
valueToBeEncoded string

Content that needs to be encoded

charset string utf-8

Charset to be used

Return Type Description
string|error<>

An encoded string. In case of errors, an error record is returned

public function byteArrayToString(byte[] b, string encoding) returns (string)

Converts given byte[] to a string.

Parameter Name Data Type Default Value Description
b byte[]
encoding string

Encoding to used in byte[] conversion to string

Return Type Description
string

String representation of the given byte[]

public function getContentDispositionObject(string contentDisposition) returns (ContentDisposition)

Given the Content-Disposition as a string, gets the ContentDisposition object with it.

Parameter Name Data Type Default Value Description
contentDisposition string

Content disposition string

Return Type Description
ContentDisposition

A ContentDisposition object

public function getMediaType(string contentType) returns (MediaType|error<>)

Given the Content-Type in string, gets the MediaType object populated with it.

Parameter Name Data Type Default Value Description
contentType string

Content-Type in string

Return Type Description
MediaType|error<>

MediaType object or an error in case of invalid content-type

public type ContentDisposition object

Represents values in Content-Disposition header.

Field Name Data Type Default Value Description
fileName string

Default filename for storing the bodypart, if the receiving agent wishes to store it in an external file

disposition string

Indicates how the body part should be presented (inline, attachment or as form-data)

name string

Represents the field name in case of multipart/form-data

parameters map<string> {}

A set of parameters, specified in attribute=value notation

  • <ContentDisposition> toString() returns (string)

    Converts the ContentDisposition type to a string suitable for use as the value of a corresponding MIME header.

    Return Type Description
    string

    The string represnetation of the ContentDisposition object

public type Entity object

Represents the headers and body of a message. This can be used to represent both the entity of a top level message and an entity(body part) inside of a multipart entity.

  • <Entity> setContentType(string mediaType) returns (error?<>)

    Sets the content-type to entity.

    Parameter Name Data Type Default Value Description
    mediaType string

    Content type that needs to be set to the entity

    Return Type Description
    error?<>

    Nil if successful, error in case of invalid media-type

  • <Entity> getContentType() returns (string)

    Gets the content type of entity.

    Return Type Description
    string

    Content type as a string

  • <Entity> setContentId(string contentId)

    Sets the content ID of the entity.

    Parameter Name Data Type Default Value Description
    contentId string

    Content ID that needs to be set to entity

  • <Entity> getContentId() returns (string)

    Gets the content ID of entity.

    Return Type Description
    string

    Content ID as a string

  • <Entity> setContentLength(int contentLength)

    Sets the content length of the entity.

    Parameter Name Data Type Default Value Description
    contentLength int

    Content length that needs to be set to entity

  • <Entity> getContentLength() returns (int|error<>)

    Gets the content length of entity.

    Return Type Description
    int|error<>

    Content length as an int

  • <Entity> setContentDisposition(mime:ContentDisposition contentDisposition)

    Sets the content disposition of the entity.

    Parameter Name Data Type Default Value Description
    contentDisposition mime:ContentDisposition

    Content disposition that needs to be set to entity

  • <Entity> getContentDisposition() returns (ContentDisposition)

    Gets the content disposition of entity.

    Return Type Description
    ContentDisposition

    A ContentDisposition object

  • <Entity> setBody(string|xml|json|byte[]|io:ReadableByteChannel|mime:Entity[] entityBody)

    Sets the entity body with the given content.

    Parameter Name Data Type Default Value Description
    entityBody string|xml|json|byte[]|io:ReadableByteChannel|mime:Entity[]

    Entity body can be of type string,xml,json,byte[],io:ReadableByteChannel or Entity[]

  • <Entity> setFileAsEntityBody(string filePath, string contentType)

    Sets the entity body with a given file. This method overrides any existing content-type headers with the default content type application/octet-stream. The default value application/octet-stream can be overridden by passing the content type as an optional parameter.

    Parameter Name Data Type Default Value Description
    filePath string

    Represents the path to the file

    contentType string application/octet-stream

    Content type to be used with the payload. This is an optional parameter. application/octet-stream is used as the default value.

  • <Entity> setJson(json jsonContent, string contentType)

    Sets the entity body with the given json content. This method overrides any existing content-type headers with the default content type application/json. The default value application/json can be overridden by passing the content type as an optional parameter.

    Parameter Name Data Type Default Value Description
    jsonContent json

    JSON content that needs to be set to entity

    contentType string application/json

    Content type to be used with the payload. This is an optional parameter. application/json is used as the default value.

  • <Entity> getJson() returns (json|error<>)

    Extracts JSON body from the entity. If the entity body is not a JSON, an error is returned.

    Return Type Description
    json|error<>

    json data extracted from the the entity body. An error record is returned in case of errors.

  • <Entity> setXml(xml xmlContent, string contentType)

    Sets the entity body with the given XML content. This method overrides any existing content-type headers with the default content-type application/xml. The default value application/xml can be overridden by passing the content-type as an optional parameter.

    Parameter Name Data Type Default Value Description
    xmlContent xml

    XML content that needs to be set to entity

    contentType string application/xml

    Content type to be used with the payload. This is an optional parameter. application/xml is used as the default value.

  • <Entity> getXml() returns (xml|error<>)

    Extracts xml body from the entity. If the entity body is not an XML, an error is returned.

    Return Type Description
    xml|error<>

    xml data extracted from the the entity body. An error record is returned in case of errors.

  • <Entity> setText(string textContent, string contentType)

    Sets the entity body with the given text content. This method overrides any existing content-type headers with the default content-type text/plain. The default value text/plain can be overridden by passing the content type as an optional parameter.

    Parameter Name Data Type Default Value Description
    textContent string

    Text content that needs to be set to entity

    contentType string text/plain

    Content type to be used with the payload. This is an optional parameter. text/plain is used as the default value.

  • <Entity> getText() returns (string|error<>)

    Extracts text body from the entity. If the entity body is not text compatible an error is returned.

    Return Type Description
    string|error<>

    string data extracted from the the entity body or error in case of errors.

  • <Entity> setByteArray(byte[] blobContent, string contentType)

    Sets the entity body with the given byte[] content. This method overrides any existing content-type headers with the default content type application/octet-stream. The default value application/octet-stream can be overridden by passing the content type as an optional parameter.

    Parameter Name Data Type Default Value Description
    blobContent byte[]

    byte[] content that needs to be set to entity

    contentType string application/octet-stream

    Content type to be used with the payload. This is an optional parameter. application/octet-stream is used as the default value.

  • <Entity> getByteArray() returns (byte[]|error<>)

    Given an entity, gets the entity body as a byte[]. If the entity size is considerably large consider using getByteChannel() method instead.

    Return Type Description
    byte[]|error<>

    byte[] data extracted from the the entity body. An error record is returned in case of errors.

  • <Entity> setByteChannel(io:ReadableByteChannel byteChannel, string contentType)

    Sets the entity body with the given byte channel content. This method overrides any existing content-type headers with the default content-type application/octet-stream. The default value application/octet-stream can be overridden by passing the content-type as an optional parameter.

    Parameter Name Data Type Default Value Description
    byteChannel io:ReadableByteChannel

    Byte channel that needs to be set to entity

    contentType string application/octet-stream

    Content-type to be used with the payload. This is an optional parameter. application/octet-stream is used as the default value.

  • <Entity> getByteChannel() returns (io:ReadableByteChannel|error<>)

    Given an entity, gets the entity body as a byte channel.

    Return Type Description
    io:ReadableByteChannel|error<>

    An io:ReadableByteChannel. An error record will be returned in case of errors

  • <Entity> getBodyParts() returns (Entity[]|error<>)

    Given an entity, gets its body parts. If the entity body is not a set of body parts an error will be returned.

    Return Type Description
    Entity[]|error<>

    An array of body parts(Entity[]) extracted from the entity body. An error record will be returned in case of errors.

  • <Entity> getBodyPartsAsChannel() returns (io:ReadableByteChannel|error<>)

    Given an entity, gets the body parts as a byte channel.

    Return Type Description
    io:ReadableByteChannel|error<>

    Body parts as a byte channel

  • <Entity> setBodyParts(mime:Entity[] bodyParts, string contentType)

    Sets body parts to entity. This method overrides any existing content-type headers with the default content type multipart/form-data. The default value multipart/form-data can be overridden by passing the content type as an optional parameter.

    Parameter Name Data Type Default Value Description
    bodyParts mime:Entity[]

    Represents the body parts that needs to be set to the entity

    contentType string multipart/form-data

    Content-type to be used with the payload. This is an optional parameter. multipart/form-data is used as the default value.

  • <Entity> getHeader(string headerName) returns (string)

    Gets the header value associated with the given header name.

    Parameter Name Data Type Default Value Description
    headerName string

    Represents header name

    Return Type Description
    string

    Header value associated with the given header name as a string. If multiple header values are present, then the first value is returned. An exception is thrown if no header is found. Use hasHeader() beforehand to check the existence of header.

  • <Entity> getHeaders(string headerName) returns (string[])

    Gets all the header values associated with the given header name.

    Parameter Name Data Type Default Value Description
    headerName string

    The header name

    Return Type Description
    string[]

    All the header values associated with the given header name as a string[]. An exception is thrown if no header is found. Use hasHeader() beforehand to check the existence of header.

  • <Entity> getHeaderNames() returns (string[])

    Gets all header names.

    Return Type Description
    string[]

    All header names as a string[]

  • <Entity> addHeader(string headerName, string headerValue)

    Adds the given header value against the given header.

    Parameter Name Data Type Default Value Description
    headerName string

    The header name

    headerValue string

    Represents the header value to be added

  • <Entity> setHeader(string headerName, string headerValue)

    Sets the given header value against the existing header. If a header already exists, its value is replaced with the given header value.

    Parameter Name Data Type Default Value Description
    headerName string

    The header name

    headerValue string

    Represents the header value

  • <Entity> removeHeader(string headerName)

    Removes the given header from the entity.

    Parameter Name Data Type Default Value Description
    headerName string

    Represents the header name

  • <Entity> removeAllHeaders()

    Removes all headers associated with the entity.

  • <Entity> hasHeader(string headerName) returns (boolean)

    Checks whether the requested header key exists in the header map.

    Parameter Name Data Type Default Value Description
    headerName string

    The header name

    Return Type Description
    boolean

    True if the specified header key exists

public type MediaType object

Describes the nature of the data in the body of a MIME entity.

Field Name Data Type Default Value Description
primaryType string

Declares the general type of data

subType string

A specific format of the primary type data

suffix string

Identify the semantics of a specific media type

parameters map<string> {}

A set of parameters, specified in an attribute=value notation

  • <MediaType> getBaseType() returns (string)

    Gets “primaryType/subtype+suffix” combination in string format.

    Return Type Description
    string

    Base type as a string from MediaType struct

  • <MediaType> toString() returns (string)

    Converts the media type to a string, suitable to be used as the value of a corresponding HTTP header.

    Return Type Description
    string

    Content type with parameters as a string