text:
package org.apache.continuum.buildmanager;

import java.io.File;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.continuum.buildqueue.BuildQueueService;
import org.apache.continuum.buildqueue.BuildQueueServiceException;
import org.apache.continuum.dao.BuildDefinitionDao;
import org.apache.continuum.dao.ProjectDao;
import org.apache.continuum.taskqueue.BuildProjectTask;
import org.apache.continuum.taskqueue.CheckOutTask;
import org.apache.continuum.taskqueue.OverallBuildQueue;
import org.apache.continuum.taskqueue.PrepareBuildProjectsTask;
import org.apache.continuum.taskqueueexecutor.ParallelBuildsThreadedTaskQueueExecutor;
import org.apache.continuum.utils.build.BuildTrigger;
import org.apache.maven.continuum.configuration.ConfigurationService;
import org.apache.maven.continuum.model.project.BuildDefinition;
import org.apache.maven.continuum.model.project.BuildQueue;
import org.apache.maven.continuum.model.project.Project;
import org.apache.maven.continuum.model.scm.ScmResult;
import org.apache.maven.continuum.store.ContinuumStoreException;
import org.codehaus.plexus.PlexusConstants;
import org.codehaus.plexus.PlexusContainer;
import org.codehaus.plexus.component.repository.exception.ComponentLifecycleException;
import org.codehaus.plexus.component.repository.exception.ComponentLookupException;
import org.codehaus.plexus.context.Context;
import org.codehaus.plexus.context.ContextException;
import org.codehaus.plexus.personality.plexus.lifecycle.phase.Contextualizable;
import org.codehaus.plexus.personality.plexus.lifecycle.phase.StoppingException;
import org.codehaus.plexus.taskqueue.TaskQueue;
import org.codehaus.plexus.taskqueue.TaskQueueException;
import org.codehaus.plexus.taskqueue.execution.TaskQueueExecutor;
import org.codehaus.plexus.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Parallel builds manager.
 *
 * @author Maria Odea Ching
 */
public class ParallelBuildsManager
    implements BuildsManager, Contextualizable
{
    private static final Logger log = LoggerFactory.getLogger( ParallelBuildsManager.class );

    // map must be synchronized!
    private Map<Integer, OverallBuildQueue> overallBuildQueues = Collections.synchronizedMap(
        new HashMap<Integer, OverallBuildQueue>() );

    private static final int BUILD_QUEUE = 1;

    private static final int CHECKOUT_QUEUE = 2;

    private static final int PREPARE_BUILD_QUEUE = 3;

    @Resource
    private BuildDefinitionDao buildDefinitionDao;

    @Resource
    private ProjectDao projectDao;

    @Resource
    private ConfigurationService configurationService;

    @Resource
    private BuildQueueService buildQueueService;

    private PlexusContainer container;

    /**
     * @see BuildsManager#buildProject(int, BuildDefinition, String, BuildTrigger, ScmResult, int)
     */
    public void buildProject( int projectId, BuildDefinition buildDefinition, String projectName,
                              BuildTrigger buildTrigger, ScmResult scmResult, int projectGroupId )
        throws BuildManagerException
    {
        try
        {
            if ( isInQueue( projectId, BUILD_QUEUE, -1 ) )
            {
                log.warn( "Project already queued." );
                return;
            }
            else if ( isProjectInAnyCurrentBuild( projectId ) )
            {
                log.warn( "Project is already building." );
                return;
            }
        }
        catch ( TaskQueueException e )
        {
            throw new BuildManagerException(
                "Error occurred while checking if the project is already in queue: " + e.getMessage() );
        }

        OverallBuildQueue overallBuildQueue = getOverallBuildQueueWhereProjectsInGroupAreQueued( projectGroupId );

        if ( overallBuildQueue == null )
        {
            overallBuildQueue = getOverallBuildQueue( BUILD_QUEUE, buildDefinition.getSchedule().getBuildQueues() );
        }

        if ( overallBuildQueue != null )
        {
            String buildDefinitionLabel = buildDefinition.getDescription();

            if ( StringUtils.isEmpty( buildDefinitionLabel ) )
            {
                buildDefinitionLabel = buildDefinition.getGoals();
            }

            BuildProjectTask buildTask = new BuildProjectTask( projectId, buildDefinition.getId(), buildTrigger,
                                                               projectName, buildDefinitionLabel, scmResult,
                                                               projectGroupId );
            try
            {
                log.info( "Project '" + projectName + "' added to overall build queue '" + overallBuildQueue.getName() +
                              "'." );
                overallBuildQueue.addToBuildQueue( buildTask );
            }
            catch ( TaskQueueException e )
            {
                throw new BuildManagerException(
                    "Error occurred while adding project to build queue: " + e.getMessage() );
            }
        }
        else
        {
            log.warn( "No build queue configured. Not building." );
        }
    }

    /**
     * @see BuildsManager#buildProjects(List, Map, BuildTrigger, Map, int)
     */
    public void buildProjects( List<Project> projects, Map<Integer, BuildDefinition> projectsBuildDefinitionsMap,
                               BuildTrigger buildTrigger, Map<Integer, ScmResult> scmResultMap, int projectGroupId )
        throws BuildManagerException
    {
        Project firstBuildableProject = null;
        // get id of the first project in the list that is not yet in the build queue
        for ( Project project : projects )
        {
            try
            {
                if ( !isInQueue( project.getId(), BUILD_QUEUE, -1 ) && !isProjectInAnyCurrentBuild( project.getId() ) )
                {
                    firstBuildableProject = project;
                    break;
                }
            }
            catch ( TaskQueueException e )
            {
                log.warn( "Error occurred while verifying if project is already queued." );
            }
        }

        boolean projectsToBuild = firstBuildableProject != null;

        if ( projectsToBuild )
        {
            BuildDefinition buildDef = projectsBuildDefinitionsMap.get( firstBuildableProject.getId() );

            if ( buildDef.getSchedule() == null )
            {
                String msg = String.format( "Invalid data, null schedule for builddef id=%s/project id=%s",
                                            buildDef.getId(), firstBuildableProject.getId() );
                log.error( msg );
                throw new BuildManagerException( msg + ", please notify your system adminitrator" );
            }
            OverallBuildQueue overallBuildQueue = getOverallBuildQueueWhereProjectsInGroupAreQueued( projectGroupId );

            if ( overallBuildQueue == null )
            {
                overallBuildQueue = getOverallBuildQueue( BUILD_QUEUE, buildDef.getSchedule().getBuildQueues() );
            }

            if ( overallBuildQueue != null )
            {
                for ( Project project : projects )
                {
                    try
                    {
                        if ( isInQueue( project.getId(), BUILD_QUEUE, projectsBuildDefinitionsMap.get(
                            project.getId() ).getId() ) )
                        {
                            log.warn( "Project '" + project.getId() + "' - '" + project.getName() +
                                          "' is already in build queue." );
                            continue;
                        }
                        else if ( isProjectInAnyCurrentBuild( project.getId() ) )
                        {
                            log.warn( "Project '" + project.getId() + "' - '" + project.getName() +
                                          "' is already building." );
                            continue;
                        }
                    }
                    catch ( TaskQueueException e )
                    {
                        log.warn( "Error occurred while verifying if project is already queued." );
                        continue;
                    }

                    BuildDefinition buildDefinition = projectsBuildDefinitionsMap.get( project.getId() );
                    String buildDefinitionLabel = buildDefinition.getDescription();
                    if ( StringUtils.isEmpty( buildDefinitionLabel ) )
                    {
                        buildDefinitionLabel = buildDefinition.getGoals();
                    }

                    ScmResult scmResult = scmResultMap.get( project.getId() );
                    BuildProjectTask buildTask = new BuildProjectTask( project.getId(), buildDefinition.getId(),
                                                                       buildTrigger, project.getName(),
                                                                       buildDefinitionLabel, scmResult,
                                                                       projectGroupId );

                    if ( buildDefinition.getSchedule() == null )
                    {
                        log.warn( String.format( "Invalid data, null schedule for builddef id=%s/project id=%s",
                                                 buildDef.getId(), project.getId() ) );
                    }
                    else
                    {
                        buildTask.setMaxExecutionTime( buildDefinition.getSchedule().getMaxJobExecutionTime() * 1000 );
                    }

                    try
                    {
                        log.info( "Project '" + project.getId() + "' - '" + project.getName() +
                                      "' added to overall build queue '" + overallBuildQueue.getName() + "'." );

                        overallBuildQueue.addToBuildQueue( buildTask );
                    }
                    catch ( TaskQueueException e )
                    {
                        throw new BuildManagerException(
                            "Error occurred while adding project to build queue: " + e.getMessage() );
                    }
                }
            }
            else
            {
                log.warn( "No build queue configured. Not building" );
            }
        }
        else
        {
            log.error( "Projects are already in build queue." );
        }
    }

    /**
     * @see BuildsManager#cancelBuildInQueue(int)
     */
    public boolean cancelBuildInQueue( int buildQueueId )
        throws BuildManagerException
    {
        synchronized ( overallBuildQueues )
        {
            OverallBuildQueue overallBuildQueue;
            overallBuildQueue = overallBuildQueues.get( buildQueueId );
            if ( overallBuildQueue != null )
            {
                overallBuildQueue.cancelCurrentBuild();
            }
            else
            {
                log.warn( "Project not found in any of the build queues." );
            }

            return true;
        }
    }

    /**
     * @see BuildsManager#cancelAllBuilds()
     */
    public boolean cancelAllBuilds()
        throws BuildManagerException
    {
        synchronized ( overallBuildQueues )
        {
            Set<Integer> keySet = overallBuildQueues.keySet();
            OverallBuildQueue overallBuildQueue = null;
            for ( Integer key : keySet )
            {
                overallBuildQueue = overallBuildQueues.get( key );
                overallBuildQueue.cancelCurrentBuild();
            }

            return true;
        }
    }

    /**
     * @see BuildsManager#cancelAllCheckouts()
     */
    public boolean cancelAllCheckouts()
        throws BuildManagerException
    {
        synchronized ( overallBuildQueues )
        {
            Set<Integer> keySet = overallBuildQueues.keySet();
            OverallBuildQueue overallBuildQueue;
            for ( Integer key : keySet )
            {
                overallBuildQueue = overallBuildQueues.get( key );
                overallBuildQueue.cancelCurrentCheckout();
            }

            return true;
        }
    }

    /**
     * @see BuildsManager#cancelBuild(int)
     */
    public boolean cancelBuild( int projectId )
        throws BuildManagerException
    {
        try
        {
            OverallBuildQueue overallBuildQueue = getOverallBuildQueueWhereProjectIsQueued( projectId, BUILD_QUEUE );
            if ( overallBuildQueue != null )
            {
                overallBuildQueue.cancelBuildTask( projectId );
            }
            else
            {
                synchronized ( overallBuildQueues )
                {
                    Set<Integer> keySet = overallBuildQueues.keySet();
                    for ( Integer key : keySet )
                    {
                        overallBuildQueue = overallBuildQueues.get( key );
                        BuildProjectTask buildTask =
                            (BuildProjectTask) overallBuildQueue.getBuildTaskQueueExecutor().getCurrentTask();
                        if ( buildTask != null && buildTask.getProjectId() == projectId )
                        {
                            overallBuildQueue.cancelBuildTask( projectId );
                            return true;
                        }
                    }
                    log.error( "Project '" + projectId + "' not found in any of the builds queues." );
                }
            }
        }
        catch ( TaskQueueException e )
        {
            throw new BuildManagerException( "Error occurred while cancelling build: " + e.getMessage() );
        }

        return true;
    }

    /**
     * @see BuildsManager#cancelCheckout(int)
     */
    public boolean cancelCheckout( int projectId )
        throws BuildManagerException
    {
        try
        {
            OverallBuildQueue overallBuildQueue = getOverallBuildQueueWhereProjectIsQueued( projectId, CHECKOUT_QUEUE );
            if ( overallBuildQueue != null )
            {
                overallBuildQueue.cancelCheckoutTask( projectId );
            }
            else
            {
                synchronized ( overallBuildQueues )
                {
                    Set<Integer> keySet = overallBuildQueues.keySet();
                    for ( Integer key : keySet )
                    {
                        overallBuildQueue = overallBuildQueues.get( key );
                        CheckOutTask checkoutTask =
                            (CheckOutTask) overallBuildQueue.getCheckoutTaskQueueExecutor().getCurrentTask();
                        if ( checkoutTask != null && checkoutTask.getProjectId() == projectId )
                        {
                            overallBuildQueue.cancelCheckoutTask( projectId );
                            return true;
                        }
                    }
                    log.info( "Project '" + projectId + "' not found in any of the checkout queues." );
                }
            }
        }
        catch ( TaskQueueException e )
        {
            throw new BuildManagerException( "Error occurred while cancelling build: " + e.getMessage() );
        }

        return true;
    }

    public boolean cancelPrepareBuild( int projectGroupId, int scmRootId )
        throws BuildManagerException
    {
        try
        {
            OverallBuildQueue overallBuildQueue = getOverallBuildQueueWhereProjectGroupIsQueued( projectGroupId,
                                                                                scmRootId );

            if ( overallBuildQueue != null )
            {
                overallBuildQueue.cancelPrepareBuildTask( projectGroupId, scmRootId );
            }
            else
            {
                synchronized ( overallBuildQueues )
                {
                    Set<Integer> keySet = overallBuildQueues.keySet();
                    for ( Integer key : keySet )
                    {
                        overallBuildQueue = overallBuildQueues.get( key );
                        PrepareBuildProjectsTask task =
                            (PrepareBuildProjectsTask) overallBuildQueue.getPrepareBuildTaskQueueExecutor().getCurrentTask();
                        if ( task != null && task.getProjectGroupId() == projectGroupId &&
                            task.getProjectScmRootId() == scmRootId )
                        {
                            overallBuildQueue.cancelPrepareBuildTask( projectGroupId, scmRootId );
                            return true;
                        }
                    }
                    log.error( "Project group '{}' with scm root '{}' not found in any of the builds queues.",
                               projectGroupId, scmRootId );
                }
            }
        }
        catch ( TaskQueueException e )
        {
            throw new BuildManagerException( "Error occurred while cancelling build: " + e.getMessage() );
        }

        return true;
    }

    public boolean cancelPrepareBuild( int projectId )
        throws BuildManagerException
    {
        try
        {
            OverallBuildQueue overallBuildQueue = getOverallBuildQueueWhereProjectIsQueued( projectId,
                                                                                PREPARE_BUILD_QUEUE );

            if ( overallBuildQueue != null )
            {
                overallBuildQueue.cancelPrepareBuildTask( projectId );
            }
            else
            {
                synchronized ( overallBuildQueues )
                {
                    Set<Integer> keySet = overallBuildQueues.keySet();
                    for ( Integer key : keySet )
                    {
                        overallBuildQueue = overallBuildQueues.get( key );
                        PrepareBuildProjectsTask task =
                            (PrepareBuildProjectsTask) overallBuildQueue.getPrepareBuildTaskQueueExecutor().getCurrentTask();
                        if ( task != null )
                        {
                            Map<Integer, Integer> map = task.getProjectsBuildDefinitionsMap();

                            if ( map.size() > 0 )
                            {
                                Set<Integer> projectIds = map.keySet();

                                if ( projectIds.contains( new Integer( projectId ) ) )
                                {
                                    overallBuildQueue.cancelPrepareBuildTask( projectId );
                                    return true;
                                }
                            }
                        }
                    }
                    log.error( "Project '{}' not found in any of the builds queues.", projectId );
                }
            }
        }
        catch ( TaskQueueException e )
        {
            throw new BuildManagerException( "Error occurred while cancelling build: " + e.getMessage() );
        }

        return true;
    }

    /**
     * @see BuildsManager#checkoutProject(int, String, File, String, String, String, BuildDefinition, List)
     */
    public void checkoutProject( int projectId, String projectName, File workingDirectory, String scmRootUrl,
                                 String scmUsername, String scmPassword, BuildDefinition defaultBuildDefinition,
                                 List<Project> subProjects )
        throws BuildManagerException
    {
        try
        {
            if ( isInQueue( projectId, CHECKOUT_QUEUE, -1 ) )
            {
                log.warn( "Project already in checkout queue." );
                return;
            }
        }
        catch ( TaskQueueException e )
        {
            throw new BuildManagerException(
                "Error occurred while checking if the project is already in queue: " + e.getMessage() );
        }

        OverallBuildQueue overallBuildQueue = getOverallBuildQueue( CHECKOUT_QUEUE,
                                                                    defaultBuildDefinition.getSchedule().getBuildQueues() );
        CheckOutTask checkoutTask = new CheckOutTask( projectId, workingDirectory, projectName, scmUsername,
                                                      scmPassword, scmRootUrl, subProjects );
        try
        {
            if ( overallBuildQueue != null )
            {
                log.info( "Project '" + projectName + "' added to overall build queue '" + overallBuildQueue.getName() +
                              "'." );
                overallBuildQueue.addToCheckoutQueue( checkoutTask );
            }
            else
            {
                throw new BuildManagerException(
                    "Unable to add project to checkout queue. No overall build queue configured." );
            }
        }
        catch ( TaskQueueException e )
        {
            throw new BuildManagerException(
                "Error occurred while adding project to checkout queue: " + e.getMessage() );
        }
    }

    /**
     * @see BuildsManager#isInAnyBuildQueue(int)
     */
    public boolean isInAnyBuildQueue( int projectId )
        throws BuildManagerException
    {
        try
        {
            return isInQueue( projectId, BUILD_QUEUE, -1 );
        }
        catch ( TaskQueueException e )
        {
            throw new BuildManagerException( e.getMessage() );
        }
    }

    /**
     * @see BuildsManager#isInAnyBuildQueue(int, int)
     */
    public boolean isInAnyBuildQueue( int projectId, int buildDefinitionId )
        throws BuildManagerException
    {
        try
        {
            return isInQueue( projectId, BUILD_QUEUE, buildDefinitionId );
        }
        catch ( TaskQueueException e )
        {
            throw new BuildManagerException( e.getMessage() );
        }
    }

    /**
     * @see BuildsManager#isInAnyCheckoutQueue(int)
     */
    public boolean isInAnyCheckoutQueue( int projectId )
        throws BuildManagerException
    {
        try
        {
            return isInQueue( projectId, CHECKOUT_QUEUE, -1 );
        }
        catch ( TaskQueueException e )
        {
            throw new BuildManagerException( e.getMessage() );
        }
    }

    /**
     * @see BuildsManager#isAnyProjectCurrentlyBeingCheckedOut(int[])
     */
    public boolean isAnyProjectCurrentlyBeingCheckedOut( int[] projectIds )
        throws BuildManagerException
    {
        for ( int projectId : projectIds )
        {
            Map<String, CheckOutTask> checkouts = getCurrentCheckouts();
            Set<String> keySet = checkouts.keySet();
            for ( String key : keySet )
            {
                CheckOutTask task = checkouts.get( key );
                if ( task.getProjectId() == projectId )
                {
                    log.info( "Project " + projectId + " is currently being checked out" );
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * @see BuildsManager#isInPrepareBuildQueue(int)
     */
    public boolean isInPrepareBuildQueue( int projectId )
        throws BuildManagerException
    {
        try
        {
            synchronized ( overallBuildQueues )
            {
                Set<Integer> keySet = overallBuildQueues.keySet();
                for ( Integer key : keySet )
                {
                    OverallBuildQueue overallBuildQueue = overallBuildQueues.get( key );

                    if ( overallBuildQueue.isInPrepareBuildQueue( projectId ) )
                    {
                        return true;
                    }
                }

                return false;
            }
        }
        catch ( TaskQueueException e )
        {
            throw new BuildManagerException( "Unable to check if projectId " + projectId + " is in prepare build queue",
                                             e );
        }
    }

    /**
     * @param projectGroupId
     * @param scmRootId
     * @return
     * @see BuildsManager#isInPrepareBuildQueue(int, int)
     */
    public boolean isInPrepareBuildQueue( int projectGroupId, int scmRootId )
        throws BuildManagerException
    {
        try
        {
            synchronized ( overallBuildQueues )
            {
                Set<Integer> keySet = overallBuildQueues.keySet();
                for ( Integer key : keySet )
                {
                    OverallBuildQueue overallBuildQueue = overallBuildQueues.get( key );

                    if ( overallBuildQueue.isInPrepareBuildQueue( projectGroupId, scmRootId ) )
                    {
                        return true;
                    }
                }

                return false;
            }
        }
        catch ( TaskQueueException e )
        {
            throw new BuildManagerException(
                "Unable to check if projectGroupId " + projectGroupId + " with scmRootId " + scmRootId +
                    " is in prepare build queue", e );
        }
    }

    /**
     * @see BuildsManager#isProjectInAnyCurrentBuild(int)
     */
    public boolean isProjectInAnyCurrentBuild( int projectId )
        throws BuildManagerException
    {
        synchronized ( overallBuildQueues )
        {
            Set<Integer> keys = overallBuildQueues.keySet();
            for ( Integer key : keys )
            {
                OverallBuildQueue overallBuildQueue = overallBuildQueues.get( key );
                BuildProjectTask task =
                    (BuildProjectTask) overallBuildQueue.getBuildTaskQueueExecutor().getCurrentTask();
                if ( task != null && task.getProjectId() == projectId )
                {
                    log.info( "Project " + projectId + " is currently building in " + overallBuildQueue.getName() );
                    return true;
                }
            }
            return false;
        }
    }

    /**
     * @see BuildsManager#prepareBuildProjects(Map, BuildTrigger, int, String, String, int)
     */
    public void prepareBuildProjects( Map<Integer, Integer> projectsBuildDefinitionsMap, BuildTrigger buildTrigger,
                                      int projectGroupId, String projectGroupName, String scmRootAddress,
                                      int scmRootId )
        throws BuildManagerException
    {
        if ( isInPrepareBuildQueue( projectGroupId, scmRootId ) )
        {
            log.warn(
                "Project group {} with scm root id {} is already in prepare build queue. Will not queue anymore." );
            return;
        }

        Collection<Integer> buildDefs = projectsBuildDefinitionsMap.values();
        BuildDefinition buildDef = null;

        // get the first build definition
        try
        {
            for ( Integer buildDefId : buildDefs )
            {
                buildDef = buildDefinitionDao.getBuildDefinition( buildDefId );
            }
        }
        catch ( ContinuumStoreException e )
        {
            throw new BuildManagerException(
                "Error occurred while retrieving build definition of project group " + projectGroupId, e );
        }

        OverallBuildQueue overallBuildQueue = getOverallBuildQueue( PREPARE_BUILD_QUEUE,
                                                                    buildDef.getSchedule().getBuildQueues() );

        PrepareBuildProjectsTask task = new PrepareBuildProjectsTask( projectsBuildDefinitionsMap, buildTrigger,
                                                                      projectGroupId, projectGroupName, scmRootAddress,
                                                                      scmRootId );

        try
        {
            if ( overallBuildQueue != null )
            {
                log.info( "Project group '{}' added to overall build queue '{}'", projectGroupId,
                          overallBuildQueue.getName() );
                overallBuildQueue.addToPrepareBuildQueue( task );
            }
            else
            {
                throw new BuildManagerException(
                    "Unable to add project to prepare build queue. No overall build queue configured." );
            }
        }
        catch ( TaskQueueException e )
        {
            throw new BuildManagerException(
                "Error occurred while adding project to prepare build queue: " + e.getMessage() );
        }
    }

    /**
     * @see BuildsManager#removeProjectFromBuildQueue(int)
     */
    public void removeProjectFromBuildQueue( int projectId )
        throws BuildManagerException
    {
        try
        {
            OverallBuildQueue overallBuildQueue = getOverallBuildQueueWhereProjectIsQueued( projectId, BUILD_QUEUE );
            if ( overallBuildQueue != null )
            {
                overallBuildQueue.removeProjectFromBuildQueue( projectId );
            }
            else
            {
                log.info( "Project '" + projectId + "' not found in any of the build queues." );
            }
        }
        catch ( TaskQueueException e )
        {
            throw new BuildManagerException(
                "Error occurred while removing project from build queue: " + e.getMessage() );
        }
    }

    /**
     * @see BuildsManager#removeProjectFromBuildQueue(int, int, BuildTrigger, String, int)
     */
    public void removeProjectFromBuildQueue( int projectId, int buildDefinitionId, BuildTrigger buildTrigger,
                                             String projectName, int projectGroupId )
        throws BuildManagerException
    {
        try
        {
            OverallBuildQueue overallBuildQueue = getOverallBuildQueueWhereProjectIsQueued( projectId, BUILD_QUEUE );
            if ( overallBuildQueue != null )
            {
                overallBuildQueue.removeProjectFromBuildQueue( projectId, buildDefinitionId, buildTrigger, projectName,
                                                               projectGroupId );
            }
            else
            {
                log.info( "Project '" + projectId + "' not found in any of the build queues." );
            }
        }
        catch ( TaskQueueException e )
        {
            throw new BuildManagerException(
                "Error occurred while removing project from build queue: " + e.getMessage() );
        }
    }

    /**
     * @see BuildsManager#removeProjectFromCheckoutQueue(int)
     */
    public void removeProjectFromCheckoutQueue( int projectId )
        throws BuildManagerException
    {
        try
        {
            OverallBuildQueue overallBuildQueue = getOverallBuildQueueWhereProjectIsQueued( projectId, CHECKOUT_QUEUE );
            if ( overallBuildQueue != null )
            {
                overallBuildQueue.removeProjectFromCheckoutQueue( projectId );
            }
            else
            {
                log.info( "Project '" + projectId + "' not found in any of the checkout queues." );
            }
        }
        catch ( TaskQueueException e )
        {
            throw new BuildManagerException(
                "Error occurred while removing project from checkout queue: " + e.getMessage() );
        }
    }

    /**
     * @see BuildsManager#removeProjectsFromBuildQueue(int[])
     */
    public void removeProjectsFromBuildQueue( int[] projectIds )
    {
        for ( int projectId : projectIds )
        {
            try
            {
                OverallBuildQueue overallBuildQueue = getOverallBuildQueueWhereProjectIsQueued( projectId,
                                                                                BUILD_QUEUE );
                if ( overallBuildQueue != null )
                {
                    overallBuildQueue.removeProjectFromBuildQueue( projectId );
                }
                else
                {
                    log.error( "Project '" + projectId + "' not found in any of the build queues." );
                }
            }
            catch ( TaskQueueException e )
            {
                log.error( "Error occurred while removing project '" + projectId + "' from build queue." );
            }
        }
    }

    /**
     * @see BuildsManager#removeProjectsFromCheckoutQueue(int[])
     */
    public void removeProjectsFromCheckoutQueue( int[] projectIds )
    {
        for ( int projectId : projectIds )
        {
            try
            {
                OverallBuildQueue overallBuildQueue = getOverallBuildQueueWhereProjectIsQueued( projectId,
                                                                                CHECKOUT_QUEUE );
                if ( overallBuildQueue != null )
                {
                    overallBuildQueue.removeProjectFromCheckoutQueue( projectId );
                }
                else
                {
                    log.error( "Project '" + projectId + "' not found in any of the checkout queues." );
                }
            }
            catch ( TaskQueueException e )
            {
                log.error( "Error occurred while removing project '" + projectId + "' from checkout queue." );
            }
        }
    }

    /**
     * @see BuildsManager#removeProjectsFromCheckoutQueueWithHashcodes(int[])
     */
    public void removeProjectsFromCheckoutQueueWithHashcodes( int[] hashcodes )
        throws BuildManagerException
    {
        try
        {
            synchronized ( overallBuildQueues )
            {
                Set<Integer> keySet = overallBuildQueues.keySet();
                for ( Integer key : keySet )
                {
                    OverallBuildQueue overallBuildQueue = overallBuildQueues.get( key );
                    overallBuildQueue.removeTasksFromCheckoutQueueWithHashCodes( hashcodes );
                }
            }
        }
        catch ( TaskQueueException e )
        {
            throw new BuildManagerException( "Error encountered while removing project(s) from checkout queue.", e );
        }
    }

    /**
     * @see BuildsManager#removeProjectsFromBuildQueueWithHashcodes(int[])
     */
    public void removeProjectsFromBuildQueueWithHashcodes( int[] hashcodes )
        throws BuildManagerException
    {
        try
        {
            synchronized ( overallBuildQueues )
            {
                Set<Integer> keySet = overallBuildQueues.keySet();
                for ( Integer key : keySet )
                {
                    OverallBuildQueue overallBuildQueue = overallBuildQueues.get( key );
                    overallBuildQueue.removeProjectsFromBuildQueueWithHashCodes( hashcodes );
                }
            }
        }
        catch ( TaskQueueException e )
        {
            throw new BuildManagerException( "Error encountered while removing project(s) from build queue.", e );
        }
    }

    public boolean removeProjectGroupFromPrepareBuildQueue( int projectGroupId, String scmRootAddress )
        throws BuildManagerException
    {
        try
        {
            OverallBuildQueue overallBuildQueue = getOverallBuildQueueWhereProjectGroupIsQueued( projectGroupId,
                                                                                scmRootAddress );
            if ( overallBuildQueue != null )
            {
                overallBuildQueue.removeProjectFromPrepareBuildQueue( projectGroupId, scmRootAddress );
            }
            else
            {
                log.info( "Project group '{}' with scm '{}' not found in any of the build queues.", projectGroupId,
                          scmRootAddress );
            }
        }
        catch ( TaskQueueException e )
        {
            throw new BuildManagerException(
                "Error occurred while removing project group from prepare build queue: " + e.getMessage() );
        }

        return true;
    }

    /**
     * @see BuildsManager#addOverallBuildQueue(BuildQueue)
     */
    public void addOverallBuildQueue( BuildQueue buildQueue )
        throws BuildManagerException
    {
        synchronized ( overallBuildQueues )
        {
            try
            {
                OverallBuildQueue overallBuildQueue = (OverallBuildQueue) container.lookup( OverallBuildQueue.class );
                overallBuildQueue.setId( buildQueue.getId() );
                overallBuildQueue.setName( buildQueue.getName() );

                if ( overallBuildQueues.get( buildQueue.getId() ) == null )
                {
                    log.info( "Adding overall build queue to map : " + overallBuildQueue.getName() );
                    overallBuildQueues.put( overallBuildQueue.getId(), overallBuildQueue );
                }
                else
                {
                    log.warn( "Overall build queue already in the map." );
                }
            }
            catch ( ComponentLookupException e )
            {
                throw new BuildManagerException( "Error creating overall build queue.", e );
            }
        }
    }

    /**
     * @see BuildsManager#removeOverallBuildQueue(int)
     */
    public void removeOverallBuildQueue( int overallBuildQueueId )
        throws BuildManagerException
    {
        List<BuildProjectTask> tasks;
        List<CheckOutTask> checkoutTasks;
        List<PrepareBuildProjectsTask> prepareBuildTasks;

        synchronized ( overallBuildQueues )
        {
            OverallBuildQueue overallBuildQueue = overallBuildQueues.get( overallBuildQueueId );
            if ( overallBuildQueue.getName().equals( ConfigurationService.DEFAULT_BUILD_QUEUE_NAME ) )
            {
                throw new BuildManagerException( "Cannot remove default build queue." );
            }

            try
            {
                if ( overallBuildQueue.getBuildTaskQueueExecutor().getCurrentTask() != null ||
                    overallBuildQueue.getCheckoutTaskQueueExecutor().getCurrentTask() != null ||
                    overallBuildQueue.getPrepareBuildTaskQueueExecutor().getCurrentTask() != null )
                {
                    throw new BuildManagerException( "Cannot remove build queue. A task is currently executing." );
                }

                tasks = overallBuildQueue.getProjectsInBuildQueue();
                checkoutTasks = overallBuildQueue.getProjectsInCheckoutQueue();
                prepareBuildTasks = overallBuildQueue.getProjectsInPrepareBuildQueue();

                overallBuildQueue.getBuildQueue().removeAll( tasks );
                overallBuildQueue.getCheckoutQueue().removeAll( checkoutTasks );
                overallBuildQueue.getPrepareBuildQueue().removeAll( prepareBuildTasks );

                ( (ParallelBuildsThreadedTaskQueueExecutor) overallBuildQueue.getBuildTaskQueueExecutor() ).stop();
                ( (ParallelBuildsThreadedTaskQueueExecutor) overallBuildQueue.getCheckoutTaskQueueExecutor() ).stop();
                ( (ParallelBuildsThreadedTaskQueueExecutor) overallBuildQueue.getPrepareBuildTaskQueueExecutor() ).stop();
                container.release( overallBuildQueue );
            }
            catch ( TaskQueueException e )
            {
                throw new BuildManagerException(
                    "Cannot remove build queue. An error occurred while retrieving queued tasks." );
            }
            catch ( ComponentLifecycleException e )
            {
                throw new BuildManagerException(
                    "Cannot remove build queue. An error occurred while destroying the build queue: " +
                        e.getMessage() );
            }
            catch ( StoppingException e )
            {
                throw new BuildManagerException(
                    "Cannot remove build queue. An error occurred while stopping the build queue: " + e.getMessage() );
            }

            this.overallBuildQueues.remove( overallBuildQueueId );
            log.info( "Removed overall build queue '" + overallBuildQueueId + "' from build queues map." );
        }

        for ( BuildProjectTask buildTask : tasks )
        {
            try
            {
                BuildDefinition buildDefinition = buildDefinitionDao.getBuildDefinition(
                    buildTask.getBuildDefinitionId() );

                buildProject( buildTask.getProjectId(), buildDefinition, buildTask.getProjectName(),
                              buildTask.getBuildTrigger(), buildTask.getScmResult(), buildTask.getProjectGroupId() );
            }
            catch ( ContinuumStoreException e )
            {
                log.error( "Unable to queue build task for project '" + buildTask.getProjectName() + "'" );
            }
        }

        for ( CheckOutTask task : checkoutTasks )
        {
            try
            {
                BuildDefinition buildDefinition = buildDefinitionDao.getDefaultBuildDefinition( task.getProjectId() );
                checkoutProject( task.getProjectId(), task.getProjectName(), task.getWorkingDirectory(),
                                 task.getScmRootUrl(), task.getScmUserName(), task.getScmPassword(), buildDefinition,
                                 task.getProjectsWithCommonScmRoot() );
            }
            catch ( ContinuumStoreException e )
            {
                log.error( "Unable to queue checkout task for project '" + task.getProjectName() + "'" );
            }
        }

        for ( PrepareBuildProjectsTask prepareTask : prepareBuildTasks )
        {
            prepareBuildProjects( prepareTask.getProjectsBuildDefinitionsMap(), prepareTask.getBuildTrigger(),
                                  prepareTask.getProjectGroupId(), prepareTask.getProjectGroupName(),
                                  prepareTask.getScmRootAddress(), prepareTask.getProjectScmRootId() );
        }
    }

    public Map<Integer, OverallBuildQueue> getOverallBuildQueues()
    {
        return overallBuildQueues;
    }

    /**
     * @see BuildsManager#getCurrentBuilds()
     */
    public Map<String, BuildProjectTask> getCurrentBuilds()
        throws BuildManagerException
    {
        synchronized ( overallBuildQueues )
        {
            Map<String, BuildProjectTask> currentBuilds = new HashMap<String, BuildProjectTask>();
            Set<Integer> keys = overallBuildQueues.keySet();
            for ( Integer key : keys )
            {
                OverallBuildQueue overallBuildQueue = overallBuildQueues.get( key );
                BuildProjectTask task =
                    (BuildProjectTask) overallBuildQueue.getBuildTaskQueueExecutor().getCurrentTask();
                if ( task != null )
                {
                    currentBuilds.put( overallBuildQueue.getName(), task );
                }
            }
            return currentBuilds;
        }
    }

    /**
     * @see BuildsManager#getCurrentCheckouts()
     */
    public Map<String, CheckOutTask> getCurrentCheckouts()
        throws BuildManagerException
    {
        synchronized ( overallBuildQueues )
        {
            Map<String, CheckOutTask> currentCheckouts = new HashMap<String, CheckOutTask>();
            Set<Integer> keys = overallBuildQueues.keySet();
            for ( Integer key : keys )
            {
                OverallBuildQueue overallBuildQueue = overallBuildQueues.get( key );
                CheckOutTask task = (CheckOutTask) overallBuildQueue.getCheckoutTaskQueueExecutor().getCurrentTask();
                if ( task != null )
                {
                    currentCheckouts.put( overallBuildQueue.getName(), task );
                }
            }
            return currentCheckouts;
        }
    }

    /**
     * @see BuildsManager#getProjectsInBuildQueues()
     */
    public Map<String, List<BuildProjectTask>> getProjectsInBuildQueues()
        throws BuildManagerException
    {
        synchronized ( overallBuildQueues )
        {
            Map<String, List<BuildProjectTask>> queuedBuilds = new HashMap<String, List<BuildProjectTask>>();
            Set<Integer> keySet = overallBuildQueues.keySet();
            for ( Integer key : keySet )
            {
                OverallBuildQueue overallBuildQueue = overallBuildQueues.get( key );
                try
                {
                    queuedBuilds.put( overallBuildQueue.getName(), overallBuildQueue.getProjectsInBuildQueue() );
                }
                catch ( TaskQueueException e )
                {
                    throw new BuildManagerException(
                        "Error occurred while getting projects in build queue '" + overallBuildQueue.getName() + "'.",
                        e );
                }
            }
            return queuedBuilds;
        }
    }

    /**
     * @see BuildsManager#getProjectsInCheckoutQueues()
     */
    public Map<String, List<CheckOutTask>> getProjectsInCheckoutQueues()
        throws BuildManagerException
    {
        synchronized ( overallBuildQueues )
        {
            Map<String, List<CheckOutTask>> queuedCheckouts = new HashMap<String, List<CheckOutTask>>();
            Set<Integer> keySet = overallBuildQueues.keySet();
            for ( Integer key : keySet )
            {
                OverallBuildQueue overallBuildQueue = overallBuildQueues.get( key );
                try
                {
                    queuedCheckouts.put( overallBuildQueue.getName(), overallBuildQueue.getProjectsInCheckoutQueue() );
                }
                catch ( TaskQueueException e )
                {
                    throw new BuildManagerException(
                        "Error occurred while getting projects in build queue '" + overallBuildQueue.getName() + "'.",
                        e );
                }
            }
            return queuedCheckouts;
        }
    }

    /**
     * @see BuildsManager#cancelAllPrepareBuilds()
     */
    public boolean cancelAllPrepareBuilds()
        throws BuildManagerException
    {
        synchronized ( overallBuildQueues )
        {
            Set<Integer> keySet = overallBuildQueues.keySet();
            OverallBuildQueue overallBuildQueue = null;
            for ( Integer key : keySet )
            {
                overallBuildQueue = overallBuildQueues.get( key );
                overallBuildQueue.cancelCurrentPrepareBuild();
            }

            return true;
        }
    }

    /**
     * @see BuildsManager#isBuildInProgress()
     */
    public boolean isBuildInProgress()
    {
        synchronized ( overallBuildQueues )
        {
            Set<Integer> keySet = overallBuildQueues.keySet();
            for ( Integer key : keySet )
            {
                OverallBuildQueue overallBuildQueue = overallBuildQueues.get( key );
                if ( overallBuildQueue.getBuildTaskQueueExecutor().getCurrentTask() != null )
                {
                    return true;
                }
            }
            return false;
        }
    }

    public boolean isProjectCurrentlyPreparingBuild( int projectId )
        throws BuildManagerException
    {
        Map<String, PrepareBuildProjectsTask> tasks = getCurrentProjectInPrepareBuild();

        if ( tasks != null )
        {
            for ( PrepareBuildProjectsTask task : tasks.values() )
            {
                Map<Integer, Integer> map = task.getProjectsBuildDefinitionsMap();

                if ( map.size() > 0 )
                {
                    Set<Integer> projectIds = map.keySet();

                    if ( projectIds.contains( new Integer( projectId ) ) )
                    {
                        log.info( "Project '{}' is currently preparing build", projectId );
                        return true;
                    }
                }
            }
        }

        return false;
    }

    public boolean isProjectGroupCurrentlyPreparingBuild( int projectGroupId, int scmRootId )
        throws BuildManagerException
    {
        Map<String, PrepareBuildProjectsTask> tasks = getCurrentProjectInPrepareBuild();

        if ( tasks != null )
        {
            for ( PrepareBuildProjectsTask task : tasks.values() )
            {
                if ( task != null && task.getProjectGroupId() == projectGroupId &&
                    task.getProjectScmRootId() == scmRootId )
                {
                    log.info( "Project group '{}' with scm root '{}' is currently preparing build", projectGroupId,
                              scmRootId );
                    return true;
                }
            }
        }

        return false;
    }

    public Map<String, PrepareBuildProjectsTask> getCurrentProjectInPrepareBuild()
        throws BuildManagerException
    {
        synchronized ( overallBuildQueues )
        {
            Map<String, PrepareBuildProjectsTask> currentBuilds = new HashMap<String, PrepareBuildProjectsTask>();
            Set<Integer> keys = overallBuildQueues.keySet();
            for ( Integer key : keys )
            {
                OverallBuildQueue overallBuildQueue = overallBuildQueues.get( key );
                PrepareBuildProjectsTask task =
                    (PrepareBuildProjectsTask) overallBuildQueue.getPrepareBuildTaskQueueExecutor().getCurrentTask();
                if ( task != null )
                {
                    currentBuilds.put( overallBuildQueue.getName(), task );
                }
            }
            return currentBuilds;
        }
    }

    public Map<String, List<PrepareBuildProjectsTask>> getProjectsInPrepareBuildQueue()
        throws BuildManagerException
    {
        synchronized ( overallBuildQueues )
        {
            Map<String, List<PrepareBuildProjectsTask>> queuedPrepareBuilds =
                new HashMap<String, List<PrepareBuildProjectsTask>>();
            Set<Integer> keySet = overallBuildQueues.keySet();
            for ( Integer key : keySet )
            {
                OverallBuildQueue overallBuildQueue = overallBuildQueues.get( key );
                try
                {
                    queuedPrepareBuilds.put( overallBuildQueue.getName(),
                                             overallBuildQueue.getProjectsInPrepareBuildQueue() );
                }
                catch ( TaskQueueException e )
                {
                    throw new BuildManagerException(
                        "Error occurred while getting projects in prepare build queue '" + overallBuildQueue.getName() +
                            "'.", e );
                }
            }
            return queuedPrepareBuilds;
        }
    }

    public boolean removeProjectFromPrepareBuildQueue( int projectGroupId, int scmRootId )
        throws BuildManagerException
    {
        try
        {
            OverallBuildQueue overallBuildQueue = getOverallBuildQueueWhereProjectGroupIsQueued( projectGroupId,
                                                                                scmRootId );
            if ( overallBuildQueue != null )
            {
                overallBuildQueue.removeProjectFromPrepareBuildQueue( projectGroupId, scmRootId );
            }
            else
            {
                log.info( "Project group '{}' with scm '{}' not found in any of the build queues.", projectGroupId,
                          scmRootId );
            }
        }
        catch ( TaskQueueException e )
        {
            throw new BuildManagerException(
                "Error occurred while removing project group from prepare build queue: " + e.getMessage() );
        }

        return true;
    }

    public void removeProjectsFromPrepareBuildQueueWithHashCodes( int[] hashCodes )
        throws BuildManagerException
    {
        try
        {
            synchronized ( overallBuildQueues )
            {
                Set<Integer> keySet = overallBuildQueues.keySet();
                for ( Integer key : keySet )
                {
                    OverallBuildQueue overallBuildQueue = overallBuildQueues.get( key );
                    overallBuildQueue.removeProjectsFromPrepareBuildQueueWithHashCodes( hashCodes );
                }
            }
        }
        catch ( TaskQueueException e )
        {
            throw new BuildManagerException( "Error encountered while removing project group(s) from build queue.", e );
        }
    }

    private boolean isInQueue( int projectId, int typeOfQueue, int buildDefinitionId )
        throws TaskQueueException
    {
        synchronized ( overallBuildQueues )
        {
            Set<Integer> keySet = overallBuildQueues.keySet();
            for ( Integer key : keySet )
            {
                OverallBuildQueue overallBuildQueue = overallBuildQueues.get( key );
                if ( typeOfQueue == BUILD_QUEUE )
                {
                    if ( buildDefinitionId < 0 )
                    {
                        if ( overallBuildQueue.isInBuildQueue( projectId ) )
                        {
                            log.info( "Project " + projectId + " is in build queue " + overallBuildQueue.getName() );
                            return true;
                        }
                    }
                    else
                    {
                        if ( overallBuildQueue.isInBuildQueue( projectId, buildDefinitionId ) )
                        {
                            log.info( "Project " + projectId + " is in build queue " + overallBuildQueue.getName() );
                            return true;
                        }
                    }
                }
                else if ( typeOfQueue == CHECKOUT_QUEUE )
                {
                    if ( overallBuildQueue.isInCheckoutQueue( projectId ) )
                    {
                        log.info( "Project " + projectId + " is in checkout queue " + overallBuildQueue.getName() );
                        return true;
                    }
                }
            }

            return false;
        }
    }

    // get overall queue where project is queued
    private OverallBuildQueue getOverallBuildQueueWhereProjectIsQueued( int projectId, int typeOfQueue )
        throws TaskQueueException
    {
        synchronized ( overallBuildQueues )
        {
            OverallBuildQueue whereQueued = null;
            Set<Integer> keySet = overallBuildQueues.keySet();

            for ( Integer key : keySet )
            {
                OverallBuildQueue overallBuildQueue = overallBuildQueues.get( key );
                if ( typeOfQueue == BUILD_QUEUE )
                {
                    if ( overallBuildQueue.isInBuildQueue( projectId ) )
                    {
                        whereQueued = overallBuildQueue;
                        break;
                    }
                }
                else if ( typeOfQueue == CHECKOUT_QUEUE )
                {
                    if ( overallBuildQueue.isInCheckoutQueue( projectId ) )
                    {
                        whereQueued = overallBuildQueue;
                        break;
                    }
                }
                else if ( typeOfQueue == PREPARE_BUILD_QUEUE )
                {
                    if ( overallBuildQueue.isInPrepareBuildQueue( projectId ) )
                    {
                        whereQueued = overallBuildQueue;
                        break;
                    }
                }
            }

            return whereQueued;
        }
    }

    // get overall queue where project will be queued
    private OverallBuildQueue getOverallBuildQueue( int typeOfQueue, List<BuildQueue> buildQueues )
        throws BuildManagerException
    {
        OverallBuildQueue whereToBeQueued = null;
        synchronized ( overallBuildQueues )
        {
            if ( overallBuildQueues == null || overallBuildQueues.isEmpty() )
            {
                throw new BuildManagerException( "No build queues configured." );
            }

            int size = 0;
            int idx = 0;
            int allowedBuilds = configurationService.getNumberOfBuildsInParallel();

            try
            {
                int count = 1;
                for ( BuildQueue buildQueue : buildQueues )
                {
                    if ( count <= allowedBuilds )
                    {
                        OverallBuildQueue overallBuildQueue = overallBuildQueues.get( buildQueue.getId() );
                        if ( overallBuildQueue != null )
                        {
                            TaskQueue taskQueue = null;
                            TaskQueueExecutor taskQueueExecutor = null;
                            int tempSize = 0;
                            if ( typeOfQueue == BUILD_QUEUE )
                            {
                                taskQueue = overallBuildQueue.getBuildQueue();
                                taskQueueExecutor = overallBuildQueue.getBuildTaskQueueExecutor();
                            }
                            else if ( typeOfQueue == CHECKOUT_QUEUE )
                            {
                                taskQueue = overallBuildQueue.getCheckoutQueue();
                                taskQueueExecutor = overallBuildQueue.getCheckoutTaskQueueExecutor();
                            }
                            else if ( typeOfQueue == PREPARE_BUILD_QUEUE )
                            {
                                taskQueue = overallBuildQueue.getPrepareBuildQueue();
                                taskQueueExecutor = overallBuildQueue.getPrepareBuildTaskQueueExecutor();
                            }

                            tempSize = taskQueue.getQueueSnapshot().size();
                            if ( taskQueueExecutor.getCurrentTask() != null )
                            {
                                tempSize++;
                            }

                            if ( idx == 0 )
                            {
                                whereToBeQueued = overallBuildQueue;
                                size = tempSize;
                            }

                            if ( tempSize < size )
                            {
                                whereToBeQueued = overallBuildQueue;
                                size = tempSize;
                            }

                            idx++;
                        }
                        else
                        {
                            log.error( "Build queue not found." );
                        }
                        count++;
                    }
                    else
                    {
                        break;
                    }
                }
            }
            catch ( TaskQueueException e )
            {
                throw new BuildManagerException( "Error occurred while retrieving task quueue: " + e.getMessage() );
            }
        }

        // use default overall build queue if none is configured
        if ( whereToBeQueued == null )
        {
            Set<Integer> keySet = overallBuildQueues.keySet();
            for ( Integer key : keySet )
            {
                OverallBuildQueue overallBuildQueue = overallBuildQueues.get( key );
                if ( overallBuildQueue.getName().equals( ConfigurationService.DEFAULT_BUILD_QUEUE_NAME ) )
                {
                    return overallBuildQueue;
                }
            }
        }

        return whereToBeQueued;
    }

    public OverallBuildQueue getOverallBuildQueueWhereProjectsInGroupAreQueued( int projectGroupId )
        throws BuildManagerException
    {
        OverallBuildQueue whereToBeQueued = null;

        try
        {
            List<Project> projects = projectDao.getProjectsInGroup( projectGroupId );

            if ( projects != null )
            {
                for ( Project project : projects )
                {
                    whereToBeQueued = getOverallBuildQueueWhereProjectIsQueued( project.getId(), BUILD_QUEUE );

                    if ( whereToBeQueued == null )
                    {
                        whereToBeQueued = getOverallBuildQueueWhereProjectIsBuilding( project.getId() );
                    }

                    if ( whereToBeQueued != null )
                    {
                        break;
                    }
                }
            }
        }
        catch ( ContinuumStoreException e )
        {
            throw new BuildManagerException(
                "Error while retrieving overall build queue for project: " + e.getMessage() );
        }
        catch ( TaskQueueException e )
        {
            throw new BuildManagerException(
                "Error while retrieving overall build queue for project: " + e.getMessage() );
        }

        return whereToBeQueued;
    }

    private OverallBuildQueue getOverallBuildQueueWhereProjectGroupIsQueued( int projectGroupId, int scmRootId )
        throws TaskQueueException
    {
        synchronized ( overallBuildQueues )
        {
            OverallBuildQueue whereQueued = null;
            Set<Integer> keySet = overallBuildQueues.keySet();

            for ( Integer key : keySet )
            {
                OverallBuildQueue overallBuildQueue = overallBuildQueues.get( key );

                if ( overallBuildQueue.isInPrepareBuildQueue( projectGroupId, scmRootId ) )
                {
                    whereQueued = overallBuildQueue;
                }
            }

            return whereQueued;
        }
    }

    private OverallBuildQueue getOverallBuildQueueWhereProjectGroupIsQueued( int projectGroupId, String scmRootAddress )
        throws TaskQueueException
    {
        synchronized ( overallBuildQueues )
        {
            OverallBuildQueue whereQueued = null;
            Set<Integer> keySet = overallBuildQueues.keySet();

            for ( Integer key : keySet )
            {
                OverallBuildQueue overallBuildQueue = overallBuildQueues.get( key );

                if ( overallBuildQueue.isInPrepareBuildQueue( projectGroupId, scmRootAddress ) )
                {
                    whereQueued = overallBuildQueue;
                }
            }

            return whereQueued;
        }
    }

    private OverallBuildQueue getOverallBuildQueueWhereProjectIsBuilding( int projectId )
    {
        synchronized ( overallBuildQueues )
        {
            for ( Integer key : overallBuildQueues.keySet() )
            {
                OverallBuildQueue overallBuildQueue = overallBuildQueues.get( key );
                BuildProjectTask task =
                    (BuildProjectTask) overallBuildQueue.getBuildTaskQueueExecutor().getCurrentTask();
                if ( task != null && task.getProjectId() == projectId )
                {
                    return overallBuildQueue;
                }
            }
            return null;
        }
    }

    public boolean isProjectCurrentlyBeingCheckedOut( int projectId )
        throws BuildManagerException
    {
        Map<String, CheckOutTask> checkouts = getCurrentCheckouts();
        for ( String key : checkouts.keySet() )
        {
            CheckOutTask task = checkouts.get( key );
            if ( task.getProjectId() == projectId )
            {
                return true;
            }
        }

        return false;
    }

    public boolean isAnyProjectCurrentlyBuilding( int[] projectIds )
        throws BuildManagerException
    {
        for ( int i = 0; i < projectIds.length; i++ )
        {
            if ( isProjectInAnyCurrentBuild( projectIds[i] ) )
            {
                return true;
            }
        }

        return false;
    }

    public boolean isAnyProjectCurrentlyPreparingBuild( int[] projectIds )
        throws BuildManagerException
    {
        for ( int i = 0; i < projectIds.length; i++ )
        {
            if ( isProjectCurrentlyPreparingBuild( projectIds[i] ) )
            {
                return true;
            }
        }

        return false;
    }

    public void contextualize( Context context )
        throws ContextException
    {
        container = (PlexusContainer) context.get( PlexusConstants.PLEXUS_KEY );

        synchronized ( overallBuildQueues )
        {
            try
            {
                // create all the build queues configured in the database, not just the default!
                List<BuildQueue> buildQueues = buildQueueService.getAllBuildQueues();
                for ( BuildQueue buildQueue : buildQueues )
                {
                    createOverallBuildQueue( buildQueue );
                }

                // add default overall build queue if not yet added to the map
                BuildQueue defaultBuildQueue = configurationService.getDefaultBuildQueue();
                if ( overallBuildQueues.get( defaultBuildQueue.getId() ) == null )
                {
                    createOverallBuildQueue( defaultBuildQueue );
                }
            }
            catch ( ComponentLookupException e )
            {
                log.error( "Cannot create overall build queue: " + e.getMessage() );
            }
            catch ( BuildQueueServiceException e )
            {
                log.error( "Cannot create overall build queue: " + e.getMessage() );
            }
        }
    }

    public void setContainer( PlexusContainer container )
    {
        this.container = container;
    }

    private void createOverallBuildQueue( BuildQueue defaultBuildQueue )
        throws ComponentLookupException
    {
        OverallBuildQueue overallBuildQueue = (OverallBuildQueue) container.lookup( OverallBuildQueue.class );
        overallBuildQueue.setId( defaultBuildQueue.getId() );
        overallBuildQueue.setName( defaultBuildQueue.getName() );

        overallBuildQueues.put( overallBuildQueue.getId(), overallBuildQueue );
    }

    // for unit tests..

    public void setOverallBuildQueues( Map<Integer, OverallBuildQueue> overallBuildQueues )
    {
        this.overallBuildQueues = overallBuildQueues;
    }

    public void setConfigurationService( ConfigurationService configurationService )
    {
        this.configurationService = configurationService;
    }

    public void setBuildQueueService( BuildQueueService buildQueueService )
    {
        this.buildQueueService = buildQueueService;
    }

    public void setBuildDefinitionDao( BuildDefinitionDao buildDefinitionDao )
    {
        this.buildDefinitionDao = buildDefinitionDao;
    }

    public void setProjectDao( ProjectDao projectDao )
    {
        this.projectDao = projectDao;
    }
}


In this episode, Nono talks to Zach Kron (@zachkron)—senior product manager at Autodesk—about how new digital tools allow designers to work (and wether these tools make our lives simpler), and about life habits, boredom, constant connectivity and disconnection, digital clutter, and more.
Listen to this episode on iTunes, Castbox or Stitcher.
Zach describes his daily job as "Banging digital tools with a stick to make them break." Since 2007, Zach has been involved in the research and implementation of software that drives real world building projects and democratizes advanced design practices. Before joining Autodesk—where he is a senior product manager–Zach worked as a designer in several Boston-area architectural offices on projects ranging in scale from furniture to bridges, and has taught at Autodesk, at MIT (Massachusetts Institute of Technology), and ACADIA (Association for Computer Aided Design in Architecture).
You can find Zach on Twitter at @ZachKron and writing at DynamoBIM.org.
Dynamo is an open source visual programming environment for design.
Haiku is a very short form of Japanese poetry.
Bad Monkeys is a group of design technologists spread around the world, working to change the AEC (architecture, engineering, construction) industry "one workflow at a time."
Bread & Puppet Theater is a politically radical puppet theater founded by Peter Schumann, active since 1960s, where bread and theater belong together, currently based in Glover, Vermont.
The Cheap Art Manifesto, Bread and Puppet Glover, Vermont, 1984.
Walter Benjamin was a German Jewish philosopher, cultural critic and essayist.
Shapeways is a 3D printing service and marketplace.
Style transfer is "the technique of recomposing images in the style of other images."
The Resistance is Handmade is a project by Victoria and printed at Albertine Pres by Gather Here.
Designalyze is a podcast (and website) by Brian Ringley (@brianringley) and Zach Downey (@zdowney).
Buildz. Practical notes for making impractical things by Zach, 2009-2015.


text:
Home Otwo Film & TV
A Fading Star System
Dermot O'Rourke
Share the post "A Fading Star System"
As A-list Hollywood stars fail to sell tickets at the box office, Dermot O'Rourke explains why their appeal is waning
Who is your favourite movie star? If your favourite movie star is cast in any movie, does the movie become mandatory viewing? It is these questions Hollywood studios still consider when producing their new movies, however, it appears that this attitude does not reflect the consumption behaviour of modern audiences. In recent times, many of Hollywood's biggest stars have failed to illuminate the box office. Some stars, including Tom Hanks, Tom Cruise and Julia Roberts are among the biggest earners in the film industry yet their movies are failing to generate the revenue that their status or wages command.
Hollywood is currently dependent on stardom to sell movies. The studios employ movie stars not just as actors, but as the representation of the film in the public domain, and are reliant on a star's celebrity status in the promotion and consumption of their films. However, if Hollywood casts a star on their ability to sell a film, a prerequisite for which is a star's exposure to the public, it does prompt the question – in an unprecedented time of celebrity voyeurism, why is it that the most famous cannot seem to appeal to the public?
This system of promoting the star as a mechanism for selling tickets was conceived in the Golden Era of Hollywood (1920s-1950s). At that time, filmmaking operated under the studio system, and each major studio had all personnel, including stars, under long-term contracts. With these contracts, studios had the power to control decisions on the stars' roles, and by sending publicity materials to media outlets about their private lives (designed to complement their on-screen image), they could construct a coherent identity for each star.
In the modern era, Hollywood stars are liberated from restrictive studio contracts and are largely the manufacturer of their own image. In contrast to the professional image seeming to reflect the private life of the stars in the Golden Era, there appears to be a paradox of images for certain movie stars of the modern era. For actors such as John Travolta and Tom Cruise, the public are acutely aware of the distinction between their screen image as charismatic leading men and their involvement in Scientology, which has damaged their appeal – From Paris with Love and Knight and Day having both performed poorly at the box office in 2010. Mel Gibson has seen his public reputation so irreversibly damaged that he is considered toxic in any film, as his role in The Beaver and its subsequent flop proved.
For stars such as Tom Hanks and Julia Roberts of box office failure Larry Crowne there is a more pertinent factor that can limit a movie star's economic power: a rapidly fragmenting entertainment marketplace. Other public figures such as pop stars, reality TV stars and sportsmen have become more influential in the products the public consume. The market has become saturated with people craving public attention, which often dilutes the exposure of the movie star.
The Hollywood studios have recognised their diminishing grip on the front pages of magazines and this is reflected in their confidence in emerging stars to generate the publicity to sell movies. For instance, recent promotional posters for The Green Lantern starring Ryan Reynolds declared: "Hal Jordan is the Green Lantern." This suggested that the studio did not believe Reynolds could sell the movie to a wider audience beyond the fans already familiar with the material. Similarly, for the film Limitless starring Bradley Cooper, Robert de Niro was cast opposite Cooper and was depicted as having a larger role in the promotional material to bolster publicity and appeal for this high concept premise, despite being only introduced in the second act and having very few scenes in the film.
There are stars in the modern era, however, that are anomalies to any concept of stardom as an essential ingredient to the success of a film. Leonardo DiCaprio had relative success before he was propelled into the stratosphere with his starring role in (what was) the most successful film of all time, Titanic. DiCaprio has since had tremendous critical and commercial success with multiple films including Catch Me If You Can, Shutter Island and Inception. However, I do not think that the success of these films has been solely due to DiCaprio's stardom. Although his fame has been a complementary factor, their popularity is a result of collaborations with some of the greatest filmmakers in American cinema.
While the breakdown of the studio system has given stars new independence it has ultimately meant less productions and higher job insecurity. Studios are placing too much weight on the appeal of a star when they are certainly not a pre-condition of profitability at the box office. With an oversupply of actors and a star's status defined by their latest film, there is always a sense of any star being replaceable. Well, except Leonardo DiCaprio.
Previous articleHidden Gem – Print Museum
Next articleAlkaline Energy

redpajama_set_name: RedPajamaCommonCrawl


text:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>structure | Digital Egyptian Gazette</title>
    <link>https://dig-eg-gaz.github.io/tag/structure/</link>
      <atom:link href="https://dig-eg-gaz.github.io/tag/structure/index.xml" rel="self" type="application/rss+xml" />
    <description>structure</description>
    <generator>Wowchemy (https://wowchemy.com)</generator><language>en-us</language><lastBuildDate>Sun, 27 Nov 2016 00:00:00 +0000</lastBuildDate>
    <image>
      <url>https://dig-eg-gaz.github.io/media/icon_hu3ccbb7e8d76090b34f602b231dc00fc8_804790_512x512_fill_lanczos_center_3.png</url>
      <title>structure</title>
      <link>https://dig-eg-gaz.github.io/tag/structure/</link>
    </image>

    <item>
      <title>Egyptian Gazette Structural Issues</title>
      <link>https://dig-eg-gaz.github.io/post/2016-11-27-esteve-egyptiangazettestructuralissues/</link>
      <pubDate>Sun, 27 Nov 2016 00:00:00 +0000</pubDate>
      <guid>https://dig-eg-gaz.github.io/post/2016-11-27-esteve-egyptiangazettestructuralissues/</guid>
      <description>
During my week of the Egyptian Gazette, I have several page sevens that are unlike the other pages. These pages focus on travel and mostly have hotel advertisements. However, they also contain commentary about the best way to travel to different places and the differences in climate between the two. This commentary is split between all six columns of the newspaper. There are some advertisements (see below) that are similar in that they take up two columns. However, I have no idea how to encode these page sevens in order to reflect the structure of the newspaper. Up till now, I have just grouped the commentary in one div. If I encoded the page sevens by columns, I would get six random groups of text. Obviously, this would cause a great deal of confusion unless there was a way to connect the text in each column together. A tag that connects the text together might work, but this issue is definitely one worth exploring as we move forward.

</description>
    </item>

  </channel>
</rss>

redpajama_set_name: RedPajamaGithub


text:
'We can't pinpoint why so many are attending hospital for alcohol related issues' says Doncaster health boss
Doncaster herbalist shop committed to helping out the environment
A Doncaster shop is so committed to reusing and recycling that it only produces one bag of rubbish every fortnight.
By Laura Andrew
Wednesday, 10 July, 2019, 10:03
The herbalist health shop Jackson's has a rich history in Doncaster, where it has been on Printing Office Street for over 80 years.
It was taken over by a young couple 18 months ago both who are passionate about herbalism.
Lydia and Arman in the shop.
Lydia Lakemoore and Arman Mantella, both 26, live a very green lifestyle and bring eco-friendly practice into their shop.
Arman said: "Here at Jackson's we have a big belief in reusing and recycling when we can.
"All the brands that we work with have a big ethical standpoint when it comes to using reused plastics or trying to eradicate plastic from their packaging.
"We do try and look after the planet when we can."
Jackson's shop shelves.
The shop only uses one big bin bag per two weeks at the shop because it tries to recycle as much as possible.
"We also take old bags from our customers and reuse them which means we don't charge anyone to take one of the reused bags with their shopping," Arman continued.
"We encourage customers to bring back their jars and supplement pots and then we recycle them on their behalf.
"We will happily send them back to the manufacturers who will take them back and recycle them."
Everything is recycled – even the bubble wrap goes to their local postman because he sells things on Etsy.
Arman said: "It's your community and a lot of our customers don't want to be creating waste."They will refuse plastic bags and bring back jars.
"Our local honey man will take back glass jars and re-use them.
"He thoroughly cleans them out and sterilises them and brings them back to us when we restock."
Jackson's is an independent health food shop which sells products such as vitamins, herbs, and supplements.
Lydia said: "Herbalism is a way of life that encompasses many rewarding skills such as gardening, harvesting, wildcrafting, medicine making, clinical work and cooking and everything in-between.
"We sell everything you might need to start on a path to herbalism from dried herbs and herbal tea to herbal body care, herbal remedies and more.
"It's not just your ordinary dried lavender and chamomile flowers we've also got gems like damiana and mullein and ashwagandha."
Their herb range has almost doubled since they opened.
In herbal medicine, there are about 200-400 herbs to work with but there are hundreds of thousands of plants out there in the world, meaning there are many uses.
Arman said: "People come to us for all sorts of reasons including wanting to live a natural life, to take control of their diets and add variety."
Both Arman and Lydia come from families with Mediterranean descent, and they say this has influenced their connection to herbs and the way they are used.
Lydia said: "We always had herbs in the kitchen. Grandma's recipes were seen as better than anything else.
"Clove oil was used to cure toothache."
The couple have also ventured into the world of natural soap.
They founded the company Your Organic Soap Co which they run out of a soap-making factory in Thorne and sell their soap in Jackson's and online.
"We wanted to make soaps that would not harm the environment, that could be used outside and that are biodegradable," Lydia said.
"The packaging is biodegradable there is no palm oil and it's organic.
The inspiration for the soap came from the time that the couple spends outside in Yorkshire's rivers and natural spaces.
You can find their shop online at https://theherbalists.co.uk/.


Basmati is a variety of long, slender-grained aromatic rice which is traditionally from the Indian subcontinent. As of 2014, India exported 59 percent of the overseas basmati rice market, while Pakistan accounted for the remainder, according to the state-run Agricultural and Processed Food Products Export Development Authority. However, many countries use domestically grown basmati rice crops.
Any rice other than basmati rice is named as non- basmati rice. In the world it has been reported that there are 10000 varieties of rice and out of which the maximum number are in India.


Casablanca may not rank as high on most people's must-see list but it is where the heart of Morocco lies. The commerical and economic center of the country, it is located in central-western Morocco and boasts the bustling Port of Casablanca, one of the largest artificial ports in the world and the second largest port in North Africa.
A city that sports hallmarks of its past as a French colony and rich Arab culture, its vibrant streets are lined with art deco buildings sitting side-by-side with old stone medina alleyways, European style cafes and an old Portugese style fortress with ramparts that offer a view over the Atlantic Ocean.
Whether you're in Casbalanca for a day or just a few hours, here's a snapshot of what to see and do.
If stepping inside a mosque in Morocco is high on your list of priorities, the iconic Hassan II Mosque is one of the few that welcome non-Muslims on a guided tour (selected timings everyday except Fridays) of this religious building. Constructed in the 1990s, in commeration of the 60th birthday of Morocco's former king, it is the largest mosque in Africa with a minaret of 210 metres, the highest in the world. Decorated with intricate tiles – more than 10,000 m2 of zellige was used – beautiful carvings and an unusual glass floor, allowing worshippers to feel like they're praying directly over the ocean. Said to accommodate up to 25,000 worshippers, the spacious courtyard that's open to all can hold an additional 80,000 people. The promenade that runs alongside the mosque also serves as a prime people watching spot with food vendors, strolling locals and the odd soccer game taking place. Modest dress is expected and bring a pair of socks as you will have to remove all footwear before entering.
Unlike Fez's maze-like medina, Casablanca's medina is a little easier to navigate. Located near the Hassan II Mosque, the entrance through Bab Marrakech on Ave Tahar El Alaoui is where most of the shops are. Less touristy than the medinas in Fez and Marrakech, the shops here offer more day-to-day necessities – knife sharpeners, tailors, fruit stalls, spice sellers – but is rich in its offer of what a day in a life of a Casa local looks like. For Casablanca fans, seek out Rick's Café, a reproduction of the bar complete with a 1930s piano, featured in the Hollywood classic.
Thanks to the French and their grand architectural dreams, the city has a number of buildings that make for more than just a pretty postcard. Navigate to the Cathédrale du Sacré Coeur (Sacre Coeur Cathedral), built in the 1930s by architect Paul Turnon and used as a Christian place of worship till the 1950s. While it's since been abandoned, it's all-white façade is still impressive with its two dome bell chambers and arched entrance and visitors are welcome access the towers for a breathtaking view of the Atlantic Ocean. Equally impressive is the Notre Dame de Lourdes with its elongated structure and high roof. Built in the 1950s with beautiful stained glass, it's an impressive example of modernist architecture.
Set up with the ONA foundation, the Villa des Arts is Casablanca's largest museum which is located inside an elegant 1930s art deco mansion. Situated near the Parc de la Ligue Arabe, it showcases 800 contemporary artworks through the lens of Morocco's culture and heritage with temporary exhibitions by visiting contemporary artists.
This busy beachfront stretch of nightclubs, cafes and restaurants is busiest during the summer where locals hang out and enjoy the balmy summer weather at one of the many pools and beaches. By nightfall, the area is popular as a pre/post dinner promenading spot.


Rudolf G. Wunderlich passed away peacefully on September 22, 2004 in Fountain Valley, California after a long illness. Born in Tarrytown, NY in 1920, Rudy graduated from Hackley School in Tarrytown, and then proceeded into the family art business. As president of Kennedy Galleries, which was founded by his grandfather Hermann Wunderlich in 1874, Rudolf Wunderlich was a leading art dealer in American art for over 50 years.
During the 1950's he transformed Kennedy Galleries from a leading print gallery to the premier dealer in American art. He wrote and published the Kennedy Quarterly, and advised many of the foremost collectors of his day including Thomas Gilcrease, the Hochshield family, Jack Warner, Philip Anschutz, the Rockefeller family, Ross Perot and helped Jacqueline Kennedy as she set up the White House Collection.
He was a leading authority on Western Americana – the art of Frederic Remington, Charles M. Russell and other artists who portrayed the early Western frontier. In this capacity he advised, and appraised virtually every major public and private collection in the field including the Amon Carter Museum, The Cowboy Hall of Fame, The Buffalo Bill Museum, The Sid Richardson Collection, and the R. W. Norton Museum. Other institutions in which he was instrumentally involved included the Adirondack Museum and the New York Historical Society, to name a few. He was best identified with the sculpture of Frederic Remington and became the leading expert on Remington bronzes, sorting out the reproductions and fakes from the original castings.
Thomas Gilcrease with Rudy Wunderlich in the mountains, Summer 1958.
At Kennedy Galleries he established the reputations of Harry Jackson, the western sculptor, and launched the career of John Stobart, the leading marine painter in America. He was also an expert in nineteenth century American prints, twentieth century American fine prints – from Whistler to Hopper, and continued the family tradition of dealing in Old Master prints. He was an original member of the Art Dealers Assoc. of America, one of the inaugural exhibitors at the Winter Antiques Show, and was on the original Art Advisory Panel of the IRS. In 1985, he moved to Chicago and became president of Mongerson-Wunderlich Galleries until his retirement in 1998.
On a more personal level, Rudy Wunderlich was a collector of nineteenth century American stamps, and formed one of the foremost collections of proofs, essays. His collections were exhibited widely, and won numerous prizes, including gold awards at Sipex (1966), Interphil (1976), Capex (1979), Tokyo (1981) and the Grand Award at Aripex (1982). He served on the board of the Philatelic Foundation. His wife, Susan, and his sister Roberta Chamberlain survive him. His children, Gerold, Theodore and John, his stepchildren, Tyler Mongerson, Tina Smith, and Lindsey Jackson, nine grandchildren, and two great grandchildren also survive him.