append to file in tizen - filesystems

I create test.txt with this code:
=====================
function e(arg){
if (typeof arg === "function") {
return arg;
} else {
return function (er) { console.log('[' + arg + '] ' + er); };
}
}
function rs(dir) {
var fh = dir.createFile(" test.text");
{
fh.openStream('rw', function(fs){
fs.write("Hello ");
fs.close();
}, e('openStream'), 'UTF-8');
}
}
tizen.filesystem.resolve('downloads', rs, e('resolve'), 'rw');
=====================
And try to append some text by this code :
=====================
function append(dir) {
var fh = dir.resolve(" test.text");
{
fh.openStream('a', function(fs){
fs.write(" Tizen .. ");
fs.close();
}, e('openStream'), 'UTF-8');
}
}
tizen.filesystem.resolve('downloads', append, e('resolve'), 'a');
====================
but file contain only last text ('Tizen ..').
how to solve this problem?
thanks

Try the code below. It worked in my case.
var newDir, newFile;
tizen.filesystem.resolve("documents", function(dir) {
newDir = dir.createDirectory("newDir");
newFile = newDir.createFile("newFilePath.txt");
newFile.openStream(
"w",
function(fs) {
fs.write("Hello");
fs.close();
},
function(e) {
console.log("Error " + e.message);
}, "UTF-8");
});
var text2;
tizen.filesystem.resolve("documents", function(dir) {
file = dir.resolve("newDir/newFilePath.txt");
file.openStream(
"a",
function(fs) {
fs.write('Tizen .. ');
},
function(e) {
console.log("Error " + e.message);
}, "UTF-8");
file.openStream(
"r",
function(fs) {
text2 = fs.read(file.fileSize);
fs.close();
console.log(text2);
},
function(e) {
console.log("Error " + e.message);
}, "UTF-8");
});
Note: Please check in your project's config.xml file whether you've added the following privileges or not.
<tizen:privilege name="http://tizen.org/privilege/filesystem.read"/>
<tizen:privilege name="http://tizen.org/privilege/filesystem.write"/>

Related

Not able to insert the sensor data into Database

I am trying to insert the sensor data into a SQL Server database. I have tried all the possible way to insert the incoming data into database, but I failed. I am new to Nodejs and I really have no idea why these errors are occurred during executing process. It would be great if anyone could help me.
Thank you in advance.
The error I get is:
TypeError: Cannot read property 'writeHead' of undefined.
function addData (req, resp, reqBody, data)
{
try {
if (!reqBody) throw new Error("Input not valid");
data = JSON.parse(reqBody);
//reqBody = JSON.parse(data);
if (data) {//add more validations if necessary
var sql = "INSERT INTO arduinoData (Machine, StartTime, EndTime, LengthTime) VALUES ";
sql += util.format("(%s, '%s', %s, %s) ", data.Machine, data.StartTime, data.EndTime, data.LengthTime);
db.executeSql(sql, function (data, err) {
if (err) {
httpMsgs.show500(req, resp, err);
}
else {
httpMsgs.send200(req, resp);
}
});
}
else {
throw new Error("Input not valid");
}
}
catch (ex) {
httpMsgs.show500(req, resp, ex);
}
};
function sendBackupData()
{
var jsonTable = { "table": [] };
fs.readFile("backup.json", "utf8", function (err, data) {
if (err) throw err;
jsonTable = JSON.parse(data);
if (jsonTable.table.length == 0) {
return;
}
for (var index = 0; index < jsonTable.table.length; index++) {
var options = {
url: serverURL,
method: "POST",
form: jsonTable.table.shift()
};
request.post(options, function (error, response, body) {
if (!error) {
console.log("Sent backup message!");
} else {
console.log('Error: ' + error);
console.log("CANT'T SEND BACK");
console.log(options.form);
jsonTable.table.push(options.form);
}
});
}
var outputJSON = JSON.stringify(jsonTable);
console.log(outputJSON);
fs.writeFile("backup.json", outputJSON, "utf8", function (err) {
if (err) throw err;
console.log("Sent backup data!");
});
});
}
function getTime()
{
var date = new Date();
var year = date.getFullYear();
var month = ('0' + (date.getMonth() + 1)).slice(-2);
var day = ('0' + date.getDate()).slice(-2);
var hour = ('0' + date.getHours()).slice(-2);
var minute = ('0' + date.getMinutes()).slice(-2);
var second = ('0' + date.getSeconds()).slice(-2);
// Unix Time
var unixTime = Math.floor(date / 1000);
// Check if it is day or night
var isDay;
if (date.getHours() >= 8 & date.getHours() < 16)
{
isDay = true;
}
else
{
isDay = false;
}
return [year + '-' + month + '-' + day, hour + ':' + minute + ':' + second, unixTime, isDay];
}
/*
--- Main Code ---
*/
function vibrationStart()
{
/*
Should get:
- Start time and date the vibration started
- Whether it was day or night
Will send the message, if there is network connection, once complete.
Will store message into a JSON file if there is no network connection.
*/
var jsonTable = { "table": [] };
var startTime = getTime();
console.log(startTime[0] + " " + startTime[1]);
var startData = {
machine: machineName,
start_time: startTime[0] + " " + startTime[1],
day_night: startTime[3],
active: "true"
};
const options = {
url: serverURL,
method: "POST",
form: startData
};
var reqBody = [{
Machine : "",
StartTime : ""
}];
reqBody.push({"Machine" : startData.machine,"StartTime" : startData.start_time});
var outputJSON = JSON.stringify(reqBody);
request.post(options, function (error, response, body) {
if (!error) {
console.log("Sent starting message!");
sendBackupData();
addData();
} else {
console.log("CANT'T SEND");
// Write to JSON file for backup if can't send to server
fs.readFile("backup.json", "utf8", function readFileCallback(err, data) {
if (err) throw err;
jsonTable = JSON.parse(data);
jsonTable.table.push(startData);
var outputJSON = JSON.stringify(jsonTable);
fs.writeFile("backup.json", outputJSON, "utf8", function (err) {
if (err) throw err;
});
});
}
});
return startTime[2];
}
function vibrationStop(startTimeUnix)
{
var jsonTable = { "table": [] };
var endTime = getTime();
console.log(endTime[0] + " " + endTime[1]);
var endTimeUnix = endTime[2];
var lengthTime = endTimeUnix - startTimeUnix;
console.log("Length time: " + lengthTime);
var endData = {
machine: machineName,
end_time: endTime[0] + " " + endTime[1],
length_time: lengthTime,
active: "false"
};
const options = {
url: serverURL,
method: "POST",
form: endData
};
var reqBody = [{
EndTime : "",
LengthTime :"",
}];
reqBody.push({"EndTime" : endData.end_time,"LengthTime" : endData.length_time});
var outputJSON = JSON.stringify(reqBody);
request.post(options, function (error, response, body) {
if (!error) {
console.log("Sent end message!");
sendBackupData();
addData()
} else {
console.log("CANT'T SEND");
// Write to JSON file for backup if can't send to server
fs.readFile("backup.json", "utf8", function readFileCallback(err, data) {
if (err) throw err;
jsonTable = JSON.parse(data);
jsonTable.table.push(endData);
var outputJSON = JSON.stringify(jsonTable);
fs.writeFile("backup.json", outputJSON, "utf8", function (err) {
if (err) throw err;
});
});
}
});
}
http.createServer(function (req, resp) {
app.get('/', addData);
}).listen(settings.webPort, function () {
console.log("Started listening at: " + settings.webPort);
});

AngularJS and QUnit: Unknown provider: LocalDataProvider <- LocalData <- FileLogger

Anyone who can help me fix this? I'm such a beginner in unit testing scripts.
Here's my html code.
<html>
<head>
<meta charset = "utf-8">
<title>QUnit and AngularJS</title>
<link rel = "stylesheet" href = "https://code.jquery.com/qunit/qunit-1.22.0.css">
<script src = "https://code.angularjs.org/1.1.0/angular.js"></script>
<script src = "https://code.angularjs.org/1.1.0/angular-mocks.js"></script>
<script src = "https://code.jquery.com/qunit/qunit-1.22.0.js"></script>
<script src = "OfflineStorage/local-storage.service.js"></script>
<script src = "AppLogging/file-logger.service.js"></script>
<script src = "basic.js"></script>
<script src = "qunit.js"></script>
</head>
<body>
<div id = "qunit"></div>
<div id = "qunit-fixture"></div>
</body>
</html>
here's qunit js.
var injector = angular.injector(['ng', 'FileLoggerManager']);
module("File Logger Test", function () {
var svc = injector.get('FileLogger');
});
and here's the one that needed to be tested.
(function() {
'use strict';
angular
.module('FileLoggerManager', [])
.service('FileLogger', Body);
function Body(LocalData, $q, $timeout) {
var service = {
writeLog: writeLog,
SetLogLevel: SetLogLevel,
SetFilePath: SetFilePath,
SetMaxLogSize: SetMaxLogSize,
DeleteLogFiles: DeleteLogFiles,
SendLogsToEmail: SendLogsToEmail
};
// LOG WRITER
var logOb;
var logDirOb;
var logLocation;
var curlogsize = 0;
var logStrings = [];
var loggingStopped = true;
// DEFAULT CURRENT LOG FILE NAME
var logfilename = "MPC";
var appObj = null;
var maxlogsize = 1000000;
var customlogfolder = "sdcard/";
var maxloglevel = 2;
console.log("File Logger initialized.");
// SETTINGS
if (LocalData.loadData('application')) {
appObj = JSON.parse(LocalData.loadData('application'));
// MAX LOGFILE SIZE (BYTES)
maxlogsize = 1000000 * ( appObj.maxLogFileSize ? appObj.maxLogFileSize : 1 );
// LOG SAVE PATH CUSTOM FOLDER NAME
customlogfolder = appObj.logFilePath ? appObj.logFilePath + '/' : 'sdcard/';
// MAX LOG LEVEL (everything below will be logged)
maxloglevel = appObj.logLevel ? appObj.logLevel : 2;
}
// DEVICE READY
document.addEventListener('deviceready', onDeviceReady, false);
function onDeviceReady(){
// WRITE AND GET LOG FILE READY
SetFilePath(customlogfolder);
}
// SET LOG LEVEL
function SetLogLevel(logLevel) {
console.log("File Logger: Set log level to " + logLevel);
maxloglevel = logLevel;
}
// SET FILE PATH
function SetFilePath(filePath) {
while (filePath.indexOf('//') > -1) {
filePath = filePath.replace('//','/');
}
while(filePath[0] == '/') {
filePath = filePath.substring(1);
}
if (filePath[filePath.length-1] != '/') {
filePath = filePath + '/';
}
if (filePath.indexOf('sdcard') == 0) {
filePath = filePath.substring(7);
}
customlogfolder = filePath;
logLocation = cordova.file.externalRootDirectory + customlogfolder;
console.log("File Logger: Log Path = " + customlogfolder);
if (customlogfolder == "") {
initializeLogFile(logLocation);
}
else {
checkIfDirectoryExist(customlogfolder, cordova.file.externalRootDirectory);
}
}
/*
CHECK IF DIRECTORY EXISTS
*/
function checkIfDirectoryExist(filePath, rootDirLoc) {
window.resolveLocalFileSystemURL(filePath, function(dir) {
console.log("File Logger: Path found = " + filePath);
},
function (dir) {
var curFolder = filePath;
var withSubDir = false;
if ((filePath.indexOf('/') > 0) &&
(filePath.indexOf('/') != filePath.length-1)) {
withSubDir = true;
curFolder = filePath.substring(0, filePath.indexOf('/'));
}
window.resolveLocalFileSystemURL(rootDirLoc, function(dir) {
dir.getDirectory(curFolder, { create: true }, function (dirEntry) {
console.log("File Logger: New Directory = " + curFolder );
if(withSubDir == false) {
initializeLogFile(logLocation);
}
},
function(dirEntry) {
console.log("File Logger: Create Dir failed = " + curFolder);
});
},
function(dir){
console.log("File Logger: Root directory not found = " + rootDirLoc);
});
if (withSubDir) {
filePath = filePath.substring(filePath.indexOf('/')+1);
checkIfDirectoryExist(filePath, rootDirLoc + curFolder + '/');
}
});
}
// INITIALIZE AND CREATE LOG FILE
function initializeLogFile(logLocation) {
window.resolveLocalFileSystemURL(logLocation, function(dir) {
logDirOb = dir;
dir.getFile(logfilename + ".txt", { create:true }, function(file) {
logOb = file;
writeToLog();
});
});
}
// SET MAX SIZE
function SetMaxLogSize (maxSize) {
maxlogsize = 1000000 * ( maxSize? maxSize : 1 );
console.log("File Logger: Max File size = " + maxlogsize);
}
// WRITE LOG
function writeToLog() {
if(!logOb){
console.log("File Logger: No log added.");
return;
}
if(logStrings.length == 0) {
return;
}
loggingStopped = false;
logOb.createWriter(function(fileWriter) {
fileWriter.onwriteend = function(e) {
logStrings.splice(0,1);
if(logStrings.length == 0) {
loggingStopped = true;
}
else {
loggingStopped = false;
writeToLog();
}
};
var log = logStrings[0];
fileWriter.seek(fileWriter.length);
var blob = new Blob([log], {type:'text/plain'});
fileWriter.write(blob);
}, ReadLogfail);
CheckLogSize();
}
function writeLog(logLevel, str) {
if (maxloglevel == 0) return;
if (maxloglevel>=logLevel && logLevel>0){
var level;
if(logLevel == 4)
level = "DEBUG";
else if(logLevel == 3)
level = "INFO";
else if(logLevel == 2)
level = "WARNING";
else if(logLevel == 1)
level = "ERROR";
var log = "[" + GetLogDate() + "] " + level + " : " + str + "\n";
logStrings.push(log);
if(loggingStopped){
writeToLog();
}
}
}
// CHECK LOG SIZE
function CheckLogSize(){
logOb.file(function(file) {
curlogsize = file.size;
if (parseFloat(curlogsize)>parseFloat(maxlogsize)) {
DeleteLogFiles();
initializeLogFile(logLocation);
}
}, ReadLogfail);
}
function ReadLogfail(e) {
console.log("File Logger: FileSystem Error");
console.dir(e);
}
// GET DATE (SERIAL/NORMAL)
function GetLogDate(){
//var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var date = new Date();
var dateYear = date.getFullYear();
var dateMonth = LogPad(date.getMonth()+1);
var dateDay = LogPad(date.getDate());
var dateHour = LogPad(date.getHours());
var dateMinute = LogPad(date.getMinutes());
var dateSeconds = LogPad(date.getSeconds());
return dateYear + '.' + dateMonth + '.' + dateDay + ' ' + dateHour + ':' + dateMinute + ':' + dateSeconds;
}
// ADD 0 if number is below 9
function LogPad(n){
return n<10 ? '0'+n : n;
}
// DELETE LOG FILE
function DeleteLogFiles(){
if (!logOb) return 0;
window.resolveLocalFileSystemURL(logLocation, function(dir) {
logDirOb = dir;
dir.getFile(logfilename+".txt", {create:true}, function(file) {
file.remove(function() {
console.log('File logger: File removed = ' + logfilename + ".txt");
});
});
});
}
function SendLogsToEmail() {
cordova.plugins.email.isAvailable( function (isAvailable) {
if(isAvailable) {
cordova.plugins.email.open({
to: '',
subject: 'MSCM MPC Logs',
body: '',
attachments: [logLocation+'MPC.txt',logLocation+'MPC_COMM.txt']
});
} else {
console.log("No email account is setup in this device.");
var confirmPopup = $ionicPopup.alert({
cssClass: 'custom-popup',
template: '<div>{{ "confirm_no_email_setup" | translate }}</div>'
});
};
});
}
return service;
}})();
However while writing QUnit test an error occurs. "Unknown provider: LocalDataProvider <- LocalData <- FileLogger".
Thanks in advance!

Cordova delete files after sqlite delete it

I have this app where I take picture or select it from gallery then move it into file-system , save the imgpath for the image into sqlite db and display it, everything works great so far , now when I delete the imgpath from the sqlite db , I want to delete it from file-system at the same time .
$scope.deleteImg = function(imgPath) {
if (!imgPath) {
console.error("No fileName specified. File could not be deleted.");
return false;
} else {
$cordovaFile.checkFile(cordova.file.externalRootDirectory, imgPath.id).then(function() {
$cordovaFile.removeFile(cordova.file.externalRootDirectory, imgPath.id).then(function(result) {
console.log("image '" + imgPath + "' deleted", JSON.stringify(result));
}, function(err) {
console.error("Failed to delete file '" + imgPath.id + "'", JSON.stringify(err));
});
}, function(err) {
console.log("image '" + imgPath.id + "' does not exist", JSON.stringify(err));
});
}
$scope.add = function(path) {
 
console.log("I AM ADDING TO DB WITH PATH: " + path);   
  
$cordovaSQLite.execute(db, "INSERT INTO imageTable (image) VALUES(?)", [path]).then(
function(res) {
console.log("I AM DONE ADDING TO DB");   
}
);                
      
},
function(e) {        
alert(e);      
};
    
  
$scope.ShowAllData = function() {
console.log("I AM READING FROM DB");   
$scope.images = [];             
$cordovaSQLite.execute(db,"SELECT * FROM imageTable ORDER BY id DESC"  ).then(        function(res) {
console.log("I FINISHED READING FROM DB");   
          
if (res.rows.length > 0) {            
for (var i = 0; i < res.rows.length; i++) {              
$scope.images.push({
id: res.rows.item(i).id,
image: res.rows.item(i).image
              
});
}          
} 
return $scope.images;
        
},         function(error) {          
alert(error);        
}      );
    
}  
$scope.getImgIDbyName = function(name) {
console.log('[getImgIDbyName] - get image with name: ' + name);
var sql = "SELECT * FROM imageTable WHERE image = '" + name + "';";
console.log(sql);
$cordovaSQLite.execute(db,
sql
).then(
function(res) {
if (res.rows.length > 0) {
if (res.rows.length > 1) {
console.log('[getImgIDbyName] - OOPS more than 1 image returned!!!! ' + name);
} else {
$scope.delete(res.rows.item(0).id);
$scope.deleteImg(imagePath.id);
}
} else {
console.log('[getImgIDbyName] - no image found with name: ' + name);
}
},
function(error) {
alert("error occured: " + error.message);
}
);
}
First download the plugin - cordova plugin add cordova-plugin-file
and then execute the following code
var path = cordova.file.applicationDirectory + '/www/res/image'; // get the absolute path
var filename = "image.png";
window.resolveLocalFileSystemURL(path, function(dir) {
dir.getFile(filename, {create:false}, function(fileEntry) {
fileEntry.remove(function(){
// The file has been removed succesfully
},function(error){
// Error deleting the file
},function(){
// The file doesn't exist
});
});
});
Here is the complete documentation : https://github.com/apache/cordova-plugin-file/#where-to-store-files

Delete cacheDirectory cache cordova file system ionic

There is a mobile app in which i want to delete the cached images downloaded by a particular user after log out.Suppose user1 logged in and download few images and user2 logged in and downloaded few images.User2 should not see downloaded images of any other user.
downloadFile : function(downloadLink, downloadFileName, downloadFileMimeType) {
$ionicLoading.show({
template: '<ion-spinner></ion-spinner>'
});
var accessToken = $window.localStorage.getItem(SYSTEM.AUTH_TOKEN);
var options = {
headers : {
'Authorization' : 'Bearer ' + accessToken
}
};
var ext;
if (downloadFileMimeType == 'application/pdf') {
ext = '.pdf';
} else {
ext = '.jpg';
}
var localPath;
if(ionic.Platform.isAndroid()){
localPath = cordova.file.externalCacheDirectory;
}else{
localPath = cordova.file.cacheDirectory;
}
localPath = localPath + downloadFileName.trim().replace(/\s+/g, '-') + ext;
var ft = new FileTransfer();
ft.download(downloadLink, localPath, function(entry) {
$ionicLoading.hide();
console.log("Downloading report on path - " + entry.toURL());
cordova.plugins.fileOpener2.open(entry.toURL(), downloadFileMimeType, {
error : function(e) {
console.log('Error status: ' + e.status + ' - Error message: ' + e.message);
},
success : function(fileEntry) {
console.log('File opened successfully');
}
});
}, function fail(error) {
$ionicLoading.hide();
console.log("Error while downloading report with error code - " + error.code);
}, true, options);
}
You can store files downloaded by specific user under a user specific folder in device and delete the same when the other user logs in. Else you can follow some file naming convention specific to the users while storing the files in folder and delete those files specific to particular user when the other user logs in. The sample snippet for directory deletion and its contents using cordova file plugin is as follows:
function clearDirectory() {
if (ionic.Platform.isAndroid()) {
window.resolveLocalFileSystemURL(cordova.file.externalRootDirectory, onFileSystemDirSuccess, fail);
} else {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFileSystemDirSuccess, fail);
}
function onFileSystemDirSuccess(fileSystem) {
var entry = "";
if (ionic.Platform.isAndroid()) {
entry = fileSystem;
} else {
entry = fileSystem.root;
}
entry.getDirectory("DIRECTORY_TO_DELETE", {
create: true,
exclusive: false
},
function(entry) {
entry.removeRecursively(function() {
console.log("Remove Recursively Succeeded");
}, fail);
}, getDirFail);
}
function getDirFail(error) {
navigator.notification.alert("Error");
};
function fail(error) {
navigator.notification.alert("Error");
};
}

Ext.device.filesystem.FileEntry.read() - type: "text" returns blank file

I am facing a problem with Ext.device.filesystem.FileEntry.read() method. When I try to read the text/JSON file as text, I get a blank file. Any idea? Looks like readastext method of extjs file reader is buggy.
Following does not work:
var fileEntry = new Ext.device.filesystem.FileEntry(newFilePath, fileSystem);
fileEntry.read({
//type: "binaryString",
encoding: 'UTF8',
type: "text",
//type: "text",
success: function(fileData) {
console.log('--- fileData');
console.log(fileData);
console.log('//--- fileData');
self.onUploadJSONSuccess(fileData, fileName, networkId, activityId, section, showWaitScreen, callback);
},
failure: function(error) {
if(showWaitScreen) {
console.log('Failed to read file: ' + error);
Ext.Msg.alert('Failed to read file: ' + error);
}
}
});
But if I change the type from "text" to "binaryString", it reads the file but off course mess up the special characters.
var fileEntry = new Ext.device.filesystem.FileEntry(newFilePath, fileSystem);
fileEntry.read({
type: "binaryString",
success: function(fileData) {
console.log('--- fileData');
console.log(fileData);
console.log('//--- fileData');
self.onUploadJSONSuccess(fileData, fileName, networkId, activityId, section, showWaitScreen, callback);
},
failure: function(error) {
if(showWaitScreen) {
console.log('Failed to read file: ' + error);
Ext.Msg.alert('Failed to read file: ' + error);
}
}
});
Regards,
Waheed
Changing the encoding to 'UTF-8' does the trick. So, working code is below:
fileEntry.read({
//type: "binaryString",
type: "text",
encoding: "UTF-8",
success: function(fileData) {
console.log('--- fileData');
console.log(fileData);
console.log('//--- fileData');
self.onUploadJSONSuccess(fileData, fileName, networkId, activityId, section, showWaitScreen, callback);
},
failure: function(error) {
if(showWaitScreen) {
console.log('Failed to read file: ' + error);
Ext.Msg.alert('Failed to read file: ' + error);
}
}
});

Resources