XWIKI-5725: Deprecate XWiki#parseMessage
Fix aspect

git-svn-id: d23d7a6431d93e1bdd218a46658458610974b053@33151 f329d543-caf0-0310-9063-dda96c69346f

/*
 * See the NOTICE file distributed with this work for additional
 * information regarding copyright ownership.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 *
 */
package com.xpn.xwiki;

import com.xpn.xwiki.XWiki;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.cache.api.XWikiCache;
import com.xpn.xwiki.cache.api.XWikiCacheService;
import com.xpn.xwiki.cache.api.internal.XWikiCacheServiceStub;
import com.xpn.xwiki.cache.api.internal.XWikiCacheStub;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * Add a backward compatibility layer to the {@link com.xpn.xwiki.XWiki} class.
 *
 * @version $Id$
 */
public privileged aspect XWikiCompatibilityAspect
{
    private static Map XWiki.threadMap = new HashMap();

    /**
     * Transform a text in a URL compatible text
     *
     * @param content text to transform
     * @return encoded result
     * @deprecated replaced by Util#encodeURI since 1.3M2
     */
    @Deprecated
    public String XWiki.getURLEncoded(String content)
    {
        try {
            return URLEncoder.encode(content, this.getEncoding());
        } catch (UnsupportedEncodingException e) {
            return content;
        }
    }

    /**
     * @return true for multi-wiki/false for mono-wiki
     * @deprecated replaced by {@link XWiki#isVirtualMode()} since 1.4M1.
     */
    @Deprecated
    public boolean XWiki.isVirtual()
    {
        return this.isVirtualMode();
    }

    /**
     * @deprecated Removed since it isn't used; since 1.5M1.
     */
    @Deprecated
    public static Map XWiki.getThreadMap()
    {
        return XWiki.threadMap;
    }

    /**
     * @deprecated Removed since it isn't used; since 1.5M1.
     */
    @Deprecated
    public static void XWiki.setThreadMap(Map threadMap)
    {
        XWiki.threadMap = threadMap;
    }

    /**
     * @return the cache service.
     * @deprecated replaced by {@link XWiki#getCacheFactory(XWikiContext)} or
     *             {@link XWiki#getLocalCacheFactory(XWikiContext)} since 1.5M2.
     */
    @Deprecated
    public XWikiCacheService XWiki.getCacheService()
    {
        return new XWikiCacheServiceStub(getCacheFactory(), getLocalCacheFactory());
    }

    /**
     * @deprecated replaced by {@link XWiki#getVirtualWikiCache(XWikiContext)} since 1.5M2.
     */
    @Deprecated
    public XWikiCache XWiki.getVirtualWikiMap()
    {
        return new XWikiCacheStub(this.virtualWikiMap);
    }

    /**
     * @deprecated replaced by {@link XWiki#getSpaceCopyright(XWikiContext)} since 2.3M1
     */
    @Deprecated
    public String XWiki.getWebCopyright(XWikiContext context)
    {
        return this.getSpaceCopyright(context);
    }

    /**
     * @deprecated replaced by {@link XWiki#getSpacePreference(String, XWikiContext)} since 2.3M1
     */
    @Deprecated
    public String XWiki.getWebPreference(String preference, XWikiContext context)
    {
        return this.getSpacePreference(preference, context);
    }

    /**
     * @deprecated replaced by {@link XWiki#getSpacePreference(String, String, XWikiContext)} since 2.3M1
     */
    @Deprecated
    public String XWiki.getWebPreference(String preference, String defaultValue, XWikiContext context)
    {
        return this.getSpacePreference(preference, defaultValue, context);
    }

    /**
     * @deprecated replaced by {@link XWiki#getSpacePreference(String, String, String, XWikiContext)} since 2.3M1
     */
    @Deprecated
    public String XWiki.getWebPreference(String preference, String space, String defaultValue, XWikiContext context)
    {
        return this.getSpacePreference(preference, space, defaultValue, context);
    }

    /**
     * @deprecated replaced by {@link XWiki#getSpacePreferenceAsLong(String, XWikiContext)} since 2.3M1
     */
    @Deprecated
    public long XWiki.getWebPreferenceAsLong(String preference, XWikiContext context)
    {
        return this.getSpacePreferenceAsLong(preference, context);
    }

    /**
     * @deprecated replaced by {@link XWiki#getSpacePreferenceAsLong(String, long, XWikiContext)} since 2.3M1
     */
    @Deprecated
    public long XWiki.getWebPreferenceAsLong(String preference, long defaultValue, XWikiContext context)
    {
        return this.getSpacePreferenceAsLong(preference, defaultValue, context);
    }

    /**
     * @deprecated replaced by {@link XWiki#getSpacePreferenceAsInt(String, XWikiContext)} since 2.3M1
     */
    @Deprecated
    public int XWiki.getWebPreferenceAsInt(String preference, XWikiContext context)
    {
        return this.getSpacePreferenceAsInt(preference, context);
    }

    /**
     * @deprecated replaced by {@link XWiki#getSpacePreferenceAsInt(String, int, XWikiContext)} since 2.3M1
     */
    @Deprecated
    public int XWiki.getWebPreferenceAsInt(String preference, int defaultValue, XWikiContext context)
    {
        return this.getSpacePreferenceAsInt(preference, defaultValue, context);
    }

    /**
     * @deprecated replaced by {@link XWiki#copySpaceBetweenWikis(String, String, String, String, XWikiContext)} since
     *             2.3M1
     */
    @Deprecated
    public int XWiki.copyWikiWeb(String space, String sourceWiki, String targetWiki, String language, XWikiContext context)
        throws XWikiException
    {
        return this.copySpaceBetweenWikis(space, sourceWiki, targetWiki, language, context);
    }

    /**
     * @deprecated replaced by
     *             {@link XWiki#copySpaceBetweenWikis(String, String, String, String, boolean, XWikiContext)} since
     *             2.3M1
     */
    @Deprecated
    public int XWiki.copyWikiWeb(String space, String sourceWiki, String targetWiki, String language, boolean clean,
        XWikiContext context) throws XWikiException
    {
        return this.copySpaceBetweenWikis(space, sourceWiki, targetWiki, language, clean, context);
    }

    /**
     * @deprecated replaced by {@link XWiki#getDefaultSpace(XWikiContext)} since 2.3M1
     */
    @Deprecated
    public String XWiki.getDefaultWeb(XWikiContext context)
    {
        return this.getDefaultSpace(context);
    }

    /**
     * @deprecated replaced by {@link XWiki#skipDefaultSpaceInURLs(XWikiContext)} since 2.3M1
     */
    @Deprecated
    public boolean XWiki.useDefaultWeb(XWikiContext context)
    {
        return this.skipDefaultSpaceInURLs(context);
    }

    /**
     * @deprecated use {@link XWikiMessageTool#get(String, List)} instead. You can access message tool using
     *             {@link XWikiContext#getMessageTool()}.
     */
    @Deprecated
    public String XWiki.getMessage(String item, XWikiContext context)
    {
        XWikiMessageTool msg = context.getMessageTool();
        if (msg == null) {
            return item;
        } else {
            return msg.get(item);
        }
    }

    /**
     * @deprecated use {@link XWikiMessageTool#get(String, List)} instead. You can access message tool using
     *             {@link XWikiContext#getMessageTool()}.
     */
    @Deprecated
    public String XWiki.parseMessage(String id, XWikiContext context)
    {
        XWikiMessageTool msg = context.getMessageTool();

        return parseContent(msg.get(id), context);
    }

    /**
     * @deprecated use {@link XWikiMessageTool#get(String, List)} instead. You can access message tool using
     *             {@link XWikiContext#getMessageTool()}.
     */
    @Deprecated
    public String XWiki.parseMessage(XWikiContext context)
    {
        String message = (String) context.get("message");
        if (message == null) {
            return null;
        }

        return parseMessage(message, context);
    }
}

/*
 * See the NOTICE file distributed with this work for additional
 * information regarding copyright ownership.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 *
 */
package com.xpn.xwiki;

import com.xpn.xwiki.XWiki;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.cache.api.XWikiCache;
import com.xpn.xwiki.cache.api.XWikiCacheService;
import com.xpn.xwiki.cache.api.internal.XWikiCacheServiceStub;
import com.xpn.xwiki.cache.api.internal.XWikiCacheStub;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * Add a backward compatibility layer to the {@link com.xpn.xwiki.XWiki} class.
 *
 * @version $Id$
 */
public privileged aspect XWikiCompatibilityAspect
{
    private static Map XWiki.threadMap = new HashMap();

    /**
     * Transform a text in a URL compatible text
     *
     * @param content text to transform
     * @return encoded result
     * @deprecated replaced by Util#encodeURI since 1.3M2
     */
    @Deprecated
    public String XWiki.getURLEncoded(String content)
    {
        try {
            return URLEncoder.encode(content, this.getEncoding());
        } catch (UnsupportedEncodingException e) {
            return content;
        }
    }

    /**
     * @return true for multi-wiki/false for mono-wiki
     * @deprecated replaced by {@link XWiki#isVirtualMode()} since 1.4M1.
     */
    @Deprecated
    public boolean XWiki.isVirtual()
    {
        return this.isVirtualMode();
    }

    /**
     * @deprecated Removed since it isn't used; since 1.5M1.
     */
    @Deprecated
    public static Map XWiki.getThreadMap()
    {
        return XWiki.threadMap;
    }

    /**
     * @deprecated Removed since it isn't used; since 1.5M1.
     */
    @Deprecated
    public static void XWiki.setThreadMap(Map threadMap)
    {
        XWiki.threadMap = threadMap;
    }

    /**
     * @return the cache service.
     * @deprecated replaced by {@link XWiki#getCacheFactory(XWikiContext)} or
     *             {@link XWiki#getLocalCacheFactory(XWikiContext)} since 1.5M2.
     */
    @Deprecated
    public XWikiCacheService XWiki.getCacheService()
    {
        return new XWikiCacheServiceStub(getCacheFactory(), getLocalCacheFactory());
    }

    /**
     * @deprecated replaced by {@link XWiki#getVirtualWikiCache(XWikiContext)} since 1.5M2.
     */
    @Deprecated
    public XWikiCache XWiki.getVirtualWikiMap()
    {
        return new XWikiCacheStub(this.virtualWikiMap);
    }

    /**
     * @deprecated replaced by {@link XWiki#getSpaceCopyright(XWikiContext)} since 2.3M1
     */
    @Deprecated
    public String XWiki.getWebCopyright(XWikiContext context)
    {
        return this.getSpaceCopyright(context);
    }

    /**
     * @deprecated replaced by {@link XWiki#getSpacePreference(String, XWikiContext)} since 2.3M1
     */
    @Deprecated
    public String XWiki.getWebPreference(String preference, XWikiContext context)
    {
        return this.getSpacePreference(preference, context);
    }

    /**
     * @deprecated replaced by {@link XWiki#getSpacePreference(String, String, XWikiContext)} since 2.3M1
     */
    @Deprecated
    public String XWiki.getWebPreference(String preference, String defaultValue, XWikiContext context)
    {
        return this.getSpacePreference(preference, defaultValue, context);
    }

    /**
     * @deprecated replaced by {@link XWiki#getSpacePreference(String, String, String, XWikiContext)} since 2.3M1
     */
    @Deprecated
    public String XWiki.getWebPreference(String preference, String space, String defaultValue, XWikiContext context)
    {
        return this.getSpacePreference(preference, space, defaultValue, context);
    }

    /**
     * @deprecated replaced by {@link XWiki#getSpacePreferenceAsLong(String, XWikiContext)} since 2.3M1
     */
    @Deprecated
    public long XWiki.getWebPreferenceAsLong(String preference, XWikiContext context)
    {
        return this.getSpacePreferenceAsLong(preference, context);
    }

    /**
     * @deprecated replaced by {@link XWiki#getSpacePreferenceAsLong(String, long, XWikiContext)} since 2.3M1
     */
    @Deprecated
    public long XWiki.getWebPreferenceAsLong(String preference, long defaultValue, XWikiContext context)
    {
        return this.getSpacePreferenceAsLong(preference, defaultValue, context);
    }

    /**
     * @deprecated replaced by {@link XWiki#getSpacePreferenceAsInt(String, XWikiContext)} since 2.3M1
     */
    @Deprecated
    public int XWiki.getWebPreferenceAsInt(String preference, XWikiContext context)
    {
        return this.getSpacePreferenceAsInt(preference, context);
    }

    /**
     * @deprecated replaced by {@link XWiki#getSpacePreferenceAsInt(String, int, XWikiContext)} since 2.3M1
     */
    @Deprecated
    public int XWiki.getWebPreferenceAsInt(String preference, int defaultValue, XWikiContext context)
    {
        return this.getSpacePreferenceAsInt(preference, defaultValue, context);
    }

    /**
     * @deprecated replaced by {@link XWiki#copySpaceBetweenWikis(String, String, String, String, XWikiContext)} since
     *             2.3M1
     */
    @Deprecated
    public int XWiki.copyWikiWeb(String space, String sourceWiki, String targetWiki, String language, XWikiContext context)
        throws XWikiException
    {
        return this.copySpaceBetweenWikis(space, sourceWiki, targetWiki, language, context);
    }

    /**
     * @deprecated replaced by
     *             {@link XWiki#copySpaceBetweenWikis(String, String, String, String, boolean, XWikiContext)} since
     *             2.3M1
     */
    @Deprecated
    public int XWiki.copyWikiWeb(String space, String sourceWiki, String targetWiki, String language, boolean clean,
        XWikiContext context) throws XWikiException
    {
        return this.copySpaceBetweenWikis(space, sourceWiki, targetWiki, language, clean, context);
    }

    /**
     * @deprecated replaced by {@link XWiki#getDefaultSpace(XWikiContext)} since 2.3M1
     */
    @Deprecated
    public String XWiki.getDefaultWeb(XWikiContext context)
    {
        return this.getDefaultSpace(context);
    }

    /**
     * @deprecated replaced by {@link XWiki#skipDefaultSpaceInURLs(XWikiContext)} since 2.3M1
     */
    @Deprecated
    public boolean XWiki.useDefaultWeb(XWikiContext context)
    {
        return this.skipDefaultSpaceInURLs(context);
    }

    /**
     * @deprecated use {@link XWikiMessageTool#get(String, List)} instead. You can access message tool using
     *             {@link XWikiContext#getMessageTool()}.
     */
    @Deprecated
    public String getMessage(String item, XWikiContext context)
    {
        XWikiMessageTool msg = context.getMessageTool();
        if (msg == null) {
            return item;
        } else {
            return msg.get(item);
        }
    }

    /**
     * @deprecated use {@link XWikiMessageTool#get(String, List)} instead. You can access message tool using
     *             {@link XWikiContext#getMessageTool()}.
     */
    @Deprecated
    public String parseMessage(String id, XWikiContext context)
    {
        XWikiMessageTool msg = context.getMessageTool();

        return parseContent(msg.get(id), context);
    }

    /**
     * @deprecated use {@link XWikiMessageTool#get(String, List)} instead. You can access message tool using
     *             {@link XWikiContext#getMessageTool()}.
     */
    @Deprecated
    public String parseMessage(XWikiContext context)
    {
        String message = (String) context.get("message");
        if (message == null) {
            return null;
        }

        return parseMessage(message, context);
    }
}


Included ThreadPoolExecutor.

Included ThreadPoolExecutor.

/*
 * Copyright (c) 2013 original authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.eigengo.monitor.agent.akka;

import akka.actor.ActorCell;
import org.eigengo.monitor.agent.AgentConfiguration;
import org.eigengo.monitor.output.CounterInterface;
import scala.concurrent.forkjoin.ForkJoinPool;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * Monitors the performance of the ``ForkJoinPool``. This will need much more tidying up, but it
 * outlines the strategy.
 *
 * The aspect contains advices that will--in the future--monitor the performance of all types of
 * thread pools, giving the users the insight into the threading in their actor systems.
 */
public aspect DispatcherMonitoringAspect extends AbstractMonitoringAspect {
    private final CounterInterface counterInterface;
    private final DispatcherTagger tagger;

    // this is really icky, but it replaces the failing cflowbelow pointcut
    private final Map<Long, String[]> actorCellCflowTags = new ConcurrentHashMap<Long, String[]>();

    /**
     * Constructs this aspects, loads its configuration and instantiates the {@code counterInterface}.
     */
    public DispatcherMonitoringAspect() {
        AgentConfiguration<AkkaAgentConfiguration> configuration = getAgentConfiguration("akka", AkkaAgentConfigurationJapi.apply());
        this.counterInterface = createCounterInterface(configuration.common());
        this.tagger = new DispatcherTagger(configuration.agent().includeRoutees());
    }

    pointcut messageDispatcherDispatch(ActorCell actorCell) : execution(* akka.dispatch.MessageDispatcher+.dispatch(..)) && args(actorCell, *);

    before(ActorCell actorCell) : messageDispatcherDispatch(actorCell) {
        final String[] tags = this.tagger.getTags(actorCell);
        this.actorCellCflowTags.put(Thread.currentThread().getId(), tags);
    }

    /**
     * Advises the ``execute`` method of an ``ExecutorService``, and then branches depending on the
     * exact type of the {@code ExecutorService}. This is slightly better option than having multiple
     * advices for the concrete {@code ExecutorService}s at the moment.
     *
     * Ideally, we would like to use cflowbelow pointcut expression, but that fails
     * in the LTW stage with NoSuchFieldError, because the control flow stack field
     * does not get properly generated.
     */
    before(ExecutorService es) : call(* java.util.concurrent.ExecutorService+.execute(..)) && target(es) {
        final String[] tags = this.actorCellCflowTags.get(Thread.currentThread().getId());
        if (tags == null) {
            // this is execute outside the ActorCell.dispatch cflow. We don't care about that.
            return;
        }

        if (es instanceof ForkJoinPool) forkJoinPool((ForkJoinPool)es, tags);
        else if (es instanceof ThreadPoolExecutor) threadPoolExecutor((ThreadPoolExecutor)es, tags);
    }

    private void forkJoinPool(ForkJoinPool es, String[] tags) {
        this.counterInterface.recordGaugeValue(Aspects.activeThreadCount(), es.getActiveThreadCount(), tags);
        this.counterInterface.recordGaugeValue(Aspects.runningThreadCount(), es.getRunningThreadCount(), tags);

        this.counterInterface.recordGaugeValue(Aspects.poolSize(), es.getPoolSize(), tags);
        this.counterInterface.recordGaugeValue(Aspects.queuedTaskCount(), (int) es.getQueuedTaskCount(), tags);
    }

    private void threadPoolExecutor(ThreadPoolExecutor es, String[] tags) {
        this.counterInterface.recordGaugeValue(Aspects.activeThreadCount(), es.getActiveCount(), tags);
        this.counterInterface.recordGaugeValue(Aspects.runningThreadCount(), es.getActiveCount(), tags);

        this.counterInterface.recordGaugeValue(Aspects.poolSize(), es.getPoolSize(), tags);
        this.counterInterface.recordGaugeValue(Aspects.queuedTaskCount(), es.getQueue().size(), tags);
    }

}

/*
 * Copyright (c) 2013 original authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.eigengo.monitor.agent.akka;

import akka.actor.ActorCell;
import org.eigengo.monitor.agent.AgentConfiguration;
import org.eigengo.monitor.output.CounterInterface;
import scala.concurrent.forkjoin.ForkJoinPool;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Monitors the performance of the ``ForkJoinPool``. This will need much more tidying up, but it
 * outlines the strategy.
 *
 * The aspect contains advices that will--in the future--monitor the performance of all types of
 * thread pools, giving the users the insight into the threading in their actor systems.
 */
public aspect DispatcherMonitoringAspect extends AbstractMonitoringAspect {
    private final CounterInterface counterInterface;
    private final DispatcherTagger tagger;

    // this is really icky, but it replaces the failing cflowbelow pointcut
    private final Map<Long, String[]> actorCellCflowTags = new ConcurrentHashMap<Long, String[]>();

    /**
     * Constructs this aspects, loads its configuration and instantiates the {@code counterInterface}.
     */
    public DispatcherMonitoringAspect() {
        AgentConfiguration<AkkaAgentConfiguration> configuration = getAgentConfiguration("akka", AkkaAgentConfigurationJapi.apply());
        this.counterInterface = createCounterInterface(configuration.common());
        this.tagger = new DispatcherTagger(configuration.agent().includeRoutees());
    }

    pointcut messageDispatcherDispatch(ActorCell actorCell) : execution(* akka.dispatch.MessageDispatcher+.dispatch(..)) && args(actorCell, *);

    before(ActorCell actorCell) : messageDispatcherDispatch(actorCell) {
        final String[] tags = this.tagger.getTags(actorCell);
        this.actorCellCflowTags.put(Thread.currentThread().getId(), tags);
    }

    /**
     * Advises the ``execute`` method of an ``ExecutorService`` if that executor service is the
     * ``ForkJoinPool``.
     *
     * Ideally, we would like to use cflowbelow pointcut expression, but that fails
     * in the LTW stage with NoSuchFieldError
     */
    before(ForkJoinPool es) : call(* java.util.concurrent.ExecutorService+.execute(..)) && target(es) {
        final String[] tags = this.actorCellCflowTags.get(Thread.currentThread().getId());
        if (tags == null) {
            // this is execute without ActorCell.dispatch. We don't care about that.
            return;
        }
        this.counterInterface.recordGaugeValue(Aspects.activeThreadCount(), es.getActiveThreadCount(), tags);
        this.counterInterface.recordGaugeValue(Aspects.runningThreadCount(), es.getRunningThreadCount(), tags);

        this.counterInterface.recordGaugeValue(Aspects.poolSize(), es.getPoolSize(), tags);
        this.counterInterface.recordGaugeValue(Aspects.queuedTaskCount(), (int) es.getQueuedTaskCount(), tags);
    }

}


* change poincuts visible

* change poincuts visible

package ru.agentlab.maia.context.aj;

import ru.agentlab.maia.context.IMaiaContext;

/**
 * Abstract aspect with pointcuts of {@link IMaiaContext} methods
 *
 * @author Shishkin Dmitriy
 *
 */
public abstract aspect AMaiaContext {

	/**
	 * When actual IMaiaContext object is created
	 */
	public pointcut onConstruct() :
		execution(IMaiaContext+.new(..));

	/**
	 * When {@link IMaiaContext} get service object by string identifier
	 *
	 * @param context
	 *            - current context
	 * @param id
	 *            - string identifier of context service
	 */
	public pointcut onGetByString(IMaiaContext context, String id) :
		execution(Object IMaiaContext+.get(String)) &&
		target(context) &&
		args(id);

	/**
	 * When {@link IMaiaContext} get service object by it's type
	 *
	 * @param context
	 *            - current context
	 * @param id
	 *            - type of context service
	 */
	public pointcut onGetByClass(IMaiaContext context, Class<?> id) :
		execution(Object IMaiaContext+.get(Class)) &&
		target(context) &&
		args(id);

	/**
	 * When {@link IMaiaContext} set service object by string identifier
	 *
	 * @param context
	 *            - current context
	 * @param id
	 *            - string identifier of context service
	 * @param obj
	 *            - service object
	 */
	public pointcut onSetByString(IMaiaContext context, String id, Object obj) :
		execution(void IMaiaContext+.set(String, Object)) &&
		target(context) &&
		args(id, obj);

	/**
	 * When {@link IMaiaContext} set service object by it's type
	 *
	 * @param context
	 *            - current context
	 * @param id
	 *            - type of context service
	 * @param obj
	 *            - service object
	 */
	public pointcut onSetByClass(IMaiaContext context, Class<?> id,
			Object obj) :
		execution(void IMaiaContext+.set(Class, Object)) &&
		target(context) &&
		args(id, obj);

	/**
	 * When {@link IMaiaContext} get service object locally by string identifier
	 *
	 * @param context
	 *            - current context
	 * @param id
	 *            - string identifier of context service
	 */
	public pointcut onGetLocalByString(IMaiaContext context, String id) :
		execution(Object IMaiaContext+.getLocal(String)) &&
		target(context) &&
		args(id);

	/**
	 * When {@link IMaiaContext} get service object locally by it's type
	 *
	 * @param context
	 *            - current context
	 * @param id
	 *            - type of context service
	 */
	public pointcut onGetLocalByClass(IMaiaContext context, Class<?> id) :
		execution(Object IMaiaContext+.getLocal(Class)) &&
		target(context) &&
		args(id);

	/**
	 * When {@link IMaiaContext} remove service object by string identifier
	 *
	 * @param context
	 *            - current context
	 * @param id
	 *            - string identifier of context service to be removed
	 */
	public pointcut onRemoveByString(IMaiaContext context, String id) :
		execution(void IMaiaContext+.remove(String)) &&
		target(context) &&
		args(id);

	/**
	 * When {@link IMaiaContext} remove service object by it's type
	 *
	 * @param context
	 *            - current context
	 * @param id
	 *            - type of context service
	 */
	public pointcut onRemoveByClass(IMaiaContext context, Class<?> id) :
		execution(void IMaiaContext+.remove(Class)) &&
		target(context) &&
		args(id);

	/**
	 * When {@link IMaiaContext} retrieve all it's childs contexts
	 *
	 * @param context
	 *            - current context
	 */
	public pointcut onGetChilds(IMaiaContext context) :
		execution(Iterable<IMaiaContext>  IMaiaContext+.getChilds()) &&
		target(context);

	/**
	 * When {@link IMaiaContext} retrieve parent context
	 *
	 * @param context
	 *            - current context
	 */
	public pointcut onGetParent(IMaiaContext context) :
		execution(IMaiaContext IMaiaContext+.getParent(..)) &&
		target(context);

}

package ru.agentlab.maia.context.aj;

import ru.agentlab.maia.context.IMaiaContext;

/**
 * Abstract aspect with pointcuts of {@link IMaiaContext} methods
 *
 * @author Shishkin Dmitriy
 *
 */
public abstract aspect AMaiaContext {

	/**
	 * When actual IMaiaContext object is created
	 */
	public pointcut onConstruct() :
		execution(IMaiaContext+.new(..));

	/**
	 * When {@link IMaiaContext} get service object by string identifier
	 *
	 * @param context
	 *            - current context
	 * @param id
	 *            - string identifier of context service
	 */
	public pointcut onGetByString(IMaiaContext context, String id) :
		execution(Object IMaiaContext+.get(String)) &&
		target(context) &&
		args(id);

	/**
	 * When {@link IMaiaContext} get service object by it's type
	 *
	 * @param context
	 *            - current context
	 * @param id
	 *            - type of context service
	 */
	public pointcut onGetByClass(IMaiaContext context, Class<?> id) :
		execution(Object IMaiaContext+.get(Class)) &&
		target(context) &&
		args(id);

	/**
	 * When {@link IMaiaContext} set service object by string identifier
	 *
	 * @param context
	 *            - current context
	 * @param id
	 *            - string identifier of context service
	 * @param obj
	 *            - service object
	 */
	protected pointcut onSetByString(IMaiaContext context, String id, Object obj) :
		execution(void IMaiaContext+.set(String, Object)) &&
		target(context) &&
		args(id, obj);

	/**
	 * When {@link IMaiaContext} set service object by it's type
	 *
	 * @param context
	 *            - current context
	 * @param id
	 *            - type of context service
	 * @param obj
	 *            - service object
	 */
	protected pointcut onSetByClass(IMaiaContext context, Class<?> id,
			Object obj) :
		execution(void IMaiaContext+.set(Class, Object)) &&
		target(context) &&
		args(id, obj);

	/**
	 * When {@link IMaiaContext} get service object locally by string identifier
	 *
	 * @param context
	 *            - current context
	 * @param id
	 *            - string identifier of context service
	 */
	public pointcut onGetLocalByString(IMaiaContext context, String id) :
		execution(Object IMaiaContext+.getLocal(String)) &&
		target(context) &&
		args(id);

	/**
	 * When {@link IMaiaContext} get service object locally by it's type
	 *
	 * @param context
	 *            - current context
	 * @param id
	 *            - type of context service
	 */
	public pointcut onGetLocalByClass(IMaiaContext context, Class<?> id) :
		execution(Object IMaiaContext+.getLocal(Class)) &&
		target(context) &&
		args(id);

	/**
	 * When {@link IMaiaContext} remove service object by string identifier
	 *
	 * @param context
	 *            - current context
	 * @param id
	 *            - string identifier of context service to be removed
	 */
	public pointcut onRemoveByString(IMaiaContext context, String id) :
		execution(void IMaiaContext+.remove(String)) &&
		target(context) &&
		args(id);

	/**
	 * When {@link IMaiaContext} remove service object by it's type
	 *
	 * @param context
	 *            - current context
	 * @param id
	 *            - type of context service
	 */
	public pointcut onRemoveByClass(IMaiaContext context, Class<?> id) :
		execution(void IMaiaContext+.remove(Class)) &&
		target(context) &&
		args(id);

	/**
	 * When {@link IMaiaContext} retrieve all it's childs contexts
	 *
	 * @param context
	 *            - current context
	 */
	public pointcut onGetChilds(IMaiaContext context) :
		execution(Iterable<IMaiaContext>  IMaiaContext+.getChilds()) &&
		target(context);

	/**
	 * When {@link IMaiaContext} retrieve parent context
	 *
	 * @param context
	 *            - current context
	 */
	public pointcut onGetParent(IMaiaContext context) :
		execution(IMaiaContext IMaiaContext+.getParent(..)) &&
		target(context);

}


syso on Aspect

syso on Aspect

/**
 * Copyright (C) 2011-2013 Thales Services - ThereSIS - All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package com.thalesgroup.authzforce.audit.aspect;

import java.io.StringWriter;
import java.net.URI;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;

import oasis.names.tc.xacml._3_0.core.schema.wd_17.Attribute;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.Policy;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.Result;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.Rule;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sun.xacml.BasicEvaluationCtx;
import com.sun.xacml.attr.DateTimeAttribute;
import com.sun.xacml.attr.xacmlv3.AttributeValue;
import com.sun.xacml.cond.xacmlv3.EvaluationResult;
import com.thalesgroup.authzforce.audit.AttributesResolved;
import com.thalesgroup.authzforce.audit.AuditLogs;
import com.thalesgroup.authzforce.audit.annotations.Audit;
import com.thalesgroup.authzforce.audit.schema.pdp.AuditLog;
import com.thalesgroup.authzforce.audit.schema.pdp.AuditedPolicy;
import com.thalesgroup.authzforce.audit.schema.pdp.AuditedResult;
import com.thalesgroup.authzforce.audit.schema.pdp.AuditedRule;
import com.thalesgroup.authzforce.xacml.schema.XACMLAttributeId;
import com.thalesgroup.authzforce.xacml.schema.XACMLDatatypes;

@Aspect
public class AuditAspect {

	private static final Logger LOGGER = LoggerFactory
			.getLogger(AuditAspect.class);
	private static final DateFormat dateFormat = new SimpleDateFormat(
			"dd-MM-yyyy HH:mm:ss.SSSSSSSSS");
	private static final DateFormat dateFormatWOoNano = new SimpleDateFormat(
			"dd-MM-yyyy HH:mm:ss");

	@Pointcut("execution (@com.thalesgroup.authzforce.audit.annotations * *.*(..))")
	public void searchAnnotation() {

	}

	@AfterReturning(value = "@annotation(annotation)", returning = "result")
	public void doAuditLog(Audit annotation, JoinPoint jp, Object result) {
		switch (annotation.type()) {
		case RULE:
			AuditLog audit = new AuditLog();
			AuditedRule auditedRule = new AuditedRule();
			auditedRule.setId(((Rule) jp.getTarget()).getRuleId());
			auditedRule.setResult(AuditedResult.fromValue(((Result) result)
					.getDecision().value()));
			for (Object arg : jp.getArgs()) {
				if (arg instanceof BasicEvaluationCtx) {
					audit.setDate(this.formatDate(((BasicEvaluationCtx) arg)
							.getCurrentDateTime()));
					audit.setRequest(((BasicEvaluationCtx) arg).getRequest());
					audit = this.setAttributes(audit, ((BasicEvaluationCtx) arg));
				}
			}

			audit.getRules().add(auditedRule);

			AuditLogs.getInstance().addAudit(audit);
			break;

		case POLICY:
			audit = new AuditLog();
			AuditedPolicy auditedPolicy = new AuditedPolicy();
			auditedPolicy.setId(((Policy) jp.getTarget()).getPolicyId());
			auditedPolicy.setRuleCombiningAlgorithm(((Policy) jp.getTarget())
					.getRuleCombiningAlgId());
			auditedPolicy.setResult(AuditedResult.fromValue(((Result) result)
					.getDecision().value()));
			for (Object arg : jp.getArgs()) {
				if (arg instanceof BasicEvaluationCtx) {
					audit.setDate(this.formatDate(((BasicEvaluationCtx) arg)
							.getCurrentDateTime()));
					audit.setRequest(((BasicEvaluationCtx) arg).getRequest());
					audit = this.setAttributes(audit, ((BasicEvaluationCtx) arg));;
				}
			}
			audit.getMatchedPolicies().add(auditedPolicy);
			AuditLogs.getInstance().addAudit(audit);
			break;

		case ATTRIBUTE:
			audit = new AuditLog();
			AttributesResolved attrResolved = new AttributesResolved();
			for (Object arg : jp.getArgs()) {
				if (arg instanceof BasicEvaluationCtx) {
					audit.setDate(this.formatDate(((BasicEvaluationCtx) arg)
							.getCurrentDateTime()));
					audit.setRequest(((BasicEvaluationCtx) arg).getRequest());
					audit = this.setAttributes(audit, ((BasicEvaluationCtx) arg));
				}
			}
			attrResolved.setAttributeValue(((EvaluationResult) result)
					.getAttributeValue());
			break;

		// Used to display and clean the audit log pool
		case DISPLAY:
			LOGGER.info(AuditLogs.getInstance().toString());
			System.out.println(AuditLogs.getInstance().toString());
			break;
		default:
			System.err.println("Type unknown: " + annotation.type());
			;
		}
	}

	private AuditLog setAttributes(AuditLog audit,
			BasicEvaluationCtx basicEvaluationCtx) {
		if (((BasicEvaluationCtx) basicEvaluationCtx).getSubjectAttribute(
				URI.create(XACMLDatatypes.XACML_DATATYPE_STRING.value()),
				URI.create(XACMLAttributeId.XACML_SUBJECT_SUBJECT_ID.value()),
				URI.create(XACMLAttributeId.SUBJECT_CATEGORY.value())) != null) {
			if(((BasicEvaluationCtx) basicEvaluationCtx).getSubjectAttribute(
						URI.create(XACMLDatatypes.XACML_DATATYPE_STRING.value()),
						URI.create(XACMLAttributeId.XACML_SUBJECT_SUBJECT_ID.value()),
						URI.create(XACMLAttributeId.SUBJECT_CATEGORY.value())).getAttributeValue().getContent().size() > 0) {
							String subjectId = (String) ((BasicEvaluationCtx) basicEvaluationCtx).getSubjectAttribute(
									URI.create(XACMLDatatypes.XACML_DATATYPE_STRING.value()),
									URI.create(XACMLAttributeId.XACML_SUBJECT_SUBJECT_ID.value()),
									URI.create(XACMLAttributeId.SUBJECT_CATEGORY.value())).getAttributeValue().getContent().get(0);

							audit.setSubjectId(subjectId);
						}
		}

		AttributeValue resourceId = ((BasicEvaluationCtx) basicEvaluationCtx).getResourceId();
		if(resourceId.getContent().size() > 0) {
			audit.setResourceId(String.valueOf(resourceId.getContent().get(0)));
		}

		// FIXME: Set the ActionId attribute
		// audit.setActionId();

		return audit;
	}

	private String formatDate(DateTimeAttribute currentDateTime) {
		String date = dateFormatWOoNano.format(currentDateTime.getValue())
				+ "." + String.valueOf(currentDateTime.getNanoseconds());

		return date;
	}
}

/**
 * Copyright (C) 2011-2013 Thales Services - ThereSIS - All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package com.thalesgroup.authzforce.audit.aspect;

import java.io.StringWriter;
import java.net.URI;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;

import oasis.names.tc.xacml._3_0.core.schema.wd_17.Attribute;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.Policy;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.Result;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.Rule;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sun.xacml.BasicEvaluationCtx;
import com.sun.xacml.attr.DateTimeAttribute;
import com.sun.xacml.attr.xacmlv3.AttributeValue;
import com.sun.xacml.cond.xacmlv3.EvaluationResult;
import com.thalesgroup.authzforce.audit.AttributesResolved;
import com.thalesgroup.authzforce.audit.AuditLogs;
import com.thalesgroup.authzforce.audit.annotations.Audit;
import com.thalesgroup.authzforce.audit.schema.pdp.AuditLog;
import com.thalesgroup.authzforce.audit.schema.pdp.AuditedPolicy;
import com.thalesgroup.authzforce.audit.schema.pdp.AuditedResult;
import com.thalesgroup.authzforce.audit.schema.pdp.AuditedRule;
import com.thalesgroup.authzforce.xacml.schema.XACMLAttributeId;
import com.thalesgroup.authzforce.xacml.schema.XACMLDatatypes;

@Aspect
public class AuditAspect {

	private static final Logger LOGGER = LoggerFactory
			.getLogger(AuditAspect.class);
	private static final DateFormat dateFormat = new SimpleDateFormat(
			"dd-MM-yyyy HH:mm:ss.SSSSSSSSS");
	private static final DateFormat dateFormatWOoNano = new SimpleDateFormat(
			"dd-MM-yyyy HH:mm:ss");

	@Pointcut("execution (@com.thalesgroup.authzforce.audit.annotations * *.*(..))")
	public void searchAnnotation() {

	}

	@AfterReturning(value = "@annotation(annotation)", returning = "result")
	public void doAuditLog(Audit annotation, JoinPoint jp, Object result) {
		switch (annotation.type()) {
		case RULE:
			AuditLog audit = new AuditLog();
			AuditedRule auditedRule = new AuditedRule();
			auditedRule.setId(((Rule) jp.getTarget()).getRuleId());
			auditedRule.setResult(AuditedResult.fromValue(((Result) result)
					.getDecision().value()));
			for (Object arg : jp.getArgs()) {
				if (arg instanceof BasicEvaluationCtx) {
					audit.setDate(this.formatDate(((BasicEvaluationCtx) arg)
							.getCurrentDateTime()));
					audit.setRequest(((BasicEvaluationCtx) arg).getRequest());
					audit = this.setAttributes(audit, ((BasicEvaluationCtx) arg));
				}
			}

			audit.getRules().add(auditedRule);

			AuditLogs.getInstance().addAudit(audit);
			break;

		case POLICY:
			audit = new AuditLog();
			AuditedPolicy auditedPolicy = new AuditedPolicy();
			auditedPolicy.setId(((Policy) jp.getTarget()).getPolicyId());
			auditedPolicy.setRuleCombiningAlgorithm(((Policy) jp.getTarget())
					.getRuleCombiningAlgId());
			auditedPolicy.setResult(AuditedResult.fromValue(((Result) result)
					.getDecision().value()));
			for (Object arg : jp.getArgs()) {
				if (arg instanceof BasicEvaluationCtx) {
					audit.setDate(this.formatDate(((BasicEvaluationCtx) arg)
							.getCurrentDateTime()));
					audit.setRequest(((BasicEvaluationCtx) arg).getRequest());
					audit = this.setAttributes(audit, ((BasicEvaluationCtx) arg));;
				}
			}
			audit.getMatchedPolicies().add(auditedPolicy);
			AuditLogs.getInstance().addAudit(audit);
			break;

		case ATTRIBUTE:
			audit = new AuditLog();
			AttributesResolved attrResolved = new AttributesResolved();
			for (Object arg : jp.getArgs()) {
				if (arg instanceof BasicEvaluationCtx) {
					audit.setDate(this.formatDate(((BasicEvaluationCtx) arg)
							.getCurrentDateTime()));
					audit.setRequest(((BasicEvaluationCtx) arg).getRequest());
					audit = this.setAttributes(audit, ((BasicEvaluationCtx) arg));
				}
			}
			attrResolved.setAttributeValue(((EvaluationResult) result)
					.getAttributeValue());
			break;

		// Used to display and clean the audit log pool
		case DISPLAY:
			LOGGER.info(AuditLogs.getInstance().toString());
			break;
		default:
			System.err.println("Type unknown: " + annotation.type());
			;
		}
	}

	private AuditLog setAttributes(AuditLog audit,
			BasicEvaluationCtx basicEvaluationCtx) {
		if (((BasicEvaluationCtx) basicEvaluationCtx).getSubjectAttribute(
				URI.create(XACMLDatatypes.XACML_DATATYPE_STRING.value()),
				URI.create(XACMLAttributeId.XACML_SUBJECT_SUBJECT_ID.value()),
				URI.create(XACMLAttributeId.SUBJECT_CATEGORY.value())) != null) {
			if(((BasicEvaluationCtx) basicEvaluationCtx).getSubjectAttribute(
						URI.create(XACMLDatatypes.XACML_DATATYPE_STRING.value()),
						URI.create(XACMLAttributeId.XACML_SUBJECT_SUBJECT_ID.value()),
						URI.create(XACMLAttributeId.SUBJECT_CATEGORY.value())).getAttributeValue().getContent().size() > 0) {
							String subjectId = (String) ((BasicEvaluationCtx) basicEvaluationCtx).getSubjectAttribute(
									URI.create(XACMLDatatypes.XACML_DATATYPE_STRING.value()),
									URI.create(XACMLAttributeId.XACML_SUBJECT_SUBJECT_ID.value()),
									URI.create(XACMLAttributeId.SUBJECT_CATEGORY.value())).getAttributeValue().getContent().get(0);

							audit.setSubjectId(subjectId);
						}
		}

		AttributeValue resourceId = ((BasicEvaluationCtx) basicEvaluationCtx).getResourceId();
		if(resourceId.getContent().size() > 0) {
			audit.setResourceId(String.valueOf(resourceId.getContent().get(0)));
		}

		// FIXME: Set the ActionId attribute
		// audit.setActionId();

		return audit;
	}

	private String formatDate(DateTimeAttribute currentDateTime) {
		String date = dateFormatWOoNano.format(currentDateTime.getValue())
				+ "." + String.valueOf(currentDateTime.getNanoseconds());

		return date;
	}
}


Comment out some superfluous baggage logging

package edu.brown.cs.systems.xtrace.logging;

import com.google.protobuf.ByteString;

import edu.brown.cs.systems.baggage.Baggage;
import edu.brown.cs.systems.baggage.DetachedBaggage;
import edu.brown.cs.systems.xtrace.XTrace;

/** Invoke X-Trace APIs when baggage is set and unset */
public aspect BaggageWrappers {

    static XTraceLogger xtrace = XTrace.getLogger(BaggageWrappers.class);

//    after(): call(void Baggage.start()) && if(xtrace.valid()) {
//        xtrace.log(thisJoinPointStaticPart, "Baggage started with Baggage.start()");
//    }
//
//    after(): (
//            call(void Baggage.start(DetachedBaggage)) ||
//            call(void Baggage.start(ByteString)) ||
//            call(void Baggage.start(byte[])) ||
//            call(void Baggage.start(String))
//            ) && if(xtrace.valid()) {
//        xtrace.log(thisJoinPointStaticPart, "Resumed previously detached baggage");
//    }

//    before(): call(DetachedBaggage Baggage.swap(..)) && if(xtrace.valid()) {
//        xtrace.log(thisJoinPointStaticPart, "Detaching current baggage with Baggage.swap()");
//    }

//    after(): call(DetachedBaggage Baggage.swap(..)) && if(xtrace.valid()) {
//        xtrace.log(thisJoinPointStaticPart, "Baggage started with Baggage.swap()");
//    }

//    before(): call(void Baggage.discard()) && if(xtrace.valid()) {
//        xtrace.log(thisJoinPointStaticPart, "Discarding baggage with Baggage.discard()");
//    }

//    before(): call(DetachedBaggage Baggage.stop()) && if(xtrace.valid()) {
//        xtrace.log(thisJoinPointStaticPart, "Detaching current baggage with Baggage.stop()");
//    }

    before(): call(DetachedBaggage Baggage.fork()) && if(xtrace.valid()) {
        xtrace.log(thisJoinPointStaticPart, "Forking current baggage with Baggage.fork()");
    }

    after(): (
            call(void Baggage.join(DetachedBaggage)) ||
            call(void Baggage.join(ByteString)) ||
            call(void Baggage.join(byte[])) ||
            call(void Baggage.join(String))
            ) && if(xtrace.valid()) {
        xtrace.log(thisJoinPointStaticPart, "Merged current baggage with other baggage");
    }

}

package edu.brown.cs.systems.xtrace.logging;

import com.google.protobuf.ByteString;

import edu.brown.cs.systems.baggage.Baggage;
import edu.brown.cs.systems.baggage.DetachedBaggage;
import edu.brown.cs.systems.xtrace.XTrace;

/** Invoke X-Trace APIs when baggage is set and unset */
public aspect BaggageWrappers {

    static XTraceLogger xtrace = XTrace.getLogger(BaggageWrappers.class);

    after(): call(void Baggage.start()) && if(xtrace.valid()) {
        xtrace.log(thisJoinPointStaticPart, "Baggage started with Baggage.start()");
    }

    after(): (
            call(void Baggage.start(DetachedBaggage)) ||
            call(void Baggage.start(ByteString)) ||
            call(void Baggage.start(byte[])) ||
            call(void Baggage.start(String))
            ) && if(xtrace.valid()) {
        xtrace.log(thisJoinPointStaticPart, "Resumed previously detached baggage");
    }

    before(): call(DetachedBaggage Baggage.swap(..)) && if(xtrace.valid()) {
        xtrace.log(thisJoinPointStaticPart, "Detaching current baggage with Baggage.swap()");
    }

    after(): call(DetachedBaggage Baggage.swap(..)) && if(xtrace.valid()) {
        xtrace.log(thisJoinPointStaticPart, "Baggage started with Baggage.swap()");
    }

    before(): call(void Baggage.discard()) && if(xtrace.valid()) {
        xtrace.log(thisJoinPointStaticPart, "Discarding baggage with Baggage.discard()");
    }

    before(): call(DetachedBaggage Baggage.stop()) && if(xtrace.valid()) {
        xtrace.log(thisJoinPointStaticPart, "Detaching current baggage with Baggage.stop()");
    }

    before(): call(DetachedBaggage Baggage.fork()) && if(xtrace.valid()) {
        xtrace.log(thisJoinPointStaticPart, "Forking current baggage with Baggage.fork()");
    }

    after(): (
            call(void Baggage.join(DetachedBaggage)) ||
            call(void Baggage.join(ByteString)) ||
            call(void Baggage.join(byte[])) ||
            call(void Baggage.join(String))
            ) && if(xtrace.valid()) {
        xtrace.log(thisJoinPointStaticPart, "Merged current baggage with other baggage");
    }

}


Event printing commented

Event printing commented

package benchmark.competition.java.larva.monitoring;

import monitoring.impl.MonitorFactory;
import monitoring.intf.Monitor;
import properties.Property;
import properties.competition.Larva;
import structure.impl.other.Verdict;
import structure.intf.QEA;
import benchmark.competition.java.larva.transactionsystem.UserSession;

public aspect LarvaTenAspect {

	private final Monitor monitor;

	private final int OPEN_SESSION = 1;
	private final int CLOSE_SESSION = 2;
	private final int LOG = 3;

	public LarvaTenAspect() {
		QEA qea = new Larva().make(Property.LARVA_TEN);
		monitor = MonitorFactory.create(qea);
	}

	pointcut openSession(UserSession session) :
		call(void UserSession.openSession()) && target(session);

	pointcut closeSession(UserSession session) :
		call(void UserSession.closeSession()) && target(session);

	pointcut log(UserSession session) :
		call(void UserSession.log(String)) && target(session);

	before(UserSession session) : openSession(session) {
//		System.out.println(">> openSession(" + session.getOwner() + ")");
		Verdict verdict = monitor.step(OPEN_SESSION, session.getOwner());
		if (verdict == Verdict.FAILURE || verdict == Verdict.WEAK_FAILURE) {
			System.err.println("Violation in Larva 10. [userId="
					+ session.getOwner() + "] [sid=" + session.getId()
					+ "]. Logging can only be made to an active session.");
		}
	};

	before(UserSession session) : closeSession(session) {
//		System.out.println(">> closeSession(" + session.getOwner() + ")");
		Verdict verdict = monitor.step(CLOSE_SESSION, session.getOwner());
		if (verdict == Verdict.FAILURE || verdict == Verdict.WEAK_FAILURE) {
			System.err.println("Violation in Larva 10. [userId="
					+ session.getOwner() + "] [sid=" + session.getId()
					+ "]. Logging can only be made to an active session.");
		}
	};

	before(UserSession session) : log(session) {
//		System.out.println(">> log(" + session.getOwner() + ")");
		Verdict verdict = monitor.step(LOG, session.getOwner());
		if (verdict == Verdict.FAILURE || verdict == Verdict.WEAK_FAILURE) {
			System.err.println("Violation in Larva 10. [userId="
					+ session.getOwner() + "] [sid=" + session.getId()
					+ "]. Logging can only be made to an active session.");
		}
	};
}

package benchmark.competition.java.larva.monitoring;

import monitoring.impl.MonitorFactory;
import monitoring.intf.Monitor;
import properties.Property;
import properties.competition.Larva;
import structure.impl.other.Verdict;
import structure.intf.QEA;
import benchmark.competition.java.larva.transactionsystem.UserSession;

public aspect LarvaTenAspect {

	private final Monitor monitor;

	private final int OPEN_SESSION = 1;
	private final int CLOSE_SESSION = 2;
	private final int LOG = 3;

	public LarvaTenAspect() {
		QEA qea = new Larva().make(Property.LARVA_TEN);
		monitor = MonitorFactory.create(qea);
	}

	pointcut openSession(UserSession session) :
		call(void UserSession.openSession()) && target(session);

	pointcut closeSession(UserSession session) :
		call(void UserSession.closeSession()) && target(session);

	pointcut log(UserSession session) :
		call(void UserSession.log(String)) && target(session);

	before(UserSession session) : openSession(session) {
		System.out.println(">> openSession(" + session.getOwner() + ")");
		Verdict verdict = monitor.step(OPEN_SESSION, session.getOwner());
		if (verdict == Verdict.FAILURE || verdict == Verdict.WEAK_FAILURE) {
			System.err.println("Violation in Larva 10. [userId="
					+ session.getOwner() + "] [sid=" + session.getId()
					+ "]. Logging can only be made to an active session.");
		}
	};

	before(UserSession session) : closeSession(session) {
		System.out.println(">> closeSession(" + session.getOwner() + ")");
		Verdict verdict = monitor.step(CLOSE_SESSION, session.getOwner());
		if (verdict == Verdict.FAILURE || verdict == Verdict.WEAK_FAILURE) {
			System.err.println("Violation in Larva 10. [userId="
					+ session.getOwner() + "] [sid=" + session.getId()
					+ "]. Logging can only be made to an active session.");
		}
	};

	before(UserSession session) : log(session) {
		System.out.println(">> log(" + session.getOwner() + ")");
		Verdict verdict = monitor.step(LOG, session.getOwner());
		if (verdict == Verdict.FAILURE || verdict == Verdict.WEAK_FAILURE) {
			System.err.println("Violation in Larva 10. [userId="
					+ session.getOwner() + "] [sid=" + session.getId()
					+ "]. Logging can only be made to an active session.");
		}
	};
}


Fixed method count in AbstractMethodMockingControl's IllegalStateException message

Issue: SPR-10885
(cherry picked from commit 5596154)

/*
 * Copyright 2002-2013 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.mock.staticmock;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * Abstract aspect to enable mocking of methods picked out by a pointcut.
 * Sub-aspects must define the mockStaticsTestMethod() pointcut to
 * indicate call stacks when mocking should be triggered, and the
 * methodToMock() pointcut to pick out a method invocations to mock.
 *
 * @author Rod Johnson
 * @author Ramnivas Laddad
 */
public abstract aspect AbstractMethodMockingControl percflow(mockStaticsTestMethod()) {

	protected abstract pointcut mockStaticsTestMethod();

	protected abstract pointcut methodToMock();

	private boolean recording = true;

	static enum CallResponse { nothing, return_, throw_ };

	// Represents a list of expected calls to static entity methods
	// Public to allow inserted code to access: is this normal??
	public class Expectations {

		// Represents an expected call to a static entity method
		private class Call {
			private final String signature;
			private final Object[] args;

			private Object responseObject; // return value or throwable
			private CallResponse responseType = CallResponse.nothing;

			public Call(String name, Object[] args) {
				this.signature = name;
				this.args = args;
			}

			public boolean hasResponseSpecified() {
				return responseType != CallResponse.nothing;
			}

			public void setReturnVal(Object retVal) {
				this.responseObject = retVal;
				responseType = CallResponse.return_;
			}

			public void setThrow(Throwable throwable) {
				this.responseObject = throwable;
				responseType = CallResponse.throw_;
			}

			public Object returnValue(String lastSig, Object[] args) {
				checkSignature(lastSig, args);
				return responseObject;
			}

			public Object throwException(String lastSig, Object[] args) {
				checkSignature(lastSig, args);
				throw (RuntimeException)responseObject;
			}

			private void checkSignature(String lastSig, Object[] args) {
				if (!signature.equals(lastSig)) {
					throw new IllegalArgumentException("Signature doesn't match");
				}
				if (!Arrays.equals(this.args, args)) {
					throw new IllegalArgumentException("Arguments don't match");
				}
			}
		}

		private List<Call> calls = new LinkedList<Call>();

		// Calls already verified
		private int verified;

		public void verify() {
			if (verified != calls.size()) {
				throw new IllegalStateException("Expected " + calls.size() + " calls, received " + verified);
			}
		}

		/**
		 * Validate the call and provide the expected return value.
		 */
		public Object respond(String lastSig, Object[] args) {
			Call call = nextCall();
			CallResponse responseType = call.responseType;
			if (responseType == CallResponse.return_) {
				return call.returnValue(lastSig, args);
			}
			else if (responseType == CallResponse.throw_) {
				return call.throwException(lastSig, args);
			}
			else if (responseType == CallResponse.nothing) {
				// do nothing
			}
			throw new IllegalStateException("Behavior of " + call + " not specified");
		}

		private Call nextCall() {
			verified++;
			if (verified > calls.size()) {
				throw new IllegalStateException("Expected " + calls.size() + " calls, received " + verified);
			}
			return calls.get(verified);
		}

		public void expectCall(String lastSig, Object lastArgs[]) {
			Call call = new Call(lastSig, lastArgs);
			calls.add(call);
		}

		public boolean hasCalls() {
			return !calls.isEmpty();
		}

		public void expectReturn(Object retVal) {
			Call call = calls.get(calls.size() - 1);
			if (call.hasResponseSpecified()) {
				throw new IllegalStateException("No static method invoked before setting return value");
			}
			call.setReturnVal(retVal);
		}

		public void expectThrow(Throwable throwable) {
			Call call = calls.get(calls.size() - 1);
			if (call.hasResponseSpecified()) {
				throw new IllegalStateException("No static method invoked before setting throwable");
			}
			call.setThrow(throwable);
		}
	}

	private Expectations expectations = new Expectations();

	after() returning : mockStaticsTestMethod() {
		if (recording && (expectations.hasCalls())) {
			throw new IllegalStateException(
					"Calls recorded, yet playback state never reached: Create expectations then call "
							+ this.getClass().getSimpleName() + ".playback()");
		}
		expectations.verify();
	}

	Object around() : methodToMock() && cflowbelow(mockStaticsTestMethod()) {
		if (recording) {
			expectations.expectCall(thisJoinPointStaticPart.toLongString(), thisJoinPoint.getArgs());
			// Return value doesn't matter
			return null;
		}
		else {
			return expectations.respond(thisJoinPointStaticPart.toLongString(), thisJoinPoint.getArgs());
		}
	}

	public void expectReturnInternal(Object retVal) {
		if (!recording) {
			throw new IllegalStateException("Not recording: Cannot set return value");
		}
		expectations.expectReturn(retVal);
	}

	public void expectThrowInternal(Throwable throwable) {
		if (!recording) {
			throw new IllegalStateException("Not recording: Cannot set throwable value");
		}
		expectations.expectThrow(throwable);
	}

	public void playbackInternal() {
		recording = false;
	}

}

/*
 * Copyright 2002-2013 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.mock.staticmock;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * Abstract aspect to enable mocking of methods picked out by a pointcut.
 * Sub-aspects must define the mockStaticsTestMethod() pointcut to
 * indicate call stacks when mocking should be triggered, and the
 * methodToMock() pointcut to pick out a method invocations to mock.
 *
 * @author Rod Johnson
 * @author Ramnivas Laddad
 */
public abstract aspect AbstractMethodMockingControl percflow(mockStaticsTestMethod()) {

	protected abstract pointcut mockStaticsTestMethod();

	protected abstract pointcut methodToMock();

	private boolean recording = true;

	static enum CallResponse { nothing, return_, throw_ };

	// Represents a list of expected calls to static entity methods
	// Public to allow inserted code to access: is this normal??
	public class Expectations {

		// Represents an expected call to a static entity method
		private class Call {
			private final String signature;
			private final Object[] args;

			private Object responseObject; // return value or throwable
			private CallResponse responseType = CallResponse.nothing;

			public Call(String name, Object[] args) {
				this.signature = name;
				this.args = args;
			}

			public boolean hasResponseSpecified() {
				return responseType != CallResponse.nothing;
			}

			public void setReturnVal(Object retVal) {
				this.responseObject = retVal;
				responseType = CallResponse.return_;
			}

			public void setThrow(Throwable throwable) {
				this.responseObject = throwable;
				responseType = CallResponse.throw_;
			}

			public Object returnValue(String lastSig, Object[] args) {
				checkSignature(lastSig, args);
				return responseObject;
			}

			public Object throwException(String lastSig, Object[] args) {
				checkSignature(lastSig, args);
				throw (RuntimeException)responseObject;
			}

			private void checkSignature(String lastSig, Object[] args) {
				if (!signature.equals(lastSig)) {
					throw new IllegalArgumentException("Signature doesn't match");
				}
				if (!Arrays.equals(this.args, args)) {
					throw new IllegalArgumentException("Arguments don't match");
				}
			}
		}

		private List<Call> calls = new LinkedList<Call>();

		// Calls already verified
		private int verified;

		public void verify() {
			if (verified != calls.size()) {
				throw new IllegalStateException("Expected " + calls.size()
						+ " calls, received " + verified);
			}
		}

		/**
		 * Validate the call and provide the expected return value
		 * @param lastSig
		 * @param args
		 * @return
		 */
		public Object respond(String lastSig, Object[] args) {
			Call call = nextCall();
			CallResponse responseType = call.responseType;
			if (responseType == CallResponse.return_) {
				return call.returnValue(lastSig, args);
			} else if(responseType == CallResponse.throw_) {
				return (RuntimeException)call.throwException(lastSig, args);
			} else if(responseType == CallResponse.nothing) {
				// do nothing
			}
			throw new IllegalStateException("Behavior of " + call + " not specified");
		}

		private Call nextCall() {
			if (verified > calls.size() - 1) {
				throw new IllegalStateException("Expected " + calls.size()
						+ " calls, received " + verified);
			}
			return calls.get(verified++);
		}

		public void expectCall(String lastSig, Object lastArgs[]) {
			Call call = new Call(lastSig, lastArgs);
			calls.add(call);
		}

		public boolean hasCalls() {
			return !calls.isEmpty();
		}

		public void expectReturn(Object retVal) {
			Call call = calls.get(calls.size() - 1);
			if (call.hasResponseSpecified()) {
				throw new IllegalStateException("No static method invoked before setting return value");
			}
			call.setReturnVal(retVal);
		}

		public void expectThrow(Throwable throwable) {
			Call call = calls.get(calls.size() - 1);
			if (call.hasResponseSpecified()) {
				throw new IllegalStateException("No static method invoked before setting throwable");
			}
			call.setThrow(throwable);
		}
	}

	private Expectations expectations = new Expectations();

	after() returning : mockStaticsTestMethod() {
		if (recording && (expectations.hasCalls())) {
			throw new IllegalStateException(
					"Calls recorded, yet playback state never reached: Create expectations then call "
							+ this.getClass().getSimpleName() + ".playback()");
		}
		expectations.verify();
	}

	Object around() : methodToMock() && cflowbelow(mockStaticsTestMethod()) {
		if (recording) {
			expectations.expectCall(thisJoinPointStaticPart.toLongString(), thisJoinPoint.getArgs());
			// Return value doesn't matter
			return null;
		} else {
			return expectations.respond(thisJoinPointStaticPart.toLongString(), thisJoinPoint.getArgs());
		}
	}

	public void expectReturnInternal(Object retVal) {
		if (!recording) {
			throw new IllegalStateException("Not recording: Cannot set return value");
		}
		expectations.expectReturn(retVal);
	}

	public void expectThrowInternal(Throwable throwable) {
		if (!recording) {
			throw new IllegalStateException("Not recording: Cannot set throwable value");
		}
		expectations.expectThrow(throwable);
	}

	public void playbackInternal() {
		recording = false;
	}

}


remove source location annotation and fix indentation in ovirt-sync

        package org.ovirt.engine.core.bll;

        import java.util.*;

        import org.ovirt.engine.core.common.action.LockProperties;
        import org.ovirt.engine.core.common.action.LockProperties.Scope;
        import org.ovirt.engine.core.common.locks.LockingGroup;
        import org.ovirt.engine.core.bll.CommandBase;
        import org.ovirt.engine.core.utils.lock.EngineLock;
        import org.ovirt.engine.core.common.utils.Pair;
        import org.ovirt.engine.core.common.action.VdcReturnValueBase;
        import org.ovirt.engine.core.common.businessentities.IVdsAsyncCommand;
        import org.ovirt.engine.core.common.errors.EngineMessage;

        public privileged aspect Locks {

            /** Infrastructure Code **/

            /** Acquire locks */
            boolean around(CommandBase commandBase): execution(* CommandBase.acquireLock()) && this(commandBase) {
                LockProperties lockProperties = commandBase.getLockProperties();
                boolean returnValue = true;
                if (!Scope.None.equals(lockProperties.getScope())) {
                    commandBase.releaseLocksAtEndOfExecute = Scope.Execution.equals(lockProperties.getScope());
                    if (!lockProperties.isWait()) {
                        returnValue = commandBase.acquireLockInternal();
                    } else {
                        commandBase.acquireLockAndWait();
                    }
                }
                return returnValue;
            }

            boolean around(CommandBase command): execution(* acquireLockInternal()) && this(command) {
                // if commandLock is null then we acquire new lock, otherwise probably we got lock from caller command.
                if (command.context.getLock() == null) {
                    EngineLock lock = command.buildLock();
                    if (lock != null) {
                        Pair<Boolean, Set<String>> lockAcquireResult = command.getLockManager().acquireLock(lock);
                        if (lockAcquireResult.getFirst()) {
                            command.log.info("Lock Acquired to object '{}'", lock);
                            command.context.withLock(lock);
                        } else {
                            command.log.info("Failed to Acquire Lock to object '{}'", lock);
                            command.getReturnValue().getValidationMessages()
                            .addAll(command.extractVariableDeclarations(lockAcquireResult.getSecond()));
                            return false;
                        }
                    }
                }
                return true;
            }

            void around(CommandBase command): execution(* acquireLockAndWait()) && this(command) {
                // if commandLock is null then we acquire new lock, otherwise probably we got lock from caller command.
                if (command.context.getLock() == null) {
                    Map<String, Pair<String, String>> exclusiveLocks = command.getExclusiveLocks();
                    if (exclusiveLocks != null) {
                        EngineLock lock = new EngineLock(exclusiveLocks, null);
                        command.log.info("Before acquiring and wait lock '{}'", lock);
                        command.getLockManager().acquireLockWait(lock);
                        command.context.withLock(lock);
                        command.log.info("Lock-wait acquired to object '{}'", lock);
                    }
                }
            }

            /** Release locks if validation fails */
            boolean around(CommandBase command): execution(* internalValidate()) && this(command) {
                boolean result = false;
                try {
                   result = proceed(command);
                }
                finally {
                   if (!result) {
                      command.freeLock();
                   }
                }
                return result;
            }

            /** How to release locks */
            void around(CommandBase command): execution(* freeLock()) && this(command) {
                if (command.context.getLock() != null) {
                    command.getLockManager().releaseLock(command.context.getLock());
                    command.log.info("Lock freed to object '{}'", command.context.getLock());
                    command.context.withLock(null);
                    // free other locks here to guarantee they will be freed only once
                    command.freeCustomLocks();
                }
            }

            /** Release locks after the synchronous phase */
            VdcReturnValueBase around(CommandBase command): execution(* executeAction()) && this(command) {
                try {
                   return proceed(command);
                }
                finally {
                   command.freeLockExecute();
                }
            }

            /** Release locks after the asynchronous phase */
            void around(CommandBase command): execution(* endActionInTransactionScope()) && this(command) {
                try {
                   proceed(command);
                }
                finally {
                   command.freeLockEndAction();
                }
            }

            /** Acquire locks for the asynchronous part */
            VdcReturnValueBase around(CommandBase commandBase): execution(* endAction()) && this(commandBase) {
                VdcReturnValueBase result = null;
                try {
                    commandBase.initiateLockEndAction();
                    result = proceed(commandBase);
                } finally {
                    commandBase.freeLockEndAction();
                }
                return result;
            }

            private void CommandBase.freeLockExecute() {
                if (releaseLocksAtEndOfExecute || !getSucceeded() ||
                        (noAsyncOperations() && !(this instanceof IVdsAsyncCommand))) {
                    freeLock();
                }
            }

            /**
             * If the command has more than one task handler, we can reach the end action
             * phase and in that phase execute the next task handler. In that case, we
             * don't want to release the locks, so we ask whether we're not in execute state.
             */
            private void CommandBase.freeLockEndAction() {
                if (getActionState() != CommandActionState.EXECUTE) {
                    freeLock();
                }
            }

            /**
             * The following method should initiate a lock , in order to release it at endAction()
             */
            private void CommandBase.initiateLockEndAction() {
                if (context.getLock() == null) {
                    LockProperties lockProperties = getLockProperties();
                    if (Scope.Command.equals(lockProperties.getScope())) {
                        context.withLock(buildLock());
                    }
                }
            }

            private EngineLock CommandBase.buildLock() {
                EngineLock lock = null;
                Map<String, Pair<String, String>> exclusiveLocks = getExclusiveLocks();
                Map<String, Pair<String, String>> sharedLocks = getSharedLocks();
                if (exclusiveLocks != null || sharedLocks != null) {
                    lock = new EngineLock(exclusiveLocks, sharedLocks);
                }
                return lock;
            }

            /** Command Locks **/

        /** org.ovirt.engine.core.bll.MigrateVmCommand **/
            LockProperties around(LockProperties lockProperties, org.ovirt.engine.core.bll.MigrateVmCommand command): execution(* applyLockProperties(..)) && args(lockProperties) && target(command) {
                return lockProperties.withScope(Scope.Command).withWait(false);
            }

            Map<String, Pair<String, String>> around(org.ovirt.engine.core.bll.MigrateVmCommand command): execution(* getExclusiveLocks()) && target(command) {
                Map<String, Pair<String, String>> locks = new HashMap<String, Pair<String, String>>();

                locks.put(command.getVmId().toString(),
                    LockMessagesMatchUtil.makeLockingPair(LockingGroup.VM, EngineMessage.ACTION_TYPE_FAILED_OBJECT_LOCKED));

                return locks;
            }

        /** org.ovirt.engine.core.bll.AddDiskCommand **/
            LockProperties around(LockProperties lockProperties, org.ovirt.engine.core.bll.storage.disk.AddDiskCommand command): execution(* applyLockProperties(..)) && args(lockProperties) && target(command) {
                return lockProperties.withScope(Scope.Execution).withWait(false);
            }

            Map<String, Pair<String, String>> around(org.ovirt.engine.core.bll.storage.disk.AddDiskCommand command): execution(* getExclusiveLocks()) && target(command) {
                Map<String, Pair<String, String>> locks = new HashMap<String, Pair<String, String>>();

                locks.put(command.getVmId().toString(),
                    LockMessagesMatchUtil.makeLockingPair(LockingGroup.VM_DISK_BOOT, EngineMessage.ACTION_TYPE_FAILED_OBJECT_LOCKED));

                return locks;
            }

            Map<String, Pair<String, String>> around(org.ovirt.engine.core.bll.storage.disk.AddDiskCommand command): execution(* getSharedLocks()) && target(command) {
                Map<String, Pair<String, String>> locks = new HashMap<String, Pair<String, String>>();

                locks.put(command.getVmId().toString(),
                    LockMessagesMatchUtil.makeLockingPair(LockingGroup.VM, EngineMessage.ACTION_TYPE_FAILED_OBJECT_LOCKED));

                return locks;
            }

        }

	package org.ovirt.engine.core.bll;

	import java.util.*;

	import org.ovirt.engine.core.common.action.LockProperties;
	import org.ovirt.engine.core.common.action.LockProperties.Scope;
	import org.ovirt.engine.core.common.locks.LockingGroup;
	import org.ovirt.engine.core.bll.CommandBase;
	import org.ovirt.engine.core.utils.lock.EngineLock;
	import org.ovirt.engine.core.common.utils.Pair;
	import org.ovirt.engine.core.common.action.VdcReturnValueBase;
	import org.ovirt.engine.core.common.businessentities.IVdsAsyncCommand;
	import org.ovirt.engine.core.common.errors.EngineMessage;

	public privileged aspect Locks {

		void around(CommandBase command): execution(* endActionInTransactionScope()) && this(command) {
			try {
	          proceed(command);
	        }
	        finally {
	          command.freeLockEndAction();
	        }
	    }

	   boolean around(CommandBase command): execution(* internalCanDoAction()) && this(command) {
	        boolean result = false;
	        try {
	          result = proceed(command);
	        }
	        finally {
	          if (!result) {
	            command.freeLock();
	          }
	        }
	        return result;
	   }

	   void around(CommandBase command): execution(* freeLock()) && this(command) {
            if (command.context.getLock() != null) {
                command.getLockManager().releaseLock(command.context.getLock());
                command.log.info("Lock freed to object '{}'", command.context.getLock());
                command.context.withLock(null);
                // free other locks here to guarantee they will be freed only once
                command.freeCustomLocks();
            }
        }

	    VdcReturnValueBase around(CommandBase command): execution(* executeAction()) && this(command) {
	        try {
	          return proceed(command);
	        }
	        finally {
	          command.freeLockExecute();
	        }
	    }

	    boolean around(CommandBase commandBase): execution(* CommandBase.acquireLock()) && this(commandBase) {
	        LockProperties lockProperties = commandBase.getLockProperties();
	        boolean returnValue = true;
	        if (!Scope.None.equals(lockProperties.getScope())) {
	            commandBase.releaseLocksAtEndOfExecute = Scope.Execution.equals(lockProperties.getScope());
	            if (!lockProperties.isWait()) {
	                returnValue = commandBase.acquireLockInternal();
	            } else {
	                commandBase.acquireLockAndWait();
	            }
	        }
	        return returnValue;
	    }

		boolean around(CommandBase command): execution(* acquireLockInternal()) && this(command) {
	        // if commandLock is null then we acquire new lock, otherwise probably we got lock from caller command.
	        if (command.context.getLock() == null) {
	            EngineLock lock = command.buildLock();
	            if (lock != null) {
	                Pair<Boolean, Set<String>> lockAcquireResult = command.getLockManager().acquireLock(lock);
	                if (lockAcquireResult.getFirst()) {
	                    command.log.info("Lock Acquired to object '{}'", lock);
	                    command.context.withLock(lock);
	                } else {
	                    command.log.info("Failed to Acquire Lock to object '{}'", lock);
	                    command.getReturnValue().getCanDoActionMessages()
	                    .addAll(command.extractVariableDeclarations(lockAcquireResult.getSecond()));
	                    return false;
	                }
	            }
	        }
	        return true;
	   }

	   void around(CommandBase command): execution(* acquireLockAndWait()) && this(command) {
	        // if commandLock is null then we acquire new lock, otherwise probably we got lock from caller command.
	         if (command.context.getLock() == null) {
	            Map<String, Pair<String, String>> exclusiveLocks = command.getExclusiveLocks();
	             if (exclusiveLocks != null) {
	                 EngineLock lock = new EngineLock(exclusiveLocks, null);
	                 command.getLockManager().acquireLockWait(lock);
	                 command.context.withLock(lock);
	            }
	         }
	    }

		VdcReturnValueBase around(CommandBase commandBase): execution(* endAction()) && this(commandBase) {
	        VdcReturnValueBase result = null;
	        try {
	            commandBase.initiateLockEndAction();
	            result = proceed(commandBase);
	        } finally {
	            commandBase.freeLockEndAction();
	        }
	                return result;
	        }

	   private void CommandBase.freeLockExecute() {
	        if (releaseLocksAtEndOfExecute || !getSucceeded() ||
	                (noAsyncOperations() && !(this instanceof IVdsAsyncCommand))) {
	            freeLock();
	        }
	    }

		/**
	     * If the command has more than one task handler, we can reach the end action
	     * phase and in that phase execute the next task handler. In that case, we
	     * don't want to release the locks, so we ask whether we're not in execute state.
	     */
	    private void CommandBase.freeLockEndAction() {
	        if (getActionState() != CommandActionState.EXECUTE) {
	            freeLock();
	        }
	    }

		/**
	     * The following method should initiate a lock , in order to release it at endAction()
	     */
	    private void CommandBase.initiateLockEndAction() {
	        if (context.getLock() == null) {
	            LockProperties lockProperties = getLockProperties();
	            if (Scope.Command.equals(lockProperties.getScope())) {
	                context.withLock(buildLock());
	            }

	        }
	    }

	    private EngineLock CommandBase.buildLock() {
	        EngineLock lock = null;
	        Map<String, Pair<String, String>> exclusiveLocks = getExclusiveLocks();
	        Map<String, Pair<String, String>> sharedLocks = getSharedLocks();
	        if (exclusiveLocks != null || sharedLocks != null) {
	            lock = new EngineLock(exclusiveLocks, sharedLocks);
	        }
	        return lock;
	    }

			LockProperties around(LockProperties lockProperties, org.ovirt.engine.core.bll.ExportVmTemplateCommand command): execution(* applyLockProperties(..)) && args(lockProperties) && target(command) {
				return lockProperties.withScope(Scope.Execution);
			}

			Map<String, Pair<String, String>> around(org.ovirt.engine.core.bll.ExportVmTemplateCommand command): execution(* getExclusiveLocks()) && target(command) {
			        Map<String, Pair<String, String>> locks = new HashMap<String, Pair<String, String>>();

		locks.put(command.getVmTemplateId().toString(),
			LockMessagesMatchUtil.makeLockingPair(LockingGroup.REMOTE_TEMPLATE, EngineMessage.ACTION_TYPE_FAILED_OBJECT_LOCKED));

				return locks;
			    }

		Map<String, Pair<String, String>> around(org.ovirt.engine.core.bll.ExportVmTemplateCommand command): execution(* getSharedLocks()) && target(command) {
		    Map<String, Pair<String, String>> locks = new HashMap<String, Pair<String, String>>();

		locks.put(command.getVmTemplateId().toString(),
			LockMessagesMatchUtil.makeLockingPair(LockingGroup.TEMPLATE, EngineMessage.ACTION_TYPE_FAILED_OBJECT_LOCKED));

		    return locks;
		}

	}


added constructor pointcut exception for the instatiator

package org.springframework.persistence.graph.neo4j;

import java.lang.reflect.Field;
import java.util.AbstractSet;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import org.aspectj.lang.reflect.FieldSignature;
import org.neo4j.graphdb.Direction;
import org.neo4j.graphdb.DynamicRelationshipType;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.NotInTransactionException;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.RelationshipType;
import org.neo4j.util.GraphDatabaseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.dao.InvalidDataAccessResourceUsageException;
import org.springframework.persistence.graph.Graph;
import org.springframework.persistence.support.AbstractTypeAnnotatingMixinFields;
import org.springframework.persistence.support.EntityInstantiator;

/**
 * Aspect to turn an object annotated with GraphEntity into a graph entity using Neo4J.
 * Delegates all field access (except for fields assumed to be transient)
 * to an underlying Neo4 graph node.
 *
 * @author Rod Johnson
 */
public aspect Neo4jNodeBacking extends AbstractTypeAnnotatingMixinFields<Graph.Entity,NodeBacked> {

	//-------------------------------------------------------------------------
	// Configure aspect for whole system.
	// init() method can be invoked automatically if the aspect is a Spring
	// bean, or called in user code.
	//-------------------------------------------------------------------------
	// Aspect shared Neo4J Graph Database Service
	private GraphDatabaseService graphDatabaseService;

	private EntityInstantiator<NodeBacked, Node> graphEntityInstantiator;

	private FieldAccessorFactory fieldAccessorFactory;

	private EntityInstantiator<RelationshipBacked, Relationship> relationshipEntityInstantiator;

	@Autowired
	public void init(GraphDatabaseService gds, EntityInstantiator<NodeBacked, Node> gei, EntityInstantiator<RelationshipBacked, Relationship> rei) {
		this.graphDatabaseService = gds;
		this.graphEntityInstantiator = gei;
		this.relationshipEntityInstantiator = rei;
		this.fieldAccessorFactory = new FieldAccessorFactory(graphEntityInstantiator, relationshipEntityInstantiator);
	}

	//-------------------------------------------------------------------------
	// Advise user-defined constructors of NodeBacked objects to create a new
	// Neo4J backing node
	//-------------------------------------------------------------------------
	pointcut arbitraryUserConstructorOfNodeBackedObject(NodeBacked entity) :
		execution((@Graph.Entity *).new(..)) &&
		!execution((@Graph.Entity *).new(Node)) &&
		this(entity);
		execution((@GraphEntity *).new(..)) &&
		!execution((@GraphEntity *).new(Node)) &&
		this(entity);  // && !cflow(execution(* fromStateInternal(..));

	// Create a new node in the Graph if no Node was passed in a constructor
	before(NodeBacked entity) : arbitraryUserConstructorOfNodeBackedObject(entity) {
		try {
			entity.setUnderlyingNode(graphDatabaseService.createNode());
			log.info("User-defined constructor called on class " + entity.getClass() + "; created Node [" + entity.getUnderlyingNode() +"]; " +
					"Updating metamodel");
			// TODO pull naming out into a strategy interface, todo a separate one, or the Entity Instatiator
			// graphEntityInstantiator.postEntityCreation(entity);
			postEntityCreation(entity);
		} catch(NotInTransactionException e) {
			throw new InvalidDataAccessResourceUsageException("Not in a Neo4j transaction.", e);
		}
	}

	private void postEntityCreation(NodeBacked entity) {
		Node subReference = Neo4jHelper.findSubreferenceNode(entity.getClass(), graphDatabaseService);
		entity.getUnderlyingNode().createRelationshipTo(subReference, Neo4jHelper.INSTANCE_OF_RELATIONSHIP_TYPE);
		GraphDatabaseUtil.incrementAndGetCounter(subReference, Neo4jHelper.SUBREFERENCE_NODE_COUNTER_KEY);
	}

	// Introduced field
	private Node NodeBacked.underlyingNode;

	public void NodeBacked.setUnderlyingNode(Node n) {
		this.underlyingNode = n;
	}

	public Node NodeBacked.getUnderlyingNode() {
		return underlyingNode;
	}

	public Relationship NodeBacked.relateTo(NodeBacked nb, RelationshipType type) {
		return this.underlyingNode.createRelationshipTo(nb.getUnderlyingNode(), type);
	}

	public long NodeBacked.getId() {
		return underlyingNode.getId();
	}

	//-------------------------------------------------------------------------
	// Equals and hashCode for Neo4j entities.
	// Final to prevent overriding.
	//-------------------------------------------------------------------------
	// TODO could use template method for further checks if needed
	public final boolean NodeBacked.equals(Object obj) {
		if (obj instanceof NodeBacked) {
			return this.getUnderlyingNode().equals(((NodeBacked) obj).getUnderlyingNode());
		}
		return false;
	}

	public final int NodeBacked.hashCode() {
		return getUnderlyingNode().hashCode();
	}

	Object around(NodeBacked entity) : entityFieldGet(entity) {
		FieldSignature fieldSignature=(FieldSignature) thisJoinPoint.getSignature();
		Field f = fieldSignature.getField();

		// TODO fix arrays, TODO serialize other types as byte[] or string (for indexing, querying) via Annotation
		if (isPropertyType(f.getType())) {
			String propName = FieldAccessorFactory.getNeo4jPropertyName(f);
			log.info("GET " + f + " <- Neo4J simple node property [" + propName + "]");
			return entity.getUnderlyingNode().getProperty(propName, null);
		}

		FieldAccessor accessor = fieldAccessorFactory.forField(f);
		Object obj = accessor.readObject(entity);
		if (obj == null) {
			log.info("Ignored GET " + f + ": " + f.getType().getName() + " not primitive or GraphEntity");
			return proceed(entity);
		}
		return obj;
	}

	Object around(NodeBacked entity, Object newVal) : entityFieldSet(entity, newVal) {
		try {
			FieldSignature fieldSignature=(FieldSignature) thisJoinPoint.getSignature();
			Field f = fieldSignature.getField();
			// TODO fix arrays
			Class<?> fieldType = f.getType();
			if (isPropertyType(fieldType)) {
				String propName = FieldAccessorFactory.getNeo4jPropertyName(f);
				entity.getUnderlyingNode().setProperty(propName, newVal);
				log.info("SET " + f + " -> Neo4J simple node property [" + propName + "] with value=[" + newVal + "]");
				return proceed(entity, newVal);
			}

			FieldAccessor accessor = fieldAccessorFactory.forField(f);
			if (accessor == null) {
				log.info("Ignored SET " + f + ": " + f.getType().getName() + " not primitive or GraphEntity");
				return proceed(entity, newVal);
			}
			log.info("SET " + f + " -> Neo4J relationship with value=[" + newVal + "]");
			Object result = accessor.apply(entity, newVal);
			return proceed(entity,result);
		} catch(NotInTransactionException e) {
			throw new InvalidDataAccessResourceUsageException("Not in a Neo4j transaction.", e);
		}
	}

	private boolean isPropertyType(Class<?> fieldType) {
		// todo: add array support
		return fieldType.isPrimitive()
	  		|| (fieldType.isArray() && !fieldType.getComponentType().isArray() && isPropertyType(fieldType.getComponentType()))
	  		|| fieldType.equals(String.class)
	  		|| fieldType.equals(Character.class)
	  		|| fieldType.equals(Boolean.class)
	  		|| (fieldType.getName().startsWith("java.lang") && Number.class.isAssignableFrom(fieldType));
	}

}

package org.springframework.persistence.graph.neo4j;

import java.lang.reflect.Field;
import java.util.AbstractSet;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import org.aspectj.lang.reflect.FieldSignature;
import org.neo4j.graphdb.Direction;
import org.neo4j.graphdb.DynamicRelationshipType;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.NotInTransactionException;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.RelationshipType;
import org.neo4j.util.GraphDatabaseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.dao.InvalidDataAccessResourceUsageException;
import org.springframework.persistence.graph.Graph;
import org.springframework.persistence.support.AbstractTypeAnnotatingMixinFields;
import org.springframework.persistence.support.EntityInstantiator;

/**
 * Aspect to turn an object annotated with GraphEntity into a graph entity using Neo4J.
 * Delegates all field access (except for fields assumed to be transient)
 * to an underlying Neo4 graph node.
 *
 * @author Rod Johnson
 */
public aspect Neo4jNodeBacking extends AbstractTypeAnnotatingMixinFields<Graph.Entity,NodeBacked> {

	//-------------------------------------------------------------------------
	// Configure aspect for whole system.
	// init() method can be invoked automatically if the aspect is a Spring
	// bean, or called in user code.
	//-------------------------------------------------------------------------
	// Aspect shared Neo4J Graph Database Service
	private GraphDatabaseService graphDatabaseService;

	private EntityInstantiator<NodeBacked, Node> graphEntityInstantiator;

	private FieldAccessorFactory fieldAccessorFactory;

	private EntityInstantiator<RelationshipBacked, Relationship> relationshipEntityInstantiator;

	@Autowired
	public void init(GraphDatabaseService gds, EntityInstantiator<NodeBacked, Node> gei, EntityInstantiator<RelationshipBacked, Relationship> rei) {
		this.graphDatabaseService = gds;
		this.graphEntityInstantiator = gei;
		this.relationshipEntityInstantiator = rei;
		this.fieldAccessorFactory = new FieldAccessorFactory(graphEntityInstantiator, relationshipEntityInstantiator);
	}

	//-------------------------------------------------------------------------
	// Advise user-defined constructors of NodeBacked objects to create a new
	// Neo4J backing node
	//-------------------------------------------------------------------------
	pointcut arbitraryUserConstructorOfNodeBackedObject(NodeBacked entity) :
		execution((@Graph.Entity *).new(..)) &&
		!execution((@Graph.Entity *).new(Node)) &&
		this(entity);

	// Create a new node in the Graph if no Node was passed in a constructor
	before(NodeBacked entity) : arbitraryUserConstructorOfNodeBackedObject(entity) {
		try {
			entity.setUnderlyingNode(graphDatabaseService.createNode());
			log.info("User-defined constructor called on class " + entity.getClass() + "; created Node [" + entity.getUnderlyingNode() +"]; " +
					"Updating metamodel");
			// TODO pull naming out into a strategy interface, todo a separate one, or the Entity Instatiator
			// graphEntityInstantiator.postEntityCreation(entity);
			postEntityCreation(entity);
		} catch(NotInTransactionException e) {
			throw new InvalidDataAccessResourceUsageException("Not in a Neo4j transaction.", e);
		}
	}

	private void postEntityCreation(NodeBacked entity) {
		Node subReference = Neo4jHelper.findSubreferenceNode(entity.getClass(), graphDatabaseService);
		entity.getUnderlyingNode().createRelationshipTo(subReference, Neo4jHelper.INSTANCE_OF_RELATIONSHIP_TYPE);
		GraphDatabaseUtil.incrementAndGetCounter(subReference, Neo4jHelper.SUBREFERENCE_NODE_COUNTER_KEY);
	}

	// Introduced field
	private Node NodeBacked.underlyingNode;

	public void NodeBacked.setUnderlyingNode(Node n) {
		this.underlyingNode = n;
	}

	public Node NodeBacked.getUnderlyingNode() {
		return underlyingNode;
	}

	public Relationship NodeBacked.relateTo(NodeBacked nb, RelationshipType type) {
		return this.underlyingNode.createRelationshipTo(nb.getUnderlyingNode(), type);
	}

	public long NodeBacked.getId() {
		return underlyingNode.getId();
	}

	//-------------------------------------------------------------------------
	// Equals and hashCode for Neo4j entities.
	// Final to prevent overriding.
	//-------------------------------------------------------------------------
	// TODO could use template method for further checks if needed
	public final boolean NodeBacked.equals(Object obj) {
		if (obj instanceof NodeBacked) {
			return this.getUnderlyingNode().equals(((NodeBacked) obj).getUnderlyingNode());
		}
		return false;
	}

	public final int NodeBacked.hashCode() {
		return getUnderlyingNode().hashCode();
	}

	Object around(NodeBacked entity) : entityFieldGet(entity) {
		FieldSignature fieldSignature=(FieldSignature) thisJoinPoint.getSignature();
		Field f = fieldSignature.getField();

		// TODO fix arrays, TODO serialize other types as byte[] or string (for indexing, querying) via Annotation
		if (isPropertyType(f.getType())) {
			String propName = FieldAccessorFactory.getNeo4jPropertyName(f);
			log.info("GET " + f + " <- Neo4J simple node property [" + propName + "]");
			return entity.getUnderlyingNode().getProperty(propName, null);
		}

		FieldAccessor accessor = fieldAccessorFactory.forField(f);
		Object obj = accessor.readObject(entity);
		if (obj == null) {
			log.info("Ignored GET " + f + ": " + f.getType().getName() + " not primitive or GraphEntity");
			return proceed(entity);
		}
		return obj;
	}

	Object around(NodeBacked entity, Object newVal) : entityFieldSet(entity, newVal) {
		try {
			FieldSignature fieldSignature=(FieldSignature) thisJoinPoint.getSignature();
			Field f = fieldSignature.getField();
			// TODO fix arrays
			Class<?> fieldType = f.getType();
			if (isPropertyType(fieldType)) {
				String propName = FieldAccessorFactory.getNeo4jPropertyName(f);
				entity.getUnderlyingNode().setProperty(propName, newVal);
				log.info("SET " + f + " -> Neo4J simple node property [" + propName + "] with value=[" + newVal + "]");
				return proceed(entity, newVal);
			}

			FieldAccessor accessor = fieldAccessorFactory.forField(f);
			if (accessor == null) {
				log.info("Ignored SET " + f + ": " + f.getType().getName() + " not primitive or GraphEntity");
				return proceed(entity, newVal);
			}
			log.info("SET " + f + " -> Neo4J relationship with value=[" + newVal + "]");
			Object result = accessor.apply(entity, newVal);
			return proceed(entity,result);
		} catch(NotInTransactionException e) {
			throw new InvalidDataAccessResourceUsageException("Not in a Neo4j transaction.", e);
		}
	}

	private boolean isPropertyType(Class<?> fieldType) {
		// todo: add array support
		return fieldType.isPrimitive()
	  		|| (fieldType.isArray() && !fieldType.getComponentType().isArray() && isPropertyType(fieldType.getComponentType()))
	  		|| fieldType.equals(String.class)
	  		|| fieldType.equals(Character.class)
	  		|| fieldType.equals(Boolean.class)
	  		|| (fieldType.getName().startsWith("java.lang") && Number.class.isAssignableFrom(fieldType));
	}

}