ballerina/mime package

Package Overview

This package 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 package 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 to a string, and sends a response.

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

@http:ServiceConfig {basePath:"/test"}
service<http:Service> test bind {port:9090} {

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

       // Get the body parts from the request.
       match request.getBodyParts() {
           // If the body parts were returned, iterate through each body part and handle the content.
           mime:Entity[] bodyParts => {
               string content = "";
               foreach part in bodyParts {
                    content = content + " -- " + handleContent(part);
               }
               response.setPayload(content);
           }
           // 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.
          error err => {
              response.statusCode = 500;
              response.setPayload(err.message);
          }
       }
       client -> respond(response) but { error e => log:printError("Error in responding", err = e) };
   }
}

// The function that handles the content based on the body part type.
function handleContent(mime:Entity bodyPart) returns (string) {
   // Get the base type of the specific body part.
   string baseType = check mime:getMediaType(bodyPart.getContentType())!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();
       match payload {
           error err => return err.message;
           xml xmlContent => return xmlContent.getTextValue();
       }
   } else if (mime:APPLICATION_JSON == baseType) {
       // If the base type is ‘application/json’, get the JSON content from body part.
       var payload = bodyPart.getJson();
       match payload {
           error err => return err.message;
           json jsonContent => {
               return jsonContent.toString();
           }
       }
   } 
   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);

Objects Summary

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 Summary

Return Type Function and Description
blob | error base64DecodeBlob(blob valueToBeDecoded)

Decodes a given blob with Base64 encoding scheme.

ioByteChannel | error base64DecodeByteChannel(io:ByteChannel valueToBeDecoded)

Decodes a given ByteChannel with Base64 encoding scheme.

string | error base64DecodeString(string valueToBeDecoded, string charset)

Decodes a given string with Base64 encoding scheme.

blob | error base64EncodeBlob(blob valueToBeEncoded)

Encodes a given blob with Base64 encoding scheme.

ioByteChannel | error base64EncodeByteChannel(io:ByteChannel valueToBeEncoded)

Encodes a given ByteChannel with Base64 encoding scheme.

string | error base64EncodeString(string valueToBeEncoded, string charset)

Encodes a given string with Base64 encoding scheme.

ContentDisposition getContentDispositionObject(string contentDisposition)

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

MediaType | error getMediaType(string contentType)

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

Global Variables

Name Data Type Description
APPLICATION_FORM_URLENCODED string

Represent application/x-www-form-urlencoded media type.

APPLICATION_JSON string

Represent application/json media type.

APPLICATION_OCTET_STREAM string

Represent application/octet-stream media type.

APPLICATION_PDF string

Represent application/pdf media type.

APPLICATION_SOAP_XML string

Represent application/soap+xml media type.

APPLICATION_SVG_XML string

Represent application/svg+xml media type.

APPLICATION_XHTML_XML string

Represent application/xhtml+xml media type.

APPLICATION_XML string

Represent application/xml media type.

BOUNDARY string

Key name for boundary parameter in MediaType. This is needed for composite type media types.

CHARSET string

Key name for charset parameter in MediaType. This indicates the character set of the body text.

CONTENT_DISPOSITION string

Represents content-disposition header name.

CONTENT_ID string

Represents content-id header name.

CONTENT_LENGTH string

Represents content-length header name.

CONTENT_TYPE string

Represents content-type header name.

DEFAULT_CHARSET string

Default charset to be used with MIME encoding and decoding.

IMAGE_GIF string

Represent image/gif media type.

IMAGE_JPEG string

Represent image/jpeg media type.

IMAGE_PNG string

Represent image/png media type.

MULTIPART_ALTERNATIVE string

Represent multipart/alternative media type.

MULTIPART_FORM_DATA string

Represent multipart/form-data media type.

MULTIPART_MIXED string

Represent multipart/mixed media type.

MULTIPART_PARALLEL string

Represent multipart/parallel media type.

MULTIPART_RELATED string

Represent multipart/related media type.

START string

Key name for start parameter in MediaType. This determines which part in the multipart message contains the payload.

TEXT_HTML string

Represent text/html media type.

TEXT_PLAIN string

Represent text/plain media type.

TEXT_XML string

Represent text/xml media type.

TYPE string

Key name for type parameter in MediaType. This indicates the MIME media type of the root body part.

public function base64DecodeBlob(blob valueToBeDecoded) returns (blob | error)

Decodes a given blob with Base64 encoding scheme.

Parameter Name Data Type Default Value Description
valueToBeDecoded blob

Content that needs to be decoded

Return Type Description
blob | error

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

public function base64DecodeByteChannel(io:ByteChannel valueToBeDecoded) returns (ioByteChannel | error)

Decodes a given ByteChannel with Base64 encoding scheme.

Parameter Name Data Type Default Value Description
valueToBeDecoded io:ByteChannel

Content that needs to be decoded

Return Type Description
ioByteChannel | error

A decoded io:ByteChannel. 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(blob valueToBeEncoded) returns (blob | error)

Encodes a given blob with Base64 encoding scheme.

Parameter Name Data Type Default Value Description
valueToBeEncoded blob

Content that needs to be encoded

Return Type Description
blob | error

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

public function base64EncodeByteChannel(io:ByteChannel valueToBeEncoded) returns (ioByteChannel | error)

Encodes a given ByteChannel with Base64 encoding scheme.

Parameter Name Data Type Default Value Description
valueToBeEncoded io:ByteChannel

Content that needs to be encoded

Return Type Description
ioByteChannel | error

An encoded io:ByteChannel. 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 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 error

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

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)

    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

  • <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:0.0.0:ContentDisposition contentDisposition)

    Sets the content disposition of the entity.

    Parameter Name Data Type Default Value Description
    contentDisposition mime:0.0.0: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|blob|io:ByteChannel|mime:0.0.0:Entity[] entityBody)

    Sets the entity body with the given content.

    Parameter Name Data Type Default Value Description
    entityBody string|xml|json|blob|io:ByteChannel|mime:0.0.0:Entity[]

    Entity body can be of type string,xml,json,blob,io:ByteChannel 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> getBodyAsString() returns (string | error)

    Given an entity, gets the entity body as a string. Content type is checked during entity body construction which makes this different from getText() method.

    Return Type Description
    string | error

    Entity body as a string or error in case of errors occurred during construction of the string body.

  • <Entity> setBlob(blob blobContent, string contentType)

    Sets the entity body with the given blob 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 blob

    Blob 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> getBlob() returns (blob | error)

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

    Return Type Description
    blob | error

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

  • <Entity> setByteChannel(io:ByteChannel 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:ByteChannel

    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 (ioByteChannel | error)

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

    Return Type Description
    ioByteChannel | error

    An io:ByteChannel. 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 (ByteChannel)

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

    Return Type Description
    ByteChannel

    Body parts as a byte channel

  • <Entity> setBodyParts(mime:0.0.0: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:0.0.0: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

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