ballerina/mime package

Package Overview

This package provides functions to transmit and receive messages that have multiple parts, such as an attachment. 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 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. For example, 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 gets the message from each part of the body, converts the messages to a string, and sends a response.

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

endpoint http:Listener mockEP {
   port:9090
};

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

   @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 there is an error while getting the body parts, set the response code as 500 and set the error message as the response message.
           mime:EntityError err => {
               response.statusCode = 500;
               response.setStringPayload(err.message);
           }
           // If the body parts were returned, iterate through each body part and handle the content.
           mime:Entity[] bodyParts => {
               string content = "";
               int i = 0;
               while (i < lengthof bodyParts) {
                   mime:Entity part = bodyParts[i];
                   content = content + " -- " + handleContent(part);
                   i = i + 1;
               }
               response.setStringPayload(content);
           }
       }
       _ = client -> respond(response);
   }

}

// The function that handles the content based on the body part type.
function handleContent(mime:Entity bodyPart) returns (string) {
   // Getting the base type of the specific body part.
   string baseType = bodyPart.contentType.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 {
           mime:EntityError err => return "Error in getting xml payload";
           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 {
           mime:EntityError err => return "Error in getting json payload";
           json jsonContent => {
               return jsonContent.toString();
           }
       }
   } 
   return "";
}

The sample request that is sent to the above service and the response that is printed on the console are shown below.

curl -v -F "request={\"param1\": \"value1\"};type=application/json" -F "language=ballerina;type=text/plain" -F "upload=@/home/megala/encode.txt;type=application/octet-stream"  http://localhost:9090/test/multipleparts -H "Expect:"
*   Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 9090 (#0)
> POST /test/multipleparts HTTP/1.1
> Host: localhost:9090
> User-Agent: curl/7.47.0
> Accept: */*
> Content-Length: 521
> Content-Type: multipart/form-data; boundary=------------------------bf3f6dafe84260f2
> 
< HTTP/1.1 200 OK
< content-type: text/plain
< content-length: 77
< server: ballerina/0.970.0-beta1-SNAPSHOT
< date: Wed, 18 Apr 2018 22:20:48 +0530
< 
 -- {"param1":"value1"} -- ballerina -- VGhpcyBpcyBhIGJhbGxlcmluYSBzYW1wbGU=

Create a multipart response

The sample given below creates a multipart response. It includes ‘application/json’ and ‘text/xml’ type content.

// Create a new body part.
mime:Entity bodyPart1 = new;
// Set the content type as ‘application/json’.
bodyPart1.contentType = mime:getMediaType(mime:APPLICATION_JSON);
// Finally, set the JSON content.
bodyPart1.setJson({"bodyPart":"jsonPart"});

// Create body part using an XML file.
mime:Entity bodyPart2 = new;
mime:MediaType textXml = mime:getMediaType(mime:TEXT_XML);
bodyPart2.contentType = textXml;
file:Path fileHandler = new("ballerina/mime/file.xml");
bodyPart2.setFileAsEntityBody(fileHandler);

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

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

Primitives Summary

Type Description

Type Definitions

Type Values Description

Annotations

Name Attachement Points Data Type Description

Objects Summary

Object Description
Base64DecodeError
Represent errors related to mime base64 decoder.
Base64EncodeError
Represent errors related to mime base64 encoder.
EntityError
Represent all entity related errors.

Endpoints Summary

Endpoint Description

Functions Summary

Return Type Function and Description
blob | Base64DecodeError base64DecodeBlob(blob valueToBeDecoded)
Decode a given blob with Base64 encoding scheme.
ioByteChannel | Base64DecodeError base64DecodeByteChannel(ByteChannel valueToBeDecoded)
Decode a given ByteChannel with Base64 encoding scheme.
string | Base64DecodeError base64DecodeString(string valueToBeDecoded)
Decode a given string with Base64 encoding scheme.
blob | Base64EncodeError base64EncodeBlob(blob valueToBeEncoded)
Encode a given blob with Base64 encoding scheme.
ioByteChannel | Base64EncodeError base64EncodeByteChannel(ByteChannel valueToBeEncoded)
Encode a given ByteChannel with Base64 encoding scheme.
string | Base64EncodeError base64EncodeString(string valueToBeEncoded)
Encode a given string with Base64 encoding scheme.
ContentDisposition getContentDispositionObject(string contentDisposition)
Given the Content-Disposition as a string, get the ContentDisposition struct object with it.
MediaType | error getMediaType(string contentType)
Given the Content-Type in string, get 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_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. Indicate the character set of the body text.
CONTENT_DISPOSITION string
Represent 'content-disposition' header name.
CONTENT_ID string
Represent 'content-id' header name.
CONTENT_LENGTH string
Represent 'content-length' header name.
CONTENT_TYPE string
Represent '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 object Base64DecodeError

Represent errors related to mime base64 decoder.

Field Name Data Type Default Value Description
message string

The error message

cause error

The cause of the error

public object Base64EncodeError

Represent errors related to mime base64 encoder.

Field Name Data Type Default Value Description
message string

The error message

cause error

The cause of the error

public object EntityError

Represent all entity related errors.

Field Name Data Type Default Value Description
message string

The error message

cause error

The error which caused the entity error

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

Decode 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 | Base64DecodeError

Return a decoded blob

public function base64DecodeByteChannel(ByteChannel valueToBeDecoded) returns (ioByteChannel | Base64DecodeError)

Decode a given ByteChannel with Base64 encoding scheme.

Parameter Name Data Type Default Value Description
valueToBeDecoded ByteChannel

Content that needs to be decoded

Return Type Description
ioByteChannel | Base64DecodeError

Return a decoded ByteChannel

public function base64DecodeString(string valueToBeDecoded) returns (string | Base64DecodeError)

Decode a given string with Base64 encoding scheme.

Parameter Name Data Type Default Value Description
valueToBeDecoded string

Content that needs to be decoded

Return Type Description
string | Base64DecodeError

Return a decoded string

public function base64EncodeBlob(blob valueToBeEncoded) returns (blob | Base64EncodeError)

Encode 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 | Base64EncodeError

Return an encoded blob

public function base64EncodeByteChannel(ByteChannel valueToBeEncoded) returns (ioByteChannel | Base64EncodeError)

Encode a given ByteChannel with Base64 encoding scheme.

Parameter Name Data Type Default Value Description
valueToBeEncoded ByteChannel

Content that needs to be encoded

Return Type Description
ioByteChannel | Base64EncodeError

Return an encoded ByteChannel

public function base64EncodeString(string valueToBeEncoded) returns (string | Base64EncodeError)

Encode a given string with Base64 encoding scheme.

Parameter Name Data Type Default Value Description
valueToBeEncoded string

Content that needs to be encoded

Return Type Description
string | Base64EncodeError

Return an encoded string

public function getContentDispositionObject(string contentDisposition) returns (ContentDisposition)

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

Parameter Name Data Type Default Value Description
contentDisposition string

content disposition string

Return Type Description
ContentDisposition

Return ContentDisposition object

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

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

Parameter Name Data Type Default Value Description
contentType string

Content-Type in string

Return Type Description
MediaType | error

Return MediaType struct or an error in case of error

public type ContentDisposition object

Represent 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

Represent 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)

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

    Return Type Description
    string

    Return the ContentDisposition object's content as a string

public type Entity object

Represent 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)

        Set the content-type to entity.
    

    Parameter Name Data Type Default Value Description
    mediaType string

    content-type that needs to be set to entity

  • <Entity> getContentType() returns (string)

        Get the content-type of entity.
    

    Return Type Description
    string

    Return content-type as a string

  • <Entity> setContentId(string contentId)

        Set 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)

        Get the content-id of entity.
    

    Return Type Description
    string

    Return content-id as a string

  • <Entity> setContentLength(int contentLength)

        Set 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)

        Get the content-length of entity.
    

    Return Type Description
    int | error

    Return content-length as an int

  • <Entity> setContentDisposition(ContentDisposition contentDisposition)

        Set the content-disposition of the entity.
    

    Parameter Name Data Type Default Value Description
    contentDisposition ContentDisposition

    content-disposition that needs to be set to entity

  • <Entity> getContentDisposition() returns (ContentDisposition)

        Get the content-disposition of entity.
    

    Return Type Description
    ContentDisposition

    Return ContentDisposition object

  • <Entity> setBody(string | xml | json | blob | ioByteChannel | Entity[] entityBody)

        Set the entity body with a given content.
    

    Parameter Name Data Type Default Value Description
    entityBody string | xml | json | blob | ioByteChannel | Entity[]
  • <Entity> setFileAsEntityBody(string filePath)

        Set the entity body with a given file handler.
    

    Parameter Name Data Type Default Value Description
    filePath string

    Represent a file

  • <Entity> setJson(json jsonContent)

        Set the entity body with the given json content.
    

    Parameter Name Data Type Default Value Description
    jsonContent json

    Json content that needs to be set to entity

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

        Given an entity, get the entity body in json form.
    

    Return Type Description
    json | EntityError

    Return json data

  • <Entity> setXml(xml xmlContent)

        Set the entity body with the given xml content
    

    Parameter Name Data Type Default Value Description
    xmlContent xml

    Xml content that needs to be set to entity

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

        Given an entity, get the entity body in xml form.
    

    Return Type Description
    xml | EntityError

    Return xml data

  • <Entity> setText(string textContent)

        Set the entity body with the given text content.
    

    Parameter Name Data Type Default Value Description
    textContent string

    Text content that needs to be set to entity

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

        Given an entity, get the entity body in text form.
    

    Return Type Description
    string | EntityError

    Return text data

  • <Entity> setBlob(blob blobContent)

        Set the entity body with the given blob content.
    

    Parameter Name Data Type Default Value Description
    blobContent blob

    Blob content that needs to be set to entity

  • <Entity> getBlob() returns (blob | EntityError)

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

    Return Type Description
    blob | EntityError

    Return a blob

  • <Entity> setByteChannel(ByteChannel byteChannel)

        Set the entity body with the given byte channel content.
    

    Parameter Name Data Type Default Value Description
    byteChannel ByteChannel

    Byte channel that needs to be set to entity

  • <Entity> getByteChannel() returns (ioByteChannel | EntityError)

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

    Return Type Description
    ioByteChannel | EntityError

    Return a byte channel

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

        Given an entity, get its body parts.
    

    Return Type Description
    Entity[] | EntityError

    Return an array of entities which represent its body parts

  • <Entity> getBodyPartsAsChannel() returns (ByteChannel)

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

    Return Type Description
    ByteChannel

    Return body parts as a byte channel

  • <Entity> setBodyParts(Entity[] bodyParts)

        Set body parts to entity.
    

    Parameter Name Data Type Default Value Description
    bodyParts Entity[]

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

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

        Get the header value associated with the given header name.
    

    Parameter Name Data Type Default Value Description
    headerName string

    Represent header name

    Return Type Description
    string

    Return header value associated with the given header name. If multiple header values are present, then the first value will be returned

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

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

    Parameter Name Data Type Default Value Description
    headerName string

    Represent the header name

    Return Type Description
    string[]

    Return all the header values associated with the given header name as a string of arrays

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

        Get all header names.
    

    Return Type Description
    string[]

    Return all header names as an array of strings

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

        Add the given header value against the given header.
    

    Parameter Name Data Type Default Value Description
    headerName string

    Represent the header name

    headerValue string

    Represent the header value to be added

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

        Set the given header value against the given header. If a header already exist, its value will be replaced
        with the given header value.
    

    Parameter Name Data Type Default Value Description
    headerName string

    Represent the header name

    headerValue string

    Represent the header value

  • <Entity> removeHeader(string headerName)

        Remove the given header from the entity.
    

    Parameter Name Data Type Default Value Description
    headerName string

    Represent the header name

  • <Entity> removeAllHeaders()

        Remove all headers associated with the entity.
    

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

        Check the header existence.
    

    Parameter Name Data Type Default Value Description
    headerName string
    Return Type Description
    boolean

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)

        Get ���primaryType/subtype+suffix��� combination in string format.
    

    Return Type Description
    string

    Return base type from MediaType struct

  • <MediaType> toString() returns (string)

        Convert the media type to a string suitable for use as the value of a corresponding HTTP header.
    

    Return Type Description
    string

    Return the Content-Type with parameters as a string