AnsweredAssumed Answered

Custom Module Evaluator not working properly

Question asked by hiten.rastogi on Jan 21, 2016
Latest reply on Jul 5, 2016 by twasyl
Hi Folks,

After creating a custom module using  <a href="http://docs.alfresco.com/5.1/tasks/dev-extensions-share-tutorials-add-menuitem-create-menu.html">this</a> tutorial I have created a custom module evaluator which should disable the module under certain space and show under certain, but I am not able to get it worked properly.

Here, I want to disable the country folder custom module if we are in space other than the document library space, but if I apply the custom evaluator it seems to hide it everywhere


Copying my custom evalutator and the webscript. Please help me out if anyone has any suggestion.

<strong>country-folder-extension.xml - Custom Module</strong>

<extension>
   <modules>
      <!– This module is dependent on the custom content model setup in the
         repo-amp module –>
      <module>
         <id>Add a Goyal Brothers Country Folder option to Create… menu in
            DocLib
         </id>
         <!– Use this to automatically apply the evaluator for this module –>
         <evaluator type="country.folder.module.evaluator">
            <params>
               <apply>true</apply>
            </params>
         </evaluator>
         <version>1.0</version>
         <auto-deploy>true</auto-deploy>
         <configurations>
            <config evaluator="string-compare" condition="DocumentLibrary">
               <create-content>
                  <content id="goyal-brothers-country-folder" label="prop.evgb_countryFolder"
                     icon="folder" type="pagelink">
                     <param name="page">create-content?destination={nodeRef}&amp;itemId=evgb:goyalBrothersCountryFol
                     </param>
                  </content>
               </create-content>
            </config>

            <config evaluator="model-type" condition="evgb:goyalBrothersCountryFol">
               <forms>
                  <form>
                     <field-visibility>
                        <show id="cm:name" />
                     </field-visibility>
                     <appearance>
                        <field id="cm:name" label-id="prop.evgb_country">
                           <control>
                              <control-param name="maxLength">255</control-param>
                           </control>
                        </field>
                     </appearance>
                  </form>
               </forms>
            </config>
         </configurations>
      </module>
   </modules>
</extension>


<strong>CountryFolderModuleEvaluator.java - Custom Module Evaluator</strong>

import java.util.Map;

import org.alfresco.error.AlfrescoRuntimeException;
import org.apache.log4j.Logger;
import org.json.JSONException;
import org.springframework.extensions.surf.RequestContext;
import org.springframework.extensions.surf.ServletUtil;
import org.springframework.extensions.surf.exception.ConnectorServiceException;
import org.springframework.extensions.surf.extensibility.ExtensionModuleEvaluator;
import org.springframework.extensions.surf.support.ThreadLocalRequestContext;
import org.springframework.extensions.webscripts.Status;
import org.springframework.extensions.webscripts.connector.Connector;
import org.springframework.extensions.webscripts.connector.Response;

public class CountryFolderModuleEvaluator implements ExtensionModuleEvaluator {

   private Logger logger = Logger
         .getLogger(CountryFolderModuleEvaluator.class);

   @Override
   public boolean applyModule(RequestContext context,
         Map<String, String> evaluationProperties) {

      if (logger.isDebugEnabled()) {
         logger.debug("******************* context.getUri() : "
               + context.getUri() + " *******************");
      }

      String spaceUri = context.getUri();

      int indexOfDocLib = spaceUri.lastIndexOf("/") + 1;

      String docLib = spaceUri.substring(indexOfDocLib);

      return hasCorrectParentType(docLib);
   }

   private boolean hasCorrectParentType(String docLib) {

      if (logger.isDebugEnabled()) {
         logger.debug("******************* Inside hasCorrectParentType() *******************");
      }
      Boolean result = false;
      try {

         final RequestContext rc = ThreadLocalRequestContext
               .getRequestContext();// get request context
         final String userId = rc.getUserId();

         final Connector conn = rc.getServiceRegistry()
               .getConnectorService()
               .getConnector("alfresco", userId, ServletUtil.getSession());// get
                                                            // connector

         // custom repository webscript which checks if noderef has given
         // parent type or not
         final String url = "/node/parentType/country?spaceName=" + docLib;

         if (logger.isDebugEnabled()) {
            logger.debug("******************* Calling countryCheck Webscript; url: "
                  + url + " *******************");
         }

         final Response response = conn.call(url);// get response

         // make sure we are getting valid esponse
         if (Status.STATUS_OK == response.getStatus().getCode()) {
            final org.json.JSONObject scriptResponse = new org.json.JSONObject(
                  response.getResponse());
            result = scriptResponse.getBoolean("hasCorrectParentNode");
            if (logger.isDebugEnabled()) {
               logger.debug("******************* Printing result from webscript - "
                     + result + " *******************");
            }
         }
      } catch (final ConnectorServiceException e) {
         throw new AlfrescoRuntimeException("Failed to connect repository: "
               + e.getMessage());

      } catch (final JSONException e) {

         throw new AlfrescoRuntimeException("Failed to parse JSON string: "
               + e.getMessage());
      }

      return result;
   }

   @Override
   public String[] getRequiredProperties() {
      return null;
   }

}


<strong>countryCheck.get.desc.xml - Descriptor</strong>

<webscript>
  <shortname>Country Folder creation check</shortname>
  <description>Check if folder node creation is valid  or not</description>
  <url>/node/parentType/country?currNodeRef={currNodeRef}</url>
  <format default="json">argument</format>
  <authentication>user</authentication>
</webscript>


<strong>ValidateParentForCountryFolder.java - Controller</strong>

import java.util.HashMap;
import java.util.Map;

import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.StoreRef;
import org.alfresco.service.cmr.search.ResultSet;
import org.alfresco.service.cmr.search.ResultSetRow;
import org.alfresco.service.cmr.search.SearchParameters;
import org.alfresco.service.cmr.search.SearchService;
import org.apache.log4j.Logger;
import org.springframework.extensions.webscripts.DeclarativeWebScript;
import org.springframework.extensions.webscripts.Status;
import org.springframework.extensions.webscripts.WebScriptRequest;

public class ValidateParentForCountryFolder extends DeclarativeWebScript {

   private SearchService searchService;

   private Logger logger = Logger.getLogger(ValidateParentForCountryFolder.class);
   
   @Override
   protected Map<String, Object> executeImpl(WebScriptRequest req,
         Status status) {

      Boolean hasCorrectParentNode = true;
      Map<String, Object> model = new HashMap<String, Object>();
      String docLibName = req.getParameter("spaceName");
      
         System.out.println("******************* stateName : "+ docLibName +" *******************");
      
      // Make sure we are getting value
      if (docLibName.equals("null")) {
         status.setCode(400, "Required data has not been provided");
         status.setRedirect(true);
      } else {
         
         //find the node with the given name
         String query = "TYPE:\"cm:folder\" AND @cm\\:name:"+docLibName;
         
         SearchParameters sp = new SearchParameters();
         sp.addStore(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE);
         sp.setLanguage(SearchService.LANGUAGE_LUCENE);
         sp.setQuery(query);
         
         ResultSet results = null;
           try
           {
               results = searchService.query(sp);
               for(ResultSetRow row : results)
               {
                   NodeRef currentNodeRef = row.getNodeRef();
                   if (logger.isDebugEnabled()) {
                    logger.debug("######################## currentNodeRef = " + currentNodeRef + "########################");
                 }
               }
           }
           finally
           {
               if(results != null)
               {
                   results.close();
               }
           }
          
         if (results.length() == 0) {
            hasCorrectParentNode = false;
         }
      }
      model.put("hasCorrectParentNode", hasCorrectParentNode);
      return model;
   }

   public void setSearchService(SearchService searchService) {
      this.searchService = searchService;
   }
}


<strong>countryCheck.get.json.ftl - View</strong>

{
"hasCorrectParentNode":"${hasCorrectParentNode?string}"
}



Thanks

Outcomes