How to retrieve a folder from the repository in alfresco? - alfresco

I have the following code(s) in an attempt to retrieve a folder located in the repository root in alfresco:
test-folder.get.json.ftl:
<#escape x as jsonUtils.encodeJSONString(x)>
{"data" :
{
<#if folder??>
"folderName" : "${folder.name}",
"folderPath" : "${folder.displayPath}/${folder.name}",
</#if>
"status" : "${status}"
}
}
</#escape>
test-folder.get.json.js
main();
function main()
{
var folder = companyhome.childByNamePath("Photo");
if (folder == undefined || !folder.isContainer){
logger.log("\n\n==>Folder is undefined<===\n\n");
status.code = 404;
status.message = "Folder " + url.extension + " not found.";
}
else{
logger.log("\n\n==> Got the folder path: "+ folder.displayPath);
model.folder=folder;
}
model.status=status;
}
when I check the webscripts in the repo I get only the status code. further more neither of the logger messages are printed in the logs and no errors are showing in the logs.
Anything I'm missing?

One thing I can advice you is to use the JavaScript Console developed by Florian Maul.
For me, It was a very useful tool.
You can know the result of your,"var folder = companyhome.childByNamePath("Photo");", just in a milli second.And you can just log the "folder[cm:name]" to view the results.
This link is useful.
JavaScript Console

A couple of possible issues:
are you logged in when calling this webscript? Non-logged-in users might not have access to the "Photo" space.
is your logging enabled? Try using logger.error instead of logger.log (or check your logging levels in log4j.properties).

Related

how to solve Browser errors were logged to the console?

PageSpeed Insights is showing this error message for my wordpress website (MyBGMI.Com
I can't fix this problem. To be very honest can't understand the problem.
**Errors logged to the console indicate unresolved problems. They can come from network request failures and other browser concerns. Learn more
Source
Description
TypeError: Cannot read properties of null (reading 'parentNode') at data:text/javascript;base64,dmFyIGRvd25sb2FkQnV0dG9uPWRvY3VtZW50LmdldEVsZW1lbnRCeUlkKCJkb3dubG9hZCIpO3ZhciBjb3VudGVyPTQwO3ZhciBuZXdFbGVtZW50PWRvY3VtZW50LmNyZWF0ZUVsZW1lbnQoInAiKTtuZXdFbGVtZW50LmlubmVySFRNTD0iWW91IGNhbiBkb3dubG9hZCB0aGUgZmlsZSBpbiA0MCBzZWNvbmRzLiI7dmFyIGlkO2Rvd25sb2FkQnV0dG9uLnBhcmVudE5vZGUucmVwbGFjZUNoaWxkKG5ld0VsZW1lbnQsZG93bmxvYWRCdXR0b24pO2lkPXNldEludGVydmFsKGZ1bmN0aW9uKCl7Y291bnRlci0tO2lmKGNvdW50ZXI8MCl7bmV3RWxlbWVudC5wYXJlbnROb2RlLnJlcGxhY2VDaGlsZChkb3dubG9hZEJ1dHRvbixuZXdFbGVtZW50KTtjbGVhckludGVydmFsKGlkKX1lbHNle25ld0VsZW1lbnQuaW5uZXJIVE1MPSJKVVNUIFdBSVQgIitjb3VudGVyLnRvU3RyaW5nKCkrIiBTRUNPTkRTLiIrIllPVVIgQkdNSSAyLjMgRE9XTkxPQUQgTElOSyBJUyBHRU5FUkFUSU5HIn19LDEwMDAp:1:200**
I tired figured out the issue but did not understand anything. Just checked the page with chrome browser developers tool.
And where i found two erros. but can't understand how to fix them.
enter image description here
This is base64 encoded JavaScript (usually bad when found on WordPress site)
(you can decode it online here: https://www.base64decode.org/)
Decoded it says:
var downloadButton=document.getElementById("download");
var counter=40;
var newElement=document.createElement("p");
newElement.innerHTML="You can download the file in 40 seconds.";
var id;
downloadButton.parentNode.replaceChild(newElement,downloadButton);
id=setInterval(function(){
counter--;
if(counter<0){
newElement.parentNode.replaceChild(downloadButton,newElement);
clearInterval(id)
}else{
newElement.innerHTML="JUST WAIT "+counter.toString()+" SECONDS."+"YOUR BGMI 2.3 DOWNLOAD LINK IS GENERATING"
}
},1000)
it appears that newElement.parentNode is null and that's what's causing the error.
if this is your code, and a desired code-piece on your WordPress website - try changing if(counter<0){ into if (newElement.parentNode && counter<0) { . otherwise, find where this is coming from, and remove it from your code base.
Update
Try this:
var downloadButton=document.getElementById("download");
var counter=40;
var newElement=document.createElement("p");
newElement.innerHTML="You can download the file in 40 seconds.";
var id;
if (downloadButton && newElement.parentNode) {
downloadButton.parentNode.replaceChild(newElement,downloadButton);
id=setInterval(function(){
counter--;
if(counter<0){
newElement.parentNode.replaceChild(downloadButton,newElement);
clearInterval(id)
}else{
newElement.innerHTML="JUST WAIT "+counter.toString()+" SECONDS."+"YOUR BGMI 2.3 DOWNLOAD LINK IS GENERATING"
}
},1000)
}

NSFileProtectionComplete doesn't encrypt the core data file

I am using Xcode 7.3 for iOS 9.3 to try and encrypt a Core Data file. I am trying to use NSPersistentStoreFileProtectionKey and set it to NSFileProtectionComplete to enable the encryption. It is not working for some reason and I can always see the .sqlite file generated by the app and browse through the content in sqlitebrowser or iexplorer. Here is my code :
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
let dict: [NSObject : AnyObject] = [
NSPersistentStoreFileProtectionKey : NSFileProtectionComplete
]
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: dict)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
do {
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
try NSFileManager.defaultManager().setAttributes([NSFileProtectionKey : NSFileProtectionComplete], ofItemAtPath: url.path!)
} catch {
}
do {
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite-wal")
try NSFileManager.defaultManager().setAttributes([NSFileProtectionKey : NSFileProtectionComplete], ofItemAtPath: url.path!)
// try print(NSFileManager.defaultManager().attributesOfFileSystemForPath(String(url)))
} catch {
}
do {
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite-shm")
try NSFileManager.defaultManager().setAttributes([NSFileProtectionKey : NSFileProtectionComplete], ofItemAtPath: url.path!)
// try print(NSFileManager.defaultManager().attributesOfFileSystemForPath(String(url)))
} catch {
}
return coordinator
}()
I have also enabled Data Protection for my target in the "Capabilities". I have regenerated the provisioning profile from the Apple Developer portal and am using that with Enabled Data Protection.
I am also using the following code to check the file attributes of .sqlite , .sqlite-wal and .sqlite-shm files. NSFileProtectionKey is correctly set for all 3 of them.
func checkProtectionForLocalDb(atDir : String){
let fileManager = NSFileManager.defaultManager()
let enumerator: NSDirectoryEnumerator = fileManager.enumeratorAtPath(atDir)!
for path in enumerator {
let attr : NSDictionary = enumerator.fileAttributes!
print(attr)
}
}
I also tried disabling the Journal mode to prevent -wal and -shm files from being created. But I can still read the .sqlite file. Even though the attributes read NSFileProtectionComplete.
As described in the Apple Documentation at Apple Docs under "Protecting Data using On Disk Encryption", I tried to check whether the value of variable protectedDataAvailable changes as shown in the code below
public func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
NSThread.sleepForTimeInterval(10)
sleep(10)
let dataAvailable : Bool = UIApplication.sharedApplication().protectedDataAvailable
print("Protected Data Available : " + String(dataAvailable))
}
If I check the value without the delay it's set to true but after adding the delay it's set to false. This is kind of encouraging, however, right after, when I download the container, to show the content, it still has .sqlite file that still shows the content when opened in sqlitebrowser.
Ok, I finally understand this.
Using Xcode 7.3.1
Enabling File Protection
Enable File Protection using the Capabilities tab on your app target
If you do not want the default NSFileProtectionComplete, change this setting in the developer portal under your app id
Make sure Xcode has the new provisioning profile this creates.
For protecting files your app creates, that's it.
To protect Core Data, you need to add the NSPersistentStoreFileProtectionKey: NSFileProtectionComplete option to your persistent store.
Example:
var options: [NSObject : AnyObject] = [NSMigratePersistentStoresAutomaticallyOption: true,
NSPersistentStoreFileProtectionKey: NSFileProtectionComplete,
NSInferMappingModelAutomaticallyOption: true]
do {
try coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: options)
Testing File Protection
I am not able to test this using a non-jailbroken device connected to a computer. Every attempt to access the device this way requires that I "trust" the computer and I believe that trusted computers are always able to read the phone's data ("Trusted computers can sync with your iOS device, create backups, and access your device's photos, videos, contacts, and other content" - https://support.apple.com/en-us/HT202778). I think the other answers on SO referencing this technique are no longer valid with more recent versions of iOS. Indeed, I am always able to download the container using XCode and view the app's data using iPhone Explorer. So how to test...
1 - Create an archive and ensure that it is has the proper entitlements by running the following on the .app file from the command line:
codesign -d --entitlements :- <path_to_app_binary>
You should see a key/value pair that represents your Data Protection level. In this example, NSFileProtectionComplete:
<key>com.apple.developer.default-data-protection</key>
<string>NSFileProtectionComplete</string>
In addition, I used the following two techniques to satisfy myself that the data protection is indeed working. They both require code changes.
2 - Add some code to verify that the proper NSFileProtectionKey is being set on your files and/or core data store:
NSFileManager.defaultManager().attributesOfItemAtPath(dbPath.path!)
If I print this out on one of my files I get:
["NSFileCreationDate": 2016-10-14 02:06:39 +0000, "NSFileGroupOwnerAccountName": mobile, "NSFileType": NSFileTypeRegular, "NSFileSystemNumber": 16777218, "NSFileOwnerAccountName": mobile, "NSFileReferenceCount": 1, "NSFileModificationDate": 2016-10-14 02:06:39 +0000, "NSFileExtensionHidden": 0, "NSFileSize": 81920, "NSFileGroupOwnerAccountID": 501, "NSFileOwnerAccountID": 501, "NSFilePosixPermissions": 420, "NSFileProtectionKey": NSFileProtectionComplete, "NSFileSystemFileNumber": 270902]
Note the "NSFileProtectionKey": "NSFileProtectionComplete" pair.
3 - Modify the following code and hook it up to some button in your app.
#IBAction func settingButtonTouch(sender: AnyObject) {
updateTimer = NSTimer.scheduledTimerWithTimeInterval(0.5, target: self,
selector: #selector(TabbedOverviewViewController.runTest), userInfo: nil, repeats: true)
registerBackgroundTask()
}
var backgroundTask: UIBackgroundTaskIdentifier = UIBackgroundTaskInvalid
var updateTimer: NSTimer?
func registerBackgroundTask() {
backgroundTask = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler {
[unowned self] in
self.endBackgroundTask()
}
assert(backgroundTask != UIBackgroundTaskInvalid)
}
func endBackgroundTask() {
NSLog("Background task ended.")
UIApplication.sharedApplication().endBackgroundTask(backgroundTask)
backgroundTask = UIBackgroundTaskInvalid
}
func runTest() {
switch UIApplication.sharedApplication().applicationState {
case .Active:
NSLog("App is active.")
checkFiles()
case .Background:
NSLog("App is backgrounded.")
checkFiles()
case .Inactive:
break
}
}
func checkFiles() {
// attempt to access a protected resource, i.e. a core data store or file
}
When you tap the button this code begins executing the checkFiles method every .5 seconds. This should run indefinitely with the app in the foreground or background - until you lock your phone. At that point it should reliably fail after roughly 10 seconds - exactly as described in the description of NSFileProtectionComplete.
We need to understand how Data Protection works.
Actually, you don't even need to enable it. Starting with iOS7, the default protection level is “File Protection Complete until first user authentication.”
This means that the files are not accessible until the user unlocks the device for the first time. After that, the files remain accessible even when the device is locked and until it shuts down or reboots.
The other thing is that you're going to see the app's data on a trusted computer always - regardless of the Data Protection level setting.
However, the data can’t be accessed if somebody tries to read them from the flash drive directly. The purpose of Data Protection is to ensure that sensitive data can’t be extracted from a password-protected device’s storage.
After running this code, I could still access and read the contents written to protectedFileURL, even after locking the device.
do {
try data.write(to: protectedFileURL, options: .completeFileProtectionUnlessOpen)
} catch {
print(error)
}
But that's normal since I ran iExplorer on a trusted computer.
And for the same reason, it's fine if you see your sqlite file.
The situation is different if your device gets lost or stolen. A hacker won't be able to read the sqlite file since it's encrypted. Well, unless he guesses your passcode somehow.
Swift 5.0 & Xcode 11:
Enable "Data Protection" in "Capabilities".
Use the following code to protect a file or folder at a specific path:
// Protects a file or folder + excludes it from backup.
// - parameter path: Path component of the file.
// - parameter fileProtectionType: `FileProtectionType`.
// - returns: True, when protected successful.
static func protectFileOrFolderAtPath(_ path: String, fileProtectionType: FileProtectionType) -> Bool {
guard FileManager.default.fileExists(atPath: path) else { return false }
let fileProtectionAttrs = [FileAttributeKey.protectionKey: fileProtectionType]
do {
try FileManager.default.setAttributes(fileProtectionAttrs, ofItemAtPath: path)
return true
} catch {
assertionFailure("Failed protecting path with error: \(error).")
return false
}
}
(Optional) Use the following code to check whether the file or folder at the specific path is protected (note: This only works on physical devices):
/// Returns true, when the file at the provided path is protected.
/// - parameter path: Path of the file to check.
/// - note: Returns true, for simulators. Simulators do not have hardware file encryption. This feature is only available for real devices.
static func isFileProtectedAtPath(_ path: String) -> Bool {
guard !Environment.isSimulator else { return true } // file protection does not work on simulator!
do {
let attributes = try FileManager.default.attributesOfItem(atPath: path)
if attributes.contains(where: { $0.key == .protectionKey }) {
return true
} else {
return false
}
} catch {
assertionFailure(String(describing: error))
return false
}
}
Rather than encrypt a file at the local level I set NSFileProtectionComplete for the app as a whole.
Create the file 'entitlements.plist' in your apps root folder with the following content.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>DataProtectionClass</key>
<string>NSFileProtectionComplete</string>
</dict>
</plist>
Then if you haven't already done so already (this could be the problem with your file level encryption) enable Data Protection in your apps capabilities.

Send SQLite db file from within app

I have looked everywhere and I can't find out how to do this; I'm so frustrated...
How can I allow the user to send (via email) the SQLite db file?
That's it in a nutshell. I can convert it to string and attach, but I want to send the actual db file. And I'm using a new phone that doesn't have an external SD card.
The app is just a form that the user fills out, then it's saved to a SQLite database. That works wonderfully. As does printing the db to string (text) and then sending it. But, I want the user to email the actual db file (so I can use C# to read, process it, and "recreate" a real form).
Or should I be using something other than SQLite?
Edit: This is as far as I've made it. It seems to work, but it does not actually attach the file or rather the file is "blank/empty". Debug log says no such file or directory. screenshot of debug log here:http://imgur.com/oyzdtuJ
//trying again to send a SQL db file
//this seems to work and shows that it's attaching a file, but the file is empty so it won't attach
//gmail will say "cant attach empty file"
private void sendFile(String email){
File myFile = this.getFileStreamPath("testresults.db");
if(myFile != null) {
Log.d("LOG PRINT SHARE DB", "File Found, Here is file location: " + myFile.toString());
}else {
Log.w("Tag", "file not found!");
}
Uri contentUri = FileProvider.getUriForFile(this, "com.columbiawestengineering.columbiawest.MainActivity", myFile);
Log.d("LOG PRINT SHARE DB", "contentUri got: here is contentUri: " + contentUri.toString());
//grant permision for app with package "com.columbiawestengineering.columbiawest", eg. before starting other app via intent
this.grantUriPermission("com.columbiawestengineering.columbiawest", contentUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
Log.d("LOG PRINT SHARE DB", "permission granted, here is contentUri: " + contentUri.toString());
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.setType("application/octet-stream");
shareIntent.putExtra(Intent.EXTRA_SUBJECT, "blaaa subject");
String to[] = { email };
shareIntent.putExtra(Intent.EXTRA_EMAIL, to);
shareIntent.putExtra(Intent.EXTRA_TEXT, "blah blah message");
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
shareIntent.putExtra(Intent.EXTRA_STREAM, contentUri);
startActivityForResult(Intent.createChooser(shareIntent, "Send mail..."), 1252);
//revoke permisions
this.revokeUriPermission(contentUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
See this answer
Android Utility to send sqlite db to server
You could do this any number of ways. I'd say posting it to a web service is easiest. If you can only use email then I'd compress and encode it and attach it to an email but that sounds painful.
Solved. FileProvider cannot access the database directory. The db file must be copied to the files directory before it is attached. See solution here:Android: FileProvider "Failed to find configured root"

Meteor: The application is not spiderable

My application is not spiderable both on local and production.
When I go to http://localhost:3000/?_escaped_fragment_=, I can see the following error appears (phantom is killed after 15 seconds):
spiderable: phantomjs failed: { [Error: Command failed: ] killed: true, code: null, signal: 'SIGTERM' }
It seems that many other people got this problem:
https://github.com/gadicc/meteor-phantomjs/issues/1
https://groups.google.com/forum/#!msg/meteor-talk/Lnm9HFs4MgM/YKDMR80fVecJ
https://groups.google.com/forum/#!topic/meteor-talk/7ZbidddRGo4
The thing is I am not using observatory or select2 and all my publications return a cursor. According to me, the problem comes from the minification. I just read in this thread that someone succeed to display "SyntaxError: Parse error". How can I know more about what is going wrong with Phantom and which file is causing the problem?
This happens when spiderable is waiting for subscriptions that fail to return any data and end up timing out, as mentioned in some of the threads you linked.
Make sure that all of your publish functions are either returning a cursor, a (possibly empty) list of cursors, or sending this.ready().
Meteor APM may be useful in determining which publications aren't returning.
If you want to know more about what is wrong with phatomjs, you might try this code (1):
// Put your URL below, no "?_escaped_fragment_=" necessary
var url = "http://your-url.com/";
var page = require('webpage').create();
page.open(url);
setInterval(function() {
var ready = page.evaluate(function () {
if (typeof Meteor !== 'undefined'
&& typeof(Meteor.status) !== 'undefined'
&& Meteor.status().connected) {
Deps.flush();
return DDP._allSubscriptionsReady();
}
return false;
});
if (ready) {
var out = page.content;
out = out.replace(/<script[^>]+>(.|\n|\r)*?<\/script\s*>/ig, '');
out = out.replace('<meta name=\"fragment\" content=\"!\">', '');
console.log(out);
phantom.exit();
}
}, 100);
For use in local, install phantomjs. Then outside your app, create a file phantomtest.js with the code above. And run phantomjs phantomtest.js
Another thing that maybe you can try is to use UglifyJS to catch some errors in the minified JS file as Payner35 did.
My problem was coming from SSL. You can have a complete overview of what I did here.
Edit the spiderable source and add --ignore-ssl-errors=yes to the phantomjs command line, it will work.

System.Web.HttpException: Unable to validate data - after publishing site

I have written the following code for login:
Session["IsLogin"] = false;
System.Configuration.Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
if (txtPassword.Text.Trim() == string.Empty)
{
// Display Error
}
else
{
string Pwd = config.AppSettings.Settings["PWD"].Value.ToString();
FormsAuthenticationTicket formAuthTk = FormsAuthentication.Decrypt(Pwd);
string strDcryptedPwd = formAuthTk.Name.Trim().ToString();
if (txtPassword.Text.Trim() == strDcryptedPwd)
{
Session["IsLogin"] = true;
Response.Redirect("AnyPage.aspx");
}
else
{
// Error, Wrong password
}
}
Which is running fine while running through Visual studio. But when I published it it is showing the below error:
System.Web.HttpException: Unable to validate data
NOTE:
I publish the application on the
same server on which I am developing
the site.
I have tried EnableViewStateMAC =
false on page level. [Login Page]
What is the reson of this error? Why it is only appears when I have published the site?
I have changed the way to encrypt the string and the problem disapperars. I have no idea about the reason of the error, but I resolved it like this.
Hope it will help to others, who are facing the same issue.
you do not need to declare the config in the way you did, just use Configuration.AppSettings["PWD"].ToString()...
see here:
How to: Read Application Settings from the Web.config File

Resources