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

Objects Summary

Object Description
ContentDisposition

Represent values in Content-Disposition header.

Entity

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.

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)

Decode a given blob with Base64 encoding scheme.

ioByteChannel | error base64DecodeByteChannel(ByteChannel valueToBeDecoded)

Decode a given ByteChannel with Base64 encoding scheme.

string | error base64DecodeString(string valueToBeDecoded)

Decode a given string with Base64 encoding scheme.

blob | error base64EncodeBlob(blob valueToBeEncoded)

Encode a given blob with Base64 encoding scheme.

ioByteChannel | error base64EncodeByteChannel(ByteChannel valueToBeEncoded)

Encode a given ByteChannel with Base64 encoding scheme.

string | error 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 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 function base64DecodeBlob(blob valueToBeDecoded) returns (blob | error)

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 | error

Return a decoded blob. An error will be returned, in case of errors

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

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 | error

Return a decoded io:ByteChannel. An error will be returned, in case of errors

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

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 | error

Return a decoded string. An error will be returned, in case of errors

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

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 | error

Return an encoded blob. An error record will be returned, in case of errors

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

Encode a given ByteChannel with Base64 encoding scheme.

Parameter Name Data Type Default Value Description
valueToBeEncoded ByteChannel

Content that needs to be encoded Return an encoded io:ByteChannel. An error record will be returned in case of errors

Return Type Description
ioByteChannel | error

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

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 | error

Return an encoded string. An error record will be returned in case of errors

public function getContentDispositionObject(string contentDisposition) returns (ContentDisposition)

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

Parameter Name Data Type Default Value Description
contentDisposition string

content disposition string

Return Type Description
ContentDisposition

Return a 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 object 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 a string represnetation of ContentDisposition object

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 a 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 body can be of type string,xml,json,blob,io:ByteChannel or Entity[]

  • <Entity> setFileAsEntityBody(string filePath)

    Set the entity body with a given file. This method will override any existing content-type headers with the default content-type 'application/octec-stream'. You can override the default value by passing the content-type as an optional parameter.

    Parameter Name Data Type Default Value Description
    filePath string

    Represent the path to the file

  • <Entity> setJson(json jsonContent)

    Set the entity body with the given json content. This method will override any existing content-type headers with the default content-type 'application/json'. You can override the default value 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

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

    Extract json body from the entity. If the entity body is not json compatible an error will be returned.

    Return Type Description
    json | error

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

  • <Entity> setXml(xml xmlContent)

    Set the entity body with the given xml content. This method will override any existing content-type headers with the default content-type 'application/xml'. You can override the default value 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

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

    Extract xml body from the entity. If the entity body is not xml compatible an error will be returned.

    Return Type Description
    xml | error

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

  • <Entity> setText(string textContent)

    Set the entity body with the given text content. This method will override any existing content-type headers with the default content-type 'text/plain'. You can override the default value 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

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

    Extract text body from the entity. If the entity body is not text compatible an error will be returned.

    Return Type Description
    string | error

    Return string data extracted from the the entity body. An error record will be returned in case of errors.

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

    Given an entity, get the entity body as a string. Content-type will not be checked during entity body construction which makes this different from getText() method.

    Return Type Description
    string | error

    Return entity body as a string. An error record will be returned in case of errors occurred during construction of the string body.

  • <Entity> setBlob(blob blobContent)

    Set the entity body with the given blob content. This method will override any existing content-type headers with the default content-type 'application/octec-stream'. You can override the default value 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

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

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

    Return Type Description
    blob | error

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

  • <Entity> setByteChannel(ByteChannel byteChannel)

    Set the entity body with the given byte channel content. This method will override any existing content-type headers with the default content-type 'application/octec-stream'. You can override the default value by passing the content-type as an optional parameter.

    Parameter Name Data Type Default Value Description
    byteChannel ByteChannel

    Byte channel that needs to be set to entity

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

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

    Return Type Description
    ioByteChannel | error

    Return an io:ByteChannel. An error record will be returned in case of errors

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

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

    Return Type Description
    Entity[] | error

    Return 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, 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. This method will override any existing content-type headers with the default content-type 'multipart/form-data'. You can override the default value by passing the content-type as an optional parameter.

    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 as a string. 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[]

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

    Get all header names.

    Return Type Description
    string[]

    Return all header names as a string[]

  • <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 as a string from MediaType struct

  • <MediaType> toString() returns (string)

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

    Return Type Description
    string

    Return the content-type with parameters as a string