Esempi di Automazione

Questa sezione raccoglie una serie di script di automazione di esempio che è possibile copiare e regolare per implementare i propri algoritmi.

Ottenere informazioni di sistema richiamando il servizio web REST

# Instantiate a utility to handle IO
#set($IOUtils = $ClassTool.newInstance("org.apache.commons.io.IOUtils"))

# Instantiate a URL to the getInfo service of LogicalDOC
#set($clazzUrl = $context.getClass().forName("java.net.URL"))
#set($clazzString = $context.getClass().forName("java.lang.String"))

# Adjust the url to point to your LogicalDOC installation
#set($url = $clazzUrl.getConstructor($clazzString).newInstance("http://localhost:8080/services/rest/system/getInfo"))
$log.info("url: $url") 

# Open the connection to the remote server
#set ($con = $url.openConnection())

# Send a GET request and print the response status
$con.setRequestMethod("GET");
#set ($status = $con.getResponseCode())
$log.info("status: $status") 

# Get the body of the response and store it in a variable
#set ($result = '')
#if ($status > 299) {
    #set ($result = $IOUtils.toString($con.getErrorStream(), "UTF-8"))
#else
    #set ($result = $IOUtils.toString($con.getInputStream(), "UTF-8"))
#end

# Print the result
$log.info("result: $result");

Questa procedura è progettata per dimostrare l'invocazione di un metodo di servizio web REST esterno. Richiama semplicemente un URL e stampa il risultato, in questo caso utilizziamo l'endpoint del webservice REST System.getInfo disponibile in ogni installazione di LogicalDOC.

Sostituisci http://localhost:8080 con l'URL di base della tua installazione.

 

Crea un nuovo file sulla base di un altro documento esistente

# if the user is not available, take it from the event
#if(!$user)
    #set($user = $event.user)
#end

# if the current folder is not available, take it from the event
#if(!$folder)
    #set($folder = $event.folder)    
#end

# get the document referenced by the current event
#set($document = $DocTool.findById($event.docId)) 

#if($user.isMemberOf("admin"))
    $log.info("user is admin");
    
    #set ($ctime = $DateTool.currentTime())
    $log.info("current time is $ctime");
    
    $DateTool.setDateFormatShort('yyyy-MM-dd')
    #set ($fdate = $DateTool.format($ctime,false))
    $log.info("fdate $fdate");
    
    # get the custom attribute 'output' of the folder
    #set ($val1 = $folder.getValue('output'))
    $log.info("val1 is $val1");
    #if( !$val1 )
        #set ($val1 = '')
    #end       
    
    # get the custom attribute 'attr1' of the document and update val1
    #set($val1 = $val1 + $document.getValue('attr1') +" - " + $fdate)

    # update the custom attribute 'output' of the fodler with the new val1
    $folder.setValue('output', $val1);
    
    # instantiate a new event for the folder(class FolderHistory) and prepare it
    #set ( $history = $ClassTool.newInstance("core.folder.FolderHistory") )
    $history.setUser($user);
    
    # retrieve the FolderDAO and use it to save the folder with it's event
    #set($folderDAO = $ContextTool.getBean("FolderDAO"))     
    $folderDAO.store($folder, $history);        
    
    # retrieve the custom attribute 'attr2' of the document
    #set($attr2Value = $document.getValue("attr2"))
    
    # instantiate the 3rd party library class IOUtils 
    #set($IOUtils = $ClassTool.newInstance("org.apache.commons.io.IOUtils"))
    
    #set ($current_time = $DateTool.currentTime())
    #set ($java_year = $current_time.getYear())
    #set ($current_year = $java_year + 1900)    
    #set($docAttrs = $document.getAttributeNames())
    
    # iterate over the custom attribute of the document
    #foreach( $attrn in $docAttrs )
        # if we find the existence of the 'attr3' attribute we have to elaborate it
        #if($attrn.toString().contains("attr3"))
            #set($attr3Value = $document.getValue($attrn.toString()))
            
            # define a new name for the document
            #set($newFileName = $attr2Value + "-" + $attr3Value + "-" +$fdate + ".txt")
            
            # prepare the content of the new document as a string and convert it into an InputStream with IOUtils
            #set ($docContent =  $document.getFileName() + ", " + $attr3Value)        
            #set ($docIS = $IOUtils.toInputStream($docContent))                
            
            # create a new document from scratch
            #set ( $documentVO = $ClassTool.newInstance("core.document.Document") )
            $documentVO.setFileName($newFileName);
            
            # get the 'prot' attribute and if the case initialize it
            #set($protValue = $document.getValue('prot'))
            #if(!$protValue)
                #set($protValue = 'NA');
            #end
            
            # define the path of folder that will receive the new document and create it 
            #set($targetFldPath = "/Received Emails/Sent/" + $current_year + "/" + $protValue)
            #set($docTargetFld = $DocTool.createPath($document, $targetFldPath, $user.username))
            
            $log.info("docTargetFld: $docTargetFld.id");    
            
            # Set the folder and fill the other metadata for the new file
            $documentVO.setFolder($docTargetFld);
            $documentVO.setLanguage('en');
            
            #set($templateDAO = $ContextTool.getBean('TemplateDAO'));
            #set($sendingsTemp = $templateDAO.findByName('sendings',1)); 
            $documentVO.setTemplate($sendingsTemp);
            $documentVO.setValue('prot',$protValue);
            $documentVO.setValue('dest-ind',$attr3Value);
            $documentVO.setValue('fecha-env',$fdate);
                        
            $log.info("content: $docIS"); 
            $log.info("document: $documentVO");             
            
            #set($dmanager = $ContextTool.getBean("DocumentManager") )  
            
            #set ( $dhistory = $ClassTool.newInstance("core.document.DocumentHistory") )
            $dhistory.setUser($user);
            $log.info("history: $dhistory");                        
            
            #set($newDocument = $dmanager.create($docIS, $documentVO, $dhistory) )
            $log.info("created new document with ID: $newDocument.id");            
        #end
    #end
#end

Aggiorna l'attributo di output della cartella aggiungendo la stringa attr1 - date (dove attr1 è un attributo e date è la data corrente, ad esempio 2020-02-18).
Crea un file di testo per ogni valore di metadati attr3 (attr3 è un attributo con più valori) del documento originale il cui contenuto sarà una stringa a riga singola.
Le caratteristiche del file di testo sono:

  • Nome file: attr2 - attr3 - date (dove attr2 è il valore dell'attributo attr2, attr3 è uno dei valori multipli dell'attributo attr3)
  • Contenuto del file di testo: nomefile.ext, attr3 (dove nomefile.ext è il nome del documento con la sua estensione (.doc, .docx, ecc.), attr3 è uno dei valori multipli dell'attributo attr3)
  • Cartella di destinazione: /Received Emails/Sent/prot (prot è l'attributo prot)

Aggiorna i metadati del nuovo file di testo.
Applica la classe documentale sendings e imposta alcuni metadati:

  • prot (copiando l'attributo port del documento originale)
  • dest-ind (copiando l'attributo attr3 che ha più valori)
  • date-sent

Replica le annotazioni del workflow nelle note del documento

# iterate over the documents attached to the current workflow
#foreach( $doc in $documents ) 
  # retrieve the last task completion event
  #set($lastEvent = $WorkflowTool.getLastHistory($processId,'task.end'))
  
  # apply the 'rejected' stamp and move the file to the Approved subfolder
  $StampTool.stamp($doc, 'approved', $lastEvent.user.username);
  $DocTool.move($doc, 'Approved', $lastEvent.user.username);
  
  # make a pdf conversion of the approved file an store it in a public area
  #set($docConverted = $DocTool.convert($doc, "pdf", $lastEvent.user.username))
  $DocTool.move($docConverted, "/AreaTEST/TEST MERITOR/PUBLIC/Approved", $lastEvent.user.username);
  
  # get the collection of all annotation done by the participants in the current workflow
  #set($histories = $WorkflowTool.getHistories($processId, 'task.note'))
  $log.info("histories: $histories")
  $log.info("histories.size: $histories.size()")
  
  # iterate over the annotations and replicate them in the document
  #set($noteDAO = $ContextTool.getBean('DocumentNoteDAO'))
  #foreach( $hist in $histories )      
      # create the new note to be saved for the document
      #set($note = $ClassTool.newInstance('com.logicaldoc.core.document.DocumentNote'))

      # prepare all the metadata and save to database
      $note.setDocId($doc.id);
      $note.setUsername($hist.username);
      $note.setMessage($hist.comment);
      $note.setDate($doc.date);
      $note.setUserId($hist.userId);
      $note.setFileName($doc.fileName);
      $note.setFileVersion($doc.fileVersion);

      $noteDAO.store($note, null);
  #end
#end

Questa procedura è progettata per essere eseguita all'interno di un flusso di lavoro, l'identificatore dell'istanza del flusso di lavoro corrente è memorizzato nella variabile processId.

Per ogni documento allegato al flusso di lavoro, viene applicato il timbro approved e una conversione pdf viene archiviata in una cartella pubblica.

Una volta completato il flusso di lavoro, le annotazioni lasciate dagli utenti rimangono nella cronologia del forkflow (all'interno della bacheca del workflow), quindi per renderle più facilmente accessibili agli utenti normali, ogni annotazione viene replicata nei documenti come note.

Suddivide gli stipendi e li invia tramite e-mail ai dipendenti

# split the big payolls pdf in segments of two pages
#set( $paychecks = $SplitTool.splitSelection($document.id, '1-2,3-4,5-6,7-8', 'admin'))

# iterate over the segments, each segment is the paycheck of a single employee
#foreach( $paycheck in $paychecks )
  # parse the segment body and save it in the paycheckBody variable
  #set( $paycheckBody  =  $ContextTool.getBean('DocumentManager').parseDocument($paycheck, null) )
  
  # inspect the body of the segment to understand what is the employee
  # in order to rename the segment file and define the email to send the paycheck to 
  #if($paycheckBody.toUpperCase().contains("JOHN DOE") )
     #set( $newname = $document.title + "-john.pdf")
     #set( $recipient = "john[at]acme.com")
  #elseif($paycheckBody.toUpperCase().contains("MARIO ROSSI")  )
     #set( $newname = $document.title + "-mario.pdf")
     #set( $recipient = "mario[at]acme.com")
  #elseif( $paycheckBody.toUpperCase().contains("ELENA BORGHI") )
     #set( $newname = $document.title + "-elena.pdf")
     #set( $recipient = "elena[at]acme.com")
  #elseif( $paycheckBody.toUpperCase().contains("ALDO MORO") )
     #set( $newname = $document.title + "-aldo.pdf")
     #set( $recipient = "aldo[at]acme.com")
  #end

 # rename the current segment(the user's paycheck pdf)
 $paycheck.setFileName($newname);
 $DocTool.store($paycheck); 

 # notify the employee sending him his paycheck document
 $MailTool.sendDocument($paycheck, null, $recipient, "Acme Paycheck", "Dear employee, please find your new paycheck in attachment of this email.

Remember to save it in your records

Best Regards
Acme paycheck department"); #end

Questo script funziona sul documento attualmente selezionato a cui fa riferimento ls variabile document che è considerato un grande PDF contenente tutti gli stipendi di un mese.

Il documento è suddiviso in segmenti di due pagine, ogni segmento viene salvato come un singolo PDF di busta paga e il suo contenuto viene ispezionato per scoprire a quale dipendente appartiene lo stipendio per inviarlo via e-mail.

Frammenti di Automazione

# iterate over the documents
#foreach( $doc in $documents ) 
... 
#end

--------------------------------------------------------------------------------
# move the documents into a target folder computed dinamically
#foreach( $doc in $documents )
  # get the custom attribue 'InvoiceNo' and store it in the fld variable
  #set( $fld = $doc.getValue('InvoiceNo') )
  
  # move the document to a path that is composed by a fixed prefix and the fld value
  $DocTool.move($doc, "/Default/approved/$fld", '_system');
#end

--------------------------------------------------------------------------------
# apply a stamp in the documents
#foreach( $doc in $documents )
 $StampTool.stamp($doc, 'name_of_stamp', 'username');
#end

--------------------------------------------------------------------------------
# get the value of a procedure's invocation parameter
#set($value = $parameters.get('param_name') ) -------------------------------------------------------------------------------- # print logs (useful for debuging) # the log is printed in the file /repository/logs/automation.log #set($now = $ClassTool.newInstance('java.util.Date')) $log.debug( "debug current date: $DateTool.format($now, true)"); #set($lastEvent = $WorkflowTool.getLastHistory($processId,'task.end')) $log.info("The user that completed the last task was: $lastEvent.user.fullName"); $log.warn( "Just print a row in warn priority"); $log.error( "Just print a row in error priority"); -------------------------------------------------------------------------------- # send documents to a set of recipients #set( $recipients= ["a[at]acme.com", "b[at]acme.com", "c[at]acme.com"] ) $MailTool.sendDocuments($documents, 'sender[at]acme.com', $recipients, 'subject', 'message'); -------------------------------------------------------------------------------- # execute a routine $AutomationTool.execute('Routine', $tenantId, $dictionary, null); -------------------------------------------------------------------------------- # change an extended attribute #foreach( $doc in $documents ) $doc.setValue('attribute_name','attribute_value'); $DocTool.store($doc); #end -------------------------------------------------------------------------------- # adding a note #set($note = $ClassTool.newInstance('core.document.DocumentNote')) #set($noteDao = $ContextTool.getBean('DocumentNoteDAO')) $note.setDocId($document.id); $note.setUsername('admin'); $note.setMessage('test note'); $noteDao.store($note, null); -------------------------------------------------------------------------------- # automatically choose a workflow transition depending on attribute's value #foreach( $doc in $documents ) #set($amount = $doc.getValue("myAttributeName")) #if( $amount > 50000 ) $WorkflowTool.complete($task, "Approve Document") #break #else $WorkflowTool.complete($task, "Reject Document") #break #end #end -------------------------------------------------------------------------------- # reverse foreach #set($max = $opportunityList.size() - 1) #foreach($i in [ $max .. 0 ]) #set($opportunity = $opportunityList[$i]) ... #end -------------------------------------------------------------------------------- # digitally sign a selection of documents #foreach($doc in $documents ) $SignTool.sign($doc, $assignee, "Approved") #end -------------------------------------------------------------------------------- # get the path of files and folders #foreach( $doc in $documents ) #set($docPath = $DocTool.getPath($doc)) $log.info("path of document $doc.fileName: $docPath"); #set($folderPath = $FolderTool.getPath($doc.folder.id)) $log.info("path of folder $doc.folder.name: $folderPath"); #end

Non proprio uno script completo ma una raccolta di frammenti.

Modello email personalizzato

# use the I18N class to display localized labels, the recipient's locale will be used
$I18N.get('dear') $assignee.fullName, $I18N.get('youareassignedtotask') <b>$taskName</b> $I18N.get('ofworkflow') <b>$workflow</b>
<hr/>

# display the links to take one of the possible actions defined for the current task
<b>$I18N.get('actions')</b>:
#foreach( $action in $actions)
  | <a target="_blank" href="/$WorkflowTool.completeUrl($task, $action, $assignee)">$action</a>
#end
<hr/>

# display the clickable list of the documents appended to the current workflow
<b>$I18N.get('documents')</b>:
#foreach( $doc in $documents )
  <br/>$doc.fileName | <a target="_blank" href="/$DocTool.downloadUrl($doc)">$I18N.get('download')</a> | <a target="_blank" href="/$DocTool.displayUrl($doc)">$I18N.get('display')</a>
#end

# iterate over the events of the current workflow to find the most recent one and save it in the lastAction variable
#set($hists = $WorkflowTool.getHistories($processId, null))
#foreach( $hhit in $hists )
   #if($hhit.taskName)
     #if($hhit.taskName != $taskName)
        #set($lastAction = $hhit)
        #break
     #end 
   #end   
#end

# display the last action taken inside the workflow
#if($lastAction) 
  <br/><br/>last taken action: $lastAction.taskName 
#end

# retrieves all the workflow annotations left until now
#set($hists = $WorkflowTool.getHistories($processId, 'task.note'))

# prepare a table to display the workflow annotations
<br/><br/>Annotations<br/>
<table>
<tr><td>Date</td><td>User</td><td>Annotation</td></tr>

#foreach( $hhit in $hists )
   <tr>
      <td>$hhit.date</td>
      <td>$hhit.username</td>
      <td>$hhit.comment</td>
   </tr>
#end
</table>

Una personalizzazione del modello e-mail utilizzato per notificare agli utenti le attività del flusso di lavoro. Questa proposta differisce dal modello standard perché include l'elenco delle annotazioni lasciate sul flusso di lavoro dagli altri utenti. In questo script puoi vedere l'uso della classe I18N per stampare etichette localizzate. L'istanza del flusso di lavoro corrente è referenziata dalla variabile processId.

Classifica un documento sulla base di attributi personalizzati

#set($templateDAO = $ContextTool.getBean('TemplateDAO'))

# retrieve the template that will be assigned to the document
#set($privateTemp = $templateDAO.findByName('TaxLienServicing'))

# store the document's path into the variable T_Path
#set($T_Path=$DocTool.getPath($document))

# get a couple of custom attributes from the document
#set($T_NewType=$document.getValue("DT-LegacyWebLT"))
#set($T_ClientName=$document.getValue("ClientName"))

# Now inspect the value of the DT-LegacyWebLT attribute to move the file to the proper folder
#if($T_NewType=="Import")
  $log.info("Reclassify triggered but no new document type selected");
#elseif ($T_NewType=="Payoff Requests Quotes")
  #set ($T_NewFG="Call Center - Payoff Requests Quotes")
  
  # set the correct template and update a custom attribute
  $document.setTemplate($privateTemp);
  $document.setValue("FunctionalArea","$T_NewFG");
  
  # make the changes persisten into the database
  $DocTool.store($document);
  
  # move to a target folder caclulated dynamically
  $DocTool.move($document,"/$T_ClientName/$T_NewFG/",'_system');

  # exit the procedure
  #stop
#elseif (($T_NewType=="Lockbox Backup") || ($T_NewType=="2 day letters"))
  #set ($T_NewFG="Payment Processing - Lockbox")
  $document.setTemplate($privateTemp);
  $document.setValue("FunctionalArea","$T_NewFG");
  $DocTool.store($document);
  $DocTool.move($document,"/$T_ClientName/$T_NewFG/",'_system')
  #stop
#elseif ($T_NewType=="TN Reconciliation")
  #set ($T_NewFG="Payment Processing - Reconciliation")
  $document.setTemplate($privateTemp);
  $document.setValue("FunctionalArea","$T_NewFG");
  $DocTool.store($document);
  $DocTool.move($document,"/$T_ClientName/$T_NewFG/",'_system');
  #stop
#elseif ($T_NewType=="TX Loan")
  #set ($T_NewFG="Payment Processing - Texas Loans")
  $document.setTemplate($privateTemp);
  $document.setValue("FunctionalArea","$T_NewFG");
  $DocTool.store($document);
  $DocTool.move($document,"/$T_ClientName/$T_NewFG/",'_system');
  #stop
#elseif ($T_NewType=="RIE")
  #set ($T_NewFG="Payment Processing - Received In Error")
  $document.setTemplate($privateTemp);
  $document.setValue("FunctionalArea","$T_NewFG");
  $DocTool.store($document);
  $DocTool.move($document,"/$T_ClientName/$T_NewFG/",'_system');
  #stop
#elseif ($T_NewType=="Checks")
  #set ($T_NewFG="Payment Processing - Refunds")
  $document.setTemplate($privateTemp);
  $document.setValue("FunctionalArea","$T_NewFG");
  $DocTool.store($document);
  $DocTool.move($document,"/$T_ClientName/$T_NewFG/",'_system');
  #stop
#elseif ($T_NewType=="Client Reports" ||  $T_NewType=="Reconciliation")
  #set ($T_NewFG="Reporting")
  $document.setTemplate($privateTemp);
  $document.setValue("FunctionalArea","$T_NewFG");
  $DocTool.store($document);
  $DocTool.move($document,"/$T_ClientName/$T_NewFG/",'_system');
  #stop
#else 
  $log.info("Not in main $document.fileName");
#end

$log.info("Running 2")
#if ($T_NewType=="Proof of Purchase")  
  #set ($T_NewFG="Custodial - Imports")
  $document.setTemplate($privateTemp);
  $document.setValue("FunctionalArea","$T_NewFG");
  $DocTool.store($document);
  $DocTool.move($document,"/$T_ClientName/$T_NewFG/",'_system');
  #stop
#elseif ($T_NewType=="Redemption Notice" || $T_NewType=="Verification Request" || $T_NewType=="Redemption Packet" || $T_NewType=="Redemption Affidavit")
  #set ($T_NewFG="Custodial - Redemption Processing")
  $document.setTemplate($privateTemp);
  $document.setValue("FunctionalArea","$T_NewFG");
  $DocTool.store($document);
  $DocTool.move($document,"/$T_ClientName/$T_NewFG/",'_system');
  #stop
#elseif ($T_NewType=="Lien Release")
  #set ($T_NewFG="Custodial - Release Processing")
  $document.setTemplate($privateTemp);
  $document.setValue("FunctionalArea","$T_NewFG");
  $DocTool.store($document);
  $DocTool.move($document,"/$T_ClientName/$T_NewFG/",'_system');
  #stop
#elseif ($T_NewType=="Certs-Received, Not Processed" || $T_NewType=="Certs-Stickered and Recorded" || $T_NewType=="Certs-Stickered Only" || $T_NewType=="Deed")
  #set ($T_NewFG="Custodial - Collateral Management")
  $document.setTemplate($privateTemp);
  $document.setValue("FunctionalArea","$T_NewFG");
  $DocTool.store($document);
  $DocTool.move($document,"/$T_ClientName/$T_NewFG/",'_system');
  #stop
#elseif ($T_NewType=="Assignment Form" || $T_NewType=="List of Property")
  #set ($T_NewFG="Custodial - Lien Assignment Packets")
  $document.setTemplate($privateTemp);
  $document.setValue("FunctionalArea","$T_NewFG");
  $DocTool.store($document);
  $DocTool.move($document,"/$T_ClientName/$T_NewFG/",'_system');
  #stop
#else 
  $log.info("Not in Reclassify2 $document.fileName");
#end

$log.info("Running 3")
#if ($T_NewType=="Hello Letters" || $T_NewType=="Goodbye Letters" || $T_NewType=="Demand Letter" || $T_NewType=="Collection Letter" || $T_NewType=="General Collection Letter" || $T_NewType=="Annual Notice" || $T_NewType=="Take Notices" || $T_NewType=="Extension Letter" || $T_NewType=="10 Day Notice")
  #set ($T_NewFG="Asset Management - Noticing")
  $document.setTemplate($privateTemp);
  $document.setValue("FunctionalArea","$T_NewFG");
  $DocTool.store($document);
  $DocTool.move($document,"/$T_ClientName/$T_NewFG/",'_system');
  #stop
#elseif ($T_NewType=="Notice of Filing" || $T_NewType=="Notice of Hearing" || $T_NewType=="Notice of Discharge" || $T_NewType=="Notice of Dismissal" || $T_NewType=="Proof of Claim" || $T_NewType=="Motion to Lift Stay" || $T_NewType=="Motion to Appoint Trustee" || $T_NewType=="Motion to Dismiss" || $T_NewType=="Debtor's Motion to Extend Exclusive Period"|| $T_NewType=="Disclosure Statement" || $T_NewType=="Confirmed Plan" || $T_NewType=="Reorganization Plan" || $T_NewType=="Objections to Plan")
  #set ($T_NewFG="Asset Management - Bankruptcy")
  $document.setTemplate($privateTemp);
  $document.setValue("FunctionalArea","$T_NewFG");
  $DocTool.store($document);
  $DocTool.move($document,"/$T_ClientName/$T_NewFG/",'_system');
  #stop
#elseif ($T_NewType=="Project Status Report")
  #set ($T_NewFG="Project Status Report")
  $document.setTemplate($privateTemp);
  $document.setValue("FunctionalArea","$T_NewFG");
  $DocTool.store($document);
  $DocTool.move($document,"/$T_ClientName/$T_NewFG/",'_system');
  #stop
#else 
  $log.info("Not in Reclassify3 $document.fileName");
#end

Questa procedura analizza il documento(variabile document) e lo classifica in base al valore di un attributo personalizzato. La classificazione implica l'aggiornamento di alcuni metadati e los spostamento a una cartella specifica calcolata in modo dinamico.

Ricerca per attributi estesi

# Retrieve a folder to search in
#set($folder = $FolderTool.findByPath('/Default/Emails'))

# Retrieve the template by it's name
#set($templateDao = $ContextTool.getBean('TemplateDAO'))
#set($template = $templateDao.findByName('email', $folder.tenantId))

# Prepare the list of search criteria
#set($criteria = [])

# Prepare the condition on the root folder
#set($criterion = $ClassTool.newInstance("enterprise.search.Criterion"))
$criterion.setComposition("and");
$criterion.setLongValue($folder.id);
$criterion.setType(101);
$criterion.setOperator("inorsubfolders");
$criterion.setField("folder");
$criteria.add($criterion);

# Prepare the condition on the extended attribute sendername
#set($criterion = $ClassTool.newInstance("enterprise.search.Criterion"))
$criterion.setComposition("and");
$criterion.setField("sendername");
$criterion.setType(0);
$criterion.setOperator("contains");
$criterion.setStringValue("john");
$criterion.setExtendedAttribute(true);
$criteria.add($criterion);

# Instantiate the search options
#set($options = $ClassTool.newInstance("enterprise.search.ParametricSearchOptions"))
$options.setMaxHits(100);
$options.setUserId(1);
$options.setRetrieveAliases(false);

# Define the template we want to use
$options.setTemplate($template.id);

# Put all the criteria
$options.setCriteria($criteria);

# Get the ParametricSearch object and execute the search
#set($searchFactory = $ClassTool.newInstance("enterprise.search.ParametricSearch"))
#set($search = $searchFactory.get($options))
$log.info("Search $search");

# Search and iterate over the results  
#set($hits = $search.search())
#foreach($hit in $hits)
  $log.info("Hit: $hit.fileName");
#end

Questa procedura cerca tutti quei documenti all'interno della cartella /Default/Emails che sono messaggi di posta elettronica e l'attributo sendername contiene john.