Added additional checks for non-existing state-accessors in the case of broken graph-backed entities that are created before the initial spring lifecycle has been completed.

/*
 * Copyright 2010 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.data.graph.neo4j.support.node;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.FieldSignature;
import org.neo4j.graphdb.DynamicRelationshipType;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.RelationshipType;
import org.neo4j.graphdb.traversal.TraversalDescription;
import org.neo4j.graphdb.traversal.Traverser;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.data.graph.annotation.NodeEntity;
import org.springframework.data.graph.core.NodeBacked;
import org.springframework.data.graph.core.RelationshipBacked;
import org.springframework.data.graph.neo4j.fieldaccess.*;
import org.springframework.data.graph.neo4j.support.GraphDatabaseContext;
import org.springframework.persistence.support.AbstractTypeAnnotatingMixinFields;

import java.lang.reflect.Field;

import static org.springframework.data.graph.neo4j.fieldaccess.DoReturn.unwrap;

import org.springframework.persistence.support.StateProvider;

/**
 * Aspect for handling node entity creation and field access (read & write)
 * puts the underlying state (Node) into and delegates field access to an {@link EntityStateAccessors} instance,
 * created by a configured {@link NodeEntityStateAccessorsFactory}.
 *
 * Handles constructor invocation and partial entities as well.
 */
public aspect Neo4jNodeBacking { // extends AbstractTypeAnnotatingMixinFields<NodeEntity, NodeBacked> {

    protected final Log log = LogFactory.getLog(getClass());

    declare parents : (@NodeEntity *) implements NodeBacked;
    declare @type: NodeBacked+: @Configurable;

    protected pointcut entityFieldGet(NodeBacked entity) :
            get(* NodeBacked+.*) &&
            this(entity) &&
            !get(* NodeBacked.*);

    protected pointcut entityFieldSet(NodeBacked entity, Object newVal) :
            set(* NodeBacked+.*) &&
            this(entity) &&
            args(newVal) &&
            !set(* NodeBacked.*);

    private GraphDatabaseContext graphDatabaseContext;
    private NodeEntityStateAccessorsFactory entityStateAccessorsFactory;

    public void setGraphDatabaseContext(GraphDatabaseContext graphDatabaseContext) {
        this.graphDatabaseContext = graphDatabaseContext;
    }
    public void setNodeEntityStateAccessorsFactory(NodeEntityStateAccessorsFactory entityStateAccessorsFactory) {
        this.entityStateAccessorsFactory = entityStateAccessorsFactory;
    }
    /**
     * pointcut for constructors not taking a node to be handled by the aspect and the {@link EntityStateAccessors}
     */
	pointcut arbitraryUserConstructorOfNodeBackedObject(NodeBacked entity) :
		execution((@NodeEntity *).new(..)) &&
		!execution((@NodeEntity *).new(Node)) &&
		this(entity) && !cflowbelow(call(* fromStateInternal(..)));

    /**
     * Handle outside entity instantiation by either creating an appropriate backing node in the graph or in the case
     * of a reinstantiated partial entity by assigning the original node to the entity, the concrete behaviour is delegated
     * to the {@link EntityStateAccessors}. Also handles the java type representation in the graph.
     * When running outside of a transaction, no node is created, this is handled later when the entity is accessed within
     * a transaction again.
     */
    before(NodeBacked entity): arbitraryUserConstructorOfNodeBackedObject(entity) {
        if (entityStateAccessorsFactory == null) {
            log.error("entityStateAccessorsFactory not set, not creating accessors for " + entity.getClass());
        } else {
            if (entity.stateAccessors != null) return;
            EntityStateAccessors<NodeBacked, Node> stateAccessors = entityStateAccessorsFactory.getEntityStateAccessors(entity);
            entity.stateAccessors = stateAccessors;
            stateAccessors.attach(true);
        }
    }

    public NodeBacked NodeBacked.attach() {
        return this.stateAccessors.attach(false);
    }
    /**
     * State accessors that encapsulate the underlying state and the behaviour related to it (field access, creation)
     */
    private transient EntityStateAccessors<NodeBacked,Node> NodeBacked.stateAccessors;

    /**
     * sets the underlying state to the given node, creates an {@link EntityStateAccessors} instance on demand for delegating
     * the behaviour, otherwise just updates the backing state
     * @param n the node to be the backing state of the entity
     */
	public void NodeBacked.setUnderlyingState(Node n) {
        if (this.stateAccessors == null) {
            this.stateAccessors = Neo4jNodeBacking.aspectOf().entityStateAccessorsFactory.getEntityStateAccessors(this);
        }
        this.stateAccessors.setUnderlyingState(n);
	}

	public Node NodeBacked.getUnderlyingState() {
		return this.stateAccessors.getUnderlyingState();
	}

    public EntityStateAccessors NodeBacked.getStateAccessors() {
        return stateAccessors;
    }

    public boolean NodeBacked.hasUnderlyingNode() {
        return this.stateAccessors!=null && this.stateAccessors.hasUnderlyingState();
    }

    public <T extends NodeBacked> T NodeBacked.projectTo(Class<T> targetType) {
        return (T)Neo4jNodeBacking.aspectOf().graphDatabaseContext.projectTo( this, targetType);
    }

    /**
     * creates a relationship to the target node entity with the given relationship type
     * @param target entity
     * @param type neo4j relationship type for the underlying relationship
     * @return the newly created relationship to the target node
     */
	public Relationship NodeBacked.relateTo(NodeBacked target, RelationshipType type) {
		return this.getUnderlyingState().createRelationshipTo(target.getUnderlyingState(), type);
	}

    /**
     * @return node id or null if there is no underlying state
     */
	public Long NodeBacked.getNodeId() {
        if (!hasUnderlyingNode()) return null;
		return getUnderlyingState().getId();
	}

    /**
     * handles traversal from the current node with the given traversal description, the entities returned must be instances of the
     * provided target type
     * @param targetType node entity java types of the traversal results
     * @param traversalDescription
     * @return lazy Iterable over the traversal results, converted to the expected node entity instances
     */
    public  <T extends NodeBacked> Iterable<T> NodeBacked.findAllByTraversal(final Class<T> targetType, TraversalDescription traversalDescription) {
        if (!hasUnderlyingNode()) throw new IllegalStateException("No node attached to " + this);
        final Traverser traverser = traversalDescription.traverse(this.getUnderlyingState());
        return new NodeBackedNodeIterableWrapper<T>(traverser, targetType, Neo4jNodeBacking.aspectOf().graphDatabaseContext);
    }

//    public Iterable<? extends NodeBacked> NodeBacked.traverse(TraversalDescription traversalDescription) {
//        final Class<? extends NodeBacked> target = this.getClass();
//        return this.traverse(target,traversalDescription);
//    }

    /**
     * Creates a relationship to the target node  with the given relationship type.
     * @param target node
     * @param relationshipClass  expected relationship class of the resulting relationship entity
     * @param relationshipType
     * @return relationship entity, instance of the provided relationshipClass
     */
    public <R extends RelationshipBacked, N extends NodeBacked> R NodeBacked.relateTo(N target, Class<R> relationshipClass, String relationshipType) {
        Relationship rel = this.getUnderlyingState().createRelationshipTo( target.getUnderlyingState(), DynamicRelationshipType.withName(relationshipType));
        return (R)Neo4jNodeBacking.aspectOf().graphDatabaseContext.createEntityFromState(rel, relationshipClass);
    }

    /**
     * removes the entity using @{link GraphDatabaseContext.removeNodeEntity}
     * the entity and relationship are still accessible after removal but before transaction commit
     * but all modifications will throw an exception
     */
    public void NodeBacked.remove() {
        Neo4jNodeBacking.aspectOf().graphDatabaseContext.removeNodeEntity(this);
    }
    /**
     * removes the relationship to the target node entity with the given relationship type
     * @param target node entity
     * @param relationshipType
     */
    public void NodeBacked.removeRelationshipTo(NodeBacked target, String relationshipType) {
        Node myNode=this.getUnderlyingState();
        Node otherNode=target.getUnderlyingState();
        for (Relationship rel : this.getUnderlyingState().getRelationships(DynamicRelationshipType.withName(relationshipType))) {
            if (rel.getOtherNode(myNode).equals(otherNode)) {
                rel.delete();
                return;
            }
        }
    }

    /**
     * introduced method for accessing and Relationship Entity instance for the given start node and relationship type.
     * @param node start node
     * @param relationshipClass class of the relationship entity
     * @param type type of the graph relationship
     * @return and instance of the requested relationshipClass if the relationship was found, null otherwise
     */
    public <R extends RelationshipBacked> R NodeBacked.getRelationshipTo( NodeBacked node, Class<R> relationshipClass, String type) {
        Node myNode=this.getUnderlyingState();
        Node otherNode=node.getUnderlyingState();
        for (Relationship rel : this.getUnderlyingState().getRelationships(DynamicRelationshipType.withName(type))) {
            if (rel.getOtherNode(myNode).equals(otherNode)) return (R)Neo4jNodeBacking.aspectOf().graphDatabaseContext.createEntityFromState(rel, relationshipClass);
        }
        return null;
    }

    /**
     * @param obj
     * @return result of equals operation fo the underlying node, false if there is none
     */
	public final boolean NodeBacked.equals(Object obj) {
        if (obj == this) return true;
        if (!hasUnderlyingNode()) return false;
		if (obj instanceof NodeBacked) {
			return this.getUnderlyingState().equals(((NodeBacked) obj).getUnderlyingState());
		}
		return false;
	}

    /**
     * @return result of the hashCode of the underlying node (if any, otherwise identityHashCode)
     */
	public final int NodeBacked.hashCode() {
        if (!hasUnderlyingNode()) return System.identityHashCode(this);
		return getUnderlyingState().hashCode();
	}

    /**
     * delegates field reads to the state accessors instance
     */
    Object around(NodeBacked entity): entityFieldGet(entity) {
        if (entity.stateAccessors==null) return proceed(entity);
        Object result=entity.stateAccessors.getValue(field(thisJoinPoint));
        if (result instanceof DoReturn) return unwrap(result);
        return proceed(entity);
    }

    /**
     * delegates field writes to the state accessors instance
     */
    Object around(NodeBacked entity, Object newVal) : entityFieldSet(entity, newVal) {
        if (entity.stateAccessors==null) return proceed(entity,newVal);
        Object result=entity.stateAccessors.setValue(field(thisJoinPoint),newVal);
        if (result instanceof DoReturn) return unwrap(result);
        return proceed(entity,result);
	}

    Field field(JoinPoint joinPoint) {
        FieldSignature fieldSignature = (FieldSignature)joinPoint.getSignature();
        return fieldSignature.getField();
    }
}

/*
 * Copyright 2010 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.data.graph.neo4j.support.node;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.FieldSignature;
import org.neo4j.graphdb.DynamicRelationshipType;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.RelationshipType;
import org.neo4j.graphdb.traversal.TraversalDescription;
import org.neo4j.graphdb.traversal.Traverser;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.data.graph.annotation.NodeEntity;
import org.springframework.data.graph.core.NodeBacked;
import org.springframework.data.graph.core.RelationshipBacked;
import org.springframework.data.graph.neo4j.fieldaccess.*;
import org.springframework.data.graph.neo4j.support.GraphDatabaseContext;
import org.springframework.persistence.support.AbstractTypeAnnotatingMixinFields;

import java.lang.reflect.Field;

import static org.springframework.data.graph.neo4j.fieldaccess.DoReturn.unwrap;

import org.springframework.persistence.support.StateProvider;

/**
 * Aspect for handling node entity creation and field access (read & write)
 * puts the underlying state (Node) into and delegates field access to an {@link EntityStateAccessors} instance,
 * created by a configured {@link NodeEntityStateAccessorsFactory}.
 *
 * Handles constructor invocation and partial entities as well.
 */
public aspect Neo4jNodeBacking { // extends AbstractTypeAnnotatingMixinFields<NodeEntity, NodeBacked> {

    protected final Log log = LogFactory.getLog(getClass());

    declare parents : (@NodeEntity *) implements NodeBacked;
    declare @type: NodeBacked+: @Configurable;

    protected pointcut entityFieldGet(NodeBacked entity) :
            get(* NodeBacked+.*) &&
            this(entity) &&
            !get(* NodeBacked.*);

    protected pointcut entityFieldSet(NodeBacked entity, Object newVal) :
            set(* NodeBacked+.*) &&
            this(entity) &&
            args(newVal) &&
            !set(* NodeBacked.*);

    private GraphDatabaseContext graphDatabaseContext;
    private NodeEntityStateAccessorsFactory entityStateAccessorsFactory;

    public void setGraphDatabaseContext(GraphDatabaseContext graphDatabaseContext) {
        this.graphDatabaseContext = graphDatabaseContext;
    }
    public void setNodeEntityStateAccessorsFactory(NodeEntityStateAccessorsFactory entityStateAccessorsFactory) {
        this.entityStateAccessorsFactory = entityStateAccessorsFactory;
    }
    /**
     * pointcut for constructors not taking a node to be handled by the aspect and the {@link EntityStateAccessors}
     */
	pointcut arbitraryUserConstructorOfNodeBackedObject(NodeBacked entity) :
		execution((@NodeEntity *).new(..)) &&
		!execution((@NodeEntity *).new(Node)) &&
		this(entity) && !cflowbelow(call(* fromStateInternal(..)));

    /**
     * Handle outside entity instantiation by either creating an appropriate backing node in the graph or in the case
     * of a reinstantiated partial entity by assigning the original node to the entity, the concrete behaviour is delegated
     * to the {@link EntityStateAccessors}. Also handles the java type representation in the graph.
     * When running outside of a transaction, no node is created, this is handled later when the entity is accessed within
     * a transaction again.
     */
    before(NodeBacked entity): arbitraryUserConstructorOfNodeBackedObject(entity) {
        if (entityStateAccessorsFactory == null) {
            log.error("entityStateAccessorsFactory not set, not creating accessors for " + entity.getClass());
        } else {
            if (entity.stateAccessors != null) return;
            EntityStateAccessors<NodeBacked, Node> stateAccessors = entityStateAccessorsFactory.getEntityStateAccessors(entity);
            entity.stateAccessors = stateAccessors;
            stateAccessors.attach(true);
        }
    }

    public NodeBacked NodeBacked.attach() {
        return this.stateAccessors.attach(false);
    }
    /**
     * State accessors that encapsulate the underlying state and the behaviour related to it (field access, creation)
     */
    private transient EntityStateAccessors<NodeBacked,Node> NodeBacked.stateAccessors;

    /**
     * sets the underlying state to the given node, creates an {@link EntityStateAccessors} instance on demand for delegating
     * the behaviour, otherwise just updates the backing state
     * @param n the node to be the backing state of the entity
     */
	public void NodeBacked.setUnderlyingState(Node n) {
        if (this.stateAccessors == null) {
            this.stateAccessors = Neo4jNodeBacking.aspectOf().entityStateAccessorsFactory.getEntityStateAccessors(this);
        }
        this.stateAccessors.setUnderlyingState(n);
	}

	public Node NodeBacked.getUnderlyingState() {
		return this.stateAccessors.getUnderlyingState();
	}

    public EntityStateAccessors NodeBacked.getStateAccessors() {
        return stateAccessors;
    }

    public boolean NodeBacked.hasUnderlyingNode() {
        return this.stateAccessors.hasUnderlyingState();
    }

    public <T extends NodeBacked> T NodeBacked.projectTo(Class<T> targetType) {
        return (T)Neo4jNodeBacking.aspectOf().graphDatabaseContext.projectTo( this, targetType);
    }

    /**
     * creates a relationship to the target node entity with the given relationship type
     * @param target entity
     * @param type neo4j relationship type for the underlying relationship
     * @return the newly created relationship to the target node
     */
	public Relationship NodeBacked.relateTo(NodeBacked target, RelationshipType type) {
		return this.getUnderlyingState().createRelationshipTo(target.getUnderlyingState(), type);
	}

    /**
     * @return node id or null if there is no underlying state
     */
	public Long NodeBacked.getNodeId() {
        if (!hasUnderlyingNode()) return null;
		return getUnderlyingState().getId();
	}

    /**
     * handles traversal from the current node with the given traversal description, the entities returned must be instances of the
     * provided target type
     * @param targetType node entity java types of the traversal results
     * @param traversalDescription
     * @return lazy Iterable over the traversal results, converted to the expected node entity instances
     */
    public  <T extends NodeBacked> Iterable<T> NodeBacked.findAllByTraversal(final Class<T> targetType, TraversalDescription traversalDescription) {
        if (!hasUnderlyingNode()) throw new IllegalStateException("No node attached to " + this);
        final Traverser traverser = traversalDescription.traverse(this.getUnderlyingState());
        return new NodeBackedNodeIterableWrapper<T>(traverser, targetType, Neo4jNodeBacking.aspectOf().graphDatabaseContext);
    }

//    public Iterable<? extends NodeBacked> NodeBacked.traverse(TraversalDescription traversalDescription) {
//        final Class<? extends NodeBacked> target = this.getClass();
//        return this.traverse(target,traversalDescription);
//    }

    /**
     * Creates a relationship to the target node  with the given relationship type.
     * @param target node
     * @param relationshipClass  expected relationship class of the resulting relationship entity
     * @param relationshipType
     * @return relationship entity, instance of the provided relationshipClass
     */
    public <R extends RelationshipBacked, N extends NodeBacked> R NodeBacked.relateTo(N target, Class<R> relationshipClass, String relationshipType) {
        Relationship rel = this.getUnderlyingState().createRelationshipTo( target.getUnderlyingState(), DynamicRelationshipType.withName(relationshipType));
        return (R)Neo4jNodeBacking.aspectOf().graphDatabaseContext.createEntityFromState(rel, relationshipClass);
    }

    /**
     * removes the entity using @{link GraphDatabaseContext.removeNodeEntity}
     * the entity and relationship are still accessible after removal but before transaction commit
     * but all modifications will throw an exception
     */
    public void NodeBacked.remove() {
        Neo4jNodeBacking.aspectOf().graphDatabaseContext.removeNodeEntity(this);
    }
    /**
     * removes the relationship to the target node entity with the given relationship type
     * @param target node entity
     * @param relationshipType
     */
    public void NodeBacked.removeRelationshipTo(NodeBacked target, String relationshipType) {
        Node myNode=this.getUnderlyingState();
        Node otherNode=target.getUnderlyingState();
        for (Relationship rel : this.getUnderlyingState().getRelationships(DynamicRelationshipType.withName(relationshipType))) {
            if (rel.getOtherNode(myNode).equals(otherNode)) {
                rel.delete();
                return;
            }
        }
    }

    /**
     * introduced method for accessing and Relationship Entity instance for the given start node and relationship type.
     * @param node start node
     * @param relationshipClass class of the relationship entity
     * @param type type of the graph relationship
     * @return and instance of the requested relationshipClass if the relationship was found, null otherwise
     */
    public <R extends RelationshipBacked> R NodeBacked.getRelationshipTo( NodeBacked node, Class<R> relationshipClass, String type) {
        Node myNode=this.getUnderlyingState();
        Node otherNode=node.getUnderlyingState();
        for (Relationship rel : this.getUnderlyingState().getRelationships(DynamicRelationshipType.withName(type))) {
            if (rel.getOtherNode(myNode).equals(otherNode)) return (R)Neo4jNodeBacking.aspectOf().graphDatabaseContext.createEntityFromState(rel, relationshipClass);
        }
        return null;
    }

    /**
     * @param obj
     * @return result of equals operation fo the underlying node, false if there is none
     */
	public final boolean NodeBacked.equals(Object obj) {
        if (obj == this) return true;
        if (!hasUnderlyingNode()) return false;
		if (obj instanceof NodeBacked) {
			return this.getUnderlyingState().equals(((NodeBacked) obj).getUnderlyingState());
		}
		return false;
	}

    /**
     * @return result of the hashCode of the underlying node (if any, otherwise identityHashCode)
     */
	public final int NodeBacked.hashCode() {
        if (!hasUnderlyingNode()) return System.identityHashCode(this);
		return getUnderlyingState().hashCode();
	}

    /**
     * delegates field reads to the state accessors instance
     */
    Object around(NodeBacked entity): entityFieldGet(entity) {
		if (field(thisJoinPoint).getDeclaringClass().equals("Named")) log.warn("entityFieldGet "+field(thisJoinPoint));
        Object result=entity.stateAccessors.getValue(field(thisJoinPoint));
        if (result instanceof DoReturn) return unwrap(result);
        return proceed(entity);
    }

    /**
     * delegates field writes to the state accessors instance
     */
    Object around(NodeBacked entity, Object newVal) : entityFieldSet(entity, newVal) {
        Object result=entity.stateAccessors.setValue(field(thisJoinPoint),newVal);
        if (result instanceof DoReturn) return unwrap(result);
        return proceed(entity,result);
	}

    Field field(JoinPoint joinPoint) {
        FieldSignature fieldSignature = (FieldSignature)joinPoint.getSignature();
        return fieldSignature.getField();
    }
}


make autowiring less confusing for spring by informing it to use mongoEntityRepository

package org.slc.sli.sandbox.idp.aspect;

import java.lang.management.ManagementFactory;

import org.slc.sli.common.util.datetime.DateTimeUtil;
import org.slc.sli.common.util.logging.LoggerCarrier;
import org.slc.sli.common.util.logging.SecurityEvent;
import org.slc.sli.domain.Entity;
import org.slc.sli.domain.Repository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

public aspect LoggerCarrierAspect {

    private static final Logger LOG = LoggerFactory.getLogger("SecurityMonitor");

    private static final String SIMPLEIDP_APPLICATION_ID = "SimpleIDP";

    declare parents : org.slc.sli.sandbox.idp.controller.Login implements LoggerCarrier;

    @Autowired
    private Repository<Entity> mongoEntityRepository;

    public void LoggerCarrier.audit(SecurityEvent event) {
        event.setAppId(SIMPLEIDP_APPLICATION_ID);
        event.setClassName(this.getClass().getName());
        event.setTimeStamp(DateTimeUtil.getNowInUTC());
        event.setProcessNameOrId(ManagementFactory.getRuntimeMXBean().getName());

        LoggerCarrierAspect.aspectOf().getRepo().create("securityEvent", event.getProperties());
        switch (event.getLogLevel()) {
        case TYPE_DEBUG:
            LOG.debug(event.toString());
            break;

        case TYPE_WARN:
            LOG.warn(event.toString());
            break;

        case TYPE_INFO:
            LOG.info(event.toString());
            break;

        case TYPE_ERROR:
            LOG.error(event.toString());
            break;

        case TYPE_TRACE:
            LOG.trace(event.toString());
            break;

        default:
            LOG.info(event.toString());
            break;
        }
    }

    public Repository<Entity> getRepo() {
        return mongoEntityRepository;
    }

    public void setRepo(Repository<Entity> repo) {
        this.mongoEntityRepository = repo;
    }

}

package org.slc.sli.sandbox.idp.aspect;

import java.lang.management.ManagementFactory;

import org.slc.sli.common.util.datetime.DateTimeUtil;
import org.slc.sli.common.util.logging.LoggerCarrier;
import org.slc.sli.common.util.logging.SecurityEvent;
import org.slc.sli.domain.Entity;
import org.slc.sli.domain.Repository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

public aspect LoggerCarrierAspect {

    private static final Logger LOG = LoggerFactory.getLogger("SecurityMonitor");

    private static final String SIMPLEIDP_APPLICATION_ID = "SimpleIDP";

    declare parents : org.slc.sli.sandbox.idp.controller.Login implements LoggerCarrier;

    @Autowired
    private Repository<Entity> repo;

    public void LoggerCarrier.audit(SecurityEvent event) {
        event.setAppId(SIMPLEIDP_APPLICATION_ID);
        event.setClassName(this.getClass().getName());
        event.setTimeStamp(DateTimeUtil.getNowInUTC());
        event.setProcessNameOrId(ManagementFactory.getRuntimeMXBean().getName());

        LoggerCarrierAspect.aspectOf().getRepo().create("securityEvent", event.getProperties());
        switch (event.getLogLevel()) {
        case TYPE_DEBUG:
            LOG.debug(event.toString());
            break;

        case TYPE_WARN:
            LOG.warn(event.toString());
            break;

        case TYPE_INFO:
            LOG.info(event.toString());
            break;

        case TYPE_ERROR:
            LOG.error(event.toString());
            break;

        case TYPE_TRACE:
            LOG.trace(event.toString());
            break;

        default:
            LOG.info(event.toString());
            break;
        }
    }

    public Repository<Entity> getRepo() {
        return repo;
    }

    public void setRepo(Repository<Entity> repo) {
        this.repo = repo;
    }

}


add try blocks

add try blocks

package ru.agentlab.maia.container.events;

import ru.agentlab.maia.container.events.MaiaContextChangeObjectEvent;
import ru.agentlab.maia.container.events.MaiaContextRemoveObjectEvent;
import ru.agentlab.maia.container.events.MaiaContextSetObjectEvent;
import ru.agentlab.maia.event.IMaiaEventBroker;
import ru.agentlab.maia.exception.ServiceNotFound;
import ru.agentlab.maia.IContainer;
import ru.agentlab.maia.container.aspect.AContext;

public aspect AContextEvents extends AContext {

	void around(IContainer context, String id): onRemoveByString(context, id) {
		IMaiaEventBroker broker = null;
		Object old = null;
		try {
			broker = context.get(IMaiaEventBroker.class);
			old = context.getLocal(id);
		} catch (ServiceNotFound e){
		}

		proceed(context, id);

		if (broker != null) {
			if (old != null) {
				broker.post(new MaiaContextRemoveObjectEvent(old));
			}
		}
	}

	void around(IContainer context, Class<?> id): onRemoveByClass(context, id) {
		IMaiaEventBroker broker = null;
		Object old = null;
		try {
			broker = context.get(IMaiaEventBroker.class);
			old = context.getLocal(id);
		} catch (ServiceNotFound e){
		}

		proceed(context, id);

		if (broker != null) {
			if (old != null) {
				broker.post(new MaiaContextRemoveObjectEvent(old));
			}
		}
	}

	void around(IContainer context, String id, Object value): onSetByString(context, id, value) {
		IMaiaEventBroker broker = null;
		Object old = null;
		try {
			broker = context.get(IMaiaEventBroker.class);
			old = context.getLocal(id);
		} catch (ServiceNotFound e){
		}

		proceed(context, id, value);

		if (broker != null) {
			if (old == null) {
				broker.post(new MaiaContextSetObjectEvent(context, value));
			} else {
				broker.post(new MaiaContextChangeObjectEvent(context, value));
			}
		}
	}

	void around(IContainer context, Class<?> id, Object value): onSetByClass(context, id, value) {
		IMaiaEventBroker broker = null;
		Object old = null;
		try {
			broker = context.get(IMaiaEventBroker.class);
			old = context.getLocal(id);
		} catch (ServiceNotFound e){
		}

		proceed(context, id, value);

		if (broker != null) {
			if (old == null) {
				broker.post(new MaiaContextSetObjectEvent(context, value));
			} else {
				broker.post(new MaiaContextChangeObjectEvent(context, value));
			}
		}
	}
}

package ru.agentlab.maia.container.events;

import ru.agentlab.maia.container.events.MaiaContextChangeObjectEvent;
import ru.agentlab.maia.container.events.MaiaContextRemoveObjectEvent;
import ru.agentlab.maia.container.events.MaiaContextSetObjectEvent;
import ru.agentlab.maia.event.IMaiaEventBroker;
import ru.agentlab.maia.IContainer;
import ru.agentlab.maia.container.aspect.AContext;

public aspect AContextEvents extends AContext {

	void around(IContainer context, String id): onRemoveByString(context, id) {
		IMaiaEventBroker broker = null;
		Object old = null;
		broker = context.get(IMaiaEventBroker.class);
		old = context.getLocal(id);

		proceed(context, id);

		if (broker != null) {
			if (old != null) {
				broker.post(new MaiaContextRemoveObjectEvent(old));
			}
		}
	}

	void around(IContainer context, Class<?> id): onRemoveByClass(context, id) {
		IMaiaEventBroker broker = null;
		Object old = null;
		broker = context.get(IMaiaEventBroker.class);
		old = context.getLocal(id);

		proceed(context, id);

		if (broker != null) {
			if (old != null) {
				broker.post(new MaiaContextRemoveObjectEvent(old));
			}
		}
	}

	void around(IContainer context, String id, Object value): onSetByString(context, id, value) {
		IMaiaEventBroker broker = null;
		Object old = null;
		broker = context.get(IMaiaEventBroker.class);
		old = context.getLocal(id);

		proceed(context, id, value);

		if (broker != null) {
			if (old == null) {
				broker.post(new MaiaContextSetObjectEvent(context, value));
			} else {
				broker.post(new MaiaContextChangeObjectEvent(context, value));
			}
		}
	}

	void around(IContainer context, Class<?> id, Object value): onSetByClass(context, id, value) {
		IMaiaEventBroker broker = null;
		Object old = null;
		broker = context.get(IMaiaEventBroker.class);
		old = context.getLocal(id);

		proceed(context, id, value);

		if (broker != null) {
			if (old == null) {
				broker.post(new MaiaContextSetObjectEvent(context, value));
			} else {
				broker.post(new MaiaContextChangeObjectEvent(context, value));
			}
		}
	}
}


Missed file for previous commit.

Missed file for previous commit.

package damp.ekeko.aspectj.annasstests;

import damp.ekeko.aspectj.annotations.ExcludesPrevious;
import damp.ekeko.aspectj.annotations.Label;
import damp.ekeko.aspectj.annotations.RequiresPrevious;

//fixture for requires / excludes previous tests
public aspect PrevFix {

	//succeeds
	@RequiresPrevious("thinking")
	@ExcludesPrevious("cleaning")
	@Label("beforecompute")
	before() : call(int *.compute(String))
	{
		this.prepareCompute();
	}

	@Label("preparing")
	private void prepareCompute(){}

	//fails, never happens
	@RequiresPrevious("executing")
	//fails, always happens
	@ExcludesPrevious("thinking")
	after() : call(void *.simulate())
	{	}

	//fails, only sometimes happens
	@RequiresPrevious("executing")
	@ExcludesPrevious("simulating")
	void around() : execution(void *.cleanup())
	{
		proceed();
	}
}

package damp.ekeko.aspectj.annasstests;

import damp.ekeko.aspectj.annotations.ExcludesPrevious;
import damp.ekeko.aspectj.annotations.RequiresPrevious;

//fixture for requires / excludes previous tests
public aspect PrevFix {

	//succeeds
	@RequiresPrevious("thinking")
	@ExcludesPrevious("cleaning")
	before() : call(int *.compute(String))
	{	}

	//fails, never happens
	@RequiresPrevious("executing")
	//fails, always happens
	@ExcludesPrevious("thinking")
	after() : call(void *.simulate())
	{	}

	//fails, only sometimes happens
	@RequiresPrevious("executing")
	@ExcludesPrevious("simulating")
	void around() : execution(void *.cleanup())
	{
		proceed();
	}
}


*around pointcuts added for lock and unlock

package benchmark.competition.java.jUnitRV_MMT.monitoring;

import java.util.concurrent.locks.Lock;

import monitoring.impl.MonitorFactory;
import monitoring.intf.Monitor;
import properties.Property;
import properties.competition.JavaRV_mmt;
import structure.impl.other.Verdict;
import structure.intf.QEA;
import benchmark.competition.java.jUnitRV_MMT.ExampleLocking;

public aspect JUnitRV_MMTThreeAspect {

	private final Monitor monitor;

	private final int RUN = 1;
	private final int LOCK_TRUE = 2;
	private final int UNLOCK = 3;
	private final int ACTION = 4;

	public JUnitRV_MMTThreeAspect() {
		QEA qea = new JavaRV_mmt().make(Property.JAVARV_MMT_THREE);
		monitor = MonitorFactory.create(qea);
	}

	pointcut run(ExampleLocking thread) : execution(void ExampleLocking.run())
		&& target(thread);

	pointcut action(ExampleLocking thread) : call(void ExampleLocking.action())
		&& target(thread);

	before(ExampleLocking thread) : run(thread) {
		Verdict verdict = null;
		synchronized (monitor) {
			verdict = monitor.step(RUN, thread);
		}
		if (verdict == Verdict.FAILURE || verdict == Verdict.WEAK_FAILURE) {
			System.err
					.println("Violation in JUnitRV (MMT) 3. [thread="
							+ thread
							+ "]. - A thread has to call lock (returning true) to acquire the lock before it may call action - A call to lock only returns true, if no thread is currently holding the lock.");
		}
	};

	boolean around(Lock lockObj, ExampleLocking thread) :
			call(boolean Lock.tryLock())
			&& cflow(call(boolean ExampleLocking.lock())) && target(lockObj)
			&& this(thread) {

		boolean result = false;
		synchronized (lockObj) {
			result = proceed(lockObj, thread); // TODO Not sure if this is right
		}
		if (result) {
			Verdict verdict = null;
			synchronized (monitor) {
				verdict = monitor.step(LOCK_TRUE, thread);
			}
			if (verdict == Verdict.FAILURE || verdict == Verdict.WEAK_FAILURE) {
				System.err
						.println("Violation in JUnitRV (MMT) 3. [thread="
								+ thread
								+ "]. - A thread has to call lock (returning true) to acquire the lock before it may call action - A call to lock only returns true, if no thread is currently holding the lock.");
			}

		}
		return result;
	};

	void around(Lock lockObj, ExampleLocking thread) :
		call(void Lock.unlock()) && cflow(call(void ExampleLocking.unlock()))
		&& target(lockObj) && this(thread) {

		synchronized (lockObj) {
			proceed(lockObj, thread); // TODO Not sure if this is right
		}
		Verdict verdict = null;
		synchronized (monitor) {
			verdict = monitor.step(LOCK_TRUE, thread);
		}
		if (verdict == Verdict.FAILURE || verdict == Verdict.WEAK_FAILURE) {
			System.err
					.println("Violation in JUnitRV (MMT) 3. [thread="
							+ thread
							+ "]. - A thread has to call lock (returning true) to acquire the lock before it may call action - A call to lock only returns true, if no thread is currently holding the lock.");
		}
	};

	before(ExampleLocking thread) : action(thread) {
		Verdict verdict = null;
		synchronized (monitor) {
			verdict = monitor.step(ACTION, thread);
		}
		if (verdict == Verdict.FAILURE || verdict == Verdict.WEAK_FAILURE) {
			System.err
					.println("Violation in JUnitRV (MMT) 3. [id="
							+ thread
							+ "]. - A thread has to call lock (returning true) to acquire the lock before it may call action - A call to lock only returns true, if no thread is currently holding the lock.");
		}
	};

}

package benchmark.competition.java.jUnitRV_MMT.monitoring;

import monitoring.impl.MonitorFactory;
import monitoring.intf.Monitor;
import properties.Property;
import properties.competition.JavaRV_mmt;
import structure.impl.other.Verdict;
import structure.intf.QEA;
import benchmark.competition.java.jUnitRV_MMT.ExampleLocking;

public aspect JUnitRV_MMTThreeAspect {

	private final Monitor monitor;

	private final int RUN = 1;
	private final int LOCK_TRUE = 2;
	private final int UNLOCK = 3;
	private final int ACTION = 4;

	public JUnitRV_MMTThreeAspect() {
		QEA qea = new JavaRV_mmt().make(Property.JAVARV_MMT_THREE);
		monitor = MonitorFactory.create(qea);
	}

	pointcut run(ExampleLocking t) : execution(void ExampleLocking.run())
		&& target(t);

	pointcut lockEvent(ExampleLocking t) : call(boolean ExampleLocking.lock())
		&& target(t);

	pointcut unlockEvent(ExampleLocking t) :
		call(void ExampleLocking.unlock()) && target(t);

	pointcut action(ExampleLocking t) : call(void ExampleLocking.action())
		&& target(t);

	before(ExampleLocking t) : run(t) {
		Verdict verdict = null;
		synchronized (monitor) {
			verdict = monitor.step(RUN, t.getId());
		}
		if (verdict == Verdict.FAILURE || verdict == Verdict.WEAK_FAILURE) {
			System.err
					.println("Violation in JUnitRV (MMT) 3. [id="
							+ t.getId()
							+ "]. - A thread has to call lock (returning true) to acquire the lock before it may call action - A call to lock only returns true, if no thread is currently holding the lock.");
		}
	};

	after(ExampleLocking t) returning(boolean result) : lockEvent(t) {
		if (result) {
			Verdict verdict = null;
			synchronized (monitor) {
				verdict = monitor.step(LOCK_TRUE, t.getId());
			}
			if (verdict == Verdict.FAILURE || verdict == Verdict.WEAK_FAILURE) {
				System.err
						.println("Violation in JUnitRV (MMT) 3. [id="
								+ t.getId()
								+ "]. - A thread has to call lock (returning true) to acquire the lock before it may call action - A call to lock only returns true, if no thread is currently holding the lock.");
			}
		}
	};

	before(ExampleLocking t) : unlockEvent(t) {
		Verdict verdict = null;
		synchronized (monitor) {
			verdict = monitor.step(UNLOCK, t.getId());
		}
		if (verdict == Verdict.FAILURE || verdict == Verdict.WEAK_FAILURE) {
			System.err
					.println("Violation in JUnitRV (MMT) 3. [id="
							+ t.getId()
							+ "]. - A thread has to call lock (returning true) to acquire the lock before it may call action - A call to lock only returns true, if no thread is currently holding the lock.");
		}
	};

	before(ExampleLocking t) : action(t) {
		Verdict verdict = null;
		synchronized (monitor) {
			verdict = monitor.step(ACTION, t.getId());
		}
		if (verdict == Verdict.FAILURE || verdict == Verdict.WEAK_FAILURE) {
			System.err
					.println("Violation in JUnitRV (MMT) 3. [id="
							+ t.getId()
							+ "]. - A thread has to call lock (returning true) to acquire the lock before it may call action - A call to lock only returns true, if no thread is currently holding the lock.");
		}
	};

}


Simplify the aspect using intermediate classes added in the parallelj kernel (KProcessor, CallableProcedure, RunnableProcedure and SubProcessProcedure)

/*
 *     ParallelJ, framework for parallel computing
 *
 *     Copyright (C) 2010, 2011, 2012 Atos Worldline or third-party contributors as
 *     indicated by the @author tags or express copyright attribution
 *     statements applied by the authors.
 *
 *     This library 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.
 *
 *     This library 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 library; if not, write to the Free Software
 *     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */
package org.parallelj.launching.quartz;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.parallelj.Programs;
import org.parallelj.Programs.ProcessHelper;
import org.parallelj.internal.kernel.KProcess;
import org.parallelj.internal.kernel.KProcessor;
import org.parallelj.internal.kernel.KProgram;
import org.parallelj.internal.kernel.procedure.CallableProcedure;
import org.parallelj.internal.kernel.procedure.RunnableProcedure;
import org.parallelj.internal.reflect.ProgramAdapter.Adapter;
import org.parallelj.launching.LaunchingMessageKind;
import org.parallelj.launching.ReturnCodes;
import org.parallelj.mirror.ProgramType;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

/**
 * Implements the Job.execute(..) method
 *
 *
 */
privileged public aspect ProgramJobsAdapter {

	/*
	 * The Aspect JobsAdapter must be passed before this.
	 */
	declare precedence :
		org.parallelj.internal.kernel.Identifiers,
		org.parallelj.internal.reflect.ProgramAdapter,
		org.parallelj.internal.util.sm.impl.KStateMachines,
		org.parallelj.internal.util.sm.impl.KStateMachines.PerMachine,
		org.parallelj.Executables$PerExecutable,
		org.parallelj.internal.reflect.ProgramAdapter.PerProgram,
		org.parallelj.internal.log.Logs,
		org.parallelj.launching.quartz.JobsAdapter;

	/*
	 * Add the interface IProceduresInError to the KProcessor
	*/
	private interface IProceduresInError {
		public void addProcedureInError(String name, Exception exception);
	}
	public Map<String, Set<String>> IProceduresInError.proceduresInError=new HashMap<String, Set<String>>();

	public synchronized void IProceduresInError.addProcedureInError(String name, Exception exception) {
		Set<String> exceptions = ((IProceduresInError)this).proceduresInError.get(name);
		if (exceptions==null) {
			// This is the first "name" Procedure in error
			exceptions = new HashSet<String>();
		}
		if (!exceptions.contains(exception.getClass().getCanonicalName())) {
			exceptions.add(exception.getClass().getCanonicalName());
		}
		((IProceduresInError)this).proceduresInError.put(name, exceptions);
	}

	declare parents: org.parallelj.internal.kernel.KProcessor implements IProceduresInError;

	/**
	 * Launch a Program and initialize the Result as a JobDataMap.
	 *
	 * @param self
	 * @param context
	 * @throws JobExecutionException
	 */
	void around(Job self, JobExecutionContext context)
			throws JobExecutionException :
		execution( public void  Job+.execute(..) throws JobExecutionException)
			&& (within(@org.parallelj.Program *) || within(JobsAdapter))
				&& args(context) && this(self) {
		JobDataMap jobDataMap = new JobDataMap();
		context.setResult(jobDataMap);
		jobDataMap.put(QuartzUtils.RETURN_CODE, ReturnCodes.SUCCESS);

		proceed(self, context);

		try {
			// Initialize an ExecutorService with the Capacity of the Program
			ProcessHelper<?> processHelper = Programs.as((Adapter) self);
			if (processHelper == null) {
				jobDataMap.put(QuartzUtils.RETURN_CODE, ReturnCodes.NOTSTARTED);
				throw new JobExecutionException(LaunchingMessageKind.ELAUNCH0003.getFormatedMessage(self));
			}
			ProgramType programType = processHelper.getProcess().getProgram();
			ExecutorService service = null;
			// If an executorService was specified, we use it

			if (context.getJobDetail().getJobDataMap().get(Launch.DEFAULT_EXECUTOR_KEY) != null) {
				service = (ExecutorService)context.getJobDetail().getJobDataMap().get(Launch.DEFAULT_EXECUTOR_KEY);
			} else
			if (programType instanceof KProgram) {
				short programCapacity = ((KProgram) programType)
						.getCapacity();
				service = (programCapacity == Short.MAX_VALUE) ? Executors
						.newCachedThreadPool() : Executors
						.newFixedThreadPool(programCapacity);
			} else {
				service = Executors
						.newCachedThreadPool();
			}

			// Launch the program with the initialized ExecutorService
			processHelper.execute(service).join();

			KProcessor rootProcessor = ((KProcessor)processHelper.getProcess().getProcessor());
			IProceduresInError procedures = (IProceduresInError)rootProcessor;
			if(procedures.proceduresInError.size()>0) {
				jobDataMap.put(QuartzUtils.RETURN_CODE, ReturnCodes.FAILURE);
			}

			ProgramFieldsBinder.getProgramOutputFields(this, context);
			service.shutdown();

			if (procedures.proceduresInError.size()>0){
				jobDataMap.put(QuartzUtils.PROCEDURES_IN_ERROR, procedures.proceduresInError);
				throw new JobExecutionException();
			}
		} catch (IllegalAccessException e) {
			jobDataMap.put(QuartzUtils.RETURN_CODE, ReturnCodes.FAILURE);
			throw new JobExecutionException(e);
		} catch (NoSuchFieldException e) {
			jobDataMap.put(QuartzUtils.RETURN_CODE, ReturnCodes.FAILURE);
			throw new JobExecutionException(e);
		}
	}

	// Interception around Runnable execution
	void around(Object self): call(void complete())
		&& target(org.parallelj.internal.kernel.procedure.RunnableProcedure.RunnableCall)
		&& this(self)  {

		RunnableProcedure.RunnableCall runnable = (RunnableProcedure.RunnableCall)thisJoinPoint.getTarget();
		RunnableProcedure procedure = (RunnableProcedure)runnable.getProcedure();
		if (procedure.getHandler() == null
				&& runnable.getException() != null) {
			// There is an error !!!
			KProcess process = runnable.getProcess();
			KProcessor rootProcessor = process.getProcessor();//.getRootProcessor();
			((IProceduresInError)rootProcessor).addProcedureInError(procedure.getType(), runnable.getException());
		}
		proceed(self);
	}

	// Interception around Callable execution
	void around(Object self): call(void complete())
		&& target(org.parallelj.internal.kernel.procedure.CallableProcedure.CallableCall)
		&& this(self)  {

		CallableProcedure.CallableCall callable = (CallableProcedure.CallableCall)thisJoinPoint.getTarget();
		CallableProcedure procedure = (CallableProcedure)callable.getProcedure();

		if (
				procedure.getHandler() == null
				&& callable.getException() != null
				) {
			// There is an error !!!
			KProcess process = callable.getProcess();
			KProcessor rootProcessor = process.getProcessor();//.getRootProcessor();
			((IProceduresInError)rootProcessor).addProcedureInError(procedure.getType(), callable.getException());
		}
		proceed(self);
	}

	/*
	 * Allow to get the procedures in error of a Process (the root Process !!!)
	 */
	public static synchronized Map<String, Set<String>> getProceduresInErrors(
			org.parallelj.mirror.Process process) {
		KProcessor rootProcessor = ((KProcessor) process.getProcessor());
		IProceduresInError procedures = (IProceduresInError) rootProcessor;
		return procedures.proceduresInError;
	}
}

/*
 *     ParallelJ, framework for parallel computing
 *
 *     Copyright (C) 2010, 2011, 2012 Atos Worldline or third-party contributors as
 *     indicated by the @author tags or express copyright attribution
 *     statements applied by the authors.
 *
 *     This library 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.
 *
 *     This library 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 library; if not, write to the Free Software
 *     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */
package org.parallelj.launching.quartz;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.parallelj.Programs;
import org.parallelj.Programs.ProcessHelper;
import org.parallelj.internal.kernel.KProcess;
import org.parallelj.internal.kernel.KProcessor;
import org.parallelj.internal.kernel.KProgram;
import org.parallelj.internal.kernel.procedure.CallableProcedure;
import org.parallelj.internal.kernel.procedure.RunnableProcedure;
import org.parallelj.internal.reflect.ProgramAdapter.Adapter;
import org.parallelj.launching.LaunchingMessageKind;
import org.parallelj.launching.ReturnCodes;
import org.parallelj.mirror.ProgramType;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

/**
 * Implements the Job.execute(..) method
 *
 *
 */
privileged public aspect ProgramJobsAdapter {

	/*
	 * The Aspect JobsAdapter must be passed before this.
	 */
	declare precedence :
		org.parallelj.internal.kernel.Identifiers,
		org.parallelj.internal.reflect.ProgramAdapter,
		org.parallelj.internal.util.sm.impl.KStateMachines,
		org.parallelj.internal.util.sm.impl.KStateMachines.PerMachine,
		org.parallelj.Executables$PerExecutable,
		org.parallelj.internal.reflect.ProgramAdapter.PerProgram,
		org.parallelj.internal.log.Logs,
		org.parallelj.launching.quartz.JobsAdapter;

	/*
	 * Add the interface IProceduresInError to the KProcessor
	*/
	private interface IProceduresInError {
		public void addProcedureInError(String name, Exception exception);
	}
	public Map<String, Set<String>> IProceduresInError.proceduresInError=new HashMap<String, Set<String>>();

	public synchronized void IProceduresInError.addProcedureInError(String name, Exception exception) {
		Set<String> exceptions = ((IProceduresInError)this).proceduresInError.get(name);
		if (exceptions==null) {
			// This is the first "name" Procedure in error
			exceptions = new HashSet<String>();
		}
		if (!exceptions.contains(exception.getClass().getCanonicalName())) {
			exceptions.add(exception.getClass().getCanonicalName());
		}
		((IProceduresInError)this).proceduresInError.put(name, exceptions);
	}

	declare parents: org.parallelj.internal.kernel.KProcessor implements IProceduresInError;

	/**
	 * Launch a Program and initialize the Result as a JobDataMap.
	 *
	 * @param self
	 * @param context
	 * @throws JobExecutionException
	 */
	void around(Job self, JobExecutionContext context)
			throws JobExecutionException :
		execution( public void  Job+.execute(..) throws JobExecutionException)
			&& (within(@org.parallelj.Program *) || within(JobsAdapter))
				&& args(context) && this(self) {
		JobDataMap jobDataMap = new JobDataMap();
		context.setResult(jobDataMap);
		jobDataMap.put(QuartzUtils.RETURN_CODE, ReturnCodes.SUCCESS);

		proceed(self, context);

		try {
			// Initialize an ExecutorService with the Capacity of the Program
			ProcessHelper<?> processHelper = Programs.as((Adapter) self);
			if (processHelper == null) {
				jobDataMap.put(QuartzUtils.RETURN_CODE, ReturnCodes.NOTSTARTED);
				throw new JobExecutionException(LaunchingMessageKind.ELAUNCH0003.getFormatedMessage(self));
			}
			ProgramType programType = processHelper.getProcess().getProgram();
			ExecutorService service = null;
			// If an executorService was specified, we use it

			if (context.getJobDetail().getJobDataMap().get(Launch.DEFAULT_EXECUTOR_KEY) != null) {
				service = (ExecutorService)context.getJobDetail().getJobDataMap().get(Launch.DEFAULT_EXECUTOR_KEY);
			} else
			if (programType instanceof KProgram) {
				short programCapacity = ((KProgram) programType)
						.getCapacity();
				service = (programCapacity == Short.MAX_VALUE) ? Executors
						.newCachedThreadPool() : Executors
						.newFixedThreadPool(programCapacity);
			} else {
				service = Executors
						.newCachedThreadPool();
			}

			// Launch the program with the initialized ExecutorService
			processHelper.execute(service).join();

			KProcessor rootProcessor = ((KProcessor)processHelper.getProcess().getProcessor());
			IProceduresInError procedures = (IProceduresInError)rootProcessor;
			if(procedures.proceduresInError.size()>0) {
				jobDataMap.put(QuartzUtils.RETURN_CODE, ReturnCodes.FAILURE);
			}

			ProgramFieldsBinder.getProgramOutputFields(this, context);
			service.shutdown();

			if (procedures.proceduresInError.size()>0){
				jobDataMap.put(QuartzUtils.PROCEDURES_IN_ERROR, procedures.proceduresInError);
				throw new JobExecutionException();
			}
		} catch (IllegalAccessException e) {
			jobDataMap.put(QuartzUtils.RETURN_CODE, ReturnCodes.FAILURE);
			throw new JobExecutionException(e);
		} catch (NoSuchFieldException e) {
			jobDataMap.put(QuartzUtils.RETURN_CODE, ReturnCodes.FAILURE);
			throw new JobExecutionException(e);
		}
	}

	/*
	 * Add the interface IExceptionTracking to all Runnable and Callable
	 */
    public interface IExceptionTracking {};
  	private Object IExceptionTracking.context = null;

    declare parents:
    	(java.lang.Runnable+ ) implements IExceptionTracking;
    declare parents:
    	(java.util.concurrent.Callable+ ) implements IExceptionTracking;

	// Interception around Runnable execution
  	after(Object self) returning (Runnable ret):
  		execution(* org.parallelj.internal.kernel.procedure.RunnableProcedure.RunnableCall.toRunnable())
      && this(self)  {
   	  ((IExceptionTracking)ret).context = ((org.parallelj.internal.kernel.KCall)self);
    }

	// Interception around Callable execution
  	after(Object self) returning (Runnable ret):
  		execution(* org.parallelj.internal.kernel.procedure.CallableProcedure.CallableCall.toRunnable())
      && this(self)  {
   	  ((IExceptionTracking)ret).context = ((org.parallelj.internal.kernel.KCall)self);
    }

	// Interception around Runnable execution
	 void around(Object self): call(void complete())
	&& within(org.parallelj.internal.kernel.procedure.RunnableProcedure.RunnableCall)
		&& this(self)  {

			RunnableProcedure.RunnableCall runnable = (RunnableProcedure.RunnableCall)((IExceptionTracking)self).context;
			RunnableProcedure procedure = (RunnableProcedure)runnable.getProcedure();
			if (procedure.getHandler() == null
					&& runnable.getException() != null) {
				// There is an error !!!
				KProcess process = ((RunnableProcedure.RunnableCall)((IExceptionTracking)self).context).getProcess();
				KProcessor rootProcessor = process.getProcessor();//.getRootProcessor();
				((IProceduresInError)rootProcessor).addProcedureInError(procedure.getType(), runnable.getException());
			}
		proceed(self);
	}

	// Interception around Callable execution
	 void around(Object self): call(void complete())
		 && within(org.parallelj.internal.kernel.procedure.CallableProcedure.CallableCall)
		&& this(self)  {

			CallableProcedure.CallableCall callable = (CallableProcedure.CallableCall)((IExceptionTracking)self).context;
			CallableProcedure procedure = (CallableProcedure)callable.getProcedure();

			if (
					procedure.getHandler() == null
					&& callable.getException() != null
					) {
				// There is an error !!!
				KProcess process = ((CallableProcedure.CallableCall)((IExceptionTracking)self).context).getProcess();
				KProcessor rootProcessor = process.getProcessor();//.getRootProcessor();
				((IProceduresInError)rootProcessor).addProcedureInError(procedure.getType(), callable.getException());
			}
		proceed(self);
	}

	/*
	 * Allow to get the procedures in error of a Process (the root Process !!!)
	 */
	public static synchronized Map<String, Set<String>> getProceduresInErrors(
			org.parallelj.mirror.Process process) {
		KProcessor rootProcessor = ((KProcessor) process.getProcessor());
		IProceduresInError procedures = (IProceduresInError) rootProcessor;
		return procedures.proceduresInError;
	}
}


corriger les import dans myfirstaspectj.aj

package it.sauronsoftware;
import it.sauronsoftware.cron4j.Task;
import it.sauronsoftware.cron4j.TaskExecutionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;

public aspect MyFirstAspecj{
    public static final Logger LOGGER = LoggerFactory.getLogger(MyAspectTrace.class);

    private Map<Task, AtomicLong> counters = new HashMap<Task, AtomicLong>();
    private ThreadLocal<AtomicLong> local = new ThreadLocal<AtomicLong>();

    pointcut run(TaskExecutionContext context) : execution(it.sauronsoftware.cron4j.RunnableTask.execute             (TaskExecutionContext context));

    before(TaskExecutionContext context) : run() && args(context){
           Task task = context.getTaskExecutor().getTask();

        // Code using the global map
        AtomicLong count = counters.get(task);
        if (count == null) {
            count = new AtomicLong(0);
            counters.put(task, count);
        }
        long n1 = count.incrementAndGet();

        // Code using the thread local
        count = local.get();
        if (count == null) {
            count = new AtomicLong(0);
            local.set(count);
        }
        long n2 = count.incrementAndGet();
        LOGGER.info("Calling {} - execution #{},{} - thread[{}]", task, n1, n2, Thread.currentThread().getId());
    }

    after(TaskExecutionContext context) : run() && args(context){
        Task task = context.getTaskExecutor().getTask();
        // Cannot be null, it was necessarily set in `before`.
        long n1 = counters.get(task).get();
        long n2 = local.get().get();
        LOGGER.info("End of {}#{},{}", task, n1, n2);
    }
}


Fix syntax error due to missing semicolon

package tlc2.tool.distributed;

public aspect RMIMethodMonitorAspect {

	// catch all method calls to RMI methods
	pointcut callToRemoteMethod() :
		   execution(* tlc2.tool.distributed.InternRMI.*(..))
		|| execution(* tlc2.tool.distributed.TLCServerRMI.*(..))
		|| execution(* tlc2.tool.distributed.TLCWorkerRMI.*(..))
		|| execution(* tlc2.tool.distributed.fp.FPSetRMI.*(..));

	before(): (callToRemoteMethod()) {
		RMIMethodMonitor.entering(thisJoinPoint);
	}
}

package tlc2.tool.distributed;

public aspect RMIMethodMonitorAspect {

	// catch all method calls to RMI methods
	pointcut callToRemoteMethod() :
		   execution(* tlc2.tool.distributed.InternRMI.*(..))
		|| execution(* tlc2.tool.distributed.TLCServerRMI.*(..))
		|| execution(* tlc2.tool.distributed.TLCWorkerRMI.*(..))
		|| execution(* tlc2.tool.distributed.fp.FPSetRMI.*(..))

	before(): (callToRemoteMethod()) {
		RMIMethodMonitor.entering(thisJoinPoint);
	}
}


added ui update

added ui update

import java.awt.Component;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.swing.JFileChooser;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;

import model.SystemValues;
import model.db.DataObject;
import model.db.GameData;
import view.GUI;
import view.SchafkopfTableModel;

privileged aspect Import {

    private GUI gui;

    /**
     * catch constructor call, so that we have the correct gui, to refer to everywhere
     */
    after() returning(GUI gui): call(GUI.new(*)) {
        this.gui = gui;
    }

    private void importFromHtmlTable(BufferedReader in) throws IOException {
        GameData newData = new GameData();
        String line;

        while((line=in.readLine()) != null) {
            if (line.startsWith("
")) {
                line = line.replaceAll("
", "");
                line = line.replaceAll("
", "");
                if (line.startsWith("")) {
                    line = line.replaceAll("	", "");
                    line = line.replaceFirst("", "");
                    String[] tmp = line.split("");
                    SystemValues.Players.PLAYER_1.setName(tmp[4]);
                    SystemValues.Players.PLAYER_2.setName(tmp[5]);
                    SystemValues.Players.PLAYER_3.setName(tmp[6]);
                    SystemValues.Players.PLAYER_4.setName(tmp[7]);
                    continue;
                } else if (!line.startsWith("")) {
                    continue;
                }
                line = line.replaceAll("	", "");
                line = line.replaceFirst("", "");
                String[] tmp = line.split("");
                // first line is ignored
                if (tmp[0].equals("0")) {
                    continue;
                }
                newData.addData(new DataObject(tmp));
            }
        }
        gui.model.gameDB = newData;
        gui.table.setModel(new SchafkopfTableModel(gui.model.getGameData()));
        gui.updateValues();
    }

    after() returning(JMenuBar bar): call(JMenuBar GUI.createMenu()) {
        JMenuItem itemLoad = new JMenuItem("Spielstand laden");
        itemLoad.addActionListener(new LoadFileListener());

        Component[] menus = bar.getComponents();
        if (menus.length != 0 && menus[0] instanceof JMenu) {
            ((JMenu)bar.getComponents()[0]).add(itemLoad);
        } else {
            throw new AssertionError("There should be a menu entry!");
        }
    }

    after() : execution(* LoadFileListener.actionPerformed(*)) {
        JFileChooser chooser = new JFileChooser();
        if (chooser.showOpenDialog(gui) == JFileChooser.APPROVE_OPTION) {
            try {
                BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(chooser.getSelectedFile())));
                if (!LoadFileListener.setSystemValues(in.readLine(), in.readLine())) {
                    JOptionPane.showConfirmDialog(gui, "Laden fehlgeschlagen\n(Ungültiges Dateiformat)");
                    in.close();
                }
                importFromHtmlTable(in);
                gui.tabbedPane.setEnabledAt(1, true);
                gui.repaint();
            } catch (IOException e1) {
                JOptionPane.showConfirmDialog(gui, "Laden fehlgeschlagen\n"+e1.getMessage());
            }
        }
    }
}

import java.awt.Component;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.swing.JFileChooser;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;

import model.SystemValues;
import model.db.DataObject;
import model.db.GameData;
import view.GUI;
import view.SchafkopfTableModel;

privileged aspect Import {

    private GUI gui;

    /**
     * catch constructor call, so that we have the correct gui, to refer to everywhere
     */
    after() returning(GUI gui): call(GUI.new(*)) {
        this.gui = gui;
    }

    private void importFromHtmlTable(BufferedReader in) throws IOException {
        GameData newData = new GameData();
        String line;

        while((line=in.readLine()) != null) {
            if (line.startsWith("
")) {
                line = line.replaceAll("
", "");
                line = line.replaceAll("
", "");
                if (line.startsWith("")) {
                    line = line.replaceAll("	", "");
                    line = line.replaceFirst("", "");
                    String[] tmp = line.split("");
                    SystemValues.Players.PLAYER_1.setName(tmp[4]);
                    SystemValues.Players.PLAYER_2.setName(tmp[5]);
                    SystemValues.Players.PLAYER_3.setName(tmp[6]);
                    SystemValues.Players.PLAYER_4.setName(tmp[7]);
                    continue;
                } else if (!line.startsWith("")) {
                    continue;
                }
                line = line.replaceAll("	", "");
                line = line.replaceFirst("", "");
                String[] tmp = line.split("");
                // first line is ignored
                if (tmp[0].equals("0")) {
                    continue;
                }
                newData.addData(new DataObject(tmp));
            }
        }
        gui.model.gameDB = newData;
        gui.table.setModel(new SchafkopfTableModel(gui.model.getGameData()));
    }

    after() returning(JMenuBar bar): call(JMenuBar GUI.createMenu()) {
        JMenuItem itemLoad = new JMenuItem("Spielstand laden");
        itemLoad.addActionListener(new LoadFileListener());

        Component[] menus = bar.getComponents();
        if (menus.length != 0 && menus[0] instanceof JMenu) {
            ((JMenu)bar.getComponents()[0]).add(itemLoad);
        } else {
            throw new AssertionError("There should be a menu entry!");
        }
    }

    after() : execution(* LoadFileListener.actionPerformed(*)) {
        JFileChooser chooser = new JFileChooser();
        if (chooser.showOpenDialog(gui) == JFileChooser.APPROVE_OPTION) {
            try {
                BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(chooser.getSelectedFile())));
                if (!LoadFileListener.setSystemValues(in.readLine(), in.readLine())) {
                    JOptionPane.showConfirmDialog(gui, "Laden fehlgeschlagen\n(Ungültiges Dateiformat)");
                    in.close();
                }
                importFromHtmlTable(in);
                gui.tabbedPane.setEnabledAt(1, true);
                gui.repaint();
            } catch (IOException e1) {
                JOptionPane.showConfirmDialog(gui, "Laden fehlgeschlagen\n"+e1.getMessage());
            }
        }
    }
}


changes made by roo

changes made by roo

// WARNING: DO NOT EDIT THIS FILE. THIS FILE IS MANAGED BY SPRING ROO.
// You may push code into the target .java compilation unit if you wish to edit any member(s).

package org.datacite.mds.web;

import java.io.UnsupportedEncodingException;
import java.lang.Long;
import java.lang.String;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.datacite.mds.domain.Datacentre;
import org.datacite.mds.domain.Dataset;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.support.GenericConversionService;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.util.UriUtils;
import org.springframework.web.util.WebUtils;

privileged aspect DatasetController_Roo_Controller {

    @Autowired
    private GenericConversionService DatasetController.conversionService;

    @RequestMapping(params = "form", method = RequestMethod.GET)
    public String DatasetController.createForm(Model model) {
        model.addAttribute("dataset", new Dataset());
        List dependencies = new ArrayList();
        if (Datacentre.countDatacentres() == 0) {
            dependencies.add(new String[]{"datacentre", "datacentres"});
        }
        model.addAttribute("dependencies", dependencies);
        return "datasets/create";
    }

    @RequestMapping(value = "/{id}", params = "form", method = RequestMethod.GET)
    public String DatasetController.updateForm(@PathVariable("id") Long id, Model model) {
        model.addAttribute("dataset", Dataset.findDataset(id));
        return "datasets/update";
    }

    @RequestMapping(params = { "find=ByDoiEquals", "form" }, method = RequestMethod.GET)
    public String DatasetController.findDatasetsByDoiEqualsForm(Model model) {
        return "datasets/findDatasetsByDoiEquals";
    }

    @RequestMapping(params = "find=ByDoiEquals", method = RequestMethod.GET)
    public String DatasetController.findDatasetsByDoiEquals(@RequestParam("doi") String doi, Model model) {
        model.addAttribute("datasets", Dataset.findDatasetsByDoiEquals(doi).getResultList());
        return "datasets/list";
    }

    private String DatasetController.encodeUrlPathSegment(String pathSegment, HttpServletRequest request) {
        String enc = request.getCharacterEncoding();
        if (enc == null) {
            enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
        }
        try {
            pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
        }
        catch (UnsupportedEncodingException uee) {}
        return pathSegment;
    }

}

// WARNING: DO NOT EDIT THIS FILE. THIS FILE IS MANAGED BY SPRING ROO.
// You may push code into the target .java compilation unit if you wish to edit any member(s).

package org.datacite.mds.web;

import java.io.UnsupportedEncodingException;
import java.lang.Long;
import java.lang.String;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.datacite.mds.domain.Datacentre;
import org.datacite.mds.domain.Dataset;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.support.GenericConversionService;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.util.UriUtils;
import org.springframework.web.util.WebUtils;

privileged aspect DatasetController_Roo_Controller {

    @Autowired
    private GenericConversionService DatasetController.conversionService;

    @RequestMapping(params = "form", method = RequestMethod.GET)
    public String DatasetController.createForm(Model model) {
        model.addAttribute("dataset", new Dataset());
        List dependencies = new ArrayList();
        if (Datacentre.countDatacentres() == 0) {
            dependencies.add(new String[]{"datacentre", "datacentres"});
        }
        model.addAttribute("dependencies", dependencies);
        return "datasets/create";
    }

    @RequestMapping(value = "/{id}", params = "form", method = RequestMethod.GET)
    public String DatasetController.updateForm(@PathVariable("id") Long id, Model model) {
        model.addAttribute("dataset", Dataset.findDataset(id));
        return "datasets/update";
    }

    @RequestMapping(params = { "find=ByDoiEquals", "form" }, method = RequestMethod.GET)
    public String DatasetController.findDatasetsByDoiEqualsForm(Model model) {
        return "datasets/findDatasetsByDoiEquals";
    }

    @RequestMapping(params = "find=ByDoiEquals", method = RequestMethod.GET)
    public String DatasetController.findDatasetsByDoiEquals(@RequestParam("doi") String doi, Model model) {
        model.addAttribute("datasets", Dataset.findDatasetsByDoiEquals(doi).getResultList());
        return "datasets/list";
    }

    private String DatasetController.encodeUrlPathSegment(String pathSegment, HttpServletRequest request) {
        String enc = request.getCharacterEncoding();
        if (enc == null) {
            enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
        }
        try {
            pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
        }
        catch (UnsupportedEncodingException uee) {}
        return pathSegment;
    }

}


the map won't be null now

the map won't be null now

package com.mebigfatguy.hashshmash;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

import org.aspectj.lang.Signature;

public aspect HashCollector {

    private static final Journaller journaller = new Journaller();

    after() returning (Map m): call(HashMap.new(..)) {
        Signature sig = thisJoinPointStaticPart.getSignature();
        int line = thisJoinPointStaticPart.getSourceLocation().getLine();

        HashMapDetails details = new HashMapDetails(m, System.currentTimeMillis(), sig + ":" + line);
        journaller.add(details);
    }
}

final class Journaller implements Runnable {

    private static final int SLEEP_TIME = 10 * 1000;

    private Field tableField;
    private ConcurrentHashMap<HashMapDetails, HashMapDetails> hmDetails = new ConcurrentHashMap<HashMapDetails, HashMapDetails>();
    private PrintWriter writer;

    public Journaller() {
        try {
            tableField = HashMap.class.getDeclaredField("table");
            tableField.setAccessible(true);

            File dir = new File(System.getProperty("user.home"), ".hashshmash");
            dir.mkdirs();

            writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(dir, new Date().toString() + ".txt")))));

            Thread t = new Thread(this);
            t.setDaemon(true);
            t.start();
        } catch (Exception e) {
        }
    }

    public void add(HashMapDetails details) {
        hmDetails.put(details,  details);
    }

    public void run() {
        try {
            while (!Thread.interrupted()) {
                Thread.sleep(SLEEP_TIME);

                for (HashMapDetails details : hmDetails.keySet()) {
                    try {
                        int newSize = details.map.size();
                        if (newSize == details.size) {
                            Entry<?, ?>[] table = (Entry<?, ?>[])tableField.get(details.map);
                            details.totalSlots = table.length;
                            for (Entry<?, ?> e : table) {
                                if (e != null) {
                                    details.usedSlots++;
                                }
                            }
                            writer.println(details.allocTime + "\t" + details.caller + "\t" + details.map.size() + "\t" + details.totalSlots + "\t" + details.usedSlots);
                            hmDetails.remove(details);
                        }
                    } catch (Exception e) {
                        //might get ConcurrentModificationException or such, just ignore
                    }
                }
                writer.flush();
            }
        } catch (InterruptedException ie) {
        }
    }
}

class HashMapDetails {
    public Map<?, ?> map;
    public long allocTime;
    public String caller;
    public int size;
    public int usedSlots;
    public int totalSlots;

    public HashMapDetails(Map<?, ?> m, long t, String c) {
        map = m;
        allocTime = t;
        caller = c;
        size = map.size();
    }
}

package com.mebigfatguy.hashshmash;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

import org.aspectj.lang.Signature;

public aspect HashCollector {

    private static final Journaller journaller = new Journaller();

    after() returning (Map m): call(HashMap.new(..)) {
        Signature sig = thisJoinPointStaticPart.getSignature();
        int line = thisJoinPointStaticPart.getSourceLocation().getLine();

        HashMapDetails details = new HashMapDetails(m, System.currentTimeMillis(), sig + ":" + line);
        journaller.add(details);
    }
}

final class Journaller implements Runnable {

    private static final int SLEEP_TIME = 10 * 1000;

    private Field tableField;
    private ConcurrentHashMap<HashMapDetails, HashMapDetails> hmDetails = new ConcurrentHashMap<HashMapDetails, HashMapDetails>();
    private PrintWriter writer;

    public Journaller() {
        try {
            tableField = HashMap.class.getDeclaredField("table");
            tableField.setAccessible(true);

            File dir = new File(System.getProperty("user.home"), ".hashshmash");
            dir.mkdirs();

            writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(dir, new Date().toString() + ".txt")))));

            Thread t = new Thread(this);
            t.setDaemon(true);
            t.start();
        } catch (Exception e) {
        }
    }

    public void add(HashMapDetails details) {
        hmDetails.put(details,  details);
    }

    public void run() {
        try {
            while (!Thread.interrupted()) {
                Thread.sleep(SLEEP_TIME);

                for (HashMapDetails details : hmDetails.keySet()) {
                    try {
                        if (details.map != null) {
                            int newSize = details.map.size();
                            if (newSize == details.size) {
                                Entry<?, ?>[] table = (Entry<?, ?>[])tableField.get(details.map);
                                details.totalSlots = table.length;
                                for (Entry<?, ?> e : table) {
                                    if (e != null) {
                                        details.usedSlots++;
                                    }
                                }
                                writer.println(details.allocTime + "\t" + details.caller + "\t" + details.map.size() + "\t" + details.totalSlots + "\t" + details.usedSlots);
                                hmDetails.remove(details);
                            }
                        }
                    } catch (Exception e) {
                        //might get ConcurrentModificationException or such, just ignore
                    }
                }
                writer.flush();
            }
        } catch (InterruptedException ie) {
        }
    }
}

class HashMapDetails {
    public Map<?, ?> map;
    public long allocTime;
    public String caller;
    public int size;
    public int usedSlots;
    public int totalSlots;

    public HashMapDetails(Map<?, ?> m, long t, String c) {
        map = m;
        allocTime = t;
        caller = c;
        size = map.size();
    }
}


- Remove pointcut to deleted interface
- Reflect new .fp package in pointcut

git-svn-id: 7acc490bd371dbc82047a939b87dc892fdc31f59@28619 76a6fc44-f60b-0410-a9a8-e67b0e8fc65c

package tlc2.tool.distributed;

public aspect RMIMethodMonitorAspect {

	// catch all method calls to RMI methods
	pointcut callToRemoteMethod() :
		   execution(* tlc2.tool.distributed.InternRMI.*(..))
		|| execution(* tlc2.tool.distributed.TLCServerRMI.*(..))
		|| execution(* tlc2.tool.distributed.TLCWorkerRMI.*(..))
		|| execution(* tlc2.tool.distributed.fp.FPSetRMI.*(..))

	before(): (callToRemoteMethod()) {
		RMIMethodMonitor.entering(thisJoinPoint);
	}
}

package tlc2.tool.distributed;

public aspect RMIMethodMonitorAspect {

	// catch all method calls to RMI methods
	pointcut callToRemoteMethod() :
		   execution(* tlc2.tool.distributed.InternRMI.*(..))
		|| execution(* tlc2.tool.distributed.TLCServerRMI.*(..))
		|| execution(* tlc2.tool.distributed.TLCWorkerRMI.*(..))
		|| execution(* tlc2.tool.distributed.FPSetRMI.*(..))
		|| execution(* tlc2.tool.distributed.FPIntSetRMI.*(..));

	before(): (callToRemoteMethod()) {
		RMIMethodMonitor.entering(thisJoinPoint);
	}
}