Ejemplos de Automatización

Esta sección recopila un conjunto de scripts de automatización de muestra que puede copiar y ajustar para implementar sus propios algoritmos.

Obtener información del sistema invocando el servicio 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");

Este procedimiento está diseñado para demostrar la invocación de un método de servicio web REST externo. Simplemente invoca una URL e imprime el resultado, en este caso usamos el punto final del servicio web REST System.getInfo disponible en cada instalación de LogicalDOC.

Reemplaze  http://localhost:8080 con la URL base de su instalación.

Crea un nuevo archivo sobre la base de otro documento existente

# 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

Actualiza el atributo de output de la carpeta agregando el texto attr1 - date (donde attr1 es un atributo y date es la fecha actual, por ejemplo 2020-02-18).
Crea un archivo de texto para cada valor de metadatos attr3 (attr3 es un atributo con valores múltiples) del documento original cuyo contenido será un texto de línea única.
Las características del archivo de texto son:

  • Nombre de archivo: attr2 - attr3 - date (donde attr2 es el valor del atributo attr2, attr3 es uno de los múltiples valores del atributo attr3)
  • Contenido del archivo de texto: filename.ext, attr3 (donde filename.ext es el nombre del documento con su extensión (.doc, .docx, etc.), attr3 es uno de los múltiples valores del atributo attr3)
  • Carpeta de destino: /Received Emails/Sent/prot (prot es el atributo prot)

Actualiza los metadatos del nuevo archivo de texto.
Aplica la plantilla sendings y establece algunos metadatos:

  • prot (copiando el atributo prot del documento original)
  • dest-ind (copiando el atributo attr3 que tiene múltiples valores)
  • date-sent

Replica las anotaciones de flujo de trabajo a las notas 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

Este procedimiento está diseñado para ejecutarse dentro de un flujo de trabajo, el identificador de instancia del flujo de trabajo actual se encuentra en la variable processId.

Para cada documento adjunto al flujo de trabajo, se aplica el sello approved y se almacena una conversión PDF en una carpeta pública.

Una vez que se ha completado el flujo de trabajo, las anotaciones dejadas por los usuarios permanecen en el historial del flujo de trabajo (dentro del panel de control del flujo de trabajo), entonces para que los usuarios normales puedan acceder a ellas más fácilmente, cada anotación se replica en los documentos como notas.

Divide los cheques de pago y los envía por correo electrónico a los empleados

# 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

Este script funciona en el documento actualmente seleccionado al que hace referencia la variable document que se considera un gran PDF que contiene todos los cheques de pago de un mes.

El documento se divide en segmentos de dos páginas, cada segmento se guarda como un solo cheque PDF y su contenido se inspecciona para descubrir a qué empleado pertenece para enviárselo por correo electrónico.

Fragmentos de Automatización

# 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

No es realmente un script completo, sino una colección de fragmentos.

Plantilla de correo electrónico personalizado

# 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 personalización de la plantilla de correo electrónico utilizada para notificar a los usuarios sobre las tareas de flujo de trabajo. Esta propuesta difiere de la plantilla estándar porque incluye la lista de anotaciones dejadas en el flujo de trabajo por los otros usuarios. En este script, puede ver el uso de la clase I18N para imprimir etiquetas localizadas. La instancia de flujo de trabajo actual está referenciada por la variable processId.

Clasifica un documento en función de atributos personalizados

#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

Este procedimiento analiza el documento(variable document) y lo clasifica según el valor de un atributo personalizado. La clasificación implica la actualización de algunos metadatos y el movimiento a una carpeta específica calculada dinámicamente.

Search on Extended Attributes

# 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

Este procedimiento busca todos aquellos documentos dentro de la carpeta /Default/Emails que son correos electrónicos y el atributo sendername contiene john.