fixed merge error

fixed merge error

package org.springframework.datastore.graph.neo4j.spi.node;

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.Autowired;
import org.springframework.datastore.graph.api.GraphEntity;
import org.springframework.datastore.graph.api.NodeBacked;
import org.springframework.datastore.graph.api.RelationshipBacked;
import org.springframework.datastore.graph.neo4j.fieldaccess.*;
import org.springframework.datastore.graph.neo4j.support.GraphDatabaseContext;
import org.springframework.persistence.support.AbstractTypeAnnotatingMixinFields;

import org.springframework.persistence.support.AbstractConstructorEntityInstantiator;
import org.springframework.datastore.graph.neo4j.spi.node.Neo4jConstructorGraphEntityInstantiator;
import org.springframework.datastore.graph.neo4j.spi.relationship.ConstructorBypassingGraphRelationshipInstantiator;

import java.lang.reflect.Field;

import static org.springframework.datastore.graph.neo4j.fieldaccess.DoReturn.unwrap;
import org.springframework.datastore.graph.neo4j.fieldaccess.NodeEntityStateAccessorsFactory;
import org.springframework.persistence.support.StateProvider;

/**
 * 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<GraphEntity, NodeBacked> {
    private GraphDatabaseContext graphDatabaseContext;
    private NodeEntityStateAccessorsFactory entityStateAccessorsFactory;

    @Autowired
    public void init(GraphDatabaseContext graphDatabaseContext, NodeEntityStateAccessorsFactory entityStateAccessorsFactory) {
        this.graphDatabaseContext = graphDatabaseContext;
        this.entityStateAccessorsFactory = entityStateAccessorsFactory;
    }
	//-------------------------------------------------------------------------
	// Advise user-defined constructors of NodeBacked objects to create a new Neo4J backing node
	//-------------------------------------------------------------------------
	pointcut arbitraryUserConstructorOfNodeBackedObject(NodeBacked entity) :
		execution((@GraphEntity *).new(..)) &&
		!execution((@GraphEntity *).new(Node)) &&
		this(entity) && !cflowbelow(call(* fromStateInternal(..)));

	// Create a new node in the Graph if no Node was passed in a constructor
    before(NodeBacked entity): arbitraryUserConstructorOfNodeBackedObject(entity) {
        if (entityStateAccessorsFactory == null) {
            log.error("entityStateAccessorsFactory not set, not creating accessors for " + entity.getClass());
        } else {
            entity.stateAccessors = entityStateAccessorsFactory.getEntityStateAccessors(entity);
            Node node = StateProvider.retrieveState();
            if (node != null) {
                entity.setUnderlyingState(node);
            } else {
                if (graphDatabaseContext.transactionIsRunning()) {
                    entity.stateAccessors.createAndAssignState();
                } else {
                    log.warn("New Nodebacked created outside of transaction " + entity.getClass());
                }
            }

        }
    }

    // Introduced field
	private transient Node NodeBacked.underlyingNode;
    private transient EntityStateAccessors<NodeBacked,Node> NodeBacked.stateAccessors;

    /*
    public NodeBacked.new(Node n) {
       this.setUnderlyingState(n);
    }
    */
	public void NodeBacked.setUnderlyingState(Node n) {
		this.underlyingNode = n;
        if (this.stateAccessors == null) {
            this.stateAccessors = Neo4jNodeBacking.aspectOf().entityStateAccessorsFactory.getEntityStateAccessors(this);
        } else {
            this.stateAccessors.setUnderlyingState(n);
        }
	}

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

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

    public boolean NodeBacked.hasUnderlyingNode() {
        return underlyingNode!=null;
    }

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

	public Long NodeBacked.getNodeId() {
        if (!hasUnderlyingNode()) return null;
		return underlyingNode.getId();
	}

    public  Iterable<? extends NodeBacked> NodeBacked.find(final Class<? extends NodeBacked> targetType, TraversalDescription traversalDescription) {
        if (!hasUnderlyingNode()) throw new IllegalStateException("No node attached to " + this);
        final Traverser traverser = traversalDescription.traverse(this.getUnderlyingState());
        return new NodeBackedNodeIterableWrapper(traverser, targetType, Neo4jNodeBacking.aspectOf().graphDatabaseContext);
    }
    /* todo Andy Clement
    public Iterable<? extends NodeBacked> NodeBacked.traverse(TraversalDescription traversalDescription) {
        final Class<? extends NodeBacked> target = this.getClass();
        return this.traverse(target,traversalDescription);
    }
    */

    /* todo Andy Clement
    public <R extends RelationshipBacked, N extends NodeBacked> R NodeBacked.relateTo(N node, Class<R> relationshipType, String type) {
        Relationship rel = this.getUnderlyingState().createRelationshipTo(node.getUnderlyingState(), DynamicRelationshipType.withName(type));
        Neo4jNodeBacking.aspectOf().relationshipEntityInstantiator.createEntityFromState(rel, relationshipType);
    }
    */

    public RelationshipBacked NodeBacked.relateTo(NodeBacked node, Class<? extends RelationshipBacked> relationshipType, String type) {
        Relationship rel = this.getUnderlyingState().createRelationshipTo(node.getUnderlyingState(), DynamicRelationshipType.withName(type));
        return Neo4jNodeBacking.aspectOf().graphDatabaseContext.createEntityFromState(rel, relationshipType);
    }

    public void NodeBacked.removeRelationshipTo(NodeBacked node, 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)) {
                rel.delete();
                return;
            }
        }
        return;
    }

    public RelationshipBacked NodeBacked.getRelationshipTo(NodeBacked node, Class<? extends RelationshipBacked> relationshipType, 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 Neo4jNodeBacking.aspectOf().graphDatabaseContext.createEntityFromState(rel, relationshipType);
        }
        return null;
    }

	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;
	}

	public final int NodeBacked.hashCode() {
        if (!hasUnderlyingNode()) return System.identityHashCode(this);
		return getUnderlyingState().hashCode();
	}

    Object around(NodeBacked entity): entityFieldGet(entity) {
        Object result=entity.stateAccessors.getValue(field(thisJoinPoint));
        if (result instanceof DoReturn) return unwrap(result);
        return proceed(entity);
    }

    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();
    }
}

package org.springframework.datastore.graph.neo4j.spi.node;

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.Autowired;
import org.springframework.datastore.graph.api.GraphEntity;
import org.springframework.datastore.graph.api.NodeBacked;
import org.springframework.datastore.graph.api.RelationshipBacked;
import org.springframework.datastore.graph.neo4j.fieldaccess.*;
import org.springframework.datastore.graph.neo4j.support.GraphDatabaseContext;
import org.springframework.persistence.support.AbstractTypeAnnotatingMixinFields;

import org.springframework.persistence.support.AbstractConstructorEntityInstantiator;
import org.springframework.datastore.graph.neo4j.spi.node.Neo4jConstructorGraphEntityInstantiator;
import org.springframework.datastore.graph.neo4j.spi.relationship.ConstructorBypassingGraphRelationshipInstantiator;

import java.lang.reflect.Field;

import static org.springframework.datastore.graph.neo4j.fieldaccess.DoReturn.unwrap;
import org.springframework.datastore.graph.neo4j.fieldaccess.NodeEntityStateAccessorsFactory;
import org.springframework.persistence.support.StateProvider;

/**
 * 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<GraphEntity, NodeBacked> {
    private GraphDatabaseContext graphDatabaseContext;
    private NodeEntityStateAccessorsFactory entityStateAccessorsFactory;

    @Autowired
    public void init(GraphDatabaseContext graphDatabaseContext, NodeEntityStateAccessorsFactory entityStateAccessorsFactory) {
        this.graphDatabaseContext = graphDatabaseContext;
        this.entityStateAccessorsFactory = entityStateAccessorsFactory;
    }
	//-------------------------------------------------------------------------
	// Advise user-defined constructors of NodeBacked objects to create a new Neo4J backing node
	//-------------------------------------------------------------------------
	pointcut arbitraryUserConstructorOfNodeBackedObject(NodeBacked entity) :
		execution((@GraphEntity *).new(..)) &&
		!execution((@GraphEntity *).new(Node)) &&
		this(entity) && !cflowbelow(call(* fromStateInternal(..)));

	// Create a new node in the Graph if no Node was passed in a constructor
    before(NodeBacked entity): arbitraryUserConstructorOfNodeBackedObject(entity) {
        if (entityStateAccessorsFactory == null) {
            log.error("entityStateAccessorsFactory not set, not creating accessors for " + entity.getClass());
        } else {
            entity.stateAccessors = entityStateAccessorsFactory.getEntityStateAccessors(entity);
            Node node = StateProvider.retrieveState();
            if (node != null) {
                entity.setUnderlyingState(node);
            } else {
                if (log.isWarnEnabled()) log.warn("New Nodebacked created outside of transaction " + entity.getClass());
                else {}

                if (graphDatabaseContext.transactionIsRunning()) {
                    entity.stateAccessors.createAndAssignState();
                } else {
                    log.warn("New Nodebacked created outside of transaction " + entity.getClass());
                }
            }
        }
    }

    // Introduced field
	private transient Node NodeBacked.underlyingNode;
    private transient EntityStateAccessors<NodeBacked,Node> NodeBacked.stateAccessors;

    /*
    public NodeBacked.new(Node n) {
       this.setUnderlyingState(n);
    }
    */
	public void NodeBacked.setUnderlyingState(Node n) {
		this.underlyingNode = n;
        if (this.stateAccessors == null) {
            this.stateAccessors = Neo4jNodeBacking.aspectOf().entityStateAccessorsFactory.getEntityStateAccessors(this);
        } else {
            this.stateAccessors.setUnderlyingState(n);
        }
	}

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

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

    public boolean NodeBacked.hasUnderlyingNode() {
        return underlyingNode!=null;
    }

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

	public Long NodeBacked.getNodeId() {
        if (!hasUnderlyingNode()) return null;
		return underlyingNode.getId();
	}

    public  Iterable<? extends NodeBacked> NodeBacked.find(final Class<? extends NodeBacked> targetType, TraversalDescription traversalDescription) {
        if (!hasUnderlyingNode()) throw new IllegalStateException("No node attached to " + this);
        final Traverser traverser = traversalDescription.traverse(this.getUnderlyingState());
        return new NodeBackedNodeIterableWrapper(traverser, targetType, Neo4jNodeBacking.aspectOf().graphDatabaseContext);
    }
    /* todo Andy Clement
    public Iterable<? extends NodeBacked> NodeBacked.traverse(TraversalDescription traversalDescription) {
        final Class<? extends NodeBacked> target = this.getClass();
        return this.traverse(target,traversalDescription);
    }
    */

    /* todo Andy Clement
    public <R extends RelationshipBacked, N extends NodeBacked> R NodeBacked.relateTo(N node, Class<R> relationshipType, String type) {
        Relationship rel = this.getUnderlyingState().createRelationshipTo(node.getUnderlyingState(), DynamicRelationshipType.withName(type));
        Neo4jNodeBacking.aspectOf().relationshipEntityInstantiator.createEntityFromState(rel, relationshipType);
    }
    */

    public RelationshipBacked NodeBacked.relateTo(NodeBacked node, Class<? extends RelationshipBacked> relationshipType, String type) {
        Relationship rel = this.getUnderlyingState().createRelationshipTo(node.getUnderlyingState(), DynamicRelationshipType.withName(type));
        return Neo4jNodeBacking.aspectOf().graphDatabaseContext.createEntityFromState(rel, relationshipType);
    }

    public void NodeBacked.removeRelationshipTo(NodeBacked node, 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)) {
                rel.delete();
                return;
            }
        }
        return;
    }

    public RelationshipBacked NodeBacked.getRelationshipTo(NodeBacked node, Class<? extends RelationshipBacked> relationshipType, 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 Neo4jNodeBacking.aspectOf().graphDatabaseContext.createEntityFromState(rel, relationshipType);
        }
        return null;
    }

	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;
	}

	public final int NodeBacked.hashCode() {
        if (!hasUnderlyingNode()) return System.identityHashCode(this);
		return getUnderlyingState().hashCode();
	}

    Object around(NodeBacked entity): entityFieldGet(entity) {
        Object result=entity.stateAccessors.getValue(field(thisJoinPoint));
        if (result instanceof DoReturn) return unwrap(result);
        return proceed(entity);
    }

    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();
    }
}


fixed exception messages

fixed exception messages

/**
 * Copyright 2010 CosmoCode GmbH
 *
 * 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 de.cosmocode.palava.core.aop;

import java.util.Collections;

import org.aspectj.lang.annotation.SuppressAjWarnings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Preconditions;
import com.google.common.collect.Iterables;
import com.google.inject.Binder;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Module;
import com.google.inject.Stage;

/**
 * Abstract aspect which intercepts {@link Guice#createInjector(..)} calls
 * to get hands on the injector.
 *
 * @since 2.0
 * @author Willi Schoenborn
 */
public abstract aspect AbstractPalavaAspect {

    private static final Logger LOG = LoggerFactory.getLogger(AbstractPalavaAspect.class);

    private final Module module = new Module() {

        @Override
        public void configure(Binder binder) {
            final AbstractPalavaAspect self = AbstractPalavaAspect.this;
            LOG.trace("Injecting members on {}", self);
            Preconditions.checkState(!alreadyInjected, "Members have been already injected on %s", self);
            binder.requestInjection(self);
            alreadyInjected = true;
        }

    };

    private boolean alreadyInjected;

    private Module[] append(Module[] modules) {
        final Module[] array = new Module[modules.length + 1];
        System.arraycopy(modules, 0, array, 0, modules.length);
        array[modules.length] = module;
        return array;
    }

    private Iterable<Module> append(Iterable<? extends Module> modules) {
        return Iterables.concat(modules, Collections.singleton(module));
    }

    @SuppressAjWarnings("adviceDidNotMatch")
    Injector around(Module[] modules): call(Injector Guice.createInjector(Module...)) && args(modules) {
        return proceed(append(modules));
    }

    @SuppressAjWarnings("adviceDidNotMatch")
    Injector around(Iterable<? extends Module> modules):
        call(Injector Guice.createInjector(Iterable<? extends Module>)) && args(modules) {
        return proceed(append(modules));
    }

    @SuppressAjWarnings("adviceDidNotMatch")
    Injector around(Stage stage, Module[] modules):
        call(Injector Guice.createInjector(Stage, Module...)) && args(stage, modules) {
        return proceed(stage, append(modules));
    }

    @SuppressAjWarnings("adviceDidNotMatch")
    Injector around(Stage stage, Iterable<? extends Module> modules):
        call(Injector Guice.createInjector(Stage, Iterable<? extends Module>)) && args(stage, modules) {
        return proceed(stage, append(modules));
    }

    protected final void checkState() {
        Preconditions.checkState(alreadyInjected, "Members have not been injected on %s", this);
    }

}

/**
 * Copyright 2010 CosmoCode GmbH
 *
 * 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 de.cosmocode.palava.core.aop;

import java.util.Collections;

import org.aspectj.lang.annotation.SuppressAjWarnings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Preconditions;
import com.google.common.collect.Iterables;
import com.google.inject.Binder;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Module;
import com.google.inject.Stage;

/**
 * Abstract aspect which intercepts {@link Guice#createInjector(..)} calls
 * to get hands on the injector.
 *
 * @since 2.0
 * @author Willi Schoenborn
 */
public abstract aspect AbstractPalavaAspect {

    private static final Logger LOG = LoggerFactory.getLogger(AbstractPalavaAspect.class);

    private final Module module = new Module() {

        @Override
        public void configure(Binder binder) {
            final AbstractPalavaAspect self = AbstractPalavaAspect.this;
            LOG.trace("Injecting members on {}", self);
            Preconditions.checkState(!alreadyInjected, "Members have been already injected on {}", self);
            binder.requestInjection(self);
            alreadyInjected = true;
        }

    };

    private boolean alreadyInjected;

    private Module[] append(Module[] modules) {
        final Module[] array = new Module[modules.length + 1];
        System.arraycopy(modules, 0, array, 0, modules.length);
        array[modules.length] = module;
        return array;
    }

    private Iterable<Module> append(Iterable<? extends Module> modules) {
        return Iterables.concat(modules, Collections.singleton(module));
    }

    @SuppressAjWarnings("adviceDidNotMatch")
    Injector around(Module[] modules): call(Injector Guice.createInjector(Module...)) && args(modules) {
        return proceed(append(modules));
    }

    @SuppressAjWarnings("adviceDidNotMatch")
    Injector around(Iterable<? extends Module> modules):
        call(Injector Guice.createInjector(Iterable<? extends Module>)) && args(modules) {
        return proceed(append(modules));
    }

    @SuppressAjWarnings("adviceDidNotMatch")
    Injector around(Stage stage, Module[] modules):
        call(Injector Guice.createInjector(Stage, Module...)) && args(stage, modules) {
        return proceed(stage, append(modules));
    }

    @SuppressAjWarnings("adviceDidNotMatch")
    Injector around(Stage stage, Iterable<? extends Module> modules):
        call(Injector Guice.createInjector(Stage, Iterable<? extends Module>)) && args(stage, modules) {
        return proceed(stage, append(modules));
    }

    protected final void checkState() {
        Preconditions.checkState(alreadyInjected, "Members have not been injected on {}", this);
    }

}


Got rid of an unnecessary catch

Got rid of an unnecessary catch

package com.chitter.aspect;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Transaction;
import javax.jdo.annotations.PersistenceCapable;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.chitter.persistence.UserAccount;
import com.chitter.persistence.UserStatistic;

public aspect Persistence {
	/**
	 * captures ctors with more than one arg and
	 * all setters of @PersistenceCapable objects.
	 */
	pointcut pushObject(Object o): target(o) && (call(* (@PersistenceCapable *).set*(..)) || execution((@PersistenceCapable *).new(*,*,..)));
	pointcut pullObject(Object pk): args(pk) && call((@PersistenceCapable *).new(*));
	pointcut pullList(): call(List (@PersistenceCapable *).get*List());

	pointcut pmShouldClose() : call(* com.chitter..*Servlet.processRequest(HttpServletRequest,HttpServletResponse) throws *);

	pointcut withinEscapePersistence(): withincode(@EscapePersistence * *(..));

	@SuppressWarnings("all")
	public static List UserAccount.getUserAccountList(){
		return new ArrayList<UserAccount>();
	}

	@SuppressWarnings("all")
	public static List UserStatistic.getUserStatisticList() {
		return new ArrayList<UserStatistic> ();
	}

	private static final PersistenceManagerFactory PMF =
        JDOHelper.getPersistenceManagerFactory("transactions-optional");
    private static final ThreadLocal<PersistenceManager> perThreadPM
    	= new ThreadLocal<PersistenceManager>();

    private Persistence() {};

    private static PersistenceManager getPM() {
    	PersistenceManager PM = perThreadPM.get();
        if (PM == null) {
          PM = PMF.getPersistenceManager();
          perThreadPM.set(PM);
        }
        return PM;
    }

    after(Object o) : pushObject(o) && !withinEscapePersistence(){
		System.out.println("I should persist an instance of "+o.getClass());
    	PersistenceManager pm = getPM();
    	try{
    		UserStatistic statistic=(UserStatistic) o;
    		System.out.println("which is a statistic object btw with pk "+statistic.getGtalkId());
    		JDOHelper.makeDirty(statistic, "statistics");
    	} finally {
        	pm.makePersistent(o.getClass().cast(o));
    		pm.flush();
    	}
    }

    @SuppressWarnings("all")
	Object around(Object pk) : pullObject(pk) && !withinEscapePersistence(){
    	PersistenceManager pm = getPM();
		try{
			Object r = pm.getObjectById(thisJoinPoint.getSignature().getDeclaringType(),pk);
			System.out.println("Yes I did and will return "+r);
			return r;
		} catch (Exception e) {
			System.err.println("No I could not and will return null");
			return null;
		}
    }

    @SuppressWarnings("all")
	List around() : pullList() {
		PersistenceManager pm = getPM();

		try {
			System.out.println("I am trying to pull a list of "+getClass()+" from db with ");
			List list = (List) pm.newQuery(thisJoinPoint.getSignature().getDeclaringType()).execute();
			System.out.println("Yes I did");
			return list;
		} catch (Exception e) {
			System.err.println("No I am returning an empty list");
			return (List)(new ArrayList<Object>());
		}
    }

	after() : pmShouldClose() {
		PersistenceManager PM = perThreadPM.get();
		if (PM != null) {
			System.out.println("PM should definitely close");
			perThreadPM.remove();
			Transaction tx = PM.currentTransaction();
			if (tx.isActive()) {
				tx.rollback();
			}
			PM.close();
		}
	}

}

package com.chitter.aspect;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Transaction;
import javax.jdo.annotations.PersistenceCapable;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.chitter.persistence.UserAccount;
import com.chitter.persistence.UserStatistic;

public aspect Persistence {
	/**
	 * captures ctors with more than one arg and
	 * all setters of @PersistenceCapable objects.
	 */
	pointcut pushObject(Object o): target(o) && (call(* (@PersistenceCapable *).set*(..)) || execution((@PersistenceCapable *).new(*,*,..)));
	pointcut pullObject(Object pk): args(pk) && call((@PersistenceCapable *).new(*));
	pointcut pullList(): call(List (@PersistenceCapable *).get*List());

	pointcut pmShouldClose() : call(* com.chitter..*Servlet.processRequest(HttpServletRequest,HttpServletResponse) throws *);

	pointcut withinEscapePersistence(): withincode(@EscapePersistence * *(..));

	@SuppressWarnings("all")
	public static List UserAccount.getUserAccountList(){
		return new ArrayList<UserAccount>();
	}

	@SuppressWarnings("all")
	public static List UserStatistic.getUserStatisticList() {
		return new ArrayList<UserStatistic> ();
	}

	private static final PersistenceManagerFactory PMF =
        JDOHelper.getPersistenceManagerFactory("transactions-optional");
    private static final ThreadLocal<PersistenceManager> perThreadPM
    	= new ThreadLocal<PersistenceManager>();

    private Persistence() {};

    private static PersistenceManager getPM() {
    	PersistenceManager PM = perThreadPM.get();
        if (PM == null) {
          PM = PMF.getPersistenceManager();
          perThreadPM.set(PM);
        }
        return PM;
    }

    after(Object o) : pushObject(o) && !withinEscapePersistence(){
		System.out.println("I should persist an instance of "+o.getClass());
    	PersistenceManager pm = getPM();
    	try{
    		UserStatistic statistic=(UserStatistic) o;
    		System.out.println("which is a statistic object btw with pk "+statistic.getGtalkId());
    		JDOHelper.makeDirty(statistic, "statistics");
    	} catch(Exception e){

    	} finally {
        	pm.makePersistent(o.getClass().cast(o));
    		pm.flush();
    	}
    }

    @SuppressWarnings("all")
	Object around(Object pk) : pullObject(pk) && !withinEscapePersistence(){
    	PersistenceManager pm = getPM();
		try{
			Object r = pm.getObjectById(thisJoinPoint.getSignature().getDeclaringType(),pk);
			System.out.println("Yes I did and will return "+r);
			return r;
		} catch (Exception e) {
			System.err.println("No I could not and will return null");
			return null;
		}
    }

    @SuppressWarnings("all")
	List around() : pullList() {
		PersistenceManager pm = getPM();

		try {
			System.out.println("I am trying to pull a list of "+getClass()+" from db with ");
			List list = (List) pm.newQuery(thisJoinPoint.getSignature().getDeclaringType()).execute();
			System.out.println("Yes I did");
			return list;
		} catch (Exception e) {
			System.err.println("No I am returning an empty list");
			return (List)(new ArrayList<Object>());
		}
    }

	after() : pmShouldClose() {
		PersistenceManager PM = perThreadPM.get();
		if (PM != null) {
			System.out.println("PM should definitely close");
			perThreadPM.remove();
			Transaction tx = PM.currentTransaction();
			if (tx.isActive()) {
				tx.rollback();
			}
			PM.close();
		}
	}

}


fix graph labels

fix graph labels

import java.awt.Color;

import de.erichseifert.gral.data.DataSeries;
import de.erichseifert.gral.data.DataTable;
import de.erichseifert.gral.plots.XYPlot;
import de.erichseifert.gral.plots.lines.DefaultLineRenderer2D;
import de.erichseifert.gral.ui.InteractivePanel;
import de.erichseifert.gral.util.Orientation;

import static model.SystemValues.Players.*;

import view.GUI;
import view.UIUpdater;

public privileged aspect Graph {

    private static GUI gui;
    private static DataSeries[] playersGraphs = new DataSeries[4];
    private static InteractivePanel tabGraph = null;

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

    static void addGraphPane() {
        gui.tabbedPane.remove(tabGraph);
        tabGraph = new InteractivePanel(createPlot());
        gui.tabbedPane.add(tabGraph, "Grafik", 2);
    }

    /**
     * Set the values for the lines of the graph
     */
    static void setPlayersGraphs() {
        DataTable[] tmp = gui.model.getGameData().getTables();
        playersGraphs[0] = new DataSeries(PLAYER_1.toString(), tmp[0], 0, 1);
        playersGraphs[1] = new DataSeries(PLAYER_2.toString(), tmp[1], 0, 1);
        playersGraphs[2] = new DataSeries(PLAYER_3.toString(), tmp[2], 0, 1);
        playersGraphs[3] = new DataSeries(PLAYER_4.toString(), tmp[3], 0, 1);
    }

    /**
     * when the ui update is running, we want to update the names in the graphs
     */
    after() : execution(* UIUpdater.run()) {
        playersGraphs[0].setName(PLAYER_1.toString());
        playersGraphs[1].setName(PLAYER_2.toString());
        playersGraphs[2].setName(PLAYER_3.toString());
        playersGraphs[3].setName(PLAYER_4.toString());
    }

    /**
     * create the plot tath is shown in the Grafik tab
     */
    private static XYPlot createPlot() {
        XYPlot plot = new XYPlot(playersGraphs[0], playersGraphs[1], playersGraphs[2], playersGraphs[3]);
        plot.setLegendVisible(true);
        plot.getLegend().setOrientation(Orientation.HORIZONTAL);
        plot.getLegend().setAlignmentY(1.0);

        plot.getAxisRenderer(XYPlot.AXIS_X).setLabel("Spielanzahl");
        plot.getAxisRenderer(XYPlot.AXIS_Y).setLabel("Geld");

        plot.setLineRenderer(playersGraphs[0], new DefaultLineRenderer2D());
        plot.setLineRenderer(playersGraphs[1], new DefaultLineRenderer2D());
        plot.setLineRenderer(playersGraphs[2], new DefaultLineRenderer2D());
        plot.setLineRenderer(playersGraphs[3], new DefaultLineRenderer2D());

        plot.getPointRenderer(playersGraphs[0]).setColor(Color.blue);
        plot.getLineRenderer(playersGraphs[0]).setColor(Color.blue);
        plot.getPointRenderer(playersGraphs[1]).setColor(Color.red);
        plot.getLineRenderer(playersGraphs[1]).setColor(Color.red);
        plot.getPointRenderer(playersGraphs[2]).setColor(Color.green);
        plot.getLineRenderer(playersGraphs[2]).setColor(Color.green);
        plot.getPointRenderer(playersGraphs[3]).setColor(Color.gray);
        plot.getLineRenderer(playersGraphs[3]).setColor(Color.gray);

        return plot;
    }
}

import java.awt.Color;

import de.erichseifert.gral.data.DataSeries;
import de.erichseifert.gral.data.DataTable;
import de.erichseifert.gral.plots.XYPlot;
import de.erichseifert.gral.plots.lines.DefaultLineRenderer2D;
import de.erichseifert.gral.ui.InteractivePanel;
import de.erichseifert.gral.util.Orientation;

import static model.SystemValues.Players.*;

import view.GUI;
import view.UIUpdater;

public privileged aspect Graph {

    private static GUI gui;
    private static DataSeries[] playersGraphs = new DataSeries[4];
    private static InteractivePanel tabGraph = null;

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

    static void addGraphPane() {
        gui.tabbedPane.remove(tabGraph);
        tabGraph = new InteractivePanel(createPlot());
        gui.tabbedPane.add(tabGraph, "Grafik", 2);
    }

    /**
     * Set the values for the lines of the graph
     */
    static void setPlayersGraphs() {
        DataTable[] tmp = gui.model.getGameData().getTables();
        playersGraphs[0] = new DataSeries(PLAYER_1.toString(), tmp[0], 0, 1);
        playersGraphs[1] = new DataSeries(PLAYER_2.toString(), tmp[1], 0, 1);
        playersGraphs[2] = new DataSeries(PLAYER_3.toString(), tmp[2], 0, 1);
        playersGraphs[3] = new DataSeries(PLAYER_4.toString(), tmp[3], 0, 1);
    }

    /**
     * when the ui update is running, we want to update the names in the graphs
     */
    after() : execution(* UIUpdater.run()) {
        playersGraphs[0].setName(PLAYER_1.toString());
        playersGraphs[1].setName(PLAYER_2.toString());
        playersGraphs[2].setName(PLAYER_3.toString());
        playersGraphs[3].setName(PLAYER_4.toString());
    }

    /**
     * create the plot tath is shown in the Grafik tab
     */
    private static XYPlot createPlot() {
        XYPlot plot = new XYPlot(playersGraphs[0], playersGraphs[1], playersGraphs[2], playersGraphs[3]);
        plot.setLegendVisible(true);
        plot.getLegend().setOrientation(Orientation.HORIZONTAL);
        plot.getLegend().setAlignmentY(1.0);

        plot.getAxisRenderer(XYPlot.AXIS_X).setLabel("Geld");
        plot.getAxisRenderer(XYPlot.AXIS_Y).setLabel("Spielanazahl");

        plot.setLineRenderer(playersGraphs[0], new DefaultLineRenderer2D());
        plot.setLineRenderer(playersGraphs[1], new DefaultLineRenderer2D());
        plot.setLineRenderer(playersGraphs[2], new DefaultLineRenderer2D());
        plot.setLineRenderer(playersGraphs[3], new DefaultLineRenderer2D());

        plot.getPointRenderer(playersGraphs[0]).setColor(Color.blue);
        plot.getLineRenderer(playersGraphs[0]).setColor(Color.blue);
        plot.getPointRenderer(playersGraphs[1]).setColor(Color.red);
        plot.getLineRenderer(playersGraphs[1]).setColor(Color.red);
        plot.getPointRenderer(playersGraphs[2]).setColor(Color.green);
        plot.getLineRenderer(playersGraphs[2]).setColor(Color.green);
        plot.getPointRenderer(playersGraphs[3]).setColor(Color.gray);
        plot.getLineRenderer(playersGraphs[3]).setColor(Color.gray);

        return plot;
    }
}


commit d97cbd749de78bd0c8c470142bf943a1ee2abe6d
Author: Vinay Kumar Thota <vinayt@yahoo-inc.com>
Date:   Fri Jun 4 08:50:52 2010 +0000

    HADOOP:6788 from https://issues.apache.org/jira/secure/attachment/12446102/6788-ydist-security.patch

git-svn-id: 7e7a2d564dde2945c3a26e08d1235fcc0cb7aba1@1077489 13f79535-47bb-0310-9956-ffa450edef68

/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.apache.hadoop.test.system;

import java.io.File;
import java.io.IOException;
import java.security.PrivilegedExceptionAction;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.Properties;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.util.Shell.ShellCommandExecutor;
import org.apache.hadoop.util.Shell;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.conf.Configuration;

/**
 * Default DaemonProtocolAspect which is used to provide default implementation
 * for all the common daemon methods. If a daemon requires more specialized
 * version of method, it is responsibility of the DaemonClient to introduce the
 * same in woven classes.
 *
 */
public aspect DaemonProtocolAspect {

  private boolean DaemonProtocol.ready;

  @SuppressWarnings("unchecked")
  private HashMap<Object, List<ControlAction>> DaemonProtocol.actions =
    new HashMap<Object, List<ControlAction>>();
  private static final Log LOG = LogFactory.getLog(
      DaemonProtocolAspect.class.getName());
  /**
   * Set if the daemon process is ready or not, concrete daemon protocol should
   * implement pointcuts to determine when the daemon is ready and use the
   * setter to set the ready state.
   *
   * @param ready
   *          true if the Daemon is ready.
   */
  public void DaemonProtocol.setReady(boolean ready) {
    this.ready = ready;
  }

  /**
   * Checks if the daemon process is alive or not.
   *
   * @throws IOException
   *           if daemon is not alive.
   */
  public void DaemonProtocol.ping() throws IOException {
  }

  /**
   * Checks if the daemon process is ready to accepting RPC connections after it
   * finishes initialization.

   *
   * @return true if ready to accept connection.
   *
   * @throws IOException
   */
  public boolean DaemonProtocol.isReady() throws IOException {
    return ready;
  }

  /**
   * Returns the process related information regarding the daemon process.

   *
   * @return process information.
   * @throws IOException
   */
  public ProcessInfo DaemonProtocol.getProcessInfo() throws IOException {
    int activeThreadCount = Thread.activeCount();
    long currentTime = System.currentTimeMillis();
    long maxmem = Runtime.getRuntime().maxMemory();
    long freemem = Runtime.getRuntime().freeMemory();
    long totalmem = Runtime.getRuntime().totalMemory();
    Map<String, String> envMap = System.getenv();
    Properties sysProps = System.getProperties();
    Map<String, String> props = new HashMap<String, String>();
    for (Map.Entry entry : sysProps.entrySet()) {
      props.put((String) entry.getKey(), (String) entry.getValue());
    }
    ProcessInfo info = new ProcessInfoImpl(activeThreadCount, currentTime,
        freemem, maxmem, totalmem, envMap, props);
    return info;
  }

  public void DaemonProtocol.enable(List<Enum<?>> faults) throws IOException {
  }

  public void DaemonProtocol.disableAll() throws IOException {
  }

  public abstract Configuration DaemonProtocol.getDaemonConf()
    throws IOException;

  public FileStatus DaemonProtocol.getFileStatus(String path, boolean local)
    throws IOException {
    Path p = new Path(path);
    FileSystem fs = getFS(p, local);
    p.makeQualified(fs);
    FileStatus fileStatus = fs.getFileStatus(p);
    return cloneFileStatus(fileStatus);
  }

  public FileStatus[] DaemonProtocol.listStatus(String path, boolean local)
    throws IOException {
    Path p = new Path(path);
    FileSystem fs = getFS(p, local);
    FileStatus[] status = fs.listStatus(p);
    if (status != null) {
      FileStatus[] result = new FileStatus[status.length];
      int i = 0;
      for (FileStatus fileStatus : status) {
        result[i++] = cloneFileStatus(fileStatus);
      }
      return result;
    }
    return status;
  }

  /**
   * FileStatus object may not be serializable. Clone it into raw FileStatus
   * object.
   */
  private FileStatus DaemonProtocol.cloneFileStatus(FileStatus fileStatus) {
    return new FileStatus(fileStatus.getLen(),
        fileStatus.isDir(),
        fileStatus.getReplication(),
        fileStatus.getBlockSize(),
        fileStatus.getModificationTime(),
        fileStatus.getAccessTime(),
        fileStatus.getPermission(),
        fileStatus.getOwner(),
        fileStatus.getGroup(),
        fileStatus.getPath());
  }

  private FileSystem DaemonProtocol.getFS(final Path path, final boolean local)
      throws IOException {
    FileSystem ret = null;
    try {
      ret = UserGroupInformation.getLoginUser().doAs (
          new PrivilegedExceptionAction<FileSystem>() {
            public FileSystem run() throws IOException {
              FileSystem fs = null;
              if (local) {
                fs = FileSystem.getLocal(getDaemonConf());
              } else {
                fs = path.getFileSystem(getDaemonConf());
              }
              return fs;
            }
          });
    } catch (InterruptedException ie) {
    }
    return ret;
  }

  @SuppressWarnings("unchecked")
  public ControlAction[] DaemonProtocol.getActions(Writable key)
    throws IOException {
    synchronized (actions) {
      List<ControlAction> actionList = actions.get(key);
      if(actionList == null) {
        return new ControlAction[0];
      } else {
        return (ControlAction[]) actionList.toArray(new ControlAction[actionList
                                                                      .size()]);
      }
    }
  }

  @SuppressWarnings("unchecked")
  public void DaemonProtocol.sendAction(ControlAction action)
      throws IOException {
    synchronized (actions) {
      List<ControlAction> actionList = actions.get(action.getTarget());
      if(actionList == null) {
        actionList = new ArrayList<ControlAction>();
        actions.put(action.getTarget(), actionList);
      }
      actionList.add(action);
    }
  }

  @SuppressWarnings("unchecked")
  public boolean DaemonProtocol.isActionPending(ControlAction action)
    throws IOException{
    synchronized (actions) {
      List<ControlAction> actionList = actions.get(action.getTarget());
      if(actionList == null) {
        return false;
      } else {
        return actionList.contains(action);
      }
    }
  }

  @SuppressWarnings("unchecked")
  public void DaemonProtocol.removeAction(ControlAction action)
    throws IOException {
    synchronized (actions) {
      List<ControlAction> actionList = actions.get(action.getTarget());
      if(actionList == null) {
        return;
      } else {
        actionList.remove(action);
      }
    }
  }

  public void DaemonProtocol.clearActions() throws IOException {
    synchronized (actions) {
      actions.clear();
    }
  }

  public String DaemonProtocol.getFilePattern() {
    //We use the environment variable HADOOP_LOGFILE to get the
    //pattern to use in the search.
    String logDir = System.getenv("HADOOP_LOG_DIR");
    String daemonLogPattern = System.getenv("HADOOP_LOGFILE");
    if(daemonLogPattern == null && daemonLogPattern.isEmpty()) {
      return "*";
    }
    return  logDir+File.separator+daemonLogPattern+"*";
  }

  public int DaemonProtocol.getNumberOfMatchesInLogFile(String pattern,
      String[] list) throws IOException {
    StringBuffer filePattern = new StringBuffer(getFilePattern());
    String[] cmd = null;
    if (list != null) {
      StringBuffer filterExpPattern = new StringBuffer();
      int index=0;
      for (String excludeExp : list) {
        if (index++ < list.length -1) {
           filterExpPattern.append("grep -v " + excludeExp + " | ");
        } else {
           filterExpPattern.append("grep -vc " + excludeExp);
        }
      }
      cmd = new String[] {
                "bash",
                "-c",
                "grep "
                + pattern + " " + filePattern + " | "
                + filterExpPattern};
    } else {
      cmd = new String[] {
                "bash",
                "-c",
                "grep -c "
                + pattern + " " + filePattern
                + " | awk -F: '{s+=$2} END {print s}'" };
    }
    ShellCommandExecutor shexec = new ShellCommandExecutor(cmd);
    shexec.execute();
    String output = shexec.getOutput();
    return Integer.parseInt(output.replaceAll("\n", "").trim());
  }

  /**
   * This method is used for suspending the process.
   * @param pid process id
   * @throws IOException if an I/O error occurs.
   * @return true if process is suspended otherwise false.
   */
  public boolean DaemonProtocol.suspendProcess(String pid) throws IOException {
    String suspendCmd = getDaemonConf().get("test.system.hdrc.suspend.cmd",
        "kill -SIGSTOP");
    String [] command = {"bash", "-c", suspendCmd + " " + pid};
    ShellCommandExecutor shexec = new ShellCommandExecutor(command);
    try {
      shexec.execute();
    } catch (Shell.ExitCodeException e) {
      LOG.warn("suspended process throws an exitcode "
          + "exception for not being suspended the given process id.");
      return false;
    }
    LOG.info("The suspend process command is :"
        + shexec.toString()
        + " and the output for the command is "
        + shexec.getOutput());
    return true;
  }

  /**
   * This method is used for resuming the process
   * @param pid process id of suspended process.
   * @throws IOException if an I/O error occurs.
   * @return true if suspeneded process is resumed otherwise false.
   */
  public boolean DaemonProtocol.resumeProcess(String pid) throws IOException {
    String resumeCmd = getDaemonConf().get("test.system.hdrc.resume.cmd",
        "kill -SIGCONT");
    String [] command = {"bash", "-c", resumeCmd + " " + pid};
    ShellCommandExecutor shexec = new ShellCommandExecutor(command);
    try {
      shexec.execute();
    } catch(Shell.ExitCodeException e) {
        LOG.warn("Resume process throws an exitcode "
          + "exception for not being resumed the given process id.");
      return false;
    }
    LOG.info("The resume process command is :"
        + shexec.toString()
        + " and the output for the command is "
        + shexec.getOutput());
    return true;
  }

  private String DaemonProtocol.user = null;

  public String DaemonProtocol.getDaemonUser() {
    return user;
  }

  public void DaemonProtocol.setUser(String user) {
    this.user = user;
  }
}

/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.apache.hadoop.test.system;

import java.io.File;
import java.io.IOException;
import java.security.PrivilegedExceptionAction;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.Properties;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.util.Shell.ShellCommandExecutor;
import org.apache.hadoop.util.Shell;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.conf.Configuration;

/**
 * Default DaemonProtocolAspect which is used to provide default implementation
 * for all the common daemon methods. If a daemon requires more specialized
 * version of method, it is responsibility of the DaemonClient to introduce the
 * same in woven classes.
 *
 */
public aspect DaemonProtocolAspect {

  private boolean DaemonProtocol.ready;

  @SuppressWarnings("unchecked")
  private HashMap<Object, List<ControlAction>> DaemonProtocol.actions =
    new HashMap<Object, List<ControlAction>>();
  private static final Log LOG = LogFactory.getLog(
      DaemonProtocolAspect.class.getName());
  /**
   * Set if the daemon process is ready or not, concrete daemon protocol should
   * implement pointcuts to determine when the daemon is ready and use the
   * setter to set the ready state.
   *
   * @param ready
   *          true if the Daemon is ready.
   */
  public void DaemonProtocol.setReady(boolean ready) {
    this.ready = ready;
  }

  /**
   * Checks if the daemon process is alive or not.
   *
   * @throws IOException
   *           if daemon is not alive.
   */
  public void DaemonProtocol.ping() throws IOException {
  }

  /**
   * Checks if the daemon process is ready to accepting RPC connections after it
   * finishes initialization.

   *
   * @return true if ready to accept connection.
   *
   * @throws IOException
   */
  public boolean DaemonProtocol.isReady() throws IOException {
    return ready;
  }

  /**
   * Returns the process related information regarding the daemon process.

   *
   * @return process information.
   * @throws IOException
   */
  public ProcessInfo DaemonProtocol.getProcessInfo() throws IOException {
    int activeThreadCount = Thread.activeCount();
    long currentTime = System.currentTimeMillis();
    long maxmem = Runtime.getRuntime().maxMemory();
    long freemem = Runtime.getRuntime().freeMemory();
    long totalmem = Runtime.getRuntime().totalMemory();
    Map<String, String> envMap = System.getenv();
    Properties sysProps = System.getProperties();
    Map<String, String> props = new HashMap<String, String>();
    for (Map.Entry entry : sysProps.entrySet()) {
      props.put((String) entry.getKey(), (String) entry.getValue());
    }
    ProcessInfo info = new ProcessInfoImpl(activeThreadCount, currentTime,
        freemem, maxmem, totalmem, envMap, props);
    return info;
  }

  public void DaemonProtocol.enable(List<Enum<?>> faults) throws IOException {
  }

  public void DaemonProtocol.disableAll() throws IOException {
  }

  public abstract Configuration DaemonProtocol.getDaemonConf()
    throws IOException;

  public FileStatus DaemonProtocol.getFileStatus(String path, boolean local)
    throws IOException {
    Path p = new Path(path);
    FileSystem fs = getFS(p, local);
    p.makeQualified(fs);
    FileStatus fileStatus = fs.getFileStatus(p);
    return cloneFileStatus(fileStatus);
  }

  public FileStatus[] DaemonProtocol.listStatus(String path, boolean local)
    throws IOException {
    Path p = new Path(path);
    FileSystem fs = getFS(p, local);
    FileStatus[] status = fs.listStatus(p);
    if (status != null) {
      FileStatus[] result = new FileStatus[status.length];
      int i = 0;
      for (FileStatus fileStatus : status) {
        result[i++] = cloneFileStatus(fileStatus);
      }
      return result;
    }
    return status;
  }

  /**
   * FileStatus object may not be serializable. Clone it into raw FileStatus
   * object.
   */
  private FileStatus DaemonProtocol.cloneFileStatus(FileStatus fileStatus) {
    return new FileStatus(fileStatus.getLen(),
        fileStatus.isDir(),
        fileStatus.getReplication(),
        fileStatus.getBlockSize(),
        fileStatus.getModificationTime(),
        fileStatus.getAccessTime(),
        fileStatus.getPermission(),
        fileStatus.getOwner(),
        fileStatus.getGroup(),
        fileStatus.getPath());
  }

  private FileSystem DaemonProtocol.getFS(final Path path, final boolean local)
      throws IOException {
    FileSystem ret = null;
    try {
      ret = UserGroupInformation.getLoginUser().doAs (
          new PrivilegedExceptionAction<FileSystem>() {
            public FileSystem run() throws IOException {
              FileSystem fs = null;
              if (local) {
                fs = FileSystem.getLocal(getDaemonConf());
              } else {
                fs = path.getFileSystem(getDaemonConf());
              }
              return fs;
            }
          });
    } catch (InterruptedException ie) {
    }
    return ret;
  }

  @SuppressWarnings("unchecked")
  public ControlAction[] DaemonProtocol.getActions(Writable key)
    throws IOException {
    synchronized (actions) {
      List<ControlAction> actionList = actions.get(key);
      if(actionList == null) {
        return new ControlAction[0];
      } else {
        return (ControlAction[]) actionList.toArray(new ControlAction[actionList
                                                                      .size()]);
      }
    }
  }

  @SuppressWarnings("unchecked")
  public void DaemonProtocol.sendAction(ControlAction action)
      throws IOException {
    synchronized (actions) {
      List<ControlAction> actionList = actions.get(action.getTarget());
      if(actionList == null) {
        actionList = new ArrayList<ControlAction>();
        actions.put(action.getTarget(), actionList);
      }
      actionList.add(action);
    }
  }

  @SuppressWarnings("unchecked")
  public boolean DaemonProtocol.isActionPending(ControlAction action)
    throws IOException{
    synchronized (actions) {
      List<ControlAction> actionList = actions.get(action.getTarget());
      if(actionList == null) {
        return false;
      } else {
        return actionList.contains(action);
      }
    }
  }

  @SuppressWarnings("unchecked")
  public void DaemonProtocol.removeAction(ControlAction action)
    throws IOException {
    synchronized (actions) {
      List<ControlAction> actionList = actions.get(action.getTarget());
      if(actionList == null) {
        return;
      } else {
        actionList.remove(action);
      }
    }
  }

  public void DaemonProtocol.clearActions() throws IOException {
    synchronized (actions) {
      actions.clear();
    }
  }

  public String DaemonProtocol.getFilePattern() {
    //We use the environment variable HADOOP_LOGFILE to get the
    //pattern to use in the search.
    String logDir = System.getenv("HADOOP_LOG_DIR");
    String daemonLogPattern = System.getenv("HADOOP_LOGFILE");
    if(daemonLogPattern == null && daemonLogPattern.isEmpty()) {
      return "*";
    }
    return  logDir+File.separator+daemonLogPattern+"*";
  }

  public int DaemonProtocol.getNumberOfMatchesInLogFile(String pattern,
      String[] list) throws IOException {
    StringBuffer filePattern = new StringBuffer(getFilePattern());
    if(list != null){
      for(int i =0; i < list.length; ++i)
      {
        filePattern.append(" | grep -v " + list[i] );
      }
    }
    String[] cmd =
        new String[] {
            "bash",
            "-c",
            "grep -c "
                + pattern + " " + filePattern
                + " | awk -F: '{s+=$2} END {print s}'" };
    ShellCommandExecutor shexec = new ShellCommandExecutor(cmd);
    shexec.execute();
    String output = shexec.getOutput();
    return Integer.parseInt(output.replaceAll("\n", "").trim());
  }

  /**
   * This method is used for suspending the process.
   * @param pid process id
   * @throws IOException if an I/O error occurs.
   * @return true if process is suspended otherwise false.
   */
  public boolean DaemonProtocol.suspendProcess(String pid) throws IOException {
    String suspendCmd = getDaemonConf().get("test.system.hdrc.suspend.cmd",
        "kill -SIGSTOP");
    String [] command = {"bash", "-c", suspendCmd + " " + pid};
    ShellCommandExecutor shexec = new ShellCommandExecutor(command);
    try {
      shexec.execute();
    } catch (Shell.ExitCodeException e) {
      LOG.warn("suspended process throws an exitcode "
          + "exception for not being suspended the given process id.");
      return false;
    }
    LOG.info("The suspend process command is :"
        + shexec.toString()
        + " and the output for the command is "
        + shexec.getOutput());
    return true;
  }

  /**
   * This method is used for resuming the process
   * @param pid process id of suspended process.
   * @throws IOException if an I/O error occurs.
   * @return true if suspeneded process is resumed otherwise false.
   */
  public boolean DaemonProtocol.resumeProcess(String pid) throws IOException {
    String resumeCmd = getDaemonConf().get("test.system.hdrc.resume.cmd",
        "kill -SIGCONT");
    String [] command = {"bash", "-c", resumeCmd + " " + pid};
    ShellCommandExecutor shexec = new ShellCommandExecutor(command);
    try {
      shexec.execute();
    } catch(Shell.ExitCodeException e) {
        LOG.warn("Resume process throws an exitcode "
          + "exception for not being resumed the given process id.");
      return false;
    }
    LOG.info("The resume process command is :"
        + shexec.toString()
        + " and the output for the command is "
        + shexec.getOutput());
    return true;
  }

  private String DaemonProtocol.user = null;

  public String DaemonProtocol.getDaemonUser() {
    return user;
  }

  public void DaemonProtocol.setUser(String user) {
    this.user = user;
  }
}


comments for graph

comments for graph

import java.awt.Color;

import de.erichseifert.gral.data.DataSeries;
import de.erichseifert.gral.data.DataTable;
import de.erichseifert.gral.plots.XYPlot;
import de.erichseifert.gral.plots.lines.DefaultLineRenderer2D;
import de.erichseifert.gral.ui.InteractivePanel;
import de.erichseifert.gral.util.Orientation;

import static model.SystemValues.Players.*;

import view.GUI;
import view.UIUpdater;

public privileged aspect Graph {

    private static GUI gui;
    private static DataSeries[] playersGraphs = new DataSeries[4];
    private static InteractivePanel tabGraph = null;

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

    static void addGraphPane() {
        gui.tabbedPane.remove(tabGraph);
        tabGraph = new InteractivePanel(createPlot());
        gui.tabbedPane.add(tabGraph, "Grafik", 2);
    }

    /**
     * Set the values for the lines of the graph
     */
    static void setPlayersGraphs() {
        DataTable[] tmp = gui.model.getGameData().getTables();
        playersGraphs[0] = new DataSeries(PLAYER_1.toString(), tmp[0], 0, 1);
        playersGraphs[1] = new DataSeries(PLAYER_2.toString(), tmp[1], 0, 1);
        playersGraphs[2] = new DataSeries(PLAYER_3.toString(), tmp[2], 0, 1);
        playersGraphs[3] = new DataSeries(PLAYER_4.toString(), tmp[3], 0, 1);
    }

    /**
     * when the ui update is running, we want to update the names in the graphs
     */
    after() : execution(* UIUpdater.run()) {
        playersGraphs[0].setName(PLAYER_1.toString());
        playersGraphs[1].setName(PLAYER_2.toString());
        playersGraphs[2].setName(PLAYER_3.toString());
        playersGraphs[3].setName(PLAYER_4.toString());
    }

    /**
     * create the plot tath is shown in the Grafik tab
     */
    private static XYPlot createPlot() {
        XYPlot plot = new XYPlot(playersGraphs[0], playersGraphs[1], playersGraphs[2], playersGraphs[3]);
        plot.setLegendVisible(true);
        plot.getLegend().setOrientation(Orientation.HORIZONTAL);
        plot.getLegend().setAlignmentY(1.0);

        plot.getAxisRenderer(XYPlot.AXIS_X).setLabel("Geld");
        plot.getAxisRenderer(XYPlot.AXIS_Y).setLabel("Spielanazahl");

        plot.setLineRenderer(playersGraphs[0], new DefaultLineRenderer2D());
        plot.setLineRenderer(playersGraphs[1], new DefaultLineRenderer2D());
        plot.setLineRenderer(playersGraphs[2], new DefaultLineRenderer2D());
        plot.setLineRenderer(playersGraphs[3], new DefaultLineRenderer2D());

        plot.getPointRenderer(playersGraphs[0]).setColor(Color.blue);
        plot.getLineRenderer(playersGraphs[0]).setColor(Color.blue);
        plot.getPointRenderer(playersGraphs[1]).setColor(Color.red);
        plot.getLineRenderer(playersGraphs[1]).setColor(Color.red);
        plot.getPointRenderer(playersGraphs[2]).setColor(Color.green);
        plot.getLineRenderer(playersGraphs[2]).setColor(Color.green);
        plot.getPointRenderer(playersGraphs[3]).setColor(Color.gray);
        plot.getLineRenderer(playersGraphs[3]).setColor(Color.gray);

        return plot;
    }
}

import java.awt.Color;

import de.erichseifert.gral.data.DataSeries;
import de.erichseifert.gral.data.DataTable;
import de.erichseifert.gral.plots.XYPlot;
import de.erichseifert.gral.plots.lines.DefaultLineRenderer2D;
import de.erichseifert.gral.ui.InteractivePanel;
import de.erichseifert.gral.util.Orientation;

import static model.SystemValues.Players.*;

import view.GUI;
import view.UIUpdater;

public privileged aspect Graph {

    private static GUI gui;
    private static DataSeries[] playersGraphs = new DataSeries[4];
    private static InteractivePanel tabGraph = null;

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

    static void addGraphPane() {
        gui.tabbedPane.remove(tabGraph);
        tabGraph = new InteractivePanel(createPlot());
        gui.tabbedPane.add(tabGraph, "Grafik", 2);
    }

    /**
     * Set the values for the lines of the graph
     */
    static void setPlayersGraphs() {
        DataTable[] tmp = gui.model.getGameData().getTables();
        playersGraphs[0] = new DataSeries(PLAYER_1.toString(), tmp[0], 0, 1);
        playersGraphs[1] = new DataSeries(PLAYER_2.toString(), tmp[1], 0, 1);
        playersGraphs[2] = new DataSeries(PLAYER_3.toString(), tmp[2], 0, 1);
        playersGraphs[3] = new DataSeries(PLAYER_4.toString(), tmp[3], 0, 1);
    }

    /**
     * when the ui update is running, we want to update the names in the graphs
     */
    after() : execution(* UIUpdater.run()) {
        playersGraphs[0].setName(PLAYER_1.toString());
        playersGraphs[1].setName(PLAYER_2.toString());
        playersGraphs[2].setName(PLAYER_3.toString());
        playersGraphs[3].setName(PLAYER_4.toString());
    }

    private static XYPlot createPlot() {
        XYPlot plot = new XYPlot(playersGraphs[0], playersGraphs[1], playersGraphs[2], playersGraphs[3]);
        plot.setLegendVisible(true);
        plot.getLegend().setOrientation(Orientation.HORIZONTAL);
        plot.getLegend().setAlignmentY(1.0);

        plot.getAxisRenderer(XYPlot.AXIS_X).setLabel("Geld");
        plot.getAxisRenderer(XYPlot.AXIS_Y).setLabel("Spielanazahl");

        plot.setLineRenderer(playersGraphs[0], new DefaultLineRenderer2D());
        plot.setLineRenderer(playersGraphs[1], new DefaultLineRenderer2D());
        plot.setLineRenderer(playersGraphs[2], new DefaultLineRenderer2D());
        plot.setLineRenderer(playersGraphs[3], new DefaultLineRenderer2D());

        plot.getPointRenderer(playersGraphs[0]).setColor(Color.blue);
        plot.getLineRenderer(playersGraphs[0]).setColor(Color.blue);
        plot.getPointRenderer(playersGraphs[1]).setColor(Color.red);
        plot.getLineRenderer(playersGraphs[1]).setColor(Color.red);
        plot.getPointRenderer(playersGraphs[2]).setColor(Color.green);
        plot.getLineRenderer(playersGraphs[2]).setColor(Color.green);
        plot.getPointRenderer(playersGraphs[3]).setColor(Color.gray);
        plot.getLineRenderer(playersGraphs[3]).setColor(Color.gray);

        return plot;
    }
}


We can now reliably monitor the dispatchers

/*
 * 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 ActorPathTagger 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 ActorPathTagger(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.self().path(), ActorPathTagger.ANONYMOUS_ACTOR_CLASS_NAME);
        final String[] allTags = new String[tags.length + 1];
        System.arraycopy(tags, 0, allTags, 1, tags.length);
        allTags[0] = String.format("akka.dispatcher:%s", actorCell.dispatcher().id());
        this.actorCellCflowTags.put(Thread.currentThread().getId(), allTags);
    }

    /**
     * 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);
    }

}

/*
 * 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.Arrays;
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 ActorPathTagger 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 ActorPathTagger(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.self().path(), ActorPathTagger.ANONYMOUS_ACTOR_CLASS_NAME);
        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);
    }

}


removed debug print.

removed debug print.

package de.unipotsdam.hpi.thorben.ppi.aspects;

import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.impl.pvm.runtime.AtomicOperation;
import org.activiti.engine.impl.pvm.runtime.AtomicOperationActivityExecute;
import org.activiti.engine.impl.pvm.runtime.AtomicOperationTransitionDestroyScope;

import de.unipotsdam.hpi.thorben.ppi.condition.event.ActivityEndEvent;
import de.unipotsdam.hpi.thorben.ppi.condition.event.ActivityStartEvent;
import de.unipotsdam.hpi.thorben.ppi.condition.event.ConditionEvent;

/**
 * Defines all points of emitting time instant condition events.
 * @author Thorben
 *
 */
public aspect TimeInstantConditionAspect {
	/**
	 * Captures the ActivityStartCondition
	 * @param operation
	 * @param execution
	 */
	pointcut execute(AtomicOperationActivityExecute operation,
			ExecutionEntity execution) : target(operation) && call(void AtomicOperation+.execute(..)) && args(execution);

	/**
	 * Signals the ActivityStartCondition
	 * @param operation
	 * @param execution
	 */
	before(AtomicOperationActivityExecute operation, ExecutionEntity execution) : execute(operation, execution) {
		ActivityImpl activity = (ActivityImpl) execution.getActivity();

		ConditionEvent event = new ActivityStartEvent(activity);
		event.setProcessInstanceId(execution.getProcessInstanceId());

		activity.notifyObservers(event);
	}

	/**
	 * Captures the ActivityEndCondition
	 * @param operation
	 * @param execution
	 */
	pointcut finish(AtomicOperationTransitionDestroyScope operation, ExecutionEntity execution) : target(operation) && call(void AtomicOperation+.execute(..)) && args(execution);

	/**
	 * Signals the ActivityEndCondition
	 * @param operation
	 * @param execution
	 */
	before(AtomicOperationTransitionDestroyScope operation, ExecutionEntity execution) : finish(operation, execution) {
		ActivityImpl activity = (ActivityImpl) execution.getActivity();

		ConditionEvent event = new ActivityEndEvent(activity);
		event.setProcessInstanceId(execution.getProcessInstanceId());
		activity.notifyObservers(event);
	}

}

package de.unipotsdam.hpi.thorben.ppi.aspects;

import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.impl.pvm.runtime.AtomicOperation;
import org.activiti.engine.impl.pvm.runtime.AtomicOperationActivityExecute;
import org.activiti.engine.impl.pvm.runtime.AtomicOperationTransitionDestroyScope;

import de.unipotsdam.hpi.thorben.ppi.condition.event.ActivityEndEvent;
import de.unipotsdam.hpi.thorben.ppi.condition.event.ActivityStartEvent;
import de.unipotsdam.hpi.thorben.ppi.condition.event.ConditionEvent;

/**
 * Defines all points of emitting time instant condition events.
 * @author Thorben
 *
 */
public aspect TimeInstantConditionAspect {
	/**
	 * Captures the ActivityStartCondition
	 * @param operation
	 * @param execution
	 */
	pointcut execute(AtomicOperationActivityExecute operation,
			ExecutionEntity execution) : target(operation) && call(void AtomicOperation+.execute(..)) && args(execution);

	/**
	 * Signals the ActivityStartCondition
	 * @param operation
	 * @param execution
	 */
	before(AtomicOperationActivityExecute operation, ExecutionEntity execution) : execute(operation, execution) {
		ActivityImpl activity = (ActivityImpl) execution.getActivity();
		System.out.println("In execution " + execution.toString() + " Start of " + activity.toString() + " with behavior " + operation.toString());

		ConditionEvent event = new ActivityStartEvent(activity);
		event.setProcessInstanceId(execution.getProcessInstanceId());

		activity.notifyObservers(event);
	}

	/**
	 * Captures the ActivityEndCondition
	 * @param operation
	 * @param execution
	 */
	pointcut finish(AtomicOperationTransitionDestroyScope operation, ExecutionEntity execution) : target(operation) && call(void AtomicOperation+.execute(..)) && args(execution);

	/**
	 * Signals the ActivityEndCondition
	 * @param operation
	 * @param execution
	 */
	before(AtomicOperationTransitionDestroyScope operation, ExecutionEntity execution) : finish(operation, execution) {
		ActivityImpl activity = (ActivityImpl) execution.getActivity();
		System.out.println("In execution " + execution.toString() + " End of " + activity.toString() + " with behavior " + operation.toString());

		ConditionEvent event = new ActivityEndEvent(activity);
		event.setProcessInstanceId(execution.getProcessInstanceId());
		activity.notifyObservers(event);
	}

}


static

static

/*
 * 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 akka.actor.ActorRef;
import akka.actor.Props;

/**
 * Centralises the pointcuts
 */
abstract aspect Pointcuts {

    /**
     * Pointcut for {@code ActorCell.receiveMessage(msg)}, extracting the {@code ActorCell} and the message being received
     */
    static pointcut actorCellReceiveMessage(ActorCell actorCell, Object msg) : target(actorCell) &&
            call(* akka.actor.ActorCell.receiveMessage(..)) && args(msg);

    /**
     * Pointcut for {@code ActorCell.handleInvokeFailure(_, failure)}, extracting the {@code ActorCell} and the
     * cause of the failure
     */
    static pointcut actorCellHandleInvokeFailure(ActorCell actorCell, Throwable failure) : target(actorCell) &&
            execution(* akka.actor.ActorCell.handleInvokeFailure(..)) && args(*, failure);

    /**
     * Pointcut for the {@code EventStream.publish(event)} method, extracting just the event
     */
    static pointcut eventStreamPublish(Object event) :
            execution(* akka.event.EventStream.publish(..)) && args(event);

    /**
     * Pointcut for the {@code actorOf} method in {@code ActorRefFactory} implementations. You would typically use
     * it in the {@code after returning()} advices.
     */
    private static pointcut unnamedActorOf(Props props) : execution(* akka.actor.ActorRefFactory+.actorOf(*)) && args(props);
    /**
     * Pointcut for the {@code actorOf} method in {@code ActorRefFactory} implementations where actor is named on creation
     */
    private static pointcut namedActorOf(Props props) : execution(* akka.actor.ActorRefFactory+.actorOf(*,*)) && args(props, *);
    /**
     * Public pointcut for retrieving Props instance used by {@code actorOf} method in {@code ActorRefFactory}
     */
    static pointcut anyActorOf(Props props) : namedActorOf(props) || unnamedActorOf(props);

    /**
     * Pointcut for {@code ActorCell.stop(actor)} method, extracting the {@code ActorRef}
     */
    static pointcut actorCellStop(ActorRef actor) : execution(* akka.actor.ActorCell.stop(..)) && args(actor);

    /**
     * Pointcut for {@code ActorCell.stop()} method, extracting the targeted {@code ActorCell}
     */
    static pointcut actorCellInternalStop(ActorCell actorCell) : target(actorCell) && execution(* akka.actor.ActorCell.stop());
}

/*
 * 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 akka.actor.ActorRef;
import akka.actor.Props;

/**
 * Centralises the pointcuts
 */
abstract aspect Pointcuts {

    /**
     * Pointcut for {@code ActorCell.receiveMessage(msg)}, extracting the {@code ActorCell} and the message being received
     */
    static pointcut actorCellReceiveMessage(ActorCell actorCell, Object msg) : target(actorCell) &&
            call(* akka.actor.ActorCell.receiveMessage(..)) && args(msg);

    /**
     * Pointcut for {@code ActorCell.handleInvokeFailure(_, failure)}, extracting the {@code ActorCell} and the
     * cause of the failure
     */
    static pointcut actorCellHandleInvokeFailure(ActorCell actorCell, Throwable failure) : target(actorCell) &&
            execution(* akka.actor.ActorCell.handleInvokeFailure(..)) && args(*, failure);

    /**
     * Pointcut for the {@code EventStream.publish(event)} method, extracting just the event
     */
    static pointcut eventStreamPublish(Object event) :
            execution(* akka.event.EventStream.publish(..)) && args(event);

    /**
     * Pointcut for the {@code actorOf} method in {@code ActorRefFactory} implementations. You would typically use
     * it in the {@code after returning()} advices.
     */
    private pointcut unnamedActorOf(Props props) : execution(* akka.actor.ActorRefFactory+.actorOf(*)) && args(props);
    /**
     * Pointcut for the {@code actorOf} method in {@code ActorRefFactory} implementations where actor is named on creation
     */
    private pointcut namedActorOf(Props props) : execution(* akka.actor.ActorRefFactory+.actorOf(*,*)) && args(props, *);
    /**
     * Public pointcut for retrieving Props instance used by {@code actorOf} method in {@code ActorRefFactory}
     */
    pointcut anyActorOf(Props props) : namedActorOf(props) || unnamedActorOf(props);

    /**
     * Pointcut for {@code ActorCell.stop(actor)} method, extracting the {@code ActorRef}
     */
    static pointcut actorCellStop(ActorRef actor) : execution(* akka.actor.ActorCell.stop(..)) && args(actor);

    /**
     * Pointcut for {@code ActorCell.stop()} method, extracting the targeted {@code ActorCell}
     */
    static pointcut actorCellInternalStop(ActorCell actorCell) : target(actorCell) && execution(* akka.actor.ActorCell.stop());
}


Avoid aspectj warning adviceDidNotMatch

Avoid aspectj warning adviceDidNotMatch

package org.folio.rest.annotations;

import java.util.Arrays;
import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.ValidationException;
import javax.validation.ValidatorFactory;
import javax.validation.executable.ExecutableValidator;
import org.aspectj.lang.reflect.MethodSignature;
import org.aspectj.lang.annotation.SuppressAjWarnings;

public aspect RestValidator {

  static private ValidatorFactory factory;

  static {
    factory = Validation.buildDefaultValidatorFactory();
  }

  static private ExecutableValidator getMethodValidator() {
    return factory.getValidator().forExecutables();
  }

  pointcut validatedMethodCall() : execution(@Validate * *(..));

  /**
   * Validates the method parameters.
   */
  @SuppressAjWarnings({"adviceDidNotMatch"})
  before() : validatedMethodCall() {

    MethodSignature methodSignature = (MethodSignature) thisJoinPoint.getSignature();

    System.out.println("Validating call: with args " + methodSignature.getMethod() + Arrays.toString(thisJoinPoint.getArgs()));

    String[] params = methodSignature.getParameterNames();

    Set<? extends ConstraintViolation<?>> validationErrors = getMethodValidator().validateParameters(thisJoinPoint.getThis(),
        methodSignature.getMethod(), thisJoinPoint.getArgs());

    if (validationErrors.isEmpty()) {
      System.out.println("Valid call......");
    } else {
      System.out.println("Invalid call......");
      RuntimeException ex = buildValidationException(validationErrors, params);
      throw ex;
    }
  }

  /**
   * @param validationErrors
   *          The errors detected in a method/constructor call.
   * @return A RuntimeException with information about the detected validation
   *         errors.
   */
  private RuntimeException buildValidationException(Set<? extends ConstraintViolation<?>> validationErrors, String[] paramNames) {
    StringBuilder sb = new StringBuilder();
    for (ConstraintViolation<?> cv : validationErrors) {
      // sb.append("\n" + cv.getPropertyPath() + "{" + cv.getInvalidValue() +
      // "} : " + cv.getMessage());
      String positionOfBadParam = cv.getPropertyPath().toString();
      if (positionOfBadParam != null) {
        try {
          String paramName = paramNames[Integer.valueOf(positionOfBadParam.substring(positionOfBadParam.length() - 1,
              positionOfBadParam.length()))];
          sb.append("\n '" + paramName + "' parameter is incorrect. parameter value {" + cv.getInvalidValue() + "} is not valid: "
              + cv.getMessage());

        } catch (Exception e) {
          sb.append("\n not all parameters were passed properly. parameter value {" + cv.getInvalidValue() + "} is not valid: "
              + cv.getMessage());

        }
      }
    }
    return new ValidationException(sb.toString());
  }
}

package org.folio.rest.annotations;

import java.util.Arrays;
import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.ValidationException;
import javax.validation.ValidatorFactory;
import javax.validation.executable.ExecutableValidator;
import org.aspectj.lang.reflect.MethodSignature;

public aspect RestValidator {

  static private ValidatorFactory factory;

  static {
    factory = Validation.buildDefaultValidatorFactory();
  }

  static private ExecutableValidator getMethodValidator() {
    return factory.getValidator().forExecutables();
  }

  pointcut validatedMethodCall() : execution(@Validate * *(..));

  /**
   * Validates the method parameters.
   */
  before() : validatedMethodCall() {

    MethodSignature methodSignature = (MethodSignature) thisJoinPoint.getSignature();

    System.out.println("Validating call: with args " + methodSignature.getMethod() + Arrays.toString(thisJoinPoint.getArgs()));

    String[] params = methodSignature.getParameterNames();

    Set<? extends ConstraintViolation<?>> validationErrors = getMethodValidator().validateParameters(thisJoinPoint.getThis(),
        methodSignature.getMethod(), thisJoinPoint.getArgs());

    if (validationErrors.isEmpty()) {
      System.out.println("Valid call......");
    } else {
      System.out.println("Invalid call......");
      RuntimeException ex = buildValidationException(validationErrors, params);
      throw ex;
    }
  }

  /**
   * @param validationErrors
   *          The errors detected in a method/constructor call.
   * @return A RuntimeException with information about the detected validation
   *         errors.
   */
  private RuntimeException buildValidationException(Set<? extends ConstraintViolation<?>> validationErrors, String[] paramNames) {
    StringBuilder sb = new StringBuilder();
    for (ConstraintViolation<?> cv : validationErrors) {
      // sb.append("\n" + cv.getPropertyPath() + "{" + cv.getInvalidValue() +
      // "} : " + cv.getMessage());
      String positionOfBadParam = cv.getPropertyPath().toString();
      if (positionOfBadParam != null) {
        try {
          String paramName = paramNames[Integer.valueOf(positionOfBadParam.substring(positionOfBadParam.length() - 1,
              positionOfBadParam.length()))];
          sb.append("\n '" + paramName + "' parameter is incorrect. parameter value {" + cv.getInvalidValue() + "} is not valid: "
              + cv.getMessage());

        } catch (Exception e) {
          sb.append("\n not all parameters were passed properly. parameter value {" + cv.getInvalidValue() + "} is not valid: "
              + cv.getMessage());

        }
      }
    }
    return new ValidationException(sb.toString());
  }
}