Custom configs in Alfresco

While creating import services I want some configuration mechanism for (not just) BatchProcessor. I like Alfresco’s *-config-custom.xml files (aka Spring framework XMLConfigService), so I did simple custom config service. Anyone, who customized Alfresco, knows format of this file (web-client-config-custom.xml). I put that structure to new file – mis-config-custom.xml: [code lang=“xml“] <alfresco-config> <config evaluator="string-compare" condition="imports"> <processor> … Pokračovat ve čtení „Custom configs in Alfresco“

While creating import services I want some configuration mechanism for (not just) BatchProcessor. I like Alfresco’s *-config-custom.xml files (aka Spring framework XMLConfigService), so I did simple custom config service.

Anyone, who customized Alfresco, knows format of this file (web-client-config-custom.xml). I put that structure to new file – mis-config-custom.xml:

[code lang=“xml“]
<alfresco-config>
<config evaluator="string-compare" condition="imports">
<processor>
<worker-threads-num>3</worker-threads-num>
<batch-size-num>6</batch-size-num>
<split-transactions>false</split-transactions>
<logging-interval>1000</logging-interval>
</processor>
<token>
<time-refresh>1000</time-refresh>
<time-expiration>20000</time-expiration>
</token>
</config>
</alfresco-config>
[/code]

Please note those constants are just for ilustration purposes now, more on them in scripting series. My MisConfigService extends org.springframework.extensions.config.xml.XMLConfigService, but uses nothing from that class (except init method in bootstrap), I just added some statics inside to keep things together:

[code lang=“java“]
public class MisConfigService extends XMLConfigService {
public MisConfigService(ConfigSource configSource) {
super(configSource);
}

public static String getChildValue(Config config, String elementId, String childName, String defaultValue) {
ConfigElement myConfig = config.getConfigElement(elementId);
String result = myConfig.getChildValue(childName);

return (result==null ? defaultValue : result);
}

public static Integer getChildValue(Config config, String elementId, String childName, Integer defaultValue) {
Integer result = defaultValue;
try {
String number = getChildValue(config, elementId, childName, defaultValue.toString());
result = Integer.parseInt(number);
} finally { /* O:-) */ }
return result;
}

. . .
}
[/code]

To instantiate this service just add bean definition with UrlConfigSource(-s), which defines path to custom xml configuration:

[code lang=“xml“]
<bean id="misConfigService" class="cz.mis.service.MisConfigService" init-method="init">
<constructor-arg>
<bean class="org.springframework.extensions.config.source.UrlConfigSource">
<constructor-arg>
<list>
<value>classpath:alfresco/extension/mis-config-custom.xml</value>
</list>
</constructor-arg>
</bean>
</constructor-arg>
</bean>
[/code]

Now it’s possible to access those properties in code like this:

[code lang=“java“]
org.springframework.extensions.config.Config config = configService.getConfig(imports");
Boolean splitTransactions = MisConfigService.getChildValue(config, "processor", "split-transactions", false);
[/code]

It’s also possible to access attributes of nodes in that config:

[code lang=“java“]
ConfigElement myConfig = config.getConfigElement("config-element");
for(ConfigElement child : myConfig.getChildren()) {
// child.getAttributes()
// child.getName()
// child.getValue()
}
[/code]

That’s all! And now for something completely different! I also spent some time trying to get properties files working and putting those properties into Spring configurations. There’s nice solved thread in Alfresco forums. Prefix helps:

[code lang=“xml“]
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath*:alfresco/extension/mis-settings.properties</value>
</list>
</property>
<property name="ignoreResourceNotFound" value="true" />
<property name="placeholderPrefix" value="${mis:" />
<property name="placeholderSuffix" value="}" />
</bean>

<!– and I can use stuff from properties file with prefix –>
<bean class="foo.bar.Example">
<property name="fooAttribute">
<value>${mis:some.sample.property}</value>
</property>
</bean>
[/code]

More on invoking scripts in Alfresco

In my last blogpost on this topic I wrote about invoking rhino scripts programatically from Alfresco and about passing its model into freemarker templates. After that I realized that alfresco templateService is unable to render more complex models (nested classes and collections) if called this way (please note on Alfresco webscripts invoked standard way this … Pokračovat ve čtení „More on invoking scripts in Alfresco“

In my last blogpost on this topic I wrote about invoking rhino scripts programatically from Alfresco and about passing its model into freemarker templates. After that I realized that alfresco templateService is unable to render more complex models (nested classes and collections) if called this way (please note on Alfresco webscripts invoked standard way this works correctly!). I think the problem is – no wrapper is used while passing model. I spent lot of time trying many things, read a lot of posts and topics on that, played with built-ins, trying to find that part in Alfresco source, but still no result, just exceptions. But solution is VERY SIMPLE – to write own templateService :-). Well, maybe this post is more about Freemarker and Rhino than Alfresco, sorry about that!

So, what I want to achieve? Suppose some simple script like this one:

[code lang=“javascript“]
model.bar="foo";
model.foo = "bar";
model.obj = {q:1, w:3, e:9};

model.arr = new Array();
model.arr[0] = {a:1, b:8, c:9, d:{d:66}};
model.arr[1] = {a:2, b:7, c:10, d:{d:66}};
model.arr[2] = {a:3, b:6, c:11, d:{d:66}};
model.arr[3] = {a:4, b:5, c:12, d:{d:66}};
[/code]

and a Freemarker template simple as that:

[code lang=“plain“]
q attribute: ${obj.q}

<#list arr?keys as value>
– ${value} = ${arr[value].a} = ${arr[value].b} = ${arr[value].c}
<#assign obj_d = arr[value].d>
+ d: ${obj_d.d}
</#list>
[/code]

Now after calling templateService.processTemplate( . . . ) the output is Exception this and Exception that… That happens, because Rhino creates NativeObjects for those objects and after passing those objects to Freemarker (through Java – without any ObjectWrapper), which doesn’t know how to handle them. The same situation happens when passing a collection with generics like <String, Object> into model – those Objects are standard Java objects and in Freemarker acts like them, they really don’t have attributes like q, a, b, etc. :-). Similar situation can happen with collections – they needs to be wrapped too. But stop with theory, back to practise. For those interested in wrapping and so, follow Freemarker documentation on wrappers.

Before wrapping – when I printed out keys of model, there were’nt my attributes defined in Javascript. What I found inside is on following listing, note my attributes are also there – bar, foo, arr, obj:

[code lang=“plain“]
<#assign keys = model?keys>
<#list keys as key>
+ ${key}
</#list>

(** output **)
+ getClass
+ clone
+ put
+ remove
+ get
+ equals
+ entrySet
+ class
+ hashCode
+ foo
+ keySet
+ size
+ clear
+ isEmpty
+ containsKey
+ values
+ arr
+ containsValue
+ empty
+ toString
+ putAll
+ bar
+ obj
[/code]

Those properties belongs to hashMap and is possible to get rid of them using simpleMapWrapper, this technique is described well in Rizwan Ahmed post.

What about my templateService implementation? First I tried to use JSONtoFmModel and convert javascript objects to strings, but that was no way forward. That was before I discovered wrappers :-). There is RhinoWrapper class in Freemarker and it solves all my problems! It can be used as simple as this:

[code lang=“java“]
Configuration cfg = new Configuration();
RhinoWrapper rhinoWrapper = new RhinoWrapper();

rhinoWrapper.setSimpleMapWrapper(true);
cfg.setObjectWrapper(rhinoWrapper);
[/code]

Previous listing creates new Freemarker configuration instance and rhino wrapper instance and binds them together. With that configuration it’s possible to create template instance, which takes reader with template content, let’s read it from repository:

[code lang=“java“]
NodeRef nodeRef = new NodeRef("workspace://SpacesStore/56ba2237-f776-494a-939b-d259b68c021a");

ContentReader contentReader = contentService.getReader(nodeRef, ContentModel.PROP_CONTENT);
InputStream inputStream = contentReader.getContentInputStream();

Template template = new Template("my_template", new InputStreamReader(inputStream), cfg);
[/code]

That’s all we need to render. Rendering takes one more parameter – model map, which is HashMap defined in my previous blogpost. To keep it simple (and post a little shorter) I’m writing output to sysout:

[code lang=“java“]
OutputStreamWriter streamWriter = new OutputStreamWriter(java.lang.System.out);
template.process(rootMap, streamWriter);
[/code]

Those few lines and everything works fine now! But I got some silver hairs with trying to solve that, now I can feel like a boss, so I achieved new „Alfresco guru badge“ :-). Also I’m thinking about some public GIT repository with my Alfresco inventions, what you think about it?

Like an Alfresco guru!
Like an Alfresco guru!

PostScriptum: Can anyone explain me why Alfresco uses Rhino version 1.6R7 which is from year 2007? :-O

Invoking scripts in Alfresco programatically

I’m working on universal CRON runner, which runs scripts saved somewhere in repository (more on this next time). Running webscripts isn’t so easy, as I thought, there is no scriptService.runScriptWithThisDescription(path) method, so I did some research and got some results, which I’d like to share. It’s possible to run java backed actions from js-webscripts. Everything you … Pokračovat ve čtení „Invoking scripts in Alfresco programatically“

I’m working on universal CRON runner, which runs scripts saved somewhere in repository (more on this next time). Running webscripts isn’t so easy, as I thought, there is no scriptService.runScriptWithThisDescription(path) method, so I did some research and got some results, which I’d like to share.

It’s possible to run java backed actions from js-webscripts. Everything you need is just a bean extending ActionExecuterAbstractBase with definition parent=“action-executer“ and it’s possible to access that bean from webscript like actions.create(„that_bean_id“). But not in reverse, at least not so simple.

First think I found was post on forum and advice to look at unit tests of webscripts, but everything I found were invocations through http. So I went deeper and figured out that Alfresco uses Rhino JavaScript implementation for scripts. At Rhino pages are good examples, so I had first working script soon. At following codelist I firstly load content of node (script body) from repository and then invocate script itself.

[code lang=“java“]
NodeRef nodeRef = new NodeRef("workspace://SpacesStore/4a96aaaa-bb80-eeee-aaaa-800a43fcddb8");
ContentReader contentReader = contentService.getReader(nodeRef, ContentModel.PROP_CONTENT);
InputStreamReader isr = new InputStreamReader(contentReader.getContentInputStream());
BufferedReader reader = new BufferedReader(isr);

Context cx = Context.enter();
try {
Scriptable scope = cx.initStandardObjects();
Object result = cx.evaluateReader(scope, reader, "scriptInvocation", 1, null);
} finally {
Context.exit();
}
[/code]

But I wanted something more – some model in and out and something simplier. So I found ScriptService. Now all those long lines can be ommited, because there is executeScript method!

[code lang=“java“]
Map<String, Object> model = new HashMap<String, Object>();
model.put("foo", "bar");

Object result = scriptService.executeScript(scriptRef, model);
[/code]

Template rendering (I’m using FreeMarker’s ftls) is done the same way, but through TemplateService and processTemplate(nodeRef, model) method, which accepts the same model (altered by script running).

The most beautiful thing is ability of script (and also template) to call java methods, which classes are „injected“ through model, let’s see an example.

[code lang=“java“]
Map<String, Object> model = new HashMap<String, Object>();

model.put("something", new Something());
model.put("bar", "foo");

Object result = scriptService.executeScript(scriptRef, model);
String templateResult = templateService.processTemplate("workspace://SpacesStore/noderef", model);

. . .

public class Something {
public String text = "aaa";

public String getText() {
return "bbb";
}
}
[/code]

Now it’s possible to use script / template:

[code lang=“javascript“]
(** script **)
bar = something.text;

(** template **)
${something.text} ?=? ${bar}
[/code]

What is output? Is in templateResult „aaa ?=? aaa“? Nope! Script accesses class attributes directly, on the other side template accesses methods. So output is „bbb ?=? aaa“!!!

One more important thing: this JavaScript implementation is just a stub, so every alfresco service needs to be „injected“ through model, so for example it’s impossible to run stuff like this without modifications:

[code lang=“javascript“]
var connector = remote.connect("http");
var result = connector.call("http://www.google.com/");
[/code]

Remote object has to be injected (this script is from Share/Surf), more on this in this blogpost. You have to add ScriptRemote to model and create spring-webscripts-config-custom.xml with endpoints defined, see that post. Also another services needs to be injected – to get access to repository, search service… good starting point is Alfresco Wiki.

Edit: Native Java API Access described in wiki is wrong, IT IS POSSIBLE to access maps in JavaScript like this:

[code lang=“javascript“]
var value = javaMap.key;
[/code]

Pozadí ubytovníčku

Všichni chtějí přijít s nápadem, který změní svět, který vydělá miliony a já nevím, co ještě. Většina těchto nápadů končí rozčarováním, protože nejsou realizovatelé, nebo nejsou realizovatelné v podobě, jak si je dotyčný budoucí milionář představuje. To je v pořádku. Protože jsem už pár nápadů zkusil realizovat a neuspěl, zkusím v tomto miniseriálu představit kroky, … Pokračovat ve čtení „Pozadí ubytovníčku“

Všichni chtějí přijít s nápadem, který změní svět, který vydělá miliony a já nevím, co ještě. Většina těchto nápadů končí rozčarováním, protože nejsou realizovatelé, nebo nejsou realizovatelné v podobě, jak si je dotyčný budoucí milionář představuje. To je v pořádku. Protože jsem už pár nápadů zkusil realizovat a neuspěl, zkusím v tomto miniseriálu představit kroky, které jsem se naučil a které doufám, že v případě Ubytovníčku povedou k dokončení a úspěšné realizaci tohoto nápadu.

Když jsem přišel s úplně prvním nápadem, okamžitě jsem koupil doménu a pak teprve začal přemýšlet, jak to vlastně udělat, co tam bude… Postupem času (dlouhého času) jsem pivotoval a pivotoval a vždycky se dostal k začátku realizace, ale tam jsem skončil. Proč? Nápad nebyl dopracovaný, nevěděl jsem, na koho budu cílit, co z toho bude dotyčný mít, co z toho budu mít já… Teď už vím víc: pokud dostanu nápad, chvíli nad ním přemýšlím a pak se ho snažím zapomenout. Pokud se další den ráno probudím a ten nápad tam je pořád a hlodá, pokračuju k další fázi – a tou je třídění myšlenek spojených s tímto nápadem.

Co mám: chuť něco dělat
Co by mělo být výstupem fáze: nápady = množství trojic problém, řešení, zákazník
Co bude výstupem fáze: nápady, o kterých si myslím, že jsou dobré
Co budu dělat: brainstormovat
Co pro to použiju: mindmapper

Pro prvotní utřídění myšlenek používám myšlenkové mapy. Konkrétně jsem si zvyknul na nástroj mindmeister, který funguje jako online aplikace i jako aplikace pro Android, takže můžu přidávat myšlenky kdykoliv a kdekoliv. Používám dva postupy: „blití všeho“ a „brainstormovací mód“.

Mindmeister @ Android
Mindmeister @ Android

Blití všeho používám především na začátku a je to takové prvotní nakopnutí, kdy ze sebe hrnu naprosto všechno, co mě napadá, a sázím to bez ladu a skladu (víceméně) do mapy, je to takové základní vytvoření budoucích uzlů celé mapy. K této fázi se už později moc vracet nedá, protože by tento přístup narušil započatou strukturu, takže je vhodné zauvažovat o vytvoření nové mapy a potom je nějak spojit. Ale popravdě – do této fáze se v udoucnu už nevracím, protože ji dobře pokryje fáze následující.

A to je fáze brainstormovací. Začnu v kořenu celého stromu a postupně procházím k listům, kdykoliv mě kdekoliv cokoliv napadne, okamžitě to přidám. Nedělám smyčky, postupuju systematicky dál a dál. Dost často skončím na listu a najednou se roztrhne pytel s nápadama a tak se chrlí.

Potom nastupuje třídicí mód, který je vhodné provádět způsobem „ráno moudřejší večera“, ale mnohdy se to ráno zvrhne v další chrlení :-). Jde to to, že se musí vyházet spousta nesmyslů (tohle je ovšem první fáze, větší odstraňování bude následovat příště), kterých je tam zákonitě velké množství, odstranit duplicity a trochu přeskládat strukturu. Ideální je, když je na projekt více lidí a tuto část udělá někdo jiný, nebo je při tomto čištění a uspořádávání přítomen. Člověk, který tyto nápady vychrlil může být slepý k některým nelogičnostem a nesmyslům a kontrola dalším člověkem tato místa odhalí a odstraní, případně poupraví. Pravdou ale je, že než hledat kompromis, lepší je danou věc úplně odstranit. Pokud bude potřeba, vyplyne tento fakt v budoucnu a může se zpětně zapracovat – méně je více.

Tato prvotní část se dá shrnout do celku „nápad“. Jde o to si uvědomit, že nápad není nápad sám, ale jeho rozpracování a zaznamenání do nějaké takovéto podoby, aby si člověk (a to především někdo druhý) mohl prohlédnout všechny souvislosti, náležitosti… Ještě pořád není vhodný čas na nákup domény, následuje další část – část ověření myšlenek a jejich ořezání, ale o tom zase až příště.

(Repost z blogu Ubytovníčku.)

Deleting workflows in Alfresco

I tried to find out how to delete completed workflows in Alfresco, but I find no way to do that. I’m talking about HUGE number of completed workflows – a thousands. There are many questions on that topic, but no solution. I tried to play with Workflow console, also tried Alfresco Workflow Purge webscript by … Pokračovat ve čtení „Deleting workflows in Alfresco“

I tried to find out how to delete completed workflows in Alfresco, but I find no way to do that. I’m talking about HUGE number of completed workflows – a thousands. There are many questions on that topic, but no solution. I tried to play with Workflow console, also tried Alfresco Workflow Purge webscript by Rothbury software and also tried to write own deleters based on Workflow service (more on this next time), but no success at all. In better cases process dies with „out of memory“, or completely locks Alfresco in worst cases. So I choose hardcore solution – to delete database tables. And it works :-).

I’m talking about 10 tables, which are bind with foreign keys. So to remove ALL workflows follow those steps (note I’m not responsible for data loses, you’re on your own, so backup carefully!):

  1. Stop Alfresco and stop mysql
  2. Do backups – at least alf_data and /var/lib/mysql
  3. Start mysql and open mysql client
  4. Turn off foreign key checking: SET FOREIGN_KEY_CHECKS=0;
  5. Truncate following tables:
    • JBPM_TOKEN
    • JBPM_TOKENVARIABLEMAP
    • JBPM_TASKINSTANCE
    • JBPM_SWIMLANEINSTANCE
    • JBPM_PROCESSINSTANCE
    • JBPM_MODULEINSTANCE
    • JBPM_LOG
    • JBPM_BYTEBLOCK
    • JBPM_BYTEARRAY
    • JBPM_VARIABLEINSTANCE
  6. Maybe it’s good idea to set index.recovery.mode to FULL
  7. Start Alfresco and hope everything is well
  8. Turn off reindexing set in step 6

Simple yet effective. Please, let me know, if it works on your Alfresco too. I tested it od Community versions 3.4.e, 3.4.d and 4.1.0 (built from svn).

Creating rules programaticaly

Nowadays I’ve been working on policies and triggering a behavior  based on user action, so I wanted to write about it, but I found more interesting stuff I did with it than triggering itself (which is by the way well described by Jeff Potts). I wanted a routine, which runs on every node created and … Pokračovat ve čtení „Creating rules programaticaly“

Nowadays I’ve been working on policies and triggering a behavior  based on user action, so I wanted to write about it, but I found more interesting stuff I did with it than triggering itself (which is by the way well described by Jeff Potts). I wanted a routine, which runs on every node created and adds a rule, if that node is a folder.

At first I did some research on rules. How are rules bound to nodes? We’re working on repository, so it should be a node. When you open a node browser and look on node with rule bound, you’ll see ‚ruleFolder‘ child of that node of ruleFolder type. Children of this node are rules itself – one child, one rule. Inside each are actions defined with conditions and actions with their parameters, like on following structure:

RuleFolder structure
RuleFolder structure

Conditions may be structured too – if condition is not „no-condition“ – there may be much complicated structure: either condition itself (actioncondition node type) with parameters as children, or composite-condition (compositeactioncondition node type) with conditions nested inside. Each condition has „invert“ boolean variable, which inverts condition meaning. Properties of simpliest condition (no-condition) are on following image:

Condition properties
Condition properties

Parameters are another types of node – actionparameter. Each has two important properties: parameterName and parameterValue and those values depends on action (or condition) on which is this parameter bind to. Example of parameter for copy-to-webproject action is on following image:

Parameter properties
Parameter properties

And of course third node type – action. With or without parameters. In both cases with properties like definitionName, executeAsynchronously, etc. see following image:

Action properties
Action properties

Examples on how to set rule on node are in nodeRef cookbook. I worked with CopyToWebProject action, which can be with parameters defined like this:

[code lang=“java“]
Action myAction = actionService.createAction(CopyToWebProjectActionExecuter.NAME);
Map<String, Serializable> actionProps = myAction.getParameterValues();
actionProps.put(CopyToWebProjectActionExecuter.PARAM_DESTINATION_FOLDER, avmRef);
myAction.setParameterValues(actionProps);
[/code]

Note static variables with parameter names (prefix PARAM_). Executers are in org.alfresco.repo.action.executer package, or it’s possible to use own action executer (extending ActionExecuterAbstractBase).

Next step is to add a condition, in my case HasAspectEvaluator like this:

[code lang=“java“]
ActionCondition condition = actionService.createActionCondition(HasAspectEvaluator.NAME);
Map<String, Serializable> conditionProps = new HashMap<String, Serializable>();
conditionProps.put(HasAspectEvaluator.PARAM_ASPECT, ContentModel.ASPECT_WORKING_COPY);
condition.setParameterValues(conditionProps);
condition.setInvertCondition(true);
[/code]

Evaluators (package org.alfresco.repo.action.evaluator) also have parameter names defined with prefix PARAM_. Previous code creates condition testing aspect is NOT set on node (note setInvertCondition() method) – this condition is for testing copied content is not working copy.

Created condition and action should be placed in CompositeAction:

[code lang=“java“]
CompositeAction compositeAction = actionService.createCompositeAction();
compositeAction.addActionCondition(condition);
compositeAction.addAction(myAction);
[/code]

And the final step is to add this whole composition inside created rule and use ruleService to bind created rule to node – through its nodeRef:

[code lang=“java“]
rule.setAction(compositeAction);
ruleService.saveRule(sourceRef, rule);
[/code]

This is enough and it should work. What am I using it for? I need CopyToWebProject rule to foolow tree structure in DM, not just copy everything in subdirs to given folder. So I have my own implementation of OnCreateNodePolicy, which binds this rule to every created folder (under some conditions of course).

Controller for views in root

Yesterday while developping ukazbobra I realized, that I don’t know how to map controller for my index view in root of Spring MVC project. I searched and experimented a bit and here is a solution. Please note I’m using Spring Roo and annotation driven setup. First thing is to create controller, for example simple one … Pokračovat ve čtení „Controller for views in root“

Yesterday while developping ukazbobra I realized, that I don’t know how to map controller for my index view in root of Spring MVC project. I searched and experimented a bit and here is a solution. Please note I’m using Spring Roo and annotation driven setup.

First thing is to create controller, for example simple one like this:

[code language=“java“]@RequestMapping("/")
@Controller
public class RootController {

@RequestMapping(method = RequestMethod.GET)
public String index(Model model) {
model.addAttribute("foo", "bar");
return "index";
}
. . .
[/code]

Now you have to turn off thing named ParameterizableViewController, which staticaly selects a view for for rendering. So open up webmvc-config.xml and remove line with mapping for index view:

[code language=“xml“]<mvc:view-controller path="/" view-name="index"/>[/code]

That is all, nothing more, nothing less – you have working controller for your index page in root and also for other views.

Proc delam svou praci spatne?

Jak tak sjizdim videa z letosniho brnenskeho Barcampu, chtel jsem okomentovat zaznam prednasky Jana Martinka (@endlife) – Proc delam svou praci spatne. Na komentar to vsak bylo moc dlouhe, tak to davam sem a trochu rozsiruju. Zacina casti nazvanou spatny odhad, kde rika neco jako „prihlasovani je jedna trida v modelu, to bude jednoduchy.“ Zminuje, jak … Pokračovat ve čtení „Proc delam svou praci spatne?“

Jak tak sjizdim videa z letosniho brnenskeho Barcampu, chtel jsem okomentovat zaznam prednasky Jana Martinka (@endlife) – Proc delam svou praci spatne. Na komentar to vsak bylo moc dlouhe, tak to davam sem a trochu rozsiruju.

Zacina casti nazvanou spatny odhad, kde rika neco jako „prihlasovani je jedna trida v modelu, to bude jednoduchy.“ Zminuje, jak se postupne nabaluji dalsi veci – login se meni na email, pridava validaci, jednotne zobrazovani chyb, moznost resetu hesla… Pokud pominu fakt, ze nepouzil nekterou z moznosti existujicich validaci (napr. z frameworku dojo), napada me otazka, proc tohle resit v nejake pomerne ranne fazi projektu? Shodou okolnosti o tom nedavno psal Jirka Knesl (blogpost Minimal Viable Product), dokonale to popsali tez panove z 37signals v knize Restart, volne cituji: „protoze platby za profi program maji probihat az koncem mesice, odlozili jsme implementaci modulu na provadeni plateb a venovali se dulezitejsim vecem.“ S tim se neda nesouhlasit – proc implementovat funkci pro obnoveni hesla? Vzdyt to muze pockat, kolik bude navstevniku, kteri zapomenou heslo chvili po registraci? Dulezite je spustit ASAP – featury se mohou pridavat casem – obrovska vyhoda webovych projektu.

Cast nazvana Matrix – administracni rozhrani (Adminer) pripomina Matrix – cisla, data, znaky… Nepovolany vubec netusi, ktera bije. Nevyhoda KISS pristupu, ale samozrejme – pokud to adminovi vyhovuje, neni to zadny problem, taky mam radsi Midnight commandera, nez okynka :-). Kdo ne, at zkusi googlit alespon termin Scaffold. V Nette tohle opravdu neni?

Pokryti aplikace testy – uvedl naprosto ukazkovy priklad toho, proc je vhodne testy psat: zakomentoval cast kodu pri ladeni a zapomnel pote komentar odstranit. Jestli tohle cloveka neprinuti o psani testu aspon premyslet, tak uz nevim co :-). Testovat, testovat, testovat! Dekuji.

Napiste nam – plural, vs. singular? To je jedno, hlavne byt profesional a verit tomu, co delam! Pekne receno, pekne tipy (odpovidat na mejly, profesional zna sve limity, cenu…).

Pointa prednasky je – hledani partaka na projekt. Jan to zjistil po roce, co vyvijel sam. Jak to zjistil? Potreba jineho pohledu na vec – kdyz clovek dela projekt sam, jiny pohled na danou vec ziska az s odstupem casu, partak muze mit jiny pohled na vec hned. Pravdive, velmi prakticke. No a pak i dalsi veci…

Takze pokud nekdo kombinuje do CV veci jako nette, TDD ci Git, muze mu poslat mejl. No a ja mu timto preju hodne stesti v nalezeni partaka i v uspechu projektu ;-).

Pisou judiste jako prasata?

Zvykam si delat veci jednoduse. Byvaly doby, kdy jsem psal univerzalni kousky kodu, protoze „co kdyz nahodou nekdy“. Dlouze a zbytecne jsem ladil genericke tridy, metody pro ruzne jine obecne vstupy atd. V posledni dobe si vsimam, ze kdyz pisu rychle a jednoduse (neboli jako prase), vubec to nevadi – proste dany fragment napisu presne … Pokračovat ve čtení „Pisou judiste jako prasata?“

Zvykam si delat veci jednoduse. Byvaly doby, kdy jsem psal univerzalni kousky kodu, protoze „co kdyz nahodou nekdy“. Dlouze a zbytecne jsem ladil genericke tridy, metody pro ruzne jine obecne vstupy atd. V posledni dobe si vsimam, ze kdyz pisu rychle a jednoduse (neboli jako prase), vubec to nevadi – proste dany fragment napisu presne na telo dane situaci a kdyz ho nahodou budu potrebovat v budoucnu modifikovat, tak jej udelam univerzalnim az tehdy (v mnoha pripadech to nebude vubec potreba a ja diky tomu usetrim spoustu casu).
Uvedomil jsem si to pri cteni Restartu – stavam se Judistou. V knize je uveden krasny priklad: „Dejme tomu, ze chceme ziskat pohled na zem z ptaci perspektivy. Jednou z moznosti je vylezt na Mount Everest. Druha moznost je vyvezt se vytahem na vyhlidkovou terasu vyskove budovy.“ V knize se to sice tyka neceho trochu jineho a navic jsem to vytrhl z kontextu, ale presne takhle to citim a od ted se tim budu ridit.

Adding columns to custom browse.jsp

Last week I had to change browse.jsp view in alfresco and I need to add custom columns – attributes from my own data model. It’s pretty simple and I’ll explain that in this blogpost. I tried to do is as much simple as possible, so I removed all other view types but details and in … Pokračovat ve čtení „Adding columns to custom browse.jsp“

Last week I had to change browse.jsp view in alfresco and I need to add custom columns – attributes from my own data model. It’s pretty simple and I’ll explain that in this blogpost.

I tried to do is as much simple as possible, so I removed all other view types but details and in this view I added some boolean properties, which have own action handler – so are clickable and after click change their state. Result of this changes is on following screenshot.

How does it look like
How does it look like

You can see I added two boolean properties (in Czech – Ano = true, Ne = false) among others (Type). To do that I needed to override BrowseBean and create own NodePropertyResolver. Now from the begining:

  • I created custom document model,
  • wrote custom browse.jsp (just copied and edited original one),
  • overrode outcomes to new view,
  • overwrote BrowseBean and wrote custom NodePropertyResolver.

Creating custom document model is well described everywhere else (at least in alfresco wiki), so I’m not going to describe it here, also overriding views. Lets start with altering browse.jsp.

Items in list are created by RichList component, in which we are interested in just some attributes: viewMode and value. ViewMode is a String value (details, icons, list) with default view mode. When I tried to change ViewMode value to details, it doesn’t work correctly, so I had to override getBrowseViewMode() to return „details“.

[code language=“java“]
public class BrowseTeletextBean extends BrowseBean {
. . .
private NodePropertyResolver pageExpiredResolver = new BooleanNodePropertyResolver(TxtModel.txtExpired, getNodeService());
. . .
@Override
public String getBrowseViewMode(){
return „details“;
}

@Override
public List<Node> getContent() {
List<Node> list = super.getContent();

for(Node node : list){
node.addPropertyResolver(„pageExpired“, pageExpiredResolver);
. . .
}

return list;
}
. . .
[/code]

Value should return list of Node type, in which I wanted to add custom fields, so I needed to override it too. I put there some propertyResolvers – I did my own BooleanPropertyResolver:

[code language=“java“]
public class BooleanNodePropertyResolver implements NodePropertyResolver {
private NodeService nodeService;
private QName qName;

public BooleanNodePropertyResolver(QName qName, NodeService nodeService){
this.qName = qName;
this.nodeService = nodeService;
}

@Override
public Object get(Node node) {
boolean expired = NodeUtils.getBoolProperty(node.getNodeRef(), qName, nodeService);
return (expired ? „Ano“ : „Ne“);
}
}
[/code]

Now it’s possible to build a list in view like this:

[code language=“xml“]
<a:richList id=“contentRichList“ binding=“#{BrowseTeletextBean.contentRichList}“ viewMode=“#{BrowseTeletextBean.browseViewMode}“ pageSize=“#{BrowseTeletextBean.pageSizeContent}“ styleClass=“recordSet“ headerStyleClass=“recordSetHeader“ rowStyleClass=“recordSetRow“ altRowStyleClass=“recordSetRowAlt“ width=“100%“ value=“#{BrowseTeletextBean.content}“ refreshOnBind=“true“ var=“r“>
. . .
<a:column id=“col14″ style=“text-align:left“>
<f:facet name=“header“>
<a:sortLink id=“col14-sort“ label=“Expired“ value=“expired“ styleClass=“header“/>
</f:facet>
<a:actionLink id=“col14-act1″ value=“#{r.pageExpired}“ actionListener=“#{BrowseTeletextBean.clickPageExpired}“>
<f:param name=“id“ value=“#{r.id}“ id=“param14-1″ />
</a:actionLink>
</a:column>
. . .
[/code]

Here you can see actionLink with value defined by custom NodePropertyResolver (r.pageExpired), which renders either „Ano“ or „Ne“ based on value in TxtModel.txtExpired (QName) property in model.

[code language=“java“]public static final QName txtExpired = QName.createQName(„http://www.alfresco.org/model/txt/1.0“, „expired“);[/code]

ActionLink has an action handler – actionListener parameter – this handler just change value of the expired property and is as simple as this:

[code language=“java“]
public void clickPageExpired(ActionEvent event){
NodeRef nodeRef = getNodeRefFromParams(event);
if(nodeRef != null) {
boolean status = NodeUtils.getBoolProperty(nodeRef, TxtModel.txtExpired, getNodeService());
getNodeService().setProperty(nodeRef, qName, !status);
UIContextService.getInstance(FacesContext.getCurrentInstance()).notifyBeans();
}
}
[/code]

Note that UIContext…notifyBeans() is needed to notify beans, that some change had been done and we need to refresh view. For this refresh also refreshOnBind parameter on richList is needed to be true.

It was easy to put it together, but like everything in Alfresco – badly documented. So I hope this post help someone. Feel free to ask questions, if something is not clear enough ;-).