text:
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no, width=device-width">
<meta name="generator" content="joDoc">
<title>Apache Cordova API Documentation</title>
<link rel="stylesheet" type="text/css" href="index.css">
<link rel="stylesheet" type="text/css" href="mobile.css" media="only screen and (max-device-width: 1024px)">
<link rel="stylesheet" type="text/css" href="prettify/prettify.css">

Apache Cordova Documentation

                <select><optgroup label="English" value="en">
<option value="edge">edge</option>
<option value="2.9.0rc1">2.9.0rc1</option>
<option value="2.9.0">2.9.0</option>
<option value="2.8.0">2.8.0</option>
<option value="2.7.0rc1">2.7.0rc1</option>
<option value="2.7.0">2.7.0</option>
<option value="2.6.0rc1">2.6.0rc1</option>
<option selected value="2.6.0">2.6.0</option>
<option value="2.5.0rc1">2.5.0rc1</option>
<option value="2.5.0">2.5.0</option>
<option value="2.4.0rc1">2.4.0rc1</option>
<option value="2.4.0">2.4.0</option>
<option value="2.3.0rc2">2.3.0rc2</option>
<option value="2.3.0rc1">2.3.0rc1</option>
<option value="2.3.0">2.3.0</option>
<option value="2.2.0rc2">2.2.0rc2</option>
<option value="2.2.0rc1">2.2.0rc1</option>
<option value="2.2.0">2.2.0</option>
<option value="2.1.0rc2">2.1.0rc2</option>
<option value="2.1.0rc1">2.1.0rc1</option>
<option value="2.1.0">2.1.0</option>
<option value="2.0.0rc1">2.0.0rc1</option>
<option value="2.0.0">2.0.0</option>
<option value="1.9.0rc1">1.9.0rc1</option>
<option value="1.9.0">1.9.0</option>
<option value="1.8.1">1.8.1</option>
<option value="1.8.0rc1">1.8.0rc1</option>
<option value="1.8.0">1.8.0</option>
<option value="1.7.0rc1">1.7.0rc1</option>
<option value="1.7.0">1.7.0</option>
<option value="1.6.1">1.6.1</option>
<option value="1.6.0rc1">1.6.0rc1</option>
<option value="1.6.0">1.6.0</option>
<option value="1.5.0rc1">1.5.0rc1</option>
<option value="1.5.0">1.5.0</option>
</optgroup>
<optgroup label="Japanese" value="jp">
<option value="2.2.0">2.2.0</option>
<option value="2.1.0">2.1.0</option>
<option value="2.0.0">2.0.0</option>
<option value="1.9.0">1.9.0</option>
<option value="1.8.1">1.8.1</option>
<option value="1.7.0">1.7.0</option>
</optgroup>
<optgroup label="Korean" value="kr"><option value="2.0.0">2.0.0</option></optgroup></select>

File

            <select><option value="File">File</option>
<option value="File_objects">      - Objects</option>
<option value="File_permissions">      - Permissions</option>
<option value="File">File</option>
<option value="File_properties">      - Properties</option>
<option value="File_methods">      - Methods</option>
<option value="File_details">      - Details</option>
<option value="File_supported_platforms">      - Supported Platforms</option>
<option value="File_slice">      - slice</option>
<option value="FileReader">FileReader</option>
<option value="FileReader_properties">      - Properties</option>
<option value="FileReader_methods">      - Methods</option>
<option value="FileReader_details">      - Details</option>
<option value="FileReader_supported_platforms">      - Supported Platforms</option>
<option value="FileReader_read_as_data_url">      - Read As Data URL </option>
<option value="FileReader_quick_example">      - Quick Example</option>
<option value="FileReader_read_as_text">      - Read As Text</option>
<option value="FileReader_quick_example">      - Quick Example</option>
<option value="FileReader_abort_quick_example">      - Abort Quick Example</option>
<option value="FileReader_full_example">      - Full Example</option>
<option value="FileReader_ios_quirks">      - iOS Quirks</option>
<option value="FileReader_read_as_binary_string">      - Read As Binary String</option>
<option value="FileReader_quick_example">      - Quick Example</option>
<option value="FileReader_read_as_array_buffer">      - Read As Array Buffer</option>
<option value="FileReader_quick_example">      - Quick Example</option>
<option value="FileWriter">FileWriter</option>
<option value="FileWriter_properties">      - Properties</option>
<option value="FileWriter_methods">      - Methods</option>
<option value="FileWriter_details">      - Details</option>
<option value="FileWriter_supported_platforms">      - Supported Platforms</option>
<option value="FileWriter_seek_quick_example">      - Seek Quick Example</option>
<option value="FileWriter_truncate_quick_example">      - Truncate Quick Example</option>
<option value="FileWriter_write_quick_example">      - Write Quick Example</option>
<option value="FileWriter_append_quick_example">      - Append Quick Example</option>
<option value="FileWriter_abort_quick_example">      - Abort Quick Example</option>
<option value="FileWriter_full_example">      - Full Example</option>
<option value="FileSystem">FileSystem</option>
<option value="FileSystem_properties">      - Properties</option>
<option value="FileSystem_details">      - Details</option>
<option value="FileSystem_supported_platforms">      - Supported Platforms</option>
<option value="FileSystem_file_system_quick_example">      -
File System Quick Example</option>
<option value="FileSystem_full_example">      - Full Example</option>
<option value="FileEntry">FileEntry</option>
<option value="FileEntry_properties">      - Properties</option>
<option value="FileEntry_methods">      - Methods</option>
<option value="FileEntry_supported_platforms">      - Supported Platforms</option>
<option value="FileEntry_getmetadata">      - getMetadata</option>
<option value="FileEntry_setmetadata">      - setMetadata</option>
<option value="FileEntry_moveto">      - moveTo</option>
<option value="FileEntry_copyto">      - copyTo</option>
<option value="FileEntry_tourl">      - toURL</option>
<option value="FileEntry_remove">      - remove</option>
<option value="FileEntry_getparent">      - getParent</option>
<option value="FileEntry_createwriter">      - createWriter</option>
<option value="FileEntry_file">      - file</option>
<option value="DirectoryEntry">DirectoryEntry</option>
<option value="DirectoryEntry_properties">      - Properties</option>
<option value="DirectoryEntry_methods">      - Methods</option>
<option value="DirectoryEntry_supported_platforms">      - Supported Platforms</option>
<option value="DirectoryEntry_getmetadata">      - getMetadata</option>
<option value="DirectoryEntry_setmetadata">      - setMetadata</option>
<option value="DirectoryEntry_moveto">      - moveTo</option>
<option value="DirectoryEntry_copyto">      - copyTo</option>
<option value="DirectoryEntry_tourl">      - toURL</option>
<option value="DirectoryEntry_remove">      - remove</option>
<option value="DirectoryEntry_getparent">      - getParent</option>
<option value="DirectoryEntry_createreader">      - createReader</option>
<option value="DirectoryEntry_getdirectory">      - getDirectory</option>
<option value="DirectoryEntry_getfile">      - getFile</option>
<option value="DirectoryEntry_removerecursively">      - removeRecursively</option>
<option value="DirectoryEntry_blackberry_quirks">      - BlackBerry Quirks</option>
<option value="DirectoryReader">DirectoryReader</option>
<option value="DirectoryReader_methods">      - Methods</option>
<option value="DirectoryReader_supported_platforms">      - Supported Platforms</option>
<option value="DirectoryReader_readentries">      - readEntries</option>
<option value="FileTransfer">FileTransfer</option>
<option value="FileTransfer_properties">      - Properties</option>
<option value="FileTransfer_methods">      - Methods</option>
<option value="FileTransfer_details">      - Details</option>
<option value="FileTransfer_supported_platforms">      - Supported Platforms</option>
<option value="FileTransfer_upload">      - upload</option>
<option value="FileTransfer_download">      - download</option>
<option value="FileTransfer_abort">      - abort</option>
<option value="FileTransfer_onprogress">      - onprogress</option>
<option value="FileUploadOptions">FileUploadOptions</option>
<option value="FileUploadOptions_properties">      - Properties</option>
<option value="FileUploadOptions_description">      - Description</option>
<option value="FileUploadOptions_wp7_quirk">      - WP7 Quirk</option>
<option value="FileUploadResult">FileUploadResult</option>
<option value="FileUploadResult_properties">      - Properties</option>
<option value="FileUploadResult_description">      - Description</option>
<option value="FileUploadResult_ios_quirks">      - iOS Quirks</option>
<option value="Flags">Flags</option>
<option value="Flags_properties">      - Properties</option>
<option value="Flags_supported_platforms">      - Supported Platforms</option>
<option value="Flags_quick_example">      - Quick Example</option>
<option value="LocalFileSystem">LocalFileSystem</option>
<option value="LocalFileSystem_methods">      - Methods</option>
<option value="LocalFileSystem_constants">      - Constants</option>
<option value="LocalFileSystem_details">      - Details</option>
<option value="LocalFileSystem_supported_platforms">      - Supported Platforms</option>
<option value="LocalFileSystem_request_file_system_quick_example">      - Request File System Quick Example</option>
<option value="LocalFileSystem_resolve_local_file_system_uri_quick_example">      - Resolve Local File System URI Quick Example</option>
<option value="LocalFileSystem_full_example">      - Full Example</option>
<option value="Metadata">Metadata</option>
<option value="Metadata_properties">      - Properties</option>
<option value="Metadata_details">      - Details</option>
<option value="Metadata_supported_platforms">      - Supported Platforms</option>
<option value="Metadata_quick_example">      - Quick Example</option>
<option value="FileError">FileError</option>
<option value="FileError_properties">      - Properties</option>
<option value="FileError_constants">      - Constants</option>
<option value="FileError_description">      - Description</option>
<option value="FileTransferError">FileTransferError</option>
<option value="FileTransferError_properties">      - Properties</option>
<option value="FileTransferError_constants">      - Constants</option>
<option value="FileTransferError_description">      - Description</option></select>

API Reference

Accelerometer

Camera

Capture

Compass

Connection

Contacts

Device

Events

File

Geolocation

Globalization

InAppBrowser

Media

Notification

Splashscreen

Storage

Guides

Getting Started Guides

Command-Line Usage

Upgrading Guides

Project Settings

Plugin Development Guide

Domain Whitelist Guide

Embedding WebView

Keyword Index

File

This API is based on the W3C File API. An API to read, write and navigate file system hierarchies.

Objects

DirectoryEntry

DirectoryReader

File

FileEntry

FileError

FileReader

FileSystem

FileTransfer

FileTransferError

FileUploadOptions

FileUploadResult

FileWriter

Flags

LocalFileSystem

Metadata

Permissions

Android

app/res/xml/config.xml

<plugin name="File" value="org.apache.cordova.FileUtils" />
<plugin name="FileTransfer" value="org.apache.cordova.FileTransfer" />

app/AndroidManifest.xml

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Bada

No permissions are required.

BlackBerry WebWorks

www/plugins.xml

<plugin name="File" value="org.apache.cordova.file.FileManager" />
<plugin name="FileTransfer" value="org.apache.cordova.http.FileTransfer" />

www/config.xml

<feature id="blackberry.io.file" required="true" version="1.0.0.0" />
<feature id="blackberry.utils"   required="true" version="1.0.0.0" />
<feature id="blackberry.io.dir"  required="true" version="1.0.0.0" />
<rim:permissions>
    <rim:permit>access_shared</rim:permit>
</rim:permissions>

iOS

config.xml

<plugin name="File" value="CDVFile" />
<plugin name="FileTransfer" value="CDVFileTransfer" />

webOS

No permissions are required.

Windows Phone

No permissions are required.

File

This object contains attributes of a single file.

Properties

name: The name of the file. (DOMString)

fullPath: The full path of the file including the file name. (DOMString)

type: The mime type of the file. (DOMString)

lastModifiedDate: The last time the file was modified. (Date)

size: The size of the file in bytes. (long)

Methods

slice: Select only a portion of the file to be read.

Details

The File object contains attributes of a single file.  You can get an instance of a File object by calling the file method of a FileEntry object.

Supported Platforms

Android

BlackBerry WebWorks (OS 5.0 and higher)

iOS

Windows Phone 7 and 8

Windows 8

slice

Return a new File object, for which FileReader will return only the specified portion of the file.
Negative values for start or end are measured from the end of the file.
The indexes are always relative to the current slice (see the full example).

Parameters:

start - The index of the first byte to read, inclusive.

end - The index of the byte after the last one to read.

Quick Example

var slicedFile = file.slice(10, 30);

Full Example

var slice1 = file.slice(100, 400);
var slice2 = slice1.slice(20, 35);

var slice3 = file.slice(120, 135);
// slice2 and slice3 are equivalent.

Supported Platforms:

Android

iOS

FileReader

FileReader is an object that allows one to read a file.

Properties

readyState: One of the three states the reader can be in EMPTY, LOADING or DONE.

result: The contents of the file that has been read. (DOMString)

error: An object containing errors. (FileError)

onloadstart: Called when the read starts. . (Function)

onprogress: Called while reading the file, reports progress (progess.loaded/progress.total). (Function) -NOT SUPPORTED

onload: Called when the read has successfully completed. (Function)

onabort: Called when the read has been aborted. For instance, by invoking the abort() method. (Function)

onerror: Called when the read has failed. (Function)

onloadend: Called when the request has completed (either in success or failure).  (Function)

Methods

abort: Aborts reading file.

readAsDataURL: Read file and return data as a base64 encoded data url.

readAsText: Reads text file.

readAsBinaryString: Reads file as binary and returns a binary string.

readAsArrayBuffer: Reads file as an ArrayBuffer.

Details

The FileReader object is a way to read files from the devices file system.  Files can be read as text or as a base64 data encoded string.  Users register their own event listeners to receive the loadstart, progress, load, loadend, error and abort events.

Supported Platforms

Android

BlackBerry WebWorks (OS 5.0 and higher)

iOS

Windows Phone 7 and 8

Windows 8

Read As Data URL

Parameters:
- file - the file object to read

Quick Example

function win(file) {
    var reader = new FileReader();
    reader.onloadend = function(evt) {
        console.log("read success");
        console.log(evt.target.result);
    };
    reader.readAsDataURL(file);
};

var fail = function(evt) {
    console.log(error.code);
};

entry.file(win, fail);

Read As Text

Parameters:

file - the file object to read

encoding - the encoding to use to encode the file's content. Default is UTF8.

Quick Example

function win(file) {
    var reader = new FileReader();
    reader.onloadend = function(evt) {
        console.log("read success");
        console.log(evt.target.result);
    };
    reader.readAsText(file);
};

var fail = function(evt) {
    console.log(error.code);
};

entry.file(win, fail);

Abort Quick Example

function win(file) {
    var reader = new FileReader();
    reader.onloadend = function(evt) {
        console.log("read success");
        console.log(evt.target.result);
    };
    reader.readAsText(file);
    reader.abort();
};

function fail(error) {
    console.log(error.code);
}

entry.file(win, fail);

Full Example

<!DOCTYPE html>
<html>
  <head>
    <title>FileReader Example</title>

    <script type="text/javascript" charset="utf-8" src="cordova-2.6.0.js"></script>
    <script type="text/javascript" charset="utf-8">

    // Wait for Cordova to load
    //
    function onLoad() {
        document.addEventListener("deviceready", onDeviceReady, false);
    }

    // Cordova is ready
    //
    function onDeviceReady() {
        window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
    }

    function gotFS(fileSystem) {
        fileSystem.root.getFile("readme.txt", null, gotFileEntry, fail);
    }

    function gotFileEntry(fileEntry) {
        fileEntry.file(gotFile, fail);
    }

    function gotFile(file){
        readDataUrl(file);
        readAsText(file);
    }

    function readDataUrl(file) {
        var reader = new FileReader();
        reader.onloadend = function(evt) {
            console.log("Read as data URL");
            console.log(evt.target.result);
        };
        reader.readAsDataURL(file);
    }

    function readAsText(file) {
        var reader = new FileReader();
        reader.onloadend = function(evt) {
            console.log("Read as text");
            console.log(evt.target.result);
        };
        reader.readAsText(file);
    }

    function fail(evt) {
        console.log(evt.target.error.code);
    }

    </script>
  </head>
  <body>
    <h1>Example</h1>
    <p>Read File</p>
  </body>
</html>

iOS Quirks

encoding parameter is not supported, UTF8 encoding is always used.

Read As Binary String

Currently supported on iOS and Android only.

Parameters:
- file - the file object to read

Quick Example

function win(file) {
    var reader = new FileReader();
    reader.onloadend = function(evt) {
        console.log("read success");
        console.log(evt.target.result);
    };
    reader.readAsBinaryString(file);
};

var fail = function(evt) {
    console.log(error.code);
};

entry.file(win, fail);

Read As Array Buffer

Currently supported on iOS and Android only.

Parameters:
- file - the file object to read

Quick Example

function win(file) {
    var reader = new FileReader();
    reader.onloadend = function(evt) {
        console.log("read success");
        console.log(new Uint8Array(evt.target.result));
    };
    reader.readAsArrayBuffer(file);
};

var fail = function(evt) {
    console.log(error.code);
};

entry.file(win, fail);

FileWriter

FileWriter is an object that allows one to write a file.

Properties

readyState: One of the three states the reader can be in INIT, WRITING or DONE.

fileName: The name of the file to be written. (DOMString)

length: The length of the file to be written. (long)

position: The current position of the file pointer. (long)

error: An object containing errors. (FileError)

onwritestart: Called when the write starts. . (Function)

onprogress: Called while writing the file, reports progress (progress.loaded/progress.total). (Function) -NOT SUPPORTED

onwrite: Called when the request has completed successfully.  (Function)

onabort: Called when the write has been aborted. For instance, by invoking the abort() method. (Function)

onerror: Called when the write has failed. (Function)

onwriteend: Called when the request has completed (either in success or failure).  (Function)

Methods

abort: Aborts writing file.

seek: Moves the file pointer to the byte specified.

truncate: Shortens the file to the length specified.

write: Writes data to the file with a UTF-8 encoding.

Details

The FileWriter object is a way to write files to the device file system (UTF-8 encoded).  Users register their own event listeners to receive the writestart, progress, write, writeend, error and abort events.

A FileWriter is created for a single file. You can use it to write to a file multiple times. The FileWriter maintains the file's position and length attributes, so you can seek and write anywhere in the file. By default, the FileWriter writes to the beginning of the file (will overwrite existing data). Set the optional append boolean to true in the FileWriter's constructor to begin writing to the end of the file.

Supported Platforms

Android

BlackBerry WebWorks (OS 5.0 and higher)

iOS

Windows Phone 7 and 8

Windows 8

Seek Quick Example

function win(writer) {
    // fast forwards file pointer to end of file
    writer.seek(writer.length);
};

var fail = function(evt) {
    console.log(error.code);
};

entry.createWriter(win, fail);

Truncate Quick Example

function win(writer) {
    writer.truncate(10);
};

var fail = function(evt) {
    console.log(error.code);
};

entry.createWriter(win, fail);

Write Quick Example

function win(writer) {
    writer.onwrite = function(evt) {
        console.log("write success");
    };
    writer.write("some sample text");
};

var fail = function(evt) {
    console.log(error.code);
};

entry.createWriter(win, fail);

Append Quick Example

function win(writer) {
    writer.onwrite = function(evt) {
        console.log("write success");
    };
    writer.seek(writer.length);
    writer.write("appended text");
};

var fail = function(evt) {
    console.log(error.code);
};

entry.createWriter(win, fail);

Abort Quick Example

function win(writer) {
    writer.onwrite = function(evt) {
        console.log("write success");
    };
    writer.write("some sample text");
    writer.abort();
};

var fail = function(evt) {
    console.log(error.code);
};

entry.createWriter(win, fail);

Full Example

<!DOCTYPE html>
<html>
  <head>
    <title>FileWriter Example</title>

    <script type="text/javascript" charset="utf-8" src="cordova-2.6.0.js"></script>
    <script type="text/javascript" charset="utf-8">

    // Wait for Cordova to load
    //
    document.addEventListener("deviceready", onDeviceReady, false);

    // Cordova is ready
    //
    function onDeviceReady() {
        window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
    }

    function gotFS(fileSystem) {
        fileSystem.root.getFile("readme.txt", {create: true, exclusive: false}, gotFileEntry, fail);
    }

    function gotFileEntry(fileEntry) {
        fileEntry.createWriter(gotFileWriter, fail);
    }

    function gotFileWriter(writer) {
        writer.onwriteend = function(evt) {
            console.log("contents of file now 'some sample text'");
            writer.truncate(11);
            writer.onwriteend = function(evt) {
                console.log("contents of file now 'some sample'");
                writer.seek(4);
                writer.write(" different text");
                writer.onwriteend = function(evt){
                    console.log("contents of file now 'some different text'");
                }
            };
        };
        writer.write("some sample text");
    }

    function fail(error) {
        console.log(error.code);
    }

    </script>
  </head>
  <body>
    <h1>Example</h1>
    <p>Write File</p>
  </body>
</html>

FileSystem

This object represents a file system.

Properties

name: The name of the file system. (DOMString)

root: The root directory of the file system. (DirectoryEntry)

Details

The FileSystem object represents information about the file system. The name of the file system will be unique across the list of exposed file systems.  The root property contains a DirectoryEntry object which represents the root directory of the file system.

Supported Platforms

Android

BlackBerry WebWorks (OS 5.0 and higher)

iOS

Windows Phone 7 and 8

Windows 8

File System Quick Example

function onSuccess(fileSystem) {
    console.log(fileSystem.name);
    console.log(fileSystem.root.name);
}

// request the persistent file system
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onSuccess, null);

Full Example

<!DOCTYPE html>
<html>
  <head>
    <title>File System Example</title>

    <script type="text/javascript" charset="utf-8" src="cordova-2.6.0.js"></script>
    <script type="text/javascript" charset="utf-8">

    // Wait for Cordova to load
    //
    document.addEventListener("deviceready", onDeviceReady, false);

    // Cordova is ready
    //
    function onDeviceReady() {
        window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFileSystemSuccess, fail);
    }

    function onFileSystemSuccess(fileSystem) {
        console.log(fileSystem.name);
        console.log(fileSystem.root.name);
    }

    function fail(evt) {
        console.log(evt.target.error.code);
    }

    </script>
  </head>
  <body>
    <h1>Example</h1>
    <p>File System</p>
  </body>
</html>

FileEntry

This object represents a file on a file system.  It is defined in the W3C Directories and Systems specification.

Properties

isFile: Always true. (boolean)

isDirectory: Always false. (boolean)

name: The name of the FileEntry, excluding the path leading to it. (DOMString)

fullPath: The full absolute path from the root to the FileEntry. (DOMString)

NOTE: The following attributes are defined by the W3C specification, but are not supported by Cordova:

filesystem: The file system on which the FileEntry resides. (FileSystem)

Methods

getMetadata: Look up metadata about a file.

setMetadata: Set metadata on a file.

moveTo: Move a file to a different location on the file system.

copyTo: Copy a file to a different location on the file system.

toURL: Return a URL that can be used to locate a file.

remove: Delete a file.

getParent: Look up the parent directory.

createWriter: Creates a FileWriter object that can be used to write to a file.

file: Creates a File object containing file properties.

Supported Platforms

Android

BlackBerry WebWorks (OS 5.0 and higher)

iOS

Windows Phone 7 and 8

Windows 8

getMetadata

Look up metadata about a file.

Parameters:

successCallback - A callback that is called with a Metadata object. (Function)

errorCallback - A callback that is called if an error occurs retrieving the Metadata. Invoked with a FileError object. (Function)

Quick Example

function success(metadata) {
    console.log("Last Modified: " + metadata.modificationTime);
}

function fail(error) {
    alert(error.code);
}

// Request the metadata object for this entry
entry.getMetadata(success, fail);

setMetadata

Set metadata on a file.
Only works on iOS currently - this will set the extended attributes of a file.

Parameters:

successCallback - A callback that is called when the metadata was successfully set. (Function)

errorCallback - A callback that is called when the metadata was not successfully set. (Function)

metadataObject - An object that contains the metadata keys and values. (Object)

Quick Example

function success() {
    console.log("The metadata was successfully set.");
}

function fail() {
    alert("There was an error in setting the metadata");
}

// Set the metadata
entry.setMetadata(success, fail, { "com.apple.MobileBackup": 1});

iOS Quirk

only the "com.apple.MobileBackup" extended attribute is supported. Set the value to 1 to NOT enable the file to be backed up by iCloud. Set the value to 0 to re-enable the file to be backed up by iCloud.

Quick Example

function setFileMetadata(localFileSystem, filePath, metadataKey, metadataValue)
{
    var onSetMetadataWin = function() {
      console.log("success setting metadata")
    }
    var onSetMetadataFail = function() {
      console.log("error setting metadata")
    }

    var onGetFileWin = function(parent) {
      var data = {};
      data[metadataKey] = metadataValue;
      parent.setMetadata(onSetMetadataWin, onSetMetadataFail, data);
    }
    var onGetFileFail = function() {
      console.log("error getting file")
    }

    var onFSWin = function(fileSystem) {
      fileSystem.root.getFile(filePath, {create: true, exclusive: false}, onGetFileWin, onGetFileFail);
    }

    var onFSFail = function(evt) {
      console.log(evt.target.error.code);
    }

    window.requestFileSystem(localFileSystem, 0, onFSWin, onFSFail);
}

setFileMetadata(LocalFileSystem.PERSISTENT, "Backups/sqlite.db", "com.apple.MobileBackup", 1);

moveTo

Move a file to a different location on the file system. It is an error to attempt to:

move a file into its parent if a name different from its current one isn't provided;

move a file to a path occupied by a directory;

In addition, an attempt to move a file on top of an existing file must attempt to delete and replace that file.

Parameters:

parent - The parent directory to which to move the file. (DirectoryEntry)

newName - The new name of the file. Defaults to the current name if unspecified. (DOMString)

successCallback - A callback that is called with the FileEntry object of the new file. (Function)

errorCallback - A callback that is called if an error occurs when attempting to move the file.  Invoked with a FileError object. (Function)

Quick Example

function success(entry) {
    console.log("New Path: " + entry.fullPath);
}

function fail(error) {
    alert(error.code);
}

function moveFile(entry) {
    var parent = document.getElementById('parent').value,
        parentName = parent.substring(parent.lastIndexOf('/')+1),
        parentEntry = new DirectoryEntry(parentName, parent);

    // move the file to a new directory and rename it
    entry.moveTo(parentEntry, "newFile.txt", success, fail);
}

copyTo

Copy a file to a new location on the file system.  It is an error to attempt to:

copy a file into its parent if a name different from its current one is not provided.

Parameters:

parent - The parent directory to which to copy the file. (DirectoryEntry)

newName - The new name of the file. Defaults to the current name if unspecified. (DOMString)

successCallback - A callback that is called with the FileEntry object of the new file. (Function)

errorCallback - A callback that is called if an error occurs when attempting to copy the file.  Invoked with a FileError object. (Function)

Quick Example

function win(entry) {
    console.log("New Path: " + entry.fullPath);
}

function fail(error) {
    alert(error.code);
}

function copyFile(entry) {
    var parent = document.getElementById('parent').value,
        parentName = parent.substring(parent.lastIndexOf('/')+1),
        parentEntry = new DirectoryEntry(parentName, parent);

    // copy the file to a new directory and rename it
    entry.copyTo(parentEntry, "file.copy", success, fail);
}

toURL

Returns a URL that can be used to locate the file.

Quick Example

// Request the URL for this entry
var fileURL = entry.toURL();
console.log(fileURL);

remove

Deletes a file.

Parameters:

successCallback - A callback that is called after the file has been deleted.  Invoked with no parameters. (Function)

errorCallback - A callback that is called if an error occurs when attempting to delete the file.  Invoked with a FileError object. (Function)

Quick Example

function success(entry) {
    console.log("Removal succeeded");
}

function fail(error) {
    alert('Error removing file: ' + error.code);
}

// remove the file
entry.remove(success, fail);

getParent

Look up the parent DirectoryEntry containing the file.

Parameters:

successCallback - A callback that is called with the file's parent DirectoryEntry. (Function)

errorCallback - A callback that is called if an error occurs when attempting to retrieve the parent DirectoryEntry.  Invoked with a FileError object. (Function)

Quick Example

function success(parent) {
    console.log("Parent Name: " + parent.name);
}

function fail(error) {
    alert(error.code);
}

// Get the parent DirectoryEntry
entry.getParent(success, fail);

createWriter

Create a FileWriter object associated with the file that the FileEntry represents.

Parameters:

successCallback - A callback that is called with a FileWriter object. (Function)

errorCallback - A callback that is called if an error occurs while attempting to create the FileWriter.  Invoked with a FileError object. (Function)

Quick Example

function success(writer) {
    writer.write("Some text to the file");
}

function fail(error) {
    alert(error.code);
}

// create a FileWriter to write to the file
entry.createWriter(success, fail);

file

Return a File object that represents the current state of the file that this FileEntry represents.

Parameters:

successCallback - A callback that is called with a File object. (Function)

errorCallback - A callback that is called if an error occurs when creating the File object (e.g. the underlying file no longer exists).  Invoked with a FileError object. (Function)

Quick Example

function success(file) {
    console.log("File size: " + file.size);
}

function fail(error) {
    alert("Unable to retrieve file properties: " + error.code);
}

// obtain properties of a file
entry.file(success, fail);

DirectoryEntry

This object represents a directory on a file system.  It is defined in the W3C Directories and Systems specification.

Properties

isFile: Always false. (boolean)

isDirectory: Always true. (boolean)

name: The name of the DirectoryEntry, excluding the path leading to it. (DOMString)

fullPath: The full absolute path from the root to the DirectoryEntry. (DOMString)

NOTE: The following attributes are defined by the W3C specification, but are not supported by Cordova:

filesystem: The file system on which the DirectoryEntry resides. (FileSystem)

Methods

The following methods can be invoked on a DirectoryEntry object:

getMetadata: Look up metadata about a directory.

setMetadata: Set metadata on a directory.

moveTo: Move a directory to a different location on the file system.

copyTo: Copy a directory to a different location on the file system.

toURL: Return a URL that can be used to locate a directory.

remove: Delete a directory.  The directory must be empty.

getParent: Look up the parent directory.

createReader: Create a new DirectoryReader that can read entries from a directory.

getDirectory: Create or look up a directory.

getFile: Create or look up a file.

removeRecursively: Delete a directory and all of its contents.

Supported Platforms

Android

BlackBerry WebWorks (OS 5.0 and higher)

iOS

Windows Phone 7 and 8

Windows 8

getMetadata

Look up metadata about a directory.

Parameters:

successCallback - A callback that is called with a Metadata object. (Function)

errorCallback - A callback that is called if an error occurs retrieving the Metadata. Invoked with a FileError object. (Function)

Quick Example

function success(metadata) {
    console.log("Last Modified: " + metadata.modificationTime);
}

function fail(error) {
    alert(error.code);
}

// Request the metadata object for this entry
entry.getMetadata(success, fail);

setMetadata

Set metadata on a directory.
Only works on iOS currently - this will set the extended attributes of a directory.

Parameters:

successCallback - A callback that is called when the metadata was successfully set. (Function)

errorCallback - A callback that is called when the metadata was not successfully set. (Function)

metadataObject - An object that contains the metadata keys and values. (Object)

Quick Example

function success() {
    console.log("The metadata was successfully set.");
}

function fail() {
    alert("There was an error in setting the metadata");
}

// Set the metadata
entry.setMetadata(success, fail, { "com.apple.MobileBackup": 1});

iOS Quirk

only the "com.apple.MobileBackup" extended attribute is supported. Set the value to 1 to NOT enable the directory to be backed up by iCloud. Set the value to 0 to re-enable the directory to be backed up by iCloud.

Quick Example

function setFolderMetadata(localFileSystem, subFolder, metadataKey, metadataValue)
{
    var onSetMetadataWin = function() {
      console.log("success setting metadata")
    }
    var onSetMetadataFail = function() {
      console.log("error setting metadata")
    }

    var onGetDirectoryWin = function(parent) {
      var data = {};
      data[metadataKey] = metadataValue;
      parent.setMetadata(onSetMetadataWin, onSetMetadataFail, data);
    }
    var onGetDirectoryFail = function() {
      console.log("error getting dir")
    }

    var onFSWin = function(fileSystem) {
      fileSystem.root.getDirectory(subFolder, {create: true, exclusive: false}, onGetDirectoryWin, onGetDirectoryFail);
    }

    var onFSFail = function(evt) {
      console.log(evt.target.error.code);
    }

    window.requestFileSystem(localFileSystem, 0, onFSWin, onFSFail);
}

setFolderMetadata(LocalFileSystem.PERSISTENT, "Backups", "com.apple.MobileBackup", 1);

moveTo

Move a directory to a different location on the file system. It is an error to attempt to:

move a directory inside itself or to any child at any depth;

move a directory into its parent if a name different from its current one is not provided;

move a directory to a path occupied by a file;

move a directory to a path occupied by a directory which is not empty.

In addition, an attempt to move a directory on top of an existing empty directory must attempt to delete and replace that directory.

Parameters:

parent - The parent directory to which to move the directory. (DirectoryEntry)

newName - The new name of the directory. Defaults to the current name if unspecified. (DOMString)

successCallback - A callback that is called with the DirectoryEntry object of the new directory. (Function)

errorCallback - A callback that is called if an error occurs when attempting to move the directory.  Invoked with a FileError object. (Function)

Quick Example

function success(entry) {
    console.log("New Path: " + entry.fullPath);
}

function fail(error) {
    alert(error.code);
}

function moveDir(entry) {
    var parent = document.getElementById('parent').value,
        parentName = parent.substring(parent.lastIndexOf('/')+1),
        newName = document.getElementById('newName').value,
        parentEntry = new DirectoryEntry(parentName, parent);

    // move the directory to a new directory and rename it
    entry.moveTo(parentEntry, newName, success, fail);
}

copyTo

Copy a directory to a different location on the file system. It is an error to attempt to:

copy a directory inside itself at any depth;

copy a directory into its parent if a name different from its current one is not provided.

Directory copies are always recursive - that is, they copy all contents of the directory.

Parameters:

parent - The parent directory to which to copy the directory. (DirectoryEntry)

newName - The new name of the directory. Defaults to the current name if unspecified. (DOMString)

successCallback - A callback that is called with the DirectoryEntry object of the new directory. (Function)

errorCallback - A callback that is called if an error occurs when attempting to copy the underlying directory.  Invoked with a FileError object. (Function)

Quick Example

function win(entry) {
    console.log("New Path: " + entry.fullPath);
}

function fail(error) {
    alert(error.code);
}

function copyDir(entry) {
    var parent = document.getElementById('parent').value,
        parentName = parent.substring(parent.lastIndexOf('/')+1),
        newName = document.getElementById('newName').value,
        parentEntry = new DirectoryEntry(parentName, parent);

    // copy the directory to a new directory and rename it
    entry.copyTo(parentEntry, newName, success, fail);
}

toURL

Returns a URL that can be used to locate the directory.

Quick Example

// Get the URL for this directory
var dirURL = entry.toURL();
console.log(dirURL);

remove

Deletes a directory. It is an error to attempt to:

delete a directory that is not empty;

delete the root directory of a filesystem.

Parameters:

successCallback - A callback that is called after the directory has been deleted.  Invoked with no parameters. (Function)

errorCallback - A callback that is called if an error occurs when attempting to delete the directory.  Invoked with a FileError object. (Function)

Quick Example

function success(entry) {
    console.log("Removal succeeded");
}

function fail(error) {
    alert('Error removing directory: ' + error.code);
}

// remove this directory
entry.remove(success, fail);

getParent

Look up the parent DirectoryEntry containing the directory.

Parameters:

successCallback - A callback that is called with the directory's parent DirectoryEntry. (Function)

errorCallback - A callback that is called if an error occurs when attempting to retrieve the parent DirectoryEntry.  Invoked with a FileError object. (Function)

Quick Example

function success(parent) {
    console.log("Parent Name: " + parent.name);
}

function fail(error) {
    alert('Failed to get parent directory: ' + error.code);
}

// Get the parent DirectoryEntry
entry.getParent(success, fail);

createReader

Creates a new DirectoryReader to read entries in a directory.

Quick Example

// create a directory reader
var directoryReader = entry.createReader();

getDirectory

Creates or looks up an existing directory.  It is an error to attempt to:

create a directory whose immediate parent does not yet exist.

Parameters:

path - The path to the directory to be looked up or created.  Either an absolute path, or a relative path from this DirectoryEntry. (DOMString)

options - Options to specify whether the directory is created if it doesn't exist.  (Flags)

successCallback - A callback that is invoked with a DirectoryEntry object. (Function)

errorCallback - A callback that is called if an error occurs creating or looking up the directory.  Invoked with a FileError object. (Function)

Quick Example

function success(parent) {
    console.log("Parent Name: " + parent.name);
}

function fail(error) {
    alert("Unable to create new directory: " + error.code);
}

// Retrieve an existing directory, or create it if it does not already exist
entry.getDirectory("newDir", {create: true, exclusive: false}, success, fail);

getFile

Creates or looks up a file.  It is an error to attempt to:

create a file whose immediate parent does not yet exist.

Parameters:

path - The path to the file to be looked up or created.  Either an absolute path, or a relative path from this DirectoryEntry. (DOMString)

options - Options to specify whether the file is created if it doesn't exist.  (Flags)

successCallback - A callback that is invoked with a FileEntry object. (Function)

errorCallback - A callback that is called if an error occurs creating or looking up the file.  Invoked with a FileError object. (Function)

Quick Example

function success(parent) {
    console.log("Parent Name: " + parent.name);
}

function fail(error) {
    alert("Failed to retrieve file: " + error.code);
}

// Retrieve an existing file, or create it if it does not exist
entry.getFile("newFile.txt", {create: true, exclusive: false}, success, fail);

removeRecursively

Deletes a directory and all of its contents.  In the event of an error (e.g. trying to delete
a directory that contains a file that cannot be removed), some of the contents of the directory may
be deleted.   It is an error to attempt to:

delete the root directory of a filesystem.

Parameters:

successCallback - A callback that is called after the DirectoryEntry has been deleted.  Invoked with no parameters. (Function)

errorCallback - A callback that is called if an error occurs when attempting to delete the DirectoryEntry.  Invoked with a FileError object. (Function)

Quick Example

function success(parent) {
    console.log("Remove Recursively Succeeded");
}

function fail(error) {
    alert("Failed to remove directory or it's contents: " + error.code);
}

// remove the directory and all it's contents
entry.removeRecursively(success, fail);

BlackBerry Quirks

May fail with a ControlledAccessException in the following cases:

Access is attempted on an directory created by a previous installation of an application.

solution: insure temporary directories are cleaned manually, or by the application before reinstall

if device is connected by usb

solution: disconnect usb cable from device and run again

DirectoryReader

An object that lists files and directories in a directory.  Defined in the Directories and Systems specification.

Methods

readEntries: Read the entries in a directory.

Supported Platforms

Android

BlackBerry WebWorks (OS 5.0 and higher)

iOS

Windows Phone 7 and 8

Windows 8

readEntries

Read the entries in this directory.

Parameters:

successCallback - A callback that is passed an array of FileEntry and DirectoryEntry objects. (Function)

errorCallback - A callback that is called if an error occurs retrieving the directory listing. Invoked with a FileError object. (Function)

Quick Example

function success(entries) {
    var i;
    for (i=0; i<entries.length; i++) {
        console.log(entries[i].name);
    }
}

function fail(error) {
    alert("Failed to list directory contents: " + error.code);
}

// Get a directory reader
var directoryReader = dirEntry.createReader();

// Get a list of all the entries in the directory
directoryReader.readEntries(success,fail);

FileTransfer

FileTransfer is an object that allows you to upload files to a server or download files from a server.

Properties

onprogress: Called with a ProgressEvent whenever a new chunk of data is transferred. (Function)

Methods

upload: sends a file to a server.

download: downloads a file from server.

abort: Aborts an in-progress transfer.

Details

The FileTransfer object provides a way to upload files to a remote server using an HTTP multi-part POST request.  Both HTTP and HTTPS protocols are supported.  Optional parameters can be specified by passing a FileUploadOptions object to the upload method.  On successful upload, the success callback will be called with a FileUploadResult object.  If an error occurs, the error callback will be invoked with a FileTransferError object.
It is also possible to download a file from remote and save it on the device (only iOS and Android).

Supported Platforms

Android

BlackBerry WebWorks (OS 5.0 and higher)

iOS

Windows Phone 7 and 8

Windows 8

upload

Parameters:

filePath - Full path of the file on the device

server - URL of the server to receive the file (must already be encoded using encodeURI())

successCallback - A callback that is called with a Metadata object. (Function)

errorCallback - A callback that is called if an error occurs retrieving the Metadata. Invoked with a FileTransferError object. (Function)

options - Optional parameters such as file name and mimetype

trustAllHosts - Optional parameter, defaults to false. If set to true then it will accept all security certificates. This is useful as Android rejects self signed security certificates. Not recommended for production use. Supported on Android and iOS. (boolean)

Quick Example

// !! Assumes variable fileURI contains a valid URI to a text file on the device

var win = function(r) {
    console.log("Code = " + r.responseCode);
    console.log("Response = " + r.response);
    console.log("Sent = " + r.bytesSent);
}

var fail = function(error) {
    alert("An error has occurred: Code = " + error.code);
    console.log("upload error source " + error.source);
    console.log("upload error target " + error.target);
}

var options = new FileUploadOptions();
options.fileKey="file";
options.fileName=fileURI.substr(fileURI.lastIndexOf('/')+1);
options.mimeType="text/plain";

var params = {};
    params.value1 = "test";
    params.value2 = "param";

options.params = params;

var ft = new FileTransfer();
ft.upload(fileURI, encodeURI("http://some.server.com/upload.php"), win, fail, options);

Full Example

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
    <title>File Transfer Example</title>

    <script type="text/javascript" charset="utf-8" src="cordova-2.6.0.js"></script>
    <script type="text/javascript" charset="utf-8">

        // Wait for Cordova to load
        //
        document.addEventListener("deviceready", onDeviceReady, false);

        // Cordova is ready
        //
        function onDeviceReady() {

            // Retrieve image file location from specified source
            navigator.camera.getPicture(uploadPhoto,
                                        function(message) { alert('get picture failed'); },
                                        { quality: 50,
                                        destinationType: navigator.camera.DestinationType.FILE_URI,
                                        sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY }
                                        );

        }

        function uploadPhoto(imageURI) {
            var options = new FileUploadOptions();
            options.fileKey="file";
            options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
            options.mimeType="image/jpeg";

            var params = {};
            params.value1 = "test";
            params.value2 = "param";

            options.params = params;

            var ft = new FileTransfer();
            ft.upload(imageURI, encodeURI("http://some.server.com/upload.php"), win, fail, options);
        }

        function win(r) {
            console.log("Code = " + r.responseCode);
            console.log("Response = " + r.response);
            console.log("Sent = " + r.bytesSent);
        }

        function fail(error) {
            alert("An error has occurred: Code = " + error.code);
            console.log("upload error source " + error.source);
            console.log("upload error target " + error.target);
        }

        </script>
</head>
<body>
    <h1>Example</h1>
    <p>Upload File</p>
</body>
</html>

Setting Upload Headers

Supported on Android and iOS

function win(r) {
    console.log("Code = " + r.responseCode);
    console.log("Response = " + r.response);
    console.log("Sent = " + r.bytesSent);
}

function fail(error) {
    alert("An error has occurred: Code = " + error.code);
    console.log("upload error source " + error.source);
    console.log("upload error target " + error.target);
}

var uri = encodeURI("http://some.server.com/upload.php");

var options = new FileUploadOptions();
options.fileKey="file";
options.fileName=fileURI.substr(fileURI.lastIndexOf('/')+1);
options.mimeType="text/plain";

var headers={'headerParam':'headerValue'};

options.headers = headers;

var ft = new FileTransfer();
ft.upload(fileURI, uri, win, fail, options);

Android Quirks

If you experience problems uploading to a Nginx server then make sure you have the chunkedMode option set to false.

download

Parameters:

source - URL of the server to download the file (must already be encoded using encodeURI())

target - Full path of the file on the device

successCallback - A callback that is called with a FileEntry object. (Function)

errorCallback - A callback that is called if an error occurs retrieving the Metadata. Invoked with a FileTransferError object. (Function)

trustAllHosts - Optional parameter, defaults to false. If set to true then it will accept all security certificates. This is useful as Android rejects self signed security certificates. Not recommended for production use. Supported on Android and iOS. (boolean)

options - Optional parameters, currently only supports headers (such as Authorization (Basic Authentication), etc).

Quick Example

// !! Assumes filePath is a valid path on the device

var fileTransfer = new FileTransfer();
var uri = encodeURI("http://some.server.com/download.php");

fileTransfer.download(
    uri,
    filePath,
    function(entry) {
        console.log("download complete: " + entry.fullPath);
    },
    function(error) {
        console.log("download error source " + error.source);
        console.log("download error target " + error.target);
        console.log("upload error code" + error.code);
    },
    false,
    {
        headers: {
            "Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=="
        }
    }
);

abort

Aborts an in-progress transfer. The onerror callback will be called with a FileTransferError object which has an error code of FileTransferError.ABORT_ERR.

Supported Platforms

Android

iOS

Quick Example

// !! Assumes variable fileURI contains a valid URI to a text file on the device

var win = function(r) {
    console.log("Code = " + r.responseCode);
    console.log("Response = " + r.response);
    console.log("Sent = " + r.bytesSent);
}

var fail = function(error) {
    alert("An error has occurred: Code = " + error.code);
    console.log("upload error source " + error.source);
    console.log("upload error target " + error.target);
}

var options = new FileUploadOptions();
options.fileKey="file";
options.fileName=fileURI.substr(fileURI.lastIndexOf('/')+1);
options.mimeType="text/plain";

var params = {};
params.value1 = "test";
params.value2 = "param";

options.params = params;

var ft = new FileTransfer();
ft.upload(fileURI, encodeURI("http://some.server.com/upload.php"), win, fail, options);
ft.abort(win, fail);

onprogress

Called with a ProgressEvent whenever a new chunk of data is transferred.

Supported Platforms

Android

iOS

Example

fileTransfer.onprogress = function(progressEvent) {
    if (progressEvent.lengthComputable) {
      loadingStatus.setPercentage(progressEvent.loaded / progressEvent.total);
    } else {
      loadingStatus.increment();
    }
};
fileTransfer.download(...); // or fileTransfer.upload(...);

Quirks
- On both Android an iOS, lengthComputable is false for downloads that use gzip encoding.

FileUploadOptions

A FileUploadOptions object can be passed to the FileTransfer objects upload method in order to specify additional parameters to the upload script.

Properties

fileKey: The name of the form element.  If not set defaults to "file". (DOMString)

fileName: The file name you want the file to be saved as on the server.  If not set defaults to "image.jpg". (DOMString)

mimeType: The mime type of the data you are uploading.  If not set defaults to "image/jpeg". (DOMString)

params: A set of optional key/value pairs to be passed along in the HTTP request. (Object)

chunkedMode: Should the data be uploaded in chunked streaming mode. If not set defaults to "true". (Boolean)

headers: A map of header name => header value. To specify multiple values for a header, use an array of values. (Object)

Description

A FileUploadOptions object can be passed to the FileTransfer objects upload method in order to specify additional parameters to the upload script.

WP7 Quirk

chunkedMode:
This parameter is ignored on WP7.

FileUploadResult

A FileUploadResult object is returned via the success callback of the FileTransfer upload method.

Properties

bytesSent: The number of bytes sent to the server as part of the upload. (long)

responseCode: The HTTP response code returned by the server. (long)

response: The HTTP response returned by the server. (DOMString)

Description

The FileUploadResult object is returned via the success callback of the FileTransfer upload method.

iOS Quirks

iOS does not include values for responseCode nor bytesSent in the success callback FileUploadResult object.

Flags

This object is used to supply arguments to the DirectoryEntry getFile and getDirectory methods, which look up or create files and directories, respectively.

Properties

create: Used to indicate that the file or directory should be created, if it does not exist. (boolean)

exclusive: By itself, exclusive has no effect. Used with create, it causes the file or directory creation to fail if the target path already exists. (boolean)

Supported Platforms

Android

BlackBerry WebWorks (OS 5.0 and higher)

iOS

Windows Phone 7 and 8

Windows 8

Quick Example

// Get the data directory, creating it if it doesn't exist.
dataDir = fileSystem.root.getDirectory("data", {create: true});

// Create the lock file, if and only if it doesn't exist.
lockFile = dataDir.getFile("lockfile.txt", {create: true, exclusive: true});

LocalFileSystem

This object provides a way to obtain root file systems.

Methods

requestFileSystem: Requests a filesystem. (Function)

resolveLocalFileSystemURI: Retrieve a DirectoryEntry or FileEntry using local URI. (Function)

Constants

LocalFileSystem.PERSISTENT: Used for storage that should not be removed by the user agent without application or user permission.

LocalFileSystem.TEMPORARY: Used for storage with no guarantee of persistence.

Details

The LocalFileSystem object methods are defined on the window object.

Supported Platforms

Android

BlackBerry WebWorks (OS 5.0 and higher)

iOS

Windows Phone 7 and 8

Windows 8

Request File System Quick Example

function onSuccess(fileSystem) {
    console.log(fileSystem.name);
}

// request the persistent file system
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onSuccess, onError);

Resolve Local File System URI Quick Example

function onSuccess(fileEntry) {
    console.log(fileEntry.name);
}

window.resolveLocalFileSystemURI("file:///example.txt", onSuccess, onError);

Full Example

<!DOCTYPE html>
<html>
  <head>
    <title>Local File System Example</title>

    <script type="text/javascript" charset="utf-8" src="cordova-2.6.0.js"></script>
    <script type="text/javascript" charset="utf-8">

    // Wait for Cordova to load
    //
    document.addEventListener("deviceready", onDeviceReady, false);

    // Cordova is ready
    //
    function onDeviceReady() {
        window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFileSystemSuccess, fail);
        window.resolveLocalFileSystemURI("file:///example.txt", onResolveSuccess, fail);
    }

    function onFileSystemSuccess(fileSystem) {
        console.log(fileSystem.name);
    }

    function onResolveSuccess(fileEntry) {
        console.log(fileEntry.name);
    }

    function fail(evt) {
        console.log(evt.target.error.code);
    }

    </script>
  </head>
  <body>
    <h1>Example</h1>
    <p>Local File System</p>
  </body>
</html>

Metadata

This interface supplies information about the state of a file or directory.

Properties

modificationTime: This is the time at which the file or directory was last modified. (Date)

Details

The Metadata object represents information about the state of a file or directory.  You can get an instance of a Metadata object by calling the getMetadata method of a DirectoryEntry or FileEntry object.

Supported Platforms

Android

BlackBerry WebWorks (OS 5.0 and higher)

iOS

Windows Phone 7 and 8

Windows 8

Quick Example

function win(metadata) {
    console.log("Last Modified: " + metadata.modificationTime);
}

// Request the metadata object for this entry
entry.getMetadata(win, null);

FileError

A 'FileError' object is set when an error occurs in any of the File API methods.

Properties

code: One of the predefined error codes listed below.

Constants

FileError.NOT_FOUND_ERR

FileError.SECURITY_ERR

FileError.ABORT_ERR

FileError.NOT_READABLE_ERR

FileError.ENCODING_ERR

FileError.NO_MODIFICATION_ALLOWED_ERR

FileError.INVALID_STATE_ERR

FileError.SYNTAX_ERR

FileError.INVALID_MODIFICATION_ERR

FileError.QUOTA_EXCEEDED_ERR

FileError.TYPE_MISMATCH_ERR

FileError.PATH_EXISTS_ERR

Description

The FileError object is the only parameter of any of the File API's error callbacks.  Developers must read the code property to determine the type of error.

FileTransferError

A FileTransferError object is returned via the error callback when an error occurs.

Properties

code One of the predefined error codes listed below. (Number)

source URI to the source (String)

target URI to the target (String)

http_status HTTP status code.  This attribute is only available when a response code is received from the HTTP connection. (Number)

Constants

FileTransferError.FILE_NOT_FOUND_ERR

FileTransferError.INVALID_URL_ERR

FileTransferError.CONNECTION_ERR

FileTransferError.ABORT_ERR

Description

The FileTransferError object is returned via the error callback when an error occurs when uploading or downloading a file.


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace Ferret.Core.Services
{
    /// <summary>
    /// Responsible to return the right instance of <see cref="IPinpadService"/>,
    /// accordingly to the arguments received.
    /// </summary>
    static public class ServiceFactory
    {
        /// <summary>
        /// Argument options. To add a new command to this property, just create
        /// a new class that implements <see cref="IPinpadService"/>.
        /// </summary>
        static private List<IPinpadService> AvailableServices { get; set; }

        /// <summary>
        /// Get's all available commands.
        /// </summary>
        static ServiceFactory()
        {
            // Selects all classes that inherit from IPinpadService and are not abstract:
            ServiceFactory.AvailableServices = Assembly.GetExecutingAssembly()
                .GetTypes()
                .Where(t => t.GetInterfaces()
                             .Contains(typeof(IPinpadService)))
                .Where(t => t.GetTypeInfo().IsAbstract == false)
                .Select(currentType => Activator.CreateInstance(currentType) as IPinpadService)
                .ToList();
        }

        /// <summary>
        /// Create a new instance of <see cref="IPinpadService"/> based on the
        /// arguments received.
        /// </summary>
        /// <param name="args">Arguments read from command prompt.</param>
        /// <returns>Arguments corresponding service, or null if arguments are
        /// unknown.</returns>
        static public IPinpadService Create(string[] args)
        {
            IPinpadService service = ServiceFactory.AvailableServices
                .Where(s =>
                {
                    return s.IsServiceFromCommandLineArgs(args) == true;
                })
                .FirstOrDefault();

            return service;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package io.github.hsyyid.essentialcmds.utils;

import org.spongepowered.api.item.inventory.ItemStack;

import java.util.List;
import java.util.UUID;

public class PlayerInventory
{
	private UUID playerUuid;
	private UUID worldUuid;
	private List<ItemStack> slots;

	public PlayerInventory(UUID playerUuid, UUID worldUuid, List<ItemStack> slots)
	{
		this.playerUuid = playerUuid;
		this.worldUuid = worldUuid;
		this.slots = slots;
	}

	public UUID getPlayerUuid()
	{
		return playerUuid;
	}

	public UUID getWorldUuid()
	{
		return worldUuid;
	}

	public List<ItemStack> getSlots()
	{
		return slots;
	}
}


text:
<?php
namespace PSB\Core\Transport\RabbitMq;

use PSB\Core\EndpointControlToken;
use PSB\Core\Transport\MessagePusherInterface;
use PSB\Core\Transport\PushPipe;
use PSB\Core\Transport\PushSettings;
use PSB\Core\Transport\ReceiveCancellationToken;

class RabbitMqMessagePusher implements MessagePusherInterface
{
    /**
     * @var BrokerModel
     */
    private $brokerModel;

    /**
     * @var MessageProcessor
     */
    private $messageProcessor;

    /**
     * @var PushPipe
     */
    private $pushPipe;

    /**
     * @var PushSettings
     */
    private $pushSettings;

    /**
     * @param BrokerModel      $brokerModel
     * @param MessageProcessor $messageProcessor
     */
    public function __construct(
        BrokerModel $brokerModel,
        MessageProcessor $messageProcessor
    ) {
        $this->brokerModel = $brokerModel;
        $this->messageProcessor = $messageProcessor;
    }

    /**
     * It initializes the message pusher with the pipe it will send messages through.
     * The pipe is invoked for each incoming message.
     *
     * @param PushPipe     $pushPipe
     * @param PushSettings $pushSettings
     */
    public function init(PushPipe $pushPipe, PushSettings $pushSettings)
    {
        $this->pushPipe = $pushPipe;
        $this->pushSettings = $pushSettings;

        if ($pushSettings->isPurgeOnStartup()) {
            $this->brokerModel->purgeQueue($pushSettings->getInputQueue());
        }
    }

    /**
     * Starts pushing messages
     */
    public function start()
    {
        $this->brokerModel->consume(
            $this->pushSettings->getInputQueue(),
            function (\AMQPEnvelope $envelope, \AMQPQueue $queue) {
                return $this->messageProcessor->process(
                    $envelope,
                    $queue,
                    $this->pushPipe,
                    $this->pushSettings->getErrorQueue(),
                    new ReceiveCancellationToken(),
                    new EndpointControlToken()
                );
            }
        );
    }
}


text:
module Chainer
  class Fn

    def initialize(fn)
      @fn = fn
    end

    def fmap(other)
      wrap ->(*args) { other.(self.(*args)) }
    end

    def call(*args)
      fn.(*args)
    end

    private

    attr_reader :fn

    def wrap(value)
      self.class.new value
    end

  end
end


text:
package com.amazonaws.monitoring.internal;

import static com.amazonaws.util.AWSRequestMetrics.Field.HttpRequestTime;
import static com.amazonaws.util.AwsClientSideMonitoringMetrics.MaxRetriesExceeded;

import com.amazonaws.AmazonServiceException;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.Request;
import com.amazonaws.RequestClientOptions;
import com.amazonaws.Response;
import com.amazonaws.annotation.SdkInternalApi;
import com.amazonaws.auth.internal.SignerConstants;
import com.amazonaws.handlers.HandlerAfterAttemptContext;
import com.amazonaws.handlers.HandlerContextKey;
import com.amazonaws.handlers.RequestHandler2;
import com.amazonaws.http.timers.client.ClientExecutionTimeoutException;
import com.amazonaws.monitoring.ApiCallAttemptMonitoringEvent;
import com.amazonaws.monitoring.ApiCallMonitoringEvent;
import com.amazonaws.monitoring.MonitoringEvent;
import com.amazonaws.monitoring.MonitoringListener;
import com.amazonaws.util.AWSRequestMetrics;
import com.amazonaws.util.AwsClientSideMonitoringMetrics;
import com.amazonaws.util.CollectionUtils;
import com.amazonaws.util.ImmutableMapParameter;
import com.amazonaws.util.StringUtils;
import com.amazonaws.util.Throwables;
import com.amazonaws.util.TimingInfo;
import java.net.URI;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Client Side Monitoring Request Handler to generate monitoring events and send them to agent listener.
 */
@SdkInternalApi
public final class ClientSideMonitoringRequestHandler extends RequestHandler2 {

    private static final Log LOG = LogFactory.getLog(ClientSideMonitoringRequestHandler.class);
    private static final String X_AMZN_REQUEST_ID_HEADER_KEY = "x-amzn-RequestId";
    private static final String X_AMZ_REQUEST_ID_HEADER_KEY = "x-amz-request-id";
    private static final String X_AMZ_REQUEST_ID_2_HEADER_KEY = "x-amz-id-2";

    private static final String EXCEPTION_MESSAGE_KEY = "ExceptionMessage";
    private static final String EXCEPTION_KEY = "Exception";
    private static final String CLIENT_ID_KEY = "ClientId";
    private static final String USER_AGENT_KEY = "UserAgent";

    private static final HandlerContextKey<ApiCallAttemptMonitoringEvent> LAST_CALL_ATTEMPT =
            new HandlerContextKey<ApiCallAttemptMonitoringEvent>("LastCallAttemptMonitoringEvent");

    private static final Integer VERSION = 1;
    private static final List<String> SECURITY_TOKENS = Arrays.asList("x-amz-security-token",
                                                                      SignerConstants.X_AMZ_SECURITY_TOKEN);

    private static final Map<String, Integer> ENTRY_TO_MAX_SIZE = new ImmutableMapParameter.Builder<String, Integer>()
        .put(CLIENT_ID_KEY, 255)
        .put(USER_AGENT_KEY, 256)
        .put(EXCEPTION_MESSAGE_KEY, 512)
        .put(EXCEPTION_KEY, 128).build();

    private final String clientId;

    private final Collection<MonitoringListener> monitoringListeners;

    public ClientSideMonitoringRequestHandler(String clientId, Collection<MonitoringListener> monitoringListeners) {
        this.clientId = trimValueIfExceedsMaxLength(CLIENT_ID_KEY, clientId);
        this.monitoringListeners = monitoringListeners;
    }

    @Override
    public void afterAttempt(HandlerAfterAttemptContext context) {
        ApiCallAttemptMonitoringEvent event = generateApiCallAttemptMonitoringEvent(context);
        context.getRequest().addHandlerContext(LAST_CALL_ATTEMPT, event);
        handToMonitoringListeners(event);
    }

    @Override
    public void afterResponse(Request<?> request, Response<?> response) {
        ApiCallMonitoringEvent event = generateApiCallMonitoringEvent(request);
        handToMonitoringListeners(event);
    }

    @Override
    public void afterError(Request<?> request, Response<?> response, Exception e) {
        ApiCallMonitoringEvent event = generateApiCallMonitoringEvent(request, e);
        handToMonitoringListeners(event);
    }

    /**
     * Collect {@link ApiCallAttemptMonitoringEvent} per attempt.
     */
    private ApiCallAttemptMonitoringEvent generateApiCallAttemptMonitoringEvent(HandlerAfterAttemptContext context) {
        Request<?> request = context.getRequest();
        AWSRequestMetrics metrics = context.getRequest().getAWSRequestMetrics();

        String apiName = request.getHandlerContext(HandlerContextKey.OPERATION_NAME);
        String serviceId = request.getHandlerContext(HandlerContextKey.SERVICE_ID);
        String sessionToken = getSessionToken(request.getHeaders());
        String region = request.getHandlerContext(HandlerContextKey.SIGNING_REGION);

        String accessKey = null;
        if (request.getHandlerContext(HandlerContextKey.AWS_CREDENTIALS) != null) {
            accessKey = request.getHandlerContext(HandlerContextKey.AWS_CREDENTIALS).getAWSAccessKeyId();
        }

        String fqdn = extractFqdn(request.getEndpoint());
        TimingInfo timingInfo = metrics == null ? null : metrics.getTimingInfo();

        TimingInfo httpRequestTime;
        Long timestamp = null;
        Long attemptLatency = null;

        if (timingInfo != null && timingInfo.getLastSubMeasurement(HttpRequestTime.name()) != null) {
            httpRequestTime = timingInfo.getLastSubMeasurement(HttpRequestTime.name());
            timestamp = httpRequestTime.getStartEpochTimeMilliIfKnown();
            attemptLatency = convertToLongIfNotNull(httpRequestTime.getTimeTakenMillisIfKnown());
        }

        ApiCallAttemptMonitoringEvent event = new ApiCallAttemptMonitoringEvent()
            .withFqdn(fqdn)
            .withVersion(VERSION)
            .withService(serviceId)
            .withClientId(clientId)
            .withRegion(region)
            .withAccessKey(accessKey)
            .withUserAgent(trimValueIfExceedsMaxLength(USER_AGENT_KEY, getDefaultUserAgent(request)))
            .withTimestamp(timestamp)
            .withAttemptLatency(attemptLatency)
            .withSessionToken(sessionToken)
            .withApi(apiName);

        addConditionalFieldsToAttemptEvent(metrics, context, event);
        return event;
    }

    /**
     * Collect {@link ApiCallMonitoringEvent} per request.
     */
    private ApiCallMonitoringEvent generateApiCallMonitoringEvent(Request<?> request) {
        String apiName = request.getHandlerContext(HandlerContextKey.OPERATION_NAME);
        String serviceId = request.getHandlerContext(HandlerContextKey.SERVICE_ID);
        String region = request.getHandlerContext(HandlerContextKey.SIGNING_REGION);
        ApiCallAttemptMonitoringEvent lastApiCallAttempt = request.getHandlerContext(LAST_CALL_ATTEMPT);

        Long timestamp = null;
        Long latency = null;
        Integer requestCount = 0;
        AWSRequestMetrics metrics = request.getAWSRequestMetrics();

        if (metrics != null) {
            TimingInfo timingInfo = metrics.getTimingInfo();
            requestCount = timingInfo.getCounter(AWSRequestMetrics.Field.RequestCount.name()) == null ? 0 :
                           timingInfo.getCounter(AWSRequestMetrics.Field.RequestCount.name()).intValue();

            TimingInfo latencyTimingInfo = timingInfo.getSubMeasurement(AwsClientSideMonitoringMetrics.ApiCallLatency.name());
            if (latencyTimingInfo != null) {
                latency = convertToLongIfNotNull(latencyTimingInfo.getTimeTakenMillisIfKnown());
                timestamp = latencyTimingInfo.getStartEpochTimeMilliIfKnown();
            }
        }

        ApiCallMonitoringEvent event = new ApiCallMonitoringEvent()
                .withApi(apiName)
                .withVersion(VERSION)
                .withRegion(region)
                .withService(serviceId)
                .withClientId(clientId)
                .withAttemptCount(requestCount)
                .withLatency(latency)
                .withUserAgent(trimValueIfExceedsMaxLength(USER_AGENT_KEY, getDefaultUserAgent(request)))
                .withTimestamp(timestamp);

        if (lastApiCallAttempt != null) {
            event.withFinalAwsException(lastApiCallAttempt.getAwsException())
                 .withFinalAwsExceptionMessage(lastApiCallAttempt.getAwsExceptionMessage())
                 .withFinalSdkException(lastApiCallAttempt.getSdkException())
                 .withFinalSdkExceptionMessage(lastApiCallAttempt.getSdkExceptionMessage())
                 .withFinalHttpStatusCode(lastApiCallAttempt.getHttpStatusCode());
        }

        return event;
    }

    private ApiCallMonitoringEvent generateApiCallMonitoringEvent(Request<?> request, Exception e) {
        ApiCallMonitoringEvent event = generateApiCallMonitoringEvent(request);
        AWSRequestMetrics metrics = request.getAWSRequestMetrics();

        if (e instanceof ClientExecutionTimeoutException) {
            event.withApiCallTimeout(1);
        }

        if (metrics != null && !CollectionUtils.isNullOrEmpty(metrics.getProperty(MaxRetriesExceeded))) {
            boolean maxRetriesExceeded = (Boolean) metrics.getProperty(MaxRetriesExceeded).get(0);
            event.withMaxRetriesExceeded(maxRetriesExceeded ? 1 : 0);
        }

        return event;
    }

    /**
     * Add conditional fields to {@link ApiCallAttemptMonitoringEvent} based on the
     * {@link HandlerAfterAttemptContext#getResponse()} and {@link HandlerAfterAttemptContext#getException()}
     */
    private void addConditionalFieldsToAttemptEvent(AWSRequestMetrics metrics, HandlerAfterAttemptContext context,
                                                    ApiCallAttemptMonitoringEvent event) {
        TimingInfo timingInfo = metrics == null ? null : metrics.getTimingInfo();
        Response<?> response = context.getResponse();
        Integer statusCode = null;
        String xAmznRequestId = null;
        String xAmzRequestId = null;
        String xAmzId2 = null;
        Long requestLatency = null;

        Map<String, String> responseHeaders = null;
        if (response != null && response.getHttpResponse() != null) {
            responseHeaders = response.getHttpResponse().getHeaders();
            statusCode = response.getHttpResponse().getStatusCode();
            requestLatency = calculateRequestLatency(timingInfo);
        } else if (context.getException() instanceof AmazonServiceException) {
            responseHeaders = ((AmazonServiceException) context.getException()).getHttpHeaders();
            statusCode = extractHttpStatusCode((AmazonServiceException) context.getException());
            requestLatency = calculateRequestLatency(timingInfo);
        }

        if (responseHeaders != null) {
            xAmznRequestId = responseHeaders.get(X_AMZN_REQUEST_ID_HEADER_KEY);
            xAmzRequestId = responseHeaders.get(X_AMZ_REQUEST_ID_HEADER_KEY);
            xAmzId2 = responseHeaders.get(X_AMZ_REQUEST_ID_2_HEADER_KEY);
        }

        event.withXAmznRequestId(xAmznRequestId)
             .withXAmzRequestId(xAmzRequestId)
             .withXAmzId2(xAmzId2)
             .withHttpStatusCode(statusCode)
             .withRequestLatency(requestLatency);
        addException(context.getException(), event);
    }

    private void handToMonitoringListeners(MonitoringEvent event) {
        for (MonitoringListener monitoringListener : monitoringListeners) {
            try {
                monitoringListener.handleEvent(event);
            } catch (Exception exception) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug(String.format("MonitoringListener: %s failed to handle event", monitoringListener.toString()),
                              exception);
                }
            }
        }
    }

    /**
     * Extract fqdn from endpoint. eg: https:some-service.aws.com:8080 -> some-service.aws.com
     */
    private String extractFqdn(URI endpoint) {
        if (endpoint == null) {
            return null;
        }

        return endpoint.getHost();
    }

    /**
     * If the entry exceeds the maximum length limit associated with the entry, its value will be trimmed to meet its limit.
     */
    private String trimValueIfExceedsMaxLength(String entry, String value) {
        if (value == null) {
            return null;
        }

        String result = value;
        Integer maximumSize = ENTRY_TO_MAX_SIZE.get(entry);
        if (maximumSize != null && value.length() > maximumSize) {
            result = value.substring(0, maximumSize);
        }
        return result;
    }

    /**
     * Get the default user agent and append the user agent marker if there are any.
     */
    private String getDefaultUserAgent(Request<?> request) {
        String userAgentMarker = request.getOriginalRequest().getRequestClientOptions().getClientMarker(RequestClientOptions
                                                                                .Marker.USER_AGENT);
        String userAgent = ClientConfiguration.DEFAULT_USER_AGENT;
        if (StringUtils.hasValue(userAgentMarker)) {
            userAgent += " " + userAgentMarker;
        }
        return userAgent;
    }

    private String getSessionToken(Map<String, String> requestHeaders) {
        for (String header : SECURITY_TOKENS) {
            if (requestHeaders.get(header) != null) {
                return requestHeaders.get(header);
            }
        }
        return null;
    }

    private Long convertToLongIfNotNull(Double number) {
        if (number == null) {
            return null;
        }

        return number.longValue();
    }

    /**
     * Calculate the request latency. RequestLatency = httpClientSendRequestTime + HttpClientReceiveResponseTime
     */
    private Long calculateRequestLatency(TimingInfo timingInfo) {
        if (timingInfo == null) {
            return null;
        }

        TimingInfo httpClientSendRequestTime = timingInfo.getLastSubMeasurement(AWSRequestMetrics.Field.HttpClientSendRequestTime
                                                                                .name());
        TimingInfo httpClientReceiveResponseTime = timingInfo.getLastSubMeasurement(AWSRequestMetrics.Field
                                                                                .HttpClientReceiveResponseTime.name());
        if (httpClientSendRequestTime != null && httpClientSendRequestTime.getTimeTakenMillisIfKnown() != null &&
            httpClientReceiveResponseTime != null && httpClientReceiveResponseTime.getTimeTakenMillisIfKnown() != null) {
            return httpClientSendRequestTime.getTimeTakenMillisIfKnown().longValue()
                   + httpClientReceiveResponseTime.getTimeTakenMillisIfKnown().longValue();
        }
        return null;
    }

    private void addException(Exception exception, ApiCallAttemptMonitoringEvent event) {
        if (exception == null) {
            return;
        }

        if (exception instanceof AmazonServiceException) {
            String errorCode = ((AmazonServiceException) exception).getErrorCode();
            String errorMessage = ((AmazonServiceException) exception).getErrorMessage();

            event.withAwsException(trimValueIfExceedsMaxLength(EXCEPTION_KEY, errorCode));
            event.withAwsExceptionMessage(trimValueIfExceedsMaxLength(EXCEPTION_MESSAGE_KEY, errorMessage));
        } else {
            String exceptionClassName = exception.getClass().getName();
            String exceptionMessage = getRootCauseMessage(exception);

            event.withSdkException(trimValueIfExceedsMaxLength(EXCEPTION_KEY, exceptionClassName));
            event.withSdkExceptionMessage(trimValueIfExceedsMaxLength(EXCEPTION_MESSAGE_KEY, exceptionMessage));
        }
    }

    private String getRootCauseMessage(Exception exception) {
        if (exception.getMessage() != null) {
            return exception.getMessage();
        }

        return Throwables.getRootCause(exception).getMessage();
    }

    private int extractHttpStatusCode(AmazonServiceException exception) {
        return exception.getStatusCode();
    }
}


text:
import unittest

import pwm.workspaces
import pwm.bar
import test.util as util

class TestBar(unittest.TestCase):
    def setUp(self):
        util.setup()

    def tearDown(self):
        util.tear_down()

    #def test_show(self):
    #    # show() should already have been called in setUp
    #    attr = pwm.xcb.core.GetWindowAttributes(self.bar.wid).reply()
    #    self.assertEqual(attr.map_state, xproto.MapState.Viewable)


text:
package langs

import (
	"fmt"
	"os"
	"os/exec"
	"strings"
)

type GoLangHelper struct {
	BaseHelper
}

func (lh *GoLangHelper) Entrypoint() string {
	return "./func"
}

func (lh *GoLangHelper) HasPreBuild() bool {
	return true
}

// PreBuild for Go builds the binary so the final image can be as small as possible
func (lh *GoLangHelper) PreBuild() error {
	wd, err := os.Getwd()
	if err != nil {
		return err
	}
	// todo: this won't work if the function is more complex since the import paths won't match up, need to fix
	pbcmd := fmt.Sprintf("docker run --rm -v %s:/go/src/github.com/x/y -w /go/src/github.com/x/y iron/go:dev go build -o func", wd)
	fmt.Println("Running prebuild command:", pbcmd)
	parts := strings.Fields(pbcmd)
	head := parts[0]
	parts = parts[1:len(parts)]
	cmd := exec.Command(head, parts...)
	// cmd.Dir = dir
	cmd.Stderr = os.Stderr
	cmd.Stdout = os.Stdout
	if err := cmd.Run(); err != nil {
		return fmt.Errorf("error running docker build: %v", err)
	}
	return nil
}

func (lh *GoLangHelper) AfterBuild() error {
	return os.Remove("func")

}


text:
package mesosphere.marathon
package storage.repository

import java.time.OffsetDateTime
import java.util.UUID

import akka.Done
import akka.stream.scaladsl.Sink
import com.mesosphere.utils.zookeeper.ZookeeperServerTest
import mesosphere.AkkaUnitTest
import mesosphere.marathon.core.base.JvmExitsCrashStrategy
import mesosphere.marathon.core.storage.repository.RepositoryConstants
import mesosphere.marathon.core.storage.store.impl.cache.{LazyCachingPersistenceStore, LoadTimeCachingPersistenceStore}
import mesosphere.marathon.core.storage.store.impl.memory.InMemoryPersistenceStore
import mesosphere.marathon.core.storage.store.impl.zk.{RichCuratorFramework, ZkPersistenceStore}
import mesosphere.marathon.metrics.dummy.DummyMetrics
import mesosphere.marathon.state.{AppDefinition, PathId, RootGroup, Timestamp}
import mesosphere.marathon.test.Mockito

import scala.collection.immutable.Seq
import scala.concurrent.Future

class GroupRepositoryTest extends AkkaUnitTest with Mockito with ZookeeperServerTest {
  import PathId._

  val metrics = DummyMetrics

  def basicGroupRepository[K, C, S](name: String, createRepo: (AppRepository, PodRepository, Int) => GroupRepository): Unit = {
    name should {
      "return an empty root if no root exists" in {
        val repo = createRepo(mock[AppRepository], mock[PodRepository], 1)
        val root = repo.root().futureValue
        root.transitiveApps should be('empty)
        root.dependencies should be('empty)
        root.groupsById should be('empty)
      }
      "have no versions" in {
        val repo = createRepo(mock[AppRepository], mock[PodRepository], 1)
        repo.rootVersions().runWith(Sink.seq).futureValue should be('empty)
      }
      "not be able to get historical versions" in {
        val repo = createRepo(mock[AppRepository], mock[PodRepository], 1)
        repo.rootVersion(OffsetDateTime.now).futureValue should not be 'defined
      }
      "store and retrieve the empty group" in {
        val repo = createRepo(mock[AppRepository], mock[PodRepository], 1)
        val root = repo.root().futureValue
        repo.storeRoot(root, Nil, Nil, Nil, Nil).futureValue
        repo.root().futureValue should be(root)
        root.id should be('empty)
      }
      "store new apps when storing the root" in {
        val appRepo = mock[AppRepository]
        val repo = createRepo(appRepo, mock[PodRepository], 1)
        val apps = Seq(AppDefinition("app1".toAbsolutePath, role = "*"), AppDefinition("app2".toAbsolutePath, role = "*"))
        val root = repo.root().futureValue

        val newRoot = root.updateApps(PathId.root, _ => apps.iterator.map(app => app.id -> app).toMap, root.version)

        appRepo.store(any) returns Future.successful(Done)

        repo.storeRoot(newRoot, apps, Nil, Nil, Nil).futureValue
        repo.root().futureValue should equal(newRoot)
        newRoot.id should be('empty)

        verify(appRepo).store(apps.head)
        verify(appRepo).store(apps.tail.head)
        noMoreInteractions(appRepo)
      }
      "not store the group if updating apps fails" in {
        val appRepo = mock[AppRepository]
        val repo = createRepo(appRepo, mock[PodRepository], 1)
        val apps = Seq(AppDefinition("app1".toAbsolutePath, role = "*"), AppDefinition("app2".toAbsolutePath, role = "*"))
        val root = repo.root().futureValue
        repo.storeRoot(root, Nil, Nil, Nil, Nil).futureValue

        val newRoot = root.updateApps(PathId.root, apps = _ => apps.iterator.map(app => app.id -> app).toMap, root.version)

        val exception = new Exception("App Store Failed")
        appRepo.store(any) returns Future.failed(exception)

        repo.storeRoot(newRoot, apps, Nil, Nil, Nil).failed.futureValue should equal(exception)
        repo.root().futureValue should equal(root)

        repo match {
          case s: StoredGroupRepositoryImpl[_, _, _] =>
            s.underlyingRoot().futureValue should equal(root)
        }

        verify(appRepo).store(apps.head)
        verify(appRepo).store(apps.tail.head)
        noMoreInteractions(appRepo)
      }
      "store the group if deleting apps fails" in {
        val appRepo = mock[AppRepository]
        val repo = createRepo(appRepo, mock[PodRepository], 1)
        val app1 = AppDefinition("app1".toAbsolutePath, role = "*")
        val app2 = AppDefinition("app2".toAbsolutePath, role = "*")
        val apps = Seq(app1, app2)
        val root = repo.root().futureValue
        repo.storeRoot(root, Nil, Nil, Nil, Nil).futureValue
        val deleted = "deleteMe".toAbsolutePath

        val newRoot = root.updateApps(PathId.root, _ => apps.iterator.map(app => app.id -> app).toMap, root.version)

        val exception = new Exception("App Delete Failed")
        appRepo.store(any) returns Future.successful(Done)
        // The legacy repos call delete, the new ones call deleteCurrent
        appRepo.deleteCurrent(deleted) returns Future.failed(exception)
        appRepo.delete(deleted) returns Future.failed(exception)

        appRepo.getVersion(app1.id, app1.version.toOffsetDateTime) returns Future.successful(Some(app1))
        appRepo.getVersion(app2.id, app2.version.toOffsetDateTime) returns Future.successful(Some(app2))

        repo.storeRoot(newRoot, apps, Seq(deleted), Nil, Nil).futureValue
        repo.root().futureValue should equal(newRoot)

        verify(appRepo).store(apps.head)
        verify(appRepo).store(apps.tail.head)
        verify(appRepo, atMost(1)).deleteCurrent(deleted)
        verify(appRepo, atMost(1)).delete(deleted)
        verify(appRepo, atMost(1)).getVersion(app1.id, app1.version.toOffsetDateTime)
        verify(appRepo, atMost(1)).getVersion(app2.id, app2.version.toOffsetDateTime)
        noMoreInteractions(appRepo)
      }
      "retrieve a historical version" in {
        val store = new InMemoryPersistenceStore(metrics)
        store.markOpen()

        val appRepo = AppRepository.inMemRepository(store)
        val repo = createRepo(appRepo, mock[PodRepository], 2)

        val app1 = AppDefinition("app1".toAbsolutePath, role = "*")
        val app2 = AppDefinition("app2".toAbsolutePath, role = "*")

        val initialRoot = repo.root().futureValue
        val firstRoot = initialRoot.updateApps(PathId.root, _ => Map(app1.id -> app1), initialRoot.version)
        repo.storeRoot(firstRoot, Seq(app1), Nil, Nil, Nil).futureValue

        val nextRoot = initialRoot.updateApps(PathId.root, _ => Map(app2.id -> app2), version = Timestamp(1))
        repo.storeRoot(nextRoot, Seq(app2), Seq(app1.id), Nil, Nil).futureValue

        repo.rootVersion(firstRoot.version.toOffsetDateTime).futureValue.value should equal(firstRoot)
        repo.rootVersions().runWith(Sink.seq).futureValue should contain theSameElementsAs
          Seq(firstRoot.version.toOffsetDateTime, nextRoot.version.toOffsetDateTime)
        repo
          .rootVersions()
          .mapAsync(RepositoryConstants.maxConcurrency)(repo.rootVersion)
          .collect { case Some(g) => g }
          .runWith(Sink.seq)
          .futureValue should contain theSameElementsAs
          Seq(firstRoot, nextRoot)
      }
    }
  }

  val versionCacheMaxSize = 1000

  def createInMemRepos(appRepository: AppRepository, podRepository: PodRepository, maxVersions: Int): GroupRepository = { // linter:ignore:UnusedParameter
    val store = new InMemoryPersistenceStore(metrics)
    store.markOpen()
    GroupRepository.inMemRepository(store, appRepository, podRepository, versionCacheMaxSize, RootGroup.NewGroupStrategy.Fail)
  }

  private def zkStore: ZkPersistenceStore = {
    val root = UUID.randomUUID().toString
    val rootClient = RichCuratorFramework(zkClient(namespace = Some(root)), JvmExitsCrashStrategy)
    new ZkPersistenceStore(metrics, rootClient)
  }

  def createZkRepos(appRepository: AppRepository, podRepository: PodRepository, maxVersions: Int): GroupRepository = { // linter:ignore:UnusedParameter
    val store = zkStore
    store.markOpen()
    GroupRepository.zkRepository(store, appRepository, podRepository, versionCacheMaxSize, RootGroup.NewGroupStrategy.Fail)
  }

  def createLazyCachingRepos(appRepository: AppRepository, podRepository: PodRepository, maxVersions: Int): GroupRepository = { // linter:ignore:UnusedParameter
    val store = LazyCachingPersistenceStore(metrics, new InMemoryPersistenceStore(metrics))
    store.markOpen()
    GroupRepository.inMemRepository(store, appRepository, podRepository, versionCacheMaxSize, RootGroup.NewGroupStrategy.Fail)
  }

  def createLoadCachingRepos(appRepository: AppRepository, podRepository: PodRepository, maxVersions: Int): GroupRepository = { // linter:ignore:UnusedParameter
    val store = new LoadTimeCachingPersistenceStore(new InMemoryPersistenceStore(metrics))
    store.markOpen()
    store.preDriverStarts.futureValue
    GroupRepository.inMemRepository(store, appRepository, podRepository, versionCacheMaxSize, RootGroup.NewGroupStrategy.Fail)
  }

  behave like basicGroupRepository("InMemory", createInMemRepos)
  behave like basicGroupRepository("Zk", createZkRepos)
  behave like basicGroupRepository("LazyCaching", createLazyCachingRepos)
  behave like basicGroupRepository("LoadCaching", createLoadCachingRepos)
}


text:
/*
use std::fmt;
use std::io::{self, Write};
use std::marker::PhantomData;
use std::sync::mpsc;

use url::Url;
use tick;
use time::now_utc;

use header::{self, Headers};
use http::{self, conn};
use method::Method;
use net::{Fresh, Streaming};
use status::StatusCode;
use version::HttpVersion;
*/

pub use self::decode::Decoder;
pub use self::encode::Encoder;

pub use self::parse::parse;

mod decode;
mod encode;
mod parse;

/*
fn should_have_response_body(method: &Method, status: u16) -> bool {
    trace!("should_have_response_body({:?}, {})", method, status);
    match (method, status) {
        (&Method::Head, _) |
        (_, 100...199) |
        (_, 204) |
        (_, 304) |
        (&Method::Connect, 200...299) => false,
        _ => true
    }
}
*/
/*
const MAX_INVALID_RESPONSE_BYTES: usize = 1024 * 128;
impl HttpMessage for Http11Message {

    fn get_incoming(&mut self) -> ::Result<ResponseHead> {
        unimplemented!();
        /*
        try!(self.flush_outgoing());
        let stream = match self.stream.take() {
            Some(stream) => stream,
            None => {
                // The message was already in the reading state...
                // TODO Decide what happens in case we try to get a new incoming at that point
                return Err(From::from(
                        io::Error::new(io::ErrorKind::Other,
                        "Read already in progress")));
            }
        };

        let expected_no_content = stream.previous_response_expected_no_content();
        trace!("previous_response_expected_no_content = {}", expected_no_content);

        let mut stream = BufReader::new(stream);

        let mut invalid_bytes_read = 0;
        let head;
        loop {
            head = match parse_response(&mut stream) {
                Ok(head) => head,
                Err(::Error::Version)
                if expected_no_content && invalid_bytes_read < MAX_INVALID_RESPONSE_BYTES => {
                    trace!("expected_no_content, found content");
                    invalid_bytes_read += 1;
                    stream.consume(1);
                    continue;
                }
                Err(e) => {
                    self.stream = Some(stream.into_inner());
                    return Err(e);
                }
            };
            break;
        }

        let raw_status = head.subject;
        let headers = head.headers;

        let method = self.method.take().unwrap_or(Method::Get);

        let is_empty = !should_have_response_body(&method, raw_status.0);
        stream.get_mut().set_previous_response_expected_no_content(is_empty);
        // According to https://tools.ietf.org/html/rfc7230#section-3.3.3
        // 1. HEAD reponses, and Status 1xx, 204, and 304 cannot have a body.
        // 2. Status 2xx to a CONNECT cannot have a body.
        // 3. Transfer-Encoding: chunked has a chunked body.
        // 4. If multiple differing Content-Length headers or invalid, close connection.
        // 5. Content-Length header has a sized body.
        // 6. Not Client.
        // 7. Read till EOF.
        self.reader = Some(if is_empty {
            SizedReader(stream, 0)
        } else {
             if let Some(&TransferEncoding(ref codings)) = headers.get() {
                if codings.last() == Some(&Chunked) {
                    ChunkedReader(stream, None)
                } else {
                    trace!("not chuncked. read till eof");
                    EofReader(stream)
                }
            } else if let Some(&ContentLength(len)) =  headers.get() {
                SizedReader(stream, len)
            } else if headers.has::<ContentLength>() {
                trace!("illegal Content-Length: {:?}", headers.get_raw("Content-Length"));
                return Err(Error::Header);
            } else {
                trace!("neither Transfer-Encoding nor Content-Length");
                EofReader(stream)
            }
        });

        trace!("Http11Message.reader = {:?}", self.reader);

        Ok(ResponseHead {
            headers: headers,
            raw_status: raw_status,
            version: head.version,
        })
        */
    }
}

*/