Check the result is not null before puting something inside

/*
 *     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.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.parallelj.Programs;
import org.parallelj.internal.kernel.KCall;
import org.parallelj.internal.reflect.ProgramAdapter.Adapter;
import org.parallelj.launching.LaunchingMessageKind;
import org.parallelj.launching.ReturnCodes;
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 percflow (execution(public void Job+.execute(..) throws JobExecutionException)) {

	/**
	 * The JobExecutionContext where get Program's arguments ant where to put
	 * the Result.
	 */
	public JobExecutionContext context;

	/*
	 * The Aspect JobsAdapter must be passed before this.
	 */
	declare precedence :
		org.parallelj.launching.quartz.JobsAdapter;

	private Adapter adpater;

	/**
	 * 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) {
		this.adpater = (Adapter) self;
		this.context = context;
		JobDataMap jobDataMap = new JobDataMap();
		context.setResult(jobDataMap);
		jobDataMap.put(QuartzUtils.RETURN_CODE, ReturnCodes.SUCCESS);
		try {
			proceed(self, context);

			try {
				Programs.as((Adapter) self).execute().join();
				ProgramFieldsBinder.getProgramOutputFields(this, context);
			} catch (IllegalAccessException e) {
				jobDataMap.put(QuartzUtils.RETURN_CODE, ReturnCodes.FAILURE);
			} catch (NoSuchFieldException e) {
				jobDataMap.put(QuartzUtils.RETURN_CODE, ReturnCodes.FAILURE);
			}
		} catch (InvocationTargetException e) {
			jobDataMap.put(QuartzUtils.RETURN_CODE, ReturnCodes.FAILURE);
		}
	}

	/**
	 * Intercept Exception thrown in RunnableProcedure/CallableProcedure for tracing. If an
	 * Exception is thrown, the return code of a Launch becomes FAILURE.
	 *
	 * @param self
	 */
    pointcut enter(KCall _kCall): call(* org.parallelj.internal.kernel.callback.Entry+.enter(KCall)) && args(_kCall);
    pointcut invoke(): call(public Object Method.invoke(Object, ..)) && !within(ProgramJobsAdapter);
    after(Object oo, KCall _kCall) throwing (InvocationTargetException ite) :
    	invoke() && args(oo, ..) && cflow(enter(_kCall)) {

		LaunchingMessageKind.ELAUNCH0002.format(this.adpater, ite);
		if (this.context.getResult() != null && this.context.getResult() instanceof JobDataMap) {
			((JobDataMap) this.context.getResult()).put(
					QuartzUtils.RETURN_CODE, ReturnCodes.FAILURE);
		}
    }
}

/*
 *     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.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.parallelj.Programs;
import org.parallelj.internal.kernel.KCall;
import org.parallelj.internal.reflect.ProgramAdapter.Adapter;
import org.parallelj.launching.LaunchingMessageKind;
import org.parallelj.launching.ReturnCodes;
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 percflow (execution(public void Job+.execute(..) throws JobExecutionException)) {

	/**
	 * The JobExecutionContext where get Program's arguments ant where to put
	 * the Result.
	 */
	public JobExecutionContext context;

	/*
	 * The Aspect JobsAdapter must be passed before this.
	 */
	declare precedence :
		org.parallelj.launching.quartz.JobsAdapter;

	private Adapter adpater;

	/**
	 * 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) {
		this.adpater = (Adapter) self;
		this.context = context;
		JobDataMap jobDataMap = new JobDataMap();
		context.setResult(jobDataMap);
		jobDataMap.put(QuartzUtils.RETURN_CODE, ReturnCodes.SUCCESS);
		try {
			proceed(self, context);

			try {
				Programs.as((Adapter) self).execute().join();
				ProgramFieldsBinder.getProgramOutputFields(this, context);
			} catch (IllegalAccessException e) {
				jobDataMap.put(QuartzUtils.RETURN_CODE, ReturnCodes.FAILURE);
			} catch (NoSuchFieldException e) {
				jobDataMap.put(QuartzUtils.RETURN_CODE, ReturnCodes.FAILURE);
			}
		} catch (InvocationTargetException e) {
			jobDataMap.put(QuartzUtils.RETURN_CODE, ReturnCodes.FAILURE);
		}
	}

	/**
	 * Intercept Exception thrown in RunnableProcedure/CallableProcedure for tracing. If an
	 * Exception is thrown, the return code of a Launch becomes FAILURE.
	 *
	 * @param self
	 */
    pointcut enter(KCall _kCall): call(* org.parallelj.internal.kernel.callback.Entry+.enter(KCall)) && args(_kCall);
    pointcut invoke(): call(public Object Method.invoke(Object, ..)) && !within(ProgramJobsAdapter);
    after(Object oo, KCall _kCall) throwing (InvocationTargetException ite) :
    	invoke() && args(oo, ..) && cflow(enter(_kCall)) {

		LaunchingMessageKind.ELAUNCH0002.format(this.adpater, ite);
		((JobDataMap) this.context.getResult()).put(
				QuartzUtils.RETURN_CODE, ReturnCodes.FAILURE);
//		this.result = ReturnCodes.FAILURE.name();
//		track(_kCall, oo, false, ite);
    }
}


'cflow' changed to 'within' to specify where the method is called

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) {
			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.");
			System.exit(0);
		}
	};

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

		boolean result = false;
		// We perform the lock and the monitor step as an atomic action
		// i.e. whilst holding the lockObj, so that we cannot be interrupted
		synchronized (lockObj) {
			result = proceed(lockObj, thread);
			if (result) {
				Verdict verdict = null;
				// Ordering between lockObj and monitor important
				synchronized (monitor) {
					verdict = monitor.step(LOCK_TRUE, thread);
				}
				if (verdict == Verdict.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.");
					System.exit(0);
				}

			}
		}
		return result;
	};

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

		// We perform the unlock and the monitor step as an atomic action
		// i.e. whilst holding the lockObj, so that we cannot be interrupted
		Verdict verdict = null;
		synchronized (lockObj) {
			proceed(lockObj, thread);
			// Ordering between lockObj and monitor important
			synchronized (monitor) {
				verdict = monitor.step(UNLOCK, thread);
			}
		}
		if (verdict == Verdict.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.");
			System.exit(0);
		}
	};

	before(ExampleLocking thread) : action(thread) {
		Verdict verdict = null;
		synchronized (monitor) {
			verdict = monitor.step(ACTION, thread);
		}
		if (verdict == Verdict.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.");
			System.exit(0);
		}
	};

	pointcut endOfProgram() : execution(void ExampleLocking.main(String...));

	after() : endOfProgram() {
		Verdict verdict = monitor.end();
		if (verdict == Verdict.FAILURE || verdict == Verdict.WEAK_FAILURE) {
			System.err
					.println("Violation in JUnitRV (MMT) 3. - 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.");
		} else {
			System.err.println("Property JUnitRV (MMT) 3 satisfied");
		}
	}

}

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) {
			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.");
			System.exit(0);
		}
	};

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

		boolean result = false;
		// We perform the lock and the monitor step as an atomic action
		// i.e. whilst holding the lockObj, so that we cannot be interrupted
		synchronized (lockObj) {
			result = proceed(lockObj, thread);
			if (result) {
				Verdict verdict = null;
				// Ordering between lockObj and monitor important
				synchronized (monitor) {
					verdict = monitor.step(LOCK_TRUE, thread);
				}
				if (verdict == Verdict.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.");
					System.exit(0);
				}

			}
		}
		return result;
	};

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

		// We perform the unlock and the monitor step as an atomic action
		// i.e. whilst holding the lockObj, so that we cannot be interrupted
		Verdict verdict = null;
		synchronized (lockObj) {
			proceed(lockObj, thread);
			// Ordering between lockObj and monitor important
			synchronized (monitor) {
				verdict = monitor.step(UNLOCK, thread);
			}
		}
		if (verdict == Verdict.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.");
			System.exit(0);
		}
	};

	before(ExampleLocking thread) : action(thread) {
		Verdict verdict = null;
		synchronized (monitor) {
			verdict = monitor.step(ACTION, thread);
		}
		if (verdict == Verdict.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.");
			System.exit(0);
		}
	};

	pointcut endOfProgram() : execution(void ExampleLocking.main(String...));

	after() : endOfProgram() {
		Verdict verdict = monitor.end();
		if (verdict == Verdict.FAILURE || verdict == Verdict.WEAK_FAILURE) {
			System.err
					.println("Violation in JUnitRV (MMT) 3. - 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.");
		} else {
			System.err.println("Property JUnitRV (MMT) 3 satisfied");
		}
	}

}


removed comment

removed comment

package scala.tools.eclipse.contribution.weaving.jdt.debug;

import org.eclipse.ui.IEditorInput;
import org.eclipse.jdt.internal.ui.javaeditor.IClassFileEditorInput;
import org.eclipse.jdt.core.IClassFile;
import scala.tools.eclipse.contribution.weaving.jdt.IScalaClassFile;
import org.eclipse.jdt.internal.debug.ui.JDIModelPresentation;

/**
 * Fixes ticket 1000494.
 * @see http://www.assembla.com/spaces/scala-ide/tickets/1000494-cannot-set-breakpoint-for-files-opened-via-the-stacktrace-printed-in-the-console
 */
@SuppressWarnings("restriction")
public aspect JDIModelPresentationAspect {

  pointcut getEditorId(JDIModelPresentation jdiModelPresentation, IEditorInput input, Object inputObject):
    args(input, inputObject)
    && execution(String JDIModelPresentation.getEditorId(IEditorInput, Object))
    && target(jdiModelPresentation);

  String around(JDIModelPresentation jdiModelPresentation, IEditorInput input, Object inputObject):
    getEditorId(jdiModelPresentation, input, inputObject) {
    if(input instanceof IClassFileEditorInput) {
      IClassFile classFile = ((IClassFileEditorInput) input).getClassFile();
      if(classFile instanceof IScalaClassFile) {
        return "scala.tools.eclipse.ScalaClassFileEditor";
      }
    }
    return proceed(jdiModelPresentation, input, inputObject);
  }

}

package scala.tools.eclipse.contribution.weaving.jdt.debug;

import org.eclipse.ui.IEditorInput;
import org.eclipse.jdt.internal.ui.javaeditor.IClassFileEditorInput;
import org.eclipse.jdt.core.IClassFile;
import scala.tools.eclipse.contribution.weaving.jdt.IScalaClassFile;
import org.eclipse.jdt.internal.debug.ui.JDIModelPresentation;

/**
 * Fixes ticket 1000494.
 * @see http://www.assembla.com/spaces/scala-ide/tickets/1000494-cannot-set-breakpoint-for-files-opened-via-the-stacktrace-printed-in-the-console
 */
@SuppressWarnings("restriction")
public aspect JDIModelPresentationAspect {
  //FIXME: Can we share code with ClassFileEditorIdAspect ?! How? (duplication!)
  pointcut getEditorId(JDIModelPresentation jdiModelPresentation, IEditorInput input, Object inputObject):
    args(input, inputObject)
    && execution(String JDIModelPresentation.getEditorId(IEditorInput, Object))
    && target(jdiModelPresentation);

  String around(JDIModelPresentation jdiModelPresentation, IEditorInput input, Object inputObject):
    getEditorId(jdiModelPresentation, input, inputObject) {
    if(input instanceof IClassFileEditorInput) {
      IClassFile classFile = ((IClassFileEditorInput) input).getClassFile();
      if(classFile instanceof IScalaClassFile) {
        return "scala.tools.eclipse.ScalaClassFileEditor";
      }
    }
    return proceed(jdiModelPresentation, input, inputObject);
  }

}


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 getRollbackOnly() handling to EntityTransactionAspect

/**
 * palava - a java-php-bridge
 * Copyright (C) 2007-2010  CosmoCode GmbH
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

package de.cosmocode.palava.jpa.aspectj;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.PersistenceException;

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

import com.google.common.base.Preconditions;
import com.google.inject.Inject;
import com.google.inject.Provider;

import de.cosmocode.palava.core.aop.AbstractPalavaAspect;
import de.cosmocode.palava.jpa.Transactional;

public final aspect EntityTransactionAspect extends AbstractPalavaAspect issingleton() {

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

    private Provider<EntityManager> currentManager;

    @Inject
    public void setProvider(Provider<EntityManager> manager) {
        this.currentManager = Preconditions.checkNotNull(manager, "Manager");
    }

    pointcut transactional(): execution(@Transactional * *.*(..));

    @SuppressAjWarnings("adviceDidNotMatch")
    Object around(): transactional() {
        final EntityManager manager = currentManager.get();
        LOG.trace("Retrieved entitymanager {}", manager);
        final EntityTransaction tx = manager.getTransaction();
        LOG.trace("Using transaction {}", tx);
        final boolean localTx = !tx.isActive();

        if (localTx) {
            LOG.trace("Beginning automatic transaction");
            tx.begin();
        } else {
            LOG.trace("Transaction already active");
        }

        final Object returnValue;

        try {
            returnValue = proceed();
        } catch (RuntimeException e) {
            LOG.error("Exception inside automatic transaction context", e);
            tx.rollback();
            throw e;
        }

        if (localTx && tx.isActive()) {
            if (tx.getRollbackOnly()) {
                LOG.trace("Transaction was marked as rollback only. Rolling back...");
                tx.rollback();
            } else {
                try {
                    tx.commit();
                    LOG.trace("Committed automatic transaction");
                } catch (PersistenceException e) {
                    LOG.error("Commit in automatic transaction context failed", e);
                    tx.rollback();
                    throw e;
                }
            }
        }

        return returnValue;
    }

}

/**
 * palava - a java-php-bridge
 * Copyright (C) 2007-2010  CosmoCode GmbH
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

package de.cosmocode.palava.jpa.aspectj;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.PersistenceException;

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

import com.google.common.base.Preconditions;
import com.google.inject.Inject;
import com.google.inject.Provider;

import de.cosmocode.palava.core.aop.AbstractPalavaAspect;
import de.cosmocode.palava.jpa.Transactional;

public final aspect EntityTransactionAspect extends AbstractPalavaAspect issingleton() {

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

    private Provider<EntityManager> currentManager;

    @Inject
    public void setProvider(Provider<EntityManager> manager) {
        this.currentManager = Preconditions.checkNotNull(manager, "Manager");
    }

    pointcut transactional(): execution(@Transactional * *.*(..));

    @SuppressAjWarnings("adviceDidNotMatch")
    Object around(): transactional() {
        final EntityManager manager = currentManager.get();
        LOG.trace("Retrieved entitymanager {}", manager);
        final EntityTransaction tx = manager.getTransaction();
        LOG.trace("Using transaction {}", tx);
        final boolean localTx = !tx.isActive();

        if (localTx) {
            LOG.trace("Beginning automatic transaction");
            tx.begin();
        } else {
            LOG.trace("Transaction already active");
        }

        final Object returnValue;

        try {
            returnValue = proceed();
        } catch (RuntimeException e) {
            LOG.error("Exception inside automatic transaction context", e);
            tx.rollback();
            throw e;
        }

        try {
            if (localTx && tx.isActive()) {
                tx.commit();
                LOG.trace("Committed automatic transaction");
            }
            return returnValue;
        } catch (PersistenceException e) {
            LOG.error("Commit in automatic transaction context failed", e);
            tx.rollback();
            throw e;
        }
    }

}


sync ExportVmTemplateCommand with ovirt-sync

	package org.ovirt.engine.core.bll;

	import java.util.*;

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

	public privileged aspect Locks {

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

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

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

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

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

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

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

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

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

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

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

	        }
	    }

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

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

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

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

				return locks;
			    }

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

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

		    return locks;
		}

	}

	package org.ovirt.engine.core.bll;

	import java.util.*;

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

	public privileged aspect Locks {

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

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

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

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

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

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

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

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

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

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

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

	        }
	    }

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

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

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

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

			return locks;
		}

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

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

			return locks;
		}

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

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

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

			return locks;
		}

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

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

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

			return locks;
		}

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

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

			return locks;
		}

	}


moved annotation processing to controller - much fewer chance of it getting overwritten

git-svn-id: 611fcff3babe92294e93aa7369573f5fe3352ff6@508 468f3c8c-1912-47de-8909-53fc7abe8733

package org.entitypedia.games.common.mixins;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.entitypedia.games.common.util.HibernateAwareObjectMapper;
import org.entitypedia.games.common.util.MapperSavingJackson2HttpMessageConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.security.access.intercept.aspectj.MethodInvocationAdapter;
import org.springframework.security.access.prepost.PreInvocationAttribute;
import org.springframework.security.access.prepost.PreInvocationAuthorizationAdvice;
import org.springframework.security.access.prepost.PrePostInvocationAttributeFactory;
import org.springframework.security.core.context.SecurityContextHolder;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Applies mixins from annotations to Jackson Mapper.
 *
 * @author Aliaksandr Autayeu
 */
public aspect JacksonMixinSetupAspect implements InitializingBean {

    private static final Logger log = LoggerFactory.getLogger(JacksonMixinSetupAspect.class);

    private PreInvocationAuthorizationAdvice preAdvice;

    private PrePostInvocationAttributeFactory attributeFactory;

    private MapperSavingJackson2HttpMessageConverter converter;

    private Constructor<MethodInvocationAdapter> constructor;

    private final static ThreadLocal<ObjectMapper> tlObjectMapper = new ThreadLocal<ObjectMapper>() {
        @Override protected ObjectMapper initialValue() {
            return null;
        }
    };
    private final static ThreadLocal<List<JacksonMixin>> tlMixins = new ThreadLocal<List<JacksonMixin>>() {
        @Override
        protected List<JacksonMixin> initialValue() {
            return new ArrayList<JacksonMixin>(4);
        }
    };

    @Override
    public void afterPropertiesSet() throws Exception {
        // hack package local constructor...
        constructor = MethodInvocationAdapter.class.getDeclaredConstructor(JoinPoint.class);
        constructor.setAccessible(true);

        if (null == preAdvice) {
            throw new IllegalArgumentException("org.springframework.security.access.expression.method.ExpressionBasedPreInvocationAdvice required!");
        }
        if (null == attributeFactory) {
            throw new IllegalArgumentException("org.springframework.security.access.expression.method.ExpressionBasedAnnotationAttributeFactory required!");
        }
        if (null == converter) {
            throw new IllegalArgumentException("org.entitypedia.games.common.util.MapperSavingJackson2HttpMessageConverter required!");
        }
    }

    pointcut serviceExecution(): execution(@JacksonMixins * org.entitypedia.games..api.controller..*(..));
    after() returning: serviceExecution() {
        // this prepares mixins for the filtering mapper.

        // one needs to check the control flow of the annotated method to ensure
        // there is no other mixins-annotated method being called inside the body
        // e.g. createGame calls readCrossword, both annotated
        // and the latter overwrites the mixins of the former
        // in this case warning is printed

        // jackson allows only one mixin per class... can't accumulate mixins over complex call trees

        // mixins clear in writeInternal. therefore they might get stuck if method does not render JSON
        // e.g. updateFocus calls readGame for access control and mixins get stuck.
        // in this case warning is printed too, but it has little meaning

        if (thisJoinPoint.getSignature() instanceof MethodSignature) {
            MethodSignature signature = (MethodSignature) thisJoinPoint.getSignature();
            // gets interface method
            Method method = signature.getMethod();
            if (null != method) {
                JacksonMixins annotation = method.getAnnotation(JacksonMixins.class);
                if (null != annotation && null != annotation.value() && 0 < annotation.value().length) {
                    List<JacksonMixin> mixins = tlMixins.get();
                    if (0 < mixins.size()) {
                        if (log.isWarnEnabled()) {
                            log.warn("{} is overwriting mixins {}", thisJoinPoint, Arrays.toString(mixinsToStringArray(mixins)));
                        }
                    }
                    mixins.clear();

                    for (int i = 0; i < annotation.value().length; i++) {
                        JacksonMixin mixin = annotation.value()[i];
                        boolean apply = true;
                        if (!"".equals(mixin.condition())) {
                            // evaluate condition
                            PreInvocationAttribute attribute = attributeFactory.createPreInvocationAttribute(null, null, mixin.condition());
                            try {
                                apply = preAdvice.before(
                                        SecurityContextHolder.getContext().getAuthentication(),
                                        constructor.newInstance(thisJoinPoint),
                                        attribute);
                            } catch (InstantiationException e) {
                                throw new RuntimeException(e);
                            } catch (IllegalAccessException e) {
                                throw new RuntimeException(e);
                            } catch (InvocationTargetException e) {
                                throw new RuntimeException(e);
                            }
                        }
                        if (apply) {
                            mixins.add(mixin);
                        }
                    }

                    if (0 < mixins.size()) {
                        if (log.isDebugEnabled()) {
                            log.debug("{} prepared mixins {}", thisJoinPoint, Arrays.toString(mixinsToStringArray(mixins)));
                        }
                    } else {
                        log.debug("{} cleared mixins", thisJoinPoint);
                    }
                }
            }
        }
    }

    private String[] mixinsToStringArray(List<JacksonMixin> mixins) {
        String[] result = new String[mixins.size()];
        for (int i = 0; i < mixins.size(); i++) {
            result[i] = mixins.get(i).target().getSimpleName() + "=" + mixins.get(i).mixin().getSimpleName();
        }
        return result;
    }

    pointcut writeInternalExecution(): execution(* org.entitypedia.games.common.util.MapperSavingJackson2HttpMessageConverter.writeInternal(..));
    Object around(): writeInternalExecution() {
        List<JacksonMixin> mixins = tlMixins.get();
        if (0 < mixins.size()) {
            // set up mapper
            ObjectMapper mapper = new HibernateAwareObjectMapper();
            for (JacksonMixin mixin : mixins) {
                mapper.addMixInAnnotations(mixin.target(), mixin.mixin());
            }

            log.debug("Applying mixins {} to {}", Arrays.toString(mixinsToStringArray(mixins)), converter);
            tlObjectMapper.set(converter.getObjectMapper());
            converter.setObjectMapper(mapper);
        }

        Object result = proceed();

        if (0 < mixins.size()) {
            // restore mapper
            log.debug("Removing mixins from {}", converter);
            converter.setObjectMapper(tlObjectMapper.get());

            // clean up vars
            tlObjectMapper.set(null);
            mixins.clear();
        }

        return result;
    }

    public void setConverter(MapperSavingJackson2HttpMessageConverter converter) {
        this.converter = converter;
    }

    public void setAttributeFactory(PrePostInvocationAttributeFactory attributeFactory) {
        this.attributeFactory = attributeFactory;
    }

    public void setPreAdvice(PreInvocationAuthorizationAdvice preAdvice) {
        this.preAdvice = preAdvice;
    }
}

package org.entitypedia.games.common.mixins;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.entitypedia.games.common.util.HibernateAwareObjectMapper;
import org.entitypedia.games.common.util.MapperSavingJackson2HttpMessageConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.security.access.intercept.aspectj.MethodInvocationAdapter;
import org.springframework.security.access.prepost.PreInvocationAttribute;
import org.springframework.security.access.prepost.PreInvocationAuthorizationAdvice;
import org.springframework.security.access.prepost.PrePostInvocationAttributeFactory;
import org.springframework.security.core.context.SecurityContextHolder;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Applies mixins from annotations to Jackson Mapper.
 *
 * @author Aliaksandr Autayeu
 */
public aspect JacksonMixinSetupAspect implements InitializingBean {

    private static final Logger log = LoggerFactory.getLogger(JacksonMixinSetupAspect.class);

    private PreInvocationAuthorizationAdvice preAdvice;

    private PrePostInvocationAttributeFactory attributeFactory;

    private MapperSavingJackson2HttpMessageConverter converter;

    private Constructor<MethodInvocationAdapter> constructor;

    private final static ThreadLocal<ObjectMapper> tlObjectMapper = new ThreadLocal<ObjectMapper>() {
        @Override protected ObjectMapper initialValue() {
            return null;
        }
    };
    private final static ThreadLocal<List<JacksonMixin>> tlMixins = new ThreadLocal<List<JacksonMixin>>() {
        @Override
        protected List<JacksonMixin> initialValue() {
            return new ArrayList<JacksonMixin>(4);
        }
    };

    @Override
    public void afterPropertiesSet() throws Exception {
        // hack package local constructor...
        constructor = MethodInvocationAdapter.class.getDeclaredConstructor(JoinPoint.class);
        constructor.setAccessible(true);

        if (null == preAdvice) {
            throw new IllegalArgumentException("org.springframework.security.access.expression.method.ExpressionBasedPreInvocationAdvice required!");
        }
        if (null == attributeFactory) {
            throw new IllegalArgumentException("org.springframework.security.access.expression.method.ExpressionBasedAnnotationAttributeFactory required!");
        }
        if (null == converter) {
            throw new IllegalArgumentException("org.entitypedia.games.common.util.MapperSavingJackson2HttpMessageConverter required!");
        }
    }

    pointcut serviceExecution(): execution(@JacksonMixins * org.entitypedia.games..service..*(..));
    // these 2 below might be faster, depends on performance of cflowbelow VS the current checks
    // pointcut controllerExecution(): execution(* org.entitypedia.games..api.controller..*(..));
    // after() returning: serviceExecution() && cflowbelow(controllerExecution()) {
    after() returning: serviceExecution() {
        // this prepares mixins for the filtering mapper.

        // one needs to check the control flow of the annotated method to ensure
        // there is no other mixins-annotated method being called inside the body
        // e.g. createGame calls readCrossword, both annotated
        // and the latter overwrites the mixins of the former
        // in this case warning is printed

        // jackson allows only one mixin per class... can't accumulate mixins over complex call trees

        // mixins clear in writeInternal. therefore they might get stuck if method does not render JSON
        // e.g. updateFocus calls readGame for access control and mixins get stuck.
        // in this case warning is printed too, but it has little meaning

        if (thisJoinPoint.getSignature() instanceof MethodSignature) {
            MethodSignature signature = (MethodSignature) thisJoinPoint.getSignature();
            // gets interface method
            Method method = signature.getMethod();
            if (null != method) {
                JacksonMixins annotation = method.getAnnotation(JacksonMixins.class);
                if (null != annotation && null != annotation.value() && 0 < annotation.value().length) {
                    List<JacksonMixin> mixins = tlMixins.get();
                    if (0 < mixins.size()) {
                        if (log.isWarnEnabled()) {
                            log.warn("{} is overwriting mixins {}", thisJoinPoint, Arrays.toString(mixinsToStringArray(mixins)));
                        }
                    }
                    mixins.clear();

                    for (int i = 0; i < annotation.value().length; i++) {
                        JacksonMixin mixin = annotation.value()[i];
                        boolean apply = true;
                        if (!"".equals(mixin.condition())) {
                            // evaluate condition
                            PreInvocationAttribute attribute = attributeFactory.createPreInvocationAttribute(null, null, mixin.condition());
                            try {
                                apply = preAdvice.before(
                                        SecurityContextHolder.getContext().getAuthentication(),
                                        constructor.newInstance(thisJoinPoint),
                                        attribute);
                            } catch (InstantiationException e) {
                                throw new RuntimeException(e);
                            } catch (IllegalAccessException e) {
                                throw new RuntimeException(e);
                            } catch (InvocationTargetException e) {
                                throw new RuntimeException(e);
                            }
                        }
                        if (apply) {
                            mixins.add(mixin);
                        }
                    }

                    if (0 < mixins.size()) {
                        if (log.isDebugEnabled()) {
                            log.debug("{} prepared mixins {}", thisJoinPoint, Arrays.toString(mixinsToStringArray(mixins)));
                        }
                    } else {
                        log.debug("{} cleared mixins", thisJoinPoint);
                    }
                }
            }
        }
    }

    private String[] mixinsToStringArray(List<JacksonMixin> mixins) {
        String[] result = new String[mixins.size()];
        for (int i = 0; i < mixins.size(); i++) {
            result[i] = mixins.get(i).target().getSimpleName() + "=" + mixins.get(i).mixin().getSimpleName();
        }
        return result;
    }

    pointcut writeInternalExecution(): execution(* org.entitypedia.games.common.util.MapperSavingJackson2HttpMessageConverter.writeInternal(..));
    Object around(): writeInternalExecution() {
        List<JacksonMixin> mixins = tlMixins.get();
        if (0 < mixins.size()) {
            // set up mapper
            ObjectMapper mapper = new HibernateAwareObjectMapper();
            for (JacksonMixin mixin : mixins) {
                mapper.addMixInAnnotations(mixin.target(), mixin.mixin());
            }

            log.debug("Applying mixins {} to {}", Arrays.toString(mixinsToStringArray(mixins)), converter);
            tlObjectMapper.set(converter.getObjectMapper());
            converter.setObjectMapper(mapper);
        }

        Object result = proceed();

        if (0 < mixins.size()) {
            // restore mapper
            log.debug("Removing mixins from {}", converter);
            converter.setObjectMapper(tlObjectMapper.get());

            // clean up vars
            tlObjectMapper.set(null);
            mixins.clear();
        }

        return result;
    }

    public void setConverter(MapperSavingJackson2HttpMessageConverter converter) {
        this.converter = converter;
    }

    public void setAttributeFactory(PrePostInvocationAttributeFactory attributeFactory) {
        this.attributeFactory = attributeFactory;
    }

    public void setPreAdvice(PreInvocationAuthorizationAdvice preAdvice) {
        this.preAdvice = preAdvice;
    }
}


used generic type info to avoid compilation warnings and unneccessary cast

git-svn-id: b619a0c99665f88f1afe72824344cefe9a1c8c90@8627 fd5a2b45-1f63-4059-99e9-3c7cb7fd75c8

/*
 * Copyright 2002-2006 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.beans.factory.aspectj;

/**
 * Concrete aspect that uses the Configurable annotation to identify
 * which classes need autowiring. The bean name to look up will be
 * taken from the Configurable annotation if specified, otherwise
 * the default will be the FQN of the class being configured.
 * @see Configurable
 * @author Rod Johnson
 * @since 2.0
 */
public aspect AnnotationBeanConfigurer extends AbstractBeanConfigurer {

	public AnnotationBeanConfigurer() {
		// Set a custom BeanWiringInfoResolver that is aware of
		// the Configurable annotation
		setBeanWiringInfoResolver(new BeanWiringInfoResolver() {
			public BeanWiringInfo resolve(Object instance) {
				Class<?> clazz = instance.getClass();
				Configurable configurableAnnotation = clazz.getAnnotation(Configurable.class);
				if (configurableAnnotation != null) {
					String beanName = configurableAnnotation.value();
					if ("".equals(beanName)) {
						beanName = clazz.getName();
					}
					return new BeanWiringInfo(beanName);
				}
				return null;
			}
		});
	}

	/**
     * The creation of a new bean (an object with the @SpringConfigured annotation)
     */
    protected pointcut beanCreation(Object beanInstance) :
        initialization((@Configurable *).new(..)) &&
        	this(beanInstance);
}

/*
 * Copyright 2002-2006 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.beans.factory.aspectj;

/**
 * Concrete aspect that uses the Configurable annotation to identify
 * which classes need autowiring. The bean name to look up will be
 * taken from the Configurable annotation if specified, otherwise
 * the default will be the FQN of the class being configured.
 * @see Configurable
 * @author Rod Johnson
 * @since 2.0
 */
public aspect AnnotationBeanConfigurer extends AbstractBeanConfigurer {

	public AnnotationBeanConfigurer() {
		// Set a custom BeanWiringInfoResolver that is aware of
		// the Configurable annotation
		setBeanWiringInfoResolver(new BeanWiringInfoResolver() {
			public BeanWiringInfo resolve(Object instance) {
				Class clazz = instance.getClass();
				Configurable springAnnotation = (Configurable) clazz.getAnnotation(Configurable.class);
				if (springAnnotation != null) {
					String beanName = springAnnotation.value();
					if ("".equals(beanName)) {
						beanName = clazz.getName();
					}
					return new BeanWiringInfo(beanName);
				}
				return null;
			}
		});
	}

	/**
     * The creation of a new bean (an object with the @SpringConfigured annotation)
     */
    protected pointcut beanCreation(Object beanInstance) :
        initialization((@Configurable *).new(..)) &&
        	this(beanInstance);
}


commit 6231ae49df45df5c47e8c9561ef5be03d8d7792f
Author: Vinay Kumar Thota <vinayt@yahoo-inc.com>
Date:   Wed Jun 16 09:54:29 2010 +0000

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

git-svn-id: 7e7a2d564dde2945c3a26e08d1235fcc0cb7aba1@1077506 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 -v " + excludeExp + " | wc -l");
        }
      }
      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());
    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;
  }
}


Formatting

Formatting

package org.apache.beam.aspects;

import org.aspectj.lang.Signature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by jonathan on 17.01.17.
 */
aspect TracingAspect {
    pointcut aspects(): within (org.apache.beam.aspects.*);
    pointcut project(): within (org.apache.beam.*.*) && !aspects();
    pointcut constructors(): call(*.new(..)) && project();
    pointcut methods(): project() && call(* *(..));

    Tree<Signature> tree = new Tree<>(null, null);
    Tree<Signature> currentNode = tree;

    Object around (): constructors() || methods() {
        Signature sig = thisJoinPointStaticPart.getSignature();
        Tree<Signature> child;
        if ((child=currentNode.getChildWithValue(sig))==null) {
            child = new Tree<>(sig,currentNode);
        }
        currentNode = child;
        currentNode.incrementCounter();
        Object o = proceed();
        currentNode = currentNode.getParent();
        if (currentNode==tree) {
            System.out.println(tree);
        }
        return o;
    }
}

package org.apache.beam.aspects;

import org.aspectj.lang.Signature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by jonathan on 17.01.17.
 */
aspect TracingAspect {
    pointcut aspects(): within (org.apache.beam.aspects.*);
    pointcut project(): within (org.apache.beam.*.*) && !aspects();
    pointcut constructors(): call(*.new(..)) && project();
    pointcut methods(): project() && call(* *(..));

    Tree<Signature> tree = new Tree<>(null, null);
    Tree<Signature> currentNode = tree;

    Object around (): constructors() || methods() {
        Signature sig = thisJoinPointStaticPart.getSignature();
        Tree<Signature> child;
        if ((child=currentNode.getChildWithValue(sig))==null) {
            child = new Tree<>(sig,currentNode);
        }
        currentNode = child;
        if (currentNode==tree) {
            System.out.println(tree);
        }
        currentNode.incrementCounter();
        Object o = proceed();
        currentNode = currentNode.getParent();
        return o;
    }
}


*Event id fixed for unlock event

*Event id fixed for unlock event

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;
		// We perform the lock and the monitor step as an atomic action
		// i.e. whilst holding the lockObj, so that we cannot be interrupted
		synchronized (lockObj) {
			result = proceed(lockObj, thread);
			if (result) {
				Verdict verdict = null;
				// Ordering between lockObj and monitor important
				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) {

		// We perform the unlock and the monitor step as an atomic action
		// i.e. whilst holding the lockObj, so that we cannot be interrupted
		Verdict verdict = null;
		synchronized (lockObj) {
			proceed(lockObj, thread);
			// Ordering between lockObj and monitor important
			synchronized (monitor) {
				verdict = monitor.step(UNLOCK, 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 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;
		// We perform the lock and the monitor step as an atomic action
		// i.e. whilst holding the lockObj, so that we cannot be interrupted
		synchronized (lockObj) {
			result = proceed(lockObj, thread);
			if (result) {
				Verdict verdict = null;
				// Ordering between lockObj and monitor important
				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) {

		// We perform the unlock and the monitor step as an atomic action
		// i.e. whilst holding the lockObj, so that we cannot be interrupted
		Verdict verdict = null;
		synchronized (lockObj) {
			proceed(lockObj, thread);
			// Ordering between lockObj and monitor important
			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.");
		}
	};

}