Friday, 20 October 2017

Junit of Class extending WCMUsePojo using mockito

public class SomeClass extends WCMUsePojo {

@Override
public void activate() throws Exception {

SomeClassServiceImpl someServiceImpl = getSlingScriptHelper()
.getService(SomeClassServiceImpl.class);
if (null != someServiceImpl) {
someServiceImpl.someMethod(getRequest(), getResponse(), getCurrentPage());
}

}
}

On extending the class WCMUsepojo we are able to call methods like getRequest(), getResponse(), getCurrentPage(), getSlingScriptHelper()....

While writing the Junit using the Mockito  I found it difficult to write the above way. Instead  with the init method we accessed all the bindings like REQUEST, RESPONSE, CURRENT_PAGE..
SLING. The only thing we we have to do is initailize the bindings in the testActivate method
We need to Mock SlingScriptHelper,SlingBindings, the Impl class,SlingHttpServletRequest,SlingHttpServletResponse

please find the snippet

@Test
    public void testActivate() throws Exception {

        Bindings bindings = new SimpleBindings();
        WCMBindings wcmBindings = new WCMBindings();
        request = new MyRequest(slingRequest);
        when(request.getAttribute(SlingBindings.class.getName())).thenReturn(slingBindings);
        when(request.getAttribute(WCMBindings.class.getName())).thenReturn(wcmBindings);
        when(slingBindings.getSling()).thenReturn(scriptHelper);
        response = new MyResponse(slingResponse);
        when(scriptHelper.getService(SomeClassServiceImpl.class)).thenReturn(someClassService);
        bindings.put(SlingBindings.SLING, scriptHelper);
        someClassService.someMethod(request, response, currentPage);
        when(request.getResource()).thenReturn(resource);
        when(resource.adaptTo(Page.class)).thenReturn(currentPage);
        when(page.getPath()).thenReturn("/content");
        bindings.put(SlingBindings.REQUEST, request);
        bindings.put(SlingBindings.RESPONSE, response);
        bindings.put(WCMBindings.CURRENT_PAGE, page);
        SomeClass SomeClass = new SomeClass();
        SomeClass.init(bindings);

    }

    /**
     * The Class MyRequest.
     */
    private class MyRequest extends SlingHttpServletRequestWrapper {

        /**
         * Instantiates a new my request.
         *
         * @param wrappedRequest
         *            the wrapped request
         */
        public MyRequest(SlingHttpServletRequest wrappedRequest) {
            super(wrappedRequest);
        }

    }

    /**
     * The Class MyResponse.
     */
    private class MyResponse extends SlingHttpServletResponseWrapper {

        /**
         * Instantiates a new my response.
         *
         * @param wrappedRequest
         *            the wrapped response
         */
        public MyResponse(SlingHttpServletResponse wrappedResponse) {
            super(wrappedResponse);
        }

    }
Hope you find it helpful.

Sunday, 20 September 2015

python and aem

Use Case:
Sometimes it is required to bind/unbind the configurations, restart/refresh the bundles afterwards .

Solution: We can use the below script wit some modifications according to your project setup.
def checkbundle():
          retries = 15
     response = 0
     while retries > 0 and response != '1':
          time.sleep(10)
          response = commands.getoutput('curl -silent -u admin:admin http://'+host+':'+port+'/system/console/bundles/org.apache.felix.webconsole.json | grep Active | wc
 -l')
          response = response.strip()
          retries = retries - 1
     if (response == '1'):
         bindConfig();
         startBundles();
     else:
         print "Felix console not ready :-("

def getBundleState():
        response = commands.getoutput('curl -silent -u admin:admin http://'+host+':'+port+'/system/console/config/Bundlelist.nfo | grep Kosa_CMS*')
    var = response.split('<br/>\n')
    var3 = ""
    for i in var:
        m1=re.search('&nbsp;\[(.+),&nbsp;', i)
        m2=re.search('(.+)&nbsp;\(', i)
        m3=re.search('&nbsp;\((.+)\)&nbsp;', i)
        if m1 or m2 or m3:
            var3 = var3 + m1.group(1)+";"+ m2.group(1)+";"+m3.group(1) +"\n"
    print var3.strip()
    return var3.strip()
def startBundles():
    bund2 = getBundleState();
    bund = bund2.split('\n')
       for i in bund:
        if i.split(';')[0] != 'active':
           print "Starting bundle "+i.split(';')[1]+""
           res = commands.getoutput('curl -silent -u admin:admin http://'+host+':'+port+'/system/console/bundles/'+i.split(';')[1]+' -Faction=start')
           print res
        else:
           print "The bundle "+i.split(';')[1]+" is already active"

def getConfigState():
        response = commands.getoutput('curl -silent -u admin:admin http://'+host+':'+port+'/system/console/config/Configurations.nfo |grep -e PID -e BundleLocation | grep kosa')
    var = response.split('PID')
    var3 = ""
    for i in var:
        m1=re.search('&nbsp;=&nbsp;(.+)<br/>', i)
        m2=re.search('BundleLocation&nbsp;=&nbsp;(.+)<br/>', i)
        if m2:
           loc = m2.group(1)
        else:
           loc = "UnBound"
        if m1:
           var3 = var3 +m1.group(1)+";"+loc + "\n"
    return var3.strip()
def bindConfig():
    bund2 = getConfigState();
 bund = bund2.split('\n')
       for i in bund:
        print "unbinding the config before restarting Kosa-common bundle"
        resp = commands.getoutput('curl -silent -u admin:admin -X POST "http://'+host+':'+port+'/system/console/configMgr/'+i.split(';')[0]+'?unbind=1"')
        print resp
        if i.split(';')[1] == 'UnBound':
           print "Binding the conf "+i.split(';')[0]+""
           res = commands.getoutput('curl -silent -u admin:admin -F action=refresh http://'+host+':'+port+'/system/console/bundles/com.adobe.nimish.cms.nimish-cms-common')
           print res
        else:
           print "The config "+i.split(';')[0]+" is already binded to "+i.split(';')[1]+""
    res = commands.getoutput('curl -silent -u admin:admin -F action=refresh http://'+host+':'+port+'/system/console/bundles/com.adobe.nimish.cms.nimish-cms-common')
    print "starting common bundle"
    print res

te = open('/var/CMSDump/AmsTools/log.txt','w')  # File where you need to keep the logs

class Unbuffered:

   def __init__(self, stream):

       self.stream = stream

   def write(self, data):

       self.stream.write(data)
       self.stream.flush()
       te.write(data)    # Write the data of stdout here to a text file as well


sys.stdout=Unbuffered(sys.stdout)
if __name__=='__main__':
     checkbundle();

To get all workflows which have scheduled time in the next half an hour and started 15 mins back and are running

Use Case:

1.We want to postpone the backup n the basis of count of running workflows around the backup time

Solution:



# Define a timestamp function
timestamp() {
  #date +"%T"
  date +"%s%3N"
}
var=`timestamp`
var1=$(expr $var + 1800000)
var2=$(date +"%Y-%m-%d"T"%T" --date='15 minutes ago')
var3=${var2}.000Z
# To get all workflows which have scheduled time in the next half an hour
curl -s -g -u admin:admin 'http://localhost:40102/crx/de/query.jsp?_dc=1418076406834&_charset_=utf-8&type=xpath&stmt=/jcr:root/etc/workflow/instances//*[(@absoluteTime>="'$var'")and(@absoluteTime<="'$var1'")]&showResults=true' |sed 's/\\\\\//\//g' | sed 's/[{}]//g' | awk -v k="text" '{n=split($0,a,","); for (i=1; i<=n; i++) print a[i]}' | sed 's/\"\:\"/\;/g' | sed 's/[\,]/ /g' | sed 's/\"//g' |sed 's/results\:\[//g' |sed 's/\/metaData//g'|sed 's/\/data//g' |grep path>/tmp/count
sleep 1
# To get all the workflows which is started 15 mins back and are running
curl -s -g -u admin:admin 'http://localhost:40102/crx/de/query.jsp?_dc=1418076406834&_charset_=utf-8&type=xpath&stmt=/jcr:root/etc/workflow/instances//*[(@startTime>=xs:dateTime("'$var3'"))and@modelId!="/etc/workflow/models/scheduled_activation"and@modelId!="/etc/workflow/models/scheduled_deactivation"and@status!="ABORTED"and@status!="COMPLETED"]&showResults=true' |sed 's/\\\\\//\//g' | sed 's/[{}]//g' | awk -v k="text" '{n=split($0,a,","); for (i=1; i<=n; i++) print a[i]}' | sed 's/\"\:\"/\;/g' | sed 's/[\,]/ /g' | sed 's/\"//g' | sed 's/results\:\[//g' |grep path>>/tmp/count
sleep 1