Script to create new Folder in Alfresco repository - alfresco

I want to create a script who allow me to create a new folder in Alfresco repository, but i haven't any idea to how achieve this.
Is there anyone who can tell me how to manage this.
Sorry for not posting any code, because i'm very new to alfresco and i haven't idea how to manage this.

The best way to create a folder (or perform other CRUD functions) remotely, such as from a command line program, is to use CMIS. There are a number of CMIS client implementations depending on what language you'd like to use. These are managed at the Apache Chemistry project.
Here is an example that uses cmislib, a Python CMIS client, to create a folder:
from cmislib.model import CmisClient
from cmislib.browser.binding import BrowserBinding
client = CmisClient('http://localhost:8080/alfresco/api/-default-/cmis/versions/1.1/browser', 'admin', 'admin', binding=BrowserBinding())
repo = client.defaultRepository
folder = repo.getObjectByPath("/User Homes")
createdFolder = folder.createFolder("another test folder")
print "Done, created: %s" % createdFolder.id
Here is an example that uses OpenCMIS, a Java implementation, from Groovy:
#Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.7.1')
#Grab(group="org.apache.chemistry.opencmis", module="chemistry-opencmis-commons-api", version="0.13.0")
#Grab(group="org.apache.chemistry.opencmis", module="chemistry-opencmis-commons-impl", version="0.13.0")
#Grab(group="org.apache.chemistry.opencmis", module="chemistry-opencmis-client-api", version="0.13.0")
#Grab(group="org.apache.chemistry.opencmis", module="chemistry-opencmis-client-impl", version="0.13.0")
#Grab(group="org.apache.chemistry.opencmis", module="chemistry-opencmis-client-bindings", version="0.13.0")
import org.apache.chemistry.opencmis.commons.*;
import org.apache.chemistry.opencmis.commons.enums.*;
import org.apache.chemistry.opencmis.client.*;
import org.apache.chemistry.opencmis.client.api.*;
import org.apache.chemistry.opencmis.client.runtime.*;
import org.apache.chemistry.opencmis.commons.data.*;
import org.apache.chemistry.opencmis.commons.impl.dataobjects.*;
import org.apache.chemistry.opencmis.commons.exceptions.*;
import java.nio.file.Paths
import groovy.json.JsonOutput
import groovyx.net.http.RESTClient
import static groovyx.net.http.ContentType.JSON
import java.text.NumberFormat;
def ALF_SERVICE = '/alfresco/s'
def CMIS_SERVICE = '/alfresco/api/-default-/public/cmis/versions/1.1/browser'
final BindingType CMIS_BINDING = BindingType.BROWSER;
// Get options
def url = System.console().readLine('Alfresco server URL [http://localhost:8080]: ')
if (url == null || url == '') url = "http://localhost:8080"
def folderPath = System.console().readLine('Folder path [/User Homes]: ')
if (folderPath == null || folderPath == '') folderPath = "/User Homes"
def folderName = System.console().readLine('Folder name to create: ')
def userName = System.console().readLine('Your username: ')
def password = System.console().readPassword('Your password: ')
println 'WARNING: About to modify folders on ' + url + ' as ' + userName + '.'
def confirm = System.console().readLine('Are you sure (Y/N): ')
if (confirm.toLowerCase() != 'y' && confirm.toLowerCase() != 'yes') {
println "Quitting"
System.exit(0)
}
// Login to Alfresco
def client = new RESTClient(url)
def resp = client.get(path : ALF_SERVICE + '/api/login', query: ['u': userName, 'pw': password.toString(), 'format': 'json'])
assert resp.status == 200
def ticket = resp.data.data.ticket
println "Successfully logged in to Alfresco..."
// Leave the username as an empty string to auth with a ticket
Session session = createCMISSession(url + CMIS_SERVICE, CMIS_BINDING, "", ticket);
Folder folder = findFolder(session, folderPath)
if (folder == null) {
println "ERROR: Could not find: " + folderPath
System.exit(0)
}
println "Found: " + folder.name + " (" + folder.id + ")"
Map<String,String> newFolderProps = new HashMap<String, String>()
newFolderProps.put("cmis:objectTypeId", "cmis:folder");
newFolderProps.put("cmis:name", folderName);
Folder createdFolder = folder.createFolder(newFolderProps)
println "Done, created: " + createdFolder.id
Session createCMISSession(final String cmisEndpointUrl,
final BindingType cmisBinding,
final String cmisUser,
final String cmisPassword) {
SessionFactory sf = SessionFactoryImpl.newInstance();
Session result = null;
Map<String, String> parameters = new HashMap<String, String>();
parameters.put(SessionParameter.BINDING_TYPE, cmisBinding.value());
parameters.put(SessionParameter.BROWSER_URL, cmisEndpointUrl);
parameters.put(SessionParameter.USER, cmisUser);
parameters.put(SessionParameter.PASSWORD, cmisPassword);
// Note: grabbing the first repository may not work as expected on multi-tenant Alfresco (most notably Cloud)
result = sf.getRepositories(parameters).get(0).createSession();
return (result);
}
Folder findFolder(Session session, String folderPath) {
Folder result = null;
try {
CmisObject folder = session.getObjectByPath(folderPath);
if (folder != null &&
BaseTypeId.CMIS_FOLDER.equals(folder.getBaseTypeId())) {
result = (Folder) folder;
}
} catch (CmisObjectNotFoundException confe) {
// Swallow and move on - we return null in this case
println "ERROR: getObjectByPath threw a CmisObjectNotFoundException"
}
return (result);
}
In the Groovy example, I am logging in and getting a ticket so that I can make both CMIS and non-CMIS calls, although I am not showing any non-CMIS calls in this example.

var nodeNew = parentNode.createFolder("Name of folder");
Above code will create folder using alfresco javascript.parentNode is an object of Node.
Below link have some more details on it.
https://community.alfresco.com/thread/166358-webscript-to-create-folder-space

Related

I am not able to add form entries to my database

Problem
I am trying to push username and password entries to my database using following code(named as application.py inside my project)
Code
from flask import Flask, render_template, request, redirect
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
application = Flask(__name__)
application.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///mydtb.db'
db = SQLAlchemy(application)
class Mydtb(db.Model):
id = db.Column(db.Integer, primary_key=True, autoincrement = True)
user = db.Column(db.String(50), nullable = False)
password = db.Column(db.String(20), nullable = False)
created = db.Column(db.DateTime, default = datetime.utcnow)
def __init__(self, user, password):
user = self.user
password = self.password
#application.route('/', methods=['POST', 'GET'])
def home():
title = 'Registration page'
if request.method == 'POST':
record = Mydtb(request.form['usrname'], request.form['pwd'])
db.session.add(record)
db.session.commit()
return redirect('/')
else:
mydtb = Mydtb.query.order_by(Mydtb.created)
return render_template('index.html', title=title, mydtb = mydtb)
if __name__ == '__main__':
application.run(debug = True)
I've already generated .db file, html form is also working fine but it seems application.py code is unable to push those form entries to database.
You can see the error that I am getting from debug section , I want to fix it without using extra libraries.

Haxe - SQLLite Crashing in Android target

i want to use use Sqllite datbase in my Android Game i am developing with Haxe - OpenFl but the app keep crashing when i am trying to query the database. If this is not possible or have any other ways to deal with data in Android kindly let me know as the json and shared objects are not going to work with in my scenario.
i posted this question in the OpenFl community too - but i think it is more related to Haxe then OpenFL.
OpenFl Community Post
What i am doing :
Making a database using DB Browser and saving it to the assets/data/db/data.db
then when app starts i am making a copy of it to the lime.system.System.applicationStorageDirectory
it creates the file in the applicationStorageDirectory
Then i try to connect to the newly created db file and it just connects but right after connecting to it, try to get the name of the db it is connected to
trace("Connected to database " +_conn.dbName ); and it is not showing anything in the trace except the text connected to database.
Ignoring the name i tried to query the Database and it just closes my app without any error or anything i get to know what goes wrong.
My Project.xml
<android target-sdk-version="26" install-location="preferExternal" if="android" />
<android permission="android.permission.WRITE_EXTERNAL_STORAGE"/>
<android permission="android.permission.WRITE_INTERNAL_STORAGE"/>
<haxelib name="openfl" />
<haxelib name="hxcpp" />
<assets path="assets/data/db" rename="db" />
DBClass
package;
import haxe.io.Bytes;
import lime.Assets;
import openfl.system.System;
import sys.FileSystem;
import sys.db.Connection;
import sys.db.Sqlite;
import sys.io.File;
#if android
// Make SQLite work on android by statically compiling the library
import hxcpp.StaticSqlite;
#end
/**
* ...
* #author Sim
*/
class DBManager
{
private var CLONE:String = "db/asset_database.db";
private var NEW:String = "new_db.db";
private var _conn:Connection = null;
public function new()
{
}
public function openDatabase():Void
{
trace("CREATING FILE");
trace("targetPath: " +lime.system.System.applicationStorageDirectory);
//trace("targetPath: " +lime.system.System.applicationDirectory); //Crashing the app
trace("targetPath: " +lime.system.System.documentsDirectory);
trace("targetPath: " +lime.system.System.desktopDirectory);
var targetPath: String = lime.system.System.applicationStorageDirectory+ NEW;
trace("targetPath " + targetPath);
trace("FileSystem.exists(targetPath) " + FileSystem.exists(targetPath));
//Debugging
/*var bytes:Bytes = Assets.getBytes(CLONE);
trace("bytes are here "+bytes);
var content:String = bytes.toString();
trace("content "+content);
File.saveContent(targetPath, content);
trace("Saved");*/
//uncomment when done with errors
/*if (FileSystem.exists(targetPath) == false)
{
var bytes:Bytes = Assets.getBytes(CLONE);
var content:String = bytes.toString();
File.saveContent(targetPath, content);
}*/
var bytes:Bytes = Assets.getBytes(CLONE);
var content:String = bytes.toString();
File.saveContent(targetPath, content);
trace("Saved");
try
{
_conn = Sqlite.open(targetPath+NEW);
}
catch (e:Dynamic)
{
trace("Connection failed with error: "+e);
}
if (_conn != null)
{
trace("Connected to database " +_conn.dbName );
//not getting any database name trying to query
// and KaBoom app gone :D XD
var result = _conn.request("SELECT * FROM TEST");
trace("Query Result "+result.results());
//if i comment then it will go and close the connection too
//without breaking anything O_O
_conn.close();
}
}
}
I took a nap and got the fix in my dreams: :D
The problem is here
_conn = Sqlite.open(targetPath+NEW);
Fix:
_conn = Sqlite.open(targetPath);
Because database name is already in the path :P
var targetPath: String = lime.system.System.applicationStorageDirectory+ NEW;
That’s why always sleep for 8 hours otherwise will end up like me

Alfresco webscript in edit-metadata

I've modified the behavior of edit-metadata to include some of custom aspect I've created, and everything works great. But when I was searching for the file, I saw that edit-metadata-mgr.get.js call the webscript /slingshot/edit-metadata/node/{store_type}/{store_id}/{id}
now I'm wondering where can I find the code of this webscript? I've search around but can't find it anywhere... Did I miss something? Does anyone know where those files are located?
This is Code of webscript.it is reside in jar file alfresco-share-services-5.1
function main()
{
if (url.templateArgs.store_type === null)
{
status.setCode(status.STATUS_BAD_REQUEST, "NodeRef missing");
return;
}
// nodeRef input
var storeType = url.templateArgs.store_type,
storeId = url.templateArgs.store_id,
id = url.templateArgs.id,
nodeRef = storeType + "://" + storeId + "/" + id,
node = search.findNode(nodeRef);
if (node === null)
{
status.setCode(status.STATUS_NOT_FOUND, "Not a valid nodeRef: '" + nodeRef + "'");
return null;
}
model.node = node;
if (node.parent !== null && node.parent.hasPermission("ReadProperties"))
{
model.parent = node.parent;
}
}
main();
This is share side webscript.As Sanjay mentioned its inside the alfresco-share-services-5.1.It will be available on github.Below is the link of mentioned webscript.
https://github.com/Alfresco/share/tree/master/share-services/src/main/resources/alfresco/templates/webscripts/org/alfresco/slingshot/edit-metadata

Is there a way to automatically generate the gradle dependencies declaration in build.gradle?

This is in the context of converting an existing java project into a gradle project.
Is there a tool or webservice that would help generate the dependencies declaration in the build.gradle by pointing to a directory that contain all the dependent jars ?
In general there no such tool but if all the jars all structured (I mean paths: com/google/guava/guava and so on) it should be easy to write such script on your own.
Mind that it can also be done by importing the whole folder in the following way:
repositories {
flatDir {
dirs 'lib'
}
}
or
dependencies {
runtime fileTree(dir: 'libs', include: '*.jar')
}
In my comments to #Opal 's answer, I said that I was working on a quick and dirty groovy script to achieve this. I forgot to attach the script after that. Apologies for the same.
Here's my quick and dirty script. Does solve the purpose partially.
Hoping that someone can improve on it.
#! /usr/bin/env groovy
#Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.5.2' )
import static groovyx.net.http.ContentType.JSON
import groovyx.net.http.RESTClient
import groovy.json.JsonSlurper
import groovy.util.slurpersupport.GPathResult
import static groovyx.net.http.ContentType.URLENC
//def artifactid = "activation"
//def version = "1.1"
//def packaging = "jar"
//
//def mavenCentralRepository = new RESTClient( "http://search.maven.org/solrsearch/select?q=a:%22${artifactid}%22%20AND%20v:%22${version}%22%20AND%20p:%22${packaging}%22&rows=20&wt=json".toString() )
////basecamp.auth.basic userName, password
//
//def response = mavenCentralRepository.get([:])
//println response.data.response.docs
//
//def slurper = new JsonSlurper()
//def parsedJson = slurper.parseText(response.data.toString());
//
//println parsedJson.response.docs.id
def inputFile = new File("input.txt");
def fileList = []
fileList = inputFile.readLines().collect {it.toString().substring(it.toString().lastIndexOf('/') + 1)}
def artifactIDvsVersionMap = [:]
fileList.collectEntries(artifactIDvsVersionMap) {
def versionIndex = it.substring(0,it.indexOf('.')).toString().lastIndexOf('-')
[it.substring(0,versionIndex),it.substring(versionIndex+1).minus(".jar")]
}
println artifactIDvsVersionMap
new File("output.txt").delete();
def output = new File("output.txt")
def fileWriter = new FileWriter(output, true)
def parsedGradleParameters = null
try {
parsedGradleParameters = artifactIDvsVersionMap.collect {
def artifactid = it.key
def version = it.value
def packaging = "jar"
def mavenCentralRepository = new RESTClient( "http://search.maven.org/solrsearch/select?q=a:%22${artifactid}%22%20AND%20v:%22${version}%22%20AND%20p:%22${packaging}%22&rows=20&wt=json".toString() )
def response = mavenCentralRepository.get([:])
println response.data.response.docs.id
def slurper = new JsonSlurper()
def parsedJson = slurper.parseText(response.data.toString());
def dependency = parsedJson.response.docs.id
fileWriter.write("compile '${dependency}'")
fileWriter.write('\n')
sleep (new Random().nextInt(20));
return parsedJson.response.docs.id
}
} finally {
fileWriter.close()
}
println parsedGradleParameters
Groovy pros - Pardon if the code is not not clean. :)

Alfresco web scripts: How do I stop processing or return early?

I have a web script in Alfresco that works when I pass in the correct arguments in my HTTP request. I have added validation similar to this snippet (source).
How can I tell Alfresco to stop processing the webscript if I find that my validation steps have failed? (If possible, I would like to do this without an else block.)
// extract folder listing arguments from URI
var verbose = (args.verbose == "true" ? true : false);
var folderpath = url.templateArgs.folderpath;
// search for folder within Alfresco content repository
var folder = roothome.childByNamePath(folderpath);
// validate that folder has been found
if (folder == undefined || !folder.isContainer) {
status.code = 404;
status.message = "Folder " + folderpath + " not found.";
status.redirect = true;
// ********* HOW DO I TELL ALFRESCO TO STOP PROCESSING HERE? ************
}
// perform some business logic with the parameters that passed validation......
// ********* I DO NOT WANT TO COME HERE IF VALIDATION FAILS ************
// construct model for response template to render
model.verbose = verbose;
model.folder = folder;
The trick here is to wrap your code in a function (usually called main by convention). Just call that function and return from that function if you want to stop processing. Like so:
function main() {
// extract folder listing arguments from URI
var verbose = (args.verbose == "true" ? true : false);
var folderpath = url.templateArgs.folderpath;
// search for folder within Alfresco content repository
var folder = roothome.childByNamePath(folderpath);
// validate that folder has been found
if (folder == undefined || !folder.isContainer) {
status.code = 404;
status.message = "Folder " + folderpath + " not found.";
status.redirect = true;
return;
}
// Do stuff with the folder
}
main();

Resources