Define an ExecutorService using the Capacity annotation value set on the Program. If no Capacity is set on the Program, a CachedThreadPool ExecutorService is used.

/*
 *     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 java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.parallelj.Programs;
import org.parallelj.Programs.ProcessHelper;
import org.parallelj.internal.kernel.KCall;
import org.parallelj.internal.kernel.KProgram;
import org.parallelj.internal.kernel.KReflection;
import org.parallelj.internal.reflect.ProgramAdapter.Adapter;
import org.parallelj.launching.LaunchingMessageKind;
import org.parallelj.launching.ReturnCodes;
import org.parallelj.mirror.ProgramType;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

/**
 * Implements the Job.execute(..) method
 *
 *
 */
privileged public aspect ProgramJobsAdapter 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 {
				// Initialize an ExecutorService with the Capacity of the Program
				ProcessHelper<?> processHelper = Programs.as((Adapter) self);
				ProgramType programType = processHelper.getProcess().getProgram();
				ExecutorService service = null;
				if (programType instanceof KProgram) {
					short programCapacity = ((KProgram) programType)
							.getCapacity();
					service = (programCapacity == Short.MAX_VALUE) ? Executors
							.newCachedThreadPool() : Executors
							.newFixedThreadPool(programCapacity);
				} else {
					service = Executors
							.newCachedThreadPool();
				}
				// Launch the program with the initialized ExecutorService
				processHelper.execute(service).join();
				service.shutdown();
				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 != null && 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);
		if (this.context != null
				&& this.context.getResult() != null
				&& this.context.getResult() instanceof JobDataMap) {
			((JobDataMap) this.context.getResult()).put(
					QuartzUtils.RETURN_CODE, ReturnCodes.FAILURE);
		}
    }
}


'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");
		}
	}

}


Added to eliminate XsdValidation.java build error.

package org.slc.sli.ingestion.logging;

import org.slf4j.LoggerFactory;

import org.slc.sli.ingestion.util.LogUtil;

/**
 *
 * @author mpatel
 *
 */
public aspect IngestionLoggerAspect {

    declare parents : (org.slc.sli.ingestion..*
            && !org.slc.sli.ingestion.handler.AbstractIng*
            && !org.slc.sli.ingestion.handler.Handl*
            && !org.slc.sli.ingestion.transformation.AbstractTrans*
            && !org.slc.sli.ingestion.validation.ErrorRep*
            && !org.slc.sli.ingestion.validation.Valid*
            && !org.slc.sli.ingestion.validation.spring.SimpleV*
            && !org.slc.sli.ingestion.landingzone.validation.IngestionFileVal*
            && !java.lang.Enum+ ) implements IngestionLogger;

    public void IngestionLogger.debug(String msg) {
        LoggerFactory.getLogger(this.getClass()).debug(msg);
    }

    public void IngestionLogger.info(String msg) {
        LoggerFactory.getLogger(this.getClass()).info(msg);
    }

    public void IngestionLogger.warn(String msg) {
        LoggerFactory.getLogger(this.getClass()).warn(msg);
    }

    public void IngestionLogger.debug(String msg, Object... params) {
        LoggerFactory.getLogger(this.getClass()).debug(msg, params);
    }

    public void IngestionLogger.info(String msg, Object... params) {
        LoggerFactory.getLogger(this.getClass()).info(msg, params);
    }

    public void IngestionLogger.warn(String msg, Object... params) {
        LoggerFactory.getLogger(this.getClass()).warn(msg, params);
    }

    public void IngestionLogger.error(String msg, Object... params) {
        LoggerFactory.getLogger(this.getClass()).error(msg, params);
    }

    public void IngestionLogger.error(String msg, Throwable x) {
        LoggerFactory.getLogger(this.getClass()).error(msg, x);
    }

    public void IngestionLogger.piiClearedError(String msg, Throwable x) {
        LogUtil.error(LoggerFactory.getLogger(this.getClass()), msg, (Exception)x);
    }

}

package org.slc.sli.ingestion.logging;

import org.slf4j.LoggerFactory;

import org.slc.sli.ingestion.util.LogUtil;

/**
 *
 * @author mpatel
 *
 */
public aspect IngestionLoggerAspect {

    declare parents : (org.slc.sli.ingestion..*
            && !org.slc.sli.ingestion.handler.AbstractIng*
            && !org.slc.sli.ingestion.handler.Handl*
            && !org.slc.sli.ingestion.transformation.AbstractTrans*
            && !org.slc.sli.ingestion.validation.ErrorRep*
            && !org.slc.sli.ingestion.validation.spring.SimpleV*
            && !org.slc.sli.ingestion.landingzone.validation.IngestionFileVal*
            && !java.lang.Enum+ ) implements IngestionLogger;

    public void IngestionLogger.debug(String msg) {
        LoggerFactory.getLogger(this.getClass()).debug(msg);
    }

    public void IngestionLogger.info(String msg) {
        LoggerFactory.getLogger(this.getClass()).info(msg);
    }

    public void IngestionLogger.warn(String msg) {
        LoggerFactory.getLogger(this.getClass()).warn(msg);
    }

    public void IngestionLogger.debug(String msg, Object... params) {
        LoggerFactory.getLogger(this.getClass()).debug(msg, params);
    }

    public void IngestionLogger.info(String msg, Object... params) {
        LoggerFactory.getLogger(this.getClass()).info(msg, params);
    }

    public void IngestionLogger.warn(String msg, Object... params) {
        LoggerFactory.getLogger(this.getClass()).warn(msg, params);
    }

    public void IngestionLogger.error(String msg, Object... params) {
        LoggerFactory.getLogger(this.getClass()).error(msg, params);
    }

    public void IngestionLogger.error(String msg, Throwable x) {
        LoggerFactory.getLogger(this.getClass()).error(msg, x);
    }

    public void IngestionLogger.piiClearedError(String msg, Throwable x) {
        LogUtil.error(LoggerFactory.getLogger(this.getClass()), msg, (Exception)x);
    }

}


changes made by roo

changes made by roo

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

package org.datacite.mds.web.ui.controller;

import java.io.UnsupportedEncodingException;
import java.lang.Long;
import java.lang.String;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.datacite.mds.domain.Dataset;
import org.datacite.mds.domain.Media;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.util.UriUtils;
import org.springframework.web.util.WebUtils;

privileged aspect MediaController_Roo_Controller {

    @RequestMapping(method = RequestMethod.POST)
    public String MediaController.create(@Valid Media media, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            uiModel.addAttribute("media", media);
            return "medias/create";
        }
        uiModel.asMap().clear();
        media.persist();
        return "redirect:/medias/" + encodeUrlPathSegment(media.getId().toString(), httpServletRequest);
    }

    @RequestMapping(params = "form", method = RequestMethod.GET)
    public String MediaController.createForm(Model uiModel) {
        uiModel.addAttribute("media", new Media());
        List dependencies = new ArrayList();
        if (Dataset.countDatasets() == 0) {
            dependencies.add(new String[]{"dataset", "datasets"});
        }
        uiModel.addAttribute("dependencies", dependencies);
        return "medias/create";
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public String MediaController.show(@PathVariable("id") Long id, Model uiModel) {
        uiModel.addAttribute("media", Media.findMedia(id));
        uiModel.addAttribute("itemId", id);
        return "medias/show";
    }

    @RequestMapping(method = RequestMethod.PUT)
    public String MediaController.update(@Valid Media media, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            uiModel.addAttribute("media", media);
            return "medias/update";
        }
        uiModel.asMap().clear();
        media.merge();
        return "redirect:/medias/" + encodeUrlPathSegment(media.getId().toString(), httpServletRequest);
    }

    @RequestMapping(value = "/{id}", params = "form", method = RequestMethod.GET)
    public String MediaController.updateForm(@PathVariable("id") Long id, Model uiModel) {
        uiModel.addAttribute("media", Media.findMedia(id));
        return "medias/update";
    }

    @ModelAttribute("datasets")
    public Collection<Dataset> MediaController.populateDatasets() {
        return Dataset.findAllDatasets();
    }

    @ModelAttribute("medias")
    public Collection<Media> MediaController.populateMedias() {
        return Media.findAllMedias();
    }

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

}

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

package org.datacite.mds.web.ui.controller;

import java.io.UnsupportedEncodingException;
import java.lang.Long;
import java.lang.String;
import java.util.Collection;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.datacite.mds.domain.Dataset;
import org.datacite.mds.domain.Media;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.util.UriUtils;
import org.springframework.web.util.WebUtils;

privileged aspect MediaController_Roo_Controller {

    @RequestMapping(method = RequestMethod.POST)
    public String MediaController.create(@Valid Media media, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            uiModel.addAttribute("media", media);
            return "medias/create";
        }
        uiModel.asMap().clear();
        media.persist();
        return "redirect:/medias/" + encodeUrlPathSegment(media.getId().toString(), httpServletRequest);
    }

    @RequestMapping(params = "form", method = RequestMethod.GET)
    public String MediaController.createForm(Model uiModel) {
        uiModel.addAttribute("media", new Media());
        return "medias/create";
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public String MediaController.show(@PathVariable("id") Long id, Model uiModel) {
        uiModel.addAttribute("media", Media.findMedia(id));
        uiModel.addAttribute("itemId", id);
        return "medias/show";
    }

    @RequestMapping(method = RequestMethod.PUT)
    public String MediaController.update(@Valid Media media, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            uiModel.addAttribute("media", media);
            return "medias/update";
        }
        uiModel.asMap().clear();
        media.merge();
        return "redirect:/medias/" + encodeUrlPathSegment(media.getId().toString(), httpServletRequest);
    }

    @RequestMapping(value = "/{id}", params = "form", method = RequestMethod.GET)
    public String MediaController.updateForm(@PathVariable("id") Long id, Model uiModel) {
        uiModel.addAttribute("media", Media.findMedia(id));
        return "medias/update";
    }

    @ModelAttribute("datasets")
    public Collection<Dataset> MediaController.populateDatasets() {
        return Dataset.findAllDatasets();
    }

    @ModelAttribute("medias")
    public Collection<Media> MediaController.populateMedias() {
        return Media.findAllMedias();
    }

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

}


XWIKI-2103: Add encodeURI and decodeURI to Util, deprecate XWiki.getURLEncoded, Utils.encode, Utils.decode
Add the compatibility method to the aspect

git-svn-id: cfa2b40e478804c47c05d0f328c574ec5aa2b82e@7751 f329d543-caf0-0310-9063-dda96c69346f

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

import com.xpn.xwiki.api.XWiki;
import com.xpn.xwiki.api.Util;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.stats.api.XWikiStatsService;

import java.io.IOException;
import java.awt.image.BufferedImage;
import java.util.*;

/**
 * Add a backward compatibility layer to the {@link com.xpn.xwiki.api.XWiki} class.
 *
 * @version $Id: $
 */
public privileged aspect XWikiCompatibilityAspect
{
    /**
     * Utility methods have been moved in version 1.3 Milestone 2 to the {@link Util} class.
     * However to preserve backward compatibility we have deprecated them in this class and
     * not removed them yet. All calls are funnelled through this class variable.
     */
    private Util XWiki.util;

    /**
     * Capture the api.XWiki constructor so that we can initialize this.util.
     */
    private pointcut xwikiCreation(XWiki x): this(x) && execution( public XWiki.new(..) );

    after(XWiki x): xwikiCreation(x)
    {
        x.util = new Util(x.xwiki, x.context);
    }

    /**
     * API to protect Text from Wiki transformation
     * @param text
     * @return escaped text
     * @deprecated replaced by Util#escapeText since 1.3M2
     */
    public String XWiki.escapeText(String text)
    {
        return this.util.escapeText(text);
    }

    /**
     * API to protect URLs from Wiki transformation
     * @param url
     * @return encoded URL
     * @deprecated replaced by Util#escapeURL since 1.3M2
     */
    public String XWiki.escapeURL(String url)
    {
        return this.util.escapeURL(url);
    }

    /**
     * @deprecated use {@link #getLanguagePreference()} instead
     */
    public String XWiki.getDocLanguagePreference()
    {
        return xwiki.getDocLanguagePreference(getXWikiContext());
    }

    /**
     * Privileged API to send a message to an email address
     *
     * @param sender email of the sender of the message
     * @param recipient email of the recipient of the message
     * @param message Message to send
     * @throws XWikiException if the mail was not send successfully
     * @deprecated replaced by the
     *   Mail Sender
     *   Plugin since 1.3M2
     */
    public void XWiki.sendMessage(String sender, String recipient, String message)
        throws XWikiException
    {
        if (hasProgrammingRights())
            xwiki.sendMessage(sender, recipient, message, getXWikiContext());
    }

    /**
     * Privileged API to send a message to an email address
     *
     * @param sender email of the sender of the message
     * @param recipient emails of the recipients of the message
     * @param message Message to send
     * @throws XWikiException if the mail was not send successfully
     * @deprecated replaced by the
     *   Mail Sender
     *   Plugin since 1.3M2
     */
    public void XWiki.sendMessage(String sender, String[] recipient, String message)
        throws XWikiException
    {
        if (hasProgrammingRights())
            xwiki.sendMessage(sender, recipient, message, getXWikiContext());
    }

    /**
     * @return the current date
     * @deprecated replaced by {@link com.xpn.xwiki.api.Util#getDate()} since 1.3M2
     */
    public Date XWiki.getCurrentDate()
    {
        return this.util.getDate();
    }

    /**
     * @return the current date
     * @deprecated replaced by {@link com.xpn.xwiki.api.Util#getDate()} since 1.3M2
     */
    public Date XWiki.getDate()
    {
        return this.util.getDate();
    }

    /**
     * @param time the time in milliseconds
     * @return the time delta in milliseconds between the current date and the time passed
     *         as parameter
     * @deprecated replaced by {@link com.xpn.xwiki.api.Util#getTimeDelta(long)} since 1.3M2
     */
    public int XWiki.getTimeDelta(long time)
    {
        return this.util.getTimeDelta(time);
    }

    /**
     * @param time time in milliseconds since 1970, 00:00:00 GMT
     * @return Date a date from a time in milliseconds since 01/01/1970 as a
     *         Java {@link Date} Object
     * @deprecated replaced by {@link com.xpn.xwiki.api.Util#getDate(long)} since 1.3M2
     */
    public Date XWiki.getDate(long time)
    {
        return this.util.getDate(time);
    }

    /**
     * Split a text to an array of texts, according to a separator.
     *
     * @param text the original text
     * @param sep the separator characters. The separator is one or more of the
     *        separator characters
     * @return An array containing the split text
     * @deprecated replaced by {@link com.xpn.xwiki.api.Util#split(String, String)} since 1.3M2
     */
    public String[] XWiki.split(String text, String sep)
    {
        return this.util.split(text, sep);
    }

    /**
     * Get a stack trace as a String
     *
     * @param e the exception to convert to a String
     * @return the exception stack trace as a String
     * @deprecated replaced by {@link com.xpn.xwiki.api.Util#printStrackTrace(Throwable)}
                   since 1.3M2
     */
    public String XWiki.printStrackTrace(Throwable e)
    {
        return this.util.printStrackTrace(e);
    }

    /**
     * Get a Null object. This is useful in Velocity where there is no real null object
     * for comparaisons.
     *
     * @return a Null Object
     * @deprecated replaced by {@link Util#getNull()} since 1.3M2
     */
    public Object XWiki.getNull()
    {
        return this.util.getNull();
    }

    /**
     * Get a New Line character. This is useful in Velocity where there is no real new
     * line character for inclusion in texts.
     *
     * @return a new line character
     * @deprecated replaced by {@link com.xpn.xwiki.api.Util#getNewline()} since 1.3M2
     */
    public String XWiki.getNl()
    {
        return this.util.getNewline();
    }

    /**
     * @see #getExoService(String)
     * @deprecated use {@link #getExoService(String)} instead
     */
    public java.lang.Object XWiki.getService(String className) throws XWikiException
    {
        return getExoService(className);
    }

    /**
     * @see #getExoPortalService(String)
     * @deprecated use {@link #getExoPortalService(String)} instead
     */
    public java.lang.Object XWiki.getPortalService(String className) throws XWikiException
    {
        return getExoPortalService(className);
    }

    /**
     * Creates an Array List. This is useful from Velocity since you cannot
     * create Object from Velocity with our secure uberspector.
     *
     * @return a {@link ArrayList} object
     * @deprecated replaced by {@link com.xpn.xwiki.api.Util#getArrayList()} since 1.3M2
     */
    public List XWiki.getArrayList()
    {
        return this.util.getArrayList();
    }

    /**
     * Creates a Hash Map. This is useful from Velocity since you cannot
     * create Object from Velocity with our secure uberspector.
     *
     * @return a {@link HashMap} object
     * @deprecated replaced by {@link Util#getHashMap()} since 1.3M2
     */
    public Map XWiki.getHashMap()
    {
        return this.util.getHashMap();
    }

    /**
     * Creates a Tree Map. This is useful from Velocity since you cannot
     * create Object from Velocity with our secure uberspector.
     *
     * @return a {@link TreeMap} object
     * @deprecated replaced by {@link com.xpn.xwiki.api.Util#getTreeMap()} since 1.3M2
     */
    public Map XWiki.getTreeMap()
    {
        return this.util.getTreeMap();
    }

    /**
     * Sort a list using a standard comparator. Elements need to be mutally comparable and
     * implement the Comparable interface.
     *
     * @param list the list to sort
     * @return the sorted list (as the same oject reference)
     * @see {@link java.util.Collections#sort(java.util.List)}
     * @deprecated replaced by {@link com.xpn.xwiki.api.Util#sort(java.util.List)} since 1.3M2
     */
    public List XWiki.sort(List list)
    {
        return this.util.sort(list);
    }

    /**
     * Convert an Object to a number and return null if the object is not a Number.
     *
     * @param object the object to convert
     * @return the object as a {@link Number}
     * @deprecated replaced by {@link com.xpn.xwiki.api.Util#toNumber(Object)} since 1.3M2
     */
    public Number XWiki.toNumber(Object object)
    {
        return this.util.toNumber(object);
    }

    /**
     * Generate a random string.
     *
     * @param size the desired size of the string
     * @return the randomly generated string
     * @deprecated replaced by {@link com.xpn.xwiki.api.Util#generateRandomString(int)}
                   since 1.3M2
     */
    public String XWiki.generateRandomString(int size)
    {
        return this.util.generateRandomString(size);
    }

    /**
     * Output a BufferedImage object into the response outputstream.
     * Once this method has been called, not further action is possible.
     * Users should set $context.setFinished(true) to
     * avoid template output The image is outpout as image/jpeg.
     *
     * @param image the BufferedImage to output
     * @throws java.io.IOException if the output fails
     * @deprecated replaced by
     *             {@link com.xpn.xwiki.api.Util#outputImage(java.awt.image.BufferedImage)}
     *             since 1.3M2
     */
    public void XWiki.outputImage(BufferedImage image) throws IOException
    {
        this.util.outputImage(image);
    }

    /**
     * Returns the recently visited pages for a specific action
     *
     * @param action ("view" or "edit")
     * @param size how many recent actions to retrieve
     * @return a ArrayList of document names
     * @deprecated use {@link #getStatsService()} instead
     */
    public java.util.Collection XWiki.getRecentActions(String action, int size)
    {
        XWikiStatsService stats = getXWikiContext().getWiki().getStatsService(getXWikiContext());
        if (stats == null)
            return Collections.EMPTY_LIST;
        return stats.getRecentActions(action, size, getXWikiContext());
    }

    /**
     * @param str the String to convert to an integer
     * @return the parsed integer or zero in case of exception
     * @deprecated replaced by {@link Util#parseInt(String)} since 1.3M2
     */
    public int XWiki.parseInt(String str)
    {
        return this.util.parseInt(str);
    }

    /**
     * @param str the String to convert to an Integer Object
     * @return the parsed integer or zero in case of exception
     * @deprecated replaced by {@link Util#parseInteger(String)} since 1.3M2
     */
    public Integer XWiki.parseInteger(String str)
    {
        return this.util.parseInteger(str);
    }

    /**
     * @param str the String to convert to a long
     * @return the parsed long or zero in case of exception
     * @deprecated replaced by {@link Util#parseLong(String)} since 1.3M2
     */
    public long XWiki.parseLong(String str)
    {
        return this.util.parseLong(str);
    }

    /**
     * @param str the String to convert to a float
     * @return the parsed float or zero in case of exception
     * @deprecated replaced by {@link Util#parseFloat(String)} since 1.3M2
     */
    public float XWiki.parseFloat(String str)
    {
        return this.util.parseFloat(str);
    }

    /**
     * @param str the String to convert to a double
     * @return the parsed double or zero in case of exception
     * @deprecated replaced by {@link Util#parseDouble(String)} since 1.3M2
     */
    public double XWiki.parseDouble(String str)
    {
        return this.util.parseDouble(str);
    }

    /**
     * Escape text so that it can be used in a like clause or in a test for equality clause.
     * For example it escapes single quote characters.
     *
     * @param text the text to escape
     * @return filtered text
     * @deprecated replaced by {@link Util#escapeSQL(String)} since 1.3M2
     */
    public String XWiki.sqlfilter(String text)
    {
        return this.util.escapeSQL(text);
    }

    /**
     * Cleans up the passed text by removing all accents and special characters to make it
     * a valid page name.
     *
     * @param name the page name to normalize
     * @return the valid page name
     * @deprecated replaced by {@link Util#clearName(String)} since 1.3M2
     */
    public String XWiki.clearName(String name)
    {
        return this.util.clearName(name);
    }

    /**
     * Replace all accents by their alpha equivalent.
     *
     * @param text the text to parse
     * @return a string with accents replaced with their alpha equivalent
     * @deprecated replaced by {@link Util#clearAccents(String)} since 1.3M2
     */
    public String XWiki.clearAccents(String text)
    {
        return this.util.clearAccents(text);
    }

    /**
     * Add a and b because Velocity operations are not always working.
     *
     * @param a an integer to add
     * @param b an integer to add
     * @return the sum of a and b
     * @deprecated replaced by {@link Util#add(int, int)} since 1.3M2
     */
    public int XWiki.add(int a, int b)
    {
        return this.util.add(a, b);
    }

    /**
     * Add a and b because Velocity operations are not working with longs.
     *
     * @param a a long to add
     * @param b a long to add
     * @return the sum of a and b
     * @deprecated replaced by {@link Util#add(long, long)} since 1.3M2
     */
    public long XWiki.add(long a, long b)
    {
        return this.util.add(a, b);
    }

    /**
     * Add a and b where a and b are non decimal numbers specified as Strings.
     *
     * @param a a string representing a non decimal number
     * @param b a string representing a non decimal number
     * @return the sum of a and b as a String
     * @deprecated replaced by {@link Util#add(String, String)} since 1.3M2
     */
    public String XWiki.add(String a, String b)
    {
        return this.util.add(a,  b);
    }

    /**
     * Transform a text in a URL compatible text
     *
     * @param content text to transform
     * @return encoded result
     * @deprecated replaced by {@link Util#encodeURI(String)} since 1.3M2
     */
    public String XWiki.getURLEncoded(String content)
    {
        return this.util.encodeURI(content);
    }
}

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

import com.xpn.xwiki.api.XWiki;
import com.xpn.xwiki.api.Util;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.stats.api.XWikiStatsService;

import java.io.IOException;
import java.awt.image.BufferedImage;
import java.util.*;

/**
 * Add a backward compatibility layer to the {@link com.xpn.xwiki.api.XWiki} class.
 *
 * @version $Id: $
 */
public privileged aspect XWikiCompatibilityAspect
{
    /**
     * Utility methods have been moved in version 1.3 Milestone 2 to the {@link Util} class.
     * However to preserve backward compatibility we have deprecated them in this class and
     * not removed them yet. All calls are funnelled through this class variable.
     */
    private Util XWiki.util;

    /**
     * Capture the api.XWiki constructor so that we can initialize this.util.
     */
    private pointcut xwikiCreation(XWiki x): this(x) && execution( public XWiki.new(..) );

    after(XWiki x): xwikiCreation(x)
    {
        x.util = new Util(x.xwiki, x.context);
    }

    /**
     * API to protect Text from Wiki transformation
     * @param text
     * @return escaped text
     * @deprecated replaced by Util#escapeText since 1.3M2
     */
    public String XWiki.escapeText(String text)
    {
        return this.util.escapeText(text);
    }

    /**
     * API to protect URLs from Wiki transformation
     * @param url
     * @return encoded URL
     * @deprecated replaced by Util#escapeURL since 1.3M2
     */
    public String XWiki.escapeURL(String url)
    {
        return this.util.escapeURL(url);
    }

    /**
     * @deprecated use {@link #getLanguagePreference()} instead
     */
    public String XWiki.getDocLanguagePreference()
    {
        return xwiki.getDocLanguagePreference(getXWikiContext());
    }

    /**
     * Privileged API to send a message to an email address
     *
     * @param sender email of the sender of the message
     * @param recipient email of the recipient of the message
     * @param message Message to send
     * @throws XWikiException if the mail was not send successfully
     * @deprecated replaced by the
     *   Mail Sender
     *   Plugin since 1.3M2
     */
    public void XWiki.sendMessage(String sender, String recipient, String message)
        throws XWikiException
    {
        if (hasProgrammingRights())
            xwiki.sendMessage(sender, recipient, message, getXWikiContext());
    }

    /**
     * Privileged API to send a message to an email address
     *
     * @param sender email of the sender of the message
     * @param recipient emails of the recipients of the message
     * @param message Message to send
     * @throws XWikiException if the mail was not send successfully
     * @deprecated replaced by the
     *   Mail Sender
     *   Plugin since 1.3M2
     */
    public void XWiki.sendMessage(String sender, String[] recipient, String message)
        throws XWikiException
    {
        if (hasProgrammingRights())
            xwiki.sendMessage(sender, recipient, message, getXWikiContext());
    }

    /**
     * @return the current date
     * @deprecated replaced by {@link com.xpn.xwiki.api.Util#getDate()} since 1.3M2
     */
    public Date XWiki.getCurrentDate()
    {
        return this.util.getDate();
    }

    /**
     * @return the current date
     * @deprecated replaced by {@link com.xpn.xwiki.api.Util#getDate()} since 1.3M2
     */
    public Date XWiki.getDate()
    {
        return this.util.getDate();
    }

    /**
     * @param time the time in milliseconds
     * @return the time delta in milliseconds between the current date and the time passed
     *         as parameter
     * @deprecated replaced by {@link com.xpn.xwiki.api.Util#getTimeDelta(long)} since 1.3M2
     */
    public int XWiki.getTimeDelta(long time)
    {
        return this.util.getTimeDelta(time);
    }

    /**
     * @param time time in milliseconds since 1970, 00:00:00 GMT
     * @return Date a date from a time in milliseconds since 01/01/1970 as a
     *         Java {@link Date} Object
     * @deprecated replaced by {@link com.xpn.xwiki.api.Util#getDate(long)} since 1.3M2
     */
    public Date XWiki.getDate(long time)
    {
        return this.util.getDate(time);
    }

    /**
     * Split a text to an array of texts, according to a separator.
     *
     * @param text the original text
     * @param sep the separator characters. The separator is one or more of the
     *        separator characters
     * @return An array containing the split text
     * @deprecated replaced by {@link com.xpn.xwiki.api.Util#split(String, String)} since 1.3M2
     */
    public String[] XWiki.split(String text, String sep)
    {
        return this.util.split(text, sep);
    }

    /**
     * Get a stack trace as a String
     *
     * @param e the exception to convert to a String
     * @return the exception stack trace as a String
     * @deprecated replaced by {@link com.xpn.xwiki.api.Util#printStrackTrace(Throwable)}
                   since 1.3M2
     */
    public String XWiki.printStrackTrace(Throwable e)
    {
        return this.util.printStrackTrace(e);
    }

    /**
     * Get a Null object. This is useful in Velocity where there is no real null object
     * for comparaisons.
     *
     * @return a Null Object
     * @deprecated replaced by {@link Util#getNull()} since 1.3M2
     */
    public Object XWiki.getNull()
    {
        return this.util.getNull();
    }

    /**
     * Get a New Line character. This is useful in Velocity where there is no real new
     * line character for inclusion in texts.
     *
     * @return a new line character
     * @deprecated replaced by {@link com.xpn.xwiki.api.Util#getNewline()} since 1.3M2
     */
    public String XWiki.getNl()
    {
        return this.util.getNewline();
    }

    /**
     * @see #getExoService(String)
     * @deprecated use {@link #getExoService(String)} instead
     */
    public java.lang.Object XWiki.getService(String className) throws XWikiException
    {
        return getExoService(className);
    }

    /**
     * @see #getExoPortalService(String)
     * @deprecated use {@link #getExoPortalService(String)} instead
     */
    public java.lang.Object XWiki.getPortalService(String className) throws XWikiException
    {
        return getExoPortalService(className);
    }

    /**
     * Creates an Array List. This is useful from Velocity since you cannot
     * create Object from Velocity with our secure uberspector.
     *
     * @return a {@link ArrayList} object
     * @deprecated replaced by {@link com.xpn.xwiki.api.Util#getArrayList()} since 1.3M2
     */
    public List XWiki.getArrayList()
    {
        return this.util.getArrayList();
    }

    /**
     * Creates a Hash Map. This is useful from Velocity since you cannot
     * create Object from Velocity with our secure uberspector.
     *
     * @return a {@link HashMap} object
     * @deprecated replaced by {@link Util#getHashMap()} since 1.3M2
     */
    public Map XWiki.getHashMap()
    {
        return this.util.getHashMap();
    }

    /**
     * Creates a Tree Map. This is useful from Velocity since you cannot
     * create Object from Velocity with our secure uberspector.
     *
     * @return a {@link TreeMap} object
     * @deprecated replaced by {@link com.xpn.xwiki.api.Util#getTreeMap()} since 1.3M2
     */
    public Map XWiki.getTreeMap()
    {
        return this.util.getTreeMap();
    }

    /**
     * Sort a list using a standard comparator. Elements need to be mutally comparable and
     * implement the Comparable interface.
     *
     * @param list the list to sort
     * @return the sorted list (as the same oject reference)
     * @see {@link java.util.Collections#sort(java.util.List)}
     * @deprecated replaced by {@link com.xpn.xwiki.api.Util#sort(java.util.List)} since 1.3M2
     */
    public List XWiki.sort(List list)
    {
        return this.util.sort(list);
    }

    /**
     * Convert an Object to a number and return null if the object is not a Number.
     *
     * @param object the object to convert
     * @return the object as a {@link Number}
     * @deprecated replaced by {@link com.xpn.xwiki.api.Util#toNumber(Object)} since 1.3M2
     */
    public Number XWiki.toNumber(Object object)
    {
        return this.util.toNumber(object);
    }

    /**
     * Generate a random string.
     *
     * @param size the desired size of the string
     * @return the randomly generated string
     * @deprecated replaced by {@link com.xpn.xwiki.api.Util#generateRandomString(int)}
                   since 1.3M2
     */
    public String XWiki.generateRandomString(int size)
    {
        return this.util.generateRandomString(size);
    }

    /**
     * Output a BufferedImage object into the response outputstream.
     * Once this method has been called, not further action is possible.
     * Users should set $context.setFinished(true) to
     * avoid template output The image is outpout as image/jpeg.
     *
     * @param image the BufferedImage to output
     * @throws java.io.IOException if the output fails
     * @deprecated replaced by
     *             {@link com.xpn.xwiki.api.Util#outputImage(java.awt.image.BufferedImage)}
     *             since 1.3M2
     */
    public void XWiki.outputImage(BufferedImage image) throws IOException
    {
        this.util.outputImage(image);
    }

    /**
     * Returns the recently visited pages for a specific action
     *
     * @param action ("view" or "edit")
     * @param size how many recent actions to retrieve
     * @return a ArrayList of document names
     * @deprecated use {@link #getStatsService()} instead
     */
    public java.util.Collection XWiki.getRecentActions(String action, int size)
    {
        XWikiStatsService stats = getXWikiContext().getWiki().getStatsService(getXWikiContext());
        if (stats == null)
            return Collections.EMPTY_LIST;
        return stats.getRecentActions(action, size, getXWikiContext());
    }

    /**
     * @param str the String to convert to an integer
     * @return the parsed integer or zero in case of exception
     * @deprecated replaced by {@link Util#parseInt(String)} since 1.3M2
     */
    public int XWiki.parseInt(String str)
    {
        return this.util.parseInt(str);
    }

    /**
     * @param str the String to convert to an Integer Object
     * @return the parsed integer or zero in case of exception
     * @deprecated replaced by {@link Util#parseInteger(String)} since 1.3M2
     */
    public Integer XWiki.parseInteger(String str)
    {
        return this.util.parseInteger(str);
    }

    /**
     * @param str the String to convert to a long
     * @return the parsed long or zero in case of exception
     * @deprecated replaced by {@link Util#parseLong(String)} since 1.3M2
     */
    public long XWiki.parseLong(String str)
    {
        return this.util.parseLong(str);
    }

    /**
     * @param str the String to convert to a float
     * @return the parsed float or zero in case of exception
     * @deprecated replaced by {@link Util#parseFloat(String)} since 1.3M2
     */
    public float XWiki.parseFloat(String str)
    {
        return this.util.parseFloat(str);
    }

    /**
     * @param str the String to convert to a double
     * @return the parsed double or zero in case of exception
     * @deprecated replaced by {@link Util#parseDouble(String)} since 1.3M2
     */
    public double XWiki.parseDouble(String str)
    {
        return this.util.parseDouble(str);
    }

    /**
     * Escape text so that it can be used in a like clause or in a test for equality clause.
     * For example it escapes single quote characters.
     *
     * @param text the text to escape
     * @return filtered text
     * @deprecated replaced by {@link Util#escapeSQL(String)} since 1.3M2
     */
    public String XWiki.sqlfilter(String text)
    {
        return this.util.escapeSQL(text);
    }

    /**
     * Cleans up the passed text by removing all accents and special characters to make it
     * a valid page name.
     *
     * @param name the page name to normalize
     * @return the valid page name
     * @deprecated replaced by {@link Util#clearName(String)} since 1.3M2
     */
    public String XWiki.clearName(String name)
    {
        return this.util.clearName(name);
    }

    /**
     * Replace all accents by their alpha equivalent.
     *
     * @param text the text to parse
     * @return a string with accents replaced with their alpha equivalent
     * @deprecated replaced by {@link Util#clearAccents(String)} since 1.3M2
     */
    public String XWiki.clearAccents(String text)
    {
        return this.util.clearAccents(text);
    }

    /**
     * Add a and b because Velocity operations are not always working.
     *
     * @param a an integer to add
     * @param b an integer to add
     * @return the sum of a and b
     * @deprecated replaced by {@link Util#add(int, int)} since 1.3M2
     */
    public int XWiki.add(int a, int b)
    {
        return this.util.add(a, b);
    }

    /**
     * Add a and b because Velocity operations are not working with longs.
     *
     * @param a a long to add
     * @param b a long to add
     * @return the sum of a and b
     * @deprecated replaced by {@link Util#add(long, long)} since 1.3M2
     */
    public long XWiki.add(long a, long b)
    {
        return this.util.add(a, b);
    }

    /**
     * Add a and b where a and b are non decimal numbers specified as Strings.
     *
     * @param a a string representing a non decimal number
     * @param b a string representing a non decimal number
     * @return the sum of a and b as a String
     * @deprecated replaced by {@link Util#add(String, String)} since 1.3M2
     */
    public String XWiki.add(String a, String b)
    {
        return this.util.add(a,  b);
    }
}


Fixing typos in StatOverallTxt.aj

Fixing typos in StatOverallTxt.aj

import java.awt.GridLayout;

import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;

import view.GUI;
import view.UIUpdater;

public privileged aspect StatOverallTxt {

    private static GUI gui;
    private static JPanel panel = new JPanel();
    private static JTextArea statText = new JTextArea();

    after() returning(GUI gui): call(GUI.new(*)) {
        StatOverallTxt.gui = gui;
    }

    after(JTabbedPane tabbedPane):
			execution(public static void StatisticsHelper.StatisticsPaneCreated(JTabbedPane))
			&& args(tabbedPane) {
        statText.setEditable(false);
        panel.setLayout(new GridLayout(0, 1));
        panel.add(statText);
        ((JTabbedPane) tabbedPane).addTab("OverallText", panel);
    }

    after() : execution(* UIUpdater.run()) {
        statText.setText(getOverallStatisticsString());
    }

    public String getOverallStatisticsString() {
        OverallStatistics data = gui.model.getGameData().getOverallStatistics();

        return "#Spiele (ohne weiter): " + data.getAnzahlSpieleGesamt()
                + " (gewonnen: "
                + String.format("%.2f", data.getGesamtWinPerc()) + "%)\n"
                + "#Rufspiele: " + data.getAnzahlRufspiele() + " (gewonnen: "
                + String.format("%.2f", data.getRufspieleWinPerc()) + "%)\n"
                + "          -> teuerstes Rufspiel: "
                + data.getTeuerstesRufspiel() + "\n" + "#Soli gesamt: "
                + data.getAnzahlSoliGesamt() + " (gewonnen: "
                + String.format("%.2f", data.getSoliGesamtWinPerc())
                + "%)\n" + "#Soli normal: " + data.getAnzahlSoli()
                + " (gewonnen: "
                + String.format("%.2f", data.getSoliNormalWinPerc()) + "%)\n"
                + "            -> teuerstes Solo: " + data.getTeuerstesSolo()
                + "\n" + "#Solo Tout: " + data.getAnzahlSoliTout()
                + " (gewonnen: "
                + String.format("%.2f", data.getSoliToutWinPerc()) + "%)\n"
                + "          -> teuerstes Solo Tout: "
                + data.getTeuerstesSoloTout() + "\n" + "#Solo Sie: "
                + data.getAnzahlSoliSie() + "\n"
                + "         -> teuerstes Solo Sie: "
                + data.getTeuerstesSoloSie() + "\n" + "#Weiter: "
                + data.getAnzahlWeiter();
    }
}

import java.awt.GridLayout;

import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;

import view.GUI;
import view.UIUpdater;

public privileged aspect StatOverallTxt {

    private static GUI gui;
    private static JPanel panel = new JPanel();
    private static JTextArea statText = new JTextArea();

    after() returning(GUI gui): call(GUI.new(*)) {
        StatOverallTxt.gui = gui;
    }

    after(JTabbedPane tabbedPane):
			execution(public static void StatisticsHelper.StatisticsPaneCreated(JTabbedPane))
			&& args(tabbedPane) {
        statText.setEditable(false);
        panel.setLayout(new GridLayout(0, 1));
        panel.add(statText);
        ((JTabbedPane) tabbedPane).addTab("OverallText", panel);
    }

    after() : execution(* UIUpdater.run()) {
        statText.setText(getOverallStatisticsString());
    }

    public String getOverallStatisticsString() {
        OverallStatistics data = gui.model.getGameData().getOverallStatistics();

        return "#Spiele (ohne weiter): " + data.getAnzahlSpieleGesamt()
                + " (gewonnen: "
                + String.format("%.2f", data.getGesamtWinPerc()) + "%)\n"
                + "#Rufspiele: " + data.getAnzahlRufspiele() + " (gewonnen: "
                + String.format("%.2f", data.getRufspieleWinPerc()) + "%)\n"
                + "          -> teurstes Rufspiel: "
                + data.getTeuerstesRufspiel() + "\n" + "#Soli gesamt: "
                + data.getAnzahlSoliGesamt() + " (gewonnen: "
                + String.format("%.2f", data.getSoliGesamtWinPerc())
                + "%)\n" + "#Soli normal: " + data.getAnzahlSoli()
                + " (gewonnen: "
                + String.format("%.2f", data.getSoliNormalWinPerc()) + "%)\n"
                + "            -> teurstes Solo: " + data.getTeuerstesSolo()
                + "\n" + "#Solo Tout: " + data.getAnzahlSoliTout()
                + " (gewonnen: "
                + String.format("%.2f", data.getSoliToutWinPerc()) + "%)\n"
                + "          -> teurstes Solo Tout: "
                + data.getTeuerstesSoloTout() + "\n" + "#Solo Sie: "
                + data.getAnzahlSoliSie() + "\n"
                + "         -> teurstes Solo Sie: "
                + data.getTeuerstesSoloSie() + "\n" + "#Weiter: "
                + data.getAnzahlWeiter();
    }
}


Remove unused import

Remove unused import

/**
 * Copyright (C) 2013 Antonin Stefanutti (antonin.stefanutti@gmail.com)
 *
 * 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 fr.stefanutti.metrics.aspectj;

import com.codahale.metrics.Metric;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.annotation.Gauge;
import com.codahale.metrics.annotation.ExceptionMetered;
import com.codahale.metrics.annotation.Metered;
import com.codahale.metrics.annotation.Timed;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

final aspect MetricAspect extends AbstractMetricAspect {

    declare precedence: MetricStaticAspect, MetricAspect, *;

    declare parents : (@Metrics *) implements Profiled;

    /* packaged-protected */
    final Map<String, AnnotatedMetric> Profiled.metrics = new ConcurrentHashMap<String, AnnotatedMetric>();

    pointcut profiled(Profiled object) : execution((@Metrics Profiled+).new(..)) && this(object);

    after(final Profiled object) : profiled(object) {
        final MetricStrategy strategy = MetricStrategyFactory.newInstance(object);
        for (final Method method : object.getClass().getDeclaredMethods()) {
            // Skip advising static methods
            if (Modifier.isStatic(method.getModifiers()))
                continue;

            metricAnnotation(object, method, strategy, ExceptionMetered.class, new MetricFactory() {
                @Override
                public Metric metric(MetricRegistry registry, String name, boolean absolute) {
                    String finalName = name.isEmpty() ? method.getName() + "." + ExceptionMetered.DEFAULT_NAME_SUFFIX : strategy.resolveMetricName(name);
                    return registry.meter(absolute ? finalName : MetricRegistry.name(object.getClass(), finalName));
                }
            });
            metricAnnotation(object, method, strategy, Gauge.class, new MetricFactory() {
                @Override
                public Metric metric(MetricRegistry registry, String name, boolean absolute) {
                    String finalName = name.isEmpty() ? method.getName() : strategy.resolveMetricName(name);
                    return registry.register(absolute ? finalName : MetricRegistry.name(object.getClass(), finalName), new ForwardingGauge(method, object));
                }
            });
            metricAnnotation(object, method, strategy, Metered.class, new MetricFactory() {
                @Override
                public Metric metric(MetricRegistry registry, String name, boolean absolute) {
                    String finalName = name.isEmpty() ? method.getName() : strategy.resolveMetricName(name);
                    return registry.meter(absolute ? finalName : MetricRegistry.name(object.getClass(), finalName));
                }
            });
            metricAnnotation(object, method, strategy, Timed.class, new MetricFactory() {
                @Override
                public Metric metric(MetricRegistry registry, String name, boolean absolute) {
                    String finalName = name.isEmpty() ? method.getName() : strategy.resolveMetricName(name);
                    return registry.timer(absolute ? finalName : MetricRegistry.name(object.getClass(), finalName));
                }
            });
        }
    }

    private void metricAnnotation(Profiled object, Method method, MetricStrategy strategy, Class<? extends Annotation> clazz, MetricFactory factory) {
        if (method.isAnnotationPresent(clazz)) {
            MetricRegistry registry = strategy.resolveMetricRegistry(object.getClass().getAnnotation(Registry.class).value());
            Annotation annotation = method.getAnnotation(clazz);
            Metric metric = factory.metric(registry, metricAnnotationName(annotation), metricAnnotationAbsolute(annotation));
            object.metrics.put(method.toString(), new AnnotatedMetric(metric, annotation));
        }
    }
}

/**
 * Copyright (C) 2013 Antonin Stefanutti (antonin.stefanutti@gmail.com)
 *
 * 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 fr.stefanutti.metrics.aspectj;

import com.codahale.metrics.Metric;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.annotation.Gauge;
import com.codahale.metrics.annotation.ExceptionMetered;
import com.codahale.metrics.annotation.Metered;
import com.codahale.metrics.annotation.Timed;

import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

final aspect MetricAspect extends AbstractMetricAspect {

    declare precedence: MetricStaticAspect, MetricAspect, *;

    declare parents : (@Metrics *) implements Profiled;

    /* packaged-protected */
    final Map<String, AnnotatedMetric> Profiled.metrics = new ConcurrentHashMap<String, AnnotatedMetric>();

    pointcut profiled(Profiled object) : execution((@Metrics Profiled+).new(..)) && this(object);

    after(final Profiled object) : profiled(object) {
        final MetricStrategy strategy = MetricStrategyFactory.newInstance(object);
        for (final Method method : object.getClass().getDeclaredMethods()) {
            // Skip advising static methods
            if (Modifier.isStatic(method.getModifiers()))
                continue;

            metricAnnotation(object, method, strategy, ExceptionMetered.class, new MetricFactory() {
                @Override
                public Metric metric(MetricRegistry registry, String name, boolean absolute) {
                    String finalName = name.isEmpty() ? method.getName() + "." + ExceptionMetered.DEFAULT_NAME_SUFFIX : strategy.resolveMetricName(name);
                    return registry.meter(absolute ? finalName : MetricRegistry.name(object.getClass(), finalName));
                }
            });
            metricAnnotation(object, method, strategy, Gauge.class, new MetricFactory() {
                @Override
                public Metric metric(MetricRegistry registry, String name, boolean absolute) {
                    String finalName = name.isEmpty() ? method.getName() : strategy.resolveMetricName(name);
                    return registry.register(absolute ? finalName : MetricRegistry.name(object.getClass(), finalName), new ForwardingGauge(method, object));
                }
            });
            metricAnnotation(object, method, strategy, Metered.class, new MetricFactory() {
                @Override
                public Metric metric(MetricRegistry registry, String name, boolean absolute) {
                    String finalName = name.isEmpty() ? method.getName() : strategy.resolveMetricName(name);
                    return registry.meter(absolute ? finalName : MetricRegistry.name(object.getClass(), finalName));
                }
            });
            metricAnnotation(object, method, strategy, Timed.class, new MetricFactory() {
                @Override
                public Metric metric(MetricRegistry registry, String name, boolean absolute) {
                    String finalName = name.isEmpty() ? method.getName() : strategy.resolveMetricName(name);
                    return registry.timer(absolute ? finalName : MetricRegistry.name(object.getClass(), finalName));
                }
            });
        }
    }

    private void metricAnnotation(Profiled object, Method method, MetricStrategy strategy, Class<? extends Annotation> clazz, MetricFactory factory) {
        if (method.isAnnotationPresent(clazz)) {
            MetricRegistry registry = strategy.resolveMetricRegistry(object.getClass().getAnnotation(Registry.class).value());
            Annotation annotation = method.getAnnotation(clazz);
            Metric metric = factory.metric(registry, metricAnnotationName(annotation), metricAnnotationAbsolute(annotation));
            object.metrics.put(method.toString(), new AnnotatedMetric(metric, annotation));
        }
    }
}


profiling calls exclude logging class.

profiling calls exclude logging class.

package com.sec.android.app.camera;

import org.aspectj.lang.Signature;

public aspect AutoLog {
    pointcut publicMethods() : execution(public * *..*(..));
    pointcut protectedMethods() : execution(protected * *..*(..));
    pointcut privateMethods() : execution(private * *..*(..));
    pointcut allMethods() : execution(* *..*(..));
    pointcut logObjectCalls() : execution(* Prof.*(..));
    pointcut loggableCalls() : allMethods() && ! logObjectCalls();

    before() : loggableCalls() {
        Signature sig = thisJoinPoint.getSignature();
        String str = sig.toLongString();

        Object[] paramValues = thisJoinPoint.getArgs();
        if (paramValues.length != 0)
            str += " [args] ";

        for (Object object:paramValues) {
            if (null != object)
                str += object.toString() + ",,";
        }

        Prof.entry(str);
    }

    after() returning(Object objectRet) : loggableCalls() {
        Signature sig = thisJoinPoint.getSignature();
        String str = sig.toLongString();
        if (null != objectRet){
            str += " [returns] ";
            str += objectRet.toString();
        }
        Prof.exit(str);
    }
}

package com.sec.android.app.camera;

import org.aspectj.lang.Signature;

public aspect AutoLog {
    pointcut publicMethods() : execution(public * *..*(..));
    pointcut protectedMethods() : execution(protected * *..*(..));
    pointcut privateMethods() : execution(private * *..*(..));
    pointcut allMethods() : execution(* *..*(..));
    pointcut logObjectCalls() : execution(* Prof.*(..));
    pointcut loggableCalls() : allMethods() && logObjectCalls();

    before() : loggableCalls() {
        Signature sig = thisJoinPoint.getSignature();
        String str = sig.toLongString();

        Object[] paramValues = thisJoinPoint.getArgs();
        if (paramValues.length != 0)
            str += " [args] ";

        for (Object object:paramValues) {
            if (null != object)
                str += object.toString() + ",,";
        }

        Prof.entry(str);
    }

    after() returning(Object objectRet) : loggableCalls() {
        Signature sig = thisJoinPoint.getSignature();
        String str = sig.toLongString();
        if (null != objectRet){
            str += " [returns] ";
            str += objectRet.toString();
        }
        Prof.exit(str);
    }
}


Fix for issue #72

Fix for issue #72

package org.imaginea.botbot;

import java.util.*;
import android.util.Log;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.view.*;
import android.widget.*;
import android.gesture.*;

import org.imaginea.botbot.*;

aspect OnCreate
{

	static String firstActivity;
	static int count=0;
    pointcut captureOnCreate() : (execution(* onCreate(Bundle)));

    before(): captureOnCreate()
   	{
   		Object target = thisJoinPoint.getTarget();
   		count++;
   		if (firstActivity == null) firstActivity = target.getClass().getName();
   	}

	after(): captureOnCreate()
	{
		Object target = thisJoinPoint.getTarget();

		if (!(target instanceof Activity))
			return;
		if (firstActivity == null)
			return;
		if (firstActivity.contentEquals(target.getClass().getName()) && count==1) {
			Activity a = (Activity) target;

			ListenerAdder la = new ListenerAdder();
			la.processView(a.getWindow().getDecorView().getRootView());
			firstActivity = null;
		}
		count--;
	}

    pointcut captureCreate() : (call(* create()));

    after() returning (AlertDialog d): captureCreate()
	{
	}

}

package org.imaginea.botbot;

import java.util.*;
import android.util.Log;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.view.*;
import android.widget.*;
import android.gesture.*;

import org.imaginea.botbot.*;

aspect OnCreate
{

	String firstActivity;

    pointcut captureOnCreate() : (execution(* onCreate(Bundle)));

    before(): captureOnCreate()
	{
		Object target = thisJoinPoint.getTarget();

		if (firstActivity == null) firstActivity = target.getClass().getName();
	}

    after(): captureOnCreate()
	{
		Object target = thisJoinPoint.getTarget();

		if (!(target instanceof Activity)) return;

		Activity a = (Activity) target;

		ListenerAdder la = new ListenerAdder();
		la.processView(a.getWindow().getDecorView().getRootView());    }

    pointcut captureCreate() : (call(* create()));

    after() returning (AlertDialog d): captureCreate()
	{
	}

}


AspectJ tryouts

AspectJ tryouts


+= Logger lors des achats

+= Logger lors des achats

package logger;

import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

import ca.ulaval.ticketmaster.events.tickets.model.Ticket;
import ca.ulaval.ticketmaster.purchase.model.PurchaseViewModel;
import ca.ulaval.ticketmaster.users.model.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;

public aspect LogBoughtTicketAspect {

	private static final String LOG_FILE = "src/main/resources/log.log";
	private static void log( String str )
	{
		FileWriter fwLog = null;

		try {
			fwLog = new FileWriter(LOG_FILE, true);
			fwLog.append(str);
			fwLog.flush();
			fwLog.close();
		} catch (IOException e) {
			System.out.println("Ne peut pas logger :");
			e.printStackTrace();
		}

	}

	//Purchase
	pointcut logPurchase() :
		execution(
				public String ca.ulaval.ticketmaster.purchase.PurchaseController.purchase(PurchaseViewModel, Model, HttpSession,
					    BindingResult, HttpServletRequest) );

	before() : logPurchase()
	{
		System.out.println("About to log");

		System.out.println(thisJoinPoint.getSignature());
		System.out.println(thisJoinPoint.getArgs().length);

		System.out.println(thisJoinPoint.getArgs()[0] instanceof PurchaseViewModel);

		if ( thisJoinPoint.getArgs()[0] instanceof PurchaseViewModel )
		{
			PurchaseViewModel pModel = (PurchaseViewModel)thisJoinPoint.getArgs()[0];

			System.out.println(pModel.toString());
		}
		//pModel.
		//System.out.println(model.);
				//thisJoinPoint().getArgs();
	}

	pointcut logConfirmation() :
		execution(
				private void ca.ulaval.ticketmaster.dao.util.DataManager.sendConfirmationMail(User, UUID, List<Ticket>) );

	@SuppressWarnings("unchecked")
	Object around() : logConfirmation()
	{
		System.out.println("around");

		User user = (User)thisJoinPoint.getArgs()[0];
		UUID transactionId = (UUID)thisJoinPoint.getArgs()[1];
		ArrayList<Ticket> ticketList = (ArrayList<Ticket>)thisJoinPoint.getArgs()[2];

		LogBoughtTicketAspect.log("Envoi du courriel de confirmation  l'utilisateur '" + user.getUsername()
				+ "' avec transactionId = '" + transactionId
				+ "', les billets :\n" + Arrays.toString(ticketList.toArray()));

		Object retval = proceed();

		return retval;
	}

}

package logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;

import ca.ulaval.ticketmaster.purchase.model.PurchaseViewModel;

public aspect LogBoughtTicketAspect {

	//Purchase
	pointcut logPurchase() :
		execution(
				//Ne peut pas utiliser .. pour l'argument en raison du GET
				public String ca.ulaval.ticketmaster.purchase.PurchaseController.purchase(PurchaseViewModel, Model, HttpSession,
					    BindingResult, HttpServletRequest) );
		//execution( * *(..) );

	before() : logPurchase()
	{
		System.out.println("About to log");

		System.out.println(thisJoinPoint.getSignature());
		System.out.println(thisJoinPoint.getArgs().length);

		System.out.println(thisJoinPoint.getArgs()[0] instanceof PurchaseViewModel);

		if ( thisJoinPoint.getArgs()[0] instanceof PurchaseViewModel )
		{
			PurchaseViewModel pModel = (PurchaseViewModel)thisJoinPoint.getArgs()[0];

			System.out.println(pModel.toString());
		}
		//pModel.
		//System.out.println(model.);
				//thisJoinPoint().getArgs();
	}

}


[misc] Remove unused imports

[misc] Remove unused imports

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

import java.util.List;
import java.util.Map;
import java.lang.reflect.Type;

import org.xwiki.component.descriptor.ComponentDescriptor;
import org.xwiki.component.manager.ComponentLookupException;

/**
 * Add a backward compatibility layer to the {@link EmbeddableComponentManager} class.
 *
 * @version $Id$
 * @since 4.1M1
 */
public privileged aspect EmbeddableComponentManagerCompatibilityAspect
{
    @Deprecated
    public <T> T EmbeddableComponentManager.lookup(Class<T> role) throws ComponentLookupException
    {
        return getInstance(role);
    }

    @Deprecated
    public <T> T EmbeddableComponentManager.lookup(Class<T> role, String hint) throws ComponentLookupException
    {
        return getInstance(role, hint);
    }

    @Deprecated
    public <T> List<T> EmbeddableComponentManager.lookupList(Class<T> role) throws ComponentLookupException
    {
        return getInstanceList((Type) role);
    }

    @Deprecated
    public <T> Map<String, T> EmbeddableComponentManager.lookupMap(Class<T> role) throws ComponentLookupException
    {
        return getInstanceMap((Type) role);
    }

    @Deprecated
    public <T> boolean EmbeddableComponentManager.hasComponent(Class<T> role, String hint)
    {
        return hasComponent((Type) role, hint);
    }

    @Deprecated
    public <T> boolean EmbeddableComponentManager.hasComponent(Class<T> role)
    {
        return hasComponent((Type) role);
    }

    @Deprecated
    public <T> ComponentDescriptor<T> EmbeddableComponentManager.getComponentDescriptor(Class<T> role, String hint)
    {
        return getComponentDescriptor((Type) role, hint);
    }

    @Deprecated
    public <T> void EmbeddableComponentManager.unregisterComponent(Class<T> role, String hint)
    {
        unregisterComponent((Type) role, hint);
    }
}

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

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.lang.reflect.Type;

import org.xwiki.component.descriptor.ComponentDescriptor;
import org.xwiki.component.internal.RoleHint;
import org.xwiki.component.manager.ComponentLookupException;

/**
 * Add a backward compatibility layer to the {@link EmbeddableComponentManager} class.
 *
 * @version $Id$
 * @since 4.1M1
 */
public privileged aspect EmbeddableComponentManagerCompatibilityAspect
{
    @Deprecated
    public <T> T EmbeddableComponentManager.lookup(Class<T> role) throws ComponentLookupException
    {
        return getInstance(role);
    }

    @Deprecated
    public <T> T EmbeddableComponentManager.lookup(Class<T> role, String hint) throws ComponentLookupException
    {
        return getInstance(role, hint);
    }

    @Deprecated
    public <T> List<T> EmbeddableComponentManager.lookupList(Class<T> role) throws ComponentLookupException
    {
        return getInstanceList((Type) role);
    }

    @Deprecated
    public <T> Map<String, T> EmbeddableComponentManager.lookupMap(Class<T> role) throws ComponentLookupException
    {
        return getInstanceMap((Type) role);
    }

    @Deprecated
    public <T> boolean EmbeddableComponentManager.hasComponent(Class<T> role, String hint)
    {
        return hasComponent((Type) role, hint);
    }

    @Deprecated
    public <T> boolean EmbeddableComponentManager.hasComponent(Class<T> role)
    {
        return hasComponent((Type) role);
    }

    @Deprecated
    public <T> ComponentDescriptor<T> EmbeddableComponentManager.getComponentDescriptor(Class<T> role, String hint)
    {
        return getComponentDescriptor((Type) role, hint);
    }

    @Deprecated
    public <T> void EmbeddableComponentManager.unregisterComponent(Class<T> role, String hint)
    {
        unregisterComponent((Type) role, hint);
    }
}