index
int64
0
0
repo_id
stringlengths
9
205
file_path
stringlengths
31
246
content
stringlengths
1
12.2M
__index_level_0__
int64
0
10k
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/core
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/core/action/UpdateBuildDefinitionFromProjectGroupAction.java
package org.apache.maven.continuum.core.action; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.dao.ProjectGroupDao; import org.apache.maven.continuum.model.project.BuildDefinition; import org.apache.maven.continuum.model.project.ProjectGroup; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import java.util.Map; /** * AddBuildDefinitionToProjectAction: * * @author Jesse McConnell <jmcconnell@apache.org> */ @Component( role = org.codehaus.plexus.action.Action.class, hint = "update-build-definition-from-project-group" ) public class UpdateBuildDefinitionFromProjectGroupAction extends AbstractBuildDefinitionContinuumAction { @Requirement private ProjectGroupDao projectGroupDao; public void execute( Map context ) throws Exception { BuildDefinition buildDefinition = getBuildDefinition( context ); int projectGroupId = getProjectGroupId( context ); ProjectGroup projectGroup = projectGroupDao.getProjectGroupWithBuildDetailsByProjectGroupId( projectGroupId ); resolveDefaultBuildDefinitionsForProjectGroup( buildDefinition, projectGroup ); updateBuildDefinitionInList( projectGroup.getBuildDefinitions(), buildDefinition ); AbstractContinuumAction.setBuildDefinition( context, buildDefinition ); } }
5,100
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/core
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/core/action/AddBuildDefinitionToProjectAction.java
package org.apache.maven.continuum.core.action; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.dao.ProjectDao; import org.apache.maven.continuum.model.project.BuildDefinition; import org.apache.maven.continuum.model.project.BuildDefinitionTemplate; import org.apache.maven.continuum.model.project.Project; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import java.util.List; import java.util.Map; /** * AddBuildDefinitionToProjectAction: * * @author Jesse McConnell <jmcconnell@apache.org> */ @Component( role = org.codehaus.plexus.action.Action.class, hint = "add-build-definition-to-project" ) public class AddBuildDefinitionToProjectAction extends AbstractBuildDefinitionContinuumAction { @Requirement private ProjectDao projectDao; public void execute( Map context ) throws Exception { int projectId = getProjectId( context ); Project project = projectDao.getProjectWithAllDetails( projectId ); BuildDefinitionTemplate buildDefinitionTemplate = getBuildDefinitionTemplate( context ); if ( buildDefinitionTemplate != null ) { for ( BuildDefinition buildDefinition : (List<BuildDefinition>) buildDefinitionTemplate.getBuildDefinitions() ) { resolveDefaultBuildDefinitionsForProject( buildDefinition, project ); project.addBuildDefinition( buildDefinition ); if ( buildDefinition.isDefaultForProject() ) { AbstractContinuumAction.setBuildDefinition( context, buildDefinition ); } } } else { BuildDefinition buildDefinition = getBuildDefinition( context ); resolveDefaultBuildDefinitionsForProject( buildDefinition, project ); project.addBuildDefinition( buildDefinition ); AbstractContinuumAction.setBuildDefinition( context, buildDefinition ); } // Save the project projectDao.updateProject( project ); } }
5,101
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/core
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/core/action/RemoveBuildDefinitionFromProjectAction.java
package org.apache.maven.continuum.core.action; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.dao.ProjectDao; import org.apache.maven.continuum.model.project.BuildDefinition; import org.apache.maven.continuum.model.project.Project; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import java.util.Map; /** * AddBuildDefinitionToProjectAction: * * @author: Jesse McConnell <jmcconnell@apache.org> */ @Component( role = org.codehaus.plexus.action.Action.class, hint = "remove-build-definition-from-project" ) public class RemoveBuildDefinitionFromProjectAction extends AbstractBuildDefinitionContinuumAction { @Requirement private ProjectDao projectDao; public void execute( Map context ) throws Exception { BuildDefinition buildDefinition = getBuildDefinition( context ); int projectId = getProjectId( context ); Project project = projectDao.getProjectWithAllDetails( projectId ); // removing build definition from project doesn't effect anything if it is the default for the proejct, the // default will just change automatically to the default build definition of the project group. project.removeBuildDefinition( buildDefinition ); projectDao.updateProject( project ); } }
5,102
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/core
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/core/action/CleanWorkingDirectoryAction.java
package org.apache.maven.continuum.core.action; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.dao.ProjectDao; import org.apache.continuum.utils.file.FileSystemManager; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.utils.WorkingDirectoryService; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import java.io.File; import java.util.List; import java.util.Map; /** * @author Jesse McConnell <jmcconnell@apache.org> */ @Component( role = org.codehaus.plexus.action.Action.class, hint = "clean-working-directory" ) public class CleanWorkingDirectoryAction extends AbstractContinuumAction { @Requirement private WorkingDirectoryService workingDirectoryService; @Requirement private ProjectDao projectDao; @Requirement FileSystemManager fsManager; public void execute( Map context ) throws Exception { Project project = projectDao.getProject( getProjectId( context ) ); List<Project> projectsWithCommonScmRoot = getListOfProjectsInGroupWithCommonScmRoot( context ); String projectScmRootUrl = getProjectScmRootUrl( context, project.getScmUrl() ); File workingDirectory = workingDirectoryService.getWorkingDirectory( project, projectScmRootUrl, projectsWithCommonScmRoot ); if ( workingDirectory.exists() ) { fsManager.removeDir( workingDirectory ); } } }
5,103
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/core
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/core/action/AbstractBuildDefinitionContinuumAction.java
package org.apache.maven.continuum.core.action; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.dao.BuildDefinitionDao; import org.apache.continuum.dao.ScheduleDao; import org.apache.maven.continuum.ContinuumException; import org.apache.maven.continuum.configuration.ConfigurationService; import org.apache.maven.continuum.model.project.BuildDefinition; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.model.project.ProjectGroup; import org.apache.maven.continuum.model.project.Schedule; import org.apache.maven.continuum.store.ContinuumObjectNotFoundException; import org.apache.maven.continuum.store.ContinuumStoreException; import org.codehaus.plexus.component.annotations.Requirement; import java.util.List; /** * AbstractBuildDefinitionContinuumAction: * * @author Jesse McConnell <jmcconnell@apache.org> */ public abstract class AbstractBuildDefinitionContinuumAction extends AbstractContinuumAction { @Requirement private BuildDefinitionDao buildDefinitionDao; @Requirement private ScheduleDao scheduleDao; protected void resolveDefaultBuildDefinitionsForProject( BuildDefinition buildDefinition, Project project ) throws ContinuumException { try { // if buildDefinition passed in is not default then we are done if ( buildDefinition.isDefaultForProject() ) { BuildDefinition storedDefinition = buildDefinitionDao.getDefaultBuildDefinitionForProject( project.getId() ); if ( storedDefinition != null ) { storedDefinition.setDefaultForProject( false ); buildDefinitionDao.storeBuildDefinition( storedDefinition ); } } } catch ( ContinuumObjectNotFoundException nfe ) { getLogger().debug( getClass().getName() + ": safely ignoring the resetting of old build definition becuase it didn't exist" ); } catch ( ContinuumStoreException cse ) { throw new ContinuumException( "error updating old default build definition", cse ); } } /** * resolves build definition defaults between project groups and projects * <p/> * 1) project groups have default build definitions * 2) if project has default build definition, that overrides project group definition * 3) changing parent default build definition does not effect project if it has a default declared * 4) project groups must have a default build definition * * @param buildDefinition * @param projectGroup * @throws ContinuumException */ protected void resolveDefaultBuildDefinitionsForProjectGroup( BuildDefinition buildDefinition, ProjectGroup projectGroup ) throws ContinuumException { try { List<BuildDefinition> storedDefinitions = buildDefinitionDao.getDefaultBuildDefinitionsForProjectGroup( projectGroup.getId() ); for ( BuildDefinition storedDefinition : storedDefinitions ) { // if buildDefinition passed in is not default then we are done if ( buildDefinition.isDefaultForProject() ) { if ( storedDefinition != null && storedDefinition.getId() != buildDefinition.getId() ) { if ( buildDefinition.getType() != null && buildDefinition.getType().equals( storedDefinition.getType() ) ) { //Required to get build def from store because storedDefinition is readonly BuildDefinition def = buildDefinitionDao.getBuildDefinition( storedDefinition.getId() ); def.setDefaultForProject( false ); buildDefinitionDao.storeBuildDefinition( def ); } } } else { //make sure we are not wacking out default build definition, that would be bad if ( buildDefinition.getId() == storedDefinition.getId() ) { getLogger().info( "processing this build definition would result in no default build definition for project group" ); throw new ContinuumException( "processing this build definition would result in no default build definition for project group" ); } } } } catch ( ContinuumStoreException cse ) { getLogger().info( "error updating old default build definition", cse ); throw new ContinuumException( "error updating old default build definition", cse ); } } /** * attempts to walk through the list of build definitions and upon finding a match update it with the * information in the BuildDefinition object passed in. * * @param buildDefinitions * @param buildDefinition * @throws ContinuumException */ protected void updateBuildDefinitionInList( List<BuildDefinition> buildDefinitions, BuildDefinition buildDefinition ) throws ContinuumException { try { BuildDefinition storedDefinition = null; for ( BuildDefinition bd : buildDefinitions ) { if ( bd.getId() == buildDefinition.getId() ) { storedDefinition = bd; } } if ( storedDefinition != null ) { storedDefinition.setGoals( buildDefinition.getGoals() ); storedDefinition.setArguments( buildDefinition.getArguments() ); storedDefinition.setBuildFile( buildDefinition.getBuildFile() ); storedDefinition.setBuildFresh( buildDefinition.isBuildFresh() ); storedDefinition.setUpdatePolicy( buildDefinition.getUpdatePolicy() ); // special case of this is resolved in the resolveDefaultBuildDefinitionsForProjectGroup method storedDefinition.setDefaultForProject( buildDefinition.isDefaultForProject() ); Schedule schedule; if ( buildDefinition.getSchedule() == null ) { try { schedule = scheduleDao.getScheduleByName( ConfigurationService.DEFAULT_SCHEDULE_NAME ); } catch ( ContinuumStoreException e ) { throw new ContinuumException( "Can't get default schedule.", e ); } } else { schedule = scheduleDao.getSchedule( buildDefinition.getSchedule().getId() ); } storedDefinition.setSchedule( schedule ); storedDefinition.setProfile( buildDefinition.getProfile() ); storedDefinition.setDescription( buildDefinition.getDescription() ); storedDefinition.setType( buildDefinition.getType() ); storedDefinition.setAlwaysBuild( buildDefinition.isAlwaysBuild() ); buildDefinitionDao.storeBuildDefinition( storedDefinition ); } else { throw new ContinuumException( "failed update, build definition didn't exist in project group" ); } } catch ( ContinuumStoreException cse ) { throw new ContinuumException( "error in accessing or storing build definition" ); } } }
5,104
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/core
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/core/action/ExecuteBuilderContinuumAction.java
package org.apache.maven.continuum.core.action; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.dao.BuildResultDao; import org.apache.continuum.dao.ProjectDao; import org.apache.continuum.utils.ContinuumUtils; import org.apache.continuum.utils.build.BuildTrigger; import org.apache.maven.continuum.configuration.ConfigurationService; import org.apache.maven.continuum.execution.ContinuumBuildCancelledException; import org.apache.maven.continuum.execution.ContinuumBuildExecutionResult; import org.apache.maven.continuum.execution.ContinuumBuildExecutor; import org.apache.maven.continuum.execution.manager.BuildExecutorManager; import org.apache.maven.continuum.model.project.BuildDefinition; import org.apache.maven.continuum.model.project.BuildResult; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.model.project.ProjectDependency; import org.apache.maven.continuum.model.scm.ScmResult; import org.apache.maven.continuum.notification.ContinuumNotificationDispatcher; import org.apache.maven.continuum.project.ContinuumProjectState; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import java.io.File; import java.util.Date; import java.util.List; import java.util.Map; /** * @author <a href="mailto:trygvis@inamo.no">Trygve Laugst&oslash;l</a> */ @Component( role = org.codehaus.plexus.action.Action.class, hint = "execute-builder" ) public class ExecuteBuilderContinuumAction extends AbstractContinuumAction { private static final String KEY_CANCELLED = "cancelled"; @Requirement private ConfigurationService configurationService; @Requirement private BuildExecutorManager buildExecutorManager; @Requirement private BuildResultDao buildResultDao; @Requirement private ProjectDao projectDao; @Requirement private ContinuumNotificationDispatcher notifier; public void execute( Map context ) throws Exception { // ---------------------------------------------------------------------- // Get parameters from the context // ---------------------------------------------------------------------- Project project = projectDao.getProject( getProject( context ).getId() ); BuildDefinition buildDefinition = getBuildDefinition( context ); BuildTrigger buildTrigger = getBuildTrigger( context ); ScmResult scmResult = getScmResult( context ); List<ProjectDependency> updatedDependencies = getUpdatedDependencies( context ); ContinuumBuildExecutor buildExecutor = buildExecutorManager.getBuildExecutor( project.getExecutorId() ); // ---------------------------------------------------------------------- // Make the buildResult // ---------------------------------------------------------------------- BuildResult buildResult = new BuildResult(); buildResult.setStartTime( new Date().getTime() ); buildResult.setState( ContinuumProjectState.BUILDING ); buildResult.setTrigger( buildTrigger.getTrigger() ); buildResult.setUsername( buildTrigger.getTriggeredBy() ); buildResult.setScmResult( scmResult ); buildResult.setModifiedDependencies( updatedDependencies ); buildResult.setBuildDefinition( getBuildDefinition( context ) ); // TX START: This should really be done in a single transaction project.setBuildNumber( project.getBuildNumber() + 1 ); buildResult.setBuildNumber( project.getBuildNumber() ); buildResultDao.addBuildResult( project, buildResult ); project.setLatestBuildId( buildResult.getId() ); projectDao.updateProject( project ); // TX STOP AbstractContinuumAction.setBuildId( context, Integer.toString( buildResult.getId() ) ); setCancelled( context, false ); buildResult = buildResultDao.getBuildResult( buildResult.getId() ); String projectScmRootUrl = getProjectScmRootUrl( context, project.getScmUrl() ); List<Project> projectsWithCommonScmRoot = getListOfProjectsInGroupWithCommonScmRoot( context ); try { notifier.runningGoals( project, buildDefinition, buildResult ); File buildOutputFile = configurationService.getBuildOutputFile( buildResult.getId(), project.getId() ); ContinuumBuildExecutionResult result = buildExecutor.build( project, buildDefinition, buildOutputFile, projectsWithCommonScmRoot, projectScmRootUrl ); buildResult.setState( result.getExitCode() == 0 ? ContinuumProjectState.OK : ContinuumProjectState.FAILED ); buildResult.setExitCode( result.getExitCode() ); } catch ( ContinuumBuildCancelledException e ) { getLogger().info( "Cancelled build" ); buildResult.setState( ContinuumProjectState.CANCELLED ); buildResult.setError( String.format( "Build was canceled. It may have been canceled manually or exceeded %s's maximum execution time" + " of %s seconds.", buildDefinition.getSchedule().getName(), buildDefinition.getSchedule().getMaxJobExecutionTime() ) ); setCancelled( context, true ); } catch ( Throwable e ) { getLogger().error( "Error running buildResult", e ); buildResult.setState( ContinuumProjectState.ERROR ); buildResult.setError( ContinuumUtils.throwableToString( e ) ); } finally { project = projectDao.getProject( project.getId() ); buildResult.setEndTime( new Date().getTime() ); if ( buildResult.getState() != ContinuumProjectState.OK && buildResult.getState() != ContinuumProjectState.FAILED && buildResult.getState() != ContinuumProjectState.ERROR && buildResult.getState() != ContinuumProjectState.CANCELLED ) { buildResult.setState( ContinuumProjectState.ERROR ); } // Assumes this build result is the latest for project project.setOldState( project.getState() ); project.setState( buildResult.getState() ); // ---------------------------------------------------------------------- // Copy over the buildResult result // ---------------------------------------------------------------------- buildResultDao.updateBuildResult( buildResult ); buildResult = buildResultDao.getBuildResult( buildResult.getId() ); notifier.goalsCompleted( project, buildDefinition, buildResult ); AbstractContinuumAction.setProject( context, project ); projectDao.updateProject( project ); projectScmRootUrl = getProjectScmRootUrl( context, project.getScmUrl() ); projectsWithCommonScmRoot = getListOfProjectsInGroupWithCommonScmRoot( context ); // ---------------------------------------------------------------------- // Backup test result files // ---------------------------------------------------------------------- //TODO: Move as a plugin buildExecutor.backupTestFiles( project, buildResult.getId(), projectScmRootUrl, projectsWithCommonScmRoot ); } } public static boolean isCancelled( Map<String, Object> context ) { return getBoolean( context, KEY_CANCELLED ); } private static void setCancelled( Map<String, Object> context, boolean cancelled ) { context.put( KEY_CANCELLED, cancelled ); } }
5,105
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/notification/DefaultContinuumNotificationDispatcher.java
package org.apache.maven.continuum.notification; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.dao.ProjectDao; import org.apache.continuum.dao.ProjectGroupDao; import org.apache.continuum.model.project.ProjectScmRoot; import org.apache.maven.continuum.model.project.BuildDefinition; import org.apache.maven.continuum.model.project.BuildResult; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.model.project.ProjectGroup; import org.apache.maven.continuum.model.project.ProjectNotifier; import org.apache.maven.continuum.notification.manager.NotifierManager; import org.apache.maven.continuum.store.ContinuumStoreException; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author <a href="mailto:trygvis@inamo.no">Trygve Laugst&oslash;l</a> */ @Component( role = org.apache.maven.continuum.notification.ContinuumNotificationDispatcher.class, hint = "default" ) public class DefaultContinuumNotificationDispatcher implements ContinuumNotificationDispatcher { private static final Logger log = LoggerFactory.getLogger( DefaultContinuumNotificationDispatcher.class ); @Requirement private NotifierManager notifierManager; @Requirement private ProjectDao projectDao; @Requirement private ProjectGroupDao projectGroupDao; // ---------------------------------------------------------------------- // ContinuumNotificationDispatcher Implementation // ---------------------------------------------------------------------- public void buildStarted( Project project, BuildDefinition buildDefinition ) { sendNotification( MESSAGE_ID_BUILD_STARTED, project, buildDefinition, null ); } public void checkoutStarted( Project project, BuildDefinition buildDefinition ) { sendNotification( MESSAGE_ID_CHECKOUT_STARTED, project, buildDefinition, null ); } public void checkoutComplete( Project project, BuildDefinition buildDefinition ) { sendNotification( MESSAGE_ID_CHECKOUT_COMPLETE, project, buildDefinition, null ); } public void runningGoals( Project project, BuildDefinition buildDefinition, BuildResult buildResult ) { sendNotification( MESSAGE_ID_RUNNING_GOALS, project, buildDefinition, buildResult ); } public void goalsCompleted( Project project, BuildDefinition buildDefinition, BuildResult buildResult ) { sendNotification( MESSAGE_ID_GOALS_COMPLETED, project, buildDefinition, buildResult ); } public void buildComplete( Project project, BuildDefinition buildDefinition, BuildResult buildResult ) { sendNotification( MESSAGE_ID_BUILD_COMPLETE, project, buildDefinition, buildResult ); } public void prepareBuildComplete( ProjectScmRoot projectScmRoot ) { sendNotification( MESSAGE_ID_PREPARE_BUILD_COMPLETE, projectScmRoot ); } // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- private void sendNotification( String messageId, Project project, BuildDefinition buildDefinition, BuildResult buildResult ) { // ---------------------------------------------------------------------- // The objects are reread from the store to make sure they're getting the "final" // state of the objects. Ideally this should be done on a per notifier basis or the // objects should be made read only. // ---------------------------------------------------------------------- try { // TODO: remove re-reading? // Here we need to get all the project details // - builds are used to detect if the state has changed (TODO: maybe previousState field is better) // - notifiers are used to send the notification // - scm results are used to detect if scm failed project = projectDao.getProjectWithAllDetails( project.getId() ); ProjectGroup projectGroup = projectGroupDao.getProjectGroupWithBuildDetailsByProjectGroupId( project.getProjectGroup().getId() ); Map<String, List<ProjectNotifier>> notifiersMap = new HashMap<String, List<ProjectNotifier>>(); getProjectNotifiers( project, notifiersMap ); getProjectGroupNotifiers( projectGroup, notifiersMap ); for ( String notifierType : notifiersMap.keySet() ) { MessageContext context = new MessageContext(); context.setProject( project ); context.setBuildDefinition( buildDefinition ); if ( buildResult != null ) { context.setBuildResult( buildResult ); } List<ProjectNotifier> projectNotiiers = notifiersMap.get( notifierType ); context.setNotifier( projectNotiiers ); sendNotification( messageId, context ); } } catch ( ContinuumStoreException e ) { log.error( "Error while population the notification context.", e ); } } private void sendNotification( String messageId, ProjectScmRoot projectScmRoot ) { try { ProjectGroup group = projectGroupDao.getProjectGroupWithBuildDetailsByProjectGroupId( projectScmRoot.getProjectGroup().getId() ); Map<String, List<ProjectNotifier>> notifiersMap = new HashMap<String, List<ProjectNotifier>>(); getProjectGroupNotifiers( group, notifiersMap ); for ( String notifierType : notifiersMap.keySet() ) { MessageContext context = new MessageContext(); context.setProjectScmRoot( projectScmRoot ); List<ProjectNotifier> projectNotifiers = notifiersMap.get( notifierType ); context.setNotifier( projectNotifiers ); sendNotification( messageId, context ); } } catch ( ContinuumStoreException e ) { log.error( "Error while population the notification context.", e ); } } private void sendNotification( String messageId, MessageContext context ) { String notifierType = context.getNotifiers().get( 0 ).getType(); try { Notifier notifier = notifierManager.getNotifier( notifierType ); notifier.sendMessage( messageId, context ); } catch ( NotificationException e ) { log.error( "Error while trying to use the " + notifierType + " notifier.", e ); } } private void getProjectNotifiers( Project project, Map<String, List<ProjectNotifier>> notifiersMap ) { if ( project.getNotifiers() != null ) { // perform the project level notifications for ( ProjectNotifier notifier : (List<ProjectNotifier>) project.getNotifiers() ) { List<ProjectNotifier> notifiers = notifiersMap.get( notifier.getType() ); if ( notifiers == null ) { notifiers = new ArrayList<ProjectNotifier>(); } if ( !notifier.isEnabled() ) { log.info( notifier.getType() + " notifier (id=" + notifier.getId() + ") is disabled." ); continue; } notifiers.add( notifier ); notifiersMap.put( notifier.getType(), notifiers ); } } } private void getProjectGroupNotifiers( ProjectGroup projectGroup, Map<String, List<ProjectNotifier>> notifiersMap ) { // perform the project group level notifications if ( projectGroup.getNotifiers() != null ) { for ( ProjectNotifier projectNotifier : (List<ProjectNotifier>) projectGroup.getNotifiers() ) { List<ProjectNotifier> projectNotifiers = notifiersMap.get( projectNotifier.getType() ); if ( projectNotifiers == null ) { projectNotifiers = new ArrayList<ProjectNotifier>(); } if ( !projectNotifier.isEnabled() ) { log.info( projectNotifier.getType() + " projectNotifier (id=" + projectNotifier.getId() + ") is disabled." ); continue; } projectNotifiers.add( projectNotifier ); notifiersMap.put( projectNotifier.getType(), projectNotifiers ); } } } }
5,106
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/notification
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/notification/mail/FormatterTool.java
package org.apache.maven.continuum.notification.mail; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.maven.continuum.project.ContinuumProjectState; import java.text.SimpleDateFormat; import java.util.Date; /** * @author <a href="mailto:trygvis@inamo.no">Trygve Laugst&oslash;l</a> */ public class FormatterTool { private final String timestampFormatString; private final ThreadLocal<SimpleDateFormat> timestampFormat = new ThreadLocal<SimpleDateFormat>(); public FormatterTool( String timestampFormatString ) { this.timestampFormatString = timestampFormatString; } // TODO: Add i18n public String formatProjectState( int state ) { if ( state == ContinuumProjectState.NEW || state == ContinuumProjectState.CHECKEDOUT ) { return "New"; } else if ( state == ContinuumProjectState.OK ) { return "Ok"; } else if ( state == ContinuumProjectState.FAILED ) { return "Failed"; } else if ( state == ContinuumProjectState.ERROR ) { return "Error"; } else if ( state == ContinuumProjectState.BUILDING ) { return "Building"; } else { return "Unknown project state '" + state + "'"; } } public String formatTrigger( int trigger ) { if ( trigger == ContinuumProjectState.TRIGGER_SCHEDULED ) { // TODO: fix this return "Schedule"; } else if ( trigger == ContinuumProjectState.TRIGGER_FORCED ) { return "Forced"; } else { return "Unknown build trigger: '" + trigger + "'"; } } public String formatTimestamp( long timestamp ) { if ( timestamp <= 0 ) { return null; } return getSimpleDateFormat( timestampFormat, timestampFormatString ).format( new Date( timestamp ) ); } public String formatInterval( long start, long end ) { long diff = end - start; long interval = diff / 1000L; long hours = interval / 3600L; interval -= hours * 3600; long minutes = interval / 60; interval -= minutes * 60; long seconds = interval; if ( hours > 0 ) { return Long.toString( hours ) + "h " + Long.toString( minutes ) + "m " + Long.toString( seconds ) + "s"; } if ( minutes > 0 ) { return Long.toString( minutes ) + "m " + Long.toString( seconds ) + "s"; } return Long.toString( seconds ) + "s"; } // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- private SimpleDateFormat getSimpleDateFormat( ThreadLocal<SimpleDateFormat> threadLocal, String format ) { SimpleDateFormat dateFormat = threadLocal.get(); if ( dateFormat == null ) { dateFormat = new SimpleDateFormat( format ); threadLocal.set( dateFormat ); } return dateFormat; } public String trim( String str ) { if ( str == null ) { return ""; } return str.trim(); } }
5,107
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/notification
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/notification/mail/MailContinuumNotifier.java
package org.apache.maven.continuum.notification.mail; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.model.project.ProjectScmRoot; import org.apache.maven.continuum.Continuum; import org.apache.maven.continuum.configuration.ConfigurationService; import org.apache.maven.continuum.execution.ExecutorConfigurator; import org.apache.maven.continuum.execution.ant.AntBuildExecutor; import org.apache.maven.continuum.execution.maven.m1.MavenOneBuildExecutor; import org.apache.maven.continuum.execution.maven.m2.MavenTwoBuildExecutor; import org.apache.maven.continuum.installation.InstallationException; import org.apache.maven.continuum.installation.InstallationService; import org.apache.maven.continuum.model.project.BuildDefinition; import org.apache.maven.continuum.model.project.BuildResult; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.model.project.ProjectDeveloper; import org.apache.maven.continuum.model.project.ProjectGroup; import org.apache.maven.continuum.model.project.ProjectNotifier; import org.apache.maven.continuum.model.scm.ChangeSet; import org.apache.maven.continuum.model.scm.ScmResult; import org.apache.maven.continuum.model.system.Installation; import org.apache.maven.continuum.model.system.Profile; import org.apache.maven.continuum.notification.AbstractContinuumNotifier; import org.apache.maven.continuum.notification.ContinuumNotificationDispatcher; import org.apache.maven.continuum.notification.MessageContext; import org.apache.maven.continuum.notification.NotificationException; import org.apache.maven.continuum.project.ContinuumProjectState; import org.apache.maven.continuum.reports.surefire.ReportTestResult; import org.apache.maven.continuum.reports.surefire.ReportTestSuiteGenerator; import org.apache.velocity.VelocityContext; import org.apache.velocity.exception.ResourceNotFoundException; import org.codehaus.plexus.component.annotations.Configuration; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.personality.plexus.lifecycle.phase.Initializable; import org.codehaus.plexus.util.StringUtils; import org.codehaus.plexus.velocity.VelocityComponent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.mail.javamail.JavaMailSender; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; /** * @author <a href="mailto:jason@maven.org">Jason van Zyl</a> */ public class MailContinuumNotifier extends AbstractContinuumNotifier implements Initializable { private static final Logger log = LoggerFactory.getLogger( MailContinuumNotifier.class ); // ---------------------------------------------------------------------- // Requirements // ---------------------------------------------------------------------- @Requirement private VelocityComponent velocity; @Requirement private ConfigurationService configurationService; @Requirement private Continuum continuum; @Requirement private JavaMailSender javaMailSender; @Requirement private ReportTestSuiteGenerator reportTestSuiteGenerator; // ---------------------------------------------------------------------- // Configuration // ---------------------------------------------------------------------- @Configuration( "" ) private String fromMailbox; @Configuration( "" ) private String fromName; @Configuration( "" ) private String toOverride; @Configuration( "" ) private String timestampFormat; @Configuration( "" ) private boolean includeBuildSummary = true; @Configuration( "" ) private boolean includeTestSummary = true; @Configuration( "" ) private boolean includeBuildOutput = false; /** * Customizable mail subject. Use any combination of literal text, project or build attributes. * Examples: * "[continuum] BUILD ${state}: ${project.groupId} ${project.name}" results in "[continuum] BUILD SUCCESSFUL: foo.bar Hello World" * "[continuum] BUILD ${state}: ${project.name} ${project.scmTag}" results in "[continuum] BUILD SUCCESSFUL: Hello World Branch001" * "[continuum] BUILD ${state}: ${project.name} ${build.durationTime}" results in "[continuum] BUILD SUCCESSFUL: Hello World 2 sec" * "[continuum] BUILD ${state}: ${project.name}, Build Def - ${build.buildDefinition.description}" results in "[continuum] BUILD SUCCESSFUL: Hello World, Build Def - Nightly Test Build" */ @Configuration( "" ) private String buildSubjectFormat = "[continuum] BUILD ${state}: ${project.groupId} ${project.name}"; /** * Customizable mail subject */ @Configuration( "" ) private String prepareBuildSubjectFormat = "[continuum] PREPARE BUILD ${state]: ${projectScmRoot.projectGroup.name}"; // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- private String buildHost; private FormatterTool formatterTool; // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- private static final String FALLBACK_FROM_MAILBOX = "continuum@localhost"; // ---------------------------------------------------------------------- // Component Lifecycle // ---------------------------------------------------------------------- public void initialize() { try { InetAddress address = InetAddress.getLocalHost(); buildHost = StringUtils.clean( address.getHostName() ); if ( buildHost == null ) { buildHost = "localhost"; } } catch ( UnknownHostException ex ) { fromName = "Continuum"; } // ---------------------------------------------------------------------- // From mailbox // ---------------------------------------------------------------------- if ( StringUtils.isEmpty( fromMailbox ) ) { log.info( "The from mailbox is not configured, will use the nag email address from the project." ); fromMailbox = null; } else { log.info( "Using '" + fromMailbox + "' as the from mailbox for all emails." ); } if ( StringUtils.isEmpty( fromName ) ) { fromName = "Continuum@" + buildHost; } log.info( "From name: " + fromName ); log.info( "Build host name: " + buildHost ); // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- formatterTool = new FormatterTool( timestampFormat ); } // ---------------------------------------------------------------------- // Notifier Implementation // ---------------------------------------------------------------------- public String getType() { return "mail"; } public void sendMessage( String messageId, MessageContext context ) throws NotificationException { Project project = context.getProject(); List<ProjectNotifier> notifiers = context.getNotifiers(); BuildResult build = context.getBuildResult(); if ( build != null ) { log.error( "br state=" + build.getState() ); } if ( project != null ) { log.error( "project state=" + project.getState() ); } BuildDefinition buildDefinition = context.getBuildDefinition(); ProjectScmRoot projectScmRoot = context.getProjectScmRoot(); boolean isPrepareBuildComplete = messageId.equals( ContinuumNotificationDispatcher.MESSAGE_ID_PREPARE_BUILD_COMPLETE ); if ( projectScmRoot == null && isPrepareBuildComplete ) { return; } // ---------------------------------------------------------------------- // If there wasn't any building done, don't notify // ---------------------------------------------------------------------- if ( build == null && !isPrepareBuildComplete ) { return; } // ---------------------------------------------------------------------- // Generate and send email // ---------------------------------------------------------------------- if ( messageId.equals( ContinuumNotificationDispatcher.MESSAGE_ID_BUILD_COMPLETE ) ) { buildComplete( project, notifiers, build, messageId, context, buildDefinition ); } else if ( isPrepareBuildComplete ) { prepareBuildComplete( projectScmRoot, notifiers, messageId, context ); } } private void buildComplete( Project project, List<ProjectNotifier> notifiers, BuildResult build, String messageId, MessageContext context, BuildDefinition buildDefinition ) throws NotificationException { BuildResult previousBuild = getPreviousBuild( project, buildDefinition, build ); List<ProjectNotifier> notifiersList = new ArrayList<ProjectNotifier>(); for ( ProjectNotifier notifier : notifiers ) { // ---------------------------------------------------------------------- // Check if the mail should be sent at all // ---------------------------------------------------------------------- if ( shouldNotify( build, previousBuild, notifier ) ) { notifiersList.add( notifier ); } } buildComplete( project, notifiersList, build, previousBuild, messageId, context, buildDefinition ); } private void buildComplete( Project project, List<ProjectNotifier> notifiers, BuildResult build, BuildResult previousBuild, String messageId, MessageContext messageContext, BuildDefinition buildDefinition ) throws NotificationException { // ---------------------------------------------------------------------- // Generate the mail contents // ---------------------------------------------------------------------- String packageName = getClass().getPackage().getName().replace( '.', '/' ); String templateName = packageName + "/templates/" + project.getExecutorId() + "/" + messageId + ".vm"; StringWriter writer = new StringWriter(); String content; try { VelocityContext context = new VelocityContext(); context.put( "includeTestSummary", includeTestSummary ); context.put( "includeOutput", includeBuildOutput ); if ( includeBuildOutput ) { context.put( "buildOutput", getBuildOutput( project, build ) ); } if ( includeBuildSummary ) { context.put( "build", build ); ReportTestResult reportTestResult = reportTestSuiteGenerator.generateReportTestResult( build.getId(), project.getId() ); context.put( "testResult", reportTestResult ); context.put( "project", project ); context.put( "changesSinceLastSuccess", continuum.getChangesSinceLastSuccess( project.getId(), build.getId() ) ); context.put( "previousBuild", previousBuild ); // ---------------------------------------------------------------------- // Tools // ---------------------------------------------------------------------- context.put( "formatter", formatterTool ); // TODO: Make the build host a part of the build context.put( "buildHost", buildHost ); String osName = System.getProperty( "os.name" ); String osPatchLevel = System.getProperty( "sun.os.patch.level" ); if ( osPatchLevel != null ) { osName = osName + "(" + osPatchLevel + ")"; } context.put( "osName", osName ); context.put( "javaVersion", System.getProperty( "java.version" ) + "(" + System.getProperty( "java.vendor" ) + ")" ); // TODO only in case of a java project ? context.put( "javaHomeInformations", getJavaHomeInformations( buildDefinition ) ); context.put( "builderVersions", getBuilderVersion( buildDefinition, project ) ); } // ---------------------------------------------------------------------- // Data objects // ---------------------------------------------------------------------- context.put( "reportUrl", getReportUrl( project, build, configurationService ) ); // TODO put other profile env var could be a security if they provide passwords ? // ---------------------------------------------------------------------- // Generate // ---------------------------------------------------------------------- velocity.getEngine().mergeTemplate( templateName, context, writer ); content = writer.getBuffer().toString(); } catch ( ResourceNotFoundException e ) { log.info( "No such template: '" + templateName + "'." ); return; } catch ( Exception e ) { throw new NotificationException( "Error while generating mail contents.", e ); } // ---------------------------------------------------------------------- // Send the mail // ---------------------------------------------------------------------- String subject; try { subject = generateSubject( project, build ); } catch ( Exception e ) { throw new NotificationException( "Error while generating mail subject.", e ); } sendMessage( project, notifiers, subject, content, messageContext ); } private void prepareBuildComplete( ProjectScmRoot projectScmRoot, List<ProjectNotifier> notifiers, String messageId, MessageContext messageContext ) throws NotificationException { // ---------------------------------------------------------------------- // Generate the mail contents // ---------------------------------------------------------------------- String packageName = getClass().getPackage().getName().replace( '.', '/' ); String templateName = packageName + "/templates/" + messageId + ".vm"; StringWriter writer = new StringWriter(); String content; try { VelocityContext context = new VelocityContext(); // ---------------------------------------------------------------------- // Data objects // ---------------------------------------------------------------------- context.put( "reportUrl", getReportUrl( projectScmRoot.getProjectGroup(), projectScmRoot, configurationService ) ); context.put( "projectScmRoot", projectScmRoot ); // TODO put other profile env var could be a security if they provide passwords ? // ---------------------------------------------------------------------- // Generate // ---------------------------------------------------------------------- velocity.getEngine().mergeTemplate( templateName, context, writer ); content = writer.getBuffer().toString(); } catch ( ResourceNotFoundException e ) { log.info( "No such template: '" + templateName + "'." ); return; } catch ( Exception e ) { throw new NotificationException( "Error while generating mail contents.", e ); } // ---------------------------------------------------------------------- // Send the mail // ---------------------------------------------------------------------- String subject; try { subject = generateSubject( projectScmRoot ); } catch ( Exception e ) { throw new NotificationException( "Error while generating mail subject.", e ); } sendMessage( projectScmRoot, notifiers, subject, content, messageContext ); } // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- private List<String> getJavaHomeInformations( BuildDefinition buildDefinition ) throws InstallationException { if ( buildDefinition == null ) { return continuum.getInstallationService().getDefaultJavaVersionInfo(); } Profile profile = buildDefinition.getProfile(); if ( profile == null ) { return continuum.getInstallationService().getDefaultJavaVersionInfo(); } return continuum.getInstallationService().getJavaVersionInfo( profile.getJdk() ); } private List<String> getBuilderVersion( BuildDefinition buildDefinition, Project project ) throws InstallationException { ExecutorConfigurator executorConfigurator; Installation builder = null; Profile profile = null; if ( buildDefinition != null ) { profile = buildDefinition.getProfile(); if ( profile != null ) { builder = profile.getBuilder(); } } if ( builder != null ) { executorConfigurator = continuum.getInstallationService().getExecutorConfigurator( builder.getType() ); } else { // depends on ExecutorId if ( MavenTwoBuildExecutor.ID.equals( project.getExecutorId() ) ) { executorConfigurator = continuum.getInstallationService().getExecutorConfigurator( InstallationService.MAVEN2_TYPE ); } else if ( MavenOneBuildExecutor.ID.equals( project.getExecutorId() ) ) { executorConfigurator = continuum.getInstallationService().getExecutorConfigurator( InstallationService.MAVEN1_TYPE ); } else if ( AntBuildExecutor.ID.equals( project.getExecutorId() ) ) { executorConfigurator = continuum.getInstallationService().getExecutorConfigurator( InstallationService.ANT_TYPE ); } else { return Arrays.asList( "No builder defined" ); } } return continuum.getInstallationService().getExecutorVersionInfo( builder == null ? null : builder.getVarValue(), executorConfigurator, profile ); } private String generateSubject( Project project, BuildResult build ) throws Exception { String state = getState( project, build ); VelocityContext context = new VelocityContext(); context.put( "project", project ); context.put( "build", build ); context.put( "state", state ); StringWriter writer = new StringWriter(); boolean velocityRes = velocity.getEngine().evaluate( context, writer, "subjectPattern", buildSubjectFormat ); return writer.toString(); } private String generateSubject( ProjectScmRoot projectScmRoot ) throws Exception { String state = getState( projectScmRoot ); VelocityContext context = new VelocityContext(); context.put( "projectScmRoot", projectScmRoot ); context.put( "state", state ); StringWriter writer = new StringWriter(); boolean velocityResults = velocity.getEngine().evaluate( context, writer, "subjectPattern", prepareBuildSubjectFormat ); return writer.toString(); } private String getState( Project project, BuildResult build ) { int state = project.getState(); if ( build != null ) { state = build.getState(); } if ( state == ContinuumProjectState.OK ) { return "SUCCESSFUL"; } else if ( state == ContinuumProjectState.FAILED ) { return "FAILURE"; } else if ( state == ContinuumProjectState.ERROR ) { return "ERROR"; } else { log.warn( "Unknown build state " + state + " for project " + project.getId() ); return "ERROR: Unknown build state " + state; } } private String getState( ProjectScmRoot projectScmRoot ) { int state = projectScmRoot.getState(); if ( state == ContinuumProjectState.UPDATED ) { return "SUCCESSFUL"; } else if ( state == ContinuumProjectState.ERROR ) { return "ERROR"; } else { log.warn( "Unknown prepare build state " + state + " for SCM Root URL " + projectScmRoot.getScmRootAddress() + " in projectGroup " + projectScmRoot.getProjectGroup().getId() ); return "ERROR: Unknown build state " + state; } } private void sendMessage( Project project, List<ProjectNotifier> notifiers, String subject, String content, MessageContext context ) throws NotificationException { if ( notifiers.size() == 0 ) { // This is a useful message for the users when debugging why they don't // receive any mails log.info( "No mail notifier for '" + project.getName() + "'." ); return; } String fromMailbox = getFromMailbox( notifiers ); if ( fromMailbox == null ) { log.warn( project.getName() + ": Project is missing nag email and global from mailbox is missing, not sending mail." ); return; } try { MimeMessage message = javaMailSender.createMimeMessage(); message.addHeader( "X-Continuum-Build-Host", buildHost ); message.addHeader( "X-Continuum-Project-Id", Integer.toString( project.getId() ) ); message.addHeader( "X-Continuum-Project-Name", project.getName() ); message.setSubject( subject ); log.info( "Message Subject: '" + subject + "'." ); message.setText( content ); InternetAddress from = new InternetAddress( fromMailbox, fromName ); message.setFrom( from ); log.info( "Sending message: From '" + from + "'." ); if ( StringUtils.isEmpty( toOverride ) ) { Set<String> listRecipents = new HashSet<String>(); for ( ProjectNotifier notifier : notifiers ) { Map<String, String> conf = notifier.getConfiguration(); if ( conf != null ) { String addressField = conf.get( ADDRESS_FIELD ); if ( StringUtils.isNotEmpty( addressField ) ) { String[] addresses = StringUtils.split( addressField, "," ); for ( String address : addresses ) { if ( !listRecipents.contains( address.trim() ) ) { // [CONTINUUM-2281] Dont repeat addesss in recipents. // TODO: set a proper name InternetAddress to = new InternetAddress( address.trim() ); log.info( "Recipient: To '" + to + "'." ); message.addRecipient( Message.RecipientType.TO, to ); listRecipents.add( address.trim() ); } } } if ( context.getBuildResult() != null ) { String committerField = (String) notifier.getConfiguration().get( COMMITTER_FIELD ); String developerField = (String) notifier.getConfiguration().get( DEVELOPER_FIELD ); // Developers constains committers. if ( StringUtils.isNotEmpty( developerField ) && Boolean.parseBoolean( developerField ) ) { List<ProjectDeveloper> developers = project.getDevelopers(); if ( developers == null || developers.isEmpty() ) { log.warn( "No developers have been configured...notifcation email will not be sent" ); return; } Map<String, String> developerToEmailMap = mapDevelopersToRecipients( developers ); for ( String email : developerToEmailMap.values() ) { if ( !listRecipents.contains( email.trim() ) ) { InternetAddress to = new InternetAddress( email.trim() ); log.info( "Recipient: To '" + to + "'." ); message.addRecipient( Message.RecipientType.TO, to ); listRecipents.add( email.trim() ); } } } else if ( StringUtils.isNotEmpty( committerField ) && Boolean.parseBoolean( committerField ) ) { ScmResult scmResult = context.getBuildResult().getScmResult(); if ( scmResult != null && scmResult.getChanges() != null && !scmResult.getChanges().isEmpty() ) { List<ProjectDeveloper> developers = project.getDevelopers(); if ( developers == null || developers.isEmpty() ) { log.warn( "No developers have been configured...notifcation email " + "will not be sent" ); return; } Map<String, String> developerToEmailMap = mapDevelopersToRecipients( developers ); List<ChangeSet> changes = scmResult.getChanges(); for ( ChangeSet changeSet : changes ) { String scmId = changeSet.getAuthor(); if ( StringUtils.isNotEmpty( scmId ) ) { String email = developerToEmailMap.get( scmId ); if ( StringUtils.isEmpty( email ) ) { //TODO: Add a default domain so mail address won't be required log.warn( "no email address is defined in developers list for '" + scmId + "' scm id." ); } else if ( !listRecipents.contains( email.trim() ) ) { // [CONTINUUM-2281] Dont repeat addesss in recipents.) // TODO: set a proper name InternetAddress to = new InternetAddress( email.trim() ); log.info( "Recipient: To '" + to + "'." ); message.addRecipient( Message.RecipientType.TO, to ); listRecipents.add( email.trim() ); } } } } } } } } } else { // TODO: use configuration file instead of to load it fron component configuration // TODO: set a proper name InternetAddress to = new InternetAddress( toOverride.trim() ); log.info( "Recipient: To '" + to + "'." ); message.addRecipient( Message.RecipientType.TO, to ); } message.setSentDate( new Date() ); if ( message.getAllRecipients() != null && ( message.getAllRecipients() ).length > 0 ) { javaMailSender.send( message ); } } catch ( AddressException ex ) { throw new NotificationException( "Exception while sending message.", ex ); } catch ( MessagingException ex ) { throw new NotificationException( "Exception while sending message.", ex ); } catch ( UnsupportedEncodingException ex ) { throw new NotificationException( "Exception while sending message.", ex ); } } private void sendMessage( ProjectScmRoot projectScmRoot, List<ProjectNotifier> notifiers, String subject, String content, MessageContext context ) throws NotificationException { ProjectGroup projectGroup = projectScmRoot.getProjectGroup(); if ( notifiers.size() == 0 ) { // This is a useful message for the users when debugging why they don't // receive any mails log.info( "No mail notifier for '" + projectGroup.getName() + "'." ); return; } String fromMailbox = getFromMailbox( notifiers ); if ( fromMailbox == null ) { log.warn( projectGroup.getName() + ": ProjectGroup is missing nag email and global from mailbox is missing, not sending mail." ); return; } MimeMessage message = javaMailSender.createMimeMessage(); try { message.setSubject( subject ); log.info( "Message Subject: '" + subject + "'." ); message.setText( content ); InternetAddress from = new InternetAddress( fromMailbox, fromName ); message.setFrom( from ); log.info( "Sending message: From '" + from + "'." ); if ( StringUtils.isEmpty( toOverride ) ) { for ( ProjectNotifier notifier : notifiers ) { if ( !shouldNotify( projectScmRoot, notifier ) ) { continue; } Map<String, String> conf = notifier.getConfiguration(); if ( conf != null ) { String addressField = conf.get( ADDRESS_FIELD ); if ( StringUtils.isNotEmpty( addressField ) ) { String[] addresses = StringUtils.split( addressField, "," ); for ( String address : addresses ) { // TODO: set a proper name InternetAddress to = new InternetAddress( address.trim() ); log.info( "Recipient: To '" + to + "'." ); message.addRecipient( Message.RecipientType.TO, to ); } } } } } else { // TODO: use configuration file instead of to load it fron component configuration // TODO: set a proper name InternetAddress to = new InternetAddress( toOverride.trim() ); log.info( "Recipient: To '" + to + "'." ); message.addRecipient( Message.RecipientType.TO, to ); } message.setSentDate( new Date() ); if ( message.getAllRecipients() != null && ( message.getAllRecipients() ).length > 0 ) { javaMailSender.send( message ); } } catch ( AddressException ex ) { throw new NotificationException( "Exception while sending message.", ex ); } catch ( MessagingException ex ) { throw new NotificationException( "Exception while sending message.", ex ); } catch ( UnsupportedEncodingException ex ) { throw new NotificationException( "Exception while sending message.", ex ); } } private Map<String, String> mapDevelopersToRecipients( List<ProjectDeveloper> developers ) { Map<String, String> developersMap = new HashMap<String, String>(); for ( ProjectDeveloper developer : developers ) { if ( StringUtils.isNotEmpty( developer.getScmId() ) && StringUtils.isNotEmpty( developer.getEmail() ) ) { developersMap.put( developer.getScmId(), developer.getEmail() ); } } return developersMap; } private String getFromMailbox( List<ProjectNotifier> notifiers ) { if ( fromMailbox != null ) { return fromMailbox; } String address = null; for ( ProjectNotifier notifier : notifiers ) { Map<String, String> configuration = notifier.getConfiguration(); if ( configuration != null && StringUtils.isNotEmpty( configuration.get( ADDRESS_FIELD ) ) ) { address = configuration.get( ADDRESS_FIELD ); break; } } if ( StringUtils.isEmpty( address ) ) { return FALLBACK_FROM_MAILBOX; } // olamy : CONTINUUM-860 if address contains commas we use only the first one if ( address != null && address.contains( "," ) ) { String[] addresses = StringUtils.split( address, "," ); return addresses[0]; } return address; } public String getBuildHost() { return buildHost; } public void setBuildHost( String buildHost ) { this.buildHost = buildHost; } public String getToOverride() { return toOverride; } public void setToOverride( String toOverride ) { this.toOverride = toOverride; } }
5,108
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/notification
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/notification/manager/DefaultNotifierManager.java
package org.apache.maven.continuum.notification.manager; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.maven.continuum.notification.Notifier; import java.util.Map; /** * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a> */ public class DefaultNotifierManager implements NotifierManager { private Map<String, Notifier> notifiers; public Notifier getNotifier( String notifierId ) { return notifiers.get( notifierId ); } public Map<String, Notifier> getNotifiers() { return notifiers; } public void setNotifiers( Map<String, Notifier> notifiers ) { this.notifiers = notifiers; } }
5,109
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/notification
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/notification/manager/NotifierManager.java
package org.apache.maven.continuum.notification.manager; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.maven.continuum.notification.Notifier; /** * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a> */ public interface NotifierManager { Notifier getNotifier( String notifierId ); }
5,110
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/notification/manager
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/notification/manager/spring/NotifierFactoryBean.java
package org.apache.maven.continuum.notification.manager.spring; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.maven.continuum.notification.Notifier; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactoryUtils; import org.springframework.beans.factory.BeanInitializationException; import org.springframework.beans.factory.FactoryBean; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import java.util.HashMap; import java.util.Map; /** * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a> */ public class NotifierFactoryBean implements FactoryBean, ApplicationContextAware { private static final Logger log = LoggerFactory.getLogger( NotifierFactoryBean.class ); private ApplicationContext applicationContext; public Object getObject() throws Exception { Map<String, Notifier> notifiers = new HashMap<String, Notifier>(); Map<String, Notifier> beans = BeanFactoryUtils.beansOfTypeIncludingAncestors( applicationContext, Notifier.class ); for ( Notifier notifier : beans.values() ) { if ( notifiers.containsKey( notifier.getType() ) ) { throw new BeanInitializationException( "There are two Notifier beans in the appllication context for Notifier type " + notifier.getType() + ". Probably two conflicting scm implementations are present in the classpath." ); } if ( log.isDebugEnabled() ) { log.debug( "put provider with type " + notifier.getType() + " and class " + notifier.getClass().getName() ); } notifiers.put( notifier.getType(), notifier ); } return notifiers; } public Class getObjectType() { return Map.class; } public boolean isSingleton() { return true; } public void setApplicationContext( ApplicationContext applicationContext ) throws BeansException { this.applicationContext = applicationContext; } }
5,111
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/notification
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/notification/console/ConsoleNotifier.java
package org.apache.maven.continuum.notification.console; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.model.project.ProjectScmRoot; import org.apache.maven.continuum.model.project.BuildResult; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.notification.AbstractContinuumNotifier; import org.apache.maven.continuum.notification.ContinuumNotificationDispatcher; import org.apache.maven.continuum.notification.MessageContext; import org.apache.maven.continuum.notification.NotificationException; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.util.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author <a href="mailto:trygvis@inamo.no">Trygve Laugst&oslash;l</a> */ @Component( role = org.apache.maven.continuum.notification.Notifier.class, hint = "console" ) public class ConsoleNotifier extends AbstractContinuumNotifier { private static final Logger log = LoggerFactory.getLogger( ConsoleNotifier.class ); // ---------------------------------------------------------------------- // Notifier Implementation // ---------------------------------------------------------------------- public String getType() { return "console"; } public void sendMessage( String messageId, MessageContext context ) throws NotificationException { Project project = context.getProject(); BuildResult build = context.getBuildResult(); ProjectScmRoot projectScmRoot = context.getProjectScmRoot(); if ( messageId.equals( ContinuumNotificationDispatcher.MESSAGE_ID_BUILD_STARTED ) ) { buildStarted( project ); } else if ( messageId.equals( ContinuumNotificationDispatcher.MESSAGE_ID_CHECKOUT_STARTED ) ) { checkoutStarted( project ); } else if ( messageId.equals( ContinuumNotificationDispatcher.MESSAGE_ID_CHECKOUT_COMPLETE ) ) { checkoutComplete( project ); } else if ( messageId.equals( ContinuumNotificationDispatcher.MESSAGE_ID_RUNNING_GOALS ) ) { runningGoals( project, build ); } else if ( messageId.equals( ContinuumNotificationDispatcher.MESSAGE_ID_GOALS_COMPLETED ) ) { goalsCompleted( project, build ); } else if ( messageId.equals( ContinuumNotificationDispatcher.MESSAGE_ID_BUILD_COMPLETE ) ) { buildComplete( project, build ); } else if ( messageId.equals( ContinuumNotificationDispatcher.MESSAGE_ID_PREPARE_BUILD_COMPLETE ) ) { prepareBuildComplete( projectScmRoot ); } else { log.warn( "Unknown messageId: '" + messageId + "'." ); } } // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- private void buildStarted( Project project ) { out( project, null, "Build started." ); } private void checkoutStarted( Project project ) { out( project, null, "Checkout started." ); } private void checkoutComplete( Project project ) { out( project, null, "Checkout complete." ); } private void runningGoals( Project project, BuildResult build ) { out( project, build, "Running goals." ); } private void goalsCompleted( Project project, BuildResult build ) { if ( build.getError() == null ) { out( project, build, "Goals completed. state: " + build.getState() ); } else { out( project, build, "Goals completed." ); } } private void buildComplete( Project project, BuildResult build ) { if ( build.getError() == null ) { out( project, build, "Build complete. state: " + build.getState() ); } else { out( project, build, "Build complete." ); } } private void prepareBuildComplete( ProjectScmRoot projectScmRoot ) { if ( StringUtils.isEmpty( projectScmRoot.getError() ) ) { out( projectScmRoot, "Prepare build complete. state: " + projectScmRoot.getState() ); } else { out( projectScmRoot, "Prepare build complete." ); } } private void out( Project project, BuildResult build, String msg ) { System.out.println( "Build event for project '" + project.getName() + "':" + msg ); if ( build != null && !StringUtils.isEmpty( build.getError() ) ) { System.out.println( build.getError() ); } } private void out( ProjectScmRoot projectScmRoot, String msg ) { if ( projectScmRoot != null ) { System.out.println( "Prepare build event for '" + projectScmRoot.getScmRootAddress() + "':" + msg ); if ( !StringUtils.isEmpty( projectScmRoot.getError() ) ) { System.out.println( projectScmRoot.getError() ); } } } }
5,112
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/scheduler/ContinuumBuildJob.java
package org.apache.maven.continuum.scheduler; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.maven.continuum.Continuum; import org.apache.maven.continuum.ContinuumException; import org.apache.maven.continuum.model.project.Schedule; import org.codehaus.plexus.scheduler.AbstractJob; import org.quartz.JobDetail; import org.quartz.JobExecutionContext; import org.slf4j.Logger; /** * @author <a href="mailto:jason@maven.org">Jason van Zyl</a> */ public class ContinuumBuildJob extends AbstractJob { public static final String BUILD_GROUP = "BUILD_GROUP"; public void execute( JobExecutionContext context ) { if ( isInterrupted() ) { return; } // ---------------------------------------------------------------------- // Get the job detail // ---------------------------------------------------------------------- JobDetail jobDetail = context.getJobDetail(); // ---------------------------------------------------------------------- // Get data map out of the job detail // ---------------------------------------------------------------------- Logger logger = (Logger) jobDetail.getJobDataMap().get( AbstractJob.LOGGER ); String jobName = jobDetail.getName(); logger.info( ">>>>>>>>>>>>>>>>>>>>> Executing build job (" + jobName + ")..." ); Continuum continuum = (Continuum) jobDetail.getJobDataMap().get( ContinuumSchedulerConstants.CONTINUUM ); Schedule schedule = (Schedule) jobDetail.getJobDataMap().get( ContinuumSchedulerConstants.SCHEDULE ); try { continuum.buildProjects( schedule ); } catch ( ContinuumException e ) { logger.error( "Error building projects for job" + jobName + ".", e ); } try { if ( schedule.getDelay() > 0 ) { Thread.sleep( schedule.getDelay() * 1000 ); } } catch ( InterruptedException e ) { } } }
5,113
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/scheduler/ContinuumPurgeJob.java
package org.apache.maven.continuum.scheduler; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.purge.ContinuumPurgeManager; import org.apache.continuum.purge.ContinuumPurgeManagerException; import org.apache.maven.continuum.Continuum; import org.apache.maven.continuum.model.project.Schedule; import org.codehaus.plexus.scheduler.AbstractJob; import org.quartz.JobDetail; import org.quartz.JobExecutionContext; import org.slf4j.Logger; /** * @author Maria Catherine Tan * @since 25 jul 07 */ public class ContinuumPurgeJob extends AbstractJob { public static final String PURGE_GROUP = "PURGE_GROUP"; public void execute( JobExecutionContext context ) { if ( isInterrupted() ) { return; } // ---------------------------------------------------------------------- // Get the job detail // ---------------------------------------------------------------------- JobDetail jobDetail = context.getJobDetail(); // ---------------------------------------------------------------------- // Get data map out of the job detail // ---------------------------------------------------------------------- Logger logger = (Logger) jobDetail.getJobDataMap().get( AbstractJob.LOGGER ); String jobName = jobDetail.getName(); logger.info( ">>>>>>>>>>>>>>>>>>>>> Executing purge job (" + jobName + ")..." ); Continuum continuum = (Continuum) jobDetail.getJobDataMap().get( ContinuumSchedulerConstants.CONTINUUM ); ContinuumPurgeManager purgeManager = continuum.getPurgeManager(); Schedule schedule = (Schedule) jobDetail.getJobDataMap().get( ContinuumSchedulerConstants.SCHEDULE ); try { purgeManager.purge( schedule ); } catch ( ContinuumPurgeManagerException e ) { logger.error( "Error purging for job" + jobName + ".", e ); } try { if ( schedule.getDelay() > 0 ) { Thread.sleep( schedule.getDelay() * 1000 ); } } catch ( InterruptedException e ) { } } }
5,114
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/scheduler/ContinuumSchedulerConstants.java
package org.apache.maven.continuum.scheduler; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /** * @author <a href="mailto:jason@maven.org">Jason van Zyl</a> */ public class ContinuumSchedulerConstants { // ---------------------------------------------------------------------- // Keys for JobDataMap // ---------------------------------------------------------------------- public static final String CONTINUUM = "continuum"; public static final String SCHEDULE = "schedule"; public static final String BUILD_SETTINGS = "build-settings"; }
5,115
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/initialization/DefaultContinuumInitializer.java
package org.apache.maven.continuum.initialization; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.dao.LocalRepositoryDao; import org.apache.continuum.dao.ProjectGroupDao; import org.apache.continuum.dao.RepositoryPurgeConfigurationDao; import org.apache.continuum.dao.SystemConfigurationDao; import org.apache.continuum.model.repository.LocalRepository; import org.apache.continuum.model.repository.RepositoryPurgeConfiguration; import org.apache.maven.continuum.builddefinition.BuildDefinitionService; import org.apache.maven.continuum.builddefinition.BuildDefinitionServiceException; import org.apache.maven.continuum.model.project.BuildDefinitionTemplate; import org.apache.maven.continuum.model.project.ProjectGroup; import org.apache.maven.continuum.model.system.SystemConfiguration; import org.apache.maven.continuum.store.ContinuumObjectNotFoundException; import org.apache.maven.continuum.store.ContinuumStoreException; import org.apache.maven.settings.MavenSettingsBuilder; import org.apache.maven.settings.Settings; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; import org.jpox.SchemaTool; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.Collection; /** * @author <a href="mailto:jason@maven.org">Jason van Zyl</a> * @todo use this, reintroduce default project group */ @Component( role = org.apache.maven.continuum.initialization.ContinuumInitializer.class, hint = "default" ) public class DefaultContinuumInitializer implements ContinuumInitializer { private static final Logger log = LoggerFactory.getLogger( DefaultContinuumInitializer.class ); // ---------------------------------------------------------------------- // Requirements // ---------------------------------------------------------------------- @Requirement private LocalRepositoryDao localRepositoryDao; @Requirement private RepositoryPurgeConfigurationDao repositoryPurgeConfigurationDao; @Requirement private ProjectGroupDao projectGroupDao; @Requirement private SystemConfigurationDao systemConfigurationDao; @Requirement private BuildDefinitionService buildDefinitionService; @Requirement private MavenSettingsBuilder mavenSettingsBuilder; // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- public void initialize() throws ContinuumInitializationException { log.info( "Continuum initializer running ..." ); if ( log.isDebugEnabled() ) { log.debug( "Dumping JPOX/JDO Schema Details ..." ); try { SchemaTool.outputDBInfo( null, true ); SchemaTool.outputSchemaInfo( null, true ); } catch ( Exception e ) { log.debug( "Error while dumping the database schema", e ); } } try { // System Configuration SystemConfiguration systemConf = systemConfigurationDao.getSystemConfiguration(); if ( systemConf == null ) { systemConf = new SystemConfiguration(); systemConf = systemConfigurationDao.addSystemConfiguration( systemConf ); } createDefaultLocalRepository(); createDefaultProjectGroup(); } catch ( ContinuumStoreException e ) { throw new ContinuumInitializationException( "Can't initialize default schedule.", e ); } catch ( BuildDefinitionServiceException e ) { throw new ContinuumInitializationException( "Can't get default build definition", e ); } log.info( "Continuum initializer end running ..." ); } private void createDefaultProjectGroup() throws ContinuumStoreException, BuildDefinitionServiceException { ProjectGroup group; try { group = projectGroupDao.getProjectGroupByGroupId( DEFAULT_PROJECT_GROUP_GROUP_ID ); log.info( "Default Project Group exists" ); } catch ( ContinuumObjectNotFoundException e ) { Collection<ProjectGroup> pgs = projectGroupDao.getAllProjectGroups(); if ( pgs != null && pgs.isEmpty() ) { log.info( "create Default Project Group" ); group = new ProjectGroup(); group.setName( "Default Project Group" ); group.setGroupId( DEFAULT_PROJECT_GROUP_GROUP_ID ); group.setDescription( "Contains all projects that do not have a group of their own" ); LocalRepository localRepository = localRepositoryDao.getLocalRepositoryByName( "DEFAULT" ); group.setLocalRepository( localRepository ); group = projectGroupDao.addProjectGroup( group ); BuildDefinitionTemplate bdt = buildDefinitionService.getDefaultMavenTwoBuildDefinitionTemplate(); buildDefinitionService.addBuildDefinitionTemplateToProjectGroup( group.getId(), bdt ); } } } private void createDefaultLocalRepository() throws ContinuumStoreException, ContinuumInitializationException { LocalRepository repository; repository = localRepositoryDao.getLocalRepositoryByName( "DEFAULT" ); Settings settings = getSettings(); if ( repository == null ) { log.info( "create Default Local Repository" ); repository = new LocalRepository(); repository.setName( "DEFAULT" ); repository.setLocation( settings.getLocalRepository() ); repository = localRepositoryDao.addLocalRepository( repository ); createDefaultPurgeConfiguration( repository ); } else if ( !repository.getLocation().equals( settings.getLocalRepository() ) ) { log.info( "updating location of Default Local Repository" ); repository.setLocation( settings.getLocalRepository() ); localRepositoryDao.updateLocalRepository( repository ); } } private void createDefaultPurgeConfiguration( LocalRepository repository ) throws ContinuumStoreException { RepositoryPurgeConfiguration repoPurge = new RepositoryPurgeConfiguration(); repoPurge.setRepository( repository ); repoPurge.setDefaultPurge( true ); repositoryPurgeConfigurationDao.addRepositoryPurgeConfiguration( repoPurge ); } private Settings getSettings() throws ContinuumInitializationException { try { return mavenSettingsBuilder.buildSettings( false ); } catch ( IOException e ) { throw new ContinuumInitializationException( "Error reading settings file", e ); } catch ( XmlPullParserException e ) { throw new ContinuumInitializationException( e.getMessage(), e ); } } }
5,116
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/project
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/project/builder/EasyX509TrustManager.java
package org.apache.maven.continuum.project.builder; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509TrustManager; /** * @author olamy * @since 1.2.3 */ public class EasyX509TrustManager implements X509TrustManager { private static final Logger log = LoggerFactory.getLogger( EasyX509TrustManager.class ); private X509TrustManager standardTrustManager = null; /** * Constructor for EasyX509TrustManager. */ public EasyX509TrustManager( KeyStore keystore ) throws NoSuchAlgorithmException, KeyStoreException { super(); TrustManagerFactory factory = TrustManagerFactory.getInstance( TrustManagerFactory.getDefaultAlgorithm() ); factory.init( keystore ); TrustManager[] trustmanagers = factory.getTrustManagers(); if ( trustmanagers.length == 0 ) { throw new NoSuchAlgorithmException( "no trust manager found" ); } this.standardTrustManager = (X509TrustManager) trustmanagers[0]; } /** * @see javax.net.ssl.X509TrustManager#checkClientTrusted(X509Certificate[], String authType) */ public void checkClientTrusted( X509Certificate[] certificates, String authType ) throws CertificateException { standardTrustManager.checkClientTrusted( certificates, authType ); } /** * @see javax.net.ssl.X509TrustManager#checkServerTrusted(X509Certificate[], String authType) */ public void checkServerTrusted( X509Certificate[] certificates, String authType ) throws CertificateException { if ( ( certificates != null ) && log.isDebugEnabled() ) { log.debug( "Server certificate chain:" ); for ( int i = 0; i < certificates.length; i++ ) { log.debug( "X509Certificate[" + i + "]=" + certificates[i] ); } } if ( ( certificates != null ) && ( certificates.length == 1 ) ) { certificates[0].checkValidity(); } else { standardTrustManager.checkServerTrusted( certificates, authType ); } } /** * @see javax.net.ssl.X509TrustManager#getAcceptedIssuers() */ public X509Certificate[] getAcceptedIssuers() { return this.standardTrustManager.getAcceptedIssuers(); } }
5,117
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/project
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/project/builder/AbstractContinuumProjectBuilder.java
package org.apache.maven.continuum.project.builder; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.commons.io.IOUtils; import org.apache.continuum.utils.file.FileSystemManager; import org.apache.http.HttpException; import org.apache.http.HttpHost; import org.apache.http.HttpResponse; import org.apache.http.HttpVersion; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.AuthCache; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.protocol.ClientContext; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.params.ConnManagerPNames; import org.apache.http.conn.params.ConnPerRouteBean; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.impl.auth.BasicScheme; import org.apache.http.impl.client.BasicAuthCache; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpParams; import org.apache.http.params.HttpProtocolParams; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.util.EntityUtils; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.personality.plexus.lifecycle.phase.Initializable; import org.codehaus.plexus.personality.plexus.lifecycle.phase.InitializationException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.UnknownHostException; /** * @author <a href="mailto:trygvis@inamo.no">Trygve Laugst&oslash;l</a> */ public abstract class AbstractContinuumProjectBuilder implements ContinuumProjectBuilder, Initializable { protected final Logger log = LoggerFactory.getLogger( getClass() ); @Requirement protected FileSystemManager fsManager; private HttpParams params; private ClientConnectionManager cm; public void initialize() throws InitializationException { SchemeRegistry schemeRegistry = new SchemeRegistry(); // http scheme schemeRegistry.register( new Scheme( "http", PlainSocketFactory.getSocketFactory(), 80 ) ); // https scheme schemeRegistry.register( new Scheme( "https", new EasySSLSocketFactory(), 443 ) ); params = new BasicHttpParams(); // TODO put this values to a configuration way ??? params.setParameter( ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30 ); params.setParameter( ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean( 30 ) ); HttpProtocolParams.setVersion( params, HttpVersion.HTTP_1_1 ); cm = new ThreadSafeClientConnManager( params, schemeRegistry ); } protected File createMetadataFile( File importRoot, URL metadata, String username, String password, ContinuumProjectBuildingResult result ) throws IOException, URISyntaxException, HttpException { DefaultHttpClient httpClient = new DefaultHttpClient( cm, params ); String url = metadata.toExternalForm(); if ( metadata.getProtocol().startsWith( "http" ) ) { url = hidePasswordInUrl( url ); } log.info( "Downloading " + url ); InputStream is = null; try { if ( metadata.getProtocol().startsWith( "http" ) ) { URI uri = metadata.toURI(); HttpGet httpGet = new HttpGet( uri ); httpClient.getCredentialsProvider().clear(); // basic auth if ( username != null && password != null ) { httpClient.getCredentialsProvider().setCredentials( new AuthScope( uri.getHost(), uri.getPort() ), new UsernamePasswordCredentials( username, password ) ); } // basic auth HttpResponse httpResponse = httpClient.execute( httpGet ); // CONTINUUM-2627 if ( httpResponse.getStatusLine().getStatusCode() != 200 ) { log.debug( "Initial attempt did not return a 200 status code. Trying pre-emptive authentication.." ); HttpHost targetHost = new HttpHost( uri.getHost(), uri.getPort(), uri.getScheme() ); // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); // Generate BASIC scheme object and add it to the local auth cache BasicScheme basicAuth = new BasicScheme(); authCache.put( targetHost, basicAuth ); // Add AuthCache to the execution context BasicHttpContext localcontext = new BasicHttpContext(); localcontext.setAttribute( ClientContext.AUTH_CACHE, authCache ); httpResponse = httpClient.execute( targetHost, httpGet, localcontext ); } int res = httpResponse.getStatusLine().getStatusCode(); switch ( res ) { case 200: break; case 401: log.error( "Error adding project: Unauthorized " + url ); result.addError( ContinuumProjectBuildingResult.ERROR_UNAUTHORIZED ); return null; default: log.warn( "skip non handled http return code " + res ); } is = IOUtils.toInputStream( EntityUtils.toString( httpResponse.getEntity(), EntityUtils.getContentCharSet( httpResponse.getEntity() ) ) ); } else { is = metadata.openStream(); } String path = metadata.getPath(), baseDirectory, fileName; // Split the URL's path into base directory and filename int lastIndex = path.lastIndexOf( "/" ); if ( lastIndex >= 0 ) { baseDirectory = path.substring( 0, lastIndex ); // Required for windows int colonIndex = baseDirectory.indexOf( ":" ); if ( colonIndex >= 0 ) { baseDirectory = baseDirectory.substring( colonIndex + 1 ); } fileName = path.substring( lastIndex + 1 ); } else { baseDirectory = ""; fileName = path; } // Hack for URLs containing '*' like "http://svn.codehaus.org/*checkout*/trunk/pom.xml?root=plexus" baseDirectory = baseDirectory.replaceAll( "[*]", "" ); File uploadDirectory = new File( importRoot, baseDirectory ); // Re-create the directory structure as existed remotely if necessary uploadDirectory.mkdirs(); // Write the metadata file (with the same name, like pom.xml) File file = new File( uploadDirectory, fileName ); fsManager.writeFile( file, is ); return file; } finally { if ( is != null ) { is.close(); } } } private String hidePasswordInUrl( String url ) { int indexAt = url.indexOf( "@" ); if ( indexAt < 0 ) { return url; } String s = url.substring( 0, indexAt ); int pos = s.lastIndexOf( ":" ); return s.substring( 0, pos + 1 ) + "*****" + url.substring( indexAt ); } /** * Create metadata file and handle exceptions, adding the errors to the result object. * * @param result holder with result and errors. * @param metadata * @param username * @param password * @return */ protected File createMetadataFile( File importRoot, ContinuumProjectBuildingResult result, URL metadata, String username, String password ) { String url = metadata.toExternalForm(); if ( metadata.getProtocol().startsWith( "http" ) ) { url = hidePasswordInUrl( url ); } try { return createMetadataFile( importRoot, metadata, username, password, result ); } catch ( FileNotFoundException e ) { log.info( "Metadata creation failed for '{}': {}", url, e.getMessage() ); result.addError( ContinuumProjectBuildingResult.ERROR_POM_NOT_FOUND ); } catch ( MalformedURLException e ) { log.info( "Malformed URL: " + url, e ); result.addError( ContinuumProjectBuildingResult.ERROR_MALFORMED_URL ); } catch ( URISyntaxException e ) { log.info( "Malformed URL: " + url, e ); result.addError( ContinuumProjectBuildingResult.ERROR_MALFORMED_URL ); } catch ( UnknownHostException e ) { log.info( "Unknown host: " + url, e ); result.addError( ContinuumProjectBuildingResult.ERROR_UNKNOWN_HOST ); } catch ( IOException e ) { log.warn( "Could not download the URL: " + url, e ); result.addError( ContinuumProjectBuildingResult.ERROR_UNKNOWN ); } catch ( HttpException e ) { log.warn( "Could not download the URL: " + url, e ); result.addError( ContinuumProjectBuildingResult.ERROR_UNKNOWN ); } return null; } }
5,118
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/project
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/project/builder/EasySSLSocketFactory.java
package org.apache.maven.continuum.project.builder; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.http.conn.ConnectTimeoutException; import org.apache.http.conn.scheme.LayeredSocketFactory; import org.apache.http.conn.scheme.SocketFactory; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; import java.net.UnknownHostException; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocket; import javax.net.ssl.TrustManager; /** * This socket factory will create ssl socket that accepts self signed certificate * * @author olamy * @since 1.2.3 */ public class EasySSLSocketFactory implements SocketFactory, LayeredSocketFactory { private static final Logger log = LoggerFactory.getLogger( EasySSLSocketFactory.class ); private SSLContext sslcontext = null; private static SSLContext createEasySSLContext() throws IOException { try { SSLContext context = SSLContext.getInstance( "SSL" ); context.init( null, new TrustManager[]{new EasyX509TrustManager( null )}, null ); return context; } catch ( Exception e ) { LoggerFactory.getLogger( EasySSLSocketFactory.class ).error( e.getMessage(), e ); throw new IOException( e.getMessage() ); } } private SSLContext getSSLContext() throws IOException { if ( this.sslcontext == null ) { this.sslcontext = createEasySSLContext(); } return this.sslcontext; } /** * @see org.apache.http.conn.scheme.SocketFactory#connectSocket(java.net.Socket, java.lang.String, int, java.net.InetAddress, int, org.apache.http.params.HttpParams) */ public Socket connectSocket( Socket sock, String host, int port, InetAddress localAddress, int localPort, HttpParams params ) throws IOException, UnknownHostException, ConnectTimeoutException { int connTimeout = HttpConnectionParams.getConnectionTimeout( params ); int soTimeout = HttpConnectionParams.getSoTimeout( params ); InetSocketAddress remoteAddress = new InetSocketAddress( host, port ); SSLSocket sslsock = (SSLSocket) ( ( sock != null ) ? sock : createSocket() ); if ( ( localAddress != null ) || ( localPort > 0 ) ) { // we need to bind explicitly if ( localPort < 0 ) { localPort = 0; // indicates "any" } InetSocketAddress isa = new InetSocketAddress( localAddress, localPort ); sslsock.bind( isa ); } sslsock.connect( remoteAddress, connTimeout ); sslsock.setSoTimeout( soTimeout ); return sslsock; } /** * @see org.apache.http.conn.scheme.SocketFactory#createSocket() */ public Socket createSocket() throws IOException { if ( log.isDebugEnabled() ) { log.debug( "create socket" ); } return getSSLContext().getSocketFactory().createSocket(); } /** * @see org.apache.http.conn.scheme.SocketFactory#isSecure(java.net.Socket) */ public boolean isSecure( Socket socket ) throws IllegalArgumentException { return true; } /** * @see org.apache.http.conn.scheme.LayeredSocketFactory#createSocket(java.net.Socket, java.lang.String, int, boolean) */ public Socket createSocket( Socket socket, String host, int port, boolean autoClose ) throws IOException, UnknownHostException { if ( log.isDebugEnabled() ) { log.debug( "create socket host " + host + ", port " + port ); } return getSSLContext().getSocketFactory().createSocket(); } // ------------------------------------------------------------------- // javadoc in org.apache.http.conn.scheme.SocketFactory says : // Both Object.equals() and Object.hashCode() must be overridden // for the correct operation of some connection managers // ------------------------------------------------------------------- public boolean equals( Object obj ) { return ( ( obj != null ) && obj.getClass().equals( EasySSLSocketFactory.class ) ); } public int hashCode() { return EasySSLSocketFactory.class.hashCode(); } }
5,119
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/project/builder
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/project/builder/maven/MavenTwoContinuumProjectBuilder.java
package org.apache.maven.continuum.project.builder.maven; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.dao.LocalRepositoryDao; import org.apache.continuum.dao.ProjectGroupDao; import org.apache.continuum.dao.ScheduleDao; import org.apache.continuum.model.repository.LocalRepository; import org.apache.maven.continuum.builddefinition.BuildDefinitionService; import org.apache.maven.continuum.builddefinition.BuildDefinitionServiceException; import org.apache.maven.continuum.configuration.ConfigurationService; import org.apache.maven.continuum.execution.maven.m2.MavenBuilderHelper; import org.apache.maven.continuum.execution.maven.m2.MavenTwoBuildExecutor; import org.apache.maven.continuum.model.project.BuildDefinition; import org.apache.maven.continuum.model.project.BuildDefinitionTemplate; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.model.project.ProjectGroup; import org.apache.maven.continuum.model.project.Schedule; import org.apache.maven.continuum.project.builder.AbstractContinuumProjectBuilder; import org.apache.maven.continuum.project.builder.ContinuumProjectBuilder; import org.apache.maven.continuum.project.builder.ContinuumProjectBuilderException; import org.apache.maven.continuum.project.builder.ContinuumProjectBuildingResult; import org.apache.maven.continuum.store.ContinuumStoreException; import org.apache.maven.project.MavenProject; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Configuration; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.util.StringUtils; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; /** * @author <a href="mailto:trygvis@inamo.no">Trygve Laugst&oslash;l</a> */ @Component( role = org.apache.maven.continuum.project.builder.ContinuumProjectBuilder.class, hint = "maven-two-builder" ) public class MavenTwoContinuumProjectBuilder extends AbstractContinuumProjectBuilder implements ContinuumProjectBuilder { public static final String ID = "maven-two-builder"; private static final String POM_PART = "/pom.xml"; @Requirement private LocalRepositoryDao localRepositoryDao; @Requirement private MavenBuilderHelper builderHelper; @Requirement private ScheduleDao scheduleDao; @Requirement private BuildDefinitionService buildDefinitionService; @Configuration( "" ) private List<String> excludedPackagingTypes = new ArrayList<String>(); private Project rootProject; @Requirement private ProjectGroupDao projectGroupDao; // ---------------------------------------------------------------------- // AbstractContinuumProjectBuilder Implementation // ---------------------------------------------------------------------- public ContinuumProjectBuildingResult buildProjectsFromMetadata( URL url, String username, String password ) throws ContinuumProjectBuilderException { return buildProjectsFromMetadata( url, username, password, true, false ); } public ContinuumProjectBuildingResult buildProjectsFromMetadata( URL url, String username, String password, boolean loadRecursiveProjects, boolean checkoutInSingleDirectory ) throws ContinuumProjectBuilderException { try { return buildProjectsFromMetadata( url, username, password, loadRecursiveProjects, buildDefinitionService.getDefaultMavenTwoBuildDefinitionTemplate(), checkoutInSingleDirectory ); } catch ( BuildDefinitionServiceException e ) { throw new ContinuumProjectBuilderException( e.getMessage(), e ); } } public ContinuumProjectBuildingResult buildProjectsFromMetadata( URL url, String username, String password, boolean loadRecursiveProjects, BuildDefinitionTemplate buildDefinitionTemplate, boolean checkoutInSingleDirectory ) throws ContinuumProjectBuilderException { return buildProjectsFromMetadata( url, username, password, loadRecursiveProjects, buildDefinitionTemplate, checkoutInSingleDirectory, -1 ); } public ContinuumProjectBuildingResult buildProjectsFromMetadata( URL url, String username, String password, boolean loadRecursiveProjects, BuildDefinitionTemplate buildDefinitionTemplate, boolean checkoutInSingleDirectory, int projectGroupId ) throws ContinuumProjectBuilderException { // ---------------------------------------------------------------------- // We need to roll the project data into a file so that we can use it // ---------------------------------------------------------------------- ContinuumProjectBuildingResult result = new ContinuumProjectBuildingResult(); try { ProjectGroup projectGroup = null; if ( projectGroupId > 0 ) { projectGroup = projectGroupDao.getProjectGroupWithBuildDetailsByProjectGroupId( projectGroupId ); } importProject( url, result, projectGroup, username, password, null, loadRecursiveProjects, buildDefinitionTemplate, checkoutInSingleDirectory ); } catch ( BuildDefinitionServiceException e ) { throw new ContinuumProjectBuilderException( e.getMessage(), e ); } catch ( ContinuumStoreException e ) { throw new ContinuumProjectBuilderException( e.getMessage(), e ); } return result; } // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- private void importProject( URL url, ContinuumProjectBuildingResult result, ProjectGroup projectGroup, String username, String password, String scmUrl, boolean loadRecursiveProjects, BuildDefinitionTemplate buildDefinitionTemplate, boolean checkoutInSingleDirectory ) throws ContinuumProjectBuilderException, BuildDefinitionServiceException { File importRoot = fsManager.createTempFile( "continuum-m2import-", "", fsManager.getTempDir() ); if ( !importRoot.mkdirs() ) { throw new ContinuumProjectBuilderException( "failed to create directory for import: " + importRoot ); } try { importProjects( importRoot, url, result, projectGroup, username, password, scmUrl, loadRecursiveProjects, buildDefinitionTemplate, checkoutInSingleDirectory ); } finally { if ( importRoot.exists() ) { try { fsManager.removeDir( importRoot ); } catch ( IOException e ) { log.warn( "failed to remove {} after project import: {}", importRoot, e.getMessage() ); } } } } private void importProjects( File importRoot, URL url, ContinuumProjectBuildingResult result, ProjectGroup projectGroup, String username, String password, String scmUrl, boolean loadRecursiveProjects, BuildDefinitionTemplate buildDefinitionTemplate, boolean checkoutInSingleDirectory ) throws ContinuumProjectBuilderException, BuildDefinitionServiceException { File pomFile = createMetadataFile( importRoot, result, url, username, password ); if ( result.hasErrors() ) { return; } MavenProject mavenProject = builderHelper.getMavenProject( result, pomFile ); if ( result.hasErrors() ) { return; } log.debug( "projectGroup " + projectGroup ); if ( projectGroup == null ) { projectGroup = buildProjectGroup( mavenProject, result ); // project groups have the top lvl build definition which is the default build defintion for the sub // projects log.debug( "projectGroup != null" + ( projectGroup != null ) ); if ( projectGroup != null ) { List<BuildDefinition> buildDefinitions = getBuildDefinitions( buildDefinitionTemplate, loadRecursiveProjects, mavenProject.getBuild().getDefaultGoal() ); for ( BuildDefinition buildDefinition : buildDefinitions ) { buildDefinition = persistBuildDefinition( buildDefinition ); projectGroup.addBuildDefinition( buildDefinition ); } } } if ( result.getProjectGroups().isEmpty() ) { result.addProjectGroup( projectGroup ); } if ( !excludedPackagingTypes.contains( mavenProject.getPackaging() ) ) { Project continuumProject = new Project(); /* We are interested in having the scm username and password being passed into this method be taken into account during project mapping so make sure we set it to the continuum project instance. */ if ( username != null && StringUtils.isNotEmpty( username ) ) { continuumProject.setScmUsername( username ); if ( password != null && StringUtils.isNotEmpty( password ) ) { continuumProject.setScmPassword( password ); } } continuumProject.setCheckedOutInSingleDirectory( checkoutInSingleDirectory ); // New project builderHelper.mapMavenProjectToContinuumProject( result, mavenProject, continuumProject, true ); if ( result.hasErrors() ) { log.info( "Error adding project: Unknown error mapping project " + url + ": " + result.getErrorsAsString() ); return; } // Rewrite scmurl from the one found in added project due to a bug in scm url resolution // for projects that doesn't have module name != artifactId if ( StringUtils.isNotEmpty( scmUrl ) ) { continuumProject.setScmUrl( scmUrl ); } else { scmUrl = continuumProject.getScmUrl(); } if ( !"HEAD".equals( mavenProject.getScm().getTag() ) ) { continuumProject.setScmTag( mavenProject.getScm().getTag() ); } // CONTINUUM-2563 // Don't create if the project has a build definition template assigned to it already if ( !loadRecursiveProjects && buildDefinitionTemplate.equals( getDefaultBuildDefinitionTemplate() ) ) { List<BuildDefinition> buildDefinitions = projectGroup.getBuildDefinitions(); for ( BuildDefinition buildDefinition : buildDefinitions ) { if ( buildDefinition.isDefaultForProject() ) { // create a default build definition at the project level BuildDefinition projectBuildDef = buildDefinitionService.cloneBuildDefinition( buildDefinition ); projectBuildDef.setDefaultForProject( true ); String arguments = projectBuildDef.getArguments().replace( "--non-recursive", "" ); arguments = arguments.replace( "-N", "" ); arguments = arguments.trim(); // add build definition only if it differs if ( !projectBuildDef.getArguments().equals( arguments ) ) { log.info( "Adding default build definition for project '" + continuumProject.getName() + "' without '--non-recursive' flag." ); projectBuildDef.setArguments( arguments ); continuumProject.addBuildDefinition( projectBuildDef ); } break; } } } result.addProject( continuumProject, MavenTwoBuildExecutor.ID ); if ( checkoutInSingleDirectory && rootProject == null ) { rootProject = continuumProject; result.setRootProject( rootProject ); } } List<String> modules = mavenProject.getModules(); String prefix = url.toExternalForm(); String suffix = ""; int i = prefix.indexOf( '?' ); int lastSlash; if ( i != -1 ) { suffix = prefix.substring( i ); lastSlash = prefix.lastIndexOf( "/", i ); } else { lastSlash = prefix.lastIndexOf( "/" ); } prefix = prefix.substring( 0, lastSlash ); if ( loadRecursiveProjects ) { for ( String module : modules ) { if ( StringUtils.isNotEmpty( module ) ) { String urlString = prefix + "/" + module + POM_PART + suffix; URL moduleUrl; try { urlString = StringUtils.replace( urlString, '\\', '/' ); moduleUrl = new URL( urlString ); } catch ( MalformedURLException e ) { log.debug( "Error adding project module: Malformed URL " + urlString, e ); result.addError( ContinuumProjectBuildingResult.ERROR_MALFORMED_URL, urlString ); continue; } String moduleScmUrl = ""; String modulePath = StringUtils.replace( new String( module ), '\\', '/' ); // check if module is relative if ( modulePath.indexOf( "../" ) != -1 ) { int depth = StringUtils.countMatches( StringUtils.substring( modulePath, 0, modulePath.lastIndexOf( '/' ) + 1 ), "/" ); String baseUrl = ""; for ( int j = 1; j <= depth; j++ ) { scmUrl = StringUtils.chompLast( new String( scmUrl ), "/" ); baseUrl = StringUtils.substring( scmUrl, 0, scmUrl.lastIndexOf( '/' ) ); } moduleScmUrl = baseUrl + "/" + StringUtils.substring( modulePath, modulePath.lastIndexOf( "../" ) + 3 ); } else { scmUrl = StringUtils.chompLast( scmUrl, "/" ); moduleScmUrl = scmUrl + "/" + modulePath; } // we are in recursive loading mode importProjects( importRoot, moduleUrl, result, projectGroup, username, password, moduleScmUrl, true, buildDefinitionTemplate, checkoutInSingleDirectory ); } } } } private BuildDefinition persistBuildDefinition( BuildDefinition buildDefinition ) throws BuildDefinitionServiceException { buildDefinition = buildDefinitionService.addBuildDefinition( buildDefinition ); if ( buildDefinition.getSchedule() == null ) { try { Schedule schedule = scheduleDao.getScheduleByName( ConfigurationService.DEFAULT_SCHEDULE_NAME ); buildDefinition.setSchedule( schedule ); } catch ( ContinuumStoreException e ) { log.warn( "Can't get default schedule.", e ); } } return buildDefinition; } private List<BuildDefinition> getBuildDefinitions( BuildDefinitionTemplate template, boolean loadRecursiveProjects, String defaultGoal ) throws ContinuumProjectBuilderException, BuildDefinitionServiceException { List<BuildDefinition> buildDefinitions = new ArrayList<BuildDefinition>(); boolean defaultSet = false; for ( BuildDefinition buildDefinition : template.getBuildDefinitions() ) { buildDefinition = buildDefinitionService.cloneBuildDefinition( buildDefinition ); if ( !defaultSet && buildDefinition.isDefaultForProject() ) { defaultSet = true; //CONTINUUM-1296 if ( StringUtils.isNotEmpty( defaultGoal ) ) { buildDefinition.setGoals( defaultGoal ); } } else { buildDefinition.setDefaultForProject( false ); } // due to CONTINUUM-1207 CONTINUUM-1436 user can do what they want with arguments // we must remove if exists --non-recursive or -N if ( !loadRecursiveProjects ) { if ( StringUtils.isEmpty( buildDefinition.getArguments() ) ) { // strange for a mvn build log.info( "build definition '" + buildDefinition.getId() + "' has empty args" ); } else { String arguments = buildDefinition.getArguments().replace( "--non-recursive", "" ); arguments = arguments.replace( "-N", "" ); arguments = arguments.trim(); buildDefinition.setArguments( arguments ); } } buildDefinition.setTemplate( false ); buildDefinitions.add( buildDefinition ); } return buildDefinitions; } private ProjectGroup buildProjectGroup( MavenProject mavenProject, ContinuumProjectBuildingResult result ) { ProjectGroup projectGroup = new ProjectGroup(); // ---------------------------------------------------------------------- // Group id // ---------------------------------------------------------------------- if ( StringUtils.isEmpty( mavenProject.getGroupId() ) ) { result.addError( ContinuumProjectBuildingResult.ERROR_MISSING_GROUPID ); return null; } projectGroup.setGroupId( mavenProject.getGroupId() ); // ---------------------------------------------------------------------- // Name // ---------------------------------------------------------------------- String name = mavenProject.getName(); if ( StringUtils.isEmpty( name ) ) { name = mavenProject.getGroupId(); } projectGroup.setName( name ); // ---------------------------------------------------------------------- // Description // ---------------------------------------------------------------------- projectGroup.setDescription( mavenProject.getDescription() ); // ---------------------------------------------------------------------- // Local Repository // ---------------------------------------------------------------------- try { LocalRepository repository = localRepositoryDao.getLocalRepositoryByName( "DEFAULT" ); projectGroup.setLocalRepository( repository ); } catch ( ContinuumStoreException e ) { log.warn( "Can't get default repository.", e ); } return projectGroup; } public BuildDefinitionTemplate getDefaultBuildDefinitionTemplate() throws ContinuumProjectBuilderException { try { return buildDefinitionService.getDefaultMavenTwoBuildDefinitionTemplate(); } catch ( BuildDefinitionServiceException e ) { throw new ContinuumProjectBuilderException( e.getMessage(), e ); } } }
5,120
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/project/builder
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/project/builder/maven/MavenOneContinuumProjectBuilder.java
package org.apache.maven.continuum.project.builder.maven; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.dao.ProjectGroupDao; import org.apache.maven.continuum.builddefinition.BuildDefinitionService; import org.apache.maven.continuum.builddefinition.BuildDefinitionServiceException; import org.apache.maven.continuum.execution.maven.m1.MavenOneBuildExecutor; import org.apache.maven.continuum.execution.maven.m1.MavenOneMetadataHelper; import org.apache.maven.continuum.execution.maven.m1.MavenOneMetadataHelperException; import org.apache.maven.continuum.model.project.BuildDefinition; import org.apache.maven.continuum.model.project.BuildDefinitionTemplate; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.model.project.ProjectGroup; import org.apache.maven.continuum.project.builder.AbstractContinuumProjectBuilder; import org.apache.maven.continuum.project.builder.ContinuumProjectBuilder; import org.apache.maven.continuum.project.builder.ContinuumProjectBuilderException; import org.apache.maven.continuum.project.builder.ContinuumProjectBuildingResult; import org.apache.maven.continuum.store.ContinuumStoreException; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.util.StringUtils; import java.io.File; import java.io.IOException; import java.net.URL; /** * @author <a href="mailto:trygvis@inamo.no">Trygve Laugst&oslash;l</a> */ @Component( role = org.apache.maven.continuum.project.builder.ContinuumProjectBuilder.class, hint = "maven-one-builder" ) public class MavenOneContinuumProjectBuilder extends AbstractContinuumProjectBuilder implements ContinuumProjectBuilder { public static final String ID = "maven-one-builder"; @Requirement private BuildDefinitionService buildDefinitionService; @Requirement private MavenOneMetadataHelper metadataHelper; @Requirement private ProjectGroupDao projectGroupDao; // ---------------------------------------------------------------------- // ProjectCreator Implementation // ---------------------------------------------------------------------- public ContinuumProjectBuildingResult buildProjectsFromMetadata( URL url, String username, String password ) throws ContinuumProjectBuilderException { return buildProjectsFromMetadata( url, username, password, true, false ); } public ContinuumProjectBuildingResult buildProjectsFromMetadata( URL url, String username, String password, boolean recursiveProjects, boolean checkoutInSingleDirectory ) throws ContinuumProjectBuilderException { try { return buildProjectsFromMetadata( url, username, password, recursiveProjects, buildDefinitionService.getDefaultMavenOneBuildDefinitionTemplate(), false ); } catch ( BuildDefinitionServiceException e ) { throw new ContinuumProjectBuilderException( e.getMessage(), e ); } } public ContinuumProjectBuildingResult buildProjectsFromMetadata( URL url, String username, String password, boolean recursiveProjects, BuildDefinitionTemplate buildDefinitionTemplate, boolean checkoutInSingleDirectory ) throws ContinuumProjectBuilderException { return buildProjectsFromMetadata( url, username, password, buildDefinitionTemplate, null ); } public ContinuumProjectBuildingResult buildProjectsFromMetadata( URL url, String username, String password, boolean recursiveProjects, BuildDefinitionTemplate buildDefinitionTemplate, boolean checkoutInSingleDirectory, int projectGroupId ) throws ContinuumProjectBuilderException { ProjectGroup projectGroup = null; if ( projectGroupId > 0 ) { try { projectGroup = projectGroupDao.getProjectGroupWithBuildDetailsByProjectGroupId( projectGroupId ); } catch ( ContinuumStoreException e ) { throw new ContinuumProjectBuilderException( e.getMessage(), e ); } } return buildProjectsFromMetadata( url, username, password, buildDefinitionTemplate, projectGroup ); } private ContinuumProjectBuildingResult buildProjectsFromMetadata( URL url, String username, String password, BuildDefinitionTemplate buildDefinitionTemplate, ProjectGroup projectGroup ) throws ContinuumProjectBuilderException { File importRoot = fsManager.createTempFile( "continuum-m1import-", "", fsManager.getTempDir() ); if ( !importRoot.mkdirs() ) { throw new ContinuumProjectBuilderException( "failed to create directory for import: " + importRoot ); } Project project = new Project(); ContinuumProjectBuildingResult result = new ContinuumProjectBuildingResult(); try { File pomFile = createMetadataFile( importRoot, result, url, username, password ); if ( pomFile == null ) { return result; } metadataHelper.mapMetadata( result, pomFile, project, true ); if ( result.hasErrors() ) { return result; } for ( BuildDefinition bd : buildDefinitionTemplate.getBuildDefinitions() ) { BuildDefinition cloneBuildDefinition = buildDefinitionService.cloneBuildDefinition( bd ); cloneBuildDefinition.setTemplate( false ); project.addBuildDefinition( cloneBuildDefinition ); } result.addProject( project, MavenOneBuildExecutor.ID ); } catch ( MavenOneMetadataHelperException e ) { log.error( "Unknown error while processing metadata", e ); result.addError( ContinuumProjectBuildingResult.ERROR_UNKNOWN ); } finally { if ( importRoot.exists() ) { try { fsManager.removeDir( importRoot ); } catch ( IOException e ) { log.warn( "failed to remove {} after project import: {}", importRoot, e.getMessage() ); } } } if ( projectGroup == null ) { projectGroup = new ProjectGroup(); // ---------------------------------------------------------------------- // Group id // ---------------------------------------------------------------------- if ( StringUtils.isEmpty( project.getGroupId() ) ) { result.addError( ContinuumProjectBuildingResult.ERROR_MISSING_GROUPID ); } projectGroup.setGroupId( project.getGroupId() ); // ---------------------------------------------------------------------- // Name // ---------------------------------------------------------------------- String name = project.getName(); if ( StringUtils.isEmpty( name ) ) { name = project.getGroupId(); } projectGroup.setName( name ); // ---------------------------------------------------------------------- // Description // ---------------------------------------------------------------------- projectGroup.setDescription( project.getDescription() ); } result.addProjectGroup( projectGroup ); return result; } public BuildDefinitionTemplate getDefaultBuildDefinitionTemplate() throws ContinuumProjectBuilderException { try { return buildDefinitionService.getDefaultMavenOneBuildDefinitionTemplate(); } catch ( BuildDefinitionServiceException e ) { throw new ContinuumProjectBuilderException( e.getMessage(), e ); } } }
5,121
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/project/builder
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/project/builder/manager/ContinuumProjectBuilderManager.java
package org.apache.maven.continuum.project.builder.manager; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.maven.continuum.project.builder.ContinuumProjectBuilder; /** * @author <a href="mailto:trygvis@inamo.no">Trygve Laugst&oslash;l</a> */ public interface ContinuumProjectBuilderManager { String ROLE = ContinuumProjectBuilderManager.class.getName(); ContinuumProjectBuilder getProjectBuilder( String id ) throws ContinuumProjectBuilderManagerException; }
5,122
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/project/builder
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/project/builder/manager/ContinuumProjectBuilderManagerException.java
package org.apache.maven.continuum.project.builder.manager; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /** * @author <a href="mailto:trygvis@inamo.no">Trygve Laugst&oslash;l</a> */ public class ContinuumProjectBuilderManagerException extends Exception { public ContinuumProjectBuilderManagerException( String message ) { super( message ); } public ContinuumProjectBuilderManagerException( String message, Throwable cause ) { super( message, cause ); } }
5,123
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/project/builder
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/project/builder/manager/DefaultContinuumProjectBuilderManager.java
package org.apache.maven.continuum.project.builder.manager; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.maven.continuum.project.builder.ContinuumProjectBuilder; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import java.util.Map; /** * @author <a href="mailto:trygvis@inamo.no">Trygve Laugst&oslash;l</a> */ @Component( role = org.apache.maven.continuum.project.builder.manager.ContinuumProjectBuilderManager.class, hint = "default" ) public class DefaultContinuumProjectBuilderManager implements ContinuumProjectBuilderManager { @Requirement( role = org.apache.maven.continuum.project.builder.ContinuumProjectBuilder.class ) private Map<String, ContinuumProjectBuilder> projectBuilders; // ---------------------------------------------------------------------- // ProjectCreatorManager Implementation // ---------------------------------------------------------------------- public ContinuumProjectBuilder getProjectBuilder( String id ) throws ContinuumProjectBuilderManagerException { ContinuumProjectBuilder projectBuilder = projectBuilders.get( id ); if ( projectBuilder == null ) { throw new ContinuumProjectBuilderManagerException( "No such project creator with id '" + id + "'." ); } return projectBuilder; } }
5,124
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/execution/AbstractBuildExecutor.java
package org.apache.maven.continuum.execution; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.utils.shell.ExecutionResult; import org.apache.continuum.utils.shell.ShellCommandHelper; import org.apache.maven.artifact.Artifact; import org.apache.maven.continuum.builddefinition.BuildDefinitionUpdatePolicyConstants; import org.apache.maven.continuum.installation.InstallationService; import org.apache.maven.continuum.model.project.BuildDefinition; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.model.scm.ChangeFile; import org.apache.maven.continuum.model.scm.ChangeSet; import org.apache.maven.continuum.model.scm.ScmResult; import org.apache.maven.continuum.model.system.Installation; import org.apache.maven.continuum.model.system.Profile; import org.apache.maven.continuum.project.ContinuumProjectState; import org.apache.maven.continuum.utils.WorkingDirectoryService; import org.codehaus.plexus.commandline.ExecutableResolver; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.personality.plexus.lifecycle.phase.Initializable; import org.codehaus.plexus.personality.plexus.lifecycle.phase.InitializationException; import org.codehaus.plexus.util.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; /** * @author <a href="mailto:trygvis@inamo.no">Trygve Laugst&oslash;l</a> */ public abstract class AbstractBuildExecutor implements ContinuumBuildExecutor, Initializable { protected final Logger log = LoggerFactory.getLogger( getClass() ); private static final String SUDO_EXECUTABLE = "sudo"; private static final String CHROOT_EXECUTABLE = "chroot"; // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- @Requirement private ShellCommandHelper shellCommandHelper; @Requirement private ExecutableResolver executableResolver; @Requirement private WorkingDirectoryService workingDirectoryService; @Requirement private InstallationService installationService; @Requirement private File chrootJailDirectory; @Requirement private String defaultExecutable; // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- private final String id; private boolean resolveExecutable; // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- protected AbstractBuildExecutor( String id, boolean resolveExecutable ) { this.id = id; this.resolveExecutable = resolveExecutable; } public void setShellCommandHelper( ShellCommandHelper shellCommandHelper ) { this.shellCommandHelper = shellCommandHelper; } public ShellCommandHelper getShellCommandHelper() { return shellCommandHelper; } public void setWorkingDirectoryService( WorkingDirectoryService workingDirectoryService ) { this.workingDirectoryService = workingDirectoryService; } public WorkingDirectoryService getWorkingDirectoryService() { return workingDirectoryService; } public void setDefaultExecutable( String defaultExecutable ) { this.defaultExecutable = defaultExecutable; } // ---------------------------------------------------------------------- // Component Lifecycle // ---------------------------------------------------------------------- public String getDefaultExecutable() { return defaultExecutable; } public void initialize() throws InitializationException { List path = executableResolver.getDefaultPath(); if ( resolveExecutable ) { if ( StringUtils.isEmpty( defaultExecutable ) ) { log.warn( "The default executable for build executor '" + id + "' is not set. " + "This will cause a problem unless the project has a executable configured." ); } else { File resolvedExecutable = executableResolver.findExecutable( defaultExecutable, path ); if ( resolvedExecutable == null ) { log.warn( "Could not find the executable '" + defaultExecutable + "' in the " + "path '" + path + "'." ); } else { log.info( "Resolved the executable '" + defaultExecutable + "' to " + "'" + resolvedExecutable.getAbsolutePath() + "'." ); } } } } // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- /** * Find the actual executable path to be used * * @param defaultExecutable * @return The executable path */ protected String findExecutable( String executable, String defaultExecutable, boolean resolveExecutable, File workingDirectory ) { // ---------------------------------------------------------------------- // If we're not searching the path for the executable, prefix the // executable with the working directory to make sure the path is // absolute and thus won't be tried resolved by using the PATH // ---------------------------------------------------------------------- String actualExecutable; if ( !resolveExecutable ) { actualExecutable = new File( workingDirectory, executable ).getAbsolutePath(); } else { List<String> path = executableResolver.getDefaultPath(); if ( StringUtils.isEmpty( executable ) ) { executable = defaultExecutable; } File e = executableResolver.findExecutable( executable, path ); if ( e == null ) { log.warn( "Could not find the executable '" + executable + "' in this path: " ); for ( String element : path ) { log.warn( element ); } actualExecutable = defaultExecutable; } else { actualExecutable = e.getAbsolutePath(); } } //sometimes executable isn't found in path but it exit (CONTINUUM-365) File actualExecutableFile = new File( actualExecutable ); if ( !actualExecutableFile.exists() ) { actualExecutable = executable; } return actualExecutable; } protected ContinuumBuildExecutionResult executeShellCommand( Project project, String executable, String arguments, File output, Map<String, String> environments, List<Project> projectsWithCommonScmRoot, String projectScmRootUrl ) throws ContinuumBuildExecutorException { File workingDirectory = getWorkingDirectory( project, projectScmRootUrl, projectsWithCommonScmRoot ); String actualExecutable = findExecutable( executable, defaultExecutable, resolveExecutable, workingDirectory ); // ---------------------------------------------------------------------- // Execute the build // ---------------------------------------------------------------------- try { File chrootJailDirectory = getChrootJailDirectory(); if ( chrootJailDirectory != null ) { StringBuilder sb = new StringBuilder(); sb.append( CHROOT_EXECUTABLE ); sb.append( " " ); sb.append( new File( chrootJailDirectory, project.getGroupId() ) ); sb.append( " " ); sb.append( " /bin/sh -c 'cd " ); sb.append( getRelativePath( chrootJailDirectory, workingDirectory, project.getGroupId() ) ); sb.append( " && " ); sb.append( actualExecutable ); sb.append( " " ); sb.append( arguments ); sb.append( "'" ); arguments = sb.toString(); actualExecutable = SUDO_EXECUTABLE; workingDirectory = chrootJailDirectory; // not really used but must exist } ExecutionResult result = getShellCommandHelper().executeShellCommand( workingDirectory, actualExecutable, arguments, output, project.getId(), environments ); log.info( "Exit code: " + result.getExitCode() ); return new ContinuumBuildExecutionResult( output, result.getExitCode() ); } catch ( Exception e ) { if ( e.getCause() instanceof InterruptedException ) { throw new ContinuumBuildCancelledException( "The build was cancelled", e ); } else { throw new ContinuumBuildExecutorException( "Error while executing shell command. The most common error is that '" + executable + "' " + "is not in your path.", e ); } } } private String getRelativePath( File chrootDir, File workingDirectory, String groupId ) { String path = workingDirectory.getPath(); String chrootBase = new File( chrootDir, groupId ).getPath(); if ( path.startsWith( chrootBase ) ) { return path.substring( chrootBase.length(), path.length() ); } else { throw new IllegalArgumentException( "Working directory is not inside the chroot jail " + chrootBase + " , " + path ); } } protected abstract Map<String, String> getEnvironments( BuildDefinition buildDefinition ); protected String getJavaHomeValue( BuildDefinition buildDefinition ) { Profile profile = buildDefinition.getProfile(); if ( profile == null ) { return null; } Installation jdk = profile.getJdk(); if ( jdk == null ) { return null; } return jdk.getVarValue(); } public void backupTestFiles( Project project, int buildId, String projectScmRootUrl, List<Project> projectsWithCommonScmRoot ) { //Nothing to do, by default } /** * By default, we return true because with a change, the project must be rebuilt. */ public boolean shouldBuild( List<ChangeSet> changes, Project continuumProject, File workingDirectory, BuildDefinition buildDefinition ) throws ContinuumBuildExecutorException { return true; } protected Map<String, String> getEnvironmentVariables( BuildDefinition buildDefinition ) { Profile profile = buildDefinition.getProfile(); Map<String, String> envVars = new HashMap<String, String>(); if ( profile == null ) { return envVars; } List<Installation> environmentVariables = profile.getEnvironmentVariables(); if ( environmentVariables.isEmpty() ) { return envVars; } for ( Installation installation : environmentVariables ) { envVars.put( installation.getVarName(), installation.getVarValue() ); } return envVars; } protected Properties getContinuumSystemProperties( Project project ) { Properties properties = new Properties(); properties.setProperty( "continuum.project.group.name", project.getProjectGroup().getName() ); properties.setProperty( "continuum.project.lastBuild.state", String.valueOf( project.getOldState() ) ); properties.setProperty( "continuum.project.lastBuild.number", String.valueOf( project.getBuildNumber() ) ); properties.setProperty( "continuum.project.nextBuild.number", String.valueOf( project.getBuildNumber() + 1 ) ); properties.setProperty( "continuum.project.id", String.valueOf( project.getId() ) ); properties.setProperty( "continuum.project.name", project.getName() ); properties.setProperty( "continuum.project.version", project.getVersion() ); return properties; } protected String getBuildFileForProject( Project project, BuildDefinition buildDefinition ) { String buildFile = StringUtils.clean( buildDefinition.getBuildFile() ); String relPath = StringUtils.clean( project.getRelativePath() ); if ( StringUtils.isEmpty( relPath ) ) { return buildFile; } return relPath + File.separator + buildFile; } protected boolean isDescriptionUpdated( BuildDefinition buildDefinition, ScmResult scmResult, Project project ) { boolean update = true; if ( buildDefinition != null && scmResult != null ) { int policy = buildDefinition.getUpdatePolicy(); if ( BuildDefinitionUpdatePolicyConstants.UPDATE_DESCRIPTION_NEVER == policy ) { update = false; } else if ( BuildDefinitionUpdatePolicyConstants.UPDATE_DESCRIPTION_ONLY_FOR_NEW_POM == policy ) { update = pomUpdated( buildDefinition.getBuildFile(), scmResult, project ); } } return update; } private boolean pomUpdated( String buildFile, ScmResult scmResult, Project project ) { String filename = project.getScmUrl() + "/" + buildFile; for ( Iterator changeIt = scmResult.getChanges().listIterator(); changeIt.hasNext(); ) { ChangeSet change = (ChangeSet) changeIt.next(); for ( Iterator fileIt = change.getFiles().listIterator(); fileIt.hasNext(); ) { ChangeFile changeFile = (ChangeFile) fileIt.next(); if ( filename.endsWith( changeFile.getName() ) ) { return true; } } } return false; } public boolean isBuilding( Project project ) { return project.getState() == ContinuumProjectState.BUILDING || getShellCommandHelper().isRunning( project.getId() ); } public void killProcess( Project project ) { getShellCommandHelper().killProcess( project.getId() ); } public List<Artifact> getDeployableArtifacts( Project project, File workingDirectory, BuildDefinition buildDefinition ) throws ContinuumBuildExecutorException { // Not supported by this builder return Collections.emptyList(); } public File getWorkingDirectory( Project project, String projectScmRootUrl, List<Project> projectsWithCommonScmRoot ) { return getWorkingDirectoryService().getWorkingDirectory( project, projectScmRootUrl, projectsWithCommonScmRoot ); } public InstallationService getInstallationService() { return installationService; } public void setInstallationService( InstallationService installationService ) { this.installationService = installationService; } public boolean isResolveExecutable() { return resolveExecutable; } public void setResolveExecutable( boolean resolveExecutable ) { this.resolveExecutable = resolveExecutable; } public void setExecutableResolver( ExecutableResolver executableResolver ) { this.executableResolver = executableResolver; } public ExecutableResolver getExecutableResolver() { return executableResolver; } public void setChrootJailDirectory( File chrootJailDirectory ) { this.chrootJailDirectory = chrootJailDirectory; } public File getChrootJailDirectory() { return chrootJailDirectory; } }
5,125
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/execution
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/execution/ant/AntBuildExecutor.java
package org.apache.maven.continuum.execution.ant; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.maven.continuum.configuration.ConfigurationException; import org.apache.maven.continuum.configuration.ConfigurationService; import org.apache.maven.continuum.execution.AbstractBuildExecutor; import org.apache.maven.continuum.execution.ContinuumBuildExecutionResult; import org.apache.maven.continuum.execution.ContinuumBuildExecutor; import org.apache.maven.continuum.execution.ContinuumBuildExecutorConstants; import org.apache.maven.continuum.execution.ContinuumBuildExecutorException; import org.apache.maven.continuum.execution.shared.JUnitReportArchiver; import org.apache.maven.continuum.installation.InstallationService; import org.apache.maven.continuum.model.project.BuildDefinition; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.model.scm.ScmResult; import org.apache.maven.continuum.model.system.Installation; import org.apache.maven.continuum.model.system.Profile; import org.codehaus.plexus.util.StringUtils; import java.io.File; import java.io.IOException; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; /** * @author <a href="mailto:trygvis@inamo.no">Trygve Laugst&oslash;l</a> */ public class AntBuildExecutor extends AbstractBuildExecutor implements ContinuumBuildExecutor { // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- public static final String CONFIGURATION_EXECUTABLE = "executable"; public static final String CONFIGURATION_TARGETS = "targets"; public static final String ID = ContinuumBuildExecutorConstants.ANT_BUILD_EXECUTOR; private ConfigurationService configurationService; private JUnitReportArchiver testReportArchiver; // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- public AntBuildExecutor() { super( ID, true ); } public void setConfigurationService( ConfigurationService configurationService ) { this.configurationService = configurationService; } public void setTestReportArchiver( JUnitReportArchiver testReportArchiver ) { this.testReportArchiver = testReportArchiver; } // ---------------------------------------------------------------------- // ContinuumBuilder Implementation // ---------------------------------------------------------------------- public ContinuumBuildExecutionResult build( Project project, BuildDefinition buildDefinition, File buildOutput, List<Project> projectsWithCommonScmRoot, String projectScmRootUrl ) throws ContinuumBuildExecutorException { String executable = getInstallationService().getExecutorConfigurator( InstallationService.ANT_TYPE ).getExecutable(); StringBuffer arguments = new StringBuffer(); String buildFile = getBuildFileForProject( project, buildDefinition ); if ( !StringUtils.isEmpty( buildFile ) ) { arguments.append( "-f " ).append( buildFile ).append( " " ); } arguments.append( StringUtils.clean( buildDefinition.getArguments() ) ).append( " " ); Properties props = getContinuumSystemProperties( project ); for ( Enumeration itr = props.propertyNames(); itr.hasMoreElements(); ) { String name = (String) itr.nextElement(); String value = props.getProperty( name ); arguments.append( "\"-D" ).append( name ).append( "=" ).append( value ).append( "\" " ); } arguments.append( StringUtils.clean( buildDefinition.getGoals() ) ); Map<String, String> environments = getEnvironments( buildDefinition ); String antHome = environments.get( getInstallationService().getEnvVar( InstallationService.ANT_TYPE ) ); if ( StringUtils.isNotEmpty( antHome ) ) { executable = antHome + File.separator + "bin" + File.separator + executable; setResolveExecutable( false ); } return executeShellCommand( project, executable, arguments.toString(), buildOutput, environments, null, null ); } protected Map<String, String> getEnvironments( BuildDefinition buildDefinition ) { Profile profile = buildDefinition.getProfile(); if ( profile == null ) { return Collections.EMPTY_MAP; } Map<String, String> envVars = new HashMap<String, String>(); String javaHome = getJavaHomeValue( buildDefinition ); if ( !StringUtils.isEmpty( javaHome ) ) { envVars.put( getInstallationService().getEnvVar( InstallationService.JDK_TYPE ), javaHome ); } Installation builder = profile.getBuilder(); if ( builder != null ) { envVars.put( getInstallationService().getEnvVar( InstallationService.ANT_TYPE ), builder.getVarValue() ); } envVars.putAll( getEnvironmentVariables( buildDefinition ) ); return envVars; } public void updateProjectFromCheckOut( File workingDirectory, Project p, BuildDefinition buildDefinition, ScmResult scmResult ) throws ContinuumBuildExecutorException { } @Override public void backupTestFiles( Project project, int buildId, String projectScmRootUrl, List<Project> projectsWithCommonScmRoot ) { try { File backupDirectory = configurationService.getTestReportsDirectory( buildId, project.getId() ); testReportArchiver.archiveReports( getWorkingDirectory( project, projectScmRootUrl, projectsWithCommonScmRoot ), backupDirectory ); } catch ( ConfigurationException e ) { log.error( "failed to get backup directory", e ); } catch ( IOException e ) { log.warn( "failed to copy test results to backup directory", e ); } } }
5,126
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/execution
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/execution/shell/ShellBuildExecutor.java
package org.apache.maven.continuum.execution.shell; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.maven.continuum.execution.AbstractBuildExecutor; import org.apache.maven.continuum.execution.ContinuumBuildExecutionResult; import org.apache.maven.continuum.execution.ContinuumBuildExecutor; import org.apache.maven.continuum.execution.ContinuumBuildExecutorConstants; import org.apache.maven.continuum.execution.ContinuumBuildExecutorException; import org.apache.maven.continuum.installation.InstallationService; import org.apache.maven.continuum.model.project.BuildDefinition; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.model.scm.ScmResult; import org.apache.maven.continuum.model.system.Installation; import org.apache.maven.continuum.model.system.Profile; import org.codehaus.plexus.util.StringUtils; import java.io.File; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author <a href="mailto:trygvis@inamo.no">Trygve Laugst&oslash;l</a> */ public class ShellBuildExecutor extends AbstractBuildExecutor implements ContinuumBuildExecutor { // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- public static final String CONFIGURATION_EXECUTABLE = "executable"; public static final String ID = ContinuumBuildExecutorConstants.SHELL_BUILD_EXECUTOR; // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- public ShellBuildExecutor() { super( ID, false ); } // ---------------------------------------------------------------------- // ContinuumBuilder implementation // ---------------------------------------------------------------------- public ContinuumBuildExecutionResult build( Project project, BuildDefinition buildDefinition, File buildOutput, List<Project> projectsWithCommonScmRoot, String projectScmRootUrl ) throws ContinuumBuildExecutorException { // TODO: this should be validated earlier? String executable = getBuildFileForProject( project, buildDefinition ); return executeShellCommand( project, executable, buildDefinition.getArguments(), buildOutput, getEnvironments( buildDefinition ), null, null ); } protected Map<String, String> getEnvironments( BuildDefinition buildDefinition ) { Profile profile = buildDefinition.getProfile(); if ( profile == null ) { return Collections.EMPTY_MAP; } Map<String, String> envVars = new HashMap<String, String>(); String javaHome = getJavaHomeValue( buildDefinition ); if ( !StringUtils.isEmpty( javaHome ) ) { envVars.put( getInstallationService().getEnvVar( InstallationService.JDK_TYPE ), javaHome ); } Installation builder = profile.getBuilder(); if ( builder != null ) { envVars.put( builder.getVarName(), builder.getVarValue() ); } envVars.putAll( getEnvironmentVariables( buildDefinition ) ); return envVars; } public void updateProjectFromCheckOut( File workingDirectory, Project project, BuildDefinition buildDefinition, ScmResult scmResult ) throws ContinuumBuildExecutorException { } }
5,127
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/execution/maven
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/execution/maven/m1/DefaultMavenOneMetadataHelper.java
package org.apache.maven.continuum.execution.maven.m1; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.model.project.ProjectDependency; import org.apache.maven.continuum.model.project.ProjectDeveloper; import org.apache.maven.continuum.model.project.ProjectNotifier; import org.apache.maven.continuum.notification.AbstractContinuumNotifier; import org.apache.maven.continuum.project.builder.ContinuumProjectBuildingResult; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.util.StringUtils; import org.codehaus.plexus.util.xml.Xpp3Dom; import org.codehaus.plexus.util.xml.Xpp3DomBuilder; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Properties; /** * @author <a href="mailto:trygvis@inamo.no">Trygve Laugst&oslash;l</a> */ @Component( role = org.apache.maven.continuum.execution.maven.m1.MavenOneMetadataHelper.class, hint = "default" ) public class DefaultMavenOneMetadataHelper implements MavenOneMetadataHelper { private static final Logger log = LoggerFactory.getLogger( DefaultMavenOneMetadataHelper.class ); // ---------------------------------------------------------------------- // MavenOneMetadataHelper Implementation // ---------------------------------------------------------------------- /** * @deprecated Use {@link #mapMetadata(ContinuumProjectBuildingResult, File, Project)} instead */ @Deprecated public void mapMetadata( File metadata, Project project ) throws MavenOneMetadataHelperException { mapMetadata( new ContinuumProjectBuildingResult(), metadata, project, true ); } public void mapMetadata( ContinuumProjectBuildingResult result, File metadata, Project project, boolean updateDefinition ) throws MavenOneMetadataHelperException { Xpp3Dom mavenProject; try { mavenProject = Xpp3DomBuilder.build( new FileReader( metadata ) ); } catch ( XmlPullParserException e ) { result.addError( ContinuumProjectBuildingResult.ERROR_XML_PARSE ); log.info( "Error while reading maven POM (" + e.getMessage() + ").", e ); return; } catch ( FileNotFoundException e ) { result.addError( ContinuumProjectBuildingResult.ERROR_POM_NOT_FOUND ); log.info( "Error while reading maven POM (" + e.getMessage() + ").", e ); return; } catch ( IOException e ) { result.addError( ContinuumProjectBuildingResult.ERROR_UNKNOWN ); log.info( "Error while reading maven POM (" + e.getMessage() + ").", e ); return; } // ---------------------------------------------------------------------- // We cannot deal with projects that use the <extend/> element because // we don't have the whole source tree and we might be missing elements // that are present in the parent. // ---------------------------------------------------------------------- String extend = getValue( mavenProject, "extend", null ); if ( extend != null ) { result.addError( ContinuumProjectBuildingResult.ERROR_EXTEND ); log.info( "Cannot use a POM with an 'extend' element." ); return; } // ---------------------------------------------------------------------- // Artifact and group id // ---------------------------------------------------------------------- String groupId; String artifactId; String id = getValue( mavenProject, "id", null ); if ( !StringUtils.isEmpty( id ) ) { groupId = id; artifactId = id; } else { groupId = getValue( mavenProject, "groupId", project.getGroupId() ); if ( StringUtils.isEmpty( groupId ) ) { result.addError( ContinuumProjectBuildingResult.ERROR_MISSING_GROUPID ); log.info( "Missing 'groupId' element in the POM." ); // Do not throw an exception or return here, gather up as many results as possible first. } artifactId = getValue( mavenProject, "artifactId", project.getArtifactId() ); if ( StringUtils.isEmpty( artifactId ) ) { result.addError( ContinuumProjectBuildingResult.ERROR_MISSING_ARTIFACTID ); log.info( "Missing 'artifactId' element in the POM." ); // Do not throw an exception or return here, gather up as many results as possible first. } } // ---------------------------------------------------------------------- // version // ---------------------------------------------------------------------- String version = getValue( mavenProject, "currentVersion", project.getVersion() ); if ( StringUtils.isEmpty( project.getVersion() ) && StringUtils.isEmpty( version ) ) { result.addError( ContinuumProjectBuildingResult.ERROR_MISSING_VERSION ); // Do not throw an exception or return here, gather up as many results as possible first. } // ---------------------------------------------------------------------- // name // ---------------------------------------------------------------------- String name = getValue( mavenProject, "name", project.getName() ); if ( StringUtils.isEmpty( project.getName() ) && StringUtils.isEmpty( name ) ) { result.addError( ContinuumProjectBuildingResult.ERROR_MISSING_NAME ); // Do not throw an exception or return here, gather up as many results as possible first. } // ---------------------------------------------------------------------- // description // ---------------------------------------------------------------------- String shortDescription = getValue( mavenProject, "shortDescription", project.getDescription() ); String description = getValue( mavenProject, "description", project.getDescription() ); // ---------------------------------------------------------------------- // scm // ---------------------------------------------------------------------- Xpp3Dom repository = mavenProject.getChild( "repository" ); String scmConnection = null; if ( repository == null ) { if ( !StringUtils.isEmpty( project.getScmUrl() ) ) { scmConnection = project.getScmUrl(); } else { result.addError( ContinuumProjectBuildingResult.ERROR_MISSING_REPOSITORY ); // Do not throw an exception or return here, gather up as many results as possible first. } } else { scmConnection = getValue( repository, "developerConnection", project.getScmUrl() ); scmConnection = getValue( repository, "connection", scmConnection ); if ( StringUtils.isEmpty( scmConnection ) ) { result.addError( ContinuumProjectBuildingResult.ERROR_MISSING_SCM, name ); // Do not throw an exception or return here, gather up as many results as possible first. } } // ---------------------------------------------------------------------- // Developers // ---------------------------------------------------------------------- Xpp3Dom developers = mavenProject.getChild( "developers" ); if ( developers != null ) { Xpp3Dom[] developersList = developers.getChildren(); List<ProjectDeveloper> cds = new ArrayList<ProjectDeveloper>(); for ( Xpp3Dom developer : developersList ) { ProjectDeveloper cd = new ProjectDeveloper(); cd.setScmId( getValue( developer, "id", null ) ); cd.setName( getValue( developer, "name", null ) ); cd.setEmail( getValue( developer, "email", null ) ); cds.add( cd ); } project.setDevelopers( cds ); } // ---------------------------------------------------------------------- // Dependencies // ---------------------------------------------------------------------- Xpp3Dom dependencies = mavenProject.getChild( "dependencies" ); if ( dependencies != null ) { Xpp3Dom[] dependenciesList = dependencies.getChildren(); List<ProjectDependency> deps = new ArrayList<ProjectDependency>(); for ( Xpp3Dom dependency : dependenciesList ) { ProjectDependency cd = new ProjectDependency(); if ( getValue( dependency, "groupId", null ) != null ) { cd.setGroupId( getValue( dependency, "groupId", null ) ); cd.setArtifactId( getValue( dependency, "artifactId", null ) ); } else { cd.setGroupId( getValue( dependency, "id", null ) ); cd.setArtifactId( getValue( dependency, "id", null ) ); } cd.setVersion( getValue( dependency, "version", null ) ); deps.add( cd ); } project.setDependencies( deps ); } // ---------------------------------------------------------------------- // notifiers // ---------------------------------------------------------------------- Xpp3Dom build = mavenProject.getChild( "build" ); List<ProjectNotifier> notifiers = new ArrayList<ProjectNotifier>(); // Add project Notifier if ( build != null ) { String nagEmailAddress = getValue( build, "nagEmailAddress", null ); if ( nagEmailAddress != null ) { Properties props = new Properties(); props.put( AbstractContinuumNotifier.ADDRESS_FIELD, nagEmailAddress ); ProjectNotifier notifier = new ProjectNotifier(); notifier.setConfiguration( props ); notifier.setFrom( ProjectNotifier.FROM_PROJECT ); notifiers.add( notifier ); } } // Add all user notifiers if ( project.getNotifiers() != null && !project.getNotifiers().isEmpty() ) { for ( ProjectNotifier notif : (List<ProjectNotifier>) project.getNotifiers() ) { if ( notif.isFromUser() ) { notifiers.add( notif ); } } } // ---------------------------------------------------------------------- // Handle Errors / Results // ---------------------------------------------------------------------- if ( result.hasErrors() ) { // prevent project creation if there are errors. return; } // ---------------------------------------------------------------------- // Make the project // ---------------------------------------------------------------------- project.setGroupId( groupId ); project.setArtifactId( artifactId ); if ( updateDefinition ) { project.setVersion( version ); project.setName( name ); } if ( StringUtils.isEmpty( shortDescription ) ) { project.setDescription( description ); } else { project.setDescription( shortDescription ); } project.setScmUrl( scmConnection ); project.setNotifiers( notifiers ); } // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- private String getValue( Xpp3Dom dom, String key, String defaultValue ) { Xpp3Dom child = dom.getChild( key ); if ( child == null ) { return defaultValue; } return child.getValue(); } }
5,128
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/execution/maven
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/execution/maven/m1/MavenOneMetadataHelperException.java
package org.apache.maven.continuum.execution.maven.m1; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /** * @author <a href="mailto:trygvis@inamo.no">Trygve Laugst&oslash;l</a> */ public class MavenOneMetadataHelperException extends Exception { private static final long serialVersionUID = -5868938464601717160L; public MavenOneMetadataHelperException( String message ) { super( message ); } public MavenOneMetadataHelperException( String message, Throwable cause ) { super( message, cause ); } }
5,129
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/execution/maven
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/execution/maven/m1/MavenOneBuildExecutor.java
package org.apache.maven.continuum.execution.maven.m1; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.model.repository.LocalRepository; import org.apache.maven.continuum.execution.AbstractBuildExecutor; import org.apache.maven.continuum.execution.ContinuumBuildExecutionResult; import org.apache.maven.continuum.execution.ContinuumBuildExecutor; import org.apache.maven.continuum.execution.ContinuumBuildExecutorConstants; import org.apache.maven.continuum.execution.ContinuumBuildExecutorException; import org.apache.maven.continuum.installation.InstallationService; import org.apache.maven.continuum.model.project.BuildDefinition; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.model.scm.ScmResult; import org.apache.maven.continuum.model.system.Installation; import org.apache.maven.continuum.model.system.Profile; import org.apache.maven.continuum.project.builder.ContinuumProjectBuildingResult; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.util.StringUtils; import java.io.File; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; /** * @author <a href="mailto:trygvis@inamo.no">Trygve Laugst&oslash;l</a> */ public class MavenOneBuildExecutor extends AbstractBuildExecutor implements ContinuumBuildExecutor { public final static String CONFIGURATION_GOALS = "goals"; public final static String ID = ContinuumBuildExecutorConstants.MAVEN_ONE_BUILD_EXECUTOR; @Requirement private MavenOneMetadataHelper metadataHelper; // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- public MavenOneBuildExecutor() { super( ID, true ); } public MavenOneMetadataHelper getMetadataHelper() { return metadataHelper; } public void setMetadataHelper( MavenOneMetadataHelper metadataHelper ) { this.metadataHelper = metadataHelper; } // ---------------------------------------------------------------------- // Builder Implementation // ---------------------------------------------------------------------- public ContinuumBuildExecutionResult build( Project project, BuildDefinition buildDefinition, File buildOutput, List<Project> projectsWithCommonScmRoot, String projectScmRootUrl ) throws ContinuumBuildExecutorException { String executable = getInstallationService().getExecutorConfigurator( InstallationService.MAVEN1_TYPE ).getExecutable(); StringBuffer arguments = new StringBuffer(); String buildFile = getBuildFileForProject( project, buildDefinition ); if ( !StringUtils.isEmpty( buildFile ) && !"project.xml".equals( buildFile ) ) { arguments.append( "-p " ).append( buildFile ).append( " " ); } arguments.append( StringUtils.clean( buildDefinition.getArguments() ) ).append( " " ); Properties props = getContinuumSystemProperties( project ); for ( Enumeration itr = props.propertyNames(); itr.hasMoreElements(); ) { String name = (String) itr.nextElement(); String value = props.getProperty( name ); arguments.append( "\"-D" ).append( name ).append( "=" ).append( value ).append( "\" " ); } // append -Dmaven.repo.local if project group has a local repository LocalRepository repository = project.getProjectGroup().getLocalRepository(); if ( repository != null ) { arguments.append( "\"-Dmaven.repo.local=" ).append( StringUtils.clean( repository.getLocation() ) ).append( "\" " ); } arguments.append( StringUtils.clean( buildDefinition.getGoals() ) ); Map<String, String> environments = getEnvironments( buildDefinition ); String m1Home = environments.get( getInstallationService().getEnvVar( InstallationService.MAVEN1_TYPE ) ); if ( StringUtils.isNotEmpty( m1Home ) ) { executable = m1Home + File.separator + "bin" + File.separator + executable; setResolveExecutable( false ); } return executeShellCommand( project, executable, arguments.toString(), buildOutput, environments, null, null ); } protected Map<String, String> getEnvironments( BuildDefinition buildDefinition ) { Profile profile = buildDefinition.getProfile(); if ( profile == null ) { return Collections.EMPTY_MAP; } Map<String, String> envVars = new HashMap<String, String>(); String javaHome = getJavaHomeValue( buildDefinition ); if ( !StringUtils.isEmpty( javaHome ) ) { envVars.put( getInstallationService().getEnvVar( InstallationService.JDK_TYPE ), javaHome ); } Installation builder = profile.getBuilder(); if ( builder != null ) { envVars.put( getInstallationService().getEnvVar( InstallationService.MAVEN1_TYPE ), builder.getVarValue() ); } envVars.putAll( getEnvironmentVariables( buildDefinition ) ); return envVars; } public void updateProjectFromCheckOut( File workingDirectory, Project project, BuildDefinition buildDefinition, ScmResult scmResult ) throws ContinuumBuildExecutorException { File projectXmlFile = null; if ( buildDefinition != null ) { String buildFile = StringUtils.clean( buildDefinition.getBuildFile() ); if ( !StringUtils.isEmpty( buildFile ) ) { projectXmlFile = new File( workingDirectory, buildFile ); } } if ( projectXmlFile == null ) { projectXmlFile = new File( workingDirectory, "project.xml" ); } if ( !projectXmlFile.exists() ) { throw new ContinuumBuildExecutorException( "Could not find Maven project descriptor." ); } try { boolean update = isDescriptionUpdated( buildDefinition, scmResult, project ); metadataHelper.mapMetadata( new ContinuumProjectBuildingResult(), projectXmlFile, project, update ); } catch ( MavenOneMetadataHelperException e ) { throw new ContinuumBuildExecutorException( "Error while mapping metadata.", e ); } } }
5,130
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/execution/maven
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/execution/maven/m1/MavenOneMetadataHelper.java
package org.apache.maven.continuum.execution.maven.m1; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.project.builder.ContinuumProjectBuildingResult; import java.io.File; /** * @author <a href="mailto:trygvis@inamo.no">Trygve Laugst&oslash;l</a> */ public interface MavenOneMetadataHelper { String ROLE = MavenOneMetadataHelper.class.getName(); /** * @deprecated Use {@link #mapMetadata(ContinuumProjectBuildingResult, File, Project, boolean)} instead */ void mapMetadata( File metadata, Project project ) throws MavenOneMetadataHelperException; /** * @param result contains errors that happened during the process * @param metadata * @param project * @throws MavenOneMetadataHelperException * */ void mapMetadata( ContinuumProjectBuildingResult result, File metadata, Project project, boolean updateDefinition ) throws MavenOneMetadataHelperException; }
5,131
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/execution/maven
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/execution/maven/m2/MavenBuilderHelper.java
package org.apache.maven.continuum.execution.maven.m2; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.project.builder.ContinuumProjectBuildingResult; import org.apache.maven.project.MavenProject; import java.io.File; /** * @author <a href="mailto:jason@maven.org">Jason van Zyl</a> */ public interface MavenBuilderHelper { String ROLE = MavenBuilderHelper.class.getName(); void mapMetadataToProject( ContinuumProjectBuildingResult result, File metadata, Project project, boolean updateDefinition ); MavenProject getMavenProject( ContinuumProjectBuildingResult result, File file ); /** * @param result * @param mavenProject * @param continuumProject * @param updateDefinition */ void mapMavenProjectToContinuumProject( ContinuumProjectBuildingResult result, MavenProject mavenProject, Project continuumProject, boolean updateDefinition ); }
5,132
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/execution/maven
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/execution/maven/m2/DefaultMavenBuilderHelper.java
package org.apache.maven.continuum.execution.maven.m2; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.utils.m2.LocalRepositoryHelper; import org.apache.continuum.utils.m2.SettingsHelper; import org.apache.maven.artifact.manager.WagonManager; import org.apache.maven.artifact.resolver.ArtifactNotFoundException; import org.apache.maven.continuum.execution.SettingsConfigurationException; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.model.project.ProjectDependency; import org.apache.maven.continuum.model.project.ProjectDeveloper; import org.apache.maven.continuum.model.project.ProjectNotifier; import org.apache.maven.continuum.project.builder.ContinuumProjectBuildingResult; import org.apache.maven.model.Dependency; import org.apache.maven.model.Developer; import org.apache.maven.model.Extension; import org.apache.maven.model.Model; import org.apache.maven.model.Notifier; import org.apache.maven.model.Plugin; import org.apache.maven.model.Profile; import org.apache.maven.model.ReportPlugin; import org.apache.maven.model.Scm; import org.apache.maven.model.io.xpp3.MavenXpp3Writer; import org.apache.maven.profiles.DefaultProfileManager; import org.apache.maven.profiles.ProfileManager; import org.apache.maven.project.InvalidProjectModelException; import org.apache.maven.project.MavenProject; import org.apache.maven.project.MavenProjectBuilder; import org.apache.maven.project.ProjectBuildingException; import org.apache.maven.project.validation.ModelValidationResult; import org.apache.maven.settings.Mirror; import org.apache.maven.settings.Proxy; import org.apache.maven.settings.Server; import org.apache.maven.settings.Settings; import org.apache.maven.settings.io.xpp3.SettingsXpp3Writer; import org.codehaus.plexus.PlexusConstants; import org.codehaus.plexus.PlexusContainer; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; 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.Initializable; import org.codehaus.plexus.personality.plexus.lifecycle.phase.InitializationException; import org.codehaus.plexus.util.StringUtils; import org.codehaus.plexus.util.xml.Xpp3Dom; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.io.StringWriter; import java.util.ArrayList; import java.util.List; /** * @author <a href="mailto:trygvis@inamo.no">Trygve Laugst&oslash;l</a> * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a> */ @Component( role = org.apache.maven.continuum.execution.maven.m2.MavenBuilderHelper.class, hint = "default" ) public class DefaultMavenBuilderHelper implements MavenBuilderHelper, Contextualizable, Initializable { private static final Logger log = LoggerFactory.getLogger( DefaultMavenBuilderHelper.class ); @Requirement private MavenProjectBuilder projectBuilder; @Requirement private SettingsHelper settingsHelper; @Requirement private LocalRepositoryHelper localRepoHelper; private PlexusContainer container; // ---------------------------------------------------------------------- // MavenBuilderHelper Implementation // ---------------------------------------------------------------------- public void mapMetadataToProject( ContinuumProjectBuildingResult result, File metadata, Project continuumProject, boolean update ) { MavenProject mavenProject = getMavenProject( result, metadata ); if ( mavenProject == null ) { result.addError( ContinuumProjectBuildingResult.ERROR_UNKNOWN, "Can't load the maven project. Verify that your scm url is correct and remove/readd the project." ); return; } mapMavenProjectToContinuumProject( result, mavenProject, continuumProject, update ); } public void mapMavenProjectToContinuumProject( ContinuumProjectBuildingResult result, MavenProject mavenProject, Project continuumProject, boolean update ) { if ( mavenProject == null ) { result.addError( ContinuumProjectBuildingResult.ERROR_UNKNOWN, "The maven project is null." ); return; } if ( update ) { // ---------------------------------------------------------------------- // Name // ---------------------------------------------------------------------- continuumProject.setName( getProjectName( mavenProject ) ); // ---------------------------------------------------------------------- // Version // ---------------------------------------------------------------------- continuumProject.setVersion( getVersion( mavenProject ) ); // ---------------------------------------------------------------------- // Description // ---------------------------------------------------------------------- continuumProject.setDescription( mavenProject.getDescription() ); } // ---------------------------------------------------------------------- // SCM Url // ---------------------------------------------------------------------- // TODO: Remove this: scm url shouldn't be null there if ( StringUtils.isEmpty( continuumProject.getScmUrl() ) ) { String scmUrl = getScmUrl( mavenProject ); continuumProject.setScmUrl( scmUrl ); if ( !"HEAD".equals( mavenProject.getScm().getTag() ) ) { continuumProject.setScmTag( mavenProject.getScm().getTag() ); } } // ---------------------------------------------------------------------- // GroupId // ---------------------------------------------------------------------- if ( !StringUtils.isEmpty( mavenProject.getGroupId() ) ) { continuumProject.setGroupId( mavenProject.getGroupId() ); } else { result.addError( ContinuumProjectBuildingResult.ERROR_MISSING_GROUPID ); return; } // ---------------------------------------------------------------------- // artifactId // ---------------------------------------------------------------------- if ( !StringUtils.isEmpty( mavenProject.getArtifactId() ) ) { continuumProject.setArtifactId( mavenProject.getArtifactId() ); } else { result.addError( ContinuumProjectBuildingResult.ERROR_MISSING_ARTIFACTID ); return; } // ---------------------------------------------------------------------- // Project Url // ---------------------------------------------------------------------- if ( !StringUtils.isEmpty( mavenProject.getUrl() ) ) { continuumProject.setUrl( mavenProject.getUrl() ); } // ---------------------------------------------------------------------- // Developers // ---------------------------------------------------------------------- if ( mavenProject.getDevelopers() != null ) { List<ProjectDeveloper> developers = new ArrayList<ProjectDeveloper>(); for ( Developer d : (List<Developer>) mavenProject.getDevelopers() ) { ProjectDeveloper cd = new ProjectDeveloper(); cd.setScmId( d.getId() ); cd.setName( d.getName() ); cd.setEmail( d.getEmail() ); developers.add( cd ); } continuumProject.setDevelopers( developers ); } // ---------------------------------------------------------------------- // Parent // ---------------------------------------------------------------------- if ( mavenProject.getParent() != null ) { MavenProject parentProject = mavenProject.getParent(); ProjectDependency parent = new ProjectDependency(); parent.setGroupId( parentProject.getGroupId() ); parent.setArtifactId( parentProject.getArtifactId() ); parent.setVersion( parentProject.getVersion() ); continuumProject.setParent( parent ); } // ---------------------------------------------------------------------- // Dependencies // ---------------------------------------------------------------------- List<ProjectDependency> dependencies = new ArrayList<ProjectDependency>(); for ( Dependency dependency : (List<Dependency>) mavenProject.getDependencies() ) { ProjectDependency cd = new ProjectDependency(); cd.setGroupId( dependency.getGroupId() ); cd.setArtifactId( dependency.getArtifactId() ); cd.setVersion( dependency.getVersion() ); dependencies.add( cd ); } for ( Plugin dependency : (List<Plugin>) mavenProject.getBuildPlugins() ) { ProjectDependency cd = new ProjectDependency(); cd.setGroupId( dependency.getGroupId() ); cd.setArtifactId( dependency.getArtifactId() ); cd.setVersion( dependency.getVersion() ); dependencies.add( cd ); } for ( ReportPlugin dependency : (List<ReportPlugin>) mavenProject.getReportPlugins() ) { ProjectDependency cd = new ProjectDependency(); cd.setGroupId( dependency.getGroupId() ); cd.setArtifactId( dependency.getArtifactId() ); cd.setVersion( dependency.getVersion() ); dependencies.add( cd ); } for ( Extension dependency : (List<Extension>) mavenProject.getBuildExtensions() ) { ProjectDependency cd = new ProjectDependency(); cd.setGroupId( dependency.getGroupId() ); cd.setArtifactId( dependency.getArtifactId() ); cd.setVersion( dependency.getVersion() ); dependencies.add( cd ); } continuumProject.setDependencies( dependencies ); // ---------------------------------------------------------------------- // Notifiers // ---------------------------------------------------------------------- List<ProjectNotifier> userNotifiers = new ArrayList<ProjectNotifier>(); if ( continuumProject.getNotifiers() != null ) { for ( int i = 0; i < continuumProject.getNotifiers().size(); i++ ) { ProjectNotifier notifier = (ProjectNotifier) continuumProject.getNotifiers().get( i ); if ( notifier.isFromUser() ) { ProjectNotifier userNotifier = new ProjectNotifier(); userNotifier.setType( notifier.getType() ); userNotifier.setEnabled( notifier.isEnabled() ); userNotifier.setConfiguration( notifier.getConfiguration() ); userNotifier.setFrom( notifier.getFrom() ); userNotifier.setRecipientType( notifier.getRecipientType() ); userNotifier.setSendOnError( notifier.isSendOnError() ); userNotifier.setSendOnFailure( notifier.isSendOnFailure() ); userNotifier.setSendOnSuccess( notifier.isSendOnSuccess() ); userNotifier.setSendOnWarning( notifier.isSendOnWarning() ); userNotifier.setSendOnScmFailure( notifier.isSendOnScmFailure() ); userNotifiers.add( userNotifier ); } } } List<ProjectNotifier> notifiers = getNotifiers( result, mavenProject ); if ( notifiers != null ) { continuumProject.setNotifiers( notifiers ); } for ( ProjectNotifier notifier : userNotifiers ) { continuumProject.addNotifier( notifier ); } } public MavenProject getMavenProject( ContinuumProjectBuildingResult result, File file ) { MavenProject project; try { // TODO: This seems like code that is shared with DefaultMaven, so it should be moved to the project // builder perhaps Settings settings = settingsHelper.getSettings(); if ( log.isDebugEnabled() ) { writeSettings( settings ); } ProfileManager profileManager = new DefaultProfileManager( container, settings ); project = projectBuilder.build( file, localRepoHelper.getLocalRepository(), profileManager, true ); if ( log.isDebugEnabled() ) { writePom( project ); writeActiveProfileStatement( project ); } } catch ( ProjectBuildingException e ) { StringBuffer messages = new StringBuffer(); Throwable cause = e.getCause(); if ( cause != null ) { while ( ( cause.getCause() != null ) && ( cause instanceof ProjectBuildingException ) ) { cause = cause.getCause(); } } if ( e instanceof InvalidProjectModelException ) { InvalidProjectModelException ex = (InvalidProjectModelException) e; ModelValidationResult validationResult = ex.getValidationResult(); if ( validationResult != null && validationResult.getMessageCount() > 0 ) { for ( String valmsg : (List<String>) validationResult.getMessages() ) { result.addError( ContinuumProjectBuildingResult.ERROR_VALIDATION, valmsg ); messages.append( valmsg ); messages.append( "\n" ); } } } if ( cause instanceof ArtifactNotFoundException ) { result.addError( ContinuumProjectBuildingResult.ERROR_ARTIFACT_NOT_FOUND, ( cause ).toString() ); return null; } result.addError( ContinuumProjectBuildingResult.ERROR_PROJECT_BUILDING, e.getMessage() ); String msg = "Cannot build maven project from " + file + " (" + e.getMessage() + ").\n" + messages; log.error( msg ); return null; } // TODO catch all exceptions is bad catch ( Exception e ) { result.addError( ContinuumProjectBuildingResult.ERROR_PROJECT_BUILDING, e.getMessage() ); String msg = "Cannot build maven project from " + file + " (" + e.getMessage() + ")."; log.error( msg ); return null; } // ---------------------------------------------------------------------- // Validate the MavenProject using some Continuum rules // ---------------------------------------------------------------------- // SCM connection Scm scm = project.getScm(); if ( scm == null ) { result.addError( ContinuumProjectBuildingResult.ERROR_MISSING_SCM, getProjectName( project ) ); log.error( "Missing 'scm' element in the " + getProjectName( project ) + " POM." ); return null; } String url = scm.getConnection(); if ( StringUtils.isEmpty( url ) ) { result.addError( ContinuumProjectBuildingResult.ERROR_MISSING_SCM_CONNECTION, getProjectName( project ) ); log.error( "Missing 'connection' element in the 'scm' element in the " + getProjectName( project ) + " POM." ); return null; } return project; } // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- public String getProjectName( MavenProject project ) { String name = project.getName(); if ( StringUtils.isEmpty( name ) ) { return project.getId(); } return name; } private String getScmUrl( MavenProject project ) { return project.getScm().getConnection(); } private List<ProjectNotifier> getNotifiers( ContinuumProjectBuildingResult result, MavenProject mavenProject ) { List<ProjectNotifier> notifiers = new ArrayList<ProjectNotifier>(); if ( mavenProject.getCiManagement() != null && mavenProject.getCiManagement().getNotifiers() != null ) { for ( Notifier projectNotifier : (List<Notifier>) mavenProject.getCiManagement().getNotifiers() ) { ProjectNotifier notifier = new ProjectNotifier(); if ( StringUtils.isEmpty( projectNotifier.getType() ) ) { result.addError( ContinuumProjectBuildingResult.ERROR_MISSING_NOTIFIER_TYPE ); return null; } notifier.setType( projectNotifier.getType() ); if ( projectNotifier.getConfiguration() == null ) { result.addError( ContinuumProjectBuildingResult.ERROR_MISSING_NOTIFIER_CONFIGURATION ); return null; } notifier.setConfiguration( projectNotifier.getConfiguration() ); notifier.setFrom( ProjectNotifier.FROM_PROJECT ); notifier.setSendOnSuccess( projectNotifier.isSendOnSuccess() ); notifier.setSendOnFailure( projectNotifier.isSendOnFailure() ); notifier.setSendOnError( projectNotifier.isSendOnError() ); notifier.setSendOnWarning( projectNotifier.isSendOnWarning() ); notifier.setSendOnScmFailure( false ); notifiers.add( notifier ); } } return notifiers; } private String getVersion( MavenProject project ) { return project.getVersion(); } // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- private void writeSettings( Settings settings ) { StringWriter sWriter = new StringWriter(); SettingsXpp3Writer settingsWriter = new SettingsXpp3Writer(); try { settingsWriter.write( sWriter, settings ); StringBuffer message = new StringBuffer(); message.append( "\n************************************************************************************" ); message.append( "\nEffective Settings" ); message.append( "\n************************************************************************************" ); message.append( "\n" ); message.append( sWriter.toString() ); message.append( "\n************************************************************************************" ); message.append( "\n\n" ); log.debug( message.toString() ); } catch ( IOException e ) { log.warn( "Cannot serialize Settings to XML.", e ); } } private void writePom( MavenProject project ) { StringBuffer message = new StringBuffer(); Model pom = project.getModel(); StringWriter sWriter = new StringWriter(); MavenXpp3Writer pomWriter = new MavenXpp3Writer(); try { pomWriter.write( sWriter, pom ); message.append( "\n************************************************************************************" ); message.append( "\nEffective POM for project \'" ).append( project.getId() ).append( "\'" ); message.append( "\n************************************************************************************" ); message.append( "\n" ); message.append( sWriter.toString() ); message.append( "\n************************************************************************************" ); message.append( "\n\n" ); log.debug( message.toString() ); } catch ( IOException e ) { log.warn( "Cannot serialize POM to XML.", e ); } } private void writeActiveProfileStatement( MavenProject project ) { List<Profile> profiles = project.getActiveProfiles(); StringBuffer message = new StringBuffer(); message.append( "\n" ); message.append( "\n************************************************************************************" ); message.append( "\nActive Profiles for Project \'" ).append( project.getId() ).append( "\'" ); message.append( "\n************************************************************************************" ); message.append( "\n" ); if ( profiles == null || profiles.isEmpty() ) { message.append( "There are no active profiles." ); } else { message.append( "The following profiles are active:\n" ); for ( Profile profile : profiles ) { message.append( "\n - " ).append( profile.getId() ).append( " (source: " ).append( profile.getSource() ).append( ")" ); } } message.append( "\n************************************************************************************" ); message.append( "\n\n" ); log.debug( message.toString() ); } /** * @todo [BP] this might not be required if there is a better way to pass * them in. It doesn't feel quite right. * @todo [JC] we should at least provide a mapping of protocol-to-proxy for * the wagons, shouldn't we? */ private void resolveParameters( Settings settings ) throws ComponentLookupException, ComponentLifecycleException, SettingsConfigurationException { WagonManager wagonManager = (WagonManager) container.lookup( WagonManager.ROLE ); try { Proxy proxy = settings.getActiveProxy(); if ( proxy != null ) { if ( proxy.getHost() == null ) { throw new SettingsConfigurationException( "Proxy in settings.xml has no host" ); } wagonManager.addProxy( proxy.getProtocol(), proxy.getHost(), proxy.getPort(), proxy.getUsername(), proxy.getPassword(), proxy.getNonProxyHosts() ); } for ( Server server : (List<Server>) settings.getServers() ) { wagonManager.addAuthenticationInfo( server.getId(), server.getUsername(), server.getPassword(), server.getPrivateKey(), server.getPassphrase() ); wagonManager.addPermissionInfo( server.getId(), server.getFilePermissions(), server.getDirectoryPermissions() ); if ( server.getConfiguration() != null ) { wagonManager.addConfiguration( server.getId(), (Xpp3Dom) server.getConfiguration() ); } } for ( Mirror mirror : (List<Mirror>) settings.getMirrors() ) { wagonManager.addMirror( mirror.getId(), mirror.getMirrorOf(), mirror.getUrl() ); } } finally { container.release( wagonManager ); } } // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- public void contextualize( Context context ) throws ContextException { container = (PlexusContainer) context.get( PlexusConstants.PLEXUS_KEY ); } public void initialize() throws InitializationException { try { Settings settings = settingsHelper.getSettings(); resolveParameters( settings ); } catch ( Exception e ) { throw new InitializationException( "Can't initialize '" + getClass().getName() + "'", e ); } } }
5,133
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/execution/maven
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/execution/maven/m2/MavenTwoBuildExecutor.java
package org.apache.maven.continuum.execution.maven.m2; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.model.repository.LocalRepository; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.metadata.ArtifactMetadata; import org.apache.maven.continuum.configuration.ConfigurationException; import org.apache.maven.continuum.configuration.ConfigurationService; import org.apache.maven.continuum.execution.AbstractBuildExecutor; import org.apache.maven.continuum.execution.ContinuumBuildExecutionResult; import org.apache.maven.continuum.execution.ContinuumBuildExecutor; import org.apache.maven.continuum.execution.ContinuumBuildExecutorConstants; import org.apache.maven.continuum.execution.ContinuumBuildExecutorException; import org.apache.maven.continuum.execution.shared.JUnitReportArchiver; import org.apache.maven.continuum.installation.InstallationService; import org.apache.maven.continuum.model.project.BuildDefinition; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.model.scm.ChangeFile; import org.apache.maven.continuum.model.scm.ChangeSet; import org.apache.maven.continuum.model.scm.ScmResult; import org.apache.maven.continuum.model.system.Installation; import org.apache.maven.continuum.model.system.Profile; import org.apache.maven.continuum.project.builder.ContinuumProjectBuildingResult; import org.apache.maven.project.MavenProject; import org.apache.maven.project.MavenProjectHelper; import org.apache.maven.project.artifact.ProjectArtifactMetadata; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.util.StringUtils; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; /** * @author <a href="mailto:trygvis@inamo.no">Trygve Laugst&oslash;l</a> */ public class MavenTwoBuildExecutor extends AbstractBuildExecutor implements ContinuumBuildExecutor { // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- public static final String CONFIGURATION_GOALS = "goals"; public static final String ID = ContinuumBuildExecutorConstants.MAVEN_TWO_BUILD_EXECUTOR; // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- @Requirement private MavenBuilderHelper builderHelper; @Requirement private MavenProjectHelper projectHelper; @Requirement private ConfigurationService configurationService; @Requirement private JUnitReportArchiver testReportArchiver; // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- public MavenTwoBuildExecutor() { super( ID, true ); } public MavenBuilderHelper getBuilderHelper() { return builderHelper; } public void setBuilderHelper( MavenBuilderHelper builderHelper ) { this.builderHelper = builderHelper; } public MavenProjectHelper getProjectHelper() { return projectHelper; } public void setProjectHelper( MavenProjectHelper projectHelper ) { this.projectHelper = projectHelper; } public ConfigurationService getConfigurationService() { return configurationService; } public void setConfigurationService( ConfigurationService configurationService ) { this.configurationService = configurationService; } public void setTestReportArchiver( JUnitReportArchiver testReportArchiver ) { this.testReportArchiver = testReportArchiver; } // ---------------------------------------------------------------------- // ContinuumBuilder Implementation // ---------------------------------------------------------------------- public ContinuumBuildExecutionResult build( Project project, BuildDefinition buildDefinition, File buildOutput, List<Project> projectsWithCommonScmRoot, String projectScmRootUrl ) throws ContinuumBuildExecutorException { String executable = getInstallationService().getExecutorConfigurator( InstallationService.MAVEN2_TYPE ).getExecutable(); StringBuffer arguments = new StringBuffer(); String buildFile = getBuildFileForProject( project, buildDefinition ); if ( !StringUtils.isEmpty( buildFile ) && !"pom.xml".equals( buildFile ) ) { arguments.append( "-f " ).append( buildFile ).append( " " ); } arguments.append( StringUtils.clean( buildDefinition.getArguments() ) ).append( " " ); Properties props = getContinuumSystemProperties( project ); for ( Enumeration itr = props.propertyNames(); itr.hasMoreElements(); ) { String name = (String) itr.nextElement(); String value = props.getProperty( name ); arguments.append( "\"-D" ).append( name ).append( "=" ).append( value ).append( "\" " ); } // append -Dmaven.repo.local if project group has a local repository LocalRepository repository = project.getProjectGroup().getLocalRepository(); if ( repository != null ) { arguments.append( "\"-Dmaven.repo.local=" ).append( StringUtils.clean( repository.getLocation() ) ).append( "\" " ); } arguments.append( StringUtils.clean( buildDefinition.getGoals() ) ); Map<String, String> environments = getEnvironments( buildDefinition ); String m2Home = environments.get( getInstallationService().getEnvVar( InstallationService.MAVEN2_TYPE ) ); if ( StringUtils.isNotEmpty( m2Home ) ) { executable = m2Home + File.separator + "bin" + File.separator + executable; setResolveExecutable( false ); } return executeShellCommand( project, executable, arguments.toString(), buildOutput, environments, null, null ); } public void updateProjectFromCheckOut( File workingDirectory, Project project, BuildDefinition buildDefinition, ScmResult scmResult ) throws ContinuumBuildExecutorException { File f = getPomFile( getBuildFileForProject( project, buildDefinition ), workingDirectory ); if ( !f.exists() ) { throw new ContinuumBuildExecutorException( "Could not find Maven project descriptor." ); } ContinuumProjectBuildingResult result = new ContinuumProjectBuildingResult(); boolean update = isDescriptionUpdated( buildDefinition, scmResult, project ); builderHelper.mapMetadataToProject( result, f, project, update ); if ( result.hasErrors() ) { throw new ContinuumBuildExecutorException( "Error while mapping metadata:" + result.getErrorsAsString() ); } } private static File getPomFile( String projectBuildFile, File workingDirectory ) { File f = null; String buildFile = StringUtils.clean( projectBuildFile ); if ( !StringUtils.isEmpty( buildFile ) ) { f = new File( workingDirectory, buildFile ); } if ( f == null ) { f = new File( workingDirectory, "pom.xml" ); } return f; } @Override public List<Artifact> getDeployableArtifacts( Project continuumProject, File workingDirectory, BuildDefinition buildDefinition ) throws ContinuumBuildExecutorException { MavenProject project = getMavenProject( continuumProject, workingDirectory, buildDefinition ); // Maven could help us out a lot more here by knowing how to get the deployment artifacts from a project. // TODO: this is currently quite lame Artifact artifact = project.getArtifact(); String projectPackaging = project.getPackaging(); boolean isPomArtifact = "pom".equals( projectPackaging ); if ( isPomArtifact ) { artifact.setFile( project.getFile() ); } else { // Attach pom ArtifactMetadata metadata = new ProjectArtifactMetadata( artifact, project.getFile() ); artifact.addMetadata( metadata ); String finalName = project.getBuild().getFinalName(); String filename = finalName + "." + artifact.getArtifactHandler().getExtension(); String buildDirectory = project.getBuild().getDirectory(); File artifactFile = new File( buildDirectory, filename ); artifact.setFile( artifactFile ); // sources jar File sourcesFile = new File( buildDirectory, finalName + "-sources.jar" ); if ( sourcesFile.exists() ) { projectHelper.attachArtifact( project, "java-source", "sources", sourcesFile ); } // tests sources jar File testsSourcesFile = new File( buildDirectory, finalName + "-test-sources.jar" ); if ( testsSourcesFile.exists() ) { projectHelper.attachArtifact( project, "java-source", "test-sources", testsSourcesFile ); } // javadoc jar File javadocFile = new File( buildDirectory, finalName + "-javadoc.jar" ); if ( javadocFile.exists() ) { projectHelper.attachArtifact( project, "javadoc", "javadoc", javadocFile ); } // client jar File clientFile = new File( buildDirectory, finalName + "-client.jar" ); if ( clientFile.exists() ) { projectHelper.attachArtifact( project, projectPackaging + "-client", "client", clientFile ); } // Tests jar File testsFile = new File( buildDirectory, finalName + "-tests.jar" ); if ( testsFile.exists() ) { projectHelper.attachArtifact( project, "jar", "tests", testsFile ); } } List<Artifact> attachedArtifacts = project.getAttachedArtifacts(); List<Artifact> artifacts = new ArrayList<Artifact>( attachedArtifacts.size() + 1 ); if ( artifact.getFile().exists() ) { artifacts.add( artifact ); } for ( Artifact attachedArtifact : attachedArtifacts ) { artifacts.add( attachedArtifact ); } return artifacts; } private MavenProject getMavenProject( Project continuumProject, File workingDirectory, BuildDefinition buildDefinition ) throws ContinuumBuildExecutorException { ContinuumProjectBuildingResult result = new ContinuumProjectBuildingResult(); File f = getPomFile( getBuildFileForProject( continuumProject, buildDefinition ), workingDirectory ); if ( !f.exists() ) { throw new ContinuumBuildExecutorException( "Could not find Maven project descriptor '" + f + "'." ); } MavenProject project = builderHelper.getMavenProject( result, f ); if ( result.hasErrors() ) { throw new ContinuumBuildExecutorException( "Unable to read the Maven project descriptor '" + f + "': " + result.getErrorsAsString() ); } return project; } @Override public void backupTestFiles( Project project, int buildId, String projectScmRootUrl, List<Project> projectsWithCommonScmRoot ) { File backupDirectory = null; try { backupDirectory = configurationService.getTestReportsDirectory( buildId, project.getId() ); testReportArchiver.archiveReports( getWorkingDirectory( project, projectScmRootUrl, projectsWithCommonScmRoot ), backupDirectory ); } catch ( ConfigurationException e ) { log.error( "failed to get backup directory", e ); } catch ( IOException e ) { log.warn( "failed to copy test results to backup directory", e ); } } /** * @return true if changes are in the current project, not only in sub-modules and in non-recursive mode * @see org.apache.maven.continuum.execution.ContinuumBuildExecutor#shouldBuild(java.util.List, org.apache.maven.continuum.model.project.Project, java.io.File, org.apache.maven.continuum.model.project.BuildDefinition) */ @Override public boolean shouldBuild( List<ChangeSet> changes, Project continuumProject, File workingDirectory, BuildDefinition buildDefinition ) throws ContinuumBuildExecutorException { //Check if it's a recursive build boolean isRecursive = false; if ( StringUtils.isNotEmpty( buildDefinition.getArguments() ) ) { isRecursive = buildDefinition.getArguments().indexOf( "-N" ) < 0 && buildDefinition.getArguments().indexOf( "--non-recursive" ) < 0; } if ( isRecursive && changes != null && !changes.isEmpty() ) { if ( log.isInfoEnabled() ) { log.info( "recursive build and changes found --> building" ); } return true; } MavenProject project = getMavenProject( continuumProject, workingDirectory, buildDefinition ); if ( changes == null || changes.isEmpty() ) { if ( log.isInfoEnabled() ) { log.info( "Found no changes, not building" ); } return false; } //check if changes are only in sub-modules or not List<String> modules = project.getModules(); List<ChangeFile> files = new ArrayList<ChangeFile>(); for ( ChangeSet changeSet : changes ) { files.addAll( changeSet.getFiles() ); } int i = 0; while ( i <= files.size() - 1 ) { ChangeFile file = files.get( i ); if ( log.isDebugEnabled() ) { log.debug( "changeFile.name " + file.getName() ); log.debug( "check in modules " + modules ); } boolean found = false; for ( String module : modules ) { if ( file.getName().indexOf( module ) >= 0 ) { if ( log.isDebugEnabled() ) { log.debug( "changeFile.name " + file.getName() + " removed because in a module" ); } files.remove( file ); found = true; break; } if ( log.isDebugEnabled() ) { log.debug( "no remving file " + file.getName() + " not in module " + module ); } } if ( !found ) { i++; } } boolean shouldBuild = !files.isEmpty(); if ( !shouldBuild ) { log.info( "Changes are only in sub-modules." ); } if ( log.isDebugEnabled() ) { log.debug( "shoulbuild = " + shouldBuild ); } return shouldBuild; } @Override protected Map<String, String> getEnvironments( BuildDefinition buildDefinition ) { Profile profile = buildDefinition.getProfile(); if ( profile == null ) { return Collections.EMPTY_MAP; } Map<String, String> envVars = new HashMap<String, String>(); String javaHome = getJavaHomeValue( buildDefinition ); if ( !StringUtils.isEmpty( javaHome ) ) { envVars.put( getInstallationService().getEnvVar( InstallationService.JDK_TYPE ), javaHome ); } Installation builder = profile.getBuilder(); if ( builder != null ) { envVars.put( getInstallationService().getEnvVar( InstallationService.MAVEN2_TYPE ), builder.getVarValue() ); } envVars.putAll( getEnvironmentVariables( buildDefinition ) ); return envVars; } }
5,134
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/execution/maven
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/execution/maven/m2/MavenBuilderHelperException.java
package org.apache.maven.continuum.execution.maven.m2; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /** * @author <a href="mailto:trygvis@inamo.no">Trygve Laugst&oslash;l</a> */ public class MavenBuilderHelperException extends Exception { public MavenBuilderHelperException( String message ) { super( message ); } public MavenBuilderHelperException( String message, Throwable cause ) { super( message, cause ); } }
5,135
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/execution
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/execution/shared/JUnitReportArchiver.java
package org.apache.maven.continuum.execution.shared; import org.apache.continuum.utils.file.FileSystemManager; import org.codehaus.plexus.util.DirectoryScanner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; public class JUnitReportArchiver { private static Logger log = LoggerFactory.getLogger( JUnitReportArchiver.class ); private String[] includeFiles = {}; private String[] excludeFiles = {}; private FileSystemManager fsManager; public void setIncludeFiles( String[] includeFiles ) { this.includeFiles = includeFiles; } public void setExcludeFiles( String[] excludeFiles ) { this.excludeFiles = excludeFiles; } public void setFileSystemManager( FileSystemManager fsManager ) { this.fsManager = fsManager; } public String[] findReports( File workingDir ) { DirectoryScanner scanner = new DirectoryScanner(); scanner.setBasedir( workingDir ); scanner.setIncludes( includeFiles ); scanner.setExcludes( excludeFiles ); scanner.scan(); return scanner.getIncludedFiles(); } public void archiveReports( File workingDir, File backupDir ) throws IOException { String[] testResultFiles = findReports( workingDir ); if ( testResultFiles.length > 0 ) { log.info( "Backing up {} test reports", testResultFiles.length ); } for ( String testResultFile : testResultFiles ) { File xmlFile = new File( workingDir, testResultFile ); if ( backupDir != null ) { fsManager.copyFileToDir( xmlFile, backupDir ); } } } }
5,136
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/execution
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/execution/manager/BuildExecutorManager.java
package org.apache.maven.continuum.execution.manager; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.maven.continuum.ContinuumException; import org.apache.maven.continuum.execution.ContinuumBuildExecutor; /** * @author <a href="mailto:trygvis@inamo.no">Trygve Laugst&oslash;l</a> */ public interface BuildExecutorManager { String ROLE = BuildExecutorManager.class.getName(); ContinuumBuildExecutor getBuildExecutor( String executorId ) throws ContinuumException; boolean hasBuildExecutor( String executorId ); }
5,137
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/execution
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/execution/manager/BuildExecutorNotFoundException.java
package org.apache.maven.continuum.execution.manager; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /** * @author <a href="mailto:jason@maven.org">Jason van Zyl</a> */ public class BuildExecutorNotFoundException extends Exception { private static final long serialVersionUID = 2709593430202284107L; public BuildExecutorNotFoundException( String message ) { super( message ); } }
5,138
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/execution
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/execution/manager/DefaultBuildExecutorManager.java
package org.apache.maven.continuum.execution.manager; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.maven.continuum.ContinuumException; import org.apache.maven.continuum.execution.ContinuumBuildExecutor; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.personality.plexus.lifecycle.phase.Initializable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.Map; /** * @author <a href="mailto:trygvis@inamo.no">Trygve Laugst&oslash;l</a> */ @Component( role = org.apache.maven.continuum.execution.manager.BuildExecutorManager.class, hint = "default" ) public class DefaultBuildExecutorManager implements BuildExecutorManager, Initializable { private static final Logger log = LoggerFactory.getLogger( DefaultBuildExecutorManager.class ); @Requirement( role = org.apache.maven.continuum.execution.ContinuumBuildExecutor.class ) private Map<String, ContinuumBuildExecutor> executors; // ---------------------------------------------------------------------- // Component Lifecycle // ---------------------------------------------------------------------- public void initialize() { if ( executors == null ) { executors = new HashMap<String, ContinuumBuildExecutor>(); } if ( executors.size() == 0 ) { log.warn( "No build executors defined." ); } else { log.info( "Build executors:" ); for ( String key : executors.keySet() ) { log.info( " " + key ); } } } // ---------------------------------------------------------------------- // BuildExecutorManager Implementation // ---------------------------------------------------------------------- public ContinuumBuildExecutor getBuildExecutor( String builderType ) throws ContinuumException { ContinuumBuildExecutor executor = executors.get( builderType ); if ( executor == null ) { throw new ContinuumException( "No such executor: '" + builderType + "'." ); } return executor; } public boolean hasBuildExecutor( String executorId ) { return executors.containsKey( executorId ); } }
5,139
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/buildqueue
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/buildqueue/evaluator/BuildProjectTaskViabilityEvaluator.java
package org.apache.maven.continuum.buildqueue.evaluator; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.taskqueue.BuildProjectTask; import org.apache.maven.continuum.project.ContinuumProjectState; import org.codehaus.plexus.component.annotations.Configuration; import org.codehaus.plexus.taskqueue.TaskViabilityEvaluator; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author <a href="mailto:trygvis@inamo.no">Trygve Laugst&oslash;l</a> */ public class BuildProjectTaskViabilityEvaluator implements TaskViabilityEvaluator { @Configuration( "" ) private long requiredBuildInterval; // ---------------------------------------------------------------------- // TaskViabilityEvaluator Implementation // ---------------------------------------------------------------------- /** * Removes duplicate tasks from the list. A duplicate task is one with the same * build definition and that's scheduled within the required build interval. * <p/> * <p/> * &forall; <sub>t1, t2 &isin; tasks</sub> [ t1 &ne; t2 &and; t2.buildDefinition = t2.buildDefinition]: * if ( t2.timestamp - t1.timestamp < requiredBuildInterval ) remove( t2 ). * </p> * * @param tasks A list of queued tasks to evaluate * @return a list of tasks with duplicates removed */ public Collection<BuildProjectTask> evaluate( Collection tasks ) { // ---------------------------------------------------------------------- // This code makes a Map with Lists with one list per project. For each // task in the list it puts it in the list for the project that's // requested for a build. Then all each of the lists with tasks is // checked for validity and a list of tasks to remove is returned. // ---------------------------------------------------------------------- Map<Integer, List<BuildProjectTask>> projects = new HashMap<Integer, List<BuildProjectTask>>(); for ( BuildProjectTask task : (Collection<BuildProjectTask>) tasks ) { int key = task.getProjectId(); List<BuildProjectTask> projectTasks = projects.get( key ); if ( projectTasks == null ) { projectTasks = new ArrayList<BuildProjectTask>(); projects.put( key, projectTasks ); } projectTasks.add( task ); } List<BuildProjectTask> toBeRemoved = new ArrayList<BuildProjectTask>(); for ( List<BuildProjectTask> projectTasks : projects.values() ) { toBeRemoved.addAll( checkTasks( projectTasks ) ); } return toBeRemoved; } // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- private List<BuildProjectTask> checkTasks( List<BuildProjectTask> list ) { List<BuildProjectTask> toBeRemoved = new ArrayList<BuildProjectTask>(); for ( BuildProjectTask buildProjectTask : list ) { for ( BuildProjectTask task : list ) { // check if it's the same task if ( buildProjectTask == task || buildProjectTask.getBuildDefinitionId() != task.getBuildDefinitionId() ) { continue; } // ---------------------------------------------------------------------- // If this build is forces, don't remove it // ---------------------------------------------------------------------- if ( task.getBuildTrigger().getTrigger() == ContinuumProjectState.TRIGGER_FORCED ) { continue; } // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- long interval = task.getTimestamp() - buildProjectTask.getTimestamp(); if ( interval < requiredBuildInterval ) { toBeRemoved.add( buildProjectTask ); } } } return toBeRemoved; } }
5,140
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/builddefinition/DefaultBuildDefinitionService.java
package org.apache.maven.continuum.builddefinition; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.buildqueue.BuildQueueServiceException; import org.apache.continuum.configuration.ContinuumConfigurationException; import org.apache.continuum.dao.BuildDefinitionDao; import org.apache.continuum.dao.BuildDefinitionTemplateDao; import org.apache.continuum.dao.ProjectDao; import org.apache.continuum.dao.ProjectGroupDao; import org.apache.maven.continuum.configuration.ConfigurationLoadingException; import org.apache.maven.continuum.configuration.ConfigurationService; import org.apache.maven.continuum.execution.ContinuumBuildExecutorConstants; import org.apache.maven.continuum.model.project.BuildDefinition; import org.apache.maven.continuum.model.project.BuildDefinitionTemplate; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.model.project.ProjectGroup; import org.apache.maven.continuum.model.project.Schedule; import org.apache.maven.continuum.store.ContinuumObjectNotFoundException; import org.apache.maven.continuum.store.ContinuumStoreException; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Configuration; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.personality.plexus.lifecycle.phase.Initializable; import org.codehaus.plexus.personality.plexus.lifecycle.phase.InitializationException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; /** * @author <a href="mailto:olamy@apache.org">olamy</a> * @TODO some cache mechanism ? * @since 15 sept. 07 */ @Component( role = org.apache.maven.continuum.builddefinition.BuildDefinitionService.class ) public class DefaultBuildDefinitionService implements BuildDefinitionService, Initializable { private static final Logger log = LoggerFactory.getLogger( DefaultBuildDefinitionService.class ); @Configuration( "" ) private String defaultAntGoals; @Configuration( "" ) private String defaultAntArguments; @Configuration( "clean:clean jar:install" ) private String defaultM1Goals; @Configuration( "" ) private String defaultM1Arguments; @Configuration( "clean install" ) private String defaultM2Goals; @Configuration( "--batch-mode --non-recursive" ) private String defaultM2Arguments; @Requirement private BuildDefinitionDao buildDefinitionDao; @Requirement private BuildDefinitionTemplateDao buildDefinitionTemplateDao; @Requirement private ProjectDao projectDao; @Requirement private ProjectGroupDao projectGroupDao; @Requirement( hint = "default" ) private ConfigurationService configurationService; // ----------------------------------------------- // Plexus Lifecycle // ----------------------------------------------- public void initialize() throws InitializationException { try { initializeDefaultContinuumBuildDefintions(); } catch ( BuildDefinitionServiceException e ) { throw new InitializationException( e.getMessage(), e ); } } private void initializeDefaultContinuumBuildDefintions() throws BuildDefinitionServiceException { this.getDefaultAntBuildDefinitionTemplate(); this.getDefaultMavenOneBuildDefinitionTemplate(); this.getDefaultMavenTwoBuildDefinitionTemplate(); this.getDefaultShellBuildDefinitionTemplate(); } public BuildDefinition getBuildDefinition( int buildDefinitionId ) throws BuildDefinitionServiceException { try { return buildDefinitionDao.getBuildDefinition( buildDefinitionId ); } catch ( ContinuumObjectNotFoundException e ) { return null; } catch ( ContinuumStoreException e ) { throw new BuildDefinitionServiceException( e.getMessage(), e ); } } public BuildDefinition addBuildDefinition( BuildDefinition buildDefinition ) throws BuildDefinitionServiceException { try { return buildDefinitionDao.addBuildDefinition( buildDefinition ); } catch ( ContinuumStoreException e ) { throw new BuildDefinitionServiceException( e.getMessage(), e ); } } public void removeBuildDefinition( BuildDefinition buildDefinition ) throws BuildDefinitionServiceException { try { buildDefinitionDao.removeBuildDefinition( buildDefinition ); } catch ( ContinuumStoreException e ) { throw new BuildDefinitionServiceException( e.getMessage(), e ); } } public void updateBuildDefinition( BuildDefinition buildDefinition ) throws BuildDefinitionServiceException { try { BuildDefinition storedBuildDefinition = buildDefinitionDao.getBuildDefinition( buildDefinition.getId() ); storedBuildDefinition.setBuildFresh( buildDefinition.isBuildFresh() ); storedBuildDefinition.setAlwaysBuild( buildDefinition.isAlwaysBuild() ); storedBuildDefinition.setArguments( buildDefinition.getArguments() ); storedBuildDefinition.setBuildFile( buildDefinition.getBuildFile() ); storedBuildDefinition.setDefaultForProject( buildDefinition.isDefaultForProject() ); storedBuildDefinition.setDescription( buildDefinition.getDescription() ); storedBuildDefinition.setGoals( buildDefinition.getGoals() ); storedBuildDefinition.setProfile( buildDefinition.getProfile() ); storedBuildDefinition.setSchedule( buildDefinition.getSchedule() ); storedBuildDefinition.setType( buildDefinition.getType() ); storedBuildDefinition.setUpdatePolicy( buildDefinition.getUpdatePolicy() ); buildDefinitionDao.storeBuildDefinition( storedBuildDefinition ); } catch ( ContinuumStoreException e ) { throw new BuildDefinitionServiceException( e.getMessage(), e ); } } public List<BuildDefinition> getAllBuildDefinitions() throws BuildDefinitionServiceException { try { return buildDefinitionDao.getAllBuildDefinitions(); } catch ( ContinuumStoreException e ) { throw new BuildDefinitionServiceException( e.getMessage(), e ); } } public List<BuildDefinition> getAllTemplates() throws BuildDefinitionServiceException { try { return buildDefinitionDao.getAllTemplates(); } catch ( ContinuumStoreException e ) { throw new BuildDefinitionServiceException( e.getMessage(), e ); } } /** * @see org.apache.maven.continuum.builddefinition.BuildDefinitionService#cloneBuildDefinition(org.apache.maven.continuum.model.project.BuildDefinition) */ public BuildDefinition cloneBuildDefinition( BuildDefinition buildDefinition ) { BuildDefinition cloned = new BuildDefinition(); cloned.setAlwaysBuild( buildDefinition.isAlwaysBuild() ); cloned.setArguments( buildDefinition.getArguments() ); cloned.setBuildFile( buildDefinition.getBuildFile() ); cloned.setBuildFresh( buildDefinition.isBuildFresh() ); cloned.setDefaultForProject( buildDefinition.isDefaultForProject() ); cloned.setDescription( buildDefinition.getDescription() ); cloned.setGoals( buildDefinition.getGoals() ); cloned.setProfile( buildDefinition.getProfile() ); cloned.setSchedule( buildDefinition.getSchedule() ); cloned.setType( buildDefinition.getType() ); cloned.setTemplate( buildDefinition.isTemplate() ); cloned.setUpdatePolicy( buildDefinition.getUpdatePolicy() ); return cloned; } public boolean isBuildDefinitionInUse( BuildDefinition buildDefinition ) throws BuildDefinitionServiceException { boolean inUse = false; List<BuildDefinitionTemplate> buildDefinitionTemplates = getAllBuildDefinitionTemplate(); for ( BuildDefinitionTemplate template : buildDefinitionTemplates ) { for ( BuildDefinition definition : (List<BuildDefinition>) template.getBuildDefinitions() ) { if ( buildDefinition.getId() == definition.getId() ) { inUse = true; break; } } if ( inUse ) { break; } } return inUse; } public BuildDefinitionTemplate getContinuumDefaultWithType( String type ) throws BuildDefinitionServiceException { try { return buildDefinitionTemplateDao.getContinuumBuildDefinitionTemplateWithType( type ); } catch ( ContinuumStoreException e ) { throw new BuildDefinitionServiceException( e.getMessage(), e ); } } public BuildDefinitionTemplate getDefaultAntBuildDefinitionTemplate() throws BuildDefinitionServiceException { BuildDefinitionTemplate template = getContinuumDefaultWithType( ContinuumBuildExecutorConstants.ANT_BUILD_EXECUTOR ); if ( template != null ) { return template; } log.info( "create default AntBuildDefinitionTemplate" ); template = new BuildDefinitionTemplate(); template.setContinuumDefault( true ); template.setName( "Default Ant Template" ); template.setType( ContinuumBuildExecutorConstants.ANT_BUILD_EXECUTOR ); template = addBuildDefinitionTemplate( template ); BuildDefinition bd = new BuildDefinition(); bd.setDefaultForProject( true ); bd.setGoals( defaultAntGoals ); bd.setArguments( defaultAntArguments ); bd.setBuildFile( "build.xml" ); bd.setSchedule( getDefaultSchedule() ); bd.setDescription( "Default Ant Build Definition" ); bd.setTemplate( true ); bd.setType( ContinuumBuildExecutorConstants.ANT_BUILD_EXECUTOR ); return addBuildDefinitionInTemplate( template, bd, true ); } public BuildDefinitionTemplate getDefaultMavenOneBuildDefinitionTemplate() throws BuildDefinitionServiceException { BuildDefinitionTemplate template = getContinuumDefaultWithType( ContinuumBuildExecutorConstants.MAVEN_ONE_BUILD_EXECUTOR ); if ( template != null ) { log.debug( "found default maven template " + template.getType() ); return template; } log.info( "create default MavenOneBuildDefinitionTemplate" ); template = new BuildDefinitionTemplate(); template.setContinuumDefault( true ); template.setName( "Default Maven 1 Template" ); template.setType( ContinuumBuildExecutorConstants.MAVEN_ONE_BUILD_EXECUTOR ); template = addBuildDefinitionTemplate( template ); BuildDefinition bd = new BuildDefinition(); bd.setDefaultForProject( true ); bd.setArguments( defaultM1Arguments ); bd.setGoals( defaultM1Goals ); bd.setBuildFile( "project.xml" ); bd.setSchedule( getDefaultSchedule() ); bd.setType( ContinuumBuildExecutorConstants.MAVEN_ONE_BUILD_EXECUTOR ); bd.setDescription( "Default Maven 1 Build Definition" ); bd.setTemplate( true ); return addBuildDefinitionInTemplate( template, bd, true ); } public BuildDefinitionTemplate getDefaultMavenTwoBuildDefinitionTemplate() throws BuildDefinitionServiceException { BuildDefinitionTemplate template = getContinuumDefaultWithType( ContinuumBuildExecutorConstants.MAVEN_TWO_BUILD_EXECUTOR ); if ( template != null ) { return template; } log.info( "create default MavenTwoBuildDefinitionTemplate" ); template = new BuildDefinitionTemplate(); template.setContinuumDefault( true ); template.setName( "Default Maven Template" ); template.setType( ContinuumBuildExecutorConstants.MAVEN_TWO_BUILD_EXECUTOR ); template = addBuildDefinitionTemplate( template ); BuildDefinition bd = new BuildDefinition(); bd.setDefaultForProject( true ); bd.setGoals( this.defaultM2Goals ); bd.setArguments( this.defaultM2Arguments ); bd.setBuildFile( "pom.xml" ); bd.setSchedule( getDefaultSchedule() ); bd.setType( ContinuumBuildExecutorConstants.MAVEN_TWO_BUILD_EXECUTOR ); bd.setDescription( "Default Maven Build Definition" ); bd.setTemplate( true ); return addBuildDefinitionInTemplate( template, bd, true ); } public BuildDefinitionTemplate getDefaultShellBuildDefinitionTemplate() throws BuildDefinitionServiceException { BuildDefinitionTemplate template = getContinuumDefaultWithType( ContinuumBuildExecutorConstants.SHELL_BUILD_EXECUTOR ); if ( template != null ) { return template; } log.info( "create default ShellBuildDefinitionTemplate" ); template = new BuildDefinitionTemplate(); template.setContinuumDefault( true ); template.setName( "Default Shell Template" ); template.setType( ContinuumBuildExecutorConstants.SHELL_BUILD_EXECUTOR ); template = addBuildDefinitionTemplate( template ); BuildDefinition bd = new BuildDefinition(); bd.setDefaultForProject( true ); bd.setSchedule( getDefaultSchedule() ); bd.setType( ContinuumBuildExecutorConstants.SHELL_BUILD_EXECUTOR ); bd.setTemplate( true ); bd.setDescription( "Default Shell Build Definition" ); return addBuildDefinitionInTemplate( template, bd, true ); } private Schedule getDefaultSchedule() throws BuildDefinitionServiceException { try { return configurationService.getDefaultSchedule(); } catch ( ContinuumStoreException e ) { throw new BuildDefinitionServiceException( e.getMessage(), e ); } catch ( ConfigurationLoadingException e ) { throw new BuildDefinitionServiceException( e.getMessage(), e ); } catch ( ContinuumConfigurationException e ) { throw new BuildDefinitionServiceException( e.getMessage(), e ); } catch ( BuildQueueServiceException e ) { throw new BuildDefinitionServiceException( e.getMessage(), e ); } } // ------------------------------------------------------ // BuildDefinitionTemplate // ------------------------------------------------------ public List<BuildDefinitionTemplate> getAllBuildDefinitionTemplate() throws BuildDefinitionServiceException { try { return buildDefinitionTemplateDao.getAllBuildDefinitionTemplate(); } catch ( ContinuumStoreException e ) { throw new BuildDefinitionServiceException( e.getMessage(), e ); } } public BuildDefinitionTemplate getBuildDefinitionTemplate( int id ) throws BuildDefinitionServiceException { try { return buildDefinitionTemplateDao.getBuildDefinitionTemplate( id ); } catch ( ContinuumStoreException e ) { throw new BuildDefinitionServiceException( e.getMessage(), e ); } } public void removeBuildDefinitionTemplate( BuildDefinitionTemplate buildDefinitionTemplate ) throws BuildDefinitionServiceException { try { // first remove links to buildDefs // TODO in the same db transaction ? buildDefinitionTemplate.setBuildDefinitions( null ); buildDefinitionTemplate = buildDefinitionTemplateDao.updateBuildDefinitionTemplate( buildDefinitionTemplate ); buildDefinitionTemplateDao.removeBuildDefinitionTemplate( buildDefinitionTemplate ); } catch ( ContinuumStoreException e ) { throw new BuildDefinitionServiceException( e.getMessage(), e ); } } public BuildDefinitionTemplate updateBuildDefinitionTemplate( BuildDefinitionTemplate buildDefinitionTemplate ) throws BuildDefinitionServiceException { try { if ( !hasDuplicateTemplateName( buildDefinitionTemplate ) ) { BuildDefinitionTemplate stored = getBuildDefinitionTemplate( buildDefinitionTemplate.getId() ); stored.setName( buildDefinitionTemplate.getName() ); stored.setBuildDefinitions( buildDefinitionTemplate.getBuildDefinitions() ); return buildDefinitionTemplateDao.updateBuildDefinitionTemplate( stored ); } } catch ( ContinuumStoreException e ) { throw new BuildDefinitionServiceException( e.getMessage(), e ); } return null; } public BuildDefinitionTemplate addBuildDefinitionTemplate( BuildDefinitionTemplate buildDefinitionTemplate ) throws BuildDefinitionServiceException { try { if ( !hasDuplicateTemplateName( buildDefinitionTemplate ) ) { return buildDefinitionTemplateDao.addBuildDefinitionTemplate( buildDefinitionTemplate ); } } catch ( ContinuumStoreException e ) { throw new BuildDefinitionServiceException( e.getMessage(), e ); } return null; } public BuildDefinitionTemplate addBuildDefinitionInTemplate( BuildDefinitionTemplate buildDefinitionTemplate, BuildDefinition buildDefinition, boolean template ) throws BuildDefinitionServiceException { try { BuildDefinitionTemplate stored = getBuildDefinitionTemplate( buildDefinitionTemplate.getId() ); stored.setName( buildDefinitionTemplate.getName() ); BuildDefinition storedBuildDefinition = getBuildDefinition( buildDefinition.getId() ); if ( storedBuildDefinition != null ) { buildDefinition = storedBuildDefinition; } buildDefinition.setTemplate( template ); //stored.addBuildDefinition( addBuildDefinition( buildDefinition ) ); stored.addBuildDefinition( buildDefinition ); return buildDefinitionTemplateDao.updateBuildDefinitionTemplate( stored ); } catch ( ContinuumStoreException e ) { throw new BuildDefinitionServiceException( e.getMessage(), e ); } } public BuildDefinitionTemplate removeBuildDefinitionFromTemplate( BuildDefinitionTemplate buildDefinitionTemplate, BuildDefinition buildDefinition ) throws BuildDefinitionServiceException { try { BuildDefinitionTemplate stored = getBuildDefinitionTemplate( buildDefinitionTemplate.getId() ); stored.setName( buildDefinitionTemplate.getName() ); List<BuildDefinition> buildDefinitions = new ArrayList<BuildDefinition>(); for ( int i = 0, size = stored.getBuildDefinitions().size(); i < size; i++ ) { BuildDefinition buildDef = (BuildDefinition) stored.getBuildDefinitions().get( i ); if ( buildDef.getId() != buildDefinition.getId() ) { buildDefinitions.add( getBuildDefinition( buildDef.getId() ) ); } } stored.setBuildDefinitions( buildDefinitions ); return buildDefinitionTemplateDao.updateBuildDefinitionTemplate( stored ); } catch ( ContinuumStoreException e ) { throw new BuildDefinitionServiceException( e.getMessage(), e ); } } public void addTemplateInProject( int buildDefinitionTemplateId, Project project ) throws BuildDefinitionServiceException { try { BuildDefinitionTemplate template = getBuildDefinitionTemplate( buildDefinitionTemplateId ); if ( template.getBuildDefinitions().isEmpty() ) { return; } project = projectDao.getProjectWithBuildDetails( project.getId() ); for ( BuildDefinition bd : (List<BuildDefinition>) template.getBuildDefinitions() ) { bd = cloneBuildDefinition( bd ); bd.setTemplate( false ); bd = buildDefinitionDao.addBuildDefinition( bd ); project.addBuildDefinition( bd ); } projectDao.updateProject( project ); } catch ( ContinuumStoreException e ) { throw new BuildDefinitionServiceException( e.getMessage(), e ); } } public ProjectGroup addBuildDefinitionTemplateToProjectGroup( int projectGroupId, BuildDefinitionTemplate template ) throws BuildDefinitionServiceException, ContinuumObjectNotFoundException { try { ProjectGroup projectGroup = projectGroupDao.getProjectGroupWithBuildDetailsByProjectGroupId( projectGroupId ); if ( template.getBuildDefinitions().isEmpty() ) { return null; } for ( BuildDefinition bd : (List<BuildDefinition>) template.getBuildDefinitions() ) { bd.setTemplate( false ); bd = buildDefinitionDao.addBuildDefinition( cloneBuildDefinition( bd ) ); projectGroup.addBuildDefinition( bd ); } projectGroupDao.updateProjectGroup( projectGroup ); return projectGroup; } catch ( ContinuumStoreException e ) { throw new BuildDefinitionServiceException( e.getMessage(), e ); } } public List<BuildDefinitionTemplate> getBuildDefinitionTemplatesWithType( String type ) throws BuildDefinitionServiceException { try { return buildDefinitionTemplateDao.getBuildDefinitionTemplatesWithType( type ); } catch ( ContinuumStoreException e ) { throw new BuildDefinitionServiceException( e.getMessage(), e ); } } public List<BuildDefinitionTemplate> getContinuumBuildDefinitionTemplates() throws BuildDefinitionServiceException { try { return buildDefinitionTemplateDao.getContinuumBuildDefinitionTemplates(); } catch ( ContinuumStoreException e ) { throw new BuildDefinitionServiceException( e.getMessage(), e ); } } private boolean hasDuplicateTemplateName( BuildDefinitionTemplate buildDefinitionTemplate ) throws BuildDefinitionServiceException { boolean isDuplicate = false; List<BuildDefinitionTemplate> allBuildDefinitionTemplate = this.getAllBuildDefinitionTemplate(); for ( BuildDefinitionTemplate template : allBuildDefinitionTemplate ) { String name = buildDefinitionTemplate.getName(); if ( ( template.getId() != buildDefinitionTemplate.getId() ) && ( template.getName().equals( name ) ) ) { isDuplicate = true; break; } } return isDuplicate; } }
5,141
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/build
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/build/settings/DefaultSchedulesActivator.java
package org.apache.maven.continuum.build.settings; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.dao.BuildDefinitionDao; import org.apache.continuum.dao.DirectoryPurgeConfigurationDao; import org.apache.continuum.dao.DistributedDirectoryPurgeConfigurationDao; import org.apache.continuum.dao.RepositoryPurgeConfigurationDao; import org.apache.continuum.dao.ScheduleDao; import org.apache.continuum.model.repository.DirectoryPurgeConfiguration; import org.apache.continuum.model.repository.DistributedDirectoryPurgeConfiguration; import org.apache.continuum.model.repository.RepositoryPurgeConfiguration; import org.apache.maven.continuum.Continuum; import org.apache.maven.continuum.model.project.BuildDefinition; import org.apache.maven.continuum.model.project.Schedule; import org.apache.maven.continuum.scheduler.ContinuumBuildJob; import org.apache.maven.continuum.scheduler.ContinuumPurgeJob; import org.apache.maven.continuum.scheduler.ContinuumSchedulerConstants; import org.apache.maven.continuum.store.ContinuumStoreException; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.scheduler.AbstractJob; import org.codehaus.plexus.scheduler.Scheduler; import org.codehaus.plexus.util.StringUtils; import org.quartz.CronTrigger; import org.quartz.JobDataMap; import org.quartz.JobDetail; import org.quartz.SchedulerException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.text.ParseException; import java.util.Collection; import java.util.Date; import java.util.List; /** * @author <a href="mailto:jason@maven.org">Jason van Zyl</a> */ @Component( role = org.apache.maven.continuum.build.settings.SchedulesActivator.class ) public class DefaultSchedulesActivator implements SchedulesActivator { private static final Logger log = LoggerFactory.getLogger( DefaultSchedulesActivator.class ); @Requirement private DirectoryPurgeConfigurationDao directoryPurgeConfigurationDao; @Requirement private RepositoryPurgeConfigurationDao repositoryPurgeConfigurationDao; @Requirement private DistributedDirectoryPurgeConfigurationDao distributedDirectoryPurgeConfigurationDao; @Requirement private BuildDefinitionDao buildDefinitionDao; @Requirement private ScheduleDao scheduleDao; @Requirement( hint = "default" ) private Scheduler scheduler; // private int delay = 3600; private static final int delay = 1; public void activateSchedules( Continuum continuum ) throws SchedulesActivationException { log.info( "Activating schedules ..." ); Collection<Schedule> schedules = scheduleDao.getAllSchedulesByName(); for ( Schedule schedule : schedules ) { if ( schedule.isActive() ) { try { activateSchedule( schedule, continuum ); } catch ( SchedulesActivationException e ) { log.error( "Can't activate schedule '" + schedule.getName() + "'", e ); schedule.setActive( false ); try { scheduleDao.storeSchedule( schedule ); } catch ( ContinuumStoreException e1 ) { throw new SchedulesActivationException( "Can't desactivate schedule '" + schedule.getName() + "'", e ); } } } } } public void activateSchedule( Schedule schedule, Continuum continuum ) throws SchedulesActivationException { if ( schedule != null ) { log.info( "Activating schedule " + schedule.getName() ); activateBuildSchedule( schedule, continuum ); activatePurgeSchedule( schedule, continuum ); } } public void activateBuildSchedule( Schedule schedule, Continuum continuum ) throws SchedulesActivationException { if ( schedule != null && schedule.isActive() && isScheduleFromBuildJob( schedule ) ) { schedule( schedule, continuum, ContinuumBuildJob.class, ContinuumBuildJob.BUILD_GROUP ); } } public void activatePurgeSchedule( Schedule schedule, Continuum continuum ) throws SchedulesActivationException { if ( schedule != null && schedule.isActive() && isScheduleFromPurgeJob( schedule ) ) { schedule( schedule, continuum, ContinuumPurgeJob.class, ContinuumPurgeJob.PURGE_GROUP ); } } public void unactivateSchedule( Schedule schedule, Continuum continuum ) throws SchedulesActivationException { log.info( "Deactivating schedule " + schedule.getName() ); unactivateBuildSchedule( schedule ); unactivatePurgeSchedule( schedule ); } public void unactivateOrphanBuildSchedule( Schedule schedule ) throws SchedulesActivationException { if ( schedule != null && !isScheduleFromBuildJob( schedule ) ) { unactivateBuildSchedule( schedule ); } } public void unactivateOrphanPurgeSchedule( Schedule schedule ) throws SchedulesActivationException { if ( schedule != null && !isScheduleFromPurgeJob( schedule ) ) { unactivatePurgeSchedule( schedule ); } } private void unactivateBuildSchedule( Schedule schedule ) throws SchedulesActivationException { log.debug( "Deactivating schedule " + schedule.getName() + " for Build Process" ); unschedule( schedule, ContinuumBuildJob.BUILD_GROUP ); } private void unactivatePurgeSchedule( Schedule schedule ) throws SchedulesActivationException { log.debug( "Deactivating schedule " + schedule.getName() + " for Purge Process" ); unschedule( schedule, ContinuumPurgeJob.PURGE_GROUP ); } protected void schedule( Schedule schedule, Continuum continuum, Class jobClass, String group ) throws SchedulesActivationException { if ( StringUtils.isEmpty( schedule.getCronExpression() ) ) { log.info( "Not scheduling " + schedule.getName() ); return; } JobDataMap dataMap = new JobDataMap(); dataMap.put( "continuum", continuum ); dataMap.put( AbstractJob.LOGGER, log ); dataMap.put( ContinuumSchedulerConstants.SCHEDULE, schedule ); // the name + group makes the job unique JobDetail jobDetail = new JobDetail( schedule.getName(), group, jobClass ); jobDetail.setJobDataMap( dataMap ); jobDetail.setDescription( schedule.getDescription() ); CronTrigger trigger = new CronTrigger(); trigger.setName( schedule.getName() ); trigger.setGroup( group ); Date startTime = new Date( System.currentTimeMillis() + delay * 1000 ); trigger.setStartTime( startTime ); trigger.setNextFireTime( startTime ); try { trigger.setCronExpression( schedule.getCronExpression() ); } catch ( ParseException e ) { throw new SchedulesActivationException( "Error parsing cron expression.", e ); } try { scheduler.scheduleJob( jobDetail, trigger ); log.info( trigger.getName() + ": next fire time ->" + trigger.getNextFireTime() ); } catch ( SchedulerException e ) { throw new SchedulesActivationException( "Cannot schedule job ->" + jobClass.getName(), e ); } } private void unschedule( Schedule schedule, String group ) throws SchedulesActivationException { try { if ( schedule.isActive() ) { log.info( "Stopping active schedule \"" + schedule.getName() + "\"." ); scheduler.interruptSchedule( schedule.getName(), group ); } scheduler.unscheduleJob( schedule.getName(), group ); } catch ( SchedulerException e ) { throw new SchedulesActivationException( "Cannot unschedule build job \"" + schedule.getName() + "\".", e ); } } private boolean isScheduleFromBuildJob( Schedule schedule ) { List<BuildDefinition> buildDef = buildDefinitionDao.getBuildDefinitionsBySchedule( schedule.getId() ); // Take account templateBuildDefinition too. // A improvement will be add schedule only for active buildDefinition, but it would need activate // schedule job in add project and add group process return buildDef.size() > 0; } private boolean isScheduleFromPurgeJob( Schedule schedule ) { List<RepositoryPurgeConfiguration> repoPurgeConfigs = repositoryPurgeConfigurationDao.getEnableRepositoryPurgeConfigurationsBySchedule( schedule.getId() ); List<DirectoryPurgeConfiguration> dirPurgeConfigs = directoryPurgeConfigurationDao.getEnableDirectoryPurgeConfigurationsBySchedule( schedule.getId() ); List<DistributedDirectoryPurgeConfiguration> distriDirPurgeConfigs = distributedDirectoryPurgeConfigurationDao.getEnableDistributedDirectoryPurgeConfigurationsBySchedule( schedule.getId() ); return repoPurgeConfigs.size() > 0 || dirPurgeConfigs.size() > 0 || distriDirPurgeConfigs.size() > 0; } }
5,142
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/scm
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/scm/queue/CheckOutTaskExecutor.java
package org.apache.maven.continuum.scm.queue; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.dao.ProjectDao; import org.apache.continuum.taskqueue.CheckOutTask; import org.apache.maven.continuum.core.action.AbstractContinuumAction; import org.apache.maven.continuum.core.action.CheckoutProjectContinuumAction; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.store.ContinuumStoreException; import org.codehaus.plexus.action.ActionManager; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.taskqueue.Task; import org.codehaus.plexus.taskqueue.execution.TaskExecutionException; import org.codehaus.plexus.taskqueue.execution.TaskExecutor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.Map; /** * @author <a href="mailto:trygvis@inamo.no">Trygve Laugst&oslash;l</a> */ @Component( role = org.codehaus.plexus.taskqueue.execution.TaskExecutor.class, hint = "check-out-project", instantiationStrategy = "per-lookup" ) public class CheckOutTaskExecutor implements TaskExecutor { private static final Logger log = LoggerFactory.getLogger( CheckOutTaskExecutor.class ); @Requirement private ActionManager actionManager; @Requirement private ProjectDao projectDao; // ---------------------------------------------------------------------- // TaskExecutor Implementation // ---------------------------------------------------------------------- public void executeTask( Task t ) throws TaskExecutionException { log.info( "Checkout task executor.." ); CheckOutTask task = (CheckOutTask) t; int projectId = task.getProjectId(); Project project; try { project = projectDao.getProjectWithBuildDetails( projectId ); } catch ( ContinuumStoreException ex ) { log.error( "Internal error while getting the project.", ex ); return; } String workingDirectory = task.getWorkingDirectory().getAbsolutePath(); Map<String, Object> context = new HashMap<String, Object>(); AbstractContinuumAction.setProjectId( context, projectId ); AbstractContinuumAction.setProject( context, project ); AbstractContinuumAction.setWorkingDirectory( context, workingDirectory ); CheckoutProjectContinuumAction.setScmUsername( context, task.getScmUserName() ); CheckoutProjectContinuumAction.setScmPassword( context, task.getScmPassword() ); AbstractContinuumAction.setProjectScmRootUrl( context, task.getScmRootUrl() ); AbstractContinuumAction.setListOfProjectsInGroupWithCommonScmRoot( context, task.getProjectsWithCommonScmRoot() ); try { actionManager.lookup( "checkout-project" ).execute( context ); actionManager.lookup( "store-checkout-scm-result" ).execute( context ); } catch ( Exception e ) { throw new TaskExecutionException( "Error checking out project.", e ); } } }
5,143
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/scm
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/scm/queue/PrepareBuildProjectsTaskExecutor.java
package org.apache.maven.continuum.scm.queue; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.dao.BuildDefinitionDao; import org.apache.continuum.dao.BuildResultDao; import org.apache.continuum.dao.ProjectDao; import org.apache.continuum.dao.ProjectGroupDao; import org.apache.continuum.dao.ProjectScmRootDao; import org.apache.continuum.model.project.ProjectScmRoot; import org.apache.continuum.taskqueue.PrepareBuildProjectsTask; import org.apache.continuum.utils.ContinuumUtils; import org.apache.continuum.utils.ProjectSorter; import org.apache.continuum.utils.build.BuildTrigger; import org.apache.maven.continuum.core.action.AbstractContinuumAction; import org.apache.maven.continuum.core.action.CheckWorkingDirectoryAction; import org.apache.maven.continuum.core.action.CheckoutProjectContinuumAction; import org.apache.maven.continuum.core.action.UpdateWorkingDirectoryFromScmContinuumAction; import org.apache.maven.continuum.model.project.BuildDefinition; import org.apache.maven.continuum.model.project.BuildResult; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.model.project.ProjectGroup; import org.apache.maven.continuum.model.scm.ChangeSet; import org.apache.maven.continuum.model.scm.ScmResult; import org.apache.maven.continuum.notification.ContinuumNotificationDispatcher; import org.apache.maven.continuum.project.ContinuumProjectState; import org.apache.maven.continuum.store.ContinuumStoreException; import org.apache.maven.continuum.utils.WorkingDirectoryService; import org.codehaus.plexus.action.ActionManager; import org.codehaus.plexus.action.ActionNotFoundException; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.taskqueue.Task; import org.codehaus.plexus.taskqueue.execution.TaskExecutionException; import org.codehaus.plexus.taskqueue.execution.TaskExecutor; import org.codehaus.plexus.util.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; /** * @author <a href="mailto:ctan@apache.org">Maria Catherine Tan</a> */ @Component( role = org.codehaus.plexus.taskqueue.execution.TaskExecutor.class, hint = "prepare-build-project" ) public class PrepareBuildProjectsTaskExecutor implements TaskExecutor { private static final Logger log = LoggerFactory.getLogger( PrepareBuildProjectsTaskExecutor.class ); @Requirement private ActionManager actionManager; @Requirement private ProjectDao projectDao; @Requirement private BuildDefinitionDao buildDefinitionDao; @Requirement private ProjectScmRootDao projectScmRootDao; @Requirement private BuildResultDao buildResultDao; @Requirement private WorkingDirectoryService workingDirectoryService; @Requirement private ContinuumNotificationDispatcher notifierDispatcher; @Requirement private ProjectGroupDao projectGroupDao; public void executeTask( Task task ) throws TaskExecutionException { PrepareBuildProjectsTask prepareTask = (PrepareBuildProjectsTask) task; Map<Integer, Integer> projectsBuildDefinitionsMap = prepareTask.getProjectsBuildDefinitionsMap(); BuildTrigger buildTrigger = prepareTask.getBuildTrigger(); Set<Integer> projectsId = projectsBuildDefinitionsMap.keySet(); Map<String, Object> context = new HashMap<String, Object>(); Map<Integer, ScmResult> scmResultMap = new HashMap<Integer, ScmResult>(); List<Project> projectList = new ArrayList<Project>(); int projectGroupId = 0; try { if ( !projectsId.isEmpty() ) { int projectId = projectsId.iterator().next(); Project project = projectDao.getProject( projectId ); ProjectGroup projectGroup = project.getProjectGroup(); projectGroupId = projectGroup.getId(); List<Project> projects = projectDao.getProjectsWithDependenciesByGroupId( projectGroupId ); projectList = ProjectSorter.getSortedProjects( projects, log ); } Project rootProject = null; for ( Project project : projectList ) { if ( rootProject == null ) { // first project is the root project. rootProject = project; } int projectId = project.getId(); int buildDefinitionId; if ( projectsBuildDefinitionsMap.get( projectId ) != null ) { buildDefinitionId = projectsBuildDefinitionsMap.get( projectId ); log.info( "Initializing prepare build" ); context = initializeContext( project, buildDefinitionId, prepareTask.getBuildTrigger() ); log.info( "Starting prepare build of project: " + AbstractContinuumAction.getProject( context ).getName() ); startPrepareBuild( context ); if ( !checkProjectScmRoot( context ) ) { break; } try { if ( AbstractContinuumAction.getBuildDefinition( context ).isBuildFresh() ) { log.info( "Purging existing working copy" ); cleanWorkingDirectory( context ); } // ---------------------------------------------------------------------- // TODO: Centralize the error handling from the SCM related actions. // ContinuumScmResult should return a ContinuumScmResult from all // methods, even in a case of failure. // ---------------------------------------------------------------------- log.info( "Updating working dir" ); updateWorkingDirectory( context, rootProject ); log.info( "Merging SCM results" ); //CONTINUUM-1393 if ( !AbstractContinuumAction.getBuildDefinition( context ).isBuildFresh() ) { mergeScmResults( context ); } } finally { log.info( "Ending prepare build of project: " + AbstractContinuumAction.getProject( context ).getName() ); scmResultMap.put( AbstractContinuumAction.getProjectId( context ), AbstractContinuumAction.getScmResult( context, null ) ); endProjectPrepareBuild( context ); } } } } catch ( ContinuumStoreException e ) { throw new TaskExecutionException( "Failed to prepare build project group: " + projectGroupId, e ); } finally { log.info( "Ending prepare build" ); endPrepareBuild( context ); } if ( checkProjectScmRoot( context ) ) { projectGroupId = AbstractContinuumAction.getProjectGroupId( context ); buildProjects( projectGroupId, projectList, projectsBuildDefinitionsMap, buildTrigger, scmResultMap ); } } private Map<String, Object> initializeContext( Project project, int buildDefinitionId, BuildTrigger buildTrigger ) throws TaskExecutionException { Map<String, Object> context = new HashMap<String, Object>(); try { ProjectGroup projectGroup = project.getProjectGroup(); List<ProjectScmRoot> scmRoots = projectScmRootDao.getProjectScmRootByProjectGroup( projectGroup.getId() ); String projectScmUrl = project.getScmUrl(); String projectScmRootAddress = ""; for ( ProjectScmRoot projectScmRoot : scmRoots ) { projectScmRootAddress = projectScmRoot.getScmRootAddress(); if ( projectScmUrl.startsWith( projectScmRoot.getScmRootAddress() ) ) { AbstractContinuumAction.setProjectScmRoot( context, projectScmRoot ); AbstractContinuumAction.setProjectScmRootUrl( context, projectScmRootAddress ); break; } } AbstractContinuumAction.setProjectGroupId( context, projectGroup.getId() ); AbstractContinuumAction.setProjectId( context, project.getId() ); AbstractContinuumAction.setProject( context, project ); AbstractContinuumAction.setBuildTrigger( context, buildTrigger ); AbstractContinuumAction.setBuildDefinitionId( context, buildDefinitionId ); AbstractContinuumAction.setBuildDefinition( context, buildDefinitionDao.getBuildDefinition( buildDefinitionId ) ); if ( project.isCheckedOutInSingleDirectory() ) { List<Project> projectsInGroup = projectGroupDao.getProjectGroupWithProjects( projectGroup.getId() ).getProjects(); List<Project> projectsWithCommonScmRoot = new ArrayList<Project>(); for ( Project projectInGroup : projectsInGroup ) { if ( projectInGroup.getScmUrl().startsWith( projectScmRootAddress ) ) { projectsWithCommonScmRoot.add( projectInGroup ); } } AbstractContinuumAction.setListOfProjectsInGroupWithCommonScmRoot( context, projectsWithCommonScmRoot ); } BuildResult oldBuildResult = buildResultDao.getLatestBuildResultForBuildDefinition( project.getId(), buildDefinitionId ); if ( oldBuildResult != null ) { AbstractContinuumAction.setOldScmResult( context, getOldScmResults( project.getId(), oldBuildResult.getBuildNumber(), oldBuildResult.getEndTime() ) ); } else { AbstractContinuumAction.setOldScmResult( context, null ); } } catch ( ContinuumStoreException e ) { throw new TaskExecutionException( "Error initializing pre-build context", e ); } return context; } private void cleanWorkingDirectory( Map<String, Object> context ) throws TaskExecutionException { performAction( "clean-working-directory", context ); } private void updateWorkingDirectory( Map<String, Object> context, Project rootProject ) throws TaskExecutionException { performAction( "check-working-directory", context ); boolean workingDirectoryExists = CheckWorkingDirectoryAction.isWorkingDirectoryExists( context ); ScmResult scmResult; if ( workingDirectoryExists ) { performAction( "update-working-directory-from-scm", context ); scmResult = UpdateWorkingDirectoryFromScmContinuumAction.getUpdateScmResult( context, null ); } else { Project project = AbstractContinuumAction.getProject( context ); AbstractContinuumAction.setWorkingDirectory( context, workingDirectoryService.getWorkingDirectory( project ).getAbsolutePath() ); List<Project> projectsWithCommonScmRoot = AbstractContinuumAction.getListOfProjectsInGroupWithCommonScmRoot( context ); String projectScmRootUrl = AbstractContinuumAction.getProjectScmRootUrl( context, project.getScmUrl() ); String workingDir = null; if ( rootProject.getId() == project.getId() ) { workingDir = workingDirectoryService.getWorkingDirectory( project, false ).getAbsolutePath(); if ( project.isCheckedOutInSingleDirectory() ) { File parentDir = new File( workingDir ); while ( !isRootDirectory( parentDir.getAbsolutePath(), project ) ) { parentDir = parentDir.getParentFile(); } if ( !parentDir.exists() ) { workingDir = parentDir.getAbsolutePath(); } } } if ( workingDir == null || new File( workingDir ).exists() ) { workingDir = workingDirectoryService.getWorkingDirectory( project, projectScmRootUrl, projectsWithCommonScmRoot ).getAbsolutePath(); } AbstractContinuumAction.setWorkingDirectory( context, workingDir ); if ( rootProject.getId() != project.getId() || ( rootProject.getId() == project.getId() && !isRootDirectory( workingDir, rootProject ) ) ) { AbstractContinuumAction.setRootDirectory( context, false ); } performAction( "checkout-project", context ); scmResult = CheckoutProjectContinuumAction.getCheckoutScmResult( context, null ); } // [CONTINUUM-2207] when returned scmResult is null, this causes a problem when building the project if ( scmResult == null ) { log.debug( "Returned ScmResult is null when updating the working directory" ); scmResult = new ScmResult(); } AbstractContinuumAction.setScmResult( context, scmResult ); } private boolean checkProjectScmRoot( Map<String, Object> context ) throws TaskExecutionException { ProjectScmRoot projectScmRoot = AbstractContinuumAction.getProjectScmRoot( context ); // check state of scm root return projectScmRoot.getState() != ContinuumProjectState.ERROR; } private void startPrepareBuild( Map<String, Object> context ) throws TaskExecutionException { ProjectScmRoot projectScmRoot = AbstractContinuumAction.getProjectScmRoot( context ); if ( projectScmRoot.getState() != ContinuumProjectState.UPDATING ) { try { projectScmRoot.setOldState( projectScmRoot.getState() ); projectScmRoot.setState( ContinuumProjectState.UPDATING ); projectScmRootDao.updateProjectScmRoot( projectScmRoot ); } catch ( ContinuumStoreException e ) { throw new TaskExecutionException( "Error persisting projectScmRoot", e ); } } } private void endPrepareBuild( Map<String, Object> context ) throws TaskExecutionException { ProjectScmRoot projectScmRoot = AbstractContinuumAction.getProjectScmRoot( context ); if ( projectScmRoot.getState() != ContinuumProjectState.ERROR ) { projectScmRoot.setState( ContinuumProjectState.UPDATED ); projectScmRoot.setError( null ); try { projectScmRootDao.updateProjectScmRoot( projectScmRoot ); } catch ( ContinuumStoreException e ) { throw new TaskExecutionException( "Error persisting projectScmRoot", e ); } } notifierDispatcher.prepareBuildComplete( projectScmRoot ); } /** * @param context * @throws TaskExecutionException */ private void endProjectPrepareBuild( Map<String, Object> context ) throws TaskExecutionException { ScmResult scmResult = AbstractContinuumAction.getScmResult( context, null ); if ( scmResult == null || !scmResult.isSuccess() ) { String error = convertScmResultToError( scmResult ); updateProjectScmRoot( context, error ); } } private ScmResult getOldScmResults( int projectId, long startId, long fromDate ) throws ContinuumStoreException { List<BuildResult> results = buildResultDao.getBuildResultsForProjectFromId( projectId, startId ); ScmResult res = new ScmResult(); if ( results != null && results.size() > 0 ) { for ( BuildResult result : results ) { ScmResult scmResult = result.getScmResult(); if ( scmResult != null ) { List<ChangeSet> changes = scmResult.getChanges(); if ( changes != null ) { for ( ChangeSet changeSet : changes ) { if ( changeSet.getDate() < fromDate ) { continue; } if ( !res.getChanges().contains( changeSet ) ) { res.addChange( changeSet ); } } } } } } return res; } /** * Merges scm results so we'll have all changes since last execution of current build definition * * @param context The build context */ private void mergeScmResults( Map<String, Object> context ) { ScmResult oldScmResult = AbstractContinuumAction.getOldScmResult( context ); ScmResult newScmResult = AbstractContinuumAction.getScmResult( context, null ); if ( oldScmResult != null ) { if ( newScmResult == null ) { AbstractContinuumAction.setScmResult( context, oldScmResult ); } else { List<ChangeSet> oldChanges = oldScmResult.getChanges(); List<ChangeSet> newChanges = newScmResult.getChanges(); for ( ChangeSet change : newChanges ) { if ( !oldChanges.contains( change ) ) { oldChanges.add( change ); } } newScmResult.setChanges( oldChanges ); } } } private void performAction( String actionName, Map<String, Object> context ) throws TaskExecutionException { TaskExecutionException exception; try { log.info( "Performing action " + actionName ); actionManager.lookup( actionName ).execute( context ); return; } catch ( ActionNotFoundException e ) { exception = new TaskExecutionException( "Error looking up action '" + actionName + "'", e ); } catch ( Exception e ) { exception = new TaskExecutionException( "Error executing action '" + actionName + "'", e ); } ScmResult result = new ScmResult(); result.setSuccess( false ); result.setException( ContinuumUtils.throwableToString( exception ) ); AbstractContinuumAction.setScmResult( context, result ); throw exception; } private String convertScmResultToError( ScmResult result ) { String error = ""; if ( result == null ) { error = "Scm result is null."; } else { if ( result.getCommandLine() != null ) { error = "Command line: " + StringUtils.clean( result.getCommandLine() ) + System.getProperty( "line.separator" ); } if ( result.getProviderMessage() != null ) { error = "Provider message: " + StringUtils.clean( result.getProviderMessage() ) + System.getProperty( "line.separator" ); } if ( result.getCommandOutput() != null ) { error += "Command output: " + System.getProperty( "line.separator" ); error += "-------------------------------------------------------------------------------" + System.getProperty( "line.separator" ); error += StringUtils.clean( result.getCommandOutput() ) + System.getProperty( "line.separator" ); error += "-------------------------------------------------------------------------------" + System.getProperty( "line.separator" ); } if ( result.getException() != null ) { error += "Exception:" + System.getProperty( "line.separator" ); error += result.getException(); } } return error; } private void updateProjectScmRoot( Map<String, Object> context, String error ) throws TaskExecutionException { ProjectScmRoot projectScmRoot = AbstractContinuumAction.getProjectScmRoot( context ); try { projectScmRoot.setState( ContinuumProjectState.ERROR ); projectScmRoot.setError( error ); projectScmRootDao.updateProjectScmRoot( projectScmRoot ); AbstractContinuumAction.setProjectScmRoot( context, projectScmRoot ); } catch ( ContinuumStoreException e ) { throw new TaskExecutionException( "Error storing project scm root", e ); } } private void buildProjects( int projectGroupId, List<Project> projectList, Map<Integer, Integer> projectsAndBuildDefinitionsMap, BuildTrigger buildTrigger, Map<Integer, ScmResult> scmResultMap ) throws TaskExecutionException { List<Project> projectsToBeBuilt = new ArrayList<Project>(); Map<Integer, BuildDefinition> projectsBuildDefinitionsMap = new HashMap<Integer, BuildDefinition>(); for ( Project project : projectList ) { int buildDefinitionId; if ( projectsAndBuildDefinitionsMap.get( project.getId() ) != null ) { buildDefinitionId = projectsAndBuildDefinitionsMap.get( project.getId() ); try { BuildDefinition buildDefinition = buildDefinitionDao.getBuildDefinition( buildDefinitionId ); projectsBuildDefinitionsMap.put( project.getId(), buildDefinition ); projectsToBeBuilt.add( project ); } catch ( ContinuumStoreException e ) { log.error( "Error while creating build object", e ); throw new TaskExecutionException( "Error while creating build object", e ); } } } try { Map<String, Object> context = new HashMap<String, Object>(); AbstractContinuumAction.setListOfProjects( context, projectsToBeBuilt ); AbstractContinuumAction.setProjectsBuildDefinitionsMap( context, projectsBuildDefinitionsMap ); AbstractContinuumAction.setBuildTrigger( context, buildTrigger ); AbstractContinuumAction.setScmResultMap( context, scmResultMap ); AbstractContinuumAction.setProjectGroupId( context, projectGroupId ); log.info( "Performing action create-build-project-task" ); actionManager.lookup( "create-build-project-task" ).execute( context ); } catch ( ActionNotFoundException e ) { log.error( "Error looking up action 'build-project'" ); throw new TaskExecutionException( "Error looking up action 'build-project'", e ); } catch ( Exception e ) { log.error( e.getMessage(), e ); throw new TaskExecutionException( "Error executing action 'build-project'", e ); } } private boolean isRootDirectory( String workingDir, Project rootProject ) { return workingDir.endsWith( Integer.toString( rootProject.getId() ) + System.getProperty( "line.separator" ) ) || workingDir.endsWith( Integer.toString( rootProject.getId() ) ); } }
5,144
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/buildcontroller/BuildController.java
package org.apache.maven.continuum.buildcontroller; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.utils.build.BuildTrigger; import org.apache.maven.continuum.model.scm.ScmResult; import org.codehaus.plexus.taskqueue.execution.TaskExecutionException; /** * @author <a href="mailto:trygvis@inamo.no">Trygve Laugst&oslash;l</a> */ public interface BuildController { String ROLE = BuildController.class.getName(); void build( int projectId, int buildDefinitionId, BuildTrigger buildTrigger, ScmResult scmResult ) throws TaskExecutionException; }
5,145
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/buildcontroller/DefaultBuildController.java
package org.apache.maven.continuum.buildcontroller; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.dao.BuildDefinitionDao; import org.apache.continuum.dao.BuildResultDao; import org.apache.continuum.dao.ProjectDao; import org.apache.continuum.dao.ProjectGroupDao; import org.apache.continuum.dao.ProjectScmRootDao; import org.apache.continuum.model.project.ProjectScmRoot; import org.apache.continuum.utils.ContinuumUtils; import org.apache.continuum.utils.build.BuildTrigger; import org.apache.maven.continuum.core.action.AbstractContinuumAction; import org.apache.maven.continuum.core.action.ExecuteBuilderContinuumAction; import org.apache.maven.continuum.execution.ContinuumBuildExecutor; import org.apache.maven.continuum.execution.ContinuumBuildExecutorConstants; import org.apache.maven.continuum.execution.manager.BuildExecutorManager; import org.apache.maven.continuum.model.project.BuildDefinition; import org.apache.maven.continuum.model.project.BuildResult; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.model.project.ProjectDependency; import org.apache.maven.continuum.model.project.ProjectGroup; import org.apache.maven.continuum.model.scm.ChangeFile; import org.apache.maven.continuum.model.scm.ChangeSet; import org.apache.maven.continuum.model.scm.ScmResult; import org.apache.maven.continuum.notification.ContinuumNotificationDispatcher; import org.apache.maven.continuum.project.ContinuumProjectState; import org.apache.maven.continuum.store.ContinuumObjectNotFoundException; import org.apache.maven.continuum.store.ContinuumStoreException; import org.apache.maven.continuum.utils.WorkingDirectoryService; import org.apache.maven.scm.ScmException; import org.apache.maven.scm.repository.ScmRepositoryException; import org.codehaus.plexus.action.ActionManager; import org.codehaus.plexus.action.ActionNotFoundException; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.taskqueue.execution.TaskExecutionException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; /** * @author <a href="mailto:trygvis@inamo.no">Trygve Laugst&oslash;l</a> */ @Component( role = org.apache.maven.continuum.buildcontroller.BuildController.class, hint = "default" ) public class DefaultBuildController implements BuildController { private static final Logger log = LoggerFactory.getLogger( DefaultBuildController.class ); @Requirement private BuildDefinitionDao buildDefinitionDao; @Requirement private BuildResultDao buildResultDao; @Requirement private ProjectDao projectDao; @Requirement private ProjectGroupDao projectGroupDao; @Requirement private ProjectScmRootDao projectScmRootDao; @Requirement private ContinuumNotificationDispatcher notifierDispatcher; @Requirement private ActionManager actionManager; @Requirement private WorkingDirectoryService workingDirectoryService; @Requirement private BuildExecutorManager buildExecutorManager; // ---------------------------------------------------------------------- // BuildController Implementation // ---------------------------------------------------------------------- /** * @param projectId * @param buildDefinitionId * @param buildTrigger * @param scmResult * @throws TaskExecutionException */ public void build( int projectId, int buildDefinitionId, BuildTrigger buildTrigger, ScmResult scmResult ) throws TaskExecutionException { log.info( "Initializing build" ); BuildContext context = initializeBuildContext( projectId, buildDefinitionId, buildTrigger, scmResult ); // ignore this if AlwaysBuild ? if ( !checkScmResult( context ) ) { log.info( "Error updating from SCM, not building" ); return; } log.info( "Starting build of " + context.getProject().getName() ); startBuild( context ); try { checkProjectDependencies( context ); if ( !shouldBuild( context ) ) { return; } Map<String, Object> actionContext = context.getActionContext(); try { performAction( "update-project-from-working-directory", context ); } catch ( TaskExecutionException e ) { updateBuildResult( context, ContinuumUtils.throwableToString( e ) ); //just log the error but don't stop the build from progressing in order not to suppress any build result messages there log.error( "Error executing action update-project-from-working-directory '", e ); } performAction( "execute-builder", context ); performAction( "deploy-artifact", context ); context.setCancelled( ExecuteBuilderContinuumAction.isCancelled( actionContext ) ); String s = AbstractContinuumAction.getBuildId( actionContext, null ); if ( s != null && !context.isCancelled() ) { try { context.setBuildResult( buildResultDao.getBuildResult( Integer.valueOf( s ) ) ); } catch ( NumberFormatException e ) { throw new TaskExecutionException( "Internal error: build id not an integer", e ); } catch ( ContinuumObjectNotFoundException e ) { throw new TaskExecutionException( "Internal error: Cannot find build result", e ); } catch ( ContinuumStoreException e ) { throw new TaskExecutionException( "Error loading build result", e ); } } } finally { endBuild( context ); } } /** * Checks if the build should be marked as ERROR and notifies the end of the build. * * @param context * @throws TaskExecutionException */ private void endBuild( BuildContext context ) throws TaskExecutionException { Project project = context.getProject(); try { if ( project.getState() != ContinuumProjectState.NEW && project.getState() != ContinuumProjectState.CHECKEDOUT && project.getState() != ContinuumProjectState.OK && project.getState() != ContinuumProjectState.FAILED && project.getState() != ContinuumProjectState.ERROR && !context.isCancelled() ) { try { String s = AbstractContinuumAction.getBuildId( context.getActionContext(), null ); if ( s != null ) { BuildResult buildResult = buildResultDao.getBuildResult( Integer.valueOf( s ) ); project.setState( buildResult.getState() ); projectDao.updateProject( project ); } } catch ( ContinuumStoreException e ) { throw new TaskExecutionException( "Error storing the project", e ); } } } finally { if ( !context.isCancelled() ) { notifierDispatcher.buildComplete( project, context.getBuildDefinition(), context.getBuildResult() ); } } } private void updateBuildResult( BuildContext context, String error ) throws TaskExecutionException { BuildResult build = context.getBuildResult(); if ( build == null ) { build = makeAndStoreBuildResult( context, error ); } else { updateBuildResult( build, context ); build.setError( error ); try { buildResultDao.updateBuildResult( build ); build = buildResultDao.getBuildResult( build.getId() ); context.setBuildResult( build ); } catch ( ContinuumStoreException e ) { throw new TaskExecutionException( "Error updating build result", e ); } } context.getProject().setState( build.getState() ); try { projectDao.updateProject( context.getProject() ); } catch ( ContinuumStoreException e ) { throw new TaskExecutionException( "Error updating project", e ); } } private void updateBuildResult( BuildResult build, BuildContext context ) { if ( build.getScmResult() == null && context.getScmResult() != null ) { build.setScmResult( context.getScmResult() ); } if ( build.getModifiedDependencies() == null && context.getModifiedDependencies() != null ) { build.setModifiedDependencies( context.getModifiedDependencies() ); } } private void startBuild( BuildContext context ) throws TaskExecutionException { Project project = context.getProject(); project.setOldState( project.getState() ); project.setState( ContinuumProjectState.BUILDING ); try { projectDao.updateProject( project ); } catch ( ContinuumStoreException e ) { throw new TaskExecutionException( "Error persisting project", e ); } notifierDispatcher.buildStarted( project, context.getBuildDefinition() ); } /** * Initializes a BuildContext for the build. * * @param projectId * @param buildDefinitionId * @param buildTrigger * @param scmResult * @return * @throws TaskExecutionException */ @SuppressWarnings( "unchecked" ) protected BuildContext initializeBuildContext( int projectId, int buildDefinitionId, BuildTrigger buildTrigger, ScmResult scmResult ) throws TaskExecutionException { BuildContext context = new BuildContext(); context.setStartTime( System.currentTimeMillis() ); Map actionContext = context.getActionContext(); try { Project project = projectDao.getProject( projectId ); context.setProject( project ); BuildDefinition buildDefinition = buildDefinitionDao.getBuildDefinition( buildDefinitionId ); BuildTrigger newBuildTrigger = buildTrigger; if ( newBuildTrigger.getTrigger() == ContinuumProjectState.TRIGGER_SCHEDULED ) { newBuildTrigger.setTriggeredBy( buildDefinition.getSchedule().getName() ); } context.setBuildTrigger( newBuildTrigger ); context.setBuildDefinition( buildDefinition ); BuildResult oldBuildResult = buildResultDao.getLatestBuildResultForBuildDefinition( projectId, buildDefinitionId ); context.setOldBuildResult( oldBuildResult ); context.setScmResult( scmResult ); // CONTINUUM-2193 ProjectGroup projectGroup = project.getProjectGroup(); List<ProjectScmRoot> scmRoots = projectScmRootDao.getProjectScmRootByProjectGroup( projectGroup.getId() ); String projectScmUrl = project.getScmUrl(); String projectScmRootAddress = ""; for ( ProjectScmRoot projectScmRoot : scmRoots ) { projectScmRootAddress = projectScmRoot.getScmRootAddress(); if ( projectScmUrl.startsWith( projectScmRoot.getScmRootAddress() ) ) { AbstractContinuumAction.setProjectScmRootUrl( actionContext, projectScmRoot.getScmRootAddress() ); break; } } if ( project.isCheckedOutInSingleDirectory() ) { List<Project> projectsInGroup = projectGroupDao.getProjectGroupWithProjects( projectGroup.getId() ).getProjects(); List<Project> projectsWithCommonScmRoot = new ArrayList<Project>(); for ( Project projectInGroup : projectsInGroup ) { if ( projectInGroup.getScmUrl().startsWith( projectScmRootAddress ) ) { projectsWithCommonScmRoot.add( projectInGroup ); } } AbstractContinuumAction.setListOfProjectsInGroupWithCommonScmRoot( actionContext, projectsWithCommonScmRoot ); } // CONTINUUM-1871 olamy if continuum is killed during building oldBuildResult will have a endTime 0 // this means all changes since the project has been loaded in continuum will be in memory // now we will load all BuildResult with an Id bigger or equals than the oldBuildResult one //if ( oldBuildResult != null ) //{ // context.setOldScmResult( // getOldScmResults( projectId, oldBuildResult.getBuildNumber(), oldBuildResult.getEndTime() ) ); //} } catch ( ContinuumStoreException e ) { throw new TaskExecutionException( "Error initializing the build context", e ); } // Map<String, Object> actionContext = context.getActionContext(); AbstractContinuumAction.setProjectId( actionContext, projectId ); AbstractContinuumAction.setProject( actionContext, context.getProject() ); AbstractContinuumAction.setBuildDefinitionId( actionContext, buildDefinitionId ); AbstractContinuumAction.setBuildDefinition( actionContext, context.getBuildDefinition() ); AbstractContinuumAction.setBuildTrigger( actionContext, buildTrigger ); AbstractContinuumAction.setScmResult( actionContext, context.getScmResult() ); if ( context.getOldBuildResult() != null ) { AbstractContinuumAction.setOldBuildId( actionContext, context.getOldBuildResult().getId() ); } return context; } private void performAction( String actionName, BuildContext context ) throws TaskExecutionException { String error; TaskExecutionException exception; try { log.info( "Performing action " + actionName ); actionManager.lookup( actionName ).execute( context.getActionContext() ); return; } catch ( ActionNotFoundException e ) { error = ContinuumUtils.throwableToString( e ); exception = new TaskExecutionException( "Error looking up action '" + actionName + "'", e ); } catch ( ScmRepositoryException e ) { error = getValidationMessages( e ) + "\n" + ContinuumUtils.throwableToString( e ); exception = new TaskExecutionException( "SCM error while executing '" + actionName + "'", e ); } catch ( ScmException e ) { error = ContinuumUtils.throwableToString( e ); exception = new TaskExecutionException( "SCM error while executing '" + actionName + "'", e ); } catch ( Exception e ) { exception = new TaskExecutionException( "Error executing action '" + actionName + "'", e ); error = ContinuumUtils.throwableToString( exception ); } // TODO: clean this up. We catch the original exception from the action, and then update the buildresult // for it - we need to because of the specialized error message for SCM. // If updating the buildresult fails, log the previous error and throw the new one. // If updating the buildresult succeeds, throw the original exception. The build result should NOT // be updated again - a TaskExecutionException is final, no further action should be taken upon it. try { updateBuildResult( context, error ); } catch ( TaskExecutionException e ) { log.error( "Error updating build result after receiving the following exception: ", exception ); throw e; } throw exception; } protected boolean shouldBuild( BuildContext context ) throws TaskExecutionException { BuildDefinition buildDefinition = context.getBuildDefinition(); if ( buildDefinition.isAlwaysBuild() ) { log.info( "AlwaysBuild configured, building" ); return true; } if ( context.getOldBuildResult() == null ) { log.info( "The project has never been built with the current build definition, building" ); return true; } Project project = context.getProject(); //CONTINUUM-1428 if ( project.getOldState() == ContinuumProjectState.ERROR || context.getOldBuildResult().getState() == ContinuumProjectState.ERROR ) { log.info( "Latest state was 'ERROR', building" ); return true; } if ( context.getBuildTrigger().getTrigger() == ContinuumProjectState.TRIGGER_FORCED ) { log.info( "The project build is forced, building" ); return true; } boolean shouldBuild = false; boolean allChangesUnknown = true; if ( project.getOldState() != ContinuumProjectState.NEW && project.getOldState() != ContinuumProjectState.CHECKEDOUT && context.getBuildTrigger().getTrigger() != ContinuumProjectState.TRIGGER_FORCED && project.getState() != ContinuumProjectState.NEW && project.getState() != ContinuumProjectState.CHECKEDOUT ) { // Check SCM changes if ( context.getScmResult() != null ) { allChangesUnknown = checkAllChangesUnknown( context.getScmResult().getChanges() ); } if ( allChangesUnknown ) { if ( context.getScmResult() != null && !context.getScmResult().getChanges().isEmpty() ) { log.info( "The project was not built because all changes are unknown (maybe local modifications or ignored files not defined in your SCM tool." ); } else { log.info( "The project was not built because no changes were detected in sources since the last build." ); } } // Check dependencies changes if ( context.getModifiedDependencies() != null && !context.getModifiedDependencies().isEmpty() ) { log.info( "Found dependencies changes, building" ); shouldBuild = true; } } // Check changes if ( !shouldBuild && ( ( !allChangesUnknown && context.getScmResult() != null && !context.getScmResult().getChanges().isEmpty() ) || project.getExecutorId().equals( ContinuumBuildExecutorConstants.MAVEN_TWO_BUILD_EXECUTOR ) ) ) { try { ContinuumBuildExecutor executor = buildExecutorManager.getBuildExecutor( project.getExecutorId() ); Map<String, Object> actionContext = context.getActionContext(); List<Project> projectsWithCommonScmRoot = AbstractContinuumAction.getListOfProjectsInGroupWithCommonScmRoot( actionContext ); String projectScmRootUrl = AbstractContinuumAction.getProjectScmRootUrl( actionContext, project.getScmUrl() ); if ( executor == null ) { log.warn( "No continuum build executor found for project " + project.getId() + " with executor '" + project.getExecutorId() + "'" ); } else if ( context.getScmResult() != null ) { shouldBuild = executor.shouldBuild( context.getScmResult().getChanges(), project, workingDirectoryService.getWorkingDirectory( project, projectScmRootUrl, projectsWithCommonScmRoot ), context.getBuildDefinition() ); } } catch ( Exception e ) { updateBuildResult( context, ContinuumUtils.throwableToString( e ) ); throw new TaskExecutionException( "Can't determine if the project should build or not", e ); } } if ( shouldBuild ) { log.info( "Changes found in the current project, building" ); } else { project.setState( project.getOldState() ); project.setOldState( 0 ); try { projectDao.updateProject( project ); } catch ( ContinuumStoreException e ) { throw new TaskExecutionException( "Error storing project", e ); } log.info( "No changes in the current project, not building" ); } return shouldBuild; } private boolean checkAllChangesUnknown( List<ChangeSet> changes ) { for ( ChangeSet changeSet : changes ) { List<ChangeFile> changeFiles = changeSet.getFiles(); for ( ChangeFile changeFile : changeFiles ) { if ( !"unknown".equalsIgnoreCase( changeFile.getStatus() ) ) { return false; } } } return true; } private String getValidationMessages( ScmRepositoryException ex ) { List<String> messages = ex.getValidationMessages(); StringBuffer message = new StringBuffer(); if ( messages != null && !messages.isEmpty() ) { for ( Iterator<String> i = messages.iterator(); i.hasNext(); ) { message.append( i.next() ); if ( i.hasNext() ) { message.append( System.getProperty( "line.separator" ) ); } } } return message.toString(); } protected void checkProjectDependencies( BuildContext context ) { if ( context.getOldBuildResult() == null ) { return; } try { Project project = projectDao.getProjectWithDependencies( context.getProject().getId() ); List<ProjectDependency> dependencies = project.getDependencies(); if ( dependencies == null ) { dependencies = new ArrayList<ProjectDependency>(); } if ( project.getParent() != null ) { dependencies.add( project.getParent() ); } if ( dependencies.isEmpty() ) { return; } List<ProjectDependency> modifiedDependencies = new ArrayList<ProjectDependency>(); for ( ProjectDependency dep : dependencies ) { Project dependencyProject = projectDao.getProject( dep.getGroupId(), dep.getArtifactId(), dep.getVersion() ); if ( dependencyProject != null ) { long nbBuild = buildResultDao.getNbBuildResultsInSuccessForProject( dependencyProject.getId(), context.getOldBuildResult().getEndTime() ); if ( nbBuild > 0 ) { log.debug( "Dependency changed: " + dep.getGroupId() + ":" + dep.getArtifactId() + ":" + dep.getVersion() ); modifiedDependencies.add( dep ); } else { log.debug( "Dependency not changed: " + dep.getGroupId() + ":" + dep.getArtifactId() + ":" + dep.getVersion() ); } } else { log.debug( "Skip non Continuum project: " + dep.getGroupId() + ":" + dep.getArtifactId() + ":" + dep.getVersion() ); } } context.setModifiedDependencies( modifiedDependencies ); AbstractContinuumAction.setUpdatedDependencies( context.getActionContext(), modifiedDependencies ); } catch ( ContinuumStoreException e ) { log.warn( "Can't get the project dependencies", e ); } } // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- private BuildResult makeAndStoreBuildResult( BuildContext context, String error ) throws TaskExecutionException { // Project project, ScmResult scmResult, long startTime, int trigger ) // project, scmResult, startTime, trigger ); BuildResult build = new BuildResult(); build.setState( ContinuumProjectState.ERROR ); build.setTrigger( context.getBuildTrigger().getTrigger() ); build.setUsername( context.getBuildTrigger().getTriggeredBy() ); build.setStartTime( context.getStartTime() ); build.setEndTime( System.currentTimeMillis() ); updateBuildResult( build, context ); build.setScmResult( context.getScmResult() ); build.setBuildDefinition( context.getBuildDefinition() ); if ( error != null ) { build.setError( error ); } try { buildResultDao.addBuildResult( context.getProject(), build ); build = buildResultDao.getBuildResult( build.getId() ); context.setBuildResult( build ); return build; } catch ( ContinuumStoreException e ) { throw new TaskExecutionException( "Error storing build result", e ); } } /** * Check to see if there was a error while checking out/updating the project * * @param context The build context * @return true if scm result is ok * @throws TaskExecutionException */ private boolean checkScmResult( BuildContext context ) throws TaskExecutionException { Project project = context.getProject(); int projectGroupId = project.getProjectGroup().getId(); List<ProjectScmRoot> scmRoots = projectScmRootDao.getProjectScmRootByProjectGroup( projectGroupId ); for ( ProjectScmRoot projectScmRoot : scmRoots ) { if ( project.getScmUrl().startsWith( projectScmRoot.getScmRootAddress() ) ) { if ( projectScmRoot.getState() == ContinuumProjectState.UPDATED ) { return true; } break; } } return false; } }
5,146
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/buildcontroller/BuildContext.java
package org.apache.maven.continuum.buildcontroller; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.utils.build.BuildTrigger; import org.apache.maven.continuum.model.project.BuildDefinition; import org.apache.maven.continuum.model.project.BuildResult; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.model.project.ProjectDependency; import org.apache.maven.continuum.model.scm.ScmResult; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * This class holds build context information. * * @author <a href="mailto:kenney@apache.org">Kenney Westerhof</a> */ public class BuildContext { private long startTime; private Project project; private BuildDefinition buildDefinition; private BuildResult oldBuildResult; private ScmResult oldScmResult; private Map<String, Object> actionContext; private ScmResult scmResult; private BuildTrigger buildTrigger; private BuildResult buildResult; private List<ProjectDependency> modifiedDependencies; private boolean cancelled; public void setStartTime( long startTime ) { this.startTime = startTime; } public long getStartTime() { return startTime; } public void setProject( Project project ) { this.project = project; } public Project getProject() { return project; } public void setBuildDefinition( BuildDefinition buildDefinition ) { this.buildDefinition = buildDefinition; } public BuildDefinition getBuildDefinition() { return buildDefinition; } public void setBuildResult( BuildResult build ) { this.buildResult = build; } public BuildResult getBuildResult() { return buildResult; } public void setOldBuildResult( BuildResult buildResult ) { this.oldBuildResult = buildResult; } public BuildResult getOldBuildResult() { return oldBuildResult; } public void setOldScmResult( ScmResult oldScmResult ) { this.oldScmResult = oldScmResult; } public ScmResult getOldScmResult() { return oldScmResult; } public void setScmResult( ScmResult scmResult ) { this.scmResult = scmResult; } public ScmResult getScmResult() { return scmResult; } public Map<String, Object> getActionContext() { if ( actionContext == null ) { actionContext = new HashMap<String, Object>(); } return actionContext; } public BuildTrigger getBuildTrigger() { return buildTrigger; } public void setBuildTrigger( BuildTrigger buildTrigger ) { this.buildTrigger = buildTrigger; } public List<ProjectDependency> getModifiedDependencies() { if ( modifiedDependencies == null ) { modifiedDependencies = new ArrayList<ProjectDependency>(); } return modifiedDependencies; } public void setModifiedDependencies( List<ProjectDependency> modifiedDependencies ) { this.modifiedDependencies = modifiedDependencies; } public boolean isCancelled() { return cancelled; } public void setCancelled( boolean cancelled ) { this.cancelled = cancelled; } }
5,147
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum
Create_ds/continuum/continuum-core/src/main/java/org/apache/maven/continuum/buildcontroller/BuildProjectTaskExecutor.java
package org.apache.maven.continuum.buildcontroller; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.taskqueue.BuildProjectTask; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.taskqueue.Task; import org.codehaus.plexus.taskqueue.execution.TaskExecutionException; import org.codehaus.plexus.taskqueue.execution.TaskExecutor; /** * @author <a href="mailto:trygvis@inamo.no">Trygve Laugst&oslash;l</a> */ public class BuildProjectTaskExecutor implements TaskExecutor { @Requirement private BuildController controller; // ---------------------------------------------------------------------- // TaskExecutor Implementation // ---------------------------------------------------------------------- public void executeTask( Task task ) throws TaskExecutionException { BuildProjectTask buildProjectTask = (BuildProjectTask) task; controller.build( buildProjectTask.getProjectId(), buildProjectTask.getBuildDefinitionId(), buildProjectTask.getBuildTrigger(), buildProjectTask.getScmResult() ); } }
5,148
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/continuum
Create_ds/continuum/continuum-core/src/main/java/org/apache/continuum/taskqueue/DefaultOverallBuildQueue.java
package org.apache.continuum.taskqueue; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.commons.lang.ArrayUtils; import org.apache.continuum.dao.BuildDefinitionDao; import org.apache.continuum.taskqueueexecutor.ParallelBuildsThreadedTaskQueueExecutor; import org.apache.continuum.utils.build.BuildTrigger; import org.apache.maven.continuum.model.project.BuildDefinition; import org.apache.maven.continuum.store.ContinuumStoreException; import org.codehaus.plexus.taskqueue.Task; 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; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.Resource; /** * "Overall" build queue which has a checkout queue and a build queue. * * @author <a href="mailto:oching@apache.org">Maria Odea Ching</a> */ public class DefaultOverallBuildQueue implements OverallBuildQueue { private static final Logger log = LoggerFactory.getLogger( DefaultOverallBuildQueue.class ); @Resource private BuildDefinitionDao buildDefinitionDao; private TaskQueueExecutor buildTaskQueueExecutor; private TaskQueueExecutor checkoutTaskQueueExecutor; private TaskQueueExecutor prepareBuildTaskQueueExecutor; private int id; private String name; public int getId() { return id; } public void setId( int id ) { this.id = id; } public String getName() { return name; } public void setName( String name ) { this.name = name; } /** * @see OverallBuildQueue#addToCheckoutQueue(CheckOutTask) */ public void addToCheckoutQueue( CheckOutTask checkoutTask ) throws TaskQueueException { getCheckoutQueue().put( checkoutTask ); } /** * @see OverallBuildQueue#addToCheckoutQueue(List) */ public void addToCheckoutQueue( List<CheckOutTask> checkoutTasks ) throws TaskQueueException { for ( CheckOutTask checkoutTask : checkoutTasks ) { getCheckoutQueue().put( checkoutTask ); } } /** * @see OverallBuildQueue#getProjectsInCheckoutQueue() */ public List<CheckOutTask> getProjectsInCheckoutQueue() throws TaskQueueException { return getCheckoutQueue().getQueueSnapshot(); } /** * @see OverallBuildQueue#isInCheckoutQueue(int) */ public boolean isInCheckoutQueue( int projectId ) throws TaskQueueException { List<CheckOutTask> queue = getProjectsInCheckoutQueue(); for ( CheckOutTask task : queue ) { if ( task != null && task.getProjectId() == projectId ) { return true; } } return false; } /** * @see OverallBuildQueue#removeProjectFromCheckoutQueue(int) */ public boolean removeProjectFromCheckoutQueue( int projectId ) throws TaskQueueException { List<CheckOutTask> queue = getProjectsInCheckoutQueue(); for ( CheckOutTask task : queue ) { if ( task != null && task.getProjectId() == projectId ) { return getCheckoutQueue().remove( task ); } } return false; } /** * @see OverallBuildQueue#removeProjectsFromCheckoutQueue(int[]) */ public boolean removeProjectsFromCheckoutQueue( int[] projectsId ) throws TaskQueueException { if ( projectsId == null ) { return false; } if ( projectsId.length < 1 ) { return false; } List<CheckOutTask> queue = getProjectsInCheckoutQueue(); List<CheckOutTask> tasks = new ArrayList<CheckOutTask>(); for ( CheckOutTask task : queue ) { if ( task != null ) { if ( ArrayUtils.contains( projectsId, task.getProjectId() ) ) { tasks.add( task ); } } } return !tasks.isEmpty() && getCheckoutQueue().removeAll( tasks ); } /** * @see OverallBuildQueue#removeTasksFromCheckoutQueueWithHashCodes(int[]) */ public void removeTasksFromCheckoutQueueWithHashCodes( int[] hashCodes ) throws TaskQueueException { List<CheckOutTask> queue = getProjectsInCheckoutQueue(); for ( CheckOutTask task : queue ) { if ( ArrayUtils.contains( hashCodes, task.hashCode() ) ) { getCheckoutQueue().remove( task ); } } } /** * @see OverallBuildQueue#addToBuildQueue(BuildProjectTask) */ public void addToBuildQueue( BuildProjectTask buildTask ) throws TaskQueueException { getBuildQueue().put( buildTask ); } /** * @see OverallBuildQueue#addToBuildQueue(List) */ public void addToBuildQueue( List<BuildProjectTask> buildTasks ) throws TaskQueueException { for ( BuildProjectTask buildTask : buildTasks ) { getBuildQueue().put( buildTask ); } } /** * @see OverallBuildQueue#getProjectsInBuildQueue() */ public List<BuildProjectTask> getProjectsInBuildQueue() throws TaskQueueException { return getBuildQueue().getQueueSnapshot(); } /** * @see OverallBuildQueue#isInBuildQueue(int) */ public boolean isInBuildQueue( int projectId ) throws TaskQueueException { return isInBuildQueue( projectId, -1 ); } /** * @see OverallBuildQueue#isInBuildQueue(int, int) */ public boolean isInBuildQueue( int projectId, int buildDefinitionId ) throws TaskQueueException { List<BuildProjectTask> queue = getProjectsInBuildQueue(); for ( BuildProjectTask buildTask : queue ) { if ( buildTask != null ) { if ( buildDefinitionId < 0 ) { if ( buildTask.getProjectId() == projectId ) { return true; } } else { if ( buildTask.getProjectId() == projectId && buildTask.getBuildDefinitionId() == buildDefinitionId ) { return true; } } } } return false; } /** * @see OverallBuildQueue#cancelBuildTask(int) */ public void cancelBuildTask( int projectId ) { BuildProjectTask task = (BuildProjectTask) buildTaskQueueExecutor.getCurrentTask(); if ( task != null && task.getProjectId() == projectId ) { log.info( "Cancelling build task for project '" + projectId + "' in task executor '" + buildTaskQueueExecutor ); buildTaskQueueExecutor.cancelTask( task ); } } /** * @see OverallBuildQueue#cancelCheckoutTask(int) */ public void cancelCheckoutTask( int projectId ) throws TaskQueueException { CheckOutTask task = (CheckOutTask) checkoutTaskQueueExecutor.getCurrentTask(); if ( task != null && task.getProjectId() == projectId ) { log.info( "Cancelling checkout task for project '" + projectId + "' in task executor '" + checkoutTaskQueueExecutor ); checkoutTaskQueueExecutor.cancelTask( task ); } } /** * @see OverallBuildQueue#cancelCurrentBuild() */ public boolean cancelCurrentBuild() { Task task = buildTaskQueueExecutor.getCurrentTask(); if ( task != null ) { return buildTaskQueueExecutor.cancelTask( task ); } log.info( "No build task currently executing on build executor: " + buildTaskQueueExecutor ); return false; } /** * @see OverallBuildQueue#cancelCurrentCheckout() */ public boolean cancelCurrentCheckout() { Task task = checkoutTaskQueueExecutor.getCurrentTask(); if ( task != null ) { return checkoutTaskQueueExecutor.cancelTask( task ); } log.info( "No checkout task currently executing on checkout task executor: " + checkoutTaskQueueExecutor ); return false; } /** * @see OverallBuildQueue#removeProjectFromBuildQueue(int, int, BuildTrigger, String, int) */ public boolean removeProjectFromBuildQueue( int projectId, int buildDefinitionId, BuildTrigger buildTrigger, String projectName, int projectGroupId ) throws TaskQueueException { BuildDefinition buildDefinition; // maybe we could just pass the label as a parameter to eliminate dependency to BuildDefinitionDAO? try { buildDefinition = buildDefinitionDao.getBuildDefinition( buildDefinitionId ); } catch ( ContinuumStoreException e ) { throw new TaskQueueException( "Error while removing project from build queue: " + projectName, e ); } String buildDefinitionLabel = buildDefinition.getDescription(); if ( StringUtils.isEmpty( buildDefinitionLabel ) ) { buildDefinitionLabel = buildDefinition.getGoals(); } BuildProjectTask buildProjectTask = new BuildProjectTask( projectId, buildDefinitionId, buildTrigger, projectName, buildDefinitionLabel, null, projectGroupId ); return getBuildQueue().remove( buildProjectTask ); } /** * @see OverallBuildQueue#removeProjectsFromBuildQueue(int[]) */ public boolean removeProjectsFromBuildQueue( int[] projectIds ) throws TaskQueueException { if ( projectIds == null ) { return false; } if ( projectIds.length < 1 ) { return false; } List<BuildProjectTask> queue = getProjectsInBuildQueue(); List<BuildProjectTask> tasks = new ArrayList<BuildProjectTask>(); for ( BuildProjectTask buildTask : queue ) { if ( buildTask != null ) { if ( ArrayUtils.contains( projectIds, buildTask.getProjectId() ) ) { tasks.add( buildTask ); } } } for ( BuildProjectTask buildProjectTask : tasks ) { log.info( "cancel build for project " + buildProjectTask.getProjectId() ); } return !tasks.isEmpty() && getBuildQueue().removeAll( tasks ); } /** * @see OverallBuildQueue#removeProjectFromBuildQueue(int) */ public boolean removeProjectFromBuildQueue( int projectId ) throws TaskQueueException { List<BuildProjectTask> queue = getProjectsInBuildQueue(); for ( BuildProjectTask buildTask : queue ) { if ( buildTask != null && buildTask.getProjectId() == projectId ) { return getBuildQueue().remove( buildTask ); } } return false; } /** * @see OverallBuildQueue#removeProjectsFromBuildQueueWithHashCodes(int[]) */ public void removeProjectsFromBuildQueueWithHashCodes( int[] hashCodes ) throws TaskQueueException { List<BuildProjectTask> queue = getProjectsInBuildQueue(); for ( BuildProjectTask task : queue ) { if ( ArrayUtils.contains( hashCodes, task.hashCode() ) ) { getBuildQueue().remove( task ); } } } /* Prepare Build */ /** * @see OverallBuildQueue#addToPrepareBuildQueue(PrepareBuildProjectsTask) */ public void addToPrepareBuildQueue( PrepareBuildProjectsTask prepareBuildTask ) throws TaskQueueException { getPrepareBuildQueue().put( prepareBuildTask ); } /** * @see OverallBuildQueue#addToPrepareBuildQueue(List) */ public void addToPrepareBuildQueue( List<PrepareBuildProjectsTask> prepareBuildTasks ) throws TaskQueueException { for ( PrepareBuildProjectsTask prepareBuildTask : prepareBuildTasks ) { getPrepareBuildQueue().put( prepareBuildTask ); } } /** * @see OverallBuildQueue#getProjectsInPrepareBuildQueue() */ public List<PrepareBuildProjectsTask> getProjectsInPrepareBuildQueue() throws TaskQueueException { return getPrepareBuildQueue().getQueueSnapshot(); } /** * @see OverallBuildQueue#isInPrepareBuildQueue(int) */ public boolean isInPrepareBuildQueue( int projectId ) throws TaskQueueException { List<PrepareBuildProjectsTask> queue = getProjectsInPrepareBuildQueue(); for ( PrepareBuildProjectsTask task : queue ) { if ( task != null ) { 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 already in prepare build queue", projectId ); return true; } } } } return false; } /** * @see OverallBuildQueue#isInPrepareBuildQueue(int, int) */ public boolean isInPrepareBuildQueue( int projectGroupId, int scmRootId ) throws TaskQueueException { List<PrepareBuildProjectsTask> queue = getProjectsInPrepareBuildQueue(); for ( PrepareBuildProjectsTask task : queue ) { if ( task != null && task.getProjectGroupId() == projectGroupId && task.getProjectScmRootId() == scmRootId ) { log.info( "Project group {} with scm root {} is in prepare build queue {}", new Object[]{projectGroupId, scmRootId, task} ); return true; } } return false; } /** * @see OverallBuildQueue#isInPrepareBuildQueue(int, String) */ public boolean isInPrepareBuildQueue( int projectGroupId, String scmRootAddress ) throws TaskQueueException { List<PrepareBuildProjectsTask> queue = getProjectsInPrepareBuildQueue(); for ( PrepareBuildProjectsTask task : queue ) { if ( task != null && task.getProjectGroupId() == projectGroupId && task.getScmRootAddress().equals( scmRootAddress ) ) { log.info( "Project group {} with scm root {} is in prepare build queue {}", new Object[]{projectGroupId, scmRootAddress, task} ); return true; } } return false; } /** * @see OverallBuildQueue#cancelPrepareBuildTask(int, int) */ public void cancelPrepareBuildTask( int projectGroupId, int scmRootId ) { PrepareBuildProjectsTask task = (PrepareBuildProjectsTask) prepareBuildTaskQueueExecutor.getCurrentTask(); if ( task != null && task.getProjectGroupId() == projectGroupId && task.getProjectScmRootId() == scmRootId ) { log.info( "Cancelling prepare build task for project group '{}' with scmRootId '{}' in task executor '{}'", new Object[]{projectGroupId, scmRootId, prepareBuildTaskQueueExecutor} ); prepareBuildTaskQueueExecutor.cancelTask( task ); } } /** * @see OverallBuildQueue#cancelPrepareBuildTask(int) */ public void cancelPrepareBuildTask( int projectId ) { PrepareBuildProjectsTask task = (PrepareBuildProjectsTask) prepareBuildTaskQueueExecutor.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 ) ) ) { log.info( "Cancelling prepare build task for project '{}' in task executor '{}'", projectId, prepareBuildTaskQueueExecutor ); prepareBuildTaskQueueExecutor.cancelTask( task ); } } } } /** * @see OverallBuildQueue#cancelCurrentPrepareBuild() */ public boolean cancelCurrentPrepareBuild() { Task task = prepareBuildTaskQueueExecutor.getCurrentTask(); if ( task != null ) { return prepareBuildTaskQueueExecutor.cancelTask( task ); } log.info( "No prepare build task currently executing on build executor: {}", buildTaskQueueExecutor ); return false; } /** * @see OverallBuildQueue#removeProjectFromPrepareBuildQueue(int, int) */ public boolean removeProjectFromPrepareBuildQueue( int projectGroupId, int scmRootId ) throws TaskQueueException { List<PrepareBuildProjectsTask> tasks = getProjectsInPrepareBuildQueue(); if ( tasks != null ) { for ( PrepareBuildProjectsTask task : tasks ) { if ( task.getProjectGroupId() == projectGroupId && task.getProjectScmRootId() == scmRootId ) { return getPrepareBuildQueue().remove( task ); } } } return false; } /** * @see OverallBuildQueue#removeProjectFromPrepareBuildQueue(int, String) */ public boolean removeProjectFromPrepareBuildQueue( int projectGroupId, String scmRootAddress ) throws TaskQueueException { List<PrepareBuildProjectsTask> queue = getProjectsInPrepareBuildQueue(); for ( PrepareBuildProjectsTask task : queue ) { if ( task != null && task.getProjectGroupId() == projectGroupId && task.getScmRootAddress().equals( scmRootAddress ) ) { return getPrepareBuildQueue().remove( task ); } } return false; } /** * @see OverallBuildQueue#removeProjectsFromPrepareBuildQueueWithHashCodes(int[]) */ public void removeProjectsFromPrepareBuildQueueWithHashCodes( int[] hashCodes ) throws TaskQueueException { List<PrepareBuildProjectsTask> tasks = getProjectsInPrepareBuildQueue(); if ( tasks != null ) { for ( PrepareBuildProjectsTask task : tasks ) { if ( ArrayUtils.contains( hashCodes, task.getHashCode() ) ) { getPrepareBuildQueue().remove( task ); } } } } /** * @see OverallBuildQueue#getCheckoutQueue() */ public TaskQueue getCheckoutQueue() { return ( (ParallelBuildsThreadedTaskQueueExecutor) checkoutTaskQueueExecutor ).getQueue(); } /** * @see OverallBuildQueue#getBuildQueue() */ public TaskQueue getBuildQueue() { return ( (ParallelBuildsThreadedTaskQueueExecutor) buildTaskQueueExecutor ).getQueue(); } /** * @see OverallBuildQueue#getPrepareBuildQueue() */ public TaskQueue getPrepareBuildQueue() { return ( (ParallelBuildsThreadedTaskQueueExecutor) prepareBuildTaskQueueExecutor ).getQueue(); } /** * @see OverallBuildQueue#getBuildTaskQueueExecutor() */ public TaskQueueExecutor getBuildTaskQueueExecutor() { return buildTaskQueueExecutor; } /** * @see OverallBuildQueue#getCheckoutTaskQueueExecutor() */ public TaskQueueExecutor getCheckoutTaskQueueExecutor() { return checkoutTaskQueueExecutor; } /** * @see OverallBuildQueue#getPrepareBuildTaskQueueExecutor() */ public TaskQueueExecutor getPrepareBuildTaskQueueExecutor() { return prepareBuildTaskQueueExecutor; } public void setBuildDefinitionDao( BuildDefinitionDao buildDefinitionDao ) { this.buildDefinitionDao = buildDefinitionDao; } public void setBuildTaskQueueExecutor( TaskQueueExecutor buildTaskQueueExecutor ) { this.buildTaskQueueExecutor = buildTaskQueueExecutor; } public void setCheckoutTaskQueueExecutor( TaskQueueExecutor checkoutTaskQueueExecutor ) { this.checkoutTaskQueueExecutor = checkoutTaskQueueExecutor; } public void setPrepareBuildTaskQueueExecutor( TaskQueueExecutor prepareBuildTaskQueueExecutor ) { this.prepareBuildTaskQueueExecutor = prepareBuildTaskQueueExecutor; } }
5,149
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/continuum/taskqueue
Create_ds/continuum/continuum-core/src/main/java/org/apache/continuum/taskqueue/manager/DefaultTaskQueueManager.java
package org.apache.continuum.taskqueue.manager; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.commons.lang.ArrayUtils; import org.apache.continuum.buildmanager.BuildManagerException; import org.apache.continuum.buildmanager.BuildsManager; import org.apache.continuum.dao.ProjectDao; import org.apache.continuum.model.repository.LocalRepository; import org.apache.continuum.model.repository.RepositoryPurgeConfiguration; import org.apache.continuum.purge.PurgeConfigurationService; import org.apache.continuum.purge.task.PurgeTask; import org.apache.continuum.taskqueue.BuildProjectTask; import org.apache.continuum.taskqueue.PrepareBuildProjectsTask; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.release.tasks.PerformReleaseProjectTask; import org.apache.maven.continuum.release.tasks.PrepareReleaseProjectTask; import org.apache.maven.continuum.store.ContinuumStoreException; import org.codehaus.plexus.PlexusConstants; import org.codehaus.plexus.PlexusContainer; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; 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.taskqueue.Task; import org.codehaus.plexus.taskqueue.TaskQueue; import org.codehaus.plexus.taskqueue.TaskQueueException; import org.codehaus.plexus.taskqueue.execution.TaskQueueExecutor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; /** * @author <a href="mailto:ctan@apache.org">Maria Catherine Tan</a> */ @Component( role = org.apache.continuum.taskqueue.manager.TaskQueueManager.class, hint = "default" ) public class DefaultTaskQueueManager implements TaskQueueManager, Contextualizable { private static final Logger log = LoggerFactory.getLogger( DefaultTaskQueueManager.class ); @Requirement( hint = "distributed-build-project" ) private TaskQueue distributedBuildQueue; @Requirement( hint = "purge" ) private TaskQueue purgeQueue; @Requirement( hint = "prepare-release" ) private TaskQueue prepareReleaseQueue; @Requirement( hint = "perform-release" ) private TaskQueue performReleaseQueue; @Requirement private ProjectDao projectDao; @Requirement private PurgeConfigurationService purgeConfigurationService; @Requirement( hint = "parallel" ) private BuildsManager buildsManager; private PlexusContainer container; public TaskQueue getDistributedBuildQueue() { return distributedBuildQueue; } public List<PrepareBuildProjectsTask> getDistributedBuildProjectsInQueue() throws TaskQueueManagerException { try { return distributedBuildQueue.getQueueSnapshot(); } catch ( TaskQueueException e ) { throw new TaskQueueManagerException( "Error while getting the distributed building queue", e ); } } public TaskQueue getPurgeQueue() { return purgeQueue; } public boolean isInDistributedBuildQueue( int projectGroupId, String scmRootAddress ) throws TaskQueueManagerException { try { List<PrepareBuildProjectsTask> queue = distributedBuildQueue.getQueueSnapshot(); for ( PrepareBuildProjectsTask task : queue ) { if ( task != null ) { if ( task.getProjectGroupId() == projectGroupId && task.getScmRootAddress().equals( scmRootAddress ) ) { return true; } } } return false; } catch ( TaskQueueException e ) { throw new TaskQueueManagerException( "Error while getting the tasks in distributed build queue", e ); } } public boolean isInPurgeQueue( int purgeConfigId ) throws TaskQueueManagerException { List<PurgeTask> queue = getAllPurgeConfigurationsInPurgeQueue(); for ( PurgeTask task : queue ) { if ( task != null && task.getPurgeConfigurationId() == purgeConfigId ) { return true; } } return false; } public boolean isRepositoryInPurgeQueue( int repositoryId ) throws TaskQueueManagerException { List<RepositoryPurgeConfiguration> repoPurgeConfigs = purgeConfigurationService.getRepositoryPurgeConfigurationsByRepository( repositoryId ); for ( RepositoryPurgeConfiguration repoPurge : repoPurgeConfigs ) { if ( isInPurgeQueue( repoPurge.getId() ) ) { return true; } } return false; } public boolean isRepositoryInUse( int repositoryId ) throws TaskQueueManagerException { try { Map<String, BuildProjectTask> currentBuilds = buildsManager.getCurrentBuilds(); Set<String> keys = currentBuilds.keySet(); for ( String key : keys ) { BuildProjectTask task = currentBuilds.get( key ); if ( task != null ) { int projectId = task.getProjectId(); Project project = projectDao.getProject( projectId ); LocalRepository repository = project.getProjectGroup().getLocalRepository(); if ( repository != null && repository.getId() == repositoryId ) { return true; } } } return false; } catch ( BuildManagerException e ) { log.error( "Error occured while getting current builds: " + e.getMessage() ); throw new TaskQueueManagerException( e.getMessage(), e ); } catch ( ContinuumStoreException e ) { log.error( "Error occured while getting project details: " + e.getMessage() ); throw new TaskQueueManagerException( e.getMessage(), e ); } } public boolean isProjectInReleaseStage( String releaseId ) throws TaskQueueManagerException { Task prepareTask = getCurrentTask( "prepare-release" ); if ( prepareTask != null && prepareTask instanceof PrepareReleaseProjectTask ) { if ( ( (PrepareReleaseProjectTask) prepareTask ).getReleaseId().equals( releaseId ) ) { return true; } else { try { // check if in queue List<Task> tasks = prepareReleaseQueue.getQueueSnapshot(); for ( Task prepareReleaseTask : tasks ) { if ( ( (PrepareReleaseProjectTask) prepareReleaseTask ).getReleaseId().equals( releaseId ) ) { return true; } } } catch ( TaskQueueException e ) { throw new TaskQueueManagerException( e ); } } } Task performTask = getCurrentTask( "perform-release" ); if ( performTask != null && performTask instanceof PerformReleaseProjectTask ) { if ( ( (PerformReleaseProjectTask) performTask ).getReleaseId().equals( releaseId ) ) { return true; } else { try { // check if in queue List<Task> tasks = performReleaseQueue.getQueueSnapshot(); for ( Task performReleaseTask : tasks ) { if ( ( (PerformReleaseProjectTask) performReleaseTask ).getReleaseId().equals( releaseId ) ) { return true; } } } catch ( TaskQueueException e ) { throw new TaskQueueManagerException( e ); } } } return false; } public boolean releaseInProgress() throws TaskQueueManagerException { Task task = getCurrentTask( "perform-release" ); return task != null && task instanceof PerformReleaseProjectTask; } public void removeFromDistributedBuildQueue( int projectGroupId, String scmRootAddress ) throws TaskQueueManagerException { List<PrepareBuildProjectsTask> queue = getDistributedBuildProjectsInQueue(); for ( PrepareBuildProjectsTask task : queue ) { if ( task.getProjectGroupId() == projectGroupId && task.getScmRootAddress().equals( scmRootAddress ) ) { distributedBuildQueue.remove( task ); } } } public boolean removeFromPurgeQueue( int purgeConfigId ) throws TaskQueueManagerException { List<PurgeTask> queue = getAllPurgeConfigurationsInPurgeQueue(); for ( PurgeTask task : queue ) { if ( task != null && task.getPurgeConfigurationId() == purgeConfigId ) { return purgeQueue.remove( task ); } } return false; } public boolean removeFromPurgeQueue( int[] purgeConfigIds ) throws TaskQueueManagerException { if ( purgeConfigIds == null ) { return false; } if ( purgeConfigIds.length < 1 ) { return false; } List<PurgeTask> queue = getAllPurgeConfigurationsInPurgeQueue(); List<PurgeTask> tasks = new ArrayList<PurgeTask>(); for ( PurgeTask task : queue ) { if ( task != null ) { if ( ArrayUtils.contains( purgeConfigIds, task.getPurgeConfigurationId() ) ) { tasks.add( task ); } } } return !tasks.isEmpty() && purgeQueue.removeAll( tasks ); } public void removeRepositoryFromPurgeQueue( int repositoryId ) throws TaskQueueManagerException { List<RepositoryPurgeConfiguration> repoPurgeConfigs = purgeConfigurationService.getRepositoryPurgeConfigurationsByRepository( repositoryId ); for ( RepositoryPurgeConfiguration repoPurge : repoPurgeConfigs ) { removeFromPurgeQueue( repoPurge.getId() ); } } public void removeTasksFromDistributedBuildQueueWithHashCodes( int[] hashCodes ) throws TaskQueueManagerException { List<PrepareBuildProjectsTask> queue = getDistributedBuildProjectsInQueue(); for ( PrepareBuildProjectsTask task : queue ) { if ( ArrayUtils.contains( hashCodes, task.hashCode() ) ) { distributedBuildQueue.remove( task ); } } } public void contextualize( Context context ) throws ContextException { container = (PlexusContainer) context.get( PlexusConstants.PLEXUS_KEY ); } private List<PurgeTask> getAllPurgeConfigurationsInPurgeQueue() throws TaskQueueManagerException { try { return purgeQueue.getQueueSnapshot(); } catch ( TaskQueueException e ) { throw new TaskQueueManagerException( "Error while getting the purge configs in purge queue", e ); } } private Task getCurrentTask( String task ) throws TaskQueueManagerException { try { TaskQueueExecutor executor = (TaskQueueExecutor) container.lookup( TaskQueueExecutor.class, task ); return executor.getCurrentTask(); } catch ( ComponentLookupException e ) { throw new TaskQueueManagerException( "Unable to lookup current task", e ); } } }
5,150
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/continuum
Create_ds/continuum/continuum-core/src/main/java/org/apache/continuum/repository/DefaultRepositoryService.java
package org.apache.continuum.repository; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.dao.LocalRepositoryDao; import org.apache.continuum.dao.ProjectGroupDao; import org.apache.continuum.dao.RepositoryPurgeConfigurationDao; import org.apache.continuum.model.repository.LocalRepository; import org.apache.continuum.model.repository.RepositoryPurgeConfiguration; import org.apache.continuum.taskqueue.manager.TaskQueueManager; import org.apache.continuum.taskqueue.manager.TaskQueueManagerException; import org.apache.maven.continuum.model.project.ProjectGroup; import org.apache.maven.continuum.store.ContinuumObjectNotFoundException; import org.apache.maven.continuum.store.ContinuumStoreException; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; /** * DefaultRepositoryService * * @author Maria Catherine Tan * @since 25 jul 07 */ @Component( role = org.apache.continuum.repository.RepositoryService.class, hint = "default" ) public class DefaultRepositoryService implements RepositoryService { private static final Logger log = LoggerFactory.getLogger( DefaultRepositoryService.class ); @Requirement private LocalRepositoryDao localRepositoryDao; @Requirement private RepositoryPurgeConfigurationDao repositoryPurgeConfigurationDao; @Requirement private ProjectGroupDao projectGroupDao; @Requirement private TaskQueueManager taskQueueManager; public LocalRepository addLocalRepository( LocalRepository localRepository ) throws RepositoryServiceException { LocalRepository repository = null; try { List<LocalRepository> repos = getAllLocalRepositories(); for ( LocalRepository repo : repos ) { if ( repo.getName().equals( localRepository.getName() ) ) { throw new RepositoryServiceException( "Local repository name must be unique" ); } if ( repo.getLocation().equals( localRepository.getLocation() ) ) { throw new RepositoryServiceException( "Local repository location must be unique" ); } } localRepository.setName( localRepository.getName().trim() ); localRepository.setLocation( localRepository.getLocation().trim() ); repository = localRepositoryDao.addLocalRepository( localRepository ); log.info( "Added new local repository: " + repository.getName() ); } catch ( ContinuumStoreException e ) { throw new RepositoryServiceException( "Unable to add the requested local repository", e ); } return repository; } public void removeLocalRepository( int repositoryId ) throws RepositoryServiceException { try { LocalRepository repository = getLocalRepository( repositoryId ); if ( taskQueueManager.isRepositoryInUse( repositoryId ) ) { return; } if ( taskQueueManager.isRepositoryInPurgeQueue( repositoryId ) ) { taskQueueManager.removeRepositoryFromPurgeQueue( repositoryId ); } log.info( "Remove purge configurations of " + repository.getName() ); removePurgeConfigurationsOfRepository( repositoryId ); List<ProjectGroup> groups = projectGroupDao.getProjectGroupByRepository( repositoryId ); for ( ProjectGroup group : groups ) { group.setLocalRepository( null ); projectGroupDao.updateProjectGroup( group ); } localRepositoryDao.removeLocalRepository( repository ); log.info( "Removed local repository: " + repository.getName() ); } catch ( TaskQueueManagerException e ) { // swallow? } catch ( ContinuumStoreException e ) { throw new RepositoryServiceException( "Unable to delete the requested local repository", e ); } } public void updateLocalRepository( LocalRepository localRepository ) throws RepositoryServiceException { localRepository.setName( localRepository.getName().trim() ); localRepository.setLocation( localRepository.getLocation().trim() ); try { if ( taskQueueManager.isRepositoryInUse( localRepository.getId() ) ) { return; } localRepositoryDao.updateLocalRepository( localRepository ); log.info( "Updated local repository: " + localRepository.getName() ); } catch ( TaskQueueManagerException e ) { // swallow? } catch ( ContinuumStoreException e ) { throw new RepositoryServiceException( "Unable to update the requested local repository", e ); } } public List<LocalRepository> getAllLocalRepositories() { return localRepositoryDao.getAllLocalRepositories(); } public List<LocalRepository> getLocalRepositoriesByLayout( String layout ) { return localRepositoryDao.getLocalRepositoriesByLayout( layout ); } public LocalRepository getLocalRepositoryByLocation( String location ) throws RepositoryServiceException { try { return localRepositoryDao.getLocalRepositoryByLocation( location ); } catch ( ContinuumObjectNotFoundException e ) { throw new RepositoryServiceException( "No repository found with location: " + location, e ); } catch ( ContinuumStoreException e ) { throw new RepositoryServiceException( "Unable to retrieve local repository by location: " + location, e ); } } public LocalRepository getLocalRepository( int repositoryId ) throws RepositoryServiceException { try { return localRepositoryDao.getLocalRepository( repositoryId ); } catch ( ContinuumObjectNotFoundException e ) { throw new RepositoryServiceException( "No repository found with id: " + repositoryId, e ); } catch ( ContinuumStoreException e ) { throw new RepositoryServiceException( "Unable to retrieve local repository: " + repositoryId, e ); } } public LocalRepository getLocalRepositoryByName( String repositoryName ) throws RepositoryServiceException { try { return localRepositoryDao.getLocalRepositoryByName( repositoryName ); } catch ( ContinuumObjectNotFoundException e ) { throw new RepositoryServiceException( "No repository found with name: " + repositoryName, e ); } catch ( ContinuumStoreException e ) { throw new RepositoryServiceException( "Unable to retrieve local repository: " + repositoryName, e ); } } private void removePurgeConfigurationsOfRepository( int repositoryId ) throws RepositoryServiceException { try { List<RepositoryPurgeConfiguration> purgeConfigs = repositoryPurgeConfigurationDao.getRepositoryPurgeConfigurationsByLocalRepository( repositoryId ); for ( RepositoryPurgeConfiguration purgeConfig : purgeConfigs ) { repositoryPurgeConfigurationDao.removeRepositoryPurgeConfiguration( purgeConfig ); } } catch ( ContinuumObjectNotFoundException e ) { throw new RepositoryServiceException( "Error while removing local repository: " + repositoryId, e ); } catch ( ContinuumStoreException e ) { throw new RepositoryServiceException( "Error while removing purge configurations of local repository: " + repositoryId, e ); } } }
5,151
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/continuum/release
Create_ds/continuum/continuum-core/src/main/java/org/apache/continuum/release/distributed/DistributedReleaseUtil.java
package org.apache.continuum.release.distributed; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; public class DistributedReleaseUtil { public static final String KEY_SCM_TAG = "scm-tag"; public static final String KEY_SCM_TAGBASE = "scm-tagbase"; public static final String KEY_SCM_USERNAME = "scm-username"; public static final String KEY_SCM_PASSWORD = "scm-password"; public static final String KEY_ARGUMENTS = "arguments"; public static final String KEY_PREPARE_GOALS = "preparation-goals"; public static final String KEY_PERFORM_GOALS = "perform-goals"; public static final String KEY_SCM_COMMENT_PREFIX = "scm-comment-prefix"; public static final String KEY_AUTO_VERSION_SUBMODULES = "auto-version-submodules"; public static final String KEY_ADD_SCHEMA = "add-schema"; public static final String KEY_PROJECT = "project"; public static final String KEY_PROFILE = "profile"; public static final String KEY_PROPERTIES = "properties"; public static final String KEY_RELEASE_VERSION = "releaseVersion"; public static final String KEY_DEVELOPMENT_VERSION = "developmentVersion"; public static final String KEY_PROJECT_ID = "project-id"; public static final String KEY_GROUP_ID = "group-id"; public static final String KEY_ARTIFACT_ID = "artifact-id"; public static final String KEY_SCM_URL = "scm-url"; public static final String KEY_LOCAL_REPOSITORY = "local-repository"; public static final String KEY_USE_EDIT_MODE = "use-edit-mode"; public static final String KEY_ENVIRONMENTS = "environments"; public static final String KEY_START_TIME = "start-time"; public static final String KEY_END_TIME = "end-time"; public static final String KEY_RELEASE_RESULT_CODE = "release-result-code"; public static final String KEY_RELEASE_OUTPUT = "release-output"; public static final String KEY_RELEASE_STATE = "state"; public static final String KEY_RELEASE_PHASES = "release-phases"; public static final String KEY_COMPLETED_RELEASE_PHASES = "completed-release-phases"; public static final String KEY_RELEASE_IN_PROGRESS = "release-in-progress"; public static final String KEY_RELEASE_ERROR = "release-error"; public static final String KEY_USE_RELEASE_PROFILE = "use-release-profile"; public static final String KEY_GOALS = "goals"; public static final String KEY_RELEASE_ID = "release-id"; public static final String KEY_LOCAL_REPOSITORY_NAME = "repo-name"; public static final String KEY_LOCAL_REPOSITORY_LAYOUT = "repo-layout"; public static final String KEY_RELEASE_GOAL = "release-goal"; public static final String KEY_BUILD_AGENT_URL = "build-agent-url"; public static final String KEY_USERNAME = "username"; public static String getScmTag( Map<String, Object> context, String defaultValue ) { return getString( context, KEY_SCM_TAG, defaultValue ); } public static String getScmTagBase( Map<String, Object> context, String defaultValue ) { return getString( context, KEY_SCM_TAGBASE, defaultValue ); } public static String getArguments( Map<String, Object> context, String defaultValue ) { return getString( context, KEY_ARGUMENTS, defaultValue ); } public static String getPrepareGoals( Map<String, Object> context, String defaultValue ) { return getString( context, KEY_PREPARE_GOALS, defaultValue ); } public static String getPerformGoals( Map<String, Object> context, String defaultValue ) { return getString( context, KEY_PERFORM_GOALS, defaultValue ); } public static String getScmCommentPrefix( Map<String, Object> context, String defaultValue ) { return getString( context, KEY_SCM_COMMENT_PREFIX, defaultValue ); } public static Boolean getAutoVersionSubmodules( Map<String, Object> context, boolean defaultValue ) { return getBoolean( context, KEY_AUTO_VERSION_SUBMODULES, defaultValue ); } public static Boolean getAddSchema( Map<String, Object> context, boolean defaultValue ) { return getBoolean( context, KEY_ADD_SCHEMA, defaultValue ); } public static Long getStartTime( Map<String, Object> context ) { return new Long( getString( context, KEY_START_TIME ) ); } public static Long getEndTime( Map<String, Object> context ) { return new Long( getString( context, KEY_END_TIME ) ); } public static int getReleaseResultCode( Map<String, Object> context ) { return getInteger( context, KEY_RELEASE_RESULT_CODE ); } public static String getReleaseOutput( Map<String, Object> context ) { return getString( context, KEY_RELEASE_OUTPUT ); } public static int getReleaseState( Map<String, Object> context ) { return getInteger( context, KEY_RELEASE_STATE ); } public static List getReleasePhases( Map<String, Object> context ) { return getList( context, KEY_RELEASE_PHASES, new ArrayList() ); } public static List getCompletedReleasePhases( Map<String, Object> context ) { return getList( context, KEY_COMPLETED_RELEASE_PHASES, new ArrayList() ); } public static String getReleaseInProgress( Map<String, Object> context ) { return getString( context, KEY_RELEASE_IN_PROGRESS, "" ); } public static String getReleaseError( Map<String, Object> context ) { return getString( context, KEY_RELEASE_ERROR, null ); } public static boolean getUseReleaseProfile( Map<String, Object> context, boolean defaultValue ) { return getBoolean( context, KEY_USE_RELEASE_PROFILE, defaultValue ); } public static String getGoals( Map<String, Object> context, String defaultValue ) { return getString( context, KEY_GOALS, defaultValue ); } public static String getReleaseId( Map<String, Object> context ) { return getString( context, KEY_RELEASE_ID ); } public static String getReleaseGoal( Map<String, Object> context ) { return getString( context, KEY_RELEASE_GOAL ); } public static String getBuildAgentUrl( Map<String, Object> context ) { return getString( context, KEY_BUILD_AGENT_URL ); } public static int getProjectId( Map<String, Object> context ) { return getInteger( context, KEY_PROJECT_ID ); } public static String getUsername( Map<String, Object> context ) { return getString( context, KEY_USERNAME, "" ); } // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- public static Integer getInteger( Map<String, Object> context, String key ) { return (Integer) getObject( context, key ); } public static Integer getInteger( Map<String, Object> context, String key, Object defaultValue ) { return (Integer) getObject( context, key, defaultValue ); } public static String getString( Map<String, Object> context, String key ) { return (String) getObject( context, key ); } public static String getString( Map<String, Object> context, String key, String defaultValue ) { return (String) getObject( context, key, defaultValue ); } public static boolean getBoolean( Map<String, Object> context, String key ) { return (Boolean) getObject( context, key ); } public static boolean getBoolean( Map<String, Object> context, String key, boolean defaultValue ) { return (Boolean) getObject( context, key, defaultValue ); } public static List getList( Map<String, Object> context, String key, Object defaultValue ) { Object obj = getObject( context, key, defaultValue ); if ( obj == null ) { return null; } else { List<Object> list = new ArrayList<Object>(); if ( obj instanceof Object[] ) { Object[] objA = (Object[]) obj; list.addAll( Arrays.asList( objA ) ); } else { list = (List<Object>) obj; } return list; } } protected static Object getObject( Map<String, Object> context, String key ) { if ( !context.containsKey( key ) ) { throw new RuntimeException( "Missing key '" + key + "'." ); } Object value = context.get( key ); if ( value == null ) { throw new RuntimeException( "Missing value for key '" + key + "'." ); } return value; } protected static Object getObject( Map<String, Object> context, String key, Object defaultValue ) { Object value = context.get( key ); if ( value == null ) { return defaultValue; } return value; } }
5,152
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/continuum/release/distributed
Create_ds/continuum/continuum-core/src/main/java/org/apache/continuum/release/distributed/manager/DefaultDistributedReleaseManager.java
package org.apache.continuum.release.distributed.manager; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.builder.distributed.manager.DistributedBuildManager; import org.apache.continuum.configuration.BuildAgentConfiguration; import org.apache.continuum.configuration.BuildAgentConfigurationException; import org.apache.continuum.dao.BuildResultDao; import org.apache.continuum.distributed.transport.slave.SlaveBuildAgentTransportClient; import org.apache.continuum.distributed.transport.slave.SlaveBuildAgentTransportService; import org.apache.continuum.model.repository.LocalRepository; import org.apache.continuum.release.distributed.DistributedReleaseUtil; import org.apache.continuum.release.model.PreparedRelease; import org.apache.continuum.release.model.PreparedReleaseModel; import org.apache.continuum.release.model.io.stax.ContinuumPrepareReleasesModelStaxReader; import org.apache.continuum.release.model.io.stax.ContinuumPrepareReleasesModelStaxWriter; import org.apache.maven.artifact.ArtifactUtils; import org.apache.maven.continuum.configuration.ConfigurationService; import org.apache.maven.continuum.installation.InstallationService; import org.apache.maven.continuum.model.project.BuildResult; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.release.ContinuumReleaseException; import org.apache.maven.shared.release.ReleaseResult; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.util.IOUtil; import org.codehaus.plexus.util.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Properties; import javax.xml.stream.XMLStreamException; @Component( role = org.apache.continuum.release.distributed.manager.DistributedReleaseManager.class ) public class DefaultDistributedReleaseManager implements DistributedReleaseManager { private static final Logger log = LoggerFactory.getLogger( DefaultDistributedReleaseManager.class ); public final String PREPARED_RELEASES_FILENAME = "prepared-releases.xml"; @Requirement BuildResultDao buildResultDao; @Requirement ConfigurationService configurationService; @Requirement DistributedBuildManager distributedBuildManager; private Map<String, Map<String, Object>> releasesInProgress; public Map getReleasePluginParameters( int projectId, String pomFilename ) throws ContinuumReleaseException, BuildAgentConfigurationException { String buildAgentUrl = getDefaultBuildagent( projectId ); if ( !checkBuildAgent( buildAgentUrl ) ) { throw new BuildAgentConfigurationException( buildAgentUrl ); } try { if ( distributedBuildManager.isAgentAvailable( buildAgentUrl ) ) { SlaveBuildAgentTransportService client = createSlaveBuildAgentTransportClientConnection( buildAgentUrl ); return client.getReleasePluginParameters( projectId, pomFilename ); } // call reload in case we disable the build agent distributedBuildManager.reload(); throw new ContinuumReleaseException( "Failed to retrieve release plugin parameters because build agent " + buildAgentUrl + " is not available" ); } catch ( MalformedURLException e ) { log.error( "Invalid build agent url " + buildAgentUrl ); throw new ContinuumReleaseException( "Invalid build agent url " + buildAgentUrl ); } catch ( Exception e ) { log.error( "Failed to retrieve release plugin parameters", e ); throw new ContinuumReleaseException( "Failed to retrieve release plugin parameters", e ); } } public List<Map<String, String>> processProject( int projectId, String pomFilename, boolean autoVersionSubmodules ) throws ContinuumReleaseException, BuildAgentConfigurationException { BuildResult buildResult = buildResultDao.getLatestBuildResultForProject( projectId ); String buildAgentUrl = buildResult.getBuildUrl(); if ( !checkBuildAgent( buildAgentUrl ) ) { throw new BuildAgentConfigurationException( buildAgentUrl ); } try { if ( distributedBuildManager.isAgentAvailable( buildAgentUrl ) ) { SlaveBuildAgentTransportService client = createSlaveBuildAgentTransportClientConnection( buildAgentUrl ); return client.processProject( projectId, pomFilename, autoVersionSubmodules ); } // call reload in case we disable the build agent distributedBuildManager.reload(); throw new ContinuumReleaseException( "Failed to process project for releasing because build agent " + buildAgentUrl + " is unavailable" ); } catch ( MalformedURLException e ) { log.error( "Invalid build agent url " + buildAgentUrl ); throw new ContinuumReleaseException( "Invalid build agent url " + buildAgentUrl ); } catch ( Exception e ) { log.error( "Failed to process project for releasing", e ); throw new ContinuumReleaseException( "Failed to process project for releasing", e ); } } public String releasePrepare( Project project, Properties releaseProperties, Map<String, String> releaseVersion, Map<String, String> developmentVersion, Map<String, String> environments, String username ) throws ContinuumReleaseException, BuildAgentConfigurationException { String buildAgentUrl = environments.get( DistributedReleaseUtil.KEY_BUILD_AGENT_URL ); if ( !checkBuildAgent( buildAgentUrl ) ) { throw new BuildAgentConfigurationException( buildAgentUrl ); } try { if ( distributedBuildManager.isAgentAvailable( buildAgentUrl ) ) { SlaveBuildAgentTransportService client = createSlaveBuildAgentTransportClientConnection( buildAgentUrl ); String releaseId = client.releasePrepare( createProjectMap( project ), releaseProperties, releaseVersion, developmentVersion, environments, username ); String key = ArtifactUtils.versionlessKey( project.getGroupId(), project.getArtifactId() ); addReleasePrepare( releaseId, buildAgentUrl, releaseVersion.get( key ), "prepare", releaseProperties.getProperty( "preparation-goals" ), username ); addReleaseInProgress( releaseId, "prepare", project.getId(), username ); return releaseId; } // call reload in case we disable the build agent distributedBuildManager.reload(); throw new ContinuumReleaseException( "Failed to prepare release project because the build agent " + buildAgentUrl + " is not available" ); } catch ( MalformedURLException e ) { log.error( "Invalid build agent url " + buildAgentUrl ); throw new ContinuumReleaseException( "Invalid build agent url " + buildAgentUrl ); } catch ( Exception e ) { log.error( "Failed to prepare release project " + project.getName(), e ); throw new ContinuumReleaseException( "Failed to prepare release project " + project.getName(), e ); } } public ReleaseResult getReleaseResult( String releaseId ) throws ContinuumReleaseException, BuildAgentConfigurationException { String buildAgentUrl = getBuildAgentUrl( releaseId ); if ( !checkBuildAgent( buildAgentUrl ) ) { throw new BuildAgentConfigurationException( buildAgentUrl ); } try { if ( distributedBuildManager.isAgentAvailable( buildAgentUrl ) ) { SlaveBuildAgentTransportService client = createSlaveBuildAgentTransportClientConnection( buildAgentUrl ); Map<String, Object> result = client.getReleaseResult( releaseId ); ReleaseResult releaseResult = new ReleaseResult(); releaseResult.setStartTime( DistributedReleaseUtil.getStartTime( result ) ); releaseResult.setEndTime( DistributedReleaseUtil.getEndTime( result ) ); releaseResult.setResultCode( DistributedReleaseUtil.getReleaseResultCode( result ) ); releaseResult.getOutputBuffer().append( DistributedReleaseUtil.getReleaseOutput( result ) ); return releaseResult; } // call reload in case we disable a build agent distributedBuildManager.reload(); throw new ContinuumReleaseException( "Failed to get release result of " + releaseId + " because the build agent " + buildAgentUrl + " is not available" ); } catch ( MalformedURLException e ) { log.error( "Invalid build agent url " + buildAgentUrl ); throw new ContinuumReleaseException( "Invalid build agent url " + buildAgentUrl ); } catch ( Exception e ) { log.error( "Failed to get release result of " + releaseId, e ); throw new ContinuumReleaseException( "Failed to get release result of " + releaseId, e ); } } public Map<String, Object> getListener( String releaseId ) throws ContinuumReleaseException, BuildAgentConfigurationException { String buildAgentUrl = getBuildAgentUrl( releaseId ); if ( !checkBuildAgent( buildAgentUrl ) ) { throw new BuildAgentConfigurationException( buildAgentUrl ); } try { if ( distributedBuildManager.isAgentAvailable( buildAgentUrl ) ) { SlaveBuildAgentTransportService client = createSlaveBuildAgentTransportClientConnection( buildAgentUrl ); return client.getListener( releaseId ); } // call reload in case we disable the build agent distributedBuildManager.reload(); throw new ContinuumReleaseException( "Failed to get listener for " + releaseId + " because the build agent " + buildAgentUrl + " is not available" ); } catch ( MalformedURLException e ) { log.error( "Invalid build agent url " + buildAgentUrl ); throw new ContinuumReleaseException( "Invalid build agent url " + buildAgentUrl ); } catch ( Exception e ) { log.error( "Failed to get listener for " + releaseId, e ); throw new ContinuumReleaseException( "Failed to get listener for " + releaseId, e ); } } public void removeListener( String releaseId ) throws ContinuumReleaseException, BuildAgentConfigurationException { String buildAgentUrl = getBuildAgentUrl( releaseId ); if ( !checkBuildAgent( buildAgentUrl ) ) { throw new BuildAgentConfigurationException( buildAgentUrl ); } try { if ( distributedBuildManager.isAgentAvailable( buildAgentUrl ) ) { SlaveBuildAgentTransportService client = createSlaveBuildAgentTransportClientConnection( buildAgentUrl ); client.removeListener( releaseId ); } // call reload in case we disable the build agent distributedBuildManager.reload(); throw new ContinuumReleaseException( "Failed to remove listener of " + releaseId + " because the build agent " + buildAgentUrl + " is not available" ); } catch ( MalformedURLException e ) { log.error( "Invalid build agent url " + buildAgentUrl ); throw new ContinuumReleaseException( "Invalid build agent url " + buildAgentUrl ); } catch ( Exception e ) { log.error( "Failed to remove listener of " + releaseId, e ); throw new ContinuumReleaseException( "Failed to remove listener of " + releaseId, e ); } } public String getPreparedReleaseName( String releaseId ) throws ContinuumReleaseException { String buildAgentUrl = getBuildAgentUrl( releaseId ); if ( StringUtils.isBlank( buildAgentUrl ) ) { log.info( "Unable to get prepared release name because no build agent found for " + releaseId ); return null; } try { if ( distributedBuildManager.isAgentAvailable( buildAgentUrl ) ) { SlaveBuildAgentTransportService client = createSlaveBuildAgentTransportClientConnection( buildAgentUrl ); return client.getPreparedReleaseName( releaseId ); } // call reload in case we disable the build agent distributedBuildManager.reload(); throw new ContinuumReleaseException( "Failed to get prepared release name of " + releaseId + " because the build agent " + buildAgentUrl + " is not available" ); } catch ( MalformedURLException e ) { log.error( "Invalid build agent url " + buildAgentUrl ); throw new ContinuumReleaseException( "Invalid build agent url " + buildAgentUrl ); } catch ( Exception e ) { log.error( "Failed to get prepared release name of " + releaseId, e ); throw new ContinuumReleaseException( "Failed to get prepared release name of " + releaseId, e ); } } public Map<String, String> getPreparedReleases( String groupId, String artifactId ) throws ContinuumReleaseException { String releaseId = ArtifactUtils.versionlessKey( groupId, artifactId ); Map<String, String> projectPreparedReleases = new LinkedHashMap<String, String>(); for ( PreparedRelease release : getPreparedReleases() ) { // get exact match, or one with a timestamp appended String id = release.getReleaseId(); if ( id.equals( releaseId ) || id.startsWith( releaseId + ":" ) ) { projectPreparedReleases.put( id, release.getReleaseName() ); } } return projectPreparedReleases; } public void releasePerform( int projectId, String releaseId, String goals, String arguments, boolean useReleaseProfile, LocalRepository repository, String username ) throws ContinuumReleaseException, BuildAgentConfigurationException { List<PreparedRelease> releases = getPreparedReleases(); for ( PreparedRelease release : releases ) { if ( release.getReleaseId().equals( releaseId ) ) { release.setReleaseType( "perform" ); savePreparedReleases( releases ); break; } } String buildAgentUrl = getBuildAgentUrl( releaseId ); if ( !checkBuildAgent( buildAgentUrl ) ) { throw new BuildAgentConfigurationException( buildAgentUrl ); } if ( goals == null ) { goals = ""; } if ( arguments == null ) { arguments = ""; } Map<String, String> map = new HashMap<String, String>(); map.put( DistributedReleaseUtil.KEY_USERNAME, username ); if ( repository != null ) { map.put( DistributedReleaseUtil.KEY_LOCAL_REPOSITORY_NAME, repository.getName() ); } try { if ( distributedBuildManager.isAgentAvailable( buildAgentUrl ) ) { SlaveBuildAgentTransportService client = createSlaveBuildAgentTransportClientConnection( buildAgentUrl ); client.releasePerform( releaseId, goals, arguments, useReleaseProfile, map, username ); addReleaseInProgress( releaseId, "perform", projectId, username ); } else { // call reload in case we disable the build agent distributedBuildManager.reload(); throw new ContinuumReleaseException( "Failed to perform release of " + releaseId + " because the build agent " + buildAgentUrl + " is not available" ); } } catch ( MalformedURLException e ) { log.error( "Invalid build agent url " + buildAgentUrl ); throw new ContinuumReleaseException( "Invalid build agent url " + buildAgentUrl ); } catch ( Exception e ) { log.error( "Failed to perform release of " + releaseId, e ); throw new ContinuumReleaseException( "Failed to perform release of " + releaseId, e ); } } public String releasePerformFromScm( int projectId, String goals, String arguments, boolean useReleaseProfile, LocalRepository repository, String scmUrl, String scmUsername, String scmPassword, String scmTag, String scmTagBase, Map environments, String username ) throws ContinuumReleaseException, BuildAgentConfigurationException { String buildAgentUrl = (String) environments.get( DistributedReleaseUtil.KEY_BUILD_AGENT_URL ); if ( !checkBuildAgent( buildAgentUrl ) ) { throw new BuildAgentConfigurationException( buildAgentUrl ); } if ( goals == null ) { goals = ""; } if ( arguments == null ) { arguments = ""; } Map<String, String> map = new HashMap<String, String>(); map.put( DistributedReleaseUtil.KEY_USERNAME, username ); if ( repository != null ) { map.put( DistributedReleaseUtil.KEY_LOCAL_REPOSITORY_NAME, repository.getName() ); } try { if ( distributedBuildManager.isAgentAvailable( buildAgentUrl ) ) { SlaveBuildAgentTransportService client = createSlaveBuildAgentTransportClientConnection( buildAgentUrl ); String releaseId = client.releasePerformFromScm( goals, arguments, useReleaseProfile, map, scmUrl, scmUsername, scmPassword, scmTag, scmTagBase, environments, username ); addReleasePrepare( releaseId, buildAgentUrl, scmTag, "perform", goals, username ); addReleaseInProgress( releaseId, "perform", projectId, username ); return releaseId; } // call reload in case we disable the build agent distributedBuildManager.reload(); throw new ContinuumReleaseException( "Failed to perform release because the build agent " + buildAgentUrl + " is not available" ); } catch ( MalformedURLException e ) { log.error( "Invalid build agent url " + buildAgentUrl ); throw new ContinuumReleaseException( "Invalid build agent url " + buildAgentUrl ); } catch ( Exception e ) { log.error( "Failed to perform release", e ); throw new ContinuumReleaseException( "Failed to perform release", e ); } } public void releaseRollback( String releaseId, int projectId ) throws ContinuumReleaseException, BuildAgentConfigurationException { String buildAgentUrl = getBuildAgentUrl( releaseId ); if ( !checkBuildAgent( buildAgentUrl ) ) { throw new BuildAgentConfigurationException( buildAgentUrl ); } try { if ( distributedBuildManager.isAgentAvailable( buildAgentUrl ) ) { SlaveBuildAgentTransportService client = createSlaveBuildAgentTransportClientConnection( buildAgentUrl ); client.releaseRollback( releaseId, projectId ); return; } // call reload in case we disable the build agent distributedBuildManager.reload(); throw new ContinuumReleaseException( "Unable to rollback release " + releaseId + " because the build agent " + buildAgentUrl + " is not available" ); } catch ( MalformedURLException e ) { log.error( "Invalid build agent url " + buildAgentUrl ); throw new ContinuumReleaseException( "Invalid build agent url " + buildAgentUrl ); } catch ( Exception e ) { log.error( "Unable to rollback release " + releaseId, e ); throw new ContinuumReleaseException( e ); } } public String releaseCleanup( String releaseId ) throws ContinuumReleaseException, BuildAgentConfigurationException { String buildAgentUrl = getBuildAgentUrl( releaseId ); if ( !checkBuildAgent( buildAgentUrl ) ) { throw new BuildAgentConfigurationException( buildAgentUrl ); } try { if ( distributedBuildManager.isAgentAvailable( buildAgentUrl ) ) { removeFromReleaseInProgress( releaseId ); removeFromPreparedReleases( releaseId ); SlaveBuildAgentTransportService client = createSlaveBuildAgentTransportClientConnection( buildAgentUrl ); String result = client.releaseCleanup( releaseId ); return result; } // call reload in case we disable the build agent distributedBuildManager.reload(); throw new ContinuumReleaseException( "Failed to cleanup release of " + releaseId + " because the build agent " + buildAgentUrl + " is not available" ); } catch ( MalformedURLException e ) { log.error( "Invalid build agent url " + buildAgentUrl ); throw new ContinuumReleaseException( "Invalid build agent url " + buildAgentUrl ); } catch ( Exception e ) { log.error( "Failed to cleanup release of " + releaseId, e ); throw new ContinuumReleaseException( "Failed to cleanup release of " + releaseId, e ); } } public List<Map<String, Object>> getAllReleasesInProgress() throws ContinuumReleaseException, BuildAgentConfigurationException { List<Map<String, Object>> releases = new ArrayList<Map<String, Object>>(); Map<String, Map<String, Object>> releasesMap = new HashMap<String, Map<String, Object>>(); if ( releasesInProgress != null && !releasesInProgress.isEmpty() ) { for ( String releaseId : releasesInProgress.keySet() ) { String buildAgentUrl = getBuildAgentUrl( releaseId ); if ( StringUtils.isNotBlank( buildAgentUrl ) ) { if ( !checkBuildAgent( buildAgentUrl ) ) { throw new BuildAgentConfigurationException( buildAgentUrl ); } try { if ( distributedBuildManager.isAgentAvailable( buildAgentUrl ) ) { SlaveBuildAgentTransportService client = createSlaveBuildAgentTransportClientConnection( buildAgentUrl ); Map map = client.getListener( releaseId ); if ( map != null && !map.isEmpty() ) { Map<String, Object> release = releasesInProgress.get( releaseId ); release.put( DistributedReleaseUtil.KEY_RELEASE_ID, releaseId ); release.put( DistributedReleaseUtil.KEY_BUILD_AGENT_URL, buildAgentUrl ); releases.add( release ); releasesMap.put( releaseId, releasesInProgress.get( releaseId ) ); } } } catch ( MalformedURLException e ) { log.error( "Invalid build agent url " + buildAgentUrl ); throw new ContinuumReleaseException( "Invalid build agent url " + buildAgentUrl ); } catch ( Exception e ) { log.error( "Failed to get all releases in progress ", e ); throw new ContinuumReleaseException( "Failed to get all releases in progress ", e ); } } } releasesInProgress = releasesMap; } try { // call reload in case we disable a build agent distributedBuildManager.reload(); } catch ( Exception e ) { throw new ContinuumReleaseException( e.getMessage(), e ); } return releases; } public String getDefaultBuildagent( int projectId ) { BuildResult buildResult = buildResultDao.getLatestBuildResultForProject( projectId ); return buildResult != null ? buildResult.getBuildUrl() : null; } public PreparedRelease getPreparedRelease( String releaseId, String releaseType ) throws ContinuumReleaseException { List<PreparedRelease> releases = getPreparedReleases(); for ( PreparedRelease release : releases ) { if ( release.getReleaseId().equals( releaseId ) && release.getReleaseType().equals( releaseType ) ) { return release; } } return null; } public SlaveBuildAgentTransportService createSlaveBuildAgentTransportClientConnection( String buildAgentUrl ) throws MalformedURLException, Exception { return new SlaveBuildAgentTransportClient( new URL( buildAgentUrl ), "", configurationService.getSharedSecretPassword() ); } private Map createProjectMap( Project project ) { Map<String, Object> map = new HashMap<String, Object>(); map.put( DistributedReleaseUtil.KEY_PROJECT_ID, project.getId() ); map.put( DistributedReleaseUtil.KEY_GROUP_ID, project.getGroupId() ); map.put( DistributedReleaseUtil.KEY_ARTIFACT_ID, project.getArtifactId() ); map.put( DistributedReleaseUtil.KEY_SCM_URL, project.getScmUrl() ); if ( project.getProjectGroup().getLocalRepository() != null ) { map.put( DistributedReleaseUtil.KEY_LOCAL_REPOSITORY_NAME, project.getProjectGroup().getLocalRepository().getName() ); } return map; } private List<PreparedRelease> getPreparedReleases() throws ContinuumReleaseException { File file = getPreparedReleasesFile(); if ( file.exists() ) { FileInputStream fis = null; try { fis = new FileInputStream( file ); ContinuumPrepareReleasesModelStaxReader reader = new ContinuumPrepareReleasesModelStaxReader(); PreparedReleaseModel model = reader.read( new InputStreamReader( fis ) ); return model.getPreparedReleases(); } catch ( IOException e ) { log.error( e.getMessage(), e ); throw new ContinuumReleaseException( "Unable to get prepared releases", e ); } catch ( XMLStreamException e ) { log.error( e.getMessage(), e ); throw new ContinuumReleaseException( e.getMessage(), e ); } finally { if ( fis != null ) { IOUtil.close( fis ); } } } return new ArrayList<PreparedRelease>(); } private void addReleasePrepare( String releaseId, String buildAgentUrl, String releaseName, String releaseType, String releaseGoals, String username ) throws ContinuumReleaseException { PreparedRelease release = new PreparedRelease(); release.setReleaseId( releaseId ); release.setBuildAgentUrl( buildAgentUrl ); release.setReleaseName( releaseName ); release.setReleaseType( releaseType ); release.setReleaseGoals( releaseGoals ); release.setReleaseBy( username ); List<PreparedRelease> preparedReleases = getPreparedReleases(); if ( preparedReleases == null ) { preparedReleases = new ArrayList<PreparedRelease>(); } for ( PreparedRelease preparedRelease : preparedReleases ) { if ( preparedRelease.getReleaseId().equals( release.getReleaseId() ) ) { preparedReleases.remove( preparedRelease ); break; } } preparedReleases.add( release ); savePreparedReleases( preparedReleases ); } private void addReleaseInProgress( String releaseId, String releaseType, int projectId, String username ) { if ( releasesInProgress == null ) { releasesInProgress = new HashMap<String, Map<String, Object>>(); } Map<String, Object> map = new HashMap<String, Object>(); map.put( DistributedReleaseUtil.KEY_RELEASE_GOAL, releaseType ); map.put( DistributedReleaseUtil.KEY_PROJECT_ID, projectId ); map.put( DistributedReleaseUtil.KEY_USERNAME, username ); releasesInProgress.put( releaseId, map ); } private void removeFromReleaseInProgress( String releaseId ) { if ( releasesInProgress != null && releasesInProgress.containsKey( releaseId ) ) { releasesInProgress.remove( releaseId ); } } private String getBuildAgentUrl( String releaseId ) throws ContinuumReleaseException { List<PreparedRelease> preparedReleases = getPreparedReleases(); if ( preparedReleases != null ) { for ( PreparedRelease preparedRelease : preparedReleases ) { if ( preparedRelease.getReleaseId().equals( releaseId ) ) { return preparedRelease.getBuildAgentUrl(); } } } return null; } private File getPreparedReleasesFile() { return new File( System.getProperty( "appserver.base" ) + File.separator + "conf" + File.separator + PREPARED_RELEASES_FILENAME ); } private boolean checkBuildAgent( String buildAgentUrl ) { BuildAgentConfiguration buildAgent = configurationService.getBuildAgent( buildAgentUrl ); if ( buildAgent != null && buildAgent.isEnabled() ) { return true; } log.info( "Build agent: " + buildAgentUrl + " is either disabled or removed" ); return false; } private void removeFromPreparedReleases( String releaseId ) throws ContinuumReleaseException { List<PreparedRelease> releases = getPreparedReleases(); for ( PreparedRelease release : releases ) { if ( release.getReleaseId().equals( releaseId ) ) { if ( release.getReleaseType().equals( "perform" ) ) { releases.remove( release ); savePreparedReleases( releases ); break; } } } } private void savePreparedReleases( List<PreparedRelease> preparedReleases ) throws ContinuumReleaseException { File file = getPreparedReleasesFile(); if ( !file.exists() ) { file.getParentFile().mkdirs(); } PreparedReleaseModel model = new PreparedReleaseModel(); model.setPreparedReleases( preparedReleases ); FileWriter fileWriter = null; try { ContinuumPrepareReleasesModelStaxWriter writer = new ContinuumPrepareReleasesModelStaxWriter(); fileWriter = new FileWriter( file ); writer.write( fileWriter, model ); fileWriter.flush(); } catch ( IOException e ) { throw new ContinuumReleaseException( "Failed to write prepared releases in file", e ); } catch ( XMLStreamException e ) { throw new ContinuumReleaseException( "Failed to write prepared releases in file", e ); } finally { IOUtil.close( fileWriter ); } } // for unit test public void setBuildResultDao( BuildResultDao buildResultDao ) { this.buildResultDao = buildResultDao; } }
5,153
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/continuum
Create_ds/continuum/continuum-core/src/main/java/org/apache/continuum/purge/DefaultContinuumPurgeManager.java
package org.apache.continuum.purge; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.buildmanager.BuildsManager; import org.apache.continuum.model.repository.DirectoryPurgeConfiguration; import org.apache.continuum.model.repository.DistributedDirectoryPurgeConfiguration; import org.apache.continuum.model.repository.DistributedRepositoryPurgeConfiguration; import org.apache.continuum.model.repository.LocalRepository; import org.apache.continuum.model.repository.RepositoryPurgeConfiguration; import org.apache.continuum.purge.task.PurgeTask; import org.apache.continuum.taskqueue.manager.TaskQueueManager; import org.apache.continuum.taskqueue.manager.TaskQueueManagerException; import org.apache.maven.continuum.build.settings.SchedulesActivationException; import org.apache.maven.continuum.build.settings.SchedulesActivator; import org.apache.maven.continuum.model.project.Schedule; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.taskqueue.TaskQueueException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; /** * DefaultContinuumPurgeManager * * @author Maria Catherine Tan * @since 25 jul 07 */ @Component( role = org.apache.continuum.purge.ContinuumPurgeManager.class, hint = "default" ) public class DefaultContinuumPurgeManager implements ContinuumPurgeManager { private static final Logger log = LoggerFactory.getLogger( DefaultContinuumPurgeManager.class ); @Requirement private SchedulesActivator schedulesActivator; @Requirement private PurgeConfigurationService purgeConfigurationService; @Requirement private TaskQueueManager taskQueueManager; @Requirement( hint = "parallel" ) private BuildsManager parallelBuildsManager; public void purge( Schedule schedule ) throws ContinuumPurgeManagerException { List<RepositoryPurgeConfiguration> repoPurgeList; List<DirectoryPurgeConfiguration> dirPurgeList; List<DistributedDirectoryPurgeConfiguration> distributedDirPurgeList; List<DistributedRepositoryPurgeConfiguration> distributedRepoPurgeList; repoPurgeList = purgeConfigurationService.getEnableRepositoryPurgeConfigurationsBySchedule( schedule.getId() ); dirPurgeList = purgeConfigurationService.getEnableDirectoryPurgeConfigurationsBySchedule( schedule.getId() ); distributedDirPurgeList = purgeConfigurationService.getEnableDistributedDirectoryPurgeConfigurationsBySchedule( schedule.getId() ); distributedRepoPurgeList = purgeConfigurationService.getEnableDistributedRepositoryPurgeConfigurationsBySchedule( schedule.getId() ); boolean hasRepoPurge = repoPurgeList != null && repoPurgeList.size() > 0; boolean hasDirPurge = dirPurgeList != null && dirPurgeList.size() > 0; boolean hasDitributedDirPurge = distributedDirPurgeList != null && distributedDirPurgeList.size() > 0; boolean hasDistributedRepoPurge = distributedRepoPurgeList != null && distributedRepoPurgeList.size() > 0; if ( hasRepoPurge ) { for ( RepositoryPurgeConfiguration repoPurge : repoPurgeList ) { purgeRepository( repoPurge ); } } if ( hasDirPurge ) { for ( DirectoryPurgeConfiguration dirPurge : dirPurgeList ) { purgeDirectory( dirPurge ); } } if ( hasDitributedDirPurge ) { for ( DistributedDirectoryPurgeConfiguration dirPurge : distributedDirPurgeList ) { purgeDistributedDirectory( dirPurge ); } } if ( hasDistributedRepoPurge ) { for ( DistributedRepositoryPurgeConfiguration repoPurge : distributedRepoPurgeList ) { purgeDistributedRepository( repoPurge ); } } if ( !hasRepoPurge && !hasDirPurge && !hasDitributedDirPurge && !hasDistributedRepoPurge ) { // This purge is not enable for a purge process. try { schedulesActivator.unactivateOrphanPurgeSchedule( schedule ); } catch ( SchedulesActivationException e ) { log.debug( String.format( "Can't unactivate orphan schedule '%s' for purgeConfiguration", schedule.getName() ) ); } } } public void purgeRepository( RepositoryPurgeConfiguration repoPurge ) throws ContinuumPurgeManagerException { try { LocalRepository repository = repoPurge.getRepository(); // do not purge if repository is in use and if repository is already in purge queue if ( !taskQueueManager.isRepositoryInUse( repository.getId() ) && !taskQueueManager.isInPurgeQueue( repoPurge.getId() ) ) { taskQueueManager.getPurgeQueue().put( new PurgeTask( repoPurge.getId() ) ); } } catch ( TaskQueueException e ) { throw new ContinuumPurgeManagerException( "Error while enqueuing repository", e ); } catch ( TaskQueueManagerException e ) { throw new ContinuumPurgeManagerException( e.getMessage(), e ); } } public void purgeDirectory( DirectoryPurgeConfiguration dirPurge ) throws ContinuumPurgeManagerException { try { if ( "releases".equals( dirPurge.getDirectoryType() ) ) { // do not purge if release in progress if ( !taskQueueManager.releaseInProgress() && !taskQueueManager.isInPurgeQueue( dirPurge.getId() ) ) { taskQueueManager.getPurgeQueue().put( new PurgeTask( dirPurge.getId() ) ); } } else if ( "buildOutput".equals( dirPurge.getDirectoryType() ) ) { // do not purge if build in progress if ( !parallelBuildsManager.isBuildInProgress() && !taskQueueManager.isInPurgeQueue( dirPurge.getId() ) ) { taskQueueManager.getPurgeQueue().put( new PurgeTask( dirPurge.getId() ) ); } } } catch ( TaskQueueException e ) { throw new ContinuumPurgeManagerException( "Error while enqueuing directory", e ); } catch ( TaskQueueManagerException e ) { throw new ContinuumPurgeManagerException( e.getMessage(), e ); } } public void purgeDistributedDirectory( DistributedDirectoryPurgeConfiguration dirPurge ) throws ContinuumPurgeManagerException { try { taskQueueManager.getPurgeQueue().put( new PurgeTask( dirPurge.getId() ) ); } catch ( TaskQueueException e ) { throw new ContinuumPurgeManagerException( "Error while enqueuing distributed directory", e ); } } public void purgeDistributedRepository( DistributedRepositoryPurgeConfiguration repoPurgeConfig ) throws ContinuumPurgeManagerException { try { taskQueueManager.getPurgeQueue().put( new PurgeTask( repoPurgeConfig.getId() ) ); } catch ( TaskQueueException e ) { throw new ContinuumPurgeManagerException( "Error while enqueuing distributed repository", e ); } } }
5,154
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/continuum
Create_ds/continuum/continuum-core/src/main/java/org/apache/continuum/purge/DefaultPurgeConfigurationService.java
package org.apache.continuum.purge; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.dao.DirectoryPurgeConfigurationDao; import org.apache.continuum.dao.DistributedDirectoryPurgeConfigurationDao; import org.apache.continuum.dao.DistributedRepositoryPurgeConfigurationDao; import org.apache.continuum.dao.LocalRepositoryDao; import org.apache.continuum.dao.RepositoryPurgeConfigurationDao; import org.apache.continuum.model.repository.AbstractPurgeConfiguration; import org.apache.continuum.model.repository.DirectoryPurgeConfiguration; import org.apache.continuum.model.repository.DistributedDirectoryPurgeConfiguration; import org.apache.continuum.model.repository.DistributedRepositoryPurgeConfiguration; import org.apache.continuum.model.repository.LocalRepository; import org.apache.continuum.model.repository.RepositoryPurgeConfiguration; import org.apache.continuum.purge.repository.content.RepositoryManagedContent; import org.apache.continuum.purge.repository.content.RepositoryManagedContentFactory; import org.apache.maven.continuum.store.ContinuumObjectNotFoundException; import org.apache.maven.continuum.store.ContinuumStoreException; import org.codehaus.plexus.PlexusConstants; import org.codehaus.plexus.PlexusContainer; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; 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 java.util.ArrayList; import java.util.List; /** * DefaultPurgeConfigurationService * * @author Maria Catherine Tan * @since 25 jul 07 */ @Component( role = org.apache.continuum.purge.PurgeConfigurationService.class, hint = "default" ) public class DefaultPurgeConfigurationService implements PurgeConfigurationService, Contextualizable { @Requirement private DirectoryPurgeConfigurationDao directoryPurgeConfigurationDao; @Requirement private LocalRepositoryDao localRepositoryDao; @Requirement private RepositoryPurgeConfigurationDao repositoryPurgeConfigurationDao; @Requirement private DistributedDirectoryPurgeConfigurationDao distributedDirectoryPurgeConfigurationDao; @Requirement private DistributedRepositoryPurgeConfigurationDao distributedRepositoryPurgeConfigurationDao; @Requirement private RepositoryManagedContentFactory contentFactory; private PlexusContainer container; public AbstractPurgeConfiguration addPurgeConfiguration( AbstractPurgeConfiguration purgeConfig ) throws PurgeConfigurationServiceException { AbstractPurgeConfiguration purgeConfiguration = null; if ( purgeConfig instanceof RepositoryPurgeConfiguration ) { purgeConfiguration = addRepositoryPurgeConfiguration( (RepositoryPurgeConfiguration) purgeConfig ); } else if ( purgeConfig instanceof DirectoryPurgeConfiguration ) { purgeConfiguration = addDirectoryPurgeConfiguration( (DirectoryPurgeConfiguration) purgeConfig ); } else if ( purgeConfig instanceof DistributedDirectoryPurgeConfiguration ) { purgeConfiguration = addDistributedDirectoryPurgeConfiguration( (DistributedDirectoryPurgeConfiguration) purgeConfig ); } else if ( purgeConfig instanceof DistributedRepositoryPurgeConfiguration ) { purgeConfiguration = addDistributedRepositoryPurgeConfiguration( (DistributedRepositoryPurgeConfiguration) purgeConfig ); } return purgeConfiguration; } public void updatePurgeConfiguration( AbstractPurgeConfiguration purgeConfig ) throws PurgeConfigurationServiceException { if ( purgeConfig instanceof RepositoryPurgeConfiguration ) { updateRepositoryPurgeConfiguration( (RepositoryPurgeConfiguration) purgeConfig ); } else if ( purgeConfig instanceof DirectoryPurgeConfiguration ) { updateDirectoryPurgeConfiguration( (DirectoryPurgeConfiguration) purgeConfig ); } else if ( purgeConfig instanceof DistributedDirectoryPurgeConfiguration ) { updateDistributedDirectoryPurgeConfiguration( (DistributedDirectoryPurgeConfiguration) purgeConfig ); } else if ( purgeConfig instanceof DistributedRepositoryPurgeConfiguration ) { updateDistributedRepositoryPurgeConfiguration( (DistributedRepositoryPurgeConfiguration) purgeConfig ); } } public void removePurgeConfiguration( int purgeConfigId ) throws PurgeConfigurationServiceException { AbstractPurgeConfiguration purgeConfig = getPurgeConfiguration( purgeConfigId ); if ( purgeConfig instanceof RepositoryPurgeConfiguration ) { removeRepositoryPurgeConfiguration( (RepositoryPurgeConfiguration) purgeConfig ); } else if ( purgeConfig instanceof DirectoryPurgeConfiguration ) { removeDirectoryPurgeConfiguration( (DirectoryPurgeConfiguration) purgeConfig ); } else if ( purgeConfig instanceof DistributedDirectoryPurgeConfiguration ) { removeDistributedDirectoryPurgeConfiguration( (DistributedDirectoryPurgeConfiguration) purgeConfig ); } else if ( purgeConfig instanceof DistributedRepositoryPurgeConfiguration ) { removeDistributedRepositoryPurgeConfiguration( (DistributedRepositoryPurgeConfiguration) purgeConfig ); } } public DirectoryPurgeConfiguration addDirectoryPurgeConfiguration( DirectoryPurgeConfiguration dirPurge ) throws PurgeConfigurationServiceException { DirectoryPurgeConfiguration dirPurgeConfig; try { dirPurgeConfig = directoryPurgeConfigurationDao.addDirectoryPurgeConfiguration( dirPurge ); } catch ( ContinuumStoreException e ) { throw new PurgeConfigurationServiceException( e.getMessage(), e ); } return dirPurgeConfig; } public RepositoryPurgeConfiguration addRepositoryPurgeConfiguration( RepositoryPurgeConfiguration repoPurge ) throws PurgeConfigurationServiceException { RepositoryPurgeConfiguration repoPurgeConfig; try { repoPurgeConfig = repositoryPurgeConfigurationDao.addRepositoryPurgeConfiguration( repoPurge ); } catch ( ContinuumStoreException e ) { throw new PurgeConfigurationServiceException( e.getMessage(), e ); } return repoPurgeConfig; } public RepositoryPurgeConfiguration getDefaultPurgeConfigurationForRepository( int repositoryId ) { List<RepositoryPurgeConfiguration> purgeConfigs = getRepositoryPurgeConfigurationsByRepository( repositoryId ); for ( RepositoryPurgeConfiguration purgeConfig : purgeConfigs ) { if ( purgeConfig.isDefaultPurge() ) { return purgeConfig; } } return null; } public List<DirectoryPurgeConfiguration> getAllDirectoryPurgeConfigurations() { return directoryPurgeConfigurationDao.getAllDirectoryPurgeConfigurations(); } public List<RepositoryPurgeConfiguration> getAllRepositoryPurgeConfigurations() { return repositoryPurgeConfigurationDao.getAllRepositoryPurgeConfigurations(); } public List<AbstractPurgeConfiguration> getAllPurgeConfigurations() { List<RepositoryPurgeConfiguration> repoPurge = getAllRepositoryPurgeConfigurations(); List<DirectoryPurgeConfiguration> dirPurge = getAllDirectoryPurgeConfigurations(); List<AbstractPurgeConfiguration> allPurgeConfigs = new ArrayList<AbstractPurgeConfiguration>(); allPurgeConfigs.addAll( repoPurge ); allPurgeConfigs.addAll( dirPurge ); return allPurgeConfigs; } public DirectoryPurgeConfiguration getDefaultPurgeConfigurationForDirectoryType( String directoryType ) { List<DirectoryPurgeConfiguration> purgeConfigs = directoryPurgeConfigurationDao.getDirectoryPurgeConfigurationsByType( directoryType ); for ( DirectoryPurgeConfiguration purgeConfig : purgeConfigs ) { if ( purgeConfig.isDefaultPurge() ) { return purgeConfig; } } return null; } public List<DirectoryPurgeConfiguration> getDirectoryPurgeConfigurationsByLocation( String location ) { return directoryPurgeConfigurationDao.getDirectoryPurgeConfigurationsByLocation( location ); } public List<DirectoryPurgeConfiguration> getDirectoryPurgeConfigurationsBySchedule( int scheduleId ) { return directoryPurgeConfigurationDao.getDirectoryPurgeConfigurationsBySchedule( scheduleId ); } public List<DirectoryPurgeConfiguration> getEnableDirectoryPurgeConfigurationsBySchedule( int scheduleId ) { return directoryPurgeConfigurationDao.getEnableDirectoryPurgeConfigurationsBySchedule( scheduleId ); } public List<RepositoryPurgeConfiguration> getRepositoryPurgeConfigurationsByRepository( int repositoryId ) { return repositoryPurgeConfigurationDao.getRepositoryPurgeConfigurationsByLocalRepository( repositoryId ); } public List<RepositoryPurgeConfiguration> getRepositoryPurgeConfigurationsBySchedule( int scheduleId ) { return repositoryPurgeConfigurationDao.getRepositoryPurgeConfigurationsBySchedule( scheduleId ); } public List<RepositoryPurgeConfiguration> getEnableRepositoryPurgeConfigurationsBySchedule( int scheduleId ) { return repositoryPurgeConfigurationDao.getEnableRepositoryPurgeConfigurationsBySchedule( scheduleId ); } public void removeDirectoryPurgeConfiguration( DirectoryPurgeConfiguration purgeConfig ) throws PurgeConfigurationServiceException { try { directoryPurgeConfigurationDao.removeDirectoryPurgeConfiguration( purgeConfig ); } catch ( ContinuumStoreException e ) { throw new PurgeConfigurationServiceException( e.getMessage(), e ); } } public void removeRepositoryPurgeConfiguration( RepositoryPurgeConfiguration purgeConfig ) throws PurgeConfigurationServiceException { try { repositoryPurgeConfigurationDao.removeRepositoryPurgeConfiguration( purgeConfig ); } catch ( ContinuumStoreException e ) { throw new PurgeConfigurationServiceException( e.getMessage(), e ); } } public void updateDirectoryPurgeConfiguration( DirectoryPurgeConfiguration purgeConfig ) throws PurgeConfigurationServiceException { try { directoryPurgeConfigurationDao.updateDirectoryPurgeConfiguration( purgeConfig ); } catch ( ContinuumStoreException e ) { throw new PurgeConfigurationServiceException( e.getMessage(), e ); } } public void updateRepositoryPurgeConfiguration( RepositoryPurgeConfiguration purgeConfig ) throws PurgeConfigurationServiceException { try { repositoryPurgeConfigurationDao.updateRepositoryPurgeConfiguration( purgeConfig ); } catch ( ContinuumStoreException e ) { throw new PurgeConfigurationServiceException( e.getMessage(), e ); } } public DirectoryPurgeConfiguration getDirectoryPurgeConfiguration( int purgeConfigId ) throws PurgeConfigurationServiceException { try { return directoryPurgeConfigurationDao.getDirectoryPurgeConfiguration( purgeConfigId ); } catch ( ContinuumObjectNotFoundException e ) { throw new PurgeConfigurationServiceException( e.getMessage(), e ); } catch ( ContinuumStoreException e ) { throw new PurgeConfigurationServiceException( e.getMessage(), e ); } } public RepositoryPurgeConfiguration getRepositoryPurgeConfiguration( int purgeConfigId ) throws PurgeConfigurationServiceException { try { return repositoryPurgeConfigurationDao.getRepositoryPurgeConfiguration( purgeConfigId ); } catch ( ContinuumObjectNotFoundException e ) { throw new PurgeConfigurationServiceException( e.getMessage(), e ); } catch ( ContinuumStoreException e ) { throw new PurgeConfigurationServiceException( e.getMessage(), e ); } } public AbstractPurgeConfiguration getPurgeConfiguration( int purgeConfigId ) { AbstractPurgeConfiguration purgeConfig = null; try { purgeConfig = getRepositoryPurgeConfiguration( purgeConfigId ); } catch ( PurgeConfigurationServiceException e ) { // purgeConfigId is not of type repository purge configuration } if ( purgeConfig == null ) { try { purgeConfig = getDirectoryPurgeConfiguration( purgeConfigId ); } catch ( PurgeConfigurationServiceException e ) { // purgeConfigId is not of type directory purge configuration } } if ( purgeConfig == null ) { try { purgeConfig = getDistributedDirectoryPurgeConfiguration( purgeConfigId ); } catch ( PurgeConfigurationServiceException e ) { // purgeConfigId is not of type directory purge configuration } } if ( purgeConfig == null ) { try { purgeConfig = getDistributedRepositoryPurgeConfiguration( purgeConfigId ); } catch ( PurgeConfigurationServiceException e ) { // purgeConfigId is not of type directory purge configuration } } return purgeConfig; } public RepositoryManagedContent getManagedRepositoryContent( int repositoryId ) throws PurgeConfigurationServiceException { try { LocalRepository repository = localRepositoryDao.getLocalRepository( repositoryId ); RepositoryManagedContent repoContent = contentFactory.create( repository.getLayout() ); repoContent.setRepository( repository ); return repoContent; } catch ( ContinuumObjectNotFoundException e ) { throw new PurgeConfigurationServiceException( "Error retrieving managed repository content for: " + repositoryId, e ); } catch ( ContinuumStoreException e ) { throw new PurgeConfigurationServiceException( "Error retrieving managed repository content for: " + repositoryId, e ); } catch ( ComponentLookupException e ) { throw new PurgeConfigurationServiceException( "Error retrieving managed repository content for: " + repositoryId, e ); } } public List<DistributedDirectoryPurgeConfiguration> getAllDistributedDirectoryPurgeConfigurations() { return distributedDirectoryPurgeConfigurationDao.getAllDistributedDirectoryPurgeConfigurations(); } public List<DistributedRepositoryPurgeConfiguration> getAllDistributedRepositoryPurgeConfigurations() { return distributedRepositoryPurgeConfigurationDao.getAllDistributedRepositoryPurgeConfigurations(); } public DistributedDirectoryPurgeConfiguration addDistributedDirectoryPurgeConfiguration( DistributedDirectoryPurgeConfiguration dirPurge ) throws PurgeConfigurationServiceException { try { return distributedDirectoryPurgeConfigurationDao.addDistributedDirectoryPurgeConfiguration( dirPurge ); } catch ( ContinuumStoreException e ) { throw new PurgeConfigurationServiceException( e.getMessage(), e ); } } public DistributedRepositoryPurgeConfiguration addDistributedRepositoryPurgeConfiguration( DistributedRepositoryPurgeConfiguration repoPurge ) throws PurgeConfigurationServiceException { try { return distributedRepositoryPurgeConfigurationDao.addDistributedRepositoryPurgeConfiguration( repoPurge ); } catch ( ContinuumStoreException e ) { throw new PurgeConfigurationServiceException( e.getMessage(), e ); } } public DistributedDirectoryPurgeConfiguration getDistributedDirectoryPurgeConfiguration( int dirPurgeId ) throws PurgeConfigurationServiceException { try { return distributedDirectoryPurgeConfigurationDao.getDistributedDirectoryPurgeConfiguration( dirPurgeId ); } catch ( ContinuumObjectNotFoundException e ) { throw new PurgeConfigurationServiceException( e.getMessage(), e ); } catch ( ContinuumStoreException e ) { throw new PurgeConfigurationServiceException( e.getMessage(), e ); } } public void updateDistributedDirectoryPurgeConfiguration( DistributedDirectoryPurgeConfiguration dirPurge ) throws PurgeConfigurationServiceException { try { distributedDirectoryPurgeConfigurationDao.updateDistributedDirectoryPurgeConfiguration( dirPurge ); } catch ( ContinuumStoreException e ) { throw new PurgeConfigurationServiceException( e.getMessage(), e ); } } private void updateDistributedRepositoryPurgeConfiguration( DistributedRepositoryPurgeConfiguration purgeConfig ) throws PurgeConfigurationServiceException { try { distributedRepositoryPurgeConfigurationDao.updateDistributedRepositoryPurgeConfiguration( purgeConfig ); } catch ( ContinuumStoreException e ) { throw new PurgeConfigurationServiceException( e.getMessage(), e ); } } public void removeDistributedDirectoryPurgeConfiguration( DistributedDirectoryPurgeConfiguration purgeConfig ) throws PurgeConfigurationServiceException { try { distributedDirectoryPurgeConfigurationDao.removeDistributedDirectoryPurgeConfiguration( purgeConfig ); } catch ( ContinuumStoreException e ) { throw new PurgeConfigurationServiceException( e.getMessage(), e ); } } public void removeDistributedRepositoryPurgeConfiguration( DistributedRepositoryPurgeConfiguration purgeConfig ) throws PurgeConfigurationServiceException { try { distributedRepositoryPurgeConfigurationDao.removeDistributedRepositoryPurgeConfiguration( purgeConfig ); } catch ( ContinuumStoreException e ) { throw new PurgeConfigurationServiceException( e.getMessage(), e ); } } public DistributedRepositoryPurgeConfiguration getDistributedRepositoryPurgeConfiguration( int dirPurgeId ) throws PurgeConfigurationServiceException { try { return distributedRepositoryPurgeConfigurationDao.getDistributedRepositoryPurgeConfiguration( dirPurgeId ); } catch ( ContinuumObjectNotFoundException e ) { throw new PurgeConfigurationServiceException( e.getMessage(), e ); } catch ( ContinuumStoreException e ) { throw new PurgeConfigurationServiceException( e.getMessage(), e ); } } public List<DistributedDirectoryPurgeConfiguration> getEnableDistributedDirectoryPurgeConfigurationsBySchedule( int scheduleId ) { return distributedDirectoryPurgeConfigurationDao.getEnableDistributedDirectoryPurgeConfigurationsBySchedule( scheduleId ); } public List<DistributedRepositoryPurgeConfiguration> getEnableDistributedRepositoryPurgeConfigurationsBySchedule( int scheduleId ) { return distributedRepositoryPurgeConfigurationDao.getEnableDistributedRepositoryPurgeConfigurationsBySchedule( scheduleId ); } public void contextualize( Context context ) throws ContextException { container = (PlexusContainer) context.get( PlexusConstants.PLEXUS_KEY ); } }
5,155
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/continuum/purge
Create_ds/continuum/continuum-core/src/main/java/org/apache/continuum/purge/controller/RepositoryPurgeController.java
package org.apache.continuum.purge.controller; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.model.repository.AbstractPurgeConfiguration; import org.apache.continuum.model.repository.RepositoryPurgeConfiguration; import org.apache.continuum.purge.PurgeConfigurationService; import org.apache.continuum.purge.PurgeConfigurationServiceException; import org.apache.continuum.purge.executor.ContinuumPurgeExecutor; import org.apache.continuum.purge.executor.ContinuumPurgeExecutorException; import org.apache.continuum.purge.executor.repo.RepositoryPurgeExecutorFactory; import org.apache.continuum.purge.repository.content.RepositoryManagedContent; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * DefaultPurgeController * * @author Maria Catherine Tan */ @Component( role = org.apache.continuum.purge.controller.PurgeController.class, hint = "purge-repository" ) public class RepositoryPurgeController implements PurgeController { private static final Logger log = LoggerFactory.getLogger( RepositoryPurgeController.class ); @Requirement private PurgeConfigurationService purgeConfigurationService; @Requirement private RepositoryPurgeExecutorFactory executorFactory; public void purge( AbstractPurgeConfiguration config ) { RepositoryPurgeConfiguration repoConfig = (RepositoryPurgeConfiguration) config; try { String path = repoConfig.getRepository().getLocation(); RepositoryManagedContent repositoryContent = getManagedContent( repoConfig.getRepository().getId() ); ContinuumPurgeExecutor executor = executorFactory.create( repoConfig.isDeleteAll(), repoConfig.getDaysOlder(), repoConfig.getRetentionCount(), repoConfig.isDeleteReleasedSnapshots(), repositoryContent ); log.info( "purging repository '{}'", path ); executor.purge( path ); log.info( "purge complete '{}'", path ); } catch ( ContinuumPurgeExecutorException e ) { log.error( "failure during repo purge", e ); } } private RepositoryManagedContent getManagedContent( int repoId ) throws ContinuumPurgeExecutorException { try { return purgeConfigurationService.getManagedRepositoryContent( repoId ); } catch ( PurgeConfigurationServiceException e ) { throw new ContinuumPurgeExecutorException( "Error while initializing purge executors", e ); } } }
5,156
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/continuum/purge
Create_ds/continuum/continuum-core/src/main/java/org/apache/continuum/purge/controller/DistributedRepositoryPurgeController.java
package org.apache.continuum.purge.controller; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.distributed.transport.slave.SlaveBuildAgentTransportClient; import org.apache.continuum.distributed.transport.slave.SlaveBuildAgentTransportService; import org.apache.continuum.model.repository.AbstractPurgeConfiguration; import org.apache.continuum.model.repository.DistributedRepositoryPurgeConfiguration; import org.apache.maven.continuum.configuration.ConfigurationService; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.URL; /** * DirectoryPurgeController */ @Component( role = PurgeController.class, hint = "purge-distributed-repository" ) public class DistributedRepositoryPurgeController implements PurgeController { private static final Logger log = LoggerFactory.getLogger( DistributedRepositoryPurgeController.class ); @Requirement private ConfigurationService configurationService; public void purge( AbstractPurgeConfiguration config ) { DistributedRepositoryPurgeConfiguration repoConfig = (DistributedRepositoryPurgeConfiguration) config; String agentUrl = repoConfig.getBuildAgentUrl(); try { SlaveBuildAgentTransportService transportClient = new SlaveBuildAgentTransportClient( new URL( repoConfig.getBuildAgentUrl() ), "", configurationService.getSharedSecretPassword() ); transportClient.ping(); if ( log.isInfoEnabled() ) { log.info( "sending request to {} [repo={},full={},maxAge={},retain={},snapshots={}]", new Object[] { agentUrl, repoConfig.getRepositoryName(), repoConfig.isDeleteAll(), repoConfig.getDaysOlder(), repoConfig.getRetentionCount(), repoConfig.isDeleteReleasedSnapshots() } ); } transportClient.executeRepositoryPurge( repoConfig.getRepositoryName(), repoConfig.getDaysOlder(), repoConfig.getRetentionCount(), repoConfig.isDeleteAll(), repoConfig.isDeleteReleasedSnapshots() ); } catch ( Exception e ) { log.error( String.format( "sending request to %s failed: %s", agentUrl, e.getMessage() ), e ); } } }
5,157
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/continuum/purge
Create_ds/continuum/continuum-core/src/main/java/org/apache/continuum/purge/controller/DirectoryPurgeController.java
package org.apache.continuum.purge.controller; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.model.repository.AbstractPurgeConfiguration; import org.apache.continuum.model.repository.DirectoryPurgeConfiguration; import org.apache.continuum.purge.executor.ContinuumPurgeExecutor; import org.apache.continuum.purge.executor.ContinuumPurgeExecutorException; import org.apache.continuum.purge.executor.dir.DirectoryPurgeExecutorFactory; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * DirectoryPurgeController * * @author Maria Catherine Tan */ @Component( role = org.apache.continuum.purge.controller.PurgeController.class, hint = "purge-directory" ) public class DirectoryPurgeController implements PurgeController { private static final Logger log = LoggerFactory.getLogger( DirectoryPurgeController.class ); @Requirement private DirectoryPurgeExecutorFactory executorFactory; public void purge( AbstractPurgeConfiguration config ) { DirectoryPurgeConfiguration dirPurge = (DirectoryPurgeConfiguration) config; String path = dirPurge.getLocation(); ContinuumPurgeExecutor executor = executorFactory.create( dirPurge.isDeleteAll(), dirPurge.getDaysOlder(), dirPurge.getRetentionCount(), dirPurge.getDirectoryType() ); try { log.info( "purging directory '{}'", path ); executor.purge( path ); log.info( "purge complete '{}'", path ); } catch ( ContinuumPurgeExecutorException e ) { log.error( e.getMessage(), e ); } } }
5,158
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/continuum/purge
Create_ds/continuum/continuum-core/src/main/java/org/apache/continuum/purge/controller/PurgeController.java
package org.apache.continuum.purge.controller; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.model.repository.AbstractPurgeConfiguration; /** * @author Maria Catherine Tan * @since 25 jul 07 */ public interface PurgeController { String ROLE = PurgeController.class.getName(); void purge( AbstractPurgeConfiguration config ); }
5,159
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/continuum/purge
Create_ds/continuum/continuum-core/src/main/java/org/apache/continuum/purge/controller/DistributedDirectoryPurgeController.java
package org.apache.continuum.purge.controller; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.distributed.transport.slave.SlaveBuildAgentTransportClient; import org.apache.continuum.distributed.transport.slave.SlaveBuildAgentTransportService; import org.apache.continuum.model.repository.AbstractPurgeConfiguration; import org.apache.continuum.model.repository.DistributedDirectoryPurgeConfiguration; import org.apache.maven.continuum.configuration.ConfigurationService; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.URL; /** * DirectoryPurgeController */ @Component( role = org.apache.continuum.purge.controller.PurgeController.class, hint = "purge-distributed-directory" ) public class DistributedDirectoryPurgeController implements PurgeController { private static final Logger log = LoggerFactory.getLogger( DistributedDirectoryPurgeController.class ); @Requirement private ConfigurationService configurationService; public void purge( AbstractPurgeConfiguration config ) { DistributedDirectoryPurgeConfiguration dirConfig = (DistributedDirectoryPurgeConfiguration) config; String agentUrl = dirConfig.getBuildAgentUrl(); try { SlaveBuildAgentTransportService transportClient = new SlaveBuildAgentTransportClient( new URL( dirConfig.getBuildAgentUrl() ), "", configurationService.getSharedSecretPassword() ); transportClient.ping(); if ( log.isInfoEnabled() ) { log.info( "sending request to {} [dirType={},full={},maxAge={},retain={}]", new Object[] { dirConfig.getBuildAgentUrl(), dirConfig.getDirectoryType(), dirConfig.isDeleteAll(), dirConfig.getDaysOlder(), dirConfig.getRetentionCount() } ); } transportClient.executeDirectoryPurge( dirConfig.getDirectoryType(), dirConfig.getDaysOlder(), dirConfig.getRetentionCount(), dirConfig.isDeleteAll() ); } catch ( Exception e ) { log.error( String.format( "sending request to %s failed: %s", agentUrl, e.getMessage() ), e ); } } }
5,160
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/continuum/purge
Create_ds/continuum/continuum-core/src/main/java/org/apache/continuum/purge/task/PurgeTaskExecutor.java
package org.apache.continuum.purge.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.model.repository.AbstractPurgeConfiguration; import org.apache.continuum.model.repository.DirectoryPurgeConfiguration; import org.apache.continuum.model.repository.DistributedDirectoryPurgeConfiguration; import org.apache.continuum.model.repository.DistributedRepositoryPurgeConfiguration; import org.apache.continuum.model.repository.RepositoryPurgeConfiguration; import org.apache.continuum.purge.PurgeConfigurationService; import org.apache.continuum.purge.controller.PurgeController; import org.apache.continuum.purge.executor.ContinuumPurgeExecutorException; import org.codehaus.plexus.PlexusConstants; import org.codehaus.plexus.PlexusContainer; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; 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.taskqueue.Task; import org.codehaus.plexus.taskqueue.execution.TaskExecutionException; import org.codehaus.plexus.taskqueue.execution.TaskExecutor; import java.util.HashMap; import java.util.Map; /** * @author Maria Catherine Tan */ @Component( role = org.codehaus.plexus.taskqueue.execution.TaskExecutor.class, hint = "purge" ) public class PurgeTaskExecutor implements TaskExecutor, Contextualizable { static final Map<Class, String> configControllerHints = new HashMap<Class, String>(); static { configControllerHints.put( RepositoryPurgeConfiguration.class, "purge-repository" ); configControllerHints.put( DirectoryPurgeConfiguration.class, "purge-directory" ); configControllerHints.put( DistributedRepositoryPurgeConfiguration.class, "purge-distributed-repository" ); configControllerHints.put( DistributedDirectoryPurgeConfiguration.class, "purge-distributed-directory" ); } @Requirement private PurgeConfigurationService purgeConfigurationService; private PlexusContainer container; public void executeTask( Task task ) throws TaskExecutionException { PurgeTask purgeTask = (PurgeTask) task; AbstractPurgeConfiguration purgeConfig = purgeConfigurationService.getPurgeConfiguration( purgeTask.getPurgeConfigurationId() ); try { if ( purgeConfig != null ) { performPurge( purgeConfig ); } } catch ( ComponentLookupException e ) { throw new TaskExecutionException( "Error while executing purge task", e ); } catch ( ContinuumPurgeExecutorException e ) { throw new TaskExecutionException( "Error while executing purge task", e ); } } private void performPurge( AbstractPurgeConfiguration config ) throws ContinuumPurgeExecutorException, ComponentLookupException { getController( config.getClass() ).purge( config ); } private PurgeController getController( Class configClass ) throws ComponentLookupException { String controllerHint = configControllerHints.get( configClass ); return (PurgeController) container.lookup( PurgeController.ROLE, controllerHint ); } public void contextualize( Context context ) throws ContextException { container = (PlexusContainer) context.get( PlexusConstants.PLEXUS_KEY ); } }
5,161
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/continuum/purge
Create_ds/continuum/continuum-core/src/main/java/org/apache/continuum/purge/task/PurgeTask.java
package org.apache.continuum.purge.task; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.codehaus.plexus.taskqueue.Task; /** * @author Maria Catherine Tan */ public class PurgeTask implements Task { private int purgeConfigurationId; private final long timestamp; private long maxExecutionTime; public PurgeTask( int purgeConfigurationId ) { this.purgeConfigurationId = purgeConfigurationId; this.timestamp = System.currentTimeMillis(); } public int getPurgeConfigurationId() { return purgeConfigurationId; } public void setPurgeConfigurationId( int purgeConfigurationId ) { this.purgeConfigurationId = purgeConfigurationId; } public void setMaxExecutionTime( long maxExecutionTime ) { this.maxExecutionTime = maxExecutionTime; } public long getMaxExecutionTime() { return maxExecutionTime; } public long getTimestamp() { return timestamp; } }
5,162
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/continuum
Create_ds/continuum/continuum-core/src/main/java/org/apache/continuum/buildmanager/ParallelBuildsManager.java
package org.apache.continuum.buildmanager; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ 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 <a href="mailto:oching@apache.org">Maria Odea Ching</a> */ 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; } }
5,163
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/continuum
Create_ds/continuum/continuum-core/src/main/java/org/apache/continuum/taskqueueexecutor/ParallelBuildsThreadedTaskQueueExecutor.java
package org.apache.continuum.taskqueueexecutor; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import edu.emory.mathcs.backport.java.util.concurrent.CancellationException; import edu.emory.mathcs.backport.java.util.concurrent.ExecutionException; import edu.emory.mathcs.backport.java.util.concurrent.ExecutorService; import edu.emory.mathcs.backport.java.util.concurrent.Executors; import edu.emory.mathcs.backport.java.util.concurrent.Future; import edu.emory.mathcs.backport.java.util.concurrent.TimeUnit; import edu.emory.mathcs.backport.java.util.concurrent.TimeoutException; import org.apache.continuum.utils.ThreadNames; import org.codehaus.plexus.component.annotations.Configuration; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.personality.plexus.lifecycle.phase.Disposable; import org.codehaus.plexus.personality.plexus.lifecycle.phase.Initializable; import org.codehaus.plexus.personality.plexus.lifecycle.phase.InitializationException; import org.codehaus.plexus.personality.plexus.lifecycle.phase.Startable; import org.codehaus.plexus.personality.plexus.lifecycle.phase.StartingException; import org.codehaus.plexus.personality.plexus.lifecycle.phase.StoppingException; import org.codehaus.plexus.taskqueue.Task; import org.codehaus.plexus.taskqueue.TaskQueue; import org.codehaus.plexus.taskqueue.execution.TaskExecutionException; import org.codehaus.plexus.taskqueue.execution.TaskExecutor; import org.codehaus.plexus.taskqueue.execution.TaskQueueExecutor; import org.codehaus.plexus.util.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Modified plexus ThreadedTaskQueueExecutor */ public class ParallelBuildsThreadedTaskQueueExecutor implements TaskQueueExecutor, Initializable, Startable, Disposable { private static final Logger log = LoggerFactory.getLogger( ParallelBuildsThreadedTaskQueueExecutor.class ); private static final int SHUTDOWN = 1; private static final int CANCEL_TASK = 2; @Requirement private TaskQueue queue; @Requirement private TaskExecutor executor; @Configuration( "" ) private String name; // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- private ExecutorRunnable executorRunnable; private ExecutorService executorService; private Task currentTask; private class ExecutorRunnable extends Thread { private volatile int command; private boolean done; public ExecutorRunnable() { super( ThreadNames.formatNext( "%s-executor", name ) ); } public void run() { while ( command != SHUTDOWN ) { final Task task; currentTask = null; try { task = queue.poll( 100, TimeUnit.MILLISECONDS ); } catch ( InterruptedException e ) { log.info( "Executor thread interrupted, command: " + ( command == SHUTDOWN ? "Shutdown" : command == CANCEL_TASK ? "Cancel task" : "Unknown" ) ); continue; } if ( task == null ) { continue; } currentTask = task; Future future = executorService.submit( new Runnable() { public void run() { try { executor.executeTask( task ); } catch ( TaskExecutionException e ) { log.error( "Error executing task", e ); } } } ); try { waitForTask( task, future ); } catch ( ExecutionException e ) { log.error( "Error executing task", e ); } } currentTask = null; log.info( "Executor thread '" + name + "' exited." ); done = true; synchronized ( this ) { notifyAll(); } } private void waitForTask( Task task, Future future ) throws ExecutionException { boolean stop = false; while ( !stop ) { try { if ( task.getMaxExecutionTime() == 0 ) { log.debug( "Waiting indefinitely for task to complete" ); future.get(); return; } else { log.debug( "Waiting at most " + task.getMaxExecutionTime() + "ms for task completion" ); future.get( task.getMaxExecutionTime(), TimeUnit.MILLISECONDS ); log.debug( "Task completed within " + task.getMaxExecutionTime() + "ms" ); return; } } catch ( InterruptedException e ) { switch ( command ) { case SHUTDOWN: { log.info( "Shutdown command received. Cancelling task." ); cancel( future ); return; } case CANCEL_TASK: { command = 0; log.info( "Cancelling task" ); cancel( future ); return; } default: // when can this thread be interrupted, and should we ignore it if shutdown = false? log.warn( "Interrupted while waiting for task to complete; ignoring", e ); break; } } catch ( TimeoutException e ) { log.warn( "Task " + task + " didn't complete within time, cancelling it." ); cancel( future ); return; } catch ( CancellationException e ) { log.warn( "The task was cancelled", e ); return; } } } private void cancel( Future future ) { if ( !future.cancel( true ) ) { if ( !future.isDone() && !future.isCancelled() ) { log.warn( "Unable to cancel task" ); } else { log.warn( "Task not cancelled (Flags: done: " + future.isDone() + " cancelled: " + future.isCancelled() + ")" ); } } else { log.debug( "Task successfully cancelled" ); } } public synchronized void shutdown() { log.debug( "Signalling executor thread to shutdown" ); command = SHUTDOWN; interrupt(); } public synchronized boolean cancelTask( Task task ) { if ( !task.equals( currentTask ) ) { log.debug( "Not cancelling task - it is not running" ); return false; } if ( command != SHUTDOWN ) { log.debug( "Signalling executor thread to cancel task" ); command = CANCEL_TASK; interrupt(); } else { log.debug( "Executor thread already stopping; task will be cancelled automatically" ); } return true; } public boolean isDone() { return done; } } // ---------------------------------------------------------------------- // Component lifecycle // ---------------------------------------------------------------------- public void initialize() throws InitializationException { if ( StringUtils.isEmpty( name ) ) { throw new IllegalArgumentException( "'name' must be set." ); } } public void start() throws StartingException { log.info( "Starting task executor, thread name '" + name + "'." ); this.executorService = Executors.newCachedThreadPool(); executorRunnable = new ExecutorRunnable(); executorRunnable.setDaemon( true ); executorRunnable.start(); } public void stop() throws StoppingException { executorRunnable.shutdown(); int maxSleep = 10 * 1000; // 10 seconds int interval = 1000; long endTime = System.currentTimeMillis() + maxSleep; while ( !executorRunnable.isDone() && executorRunnable.isAlive() ) { if ( System.currentTimeMillis() > endTime ) { log.warn( "Timeout waiting for executor thread '" + name + "' to stop, aborting" ); break; } log.info( "Waiting until task executor '" + name + "' is idling..." ); try { synchronized ( executorRunnable ) { executorRunnable.wait( interval ); } } catch ( InterruptedException ex ) { // ignore } // notify again, just in case. executorRunnable.shutdown(); } } public void dispose() { executorRunnable.shutdown(); } public Task getCurrentTask() { return currentTask; } public synchronized boolean cancelTask( Task task ) { return executorRunnable.cancelTask( task ); } public String getName() { return name; } public void setName( String name ) { this.name = name; } public TaskQueue getQueue() { return queue; } }
5,164
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/continuum
Create_ds/continuum/continuum-core/src/main/java/org/apache/continuum/builder/OrphanBuildStatusUpdater.java
package org.apache.continuum.builder; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.builder.distributed.work.BuildStatusUpdater; import org.apache.continuum.dao.BuildResultDao; import org.apache.maven.continuum.store.ContinuumStoreException; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Configuration; import org.codehaus.plexus.component.annotations.Requirement; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Set; @Component( role = BuildStatusUpdater.class, hint = "orphans" ) public class OrphanBuildStatusUpdater implements BuildStatusUpdater { private static final Logger log = LoggerFactory.getLogger( OrphanBuildStatusUpdater.class ); @Requirement private BuildResultDao buildResultDao; @Configuration( "24" ) private int orphanAfterHours; public void setOrphanAfterHours( int orphanAfterHours ) { this.orphanAfterHours = orphanAfterHours; } public void performScan() { if ( orphanAfterHours <= 0 ) { log.warn( "disabled by configuration: orphan-after-hours = {}", orphanAfterHours ); return; } try { long hourInMillis = 1000 * 60 * 60, now = System.currentTimeMillis(); long orphanCutoff = now - ( orphanAfterHours * hourInMillis ); log.info( "attempting to cancel results in-progress for more than {} hours", orphanAfterHours ); Set<Integer> orphans = buildResultDao.resolveOrphanedInProgressResults( orphanCutoff ); if ( orphans.isEmpty() ) { log.info( "marked no results as canceled" ); } else { log.info( "marked {} results as canceled: {}", orphans.size(), orphans ); } } catch ( ContinuumStoreException e ) { log.warn( "failed to resolve orphaned build results: ", e.getMessage() ); } } }
5,165
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/continuum/builder
Create_ds/continuum/continuum-core/src/main/java/org/apache/continuum/builder/distributed/DefaultDistributedBuildService.java
package org.apache.continuum.builder.distributed; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.commons.io.IOUtils; import org.apache.continuum.builder.distributed.manager.DistributedBuildManager; import org.apache.continuum.builder.distributed.util.DistributedBuildUtil; import org.apache.continuum.builder.utils.ContinuumBuildConstant; import org.apache.continuum.dao.BuildDefinitionDao; import org.apache.continuum.dao.BuildResultDao; import org.apache.continuum.dao.ProjectDao; import org.apache.continuum.dao.ProjectScmRootDao; import org.apache.continuum.model.project.ProjectRunSummary; import org.apache.continuum.model.project.ProjectScmRoot; import org.apache.maven.continuum.ContinuumException; import org.apache.maven.continuum.configuration.ConfigurationException; import org.apache.maven.continuum.configuration.ConfigurationService; import org.apache.maven.continuum.execution.ContinuumBuildExecutorConstants; import org.apache.maven.continuum.installation.InstallationService; import org.apache.maven.continuum.model.project.BuildDefinition; import org.apache.maven.continuum.model.project.BuildResult; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.model.project.ProjectDependency; import org.apache.maven.continuum.model.project.ProjectDeveloper; import org.apache.maven.continuum.model.project.ProjectNotifier; import org.apache.maven.continuum.model.scm.ChangeFile; import org.apache.maven.continuum.model.scm.ChangeSet; import org.apache.maven.continuum.model.system.Installation; import org.apache.maven.continuum.model.system.Profile; import org.apache.maven.continuum.notification.ContinuumNotificationDispatcher; import org.apache.maven.continuum.project.ContinuumProjectState; import org.apache.maven.continuum.store.ContinuumStoreException; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.util.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; @Component( role = org.apache.continuum.builder.distributed.DistributedBuildService.class ) public class DefaultDistributedBuildService implements DistributedBuildService { private static final Logger log = LoggerFactory.getLogger( DefaultDistributedBuildService.class ); @Requirement private ProjectDao projectDao; @Requirement private BuildDefinitionDao buildDefinitionDao; @Requirement private BuildResultDao buildResultDao; @Requirement private ProjectScmRootDao projectScmRootDao; @Requirement private ConfigurationService configurationService; @Requirement private InstallationService installationService; @Requirement private ContinuumNotificationDispatcher notifierDispatcher; @Requirement private DistributedBuildUtil distributedBuildUtil; @Requirement private DistributedBuildManager distributedBuildManager; public void updateBuildResult( Map<String, Object> context ) throws ContinuumException { try { int projectId = ContinuumBuildConstant.getProjectId( context ); int buildDefinitionId = ContinuumBuildConstant.getBuildDefinitionId( context ); Project project = projectDao.getProjectWithAllDetails( projectId ); BuildDefinition buildDefinition = buildDefinitionDao.getBuildDefinition( buildDefinitionId ); BuildResult buildResult, oldBuildResult; log.info( "update build result of project '{}'", projectId ); // Get the result id for this build, it may be current or canceled ProjectRunSummary canceledRun = null; int existingResultId = 0; try { existingResultId = distributedBuildManager.getCurrentRun( projectId, buildDefinitionId ).getBuildResultId(); } catch ( ContinuumException e ) { try { log.debug( "no current run summary found, attempting to find canceled run" ); canceledRun = distributedBuildManager.getCanceledRun( projectId, buildDefinitionId ); existingResultId = canceledRun.getBuildResultId(); } catch ( ContinuumException e1 ) { log.warn( "failed to find result for remote build {}", e.getMessage() ); } } boolean existingResult = existingResultId > 0; int buildNumber = project.getBuildNumber(); if ( existingResult ) { buildResult = buildResultDao.getBuildResult( existingResultId ); distributedBuildUtil.updateBuildResultFromMap( buildResult, context ); oldBuildResult = buildResultDao.getPreviousBuildResultForBuildDefinition( projectId, buildDefinitionId, existingResultId ); } else { buildNumber += 1; buildResult = distributedBuildUtil.convertMapToBuildResult( context ); oldBuildResult = buildResultDao.getLatestBuildResultForBuildDefinition( projectId, buildDefinitionId ); buildResult.setBuildNumber( buildNumber ); buildResult.setBuildDefinition( buildDefinition ); } // Set the complete contents of the build result... buildResult.setModifiedDependencies( distributedBuildUtil.getModifiedDependencies( oldBuildResult, context ) ); buildResult.setScmResult( distributedBuildUtil.getScmResult( context ) ); Date date = ContinuumBuildConstant.getLatestUpdateDate( context ); if ( date != null ) { buildResult.setLastChangedDate( date.getTime() ); } else if ( oldBuildResult != null ) { buildResult.setLastChangedDate( oldBuildResult.getLastChangedDate() ); } if ( existingResult ) { buildResultDao.updateBuildResult( buildResult ); } else { buildResultDao.addBuildResult( project, buildResult ); buildResult = buildResultDao.getBuildResult( buildResult.getId() ); } project.setOldState( project.getState() ); project.setState( ContinuumBuildConstant.getBuildState( context ) ); project.setBuildNumber( buildNumber ); project.setLatestBuildId( buildResult.getId() ); projectDao.updateProject( project ); File buildOutputFile = configurationService.getBuildOutputFile( buildResult.getId(), project.getId() ); FileWriter fileWriter = null; try { fileWriter = new FileWriter( buildOutputFile ); String output = ContinuumBuildConstant.getBuildOutput( context ); fileWriter.write( output == null ? "" : output ); } finally { IOUtils.closeQuietly( fileWriter ); } if ( canceledRun != null ) { // We have joined the cancellation with the result, time to clean it up distributedBuildManager.removeCanceledRun( canceledRun ); } else { // Build was successful, notify and cleanup associated run notifierDispatcher.buildComplete( project, buildDefinition, buildResult ); distributedBuildManager.removeCurrentRun( projectId, buildDefinitionId ); } } catch ( ContinuumStoreException e ) { throw new ContinuumException( "Error while updating build result for project", e ); } catch ( ConfigurationException e ) { throw new ContinuumException( "Error retrieving build output file", e ); } catch ( IOException e ) { throw new ContinuumException( "Error while writing build output to file", e ); } } public void prepareBuildFinished( Map<String, Object> context ) throws ContinuumException { int projectGroupId = ContinuumBuildConstant.getProjectGroupId( context ); String scmRootAddress = ContinuumBuildConstant.getScmRootAddress( context ); try { ProjectScmRoot scmRoot = projectScmRootDao.getProjectScmRootByProjectGroupAndScmRootAddress( projectGroupId, scmRootAddress ); String error = ContinuumBuildConstant.getScmError( context ); if ( StringUtils.isEmpty( error ) ) { scmRoot.setState( ContinuumProjectState.UPDATED ); } else { scmRoot.setState( ContinuumProjectState.ERROR ); scmRoot.setError( error ); } projectScmRootDao.updateProjectScmRoot( scmRoot ); notifierDispatcher.prepareBuildComplete( scmRoot ); } catch ( ContinuumStoreException e ) { throw new ContinuumException( "Error while updating project scm root '" + scmRootAddress + "'", e ); } } public void startProjectBuild( int projectId, int buildDefinitionId ) throws ContinuumException { try { createNewBuildResult( distributedBuildManager.getCurrentRun( projectId, buildDefinitionId ) ); } catch ( ContinuumStoreException e ) { log.error( "Error while updating project's state (projectId=" + projectId + ")", e ); throw new ContinuumException( "Error while updating project's state (projectId=" + projectId + ")", e ); } } private void createNewBuildResult( ProjectRunSummary summary ) throws ContinuumStoreException { long now = System.currentTimeMillis(); Project project = projectDao.getProject( summary.getProjectId() ); BuildDefinition buildDef = buildDefinitionDao.getBuildDefinition( summary.getBuildDefinitionId() ); project.setBuildNumber( project.getBuildNumber() + 1 ); // starting build, create a new build number BuildResult buildResult = new BuildResult(); buildResult.setBuildNumber( project.getBuildNumber() ); buildResult.setBuildUrl( summary.getBuildAgentUrl() ); buildResult.setState( ContinuumProjectState.BUILDING ); buildResult.setBuildDefinition( buildDef ); buildResult.setTrigger( summary.getTrigger() ); buildResult.setUsername( summary.getTriggeredBy() ); buildResult.setStartTime( now ); buildResultDao.addBuildResult( project, buildResult ); project.setLatestBuildId( buildResult.getId() ); project.setOldState( project.getState() ); project.setState( ContinuumProjectState.BUILDING ); projectDao.updateProject( project ); summary.setBuildResultId( buildResult.getId() ); } public void startPrepareBuild( Map<String, Object> context ) throws ContinuumException { int projectGroupId = ContinuumBuildConstant.getProjectGroupId( context ); try { String scmRootAddress = ContinuumBuildConstant.getScmRootAddress( context ); ProjectScmRoot scmRoot = projectScmRootDao.getProjectScmRootByProjectGroupAndScmRootAddress( projectGroupId, scmRootAddress ); scmRoot.setOldState( scmRoot.getState() ); scmRoot.setState( ContinuumProjectState.UPDATING ); projectScmRootDao.updateProjectScmRoot( scmRoot ); } catch ( ContinuumStoreException e ) { log.error( "Error while updating project group'" + projectGroupId + "' scm root's state", e ); throw new ContinuumException( "Error while updating project group'" + projectGroupId + "' scm root's state", e ); } } public Map<String, String> getEnvironments( int buildDefinitionId, String installationType ) throws ContinuumException { BuildDefinition buildDefinition; try { buildDefinition = buildDefinitionDao.getBuildDefinition( buildDefinitionId ); } catch ( ContinuumStoreException e ) { throw new ContinuumException( "Failed to retrieve build definition: " + buildDefinitionId, e ); } Profile profile = buildDefinition.getProfile(); if ( profile == null ) { return Collections.EMPTY_MAP; } Map<String, String> envVars = new HashMap<String, String>(); String javaHome = getJavaHomeValue( buildDefinition ); if ( !StringUtils.isEmpty( javaHome ) ) { envVars.put( installationService.getEnvVar( InstallationService.JDK_TYPE ), javaHome ); } Installation builder = profile.getBuilder(); if ( builder != null ) { envVars.put( installationService.getEnvVar( installationType ), builder.getVarValue() ); } envVars.putAll( getEnvironmentVariables( buildDefinition ) ); return envVars; } public void updateProject( Map<String, Object> context ) throws ContinuumException { try { Project project = projectDao.getProjectWithAllDetails( ContinuumBuildConstant.getProjectId( context ) ); if ( StringUtils.isNotBlank( ContinuumBuildConstant.getGroupId( context ) ) ) { project.setGroupId( ContinuumBuildConstant.getGroupId( context ) ); } if ( StringUtils.isNotBlank( ContinuumBuildConstant.getArtifactId( context ) ) ) { project.setArtifactId( ContinuumBuildConstant.getArtifactId( context ) ); } if ( StringUtils.isNotBlank( ContinuumBuildConstant.getVersion( context ) ) ) { project.setVersion( ContinuumBuildConstant.getVersion( context ) ); } if ( StringUtils.isNotBlank( ContinuumBuildConstant.getProjectName( context ) ) ) { project.setName( ContinuumBuildConstant.getProjectName( context ) ); } if ( StringUtils.isNotBlank( ContinuumBuildConstant.getProjectDescription( context ) ) ) { project.setDescription( ContinuumBuildConstant.getProjectDescription( context ) ); } if ( StringUtils.isNotBlank( ContinuumBuildConstant.getProjectUrl( context ) ) ) { project.setUrl( ContinuumBuildConstant.getProjectUrl( context ) ); } if ( StringUtils.isNotBlank( ContinuumBuildConstant.getScmUrl( context ) ) ) { project.setScmUrl( ContinuumBuildConstant.getScmUrl( context ) ); } if ( StringUtils.isNotBlank( ContinuumBuildConstant.getScmTag( context ) ) ) { project.setScmTag( ContinuumBuildConstant.getScmTag( context ) ); } project.setParent( getProjectParent( context ) ); project.setDependencies( getProjectDependencies( context ) ); project.setDevelopers( getProjectDevelopers( context ) ); List<ProjectNotifier> userNotifiers = new ArrayList<ProjectNotifier>(); if ( project.getNotifiers() != null ) { for ( ProjectNotifier notifier : project.getNotifiers() ) { if ( notifier.isFromUser() ) { ProjectNotifier userNotifier = new ProjectNotifier(); userNotifier.setType( notifier.getType() ); userNotifier.setEnabled( notifier.isEnabled() ); userNotifier.setConfiguration( notifier.getConfiguration() ); userNotifier.setFrom( notifier.getFrom() ); userNotifier.setRecipientType( notifier.getRecipientType() ); userNotifier.setSendOnError( notifier.isSendOnError() ); userNotifier.setSendOnFailure( notifier.isSendOnFailure() ); userNotifier.setSendOnSuccess( notifier.isSendOnSuccess() ); userNotifier.setSendOnWarning( notifier.isSendOnWarning() ); userNotifier.setSendOnScmFailure( notifier.isSendOnScmFailure() ); userNotifiers.add( userNotifier ); } } } project.setNotifiers( getProjectNotifiers( context ) ); for ( ProjectNotifier userNotifier : userNotifiers ) { project.addNotifier( userNotifier ); } projectDao.updateProject( project ); } catch ( ContinuumStoreException e ) { throw new ContinuumException( "Unable to update project '" + ContinuumBuildConstant.getProjectId( context ) + "' from working copy", e ); } } public boolean shouldBuild( Map<String, Object> context ) { int projectId = ContinuumBuildConstant.getProjectId( context ); try { int buildDefinitionId = ContinuumBuildConstant.getBuildDefinitionId( context ); int trigger = ContinuumBuildConstant.getTrigger( context ); Project project = projectDao.getProjectWithAllDetails( projectId ); BuildDefinition buildDefinition = buildDefinitionDao.getBuildDefinition( buildDefinitionId ); BuildResult oldBuildResult = buildResultDao.getLatestBuildResultForBuildDefinition( projectId, buildDefinitionId ); List<ProjectDependency> modifiedDependencies = distributedBuildUtil.getModifiedDependencies( oldBuildResult, context ); List<ChangeSet> changes = distributedBuildUtil.getScmChanges( context ); if ( buildDefinition.isAlwaysBuild() ) { log.info( "AlwaysBuild configured, building (projectId=" + projectId + ")" ); return true; } if ( oldBuildResult == null ) { log.info( "The project '" + projectId + "' was never built with the current build definition, building" ); return true; } //CONTINUUM-1428 if ( project.getOldState() == ContinuumProjectState.ERROR || oldBuildResult.getState() == ContinuumProjectState.ERROR ) { log.info( "Latest state was 'ERROR', building (projectId=" + projectId + ")" ); return true; } if ( trigger == ContinuumProjectState.TRIGGER_FORCED ) { log.info( "The project '" + projectId + "' build is forced, building" ); return true; } Date date = ContinuumBuildConstant.getLatestUpdateDate( context ); if ( date != null && oldBuildResult.getLastChangedDate() >= date.getTime() ) { log.info( "No changes found, not building (projectId=" + projectId + ")" ); return false; } else if ( date != null && changes.isEmpty() ) { // fresh checkout from build agent that's why changes is empty log.info( "Changes found in the current project, building (projectId=" + projectId + ")" ); return true; } boolean shouldBuild = false; boolean allChangesUnknown = true; if ( project.getOldState() != ContinuumProjectState.NEW && project.getOldState() != ContinuumProjectState.CHECKEDOUT && project.getState() != ContinuumProjectState.NEW && project.getState() != ContinuumProjectState.CHECKEDOUT ) { // Check SCM changes allChangesUnknown = checkAllChangesUnknown( changes ); if ( allChangesUnknown ) { if ( !changes.isEmpty() ) { log.info( "The project '" + projectId + "' was not built because all changes are unknown (maybe local modifications or ignored files not defined in your SCM tool." ); } else { log.info( "The project '" + projectId + "' was not built because no changes were detected in sources since the last build." ); } } // Check dependencies changes if ( modifiedDependencies != null && !modifiedDependencies.isEmpty() ) { log.info( "Found dependencies changes, building (projectId=" + projectId + ")" ); shouldBuild = true; } } // Check changes if ( !shouldBuild && ( ( !allChangesUnknown && !changes.isEmpty() ) || project.getExecutorId().equals( ContinuumBuildExecutorConstants.MAVEN_TWO_BUILD_EXECUTOR ) ) ) { shouldBuild = shouldBuild( changes, buildDefinition, project, getMavenProjectVersion( context ), getMavenProjectModules( context ) ); } if ( shouldBuild ) { log.info( "Changes found in the current project, building (projectId=" + projectId + ")" ); } else { log.info( "No changes in the current project, not building (projectId=" + projectId + ")" ); } return shouldBuild; } catch ( ContinuumStoreException e ) { log.error( "Failed to determine if project '" + projectId + "' should build", e ); } catch ( ContinuumException e ) { log.error( "Failed to determine if project '" + projectId + "' should build", e ); } return false; } private boolean shouldBuild( List<ChangeSet> changes, BuildDefinition buildDefinition, Project project, String mavenProjectVersion, List<String> mavenProjectModules ) { //Check if it's a recursive build boolean isRecursive = false; if ( StringUtils.isNotEmpty( buildDefinition.getArguments() ) ) { isRecursive = buildDefinition.getArguments().indexOf( "-N" ) < 0 && buildDefinition.getArguments().indexOf( "--non-recursive" ) < 0; } if ( isRecursive && changes != null && !changes.isEmpty() ) { if ( log.isInfoEnabled() ) { log.info( "recursive build and changes found --> building (projectId=" + project.getId() + ")" ); } return true; } if ( !project.getVersion().equals( mavenProjectVersion ) ) { log.info( "Found changes in project's version ( maybe project '" + project.getId() + "' was recently released ), building" ); return true; } if ( changes == null || changes.isEmpty() ) { if ( log.isInfoEnabled() ) { log.info( "Found no changes, not building (projectId=" + project.getId() + ")" ); } return false; } //check if changes are only in sub-modules or not List<ChangeFile> files = new ArrayList<ChangeFile>(); for ( ChangeSet changeSet : changes ) { files.addAll( changeSet.getFiles() ); } int i = 0; while ( i <= files.size() - 1 ) { ChangeFile file = files.get( i ); if ( log.isDebugEnabled() ) { log.debug( "changeFile.name " + file.getName() ); log.debug( "check in modules " + mavenProjectModules ); } boolean found = false; if ( mavenProjectModules != null ) { for ( String module : mavenProjectModules ) { if ( file.getName().indexOf( module ) >= 0 ) { if ( log.isDebugEnabled() ) { log.debug( "changeFile.name " + file.getName() + " removed because in a module" ); } files.remove( file ); found = true; break; } if ( log.isDebugEnabled() ) { log.debug( "not removing file " + file.getName() + " not in module " + module ); } } } if ( !found ) { i++; } } boolean shouldBuild = !files.isEmpty(); if ( !shouldBuild ) { log.info( "Changes are only in sub-modules (projectId=" + project.getId() + ")." ); } if ( log.isDebugEnabled() ) { log.debug( "shoulbuild = " + shouldBuild ); } return shouldBuild; } private boolean checkAllChangesUnknown( List<ChangeSet> changes ) { for ( ChangeSet changeSet : changes ) { List<ChangeFile> changeFiles = changeSet.getFiles(); for ( ChangeFile changeFile : changeFiles ) { if ( !"unknown".equalsIgnoreCase( changeFile.getStatus() ) ) { return false; } } } return true; } private String getJavaHomeValue( BuildDefinition buildDefinition ) { Profile profile = buildDefinition.getProfile(); if ( profile == null ) { return null; } Installation jdk = profile.getJdk(); if ( jdk == null ) { return null; } return jdk.getVarValue(); } private Map<String, String> getEnvironmentVariables( BuildDefinition buildDefinition ) { Profile profile = buildDefinition.getProfile(); Map<String, String> envVars = new HashMap<String, String>(); if ( profile == null ) { return envVars; } List<Installation> environmentVariables = profile.getEnvironmentVariables(); if ( environmentVariables.isEmpty() ) { return envVars; } for ( Installation installation : environmentVariables ) { envVars.put( installation.getVarName(), installation.getVarValue() ); } return envVars; } private ProjectDependency getProjectParent( Map<String, Object> context ) { Map<String, Object> map = ContinuumBuildConstant.getProjectParent( context ); if ( map != null && map.size() > 0 ) { ProjectDependency parent = new ProjectDependency(); parent.setGroupId( ContinuumBuildConstant.getGroupId( map ) ); parent.setArtifactId( ContinuumBuildConstant.getArtifactId( map ) ); parent.setVersion( ContinuumBuildConstant.getVersion( map ) ); return parent; } return null; } private List<ProjectDependency> getProjectDependencies( Map<String, Object> context ) { List<ProjectDependency> projectDependencies = new ArrayList<ProjectDependency>(); List<Map<String, Object>> dependencies = ContinuumBuildConstant.getProjectDependencies( context ); if ( dependencies != null ) { for ( Map<String, Object> map : dependencies ) { ProjectDependency dependency = new ProjectDependency(); dependency.setGroupId( ContinuumBuildConstant.getGroupId( map ) ); dependency.setArtifactId( ContinuumBuildConstant.getArtifactId( map ) ); dependency.setVersion( ContinuumBuildConstant.getVersion( map ) ); projectDependencies.add( dependency ); } } return projectDependencies; } private List<ProjectDeveloper> getProjectDevelopers( Map<String, Object> context ) { List<ProjectDeveloper> projectDevelopers = new ArrayList<ProjectDeveloper>(); List<Map<String, Object>> developers = ContinuumBuildConstant.getProjectDevelopers( context ); if ( developers != null ) { for ( Map<String, Object> map : developers ) { ProjectDeveloper developer = new ProjectDeveloper(); developer.setName( ContinuumBuildConstant.getDeveloperName( map ) ); developer.setEmail( ContinuumBuildConstant.getDeveloperEmail( map ) ); developer.setScmId( ContinuumBuildConstant.getDeveloperScmId( map ) ); projectDevelopers.add( developer ); } } return projectDevelopers; } private List<ProjectNotifier> getProjectNotifiers( Map<String, Object> context ) { List<ProjectNotifier> projectNotifiers = new ArrayList<ProjectNotifier>(); List<Map<String, Object>> notifiers = ContinuumBuildConstant.getProjectNotifiers( context ); if ( notifiers != null ) { for ( Map<String, Object> map : notifiers ) { ProjectNotifier notifier = new ProjectNotifier(); notifier.setConfiguration( ContinuumBuildConstant.getNotifierConfiguration( map ) ); notifier.setEnabled( ContinuumBuildConstant.isNotifierEnabled( map ) ); notifier.setFrom( ContinuumBuildConstant.getNotifierFrom( map ) ); notifier.setRecipientType( ContinuumBuildConstant.getNotifierRecipientType( map ) ); notifier.setSendOnError( ContinuumBuildConstant.isNotifierSendOnError( map ) ); notifier.setSendOnFailure( ContinuumBuildConstant.isNotifierSendOnFailure( map ) ); notifier.setSendOnScmFailure( ContinuumBuildConstant.isNotifierSendOnScmFailure( map ) ); notifier.setSendOnSuccess( ContinuumBuildConstant.isNotifierSendOnSuccess( map ) ); notifier.setSendOnWarning( ContinuumBuildConstant.isNotifierSendOnWarning( map ) ); notifier.setType( ContinuumBuildConstant.getNotifierType( map ) ); projectNotifiers.add( notifier ); } } return projectNotifiers; } private String getMavenProjectVersion( Map<String, Object> context ) { Map<String, Object> map = ContinuumBuildConstant.getMavenProject( context ); if ( !map.isEmpty() ) { return ContinuumBuildConstant.getVersion( map ); } return null; } private List<String> getMavenProjectModules( Map<String, Object> context ) { Map<String, Object> map = ContinuumBuildConstant.getMavenProject( context ); if ( !map.isEmpty() ) { return ContinuumBuildConstant.getProjectModules( map ); } return null; } }
5,166
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/continuum/builder/distributed
Create_ds/continuum/continuum-core/src/main/java/org/apache/continuum/builder/distributed/util/DistributedBuildUtil.java
package org.apache.continuum.builder.distributed.util; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.builder.utils.ContinuumBuildConstant; import org.apache.continuum.dao.BuildResultDao; import org.apache.continuum.dao.ProjectDao; import org.apache.maven.continuum.ContinuumException; import org.apache.maven.continuum.model.project.BuildResult; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.model.project.ProjectDependency; import org.apache.maven.continuum.model.scm.ChangeFile; import org.apache.maven.continuum.model.scm.ChangeSet; import org.apache.maven.continuum.model.scm.ScmResult; import org.apache.maven.continuum.store.ContinuumStoreException; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; import java.util.Map; @Component( role = org.apache.continuum.builder.distributed.util.DistributedBuildUtil.class ) public class DistributedBuildUtil { private Logger log = LoggerFactory.getLogger( DistributedBuildUtil.class ); @Requirement private ProjectDao projectDao; @Requirement private BuildResultDao buildResultDao; public BuildResult convertMapToBuildResult( Map<String, Object> context ) { BuildResult buildResult = new BuildResult(); updateBuildResultFromMap( buildResult, context ); return buildResult; } public void updateBuildResultFromMap( BuildResult buildResult, Map<String, Object> context ) { buildResult.setStartTime( ContinuumBuildConstant.getStartTime( context ) ); buildResult.setEndTime( ContinuumBuildConstant.getEndTime( context ) ); buildResult.setError( ContinuumBuildConstant.getBuildError( context ) ); buildResult.setExitCode( ContinuumBuildConstant.getBuildExitCode( context ) ); buildResult.setState( ContinuumBuildConstant.getBuildState( context ) ); buildResult.setTrigger( ContinuumBuildConstant.getTrigger( context ) ); buildResult.setUsername( ContinuumBuildConstant.getUsername( context ) ); buildResult.setBuildUrl( ContinuumBuildConstant.getBuildAgentUrl( context ) ); } public List<ProjectDependency> getModifiedDependencies( BuildResult oldBuildResult, Map<String, Object> context ) throws ContinuumException { if ( oldBuildResult == null ) { return null; } try { Project project = projectDao.getProjectWithAllDetails( ContinuumBuildConstant.getProjectId( context ) ); List<ProjectDependency> dependencies = project.getDependencies(); if ( dependencies == null ) { dependencies = new ArrayList<ProjectDependency>(); } if ( project.getParent() != null ) { dependencies.add( project.getParent() ); } if ( dependencies.isEmpty() ) { return null; } List<ProjectDependency> modifiedDependencies = new ArrayList<ProjectDependency>(); for ( ProjectDependency dep : dependencies ) { Project dependencyProject = projectDao.getProject( dep.getGroupId(), dep.getArtifactId(), dep.getVersion() ); if ( dependencyProject != null ) { long nbBuild = buildResultDao.getNbBuildResultsInSuccessForProject( dependencyProject.getId(), oldBuildResult.getEndTime() ); if ( nbBuild > 0 ) { log.debug( "Dependency changed: " + dep.getGroupId() + ":" + dep.getArtifactId() + ":" + dep.getVersion() ); modifiedDependencies.add( dep ); } else { log.debug( "Dependency not changed: " + dep.getGroupId() + ":" + dep.getArtifactId() + ":" + dep.getVersion() ); } } else { log.debug( "Skip non Continuum project: " + dep.getGroupId() + ":" + dep.getArtifactId() + ":" + dep.getVersion() ); } } return modifiedDependencies; } catch ( ContinuumStoreException e ) { log.warn( "Can't get the project dependencies", e ); } return null; } public ScmResult getScmResult( Map<String, Object> context ) { Map<String, Object> map = ContinuumBuildConstant.getScmResult( context ); if ( !map.isEmpty() ) { ScmResult scmResult = new ScmResult(); scmResult.setCommandLine( ContinuumBuildConstant.getScmCommandLine( map ) ); scmResult.setCommandOutput( ContinuumBuildConstant.getScmCommandOutput( map ) ); scmResult.setException( ContinuumBuildConstant.getScmException( map ) ); scmResult.setProviderMessage( ContinuumBuildConstant.getScmProviderMessage( map ) ); scmResult.setSuccess( ContinuumBuildConstant.isScmSuccess( map ) ); scmResult.setChanges( getScmChanges( map ) ); return scmResult; } return null; } public List<ChangeSet> getScmChanges( Map<String, Object> context ) { List<ChangeSet> changes = new ArrayList<ChangeSet>(); List<Map<String, Object>> scmChanges = ContinuumBuildConstant.getScmChanges( context ); if ( scmChanges != null ) { for ( Map<String, Object> map : scmChanges ) { ChangeSet changeSet = new ChangeSet(); changeSet.setAuthor( ContinuumBuildConstant.getChangeSetAuthor( map ) ); changeSet.setComment( ContinuumBuildConstant.getChangeSetComment( map ) ); changeSet.setDate( ContinuumBuildConstant.getChangeSetDate( map ) ); setChangeFiles( changeSet, map ); changes.add( changeSet ); } } return changes; } private void setChangeFiles( ChangeSet changeSet, Map<String, Object> context ) { List<Map<String, Object>> changeFiles = ContinuumBuildConstant.getChangeSetFiles( context ); if ( changeFiles != null ) { for ( Map<String, Object> map : changeFiles ) { ChangeFile changeFile = new ChangeFile(); changeFile.setName( ContinuumBuildConstant.getChangeFileName( map ) ); changeFile.setRevision( ContinuumBuildConstant.getChangeFileRevision( map ) ); changeFile.setStatus( ContinuumBuildConstant.getChangeFileStatus( map ) ); changeSet.addFile( changeFile ); } } } }
5,167
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/continuum/builder/distributed
Create_ds/continuum/continuum-core/src/main/java/org/apache/continuum/builder/distributed/manager/DefaultDistributedBuildManager.java
package org.apache.continuum.builder.distributed.manager; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.buildagent.NoBuildAgentException; import org.apache.continuum.buildagent.NoBuildAgentInGroupException; import org.apache.continuum.builder.distributed.executor.ThreadedDistributedBuildTaskQueueExecutor; import org.apache.continuum.builder.distributed.util.DistributedBuildUtil; import org.apache.continuum.builder.utils.ContinuumBuildConstant; import org.apache.continuum.configuration.BuildAgentConfiguration; import org.apache.continuum.configuration.BuildAgentGroupConfiguration; import org.apache.continuum.dao.BuildDefinitionDao; import org.apache.continuum.dao.BuildResultDao; import org.apache.continuum.dao.ProjectDao; import org.apache.continuum.dao.ProjectScmRootDao; import org.apache.continuum.distributed.transport.slave.SlaveBuildAgentTransportClient; import org.apache.continuum.distributed.transport.slave.SlaveBuildAgentTransportService; import org.apache.continuum.model.project.ProjectRunSummary; import org.apache.continuum.model.project.ProjectScmRoot; import org.apache.continuum.taskqueue.BuildProjectTask; import org.apache.continuum.taskqueue.OverallDistributedBuildQueue; import org.apache.continuum.taskqueue.PrepareBuildProjectsTask; import org.apache.continuum.utils.ContinuumUtils; import org.apache.continuum.utils.ProjectSorter; import org.apache.continuum.utils.build.BuildTrigger; import org.apache.maven.continuum.ContinuumException; import org.apache.maven.continuum.configuration.ConfigurationService; import org.apache.maven.continuum.model.project.BuildDefinition; import org.apache.maven.continuum.model.project.BuildResult; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.model.system.Installation; import org.apache.maven.continuum.model.system.Profile; import org.apache.maven.continuum.project.ContinuumProjectState; import org.apache.maven.continuum.store.ContinuumStoreException; import org.codehaus.plexus.PlexusConstants; import org.codehaus.plexus.PlexusContainer; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Configuration; import org.codehaus.plexus.component.annotations.Requirement; 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.Initializable; import org.codehaus.plexus.personality.plexus.lifecycle.phase.InitializationException; import org.codehaus.plexus.personality.plexus.lifecycle.phase.StoppingException; import org.codehaus.plexus.taskqueue.Task; import org.codehaus.plexus.taskqueue.TaskQueueException; import org.codehaus.plexus.util.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; @Component( role = org.apache.continuum.builder.distributed.manager.DistributedBuildManager.class ) public class DefaultDistributedBuildManager implements DistributedBuildManager, Contextualizable, Initializable { private static final Logger log = LoggerFactory.getLogger( DefaultDistributedBuildManager.class ); private Map<String, OverallDistributedBuildQueue> overallDistributedBuildQueues = Collections.synchronizedMap( new HashMap<String, OverallDistributedBuildQueue>() ); private List<ProjectRunSummary> currentRuns = Collections.synchronizedList( new ArrayList<ProjectRunSummary>() ); private Map<ProjectRunSummary, Long> canceledRuns = Collections.synchronizedMap( new HashMap<ProjectRunSummary, Long>() ); @Configuration( "300000" ) private Long cancellationTimeToLive; @Requirement private ConfigurationService configurationService; @Requirement private ProjectDao projectDao; @Requirement private BuildDefinitionDao buildDefinitionDao; @Requirement private BuildResultDao buildResultDao; @Requirement private ProjectScmRootDao projectScmRootDao; @Requirement private DistributedBuildUtil distributedBuildUtil; private PlexusContainer container; // -------------------------------- // Plexus Lifecycle // -------------------------------- public void contextualize( Context context ) throws ContextException { container = (PlexusContainer) context.get( PlexusConstants.PLEXUS_KEY ); } public void initialize() throws InitializationException { List<BuildAgentConfiguration> agents = configurationService.getBuildAgents(); if ( agents != null ) { synchronized ( overallDistributedBuildQueues ) { for ( BuildAgentConfiguration agent : agents ) { if ( agent.isEnabled() ) { try { SlaveBuildAgentTransportService client = createSlaveBuildAgentTransportClientConnection( agent.getUrl() ); if ( client.ping() ) { log.debug( "agent is enabled, create distributed build queue for build agent '{}'", agent.getUrl() ); createDistributedBuildQueueForAgent( agent.getUrl() ); } else { log.debug( "unable to ping build agent '{}'", agent.getUrl() ); } } catch ( MalformedURLException e ) { // do not throw exception, just log it log.error( "Invalid build agent URL {}, not creating distributed build queue", agent.getUrl() ); } catch ( ContinuumException e ) { throw new InitializationException( "Error while initializing distributed build queues", e ); } catch ( Exception e ) { agent.setEnabled( false ); log.debug( "unable to ping build agent '{}' : {}", agent.getUrl(), ContinuumUtils.throwableToString( e ) ); } } else { log.debug( "agent {} is disabled, not creating distributed build queue", agent.getUrl() ); } } } } } public void reload() throws ContinuumException { List<BuildAgentConfiguration> agents = configurationService.getBuildAgents(); if ( agents == null ) { return; } synchronized ( overallDistributedBuildQueues ) { for ( BuildAgentConfiguration agent : agents ) { if ( agent.isEnabled() && !overallDistributedBuildQueues.containsKey( agent.getUrl() ) ) { SlaveBuildAgentTransportService client = null; try { client = createSlaveBuildAgentTransportClientConnection( agent.getUrl() ); } catch ( MalformedURLException e ) { log.error( "Invalid build agent URL {}, not creating distributed build queue", agent.getUrl() ); throw new ContinuumException( "Malformed build agent url " + agent.getUrl() ); } catch ( Exception e ) { agent.setEnabled( false ); configurationService.updateBuildAgent( agent ); log.error( "Error binding build agent {} service : {} ", agent.getUrl(), ContinuumUtils.throwableToString( e ) ); throw new ContinuumException( e.getMessage() ); } boolean ping = false; try { ping = client.ping(); } catch ( Exception e ) { agent.setEnabled( false ); log.error( "Unable to ping build agent '{}': {}", agent.getUrl(), ContinuumUtils.throwableToString( e ) ); } if ( ping ) { try { createDistributedBuildQueueForAgent( agent.getUrl() ); log.debug( "Agent is enabled, create distributed build queue for build agent '{}'", agent.getUrl() ); } catch ( Exception e ) { agent.setEnabled( false ); log.error( "Unable to create distributed queue for build agent {} : {}", agent.getUrl(), ContinuumUtils.throwableToString( e ) ); } } else { agent.setEnabled( false ); log.error( "Unable to ping build agent '{}'", agent.getUrl() ); } configurationService.updateBuildAgent( agent ); } else if ( !agent.isEnabled() && overallDistributedBuildQueues.containsKey( agent.getUrl() ) ) { log.debug( "agent is disabled, remove distributed build queue for build agent '{}'", agent.getUrl() ); removeDistributedBuildQueueOfAgent( agent.getUrl() ); } } } } public void update( BuildAgentConfiguration agent ) throws ContinuumException { synchronized ( overallDistributedBuildQueues ) { if ( agent.isEnabled() && !overallDistributedBuildQueues.containsKey( agent.getUrl() ) ) { SlaveBuildAgentTransportService client; try { client = createSlaveBuildAgentTransportClientConnection( agent.getUrl() ); } catch ( MalformedURLException e ) { log.error( "Invalid build agent URL {}, not creating distributed build queue", agent.getUrl() ); throw new ContinuumException( "Malformed build agent url " + agent.getUrl() ); } catch ( Exception e ) { log.error( "Error binding build agent {} service : {} ", agent.getUrl(), ContinuumUtils.throwableToString( e ) ); throw new ContinuumException( e.getMessage() ); } boolean ping; try { ping = client.ping(); } catch ( Exception e ) { log.error( "Unable to ping build agent '{}': {}", agent.getUrl(), ContinuumUtils.throwableToString( e ) ); throw new ContinuumException( "Unable to ping build agent " + agent.getUrl() ); } if ( ping ) { try { createDistributedBuildQueueForAgent( agent.getUrl() ); log.debug( "Agent is enabled, create distributed build queue for build agent '{}'", agent.getUrl() ); } catch ( Exception e ) { log.error( "Unable to create distributed queue for build agent {} : {}", agent.getUrl(), ContinuumUtils.throwableToString( e ) ); } } else { log.error( "Unable to ping build agent '{}'", agent.getUrl() ); throw new ContinuumException( "Unable to ping build agent " + agent.getUrl() ); } } else if ( !agent.isEnabled() && overallDistributedBuildQueues.containsKey( agent.getUrl() ) ) { log.debug( "agent is disabled, remove distributed build queue for build agent '{}'", agent.getUrl() ); removeDistributedBuildQueueOfAgent( agent.getUrl() ); } } } @SuppressWarnings( "unused" ) public void prepareBuildProjects( Map<Integer, Integer> projectsBuildDefinitionsMap, BuildTrigger buildTrigger, int projectGroupId, String projectGroupName, String scmRootAddress, int scmRootId, List<ProjectScmRoot> scmRoots ) throws ContinuumException, NoBuildAgentException, NoBuildAgentInGroupException { PrepareBuildProjectsTask task = new PrepareBuildProjectsTask( projectsBuildDefinitionsMap, buildTrigger, projectGroupId, projectGroupName, scmRootAddress, scmRootId ); if ( buildTrigger.getTrigger() == ContinuumProjectState.TRIGGER_FORCED ) { log.debug( "Build project (projectGroupId={}) triggered manually by {}", projectGroupId, buildTrigger.getTriggeredBy() ); } else { log.debug( "Build project (projectGroupId={}) triggered by schedule {}", projectGroupId, buildTrigger.getTriggeredBy() ); } if ( log.isDebugEnabled() ) { Map<String, BuildProjectTask> buildTasks = getProjectsCurrentlyBuilding(); for ( String key : buildTasks.keySet() ) { log.debug( "Current build of agent {} :: Project {}", key, buildTasks.get( key ).getProjectName() ); } Map<String, List<BuildProjectTask>> buildQueues = getProjectsInBuildQueue(); for ( String key : buildQueues.keySet() ) { for ( BuildProjectTask buildTask : buildQueues.get( key ) ) { log.debug( "Build Queue of agent {} :: Project {}", key, buildTask.getProjectName() ); } } Map<String, PrepareBuildProjectsTask> prepareBuildTasks = getProjectsCurrentlyPreparingBuild(); for ( String key : prepareBuildTasks.keySet() ) { PrepareBuildProjectsTask prepareBuildTask = prepareBuildTasks.get( key ); log.debug( "Current prepare build of agent {} :: Project Group {} - Scm Root {}", new Object[] { key, prepareBuildTask.getProjectGroupName(), prepareBuildTask.getProjectScmRootId() } ); } Map<String, List<PrepareBuildProjectsTask>> prepareBuildQueues = getProjectsInPrepareBuildQueue(); for ( String key : prepareBuildQueues.keySet() ) { for ( PrepareBuildProjectsTask prepareBuildTask : prepareBuildQueues.get( key ) ) { log.debug( "Prepare Build Queue of agent {} : Project Group {} - Scm Root {}", new Object[] { key, prepareBuildTask.getProjectGroupName(), prepareBuildTask.getProjectScmRootId() } ); } } } log.debug( "Determining which build agent should build the project..." ); OverallDistributedBuildQueue overallDistributedBuildQueue = getOverallDistributedBuildQueueByGroup( projectGroupId, scmRoots, scmRootId ); if ( overallDistributedBuildQueue == null ) { log.debug( "No projects with the same continuum group is currently building, checking if build definition has an attached build agent group" ); if ( hasBuildagentGroup( projectsBuildDefinitionsMap ) ) { log.debug( "Build definition used has an attached build agent group, checking if there are configured build agents in the group" ); if ( !hasBuildagentInGroup( projectsBuildDefinitionsMap ) ) { log.warn( "No build agent configured in build agent group. Not building projects." ); throw new NoBuildAgentInGroupException( "No build agent configured in build agent group" ); } else { // get overall distributed build queue from build agent group log.info( "Getting the least busy build agent within the build agent group" ); overallDistributedBuildQueue = getOverallDistributedBuildQueueByAgentGroup( projectsBuildDefinitionsMap ); } } else { // project does not have build agent group log.info( "Project does not have a build agent group, getting the least busy of all build agents" ); overallDistributedBuildQueue = getOverallDistributedBuildQueue(); } } if ( overallDistributedBuildQueue != null ) { try { String agentUrl = overallDistributedBuildQueue.getBuildAgentUrl(); log.info( "Building project in the least busy agent {}", agentUrl ); overallDistributedBuildQueue.addToDistributedBuildQueue( task ); createProjectRunSummaries( task, agentUrl ); } catch ( TaskQueueException e ) { log.error( "Error while enqueuing prepare build task", e ); throw new ContinuumException( "Error occurred while enqueuing prepare build task", e ); } } else { log.warn( "Unable to determine which build agent should build the project. No build agent configured. Not building projects." ); throw new NoBuildAgentException( "No build agent configured" ); } // call in case we disabled a build agent reload(); } public void removeDistributedBuildQueueOfAgent( String buildAgentUrl ) throws ContinuumException { if ( overallDistributedBuildQueues.containsKey( buildAgentUrl ) ) { List<PrepareBuildProjectsTask> tasks = null; synchronized ( overallDistributedBuildQueues ) { OverallDistributedBuildQueue overallDistributedBuildQueue = overallDistributedBuildQueues.get( buildAgentUrl ); try { if ( overallDistributedBuildQueue.getDistributedBuildTaskQueueExecutor().getCurrentTask() != null ) { log.error( "Unable to remove build agent because it is currently being used" ); throw new ContinuumException( "Unable to remove build agent because it is currently being used" ); } tasks = overallDistributedBuildQueue.getProjectsInQueue(); overallDistributedBuildQueue.getDistributedBuildQueue().removeAll( tasks ); ( (ThreadedDistributedBuildTaskQueueExecutor) overallDistributedBuildQueue.getDistributedBuildTaskQueueExecutor() ).stop(); container.release( overallDistributedBuildQueue ); overallDistributedBuildQueues.remove( buildAgentUrl ); log.debug( "remove distributed build queue for build agent '{}'", buildAgentUrl ); } catch ( TaskQueueException e ) { log.error( "Error occurred while removing build agent {}", buildAgentUrl, e ); throw new ContinuumException( "Error occurred while removing build agent " + buildAgentUrl, e ); } catch ( ComponentLifecycleException e ) { log.error( "Error occurred while removing build agent {}", buildAgentUrl, e ); throw new ContinuumException( "Error occurred while removing build agent " + buildAgentUrl, e ); } catch ( StoppingException e ) { log.error( "Error occurred while removing build agent {}", buildAgentUrl, e ); throw new ContinuumException( "Error occurred while removing build agent " + buildAgentUrl, e ); } } } } public Map<String, List<PrepareBuildProjectsTask>> getProjectsInPrepareBuildQueue() throws ContinuumException { Map<String, List<PrepareBuildProjectsTask>> map = new HashMap<String, List<PrepareBuildProjectsTask>>(); synchronized ( overallDistributedBuildQueues ) { for ( String buildAgentUrl : overallDistributedBuildQueues.keySet() ) { List<PrepareBuildProjectsTask> tasks = new ArrayList<PrepareBuildProjectsTask>(); try { if ( isAgentAvailable( buildAgentUrl ) ) { log.debug( "Getting projects in prepare build queue of build agent {}", buildAgentUrl ); SlaveBuildAgentTransportService client = createSlaveBuildAgentTransportClientConnection( buildAgentUrl ); List<Map<String, Object>> projects = client.getProjectsInPrepareBuildQueue(); for ( Map<String, Object> context : projects ) { tasks.add( getPrepareBuildProjectsTask( context ) ); } map.put( buildAgentUrl, tasks ); } else { log.debug( "Unable to get projects in prepare build queue. Build agent {} not available", buildAgentUrl ); } } catch ( MalformedURLException e ) { throw new ContinuumException( "Invalid build agent url: " + buildAgentUrl ); } catch ( Exception e ) { throw new ContinuumException( "Error while retrieving projects in prepare build queue", e ); } } } // call reload in case we disable a build agent reload(); return map; } public Map<String, PrepareBuildProjectsTask> getProjectsCurrentlyPreparingBuild() throws ContinuumException { Map<String, PrepareBuildProjectsTask> map = new HashMap<String, PrepareBuildProjectsTask>(); synchronized ( overallDistributedBuildQueues ) { for ( String buildAgentUrl : overallDistributedBuildQueues.keySet() ) { try { if ( isAgentAvailable( buildAgentUrl ) ) { log.debug( "Getting project currently preparing build in build agent {}", buildAgentUrl ); SlaveBuildAgentTransportService client = createSlaveBuildAgentTransportClientConnection( buildAgentUrl ); Map<String, Object> project = client.getProjectCurrentlyPreparingBuild(); if ( !project.isEmpty() ) { map.put( buildAgentUrl, getPrepareBuildProjectsTask( project ) ); } } else { log.debug( "Unable to get projects currently preparing build. Build agent {} is not available", buildAgentUrl ); } } catch ( MalformedURLException e ) { throw new ContinuumException( "Invalid build agent url: " + buildAgentUrl ); } catch ( Exception e ) { throw new ContinuumException( "Error retrieving projects currently preparing build in " + buildAgentUrl, e ); } } } // call reload in case we disable a build agent reload(); return map; } public Map<String, BuildProjectTask> getProjectsCurrentlyBuilding() throws ContinuumException { Map<String, BuildProjectTask> map = new HashMap<String, BuildProjectTask>(); synchronized ( overallDistributedBuildQueues ) { for ( String buildAgentUrl : overallDistributedBuildQueues.keySet() ) { try { if ( isAgentAvailable( buildAgentUrl ) ) { log.debug( "Getting projects currently building in build agent {}", buildAgentUrl ); SlaveBuildAgentTransportService client = createSlaveBuildAgentTransportClientConnection( buildAgentUrl ); Map<String, Object> project = client.getProjectCurrentlyBuilding(); if ( !project.isEmpty() ) { map.put( buildAgentUrl, getBuildProjectTask( project ) ); } } else { log.debug( "Unable to get projects currently building. Build agent {} is not available", buildAgentUrl ); } } catch ( MalformedURLException e ) { throw new ContinuumException( "Invalid build agent url: " + buildAgentUrl ); } catch ( Exception e ) { throw new ContinuumException( "Error retrieving projects currently building in " + buildAgentUrl, e ); } } } // call reload in case we disable a build agent reload(); return map; } public Map<String, List<BuildProjectTask>> getProjectsInBuildQueue() throws ContinuumException { Map<String, List<BuildProjectTask>> map = new HashMap<String, List<BuildProjectTask>>(); synchronized ( overallDistributedBuildQueues ) { for ( String buildAgentUrl : overallDistributedBuildQueues.keySet() ) { List<BuildProjectTask> tasks = new ArrayList<BuildProjectTask>(); try { if ( isAgentAvailable( buildAgentUrl ) ) { log.debug( "Getting projects in build queue in build agent {}", buildAgentUrl ); SlaveBuildAgentTransportService client = createSlaveBuildAgentTransportClientConnection( buildAgentUrl ); List<Map<String, Object>> projects = client.getProjectsInBuildQueue(); for ( Map<String, Object> context : projects ) { tasks.add( getBuildProjectTask( context ) ); } map.put( buildAgentUrl, tasks ); } else { log.debug( "Unable to get projects in build queue. Build agent {} is not available", buildAgentUrl ); } } catch ( MalformedURLException e ) { throw new ContinuumException( "Invalid build agent url: " + buildAgentUrl ); } catch ( Exception e ) { throw new ContinuumException( "Error while retrieving projects in build queue", e ); } } } // call reload in case we disable a build agent reload(); return map; } public boolean isBuildAgentBusy( String buildAgentUrl ) { synchronized ( overallDistributedBuildQueues ) { OverallDistributedBuildQueue overallDistributedBuildQueue = overallDistributedBuildQueues.get( buildAgentUrl ); if ( overallDistributedBuildQueue != null && overallDistributedBuildQueue.getDistributedBuildTaskQueueExecutor().getCurrentTask() != null ) { log.debug( "build agent '" + buildAgentUrl + "' is busy" ); return true; } log.debug( "build agent '" + buildAgentUrl + "' is not busy" ); return false; } } public void cancelDistributedBuild( String buildAgentUrl ) throws ContinuumException { try { if ( isAgentAvailable( buildAgentUrl ) ) { log.debug( "Cancelling build in build agent {}", buildAgentUrl ); SlaveBuildAgentTransportService client = createSlaveBuildAgentTransportClientConnection( buildAgentUrl ); client.cancelBuild(); } else { log.debug( "Unable to cancel build, build agent {} is not available", buildAgentUrl ); } // call reload in case we disable the build agent reload(); } catch ( MalformedURLException e ) { log.error( "Error cancelling build in build agent: Invalid build agent url " + buildAgentUrl ); throw new ContinuumException( "Error cancelling build in build agent: Invalid build agent url " + buildAgentUrl ); } catch ( Exception e ) { log.error( "Error occurred while cancelling build in build agent " + buildAgentUrl, e ); throw new ContinuumException( "Error occurred while cancelling build in build agent " + buildAgentUrl, e ); } } public void cancelGroupBuild( int projectGroupId ) throws ContinuumException { log.debug( "Cancelling all builds of project group {}", projectGroupId ); List<ProjectRunSummary> runsToDelete = new ArrayList<ProjectRunSummary>(); synchronized ( currentRuns ) { for ( ProjectRunSummary run : currentRuns ) { if ( run.getProjectGroupId() == projectGroupId ) { cancelCurrentRun( run, runsToDelete ); } } cleanupCanceledRuns( runsToDelete ); } } public void cancelBuild( int projectId ) throws ContinuumException { log.debug( "Cancelling all builds of project {}", projectId ); List<ProjectRunSummary> runsToDelete = new ArrayList<ProjectRunSummary>(); synchronized ( currentRuns ) { for ( ProjectRunSummary run : currentRuns ) { if ( run.getProjectId() == projectId ) { cancelCurrentRun( run, runsToDelete ); } } cleanupCanceledRuns( runsToDelete ); } } /** * Removes canceled runs from the list of currently running and retires old cancelation records. * * @param runsToDelete */ private void cleanupCanceledRuns( List<ProjectRunSummary> runsToDelete ) { // Remove the canceled builds if ( runsToDelete.size() > 0 ) { currentRuns.removeAll( runsToDelete ); } // Remove stale cancellation records synchronized ( canceledRuns ) { long now = System.currentTimeMillis(); Iterator<Map.Entry<ProjectRunSummary, Long>> iter = canceledRuns.entrySet().iterator(); while ( iter.hasNext() ) { Map.Entry<ProjectRunSummary, Long> entry = iter.next(); long cancelTime = entry.getValue(); if ( now - cancelTime > cancellationTimeToLive ) { iter.remove(); } } } } private void cancelCurrentRun( ProjectRunSummary run, List<ProjectRunSummary> runsToDelete ) throws ContinuumException { int projectId = run.getProjectId(); int buildDefinitionId = run.getBuildDefinitionId(); String buildAgentUrl = run.getBuildAgentUrl(); // try to remove from any queue first removeFromPrepareBuildQueue( buildAgentUrl, run.getProjectGroupId(), run.getProjectScmRootId() ); removeFromBuildQueue( buildAgentUrl, projectId, buildDefinitionId ); if ( isProjectCurrentlyPreparingBuild( projectId, buildDefinitionId ) ) { log.debug( "Unable to cancel build of projectId={}, buildDefinitionId={} in build agent{}. Project is currently doing scm update." ); return; } else if ( isProjectCurrentlyBuilding( projectId, buildDefinitionId ) ) { log.debug( "Cancel build of projectId={}, buildDefinitionId={} in build agent {}", new Object[] { projectId, buildDefinitionId, buildAgentUrl } ); canceledRuns.put( run, System.currentTimeMillis() ); cancelDistributedBuild( buildAgentUrl ); runsToDelete.add( run ); } else { try { ProjectScmRoot scmRoot = projectScmRootDao.getProjectScmRoot( run.getProjectScmRootId() ); if ( scmRoot != null && scmRoot.getState() == ContinuumProjectState.UPDATING ) { // no longer updating, but state was not updated. scmRoot.setState( ContinuumProjectState.ERROR ); scmRoot.setError( "Problem encountered while returning scm update result to master by build agent '" + buildAgentUrl + "'. \n" + "Make sure build agent is configured properly. Check the logs for more information." ); projectScmRootDao.updateProjectScmRoot( scmRoot ); log.debug( "projectId={}, buildDefinitionId={} is not updating anymore. Problem encountered while return scm update result by build agent {}. Stopping the build.", new Object[] { projectId, buildDefinitionId, buildAgentUrl } ); runsToDelete.add( run ); } else if ( scmRoot != null && scmRoot.getState() == ContinuumProjectState.ERROR ) { log.debug( "projectId={}, buildDefinitionId={} is not updating anymore. Problem encountered while return scm update result by build agent {}. Stopping the build.", new Object[] { projectId, buildDefinitionId, buildAgentUrl } ); runsToDelete.add( run ); } else { // no longer building, but state was not updated Project project = projectDao.getProject( projectId ); BuildDefinition buildDefinition = buildDefinitionDao.getBuildDefinition( buildDefinitionId ); BuildResult buildResult; boolean existingResult = run.getBuildResultId() > 0; if ( existingResult ) { buildResult = buildResultDao.getBuildResult( run.getBuildResultId() ); } else { buildResult = new BuildResult(); } buildResult.setBuildDefinition( buildDefinition ); buildResult.setBuildUrl( run.getBuildAgentUrl() ); buildResult.setTrigger( run.getTrigger() ); buildResult.setUsername( run.getTriggeredBy() ); buildResult.setState( ContinuumProjectState.ERROR ); buildResult.setSuccess( false ); buildResult.setStartTime( new Date().getTime() ); buildResult.setEndTime( new Date().getTime() ); buildResult.setExitCode( 1 ); buildResult.setError( "Problem encountered while returning build result to master by build agent '" + buildAgentUrl + "'. \n" + "Make sure build agent is configured properly. Check the logs for more information." ); if ( existingResult ) { buildResultDao.updateBuildResult( buildResult ); } else { buildResultDao.addBuildResult( project, buildResult ); } project.setState( ContinuumProjectState.ERROR ); project.setLatestBuildId( buildResult.getId() ); projectDao.updateProject( project ); log.debug( "projectId={}, buildDefinitionId={} is not building anymore. Problem encountered while return build result by build agent {}. Stopping the build.", new Object[] { projectId, buildDefinitionId, buildAgentUrl } ); // create a build result runsToDelete.add( run ); } } catch ( Exception e ) { log.error( "Unable to end build for projectId={}, buildDefinitionId={} : {}", new Object[] { projectId, buildDefinitionId, e.getMessage() } ); } } } public Map<String, Object> getBuildResult( int projectId ) throws ContinuumException { Map<String, Object> map = new HashMap<String, Object>(); String buildAgentUrl = getBuildAgent( projectId ); if ( buildAgentUrl == null ) { log.debug( "Unable to determine the build agent where project is building" ); return null; } try { if ( isAgentAvailable( buildAgentUrl ) ) { log.debug( "Getting build result of project in build agent {}", buildAgentUrl ); SlaveBuildAgentTransportService client = createSlaveBuildAgentTransportClientConnection( buildAgentUrl ); Map<String, Object> result = client.getBuildResult( projectId ); if ( result != null ) { int buildDefinitionId = ContinuumBuildConstant.getBuildDefinitionId( result ); BuildDefinition buildDefinition = buildDefinitionDao.getBuildDefinition( buildDefinitionId ); BuildResult latestResult = buildResultDao.getLatestBuildResultForBuildDefinition( projectId, buildDefinitionId ); BuildResult buildResult = distributedBuildUtil.convertMapToBuildResult( result ); buildResult.setBuildDefinition( buildDefinition ); buildResult.setBuildNumber( latestResult.getBuildNumber() ); buildResult.setModifiedDependencies( distributedBuildUtil.getModifiedDependencies( latestResult, result ) ); buildResult.setScmResult( distributedBuildUtil.getScmResult( result ) ); String buildOutput = ContinuumBuildConstant.getBuildOutput( result ); map.put( ContinuumBuildConstant.KEY_BUILD_RESULT, buildResult ); map.put( ContinuumBuildConstant.KEY_BUILD_OUTPUT, buildOutput ); } else { log.debug( "No build result returned by build agent {}", buildAgentUrl ); } } else { log.debug( "Unable to get build result of project. Build agent {} is not available", buildAgentUrl ); } } catch ( MalformedURLException e ) { throw new ContinuumException( "Invalid build agent URL '" + buildAgentUrl + "'" ); } catch ( Exception e ) { throw new ContinuumException( "Error while retrieving build result for project" + projectId, e ); } // call reload in case we disable the build agent reload(); return map; } public String getBuildAgentPlatform( String buildAgentUrl ) throws ContinuumException { try { String platform = ""; if ( isAgentAvailable( buildAgentUrl ) ) { log.debug( "Getting build agent {} platform", buildAgentUrl ); SlaveBuildAgentTransportService client = createSlaveBuildAgentTransportClientConnection( buildAgentUrl ); platform = client.getBuildAgentPlatform(); } else { log.debug( "Unable to get build agent platform. Build agent {} is not available", buildAgentUrl ); } // call reload in case we disable the build agent reload(); return platform; } catch ( Exception e ) { throw new ContinuumException( "Unable to get platform of build agent", e ); } } public List<Installation> getAvailableInstallations( String buildAgentUrl ) throws ContinuumException { List<Installation> installations = new ArrayList<Installation>(); try { if ( isAgentAvailable( buildAgentUrl ) ) { log.debug( "Getting available installations in build agent {}", buildAgentUrl ); SlaveBuildAgentTransportService client = createSlaveBuildAgentTransportClientConnection( buildAgentUrl ); List<Map<String, String>> installationsList = client.getAvailableInstallations(); for ( Map context : installationsList ) { Installation installation = new Installation(); installation.setName( ContinuumBuildConstant.getInstallationName( context ) ); installation.setType( ContinuumBuildConstant.getInstallationType( context ) ); installation.setVarName( ContinuumBuildConstant.getInstallationVarName( context ) ); installation.setVarValue( ContinuumBuildConstant.getInstallationVarValue( context ) ); installations.add( installation ); } } else { log.debug( "Unable to get available installations. Build agent {} is not available", buildAgentUrl ); } // call reload in case we disable the build agent reload(); return installations; } catch ( Exception e ) { throw new ContinuumException( "Unable to get available installations of build agent", e ); } } public String generateWorkingCopyContent( int projectId, String directory, String baseUrl, String imageBaseUrl ) throws ContinuumException { BuildResult buildResult = buildResultDao.getLatestBuildResultForProject( projectId ); if ( buildResult != null ) { String buildAgentUrl = buildResult.getBuildUrl(); if ( buildAgentUrl == null ) { log.debug( "Unable to determine the build agent where project last built" ); return ""; } try { if ( directory == null ) { directory = ""; } if ( isAgentAvailable( buildAgentUrl ) ) { log.debug( "Generating working copy content of project in build agent {}", buildAgentUrl ); SlaveBuildAgentTransportService client = createSlaveBuildAgentTransportClientConnection( buildAgentUrl ); return client.generateWorkingCopyContent( projectId, directory, baseUrl, imageBaseUrl ); } else { log.debug( "Unable to generate working copy content of project. Build agent {} is not available", buildAgentUrl ); } } catch ( MalformedURLException e ) { log.error( "Invalid build agent url " + buildAgentUrl ); } catch ( Exception e ) { log.error( "Error while generating working copy content from build agent " + buildAgentUrl, e ); } } else { log.debug( "Unable to generate working copy content. Project hasn't been built yet." ); } // call reload in case we disable the build agent reload(); return ""; } public Map<String, Object> getFileContent( int projectId, String directory, String filename ) throws ContinuumException { BuildResult buildResult = buildResultDao.getLatestBuildResultForProject( projectId ); if ( buildResult != null ) { String buildAgentUrl = buildResult.getBuildUrl(); if ( buildAgentUrl == null ) { log.debug( "Unable to determine build agent where project last built" ); return null; } try { if ( isAgentAvailable( buildAgentUrl ) ) { SlaveBuildAgentTransportService client = createSlaveBuildAgentTransportClientConnection( buildAgentUrl ); return client.getProjectFile( projectId, directory, filename ); } } catch ( MalformedURLException e ) { log.error( "Invalid build agent url " + buildAgentUrl ); } catch ( Exception e ) { log.error( "Error while retrieving content of " + filename, e ); } } else { log.debug( "Unable to get file content because project hasn't been built yet" ); } // call reload in case we disable the build agent reload(); return null; } public void removeFromPrepareBuildQueue( String buildAgentUrl, int projectGroupId, int scmRootId ) throws ContinuumException { try { if ( isAgentAvailable( buildAgentUrl ) ) { log.info( "Removing projectGroupId {} from prepare build queue of build agent {}", projectGroupId, buildAgentUrl ); SlaveBuildAgentTransportService client = createSlaveBuildAgentTransportClientConnection( buildAgentUrl ); client.removeFromPrepareBuildQueue( projectGroupId, scmRootId ); } else { log.debug( "Unable to remove projectGroupId {} from prepare build queue. Build agent {} is not available", projectGroupId, buildAgentUrl ); } } catch ( MalformedURLException e ) { log.error( "Unable to remove projectGroupId=" + projectGroupId + " scmRootId=" + scmRootId + " from prepare build queue: Invalid build agent url " + buildAgentUrl ); throw new ContinuumException( "Unable to remove projectGroupId=" + projectGroupId + " scmRootId=" + scmRootId + " from prepare build queue: Invalid build agent url " + buildAgentUrl ); } catch ( Exception e ) { log.error( "Error occurred while removing projectGroupId=" + projectGroupId + " scmRootId=" + scmRootId + " from prepare build queue of agent " + buildAgentUrl, e ); throw new ContinuumException( "Error occurred while removing projectGroupId=" + projectGroupId + " scmRootId=" + scmRootId + " from prepare build queue of agent " + buildAgentUrl, e ); } // call reload in case we disable the build agent reload(); } public void removeFromBuildQueue( String buildAgentUrl, int projectId, int buildDefinitionId ) throws ContinuumException { try { if ( isAgentAvailable( buildAgentUrl ) ) { log.info( "Removing projectId {} from build queue of build agent {}", projectId, buildAgentUrl ); SlaveBuildAgentTransportService client = createSlaveBuildAgentTransportClientConnection( buildAgentUrl ); client.removeFromBuildQueue( projectId, buildDefinitionId ); } else { log.debug( "Unable to remove projectId {} from build queue. Build agent {} is not available", projectId, buildAgentUrl ); } } catch ( MalformedURLException e ) { log.error( "Unable to remove project " + projectId + " from build queue: Invalid build agent url " + buildAgentUrl ); throw new ContinuumException( "Unable to remove project " + projectId + " from build queue: Invalid build agent url " + buildAgentUrl ); } catch ( Exception e ) { log.error( "Error occurred while removing project " + projectId + " from build queue of agent " + buildAgentUrl, e ); throw new ContinuumException( "Error occurred while removing project " + projectId + " from build queue of agent " + buildAgentUrl, e ); } // call reload in case we disable the build agent reload(); } public void removeFromPrepareBuildQueue( List<String> hashCodes ) throws ContinuumException { synchronized ( overallDistributedBuildQueues ) { for ( String buildAgentUrl : overallDistributedBuildQueues.keySet() ) { try { if ( isAgentAvailable( buildAgentUrl ) ) { log.info( "Removing project groups from prepare build queue of build agent {}", buildAgentUrl ); SlaveBuildAgentTransportService client = createSlaveBuildAgentTransportClientConnection( buildAgentUrl ); client.removeFromPrepareBuildQueue( hashCodes ); } else { log.debug( "Unable to remove project groups from prepare build queue. Build agent {} is not available", buildAgentUrl ); } } catch ( MalformedURLException e ) { log.error( "Error trying to remove projects from prepare build queue. Invalid build agent url: " + buildAgentUrl ); } catch ( Exception e ) { log.error( "Error trying to remove projects from prepare build queue of agent " + buildAgentUrl, e ); } } } // call reload in case we disable a build agent reload(); } public void removeFromBuildQueue( List<String> hashCodes ) throws ContinuumException { synchronized ( overallDistributedBuildQueues ) { for ( String buildAgentUrl : overallDistributedBuildQueues.keySet() ) { try { if ( isAgentAvailable( buildAgentUrl ) ) { log.info( "Removing projects from build queue of build agent {}", buildAgentUrl ); SlaveBuildAgentTransportService client = createSlaveBuildAgentTransportClientConnection( buildAgentUrl ); client.removeFromBuildQueue( hashCodes ); } else { log.debug( "Unable to remove projects from build queue. Build agent {} is not available", buildAgentUrl ); } } catch ( MalformedURLException e ) { log.error( "Error trying to remove projects from build queue. Invalid build agent url: " + buildAgentUrl ); } catch ( Exception e ) { log.error( "Error trying to remove projects from build queue of agent " + buildAgentUrl, e ); } } } // call reload in case we disable a build agent reload(); } public boolean isProjectInAnyPrepareBuildQueue( int projectId, int buildDefinitionId ) throws ContinuumException { boolean found = false; synchronized ( overallDistributedBuildQueues ) { for ( String buildAgentUrl : overallDistributedBuildQueues.keySet() ) { try { if ( isAgentAvailable( buildAgentUrl ) ) { log.debug( "Checking if project {} is in prepare build queue of build agent {}", projectId, buildAgentUrl ); SlaveBuildAgentTransportService client = createSlaveBuildAgentTransportClientConnection( buildAgentUrl ); List<Map<String, Object>> projects = client.getProjectsAndBuildDefinitionsInPrepareBuildQueue(); for ( Map<String, Object> context : projects ) { int pid = ContinuumBuildConstant.getProjectId( context ); int buildId = ContinuumBuildConstant.getBuildDefinitionId( context ); if ( pid == projectId && ( buildId == buildDefinitionId || buildDefinitionId == -1 ) ) { found = true; break; } } } else { log.debug( "Unable to check if project {} is in prepare build queue. Build agent {} is not available", projectId, buildAgentUrl ); } if ( found ) { break; } } catch ( MalformedURLException e ) { throw new ContinuumException( "Invalid build agent url: " + buildAgentUrl ); } catch ( Exception e ) { throw new ContinuumException( "Error while retrieving projects in prepare build queue", e ); } } } // call reload in case we disable a build agent reload(); if ( found ) { return true; } else { return false; } } public boolean isProjectInAnyBuildQueue( int projectId, int buildDefinitionId ) throws ContinuumException { Map<String, List<BuildProjectTask>> map = getProjectsInBuildQueue(); for ( String url : map.keySet() ) { for ( BuildProjectTask task : map.get( url ) ) { if ( task.getProjectId() == projectId && ( buildDefinitionId == -1 || task.getBuildDefinitionId() == buildDefinitionId ) ) { return true; } } } return false; } public boolean isProjectCurrentlyPreparingBuild( int projectId, int buildDefinitionId ) throws ContinuumException { boolean found = false; synchronized ( overallDistributedBuildQueues ) { for ( String buildAgentUrl : overallDistributedBuildQueues.keySet() ) { try { if ( isAgentAvailable( buildAgentUrl ) ) { log.debug( "Checking if project {} is currently preparing build in build agent {}", projectId, buildAgentUrl ); SlaveBuildAgentTransportService client = createSlaveBuildAgentTransportClientConnection( buildAgentUrl ); List<Map<String, Object>> projects = client.getProjectsAndBuildDefinitionsCurrentlyPreparingBuild(); for ( Map<String, Object> context : projects ) { int pid = ContinuumBuildConstant.getProjectId( context ); int buildId = ContinuumBuildConstant.getBuildDefinitionId( context ); if ( pid == projectId && ( buildDefinitionId == -1 || buildId == buildDefinitionId ) ) { found = true; break; } } } else { log.debug( "Unable to check if project {} is currently preparing build. Build agent {} is not available", projectId, buildAgentUrl ); } if ( found ) { break; } } catch ( MalformedURLException e ) { throw new ContinuumException( "Invalid build agent url: " + buildAgentUrl ); } catch ( Exception e ) { throw new ContinuumException( "Error retrieving projects currently preparing build in " + buildAgentUrl, e ); } } } // call reload in case we disable a build agent reload(); if ( found ) { return true; } else { return false; } } public boolean isProjectCurrentlyBuilding( int projectId, int buildDefinitionId ) throws ContinuumException { Map<String, BuildProjectTask> map = getProjectsCurrentlyBuilding(); for ( String url : map.keySet() ) { BuildProjectTask task = map.get( url ); if ( task.getProjectId() == projectId && ( buildDefinitionId == -1 || task.getBuildDefinitionId() == buildDefinitionId ) ) { return true; } } return false; } private String getBuildAgent( int projectId ) throws ContinuumException { String agentUrl = null; synchronized ( overallDistributedBuildQueues ) { for ( String buildAgentUrl : overallDistributedBuildQueues.keySet() ) { OverallDistributedBuildQueue overallDistributedBuildQueue = overallDistributedBuildQueues.get( buildAgentUrl ); if ( overallDistributedBuildQueue != null ) { try { if ( isAgentAvailable( buildAgentUrl ) ) { SlaveBuildAgentTransportService client = createSlaveBuildAgentTransportClientConnection( buildAgentUrl ); // TODO: should check for specific build definition and handle that in UI; // project with different build definitions can build at the same time in different agents and // currently, we can't handle that in the ui. if ( client.isProjectCurrentlyBuilding( projectId, -1 ) ) { agentUrl = buildAgentUrl; break; } } else { log.debug( "Unable to check if project {} is currently building. Build agent {} is not available", projectId, buildAgentUrl ); } } catch ( MalformedURLException e ) { log.warn( "Unable to check if project {} is currently building in agent: Invalid build agent url {}", projectId, buildAgentUrl ); } catch ( Exception e ) { log.warn( "Unable to check if project {} is currently building in agent", projectId, e ); } } } } // call reload in case we disable a build agent reload(); return agentUrl; } public String getBuildAgentUrl( int projectId, int buildDefinitionId ) throws ContinuumException { String agentUrl = null; synchronized ( overallDistributedBuildQueues ) { for ( String buildAgentUrl : overallDistributedBuildQueues.keySet() ) { OverallDistributedBuildQueue overallDistributedBuildQueue = overallDistributedBuildQueues.get( buildAgentUrl ); if ( overallDistributedBuildQueue != null ) { try { if ( isAgentAvailable( buildAgentUrl ) ) { log.debug( "Checking if project {} with build definition {} is currently queued or processed in agent {}", new Object[] { projectId, buildDefinitionId, buildAgentUrl } ); SlaveBuildAgentTransportService client = createSlaveBuildAgentTransportClientConnection( buildAgentUrl ); if ( client.isProjectInPrepareBuildQueue( projectId, buildDefinitionId ) || client.isProjectCurrentlyPreparingBuild( projectId, buildDefinitionId ) || client.isProjectInBuildQueue( projectId, buildDefinitionId ) || client.isProjectCurrentlyBuilding( projectId, buildDefinitionId ) ) { log.debug( "Project {} with build definition {} is currently queued or processed in agent {}", new Object[] { projectId, buildDefinitionId, buildAgentUrl } ); agentUrl = buildAgentUrl; break; } } else { log.debug( "Unable to check if project {} is currently queued or processed in agent. Build agent {} is not available", projectId, buildAgentUrl ); } } catch ( MalformedURLException e ) { log.warn( "Unable to check if project {} is currently queued or processed in agent: Invalid build agent url {}", projectId, buildAgentUrl ); } catch ( Exception e ) { log.warn( "Unable to check if project {} is currently queued or processed in agent", projectId, e ); } } } } // call reload in case we disable a build agent reload(); return agentUrl; } private void createDistributedBuildQueueForAgent( String buildAgentUrl ) throws ComponentLookupException { if ( !overallDistributedBuildQueues.containsKey( buildAgentUrl ) ) { OverallDistributedBuildQueue overallDistributedBuildQueue = (OverallDistributedBuildQueue) container.lookup( OverallDistributedBuildQueue.class ); overallDistributedBuildQueue.setBuildAgentUrl( buildAgentUrl ); overallDistributedBuildQueue.getDistributedBuildTaskQueueExecutor().setBuildAgentUrl( buildAgentUrl ); overallDistributedBuildQueues.put( buildAgentUrl, overallDistributedBuildQueue ); } } private OverallDistributedBuildQueue getOverallDistributedBuildQueueByScmRoot( ProjectScmRoot scmRoot, int projectGroupId ) throws ContinuumException { int scmRootId = scmRoot.getId(); synchronized ( overallDistributedBuildQueues ) { for ( String buildAgentUrl : overallDistributedBuildQueues.keySet() ) { OverallDistributedBuildQueue distributedBuildQueue = overallDistributedBuildQueues.get( buildAgentUrl ); try { for ( PrepareBuildProjectsTask task : distributedBuildQueue.getProjectsInQueue() ) { if ( task.getProjectScmRootId() == scmRootId ) { log.debug( "Projects in the same continuum group are building in build agent: {}. Also building project in the same agent.", buildAgentUrl ); return distributedBuildQueue; } } Task task = distributedBuildQueue.getDistributedBuildTaskQueueExecutor().getCurrentTask(); if ( task != null && ( (PrepareBuildProjectsTask) task ).getProjectScmRootId() == scmRootId ) { log.debug( "Projects in the same continuum group are building in build agent: {}. Also building project in the same agent.", buildAgentUrl ); return distributedBuildQueue; } if ( isAgentAvailable( buildAgentUrl ) ) { List<Project> projects = projectDao.getProjectsInGroup( projectGroupId ); List<Integer> pIds = new ArrayList<Integer>(); for ( Project project : projects ) { if ( project.getScmUrl().startsWith( scmRoot.getScmRootAddress() ) ) { pIds.add( project.getId() ); } } SlaveBuildAgentTransportService client = createSlaveBuildAgentTransportClientConnection( buildAgentUrl ); if ( client.isProjectScmRootInQueue( scmRootId, pIds ) ) { log.debug( "Projects in the same continuum group are building in build agent: {}. Also building project in the same agent.", buildAgentUrl ); return distributedBuildQueue; } } else { log.debug( "Build agent {} is not available. Skipping...", buildAgentUrl ); } } catch ( TaskQueueException e ) { log.error( "Error occurred while retrieving distributed build queue of scmRootId=" + scmRootId, e ); throw new ContinuumException( "Error occurred while retrieving distributed build queue of scmRoot", e ); } catch ( MalformedURLException e ) { log.error( "Error occurred while retrieving distributed build queue of scmRootId=" + scmRootId + ": Invalid build agent url " + buildAgentUrl ); throw new ContinuumException( "Error occurred while retrieving distributed build queue of scmRootId=" + scmRootId + ": Invalid build agent url " + buildAgentUrl ); } catch ( Exception e ) { log.error( "Error occurred while retrieving distributed build queue of scmRootId=" + scmRootId, e ); throw new ContinuumException( "Error occurred while retrieving distributed build queue of scmRoot", e ); } } } return null; } private OverallDistributedBuildQueue getOverallDistributedBuildQueueByGroup( int projectGroupId, List<ProjectScmRoot> scmRoots, int scmRootId ) throws ContinuumException { if ( scmRoots != null ) { log.debug( "Checking if the project group is already building in one of the build agents" ); for ( ProjectScmRoot scmRoot : scmRoots ) { if ( scmRoot.getId() == scmRootId ) { break; } else if ( scmRoot.getProjectGroup().getId() == projectGroupId ) { return getOverallDistributedBuildQueueByScmRoot( scmRoot, projectGroupId ); } } } return null; } private OverallDistributedBuildQueue getOverallDistributedBuildQueueByAgentGroup( Map<Integer, Integer> projectsAndBuildDefinitionsMap ) throws ContinuumException { OverallDistributedBuildQueue whereToBeQueued = null; BuildAgentGroupConfiguration buildAgentGroup = getBuildAgentGroup( projectsAndBuildDefinitionsMap ); if ( buildAgentGroup != null ) { List<BuildAgentConfiguration> buildAgents = buildAgentGroup.getBuildAgents(); if ( buildAgents != null && buildAgents.size() > 0 ) { List<String> buildAgentUrls = new ArrayList<String>(); for ( BuildAgentConfiguration buildAgent : buildAgents ) { buildAgentUrls.add( buildAgent.getUrl() ); } synchronized ( overallDistributedBuildQueues ) { int idx = 0; int size = 0; for ( String buildAgentUrl : overallDistributedBuildQueues.keySet() ) { if ( !buildAgentUrls.isEmpty() && buildAgentUrls.contains( buildAgentUrl ) ) { OverallDistributedBuildQueue distributedBuildQueue = overallDistributedBuildQueues.get( buildAgentUrl ); if ( distributedBuildQueue != null ) { try { if ( isAgentAvailable( buildAgentUrl ) ) { log.debug( "Build agent {} is available", buildAgentUrl ); SlaveBuildAgentTransportService client = createSlaveBuildAgentTransportClientConnection( buildAgentUrl ); int agentBuildSize = client.getBuildSizeOfAgent(); log.debug( "Number of projects currently building in agent: {}", agentBuildSize ); if ( idx == 0 ) { log.debug( "Current least busy agent: {}", buildAgentUrl ); whereToBeQueued = distributedBuildQueue; size = agentBuildSize; idx++; } if ( agentBuildSize < size ) { log.debug( "Current least busy agent: {}", buildAgentUrl ); whereToBeQueued = distributedBuildQueue; size = agentBuildSize; } } else { log.debug( "Build agent {} is not available. Skipping...", buildAgentUrl ); } } catch ( MalformedURLException e ) { log.error( "Error occurred while retrieving distributed build queue: Invalid build agent url " + buildAgentUrl ); } catch ( Exception e ) { log.error( "Error occurred while retrieving distributed build queue ", e ); } } } } } } } return whereToBeQueued; } private OverallDistributedBuildQueue getOverallDistributedBuildQueue() throws ContinuumException { OverallDistributedBuildQueue whereToBeQueued = null; synchronized ( overallDistributedBuildQueues ) { if ( overallDistributedBuildQueues.isEmpty() ) { log.info( "No distributed build queues are configured for build agents" ); return null; } int idx = 0; int size = 0; for ( String buildAgentUrl : overallDistributedBuildQueues.keySet() ) { OverallDistributedBuildQueue distributedBuildQueue = overallDistributedBuildQueues.get( buildAgentUrl ); if ( distributedBuildQueue != null ) { try { if ( isAgentAvailable( buildAgentUrl ) ) { log.debug( "Build agent {} is available", buildAgentUrl ); SlaveBuildAgentTransportService client = createSlaveBuildAgentTransportClientConnection( buildAgentUrl ); int agentBuildSize = client.getBuildSizeOfAgent(); log.debug( "Number of projects currently building in agent: {}", agentBuildSize ); if ( idx == 0 ) { log.debug( "Current least busy agent: {}", buildAgentUrl ); whereToBeQueued = distributedBuildQueue; size = agentBuildSize; idx++; } if ( agentBuildSize < size ) { log.debug( "Current least busy agent: {}", buildAgentUrl ); whereToBeQueued = distributedBuildQueue; size = agentBuildSize; } } else { log.debug( "Build agent {} is not available. Skipping...", buildAgentUrl ); } } catch ( MalformedURLException e ) { log.error( "Error occurred while retrieving distributed build queue: invalid build agent url " + buildAgentUrl ); } catch ( Exception e ) { log.error( "Error occurred while retrieving distributed build queue", e ); throw new ContinuumException( "Error occurred while retrieving distributed build queue", e ); } } } } return whereToBeQueued; } private BuildAgentGroupConfiguration getBuildAgentGroup( Map<Integer, Integer> projectsAndBuildDefinitions ) throws ContinuumException { if ( projectsAndBuildDefinitions == null ) { return null; } try { List<Project> projects = new ArrayList<Project>(); for ( Integer projectId : projectsAndBuildDefinitions.keySet() ) { projects.add( projectDao.getProjectWithDependencies( projectId ) ); } projects = ProjectSorter.getSortedProjects( projects, log ); int buildDefinitionId = projectsAndBuildDefinitions.get( projects.get( 0 ).getId() ); BuildDefinition buildDefinition = buildDefinitionDao.getBuildDefinition( buildDefinitionId ); Profile profile = buildDefinition.getProfile(); if ( profile != null && !StringUtils.isEmpty( profile.getBuildAgentGroup() ) ) { String groupName = profile.getBuildAgentGroup(); BuildAgentGroupConfiguration buildAgentGroup = configurationService.getBuildAgentGroup( groupName ); return buildAgentGroup; } } catch ( ContinuumStoreException e ) { log.error( "Error while getting build agent group", e ); throw new ContinuumException( "Error while getting build agent group", e ); } log.info( "profile build agent group is null" ); return null; } private PrepareBuildProjectsTask getPrepareBuildProjectsTask( Map context ) { int projectGroupId = ContinuumBuildConstant.getProjectGroupId( context ); int scmRootId = ContinuumBuildConstant.getScmRootId( context ); String scmRootAddress = ContinuumBuildConstant.getScmRootAddress( context ); BuildTrigger buildTrigger = new BuildTrigger( ContinuumBuildConstant.getTrigger( context ), ContinuumBuildConstant.getUsername( context ) ); return new PrepareBuildProjectsTask( null, buildTrigger, projectGroupId, null, scmRootAddress, scmRootId ); } private BuildProjectTask getBuildProjectTask( Map context ) { int projectId = ContinuumBuildConstant.getProjectId( context ); int buildDefinitionId = ContinuumBuildConstant.getBuildDefinitionId( context ); BuildTrigger buildTrigger = new BuildTrigger( ContinuumBuildConstant.getTrigger( context ), ContinuumBuildConstant.getUsername( context ) ); int projectGroupId = ContinuumBuildConstant.getProjectGroupId( context ); String buildDefinitionLabel = ContinuumBuildConstant.getBuildDefinitionLabel( context ); return new BuildProjectTask( projectId, buildDefinitionId, buildTrigger, null, buildDefinitionLabel, null, projectGroupId ); } public boolean isAgentAvailable( String buildAgentUrl ) throws ContinuumException { try { if ( pingBuildAgent( buildAgentUrl ) ) { return true; } } catch ( Exception e ) { log.warn( "Disable build agent: {}; Unable to ping due to {}", buildAgentUrl, e ); } // disable it disableBuildAgent( buildAgentUrl ); return false; } public boolean pingBuildAgent( String buildAgentUrl ) throws ContinuumException { try { SlaveBuildAgentTransportService client = createSlaveBuildAgentTransportClientConnection( buildAgentUrl ); return client.ping(); } catch ( MalformedURLException e ) { log.warn( "Invalid build agent url {}", buildAgentUrl ); } catch ( Exception e ) { throw new ContinuumException( "Unable to ping build agent " + buildAgentUrl + " : " + e.getMessage() ); } return false; } public List<ProjectRunSummary> getCurrentRuns() { return currentRuns; } public ProjectRunSummary getCurrentRun( int projectId, int buildDefinitionId ) throws ContinuumException { synchronized ( currentRuns ) { for ( ProjectRunSummary currentRun : currentRuns ) { if ( currentRun.getProjectId() == projectId && currentRun.getBuildDefinitionId() == buildDefinitionId ) { return currentRun; } } } throw new ContinuumException( String.format( "no run summary for projectId=%s, buildDefinitionId=%s", projectId, buildDefinitionId ) ); } public ProjectRunSummary getCanceledRun( int projectId, int buildDefinitionId ) throws ContinuumException { synchronized ( canceledRuns ) { for ( ProjectRunSummary currentRun : canceledRuns.keySet() ) { if ( currentRun.getProjectId() == projectId && currentRun.getBuildDefinitionId() == buildDefinitionId ) { return currentRun; } } } throw new ContinuumException( String.format( "no canceled run summary for projectId=%s, buildDefinitionId=%s", projectId, buildDefinitionId ) ); } public void removeCurrentRun( int projectId, int buildDefinitionId ) { synchronized ( currentRuns ) { try { ProjectRunSummary runToDelete = getCurrentRun( projectId, buildDefinitionId ); currentRuns.remove( runToDelete ); } catch ( ContinuumException e ) { log.warn( "failed to remove run summary: {}", e.getMessage() ); } } } public void removeCanceledRun( ProjectRunSummary canceled ) { if ( canceled != null ) { canceledRuns.remove( canceled ); } } private void createProjectRunSummaries( PrepareBuildProjectsTask task, String buildAgentUrl ) { int projectGroupId = task.getProjectGroupId(); int projectScmRootId = task.getProjectScmRootId(); Map<Integer, Integer> map = task.getProjectsBuildDefinitionsMap(); for ( Map.Entry<Integer, Integer> projectEntry : map.entrySet() ) { int projectId = projectEntry.getKey(); int buildDefinitionId = projectEntry.getValue(); synchronized ( currentRuns ) { // Remove stale run summary if one exists try { ProjectRunSummary existingRun = getCurrentRun( projectId, buildDefinitionId ); log.info( "removing stale run summary for projectId={}, buildDefinitionId={}", projectId, buildDefinitionId ); currentRuns.remove( existingRun ); } catch ( ContinuumException e ) { log.debug( "stale run summary not removed: {}", e.getMessage() ); } // Create run summary for project build ProjectRunSummary run = new ProjectRunSummary(); run.setProjectGroupId( projectGroupId ); run.setProjectScmRootId( projectScmRootId ); run.setProjectId( projectId ); run.setBuildDefinitionId( buildDefinitionId ); run.setTriggeredBy( task.getBuildTrigger().getTriggeredBy() ); run.setTrigger( task.getBuildTrigger().getTrigger() ); run.setBuildAgentUrl( buildAgentUrl ); currentRuns.add( run ); } } } private void disableBuildAgent( String buildAgentUrl ) throws ContinuumException { List<BuildAgentConfiguration> agents = configurationService.getBuildAgents(); for ( BuildAgentConfiguration agent : agents ) { if ( agent.getUrl().equals( buildAgentUrl ) ) { agent.setEnabled( false ); configurationService.updateBuildAgent( agent ); try { configurationService.store(); log.debug( "Disabled build agent {}", buildAgentUrl ); } catch ( Exception e ) { throw new ContinuumException( "Unable to disable build agent: " + buildAgentUrl, e ); } } } } private boolean hasBuildagentGroup( Map<Integer, Integer> projectsAndBuildDefinitionsMap ) throws ContinuumException { BuildAgentGroupConfiguration buildAgentGroup = getBuildAgentGroup( projectsAndBuildDefinitionsMap ); return buildAgentGroup != null && buildAgentGroup.getName().length() > 0 ? true : false; } private boolean hasBuildagentInGroup( Map<Integer, Integer> projectsAndBuildDefinitionsMap ) throws ContinuumException { BuildAgentGroupConfiguration buildAgentGroup = getBuildAgentGroup( projectsAndBuildDefinitionsMap ); return buildAgentGroup != null && buildAgentGroup.getBuildAgents().size() > 0 ? true : false; } public SlaveBuildAgentTransportService createSlaveBuildAgentTransportClientConnection( String buildAgentUrl ) throws MalformedURLException, Exception { return new SlaveBuildAgentTransportClient( new URL( buildAgentUrl ), "", configurationService.getSharedSecretPassword() ); } // for unit testing public void setOverallDistributedBuildQueues( Map<String, OverallDistributedBuildQueue> overallDistributedBuildQueues ) { this.overallDistributedBuildQueues = overallDistributedBuildQueues; } public void setConfigurationService( ConfigurationService configurationService ) { this.configurationService = configurationService; } public void setProjectDao( ProjectDao projectDao ) { this.projectDao = projectDao; } public void setBuildDefinitionDao( BuildDefinitionDao buildDefinitionDao ) { this.buildDefinitionDao = buildDefinitionDao; } public void setBuildResultDao( BuildResultDao buildResultDao ) { this.buildResultDao = buildResultDao; } public void setContainer( PlexusContainer container ) { this.container = container; } public void setCurrentRuns( List<ProjectRunSummary> currentRuns ) { this.currentRuns = currentRuns; } public void setProjectScmRootDao( ProjectScmRootDao projectScmRootDao ) { this.projectScmRootDao = projectScmRootDao; } }
5,168
0
Create_ds/continuum/continuum-core/src/main/java/org/apache/continuum/builder/distributed
Create_ds/continuum/continuum-core/src/main/java/org/apache/continuum/builder/distributed/work/DistributedBuildStatusUpdater.java
package org.apache.continuum.builder.distributed.work; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.builder.distributed.manager.DistributedBuildManager; import org.apache.continuum.dao.BuildDefinitionDao; import org.apache.continuum.dao.BuildResultDao; import org.apache.continuum.dao.ProjectDao; import org.apache.continuum.dao.ProjectScmRootDao; import org.apache.continuum.model.project.ProjectRunSummary; import org.apache.continuum.model.project.ProjectScmRoot; import org.apache.maven.continuum.configuration.ConfigurationService; import org.apache.maven.continuum.model.project.BuildDefinition; import org.apache.maven.continuum.model.project.BuildResult; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.project.ContinuumProjectState; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Date; import java.util.List; @Component( role = BuildStatusUpdater.class, hint = "distributed" ) public class DistributedBuildStatusUpdater implements BuildStatusUpdater { private static final Logger log = LoggerFactory.getLogger( DistributedBuildStatusUpdater.class ); @Requirement private ProjectDao projectDao; @Requirement private ProjectScmRootDao projectScmRootDao; @Requirement private BuildDefinitionDao buildDefinitionDao; @Requirement private BuildResultDao buildResultDao; @Requirement private DistributedBuildManager distributedBuildManager; @Requirement private ConfigurationService configurationService; public void performScan() { if ( !configurationService.isDistributedBuildEnabled() ) { return; } log.info( "scanning for distributed build result anomalies" ); List<ProjectRunSummary> currentRuns = new ArrayList<ProjectRunSummary>( distributedBuildManager.getCurrentRuns() ); List<ProjectRunSummary> runsToDelete = new ArrayList<ProjectRunSummary>(); int runCount, resolvedCount; synchronized ( currentRuns ) { runCount = currentRuns.size(); for ( ProjectRunSummary currentRun : currentRuns ) { try { // check for scm update ProjectScmRoot scmRoot = projectScmRootDao.getProjectScmRoot( currentRun.getProjectScmRootId() ); if ( scmRoot != null && scmRoot.getState() == ContinuumProjectState.UPDATING ) { // check if it's still updating if ( !distributedBuildManager.isProjectCurrentlyPreparingBuild( currentRun.getProjectId(), currentRun.getBuildDefinitionId() ) ) { // no longer updating, but state was not updated. scmRoot.setState( ContinuumProjectState.ERROR ); scmRoot.setError( "Problem encountered while returning scm update result to master by build agent '" + currentRun.getBuildAgentUrl() + "'. \n" + "Make sure build agent is configured properly. Check the logs for more information." ); projectScmRootDao.updateProjectScmRoot( scmRoot ); log.debug( "projectId={}, buildDefinitionId={} is not updating anymore. Problem encountered while return scm update result by build agent {}. Stopping the build.", new Object[] { currentRun.getProjectId(), currentRun.getBuildDefinitionId(), currentRun.getBuildAgentUrl() } ); runsToDelete.add( currentRun ); } } else if ( scmRoot != null && scmRoot.getState() == ContinuumProjectState.ERROR ) { log.debug( "projectId={}, buildDefinitionId={} is not updating anymore. Problem encountered while return scm update result by build agent {}. Stopping the build.", new Object[] { currentRun.getProjectId(), currentRun.getBuildDefinitionId(), currentRun.getBuildAgentUrl() } ); runsToDelete.add( currentRun ); } else { Project project = projectDao.getProject( currentRun.getProjectId() ); if ( project != null && project.getState() == ContinuumProjectState.BUILDING ) { // check if it's still building if ( !distributedBuildManager.isProjectCurrentlyBuilding( currentRun.getProjectId(), currentRun.getBuildDefinitionId() ) ) { // no longer building, but state was not updated String msg = String.format( "Problem encountered while returning build result to master by build agent '%s'.%n" + "Make sure build agent is configured properly. Check the logs for more information.", currentRun.getBuildAgentUrl() ); BuildResult buildResult; int existingResultId = currentRun.getBuildResultId(); if ( existingResultId > 0 ) { // Attempt to update existing result BuildResult existingResult = buildResultDao.getBuildResult( currentRun.getBuildResultId() ); existingResult.setState( ContinuumProjectState.ERROR ); existingResult.setSuccess( false ); existingResult.setEndTime( new Date().getTime() ); existingResult.setExitCode( 1 ); existingResult.setError( msg ); buildResultDao.updateBuildResult( existingResult ); buildResult = existingResult; } else { // No existing build result, we have to add it BuildDefinition buildDefinition = buildDefinitionDao.getBuildDefinition( currentRun.getBuildDefinitionId() ); buildResult = new BuildResult(); buildResult.setBuildDefinition( buildDefinition ); buildResult.setBuildUrl( currentRun.getBuildAgentUrl() ); buildResult.setTrigger( currentRun.getTrigger() ); buildResult.setUsername( currentRun.getTriggeredBy() ); buildResult.setState( ContinuumProjectState.ERROR ); buildResult.setSuccess( false ); buildResult.setStartTime( new Date().getTime() ); buildResult.setEndTime( new Date().getTime() ); buildResult.setExitCode( 1 ); buildResult.setError( msg ); buildResultDao.addBuildResult( project, buildResult ); } project.setState( ContinuumProjectState.ERROR ); project.setLatestBuildId( buildResult.getId() ); projectDao.updateProject( project ); log.debug( "projectId={}, buildDefinitionId={} is not building anymore. " + "Problem encountered while return build result by build agent {}. " + "Stopping the build.", new Object[] { currentRun.getProjectId(), currentRun.getBuildDefinitionId(), currentRun.getBuildAgentUrl() } ); // create a build result runsToDelete.add( currentRun ); } } } } catch ( Exception e ) { log.error( "Unable to check if projectId={}, buildDefinitionId={} is still updating or building: {}", new Object[] { currentRun.getProjectId(), currentRun.getBuildDefinitionId(), e.getMessage() } ); } } resolvedCount = runsToDelete.size(); if ( resolvedCount > 0 ) { distributedBuildManager.getCurrentRuns().removeAll( runsToDelete ); } } log.info( "scan finished: resolved {} runs out of {}", resolvedCount, runCount ); } // for testing public void setProjectDao( ProjectDao projectDao ) { this.projectDao = projectDao; } public void setProjectScmRootDao( ProjectScmRootDao projectScmRootDao ) { this.projectScmRootDao = projectScmRootDao; } public void setBuildDefinitionDao( BuildDefinitionDao buildDefinitionDao ) { this.buildDefinitionDao = buildDefinitionDao; } public void setBuildResultDao( BuildResultDao buildResultDao ) { this.buildResultDao = buildResultDao; } public void setConfigurationService( ConfigurationService configurationService ) { this.configurationService = configurationService; } public void setDistributedBuildManager( DistributedBuildManager distributedBuildManager ) { this.distributedBuildManager = distributedBuildManager; } }
5,169
0
Create_ds/continuum/continuum-builder/src/main/java/org/apache/continuum/builder/distributed
Create_ds/continuum/continuum-builder/src/main/java/org/apache/continuum/builder/distributed/taskqueue/DefaultOverallDistributedBuildQueue.java
package org.apache.continuum.builder.distributed.taskqueue; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.commons.lang.ArrayUtils; import org.apache.continuum.builder.distributed.executor.DistributedBuildTaskQueueExecutor; import org.apache.continuum.builder.distributed.executor.ThreadedDistributedBuildTaskQueueExecutor; import org.apache.continuum.taskqueue.OverallDistributedBuildQueue; import org.apache.continuum.taskqueue.PrepareBuildProjectsTask; import org.codehaus.plexus.taskqueue.Task; import org.codehaus.plexus.taskqueue.TaskQueue; import org.codehaus.plexus.taskqueue.TaskQueueException; import java.util.ArrayList; import java.util.List; public class DefaultOverallDistributedBuildQueue implements OverallDistributedBuildQueue { private String buildAgentUrl; private DistributedBuildTaskQueueExecutor distributedBuildTaskQueueExecutor; public void addToDistributedBuildQueue( Task distributedBuildTask ) throws TaskQueueException { getDistributedBuildQueue().put( distributedBuildTask ); } public String getBuildAgentUrl() { return buildAgentUrl; } public TaskQueue getDistributedBuildQueue() { return ( (ThreadedDistributedBuildTaskQueueExecutor) distributedBuildTaskQueueExecutor ).getQueue(); } public DistributedBuildTaskQueueExecutor getDistributedBuildTaskQueueExecutor() { return distributedBuildTaskQueueExecutor; } public List<PrepareBuildProjectsTask> getProjectsInQueue() throws TaskQueueException { return getDistributedBuildQueue().getQueueSnapshot(); } public boolean isInDistributedBuildQueue( int projectGroupId, int scmRootId ) throws TaskQueueException { List<PrepareBuildProjectsTask> tasks = getProjectsInQueue(); for ( PrepareBuildProjectsTask task : tasks ) { if ( task != null ) { if ( task.getProjectGroupId() == projectGroupId && task.getProjectScmRootId() == scmRootId ) { return true; } } } return false; } public void removeFromDistributedBuildQueue( int projectGroupId, int scmRootId ) throws TaskQueueException { List<PrepareBuildProjectsTask> tasks = getProjectsInQueue(); for ( PrepareBuildProjectsTask task : tasks ) { if ( task != null ) { if ( task.getProjectGroupId() == projectGroupId && task.getProjectScmRootId() == scmRootId ) { getDistributedBuildQueue().remove( task ); return; } } } } public void removeFromDistributedBuildQueue( int[] hashCodes ) throws TaskQueueException { List<PrepareBuildProjectsTask> tasks = getProjectsInQueue(); List<PrepareBuildProjectsTask> tasksToRemove = new ArrayList<PrepareBuildProjectsTask>(); for ( PrepareBuildProjectsTask task : tasks ) { if ( task != null ) { if ( ArrayUtils.contains( hashCodes, task.getHashCode() ) ) { tasksToRemove.add( task ); } } } if ( !tasksToRemove.isEmpty() ) { getDistributedBuildQueue().removeAll( tasksToRemove ); } } public void removeFromDistributedBuildQueueByHashCode( int hashCode ) throws TaskQueueException { List<PrepareBuildProjectsTask> tasks = getProjectsInQueue(); for ( PrepareBuildProjectsTask task : tasks ) { if ( task != null ) { if ( task.getHashCode() == hashCode ) { getDistributedBuildQueue().remove( task ); return; } } } } public void setBuildAgentUrl( String buildAgentUrl ) { this.buildAgentUrl = buildAgentUrl; } public void setDistributedBuildTaskQueueExecutor( DistributedBuildTaskQueueExecutor distributedBuildTaskQueueExecutor ) { this.distributedBuildTaskQueueExecutor = distributedBuildTaskQueueExecutor; } }
5,170
0
Create_ds/continuum/continuum-builder/src/main/java/org/apache/continuum/builder/distributed
Create_ds/continuum/continuum-builder/src/main/java/org/apache/continuum/builder/distributed/executor/ThreadedDistributedBuildTaskQueueExecutor.java
package org.apache.continuum.builder.distributed.executor; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import edu.emory.mathcs.backport.java.util.concurrent.CancellationException; import edu.emory.mathcs.backport.java.util.concurrent.ExecutionException; import edu.emory.mathcs.backport.java.util.concurrent.ExecutorService; import edu.emory.mathcs.backport.java.util.concurrent.Executors; import edu.emory.mathcs.backport.java.util.concurrent.Future; import edu.emory.mathcs.backport.java.util.concurrent.TimeUnit; import edu.emory.mathcs.backport.java.util.concurrent.TimeoutException; import org.apache.continuum.utils.ThreadNames; import org.codehaus.plexus.component.annotations.Configuration; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.personality.plexus.lifecycle.phase.Disposable; import org.codehaus.plexus.personality.plexus.lifecycle.phase.Initializable; import org.codehaus.plexus.personality.plexus.lifecycle.phase.InitializationException; import org.codehaus.plexus.personality.plexus.lifecycle.phase.Startable; import org.codehaus.plexus.personality.plexus.lifecycle.phase.StartingException; import org.codehaus.plexus.personality.plexus.lifecycle.phase.StoppingException; import org.codehaus.plexus.taskqueue.Task; import org.codehaus.plexus.taskqueue.TaskQueue; import org.codehaus.plexus.taskqueue.execution.TaskExecutionException; import org.codehaus.plexus.util.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Codes were taken from Plexus' ThreadedTaskQueueExecutor */ public class ThreadedDistributedBuildTaskQueueExecutor implements DistributedBuildTaskQueueExecutor, Initializable, Startable, Disposable { private static final int SHUTDOWN = 1; private static final int CANCEL_TASK = 2; private static final Logger log = LoggerFactory.getLogger( ThreadedDistributedBuildTaskQueueExecutor.class ); @Requirement private TaskQueue queue; @Requirement private DistributedBuildTaskExecutor executor; @Configuration( "" ) private String name; // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- private ExecutorRunnable executorRunnable; private ExecutorService executorService; private Task currentTask; private class ExecutorRunnable extends Thread { private volatile int command; private boolean done; public ExecutorRunnable() { super( ThreadNames.formatNext( "%s-executor", name ) ); } public void run() { while ( command != SHUTDOWN ) { final Task task; currentTask = null; try { task = queue.poll( 100, TimeUnit.MILLISECONDS ); } catch ( InterruptedException e ) { log.info( "Executor thread interrupted, command: " + ( command == SHUTDOWN ? "Shutdown" : command == CANCEL_TASK ? "Cancel task" : "Unknown" ) ); continue; } if ( task == null ) { continue; } currentTask = task; Future future = executorService.submit( new Runnable() { public void run() { try { executor.executeTask( task ); } catch ( TaskExecutionException e ) { log.error( "Error executing task", e ); } } } ); try { waitForTask( task, future ); } catch ( ExecutionException e ) { log.error( "Error executing task", e ); } } currentTask = null; log.info( "Executor thread '" + name + "' exited." ); done = true; synchronized ( this ) { notifyAll(); } } private void waitForTask( Task task, Future future ) throws ExecutionException { boolean stop = false; while ( !stop ) { try { if ( task.getMaxExecutionTime() == 0 ) { log.debug( "Waiting indefinitely for task to complete" ); future.get(); return; } else { log.debug( "Waiting at most " + task.getMaxExecutionTime() + "ms for task completion" ); future.get( task.getMaxExecutionTime(), TimeUnit.MILLISECONDS ); log.debug( "Task completed within " + task.getMaxExecutionTime() + "ms" ); return; } } catch ( InterruptedException e ) { switch ( command ) { case SHUTDOWN: { log.info( "Shutdown command received. Cancelling task." ); cancel( future ); return; } case CANCEL_TASK: { command = 0; log.info( "Cancelling task" ); cancel( future ); return; } default: // when can this thread be interrupted, and should we ignore it if shutdown = false? log.warn( "Interrupted while waiting for task to complete; ignoring", e ); break; } } catch ( TimeoutException e ) { log.warn( "Task " + task + " didn't complete within time, cancelling it." ); cancel( future ); return; } catch ( CancellationException e ) { log.warn( "The task was cancelled", e ); return; } } } private void cancel( Future future ) { if ( !future.cancel( true ) ) { if ( !future.isDone() && !future.isCancelled() ) { log.warn( "Unable to cancel task" ); } else { log.warn( "Task not cancelled (Flags: done: " + future.isDone() + " cancelled: " + future.isCancelled() + ")" ); } } else { log.debug( "Task successfully cancelled" ); } } public synchronized void shutdown() { log.debug( "Signalling executor thread to shutdown" ); command = SHUTDOWN; interrupt(); } public synchronized boolean cancelTask( Task task ) { if ( !task.equals( currentTask ) ) { log.debug( "Not cancelling task - it is not running" ); return false; } if ( command != SHUTDOWN ) { log.debug( "Signalling executor thread to cancel task" ); command = CANCEL_TASK; interrupt(); } else { log.debug( "Executor thread already stopping; task will be cancelled automatically" ); } return true; } public boolean isDone() { return done; } } // ---------------------------------------------------------------------- // Component lifecycle // ---------------------------------------------------------------------- public void initialize() throws InitializationException { if ( StringUtils.isEmpty( name ) ) { throw new IllegalArgumentException( "'name' must be set." ); } } public void start() throws StartingException { log.info( "Starting task executor, thread name '" + name + "'." ); this.executorService = Executors.newSingleThreadExecutor(); executorRunnable = new ExecutorRunnable(); executorRunnable.setDaemon( true ); executorRunnable.start(); } public void stop() throws StoppingException { executorRunnable.shutdown(); int maxSleep = 10 * 1000; // 10 seconds int interval = 1000; long endTime = System.currentTimeMillis() + maxSleep; while ( !executorRunnable.isDone() && executorRunnable.isAlive() ) { if ( System.currentTimeMillis() > endTime ) { log.warn( "Timeout waiting for executor thread '" + name + "' to stop, aborting" ); break; } log.info( "Waiting until task executor '" + name + "' is idling..." ); try { synchronized ( executorRunnable ) { executorRunnable.wait( interval ); } } catch ( InterruptedException ex ) { // ignore } // notify again, just in case. executorRunnable.shutdown(); } } public void dispose() { executorRunnable.shutdown(); } public Task getCurrentTask() { return currentTask; } public synchronized boolean cancelTask( Task task ) { return executorRunnable.cancelTask( task ); } public void setBuildAgentUrl( String buildAgentUrl ) { executor.setBuildAgentUrl( buildAgentUrl ); } public String getBuildAgentUrl() { return executor.getBuildAgentUrl(); } public TaskQueue getQueue() { return queue; } }
5,171
0
Create_ds/continuum/continuum-builder/src/main/java/org/apache/continuum/builder/distributed
Create_ds/continuum/continuum-builder/src/main/java/org/apache/continuum/builder/distributed/executor/DistributedBuildProjectTaskExecutor.java
package org.apache.continuum.builder.distributed.executor; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.builder.distributed.manager.DistributedBuildManager; import org.apache.continuum.builder.utils.ContinuumBuildConstant; import org.apache.continuum.dao.BuildDefinitionDao; import org.apache.continuum.dao.BuildResultDao; import org.apache.continuum.dao.ProjectDao; import org.apache.continuum.dao.ProjectScmRootDao; import org.apache.continuum.distributed.transport.slave.SlaveBuildAgentTransportClient; import org.apache.continuum.model.project.ProjectScmRoot; import org.apache.continuum.model.repository.LocalRepository; import org.apache.continuum.taskqueue.PrepareBuildProjectsTask; import org.apache.continuum.utils.ContinuumUtils; import org.apache.continuum.utils.ProjectSorter; import org.apache.continuum.utils.build.BuildTrigger; import org.apache.maven.continuum.ContinuumException; import org.apache.maven.continuum.configuration.ConfigurationService; import org.apache.maven.continuum.model.project.BuildDefinition; import org.apache.maven.continuum.model.project.BuildResult; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.model.scm.ChangeFile; import org.apache.maven.continuum.model.scm.ChangeSet; import org.apache.maven.continuum.model.scm.ScmResult; import org.apache.maven.continuum.project.ContinuumProjectState; import org.apache.maven.continuum.store.ContinuumStoreException; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.taskqueue.Task; import org.codehaus.plexus.taskqueue.execution.TaskExecutionException; import org.codehaus.plexus.util.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; public class DistributedBuildProjectTaskExecutor implements DistributedBuildTaskExecutor { private static final Logger log = LoggerFactory.getLogger( DistributedBuildProjectTaskExecutor.class ); private String buildAgentUrl; private long startTime; private long endTime; @Requirement private ProjectDao projectDao; @Requirement private ProjectScmRootDao projectScmRootDao; @Requirement private BuildDefinitionDao buildDefinitionDao; @Requirement private BuildResultDao buildResultDao; @Requirement private ConfigurationService configurationService; @Requirement private DistributedBuildManager distributedBuildManager; public void setBuildAgentUrl( String buildAgentUrl ) { this.buildAgentUrl = buildAgentUrl; } public String getBuildAgentUrl() { return buildAgentUrl; } public void executeTask( Task task ) throws TaskExecutionException { PrepareBuildProjectsTask prepareBuildTask = (PrepareBuildProjectsTask) task; try { SlaveBuildAgentTransportClient client = new SlaveBuildAgentTransportClient( new URL( buildAgentUrl ), "", configurationService.getSharedSecretPassword() ); log.info( "initializing buildContext for projectGroupId=" + prepareBuildTask.getProjectGroupId() ); List<Map<String, Object>> buildContext = initializeBuildContext( prepareBuildTask.getProjectsBuildDefinitionsMap(), prepareBuildTask.getBuildTrigger(), prepareBuildTask.getScmRootAddress(), prepareBuildTask.getProjectScmRootId() ); startTime = System.currentTimeMillis(); client.buildProjects( buildContext ); endTime = System.currentTimeMillis(); } catch ( MalformedURLException e ) { log.error( "Invalid URL " + buildAgentUrl + ", not building" ); throw new TaskExecutionException( "Invalid URL " + buildAgentUrl, e ); } catch ( Exception e ) { log.error( "Error occurred while building task", e ); endTime = System.currentTimeMillis(); createResult( prepareBuildTask, ContinuumUtils.throwableToString( e ) ); } } private List<Map<String, Object>> initializeBuildContext( Map<Integer, Integer> projectsAndBuildDefinitions, BuildTrigger buildTrigger, String scmRootAddress, int scmRootId ) throws ContinuumException { List<Map<String, Object>> buildContext = new ArrayList<Map<String, Object>>(); try { ProjectScmRoot scmRoot = projectScmRootDao.getProjectScmRoot( scmRootId ); List<Project> projects = projectDao.getProjectsWithDependenciesByGroupId( scmRoot.getProjectGroup().getId() ); List<Project> sortedProjects = ProjectSorter.getSortedProjects( projects, null ); for ( Project project : sortedProjects ) { if ( !projectsAndBuildDefinitions.containsKey( project.getId() ) ) { continue; } int buildDefinitionId = projectsAndBuildDefinitions.get( project.getId() ); BuildDefinition buildDef = buildDefinitionDao.getBuildDefinition( buildDefinitionId ); BuildResult buildResult = buildResultDao.getLatestBuildResultForProject( project.getId() ); Map<String, Object> context = new HashMap<String, Object>(); context.put( ContinuumBuildConstant.KEY_PROJECT_GROUP_ID, project.getProjectGroup().getId() ); context.put( ContinuumBuildConstant.KEY_PROJECT_GROUP_NAME, project.getProjectGroup().getName() ); context.put( ContinuumBuildConstant.KEY_SCM_ROOT_ID, scmRootId ); context.put( ContinuumBuildConstant.KEY_SCM_ROOT_ADDRESS, scmRootAddress ); context.put( ContinuumBuildConstant.KEY_PROJECT_ID, project.getId() ); context.put( ContinuumBuildConstant.KEY_PROJECT_NAME, project.getName() ); context.put( ContinuumBuildConstant.KEY_PROJECT_VERSION, project.getVersion() ); context.put( ContinuumBuildConstant.KEY_EXECUTOR_ID, project.getExecutorId() ); context.put( ContinuumBuildConstant.KEY_PROJECT_BUILD_NUMBER, project.getBuildNumber() ); context.put( ContinuumBuildConstant.KEY_SCM_URL, project.getScmUrl() ); context.put( ContinuumBuildConstant.KEY_PROJECT_STATE, project.getState() ); if ( buildResult != null ) { context.put( ContinuumBuildConstant.KEY_LATEST_UPDATE_DATE, new Date( buildResult.getStartTime() ) ); } LocalRepository localRepo = project.getProjectGroup().getLocalRepository(); if ( localRepo != null ) { // CONTINUUM-2391 context.put( ContinuumBuildConstant.KEY_LOCAL_REPOSITORY, localRepo.getName() ); } else { context.put( ContinuumBuildConstant.KEY_LOCAL_REPOSITORY, "" ); } if ( project.getScmUsername() == null ) { context.put( ContinuumBuildConstant.KEY_SCM_USERNAME, "" ); } else { context.put( ContinuumBuildConstant.KEY_SCM_USERNAME, project.getScmUsername() ); } if ( project.getScmPassword() == null ) { context.put( ContinuumBuildConstant.KEY_SCM_PASSWORD, "" ); } else { context.put( ContinuumBuildConstant.KEY_SCM_PASSWORD, project.getScmPassword() ); } if ( project.getScmTag() != null ) { context.put( ContinuumBuildConstant.KEY_SCM_TAG, project.getScmTag() ); } else { context.put( ContinuumBuildConstant.KEY_SCM_TAG, "" ); } context.put( ContinuumBuildConstant.KEY_BUILD_DEFINITION_ID, buildDefinitionId ); String buildDefinitionLabel = buildDef.getDescription(); if ( StringUtils.isEmpty( buildDefinitionLabel ) ) { buildDefinitionLabel = buildDef.getGoals(); } context.put( ContinuumBuildConstant.KEY_BUILD_DEFINITION_LABEL, buildDefinitionLabel ); context.put( ContinuumBuildConstant.KEY_BUILD_FILE, buildDef.getBuildFile() ); if ( buildDef.getGoals() == null ) { context.put( ContinuumBuildConstant.KEY_GOALS, "" ); } else { context.put( ContinuumBuildConstant.KEY_GOALS, buildDef.getGoals() ); } if ( buildDef.getArguments() == null ) { context.put( ContinuumBuildConstant.KEY_ARGUMENTS, "" ); } else { context.put( ContinuumBuildConstant.KEY_ARGUMENTS, buildDef.getArguments() ); } context.put( ContinuumBuildConstant.KEY_TRIGGER, buildTrigger.getTrigger() ); if ( buildTrigger.getTrigger() == ContinuumProjectState.TRIGGER_FORCED ) { if ( buildTrigger.getTriggeredBy() == null ) { context.put( ContinuumBuildConstant.KEY_USERNAME, "" ); } else { context.put( ContinuumBuildConstant.KEY_USERNAME, buildTrigger.getTriggeredBy() ); } } else { context.put( ContinuumBuildConstant.KEY_USERNAME, buildDef.getSchedule().getName() ); } context.put( ContinuumBuildConstant.KEY_BUILD_FRESH, buildDef.isBuildFresh() ); context.put( ContinuumBuildConstant.KEY_ALWAYS_BUILD, buildDef.isAlwaysBuild() ); context.put( ContinuumBuildConstant.KEY_OLD_SCM_CHANGES, getOldScmChanges( project.getId(), buildDefinitionId ) ); context.put( ContinuumBuildConstant.KEY_BUILD_AGENT_URL, buildAgentUrl ); context.put( ContinuumBuildConstant.KEY_MAX_JOB_EXEC_TIME, buildDef.getSchedule().getMaxJobExecutionTime() ); buildContext.add( context ); } return buildContext; } catch ( ContinuumStoreException e ) { throw new ContinuumException( "Error while initializing build context", e ); } } private void createResult( PrepareBuildProjectsTask task, String error ) throws TaskExecutionException { try { ProjectScmRoot scmRoot = projectScmRootDao.getProjectScmRootByProjectGroupAndScmRootAddress( task.getProjectGroupId(), task.getScmRootAddress() ); if ( scmRoot.getState() == ContinuumProjectState.UPDATING ) { scmRoot.setState( ContinuumProjectState.ERROR ); scmRoot.setError( error ); projectScmRootDao.updateProjectScmRoot( scmRoot ); } else { Map<Integer, Integer> map = task.getProjectsBuildDefinitionsMap(); for ( Map.Entry<Integer, Integer> build : map.entrySet() ) { int projectId = build.getKey(), buildDefinitionId = build.getValue(); Project project = projectDao.getProject( projectId ); BuildDefinition buildDef = buildDefinitionDao.getBuildDefinition( buildDefinitionId ); BuildResult latestBuildResult = buildResultDao .getLatestBuildResultForBuildDefinition( projectId, buildDefinitionId ); if ( latestBuildResult == null || ( latestBuildResult.getStartTime() >= startTime && latestBuildResult.getEndTime() > 0 && latestBuildResult.getEndTime() < endTime ) || latestBuildResult.getStartTime() < startTime ) { BuildResult buildResult = new BuildResult(); buildResult.setBuildDefinition( buildDef ); buildResult.setError( error ); buildResult.setState( ContinuumProjectState.ERROR ); buildResult.setTrigger( task.getBuildTrigger().getTrigger() ); buildResult.setUsername( task.getBuildTrigger().getTriggeredBy() ); buildResult.setStartTime( startTime ); buildResult.setEndTime( endTime ); buildResultDao.addBuildResult( project, buildResult ); } } } } catch ( ContinuumStoreException e ) { throw new TaskExecutionException( "Error while creating result", e ); } } private List<Map<String, Object>> getOldScmChanges( int projectId, int buildDefinitionId ) throws ContinuumStoreException { List<Map<String, Object>> scmChanges = new ArrayList<Map<String, Object>>(); BuildResult oldBuildResult = buildResultDao.getLatestBuildResultForBuildDefinition( projectId, buildDefinitionId ); if ( oldBuildResult != null ) { ScmResult scmResult = getOldScmResults( projectId, oldBuildResult.getBuildNumber(), oldBuildResult.getEndTime() ); scmChanges = getScmChanges( scmResult ); } return scmChanges; } private List<Map<String, Object>> getScmChanges( ScmResult scmResult ) { List<Map<String, Object>> scmChanges = new ArrayList<Map<String, Object>>(); if ( scmResult != null && scmResult.getChanges() != null ) { for ( Object obj : scmResult.getChanges() ) { ChangeSet changeSet = (ChangeSet) obj; Map<String, Object> map = new HashMap<String, Object>(); if ( StringUtils.isNotEmpty( changeSet.getAuthor() ) ) { map.put( ContinuumBuildConstant.KEY_CHANGESET_AUTHOR, changeSet.getAuthor() ); } else { map.put( ContinuumBuildConstant.KEY_CHANGESET_AUTHOR, "" ); } if ( StringUtils.isNotEmpty( changeSet.getComment() ) ) { map.put( ContinuumBuildConstant.KEY_CHANGESET_COMMENT, changeSet.getComment() ); } else { map.put( ContinuumBuildConstant.KEY_CHANGESET_COMMENT, "" ); } if ( changeSet.getDateAsDate() != null ) { map.put( ContinuumBuildConstant.KEY_CHANGESET_DATE, changeSet.getDateAsDate() ); } map.put( ContinuumBuildConstant.KEY_CHANGESET_FILES, getScmChangeFiles( changeSet.getFiles() ) ); scmChanges.add( map ); } } return scmChanges; } private List<Map<String, String>> getScmChangeFiles( List<ChangeFile> files ) { List<Map<String, String>> scmChangeFiles = new ArrayList<Map<String, String>>(); if ( files != null ) { for ( ChangeFile changeFile : files ) { Map<String, String> map = new HashMap<String, String>(); if ( StringUtils.isNotEmpty( changeFile.getName() ) ) { map.put( ContinuumBuildConstant.KEY_CHANGEFILE_NAME, changeFile.getName() ); } else { map.put( ContinuumBuildConstant.KEY_CHANGEFILE_NAME, "" ); } if ( StringUtils.isNotEmpty( changeFile.getRevision() ) ) { map.put( ContinuumBuildConstant.KEY_CHANGEFILE_REVISION, changeFile.getRevision() ); } else { map.put( ContinuumBuildConstant.KEY_CHANGEFILE_REVISION, "" ); } if ( StringUtils.isNotEmpty( changeFile.getStatus() ) ) { map.put( ContinuumBuildConstant.KEY_CHANGEFILE_STATUS, changeFile.getStatus() ); } else { map.put( ContinuumBuildConstant.KEY_CHANGEFILE_STATUS, "" ); } scmChangeFiles.add( map ); } } return scmChangeFiles; } private ScmResult getOldScmResults( int projectId, long startId, long fromDate ) throws ContinuumStoreException { List<BuildResult> results = buildResultDao.getBuildResultsForProjectFromId( projectId, startId ); ScmResult res = new ScmResult(); if ( results != null && results.size() > 0 ) { for ( BuildResult result : results ) { ScmResult scmResult = result.getScmResult(); if ( scmResult != null ) { List<ChangeSet> changes = scmResult.getChanges(); if ( changes != null ) { for ( ChangeSet changeSet : changes ) { if ( changeSet.getDate() < fromDate ) { continue; } if ( !res.getChanges().contains( changeSet ) ) { res.addChange( changeSet ); } } } } } } return res; } }
5,172
0
Create_ds/continuum/continuum-builder/src/main/java/org/apache/continuum/builder
Create_ds/continuum/continuum-builder/src/main/java/org/apache/continuum/builder/utils/ContinuumBuildConstant.java
package org.apache.continuum.builder.utils; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.utils.build.BuildTrigger; import org.apache.maven.continuum.model.project.BuildResult; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.Map; public class ContinuumBuildConstant { public static final String KEY_PROJECT_ID = "project-id"; public static final String KEY_PROJECT_VERSION = "project-version"; public static final String KEY_PROJECT_BUILD_NUMBER = "build-number"; public static final String KEY_BUILD_DEFINITION_ID = "builddefinition-id"; public static final String KEY_BUILD_DEFINITION_LABEL = "builddefinition-label"; public static final String KEY_TRIGGER = "trigger"; public static final String KEY_USERNAME = "username"; public static final String KEY_BUILD_TRIGGER = "buildTrigger"; public static final String KEY_EXECUTOR_ID = "executor-id"; public static final String KEY_SCM_URL = "scm-url"; public static final String KEY_SCM_USERNAME = "scm-username"; public static final String KEY_SCM_PASSWORD = "scm-password"; public static final String KEY_BUILD_FILE = "build-file"; public static final String KEY_GOALS = "goals"; public static final String KEY_ARGUMENTS = "arguments"; public static final String KEY_BUILD_FRESH = "build-fresh"; public static final String KEY_ALWAYS_BUILD = "always-build"; public static final String KEY_START_TIME = "start-time"; public static final String KEY_END_TIME = "end-time"; public static final String KEY_BUILD_ERROR = "build-error"; public static final String KEY_BUILD_EXIT_CODE = "build-exit-code"; public static final String KEY_BUILD_STATE = "build-state"; public static final String KEY_SCM_COMMAND_OUTPUT = "scm-command-output"; public static final String KEY_SCM_COMMAND_LINE = "scm-command-line"; public static final String KEY_SCM_PROVIDER_MESSAGE = "scm-provider-message"; public static final String KEY_SCM_EXCEPTION = "scm-exception"; public static final String KEY_SCM_SUCCESS = "scm-success"; public static final String KEY_PROJECT_GROUP_ID = "project-group-id"; public static final String KEY_PROJECT_GROUP_NAME = "project-group-name"; public static final String KEY_SCM_ROOT_ADDRESS = "scm-root-address"; public static final String KEY_SCM_ROOT_ID = "scm-root-id"; public static final String KEY_SCM_ERROR = "scm-error"; public static final String KEY_PROJECT_NAME = "project-name"; public static final String KEY_BUILD_OUTPUT = "build-output"; public static final String KEY_BUILD_RESULT = "build-result"; public static final String KEY_PROJECT_STATE = "project-state"; public static final String KEY_INSTALLATION_NAME = "installation-name"; public static final String KEY_INSTALLATION_TYPE = "installation-type"; public static final String KEY_INSTALLATION_VAR_NAME = "installation-var-name"; public static final String KEY_INSTALLATION_VAR_VALUE = "installation-var-value"; public static final String KEY_LOCAL_REPOSITORY = "local-repository"; public static final String KEY_SCM_CHANGES = "scm-changes"; public static final String KEY_CHANGESET_ID = "changeset-id"; public static final String KEY_CHANGESET_AUTHOR = "changeset-author"; public static final String KEY_CHANGESET_COMMENT = "changeset-comment"; public static final String KEY_CHANGESET_DATE = "changeset-date"; public static final String KEY_CHANGESET_FILES = "changeset-files"; public static final String KEY_CHANGEFILE_NAME = "changefile-name"; public static final String KEY_CHANGEFILE_REVISION = "changefile-revision"; public static final String KEY_CHANGEFILE_STATUS = "changefile-status"; public static final String KEY_OLD_SCM_CHANGES = "old-scm-changes"; public static final String KEY_PROJECT_DESCRIPTION = "project-description"; public static final String KEY_GROUP_ID = "group-id"; public static final String KEY_ARTIFACT_ID = "artifact-id"; public static final String KEY_PROJECT_DEVELOPERS = "project-developers"; public static final String KEY_PROJECT_DEPENDENCIES = "project-dependencies"; public static final String KEY_PROJECT_NOTIFIERS = "project-notifiers"; public static final String KEY_PROJECT_URL = "project-url"; public static final String KEY_SCM_TAG = "scm-tag"; public static final String KEY_SCM_RESULT = "scm-result"; public static final String KEY_PROJECT_PARENT = "project-parent"; public static final String KEY_NOTIFIER_TYPE = "notifier-type"; public static final String KEY_NOTIFIER_CONFIGURATION = "notifier-configuration"; public static final String KEY_NOTIFIER_FROM = "notifier-from"; public static final String KEY_NOTIFIER_RECIPIENT_TYPE = "notifier-recipient-type"; public static final String KEY_NOTIFIER_ENABLED = "notifier-enabled"; public static final String KEY_NOTIFIER_SEND_ON_SUCCESS = "notifier-send-on-success"; public static final String KEY_NOTIFIER_SEND_ON_FAILURE = "notifier-send-on-failure"; public static final String KEY_NOTIFIER_SEND_ON_ERROR = "notifier-send-on-error"; public static final String KEY_NOTIFIER_SEND_ON_SCMFAILURE = "notifier-send-on-scmfailure"; public static final String KEY_NOTIFIER_SEND_ON_WARNING = "notifier-send-on-warning"; public static final String KEY_PROJECT_DEVELOPER_NAME = "developer-name"; public static final String KEY_PROJECT_DEVELOPER_EMAIL = "developer-email"; public static final String KEY_PROJECT_DEVELOPER_SCMID = "developer-scmid"; public static final String KEY_MAVEN_PROJECT = "maven-project"; public static final String KEY_PROJECT_MODULES = "project-modules"; public static final String KEY_LATEST_UPDATE_DATE = "latest-update-date"; public static final String KEY_BUILD_AGENT_URL = "build-agent-url"; public static final String KEY_MAX_JOB_EXEC_TIME = "max-job-exec-time"; public static int getProjectId( Map<String, Object> context ) { return getInteger( context, KEY_PROJECT_ID ); } public static int getBuildDefinitionId( Map<String, Object> context ) { return getInteger( context, KEY_BUILD_DEFINITION_ID ); } public static String getBuildError( Map<String, Object> context ) { return getString( context, KEY_BUILD_ERROR ); } public static int getTrigger( Map<String, Object> context ) { return getInteger( context, KEY_TRIGGER ); } public static String getUsername( Map<String, Object> context ) { return getString( context, KEY_USERNAME, "" ); } public static BuildTrigger getBuildTrigger( Map<String, Object> context ) { BuildTrigger defaultValue = new BuildTrigger( 0, "" ); return (BuildTrigger) getObject( context, KEY_BUILD_TRIGGER, defaultValue ); } public static long getStartTime( Map<String, Object> context ) { return new Long( getString( context, KEY_START_TIME ) ); } public static long getEndTime( Map<String, Object> context ) { return new Long( getString( context, KEY_END_TIME ) ); } public static int getBuildExitCode( Map<String, Object> context ) { return getInteger( context, KEY_BUILD_EXIT_CODE ); } public static int getBuildState( Map<String, Object> context ) { return getInteger( context, KEY_BUILD_STATE ); } public static String getScmCommandLine( Map<String, Object> context ) { return getString( context, KEY_SCM_COMMAND_LINE ); } public static String getScmCommandOutput( Map<String, Object> context ) { return getString( context, KEY_SCM_COMMAND_OUTPUT ); } public static String getScmException( Map<String, Object> context ) { return getString( context, KEY_SCM_EXCEPTION ); } public static String getScmProviderMessage( Map<String, Object> context ) { return getString( context, KEY_SCM_PROVIDER_MESSAGE ); } public static boolean isScmSuccess( Map<String, Object> context ) { return getBoolean( context, KEY_SCM_SUCCESS ); } public static int getProjectGroupId( Map<String, Object> context ) { return getInteger( context, KEY_PROJECT_GROUP_ID ); } public static String getScmRootAddress( Map<String, Object> context ) { return getString( context, KEY_SCM_ROOT_ADDRESS ); } public static String getScmError( Map<String, Object> context ) { return getString( context, KEY_SCM_ERROR ); } public static String getBuildOutput( Map<String, Object> context ) { return getString( context, KEY_BUILD_OUTPUT ); } public static BuildResult getBuildResult( Map<String, Object> context, Object defaultValue ) { return (BuildResult) getObject( context, KEY_BUILD_RESULT, defaultValue ); } public static String getInstallationName( Map<String, Object> context ) { return getString( context, KEY_INSTALLATION_NAME ); } public static String getInstallationType( Map<String, Object> context ) { return getString( context, KEY_INSTALLATION_TYPE ); } public static String getInstallationVarValue( Map<String, Object> context ) { return getString( context, KEY_INSTALLATION_VAR_VALUE ); } public static String getInstallationVarName( Map<String, Object> context ) { return getString( context, KEY_INSTALLATION_VAR_NAME ); } public static List<Map<String, Object>> getScmChanges( Map<String, Object> context ) { return getList( context, KEY_SCM_CHANGES ); } public static String getChangeSetAuthor( Map<String, Object> context ) { return getString( context, KEY_CHANGESET_AUTHOR ); } public static String getChangeSetComment( Map<String, Object> context ) { return getString( context, KEY_CHANGESET_COMMENT ); } public static long getChangeSetDate( Map<String, Object> context ) { Date date = getDate( context, KEY_CHANGESET_DATE ); if ( date == null ) { return 0; } else { return date.getTime(); } } public static List<Map<String, Object>> getChangeSetFiles( Map<String, Object> context ) { return getList( context, KEY_CHANGESET_FILES ); } public static String getChangeFileName( Map<String, Object> context ) { return getString( context, KEY_CHANGEFILE_NAME ); } public static String getChangeFileRevision( Map<String, Object> context ) { return getString( context, KEY_CHANGEFILE_REVISION ); } public static String getChangeFileStatus( Map<String, Object> context ) { return getString( context, KEY_CHANGEFILE_STATUS ); } public static String getGroupId( Map<String, Object> context ) { return getString( context, KEY_GROUP_ID ); } public static String getArtifactId( Map<String, Object> context ) { return getString( context, KEY_ARTIFACT_ID ); } public static String getVersion( Map<String, Object> context ) { return getString( context, KEY_PROJECT_VERSION ); } public static String getProjectName( Map<String, Object> context ) { return getString( context, KEY_PROJECT_NAME ); } public static String getProjectDescription( Map<String, Object> context ) { return getString( context, KEY_PROJECT_DESCRIPTION ); } public static String getProjectUrl( Map<String, Object> context ) { return getString( context, KEY_PROJECT_URL ); } public static String getScmUrl( Map<String, Object> context ) { return getString( context, KEY_SCM_URL ); } public static String getScmTag( Map<String, Object> context ) { return getString( context, KEY_SCM_TAG ); } public static Map<String, Object> getProjectParent( Map<String, Object> context ) { return getMap( context, KEY_PROJECT_PARENT ); } public static List<Map<String, Object>> getProjectDevelopers( Map<String, Object> context ) { return getList( context, KEY_PROJECT_DEVELOPERS ); } public static String getDeveloperName( Map<String, Object> context ) { return getString( context, KEY_PROJECT_DEVELOPER_NAME ); } public static String getDeveloperEmail( Map<String, Object> context ) { return getString( context, KEY_PROJECT_DEVELOPER_EMAIL ); } public static String getDeveloperScmId( Map<String, Object> context ) { return getString( context, KEY_PROJECT_DEVELOPER_SCMID ); } public static List<Map<String, Object>> getProjectDependencies( Map<String, Object> context ) { return getList( context, KEY_PROJECT_DEPENDENCIES ); } public static List<Map<String, Object>> getProjectNotifiers( Map<String, Object> context ) { return getList( context, KEY_PROJECT_NOTIFIERS ); } public static Map getNotifierConfiguration( Map<String, Object> context ) { return getMap( context, KEY_NOTIFIER_CONFIGURATION ); } public static int getNotifierFrom( Map<String, Object> context ) { return getInteger( context, KEY_NOTIFIER_FROM ); } public static int getNotifierRecipientType( Map<String, Object> context ) { return getInteger( context, KEY_NOTIFIER_RECIPIENT_TYPE ); } public static String getNotifierType( Map<String, Object> context ) { return getString( context, KEY_NOTIFIER_TYPE ); } public static boolean isNotifierEnabled( Map<String, Object> context ) { return getBoolean( context, KEY_NOTIFIER_ENABLED ); } public static boolean isNotifierSendOnError( Map<String, Object> context ) { return getBoolean( context, KEY_NOTIFIER_SEND_ON_ERROR ); } public static boolean isNotifierSendOnFailure( Map<String, Object> context ) { return getBoolean( context, KEY_NOTIFIER_SEND_ON_FAILURE ); } public static boolean isNotifierSendOnScmFailure( Map<String, Object> context ) { return getBoolean( context, KEY_NOTIFIER_SEND_ON_SCMFAILURE ); } public static boolean isNotifierSendOnSuccess( Map<String, Object> context ) { return getBoolean( context, KEY_NOTIFIER_SEND_ON_SUCCESS ); } public static boolean isNotifierSendOnWarning( Map<String, Object> context ) { return getBoolean( context, KEY_NOTIFIER_SEND_ON_WARNING ); } public static Map<String, Object> getScmResult( Map<String, Object> context ) { return getMap( context, KEY_SCM_RESULT ); } public static Map<String, Object> getMavenProject( Map<String, Object> context ) { return getMap( context, KEY_MAVEN_PROJECT ); } public static List<String> getProjectModules( Map<String, Object> context ) { return getList( context, KEY_PROJECT_MODULES ); } public static Date getLatestUpdateDate( Map<String, Object> context ) { return getDate( context, KEY_LATEST_UPDATE_DATE ); } public static String getBuildAgentUrl( Map<String, Object> context ) { return getString( context, KEY_BUILD_AGENT_URL ); } public static int getScmRootId( Map<String, Object> context ) { return getInteger( context, KEY_SCM_ROOT_ID ); } public static String getBuildDefinitionLabel( Map<String, Object> context ) { return getString( context, KEY_BUILD_DEFINITION_LABEL, "" ); } // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- protected static String getString( Map<String, Object> context, String key ) { Object obj = getObject( context, key, null ); if ( obj == null ) { return null; } else { return (String) obj; } } protected static String getString( Map<String, Object> context, String key, String defaultValue ) { return (String) getObject( context, key, defaultValue ); } protected static boolean getBoolean( Map<String, Object> context, String key ) { Object obj = getObject( context, key, null ); return obj != null && (Boolean) obj; } protected static boolean getBoolean( Map<String, Object> context, String key, boolean defaultValue ) { return (Boolean) getObject( context, key, defaultValue ); } protected static int getInteger( Map<String, Object> context, String key ) { Object obj = getObject( context, key, null ); if ( obj == null ) { return 0; } else { return (Integer) obj; } } protected static Date getDate( Map<String, Object> context, String key ) { Object obj = getObject( context, key, null ); if ( obj == null ) { return null; } else { return (Date) obj; } } protected static List getList( Map<String, Object> context, String key ) { Object obj = getObject( context, key, null ); if ( obj == null ) { return null; } else { List<Object> list = new ArrayList<Object>(); Object[] objA = (Object[]) obj; list.addAll( Arrays.asList( objA ) ); return list; } } protected static Map getMap( Map<String, Object> context, String key ) { Object obj = getObject( context, key, null ); if ( obj == null ) { return null; } else { return (Map) obj; } } protected static Object getObject( Map<String, Object> context, String key ) { if ( !context.containsKey( key ) ) { throw new RuntimeException( "Missing key '" + key + "'." ); } Object value = context.get( key ); if ( value == null ) { throw new RuntimeException( "Missing value for key '" + key + "'." ); } return value; } protected static Object getObject( Map<String, Object> context, String key, Object defaultValue ) { Object value = context.get( key ); if ( value == null ) { return defaultValue; } return value; } }
5,173
0
Create_ds/continuum/continuum-xmlrpc/continuum-xmlrpc-server/src/test/java/org/apache/continuum/xmlrpc
Create_ds/continuum/continuum-xmlrpc/continuum-xmlrpc-server/src/test/java/org/apache/continuum/xmlrpc/server/ContinuumServiceImplTest.java
package org.apache.continuum.xmlrpc.server; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.builder.distributed.manager.DistributedBuildManager; import org.apache.continuum.configuration.BuildAgentGroupConfiguration; import org.apache.continuum.model.project.ProjectScmRoot; import org.apache.continuum.release.distributed.manager.DistributedReleaseManager; import org.apache.continuum.xmlrpc.utils.BuildTrigger; import org.apache.maven.continuum.Continuum; import org.apache.maven.continuum.ContinuumException; import org.apache.maven.continuum.PlexusSpringTestCase; import org.apache.maven.continuum.configuration.ConfigurationService; import org.apache.maven.continuum.installation.InstallationException; import org.apache.maven.continuum.installation.InstallationService; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.model.project.ProjectGroup; import org.apache.maven.continuum.release.ContinuumReleaseManager; import org.apache.maven.continuum.xmlrpc.project.BuildAgentConfiguration; import org.apache.maven.continuum.xmlrpc.project.BuildDefinition; import org.apache.maven.continuum.xmlrpc.project.ContinuumProjectState; import org.apache.maven.continuum.xmlrpc.project.ProjectGroupSummary; import org.apache.maven.continuum.xmlrpc.project.ReleaseListenerSummary; import org.apache.maven.continuum.xmlrpc.server.ContinuumServiceImpl; import org.apache.maven.continuum.xmlrpc.system.Installation; import org.codehaus.plexus.redback.role.RoleManager; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.junit.Assert.*; import static org.mockito.Mockito.*; public class ContinuumServiceImplTest extends PlexusSpringTestCase { private ContinuumServiceImpl continuumService; private Continuum continuum; private DistributedReleaseManager distributedReleaseManager; private ContinuumReleaseManager releaseManager; private DistributedBuildManager distributedBuildManager; private ConfigurationService configurationService; private Project project; private Map<String, Object> params; private RoleManager roleManager; @Before public void setUp() throws Exception { distributedReleaseManager = mock( DistributedReleaseManager.class ); releaseManager = mock( ContinuumReleaseManager.class ); configurationService = mock( ConfigurationService.class ); distributedBuildManager = mock( DistributedBuildManager.class ); roleManager = mock( RoleManager.class ); continuumService = new ContinuumServiceImplStub(); continuum = mock( Continuum.class ); continuumService.setContinuum( continuum ); continuumService.setDistributedBuildManager( distributedBuildManager ); continuumService.setRoleManager( roleManager ); ProjectGroup projectGroup = new ProjectGroup(); projectGroup.setName( "test-group" ); project = new Project(); project.setId( 1 ); project.setProjectGroup( projectGroup ); project.setVersion( "1.0-SNAPSHOT" ); project.setArtifactId( "continuum-test" ); project.setScmUrl( "scm:svn:http://svn.test.org/repository/project" ); } @Test public void testGetReleasePluginParameters() throws Exception { params = new HashMap<String, Object>(); params.put( "scm-tag", "" ); params.put( "scm-tagbase", "" ); when( continuum.getProject( 1 ) ).thenReturn( project ); when( continuum.getConfiguration() ).thenReturn( configurationService ); when( configurationService.isDistributedBuildEnabled() ).thenReturn( true ); when( continuum.getDistributedReleaseManager() ).thenReturn( distributedReleaseManager ); when( distributedReleaseManager.getReleasePluginParameters( 1, "pom.xml" ) ).thenReturn( params ); when( continuum.getReleaseManager() ).thenReturn( releaseManager ); Map<String, Object> releaseParams = continuumService.getReleasePluginParameters( 1 ); assertEquals( "continuum-test-1.0", releaseParams.get( "scm-tag" ) ); assertEquals( "http://svn.test.org/repository/project/tags", releaseParams.get( "scm-tagbase" ) ); verify( releaseManager ).sanitizeTagName( "scm:svn:http://svn.test.org/repository/project", "continuum-test-1.0" ); } @Test public void testGetListenerWithDistributedBuilds() throws Exception { Map map = getListenerMap(); when( continuum.getProject( 1 ) ).thenReturn( project ); when( continuum.getConfiguration() ).thenReturn( configurationService ); when( configurationService.isDistributedBuildEnabled() ).thenReturn( true ); when( continuum.getDistributedReleaseManager() ).thenReturn( distributedReleaseManager ); when( distributedReleaseManager.getListener( "releaseId-1" ) ).thenReturn( map ); ReleaseListenerSummary summary = continuumService.getListener( 1, "releaseId-1" ); assertNotNull( summary ); assertEquals( "incomplete-phase", summary.getPhases().get( 0 ) ); assertEquals( "completed-phase", summary.getCompletedPhases().get( 0 ) ); } @Test public void testPopulateBuildDefinition() throws Exception { ContinuumServiceImplStub continuumServiceStub = new ContinuumServiceImplStub(); BuildDefinition buildDef = createBuildDefinition(); org.apache.maven.continuum.model.project.BuildDefinition buildDefinition = new org.apache.maven.continuum.model.project.BuildDefinition(); buildDefinition = continuumServiceStub.getBuildDefinition( buildDef, buildDefinition ); assertEquals( buildDef.getArguments(), buildDefinition.getArguments() ); assertEquals( buildDef.getBuildFile(), buildDefinition.getBuildFile() ); assertEquals( buildDef.getDescription(), buildDefinition.getDescription() ); assertEquals( buildDef.getGoals(), buildDefinition.getGoals() ); assertEquals( buildDef.getType(), buildDefinition.getType() ); assertEquals( buildDef.isAlwaysBuild(), buildDefinition.isAlwaysBuild() ); assertEquals( buildDef.isBuildFresh(), buildDefinition.isBuildFresh() ); assertEquals( buildDef.isDefaultForProject(), buildDefinition.isDefaultForProject() ); } @Test public void testBuildProjectWithBuildTrigger() throws Exception { final ProjectGroup projectGroup = new ProjectGroup(); projectGroup.setName( "test-group" ); BuildTrigger buildTrigger = new BuildTrigger(); buildTrigger.setTrigger( ContinuumProjectState.TRIGGER_FORCED ); buildTrigger.setTriggeredBy( "username" ); BuildDefinition buildDef = createBuildDefinition(); buildDef.setId( 1 ); when( continuum.getProject( project.getId() ) ).thenReturn( project ); when( continuum.getProjectGroupByProjectId( project.getId() ) ).thenReturn( projectGroup ); int result = continuumService.buildProject( project.getId(), buildDef.getId(), buildTrigger ); assertEquals( 0, result ); } @Test public void testGetProjectScmRootByProjectGroup() throws Exception { final ProjectGroup projectGroup = new ProjectGroup(); projectGroup.setName( "test-group" ); projectGroup.setId( 1 ); final List<ProjectScmRoot> scmRoots = new ArrayList<ProjectScmRoot>(); ProjectScmRoot scmRoot = new ProjectScmRoot(); scmRoot.setState( 1 ); scmRoot.setOldState( 3 ); scmRoot.setScmRootAddress( "address1" ); scmRoot.setProjectGroup( projectGroup ); scmRoots.add( scmRoot ); scmRoot = new ProjectScmRoot(); scmRoot.setState( 2 ); scmRoot.setOldState( 4 ); scmRoot.setScmRootAddress( "address2" ); scmRoot.setProjectGroup( projectGroup ); scmRoots.add( scmRoot ); when( continuum.getProjectScmRootByProjectGroup( projectGroup.getId() ) ).thenReturn( scmRoots ); when( continuum.getProjectGroup( projectGroup.getId() ) ).thenReturn( projectGroup ); List<org.apache.maven.continuum.xmlrpc.project.ProjectScmRoot> projectScmRoots = continuumService.getProjectScmRootByProjectGroup( projectGroup.getId() ); assertEquals( 2, projectScmRoots.size() ); assertEquals( 1, projectScmRoots.get( 0 ).getState() ); assertEquals( 2, projectScmRoots.get( 1 ).getState() ); } @Test public void testGetProjectScmRootByProject() throws Exception { final ProjectGroup projectGroup = new ProjectGroupStub(); projectGroup.setName( "test-group" ); projectGroup.setId( 1 ); final int projectId = 1; final ProjectScmRoot scmRoot = new ProjectScmRoot(); scmRoot.setState( 1 ); scmRoot.setOldState( 3 ); scmRoot.setScmRootAddress( "address1" ); scmRoot.setProjectGroup( projectGroup ); when( continuum.getProjectScmRootByProject( projectId ) ).thenReturn( scmRoot ); org.apache.maven.continuum.xmlrpc.project.ProjectScmRoot projectScmRoot = continuumService.getProjectScmRootByProject( projectId ); assertNotNull( projectScmRoot ); assertEquals( 1, projectScmRoot.getState() ); assertEquals( 3, projectScmRoot.getOldState() ); assertEquals( "address1", projectScmRoot.getScmRootAddress() ); } @Test public void testGetBuildAgentUrl() throws Exception { String expectedUrl = "http://localhost:8181/continuum-buildagent/xmlrpc"; when( continuum.getConfiguration() ).thenReturn( configurationService ); when( configurationService.isDistributedBuildEnabled() ).thenReturn( true ); when( distributedBuildManager.getBuildAgentUrl( 1, 1 ) ).thenReturn( expectedUrl ); String buildAgentUrl = continuumService.getBuildAgentUrl( 1, 1 ); assertEquals( expectedUrl, buildAgentUrl ); } @Test public void testGetBuildAgentUrlNotSupported() throws Exception { when( continuum.getConfiguration() ).thenReturn( configurationService ); when( configurationService.isDistributedBuildEnabled() ).thenReturn( false ); try { continuumService.getBuildAgentUrl( 1, 1 ); fail( "ContinuumException is expected to occur here." ); } catch ( ContinuumException e ) { //pass } } @Test public void testGetNonExistingBuildAgentGroup() throws Exception { String groupName = "Agent Group Name"; when( continuum.getConfiguration() ).thenReturn( configurationService ); when( configurationService.getBuildAgentGroup( groupName ) ).thenReturn( null ); int result = continuumService.removeBuildAgentGroup( groupName ); assertEquals( 0, result ); } @Test public void testRemoveNonExistingBuildAgentGroup() throws Exception { String groupName = "Agent Group Name"; when( continuum.getConfiguration() ).thenReturn( configurationService ); when( configurationService.getBuildAgentGroup( groupName ) ).thenReturn( null ); continuumService.removeBuildAgentGroup( groupName ); verify( configurationService, never() ).removeBuildAgentGroup( any( BuildAgentGroupConfiguration.class ) ); } @Test public void testGetBuildAgentsWithInstallations() throws Exception { final List<org.apache.continuum.configuration.BuildAgentConfiguration> buildAgents = new ArrayList<org.apache.continuum.configuration.BuildAgentConfiguration>(); org.apache.continuum.configuration.BuildAgentConfiguration buildAgent = new org.apache.continuum.configuration.BuildAgentConfiguration(); String buildAgentUrl = "http://localhost:8080/xmlrpc"; buildAgent.setUrl( buildAgentUrl ); buildAgent.setEnabled( true ); buildAgents.add( buildAgent ); org.apache.continuum.configuration.BuildAgentConfiguration buildAgent2 = new org.apache.continuum.configuration.BuildAgentConfiguration(); buildAgent2.setUrl( "http://localhost:8181/xmlrpc" ); buildAgent2.setEnabled( false ); buildAgents.add( buildAgent2 ); final List<org.apache.maven.continuum.model.system.Installation> buildAgentInstallations = new ArrayList<org.apache.maven.continuum.model.system.Installation>(); org.apache.maven.continuum.model.system.Installation buildAgentInstallation = new org.apache.maven.continuum.model.system.Installation(); buildAgentInstallation.setInstallationId( 1 ); buildAgentInstallation.setName( "JDK 6" ); buildAgentInstallation.setType( "jdk" ); buildAgentInstallation.setVarName( "JAVA_HOME" ); buildAgentInstallation.setVarValue( "/opt/java" ); buildAgentInstallations.add( buildAgentInstallation ); when( continuum.getConfiguration() ).thenReturn( configurationService ); when( configurationService.getBuildAgents() ).thenReturn( buildAgents ); when( distributedBuildManager.getBuildAgentPlatform( buildAgentUrl ) ).thenReturn( "Linux" ); when( distributedBuildManager.getAvailableInstallations( buildAgentUrl ) ).thenReturn( buildAgentInstallations ); List<BuildAgentConfiguration> agents = continuumService.getBuildAgentsWithInstallations(); assertEquals( 1, agents.size() ); BuildAgentConfiguration agent = agents.get( 0 ); assertEquals( buildAgentUrl, agent.getUrl() ); assertEquals( "Linux", agent.getPlatform() ); assertEquals( 1, agent.getInstallations().size() ); } @Test public void testAddProjectGroupWithPunctuation() throws Exception { String name = "Test :: Group Name (with punctuation)"; String groupId = "com.example.long-group-id"; String description = "Description"; ProjectGroup group = createProjectGroup( name, groupId, description ); when( continuum.getProjectGroupByGroupId( groupId ) ).thenReturn( group ); ProjectGroupSummary groupSummary = continuumService.addProjectGroup( name, groupId, description ); assertEquals( name, groupSummary.getName() ); assertEquals( groupId, groupSummary.getGroupId() ); assertEquals( description, groupSummary.getDescription() ); verify( continuum ).addProjectGroup( group ); } @Test public void testEditProjectGroupWithPunctuation() throws Exception { int projectGroupId = 1; String origName = "name", origGroupId = "groupId", origDescription = "description"; final String newName = "Test :: Group Name (with punctuation)"; final String newGroupId = "com.example.long-group-id"; final String newDescription = "Description"; List<String> roles = Arrays.asList( "project-administrator", "project-developer", "project-user" ); ProjectGroup unsavedGroup = createProjectGroup( origName, origGroupId, origDescription ); ProjectGroup savedGroup = createProjectGroup( projectGroupId, origName, origGroupId, origDescription ); ProjectGroup editedGroup = createProjectGroup( projectGroupId, newName, newGroupId, newDescription ); when( continuum.getProjectGroupByGroupId( origGroupId ) ).thenReturn( savedGroup ); ProjectGroupSummary groupSummary = continuumService.addProjectGroup( origName, origGroupId, origDescription ); verify( continuum ).addProjectGroup( unsavedGroup ); groupSummary.setName( newName ); groupSummary.setGroupId( newGroupId ); groupSummary.setDescription( newDescription ); when( continuum.getProjectGroupWithProjects( projectGroupId ) ).thenReturn( savedGroup ); when( continuum.getProjectGroup( projectGroupId ) ).thenReturn( savedGroup, savedGroup, editedGroup ); continuumService.updateProjectGroup( groupSummary ); verify( continuum ).updateProjectGroup( editedGroup ); for ( String role : roles ) { verify( roleManager ).updateRole( role, origName, newName ); } } @Test public void testInstallationEnvironmentVariableWithOtherOptions() throws ContinuumException, InstallationException { Installation target = new Installation(); target.setName( "name" ); target.setType( "envvar" ); target.setVarName( "JAVA_OPTS" ); target.setVarValue( "-XX:+CompressedOops" ); org.apache.maven.continuum.model.system.Installation returned = new org.apache.maven.continuum.model.system.Installation(); returned.setName( "name" ); returned.setType( "envvar" ); returned.setVarName( "JAVA_OPTS" ); returned.setVarValue( "-XX:+CompressedOops" ); InstallationService installationService = mock( InstallationService.class ); when( continuum.getInstallationService() ).thenReturn( installationService ); // Need to return a value for the xml mapper when( installationService.add( any( org.apache.maven.continuum.model.system.Installation.class ) ) ).thenReturn( returned ); Installation marshaledResult = continuumService.addInstallation( target ); ArgumentCaptor<org.apache.maven.continuum.model.system.Installation> arg = ArgumentCaptor.forClass( org.apache.maven.continuum.model.system.Installation.class ); verify( installationService ).add( arg.capture() ); // verify properties are correct for added installation org.apache.maven.continuum.model.system.Installation added = arg.getValue(); assertEquals( target.getName(), added.getName() ); assertEquals( target.getType(), added.getType() ); assertEquals( target.getVarName(), added.getVarName() ); assertEquals( target.getVarValue(), added.getVarValue() ); // verify properties for serialized result assertEquals( target.getName(), marshaledResult.getName() ); assertEquals( target.getType(), marshaledResult.getType() ); assertEquals( target.getVarName(), marshaledResult.getVarName() ); assertEquals( target.getVarValue(), marshaledResult.getVarValue() ); } private static ProjectGroup createProjectGroup( String name, String groupId, String description ) { ProjectGroup group = new ProjectGroup(); group.setName( name ); group.setGroupId( groupId ); group.setDescription( description ); return group; } private static ProjectGroup createProjectGroup( int projectGroupId, String name, String groupId, String description ) { ProjectGroup group = createProjectGroup( name, groupId, description ); group.setId( projectGroupId ); return group; } private BuildDefinition createBuildDefinition() { BuildDefinition buildDef = new BuildDefinition(); buildDef.setArguments( "--batch-mode -P!dev" ); buildDef.setBuildFile( "pom.xml" ); buildDef.setType( "maven2" ); buildDef.setBuildFresh( false ); buildDef.setAlwaysBuild( true ); buildDef.setDefaultForProject( true ); buildDef.setGoals( "clean install" ); buildDef.setDescription( "Test Build Definition" ); return buildDef; } private Map<String, Object> getListenerMap() { Map<String, Object> map = new HashMap<String, Object>(); map.put( "release-phases", Arrays.asList( "incomplete-phase" ) ); map.put( "completed-release-phases", Arrays.asList( "completed-phase" ) ); return map; } public class ProjectGroupStub extends ProjectGroup { @Override public List<Project> getProjects() { throw new RuntimeException( "Can't call getProjects as it will throw JDODetachedFieldAccessException" ); } } }
5,174
0
Create_ds/continuum/continuum-xmlrpc/continuum-xmlrpc-server/src/test/java/org/apache/continuum/xmlrpc
Create_ds/continuum/continuum-xmlrpc/continuum-xmlrpc-server/src/test/java/org/apache/continuum/xmlrpc/server/ContinuumServiceImplStub.java
package org.apache.continuum.xmlrpc.server; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.utils.build.BuildTrigger; import org.apache.maven.continuum.ContinuumException; import org.apache.maven.continuum.profile.ProfileException; import org.apache.maven.continuum.xmlrpc.project.BuildDefinition; import org.apache.maven.continuum.xmlrpc.server.ContinuumServiceImpl; import org.codehaus.plexus.redback.authorization.AuthorizationException; public class ContinuumServiceImplStub extends ContinuumServiceImpl { @Override protected boolean isAuthorized( String role, String resource, boolean requiredResource ) throws AuthorizationException { return true; } protected void buildProjectWithBuildDefinition( int projectId, int buildDefinitionId, BuildTrigger buildTrigger ) { // do nothing } public org.apache.maven.continuum.model.project.BuildDefinition getBuildDefinition( BuildDefinition buildDef, org.apache.maven.continuum.model.project.BuildDefinition buildDefinition ) throws ContinuumException { return populateBuildDefinition( buildDef, buildDefinition ); } }
5,175
0
Create_ds/continuum/continuum-xmlrpc/continuum-xmlrpc-server/src/main/java/org/apache/maven/continuum/xmlrpc
Create_ds/continuum/continuum-xmlrpc/continuum-xmlrpc-server/src/main/java/org/apache/maven/continuum/xmlrpc/server/ContinuumXmlRpcMetaDataHandler.java
package org.apache.maven.continuum.xmlrpc.server; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.xmlrpc.XmlRpcException; import org.apache.xmlrpc.XmlRpcHandler; import org.apache.xmlrpc.XmlRpcRequest; import org.apache.xmlrpc.common.TypeConverter; import org.apache.xmlrpc.common.TypeConverterFactory; import org.apache.xmlrpc.common.XmlRpcNotAuthorizedException; import org.apache.xmlrpc.metadata.Util; import org.apache.xmlrpc.server.AbstractReflectiveHandlerMapping; import org.apache.xmlrpc.server.RequestProcessorFactoryFactory; import org.codehaus.plexus.PlexusContainer; import org.codehaus.plexus.component.repository.exception.ComponentLifecycleException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a> */ public class ContinuumXmlRpcMetaDataHandler implements XmlRpcHandler { private static class MethodData { final Method method; final TypeConverter[] typeConverters; MethodData( Method pMethod, TypeConverterFactory pTypeConverterFactory ) { method = pMethod; Class[] paramClasses = method.getParameterTypes(); typeConverters = new TypeConverter[paramClasses.length]; for ( int i = 0; i < paramClasses.length; i++ ) { typeConverters[i] = pTypeConverterFactory.getTypeConverter( paramClasses[i] ); } } } private final AbstractReflectiveHandlerMapping mapping; private final MethodData[] methods; private final Class clazz; private final RequestProcessorFactoryFactory.RequestProcessorFactory requestProcessorFactory; private final String[][] signatures; private final String methodHelp; private final PlexusContainer container; /** * Creates a new instance. * * @param pMapping The mapping, which creates this handler. * @param pClass The class, which has been inspected to create * this handler. Typically, this will be the same as * <pre>pInstance.getClass()</pre>. It is used for diagnostic * messages only. * @param pMethods The method, which will be invoked for * executing the handler. * @param signatures The signature, which will be returned by * {@link #getSignatures()}. * @param methodHelp The help string, which will be returned * by {@link #getMethodHelp()}. * @param container The container that loaded the component */ public ContinuumXmlRpcMetaDataHandler( AbstractReflectiveHandlerMapping pMapping, TypeConverterFactory pTypeConverterFactory, Class pClass, RequestProcessorFactoryFactory.RequestProcessorFactory pFactory, Method[] pMethods, String[][] signatures, String methodHelp, PlexusContainer container ) { mapping = pMapping; clazz = pClass; methods = new MethodData[pMethods.length]; requestProcessorFactory = pFactory; for ( int i = 0; i < methods.length; i++ ) { methods[i] = new MethodData( pMethods[i], pTypeConverterFactory ); } this.signatures = signatures; this.methodHelp = methodHelp; this.container = container; } private Object getInstance( XmlRpcRequest pRequest ) throws XmlRpcException { return requestProcessorFactory.getRequestProcessor( pRequest ); } public Object execute( XmlRpcRequest pRequest ) throws XmlRpcException { AbstractReflectiveHandlerMapping.AuthenticationHandler authHandler = mapping.getAuthenticationHandler(); if ( authHandler != null && !authHandler.isAuthorized( pRequest ) ) { throw new XmlRpcNotAuthorizedException( "Not authorized" ); } Object[] args = new Object[pRequest.getParameterCount()]; for ( int j = 0; j < args.length; j++ ) { args[j] = pRequest.getParameter( j ); } Object instance = getInstance( pRequest ); for ( MethodData methodData : methods ) { TypeConverter[] converters = methodData.typeConverters; if ( args.length == converters.length ) { boolean matching = true; for ( int j = 0; j < args.length; j++ ) { if ( !converters[j].isConvertable( args[j] ) ) { matching = false; break; } } if ( matching ) { for ( int j = 0; j < args.length; j++ ) { args[j] = converters[j].convert( args[j] ); } return invoke( instance, methodData.method, args ); } } } throw new XmlRpcException( "No method matching arguments: " + Util.getSignature( args ) ); } private Object invoke( Object pInstance, Method pMethod, Object[] pArgs ) throws XmlRpcException { try { return pMethod.invoke( pInstance, pArgs ); } catch ( IllegalAccessException e ) { throw new XmlRpcException( "Illegal access to method " + pMethod.getName() + " in class " + clazz.getName(), e ); } catch ( IllegalArgumentException e ) { throw new XmlRpcException( "Illegal argument for method " + pMethod.getName() + " in class " + clazz.getName(), e ); } catch ( InvocationTargetException e ) { Throwable t = e.getTargetException(); if ( t instanceof XmlRpcException ) { throw (XmlRpcException) t; } throw new XmlRpcException( "Failed to invoke method " + pMethod.getName() + " in class " + clazz.getName() + ": " + t.getMessage(), t ); } finally { try { container.release( pInstance ); } catch ( ComponentLifecycleException e ) { //Do nothing } } } public String[][] getSignatures() throws XmlRpcException { return signatures; } public String getMethodHelp() throws XmlRpcException { return methodHelp; } }
5,176
0
Create_ds/continuum/continuum-xmlrpc/continuum-xmlrpc-server/src/main/java/org/apache/maven/continuum/xmlrpc
Create_ds/continuum/continuum-xmlrpc/continuum-xmlrpc-server/src/main/java/org/apache/maven/continuum/xmlrpc/server/ContinuumXmlRpcServletServer.java
package org.apache.maven.continuum.xmlrpc.server; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.xmlrpc.common.XmlRpcHttpRequestConfigImpl; import org.apache.xmlrpc.webserver.XmlRpcServletServer; import javax.servlet.http.HttpServletRequest; /** * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a> */ public class ContinuumXmlRpcServletServer extends XmlRpcServletServer { protected XmlRpcHttpRequestConfigImpl newConfig( HttpServletRequest request ) { ContinuumXmlRpcConfig config = new ContinuumXmlRpcConfig(); config.setHttpServletRequest( request ); return config; } }
5,177
0
Create_ds/continuum/continuum-xmlrpc/continuum-xmlrpc-server/src/main/java/org/apache/maven/continuum/xmlrpc
Create_ds/continuum/continuum-xmlrpc/continuum-xmlrpc-server/src/main/java/org/apache/maven/continuum/xmlrpc/server/ContinuumXmlRpcServlet.java
package org.apache.maven.continuum.xmlrpc.server; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.xmlrpc.XmlRpcException; import org.apache.xmlrpc.XmlRpcRequest; import org.apache.xmlrpc.server.AbstractReflectiveHandlerMapping; import org.apache.xmlrpc.server.PropertyHandlerMapping; import org.apache.xmlrpc.server.RequestProcessorFactoryFactory; import org.apache.xmlrpc.server.XmlRpcServerConfigImpl; import org.codehaus.plexus.DefaultPlexusContainer; import org.codehaus.plexus.PlexusConstants; import org.codehaus.plexus.PlexusContainer; import org.codehaus.plexus.PlexusContainerException; import org.codehaus.plexus.classworlds.ClassWorld; import org.codehaus.plexus.component.repository.exception.ComponentLifecycleException; import org.codehaus.plexus.component.repository.exception.ComponentLookupException; import org.codehaus.plexus.redback.authentication.AuthenticationException; import org.codehaus.plexus.redback.authentication.PasswordBasedAuthenticationDataSource; import org.codehaus.plexus.redback.policy.PolicyViolationException; import org.codehaus.plexus.redback.system.DefaultSecuritySession; import org.codehaus.plexus.redback.system.SecuritySystem; import org.codehaus.plexus.redback.users.UserNotFoundException; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a> */ public class ContinuumXmlRpcServlet extends HttpServlet { private ContinuumXmlRpcServletServer server; private SecuritySystem securitySystem; public String getServletInfo() { return "Continuum XMLRPC Servlet"; } public void destroy() { if ( server != null ) { try { getPlexusContainer().release( server ); } catch ( ServletException e ) { log( "Unable to release XmlRpcServletServer.", e ); } catch ( ComponentLifecycleException e ) { log( "Unable to release XmlRpcServletServer.", e ); } } } public void init( ServletConfig servletConfig ) throws ServletException { super.init( servletConfig ); ensureContainerSet( servletConfig ); initServer(); } public void initServer() throws ServletException { server = new ContinuumXmlRpcServletServer(); try { securitySystem = (SecuritySystem) getPlexusContainer().lookup( SecuritySystem.ROLE ); } catch ( ComponentLookupException e ) { throw new ServletException( "Can't init the xml rpc server, unable to obtain security system", e ); } try { XmlRpcServerConfigImpl cfg = (XmlRpcServerConfigImpl) server.getConfig(); cfg.setEnabledForExtensions( true ); PropertiesHandlerMapping mapping = (PropertiesHandlerMapping) lookup( PropertyHandlerMapping.class.getName() ); mapping.setRequestProcessorFactoryFactory( (RequestProcessorFactoryFactory) lookup( RequestProcessorFactoryFactory.class.getName() ) ); mapping.load(); mapping.setAuthenticationHandler( getAuthenticationHandler() ); server.setHandlerMapping( mapping ); } catch ( XmlRpcException e ) { throw new ServletException( "Can't init the xml rpc server", e ); } } private AbstractReflectiveHandlerMapping.AuthenticationHandler getAuthenticationHandler() { return new AbstractReflectiveHandlerMapping.AuthenticationHandler() { public boolean isAuthorized( XmlRpcRequest pRequest ) { if ( pRequest.getConfig() instanceof ContinuumXmlRpcConfig ) { ContinuumXmlRpcConfig config = (ContinuumXmlRpcConfig) pRequest.getConfig(); try { // if username is null, then treat this as a guest user with an empty security session if ( config.getBasicUserName() == null ) { config.setSecuritySession( new DefaultSecuritySession() ); return true; } else { // otherwise treat this as an authn required session, and if the credentials are invalid // do not default to guest privileges PasswordBasedAuthenticationDataSource authdatasource = new PasswordBasedAuthenticationDataSource(); authdatasource.setPrincipal( config.getBasicUserName() ); authdatasource.setPassword( config.getBasicPassword() ); config.setSecuritySession( securitySystem.authenticate( authdatasource ) ); return config.getSecuritySession().isAuthenticated(); } } catch ( AuthenticationException e ) { e.printStackTrace(); return false; } catch ( PolicyViolationException e ) { e.printStackTrace(); return false; } catch ( UserNotFoundException e ) { e.printStackTrace(); return false; } } else { System.out.println( "unknown xml rpc configiration object found..." ); return false; } } }; } public void doPost( HttpServletRequest pRequest, HttpServletResponse pResponse ) throws IOException, ServletException { server.execute( pRequest, pResponse ); } private void ensureContainerSet( ServletConfig sc ) throws ServletException { // TODO: unify this code with the lifecycle listener and application server ServletContext context = sc.getServletContext(); // Container not found. if ( context.getAttribute( PlexusConstants.PLEXUS_KEY ) != null ) { context.log( "Plexus container already in context." ); return; } // Create container. Map keys = new HashMap(); PlexusContainer pc; try { pc = new DefaultPlexusContainer( "default", keys, "META-INF/plexus/application.xml", new ClassWorld( "plexus.core", getClass().getClassLoader() ) ); context.setAttribute( PlexusConstants.PLEXUS_KEY, pc ); } catch ( PlexusContainerException e ) { throw new ServletException( "Unable to initialize Plexus Container.", e ); } } private PlexusContainer getPlexusContainer() throws ServletException { PlexusContainer container = (PlexusContainer) getServletContext().getAttribute( PlexusConstants.PLEXUS_KEY ); if ( container == null ) { throw new ServletException( "Unable to find plexus container." ); } return container; } public Object lookup( String role ) throws ServletException { try { return getPlexusContainer().lookup( role ); } catch ( ComponentLookupException e ) { throw new ServletException( "Unable to lookup role [" + role + "]", e ); } } public Object lookup( String role, String hint ) throws ServletException { try { return getPlexusContainer().lookup( role, hint ); } catch ( ComponentLookupException e ) { throw new ServletException( "Unable to lookup role [" + role + "] hint [" + hint + "]", e ); } } }
5,178
0
Create_ds/continuum/continuum-xmlrpc/continuum-xmlrpc-server/src/main/java/org/apache/maven/continuum/xmlrpc
Create_ds/continuum/continuum-xmlrpc/continuum-xmlrpc-server/src/main/java/org/apache/maven/continuum/xmlrpc/server/ContinuumServiceImpl.java
package org.apache.maven.continuum.xmlrpc.server; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import net.sf.dozer.util.mapping.DozerBeanMapperSingletonWrapper; import net.sf.dozer.util.mapping.MapperIF; import org.apache.commons.lang.StringEscapeUtils; import org.apache.commons.lang.StringUtils; import org.apache.continuum.buildagent.NoBuildAgentException; import org.apache.continuum.buildagent.NoBuildAgentInGroupException; import org.apache.continuum.builder.distributed.manager.DistributedBuildManager; import org.apache.continuum.buildmanager.BuildManagerException; import org.apache.continuum.buildmanager.BuildsManager; import org.apache.continuum.configuration.BuildAgentConfigurationException; import org.apache.continuum.configuration.ContinuumConfigurationException; import org.apache.continuum.dao.SystemConfigurationDao; import org.apache.continuum.purge.ContinuumPurgeManagerException; import org.apache.continuum.purge.PurgeConfigurationServiceException; import org.apache.continuum.repository.RepositoryServiceException; import org.apache.continuum.release.utils.ReleaseHelper; import org.apache.continuum.utils.m2.LocalRepositoryHelper; import org.apache.continuum.xmlrpc.release.ContinuumReleaseResult; import org.apache.continuum.xmlrpc.repository.DirectoryPurgeConfiguration; import org.apache.continuum.xmlrpc.repository.LocalRepository; import org.apache.continuum.xmlrpc.repository.RepositoryPurgeConfiguration; import org.apache.continuum.xmlrpc.utils.BuildTrigger; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.continuum.Continuum; import org.apache.maven.continuum.ContinuumException; import org.apache.maven.continuum.builddefinition.BuildDefinitionServiceException; import org.apache.maven.continuum.configuration.ConfigurationException; import org.apache.maven.continuum.configuration.ConfigurationService; import org.apache.maven.continuum.configuration.ConfigurationStoringException; import org.apache.maven.continuum.execution.ContinuumBuildExecutorConstants; import org.apache.maven.continuum.installation.InstallationException; import org.apache.maven.continuum.installation.InstallationService; import org.apache.maven.continuum.project.ContinuumProjectState; import org.apache.maven.continuum.project.builder.ContinuumProjectBuildingResult; import org.apache.maven.continuum.security.ContinuumRoleConstants; import org.apache.maven.continuum.store.ContinuumStoreException; import org.apache.maven.continuum.xmlrpc.project.AddingResult; import org.apache.maven.continuum.xmlrpc.project.BuildAgentConfiguration; import org.apache.maven.continuum.xmlrpc.project.BuildAgentGroupConfiguration; import org.apache.maven.continuum.xmlrpc.project.BuildDefinition; import org.apache.maven.continuum.xmlrpc.project.BuildDefinitionTemplate; import org.apache.maven.continuum.xmlrpc.project.BuildProjectTask; import org.apache.maven.continuum.xmlrpc.project.BuildResult; import org.apache.maven.continuum.xmlrpc.project.BuildResultSummary; import org.apache.maven.continuum.xmlrpc.project.Project; import org.apache.maven.continuum.xmlrpc.project.ProjectGroup; import org.apache.maven.continuum.xmlrpc.project.ProjectGroupSummary; import org.apache.maven.continuum.xmlrpc.project.ProjectNotifier; import org.apache.maven.continuum.xmlrpc.project.ProjectScmRoot; import org.apache.maven.continuum.xmlrpc.project.ProjectSummary; import org.apache.maven.continuum.xmlrpc.project.ReleaseListenerSummary; import org.apache.maven.continuum.xmlrpc.project.Schedule; import org.apache.maven.continuum.xmlrpc.system.Installation; import org.apache.maven.continuum.xmlrpc.system.Profile; import org.apache.maven.continuum.xmlrpc.system.SystemConfiguration; import org.apache.maven.scm.provider.svn.repository.SvnScmProviderRepository; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.redback.authorization.AuthorizationException; import org.codehaus.plexus.redback.role.RoleManager; import org.codehaus.plexus.redback.role.RoleManagerException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; /** * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a> */ @Component( role = org.apache.maven.continuum.xmlrpc.server.ContinuumXmlRpcComponent.class, hint = "org.apache.maven.continuum.xmlrpc.ContinuumService" ) public class ContinuumServiceImpl extends AbstractContinuumSecureService { private static final String NAME_VALID_EXPRESSION = "[A-Za-z0-9_.\\s\\-():\\/,]*"; private static final String DIRECTORY_VALID_EXPRESSION = "[A-Za-z0-9_/\\s:.\\\\-]*"; private static final String URL_VALID_EXPRESSION = "[A-Za-z0-9_.@:/-]*"; private static final String PROJECT_VERSION_VALID_EXPRESSION = "[a-zA-Z0-9.-]*"; private static final String PROJECT_SCM_URL_VALID_EXPRESSION = "[a-zA-Z0-9_.:${}#~=@\\/|\\[\\]-]*"; private static final String PROJECT_SCM_TAG_VALID_EXPRESSION = "[a-zA-Z0-9_.:@\\/|#~=\\[\\]-]*"; private static final String PROJECT_ARTIFACT_ID_VALID_EXPRESSION = "[A-Za-z0-9\\-]*"; private static final String PROJECT_EXECUTOR_OR_BUILDDEF_TYPE_VALID_EXPRESSION = "maven2|maven-1|ant|shell"; private static final String SCHEDULE_CRON_VALID_EXPRESSION = "[A-Z0-9\\s*/,-?#]*"; private static final String PROJECTGROUP_ID_VALID_EXPRESSION = "[a-zA-Z0-9_.\\s\\-]*"; private static final String REPOSITORY_LAYOUT_VALID_EXPRESSION = "default|legacy"; private static final String BUILD_DEFINITION_ARGUMENTS_VALID_EXPRESSION = "[!A-Za-z0-9_./=,${}\":\\s\\\\-]*"; private static final String BUILD_DEFINITION_GOALS_VALID_EXPRESSION = "[A-Za-z0-9_:\\s\\-]*"; private static final String BUILD_DEFINITION_BUILD_FILE_VALID_EXPRESSION = "[A-Za-z0-9_.\\-/\\\\]*"; private static final String INSTALLATION_VARNAME_VALID_EXPRESSION = "[A-Za-z][A-Za-z0-9_]*"; private static final String INSTALLATION_VARVALUE_VALID_EXPRESSION = "(?:[~A-Za-z0-9_.:=${}\\\\/\\-+]|\\s|[()])*"; private static final String INSTALLATION_TYPE_VALID_EXPRESSION = "jdk|maven2|maven1|ant|envvar"; private static final String DIRECTORY_TYPE_VALID_EXPRESSION = "releases|buildOutput"; private static final String NOTIFIER_TYPE_VALID_EXPRESSION = "irc|jabber|msn|mail|wagon"; private static final String USERNAME_VALID_EXPRESSION = "[a-zA-Z_0-9\\-.@]*"; private static final MapperIF mapper = DozerBeanMapperSingletonWrapper.getInstance(); private final Logger logger = LoggerFactory.getLogger( ContinuumServiceImpl.class ); @Requirement private Continuum continuum; @Requirement private SystemConfigurationDao systemConfigurationDao; @Requirement( hint = "default" ) private RoleManager roleManager; @Requirement( hint = "parallel" ) private BuildsManager parallelBuildsManager; @Requirement private DistributedBuildManager distributedBuildManager; @Requirement private ReleaseHelper releaseHelper; @Requirement private LocalRepositoryHelper localRepositoryHelper; public boolean ping() throws ContinuumException { return true; } // ---------------------------------------------------------------------- // Projects // ---------------------------------------------------------------------- public List<ProjectSummary> getProjects( int projectGroupId ) throws ContinuumException { checkViewProjectGroupAuthorization( getProjectGroupName( projectGroupId ) ); List<ProjectSummary> projectsList = new ArrayList<ProjectSummary>(); Collection<org.apache.maven.continuum.model.project.Project> projects = continuum.getProjectsInGroup( projectGroupId ); if ( projects != null ) { for ( org.apache.maven.continuum.model.project.Project project : projects ) { ProjectSummary ps = populateProjectSummary( project ); projectsList.add( ps ); } } return projectsList; } public ProjectSummary getProjectSummary( int projectId ) throws ContinuumException { org.apache.maven.continuum.model.project.Project project = continuum.getProject( projectId ); checkViewProjectGroupAuthorization( project.getProjectGroup().getName() ); return populateProjectSummary( project ); } public Project getProjectWithAllDetails( int projectId ) throws ContinuumException { org.apache.maven.continuum.model.project.Project project = continuum.getProjectWithAllDetails( projectId ); checkViewProjectGroupAuthorization( project.getProjectGroup().getName() ); return populateProject( project ); } public int removeProject( int projectId ) throws ContinuumException { ProjectSummary ps = getProjectSummary( projectId ); checkRemoveProjectFromGroupAuthorization( ps.getProjectGroup().getName() ); continuum.removeProject( projectId ); return 0; } public ProjectSummary updateProject( ProjectSummary project ) throws ContinuumException { if ( StringUtils.isNotBlank( project.getName() ) && !project.getName().matches( NAME_VALID_EXPRESSION ) ) //!GenericValidator.matchRegexp( project.getName(), NAME_VALID_EXPRESSION ) ) { throw new ContinuumException( "Project Name contains invalid characters" ); } if ( StringUtils.isNotBlank( project.getScmTag() ) && !project.getScmTag().matches( PROJECT_SCM_TAG_VALID_EXPRESSION ) ) { throw new ContinuumException( "Project Scm Tag contains invalid characters" ); } if ( StringUtils.isNotBlank( project.getScmUrl() ) && !project.getScmUrl().matches( PROJECT_SCM_URL_VALID_EXPRESSION ) ) { throw new ContinuumException( "Project Scm Url contains invalid characters" ); } if ( StringUtils.isNotBlank( project.getVersion() ) && !project.getVersion().matches( PROJECT_VERSION_VALID_EXPRESSION ) ) { throw new ContinuumException( "Project Version contains invalid characters" ); } ProjectSummary ps = getProjectSummary( project.getId() ); checkRemoveProjectFromGroupAuthorization( ps.getProjectGroup().getName() ); org.apache.maven.continuum.model.project.Project p = continuum.getProject( project.getId() ); p.setName( project.getName() ); p.setVersion( project.getVersion() ); p.setScmUrl( project.getScmUrl() ); p.setScmUseCache( project.isScmUseCache() ); p.setScmUsername( project.getScmUsername() ); p.setScmPassword( project.getScmPassword() ); p.setScmTag( project.getScmTag() ); continuum.updateProject( p ); return getProjectSummary( project.getId() ); } // ---------------------------------------------------------------------- // Projects Groups // ---------------------------------------------------------------------- public List<ProjectGroupSummary> getAllProjectGroups() throws ContinuumException { Collection<org.apache.maven.continuum.model.project.ProjectGroup> pgList = continuum.getAllProjectGroups(); List<ProjectGroupSummary> result = new ArrayList<ProjectGroupSummary>(); for ( org.apache.maven.continuum.model.project.ProjectGroup projectGroup : pgList ) { try { if ( isAuthorized( ContinuumRoleConstants.CONTINUUM_VIEW_GROUP_OPERATION, projectGroup.getName() ) ) { result.add( populateProjectGroupSummary( projectGroup ) ); } } catch ( AuthorizationException e ) { throw new ContinuumException( "error authorizing request." ); } } return result; } public ProjectGroup getProjectGroup( int projectGroupId ) throws ContinuumException { ProjectGroup result = null; org.apache.maven.continuum.model.project.ProjectGroup projectGroup = continuum.getProjectGroup( projectGroupId ); try { if ( isAuthorized( ContinuumRoleConstants.CONTINUUM_VIEW_GROUP_OPERATION, projectGroup.getName() ) ) { result = populateProjectGroupWithAllDetails( projectGroup ); } } catch ( AuthorizationException e ) { throw new ContinuumException( "error authorizing request." ); } return result; } public List<ProjectGroup> getAllProjectGroupsWithAllDetails() throws ContinuumException { Collection<org.apache.maven.continuum.model.project.ProjectGroup> pgList = continuum.getAllProjectGroupsWithBuildDetails(); List<ProjectGroup> result = new ArrayList<ProjectGroup>(); for ( org.apache.maven.continuum.model.project.ProjectGroup projectGroup : pgList ) { try { if ( isAuthorized( ContinuumRoleConstants.CONTINUUM_VIEW_GROUP_OPERATION, projectGroup.getName() ) ) { result.add( populateProjectGroupWithAllDetails( projectGroup ) ); } } catch ( AuthorizationException e ) { throw new ContinuumException( "error authorizing request." ); } } return result; } public List<ProjectGroup> getAllProjectGroupsWithProjects() throws ContinuumException { return getAllProjectGroupsWithAllDetails(); } protected String getProjectGroupName( int projectGroupId ) throws ContinuumException { ProjectGroupSummary pgs = getPGSummary( projectGroupId ); return pgs.getName(); } private ProjectGroupSummary getPGSummary( int projectGroupId ) throws ContinuumException { org.apache.maven.continuum.model.project.ProjectGroup projectGroup = continuum.getProjectGroup( projectGroupId ); checkViewProjectGroupAuthorization( projectGroup.getName() ); return populateProjectGroupSummary( projectGroup ); } public ProjectGroupSummary getProjectGroupSummary( int projectGroupId ) throws ContinuumException { checkViewProjectGroupAuthorization( getProjectGroupName( projectGroupId ) ); org.apache.maven.continuum.model.project.ProjectGroup projectGroup = continuum.getProjectGroup( projectGroupId ); return populateProjectGroupSummary( projectGroup ); } public ProjectGroup getProjectGroupWithProjects( int projectGroupId ) throws ContinuumException { checkViewProjectGroupAuthorization( getProjectGroupName( projectGroupId ) ); org.apache.maven.continuum.model.project.ProjectGroup projectGroup = continuum.getProjectGroupWithProjects( projectGroupId ); return populateProjectGroupWithAllDetails( projectGroup ); } public int removeProjectGroup( int projectGroupId ) throws ContinuumException { checkRemoveProjectGroupAuthorization( getProjectGroupName( projectGroupId ) ); continuum.removeProjectGroup( projectGroupId ); return 0; } public ProjectGroupSummary updateProjectGroup( ProjectGroupSummary projectGroup ) throws ContinuumException { if ( projectGroup == null ) { return null; } checkModifyProjectGroupAuthorization( getProjectGroupName( projectGroup.getId() ) ); if ( StringUtils.isEmpty( projectGroup.getName() ) ) { throw new ContinuumException( "project group name is required" ); } else if ( StringUtils.isEmpty( projectGroup.getName().trim() ) ) { throw new ContinuumException( "project group name can't be spaces" ); } if ( !projectGroup.getName().matches( NAME_VALID_EXPRESSION ) ) { throw new ContinuumException( "ProjectGroup Name contains invalid characters" ); } org.apache.maven.continuum.model.project.ProjectGroup pg = continuum.getProjectGroupWithProjects( projectGroup.getId() ); // need to administer roles since they are based off of this // todo convert everything like to work off of string keys if ( !projectGroup.getName().equals( pg.getName() ) ) { try { roleManager.updateRole( "project-administrator", pg.getName(), projectGroup.getName() ); roleManager.updateRole( "project-developer", pg.getName(), projectGroup.getName() ); roleManager.updateRole( "project-user", pg.getName(), projectGroup.getName() ); pg.setName( projectGroup.getName() ); } catch ( RoleManagerException e ) { throw new ContinuumException( "unable to rename the project group", e ); } } pg.setDescription( StringEscapeUtils.escapeXml( projectGroup.getDescription() ) ); org.apache.continuum.model.repository.LocalRepository repo = new org.apache.continuum.model.repository.LocalRepository(); pg.setLocalRepository( populateLocalRepository( projectGroup.getLocalRepository(), repo ) ); continuum.updateProjectGroup( pg ); return getProjectGroupSummary( projectGroup.getId() ); } public ProjectGroupSummary addProjectGroup( String groupName, String groupId, String description ) throws Exception { if ( StringUtils.isNotBlank( groupId ) && !groupId.matches( PROJECTGROUP_ID_VALID_EXPRESSION ) ) { throw new ContinuumException( "ProjectGroup Id contains invalid characters" ); } if ( StringUtils.isNotBlank( groupName ) && !groupName.matches( NAME_VALID_EXPRESSION ) ) { throw new ContinuumException( "ProjectGroup Name contains invalid characters" ); } org.apache.maven.continuum.model.project.ProjectGroup pg = new org.apache.maven.continuum.model.project.ProjectGroup(); pg.setName( groupName ); pg.setGroupId( groupId ); pg.setDescription( StringEscapeUtils.escapeXml( description ) ); continuum.addProjectGroup( pg ); return populateProjectGroupSummary( continuum.getProjectGroupByGroupId( groupId ) ); } public ProjectNotifier getNotifier( int projectid, int notifierId ) throws ContinuumException { return populateProjectNotifier( continuum.getNotifier( projectid, notifierId ) ); } public ProjectNotifier updateNotifier( int projectid, ProjectNotifier newNotifier ) throws ContinuumException { if ( StringUtils.isNotBlank( newNotifier.getType() ) && !newNotifier.getType().matches( NOTIFIER_TYPE_VALID_EXPRESSION ) ) { throw new ContinuumException( "Notifier Type can only be 'irc, jabber, msn, mail or wagon" ); } org.apache.maven.continuum.model.project.ProjectNotifier notifier = continuum.getNotifier( projectid, newNotifier.getId() ); notifier.setConfiguration( newNotifier.getConfiguration() ); notifier.setFrom( newNotifier.getFrom() ); notifier.setRecipientType( newNotifier.getRecipientType() ); notifier.setType( newNotifier.getType() ); notifier.setEnabled( newNotifier.isEnabled() ); notifier.setSendOnError( newNotifier.isSendOnError() ); notifier.setSendOnFailure( newNotifier.isSendOnFailure() ); notifier.setSendOnSuccess( newNotifier.isSendOnSuccess() ); notifier.setSendOnWarning( newNotifier.isSendOnWarning() ); return populateProjectNotifier( continuum.updateNotifier( projectid, notifier ) ); } public ProjectNotifier addNotifier( int projectid, ProjectNotifier newNotifier ) throws ContinuumException { if ( StringUtils.isNotBlank( newNotifier.getType() ) && !newNotifier.getType().matches( NOTIFIER_TYPE_VALID_EXPRESSION ) ) { throw new ContinuumException( "Notifier Type can only be 'irc, jabber, msn, mail or wagon'" ); } org.apache.maven.continuum.model.project.ProjectNotifier notifier = new org.apache.maven.continuum.model.project.ProjectNotifier(); notifier.setConfiguration( newNotifier.getConfiguration() ); notifier.setFrom( newNotifier.getFrom() ); notifier.setRecipientType( newNotifier.getRecipientType() ); notifier.setType( newNotifier.getType() ); notifier.setEnabled( newNotifier.isEnabled() ); notifier.setSendOnError( newNotifier.isSendOnError() ); notifier.setSendOnFailure( newNotifier.isSendOnFailure() ); notifier.setSendOnSuccess( newNotifier.isSendOnSuccess() ); notifier.setSendOnWarning( newNotifier.isSendOnWarning() ); return populateProjectNotifier( continuum.addNotifier( projectid, notifier ) ); } public int removeNotifier( int projectid, int notifierId ) throws ContinuumException { continuum.removeNotifier( projectid, notifierId ); return 0; } public ProjectNotifier getGroupNotifier( int projectgroupid, int notifierId ) throws ContinuumException { return populateProjectNotifier( continuum.getGroupNotifier( projectgroupid, notifierId ) ); } public ProjectNotifier updateGroupNotifier( int projectgroupid, ProjectNotifier newNotifier ) throws ContinuumException { if ( StringUtils.isNotBlank( newNotifier.getType() ) && !newNotifier.getType().matches( NOTIFIER_TYPE_VALID_EXPRESSION ) ) { throw new ContinuumException( "Notifier Type can only be 'irc, jabber, msn, mail, or wagon" ); } org.apache.maven.continuum.model.project.ProjectNotifier notifier = continuum.getGroupNotifier( projectgroupid, newNotifier.getId() ); notifier.setConfiguration( newNotifier.getConfiguration() ); notifier.setFrom( newNotifier.getFrom() ); notifier.setRecipientType( newNotifier.getRecipientType() ); notifier.setType( newNotifier.getType() ); notifier.setEnabled( newNotifier.isEnabled() ); notifier.setSendOnError( newNotifier.isSendOnError() ); notifier.setSendOnFailure( newNotifier.isSendOnFailure() ); notifier.setSendOnSuccess( newNotifier.isSendOnSuccess() ); notifier.setSendOnWarning( newNotifier.isSendOnWarning() ); return populateProjectNotifier( continuum.updateGroupNotifier( projectgroupid, notifier ) ); } public ProjectNotifier addGroupNotifier( int projectgroupid, ProjectNotifier newNotifier ) throws ContinuumException { org.apache.maven.continuum.model.project.ProjectNotifier notifier = new org.apache.maven.continuum.model.project.ProjectNotifier(); if ( StringUtils.isNotBlank( newNotifier.getType() ) && !newNotifier.getType().matches( NOTIFIER_TYPE_VALID_EXPRESSION ) ) { throw new ContinuumException( "Notifier Type can only be 'irc, jabber, msn, mail or wagon" ); } notifier.setConfiguration( newNotifier.getConfiguration() ); notifier.setFrom( newNotifier.getFrom() ); notifier.setRecipientType( newNotifier.getRecipientType() ); notifier.setType( newNotifier.getType() ); notifier.setEnabled( newNotifier.isEnabled() ); notifier.setSendOnError( newNotifier.isSendOnError() ); notifier.setSendOnFailure( newNotifier.isSendOnFailure() ); notifier.setSendOnSuccess( newNotifier.isSendOnSuccess() ); notifier.setSendOnWarning( newNotifier.isSendOnWarning() ); return populateProjectNotifier( continuum.addGroupNotifier( projectgroupid, notifier ) ); } public int removeGroupNotifier( int projectgroupid, int notifierId ) throws ContinuumException { continuum.removeGroupNotifier( projectgroupid, notifierId ); return 0; } // ---------------------------------------------------------------------- // Build Definitions // ---------------------------------------------------------------------- public List<BuildDefinition> getBuildDefinitionsForProject( int projectId ) throws ContinuumException { ProjectSummary ps = getProjectSummary( projectId ); checkViewProjectGroupAuthorization( ps.getProjectGroup().getName() ); List<org.apache.maven.continuum.model.project.BuildDefinition> bds = continuum.getBuildDefinitionsForProject( projectId ); List<BuildDefinition> result = new ArrayList<BuildDefinition>(); for ( org.apache.maven.continuum.model.project.BuildDefinition bd : bds ) { result.add( populateBuildDefinition( bd ) ); } return result; } public List<BuildDefinition> getBuildDefinitionsForProjectGroup( int projectGroupId ) throws ContinuumException { checkViewProjectGroupAuthorization( getProjectGroupName( projectGroupId ) ); List<org.apache.maven.continuum.model.project.BuildDefinition> bds = continuum.getBuildDefinitionsForProjectGroup( projectGroupId ); List<BuildDefinition> result = new ArrayList<BuildDefinition>(); for ( org.apache.maven.continuum.model.project.BuildDefinition bd : bds ) { result.add( populateBuildDefinition( bd ) ); } return result; } public BuildDefinition getBuildDefinition( int buildDefinitionId ) throws Exception { org.apache.maven.continuum.model.project.BuildDefinition bd = continuum.getBuildDefinition( buildDefinitionId ); return populateBuildDefinition( bd ); } public int removeBuildDefinitionFromProjectGroup( int projectGroupId, int buildDefinitionId ) throws ContinuumException { checkRemoveGroupBuildDefinitionAuthorization( getProjectGroupName( projectGroupId ) ); continuum.removeBuildDefinitionFromProjectGroup( projectGroupId, buildDefinitionId ); return 0; } public BuildDefinition updateBuildDefinitionForProject( int projectId, BuildDefinition buildDef ) throws ContinuumException { ProjectSummary ps = getProjectSummary( projectId ); checkModifyProjectBuildDefinitionAuthorization( ps.getProjectGroup().getName() ); org.apache.maven.continuum.model.project.BuildDefinition newbd = continuum.getBuildDefinition( buildDef.getId() ); org.apache.maven.continuum.model.project.BuildDefinition bd = populateBuildDefinition( buildDef, newbd ); bd = continuum.updateBuildDefinitionForProject( projectId, bd ); return populateBuildDefinition( bd ); } public BuildDefinition updateBuildDefinitionForProjectGroup( int projectGroupId, BuildDefinition buildDef ) throws ContinuumException { checkModifyGroupBuildDefinitionAuthorization( getProjectGroupName( projectGroupId ) ); org.apache.maven.continuum.model.project.BuildDefinition newbd = continuum.getBuildDefinition( buildDef.getId() ); org.apache.maven.continuum.model.project.BuildDefinition bd = populateBuildDefinition( buildDef, newbd ); bd = continuum.updateBuildDefinitionForProjectGroup( projectGroupId, bd ); return populateBuildDefinition( bd ); } public BuildDefinition addBuildDefinitionToProject( int projectId, BuildDefinition buildDef ) throws ContinuumException { checkAddProjectBuildDefinitionAuthorization( getProjectSummary( projectId ).getProjectGroup().getName() ); if ( buildDef.getSchedule() == null ) { throw new ContinuumException( "The schedule can't be null." ); } org.apache.maven.continuum.model.project.BuildDefinition newbd = new org.apache.maven.continuum.model.project.BuildDefinition(); org.apache.maven.continuum.model.project.BuildDefinition bd = populateBuildDefinition( buildDef, newbd ); bd = continuum.addBuildDefinitionToProject( projectId, bd ); return populateBuildDefinition( bd ); } public BuildDefinition addBuildDefinitionToProjectGroup( int projectGroupId, BuildDefinition buildDef ) throws ContinuumException { checkAddGroupBuildDefinitionAuthorization( getPGSummary( projectGroupId ).getName() ); if ( buildDef.getSchedule() == null ) { throw new ContinuumException( "The schedule can't be null." ); } org.apache.maven.continuum.model.project.BuildDefinition newbd = new org.apache.maven.continuum.model.project.BuildDefinition(); org.apache.maven.continuum.model.project.BuildDefinition bd = populateBuildDefinition( buildDef, newbd ); bd = continuum.addBuildDefinitionToProjectGroup( projectGroupId, bd ); return populateBuildDefinition( bd ); } public List<BuildDefinitionTemplate> getBuildDefinitionTemplates() throws Exception { checkManageBuildDefinitionTemplatesAuthorization(); List<org.apache.maven.continuum.model.project.BuildDefinitionTemplate> bdts = continuum.getBuildDefinitionService().getAllBuildDefinitionTemplate(); List<BuildDefinitionTemplate> result = new ArrayList<BuildDefinitionTemplate>(); for ( org.apache.maven.continuum.model.project.BuildDefinitionTemplate bdt : bdts ) { result.add( populateBuildDefinitionTemplate( bdt ) ); } return result; } // ---------------------------------------------------------------------- // Building // ---------------------------------------------------------------------- // TODO: delete this since it does exactly the same as buildProject( int projectId ) public int addProjectToBuildQueue( int projectId ) throws ContinuumException, NoBuildAgentException, NoBuildAgentInGroupException { ProjectSummary ps = getProjectSummary( projectId ); checkBuildProjectInGroupAuthorization( ps.getProjectGroup().getName() ); continuum.buildProject( projectId, new org.apache.continuum.utils.build.BuildTrigger( ContinuumProjectState.TRIGGER_SCHEDULED, "" ) ); return 0; } // Alternative to buildProject since that forces TRIGGER_FORCED public int addProjectToBuildQueue( int projectId, int buildDefinitionId ) throws ContinuumException, NoBuildAgentException, NoBuildAgentInGroupException { ProjectSummary ps = getProjectSummary( projectId ); checkBuildProjectInGroupAuthorization( ps.getProjectGroup().getName() ); continuum.buildProject( projectId, buildDefinitionId, new org.apache.continuum.utils.build.BuildTrigger( ContinuumProjectState.TRIGGER_SCHEDULED, "" ) ); return 0; } public int buildProject( int projectId ) throws ContinuumException, NoBuildAgentException, NoBuildAgentInGroupException { ProjectSummary ps = getProjectSummary( projectId ); checkBuildProjectInGroupAuthorization( ps.getProjectGroup().getName() ); continuum.buildProject( projectId, new org.apache.continuum.utils.build.BuildTrigger( ContinuumProjectState.TRIGGER_SCHEDULED, "" ) ); return 0; } public int buildProject( int projectId, int buildDefinitionId ) throws ContinuumException, NoBuildAgentException, NoBuildAgentInGroupException { ProjectSummary ps = getProjectSummary( projectId ); checkBuildProjectInGroupAuthorization( ps.getProjectGroup().getName() ); buildProjectWithBuildDefinition( projectId, buildDefinitionId, new org.apache.continuum.utils.build.BuildTrigger( ContinuumProjectState.TRIGGER_SCHEDULED, "" ) ); return 0; } public int buildProject( int projectId, BuildTrigger xmlrpcBuildTrigger ) throws ContinuumException, NoBuildAgentException, NoBuildAgentInGroupException { ProjectSummary ps = getProjectSummary( projectId ); checkBuildProjectInGroupAuthorization( ps.getProjectGroup().getName() ); org.apache.continuum.utils.build.BuildTrigger buildTrigger = populateBuildTrigger( xmlrpcBuildTrigger ); continuum.buildProject( projectId, buildTrigger ); return 0; } public int buildProject( int projectId, int buildDefinitionId, BuildTrigger xmlrpcBuildTrigger ) throws ContinuumException, NoBuildAgentException, NoBuildAgentInGroupException { ProjectSummary projectSummary = getProjectSummary( projectId ); checkBuildProjectInGroupAuthorization( projectSummary.getProjectGroup().getName() ); org.apache.continuum.utils.build.BuildTrigger buildTrigger = populateBuildTrigger( xmlrpcBuildTrigger ); buildProjectWithBuildDefinition( projectId, buildDefinitionId, buildTrigger ); return 0; } public int buildGroup( int projectGroupId ) throws ContinuumException, NoBuildAgentException, NoBuildAgentInGroupException { ProjectGroupSummary pg = getProjectGroupSummary( projectGroupId ); checkBuildProjectInGroupAuthorization( pg.getName() ); continuum.buildProjectGroup( projectGroupId, new org.apache.continuum.utils.build.BuildTrigger( ContinuumProjectState.TRIGGER_SCHEDULED, "" ) ); return 0; } public int buildGroup( int projectGroupId, int buildDefinitionId ) throws ContinuumException, NoBuildAgentException, NoBuildAgentInGroupException { ProjectGroupSummary pg = getProjectGroupSummary( projectGroupId ); checkBuildProjectInGroupAuthorization( pg.getName() ); continuum.buildProjectGroupWithBuildDefinition( projectGroupId, buildDefinitionId, new org.apache.continuum.utils.build.BuildTrigger( ContinuumProjectState.TRIGGER_SCHEDULED, "" ) ); return 0; } // ---------------------------------------------------------------------- // SCM roots // ---------------------------------------------------------------------- public List<ProjectScmRoot> getProjectScmRootByProjectGroup( int projectGroupId ) throws ContinuumException { checkViewProjectGroupAuthorization( getProjectGroupName( projectGroupId ) ); List<org.apache.continuum.model.project.ProjectScmRoot> projectScmRoots = continuum.getProjectScmRootByProjectGroup( projectGroupId ); List<ProjectScmRoot> result = new ArrayList<ProjectScmRoot>( projectScmRoots.size() ); for ( org.apache.continuum.model.project.ProjectScmRoot projectScmRoot : projectScmRoots ) { result.add( populateProjectScmRoot( projectScmRoot ) ); } return result; } public ProjectScmRoot getProjectScmRootByProject( int projectId ) throws ContinuumException { org.apache.continuum.model.project.ProjectScmRoot projectScmRoot = continuum.getProjectScmRootByProject( projectId ); checkViewProjectGroupAuthorization( projectScmRoot.getProjectGroup().getName() ); return populateProjectScmRoot( projectScmRoot ); } // ---------------------------------------------------------------------- // Build Results // ---------------------------------------------------------------------- public BuildResult getLatestBuildResult( int projectId ) throws ContinuumException { ProjectSummary ps = getProjectSummary( projectId ); checkViewProjectGroupAuthorization( ps.getProjectGroup().getName() ); org.apache.maven.continuum.model.project.BuildResult buildResult = continuum.getLatestBuildResultForProject( projectId ); if ( buildResult != null ) { return getBuildResult( projectId, buildResult.getId() ); } return null; } public BuildResult getBuildResult( int projectId, int buildId ) throws ContinuumException { ProjectSummary ps = getProjectSummary( projectId ); checkViewProjectGroupAuthorization( ps.getProjectGroup().getName() ); return populateBuildResult( continuum.getBuildResult( buildId ) ); } public List<BuildResultSummary> getBuildResultsForProject( int projectId, int offset, int length ) throws ContinuumException { ProjectSummary ps = getProjectSummary( projectId ); checkViewProjectGroupAuthorization( ps.getProjectGroup().getName() ); List<BuildResultSummary> result = new ArrayList<BuildResultSummary>(); Collection<org.apache.maven.continuum.model.project.BuildResult> buildResults = continuum.getBuildResultsForProject( projectId, offset, length ); if ( buildResults != null ) { for ( org.apache.maven.continuum.model.project.BuildResult buildResult : buildResults ) { BuildResultSummary br = populateBuildResultSummary( buildResult ); result.add( br ); } } return result; } public int removeBuildResult( BuildResult br ) throws ContinuumException { checkModifyProjectGroupAuthorization( getProjectSummary( br.getProject().getId() ).getProjectGroup().getName() ); continuum.removeBuildResult( br.getId() ); return 0; } public String getBuildOutput( int projectId, int buildId ) throws ContinuumException { ProjectSummary ps = getProjectSummary( projectId ); checkViewProjectGroupAuthorization( ps.getProjectGroup().getName() ); return continuum.getBuildOutput( projectId, buildId ); } // ---------------------------------------------------------------------- // Maven 2.x projects // ---------------------------------------------------------------------- public AddingResult addMavenTwoProject( String url ) throws ContinuumException { checkAddProjectGroupAuthorization(); ContinuumProjectBuildingResult result = continuum.addMavenTwoProject( url ); return populateAddingResult( result ); } public AddingResult addMavenTwoProject( String url, int projectGroupId ) throws ContinuumException { checkAddProjectAuthorization( projectGroupId ); ContinuumProjectBuildingResult result = continuum.addMavenTwoProject( url, projectGroupId ); return populateAddingResult( result ); } public AddingResult addMavenTwoProject( String url, int projectGroupId, boolean checkoutInSingleDirectory ) throws ContinuumException { checkAddProjectAuthorization( projectGroupId ); ContinuumProjectBuildingResult result; try { result = continuum.addMavenTwoProject( url, projectGroupId, true, // checkProtocol false, // useCredentialsCache true, // recursiveProjects continuum.getBuildDefinitionService().getDefaultMavenTwoBuildDefinitionTemplate().getId(), checkoutInSingleDirectory ); } catch ( BuildDefinitionServiceException e ) { throw new ContinuumException( e.getMessage(), e ); } return populateAddingResult( result ); } public AddingResult addMavenTwoProjectAsSingleProject( String url, int projectGroupId ) throws Exception { checkAddProjectAuthorization( projectGroupId ); ContinuumProjectBuildingResult result; try { result = continuum.addMavenTwoProject( url, projectGroupId, true, // checkProtocol false, // useCredentialsCache false, // recursiveProjects continuum.getBuildDefinitionService().getDefaultMavenTwoBuildDefinitionTemplate().getId(), true ); // a multi-module project added as a single project is always // checked out // in a single directory, regardless the value set for // checkoutInSingleDirectory // variable } catch ( BuildDefinitionServiceException e ) { throw new ContinuumException( e.getMessage(), e ); } return populateAddingResult( result ); } private void checkAddProjectAuthorization( int projectGroupId ) throws ContinuumException { if ( projectGroupId == -1 ) { checkAuthorization( ContinuumRoleConstants.CONTINUUM_ADD_GROUP_OPERATION ); } else { checkAuthorization( ContinuumRoleConstants.CONTINUUM_ADD_PROJECT_TO_GROUP_OPERATION, getProjectGroupName( projectGroupId ) ); } } public AddingResult addMavenTwoProject( String url, int projectGroupId, boolean checkProtocol, boolean useCredentialsCache, boolean recursiveProjects, boolean checkoutInSingleDirectory ) throws Exception { checkAddProjectAuthorization( projectGroupId ); ContinuumProjectBuildingResult result; try { result = continuum.addMavenTwoProject( url, projectGroupId, checkProtocol, useCredentialsCache, recursiveProjects, continuum.getBuildDefinitionService().getDefaultMavenTwoBuildDefinitionTemplate().getId(), checkoutInSingleDirectory ); } catch ( BuildDefinitionServiceException e ) { throw new ContinuumException( e.getMessage(), e ); } return populateAddingResult( result ); } // ---------------------------------------------------------------------- // Maven 1.x projects // ---------------------------------------------------------------------- public AddingResult addMavenOneProject( String url, int projectGroupId ) throws ContinuumException { checkAddProjectAuthorization( projectGroupId ); ContinuumProjectBuildingResult result = continuum.addMavenOneProject( url, projectGroupId ); return populateAddingResult( result ); } // ---------------------------------------------------------------------- // Maven ANT projects // ---------------------------------------------------------------------- public ProjectSummary addAntProject( ProjectSummary project, int projectGroupId ) throws ContinuumException { checkAddProjectGroupAuthorization(); org.apache.maven.continuum.model.project.Project newProject = new org.apache.maven.continuum.model.project.Project(); int projectId = continuum.addProject( populateProject( project, newProject ), ContinuumBuildExecutorConstants.ANT_BUILD_EXECUTOR, projectGroupId ); return getProjectSummary( projectId ); } // ---------------------------------------------------------------------- // Maven Shell projects // ---------------------------------------------------------------------- public ProjectSummary addShellProject( ProjectSummary project, int projectGroupId ) throws ContinuumException { checkAddProjectGroupAuthorization(); org.apache.maven.continuum.model.project.Project newProject = new org.apache.maven.continuum.model.project.Project(); int projectId = continuum.addProject( populateProject( project, newProject ), ContinuumBuildExecutorConstants.SHELL_BUILD_EXECUTOR, projectGroupId ); return getProjectSummary( projectId ); } // ---------------------------------------------------------------------- // Schedules // ---------------------------------------------------------------------- public List<Schedule> getSchedules() throws ContinuumException { checkManageSchedulesAuthorization(); Collection schedules = continuum.getSchedules(); List<Schedule> s = new ArrayList<Schedule>(); for ( Object schedule : schedules ) { s.add( populateSchedule( (org.apache.maven.continuum.model.project.Schedule) schedule ) ); } return s; } public Schedule getSchedule( int scheduleId ) throws ContinuumException { checkManageSchedulesAuthorization(); return populateSchedule( continuum.getSchedule( scheduleId ) ); } public Schedule updateSchedule( Schedule schedule ) throws ContinuumException { checkManageSchedulesAuthorization(); org.apache.maven.continuum.model.project.Schedule s = continuum.getSchedule( schedule.getId() ); org.apache.maven.continuum.model.project.Schedule newSchedule = populateSchedule( schedule, s ); org.apache.maven.continuum.model.project.Schedule storedSchedule = continuum.getSchedule( schedule.getId() ); storedSchedule.setActive( newSchedule.isActive() ); storedSchedule.setName( newSchedule.getName() ); storedSchedule.setDescription( StringEscapeUtils.escapeXml( newSchedule.getDescription() ) ); storedSchedule.setDelay( newSchedule.getDelay() ); storedSchedule.setCronExpression( newSchedule.getCronExpression() ); storedSchedule.setMaxJobExecutionTime( newSchedule.getMaxJobExecutionTime() ); continuum.updateSchedule( storedSchedule ); return populateSchedule( continuum.getScheduleByName( schedule.getName() ) ); } public Schedule addSchedule( Schedule schedule ) throws ContinuumException { checkManageSchedulesAuthorization(); org.apache.maven.continuum.model.project.Schedule s = new org.apache.maven.continuum.model.project.Schedule(); continuum.addSchedule( populateSchedule( schedule, s ) ); return populateSchedule( continuum.getScheduleByName( schedule.getName() ) ); } // ---------------------------------------------------------------------- // Profiles // ---------------------------------------------------------------------- public List<Profile> getProfiles() throws ContinuumException { checkManageProfilesAuthorization(); Collection profiles = continuum.getProfileService().getAllProfiles(); List<Profile> p = new ArrayList<Profile>(); for ( Object profile : profiles ) { p.add( populateProfile( (org.apache.maven.continuum.model.system.Profile) profile ) ); } return p; } public Profile getProfile( int profileId ) throws ContinuumException { checkManageProfilesAuthorization(); return populateProfile( continuum.getProfileService().getProfile( profileId ) ); } public Profile getProfileWithName( String profileName ) throws ContinuumException { checkManageProfilesAuthorization(); org.apache.maven.continuum.model.system.Profile profile = continuum.getProfileService().getProfileWithName( profileName ); return profile != null ? populateProfile( profile ) : null; } public Profile addProfile( Profile profile ) throws ContinuumException { org.apache.maven.continuum.model.system.Profile newProfile = new org.apache.maven.continuum.model.system.Profile(); return populateProfile( continuum.getProfileService().addProfile( populateProfile( profile, newProfile ) ) ); } public int updateProfile( Profile profile ) throws ContinuumException { org.apache.maven.continuum.model.system.Profile newProfile = continuum.getProfileService().getProfile( profile.getId() ); continuum.getProfileService().updateProfile( populateProfile( profile, newProfile ) ); return 0; } public int deleteProfile( int profileId ) throws ContinuumException { continuum.getProfileService().deleteProfile( profileId ); return 0; } // ---------------------------------------------------------------------- // Installations // ---------------------------------------------------------------------- public List<Installation> getInstallations() throws ContinuumException { checkManageInstallationsAuthorization(); try { List<org.apache.maven.continuum.model.system.Installation> installs = continuum.getInstallationService().getAllInstallations(); List<Installation> i = new ArrayList<Installation>(); for ( Object install : installs ) { i.add( populateInstallation( (org.apache.maven.continuum.model.system.Installation) install ) ); } return i; } catch ( InstallationException e ) { throw new ContinuumException( "Can't load installations", e ); } } public List<Installation> getBuildAgentInstallations( String url ) throws ContinuumException { try { List<org.apache.maven.continuum.model.system.Installation> buildAgentInstallations = distributedBuildManager.getAvailableInstallations( url ); List<Installation> convertedBuildAgentInstallations = new ArrayList<Installation>(); for ( Object buildAgentInstallation : buildAgentInstallations ) { convertedBuildAgentInstallations.add( populateInstallation( (org.apache.maven.continuum.model.system.Installation) buildAgentInstallation ) ); } return convertedBuildAgentInstallations; } catch ( Exception e ) { throw new ContinuumException( "Can't load installations", e ); } } public Installation getInstallation( int installationId ) throws ContinuumException { checkManageInstallationsAuthorization(); try { org.apache.maven.continuum.model.system.Installation install = continuum.getInstallationService().getInstallation( installationId ); return populateInstallation( install ); } catch ( InstallationException e ) { throw new ContinuumException( "Can't load installations", e ); } } public Installation getInstallation( String installationName ) throws ContinuumException { checkManageInstallationsAuthorization(); try { org.apache.maven.continuum.model.system.Installation install = continuum.getInstallationService().getInstallation( installationName ); return install != null ? populateInstallation( install ) : null; } catch ( InstallationException e ) { throw new ContinuumException( "Can't load installations", e ); } } public Installation addInstallation( Installation installation ) throws ContinuumException { try { org.apache.maven.continuum.model.system.Installation newInstallation = new org.apache.maven.continuum.model.system.Installation(); return populateInstallation( continuum.getInstallationService().add( populateInstallation( installation, newInstallation ) ) ); } catch ( InstallationException e ) { throw new ContinuumException( "Can't delete installations", e ); } } public int updateInstallation( Installation installation ) throws ContinuumException { try { final org.apache.maven.continuum.model.system.Installation newInst = continuum.getInstallationService().getInstallation( installation.getInstallationId() ); continuum.getInstallationService().update( populateInstallation( installation, newInst ) ); return 0; } catch ( InstallationException e ) { throw new ContinuumException( "Can't delete installations", e ); } } public int deleteInstallation( int installationId ) throws ContinuumException { try { org.apache.maven.continuum.model.system.Installation installationTODelete = continuum.getInstallationService().getInstallation( installationId ); continuum.getInstallationService().delete( installationTODelete ); return 0; } catch ( InstallationException e ) { throw new ContinuumException( "Can't delete installations", e ); } } // ---------------------------------------------------------------------- // SystemConfigurationDao // ---------------------------------------------------------------------- public SystemConfiguration getSystemConfiguration() throws ContinuumException { checkManageConfigurationAuthorization(); try { org.apache.maven.continuum.model.system.SystemConfiguration sysConf = systemConfigurationDao.getSystemConfiguration(); return populateSystemConfiguration( sysConf ); } catch ( ContinuumStoreException e ) { throw new ContinuumException( "Can't get SystemConfigurationDao.", e ); } } // ---------------------------------------------------------------------- // Queue // ---------------------------------------------------------------------- public boolean isProjectInPrepareBuildQueue( int projectId ) throws ContinuumException { return isProjectInPrepareBuildQueue( projectId, -1 ); } public boolean isProjectInPrepareBuildQueue( int projectId, int buildDefinitionId ) throws ContinuumException { try { if ( continuum.getConfiguration().isDistributedBuildEnabled() ) { return distributedBuildManager.isProjectInAnyPrepareBuildQueue( projectId, buildDefinitionId ); } else { return parallelBuildsManager.isInPrepareBuildQueue( projectId ); } } catch ( BuildManagerException e ) { throw new ContinuumException( e.getMessage(), e ); } } public boolean isProjectInBuildingQueue( int projectId ) throws ContinuumException { return isProjectInBuildingQueue( projectId, -1 ); } public boolean isProjectInBuildingQueue( int projectId, int buildDefinitionId ) throws ContinuumException { try { if ( continuum.getConfiguration().isDistributedBuildEnabled() ) { return distributedBuildManager.isProjectInAnyBuildQueue( projectId, buildDefinitionId ); } else { return parallelBuildsManager.isInAnyBuildQueue( projectId ); } } catch ( BuildManagerException e ) { throw new ContinuumException( e.getMessage(), e ); } } public boolean isProjectCurrentlyPreparingBuild( int projectId ) throws ContinuumException { return isProjectCurrentlyPreparingBuild( projectId, -1 ); } public boolean isProjectCurrentlyPreparingBuild( int projectId, int buildDefinitionId ) throws ContinuumException { try { if ( continuum.getConfiguration().isDistributedBuildEnabled() ) { return distributedBuildManager.isProjectCurrentlyPreparingBuild( projectId, buildDefinitionId ); } else { return parallelBuildsManager.isProjectCurrentlyPreparingBuild( projectId ); } } catch ( BuildManagerException e ) { throw new ContinuumException( e.getMessage(), e ); } } public boolean isProjectCurrentlyBuilding( int projectId ) throws ContinuumException { return isProjectCurrentlyBuilding( projectId, -1 ); } public boolean isProjectCurrentlyBuilding( int projectId, int buildDefinitionId ) throws ContinuumException { try { if ( continuum.getConfiguration().isDistributedBuildEnabled() ) { return distributedBuildManager.isProjectCurrentlyBuilding( projectId, buildDefinitionId ); } else { return parallelBuildsManager.isProjectInAnyCurrentBuild( projectId ); } } catch ( BuildManagerException e ) { throw new ContinuumException( e.getMessage(), e ); } } public List<BuildProjectTask> getProjectsInBuildQueue() throws ContinuumException { try { Map<String, List<org.apache.continuum.taskqueue.BuildProjectTask>> buildTasks; if ( continuum.getConfiguration().isDistributedBuildEnabled() ) { buildTasks = distributedBuildManager.getProjectsInBuildQueue(); } else { buildTasks = parallelBuildsManager.getProjectsInBuildQueues(); } Set<String> keys = buildTasks.keySet(); List<org.apache.continuum.taskqueue.BuildProjectTask> convertedTasks = new ArrayList<org.apache.continuum.taskqueue.BuildProjectTask>(); for ( String key : keys ) { List<org.apache.continuum.taskqueue.BuildProjectTask> tasks = buildTasks.get( key ); for ( org.apache.continuum.taskqueue.BuildProjectTask task : tasks ) { convertedTasks.add( task ); } } return populateBuildProjectTaskList( convertedTasks ); } catch ( BuildManagerException e ) { throw new ContinuumException( e.getMessage(), e ); } } public int removeProjectsFromBuildingQueue( int[] projectsId ) throws ContinuumException { checkManageQueuesAuthorization(); parallelBuildsManager.removeProjectsFromBuildQueue( projectsId ); return 0; } public boolean cancelCurrentBuild() throws ContinuumException { checkManageQueuesAuthorization(); try { return parallelBuildsManager.cancelAllBuilds(); } catch ( BuildManagerException e ) { throw new ContinuumException( e.getMessage(), e ); } } public boolean cancelBuild( int projectId, int buildDefinitionId ) throws ContinuumException { checkManageQueuesAuthorization(); try { if ( continuum.getConfiguration().isDistributedBuildEnabled() ) { DistributedBuildManager dbm = continuum.getDistributedBuildManager(); String buildAgentUrl = dbm.getBuildAgentUrl( projectId, buildDefinitionId ); if ( dbm.isProjectInAnyPrepareBuildQueue( projectId, buildDefinitionId ) ) { if ( buildAgentUrl != null ) { org.apache.continuum.model.project.ProjectScmRoot scmRoot = continuum.getProjectScmRootByProject( projectId ); dbm.removeFromPrepareBuildQueue( buildAgentUrl, scmRoot.getProjectGroup().getId(), scmRoot.getId() ); } } // wait if already preparing else if ( dbm.isProjectCurrentlyPreparingBuild( projectId, buildDefinitionId ) ) { while ( dbm.isProjectCurrentlyPreparingBuild( projectId, buildDefinitionId ) ) { try { Thread.sleep( 1000 ); } catch ( InterruptedException e ) { // do nothing } } } if ( dbm.isProjectInAnyBuildQueue( projectId, buildDefinitionId ) ) { dbm.removeFromBuildQueue( buildAgentUrl, projectId, buildDefinitionId ); } else if ( dbm.isProjectCurrentlyBuilding( projectId, buildDefinitionId ) ) { if ( buildAgentUrl != null ) { dbm.cancelDistributedBuild( buildAgentUrl ); } } return true; } else { // if currently preparing build or being checked out, wait until done if ( parallelBuildsManager.isProjectCurrentlyPreparingBuild( projectId ) || parallelBuildsManager.isProjectCurrentlyBeingCheckedOut( projectId ) ) { while ( parallelBuildsManager.isProjectCurrentlyPreparingBuild( projectId ) || parallelBuildsManager.isProjectCurrentlyBeingCheckedOut( projectId ) ) { try { Thread.sleep( 1000 ); } catch ( InterruptedException e ) { // do nothing } } } if ( parallelBuildsManager.isInPrepareBuildQueue( projectId ) ) { org.apache.continuum.model.project.ProjectScmRoot scmRoot = continuum.getProjectScmRootByProject( projectId ); parallelBuildsManager.removeProjectFromPrepareBuildQueue( scmRoot.getProjectGroup().getId(), scmRoot.getId() ); } else if ( parallelBuildsManager.isInAnyCheckoutQueue( projectId ) ) { parallelBuildsManager.removeProjectFromCheckoutQueue( projectId ); } else if ( parallelBuildsManager.isInAnyBuildQueue( projectId ) ) { parallelBuildsManager.removeProjectFromBuildQueue( projectId ); } else if ( parallelBuildsManager.isProjectInAnyCurrentBuild( projectId ) ) { return parallelBuildsManager.cancelBuild( projectId ); } return true; } } catch ( BuildManagerException e ) { throw new ContinuumException( e.getMessage(), e ); } } // ---------------------------------------------------------------------- // Release Results // ---------------------------------------------------------------------- public ContinuumReleaseResult getReleaseResult( int releaseId ) throws ContinuumException { org.apache.continuum.model.release.ContinuumReleaseResult releaseResult = continuum.getContinuumReleaseResult( releaseId ); checkViewProjectGroupAuthorization( getProjectGroupName( releaseResult.getProjectGroup().getId() ) ); return populateReleaseResult( releaseResult ); } public List<ContinuumReleaseResult> getReleaseResultsForProjectGroup( int projectGroupId ) throws ContinuumException { checkViewProjectGroupAuthorization( getProjectGroupName( projectGroupId ) ); Collection releaseResults = continuum.getContinuumReleaseResultsByProjectGroup( projectGroupId ); List<ContinuumReleaseResult> r = new ArrayList<ContinuumReleaseResult>(); for ( Object releaseResult : releaseResults ) { r.add( populateReleaseResult( (org.apache.continuum.model.release.ContinuumReleaseResult) releaseResult ) ); } return r; } public int removeReleaseResult( ContinuumReleaseResult releaseResult ) throws ContinuumException { checkModifyProjectGroupAuthorization( getProjectGroupName( releaseResult.getProjectGroup().getId() ) ); continuum.removeContinuumReleaseResult( releaseResult.getId() ); return 0; } public String getReleaseOutput( int releaseId ) throws ContinuumException { org.apache.continuum.model.release.ContinuumReleaseResult releaseResult = continuum.getContinuumReleaseResult( releaseId ); checkViewProjectGroupAuthorization( getProjectGroupName( releaseResult.getProjectGroup().getId() ) ); return continuum.getReleaseOutput( releaseId ); } // ---------------------------------------------------------------------- // Purge Configuration // ---------------------------------------------------------------------- public RepositoryPurgeConfiguration addRepositoryPurgeConfiguration( RepositoryPurgeConfiguration repoPurge ) throws ContinuumException { checkManagePurgingAuthorization(); try { org.apache.continuum.model.repository.RepositoryPurgeConfiguration newPurge = new org.apache.continuum.model.repository.RepositoryPurgeConfiguration(); return populateRepositoryPurgeConfiguration( continuum.getPurgeConfigurationService().addRepositoryPurgeConfiguration( populateRepositoryPurgeConfiguration( repoPurge, newPurge ) ) ); } catch ( RepositoryServiceException e ) { throw new ContinuumException( "Error while converting repository purge configuration", e ); } catch ( PurgeConfigurationServiceException e ) { throw new ContinuumException( "Can't add repositoryPurgeConfiguration", e ); } } public int updateRepositoryPurgeConfiguration( RepositoryPurgeConfiguration repoPurge ) throws ContinuumException { checkManagePurgingAuthorization(); try { org.apache.continuum.model.repository.RepositoryPurgeConfiguration purge = new org.apache.continuum.model.repository.RepositoryPurgeConfiguration(); continuum.getPurgeConfigurationService().updateRepositoryPurgeConfiguration( populateRepositoryPurgeConfiguration( repoPurge, purge ) ); return 0; } catch ( RepositoryServiceException e ) { throw new ContinuumException( "Error while converting repository purge configuration", e ); } catch ( PurgeConfigurationServiceException e ) { throw new ContinuumException( "Cant' update repository PurgeException", e ); } } public int removeRepositoryPurgeConfiguration( int repoPurgeId ) throws ContinuumException { checkManagePurgingAuthorization(); try { org.apache.continuum.model.repository.RepositoryPurgeConfiguration repoPurge = continuum.getPurgeConfigurationService().getRepositoryPurgeConfiguration( repoPurgeId ); continuum.getPurgeConfigurationService().removeRepositoryPurgeConfiguration( repoPurge ); return 0; } catch ( PurgeConfigurationServiceException e ) { throw new ContinuumException( "Can't delete repository purge configuration", e ); } } public RepositoryPurgeConfiguration getRepositoryPurgeConfiguration( int repoPurgeId ) throws ContinuumException { checkManagePurgingAuthorization(); try { org.apache.continuum.model.repository.RepositoryPurgeConfiguration repoPurgeConfig = continuum.getPurgeConfigurationService().getRepositoryPurgeConfiguration( repoPurgeId ); return populateRepositoryPurgeConfiguration( repoPurgeConfig ); } catch ( PurgeConfigurationServiceException e ) { throw new ContinuumException( "Error while retrieving repository purge configuration", e ); } } public List<RepositoryPurgeConfiguration> getAllRepositoryPurgeConfigurations() throws ContinuumException { checkManagePurgingAuthorization(); Collection repoPurgeConfigs = continuum.getPurgeConfigurationService().getAllRepositoryPurgeConfigurations(); List<RepositoryPurgeConfiguration> r = new ArrayList<RepositoryPurgeConfiguration>(); for ( Object repoPurgeConfig : repoPurgeConfigs ) { r.add( populateRepositoryPurgeConfiguration( (org.apache.continuum.model.repository.RepositoryPurgeConfiguration) repoPurgeConfig ) ); } return r; } public DirectoryPurgeConfiguration addDirectoryPurgeConfiguration( DirectoryPurgeConfiguration dirPurge ) throws ContinuumException { checkManagePurgingAuthorization(); try { org.apache.continuum.model.repository.DirectoryPurgeConfiguration newPurge = new org.apache.continuum.model.repository.DirectoryPurgeConfiguration(); return populateDirectoryPurgeConfiguration( continuum.getPurgeConfigurationService().addDirectoryPurgeConfiguration( populateDirectoryPurgeConfiguration( dirPurge, newPurge ) ) ); } catch ( RepositoryServiceException e ) { throw new ContinuumException( "Error while converting directory purge configuration", e ); } catch ( PurgeConfigurationServiceException e ) { throw new ContinuumException( "Can't add directory purge configuration", e ); } } public int updateDirectoryPurgeConfiguration( DirectoryPurgeConfiguration dirPurge ) throws ContinuumException { checkManagePurgingAuthorization(); try { org.apache.continuum.model.repository.DirectoryPurgeConfiguration purge = new org.apache.continuum.model.repository.DirectoryPurgeConfiguration(); continuum.getPurgeConfigurationService().updateDirectoryPurgeConfiguration( populateDirectoryPurgeConfiguration( dirPurge, purge ) ); return 0; } catch ( RepositoryServiceException e ) { throw new ContinuumException( "Error while converting directory purge configuration", e ); } catch ( PurgeConfigurationServiceException e ) { throw new ContinuumException( "Can't add directory purge configuration", e ); } } public int removeDirectoryPurgeConfiguration( int dirPurgeId ) throws ContinuumException { checkManagePurgingAuthorization(); try { org.apache.continuum.model.repository.DirectoryPurgeConfiguration dirPurge = continuum.getPurgeConfigurationService().getDirectoryPurgeConfiguration( dirPurgeId ); continuum.getPurgeConfigurationService().removeDirectoryPurgeConfiguration( dirPurge ); return 0; } catch ( PurgeConfigurationServiceException e ) { throw new ContinuumException( "Can't delete directory purge configuration", e ); } } public DirectoryPurgeConfiguration getDirectoryPurgeConfiguration( int dirPurgeId ) throws ContinuumException { checkManagePurgingAuthorization(); try { org.apache.continuum.model.repository.DirectoryPurgeConfiguration dirPurgeConfig = continuum.getPurgeConfigurationService().getDirectoryPurgeConfiguration( dirPurgeId ); return populateDirectoryPurgeConfiguration( dirPurgeConfig ); } catch ( PurgeConfigurationServiceException e ) { throw new ContinuumException( "Error while retrieving directory purge configuration", e ); } } public List<DirectoryPurgeConfiguration> getAllDirectoryPurgeConfigurations() throws ContinuumException { checkManagePurgingAuthorization(); Collection dirPurgeConfigs = continuum.getPurgeConfigurationService().getAllDirectoryPurgeConfigurations(); List<DirectoryPurgeConfiguration> d = new ArrayList<DirectoryPurgeConfiguration>(); for ( Object dirPurgeConfig : dirPurgeConfigs ) { d.add( populateDirectoryPurgeConfiguration( (org.apache.continuum.model.repository.DirectoryPurgeConfiguration) dirPurgeConfig ) ); } return d; } public int purgeLocalRepository( int repoPurgeId ) throws ContinuumException { checkManagePurgingAuthorization(); try { org.apache.continuum.model.repository.RepositoryPurgeConfiguration repoPurgeConfig = continuum.getPurgeConfigurationService().getRepositoryPurgeConfiguration( repoPurgeId ); continuum.getPurgeManager().purgeRepository( repoPurgeConfig ); return 0; } catch ( PurgeConfigurationServiceException e ) { throw new ContinuumException( "Error while retrieving repository purge configuration", e ); } catch ( ContinuumPurgeManagerException e ) { throw new ContinuumException( "Error while purging local repository", e ); } } public int purgeDirectory( int dirPurgeId ) throws ContinuumException { checkManagePurgingAuthorization(); try { org.apache.continuum.model.repository.DirectoryPurgeConfiguration dirPurgeConfig = continuum.getPurgeConfigurationService().getDirectoryPurgeConfiguration( dirPurgeId ); continuum.getPurgeManager().purgeDirectory( dirPurgeConfig ); return 0; } catch ( PurgeConfigurationServiceException e ) { throw new ContinuumException( "Error while retrieving directory purge configuration", e ); } catch ( ContinuumPurgeManagerException e ) { throw new ContinuumException( "Error while purging directory", e ); } } // ---------------------------------------------------------------------- // Local Repository // ---------------------------------------------------------------------- public LocalRepository addLocalRepository( LocalRepository repository ) throws ContinuumException { checkManageRepositoriesAuthorization(); try { org.apache.continuum.model.repository.LocalRepository newRepository = new org.apache.continuum.model.repository.LocalRepository(); return populateLocalRepository( continuum.getRepositoryService().addLocalRepository( populateLocalRepository( repository, newRepository ) ) ); } catch ( RepositoryServiceException e ) { throw new ContinuumException( "Unable to add repository", e ); } } public int updateLocalRepository( LocalRepository repository ) throws ContinuumException { checkManageRepositoriesAuthorization(); try { final org.apache.continuum.model.repository.LocalRepository newRepo = continuum.getRepositoryService().getLocalRepository( repository.getId() ); continuum.getRepositoryService().updateLocalRepository( populateLocalRepository( repository, newRepo ) ); return 0; } catch ( RepositoryServiceException e ) { throw new ContinuumException( "Can't update repository", e ); } } public int removeLocalRepository( int repositoryId ) throws ContinuumException { checkManageRepositoriesAuthorization(); try { continuum.getRepositoryService().removeLocalRepository( repositoryId ); return 0; } catch ( RepositoryServiceException e ) { throw new ContinuumException( "Can't delete repository", e ); } } public LocalRepository getLocalRepository( int repositoryId ) throws ContinuumException { checkManageRepositoriesAuthorization(); try { return populateLocalRepository( continuum.getRepositoryService().getLocalRepository( repositoryId ) ); } catch ( RepositoryServiceException e ) { throw new ContinuumException( "Error while retrieving repository.", e ); } } public List<LocalRepository> getAllLocalRepositories() throws ContinuumException { checkManageRepositoriesAuthorization(); Collection repos = continuum.getRepositoryService().getAllLocalRepositories(); List<LocalRepository> r = new ArrayList<LocalRepository>(); for ( Object repo : repos ) { r.add( populateLocalRepository( (org.apache.continuum.model.repository.LocalRepository) repo ) ); } return r; } // ---------------------------------------------------------------------- // Build agent // ---------------------------------------------------------------------- public BuildAgentConfiguration addBuildAgent( BuildAgentConfiguration buildAgentConfiguration ) throws ConfigurationException, ConfigurationStoringException, ContinuumConfigurationException { ConfigurationService configurationService = continuum.getConfiguration(); if ( buildAgentConfiguration == null ) { return null; } try { configurationService.addBuildAgent( populateBuildAgent( buildAgentConfiguration ) ); configurationService.store(); return populateBuildAgent( configurationService.getBuildAgent( buildAgentConfiguration.getUrl() ) ); } catch ( ContinuumException e ) { throw new ConfigurationException( "Error in adding buildAgent", e ); } } public BuildAgentConfiguration getBuildAgent( String url ) { ConfigurationService configurationService = continuum.getConfiguration(); org.apache.continuum.configuration.BuildAgentConfiguration buildAgent = configurationService.getBuildAgent( url ); return buildAgent != null ? populateBuildAgent( buildAgent ) : null; } /** * {@inheritDoc} * * @throws ContinuumException distributed build is not enabled or error during retrieval of build agent url * @see DistributedBuildManager#getBuildAgentUrl(int, int) */ public String getBuildAgentUrl( int projectId, int buildDefinitionId ) throws ContinuumException { if ( !continuum.getConfiguration().isDistributedBuildEnabled() ) { throw new ContinuumException( "Method available only in distributed build mode." ); } return distributedBuildManager.getBuildAgentUrl( projectId, buildDefinitionId ); } public BuildAgentConfiguration updateBuildAgent( BuildAgentConfiguration buildAgentConfiguration ) throws ConfigurationStoringException, ContinuumConfigurationException { try { ConfigurationService configurationService = continuum.getConfiguration(); org.apache.continuum.configuration.BuildAgentConfiguration buildAgent = configurationService.getBuildAgent( buildAgentConfiguration.getUrl() ); BuildAgentConfiguration buildAgentConfigurationToUpdate = buildAgent != null ? populateBuildAgent( buildAgent ) : null; if ( buildAgentConfigurationToUpdate != null ) { buildAgentConfigurationToUpdate.setDescription( StringEscapeUtils.escapeXml( buildAgentConfiguration.getDescription() ) ); buildAgentConfigurationToUpdate.setEnabled( buildAgentConfiguration.isEnabled() ); configurationService.updateBuildAgent( populateBuildAgent( buildAgentConfigurationToUpdate ) ); configurationService.store(); return populateBuildAgent( configurationService.getBuildAgent( buildAgentConfiguration.getUrl() ) ); } else { return null; } } catch ( ContinuumException e ) { throw new ContinuumConfigurationException( "Error in adding buildAgent", e ); } } public boolean removeBuildAgent( String url ) throws BuildAgentConfigurationException, ConfigurationStoringException, ContinuumConfigurationException, ContinuumException { ConfigurationService configurationService = continuum.getConfiguration(); boolean SUCCESS; org.apache.continuum.configuration.BuildAgentConfiguration buildAgent = configurationService.getBuildAgent( url ); BuildAgentConfiguration buildAgentConfiguration = buildAgent != null ? populateBuildAgent( buildAgent ) : null; if ( buildAgentConfiguration != null ) { if ( continuum.getDistributedBuildManager().isBuildAgentBusy( buildAgentConfiguration.getUrl() ) ) { throw new BuildAgentConfigurationException( "Cannot delete build agent because it's busy at the moment" ); } if ( configurationService.getBuildAgentGroups() != null ) { for ( org.apache.continuum.configuration.BuildAgentGroupConfiguration buildAgentGroup : configurationService.getBuildAgentGroups() ) { if ( configurationService.containsBuildAgentUrl( buildAgentConfiguration.getUrl(), buildAgentGroup ) ) { throw new BuildAgentConfigurationException( "Cannot delete build agent because it's in use at the moment" ); } } } try { continuum.getDistributedBuildManager().removeDistributedBuildQueueOfAgent( buildAgentConfiguration.getUrl() ); configurationService.removeBuildAgent( populateBuildAgent( buildAgentConfiguration ) ); configurationService.store(); SUCCESS = true; } catch ( ContinuumException e ) { throw new ContinuumException( "Error when removing build agent in build queue", e ); } } else { throw new BuildAgentConfigurationException( "Build agent does not exist." ); } return SUCCESS; } public List<BuildAgentConfiguration> getAllBuildAgents() { ConfigurationService configurationService = continuum.getConfiguration(); List<org.apache.continuum.configuration.BuildAgentConfiguration> buildAgents = configurationService.getBuildAgents(); List<BuildAgentConfiguration> buildAgentConfigurations = new ArrayList<BuildAgentConfiguration>(); if ( buildAgents != null ) { for ( org.apache.continuum.configuration.BuildAgentConfiguration buildAgent : buildAgents ) { buildAgentConfigurations.add( populateBuildAgent( buildAgent ) ); } } return buildAgentConfigurations; } public List<BuildAgentConfiguration> getBuildAgentsWithInstallations() throws Exception { ConfigurationService configurationService = continuum.getConfiguration(); List<org.apache.continuum.configuration.BuildAgentConfiguration> buildAgents = configurationService.getBuildAgents(); List<BuildAgentConfiguration> buildAgentConfigurations = new ArrayList<BuildAgentConfiguration>(); if ( buildAgents != null ) { for ( org.apache.continuum.configuration.BuildAgentConfiguration buildAgent : buildAgents ) { if ( buildAgent.isEnabled() ) { BuildAgentConfiguration agent = populateBuildAgent( buildAgent ); agent.setInstallations( getBuildAgentInstallations( buildAgent.getUrl() ) ); buildAgentConfigurations.add( agent ); } } } return buildAgentConfigurations; } // ---------------------------------------------------------------------- // Build agent group // ---------------------------------------------------------------------- public BuildAgentGroupConfiguration addBuildAgentGroup( BuildAgentGroupConfiguration buildAgentGroup ) throws ConfigurationException, ConfigurationStoringException, ContinuumConfigurationException { ConfigurationService configurationService = continuum.getConfiguration(); if ( buildAgentGroup == null ) { return null; } try { configurationService.addBuildAgentGroup( populateBuildAgentGroup( buildAgentGroup ) ); configurationService.store(); return populateBuildAgentGroup( configurationService.getBuildAgentGroup( buildAgentGroup.getName() ) ); } catch ( ContinuumException e ) { throw new ConfigurationException( "Error in adding buildAgentGroup", e ); } } public BuildAgentGroupConfiguration getBuildAgentGroup( String name ) { ConfigurationService configurationService = continuum.getConfiguration(); org.apache.continuum.configuration.BuildAgentGroupConfiguration buildAgentGroup = configurationService.getBuildAgentGroup( name ); return buildAgentGroup != null ? populateBuildAgentGroup( buildAgentGroup ) : null; } public BuildAgentGroupConfiguration updateBuildAgentGroup( BuildAgentGroupConfiguration buildAgentGroup ) throws ConfigurationException, ConfigurationStoringException, ContinuumConfigurationException { try { ConfigurationService configurationService = continuum.getConfiguration(); org.apache.continuum.configuration.BuildAgentGroupConfiguration buildAgentGroupConfiguration = configurationService.getBuildAgentGroup( buildAgentGroup.getName() ); if ( buildAgentGroupConfiguration != null ) { buildAgentGroupConfiguration.setName( StringEscapeUtils.escapeXml( buildAgentGroup.getName() ) ); if ( buildAgentGroup.getBuildAgents() != null ) { buildAgentGroupConfiguration.getBuildAgents().clear(); for ( BuildAgentConfiguration buildAgent : buildAgentGroup.getBuildAgents() ) { buildAgentGroupConfiguration.getBuildAgents().add( populateBuildAgent( buildAgent ) ); } } else { buildAgentGroupConfiguration.setBuildAgents( null ); } configurationService.updateBuildAgentGroup( buildAgentGroupConfiguration ); configurationService.store(); return populateBuildAgentGroup( configurationService.getBuildAgentGroup( buildAgentGroup.getName() ) ); } else { return null; } } catch ( ContinuumException e ) { throw new ContinuumConfigurationException( "Error in updating build agent group " + buildAgentGroup.getName(), e ); } } public int removeBuildAgentGroup( String name ) throws ConfigurationException { ConfigurationService configurationService = continuum.getConfiguration(); org.apache.continuum.configuration.BuildAgentGroupConfiguration buildAgentGroupConfiguration = configurationService.getBuildAgentGroup( name ); if ( buildAgentGroupConfiguration != null ) { configurationService.removeBuildAgentGroup( buildAgentGroupConfiguration ); } return 0; } // ---------------------------------------------------------------------- // Converters // ---------------------------------------------------------------------- private List<BuildProjectTask> populateBuildProjectTaskList( List<org.apache.continuum.taskqueue.BuildProjectTask> buildProjectTasks ) { List<BuildProjectTask> responses = new ArrayList<BuildProjectTask>(); for ( org.apache.continuum.taskqueue.BuildProjectTask buildProjectTask : buildProjectTasks ) { responses.add( (BuildProjectTask) mapper.map( buildProjectTask, BuildProjectTask.class ) ); } return responses; } private ProjectSummary populateProjectSummary( org.apache.maven.continuum.model.project.Project project ) { return (ProjectSummary) mapper.map( project, ProjectSummary.class ); } private Project populateProject( org.apache.maven.continuum.model.project.Project project ) { return (Project) mapper.map( project, Project.class ); } private ProjectScmRoot populateProjectScmRoot( org.apache.continuum.model.project.ProjectScmRoot projectScmRoot ) { return (ProjectScmRoot) mapper.map( projectScmRoot, ProjectScmRoot.class ); } private org.apache.maven.continuum.model.project.Project populateProject( ProjectSummary projectSummary, org.apache.maven.continuum.model.project.Project project ) throws ContinuumException { if ( projectSummary == null ) { return null; } // validate if ( StringUtils.isNotBlank( projectSummary.getArtifactId() ) && !projectSummary.getArtifactId().matches( PROJECT_ARTIFACT_ID_VALID_EXPRESSION ) ) { throw new ContinuumException( "Project Artifact Id contains invalid characters" ); } if ( StringUtils.isNotBlank( projectSummary.getExecutorId() ) && !projectSummary.getExecutorId().matches( PROJECT_EXECUTOR_OR_BUILDDEF_TYPE_VALID_EXPRESSION ) ) { throw new ContinuumException( "Project Executor Id can only be 'maven2, maven-1, ant or shell'" ); } if ( StringUtils.isNotBlank( projectSummary.getGroupId() ) && !projectSummary.getGroupId().matches( PROJECTGROUP_ID_VALID_EXPRESSION ) ) { throw new ContinuumException( "Project Group Id contains invalid characters" ); } if ( StringUtils.isNotBlank( projectSummary.getName() ) && !projectSummary.getName().matches( NAME_VALID_EXPRESSION ) ) { throw new ContinuumException( "Project Name contains invalid characters" ); } if ( StringUtils.isNotBlank( projectSummary.getScmTag() ) && !projectSummary.getScmTag().matches( PROJECT_SCM_TAG_VALID_EXPRESSION ) ) { throw new ContinuumException( "Project Scm Tag contains invalid characters" ); } if ( StringUtils.isNotBlank( projectSummary.getScmUrl() ) && !projectSummary.getScmUrl().matches( PROJECT_SCM_URL_VALID_EXPRESSION ) ) { throw new ContinuumException( "Project Scm Url contains invalid characters" ); } if ( StringUtils.isNotBlank( projectSummary.getUrl() ) && !projectSummary.getUrl().matches( URL_VALID_EXPRESSION ) ) { throw new ContinuumException( "Project Url contains invalid characters" ); } if ( StringUtils.isNotBlank( projectSummary.getVersion() ) && !projectSummary.getVersion().matches( PROJECT_VERSION_VALID_EXPRESSION ) ) { throw new ContinuumException( "Project Version contains invalid characters" ); } if ( StringUtils.isNotBlank( projectSummary.getWorkingDirectory() ) && !projectSummary.getWorkingDirectory().matches( DIRECTORY_VALID_EXPRESSION ) ) { throw new ContinuumException( "Project Working Directory contains invalid characters" ); } project.setArtifactId( projectSummary.getArtifactId() ); project.setBuildNumber( projectSummary.getBuildNumber() ); project.setDescription( StringEscapeUtils.escapeXml( projectSummary.getDescription() ) ); project.setExecutorId( projectSummary.getExecutorId() ); project.setGroupId( projectSummary.getGroupId() ); project.setId( projectSummary.getId() ); project.setLatestBuildId( projectSummary.getLatestBuildId() ); project.setName( projectSummary.getName() ); if ( projectSummary.getProjectGroup() != null ) { org.apache.maven.continuum.model.project.ProjectGroup g = continuum.getProjectGroup( projectSummary.getProjectGroup().getId() ); project.setProjectGroup( populateProjectGroupSummary( projectSummary.getProjectGroup(), g ) ); } else { project.setProjectGroup( null ); } project.setScmTag( projectSummary.getScmTag() ); project.setScmUrl( projectSummary.getScmUrl() ); project.setScmUseCache( projectSummary.isScmUseCache() ); project.setScmUsername( projectSummary.getScmUsername() ); project.setState( projectSummary.getState() ); project.setUrl( projectSummary.getUrl() ); project.setVersion( projectSummary.getVersion() ); project.setWorkingDirectory( projectSummary.getWorkingDirectory() ); return project; } private ProjectNotifier populateProjectNotifier( org.apache.maven.continuum.model.project.ProjectNotifier notifier ) { return (ProjectNotifier) mapper.map( notifier, ProjectNotifier.class ); } private ProjectGroupSummary populateProjectGroupSummary( org.apache.maven.continuum.model.project.ProjectGroup group ) { return (ProjectGroupSummary) mapper.map( group, ProjectGroupSummary.class ); } private org.apache.maven.continuum.model.project.ProjectGroup populateProjectGroupSummary( ProjectGroupSummary group, org.apache.maven.continuum.model.project.ProjectGroup g ) throws ContinuumException { if ( group == null ) { return null; } if ( StringUtils.isNotBlank( group.getGroupId() ) && !group.getGroupId().matches( PROJECTGROUP_ID_VALID_EXPRESSION ) ) { throw new ContinuumException( "ProjectGroup Id contains invalid characters" ); } if ( StringUtils.isNotBlank( group.getName() ) && !group.getName().matches( NAME_VALID_EXPRESSION ) ) { throw new ContinuumException( "ProjectGroup Name contains invalid characters" ); } g.setDescription( StringEscapeUtils.escapeXml( group.getDescription() ) ); g.setGroupId( group.getGroupId() ); g.setId( group.getId() ); g.setName( group.getName() ); org.apache.continuum.model.repository.LocalRepository repo = new org.apache.continuum.model.repository.LocalRepository(); g.setLocalRepository( populateLocalRepository( group.getLocalRepository(), repo ) ); return g; } private ProjectGroup populateProjectGroupWithAllDetails( org.apache.maven.continuum.model.project.ProjectGroup group ) { return (ProjectGroup) mapper.map( group, ProjectGroup.class ); } private BuildResultSummary populateBuildResultSummary( org.apache.maven.continuum.model.project.BuildResult buildResult ) { return (BuildResultSummary) mapper.map( buildResult, BuildResultSummary.class ); } private BuildResult populateBuildResult( org.apache.maven.continuum.model.project.BuildResult buildResult ) throws ContinuumException { return (BuildResult) mapper.map( buildResult, BuildResult.class ); } private AddingResult populateAddingResult( ContinuumProjectBuildingResult result ) { if ( result == null ) { return null; } AddingResult res = new AddingResult(); if ( result.hasErrors() ) { if ( StringUtils.isNotBlank( result.getErrorsAsString() ) ) { res.addError( result.getErrorsAsString() ); } else { for ( String error : result.getErrors() ) { res.addError( AddingResultUtil.getErrorMessage( error ) ); } } } if ( result.getProjects() != null ) { for ( org.apache.maven.continuum.model.project.Project project : result.getProjects() ) { res.addProject( populateProjectSummary( project ) ); } } if ( result.getProjectGroups() != null ) { for ( org.apache.maven.continuum.model.project.ProjectGroup projectGroup : result.getProjectGroups() ) { res.addProjectGroup( populateProjectGroupSummary( projectGroup ) ); } } return res; } private BuildDefinition populateBuildDefinition( org.apache.maven.continuum.model.project.BuildDefinition buildDef ) { return (BuildDefinition) mapper.map( buildDef, BuildDefinition.class ); } protected org.apache.maven.continuum.model.project.BuildDefinition populateBuildDefinition( BuildDefinition buildDef, org.apache.maven.continuum.model.project.BuildDefinition bd ) throws ContinuumException { if ( buildDef == null ) { return null; } if ( StringUtils.isNotBlank( buildDef.getArguments() ) && !buildDef.getArguments().matches( BUILD_DEFINITION_ARGUMENTS_VALID_EXPRESSION ) ) { throw new ContinuumException( "Build Definition Arguments contain invalid characters" ); } if ( StringUtils.isNotBlank( buildDef.getBuildFile() ) && !buildDef.getBuildFile().matches( BUILD_DEFINITION_BUILD_FILE_VALID_EXPRESSION ) ) { throw new ContinuumException( "Build Definition Build File contains invalid characters" ); } if ( StringUtils.isNotBlank( buildDef.getGoals() ) && !buildDef.getGoals().matches( BUILD_DEFINITION_GOALS_VALID_EXPRESSION ) ) { throw new ContinuumException( "Build Definition Goals contain invalid characters" ); } if ( StringUtils.isNotBlank( buildDef.getType() ) && !buildDef.getType().matches( PROJECT_EXECUTOR_OR_BUILDDEF_TYPE_VALID_EXPRESSION ) ) { throw new ContinuumException( "Build Definition Type can only be 'maven2, maven-1, ant, or shell'" ); } bd.setArguments( buildDef.getArguments() ); bd.setBuildFile( buildDef.getBuildFile() ); bd.setType( buildDef.getType() ); bd.setBuildFresh( buildDef.isBuildFresh() ); bd.setAlwaysBuild( buildDef.isAlwaysBuild() ); bd.setDefaultForProject( buildDef.isDefaultForProject() ); bd.setGoals( buildDef.getGoals() ); bd.setId( buildDef.getId() ); if ( buildDef.getProfile() != null ) { bd.setProfile( populateProfile( buildDef.getProfile(), continuum.getProfileService().getProfile( buildDef.getProfile().getId() ) ) ); } else { bd.setProfile( null ); } if ( buildDef.getSchedule() != null ) { bd.setSchedule( populateSchedule( buildDef.getSchedule(), continuum.getSchedule( buildDef.getSchedule().getId() ) ) ); } else { bd.setSchedule( null ); } if ( StringUtils.isNotEmpty( buildDef.getDescription() ) ) { bd.setDescription( StringEscapeUtils.escapeXml( buildDef.getDescription() ) ); } return bd; } protected void buildProjectWithBuildDefinition( int projectId, int buildDefinitionId, org.apache.continuum.utils.build.BuildTrigger buildTrigger ) throws ContinuumException, NoBuildAgentException, NoBuildAgentInGroupException { continuum.buildProjectWithBuildDefinition( projectId, buildDefinitionId, buildTrigger ); } private BuildDefinitionTemplate populateBuildDefinitionTemplate( org.apache.maven.continuum.model.project.BuildDefinitionTemplate bdt ) { return (BuildDefinitionTemplate) mapper.map( bdt, BuildDefinitionTemplate.class ); } private org.apache.maven.continuum.model.project.Schedule populateSchedule( Schedule schedule, org.apache.maven.continuum.model.project.Schedule s ) throws ContinuumException { if ( schedule == null ) { return null; } if ( StringUtils.isNotBlank( schedule.getCronExpression() ) && !schedule.getCronExpression().matches( SCHEDULE_CRON_VALID_EXPRESSION ) ) { throw new ContinuumException( "Schedule Cron Expression contains invalid characters" ); } if ( StringUtils.isNotBlank( schedule.getName() ) && !schedule.getName().matches( NAME_VALID_EXPRESSION ) ) { throw new ContinuumException( "Schedule Name contains invalid characters" ); } s.setActive( schedule.isActive() ); s.setCronExpression( schedule.getCronExpression() ); s.setDelay( schedule.getDelay() ); s.setDescription( StringEscapeUtils.escapeXml( schedule.getDescription() ) ); s.setId( schedule.getId() ); s.setMaxJobExecutionTime( schedule.getMaxJobExecutionTime() ); s.setName( schedule.getName() ); return s; } private Schedule populateSchedule( org.apache.maven.continuum.model.project.Schedule schedule ) { return (Schedule) mapper.map( schedule, Schedule.class ); } private org.apache.maven.continuum.model.system.Profile populateProfile( Profile profile, org.apache.maven.continuum.model.system.Profile newProfile ) throws ContinuumException { if ( profile == null ) { return null; } if ( StringUtils.isNotBlank( profile.getName() ) && !profile.getName().matches( NAME_VALID_EXPRESSION ) ) { throw new ContinuumException( "Build Environment Name contains invalid characters" ); } try { newProfile.setActive( profile.isActive() ); newProfile.setBuildWithoutChanges( profile.isBuildWithoutChanges() ); newProfile.setDescription( StringEscapeUtils.escapeXml( profile.getDescription() ) ); newProfile.setName( profile.getName() ); newProfile.setScmMode( profile.getScmMode() ); newProfile.setBuildAgentGroup( profile.getBuildAgentGroup() ); if ( profile.getBuilder() != null ) { final org.apache.maven.continuum.model.system.Installation newBuilder = continuum.getInstallationService().getInstallation( profile.getBuilder().getInstallationId() ); newProfile.setBuilder( populateInstallation( profile.getBuilder(), newBuilder ) ); } else { newProfile.setBuilder( null ); } if ( profile.getJdk() != null ) { final org.apache.maven.continuum.model.system.Installation newJdk = continuum.getInstallationService().getInstallation( profile.getJdk().getInstallationId() ); newProfile.setJdk( populateInstallation( profile.getJdk(), newJdk ) ); } else { newProfile.setJdk( null ); } newProfile.getEnvironmentVariables().clear(); if ( profile.getEnvironmentVariables() != null ) { for ( final Installation varEnv : profile.getEnvironmentVariables() ) { final org.apache.maven.continuum.model.system.Installation newInst = continuum.getInstallationService().getInstallation( varEnv.getInstallationId() ); newProfile.getEnvironmentVariables().add( populateInstallation( varEnv, newInst ) ); } } return newProfile; } catch ( InstallationException e ) { throw new ContinuumException( "Can't load installations", e ); } } private Profile populateProfile( org.apache.maven.continuum.model.system.Profile profile ) { return (Profile) mapper.map( profile, Profile.class ); } private org.apache.maven.continuum.model.system.Installation populateInstallation( Installation install, org.apache.maven.continuum.model.system.Installation inst ) throws ContinuumException { if ( install == null ) { return null; } if ( StringUtils.isNotBlank( install.getName() ) && !install.getName().matches( NAME_VALID_EXPRESSION ) ) { throw new ContinuumException( "Installation Name contains invalid characters" ); } if ( StringUtils.isNotBlank( install.getType() ) && !install.getType().matches( INSTALLATION_TYPE_VALID_EXPRESSION ) ) { throw new ContinuumException( "Installation Type contains invalid characters" ); } if ( StringUtils.isNotBlank( install.getVarName() ) && !install.getVarName().matches( INSTALLATION_VARNAME_VALID_EXPRESSION ) ) { throw new ContinuumException( "Installation VarName contains invalid characters" ); } if ( StringUtils.isNotBlank( install.getVarValue() ) && !install.getVarValue().matches( INSTALLATION_VARVALUE_VALID_EXPRESSION ) ) { throw new ContinuumException( "Installation VarValue contains invalid characters" ); } inst.setName( install.getName() ); inst.setType( install.getType() ); inst.setVarName( install.getVarName() ); inst.setVarValue( install.getVarValue() ); return inst; } private Installation populateInstallation( org.apache.maven.continuum.model.system.Installation install ) { return (Installation) mapper.map( install, Installation.class ); } private SystemConfiguration populateSystemConfiguration( org.apache.maven.continuum.model.system.SystemConfiguration sysConf ) { return (SystemConfiguration) mapper.map( sysConf, SystemConfiguration.class ); } private ContinuumReleaseResult populateReleaseResult( org.apache.continuum.model.release.ContinuumReleaseResult releaseResult ) { return (ContinuumReleaseResult) mapper.map( releaseResult, ContinuumReleaseResult.class ); } private RepositoryPurgeConfiguration populateRepositoryPurgeConfiguration( org.apache.continuum.model.repository.RepositoryPurgeConfiguration repoPurgeConfig ) { return (RepositoryPurgeConfiguration) mapper.map( repoPurgeConfig, RepositoryPurgeConfiguration.class ); } private org.apache.continuum.model.repository.RepositoryPurgeConfiguration populateRepositoryPurgeConfiguration( RepositoryPurgeConfiguration repoPurgeConfig, org.apache.continuum.model.repository.RepositoryPurgeConfiguration repoPurge ) throws RepositoryServiceException, ContinuumException { if ( repoPurgeConfig == null ) { return null; } repoPurge.setDaysOlder( repoPurgeConfig.getDaysOlder() ); repoPurge.setDefaultPurge( repoPurgeConfig.isDefaultPurge() ); repoPurge.setDeleteAll( repoPurgeConfig.isDeleteAll() ); repoPurge.setDeleteReleasedSnapshots( repoPurgeConfig.isDeleteReleasedSnapshots() ); repoPurge.setDescription( StringEscapeUtils.escapeXml( repoPurgeConfig.getDescription() ) ); repoPurge.setEnabled( repoPurgeConfig.isEnabled() ); repoPurge.setRetentionCount( repoPurgeConfig.getRetentionCount() ); if ( repoPurgeConfig.getRepository() != null ) { repoPurge.setRepository( populateLocalRepository( repoPurgeConfig.getRepository(), continuum.getRepositoryService().getLocalRepository( repoPurgeConfig.getRepository().getId() ) ) ); } else { repoPurge.setRepository( null ); } if ( repoPurgeConfig.getSchedule() != null ) { repoPurge.setSchedule( populateSchedule( repoPurgeConfig.getSchedule(), continuum.getSchedule( repoPurgeConfig.getSchedule().getId() ) ) ); } else { repoPurge.setSchedule( null ); } return repoPurge; } private DirectoryPurgeConfiguration populateDirectoryPurgeConfiguration( org.apache.continuum.model.repository.DirectoryPurgeConfiguration dirPurgeConfig ) { return (DirectoryPurgeConfiguration) mapper.map( dirPurgeConfig, DirectoryPurgeConfiguration.class ); } private org.apache.continuum.model.repository.DirectoryPurgeConfiguration populateDirectoryPurgeConfiguration( DirectoryPurgeConfiguration dirPurgeConfig, org.apache.continuum.model.repository.DirectoryPurgeConfiguration dirPurge ) throws RepositoryServiceException, ContinuumException { if ( dirPurgeConfig == null ) { return null; } if ( StringUtils.isNotBlank( dirPurgeConfig.getDirectoryType() ) && !dirPurgeConfig.getDirectoryType().matches( DIRECTORY_TYPE_VALID_EXPRESSION ) ) { throw new ContinuumException( "Directory Purge Configuration Type can only be 'releases or buildOutput'" ); } if ( StringUtils.isNotBlank( dirPurgeConfig.getLocation() ) && !dirPurgeConfig.getLocation().matches( DIRECTORY_VALID_EXPRESSION ) ) { throw new ContinuumException( "Directory Purge Configuration Location contains invalid characters" ); } dirPurge.setDaysOlder( dirPurgeConfig.getDaysOlder() ); dirPurge.setDefaultPurge( dirPurgeConfig.isDefaultPurge() ); dirPurge.setDeleteAll( dirPurgeConfig.isDeleteAll() ); dirPurge.setDescription( StringEscapeUtils.escapeXml( dirPurgeConfig.getDescription() ) ); dirPurge.setDirectoryType( dirPurgeConfig.getDirectoryType() ); dirPurge.setEnabled( dirPurgeConfig.isEnabled() ); String path = ""; if ( dirPurge.getDirectoryType().equals( "releases" ) ) { path = continuum.getConfiguration().getWorkingDirectory().getAbsolutePath(); } else if ( dirPurge.getDirectoryType().equals( "buildOutput" ) ) { path = continuum.getConfiguration().getBuildOutputDirectory().getAbsolutePath(); } dirPurge.setLocation( path ); dirPurge.setRetentionCount( dirPurgeConfig.getRetentionCount() ); if ( dirPurgeConfig.getSchedule() != null ) { dirPurge.setSchedule( populateSchedule( dirPurgeConfig.getSchedule(), continuum.getSchedule( dirPurgeConfig.getSchedule().getId() ) ) ); } else { dirPurge.setSchedule( null ); } return dirPurge; } private LocalRepository populateLocalRepository( org.apache.continuum.model.repository.LocalRepository localRepository ) { return (LocalRepository) mapper.map( localRepository, LocalRepository.class ); } private org.apache.continuum.model.repository.LocalRepository populateLocalRepository( LocalRepository repository, org.apache.continuum.model.repository.LocalRepository repo ) throws ContinuumException { if ( repository == null ) { return null; } if ( StringUtils.isNotBlank( repository.getLayout() ) && !repository.getLayout().matches( REPOSITORY_LAYOUT_VALID_EXPRESSION ) ) { throw new ContinuumException( "Repository Layout can only be 'default or legacy'" ); } if ( StringUtils.isNotBlank( repository.getLocation() ) && !repository.getLocation().matches( DIRECTORY_VALID_EXPRESSION ) ) { throw new ContinuumException( "Repository Location contains invalid characters" ); } if ( StringUtils.isNotBlank( repository.getName() ) && !repository.getName().matches( NAME_VALID_EXPRESSION ) ) { throw new ContinuumException( "Repository Name contains invalid characters" ); } repo.setLayout( repository.getLayout() ); repo.setLocation( repository.getLocation() ); repo.setName( repository.getName() ); return repo; } private org.apache.continuum.utils.build.BuildTrigger populateBuildTrigger( BuildTrigger buildTrigger ) throws ContinuumException { if ( buildTrigger == null ) { return null; } if ( StringUtils.isNotBlank( buildTrigger.getTriggeredBy() ) && !buildTrigger.getTriggeredBy().matches( USERNAME_VALID_EXPRESSION ) ) { throw new ContinuumException( "BuildTrigger Triggered By contains invalid characters" ); } return new org.apache.continuum.utils.build.BuildTrigger( buildTrigger.getTrigger(), buildTrigger.getTriggeredBy() ); } private org.apache.continuum.configuration.BuildAgentConfiguration populateBuildAgent( BuildAgentConfiguration buildAgent ) throws ContinuumException { if ( buildAgent == null ) { return null; } if ( StringUtils.isNotBlank( buildAgent.getUrl() ) && !buildAgent.getUrl().matches( URL_VALID_EXPRESSION ) ) { throw new ContinuumException( "Build Agent URL contains invalid characters" ); } org.apache.continuum.configuration.BuildAgentConfiguration buildAgentConfiguration = new org.apache.continuum.configuration.BuildAgentConfiguration(); buildAgentConfiguration.setUrl( buildAgent.getUrl() ); buildAgentConfiguration.setDescription( StringEscapeUtils.escapeXml( buildAgent.getDescription() ) ); buildAgentConfiguration.setEnabled( buildAgent.isEnabled() ); return buildAgentConfiguration; } private BuildAgentConfiguration populateBuildAgent( org.apache.continuum.configuration.BuildAgentConfiguration buildAgent ) { BuildAgentConfiguration buildAgentConfiguration = (BuildAgentConfiguration) mapper.map( buildAgent, BuildAgentConfiguration.class ); try { buildAgentConfiguration.setPlatform( distributedBuildManager.getBuildAgentPlatform( buildAgentConfiguration.getUrl() ) ); return buildAgentConfiguration; } catch ( ContinuumException e ) { logger.warn( "Unable to connect to build agent " + buildAgentConfiguration.getUrl() + ".", e ); buildAgentConfiguration.setPlatform( "" ); return buildAgentConfiguration; } } private org.apache.continuum.configuration.BuildAgentGroupConfiguration populateBuildAgentGroup( BuildAgentGroupConfiguration buildAgentGroup ) throws ContinuumException { if ( buildAgentGroup == null ) { return null; } org.apache.continuum.configuration.BuildAgentGroupConfiguration buildAgentGroupConfiguration = new org.apache.continuum.configuration.BuildAgentGroupConfiguration(); if ( StringUtils.isBlank( buildAgentGroup.getName() ) ) { throw new ContinuumException( "Build agent group name is required" ); } buildAgentGroupConfiguration.setName( StringEscapeUtils.escapeXml( buildAgentGroup.getName() ) ); buildAgentGroupConfiguration.getBuildAgents().clear(); if ( buildAgentGroup.getBuildAgents() != null ) { for ( BuildAgentConfiguration buildAgent : buildAgentGroup.getBuildAgents() ) { buildAgentGroupConfiguration.getBuildAgents().add( populateBuildAgent( buildAgent ) ); } } return buildAgentGroupConfiguration; } private BuildAgentGroupConfiguration populateBuildAgentGroup( org.apache.continuum.configuration.BuildAgentGroupConfiguration buildAgentGroup ) { return (BuildAgentGroupConfiguration) mapper.map( buildAgentGroup, BuildAgentGroupConfiguration.class ); } private Map<String, Object> serializeObject( Object o, final String... ignore ) { if ( o != null ) { return serializeObject( o, o.getClass(), ignore ); } else { return null; } } private Map<String, Object> serializeObject( Object o, Class clasz, final String... ignore ) { final List<String> ignoreList = ignore == null ? new ArrayList<String>() : Arrays.asList( ignore ); if ( o != null ) { final Map<String, Object> retValue = new HashMap<String, Object>(); if ( !Object.class.equals( clasz.getSuperclass() ) ) { retValue.putAll( serializeObject( o, clasz.getSuperclass(), ignore ) ); } final Field[] fields = clasz.getDeclaredFields(); retValue.put( "__class", clasz.getName() ); for ( final Field field : fields ) { if ( !ignoreList.contains( field.getName() ) ) { field.setAccessible( true ); try { final Object tmpFO = field.get( o ); final Object tmpNO = mapObject( tmpFO ); retValue.put( field.getName(), tmpNO ); } catch ( IllegalAccessException e ) { e.printStackTrace(); } } } return retValue; } else { return null; } } private Object mapObject( Object tmpFO ) { final Object retValue; if ( tmpFO instanceof String ) { Object tmpNO = serializeObject( (String) tmpFO ); if ( tmpNO == null ) { tmpNO = ""; } retValue = tmpNO; } else if ( tmpFO instanceof Float ) { Object tmpNO = serializeObject( (Float) tmpFO ); if ( tmpNO == null ) { tmpNO = ""; } retValue = tmpNO; } else if ( tmpFO instanceof Boolean ) { Object tmpNO = serializeObject( (Boolean) tmpFO ); if ( tmpNO == null ) { tmpNO = ""; } retValue = tmpNO; } else if ( tmpFO instanceof Integer ) { Object tmpNO = serializeObject( (Integer) tmpFO ); if ( tmpNO == null ) { tmpNO = ""; } retValue = tmpNO; } else if ( tmpFO instanceof Long ) { Object tmpNO = serializeObject( (Long) tmpFO ); if ( tmpNO == null ) { tmpNO = ""; } retValue = tmpNO; } else if ( tmpFO instanceof Character ) { Object tmpNO = serializeObject( (Character) tmpFO ); if ( tmpNO == null ) { tmpNO = ""; } retValue = tmpNO; } else if ( tmpFO instanceof Byte ) { Object tmpNO = serializeObject( (Byte) tmpFO ); if ( tmpNO == null ) { tmpNO = ""; } retValue = tmpNO; } else if ( tmpFO instanceof Double ) { Object tmpNO = serializeObject( (Double) tmpFO ); if ( tmpNO == null ) { tmpNO = ""; } retValue = tmpNO; } else if ( tmpFO instanceof List ) { Object tmpNO = serializeObject( (List) tmpFO ); if ( tmpNO == null ) { tmpNO = ""; } retValue = tmpNO; } else if ( tmpFO instanceof Map ) { Object tmpNO = serializeObject( (Map) tmpFO ); if ( tmpNO == null ) { tmpNO = ""; } retValue = tmpNO; } else { Object tmpNO = serializeObject( tmpFO ); if ( tmpNO == null ) { tmpNO = ""; } retValue = tmpNO; } return retValue; } private Map<String, Object> serializeObject( Map<Object, Object> map ) { final Map<String, Object> retValue = new HashMap<String, Object>(); for ( Object key : map.keySet() ) { final Object tmpKey = mapObject( key ); if ( tmpKey != null ) { retValue.put( tmpKey.toString(), mapObject( map.get( key ) ) ); } } return retValue; } private List<Object> serializeObject( List list ) { final List<Object> retValue = new ArrayList<Object>(); for ( Object o : list ) { final Object tmpO = mapObject( o ); if ( tmpO == null ) { retValue.add( "" ); } else { retValue.add( tmpO ); } } return retValue; } private String serializeObject( String o ) { return o; } private String serializeObject( Byte o ) { return ( o == null ? null : o.toString() ); } private String serializeObject( Character o ) { return ( o == null ? null : o.toString() ); } private Double serializeObject( Long o ) { return ( o == null ? null : o.doubleValue() ); } private Double serializeObject( Float o ) { return ( o == null ? null : o.doubleValue() ); } private Double serializeObject( Double o ) { return o; } private Integer serializeObject( Integer o ) { return o; } private Boolean serializeObject( Boolean o ) { return o; } private Object unserializeObject( Map<String, Object> o ) { Object retValue = null; if ( o != null ) { final String className = (String) o.remove( "__class" ); if ( className != null ) { try { final Class clasz = Class.forName( className ); final Object tmpO = clasz.newInstance(); for ( final String key : o.keySet() ) { final Field field = clasz.getDeclaredField( key ); field.setAccessible( true ); final Object tmpFO = o.get( key ); field.set( tmpO, unMapObject( tmpFO ) ); } retValue = tmpO; } catch ( Exception e ) { e.printStackTrace(); retValue = null; } } else { // Not an object, it's a normal Map Map<String, Object> tmpValue = new HashMap<String, Object>(); for ( String key : o.keySet() ) { tmpValue.put( key, unMapObject( o.get( key ) ) ); } retValue = tmpValue; } } return retValue; } private Object unMapObject( Object tmpFO ) { final Object retValue; if ( tmpFO instanceof String ) { retValue = unserializeObject( (String) tmpFO ); } else if ( tmpFO instanceof Float ) { retValue = unserializeObject( (Float) tmpFO ); } else if ( tmpFO instanceof Boolean ) { retValue = unserializeObject( (Boolean) tmpFO ); } else if ( tmpFO instanceof Integer ) { retValue = unserializeObject( (Integer) tmpFO ); } else if ( tmpFO instanceof Long ) { retValue = unserializeObject( (Long) tmpFO ); } else if ( tmpFO instanceof Character ) { retValue = unserializeObject( (Character) tmpFO ); } else if ( tmpFO instanceof Byte ) { retValue = unserializeObject( (Byte) tmpFO ); } else if ( tmpFO instanceof Double ) { retValue = unserializeObject( (Double) tmpFO ); } else if ( tmpFO instanceof List ) { retValue = unserializeObject( (List) tmpFO ); } else if ( tmpFO instanceof Map ) { retValue = unserializeObject( (Map) tmpFO ); } else if ( tmpFO instanceof Object[] ) { retValue = unserializeObject( (Object[]) tmpFO ); } else { retValue = unserializeObject( tmpFO ); } return retValue; } private List<Object> unserializeObject( List list ) { final List<Object> retValue = new ArrayList<Object>(); for ( Object o : list ) { retValue.add( unMapObject( o ) ); } return retValue; } private Object unserializeObject( Object o ) { return o; } private Object unserializeObject( Object[] list ) { final List<Object> retValue = new ArrayList<Object>(); for ( Object o : list ) { retValue.add( unMapObject( o ) ); } return retValue; } private String unserializeObject( String o ) { return o; } private Byte unserializeObject( Byte o ) { return o; } private Character unserializeObject( Character o ) { return o; } private Long unserializeObject( Long o ) { return o; } private Float unserializeObject( Float o ) { return o; } private Double unserializeObject( Double o ) { return o; } private Integer unserializeObject( Integer o ) { return o; } private Boolean unserializeObject( Boolean o ) { return o; } public Map<String, Object> addAntProjectRPC( Map<String, Object> project, int projectGroupId ) throws Exception { return serializeObject( this.addAntProject( (ProjectSummary) unserializeObject( project ), projectGroupId ) ); } public Map<String, Object> addBuildDefinitionToProjectGroupRPC( int projectGroupId, Map<String, Object> buildDef ) throws Exception { return serializeObject( this.addBuildDefinitionToProjectGroup( projectGroupId, (BuildDefinition) unserializeObject( buildDef ) ) ); } public Map<String, Object> addBuildDefinitionToProjectRPC( int projectId, Map<String, Object> buildDef ) throws Exception { return serializeObject( this.addBuildDefinitionToProject( projectId, (BuildDefinition) unserializeObject( buildDef ) ) ); } public Map<String, Object> addMavenOneProjectRPC( String url, int projectGroupId ) throws Exception { return serializeObject( this.addMavenOneProject( url, projectGroupId ) ); } public Map<String, Object> addMavenTwoProjectRPC( String url ) throws Exception { return serializeObject( this.addMavenTwoProject( url ) ); } public Map<String, Object> addMavenTwoProjectRPC( String url, int projectGroupId ) throws Exception { return serializeObject( this.addMavenTwoProject( url, projectGroupId ) ); } public Map<String, Object> addMavenTwoProjectRPC( String url, int projectGroupId, boolean checkoutInSingleDirectory ) throws Exception { return serializeObject( this.addMavenTwoProject( url, projectGroupId, checkoutInSingleDirectory ) ); } public Map<String, Object> addMavenTwoProjectAsSingleProjectRPC( String url, int projectGroupId ) throws Exception { return serializeObject( this.addMavenTwoProjectAsSingleProject( url, projectGroupId ) ); } public Map<String, Object> addMavenTwoProjectRPC( String url, int projectGroupId, boolean checkProtocol, boolean useCredentialsCache, boolean recursiveProjects, boolean checkoutInSingleDirectory ) throws Exception { return serializeObject( this.addMavenTwoProject( url, projectGroupId, checkProtocol, useCredentialsCache, recursiveProjects, checkoutInSingleDirectory ) ); } public Map<String, Object> addProjectGroupRPC( String groupName, String groupId, String description ) throws Exception { return serializeObject( this.addProjectGroup( groupName, groupId, description ) ); } public Map<String, Object> addScheduleRPC( Map<String, Object> schedule ) throws Exception { return serializeObject( this.addSchedule( (Schedule) unserializeObject( schedule ) ) ); } public Map<String, Object> addShellProjectRPC( Map<String, Object> project, int projectGroupId ) throws Exception { return serializeObject( this.addShellProject( (ProjectSummary) unserializeObject( project ), projectGroupId ) ); } public List<Object> getAllProjectGroupsRPC() throws Exception { return serializeObject( this.getAllProjectGroups() ); } public List<Object> getAllProjectGroupsWithAllDetailsRPC() throws Exception { return serializeObject( this.getAllProjectGroupsWithAllDetails() ); } public List<Object> getBuildDefinitionTemplatesRPC() throws Exception { return serializeObject( this.getBuildDefinitionTemplates() ); } public List<Object> getBuildDefinitionsForProjectGroupRPC( int projectGroupId ) throws Exception { return serializeObject( this.getBuildDefinitionsForProjectGroup( projectGroupId ) ); } public List<Object> getBuildDefinitionsForProjectRPC( int projectId ) throws Exception { return serializeObject( this.getBuildDefinitionsForProject( projectId ) ); } public Map<String, Object> getBuildDefinitionRPC( int buildDefinitionId ) throws Exception { return serializeObject( this.getBuildDefinition( buildDefinitionId ) ); } public Map<String, Object> getBuildResultRPC( int projectId, int buildId ) throws Exception { return serializeObject( this.getBuildResult( projectId, buildId ) ); } public List<Object> getBuildResultsForProjectRPC( int projectId, int offset, int length ) throws Exception { return serializeObject( this.getBuildResultsForProject( projectId, offset, length ) ); } public Map<String, Object> getInstallationRPC( int installationId ) throws Exception { return serializeObject( this.getInstallation( installationId ) ); } public Map<String, Object> getInstallationRPC( String installationName ) throws Exception { return serializeObject( this.getInstallation( installationName ) ); } public List<Object> getInstallationsRPC() throws Exception { return serializeObject( this.getInstallations() ); } public List<Object> getBuildAgentInstallationsRPC( String url ) throws Exception { return serializeObject( this.getBuildAgentInstallations( url ) ); } public Map<String, Object> getLatestBuildResultRPC( int projectId ) throws Exception { return serializeObject( this.getLatestBuildResult( projectId ) ); } public Map<String, Object> getProfileRPC( int profileId ) throws Exception { return serializeObject( this.getProfile( profileId ) ); } public Map<String, Object> getProfileWithNameRPC( String profileName ) throws Exception { return serializeObject( this.getProfileWithName( profileName ) ); } public List<Object> getProfilesRPC() throws Exception { return serializeObject( this.getProfiles() ); } public Map<String, Object> getProjectGroupSummaryRPC( int projectGroupId ) throws Exception { return serializeObject( this.getProjectGroupSummary( projectGroupId ) ); } public Map<String, Object> getProjectGroupWithProjectsRPC( int projectGroupId ) throws Exception { return serializeObject( this.getProjectGroupWithProjects( projectGroupId ) ); } public Map<String, Object> updateProjectGroupRPC( Map<String, Object> projectGroup ) throws Exception { return serializeObject( this.updateProjectGroup( (ProjectGroupSummary) unserializeObject( projectGroup ) ) ); } public Map<String, Object> getProjectSummaryRPC( int projectId ) throws Exception { return serializeObject( this.getProjectSummary( projectId ) ); } public Map<String, Object> getProjectWithAllDetailsRPC( int projectId ) throws Exception { return serializeObject( this.getProjectWithAllDetails( projectId ) ); } public List<Object> getProjectsRPC( int projectGroupId ) throws Exception { return serializeObject( this.getProjects( projectGroupId ) ); } public Map<String, Object> getScheduleRPC( int scheduleId ) throws Exception { return serializeObject( this.getSchedule( scheduleId ) ); } public List<Object> getSchedulesRPC() throws Exception { return serializeObject( this.getSchedules() ); } public Map<String, Object> getSystemConfigurationRPC() throws Exception { return serializeObject( this.getSystemConfiguration() ); } public int removeBuildResultRPC( Map<String, Object> br ) throws Exception { return serializeObject( this.removeBuildResult( (BuildResult) unserializeObject( br ) ) ); } public Map<String, Object> updateBuildDefinitionForProjectGroupRPC( int projectGroupId, Map<String, Object> buildDef ) throws Exception { return serializeObject( this.updateBuildDefinitionForProjectGroup( projectGroupId, (BuildDefinition) unserializeObject( buildDef ) ) ); } public Map<String, Object> updateBuildDefinitionForProjectRPC( int projectId, Map<String, Object> buildDef ) throws Exception { return serializeObject( this.updateBuildDefinitionForProject( projectId, (BuildDefinition) unserializeObject( buildDef ) ) ); } public Map<String, Object> updateProjectRPC( Map<String, Object> project ) throws Exception { return serializeObject( this.updateProject( (ProjectSummary) unserializeObject( project ) ) ); } public Map<String, Object> updateScheduleRPC( Map<String, Object> schedule ) throws Exception { return serializeObject( this.updateSchedule( (Schedule) unserializeObject( schedule ) ) ); } public Map<String, Object> getProjectGroupRPC( int projectGroupId ) throws Exception { return serializeObject( this.getProjectGroup( projectGroupId ), "projects" ); } public Map<String, Object> getGroupNotifierRPC( int projectgroupid, int notifierId ) throws Exception { return serializeObject( this.getGroupNotifier( projectgroupid, notifierId ) ); } public Map<String, Object> getNotifierRPC( int projectid, int notifierId ) throws Exception { return serializeObject( this.getNotifier( projectid, notifierId ) ); } public Map<String, Object> updateGroupNotifierRPC( int projectgroupid, Map<String, Object> newNotifier ) throws Exception { return serializeObject( this.updateGroupNotifier( projectgroupid, (ProjectNotifier) unserializeObject( newNotifier ) ) ); } public Map<String, Object> updateNotifierRPC( int projectid, Map<String, Object> newNotifier ) throws Exception { return serializeObject( this.updateNotifier( projectid, (ProjectNotifier) unserializeObject( newNotifier ) ) ); } public Map<String, Object> addGroupNotifierRPC( int projectgroupid, Map<String, Object> newNotifier ) throws Exception { return serializeObject( this.addGroupNotifier( projectgroupid, (ProjectNotifier) unserializeObject( newNotifier ) ) ); } public Map<String, Object> addNotifierRPC( int projectid, Map<String, Object> newNotifier ) throws Exception { return serializeObject( this.addNotifier( projectid, (ProjectNotifier) unserializeObject( newNotifier ) ) ); } public Map<String, Object> addInstallationRPC( Map<String, Object> installation ) throws Exception { return serializeObject( this.addInstallation( (Installation) unserializeObject( installation ) ) ); } public Map<String, Object> addProfileRPC( Map<String, Object> profile ) throws Exception { return serializeObject( this.addProfile( (Profile) unserializeObject( profile ) ) ); } public int updateInstallationRPC( Map<String, Object> installation ) throws Exception { return this.updateInstallation( (Installation) unserializeObject( installation ) ); } public int updateProfileRPC( Map<String, Object> profile ) throws Exception { return this.updateProfile( (Profile) unserializeObject( profile ) ); } public Map<String, Object> getReleaseResultRPC( int releaseId ) throws Exception { return serializeObject( this.getReleaseResult( releaseId ) ); } public List<Object> getReleaseResultsForProjectGroupRPC( int projectGroupId ) throws Exception { return serializeObject( this.getReleaseResultsForProjectGroup( projectGroupId ) ); } public int removeReleaseResultRPC( Map<String, Object> rr ) throws Exception { return serializeObject( this.removeReleaseResult( (ContinuumReleaseResult) unserializeObject( rr ) ) ); } public Map<String, Object> addRepositoryPurgeConfigurationRPC( Map<String, Object> repoPurge ) throws Exception { return serializeObject( this.addRepositoryPurgeConfiguration( (RepositoryPurgeConfiguration) unserializeObject( repoPurge ) ) ); } public int updateRepositoryPurgeConfigurationRPC( Map<String, Object> repoPurge ) throws Exception { return serializeObject( this.updateRepositoryPurgeConfiguration( (RepositoryPurgeConfiguration) unserializeObject( repoPurge ) ) ); } public Map<String, Object> getRepositoryPurgeConfigurationRPC( int repoPurgeId ) throws Exception { return serializeObject( this.getRepositoryPurgeConfiguration( repoPurgeId ) ); } public List<Object> getAllRepositoryPurgeConfigurationsRPC() throws Exception { return serializeObject( this.getAllDirectoryPurgeConfigurations() ); } public Map<String, Object> addDirectoryPurgeConfigurationRPC( Map<String, Object> dirPurge ) throws Exception { return serializeObject( this.addDirectoryPurgeConfiguration( (DirectoryPurgeConfiguration) unserializeObject( dirPurge ) ) ); } public int updateDirectoryPurgeConfigurationRPC( Map<String, Object> dirPurge ) throws Exception { return serializeObject( this.updateDirectoryPurgeConfiguration( (DirectoryPurgeConfiguration) unserializeObject( dirPurge ) ) ); } public Map<String, Object> getDirectoryPurgeConfigurationRPC( int dirPurgeId ) throws Exception { return serializeObject( this.getDirectoryPurgeConfiguration( dirPurgeId ) ); } public List<Object> getAllDirectoryPurgeConfigurationsRPC() throws Exception { return serializeObject( this.getAllRepositoryPurgeConfigurations() ); } public Map<String, Object> addLocalRepositoryRPC( Map<String, Object> repository ) throws Exception { return serializeObject( this.addLocalRepository( (LocalRepository) unserializeObject( repository ) ) ); } public int updateLocalRepositoryRPC( Map<String, Object> repository ) throws Exception { return serializeObject( this.updateLocalRepository( (LocalRepository) unserializeObject( repository ) ) ); } public Map<String, Object> getLocalRepositoryRPC( int repositoryId ) throws Exception { return serializeObject( this.getLocalRepository( repositoryId ) ); } public List<Object> getAllLocalRepositoriesRPC() throws Exception { return serializeObject( this.getAllLocalRepositories() ); } public Map<String, Object> addBuildAgentRPC( Map<String, Object> buildAgentConfiguration ) throws Exception { return serializeObject( this.addBuildAgent( (BuildAgentConfiguration) unserializeObject( buildAgentConfiguration ) ) ); } public Map<String, Object> getBuildAgentRPC( String url ) { return serializeObject( this.getBuildAgent( url ) ); } public Map<String, Object> updateBuildAgentRPC( Map<String, Object> buildAgentConfiguration ) throws ConfigurationStoringException, ContinuumConfigurationException { return serializeObject( this.updateBuildAgent( (BuildAgentConfiguration) unserializeObject( buildAgentConfiguration ) ) ); } public List<Object> getAllBuildAgentsRPC() { return serializeObject( this.getAllBuildAgents() ); } public List<Object> getBuildAgentsWithInstallationsRPC() throws Exception { return serializeObject( this.getBuildAgentsWithInstallations() ); } public Map<String, Object> addBuildAgentGroupRPC( Map<String, Object> buildAgentGroup ) throws ConfigurationException, ConfigurationStoringException, ContinuumConfigurationException { return serializeObject( this.addBuildAgentGroup( (BuildAgentGroupConfiguration) unserializeObject( buildAgentGroup ) ) ); } public Map<String, Object> getBuildAgentGroupRPC( String name ) { return serializeObject( this.getBuildAgentGroup( name ) ); } public Map<String, Object> updateBuildAgentGroupRPC( Map<String, Object> buildAgentGroup ) throws ConfigurationException, ConfigurationStoringException, ContinuumConfigurationException { return serializeObject( this.updateBuildAgentGroup( (BuildAgentGroupConfiguration) unserializeObject( buildAgentGroup ) ) ); } public String releasePrepare( int projectId, Properties releaseProperties, Map<String, String> releaseVersions, Map<String, String> developmentVersions, Map<String, String> environments, String username ) throws Exception { org.apache.maven.continuum.model.project.Project project = continuum.getProject( projectId ); if ( project != null ) { checkBuildProjectInGroupAuthorization( project.getProjectGroup().getName() ); if ( continuum.getConfiguration().isDistributedBuildEnabled() ) { return continuum.getDistributedReleaseManager().releasePrepare( project, releaseProperties, releaseVersions, developmentVersions, environments, username ); } else { String executable = null; if ( environments != null ) { String m2Home = environments.get( continuum.getInstallationService().getEnvVar( InstallationService.MAVEN2_TYPE ) ); if ( StringUtils.isNotEmpty( m2Home ) ) { executable = m2Home + File.separator + "bin" + File.separator + executable; } } releaseProperties.setProperty( "release-by", username ); return continuum.getReleaseManager().prepare( project, releaseProperties, releaseVersions, developmentVersions, null, continuum.getWorkingDirectory( projectId ).getPath(), environments, executable ); } } else { throw new Exception( "Unable to prepare release project with id : " + projectId + " because it doesn't exist" ); } } public int releasePerform( int projectId, String releaseId, String goals, String arguments, boolean useReleaseProfile, String repositoryName, String username ) throws Exception { org.apache.maven.continuum.model.project.Project project = continuum.getProject( projectId ); if ( project != null ) { checkBuildProjectInGroupAuthorization( project.getProjectGroup().getName() ); org.apache.continuum.model.repository.LocalRepository repository = continuum.getRepositoryService().getLocalRepositoryByName( repositoryName ); if ( continuum.getConfiguration().isDistributedBuildEnabled() ) { continuum.getDistributedReleaseManager().releasePerform( projectId, releaseId, goals, arguments, useReleaseProfile, repository, username ); } else { File performDirectory = new File( continuum.getConfiguration().getWorkingDirectory(), "releases-" + System.currentTimeMillis() ); performDirectory.mkdirs(); continuum.getReleaseManager().perform( releaseId, performDirectory, goals, arguments, useReleaseProfile, null, repository ); } return 0; } else { throw new Exception( "Unable to perform release project with id : " + projectId + " because it doesn't exist" ); } } public ReleaseListenerSummary getListener( int projectId, String releaseId ) throws Exception { org.apache.maven.continuum.model.project.Project project = continuum.getProject( projectId ); if ( project != null ) { checkBuildProjectInGroupAuthorization( project.getProjectGroup().getName() ); if ( continuum.getConfiguration().isDistributedBuildEnabled() ) { Map<String, Object> map = continuum.getDistributedReleaseManager().getListener( releaseId ); return processListenerMap( map ); } else { return populateReleaseListenerSummary( continuum.getReleaseManager().getListener( releaseId ) ); } } else { throw new Exception( "Unable to get release listener for '" + releaseId + "'" ); } } public int releaseCleanup( int projectId, String releaseId ) throws Exception { return releaseCleanup( projectId, releaseId, null ); } public int releaseCleanup( int projectId, String releaseId, String releaseType ) throws Exception { org.apache.maven.continuum.model.project.Project project = continuum.getProject( projectId ); if ( project != null ) { checkBuildProjectInGroupAuthorization( project.getProjectGroup().getName() ); org.apache.continuum.model.release.ContinuumReleaseResult result = continuum.addContinuumReleaseResult( projectId, releaseId, releaseType ); if ( continuum.getConfiguration().isDistributedBuildEnabled() ) { continuum.getDistributedReleaseManager().releaseCleanup( releaseId ); } else { continuum.getReleaseManager().getReleaseResults().remove( releaseId ); continuum.getReleaseManager().getListeners().remove( releaseId ); } return result != null ? result.getId() : 0; } else { throw new Exception( "Unable to do release cleanup for release '" + releaseId + "'" ); } } public int releaseRollback( int projectId, String releaseId ) throws Exception { org.apache.maven.continuum.model.project.Project project = continuum.getProject( projectId ); if ( project != null ) { checkBuildProjectInGroupAuthorization( project.getProjectGroup().getName() ); if ( continuum.getConfiguration().isDistributedBuildEnabled() ) { continuum.getDistributedReleaseManager().releaseRollback( releaseId, projectId ); } else { continuum.getReleaseManager().rollback( releaseId, continuum.getWorkingDirectory( projectId ).getPath(), null ); continuum.getReleaseManager().getPreparedReleases().remove( releaseId ); } return 0; } else { throw new Exception( "Unable to rollback the release for '" + releaseId + "'" ); } } public Map<String, Object> getReleasePluginParameters( int projectId ) throws Exception { org.apache.maven.continuum.model.project.Project project = continuum.getProject( projectId ); if ( project != null ) { checkBuildProjectInGroupAuthorization( project.getProjectGroup().getName() ); Map<String, Object> params; if ( continuum.getConfiguration().isDistributedBuildEnabled() ) { params = continuum.getDistributedReleaseManager().getReleasePluginParameters( projectId, "pom.xml" ); } else { ArtifactRepository localRepo = localRepositoryHelper.getLocalRepository( project.getProjectGroup().getLocalRepository() ); params = releaseHelper.extractPluginParameters( localRepo, continuum.getWorkingDirectory( projectId ).getPath(), "pom.xml" ); } // set scm tag and scm tag base if no values yet // scm tag if ( StringUtils.isBlank( (String) params.get( "scm-tag" ) ) ) { String scmTag; if ( project.getScmTag() != null ) { scmTag = project.getScmTag(); } else { String version = project.getVersion(); int idx = version.indexOf( "-SNAPSHOT" ); if ( idx >= 0 ) { // strip the snapshot version suffix scmTag = project.getArtifactId() + "-" + version.substring( 0, idx ); } else { scmTag = project.getArtifactId() + "-" + version; } } continuum.getReleaseManager().sanitizeTagName( project.getScmUrl(), scmTag ); params.put( "scm-tag", scmTag ); } // scm tagbase if ( StringUtils.isBlank( (String) params.get( "scm-tagbase" ) ) ) { if ( project.getScmUrl().startsWith( "scm:svn" ) ) { String scmTagBase = new SvnScmProviderRepository( project.getScmUrl(), project.getScmUsername(), project.getScmPassword() ).getTagBase(); // strip the Maven scm protocol prefix params.put( "scm-tagbase", scmTagBase.substring( "scm:svn".length() + 1 ) ); } else { params.put( "scm-tagbase", "" ); } } return params; } else { throw new Exception( "Unable to get release plugin parameters for project with id " + projectId ); } } public List<Map<String, String>> getProjectReleaseAndDevelopmentVersions( int projectId, String pomFilename, boolean autoVersionSubmodules ) throws Exception { org.apache.maven.continuum.model.project.Project project = continuum.getProject( projectId ); if ( project != null ) { checkBuildProjectInGroupAuthorization( project.getProjectGroup().getName() ); List<Map<String, String>> projects = new ArrayList<Map<String, String>>(); if ( continuum.getConfiguration().isDistributedBuildEnabled() ) { projects = continuum.getDistributedReleaseManager().processProject( projectId, pomFilename, autoVersionSubmodules ); } else { ArtifactRepository localRepo = localRepositoryHelper.getLocalRepository( project.getProjectGroup().getLocalRepository() ); releaseHelper.buildVersionParams( localRepo, continuum.getWorkingDirectory( projectId ).getPath(), pomFilename, autoVersionSubmodules, projects ); } return projects; } else { throw new Exception( "Unable to get release plugin parameters for project with id " + projectId ); } } private ReleaseListenerSummary processListenerMap( Map<String, Object> context ) { ReleaseListenerSummary listenerSummary = new ReleaseListenerSummary(); Object value = context.get( "release-in-progress" ); if ( value != null ) { listenerSummary.setInProgress( (String) value ); } value = context.get( "release-error" ); if ( value != null ) { listenerSummary.setError( (String) value ); } value = context.get( "username" ); if ( value != null ) { listenerSummary.setUsername( (String) value ); } value = context.get( "state" ); if ( value != null ) { listenerSummary.setState( (Integer) value ); } value = context.get( "release-phases" ); if ( value != null ) { listenerSummary.setPhases( getList( value ) ); } value = context.get( "completed-release-phases" ); if ( value != null ) { listenerSummary.setCompletedPhases( getList( value ) ); } return listenerSummary; } private ReleaseListenerSummary populateReleaseListenerSummary( org.apache.continuum.model.release.ReleaseListenerSummary listener ) { return (ReleaseListenerSummary) mapper.map( listener, ReleaseListenerSummary.class ); } public boolean pingBuildAgent( String buildAgentUrl ) throws Exception { return distributedBuildManager.pingBuildAgent( buildAgentUrl ); } private List<String> getList( Object obj ) { List<String> list = new ArrayList<String>(); if ( obj instanceof String[] ) { list.addAll( Arrays.asList( (String[]) obj ) ); } else if ( obj instanceof Object[] ) { // fallback needed since XMLRPC to the build agent will return a List<String> as Object[] for ( Object o : (Object[]) obj ) { list.add( (String) o ); } } else { list = (List<String>) obj; } return list; } // testing public void setContinuum( Continuum continuum ) { this.continuum = continuum; } public void setDistributedBuildManager( DistributedBuildManager distributedBuildManager ) { this.distributedBuildManager = distributedBuildManager; } public void setRoleManager( RoleManager roleManager ) { this.roleManager = roleManager; } }
5,179
0
Create_ds/continuum/continuum-xmlrpc/continuum-xmlrpc-server/src/main/java/org/apache/maven/continuum/xmlrpc
Create_ds/continuum/continuum-xmlrpc/continuum-xmlrpc-server/src/main/java/org/apache/maven/continuum/xmlrpc/server/AddingResultUtil.java
package org.apache.maven.continuum.xmlrpc.server; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.HashMap; import java.util.Map; public class AddingResultUtil { private static final Map<String, String> errorMap; static { errorMap = new HashMap<String, String>(); errorMap.put( "add.project.unknown.host.error", "The specified host is either unknown or inaccessible." ); errorMap.put( "add.project.connect.error", "Unable to connect to remote server." ); errorMap.put( "add.project.malformed.url.error", "The URL provided is malformed." ); errorMap.put( "add.project.field.required.error", "Either POM URL or Upload POM is required." ); errorMap.put( "add.project.xml.parse.error", "The XML content of the POM can not be parsed." ); errorMap.put( "add.project.extend.error", "Cannot use a POM with an ''extend'' element." ); errorMap.put( "add.project.missing.pom.error", "POM file does not exist. Either the POM you specified or one of its modules does not exist." ); errorMap.put( "add.project.missing.groupid.error", "Missing 'groupId' element in the POM." ); errorMap.put( "add.project.missing.artifactid.error", "Missing 'artifactId' element in the POM." ); errorMap.put( "add.project.missing.version.error", "Missing 'version' element in the POM." ); errorMap.put( "add.project.missing.name.error", "Missing 'name' element in the POM." ); errorMap.put( "add.project.missing.repository.error", "Missing 'repository' element in the POM." ); errorMap.put( "add.project.missing.scm.error", "Missing 'scm' element in the POM project." ); errorMap.put( "add.project.missing.scm.connection.error", "Missing 'connection' sub-element in the 'scm' element in the POM." ); errorMap.put( "add.project.missing.notifier.type.error", "Missing 'type' sub-element in the 'notifier' element in the POM." ); errorMap.put( "add.project.missing.notifier.configuration.error", "Missing 'configuration' sub-element in the 'notifier' element in the POM." ); errorMap.put( "add.project.metadata.transfer.error", "Transfer of Metadata has failed." ); errorMap.put( "add.project.validation.protocol.not_allowed", "The specified resource isn't a file or the protocol used isn't allowed." ); errorMap.put( "add.project.unauthorized.error", "You are not authorized to access the requested URL. Please verify that the correct username and password are provided." ); errorMap.put( "add.project.artifact.not.found.error", "Missing artifact trying to build the POM. Check that its parent POM is available or add it first in Continuum." ); errorMap.put( "add.project.project.building.error", "Unknown error trying to build POM." ); errorMap.put( "add.project.unknown.error", "The specified resource cannot be accessed. Please try again later or contact your administrator." ); errorMap.put( "add.project.nogroup.error", "No project group specified." ); errorMap.put( "add.project.duplicate.error", "Trying to add duplicate projects in the same project group." ); } public static String getErrorMessage( String error ) { String message = errorMap.get( error ); return message == null ? error : message; } }
5,180
0
Create_ds/continuum/continuum-xmlrpc/continuum-xmlrpc-server/src/main/java/org/apache/maven/continuum/xmlrpc
Create_ds/continuum/continuum-xmlrpc/continuum-xmlrpc-server/src/main/java/org/apache/maven/continuum/xmlrpc/server/PropertiesHandlerMapping.java
package org.apache.maven.continuum.xmlrpc.server; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.xmlrpc.XmlRpcException; import org.apache.xmlrpc.XmlRpcHandler; import org.apache.xmlrpc.server.PropertyHandlerMapping; import org.apache.xmlrpc.server.RequestProcessorFactoryFactory; import org.codehaus.plexus.PlexusConstants; import org.codehaus.plexus.PlexusContainer; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.context.Context; import org.codehaus.plexus.context.ContextException; import org.codehaus.plexus.personality.plexus.lifecycle.phase.Contextualizable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.reflect.Method; import java.util.Map; /** * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a> */ @Component( role = org.apache.xmlrpc.server.PropertyHandlerMapping.class ) public class PropertiesHandlerMapping extends PropertyHandlerMapping implements Contextualizable { private static final Logger log = LoggerFactory.getLogger( PropertiesHandlerMapping.class ); @Requirement( role = org.apache.maven.continuum.xmlrpc.server.ContinuumXmlRpcComponent.class ) private Map<String, Object> xmlrpcComponents; private PlexusContainer container; public void load() throws XmlRpcException { for ( String key : xmlrpcComponents.keySet() ) { Class cl = xmlrpcComponents.get( key ).getClass(); if ( log.isDebugEnabled() ) { log.debug( key + " => " + cl.getName() ); } registerPublicMethods( key, cl ); } if ( log.isDebugEnabled() ) { String[] methods = getListMethods(); for ( String method : methods ) { log.debug( method ); } } } protected XmlRpcHandler newXmlRpcHandler( final Class pClass, final Method[] pMethods ) throws XmlRpcException { String[][] sig = getSignature( pMethods ); String help = getMethodHelp( pClass, pMethods ); RequestProcessorFactoryFactory.RequestProcessorFactory factory = getRequestProcessorFactoryFactory().getRequestProcessorFactory( pClass ); return new ContinuumXmlRpcMetaDataHandler( this, getTypeConverterFactory(), pClass, factory, pMethods, sig, help, container ); } public void contextualize( Context context ) throws ContextException { container = (PlexusContainer) context.get( PlexusConstants.PLEXUS_KEY ); } }
5,181
0
Create_ds/continuum/continuum-xmlrpc/continuum-xmlrpc-server/src/main/java/org/apache/maven/continuum/xmlrpc
Create_ds/continuum/continuum-xmlrpc/continuum-xmlrpc-server/src/main/java/org/apache/maven/continuum/xmlrpc/server/AbstractContinuumSecureService.java
package org.apache.maven.continuum.xmlrpc.server; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.maven.continuum.ContinuumException; import org.apache.maven.continuum.security.ContinuumRoleConstants; import org.apache.maven.continuum.xmlrpc.ContinuumService; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.redback.authorization.AuthorizationException; import org.codehaus.plexus.redback.system.SecuritySession; import org.codehaus.plexus.redback.system.SecuritySystem; import org.codehaus.plexus.util.StringUtils; /** * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a> */ public abstract class AbstractContinuumSecureService implements ContinuumService, ContinuumXmlRpcComponent { @Requirement( hint = "default" ) private SecuritySystem securitySystem; private ContinuumXmlRpcConfig config; public void setConfig( ContinuumXmlRpcConfig config ) { this.config = config; } public SecuritySystem getSecuritySystem() { return securitySystem; } public SecuritySession getSecuritySession() { return config.getSecuritySession(); } /** * Check if the current user is already authenticated * * @return true if the user is authenticated */ public boolean isAuthenticated() { return !( getSecuritySession() == null || !getSecuritySession().isAuthenticated() ); } /** * Check if the current user is authorized to do the action * * @param role the role * @throws ContinuumException if the user isn't authorized */ protected void checkAuthorization( String role ) throws ContinuumException { checkAuthorization( role, null, false ); } /** * Check if the current user is authorized to do the action * * @param role the role * @param resource the operation resource * @throws ContinuumException if the user isn't authorized */ protected void checkAuthorization( String role, String resource ) throws ContinuumException { checkAuthorization( role, resource, true ); } /** * Verify if the current user is authorized to do the action * * @param role the role * @param resource the operation resource * @return true if the user is authorized * @throws AuthorizationException if the authorizing request generate an error */ protected boolean isAuthorized( String role, String resource ) throws AuthorizationException { return isAuthorized( role, resource, true ); } /** * Verify if the current user is authorized to do the action * * @param role the role * @param resource the operation resource * @param requiredResource true if resource can't be null * @return true if the user is authorized * @throws AuthorizationException if the authorizing request generate an error */ protected boolean isAuthorized( String role, String resource, boolean requiredResource ) throws AuthorizationException { if ( resource != null && StringUtils.isNotEmpty( resource.trim() ) ) { if ( !getSecuritySystem().isAuthorized( config.getSecuritySession(), role, resource ) ) { return false; } } else { if ( requiredResource || !getSecuritySystem().isAuthorized( config.getSecuritySession(), role ) ) { return false; } } return true; } /** * Check if the current user is authorized to do the action * * @param role the role * @param resource the operation resource * @param requiredResource true if resource can't be null * @throws ContinuumException if the user isn't authorized */ protected void checkAuthorization( String role, String resource, boolean requiredResource ) throws ContinuumException { try { if ( !isAuthorized( role, resource, requiredResource ) ) { throw new ContinuumException( "You're not authorized to execute this action." ); } } catch ( AuthorizationException ae ) { throw new ContinuumException( "error authorizing request." ); } } /** * Check if the current user is authorized to view the specified project group * * @param resource the operation resource * @throws ContinuumException if the user isn't authorized if the user isn't authorized */ protected void checkViewProjectGroupAuthorization( String resource ) throws ContinuumException { checkAuthorization( ContinuumRoleConstants.CONTINUUM_VIEW_GROUP_OPERATION, resource ); } /** * Check if the current user is authorized to add a project group * * @throws ContinuumException if the user isn't authorized if the user isn't authorized */ protected void checkAddProjectGroupAuthorization() throws ContinuumException { checkAuthorization( ContinuumRoleConstants.CONTINUUM_ADD_GROUP_OPERATION ); } /** * Check if the current user is authorized to delete the specified project group * * @param resource the operation resource * @throws ContinuumException if the user isn't authorized if the user isn't authorized */ protected void checkRemoveProjectGroupAuthorization( String resource ) throws ContinuumException { checkAuthorization( ContinuumRoleConstants.CONTINUUM_REMOVE_GROUP_OPERATION, resource ); } /** * Check if the current user is authorized to build the specified project group * * @param resource the operation resource * @throws ContinuumException if the user isn't authorized if the user isn't authorized */ protected void checkBuildProjectGroupAuthorization( String resource ) throws ContinuumException { checkAuthorization( ContinuumRoleConstants.CONTINUUM_BUILD_GROUP_OPERATION, resource ); } /** * Check if the current user is authorized to modify the specified project group * * @param resource the operation resource * @throws ContinuumException if the user isn't authorized if the user isn't authorized */ protected void checkModifyProjectGroupAuthorization( String resource ) throws ContinuumException { checkAuthorization( ContinuumRoleConstants.CONTINUUM_MODIFY_GROUP_OPERATION, resource ); } /** * Check if the current user is authorized to add a project to a specific project group * * @param resource the operation resource * @throws ContinuumException if the user isn't authorized if the user isn't authorized */ protected void checkAddProjectToGroupAuthorization( String resource ) throws ContinuumException { checkAuthorization( ContinuumRoleConstants.CONTINUUM_ADD_PROJECT_TO_GROUP_OPERATION, resource ); } /** * Check if the current user is authorized to delete a project from a specified group * * @param resource the operation resource * @throws ContinuumException if the user isn't authorized if the user isn't authorized */ protected void checkRemoveProjectFromGroupAuthorization( String resource ) throws ContinuumException { checkAuthorization( ContinuumRoleConstants.CONTINUUM_REMOVE_PROJECT_FROM_GROUP_OPERATION, resource ); } /** * Check if the current user is authorized to modify a project in the specified group * * @param resource the operation resource * @throws ContinuumException if the user isn't authorized if the user isn't authorized */ protected void checkModifyProjectInGroupAuthorization( String resource ) throws ContinuumException { checkAuthorization( ContinuumRoleConstants.CONTINUUM_MODIFY_PROJECT_IN_GROUP_OPERATION, resource ); } /** * Check if the current user is authorized to build a project in the specified group * * @param resource the operation resource * @throws ContinuumException if the user isn't authorized if the user isn't authorized */ protected void checkBuildProjectInGroupAuthorization( String resource ) throws ContinuumException { checkAuthorization( ContinuumRoleConstants.CONTINUUM_BUILD_PROJECT_IN_GROUP_OPERATION, resource ); } /** * Check if the current user is authorized to add a build definition for the specified * project group * * @param resource the operation resource * @throws ContinuumException if the user isn't authorized if the user isn't authorized */ protected void checkAddGroupBuildDefinitionAuthorization( String resource ) throws ContinuumException { checkAuthorization( ContinuumRoleConstants.CONTINUUM_ADD_GROUP_BUILD_DEFINTION_OPERATION, resource ); } /** * Check if the current user is authorized to delete a build definition in the specified * project group * * @param resource the operation resource * @throws ContinuumException if the user isn't authorized if the user isn't authorized */ protected void checkRemoveGroupBuildDefinitionAuthorization( String resource ) throws ContinuumException { checkAuthorization( ContinuumRoleConstants.CONTINUUM_REMOVE_GROUP_BUILD_DEFINITION_OPERATION, resource ); } /** * Check if the current user is authorized to modify a build definition in the specified * project group * * @param resource the operation resource * @throws ContinuumException if the user isn't authorized if the user isn't authorized */ protected void checkModifyGroupBuildDefinitionAuthorization( String resource ) throws ContinuumException { checkAuthorization( ContinuumRoleConstants.CONTINUUM_MODIFY_GROUP_BUILD_DEFINITION_OPERATION, resource ); } /** * Check if the current user is authorized to add a group build definition to a specific * project * * @param resource the operation resource * @throws ContinuumException if the user isn't authorized if the user isn't authorized */ protected void checkAddProjectBuildDefinitionAuthorization( String resource ) throws ContinuumException { checkAuthorization( ContinuumRoleConstants.CONTINUUM_ADD_PROJECT_BUILD_DEFINTION_OPERATION, resource ); } /** * Check if the current user is authorized to modify a build definition of a specific project * * @param resource the operation resource * @throws ContinuumException if the user isn't authorized if the user isn't authorized */ protected void checkModifyProjectBuildDefinitionAuthorization( String resource ) throws ContinuumException { checkAuthorization( ContinuumRoleConstants.CONTINUUM_MODIFY_PROJECT_BUILD_DEFINITION_OPERATION, resource ); } /** * Check if the current user is authorized to delete a build definition of a specific * project * * @param resource the operation resource * @throws ContinuumException if the user isn't authorized if the user isn't authorized */ protected void checkRemoveProjectBuildDefinitionAuthorization( String resource ) throws ContinuumException { checkAuthorization( ContinuumRoleConstants.CONTINUUM_REMOVE_PROJECT_BUILD_DEFINITION_OPERATION, resource ); } /** * Check if the current user is authorized to add a notifier to the specified * project group * * @param resource the operation resource * @throws ContinuumException if the user isn't authorized if the user isn't authorized */ protected void checkAddProjectGroupNotifierAuthorization( String resource ) throws ContinuumException { checkAuthorization( ContinuumRoleConstants.CONTINUUM_ADD_GROUP_NOTIFIER_OPERATION, resource ); } /** * Check if the current user is authorized to delete a notifier in the specified * project group * * @param resource the operation resource * @throws ContinuumException if the user isn't authorized if the user isn't authorized */ protected void checkRemoveProjectGroupNotifierAuthorization( String resource ) throws ContinuumException { checkAuthorization( ContinuumRoleConstants.CONTINUUM_REMOVE_GROUP_NOTIFIER_OPERATION, resource ); } /** * Check if the current user is authorized to modify a notifier in the specified * project group * * @param resource the operartion resource * @throws ContinuumException if the user isn't authorized if the user isn't authorized */ protected void checkModifyProjectGroupNotifierAuthorization( String resource ) throws ContinuumException { checkAuthorization( ContinuumRoleConstants.CONTINUUM_MODIFY_GROUP_NOTIFIER_OPERATION, resource ); } /** * Check if the current user is authorized to add a notifier to a specific project * * @param resource the operation resource * @throws ContinuumException if the user isn't authorized if the user isn't authorized */ protected void checkAddProjectNotifierAuthorization( String resource ) throws ContinuumException { checkAuthorization( ContinuumRoleConstants.CONTINUUM_ADD_PROJECT_NOTIFIER_OPERATION, resource ); } /** * Check if the current user is authorized to delete a notifier in a specific project * * @param resource the operation resource * @throws ContinuumException if the user isn't authorized if the user isn't authorized */ protected void checkRemoveProjectNotifierAuthorization( String resource ) throws ContinuumException { checkAuthorization( ContinuumRoleConstants.CONTINUUM_REMOVE_PROJECT_NOTIFIER_OPERATION, resource ); } /** * Check if the current user is authorized to modify a notifier in a specific project * * @param resource the operation resource * @throws ContinuumException if the user isn't authorized if the user isn't authorized */ protected void checkModifyProjectNotifierAuthorization( String resource ) throws ContinuumException { checkAuthorization( ContinuumRoleConstants.CONTINUUM_MODIFY_PROJECT_NOTIFIER_OPERATION, resource ); } /** * Check if the current user is authorized to manage the application's configuration * * @throws ContinuumException if the user isn't authorized if the user isn't authenticated */ protected void checkManageConfigurationAuthorization() throws ContinuumException { if ( !isAuthenticated() ) { throw new ContinuumException( "Authentication required." ); } checkAuthorization( ContinuumRoleConstants.CONTINUUM_MANAGE_CONFIGURATION ); } /** * Check if the current user is authorized to manage the project build schedules * * @throws ContinuumException if the user isn't authorized if the user isn't authenticated */ protected void checkManageSchedulesAuthorization() throws ContinuumException { if ( !isAuthenticated() ) { throw new ContinuumException( "Authentication required." ); } checkAuthorization( ContinuumRoleConstants.CONTINUUM_MANAGE_SCHEDULES ); } /** * Check if the current user is authorized to manage the installations * * @throws ContinuumException if the user isn't authorized if the user isn't authenticated */ protected void checkManageInstallationsAuthorization() throws ContinuumException { if ( !isAuthenticated() ) { throw new ContinuumException( "Authentication required." ); } checkAuthorization( ContinuumRoleConstants.CONTINUUM_MANAGE_INSTALLATIONS ); } /** * Check if the current user is authorized to manage the profiles * * @throws ContinuumException if the user isn't authorized if the user isn't authenticated */ protected void checkManageProfilesAuthorization() throws ContinuumException { if ( !isAuthenticated() ) { throw new ContinuumException( "Authentication required." ); } checkAuthorization( ContinuumRoleConstants.CONTINUUM_MANAGE_PROFILES ); } /** * Check if the current user is authorized to manage the build definitions templates * * @throws ContinuumException if the user isn't authorized if the user isn't authenticated */ protected void checkManageBuildDefinitionTemplatesAuthorization() throws ContinuumException { if ( !isAuthenticated() ) { throw new ContinuumException( "Authentication required." ); } checkAuthorization( ContinuumRoleConstants.CONTINUUM_MANAGE_BUILD_TEMPLATES ); } protected void checkManageQueuesAuthorization() throws ContinuumException { if ( !isAuthenticated() ) { throw new ContinuumException( "Authentication required." ); } checkAuthorization( ContinuumRoleConstants.CONTINUUM_MANAGE_QUEUES ); } protected void checkManagePurgingAuthorization() throws ContinuumException { if ( !isAuthenticated() ) { throw new ContinuumException( "Authentication required." ); } try { checkAuthorization( ContinuumRoleConstants.SYSTEM_ADMINISTRATOR_ROLE ); } catch ( ContinuumException e ) { checkAuthorization( ContinuumRoleConstants.CONTINUUM_MANAGE_PURGING ); } } protected void checkManageRepositoriesAuthorization() throws ContinuumException { if ( !isAuthenticated() ) { throw new ContinuumException( "Authentication required." ); } try { checkAuthorization( ContinuumRoleConstants.SYSTEM_ADMINISTRATOR_ROLE ); } catch ( ContinuumException e ) { checkAuthorization( ContinuumRoleConstants.CONTINUUM_MANAGE_REPOSITORIES ); } } }
5,182
0
Create_ds/continuum/continuum-xmlrpc/continuum-xmlrpc-server/src/main/java/org/apache/maven/continuum/xmlrpc
Create_ds/continuum/continuum-xmlrpc/continuum-xmlrpc-server/src/main/java/org/apache/maven/continuum/xmlrpc/server/ConfiguredBeanProcessorFactory.java
package org.apache.maven.continuum.xmlrpc.server; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.xmlrpc.XmlRpcException; import org.apache.xmlrpc.XmlRpcRequest; import org.apache.xmlrpc.server.RequestProcessorFactoryFactory; import org.codehaus.plexus.PlexusConstants; import org.codehaus.plexus.PlexusContainer; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; 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.Initializable; import org.codehaus.plexus.personality.plexus.lifecycle.phase.InitializationException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.Map; /** * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a> */ @Component( role = org.apache.xmlrpc.server.RequestProcessorFactoryFactory.class ) public class ConfiguredBeanProcessorFactory implements RequestProcessorFactoryFactory, Initializable, Contextualizable { private static final Logger log = LoggerFactory.getLogger( ConfiguredBeanProcessorFactory.class ); @Requirement( role = org.apache.maven.continuum.xmlrpc.server.ContinuumXmlRpcComponent.class ) private Map<String, Object> xmlrpcComponents; private Map<String, String> componentsMapping = new HashMap<String, String>(); PlexusContainer container; public void initialize() throws InitializationException { for ( String key : xmlrpcComponents.keySet() ) { String className = xmlrpcComponents.get( key ).getClass().getName(); componentsMapping.put( className, key ); } } public RequestProcessorFactory getRequestProcessorFactory( final Class cls ) throws XmlRpcException { return new RequestProcessorFactory() { public Object getRequestProcessor( XmlRpcRequest request ) throws XmlRpcException { Object obj = ConfiguredBeanProcessorFactory.this.getRequestProcessor( cls ); if ( obj instanceof ContinuumXmlRpcComponent ) { ContinuumXmlRpcConfig config = (ContinuumXmlRpcConfig) request.getConfig(); ( (ContinuumXmlRpcComponent) obj ).setConfig( config ); } return obj; } }; } protected Object getRequestProcessor( Class cls ) throws XmlRpcException { log.debug( "Load '" + cls.getName() + "' handler." ); Object obj = null; try { obj = getComponent( cls ); } catch ( ComponentLookupException e ) { log.error( "Can't load component.", e ); } if ( obj == null ) { throw new XmlRpcException( "Handler bean not found for: " + cls ); } return obj; } private String getComponentKey( Class cls ) { return componentsMapping.get( cls.getName() ); } private Object getComponent( Class cls ) throws ComponentLookupException { String key = getComponentKey( cls ); log.debug( "load component:" + key ); return container.lookup( ContinuumXmlRpcComponent.class.getName(), key ); } public void contextualize( Context context ) throws ContextException { container = (PlexusContainer) context.get( PlexusConstants.PLEXUS_KEY ); } }
5,183
0
Create_ds/continuum/continuum-xmlrpc/continuum-xmlrpc-server/src/main/java/org/apache/maven/continuum/xmlrpc
Create_ds/continuum/continuum-xmlrpc/continuum-xmlrpc-server/src/main/java/org/apache/maven/continuum/xmlrpc/server/ContinuumXmlRpcComponent.java
package org.apache.maven.continuum.xmlrpc.server; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /** * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a> */ public interface ContinuumXmlRpcComponent { public void setConfig( ContinuumXmlRpcConfig config ); }
5,184
0
Create_ds/continuum/continuum-xmlrpc/continuum-xmlrpc-server/src/main/java/org/apache/maven/continuum/xmlrpc
Create_ds/continuum/continuum-xmlrpc/continuum-xmlrpc-server/src/main/java/org/apache/maven/continuum/xmlrpc/server/ContinuumXmlRpcConfig.java
package org.apache.maven.continuum.xmlrpc.server; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.xmlrpc.common.XmlRpcHttpRequestConfigImpl; import org.codehaus.plexus.redback.system.SecuritySession; import javax.servlet.http.HttpServletRequest; /** * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a> */ public class ContinuumXmlRpcConfig extends XmlRpcHttpRequestConfigImpl { private HttpServletRequest httpServletRequest; private SecuritySession securitySession; public HttpServletRequest getHttpServletRequest() { return httpServletRequest; } public void setHttpServletRequest( HttpServletRequest httpServletRequest ) { this.httpServletRequest = httpServletRequest; } public SecuritySession getSecuritySession() { return securitySession; } public void setSecuritySession( SecuritySession securitySession ) { this.securitySession = securitySession; } }
5,185
0
Create_ds/continuum/continuum-xmlrpc/continuum-xmlrpc-api/src/main/java/org/apache/maven/continuum
Create_ds/continuum/continuum-xmlrpc/continuum-xmlrpc-api/src/main/java/org/apache/maven/continuum/xmlrpc/ContinuumService.java
package org.apache.maven.continuum.xmlrpc; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.xmlrpc.release.ContinuumReleaseResult; import org.apache.continuum.xmlrpc.repository.DirectoryPurgeConfiguration; import org.apache.continuum.xmlrpc.repository.LocalRepository; import org.apache.continuum.xmlrpc.repository.RepositoryPurgeConfiguration; import org.apache.continuum.xmlrpc.utils.BuildTrigger; import org.apache.maven.continuum.xmlrpc.project.AddingResult; import org.apache.maven.continuum.xmlrpc.project.BuildAgentConfiguration; import org.apache.maven.continuum.xmlrpc.project.BuildAgentGroupConfiguration; import org.apache.maven.continuum.xmlrpc.project.BuildDefinition; import org.apache.maven.continuum.xmlrpc.project.BuildDefinitionTemplate; import org.apache.maven.continuum.xmlrpc.project.BuildProjectTask; import org.apache.maven.continuum.xmlrpc.project.BuildResult; import org.apache.maven.continuum.xmlrpc.project.BuildResultSummary; import org.apache.maven.continuum.xmlrpc.project.Project; import org.apache.maven.continuum.xmlrpc.project.ProjectGroup; import org.apache.maven.continuum.xmlrpc.project.ProjectGroupSummary; import org.apache.maven.continuum.xmlrpc.project.ProjectNotifier; import org.apache.maven.continuum.xmlrpc.project.ProjectScmRoot; import org.apache.maven.continuum.xmlrpc.project.ProjectSummary; import org.apache.maven.continuum.xmlrpc.project.ReleaseListenerSummary; import org.apache.maven.continuum.xmlrpc.project.Schedule; import org.apache.maven.continuum.xmlrpc.system.Installation; import org.apache.maven.continuum.xmlrpc.system.Profile; import org.apache.maven.continuum.xmlrpc.system.SystemConfiguration; import java.util.List; import java.util.Map; import java.util.Properties; /** * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a> */ public interface ContinuumService { // ---------------------------------------------------------------------- // Projects // ---------------------------------------------------------------------- /** * Get All projects. * * @param projectGroupId The project group Id * @return List of {@link ProjectSummary} * @throws Exception */ List<ProjectSummary> getProjects( int projectGroupId ) throws Exception; /** * Same method but compatible with standard XMLRPC * * @param projectGroupId The project group Id * @return List of {@link ProjectSummary} as RPC value * @throws Exception */ List<Object> getProjectsRPC( int projectGroupId ) throws Exception; /** * Get a project. * * @param projectId the project id * @return The project summary * @throws Exception */ ProjectSummary getProjectSummary( int projectId ) throws Exception; /** * Same method but compatible with standard XMLRPC * * @param projectId the project id * @return The project summary as RPC value * @throws Exception */ Map<String, Object> getProjectSummaryRPC( int projectId ) throws Exception; /** * Get a project with all details. * * @param projectId The project id * @return The project * @throws Exception */ Project getProjectWithAllDetails( int projectId ) throws Exception; /** * Same method but compatible with standard XMLRPC * * @param projectId the project id * @return The project as RPC value * @throws Exception */ Map<String, Object> getProjectWithAllDetailsRPC( int projectId ) throws Exception; /** * Remove a project. * * @param projectId The project id * @throws Exception */ int removeProject( int projectId ) throws Exception; /** * Update a project. Useful to change the scm parameters. * * @param project The project to update * @throws Exception */ ProjectSummary updateProject( ProjectSummary project ) throws Exception; /** * Same method but compatible with standard XMLRPC * * @param project The project to update * @return The project as RPC value * @throws Exception */ Map<String, Object> updateProjectRPC( Map<String, Object> project ) throws Exception; // ---------------------------------------------------------------------- // Projects Groups // ---------------------------------------------------------------------- /** * Get a project groups. * * @param projectGroupId the id * @return project group * @throws Exception */ ProjectGroup getProjectGroup( int projectGroupId ) throws Exception; /** * Same method but compatible with standard XMLRPC * * @param projectGroupId the id * @return project group as RPC value * @throws Exception */ Map<String, Object> getProjectGroupRPC( int projectGroupId ) throws Exception; /** * Get all project groups. * * @return All project groups * @throws Exception */ List<ProjectGroupSummary> getAllProjectGroups() throws Exception; /** * Same method but compatible with standard XMLRPC * * @return List of {@link ProjectGroupSummary} as RPC value * @throws Exception */ List<Object> getAllProjectGroupsRPC() throws Exception; /** * Get all project groups with all details (project summaries, notifiers, build definitions). * * @return All project groups * @throws Exception */ List<ProjectGroup> getAllProjectGroupsWithAllDetails() throws Exception; /** * Same method but compatible with standard XMLRPC * * @return List of {@link ProjectGroup} as RPC value * @throws Exception */ List<Object> getAllProjectGroupsWithAllDetailsRPC() throws Exception; /** * Get all project groups with all details. * * @return All project groups * @throws Exception * @deprecated */ List<ProjectGroup> getAllProjectGroupsWithProjects() throws Exception; /** * Get a project group. * * @param projectGroupId The project group id * @return The project group summary * @throws Exception */ ProjectGroupSummary getProjectGroupSummary( int projectGroupId ) throws Exception; /** * Same method but compatible with standard XMLRPC * * @param projectGroupId The project group id * @return The project group summary as RPC value * @throws Exception */ Map<String, Object> getProjectGroupSummaryRPC( int projectGroupId ) throws Exception; /** * Get a project group with all details. * * @param projectGroupId The project group id * @return The project group * @throws Exception */ ProjectGroup getProjectGroupWithProjects( int projectGroupId ) throws Exception; /** * Same method but compatible with standard XMLRPC * * @param projectGroupId The project group id * @return The project group as RPC value * @throws Exception */ Map<String, Object> getProjectGroupWithProjectsRPC( int projectGroupId ) throws Exception; /** * Remove a project group. * * @param projectGroupId The project group id * @throws Exception */ int removeProjectGroup( int projectGroupId ) throws Exception; /** * Update a project Group. * * @param projectGroup The project group to update * @throws Exception */ ProjectGroupSummary updateProjectGroup( ProjectGroupSummary projectGroup ) throws Exception; /** * Same method but compatible with standard XMLRPC * * @param projectGroup The project group to update * @return The project group as RPC value * @throws Exception */ Map<String, Object> updateProjectGroupRPC( Map<String, Object> projectGroup ) throws Exception; /** * Add a project Group. * * @param groupName The project group name * @param groupId The project group id * @param description The project group description * @return the project group summary of the created project group * @throws Exception */ ProjectGroupSummary addProjectGroup( String groupName, String groupId, String description ) throws Exception; int removeBuildDefinitionFromProjectGroup( int projectGroupId, int buildDefinitionId ) throws Exception; /** * Same method but compatible with standard XMLRPC * * @param groupName The project group name * @param groupId The project group id * @param description The project group description * @return the project group summary of the created project group as RPC value * @throws Exception */ Map<String, Object> addProjectGroupRPC( String groupName, String groupId, String description ) throws Exception; ProjectNotifier getNotifier( int projectid, int notifierId ) throws Exception; Map<String, Object> getNotifierRPC( int projectid, int notifierId ) throws Exception; ProjectNotifier getGroupNotifier( int projectgroupid, int notifierId ) throws Exception; Map<String, Object> getGroupNotifierRPC( int projectgroupid, int notifierId ) throws Exception; ProjectNotifier updateGroupNotifier( int projectgroupid, ProjectNotifier newNotifier ) throws Exception; Map<String, Object> updateGroupNotifierRPC( int projectgroupid, Map<String, Object> newNotifier ) throws Exception; ProjectNotifier updateNotifier( int projectid, ProjectNotifier newNotifier ) throws Exception; Map<String, Object> updateNotifierRPC( int projectid, Map<String, Object> newNotifier ) throws Exception; int removeGroupNotifier( int projectgroupid, int notifierId ) throws Exception; int removeNotifier( int projectid, int notifierId ) throws Exception; ProjectNotifier addNotifier( int projectid, ProjectNotifier newNotifier ) throws Exception; ProjectNotifier addGroupNotifier( int projectgroupid, ProjectNotifier newNotifier ) throws Exception; Map<String, Object> addNotifierRPC( int projectid, Map<String, Object> newNotifier ) throws Exception; Map<String, Object> addGroupNotifierRPC( int projectgroupid, Map<String, Object> newNotifier ) throws Exception; // ---------------------------------------------------------------------- // Build Definitions // ---------------------------------------------------------------------- /** * Get the build definitions list of the project. * * @param projectId The project id * @return The build definitions list * @throws Exception */ List<BuildDefinition> getBuildDefinitionsForProject( int projectId ) throws Exception; /** * Same method but compatible with standard XMLRPC * * @param projectId The project id * @return The build definitions list as RPC value * @throws Exception */ List<Object> getBuildDefinitionsForProjectRPC( int projectId ) throws Exception; /** * Get the build definitions list of the project group. * * @param projectGroupId The project group id * @return The build definitions list * @throws Exception */ List<BuildDefinition> getBuildDefinitionsForProjectGroup( int projectGroupId ) throws Exception; /** * Same method but compatible with standard XMLRPC * * @param projectGroupId The project group id * @return The build definitions list as RPC value * @throws Exception */ List<Object> getBuildDefinitionsForProjectGroupRPC( int projectGroupId ) throws Exception; /** * Get the build definition * * @param buildDefinitionId The build definition id * @return The build definition * @throws Exception */ BuildDefinition getBuildDefinition( int buildDefinitionId ) throws Exception; /** * Same method but compatible with standard XMLRPC * * @param buildDefinitionId The build definition id * @return The build definition as RPC value * @throws Exception */ Map<String, Object> getBuildDefinitionRPC( int buildDefinitionId ) throws Exception; /** * Update a project build definition. * * @param projectId The project id * @param buildDef The build definition to update * @return the updated build definition * @throws Exception */ BuildDefinition updateBuildDefinitionForProject( int projectId, BuildDefinition buildDef ) throws Exception; /** * Same method but compatible with standard XMLRPC * * @param projectId The project id * @param buildDef The build definition to update * @return the updated build definition as RPC value * @throws Exception */ Map<String, Object> updateBuildDefinitionForProjectRPC( int projectId, Map<String, Object> buildDef ) throws Exception; /** * Update a project group build definition. * * @param projectGroupId The project group id * @param buildDef The build definition to update * @return the updated build definition * @throws Exception */ BuildDefinition updateBuildDefinitionForProjectGroup( int projectGroupId, BuildDefinition buildDef ) throws Exception; /** * Same method but compatible with standard XMLRPC * * @param projectGroupId The project group id * @param buildDef The build definition to update * @return the updated build definition as RPC value * @throws Exception */ Map<String, Object> updateBuildDefinitionForProjectGroupRPC( int projectGroupId, Map<String, Object> buildDef ) throws Exception; /** * Add a project build definition. * * @param projectId The project id * @param buildDef The build definition to update * @return the added build definition * @throws Exception */ BuildDefinition addBuildDefinitionToProject( int projectId, BuildDefinition buildDef ) throws Exception; /** * Same method but compatible with standard XMLRPC * * @param projectId The project id * @param buildDef The build definition to update * @return the added build definition as RPC value * @throws Exception */ Map<String, Object> addBuildDefinitionToProjectRPC( int projectId, Map<String, Object> buildDef ) throws Exception; /** * Add a project group buildDefinition. * * @param projectGroupId The project group id * @param buildDef The build definition to update * @return the build definition added * @throws Exception */ BuildDefinition addBuildDefinitionToProjectGroup( int projectGroupId, BuildDefinition buildDef ) throws Exception; /** * Same method but compatible with standard XMLRPC * * @param projectGroupId The project group id * @param buildDef The build definition to update * @return the added build definition as RPC value * @throws Exception */ Map<String, Object> addBuildDefinitionToProjectGroupRPC( int projectGroupId, Map<String, Object> buildDef ) throws Exception; /** * Get the build definition templates list. * * @return The build definitions templates list * @throws Exception */ List<BuildDefinitionTemplate> getBuildDefinitionTemplates() throws Exception; /** * Same method but compatible with standard XMLRPC * * @return The build definitions templates list as RPC value * @throws Exception */ List<Object> getBuildDefinitionTemplatesRPC() throws Exception; // ---------------------------------------------------------------------- // Building // ---------------------------------------------------------------------- /** * Add the project to the build queue. * * @param projectId The project id * @throws Exception */ int addProjectToBuildQueue( int projectId ) throws Exception; /** * Add the project to the build queue. * * @param projectId The project id * @param buildDefinitionId The build definition id * @throws Exception */ int addProjectToBuildQueue( int projectId, int buildDefinitionId ) throws Exception; /** * Build the project * * @param projectId The project id * @throws Exception */ int buildProject( int projectId ) throws Exception; /** * Build the project * * @param projectId The project id * @param buildDefinitionId The build definition id * @throws Exception */ int buildProject( int projectId, int buildDefinitionId ) throws Exception; /** * Forced build the project * * @param projectId The project id * @param buildTrigger The build trigger * @return * @throws Exception */ int buildProject( int projectId, BuildTrigger buildTrigger ) throws Exception; /** * Forced build the project * * @param projectId The project id * @param buildDefinitionId The build definition id * @param buildTrigger The build trigger * @return * @throws Exception */ int buildProject( int projectId, int buildDefinitionId, BuildTrigger buildTrigger ) throws Exception; /** * Build the project group with the default build definition. * * @param projectGroupId The project group id * @throws Exception */ int buildGroup( int projectGroupId ) throws Exception; /** * Build the project group with the specified build definition. * * @param projectGroupId The project group id * @param buildDefinitionId The build definition id * @throws Exception */ int buildGroup( int projectGroupId, int buildDefinitionId ) throws Exception; // ---------------------------------------------------------------------- // SCM roots // ---------------------------------------------------------------------- /** * Get the SCM roots for all projects in a project group * * @param projectGroupId the project group id * @return * @throws Exception */ List<ProjectScmRoot> getProjectScmRootByProjectGroup( int projectGroupId ) throws Exception; /** * Get the SCM root for a specific project * * @param projectId the project id * @return * @throws Exception */ ProjectScmRoot getProjectScmRootByProject( int projectId ) throws Exception; // ---------------------------------------------------------------------- // Build Results // ---------------------------------------------------------------------- /** * Returns the latest build result for the project. * * @param projectId The project id * @return The build result * @throws Exception */ BuildResult getLatestBuildResult( int projectId ) throws Exception; /** * Same method but compatible with standard XMLRPC * * @param projectId The project id * @return The build result as RPC value * @throws Exception */ Map<String, Object> getLatestBuildResultRPC( int projectId ) throws Exception; /** * Returns the build result. * * @param projectId The project id * @param buildId The build id * @return The build result * @throws Exception */ BuildResult getBuildResult( int projectId, int buildId ) throws Exception; /** * Same method but compatible with standard XMLRPC * * @param projectId The project id * @param buildId The build id * @return The build result as RPC value * @throws Exception */ Map<String, Object> getBuildResultRPC( int projectId, int buildId ) throws Exception; /** * Returns the project build result summary list. * * @param projectId The project id * @param offset the zero-based offset to fetch from * @param length the maximum number of results to fetch, starting from offset * @return The build result list * @throws Exception */ List<BuildResultSummary> getBuildResultsForProject( int projectId, int offset, int length ) throws Exception; /** * Same method but compatible with standard XMLRPC * * @param projectId The project id * @param offset the zero-based offset of result set to start from * @param length the number of results to return, starting from the offset * @return The build result list as RPC value * @throws Exception */ List<Object> getBuildResultsForProjectRPC( int projectId, int offset, int length ) throws Exception; /** * Remove the project build result. * * @param br The project build result * @return 0 * @throws Exception */ int removeBuildResult( BuildResult br ) throws Exception; /** * Same method but compatible with standard XMLRPC * * @param br The project build result * @return 0 * @throws Exception */ int removeBuildResultRPC( Map<String, Object> br ) throws Exception; /** * Returns the build output. * * @param projectId The project id * @param buildId The build id * @return The build output * @throws Exception */ String getBuildOutput( int projectId, int buildId ) throws Exception; // ---------------------------------------------------------------------- // Maven 2.x projects // ---------------------------------------------------------------------- /** * Add a maven 2.x project from an url. * * @param url The POM url * @return The result of the action with the list of projects created * @throws Exception */ AddingResult addMavenTwoProject( String url ) throws Exception; /** * Same method but compatible with standard XMLRPC * * @param url The POM url * @return The result of the action with the list of projects created as RPC value * @throws Exception */ Map<String, Object> addMavenTwoProjectRPC( String url ) throws Exception; /** * Add a maven 2.x project from an url. * * @param url The POM url * @param projectGroupId The id of the group where projects will be stored * @return The result of the action with the list of projects created * @throws Exception */ AddingResult addMavenTwoProject( String url, int projectGroupId ) throws Exception; /** * Same method but compatible with standard XMLRPC * * @param url The POM url * @param projectGroupId The id of the group where projects will be stored * @return The result of the action with the list of projects created as RPC value * @throws Exception */ Map<String, Object> addMavenTwoProjectRPC( String url, int projectGroupId ) throws Exception; /** * Add a maven 2.x project from an url. * * @param url The POM url * @param projectGroupId The id of the group where projects will be stored * @return The result of the action with the list of projects created * @throws Exception * @Param checkoutInSingleDirectory Determines whether the project will be stored on a single directory */ AddingResult addMavenTwoProject( String url, int projectGroupId, boolean checkoutInSingleDirectory ) throws Exception; /** * Same method but compatible with standard XMLRPC * * @param url The POM url * @param projectGroupId The id of the group where projects will be stored * @return The result of the action with the list of projects created as RPC value * @throws Exception * @Param checkoutInSingleDirectory Determines whether the project will be stored on a single directory */ Map<String, Object> addMavenTwoProjectRPC( String url, int projectGroupId, boolean checkoutInSingleDirectory ) throws Exception; /** * Add a maven 2.x multi-module project from a url and add it to Continuum as a single project instead of as * multiple projects (one project per module). To add a multi-module project with its modules as separate Continuum * projects, use ContinuumService#addMavenTwoProject( String url, int projectGroupId, boolean * checkoutInSingleDirectory) instead. * * @param url * @param projectGroupId * @return * @throws Exception */ AddingResult addMavenTwoProjectAsSingleProject( String url, int projectGroupId ) throws Exception; /** * Same method but compatible with standard XMLRPC * * @param url * @param projectGroupId * @return * @throws Exception */ Map<String, Object> addMavenTwoProjectAsSingleProjectRPC( String url, int projectGroupId ) throws Exception; /** * Add a maven 2.x multi-module project from a url * * @param url The POM url * @param projectGroupId The id of the group where projects will be stored * @param checkProtocol Determines whether the protocol will be checked * @param useCredentialsCache Determines whether user credentials will be cached * @param recursiveProjects Determines whether to load recursive projects * @param checkoutInSingleDirectory Determines whether the project will be stored on a single directory * @return The result of the action with the list of projects created * @throws Exception */ AddingResult addMavenTwoProject( String url, int projectGroupId, boolean checkProtocol, boolean useCredentialsCache, boolean recursiveProjects, boolean checkoutInSingleDirectory ) throws Exception; /** * Same method but compatible with standard XMLRPC * * @param url The POM url * @param projectGroupId The id of the group where projects will be stored * @param checkProtocol Determines whether the protocol will be checked * @param useCredentialsCache Determines whether user credentials will be cached * @param recursiveProjects Determines whether to load recursive projects * @param checkoutInSingleDirectory Determines whether the project will be stored on a single directory * @return The result of the action with the list of projects created as RPC value * @throws Exception */ Map<String, Object> addMavenTwoProjectRPC( String url, int projectGroupId, boolean checkProtocol, boolean useCredentialsCache, boolean recursiveProjects, boolean checkoutInSingleDirectory ) throws Exception; // ---------------------------------------------------------------------- // Maven 1.x projects // ---------------------------------------------------------------------- /** * Add a maven 1.x project from an url. * * @param url The POM url * @param projectGroupId The id of the group where projects will be stored * @return The result of the action with the list of projects created * @throws Exception */ AddingResult addMavenOneProject( String url, int projectGroupId ) throws Exception; /** * Same method but compatible with standard XMLRPC * * @param url The POM url * @param projectGroupId The id of the group where projects will be stored * @return The result of the action with the list of projects created as RPC value * @throws Exception */ Map<String, Object> addMavenOneProjectRPC( String url, int projectGroupId ) throws Exception; // ---------------------------------------------------------------------- // Maven ANT projects // ---------------------------------------------------------------------- /** * Add an ANT project in the specified group. * * @param project The project to add. name, version and scm informations are required * @param projectGroupId The id of the group where projects will be stored * @return The project populated with the id. * @throws Exception */ ProjectSummary addAntProject( ProjectSummary project, int projectGroupId ) throws Exception; /** * Same method but compatible with standard XMLRPC * * @param project The project to add. name, version and scm informations are required * @param projectGroupId The id of the group where projects will be stored * @return The project populated with the id as RPC value * @throws Exception */ Map<String, Object> addAntProjectRPC( Map<String, Object> project, int projectGroupId ) throws Exception; // ---------------------------------------------------------------------- // Maven Shell projects // ---------------------------------------------------------------------- /** * Add an shell project in the specified group. * * @param project The project to add. name, version and scm informations are required * @param projectGroupId The id of the group where projects will be stored * @return The project populated with the id. * @throws Exception */ ProjectSummary addShellProject( ProjectSummary project, int projectGroupId ) throws Exception; /** * Same method but compatible with standard XMLRPC * * @param project The project to add. name, version and scm informations are required * @param projectGroupId The id of the group where projects will be stored * @return The project populated with the id as RPC value * @throws Exception */ Map<String, Object> addShellProjectRPC( Map<String, Object> project, int projectGroupId ) throws Exception; // ---------------------------------------------------------------------- // ADMIN TASKS // ---------------------------------------------------------------------- // ---------------------------------------------------------------------- // Schedules // ---------------------------------------------------------------------- /** * Return the schedules list. * * @return The schedule list. * @throws Exception */ List<Schedule> getSchedules() throws Exception; /** * Same method but compatible with standard XMLRPC * * @return The schedule list as RPC value. * @throws Exception */ List<Object> getSchedulesRPC() throws Exception; /** * Return the schedule defined by this id. * * @param scheduleId The schedule id * @return The schedule. * @throws Exception */ Schedule getSchedule( int scheduleId ) throws Exception; /** * Same method but compatible with standard XMLRPC * * @param scheduleId The schedule id * @return The schedule as RPC value. * @throws Exception */ Map<String, Object> getScheduleRPC( int scheduleId ) throws Exception; /** * Add the schedule. * * @param schedule The schedule * @return The schedule. * @throws Exception */ Schedule addSchedule( Schedule schedule ) throws Exception; /** * Same method but compatible with standard XMLRPC * * @param schedule The schedule * @return The schedule as RPC value. * @throws Exception */ Map<String, Object> addScheduleRPC( Map<String, Object> schedule ) throws Exception; /** * Update the schedule. * * @param schedule The schedule * @return The schedule. * @throws Exception */ Schedule updateSchedule( Schedule schedule ) throws Exception; /** * Same method but compatible with standard XMLRPC * * @param schedule The schedule * @return The schedule as RPC value. * @throws Exception */ Map<String, Object> updateScheduleRPC( Map<String, Object> schedule ) throws Exception; // ---------------------------------------------------------------------- // Profiles // ---------------------------------------------------------------------- /** * Return the profiles list. * * @return The profiles list. * @throws Exception */ List<Profile> getProfiles() throws Exception; /** * Same method but compatible with standard XMLRPC * * @return The profiles list as RPC value. * @throws Exception */ List<Object> getProfilesRPC() throws Exception; /** * Return the profile defined by this id. * * @param profileId The profile id * @return The profile. * @throws Exception */ Profile getProfile( int profileId ) throws Exception; /** * Same method but compatible with standard XMLRPC * * @param profileId The profile id * @return The profile. * @throws Exception */ Map<String, Object> getProfileRPC( int profileId ) throws Exception; Profile getProfileWithName( String profileName ) throws Exception; Map<String, Object> getProfileWithNameRPC( String profileName ) throws Exception; Profile addProfile( Profile profile ) throws Exception; int updateProfile( Profile profile ) throws Exception; int deleteProfile( int profileId ) throws Exception; Map<String, Object> addProfileRPC( Map<String, Object> profile ) throws Exception; int updateProfileRPC( Map<String, Object> profile ) throws Exception; // ---------------------------------------------------------------------- // Installations // ---------------------------------------------------------------------- /** * Return the installations list. * * @return The installations list. * @throws Exception */ List<Installation> getInstallations() throws Exception; /** * Same method but compatible with standard XMLRPC * * @return The installations list. * @throws Exception */ List<Object> getInstallationsRPC() throws Exception; /** * Return the installation defined by this id. * * @param installationId The installation id * @return The installation. * @throws Exception */ Installation getInstallation( int installationId ) throws Exception; /** * Same method but compatible with standard XMLRPC * * @param installationId The installation id * @return The installation. * @throws Exception */ Map<String, Object> getInstallationRPC( int installationId ) throws Exception; /** * Return the installation defined by this name * * @param installationName The installation name * @return The installation * @throws Exception */ Installation getInstallation( String installationName ) throws Exception; /** * Same method but compatible with standard XMLRPC * * @param installationName The installation name * @return The installation * @throws Exception */ Map<String, Object> getInstallationRPC( String installationName ) throws Exception; /** * Return the installations list defined by this URL. * * @param url The build agent URL * @return The installations list. * @throws Exception */ List<Installation> getBuildAgentInstallations( String url ) throws Exception; /** * Same method but compatible with standard XMLRPC * * @param url The build agent URL * @return The installations list. * @throws Exception */ List<Object> getBuildAgentInstallationsRPC( String url ) throws Exception; Installation addInstallation( Installation installation ) throws Exception; int updateInstallation( Installation installation ) throws Exception; int deleteInstallation( int installationId ) throws Exception; Map<String, Object> addInstallationRPC( Map<String, Object> installation ) throws Exception; int updateInstallationRPC( Map<String, Object> installation ) throws Exception; // ---------------------------------------------------------------------- // SystemConfiguration // ---------------------------------------------------------------------- SystemConfiguration getSystemConfiguration() throws Exception; Map<String, Object> getSystemConfigurationRPC() throws Exception; // ---------------------------------------------------------------------- // Queue // ---------------------------------------------------------------------- /** * Return true if the project is in prepare build queue * * @param projectId The project id * @throws ContinuumException */ boolean isProjectInPrepareBuildQueue( int projectId ) throws Exception; /** * Return true if the project is in prepare build queue * * @param projectId The project id * @param buildDefinitionId The build definition id * @throws ContinuumException */ boolean isProjectInPrepareBuildQueue( int projectId, int buildDefinitionId ) throws Exception; /** * Return true if the project is in building queue. * * @param projectId The project id * @throws ContinuumException */ boolean isProjectInBuildingQueue( int projectId ) throws Exception; /** * Return true if the project is in building queue. * * @param projectId The project id * @param buildDefinitionId The build definition id * @throws ContinuumException */ boolean isProjectInBuildingQueue( int projectId, int buildDefinitionId ) throws Exception; /** * Return true if the project is currently preparing build * * @param projectId The project id * @return * @throws Exception */ boolean isProjectCurrentlyPreparingBuild( int projectId ) throws Exception; /** * Return true if the project is currently preparing build * * @param projectId The project id * @param buildDefinitionId The build definition id * @return * @throws Exception */ boolean isProjectCurrentlyPreparingBuild( int projectId, int buildDefinitionId ) throws Exception; /** * Return true if the project is currently building * * @param projectId The project id * @return * @throws Exception */ boolean isProjectCurrentlyBuilding( int projectId ) throws Exception; /** * Return true if the project is currently building * * @param projectId The project id * @param buildDefinitionId The build definition id * @return * @throws Exception */ boolean isProjectCurrentlyBuilding( int projectId, int buildDefinitionId ) throws Exception; /** * Return projects building queue. * * @throws ContinuumException */ public List<BuildProjectTask> getProjectsInBuildQueue() throws Exception; /** * Remove projects from build queue * * @param projectsId project id to be removed from the building queue * @return * @throws Exception */ int removeProjectsFromBuildingQueue( int[] projectsId ) throws Exception; /** * Cancel the current project build * * @return * @throws Exception */ boolean cancelCurrentBuild() throws Exception; /** * Cancel a project build * * @param projectId the project id * @param buildDefinitionId the build definition id * @return * @throws Exception */ boolean cancelBuild( int projectId, int buildDefinitionId ) throws Exception; // ---------------------------------------------------------------------- // TODO:Users // ---------------------------------------------------------------------- // ---------------------------------------------------------------------- // Utils // ---------------------------------------------------------------------- boolean ping() throws Exception; // ---------------------------------------------------------------------- // Local Repository // ---------------------------------------------------------------------- /** * Add a local repository * * @param repository the local repository to add * @return * @throws Exception */ LocalRepository addLocalRepository( LocalRepository repository ) throws Exception; /** * Same method but compatible with the standard XMLRPC * * @param repository the local repository to add * @return * @throws Exception */ Map<String, Object> addLocalRepositoryRPC( Map<String, Object> repository ) throws Exception; /** * Update the local repository * * @param repository the local repository to update * @return * @throws Exception */ int updateLocalRepository( LocalRepository repository ) throws Exception; /** * Same method but compatible with the standard XMLRPC * * @param repository the local repository to update * @return * @throws Exception */ int updateLocalRepositoryRPC( Map<String, Object> repository ) throws Exception; /** * Remove the local repository * * @param repositoryId * @return * @throws Exception */ int removeLocalRepository( int repositoryId ) throws Exception; /** * Returns the local repository * * @param repositoryId the local repository id * @return * @throws Exception */ LocalRepository getLocalRepository( int repositoryId ) throws Exception; /** * Same method but compatible with the standard XMLRPC * * @param repositoryId * @return * @throws Exception */ Map<String, Object> getLocalRepositoryRPC( int repositoryId ) throws Exception; /** * Returns all local repositories * * @return * @throws Exception */ List<LocalRepository> getAllLocalRepositories() throws Exception; /** * Same method but compatible with the standard XMLRPC * * @return * @throws Exception */ List<Object> getAllLocalRepositoriesRPC() throws Exception; // ---------------------------------------------------------------------- // Purging // ---------------------------------------------------------------------- /** * Add a repository purge configuration * * @param repoPurge the repository purge configuration * @return * @throws Exception */ RepositoryPurgeConfiguration addRepositoryPurgeConfiguration( RepositoryPurgeConfiguration repoPurge ) throws Exception; /** * Same method but compatible with the standard XMLRPC * * @param repoPurge the repository purge configuration * @return * @throws Exception */ Map<String, Object> addRepositoryPurgeConfigurationRPC( Map<String, Object> repoPurge ) throws Exception; /** * Update the repository purge configuration * * @param repoPurge the repository purge configuration * @return * @throws Exception */ int updateRepositoryPurgeConfiguration( RepositoryPurgeConfiguration repoPurge ) throws Exception; /** * Same method but compatible with the standard XMLRPC * * @param repoPurge the repository purge configuration * @return * @throws Exception */ int updateRepositoryPurgeConfigurationRPC( Map<String, Object> repoPurge ) throws Exception; /** * Remove repository purge configuration * * @param repoPurgeId the repository purge configuration id * @return * @throws Exception */ int removeRepositoryPurgeConfiguration( int repoPurgeId ) throws Exception; /** * Returns the repository purge configuration * * @param purgeConfigId the repository purge configuration id * @return the repository purge configuration * @throws Exception */ RepositoryPurgeConfiguration getRepositoryPurgeConfiguration( int repoPurgeId ) throws Exception; /** * Same method but compatible with standard XMLRPC * * @param purgeConfigId the repository purge configuration id * @return the repository purge configuration * @throws Exception */ Map<String, Object> getRepositoryPurgeConfigurationRPC( int purgeConfigId ) throws Exception; /** * Returns repository purge configurations list * * @return list of repository purge configurations * @throws Exception */ List<RepositoryPurgeConfiguration> getAllRepositoryPurgeConfigurations() throws Exception; /** * Same method but compatible with standard XMLRPC * * @return list of repository purge configurations * @throws Exception */ List<Object> getAllRepositoryPurgeConfigurationsRPC() throws Exception; /** * Add a directory purge configuration * * @param dirPurge the directory purge configuration * @return * @throws Exception */ DirectoryPurgeConfiguration addDirectoryPurgeConfiguration( DirectoryPurgeConfiguration dirPurge ) throws Exception; /** * Same method but compatible with the standard XMLRPC * * @param dirPurge the directory purge configuration * @return * @throws Exception */ Map<String, Object> addDirectoryPurgeConfigurationRPC( Map<String, Object> dirPurge ) throws Exception; /** * Update the directory purge configuration * * @param dirPurge the directory purge configuration * @return * @throws Exception */ int updateDirectoryPurgeConfiguration( DirectoryPurgeConfiguration dirPurge ) throws Exception; /** * Same method but compatible with the standard XMLRPC * * @param dirPurge the directory purge configuration * @return * @throws Exception */ int updateDirectoryPurgeConfigurationRPC( Map<String, Object> dirPurge ) throws Exception; /** * Removes the directory purge configuration * * @param dirPurgeId the directory purge configuration id * @return * @throws Exception */ int removeDirectoryPurgeConfiguration( int dirPurgeId ) throws Exception; /** * Returns the directory purge configuration * * @param purgeConfigId the directory purge configuration id * @return the directory purge configuration * @throws Exception */ DirectoryPurgeConfiguration getDirectoryPurgeConfiguration( int purgeConfigId ) throws Exception; /** * Same method but compatible with standard XMLRPC * * @param purgeConfigId the directory purge configuration id * @return the directory purge configuration * @throws Exception */ Map<String, Object> getDirectoryPurgeConfigurationRPC( int purgeConfigId ) throws Exception; /** * Returns directory purge configurations list * * @return list of directory purge configurations * @throws Exception */ List<DirectoryPurgeConfiguration> getAllDirectoryPurgeConfigurations() throws Exception; /** * Same method but compatible with standard XMLRPC * * @return list of directory purge configurations * @throws Exception */ List<Object> getAllDirectoryPurgeConfigurationsRPC() throws Exception; int purgeLocalRepository( int repoPurgeId ) throws Exception; int purgeDirectory( int dirPurgeId ) throws Exception; // ---------------------------------------------------------------------- // Release Results // ---------------------------------------------------------------------- /** * Returns the release result. * * @param releaseId The release id * @return The release result * @throws Exception */ ContinuumReleaseResult getReleaseResult( int releaseId ) throws Exception; /** * Same method but compatible with standard XMLRPC * * @param releaseId The release id * @return The release result as RPC value * @throws Exception */ Map<String, Object> getReleaseResultRPC( int releaseId ) throws Exception; /** * Returns the project group release result list. * * @param projectGroupId The project group id * @return The release result list * @throws Exception */ List<ContinuumReleaseResult> getReleaseResultsForProjectGroup( int projectGroupId ) throws Exception; /** * Same method but compatible with standard XMLRPC * * @param projectGroupId The project group id * @return The release result list as RPC value * @throws Exception */ List<Object> getReleaseResultsForProjectGroupRPC( int projectGroupId ) throws Exception; /** * Remove the project release result. * * @param releaseResult The project release result * @return 0 * @throws Exception */ int removeReleaseResult( ContinuumReleaseResult releaseResult ) throws Exception; /** * Same method but compatible with standard XMLRPC * * @param rr The project release result * @return 0 * @throws Exception */ int removeReleaseResultRPC( Map<String, Object> rr ) throws Exception; /** * Returns the release output. * * @param releaseId The release id * @return The release output * @throws Exception */ String getReleaseOutput( int releaseId ) throws Exception; /** * Release prepare a project * * @param projectId * @param releaseProperties * @param releaseVersions * @param developmentVersions * @param environments * @param username * @return The release id * @throws Exception */ String releasePrepare( int projectId, Properties releaseProperties, Map<String, String> releaseVersions, Map<String, String> developmentVersions, Map<String, String> environments, String username ) throws Exception; /** * Release perform a project * * @param projectId * @param releaseId * @param goals * @param arguments * @param useReleaseProfile * @param repositoryName * @param username * @return * @throws Exception */ int releasePerform( int projectId, String releaseId, String goals, String arguments, boolean useReleaseProfile, String repositoryName, String username ) throws Exception; /** * Get release listener * * @param projectId * @param releaseId * @return * @throws Exception */ ReleaseListenerSummary getListener( int projectId, String releaseId ) throws Exception; /** * Cleanup the release * * @param projectId * @param releaseId * @return * @throws Exception */ int releaseCleanup( int projectId, String releaseId ) throws Exception; /** * Cleanup the release * * @param projectId * @param releaseId * @param releaseType * @return * @throws Exception */ int releaseCleanup( int projectId, String releaseId, String releaseType ) throws Exception; /** * Rollback a release * * @param projectId * @param releaseId * @return * @throws Exception */ int releaseRollback( int projectId, String releaseId ) throws Exception; /** * Get release plugin parameters * * @param projectId * @return */ Map<String, Object> getReleasePluginParameters( int projectId ) throws Exception; List<Map<String, String>> getProjectReleaseAndDevelopmentVersions( int projectId, String pomFilename, boolean autoVersionSubmodules ) throws Exception; /** * Add/Register build agent to Continuum Master * * @return * @throws Exception */ BuildAgentConfiguration addBuildAgent( BuildAgentConfiguration buildAgentConfiguration ) throws Exception; /** * Same method but compatible with standard XMLRPC * * @return * @throws Exception */ Map<String, Object> addBuildAgentRPC( Map<String, Object> buildAgentConfiguration ) throws Exception; /** * Get build agent in Continuum Master * * @param url - build agent URL * @return */ BuildAgentConfiguration getBuildAgent( String url ); /** * Get the url of the build agent that is processing the project * * @param projectId project Id * @param buildDefinitionId build definition Id * @return build agent url */ String getBuildAgentUrl( int projectId, int buildDefinition ) throws Exception; /** * Same method but compatible with standard XMLRPC * * @param url - build agent URL * @return */ Map<String, Object> getBuildAgentRPC( String url ); /** * Update build agent in Continuum Master * * @return * @throws Exception */ BuildAgentConfiguration updateBuildAgent( BuildAgentConfiguration buildAgentConfiguration ) throws Exception; /** * Same method but compatible with standard XMLRPC * * @return * @throws Exception */ Map<String, Object> updateBuildAgentRPC( Map<String, Object> buildAgentConfiguration ) throws Exception; /** * remove build agent in Continuum Master * * @param url - build agent URL * @return Exception */ boolean removeBuildAgent( String url ) throws Exception; /** * List all build agent in Continuum Master * * @return */ List<BuildAgentConfiguration> getAllBuildAgents(); /** * Same method but compatible with standard XMLRPC * * @return */ List<Object> getAllBuildAgentsRPC(); /** * Retrieve all enabled build agents with their available installations * * @return * @throws Exception */ List<BuildAgentConfiguration> getBuildAgentsWithInstallations() throws Exception; /** * Same method but compatible with standard XMLRPC * * @return * @throws Exception */ List<Object> getBuildAgentsWithInstallationsRPC() throws Exception; boolean pingBuildAgent( String buildAgentUrl ) throws Exception; BuildAgentGroupConfiguration addBuildAgentGroup( BuildAgentGroupConfiguration buildAgentGroup ) throws Exception; Map<String, Object> addBuildAgentGroupRPC( Map<String, Object> buildAgentGroup ) throws Exception; BuildAgentGroupConfiguration getBuildAgentGroup( String name ); Map<String, Object> getBuildAgentGroupRPC( String name ); BuildAgentGroupConfiguration updateBuildAgentGroup( BuildAgentGroupConfiguration buildAgentGroup ) throws Exception; Map<String, Object> updateBuildAgentGroupRPC( Map<String, Object> buildAgentGroup ) throws Exception; int removeBuildAgentGroup( String name ) throws Exception; }
5,186
0
Create_ds/continuum/continuum-xmlrpc/continuum-xmlrpc-client/src/main/java/org/apache/maven/continuum/xmlrpc
Create_ds/continuum/continuum-xmlrpc/continuum-xmlrpc-client/src/main/java/org/apache/maven/continuum/xmlrpc/client/ContinuumXmlRpcClient.java
package org.apache.maven.continuum.xmlrpc.client; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.xmlrpc.release.ContinuumReleaseResult; import org.apache.continuum.xmlrpc.repository.DirectoryPurgeConfiguration; import org.apache.continuum.xmlrpc.repository.LocalRepository; import org.apache.continuum.xmlrpc.repository.RepositoryPurgeConfiguration; import org.apache.continuum.xmlrpc.utils.BuildTrigger; import org.apache.maven.continuum.xmlrpc.ContinuumService; import org.apache.maven.continuum.xmlrpc.project.AddingResult; import org.apache.maven.continuum.xmlrpc.project.BuildAgentConfiguration; import org.apache.maven.continuum.xmlrpc.project.BuildAgentGroupConfiguration; import org.apache.maven.continuum.xmlrpc.project.BuildDefinition; import org.apache.maven.continuum.xmlrpc.project.BuildDefinitionTemplate; import org.apache.maven.continuum.xmlrpc.project.BuildProjectTask; import org.apache.maven.continuum.xmlrpc.project.BuildResult; import org.apache.maven.continuum.xmlrpc.project.BuildResultSummary; import org.apache.maven.continuum.xmlrpc.project.ContinuumProjectState; import org.apache.maven.continuum.xmlrpc.project.Project; import org.apache.maven.continuum.xmlrpc.project.ProjectGroup; import org.apache.maven.continuum.xmlrpc.project.ProjectGroupSummary; import org.apache.maven.continuum.xmlrpc.project.ProjectNotifier; import org.apache.maven.continuum.xmlrpc.project.ProjectScmRoot; import org.apache.maven.continuum.xmlrpc.project.ProjectSummary; import org.apache.maven.continuum.xmlrpc.project.ReleaseListenerSummary; import org.apache.maven.continuum.xmlrpc.project.Schedule; import org.apache.maven.continuum.xmlrpc.system.Installation; import org.apache.maven.continuum.xmlrpc.system.Profile; import org.apache.maven.continuum.xmlrpc.system.SystemConfiguration; import org.apache.xmlrpc.client.XmlRpcClient; import org.apache.xmlrpc.client.XmlRpcClientConfigImpl; import org.apache.xmlrpc.client.XmlRpcCommonsTransportFactory; import org.apache.xmlrpc.client.util.ClientFactory; import java.net.URL; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.Properties; /** * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a> */ public class ContinuumXmlRpcClient implements ContinuumService { private final ContinuumService continuum; private static Hashtable<Integer, String> statusMap; static { statusMap = new Hashtable<Integer, String>(); statusMap.put( ContinuumProjectState.NEW, "New" ); statusMap.put( ContinuumProjectState.CHECKEDOUT, "New" ); statusMap.put( ContinuumProjectState.OK, "OK" ); statusMap.put( ContinuumProjectState.FAILED, "Failed" ); statusMap.put( ContinuumProjectState.ERROR, "Error" ); statusMap.put( ContinuumProjectState.BUILDING, "Building" ); statusMap.put( ContinuumProjectState.CHECKING_OUT, "Checking out" ); statusMap.put( ContinuumProjectState.UPDATING, "Updating" ); statusMap.put( ContinuumProjectState.WARNING, "Warning" ); } public ContinuumXmlRpcClient( URL serviceUrl ) { this( serviceUrl, null, null ); } public ContinuumXmlRpcClient( URL serviceUrl, String login, String password ) { XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl() { public boolean isEnabledForExtensions() { return true; } }; if ( login != null ) { config.setBasicUserName( login ); config.setBasicPassword( password ); } config.setServerURL( serviceUrl ); XmlRpcClient client = new XmlRpcClient(); client.setTransportFactory( new XmlRpcCommonsTransportFactory( client ) ); client.setConfig( config ); ClientFactory factory = new ClientFactory( client ); continuum = (ContinuumService) factory.newInstance( ContinuumService.class ); } public boolean ping() throws Exception { return continuum.ping(); } // ---------------------------------------------------------------------- // Projects // ---------------------------------------------------------------------- public List<ProjectSummary> getProjects( int projectGroupId ) throws Exception { return continuum.getProjects( projectGroupId ); } public ProjectSummary getProjectSummary( int projectId ) throws Exception { return continuum.getProjectSummary( projectId ); } public Project getProjectWithAllDetails( int projectId ) throws Exception { return continuum.getProjectWithAllDetails( projectId ); } public int removeProject( int projectId ) throws Exception { return continuum.removeProject( projectId ); } public ProjectSummary updateProject( ProjectSummary project ) throws Exception { return continuum.updateProject( project ); } public ProjectSummary refreshProjectSummary( ProjectSummary project ) throws Exception { if ( project == null ) { return null; } return getProjectSummary( project.getId() ); } public Project refreshProjectWithAllDetails( ProjectSummary project ) throws Exception { if ( project == null ) { return null; } return getProjectWithAllDetails( project.getId() ); } // ---------------------------------------------------------------------- // Projects Groups // ---------------------------------------------------------------------- public List<ProjectGroupSummary> getAllProjectGroups() throws Exception { return continuum.getAllProjectGroups(); } public List<ProjectGroup> getAllProjectGroupsWithAllDetails() throws Exception { return continuum.getAllProjectGroupsWithAllDetails(); } /** * @deprecated */ public List<ProjectGroup> getAllProjectGroupsWithProjects() throws Exception { return getAllProjectGroupsWithAllDetails(); } public ProjectGroupSummary getProjectGroupSummary( int projectGroupId ) throws Exception { return continuum.getProjectGroupSummary( projectGroupId ); } public ProjectGroup getProjectGroupWithProjects( int projectGroupId ) throws Exception { return continuum.getProjectGroupWithProjects( projectGroupId ); } public int removeProjectGroup( int projectGroupId ) throws Exception { return continuum.removeProjectGroup( projectGroupId ); } public ProjectGroupSummary refreshProjectGroupSummary( ProjectGroupSummary projectGroup ) throws Exception { if ( projectGroup == null ) { return null; } return getProjectGroupSummary( projectGroup.getId() ); } public ProjectGroup refreshProjectGroupSummaryWithProjects( ProjectGroupSummary projectGroup ) throws Exception { if ( projectGroup == null ) { return null; } return getProjectGroupWithProjects( projectGroup.getId() ); } public ProjectGroupSummary updateProjectGroup( ProjectGroupSummary projectGroup ) throws Exception { return continuum.updateProjectGroup( projectGroup ); } public ProjectGroupSummary addProjectGroup( ProjectGroupSummary pg ) throws Exception { return addProjectGroup( pg.getName(), pg.getGroupId(), pg.getDescription() ); } public ProjectGroupSummary addProjectGroup( String groupName, String groupId, String description ) throws Exception { return continuum.addProjectGroup( groupName, groupId, description ); } // ---------------------------------------------------------------------- // Build Definitions // ---------------------------------------------------------------------- public List<BuildDefinition> getBuildDefinitionsForProject( int projectId ) throws Exception { return continuum.getBuildDefinitionsForProject( projectId ); } public List<BuildDefinition> getBuildDefinitionsForProjectGroup( int projectGroupId ) throws Exception { return continuum.getBuildDefinitionsForProjectGroup( projectGroupId ); } public BuildDefinition updateBuildDefinitionForProject( int projectId, BuildDefinition buildDef ) throws Exception { return continuum.updateBuildDefinitionForProject( projectId, buildDef ); } public BuildDefinition updateBuildDefinitionForProjectGroup( int projectGroupId, BuildDefinition buildDef ) throws Exception { return continuum.updateBuildDefinitionForProjectGroup( projectGroupId, buildDef ); } public int removeBuildDefinitionFromProjectGroup( int projectGroupId, int buildDefinitionId ) throws Exception { return continuum.removeBuildDefinitionFromProjectGroup( projectGroupId, buildDefinitionId ); } public BuildDefinition addBuildDefinitionToProject( int projectId, BuildDefinition buildDef ) throws Exception { return continuum.addBuildDefinitionToProject( projectId, buildDef ); } public BuildDefinition addBuildDefinitionToProjectGroup( int projectGroupId, BuildDefinition buildDef ) throws Exception { return continuum.addBuildDefinitionToProjectGroup( projectGroupId, buildDef ); } public List<BuildDefinitionTemplate> getBuildDefinitionTemplates() throws Exception { return continuum.getBuildDefinitionTemplates(); } // ---------------------------------------------------------------------- // Building // ---------------------------------------------------------------------- public int addProjectToBuildQueue( int projectId ) throws Exception { return continuum.addProjectToBuildQueue( projectId ); } public int addProjectToBuildQueue( int projectId, int buildDefinitionId ) throws Exception { return continuum.addProjectToBuildQueue( projectId, buildDefinitionId ); } public int buildProject( int projectId ) throws Exception { return continuum.buildProject( projectId ); } public int buildProject( int projectId, int buildDefinitionId ) throws Exception { return continuum.buildProject( projectId, buildDefinitionId ); } public int buildProject( int projectId, BuildTrigger buildTrigger ) throws Exception { return continuum.buildProject( projectId, buildTrigger ); } public int buildProject( int projectId, int buildDefinitionId, BuildTrigger buildTrigger ) throws Exception { return continuum.buildProject( projectId, buildDefinitionId, buildTrigger ); } public int buildGroup( int projectGroupId ) throws Exception { return continuum.buildGroup( projectGroupId ); } public int buildGroup( int projectGroupId, int buildDefinitionId ) throws Exception { return continuum.buildGroup( projectGroupId, buildDefinitionId ); } // ---------------------------------------------------------------------- // SCM roots // ---------------------------------------------------------------------- public List<ProjectScmRoot> getProjectScmRootByProjectGroup( int projectGroupId ) throws Exception { return continuum.getProjectScmRootByProjectGroup( projectGroupId ); } public ProjectScmRoot getProjectScmRootByProject( int projectId ) throws Exception { return continuum.getProjectScmRootByProject( projectId ); } // ---------------------------------------------------------------------- // Build Results // ---------------------------------------------------------------------- public BuildResult getLatestBuildResult( int projectId ) throws Exception { return continuum.getLatestBuildResult( projectId ); } public BuildResult getBuildResult( int projectId, int buildId ) throws Exception { return continuum.getBuildResult( projectId, buildId ); } public List<BuildResultSummary> getBuildResultsForProject( int projectId, int offset, int length ) throws Exception { return continuum.getBuildResultsForProject( projectId, offset, length ); } public int removeBuildResult( BuildResult br ) throws Exception { return continuum.removeBuildResult( br ); } public String getBuildOutput( int projectId, int buildId ) throws Exception { return continuum.getBuildOutput( projectId, buildId ); } // ---------------------------------------------------------------------- // Maven 2.x projects // ---------------------------------------------------------------------- public AddingResult addMavenTwoProject( String url ) throws Exception { return continuum.addMavenTwoProject( url ); } public AddingResult addMavenTwoProject( String url, int projectGroupId ) throws Exception { return continuum.addMavenTwoProject( url, projectGroupId ); } public AddingResult addMavenTwoProject( String url, int projectGroupId, boolean checkoutInSingleDirectory ) throws Exception { return continuum.addMavenTwoProject( url, projectGroupId, checkoutInSingleDirectory ); } public AddingResult addMavenTwoProjectAsSingleProject( String url, int projectGroupId ) throws Exception { return continuum.addMavenTwoProjectAsSingleProject( url, projectGroupId ); } public AddingResult addMavenTwoProject( String url, int projectGroupId, boolean checkProtocol, boolean useCredentialsCache, boolean recursiveProjects, boolean checkoutInSingleDirectory ) throws Exception { return continuum.addMavenTwoProject( url, projectGroupId, checkProtocol, useCredentialsCache, recursiveProjects, checkoutInSingleDirectory ); } // ---------------------------------------------------------------------- // Maven 1.x projects // ---------------------------------------------------------------------- public AddingResult addMavenOneProject( String url, int projectGroupId ) throws Exception { return continuum.addMavenOneProject( url, projectGroupId ); } // ---------------------------------------------------------------------- // Maven ANT projects // ---------------------------------------------------------------------- public ProjectSummary addAntProject( ProjectSummary project, int projectGroupId ) throws Exception { return continuum.addAntProject( project, projectGroupId ); } // ---------------------------------------------------------------------- // Maven Shell projects // ---------------------------------------------------------------------- public ProjectSummary addShellProject( ProjectSummary project, int projectGroupId ) throws Exception { return continuum.addShellProject( project, projectGroupId ); } // ---------------------------------------------------------------------- // Schedules // ---------------------------------------------------------------------- public List<Schedule> getSchedules() throws Exception { return continuum.getSchedules(); } public Schedule getSchedule( int scheduleId ) throws Exception { return continuum.getSchedule( scheduleId ); } public Schedule addSchedule( Schedule schedule ) throws Exception { return continuum.addSchedule( schedule ); } public Schedule updateSchedule( Schedule schedule ) throws Exception { return continuum.updateSchedule( schedule ); } // ---------------------------------------------------------------------- // Profiles // ---------------------------------------------------------------------- public List<Profile> getProfiles() throws Exception { return continuum.getProfiles(); } public Profile getProfile( int profileId ) throws Exception { return continuum.getProfile( profileId ); } public Profile getProfileWithName( String profileName ) throws Exception { return continuum.getProfileWithName( profileName ); } // ---------------------------------------------------------------------- // Installations // ---------------------------------------------------------------------- public List<Installation> getInstallations() throws Exception { return continuum.getInstallations(); } public Installation getInstallation( int installationId ) throws Exception { return continuum.getInstallation( installationId ); } public Installation getInstallation( String installationName ) throws Exception { return continuum.getInstallation( installationName ); } public List<Installation> getBuildAgentInstallations( String url ) throws Exception { return continuum.getBuildAgentInstallations( url ); } // ---------------------------------------------------------------------- // SystemConfiguration // ---------------------------------------------------------------------- public SystemConfiguration getSystemConfiguration() throws Exception { return continuum.getSystemConfiguration(); } // ---------------------------------------------------------------------- // Utils // ---------------------------------------------------------------------- public String getProjectStatusAsString( int status ) { return statusMap.get( new Integer( status ) ); } // ---------------------------------------------------------------------- // Queue // ---------------------------------------------------------------------- public boolean isProjectInPrepareBuildQueue( int projectId ) throws Exception { return continuum.isProjectInPrepareBuildQueue( projectId ); } public boolean isProjectInPrepareBuildQueue( int projectId, int buildDefinitionId ) throws Exception { return continuum.isProjectInPrepareBuildQueue( projectId, buildDefinitionId ); } public List<BuildProjectTask> getProjectsInBuildQueue() throws Exception { return continuum.getProjectsInBuildQueue(); } public boolean isProjectInBuildingQueue( int projectId ) throws Exception { return continuum.isProjectInBuildingQueue( projectId ); } public boolean isProjectInBuildingQueue( int projectId, int buildDefinitionId ) throws Exception { return continuum.isProjectInBuildingQueue( projectId, buildDefinitionId ); } public boolean isProjectCurrentlyPreparingBuild( int projectId ) throws Exception { return continuum.isProjectCurrentlyPreparingBuild( projectId ); } public boolean isProjectCurrentlyPreparingBuild( int projectId, int buildDefinitionId ) throws Exception { return continuum.isProjectCurrentlyPreparingBuild( projectId, buildDefinitionId ); } public boolean isProjectCurrentlyBuilding( int projectId ) throws Exception { return continuum.isProjectCurrentlyBuilding( projectId ); } public boolean isProjectCurrentlyBuilding( int projectId, int buildDefinitionId ) throws Exception { return continuum.isProjectCurrentlyBuilding( projectId, buildDefinitionId ); } public int removeProjectsFromBuildingQueue( int[] projectsId ) throws Exception { return continuum.removeProjectsFromBuildingQueue( projectsId ); } public boolean cancelCurrentBuild() throws Exception { return continuum.cancelCurrentBuild(); } public boolean cancelBuild( int projectId, int buildDefinitionId ) throws Exception { return continuum.cancelBuild( projectId, buildDefinitionId ); } // ---------------------------------------------------------------------- // Release Result // ---------------------------------------------------------------------- public ContinuumReleaseResult getReleaseResult( int releaseId ) throws Exception { return continuum.getReleaseResult( releaseId ); } public List<ContinuumReleaseResult> getReleaseResultsForProjectGroup( int projectGroupId ) throws Exception { return continuum.getReleaseResultsForProjectGroup( projectGroupId ); } public int removeReleaseResult( ContinuumReleaseResult releaseResult ) throws Exception { return continuum.removeReleaseResult( releaseResult ); } public String getReleaseOutput( int releaseId ) throws Exception { return continuum.getReleaseOutput( releaseId ); } // ---------------------------------------------------------------------- // Purge Configuration // ---------------------------------------------------------------------- public RepositoryPurgeConfiguration addRepositoryPurgeConfiguration( RepositoryPurgeConfiguration repoPurge ) throws Exception { return continuum.addRepositoryPurgeConfiguration( repoPurge ); } public int updateRepositoryPurgeConfiguration( RepositoryPurgeConfiguration repoPurge ) throws Exception { return continuum.updateRepositoryPurgeConfiguration( repoPurge ); } public int removeRepositoryPurgeConfiguration( int repoPurgeId ) throws Exception { return continuum.removeRepositoryPurgeConfiguration( repoPurgeId ); } public RepositoryPurgeConfiguration getRepositoryPurgeConfiguration( int repoPurgeId ) throws Exception { return continuum.getRepositoryPurgeConfiguration( repoPurgeId ); } public List<RepositoryPurgeConfiguration> getAllRepositoryPurgeConfigurations() throws Exception { return continuum.getAllRepositoryPurgeConfigurations(); } public DirectoryPurgeConfiguration addDirectoryPurgeConfiguration( DirectoryPurgeConfiguration dirPurge ) throws Exception { return continuum.addDirectoryPurgeConfiguration( dirPurge ); } public int updateDirectoryPurgeConfiguration( DirectoryPurgeConfiguration dirPurge ) throws Exception { return continuum.updateDirectoryPurgeConfiguration( dirPurge ); } public int removeDirectoryPurgeConfiguration( int dirPurgeId ) throws Exception { return continuum.removeDirectoryPurgeConfiguration( dirPurgeId ); } public DirectoryPurgeConfiguration getDirectoryPurgeConfiguration( int dirPurgeId ) throws Exception { return continuum.getDirectoryPurgeConfiguration( dirPurgeId ); } public List<DirectoryPurgeConfiguration> getAllDirectoryPurgeConfigurations() throws Exception { return continuum.getAllDirectoryPurgeConfigurations(); } public int purgeLocalRepository( int repoPurgeId ) throws Exception { return continuum.purgeLocalRepository( repoPurgeId ); } public int purgeDirectory( int dirPurgeId ) throws Exception { return continuum.purgeDirectory( dirPurgeId ); } // ---------------------------------------------------------------------- // Local Repository // ---------------------------------------------------------------------- public LocalRepository addLocalRepository( LocalRepository repository ) throws Exception { return continuum.addLocalRepository( repository ); } public int updateLocalRepository( LocalRepository repository ) throws Exception { return continuum.updateLocalRepository( repository ); } public int removeLocalRepository( int repositoryId ) throws Exception { return continuum.removeLocalRepository( repositoryId ); } public LocalRepository getLocalRepository( int repositoryId ) throws Exception { return continuum.getLocalRepository( repositoryId ); } public List<LocalRepository> getAllLocalRepositories() throws Exception { return continuum.getAllLocalRepositories(); } // ---------------------------------------------------------------------- // ConfigurationService // ---------------------------------------------------------------------- public BuildAgentConfiguration addBuildAgent( BuildAgentConfiguration buildAgentConfiguration ) throws Exception { return continuum.addBuildAgent( buildAgentConfiguration ); } public BuildAgentConfiguration getBuildAgent( String url ) { return continuum.getBuildAgent( url ); } public BuildAgentConfiguration updateBuildAgent( BuildAgentConfiguration buildAgentConfiguration ) throws Exception { return continuum.updateBuildAgent( buildAgentConfiguration ); } public boolean removeBuildAgent( String url ) throws Exception { return continuum.removeBuildAgent( url ); } public List<BuildAgentConfiguration> getAllBuildAgents() { return continuum.getAllBuildAgents(); } public Map<String, Object> addAntProjectRPC( Map<String, Object> project, int projectGroupId ) throws Exception { return continuum.addAntProjectRPC( project, projectGroupId ); } public Map<String, Object> addBuildDefinitionToProjectGroupRPC( int projectGroupId, Map<String, Object> buildDef ) throws Exception { return continuum.addBuildDefinitionToProjectGroupRPC( projectGroupId, buildDef ); } public Map<String, Object> addBuildDefinitionToProjectRPC( int projectId, Map<String, Object> buildDef ) throws Exception { return continuum.addBuildDefinitionToProjectRPC( projectId, buildDef ); } public Map<String, Object> addMavenOneProjectRPC( String url, int projectGroupId ) throws Exception { return continuum.addMavenOneProjectRPC( url, projectGroupId ); } public Map<String, Object> addMavenTwoProjectRPC( String url ) throws Exception { return continuum.addMavenTwoProjectRPC( url ); } public Map<String, Object> addMavenTwoProjectRPC( String url, int projectGroupId ) throws Exception { return continuum.addMavenTwoProjectRPC( url, projectGroupId ); } public Map<String, Object> addMavenTwoProjectRPC( String url, int projectGroupId, boolean checkoutInSingleDirectory ) throws Exception { return continuum.addMavenTwoProjectRPC( url, projectGroupId, checkoutInSingleDirectory ); } public Map<String, Object> addMavenTwoProjectAsSingleProjectRPC( String url, int projectGroupId ) throws Exception { return continuum.addMavenTwoProjectAsSingleProjectRPC( url, projectGroupId ); } public Map<String, Object> addMavenTwoProjectRPC( String url, int projectGroupId, boolean checkProtocol, boolean useCredentialsCache, boolean recursiveProjects, boolean checkoutInSingleDirectory ) throws Exception { return continuum.addMavenTwoProjectRPC( url, projectGroupId, checkProtocol, useCredentialsCache, recursiveProjects, checkoutInSingleDirectory ); } public Map<String, Object> addProjectGroupRPC( String groupName, String groupId, String description ) throws Exception { return continuum.addProjectGroupRPC( groupName, groupId, description ); } public Map<String, Object> addScheduleRPC( Map<String, Object> schedule ) throws Exception { return continuum.addScheduleRPC( schedule ); } public Map<String, Object> addShellProjectRPC( Map<String, Object> project, int projectGroupId ) throws Exception { return continuum.addShellProjectRPC( project, projectGroupId ); } public List<Object> getAllProjectGroupsRPC() throws Exception { return continuum.getAllProjectGroupsRPC(); } public List<Object> getAllProjectGroupsWithAllDetailsRPC() throws Exception { return continuum.getAllProjectGroupsWithAllDetailsRPC(); } public List<Object> getBuildDefinitionTemplatesRPC() throws Exception { return continuum.getBuildDefinitionTemplatesRPC(); } public List<Object> getBuildDefinitionsForProjectGroupRPC( int projectGroupId ) throws Exception { return continuum.getBuildDefinitionsForProjectGroupRPC( projectGroupId ); } public List<Object> getBuildDefinitionsForProjectRPC( int projectId ) throws Exception { return continuum.getBuildDefinitionsForProjectRPC( projectId ); } public Map<String, Object> getBuildResultRPC( int projectId, int buildId ) throws Exception { return continuum.getBuildResultRPC( projectId, buildId ); } public List<Object> getBuildResultsForProjectRPC( int projectId, int offset, int length ) throws Exception { return continuum.getBuildResultsForProjectRPC( projectId, offset, length ); } public Map<String, Object> getInstallationRPC( int installationId ) throws Exception { return continuum.getInstallationRPC( installationId ); } public Map<String, Object> getInstallationRPC( String installationName ) throws Exception { return continuum.getInstallationRPC( installationName ); } public List<Object> getInstallationsRPC() throws Exception { return continuum.getInstallationsRPC(); } public List<Object> getBuildAgentInstallationsRPC( String url ) throws Exception { return continuum.getBuildAgentInstallationsRPC( url ); } public Map<String, Object> getLatestBuildResultRPC( int projectId ) throws Exception { return continuum.getLatestBuildResultRPC( projectId ); } public Map<String, Object> getProfileRPC( int profileId ) throws Exception { return continuum.getProfileRPC( profileId ); } public Map<String, Object> getProfileWithNameRPC( String profileName ) throws Exception { return continuum.getProfileWithNameRPC( profileName ); } public List<Object> getProfilesRPC() throws Exception { return continuum.getProfilesRPC(); } public Map<String, Object> getProjectGroupSummaryRPC( int projectGroupId ) throws Exception { return continuum.getProjectGroupSummaryRPC( projectGroupId ); } public Map<String, Object> getProjectGroupWithProjectsRPC( int projectGroupId ) throws Exception { return continuum.getProjectGroupWithProjectsRPC( projectGroupId ); } public Map<String, Object> updateProjectGroupRPC( Map<String, Object> projectGroup ) throws Exception { return continuum.updateProjectGroupRPC( projectGroup ); } public Map<String, Object> getProjectSummaryRPC( int projectId ) throws Exception { return continuum.getProjectSummaryRPC( projectId ); } public Map<String, Object> getProjectWithAllDetailsRPC( int projectId ) throws Exception { return continuum.getProjectWithAllDetailsRPC( projectId ); } public List<Object> getProjectsRPC( int projectGroupId ) throws Exception { return continuum.getProjectsRPC( projectGroupId ); } public Map<String, Object> getScheduleRPC( int scheduleId ) throws Exception { return continuum.getScheduleRPC( scheduleId ); } public List<Object> getSchedulesRPC() throws Exception { return continuum.getSchedulesRPC(); } public Map<String, Object> getSystemConfigurationRPC() throws Exception { return continuum.getSystemConfigurationRPC(); } public int removeBuildResultRPC( Map<String, Object> br ) throws Exception { return continuum.removeBuildResultRPC( br ); } public Map<String, Object> updateBuildDefinitionForProjectGroupRPC( int projectGroupId, Map<String, Object> buildDef ) throws Exception { return continuum.updateBuildDefinitionForProjectGroupRPC( projectGroupId, buildDef ); } public Map<String, Object> updateBuildDefinitionForProjectRPC( int projectId, Map<String, Object> buildDef ) throws Exception { return continuum.updateBuildDefinitionForProjectRPC( projectId, buildDef ); } public Map<String, Object> updateProjectRPC( Map<String, Object> project ) throws Exception { return continuum.updateProjectRPC( project ); } public Map<String, Object> updateScheduleRPC( Map<String, Object> schedule ) throws Exception { return continuum.updateScheduleRPC( schedule ); } public ProjectGroup getProjectGroup( int projectGroupId ) throws Exception { return continuum.getProjectGroup( projectGroupId ); } public Map<String, Object> getProjectGroupRPC( int projectGroupId ) throws Exception { return continuum.getProjectGroupRPC( projectGroupId ); } public ProjectNotifier getGroupNotifier( int projectgroupid, int notifierId ) throws Exception { return continuum.getGroupNotifier( projectgroupid, notifierId ); } public Map<String, Object> getGroupNotifierRPC( int projectgroupid, int notifierId ) throws Exception { return continuum.getGroupNotifierRPC( projectgroupid, notifierId ); } public ProjectNotifier getNotifier( int projectid, int notifierId ) throws Exception { return continuum.getNotifier( projectid, notifierId ); } public Map<String, Object> getNotifierRPC( int projectid, int notifierId ) throws Exception { return continuum.getNotifierRPC( projectid, notifierId ); } public ProjectNotifier updateGroupNotifier( int projectgroupid, ProjectNotifier newNotifier ) throws Exception { return continuum.updateGroupNotifier( projectgroupid, newNotifier ); } public Map<String, Object> updateGroupNotifierRPC( int projectgroupid, Map<String, Object> newNotifier ) throws Exception { return continuum.updateGroupNotifierRPC( projectgroupid, newNotifier ); } public ProjectNotifier updateNotifier( int projectid, ProjectNotifier newNotifier ) throws Exception { return continuum.updateNotifier( projectid, newNotifier ); } public Map<String, Object> updateNotifierRPC( int projectid, Map<String, Object> newNotifier ) throws Exception { return continuum.updateNotifierRPC( projectid, newNotifier ); } public int removeGroupNotifier( int projectgroupid, int notifierId ) throws Exception { return continuum.removeGroupNotifier( projectgroupid, notifierId ); } public int removeNotifier( int projectid, int notifierId ) throws Exception { return continuum.removeNotifier( projectid, notifierId ); } public ProjectNotifier addGroupNotifier( int projectgroupid, ProjectNotifier newNotifier ) throws Exception { return continuum.addGroupNotifier( projectgroupid, newNotifier ); } public Map<String, Object> addGroupNotifierRPC( int projectgroupid, Map<String, Object> newNotifier ) throws Exception { return continuum.addGroupNotifierRPC( projectgroupid, newNotifier ); } public ProjectNotifier addNotifier( int projectid, ProjectNotifier newNotifier ) throws Exception { return continuum.addNotifier( projectid, newNotifier ); } public Map<String, Object> addNotifierRPC( int projectid, Map<String, Object> newNotifier ) throws Exception { return continuum.addNotifierRPC( projectid, newNotifier ); } public Installation addInstallation( Installation installation ) throws Exception { return continuum.addInstallation( installation ); } public Map<String, Object> addInstallationRPC( Map<String, Object> installation ) throws Exception { return continuum.addInstallationRPC( installation ); } public Profile addProfile( Profile profile ) throws Exception { return continuum.addProfile( profile ); } public Map<String, Object> addProfileRPC( Map<String, Object> profile ) throws Exception { return continuum.addProfileRPC( profile ); } public int deleteInstallation( int installationId ) throws Exception { return continuum.deleteInstallation( installationId ); } public int deleteProfile( int profileId ) throws Exception { return continuum.deleteProfile( profileId ); } public int updateInstallation( Installation installation ) throws Exception { return continuum.updateInstallation( installation ); } public int updateInstallationRPC( Map<String, Object> installation ) throws Exception { return continuum.updateInstallationRPC( installation ); } public int updateProfile( Profile profile ) throws Exception { return continuum.updateProfile( profile ); } public int updateProfileRPC( Map<String, Object> profile ) throws Exception { return continuum.updateProfileRPC( profile ); } public Map<String, Object> getReleaseResultRPC( int releaseId ) throws Exception { return continuum.getReleaseResultRPC( releaseId ); } public List<Object> getReleaseResultsForProjectGroupRPC( int projectGroupId ) throws Exception { return continuum.getReleaseResultsForProjectGroupRPC( projectGroupId ); } public int removeReleaseResultRPC( Map<String, Object> rr ) throws Exception { return continuum.removeReleaseResultRPC( rr ); } public Map<String, Object> addRepositoryPurgeConfigurationRPC( Map<String, Object> repoPurge ) throws Exception { return continuum.addRepositoryPurgeConfigurationRPC( repoPurge ); } public int updateRepositoryPurgeConfigurationRPC( Map<String, Object> repoPurge ) throws Exception { return continuum.updateRepositoryPurgeConfigurationRPC( repoPurge ); } public Map<String, Object> getRepositoryPurgeConfigurationRPC( int repoPurgeId ) throws Exception { return continuum.getRepositoryPurgeConfigurationRPC( repoPurgeId ); } public List<Object> getAllRepositoryPurgeConfigurationsRPC() throws Exception { return continuum.getAllRepositoryPurgeConfigurationsRPC(); } public Map<String, Object> addDirectoryPurgeConfigurationRPC( Map<String, Object> dirPurge ) throws Exception { return continuum.addDirectoryPurgeConfigurationRPC( dirPurge ); } public int updateDirectoryPurgeConfigurationRPC( Map<String, Object> dirPurge ) throws Exception { return continuum.updateDirectoryPurgeConfigurationRPC( dirPurge ); } public Map<String, Object> getDirectoryPurgeConfigurationRPC( int dirPurgeId ) throws Exception { return continuum.getDirectoryPurgeConfigurationRPC( dirPurgeId ); } public List<Object> getAllDirectoryPurgeConfigurationsRPC() throws Exception { return continuum.getAllDirectoryPurgeConfigurationsRPC(); } public Map<String, Object> addLocalRepositoryRPC( Map<String, Object> repository ) throws Exception { return continuum.addLocalRepositoryRPC( repository ); } public int updateLocalRepositoryRPC( Map<String, Object> repository ) throws Exception { return continuum.updateLocalRepositoryRPC( repository ); } public Map<String, Object> getLocalRepositoryRPC( int repositoryId ) throws Exception { return continuum.getLocalRepositoryRPC( repositoryId ); } public List<Object> getAllLocalRepositoriesRPC() throws Exception { return continuum.getAllLocalRepositoriesRPC(); } public Map<String, Object> addBuildAgentRPC( Map<String, Object> buildAgentConfiguration ) throws Exception { return continuum.addBuildAgentRPC( buildAgentConfiguration ); } public Map<String, Object> getBuildAgentRPC( String url ) { return continuum.getBuildAgentRPC( url ); } public Map<String, Object> updateBuildAgentRPC( Map<String, Object> buildAgentConfiguration ) throws Exception { return continuum.updateBuildAgentRPC( buildAgentConfiguration ); } public List<Object> getAllBuildAgentsRPC() { return continuum.getAllBuildAgentsRPC(); } public int releasePerform( int projectId, String releaseId, String goals, String arguments, boolean useReleaseProfile, String repositoryName, String username ) throws Exception { return continuum.releasePerform( projectId, releaseId, goals, arguments, useReleaseProfile, repositoryName, username ); } public String releasePrepare( int projectId, Properties releaseProperties, Map<String, String> releaseVersions, Map<String, String> developmentVersions, Map<String, String> environments, String username ) throws Exception { return continuum.releasePrepare( projectId, releaseProperties, releaseVersions, developmentVersions, environments, username ); } public ReleaseListenerSummary getListener( int projectId, String releaseId ) throws Exception { return continuum.getListener( projectId, releaseId ); } public int releaseCleanup( int projectId, String releaseId ) throws Exception { return continuum.releaseCleanup( projectId, releaseId ); } public int releaseCleanup( int projectId, String releaseId, String releaseType ) throws Exception { return continuum.releaseCleanup( projectId, releaseId, releaseType ); } public int releaseRollback( int projectId, String releaseId ) throws Exception { return continuum.releaseRollback( projectId, releaseId ); } public Map<String, Object> getReleasePluginParameters( int projectId ) throws Exception { return continuum.getReleasePluginParameters( projectId ); } public List<Map<String, String>> getProjectReleaseAndDevelopmentVersions( int projectId, String pomFilename, boolean autoVersionSubmodules ) throws Exception { return continuum.getProjectReleaseAndDevelopmentVersions( projectId, pomFilename, autoVersionSubmodules ); } public boolean pingBuildAgent( String buildAgentUrl ) throws Exception { return continuum.pingBuildAgent( buildAgentUrl ); } public String getBuildAgentUrl( int projectId, int buildDefinitionId ) throws Exception { return continuum.getBuildAgentUrl( projectId, buildDefinitionId ); } public BuildDefinition getBuildDefinition( int buildDefinitionId ) throws Exception { return continuum.getBuildDefinition( buildDefinitionId ); } public Map<String, Object> getBuildDefinitionRPC( int buildDefinitionId ) throws Exception { return continuum.getBuildDefinitionRPC( buildDefinitionId ); } public BuildAgentGroupConfiguration addBuildAgentGroup( BuildAgentGroupConfiguration buildAgentGroup ) throws Exception { return continuum.addBuildAgentGroup( buildAgentGroup ); } public Map<String, Object> addBuildAgentGroupRPC( Map<String, Object> buildAgentGroup ) throws Exception { return continuum.addBuildAgentGroupRPC( buildAgentGroup ); } public BuildAgentGroupConfiguration getBuildAgentGroup( String name ) { return continuum.getBuildAgentGroup( name ); } public Map<String, Object> getBuildAgentGroupRPC( String name ) { return continuum.getBuildAgentGroupRPC( name ); } public BuildAgentGroupConfiguration updateBuildAgentGroup( BuildAgentGroupConfiguration buildAgentGroup ) throws Exception { return continuum.updateBuildAgentGroup( buildAgentGroup ); } public Map<String, Object> updateBuildAgentGroupRPC( Map<String, Object> buildAgentGroup ) throws Exception { return continuum.updateBuildAgentGroupRPC( buildAgentGroup ); } public int removeBuildAgentGroup( String name ) throws Exception { return continuum.removeBuildAgentGroup( name ); } public List<BuildAgentConfiguration> getBuildAgentsWithInstallations() throws Exception { return continuum.getBuildAgentsWithInstallations(); } public List<Object> getBuildAgentsWithInstallationsRPC() throws Exception { return continuum.getBuildAgentsWithInstallationsRPC(); } }
5,187
0
Create_ds/continuum/continuum-xmlrpc/continuum-xmlrpc-client/src/main/java/org/apache/maven/continuum/xmlrpc
Create_ds/continuum/continuum-xmlrpc/continuum-xmlrpc-client/src/main/java/org/apache/maven/continuum/xmlrpc/client/BuildResultsPurge.java
package org.apache.maven.continuum.xmlrpc.client; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.maven.continuum.xmlrpc.project.BuildResult; import org.apache.maven.continuum.xmlrpc.project.BuildResultSummary; import org.apache.maven.continuum.xmlrpc.project.ProjectGroupSummary; import org.apache.maven.continuum.xmlrpc.project.ProjectSummary; import java.net.URL; import java.util.Date; import java.util.List; /** * Utility class to purge old build results. * The easiest way to use it is to change the exec plugin config in the pom to execute this class instead of * SampleClient, change RETENTION_DAYS if desired, and type 'mvn clean install exec:exec' */ public class BuildResultsPurge { private static ContinuumXmlRpcClient client; private static long RETENTION_DAYS = 60; private static long DAY_IN_MILLISECONDS = 24 * 60 * 60 * 1000; public static void main( String[] args ) throws Exception { client = new ContinuumXmlRpcClient( new URL( args[0] ), args[1], args[2] ); long today = new Date().getTime(); System.out.println( "Today is " + new Date( today ) ); long purgeDate = today - ( RETENTION_DAYS * DAY_IN_MILLISECONDS ); //long purgeDate = today - 1000; // 1 second ago (for testing) System.out.println( "Purging build results older than " + new Date( purgeDate ) ); List<ProjectGroupSummary> groups = client.getAllProjectGroups(); for ( ProjectGroupSummary group : groups ) { System.out.println( "Project Group [" + group.getId() + "] " + group.getName() ); List<ProjectSummary> projects = client.getProjects( group.getId() ); for ( ProjectSummary project : projects ) { System.out.println( " Project [" + project.getId() + "] " + project.getName() ); int batchSize = 100, offset = 0; List<BuildResultSummary> results; do { int retained = 0; results = client.getBuildResultsForProject( project.getId(), offset, batchSize ); for ( BuildResultSummary brs : results ) { BuildResult br = client.getBuildResult( project.getId(), brs.getId() ); System.out.print( " Build Result [" + br.getId() + "] ended " + new Date( br.getEndTime() ) ); if ( br.getEndTime() > 0 && br.getEndTime() < purgeDate ) { client.removeBuildResult( br ); System.out.println( " ...removed." ); } else { System.out.println( " ...retained." ); retained++; } } offset += retained; // Only need to advance past items we keep } while ( results != null && results.size() == batchSize ); } } } }
5,188
0
Create_ds/continuum/continuum-xmlrpc/continuum-xmlrpc-client/src/main/java/org/apache/maven/continuum/xmlrpc
Create_ds/continuum/continuum-xmlrpc/continuum-xmlrpc-client/src/main/java/org/apache/maven/continuum/xmlrpc/client/SampleClient.java
package org.apache.maven.continuum.xmlrpc.client; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.xmlrpc.repository.DirectoryPurgeConfiguration; import org.apache.continuum.xmlrpc.repository.LocalRepository; import org.apache.continuum.xmlrpc.repository.RepositoryPurgeConfiguration; import org.apache.continuum.xmlrpc.utils.BuildTrigger; import org.apache.maven.continuum.xmlrpc.project.AddingResult; import org.apache.maven.continuum.xmlrpc.project.BuildDefinition; import org.apache.maven.continuum.xmlrpc.project.BuildResult; import org.apache.maven.continuum.xmlrpc.project.BuildResultSummary; import org.apache.maven.continuum.xmlrpc.project.ContinuumProjectState; import org.apache.maven.continuum.xmlrpc.project.ProjectDependency; import org.apache.maven.continuum.xmlrpc.project.ProjectGroupSummary; import org.apache.maven.continuum.xmlrpc.project.ProjectSummary; import org.apache.maven.continuum.xmlrpc.scm.ChangeSet; import org.apache.maven.continuum.xmlrpc.scm.ScmResult; import java.net.URL; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a> */ public class SampleClient { private static ContinuumXmlRpcClient client; public static void main( String[] args ) throws Exception { client = new ContinuumXmlRpcClient( new URL( args[0] ), args[1], args[2] ); // Test for [CONTINUUM-2641]: (test with distributed builds with multiple build agents or parallel builds with > 1 build queue) // make sure to set the projectIds to the actual projectIds of your projects added in Continuum int projectIds[] = new int[] { 2, 3, 4, 5, 6 }; List<Thread> threads = new ArrayList<Thread>(); for ( int i = 0; i < projectIds.length; i++ ) { final int order = i; final int projectId = projectIds[i]; Runnable task = new Runnable() { public void run() { BuildTrigger buildTrigger = new BuildTrigger(); buildTrigger.setTrigger( ContinuumProjectState.TRIGGER_FORCED ); buildTrigger.setTriggeredBy( "admin" ); System.out.println( "Building project #" + order + " '" + projectId + "'.." ); try { client.buildProject( projectId, buildTrigger ); } catch ( Exception e ) { throw new RuntimeException( e ); } } }; threads.add( new Thread( task ) ); } for ( Thread thread : threads ) { thread.start(); } System.out.println( "Adding project..." ); AddingResult result = client.addMavenTwoProject( "http://svn.apache.org/repos/asf/continuum/sandbox/simple-example/pom.xml" ); if ( result.hasErrors() ) { System.out.println( result.getErrorsAsString() ); return; } System.out.println( "Project Groups added." ); System.out.println( "=====================" ); int projectGroupId = 0; for ( Iterator i = result.getProjectGroups().iterator(); i.hasNext(); ) { ProjectGroupSummary pg = (ProjectGroupSummary) i.next(); projectGroupId = pg.getId(); printProjectGroupSummary( client.getProjectGroupSummary( projectGroupId ) ); } System.out.println(); System.out.println( "Projects added." ); System.out.println( "=====================" ); for ( Iterator i = result.getProjects().iterator(); i.hasNext(); ) { ProjectSummary p = (ProjectSummary) i.next(); printProjectSummary( client.getProjectSummary( p.getId() ) ); } System.out.println(); System.out.println( "Waiting the end of the check out..." ); ProjectSummary ps = (ProjectSummary) result.getProjects().get( 0 ); while ( !"New".equals( client.getProjectStatusAsString( ps.getState() ) ) ) { ps = client.refreshProjectSummary( ps ); System.out.println( "State of " + ps.getName() + "(" + ps.getId() + "): " + client.getProjectStatusAsString( ps.getState() ) ); Thread.sleep( 1000 ); } System.out.println(); BuildDefinition buildDef = new BuildDefinition(); buildDef.setArguments( "A-Za-z0-9_./=,\": \\-" ); buildDef.setSchedule( client.getSchedule( 1 ) ); client.addBuildDefinitionToProjectGroup( 1, buildDef ); ps = client.getProjectSummary( 1 ); System.out.println( "Add the project to the build queue." ); BuildTrigger trigger = new BuildTrigger(); trigger.setTrigger( 1 ); trigger.setTriggeredBy( "<script>alert('hahaha' )</script>" ); client.buildProject( ps.getId(), trigger ); while ( !"Building".equals( client.getProjectStatusAsString( ps.getState() ) ) ) { ps = client.refreshProjectSummary( ps ); Thread.sleep( 1000 ); } System.out.println( "Building..." ); String state = "unknown"; while ( "Updating".equals( client.getProjectStatusAsString( ps.getState() ) ) || "Building".equals( client.getProjectStatusAsString( ps.getState() ) ) ) { ps = client.refreshProjectSummary( ps ); state = client.getProjectStatusAsString( ps.getState() ); System.out.println( "State of " + ps.getName() + "(" + ps.getId() + "): " + state ); Thread.sleep( 1000 ); } System.out.println( "Build done with state=" + state + "." ); System.out.println( "Build result." ); System.out.println( "=====================" ); printBuildResult( client.getLatestBuildResult( ps.getId() ) ); System.out.println(); System.out.println( "Build output." ); System.out.println( "=====================" ); System.out.println( client.getBuildOutput( ps.getId(), ps.getLatestBuildId() ) ); System.out.println(); System.out.println( "Removing build results." ); System.out.println( "============================" ); int batchSize = 100; List<BuildResultSummary> results; do { results = client.getBuildResultsForProject( ps.getId(), 0, batchSize ); for ( BuildResultSummary brs : results ) { System.out.print( "Removing build result (" + brs.getId() + ") - " ); BuildResult br = client.getBuildResult( ps.getId(), brs.getId() ); System.out.println( ( client.removeBuildResult( br ) == 0 ? "OK" : "Error" ) ); } } while ( results != null && results.size() > 0 ); System.out.println( "Done." ); System.out.println(); System.out.println( "Projects list." ); System.out.println( "=====================" ); List projects = client.getProjects( projectGroupId ); for ( Iterator i = projects.iterator(); i.hasNext(); ) { ps = (ProjectSummary) i.next(); printProjectSummary( ps ); System.out.println(); } System.out.println(); System.out.println( "Remove all projects." ); System.out.println( "=====================" ); for ( Iterator i = projects.iterator(); i.hasNext(); ) { ps = (ProjectSummary) i.next(); System.out.println( "Removing '" + ps.getName() + "' - " + ps.getVersion() + " (" + ps.getId() + ")'..." ); client.removeProject( ps.getId() ); System.out.println( "Done." ); } System.out.println(); System.out.println( "Remove project group." ); System.out.println( "=====================" ); ProjectGroupSummary pg = client.getProjectGroupSummary( projectGroupId ); System.out.println( "Removing Project Group '" + pg.getName() + "' - " + pg.getGroupId() + " (" + pg.getId() + ")'..." ); client.removeProjectGroup( pg.getId() ); System.out.println( "Done." ); System.out.println(); LocalRepository repository = new LocalRepository(); repository.setLocation( "/home/marica/repository" ); repository.setName( "Repository" ); repository.setLayout( "default" ); System.out.println( "Adding local repository..." ); repository = client.addLocalRepository( repository ); System.out.println(); System.out.println( "Repository list" ); System.out.println( "=====================" ); List<LocalRepository> repositories = client.getAllLocalRepositories(); for ( LocalRepository repo : repositories ) { printLocalRepository( repo ); System.out.println(); } DirectoryPurgeConfiguration dirPurgeConfig = new DirectoryPurgeConfiguration(); dirPurgeConfig.setDirectoryType( "buildOutput" ); System.out.println( "Adding Directory Purge Configuration..." ); dirPurgeConfig = client.addDirectoryPurgeConfiguration( dirPurgeConfig ); System.out.println(); RepositoryPurgeConfiguration purgeConfig = new RepositoryPurgeConfiguration(); purgeConfig.setDeleteAll( true ); purgeConfig.setRepository( repository ); purgeConfig.setDescription( "Delete all artifacts from repository" ); System.out.println( "Adding Repository Purge Configuration..." ); purgeConfig = client.addRepositoryPurgeConfiguration( purgeConfig ); System.out.println(); System.out.println( "Repository Purge list" ); System.out.println( "=====================" ); List<RepositoryPurgeConfiguration> repoPurges = client.getAllRepositoryPurgeConfigurations(); for ( RepositoryPurgeConfiguration repoPurge : repoPurges ) { printRepositoryPurgeConfiguration( repoPurge ); } System.out.println(); System.out.println( "Remove local repository" ); System.out.println( "=====================" ); System.out.println( "Removing Local Repository '" + repository.getName() + "' (" + repository.getId() + ")..." ); client.removeLocalRepository( repository.getId() ); System.out.println( "Done." ); } public static void printProjectGroupSummary( ProjectGroupSummary pg ) { System.out.println( "Id: " + pg.getId() ); System.out.println( "Group Id" + pg.getGroupId() ); System.out.println( "Name: " + pg.getName() ); System.out.println( "Description:" + pg.getDescription() ); if ( pg.getLocalRepository() != null ) { System.out.println( "Local Repository:" + pg.getLocalRepository().getName() ); } else { System.out.println( "Local Repository:" ); } } public static void printProjectSummary( ProjectSummary project ) { System.out.println( "Id: " + project.getId() ); System.out.println( "Group Id:" + project.getGroupId() ); System.out.println( "Artifact Id: " + project.getArtifactId() ); System.out.println( "Version: " + project.getVersion() ); System.out.println( "Name: " + project.getName() ); System.out.println( "Description: " + project.getDescription() ); System.out.println( "SCM Url: " + project.getScmUrl() ); } public static void printBuildResult( BuildResult result ) { System.out.println( "Id: " + result.getId() ); System.out.println( "Project Id: " + result.getProject().getId() ); System.out.println( "Build Number: " + result.getBuildNumber() ); System.out.println( "Start Time: " + result.getStartTime() ); System.out.println( "End Time: " + result.getEndTime() ); System.out.println( "State: " + client.getProjectStatusAsString( result.getState() ) ); System.out.println( "Trigger: " + result.getTrigger() ); System.out.println( "Is success: " + result.isSuccess() ); System.out.println( "Exit code: " + result.getExitCode() ); System.out.println( "Error: " + result.getError() ); if ( result.getModifiedDependencies() != null ) { System.out.println( "Modified dependencies:" ); for ( Iterator i = result.getModifiedDependencies().iterator(); i.hasNext(); ) { printDependency( (ProjectDependency) i.next() ); } } if ( result.getScmResult() != null ) { System.out.println( "Scm Result:" ); printScmResult( result.getScmResult() ); } } public static void printDependency( ProjectDependency dep ) { System.out.println( "Group Id: " + dep.getGroupId() ); System.out.println( "Artifact Id: " + dep.getArtifactId() ); System.out.println( "Version: " + dep.getVersion() ); } public static void printScmResult( ScmResult scmResult ) { System.out.println( "Command Line: " + scmResult.getCommandLine() ); System.out.println( "Command Output: " + scmResult.getCommandOutput() ); System.out.println( "SCM Providr Messqge: " + scmResult.getProviderMessage() ); System.out.println( "Is Success: " + scmResult.isSuccess() ); System.out.println( "Exception: " + scmResult.getException() ); if ( scmResult.getChanges() != null ) { System.out.println( "Changes:" ); for ( Iterator i = scmResult.getChanges().iterator(); i.hasNext(); ) { printChangeSet( (ChangeSet) i.next() ); } } System.out.println( scmResult.getCommandLine() ); } public static void printChangeSet( ChangeSet changeSet ) { System.out.println( "Author: " + changeSet.getAuthor() ); System.out.println( "Date: " + changeSet.getDateAsDate() ); System.out.println( "Comment: " + changeSet.getComment() ); if ( changeSet.getFiles() != null ) { System.out.println( "Author: " + changeSet.getFiles() ); } } public static void printBuildDefinition( BuildDefinition buildDef ) { System.out.println( buildDef.getId() ); System.out.println( buildDef.getBuildFile() ); System.out.println( buildDef.getArguments() ); System.out.println( buildDef.getGoals() ); //printProfile( buildDef.getProfile() ); //printSchedule( buildDef.getSchedule() ); System.out.println( buildDef.isBuildFresh() ); System.out.println( buildDef.isDefaultForProject() ); } public static void printLocalRepository( LocalRepository repo ) { System.out.println( "Id: " + repo.getId() ); System.out.println( "Layout: " + repo.getLayout() ); System.out.println( "Location: " + repo.getLocation() ); System.out.println( "Name: " + repo.getName() ); } public static void printRepositoryPurgeConfiguration( RepositoryPurgeConfiguration repoPurge ) { System.out.println( "Id: " + repoPurge.getId() ); System.out.println( "Description: " + repoPurge.getDescription() ); System.out.println( "Local Repository: " + repoPurge.getRepository().getName() ); System.out.println( "Days Older: " + repoPurge.getDaysOlder() ); System.out.println( "Retention Count: " + repoPurge.getRetentionCount() ); System.out.println( "Delete All: " + repoPurge.isDeleteAll() ); System.out.println( "Delete Released Snapshots: " + repoPurge.isDeleteReleasedSnapshots() ); System.out.println( "Default Purge: " + repoPurge.isDefaultPurge() ); } }
5,189
0
Create_ds/continuum/continuum-xmlrpc/continuum-xmlrpc-backup/src/main/java/org/apache/maven/continuum/xmlrpc
Create_ds/continuum/continuum-xmlrpc/continuum-xmlrpc-backup/src/main/java/org/apache/maven/continuum/xmlrpc/backup/Backup.java
package org.apache.maven.continuum.xmlrpc.backup; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import com.sampullara.cli.Args; import com.sampullara.cli.Argument; import org.apache.continuum.xmlrpc.release.ContinuumReleaseResult; import org.apache.continuum.xmlrpc.repository.DirectoryPurgeConfiguration; import org.apache.continuum.xmlrpc.repository.LocalRepository; import org.apache.continuum.xmlrpc.repository.RepositoryPurgeConfiguration; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.maven.continuum.xmlrpc.client.ContinuumXmlRpcClient; import org.apache.maven.continuum.xmlrpc.project.*; import org.apache.maven.continuum.xmlrpc.scm.ChangeFile; import org.apache.maven.continuum.xmlrpc.scm.ChangeSet; import org.apache.maven.continuum.xmlrpc.scm.ScmResult; import org.apache.maven.continuum.xmlrpc.system.Installation; import org.apache.maven.continuum.xmlrpc.system.Profile; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.lang.reflect.Field; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; public class Backup { private static final Logger LOGGER = Logger.getLogger( Backup.class ); private static ContinuumXmlRpcClient client; private static int indent = 0; private static PrintWriter writer; public static void main( String[] args ) throws Exception { Commands command = new Commands(); try { Args.parse( command, args ); if ( command.help ) { Args.usage( command ); return; } if ( command.version ) { System.out.println( "continuum-xmlrpc-backup version: " + getVersion() ); return; } if ( command.url == null ) { System.out.println( "You must specified the Continuum XMLRPC URL" ); Args.usage( command ); return; } if ( command.username == null ) { System.out.println( "You must specified the Continuum username" ); Args.usage( command ); return; } if ( command.password == null ) { System.out.println( "You must specified the Continuum password" ); Args.usage( command ); return; } } catch ( IllegalArgumentException e ) { System.err.println( e.getMessage() ); Args.usage( command ); return; } BasicConfigurator.configure(); if ( command.debug ) { Logger.getRootLogger().setLevel( Level.DEBUG ); } else { Logger.getRootLogger().setLevel( Level.INFO ); } LOGGER.info( "Connection to " + command.url + "with username '" + command.username + "'..." ); client = new ContinuumXmlRpcClient( command.url, command.username, command.password ); LOGGER.info( "connected" ); File out = command.outputFile; if ( out == null ) { out = new File( "backup/builds.xml" ); } out.getParentFile().mkdirs(); if ( !command.overwrite && out.exists() ) { System.err.println( out.getAbsolutePath() + " already exists and will not be overwritten unless the -overwrite flag is used." ); Args.usage( command ); return; } writer = new PrintWriter( new FileWriter( out ) ); writer.println( "<?xml version='1.0' encoding='UTF-8'?>" ); startTag( "continuumDatabase", true ); backupSystemConfiguration(); backupAllSchedules(); backupAllInstallations(); backupAllProfiles(); backupAllBuildDefinitionTemplates(); backupAllProjectGroup(); backupAllLocalRepositories(); backupAllRepositoryPurgeConfigurations(); backupAllDirectoryPurgeConfigurations(); endTag( "continuumDatabase", true ); writer.close(); LOGGER.info( "Done." ); } private static String getVersion() throws IOException { Properties properties = new Properties(); properties.load( Backup.class.getResourceAsStream( "/META-INF/maven/org.apache.maven.continuum/continuum-xmlrpc-backup/pom.properties" ) ); return properties.getProperty( "version" ); } private static class Commands { @Argument( description = "Display help information", value = "help", alias = "h" ) private boolean help; @Argument( description = "Display version information", value = "version", alias = "v" ) private boolean version; @Argument( description = "Continuum XMLRPC URL", value = "url" ) private URL url; @Argument( description = "Username", value = "username", alias = "u" ) private String username; @Argument( description = "Password", value = "password", alias = "p" ) private String password; @Argument( description = "Backup file", value = "outputFile", alias = "o" ) private File outputFile; @Argument( description = "Whether to overwrite the designated backup file if it already exists in export mode. Default is false.", value = "overwrite" ) private boolean overwrite; @Argument( description = "Turn on debugging information. Default is off.", value = "debug" ) private boolean debug; } private static void backupSystemConfiguration() throws Exception { LOGGER.info( "Backup system configuration" ); writeObject( client.getSystemConfiguration(), "systemConfiguration", true ); } private static void backupAllSchedules() throws Exception { LOGGER.info( "Backup schedules" ); List<Schedule> schedules = client.getSchedules(); if ( schedules != null && !schedules.isEmpty() ) { startTag( "schedules", true ); for ( Schedule schedule : schedules ) { LOGGER.debug( "Backup schedule " + schedule.getName() ); writeObject( schedule, "schedule", true ); } endTag( "schedules", true ); } } private static void backupAllInstallations() throws Exception { LOGGER.info( "Backup installations" ); List<Installation> installs = client.getInstallations(); if ( installs != null && !installs.isEmpty() ) { startTag( "installations", true ); for ( Installation install : installs ) { LOGGER.debug( "Backup installation " + install.getName() ); writeObject( install, "installation", true ); } endTag( "installations", true ); } } private static void backupAllBuildDefinitionTemplates() throws Exception { LOGGER.info( "Backup Build Definitions Templates" ); List<BuildDefinitionTemplate> bdts = client.getBuildDefinitionTemplates(); if ( bdts != null && !bdts.isEmpty() ) { startTag( "buildDefinitionTemplates", true ); for ( BuildDefinitionTemplate bdt : bdts ) { LOGGER.debug( "Backup build definition template " + bdt.getName() ); startTag( "buildDefinitionTemplate", true ); writeSimpleFields( bdt ); List<BuildDefinition> bds = bdt.getBuildDefinitions(); if ( bds != null && !bds.isEmpty() ) { startTag( "buildDefinitions", true ); for ( BuildDefinition bd : bds ) { backupBuildDefinition( bd ); } endTag( "buildDefinitions", true ); } endTag( "buildDefinitionTemplate", true ); } endTag( "buildDefinitionTemplates", true ); } } private static void backupAllProfiles() throws Exception { LOGGER.info( "Backup profiles" ); List<Profile> profiles = client.getProfiles(); if ( profiles != null && !profiles.isEmpty() ) { startTag( "profiles", true ); for ( Profile p : profiles ) { LOGGER.debug( "Backup profile " + p.getName() ); writeProfile( p ); } endTag( "profiles", true ); } } private static void backupAllProjectGroup() throws Exception { LOGGER.info( "Backup project groups" ); List<ProjectGroup> pgs = client.getAllProjectGroupsWithAllDetails(); if ( pgs != null && !pgs.isEmpty() ) { startTag( "projectGroups", true ); for ( ProjectGroup pg : pgs ) { backupProjectGroup( pg ); } endTag( "projectGroups", true ); } } private static void backupProjectGroup( ProjectGroup pg ) throws Exception { if ( pg == null ) { return; } LOGGER.debug( "Backup project group " + pg.getName() ); startTag( "projectGroup", true ); writeSimpleFields( pg ); if ( pg.getProjects() != null && !pg.getProjects().isEmpty() ) { startTag( "projects", true ); for ( ProjectSummary ps : pg.getProjects() ) { backupProject( ps ); } endTag( "projects", true ); } if ( pg.getBuildDefinitions() != null && !pg.getBuildDefinitions().isEmpty() ) { startTag( "buildDefinitions", true ); for ( BuildDefinition bd : pg.getBuildDefinitions() ) { backupBuildDefinition( bd ); } endTag( "buildDefinitions", true ); } if ( pg.getNotifiers() != null && !pg.getNotifiers().isEmpty() ) { startTag( "notifiers", true ); for ( ProjectNotifier notif : pg.getNotifiers() ) { backupNotifier( notif ); } endTag( "notifiers", true ); } backupContinuumReleaseResultsForProjectGroup( pg.getId() ); endTag( "projectGroup", true ); } private static void backupProject( ProjectSummary ps ) throws Exception { if ( ps == null ) { return; } LOGGER.debug( "Backup project " + ps.getName() ); Project p = client.getProjectWithAllDetails( ps.getId() ); startTag( "project", true ); writeSimpleFields( p ); if ( p.getProjectGroup() != null ) { writeTagWithParameter( "projectGroup", "id", String.valueOf( p.getProjectGroup().getId() ) ); } if ( p.getDevelopers() != null && !p.getDevelopers().isEmpty() ) { startTag( "developers", true ); for ( ProjectDeveloper pd : p.getDevelopers() ) { writeObject( pd, "developer", true ); } endTag( "developers", true ); } if ( p.getDependencies() != null && !p.getDependencies().isEmpty() ) { startTag( "dependencies", true ); for ( ProjectDependency pd : p.getDependencies() ) { writeObject( pd, "dependency", true ); } endTag( "dependencies", true ); } if ( p.getBuildDefinitions() != null && !p.getBuildDefinitions().isEmpty() ) { startTag( "buildDefinitions", true ); for ( BuildDefinition bd : p.getBuildDefinitions() ) { backupBuildDefinition( bd ); } endTag( "buildDefinitions", true ); } if ( p.getNotifiers() != null && !p.getNotifiers().isEmpty() ) { startTag( "notifiers", true ); for ( ProjectNotifier notif : p.getNotifiers() ) { backupNotifier( notif ); } endTag( "notifiers", true ); } int batchSize = 100, offset = 0; List<BuildResultSummary> brs; do { brs = client.getBuildResultsForProject( p.getId(), offset, batchSize ); if ( brs != null && !brs.isEmpty() ) { startTag( "buildResults", true ); for ( BuildResultSummary brSummary : brs ) { BuildResult br = client.getBuildResult( p.getId(), brSummary.getId() ); backupBuildResult( br ); } endTag( "buildResults", true ); } offset += batchSize; } while ( brs != null && brs.size() == batchSize ); endTag( "project", true ); } private static void backupBuildResult( BuildResult br ) throws Exception { if ( br == null ) { return; } startTag( "buildResult", true ); writeSimpleFields( br ); if ( br.getProject() != null ) { writeTagWithParameter( "project", "id", String.valueOf( br.getProject().getId() ) ); } if ( br.getBuildDefinition() != null ) { writeTagWithParameter( "buildDefinition", "id", String.valueOf( br.getBuildDefinition().getId() ) ); } if ( br.getModifiedDependencies() != null && !br.getModifiedDependencies().isEmpty() ) { startTag( "dependencies", true ); for ( ProjectDependency pd : br.getModifiedDependencies() ) { writeObject( pd, "dependency", true ); } endTag( "dependencies", true ); } endTag( "buildResult", true ); } private static void writeSimpleFields( Object obj ) throws Exception { if ( obj == null ) { return; } for ( Field f : getFieldsIncludingSuperclasses( obj.getClass() ) ) { if ( "modelEncoding".equals( f.getName() ) ) { continue; } if ( !f.isAccessible() ) { f.setAccessible( true ); } if ( f.getType().getName().equals( "int" ) || f.getType().getName().equals( "long" ) || f.getType().getName().equals( "boolean" ) || f.getType().getName().equals( "java.lang.String" ) ) { Object value = f.get( obj ); if ( value != null ) { startTag( f.getName(), false ); writer.print( value ); endTag( f.getName(), false ); } } else if ( ScmResult.class.getName().equals( f.getType().getName() ) ) { writeScmResult( (ScmResult) f.get( obj ) ); } else if ( ChangeFile.class.getName().equals( f.getType().getName() ) ) { writeObject( f.get( obj ), "changeFile", true ); } else if ( Profile.class.getName().equals( f.getType().getName() ) ) { writeProfile( (Profile) f.get( obj ) ); } else { //LOGGER.debug( // "Rejected: (" + f.getName() + ") " + f.getType() + " in object " + obj.getClass().getName() ); } } } private static void writeObject( Object obj, String tagName, boolean addNewLine ) throws Exception { if ( obj == null ) { return; } startTag( tagName, addNewLine ); writeSimpleFields( obj ); endTag( tagName, addNewLine ); } private static void backupBuildDefinition( BuildDefinition buildDef ) throws Exception { if ( buildDef == null ) { return; } startTag( "buildDefinition", true ); writeSimpleFields( buildDef ); if ( buildDef.getSchedule() != null ) { writeTagWithParameter( "schedule", "id", String.valueOf( buildDef.getSchedule().getId() ) ); } endTag( "buildDefinition", true ); } private static void backupNotifier( ProjectNotifier notifier ) throws Exception { startTag( "notifier", true ); writeSimpleFields( notifier ); Map conf = notifier.getConfiguration(); startTag( "configuration", true ); for ( String key : (Set<String>) conf.keySet() ) { startTag( key, false ); writer.print( conf.get( key ) ); endTag( key, false ); } endTag( "configuration", true ); endTag( "notifier", true ); } private static void writeProfile( Profile profile ) throws Exception { if ( profile == null ) { return; } startTag( "profile", true ); writeSimpleFields( profile ); if ( profile.getEnvironmentVariables() != null && !profile.getEnvironmentVariables().isEmpty() ) { startTag( "environmentVariables", true ); for ( Installation env : (List<Installation>) profile.getEnvironmentVariables() ) { writeTagWithParameter( "environmentVariable", "installationId", String.valueOf( env.getInstallationId() ) ); } endTag( "environmentVariables", true ); } if ( profile.getJdk() != null ) { writeTagWithParameter( "jdk", "installationId", String.valueOf( profile.getJdk().getInstallationId() ) ); } if ( profile.getBuilder() != null ) { writeTagWithParameter( "builder", "installationId", String.valueOf( profile.getBuilder().getInstallationId() ) ); } endTag( "profile", true ); } private static void writeScmResult( ScmResult scmResult ) throws Exception { if ( scmResult == null ) { return; } startTag( "scmResult", true ); writeSimpleFields( scmResult ); if ( scmResult.getChanges() != null && !scmResult.getChanges().isEmpty() ) { startTag( "changeSets", true ); for ( ChangeSet cs : scmResult.getChanges() ) { writeObject( cs, "changeSet", true ); } endTag( "changeSets", true ); } endTag( "scmResult", true ); } private static void startTag( String tagName, boolean addNewLineAfter ) { writer.print( getIndent() ); writer.print( "<" ); writer.print( tagName ); writer.print( ">" ); if ( addNewLineAfter ) { writer.println(); indent++; } } private static void endTag( String tagName, boolean isOnNewLine ) { if ( isOnNewLine ) { indent--; writer.print( getIndent() ); } writer.print( "</" ); writer.print( tagName ); writer.println( ">" ); } private static void writeTagWithParameter( String tagName, String parameterName, String parameterValue ) { writer.print( getIndent() ); writer.print( "<" ); writer.print( tagName ); writer.print( " " ); writer.print( parameterName ); writer.print( "=\"" ); writer.print( parameterValue ); writer.print( "\"></" ); writer.print( tagName ); writer.println( ">" ); } private static String getIndent() { String result = ""; for ( int i = 0; i < indent; i++ ) { result += " "; } return result; } private static List<Field> getFieldsIncludingSuperclasses( Class clazz ) { List<Field> fields = new ArrayList<Field>( Arrays.asList( clazz.getDeclaredFields() ) ); Class superclass = clazz.getSuperclass(); if ( superclass != null ) { fields.addAll( getFieldsIncludingSuperclasses( superclass ) ); } return fields; } private static void backupAllLocalRepositories() throws Exception { LOGGER.info( "Backup local repositories" ); List<LocalRepository> repos = client.getAllLocalRepositories(); if ( repos != null && !repos.isEmpty() ) { startTag( "localRepositories", true ); for ( LocalRepository repo : repos ) { LOGGER.debug( "Backup local repository " + repo.getName() ); writeObject( repo, "localRepository", true ); } endTag( "localRepositories", true ); } } private static void backupAllRepositoryPurgeConfigurations() throws Exception { LOGGER.info( "Backup repository purge configurations" ); List<RepositoryPurgeConfiguration> purgeConfigs = client.getAllRepositoryPurgeConfigurations(); if ( purgeConfigs != null && !purgeConfigs.isEmpty() ) { startTag( "repositoryPurgeConfigurations", true ); for ( RepositoryPurgeConfiguration purgeConfig : purgeConfigs ) { LOGGER.debug( "Backup repository purge configuration" ); backupRepositoryPurgeConfiguration( purgeConfig ); } endTag( "repositoryPurgeConfigurations", true ); } } private static void backupRepositoryPurgeConfiguration( RepositoryPurgeConfiguration repoPurge ) throws Exception { if ( repoPurge == null ) { return; } startTag( "repositoryPurgeConfiguration", true ); writeSimpleFields( repoPurge ); if ( repoPurge.getRepository() != null ) { writeTagWithParameter( "repository", "id", String.valueOf( repoPurge.getRepository().getId() ) ); } if ( repoPurge.getSchedule() != null ) { writeTagWithParameter( "schedule", "id", String.valueOf( repoPurge.getSchedule().getId() ) ); } endTag( "repositoryPurgeConfiguration", true ); } private static void backupAllDirectoryPurgeConfigurations() throws Exception { LOGGER.info( "Backup repository purge configurations" ); List<DirectoryPurgeConfiguration> purgeConfigs = client.getAllDirectoryPurgeConfigurations(); if ( purgeConfigs != null && !purgeConfigs.isEmpty() ) { startTag( "directoryPurgeConfigurations", true ); for ( DirectoryPurgeConfiguration purgeConfig : purgeConfigs ) { LOGGER.debug( "Backup directory purge configuration" ); backupDirectoryPurgeConfiguration( purgeConfig ); } endTag( "directoryPurgeConfigurations", true ); } } private static void backupDirectoryPurgeConfiguration( DirectoryPurgeConfiguration dirPurge ) throws Exception { if ( dirPurge == null ) { return; } startTag( "directoryPurgeConfiguration", true ); writeSimpleFields( dirPurge ); if ( dirPurge.getSchedule() != null ) { writeTagWithParameter( "schedule", "id", String.valueOf( dirPurge.getSchedule().getId() ) ); } endTag( "directoryPurgeConfiguration", true ); } private static void backupContinuumReleaseResultsForProjectGroup( int projectGroupId ) throws Exception { LOGGER.info( "Backup release results" ); List<ContinuumReleaseResult> results = client.getReleaseResultsForProjectGroup( projectGroupId ); if ( results != null && !results.isEmpty() ) { startTag( "continuumReleaseResults", true ); for ( ContinuumReleaseResult result : results ) { LOGGER.debug( "Backup release result" ); backupContinuumReleaseResult( result ); } endTag( "continuumReleaseResults", true ); } } private static void backupContinuumReleaseResult( ContinuumReleaseResult result ) throws Exception { if ( result == null ) { return; } startTag( "continuumReleaseResult", true ); writeSimpleFields( result ); if ( result.getProjectGroup() != null ) { writeTagWithParameter( "projectGroup", "id", String.valueOf( result.getProjectGroup().getId() ) ); } if ( result.getProject() != null ) { writeTagWithParameter( "project", "id", String.valueOf( result.getProject().getId() ) ); } endTag( "continuumReleaseResult", true ); } }
5,190
0
Create_ds/continuum/continuum-store/src/test/java/org/apache/maven/continuum
Create_ds/continuum/continuum-store/src/test/java/org/apache/maven/continuum/store/ContinuumStoreTest.java
package org.apache.maven.continuum.store; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.dao.BuildDefinitionDao; import org.apache.continuum.dao.BuildDefinitionTemplateDao; import org.apache.continuum.dao.BuildResultDao; import org.apache.continuum.model.project.ProjectGroupSummary; import org.apache.continuum.model.project.ProjectScmRoot; import org.apache.continuum.model.release.ContinuumReleaseResult; import org.apache.continuum.model.repository.DirectoryPurgeConfiguration; import org.apache.continuum.model.repository.LocalRepository; import org.apache.continuum.model.repository.RepositoryPurgeConfiguration; import org.apache.maven.continuum.execution.ContinuumBuildExecutorConstants; import org.apache.maven.continuum.installation.InstallationService; import org.apache.maven.continuum.model.project.*; import org.apache.maven.continuum.model.system.Installation; import org.apache.maven.continuum.model.system.Profile; import org.junit.Before; import org.junit.Test; import javax.jdo.JDODetachedFieldAccessException; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Map; import static org.junit.Assert.*; import static java.util.Arrays.asList; /** * @author <a href="mailto:brett@apache.org">Brett Porter</a> * @todo I think this should have all the JDO stuff from the abstract test, and the abstract test * should use a mock continuum store with the exception of the integration tests which should be * running against a fully deployed plexus application instead * @todo review for ambiguities and ensure it is all encapsulated in the store, otherwise the code may make the same mistake about not deleting things, etc */ public class ContinuumStoreTest extends AbstractContinuumStoreTestCase { private static final int INVALID_ID = 15000; private BuildDefinitionTemplateDao buildDefinitionTemplateDao; protected BuildDefinitionDao buildDefinitionDao; protected BuildResultDao buildResultDao; // ---------------------------------------------------------------------- // TEST METHODS // ---------------------------------------------------------------------- @Test public void testAddProjectGroup() throws ContinuumStoreException { String name = "testAddProjectGroup"; String description = "testAddProjectGroup description"; String groupId = "org.apache.maven.continuum.test"; LocalRepository repository = localRepositoryDao.getLocalRepository( testLocalRepository3.getId() ); ProjectGroup group = createTestProjectGroup( name, description, groupId, repository ); ProjectGroup copy = createTestProjectGroup( group ); projectGroupDao.addProjectGroup( group ); copy.setId( group.getId() ); ProjectGroup retrievedGroup = projectGroupDao.getProjectGroup( group.getId() ); assertProjectGroupEquals( copy, retrievedGroup ); assertLocalRepositoryEquals( testLocalRepository3, retrievedGroup.getLocalRepository() ); } @Test public void testGetProjectGroup() throws ContinuumStoreException { ProjectGroup retrievedGroup = projectGroupDao.getProjectGroupWithProjects( defaultProjectGroup.getId() ); assertProjectGroupEquals( defaultProjectGroup, retrievedGroup ); assertLocalRepositoryEquals( testLocalRepository1, retrievedGroup.getLocalRepository() ); List<Project> projects = retrievedGroup.getProjects(); assertEquals( "Check number of projects", 2, projects.size() ); assertTrue( "Check existence of project 1", projects.contains( testProject1 ) ); assertTrue( "Check existence of project 2", projects.contains( testProject2 ) ); checkProjectGroupDefaultFetchGroup( retrievedGroup ); Project project = projects.get( 0 ); checkProjectDefaultFetchGroup( project ); assertEquals( project.getProjectGroup().getId(), retrievedGroup.getId() ); assertProjectEquals( testProject1, project ); project = projects.get( 1 ); checkProjectDefaultFetchGroup( project ); assertEquals( project.getProjectGroup().getId(), retrievedGroup.getId() ); assertProjectEquals( testProject2, project ); } @Test public void testGetInvalidProjectGroup() throws ContinuumStoreException { try { projectGroupDao.getProjectGroup( INVALID_ID ); fail( "Should not find group with invalid ID" ); } catch ( ContinuumObjectNotFoundException expected ) { assertTrue( true ); } } @Test public void testEditProjectGroup() throws ContinuumStoreException { ProjectGroup newGroup = projectGroupDao.getProjectGroup( testProjectGroup2.getId() ); newGroup.setName( "testEditProjectGroup2" ); newGroup.setDescription( "testEditProjectGroup updated description" ); newGroup.setGroupId( "org.apache.maven.continuum.test.new" ); ProjectGroup copy = createTestProjectGroup( newGroup ); copy.setId( newGroup.getId() ); projectGroupDao.updateProjectGroup( newGroup ); ProjectGroup retrievedGroup = projectGroupDao.getProjectGroup( testProjectGroup2.getId() ); assertProjectGroupEquals( copy, retrievedGroup ); assertLocalRepositoryEquals( testLocalRepository2, retrievedGroup.getLocalRepository() ); } @Test public void testUpdateUndetachedGroup() { ProjectGroup newGroup = new ProjectGroup(); newGroup.setId( testProjectGroup2.getId() ); newGroup.setName( "testUpdateUndetachedGroup2" ); newGroup.setDescription( "testUpdateUndetachedGroup updated description" ); newGroup.setGroupId( "org.apache.maven.continuum.test.new" ); try { projectGroupDao.updateProjectGroup( newGroup ); fail( "Should not have succeeded" ); } catch ( ContinuumStoreException expected ) { // good! assertTrue( true ); } } @Test public void testGetAllProjectGroups() { Collection<ProjectGroup> groups = projectGroupDao.getAllProjectGroupsWithProjects(); assertEquals( "check size", 2, groups.size() ); assertTrue( groups.contains( defaultProjectGroup ) ); assertTrue( groups.contains( testProjectGroup2 ) ); for ( ProjectGroup group : groups ) { List<Project> projects = group.getProjects(); if ( group.getId() == testProjectGroup2.getId() ) { assertProjectGroupEquals( testProjectGroup2, group ); assertLocalRepositoryEquals( testLocalRepository2, group.getLocalRepository() ); assertTrue( "check no projects", projects.isEmpty() ); } else if ( group.getId() == defaultProjectGroup.getId() ) { assertProjectGroupEquals( defaultProjectGroup, group ); assertLocalRepositoryEquals( testLocalRepository1, group.getLocalRepository() ); assertEquals( "Check number of projects", 2, projects.size() ); assertTrue( "Check existence of project 1", projects.contains( testProject1 ) ); assertTrue( "Check existence of project 2", projects.contains( testProject2 ) ); checkProjectGroupDefaultFetchGroup( group ); Project p = projects.get( 0 ); checkProjectDefaultFetchGroup( p ); assertSame( "Check project group reference matches", p.getProjectGroup(), group ); } } } @Test public void testGetProject() throws ContinuumStoreException { Project retrievedProject = projectDao.getProject( testProject1.getId() ); assertProjectEquals( testProject1, retrievedProject ); checkProjectDefaultFetchGroup( retrievedProject ); } @Test public void testGetProjectWithDetails() throws ContinuumStoreException { Project retrievedProject = projectDao.getProjectWithAllDetails( testProject1.getId() ); assertProjectEquals( testProject1, retrievedProject ); checkProjectFetchGroup( retrievedProject, false, false, true, true ); assertBuildDefinitionsEqual( retrievedProject.getBuildDefinitions(), testProject1.getBuildDefinitions() ); assertNotifiersEqual( testProject1.getNotifiers(), retrievedProject.getNotifiers() ); assertDevelopersEqual( testProject1.getDevelopers(), retrievedProject.getDevelopers() ); assertDependenciesEqual( testProject1.getDependencies(), retrievedProject.getDependencies() ); } @Test public void testGetProjectWithCheckoutResult() throws ContinuumStoreException { Project retrievedProject = projectDao.getProjectWithCheckoutResult( testProject1.getId() ); assertProjectEquals( testProject1, retrievedProject ); assertScmResultEquals( testCheckoutResult1, retrievedProject.getCheckoutResult() ); checkProjectFetchGroup( retrievedProject, true, false, false, false ); } @Test public void testGetInvalidProject() throws ContinuumStoreException { try { projectDao.getProject( INVALID_ID ); fail( "Should not find project with invalid ID" ); } catch ( ContinuumObjectNotFoundException expected ) { assertTrue( true ); } } @Test public void testEditProject() throws ContinuumStoreException { Project newProject = projectDao.getProject( testProject2.getId() ); newProject.setName( "testEditProject2" ); newProject.setDescription( "testEditProject updated description" ); newProject.setGroupId( "org.apache.maven.continuum.test.new" ); Project copy = createTestProject( newProject ); copy.setId( newProject.getId() ); projectDao.updateProject( newProject ); Project retrievedProject = projectDao.getProject( testProject2.getId() ); assertProjectEquals( copy, retrievedProject ); } @Test public void testUpdateUndetachedProject() { Project newProject = new Project(); newProject.setId( testProject2.getId() ); newProject.setName( "testUpdateUndetached2" ); newProject.setDescription( "testUpdateUndetached updated description" ); newProject.setGroupId( "org.apache.maven.continuum.test.new" ); try { projectDao.updateProject( newProject ); fail( "Should not have succeeded" ); } catch ( ContinuumStoreException expected ) { // good! assertTrue( true ); } } @Test public void testGetAllProjects() { List<Project> projects = projectDao.getAllProjectsByName(); assertEquals( "check items", asList( testProject1, testProject2 ), projects ); Project project = projects.get( 1 ); assertProjectEquals( testProject2, project ); checkProjectDefaultFetchGroup( project ); assertNotNull( "Check project group reference matches", project.getProjectGroup() ); } @Test public void testAddSchedule() throws ContinuumStoreException { BuildQueue buildQueue = buildQueueDao.getAllBuildQueues().get( 0 ); Schedule newSchedule = createTestSchedule( "testAddSchedule", "testAddSchedule desc", 10, "cron test", false ); newSchedule.addBuildQueue( buildQueue ); Schedule copy = createTestSchedule( newSchedule ); scheduleDao.addSchedule( newSchedule ); copy.setId( newSchedule.getId() ); List<Schedule> schedules = scheduleDao.getAllSchedulesByName(); Schedule retrievedSchedule = schedules.get( schedules.size() - 1 ); assertScheduleEquals( copy, retrievedSchedule ); assertEquals( "check size of build queues", 1, retrievedSchedule.getBuildQueues().size() ); assertBuildQueueEquals( buildQueue, retrievedSchedule.getBuildQueues().get( 0 ) ); } @Test public void testEditSchedule() throws ContinuumStoreException { Schedule newSchedule = scheduleDao.getAllSchedulesByName().get( 0 ); newSchedule.setName( "name1.1" ); newSchedule.setDescription( "testEditSchedule updated description" ); assertEquals( "check size of build queues", 2, newSchedule.getBuildQueues().size() ); BuildQueue buildQueue1 = newSchedule.getBuildQueues().get( 0 ); BuildQueue buildQueue2 = newSchedule.getBuildQueues().get( 1 ); Schedule copy = createTestSchedule( newSchedule ); copy.setId( newSchedule.getId() ); scheduleDao.updateSchedule( newSchedule ); Schedule retrievedSchedule = scheduleDao.getAllSchedulesByName().get( 0 ); assertScheduleEquals( copy, retrievedSchedule ); assertBuildQueueEquals( buildQueue1, retrievedSchedule.getBuildQueues().get( 0 ) ); assertBuildQueueEquals( buildQueue2, retrievedSchedule.getBuildQueues().get( 1 ) ); } @Test public void testRemoveSchedule() { Schedule schedule = scheduleDao.getAllSchedulesByName().get( 2 ); // TODO: test if it has any attachments assertEquals( "check size of build queues", 0, schedule.getBuildQueues().size() ); scheduleDao.removeSchedule( schedule ); List<Schedule> schedules = scheduleDao.getAllSchedulesByName(); assertEquals( "check size", 2, schedules.size() ); assertFalse( "check not there", schedules.contains( schedule ) ); } @Test public void testGetAllSchedules() throws ContinuumStoreException { List<Schedule> schedules = scheduleDao.getAllSchedulesByName(); List<BuildQueue> buildQueues = buildQueueDao.getAllBuildQueues(); assertEquals( "check item count", 3, schedules.size() ); assertEquals( "check build queues count", 3, buildQueues.size() ); BuildQueue buildQueue1 = buildQueues.get( 0 ); BuildQueue buildQueue2 = buildQueues.get( 1 ); BuildQueue buildQueue3 = buildQueues.get( 2 ); // check equality and order Schedule schedule = schedules.get( 0 ); assertScheduleEquals( testSchedule1, schedule ); assertEquals( "check size of buildQueues", 2, schedule.getBuildQueues().size() ); assertBuildQueueEquals( buildQueue1, schedule.getBuildQueues().get( 0 ) ); assertBuildQueueEquals( buildQueue2, schedule.getBuildQueues().get( 1 ) ); schedule = schedules.get( 1 ); assertScheduleEquals( testSchedule2, schedule ); assertEquals( "check size of buildQueues", 2, schedule.getBuildQueues().size() ); assertBuildQueueEquals( buildQueue2, schedule.getBuildQueues().get( 0 ) ); assertBuildQueueEquals( buildQueue3, schedule.getBuildQueues().get( 1 ) ); schedule = schedules.get( 2 ); assertScheduleEquals( testSchedule3, schedule ); assertEquals( "check size of buildQueues", 0, schedule.getBuildQueues().size() ); } @Test public void testAddProfile() throws Exception { List<Installation> installations = installationDao.getAllInstallations(); Profile newProfile = createTestProfile( "testAddProfile", "testAddProfile desc", 5, false, false, installations.get( 1 ), installations.get( 2 ) ); Profile copy = createTestProfile( newProfile ); profileDao.addProfile( newProfile ); copy.setId( newProfile.getId() ); List<Profile> profiles = profileDao.getAllProfilesByName(); Profile retrievedProfile = profiles.get( profiles.size() - 1 ); assertProfileEquals( copy, retrievedProfile ); assertInstallationEquals( testInstallationMaven20a3, retrievedProfile.getBuilder() ); assertInstallationEquals( testInstallationJava14, retrievedProfile.getJdk() ); } @Test public void testEditProfile() throws ContinuumStoreException { Profile newProfile = profileDao.getAllProfilesByName().get( 0 ); newProfile.setName( "name1.1" ); newProfile.setDescription( "testEditProfile updated description" ); Profile copy = createTestProfile( newProfile ); copy.setId( newProfile.getId() ); profileDao.updateProfile( newProfile ); Profile retrievedProfile = profileDao.getAllProfilesByName().get( 0 ); assertProfileEquals( copy, retrievedProfile ); assertInstallationEquals( copy.getBuilder(), retrievedProfile.getBuilder() ); assertInstallationEquals( copy.getJdk(), retrievedProfile.getJdk() ); } @Test public void testRemoveProfile() { Profile profile = profileDao.getAllProfilesByName().get( 2 ); // TODO: test if it has any attachments profileDao.removeProfile( profile ); List<Profile> profiles = profileDao.getAllProfilesByName(); assertEquals( "check size", 3, profiles.size() ); assertFalse( "check not there", profiles.contains( profile ) ); } @Test public void testGetAllProfiles() { List<Profile> profiles = profileDao.getAllProfilesByName(); assertEquals( "check item count", 4, profiles.size() ); // check equality and order Profile profile = profiles.get( 0 ); assertProfileEquals( testProfile1, profile ); assertInstallationEquals( testProfile1.getBuilder(), profile.getBuilder() ); assertInstallationEquals( testProfile1.getJdk(), profile.getJdk() ); profile = profiles.get( 1 ); assertProfileEquals( testProfile2, profile ); assertInstallationEquals( testProfile2.getBuilder(), profile.getBuilder() ); assertInstallationEquals( testProfile2.getJdk(), profile.getJdk() ); profile = profiles.get( 2 ); assertProfileEquals( testProfile3, profile ); assertInstallationEquals( testProfile3.getBuilder(), profile.getBuilder() ); assertInstallationEquals( testProfile3.getJdk(), profile.getJdk() ); profile = profiles.get( 3 ); assertProfileEquals( testProfile4, profile ); assertInstallationEquals( testProfile4.getBuilder(), profile.getBuilder() ); assertInstallationEquals( testProfile4.getJdk(), profile.getJdk() ); assertEquals( "check env var count", 1, profile.getEnvironmentVariables().size() ); assertInstallationEquals( testProfile4.getEnvironmentVariables().get( 0 ), profile.getEnvironmentVariables().get( 0 ) ); } @Test public void testGetAllInstallations() throws Exception { List<Installation> installations = installationDao.getAllInstallations(); assertEquals( "check item count", 4, installations.size() ); // check equality and order Installation installation = installations.get( 0 ); assertInstallationEquals( testInstallationJava13, installation ); installation = installations.get( 1 ); assertInstallationEquals( testInstallationJava14, installation ); installation = installations.get( 2 ); assertInstallationEquals( testInstallationMaven20a3, installation ); installation = installations.get( 3 ); assertInstallationEquals( testInstallationEnvVar, installation ); } @Test public void testUpdateInstallation() throws Exception { String name = "installationTest"; Installation testOne = createTestInstallation( name, InstallationService.JDK_TYPE, "varName", "varValue" ); testOne = installationDao.addInstallation( testOne ); Installation fromStore = installationDao.getInstallation( testOne.getInstallationId() ); assertInstallationEquals( testOne, fromStore ); fromStore.setVarName( "JAVA_HOME" ); fromStore.setVarValue( "/usr/local/jdk1.5.0_08" ); installationDao.updateInstallation( fromStore ); Installation updatedFromStore = installationDao.getInstallation( testOne.getInstallationId() ); assertInstallationEquals( fromStore, updatedFromStore ); } @Test public void testRemoveInstallation() throws Exception { String name = "installationTestRemove"; Installation testOne = createTestInstallation( name, InstallationService.JDK_TYPE, "varName", "varValue" ); testOne = installationDao.addInstallation( testOne ); installationDao.removeInstallation( testOne ); Installation fromStore = installationDao.getInstallation( testOne.getInstallationId() ); assertNull( fromStore ); } @Test public void testRemoveLinkedInstallations() throws Exception { String nameFirstInst = "linkedFirstInstallationTestRemove"; String nameSecondInst = "linkedSecondInstallationTestRemove"; String nameFirstEnvVar = "firstEnvVar"; String nameSecondEnvVar = "secondEnvVar"; Installation testOne = createTestInstallation( nameFirstInst, InstallationService.JDK_TYPE, "varName", "varValue" ); Installation testTwo = createTestInstallation( nameSecondInst, InstallationService.MAVEN2_TYPE, "varName", "varValue" ); Installation firstEnvVar = createTestInstallation( nameFirstEnvVar, InstallationService.MAVEN2_TYPE, "varName", "varValue" ); Installation secondEnvVar = createTestInstallation( nameSecondEnvVar, InstallationService.MAVEN2_TYPE, "varName", "varValue" ); testOne = installationDao.addInstallation( testOne ); testTwo = installationDao.addInstallation( testTwo ); firstEnvVar = installationDao.addInstallation( firstEnvVar ); secondEnvVar = installationDao.addInstallation( secondEnvVar ); List<Installation> envVars = new ArrayList<Installation>( 2 ); envVars.add( firstEnvVar ); envVars.add( secondEnvVar ); Profile firstProfile = createTestProfile( "first", "", 1, true, true, testOne, testTwo, envVars ); Profile secondProfile = createTestProfile( "first", "", 1, true, true, testOne, testTwo, envVars ); firstProfile = profileDao.addProfile( firstProfile ); secondProfile = profileDao.addProfile( secondProfile ); Profile firstGetted = profileDao.getProfile( firstProfile.getId() ); Profile secondGetted = profileDao.getProfile( secondProfile.getId() ); assertNotNull( firstGetted ); assertNotNull( firstGetted.getJdk() ); assertEquals( nameFirstInst, firstGetted.getJdk().getName() ); assertNotNull( secondGetted ); assertNotNull( secondGetted.getJdk() ); assertEquals( nameFirstInst, secondGetted.getJdk().getName() ); assertNotNull( firstGetted.getBuilder() ); assertEquals( nameSecondInst, firstGetted.getBuilder().getName() ); assertEquals( 2, firstGetted.getEnvironmentVariables().size() ); assertNotNull( secondGetted.getBuilder() ); assertEquals( nameSecondInst, secondGetted.getBuilder().getName() ); assertEquals( 2, secondGetted.getEnvironmentVariables().size() ); installationDao.removeInstallation( testOne ); Installation fromStore = installationDao.getInstallation( testOne.getInstallationId() ); assertNull( fromStore ); firstGetted = profileDao.getProfile( firstProfile.getId() ); secondGetted = profileDao.getProfile( secondProfile.getId() ); assertNotNull( firstGetted ); assertNull( firstGetted.getJdk() ); assertNotNull( firstGetted.getBuilder() ); assertEquals( 2, firstGetted.getEnvironmentVariables().size() ); assertNotNull( secondGetted ); assertNull( secondGetted.getJdk() ); assertNotNull( secondGetted.getBuilder() ); assertEquals( 2, secondGetted.getEnvironmentVariables().size() ); // removing builder installationDao.removeInstallation( testTwo ); firstGetted = profileDao.getProfile( firstProfile.getId() ); secondGetted = profileDao.getProfile( secondProfile.getId() ); assertNotNull( firstGetted ); assertNull( firstGetted.getJdk() ); assertNull( firstGetted.getBuilder() ); assertEquals( 2, firstGetted.getEnvironmentVariables().size() ); assertNotNull( secondGetted ); assertNull( secondGetted.getJdk() ); assertNull( secondGetted.getBuilder() ); assertEquals( 2, secondGetted.getEnvironmentVariables().size() ); // removing firstEnvVar installationDao.removeInstallation( firstEnvVar ); firstGetted = profileDao.getProfile( firstProfile.getId() ); secondGetted = profileDao.getProfile( secondProfile.getId() ); assertNotNull( firstGetted ); assertNull( firstGetted.getJdk() ); assertNull( firstGetted.getBuilder() ); assertEquals( 1, firstGetted.getEnvironmentVariables().size() ); Installation env = firstGetted.getEnvironmentVariables().get( 0 ); assertEquals( nameSecondEnvVar, env.getName() ); assertNotNull( secondGetted ); assertNull( secondGetted.getJdk() ); assertNull( secondGetted.getBuilder() ); assertEquals( 1, secondGetted.getEnvironmentVariables().size() ); env = secondGetted.getEnvironmentVariables().get( 0 ); assertEquals( nameSecondEnvVar, env.getName() ); // removing secondEnvVar installationDao.removeInstallation( secondEnvVar ); firstGetted = profileDao.getProfile( firstProfile.getId() ); secondGetted = profileDao.getProfile( secondProfile.getId() ); assertNotNull( firstGetted ); assertNull( firstGetted.getJdk() ); assertNull( firstGetted.getBuilder() ); assertEquals( 0, firstGetted.getEnvironmentVariables().size() ); assertNotNull( secondGetted ); assertNull( secondGetted.getJdk() ); assertNull( secondGetted.getBuilder() ); assertEquals( 0, secondGetted.getEnvironmentVariables().size() ); } @Test public void testDeleteProject() throws ContinuumStoreException { Project project = projectDao.getProjectWithBuilds( testProject1.getId() ); projectDao.removeProject( project ); ProjectGroup projectGroup = projectGroupDao.getProjectGroupWithProjects( defaultProjectGroup.getId() ); assertEquals( "check size is now 1", 1, projectGroup.getProjects().size() ); assertProjectEquals( testProject2, projectGroup.getProjects().get( 0 ) ); confirmProjectDeletion( testProject1 ); } @Test public void testDeleteProjectGroup() throws ContinuumStoreException { projectGroupDao.removeProjectGroup( projectGroupDao.getProjectGroup( defaultProjectGroup.getId() ) ); try { projectGroupDao.getProjectGroup( defaultProjectGroup.getId() ); fail( "Project group was not deleted" ); } catch ( ContinuumObjectNotFoundException expected ) { assertTrue( true ); } confirmProjectDeletion( testProject1 ); confirmProjectDeletion( testProject2 ); // TODO: test the project group's notifiers are physically deleted // TODO: test the project group's build definitions are physically deleted } @Test public void testDeleteBuildResult() throws ContinuumStoreException { Project project = projectDao.getProjectWithBuilds( testProject1.getId() ); for ( Iterator<BuildResult> i = project.getBuildResults().iterator(); i.hasNext(); ) { BuildResult result = i.next(); if ( result.getId() == testBuildResult1.getId() ) { i.remove(); } } projectDao.updateProject( project ); project = projectDao.getProjectWithBuilds( testProject1.getId() ); assertEquals( "check size is now 1", 1, project.getBuildResults().size() ); assertBuildResultEquals( testBuildResult2, project.getBuildResults().get( 0 ) ); List<BuildResult> results = buildResultDao.getAllBuildsForAProjectByDate( testProject1.getId() ); assertEquals( "check item count", 1, results.size() ); assertBuildResultEquals( testBuildResult2, results.get( 0 ) ); // !! These actually aren't happening !! // TODO: test the build result was physically deleted // TODO: test the build result's SCM result was physically deleted // TODO: test the build result's SCM result's change sets and change files were physically deleted } @Test public void testGetInvalidBuildResult() throws ContinuumStoreException { try { buildResultDao.getBuildResult( INVALID_ID ); fail( "Should not find build result with invalid ID" ); } catch ( ContinuumObjectNotFoundException expected ) { assertTrue( true ); } } @Test public void testGetAllBuildsForAProject() { List<BuildResult> results = buildResultDao.getAllBuildsForAProjectByDate( testProject1.getId() ); assertEquals( "check item count", 2, results.size() ); // check equality and order BuildResult buildResult = results.get( 0 ); assertBuildResultEquals( testBuildResult2, buildResult ); assertProjectEquals( testProject1, buildResult.getProject() ); //checkBuildResultDefaultFetchGroup( buildResult ); buildResult = results.get( 1 ); assertBuildResultEquals( testBuildResult1, buildResult ); assertProjectEquals( testProject1, buildResult.getProject() ); //checkBuildResultDefaultFetchGroup( buildResult ); } @Test public void testGetBuildResult() throws ContinuumStoreException { BuildResult buildResult = buildResultDao.getBuildResult( testBuildResult3.getId() ); assertBuildResultEquals( testBuildResult3, buildResult ); //assertScmResultEquals( testBuildResult3.getScmResult(), buildResult.getScmResult() ); assertProjectEquals( testProject2, buildResult.getProject() ); // TODO: reports, artifacts, data } @Test public void testGetProjectGroupWithDetails() throws ContinuumStoreException { ProjectGroup retrievedGroup = projectGroupDao.getProjectGroupWithBuildDetailsByProjectGroupId( defaultProjectGroup.getId() ); assertProjectGroupEquals( defaultProjectGroup, retrievedGroup ); assertNotifiersEqual( defaultProjectGroup.getNotifiers(), retrievedGroup.getNotifiers() ); assertBuildDefinitionsEqual( retrievedGroup.getBuildDefinitions(), defaultProjectGroup.getBuildDefinitions() ); List<Project> projects = retrievedGroup.getProjects(); assertEquals( "Check number of projects", 2, projects.size() ); Project project = projects.get( 0 ); checkProjectFetchGroup( project, false, false, true, false ); //assertSame( "Check project group reference matches", project.getProjectGroup(), retrievedGroup ); assertEquals( project.getProjectGroup().getId(), retrievedGroup.getId() ); assertProjectEquals( testProject1, project ); assertNotifiersEqual( testProject1.getNotifiers(), project.getNotifiers() ); assertBuildDefinitionsEqual( project.getBuildDefinitions(), testProject1.getBuildDefinitions() ); project = projects.get( 1 ); checkProjectFetchGroup( project, false, false, true, false ); //assertSame( "Check project group reference matches", project.getProjectGroup(), retrievedGroup ); assertEquals( project.getProjectGroup().getId(), retrievedGroup.getId() ); assertProjectEquals( testProject2, project ); assertNotifiersEqual( testProject2.getNotifiers(), project.getNotifiers() ); assertBuildDefinitionsEqual( project.getBuildDefinitions(), testProject2.getBuildDefinitions() ); } @Test public void testGetAllProjectsGroupWithDetails() { List<ProjectGroup> projectGroups = projectGroupDao.getAllProjectGroupsWithBuildDetails(); ProjectGroup group1 = projectGroups.get( 0 ); assertProjectGroupEquals( defaultProjectGroup, group1 ); assertNotifiersEqual( defaultProjectGroup.getNotifiers(), group1.getNotifiers() ); assertBuildDefinitionsEqual( group1.getBuildDefinitions(), defaultProjectGroup.getBuildDefinitions() ); ProjectGroup group2 = projectGroups.get( 1 ); assertProjectGroupEquals( testProjectGroup2, group2 ); assertNotifiersEqual( testProjectGroup2.getNotifiers(), group2.getNotifiers() ); assertBuildDefinitionsEqual( group2.getBuildDefinitions(), testProjectGroup2.getBuildDefinitions() ); List<Project> projects = group1.getProjects(); assertEquals( "Check number of projects", 2, projects.size() ); Project project = projects.get( 0 ); checkProjectFetchGroup( project, false, false, true, false ); assertSame( "Check project group reference matches", project.getProjectGroup(), group1 ); assertProjectEquals( testProject1, project ); assertNotifiersEqual( testProject1.getNotifiers(), project.getNotifiers() ); assertBuildDefinitionsEqual( project.getBuildDefinitions(), testProject1.getBuildDefinitions() ); project = projects.get( 1 ); checkProjectFetchGroup( project, false, false, true, false ); assertSame( "Check project group reference matches", project.getProjectGroup(), group1 ); assertProjectEquals( testProject2, project ); assertNotifiersEqual( testProject2.getNotifiers(), project.getNotifiers() ); assertBuildDefinitionsEqual( project.getBuildDefinitions(), testProject2.getBuildDefinitions() ); projects = group2.getProjects(); assertEquals( "Check number of projects", 0, projects.size() ); } @Test public void testAddDeveloperToProject() throws ContinuumStoreException { Project project = projectDao.getProjectWithAllDetails( testProject1.getId() ); ProjectDeveloper developer = createTestDeveloper( 11, "email TADTP", "name TADTP", "scmId TADTP" ); ProjectDeveloper copy = createTestDeveloper( developer ); project.addDeveloper( developer ); projectDao.updateProject( project ); project = projectDao.getProjectWithAllDetails( testProject1.getId() ); assertEquals( "check # devs", 2, project.getDevelopers().size() ); assertDeveloperEquals( copy, project.getDevelopers().get( 1 ) ); } @Test public void testEditDeveloper() throws ContinuumStoreException { Project project = projectDao.getProjectWithAllDetails( testProject1.getId() ); ProjectDeveloper newDeveloper = project.getDevelopers().get( 0 ); newDeveloper.setName( "name1.1" ); newDeveloper.setEmail( "email1.1" ); ProjectDeveloper copy = createTestDeveloper( newDeveloper ); projectDao.updateProject( project ); project = projectDao.getProjectWithAllDetails( testProject1.getId() ); assertEquals( "check # devs", 1, project.getDevelopers().size() ); assertDeveloperEquals( copy, project.getDevelopers().get( 0 ) ); } @Test public void testDeleteDeveloper() throws ContinuumStoreException { Project project = projectDao.getProjectWithAllDetails( testProject1.getId() ); project.getDevelopers().remove( 0 ); projectDao.updateProject( project ); project = projectDao.getProjectWithAllDetails( testProject1.getId() ); assertEquals( "check size is now 0", 0, project.getDevelopers().size() ); // !! These actually aren't happening !! // TODO: test the developer was physically deleted } @Test public void testAddDependencyToProject() throws ContinuumStoreException { Project project = projectDao.getProjectWithAllDetails( testProject1.getId() ); ProjectDependency dependency = createTestDependency( "TADTP groupId", "TADTP artifactId", "TADTP version" ); ProjectDependency copy = createTestDependency( dependency ); project.addDependency( dependency ); projectDao.updateProject( project ); project = projectDao.getProjectWithAllDetails( testProject1.getId() ); assertEquals( "check # deps", 3, project.getDependencies().size() ); assertDependencyEquals( copy, project.getDependencies().get( 2 ) ); } @Test public void testEditDependency() throws ContinuumStoreException { Project project = projectDao.getProjectWithAllDetails( testProject1.getId() ); ProjectDependency newDependency = project.getDependencies().get( 0 ); newDependency.setGroupId( "groupId1.1" ); newDependency.setArtifactId( "artifactId1.1" ); ProjectDependency copy = createTestDependency( newDependency ); projectDao.updateProject( project ); project = projectDao.getProjectWithAllDetails( testProject1.getId() ); assertEquals( "check # deps", 2, project.getDependencies().size() ); assertDependencyEquals( copy, project.getDependencies().get( 0 ) ); } @Test public void testDeleteDependency() throws ContinuumStoreException { Project project = projectDao.getProjectWithAllDetails( testProject1.getId() ); ProjectDependency dependency = project.getDependencies().get( 1 ); project.getDependencies().remove( 0 ); projectDao.updateProject( project ); project = projectDao.getProjectWithAllDetails( testProject1.getId() ); assertEquals( "check size is now 1", 1, project.getDependencies().size() ); assertDependencyEquals( dependency, project.getDependencies().get( 0 ) ); // !! These actually aren't happening !! // TODO: test the dependency was physically deleted } @Test public void testAddNotifierToProject() throws ContinuumStoreException { Project project = projectDao.getProjectWithAllDetails( testProject1.getId() ); ProjectNotifier notifier = createTestNotifier( 13, true, false, true, "TADNTP type" ); ProjectNotifier copy = createTestNotifier( notifier ); project.addNotifier( notifier ); projectDao.updateProject( project ); project = projectDao.getProjectWithAllDetails( testProject1.getId() ); assertEquals( "check # notifiers", 2, project.getNotifiers().size() ); assertNotifierEquals( copy, project.getNotifiers().get( 1 ) ); } @Test public void testEditNotifier() throws ContinuumStoreException { Project project = projectDao.getProjectWithAllDetails( testProject1.getId() ); ProjectNotifier newNotifier = project.getNotifiers().get( 0 ); // If we use "type1.1", jpox-rc2 store "type11", weird String type = "type11"; newNotifier.setType( type ); ProjectNotifier copy = createTestNotifier( newNotifier ); projectDao.updateProject( project ); project = projectDao.getProjectWithAllDetails( testProject1.getId() ); assertEquals( "check # notifiers", 1, project.getNotifiers().size() ); assertNotifierEquals( copy, project.getNotifiers().get( 0 ) ); } @Test public void testDeleteNotifier() throws ContinuumStoreException { Project project = projectDao.getProjectWithAllDetails( testProject1.getId() ); project.getNotifiers().remove( 0 ); projectDao.updateProject( project ); project = projectDao.getProjectWithAllDetails( testProject1.getId() ); assertEquals( "check size is now 0", 0, project.getNotifiers().size() ); // !! These actually aren't happening !! // TODO: test the notifier was physically deleted } @Test public void testAddBuildDefinitionToProject() throws ContinuumStoreException { Project project = projectDao.getProjectWithAllDetails( testProject1.getId() ); Profile profile = profileDao.getProfile( testProfile1.getId() ); Schedule schedule = scheduleDao.getSchedule( testSchedule1.getId() ); BuildDefinition buildDefinition = createTestBuildDefinition( "TABDTP arguments", "TABDTP buildFile", "TABDTP goals", profile, schedule, false, false ); BuildDefinition copy = createTestBuildDefinition( buildDefinition ); project.addBuildDefinition( buildDefinition ); projectDao.updateProject( project ); project = projectDao.getProjectWithAllDetails( testProject1.getId() ); assertEquals( "check # build defs", 3, project.getBuildDefinitions().size() ); BuildDefinition retrievedBuildDefinition = project.getBuildDefinitions().get( 2 ); assertBuildDefinitionEquals( copy, retrievedBuildDefinition ); assertScheduleEquals( testSchedule1, retrievedBuildDefinition.getSchedule() ); assertProfileEquals( testProfile1, retrievedBuildDefinition.getProfile() ); } @Test public void testEditBuildDefinition() throws ContinuumStoreException { Project project = projectDao.getProjectWithAllDetails( testProject1.getId() ); BuildDefinition newBuildDefinition = project.getBuildDefinitions().get( 0 ); newBuildDefinition.setBuildFresh( true ); new BuildDefinition().setDefaultForProject( true ); String arguments = "arguments1.1"; newBuildDefinition.setArguments( arguments ); BuildDefinition copy = createTestBuildDefinition( newBuildDefinition ); buildDefinitionDao.storeBuildDefinition( newBuildDefinition ); project = projectDao.getProjectWithAllDetails( testProject1.getId() ); assertEquals( "check # build defs", 2, project.getBuildDefinitions().size() ); BuildDefinition retrievedBuildDefinition = project.getBuildDefinitions().get( 0 ); assertBuildDefinitionEquals( copy, retrievedBuildDefinition ); assertScheduleEquals( testSchedule1, retrievedBuildDefinition.getSchedule() ); assertProfileEquals( testProfile2, retrievedBuildDefinition.getProfile() ); } @Test public void testDeleteBuildDefinition() throws ContinuumStoreException { Project project = projectDao.getProjectWithAllDetails( testProject1.getId() ); BuildDefinition buildDefinition = project.getBuildDefinitions().get( 1 ); project.getBuildDefinitions().remove( 0 ); projectDao.updateProject( project ); project = projectDao.getProjectWithAllDetails( testProject1.getId() ); assertEquals( "check size is now 1", 1, project.getBuildDefinitions().size() ); BuildDefinition retrievedBuildDefinition = project.getBuildDefinitions().get( 0 ); assertBuildDefinitionEquals( buildDefinition, retrievedBuildDefinition ); assertScheduleEquals( testSchedule2, retrievedBuildDefinition.getSchedule() ); assertProfileEquals( testProfile2, retrievedBuildDefinition.getProfile() ); // !! These actually aren't happening !! // TODO: test the def was physically deleted // TODO: test the schedule/profile was NOT physically deleted } @Test public void testAddNotifierToProjectGroup() throws ContinuumStoreException { ProjectGroup projectGroup = projectGroupDao.getProjectGroupWithBuildDetailsByProjectGroupId( defaultProjectGroup.getId() ); ProjectNotifier notifier = createTestNotifier( 14, true, false, true, "TADNTPG type" ); ProjectNotifier copy = createTestNotifier( notifier ); projectGroup.addNotifier( notifier ); projectGroupDao.updateProjectGroup( projectGroup ); projectGroup = projectGroupDao.getProjectGroupWithBuildDetailsByProjectGroupId( defaultProjectGroup.getId() ); assertEquals( "check # notifiers", 3, projectGroup.getNotifiers().size() ); assertNotifierEquals( copy, projectGroup.getNotifiers().get( 2 ) ); } @Test public void testEditGroupNotifier() throws ContinuumStoreException { ProjectGroup projectGroup = projectGroupDao.getProjectGroupWithBuildDetailsByProjectGroupId( defaultProjectGroup.getId() ); ProjectNotifier newNotifier = projectGroup.getNotifiers().get( 0 ); // If we use "type1.1", jpox-rc2 store "type1", weird String type = "type1"; newNotifier.setType( type ); ProjectNotifier copy = createTestNotifier( newNotifier ); projectGroupDao.updateProjectGroup( projectGroup ); projectGroup = projectGroupDao.getProjectGroupWithBuildDetailsByProjectGroupId( defaultProjectGroup.getId() ); assertEquals( "check # notifiers", 2, projectGroup.getNotifiers().size() ); assertNotifierEquals( copy, projectGroup.getNotifiers().get( 0 ) ); } @Test public void testDeleteGroupNotifier() throws ContinuumStoreException { ProjectGroup projectGroup = projectGroupDao.getProjectGroupWithBuildDetailsByProjectGroupId( defaultProjectGroup.getId() ); ProjectNotifier notifier = projectGroup.getNotifiers().get( 1 ); projectGroup.getNotifiers().remove( 0 ); projectGroupDao.updateProjectGroup( projectGroup ); projectGroup = projectGroupDao.getProjectGroupWithBuildDetailsByProjectGroupId( defaultProjectGroup.getId() ); assertEquals( "check size is now 1", 1, projectGroup.getNotifiers().size() ); assertNotifierEquals( notifier, projectGroup.getNotifiers().get( 0 ) ); // !! These actually aren't happening !! // TODO: test the notifier was physically deleted } @Test public void testAddBuildDefinitionToProjectGroup() throws ContinuumStoreException { ProjectGroup projectGroup = projectGroupDao.getProjectGroupWithBuildDetailsByProjectGroupId( defaultProjectGroup.getId() ); Profile profile = profileDao.getProfile( testProfile1.getId() ); Schedule schedule = scheduleDao.getSchedule( testSchedule1.getId() ); BuildDefinition buildDefinition = createTestBuildDefinition( "TABDTPG arguments", "TABDTPG buildFile", "TABDTPG goals", profile, schedule, false, false ); BuildDefinition copy = createTestBuildDefinition( buildDefinition ); projectGroup.addBuildDefinition( buildDefinition ); projectGroupDao.updateProjectGroup( projectGroup ); projectGroup = projectGroupDao.getProjectGroupWithBuildDetailsByProjectGroupId( defaultProjectGroup.getId() ); assertEquals( "check # build defs", 2, projectGroup.getBuildDefinitions().size() ); BuildDefinition retrievedBuildDefinition = projectGroup.getBuildDefinitions().get( 1 ); assertBuildDefinitionEquals( copy, retrievedBuildDefinition ); assertScheduleEquals( testSchedule1, retrievedBuildDefinition.getSchedule() ); assertProfileEquals( testProfile1, retrievedBuildDefinition.getProfile() ); } @Test public void testEditGroupBuildDefinition() throws ContinuumStoreException { ProjectGroup projectGroup = projectGroupDao.getProjectGroupWithBuildDetailsByProjectGroupId( defaultProjectGroup.getId() ); BuildDefinition newBuildDefinition = projectGroup.getBuildDefinitions().get( 0 ); // If we use "arguments1.1", jpox-rc2 store "arguments11", weird String arguments = "arguments1"; newBuildDefinition.setArguments( arguments ); BuildDefinition copy = createTestBuildDefinition( newBuildDefinition ); projectGroupDao.updateProjectGroup( projectGroup ); projectGroup = projectGroupDao.getProjectGroupWithBuildDetailsByProjectGroupId( defaultProjectGroup.getId() ); assertEquals( "check # build defs", 1, projectGroup.getBuildDefinitions().size() ); BuildDefinition retrievedBuildDefinition = projectGroup.getBuildDefinitions().get( 0 ); assertBuildDefinitionEquals( copy, retrievedBuildDefinition ); assertScheduleEquals( testSchedule2, retrievedBuildDefinition.getSchedule() ); assertProfileEquals( testProfile1, retrievedBuildDefinition.getProfile() ); } @Test public void testDeleteGroupBuildDefinition() throws ContinuumStoreException { ProjectGroup projectGroup = projectGroupDao.getProjectGroupWithBuildDetailsByProjectGroupId( defaultProjectGroup.getId() ); projectGroup.getBuildDefinitions().remove( 0 ); projectGroupDao.updateProjectGroup( projectGroup ); projectGroup = projectGroupDao.getProjectGroupWithBuildDetailsByProjectGroupId( defaultProjectGroup.getId() ); assertEquals( "check size is now 0", 0, projectGroup.getBuildDefinitions().size() ); // !! These actually aren't happening !! // TODO: test the def was physically deleted // TODO: test the schedule/profile was NOT physically deleted } @Test public void testGetTemplatesBuildDefinitions() throws Exception { int all = buildDefinitionDao.getAllBuildDefinitions().size(); BuildDefinition buildDefinition = new BuildDefinition(); buildDefinition.setBuildFile( "pom.xml" ); buildDefinition.setGoals( "clean" ); buildDefinition.setTemplate( true ); BuildDefinitionTemplate template = new BuildDefinitionTemplate(); template.setName( "test" ); template.setContinuumDefault( true ); template.setType( ContinuumBuildExecutorConstants.MAVEN_TWO_BUILD_EXECUTOR ); template = buildDefinitionTemplateDao.addBuildDefinitionTemplate( template ); buildDefinition = buildDefinitionDao.addBuildDefinition( buildDefinition ); template.addBuildDefinition( buildDefinition ); template = buildDefinitionTemplateDao.updateBuildDefinitionTemplate( template ); assertEquals( "test", template.getName() ); assertTrue( template.isContinuumDefault() ); assertEquals( 1, template.getBuildDefinitions().size() ); assertEquals( all + 1, buildDefinitionDao.getAllBuildDefinitions().size() ); assertEquals( 2, buildDefinitionTemplateDao.getAllBuildDefinitionTemplate().size() ); template = buildDefinitionTemplateDao.getContinuumBuildDefinitionTemplateWithType( ContinuumBuildExecutorConstants.MAVEN_TWO_BUILD_EXECUTOR ); assertNotNull( template ); assertEquals( 1, template.getBuildDefinitions().size() ); assertEquals( 2, buildDefinitionTemplateDao.getAllBuildDefinitionTemplate().size() ); } @Test public void testAddLocalRepository() throws Exception { String name = "testAddLocalRepository"; String directory = "testAddLocalRepositoryDirectory"; String layout = "default"; LocalRepository repository = createTestLocalRepository( name, directory, layout ); LocalRepository copy = createTestLocalRepository( repository ); localRepositoryDao.addLocalRepository( repository ); copy.setId( repository.getId() ); LocalRepository retrievedRepository = localRepositoryDao.getLocalRepository( repository.getId() ); assertLocalRepositoryEquals( copy, retrievedRepository ); } @Test public void testRemoveLocalRepository() throws Exception { LocalRepository repository = localRepositoryDao.getLocalRepositoryByName( testLocalRepository2.getName() ); ProjectGroup projectGroup = projectGroupDao.getProjectGroupByGroupId( testProjectGroup2.getGroupId() ); assertLocalRepositoryEquals( testLocalRepository2, projectGroup.getLocalRepository() ); projectGroup.setLocalRepository( null ); projectGroupDao.updateProjectGroup( projectGroup ); projectGroup = projectGroupDao.getProjectGroup( testProjectGroup2.getId() ); assertNull( "check local repository", projectGroup.getLocalRepository() ); List<RepositoryPurgeConfiguration> repoPurgeList = repositoryPurgeConfigurationDao.getRepositoryPurgeConfigurationsByLocalRepository( repository.getId() ); assertEquals( "check # repo purge config", 1, repoPurgeList.size() ); repositoryPurgeConfigurationDao.removeRepositoryPurgeConfiguration( repoPurgeList.get( 0 ) ); localRepositoryDao.removeLocalRepository( repository ); List<LocalRepository> localRepositories = localRepositoryDao.getAllLocalRepositories(); assertEquals( "check # local repositories", 2, localRepositories.size() ); assertFalse( "check not there", localRepositories.contains( repository ) ); } @Test public void testGetAllLocalRepositories() throws Exception { List<LocalRepository> localRepositories = localRepositoryDao.getAllLocalRepositories(); assertEquals( "check # local repositories", 3, localRepositories.size() ); assertLocalRepositoryEquals( testLocalRepository1, localRepositories.get( 0 ) ); assertLocalRepositoryEquals( testLocalRepository2, localRepositories.get( 1 ) ); assertLocalRepositoryEquals( testLocalRepository3, localRepositories.get( 2 ) ); } @Test public void testAddRepositoryPurgeConfiguration() throws Exception { LocalRepository repository = localRepositoryDao.getLocalRepository( testLocalRepository3.getId() ); Schedule schedule = scheduleDao.getSchedule( testSchedule1.getId() ); RepositoryPurgeConfiguration repoPurge = createTestRepositoryPurgeConfiguration( true, 2, 100, false, schedule, true, repository ); RepositoryPurgeConfiguration copy = createTestRepositoryPurgeConfiguration( repoPurge ); repositoryPurgeConfigurationDao.addRepositoryPurgeConfiguration( repoPurge ); copy.setId( repoPurge.getId() ); RepositoryPurgeConfiguration retrieved = repositoryPurgeConfigurationDao.getRepositoryPurgeConfiguration( repoPurge.getId() ); assertRepositoryPurgeConfigurationEquals( copy, retrieved ); assertLocalRepositoryEquals( testLocalRepository3, retrieved.getRepository() ); assertScheduleEquals( testSchedule1, retrieved.getSchedule() ); } @Test public void testRemoveRepositoryPurgeConfiguration() throws Exception { RepositoryPurgeConfiguration repoPurge = repositoryPurgeConfigurationDao.getRepositoryPurgeConfiguration( testRepoPurgeConfiguration2.getId() ); repositoryPurgeConfigurationDao.removeRepositoryPurgeConfiguration( repoPurge ); List<RepositoryPurgeConfiguration> repoPurgeList = repositoryPurgeConfigurationDao.getAllRepositoryPurgeConfigurations(); assertEquals( "check # repo purge configurations", 2, repoPurgeList.size() ); assertFalse( "check not there", repoPurgeList.contains( repoPurge ) ); } @Test public void testAddDirectoryPurgeConfiguration() throws Exception { String location = "release-directory"; String directoryType = "release"; Schedule schedule = scheduleDao.getSchedule( testSchedule1.getId() ); DirectoryPurgeConfiguration dirPurge = createTestDirectoryPurgeConfiguration( location, directoryType, false, 2, 100, schedule, true ); DirectoryPurgeConfiguration copy = createTestDirectoryPurgeConfiguration( dirPurge ); directoryPurgeConfigurationDao.addDirectoryPurgeConfiguration( dirPurge ); copy.setId( dirPurge.getId() ); DirectoryPurgeConfiguration retrieved = directoryPurgeConfigurationDao.getDirectoryPurgeConfiguration( dirPurge.getId() ); assertDirectoryPurgeConfigurationEquals( copy, retrieved ); assertScheduleEquals( testSchedule1, retrieved.getSchedule() ); } @Test public void testRemoveDirectoryPurgeConfiguration() throws Exception { DirectoryPurgeConfiguration dirPurge = directoryPurgeConfigurationDao.getDirectoryPurgeConfiguration( testDirectoryPurgeConfig.getId() ); directoryPurgeConfigurationDao.removeDirectoryPurgeConfiguration( dirPurge ); List<DirectoryPurgeConfiguration> dirPurgeList = directoryPurgeConfigurationDao.getAllDirectoryPurgeConfigurations(); assertEquals( "check # dir purge configurations", 0, dirPurgeList.size() ); } @Test public void testGetPurgeConfigurationsBySchedule() throws Exception { List<RepositoryPurgeConfiguration> repoPurgeList = repositoryPurgeConfigurationDao.getRepositoryPurgeConfigurationsBySchedule( testSchedule2.getId() ); List<DirectoryPurgeConfiguration> dirPurgeList = directoryPurgeConfigurationDao.getDirectoryPurgeConfigurationsBySchedule( testSchedule2.getId() ); assertEquals( "check # repo purge configurations", 2, repoPurgeList.size() ); assertEquals( "check # dir purge configurations", 1, dirPurgeList.size() ); assertRepositoryPurgeConfigurationEquals( testRepoPurgeConfiguration1, repoPurgeList.get( 0 ) ); assertRepositoryPurgeConfigurationEquals( testRepoPurgeConfiguration3, repoPurgeList.get( 1 ) ); assertDirectoryPurgeConfigurationEquals( testDirectoryPurgeConfig, dirPurgeList.get( 0 ) ); } @Test public void testAddProjectScmRoot() throws Exception { ProjectGroup projectGroup = projectGroupDao.getProjectGroup( testProjectGroup2.getId() ); ProjectScmRoot projectScmRoot = createTestProjectScmRoot( "scmRootAddress", 1, 0, "", projectGroup ); projectScmRoot = projectScmRootDao.addProjectScmRoot( projectScmRoot ); List<ProjectScmRoot> projectScmRoots = projectScmRootDao.getProjectScmRootByProjectGroup( projectGroup.getId() ); assertEquals( "check # of project scm root", 2, projectScmRoots.size() ); ProjectScmRoot retrievedProjectScmRoot = projectScmRootDao.getProjectScmRootByProjectGroupAndScmRootAddress( projectGroup.getId(), "scmRootAddress" ); assertProjectScmRootEquals( projectScmRoot, retrievedProjectScmRoot ); assertProjectGroupEquals( projectScmRoot.getProjectGroup(), retrievedProjectScmRoot.getProjectGroup() ); } @Test public void testRemoveProjectScmRoot() throws Exception { ProjectGroup projectGroup = projectGroupDao.getProjectGroup( testProjectGroup2.getId() ); List<ProjectScmRoot> projectScmRoots = projectScmRootDao.getProjectScmRootByProjectGroup( projectGroup.getId() ); assertEquals( "check # of project scm root", 1, projectScmRoots.size() ); ProjectScmRoot projectScmRoot = projectScmRoots.get( 0 ); projectScmRootDao.removeProjectScmRoot( projectScmRoot ); projectScmRoots = projectScmRootDao.getProjectScmRootByProjectGroup( projectGroup.getId() ); assertEquals( "check # of project scm root", 0, projectScmRoots.size() ); } @Test public void testRemoveProjectWithReleaseResult() throws Exception { Project project = projectDao.getProject( testProject1.getId() ); ProjectGroup group = project.getProjectGroup(); ContinuumReleaseResult releaseResult = createTestContinuumReleaseResult( group, project, "releaseGoal", 0, 0, 0 ); releaseResult = releaseResultDao.addContinuumReleaseResult( releaseResult ); List<ContinuumReleaseResult> releaseResults = releaseResultDao.getAllContinuumReleaseResults(); assertEquals( "check size of continuum release results", 2, releaseResults.size() ); ContinuumReleaseResult retrievedResult = releaseResults.get( 1 ); assertReleaseResultEquals( releaseResult, retrievedResult ); assertProjectGroupEquals( group, retrievedResult.getProjectGroup() ); assertProjectEquals( project, retrievedResult.getProject() ); releaseResultDao.removeContinuumReleaseResult( releaseResult ); projectDao.removeProject( project ); assertFalse( projectDao.getProjectsInGroup( group.getId() ).contains( project ) ); releaseResults = releaseResultDao.getAllContinuumReleaseResults(); assertEquals( "check size of continuum release results", 1, releaseResults.size() ); } @Test public void testGetProjectSummaryByProjectGroup() throws Exception { List<Project> projects = projectDao.getProjectsInGroup( defaultProjectGroup.getId() ); assertEquals( 2, projects.size() ); Project project = projects.get( 0 ); project.setState( 2 ); projectDao.updateProject( project ); project = projects.get( 1 ); project.setState( 2 ); projectDao.updateProject( project ); ProjectGroup newGroup = projectGroupDao.getProjectGroupWithProjects( testProjectGroup2.getId() ); Project project1 = createTestProject( testProject1 ); project1.setState( 4 ); newGroup.addProject( project1 ); Project project2 = createTestProject( testProject2 ); project2.setState( 1 ); newGroup.addProject( project2 ); projectGroupDao.updateProjectGroup( newGroup ); Map<Integer, ProjectGroupSummary> summaries = projectDao.getProjectsSummary(); assertNotNull( summaries ); assertEquals( "check size of project summaries", 2, summaries.size() ); ProjectGroupSummary summary = summaries.get( testProjectGroup2.getId() ); assertEquals( "check id of project group", testProjectGroup2.getId(), summary.getProjectGroupId() ); assertEquals( "check number of errors", 1, summary.getNumberOfErrors() ); assertEquals( "check number of successes", 0, summary.getNumberOfSuccesses() ); assertEquals( "check number of failures", 0, summary.getNumberOfFailures() ); assertEquals( "check number of projects", 2, summary.getNumberOfProjects() ); summary = summaries.get( defaultProjectGroup.getId() ); assertEquals( "check id of project group", defaultProjectGroup.getId(), summary.getProjectGroupId() ); assertEquals( "check number of errors", 0, summary.getNumberOfErrors() ); assertEquals( "check number of successes", 2, summary.getNumberOfSuccesses() ); assertEquals( "check number of failures", 0, summary.getNumberOfFailures() ); assertEquals( "check number of projects", 2, summary.getNumberOfProjects() ); } @Test public void testGetBuildResultsInRange() throws Exception { int maxFetch = 5; List<BuildResult> results = buildResultDao.getBuildResultsInRange( null, null, 0, null, null, 0, maxFetch ); assertEquals( "check number of build results returned", 3, results.size() ); results = buildResultDao.getBuildResultsInRange( null, null, 2, null, null, 0, maxFetch ); assertEquals( "check number of build results returned with state == OK", 2, results.size() ); results = buildResultDao.getBuildResultsInRange( null, null, 0, "user", null, 0, maxFetch ); assertEquals( "check number of build results returned with triggeredBy == user", 1, results.size() ); results = buildResultDao.getBuildResultsInRange( null, null, 0, "schedule", null, 0, maxFetch ); assertEquals( "check number of build results returned with triggeredBy == schedule", 2, results.size() ); results = buildResultDao.getBuildResultsInRange( null, null, 2, "schedule", null, 0, maxFetch ); assertEquals( "check number of build results returned with state == Ok and triggeredBy == schedule", 1, results.size() ); results = buildResultDao.getBuildResultsInRange( null, null, 3, "user", null, 0, maxFetch ); assertEquals( "check number of build results returned with state == Failed and triggeredBy == user", 0, results.size() ); Calendar cal = Calendar.getInstance(); cal.setTime( new Date( baseTime ) ); cal.add( Calendar.DAY_OF_MONTH, 1 ); results = buildResultDao.getBuildResultsInRange( new Date( baseTime ), cal.getTime(), 0, null, null, 0, maxFetch ); assertEquals( "check number of build results returned with startDate and endDate", 2, results.size() ); results = buildResultDao.getBuildResultsInRange( new Date( baseTime ), new Date( baseTime ), 0, null, null, 0, maxFetch ); assertEquals( "check number of build results returned with the same startDate and endDate", 1, results.size() ); results = buildResultDao.getBuildResultsInRange( null, null, 0, null, asList(1), 0, maxFetch ); assertEquals( "check number of build results returned with an existing group id", 3, results.size() ); results = buildResultDao.getBuildResultsInRange( null, null, 0, null, asList(2), 0, maxFetch ); assertEquals( "check number of build results returned with non-existing group id", 0, results.size() ); } // ---------------------------------------------------------------------- // HELPER METHODS // ---------------------------------------------------------------------- private void confirmProjectDeletion( Project project ) throws ContinuumStoreException { try { projectDao.getProject( project.getId() ); fail( "Project should no longer exist" ); } catch ( ContinuumObjectNotFoundException expected ) { assertTrue( true ); } // !! These actually aren't happening !! // TODO: test the project's checkout SCM result was physically deleted // TODO: test the project's checkout SCM result's change sets and change files were physically deleted // TODO: test the project's dependencies are physically deleted // TODO: test the project's developers are physically deleted // TODO: test the project's builds are physically deleted // TODO: test the project's notifiers are physically deleted // TODO: test the project's build definitions are physically deleted } private static void checkProjectGroupDefaultFetchGroup( ProjectGroup retrievedGroup ) { try { retrievedGroup.getBuildDefinitions(); fail( "buildDefinitions should not be in the default fetch group" ); } catch ( JDODetachedFieldAccessException expected ) { assertTrue( true ); } try { retrievedGroup.getNotifiers(); fail( "notifiers should not be in the default fetch group" ); } catch ( JDODetachedFieldAccessException expected ) { assertTrue( true ); } } private static void checkProjectDefaultFetchGroup( Project project ) { checkProjectFetchGroup( project, false, false, false, false ); } @Before public void setUp() throws Exception { buildDefinitionDao = lookup( BuildDefinitionDao.class ); buildDefinitionTemplateDao = lookup( BuildDefinitionTemplateDao.class ); buildResultDao = lookup( BuildResultDao.class ); createBuildDatabase( false ); } private static void checkProjectFetchGroup( Project project, boolean checkoutFetchGroup, boolean buildResultsFetchGroup, boolean detailsFetchGroup, boolean fineDetailsFetchGroup ) { if ( !fineDetailsFetchGroup ) { try { project.getDevelopers(); fail( "developers should not be in the default fetch group" ); } catch ( JDODetachedFieldAccessException expected ) { assertTrue( true ); } try { project.getDependencies(); fail( "dependencies should not be in the default fetch group" ); } catch ( JDODetachedFieldAccessException expected ) { assertTrue( true ); } } if ( !detailsFetchGroup ) { try { project.getNotifiers(); fail( "notifiers should not be in the default fetch group" ); } catch ( JDODetachedFieldAccessException expected ) { assertTrue( true ); } try { project.getBuildDefinitions(); fail( "buildDefinitions should not be in the default fetch group" ); } catch ( JDODetachedFieldAccessException expected ) { assertTrue( true ); } } if ( !checkoutFetchGroup ) { try { project.getCheckoutResult(); fail( "checkoutResult should not be in the fetch group" ); } catch ( JDODetachedFieldAccessException expected ) { assertTrue( true ); } } if ( !buildResultsFetchGroup ) { try { project.getBuildResults(); fail( "buildResults should not be in the default fetch group" ); } catch ( JDODetachedFieldAccessException expected ) { assertTrue( true ); } } } }
5,191
0
Create_ds/continuum/continuum-store/src/test/java/org/apache/maven/continuum
Create_ds/continuum/continuum-store/src/test/java/org/apache/maven/continuum/store/AbstractContinuumStoreTestCase.java
package org.apache.maven.continuum.store; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.dao.*; import org.apache.continuum.model.project.ProjectScmRoot; import org.apache.continuum.model.release.ContinuumReleaseResult; import org.apache.continuum.model.repository.DirectoryPurgeConfiguration; import org.apache.continuum.model.repository.LocalRepository; import org.apache.continuum.model.repository.RepositoryPurgeConfiguration; import org.apache.maven.continuum.PlexusSpringTestCase; import org.apache.maven.continuum.installation.InstallationService; import org.apache.maven.continuum.model.project.*; import org.apache.maven.continuum.model.scm.ChangeFile; import org.apache.maven.continuum.model.scm.ChangeSet; import org.apache.maven.continuum.model.scm.ScmResult; import org.apache.maven.continuum.model.system.Installation; import org.apache.maven.continuum.model.system.Profile; import org.apache.maven.continuum.model.system.SystemConfiguration; import org.codehaus.plexus.jdo.DefaultConfigurableJdoFactory; import org.codehaus.plexus.jdo.JdoFactory; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.rules.TestName; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import static org.junit.Assert.*; /** * Base class for tests using the continuum store. */ public abstract class AbstractContinuumStoreTestCase extends PlexusSpringTestCase { @Rule public TestName testName = new TestName(); protected String getName() { return testName.getMethodName(); } protected DaoUtils daoUtilsImpl; protected DirectoryPurgeConfigurationDao directoryPurgeConfigurationDao; protected LocalRepositoryDao localRepositoryDao; protected RepositoryPurgeConfigurationDao repositoryPurgeConfigurationDao; protected InstallationDao installationDao; protected ProfileDao profileDao; protected ProjectGroupDao projectGroupDao; protected ProjectDao projectDao; protected ScheduleDao scheduleDao; protected SystemConfigurationDao systemConfigurationDao; protected ProjectScmRootDao projectScmRootDao; protected ContinuumReleaseResultDao releaseResultDao; protected BuildQueueDao buildQueueDao; protected BuildDefinitionTemplateDao buildDefinitionTemplateDao; protected ProjectGroup defaultProjectGroup; protected ProjectGroup testProjectGroup2; protected Project testProject1; protected Project testProject2; protected Schedule testSchedule1; protected Schedule testSchedule2; protected Schedule testSchedule3; protected Profile testProfile1; protected Profile testProfile2; protected Profile testProfile3; protected Profile testProfile4; protected Installation testInstallationJava13; protected Installation testInstallationJava14; protected Installation testInstallationMaven20a3; protected Installation testInstallationEnvVar; protected BuildResult testBuildResult1; protected BuildResult testBuildResult2; protected BuildResult testBuildResult3; protected ScmResult testCheckoutResult1; protected LocalRepository testLocalRepository1; protected LocalRepository testLocalRepository2; protected LocalRepository testLocalRepository3; protected RepositoryPurgeConfiguration testRepoPurgeConfiguration1; protected RepositoryPurgeConfiguration testRepoPurgeConfiguration2; protected RepositoryPurgeConfiguration testRepoPurgeConfiguration3; protected DirectoryPurgeConfiguration testDirectoryPurgeConfig; protected ProjectScmRoot testProjectScmRoot; protected ContinuumReleaseResult testContinuumReleaseResult; protected BuildQueue testBuildQueue1; protected BuildQueue testBuildQueue2; protected BuildQueue testBuildQueue3; protected long baseTime; private SystemConfiguration systemConfiguration; @Before public void setupStoreAndDaos() throws Exception { createStore(); directoryPurgeConfigurationDao = lookup( DirectoryPurgeConfigurationDao.class ); localRepositoryDao = lookup( LocalRepositoryDao.class ); repositoryPurgeConfigurationDao = lookup( RepositoryPurgeConfigurationDao.class ); installationDao = lookup( InstallationDao.class ); profileDao = lookup( ProfileDao.class ); projectGroupDao = lookup( ProjectGroupDao.class ); projectDao = lookup( ProjectDao.class ); scheduleDao = lookup( ScheduleDao.class ); systemConfigurationDao = lookup( SystemConfigurationDao.class ); projectScmRootDao = lookup( ProjectScmRootDao.class ); releaseResultDao = lookup( ContinuumReleaseResultDao.class ); buildQueueDao = lookup( BuildQueueDao.class ); buildDefinitionTemplateDao = lookup( BuildDefinitionTemplateDao.class ); } @After public void tearDownStore() throws Exception { daoUtilsImpl.eraseDatabase(); daoUtilsImpl.closeStore(); } protected void createBuildDatabase( boolean isTestFromDataManagementTool ) throws Exception { createBuildDatabase( true, isTestFromDataManagementTool ); } protected void createBuildDatabase( boolean addToStore, boolean isTestFromDataManagementTool ) throws Exception { // Setting up test data testLocalRepository1 = createTestLocalRepository( "name1", "location1", "layout1" ); LocalRepository localRepository1 = createTestLocalRepository( testLocalRepository1 ); if ( addToStore ) { localRepository1 = localRepositoryDao.addLocalRepository( localRepository1 ); testLocalRepository1.setId( localRepository1.getId() ); } else { localRepository1.setId( 1 ); testLocalRepository1.setId( 1 ); } testLocalRepository2 = createTestLocalRepository( "name2", "location2", "layout2" ); LocalRepository localRepository2 = createTestLocalRepository( testLocalRepository2 ); if ( addToStore ) { localRepository2 = localRepositoryDao.addLocalRepository( localRepository2 ); testLocalRepository2.setId( localRepository2.getId() ); } else { localRepository2.setId( 2 ); testLocalRepository2.setId( 2 ); } testLocalRepository3 = createTestLocalRepository( "name3", "location3", "layout3" ); LocalRepository localRepository3 = createTestLocalRepository( testLocalRepository3 ); if ( addToStore ) { localRepository3 = localRepositoryDao.addLocalRepository( localRepository3 ); testLocalRepository3.setId( localRepository3.getId() ); } else { localRepository3.setId( 3 ); testLocalRepository3.setId( 3 ); } testBuildQueue1 = createTestBuildQueue( "build queue 1" ); BuildQueue buildQueue1 = createTestBuildQueue( testBuildQueue1 ); if ( addToStore ) { buildQueue1 = buildQueueDao.addBuildQueue( buildQueue1 ); testBuildQueue1.setId( buildQueue1.getId() ); } else { buildQueue1.setId( 1 ); testBuildQueue1.setId( 1 ); } testBuildQueue2 = createTestBuildQueue( "build queue 2" ); BuildQueue buildQueue2 = createTestBuildQueue( testBuildQueue2 ); if ( addToStore ) { buildQueue2 = buildQueueDao.addBuildQueue( buildQueue2 ); testBuildQueue2.setId( buildQueue2.getId() ); } else { buildQueue2.setId( 2 ); testBuildQueue2.setId( 2 ); } testBuildQueue3 = createTestBuildQueue( "build queue 3" ); BuildQueue buildQueue3 = createTestBuildQueue( testBuildQueue3 ); if ( addToStore ) { buildQueue3 = buildQueueDao.addBuildQueue( buildQueue3 ); testBuildQueue3.setId( buildQueue3.getId() ); } else { buildQueue3.setId( 3 ); testBuildQueue3.setId( 3 ); } defaultProjectGroup = createTestProjectGroup( "Default Group", "The Default Group", "org.apache.maven.test.default", localRepository1 ); testProjectGroup2 = createTestProjectGroup( "test group 2", "test group 2 desc", "test group 2 groupId", localRepository2 ); testProject1 = createTestProject( "artifactId1", 1, "description1", defaultProjectGroup.getGroupId(), "name1", "scmUrl1", 1, "url1", "version1", "workingDirectory1" ); // state must be 1 unless we setup a build in the correct state testProject2 = createTestProject( "artifactId2", 2, "description2", defaultProjectGroup.getGroupId(), "name2", "scmUrl2", 1, "url2", "version2", "workingDirectory2" ); testSchedule1 = createTestSchedule( "name1", "description1", 1, "cronExpression1", true ); testSchedule1.addBuildQueue( buildQueue1 ); testSchedule1.addBuildQueue( buildQueue2 ); testSchedule2 = createTestSchedule( "name2", "description2", 2, "cronExpression2", true ); testSchedule2.addBuildQueue( buildQueue2 ); testSchedule2.addBuildQueue( buildQueue3 ); testSchedule3 = createTestSchedule( "name3", "description3", 3, "cronExpression3", true ); testInstallationJava13 = createTestInstallation( "JDK 1.3", InstallationService.JDK_TYPE, "JAVA_HOME", "/usr/local/java-1.3" ); testInstallationJava14 = createTestInstallation( "JDK 1.4", InstallationService.JDK_TYPE, "JAVA_HOME", "/usr/local/java-1.4" ); testInstallationMaven20a3 = createTestInstallation( "Maven 2.0 alpha 3", InstallationService.MAVEN2_TYPE, "M2_HOME", "/usr/local/maven-2.0-alpha-3" ); testInstallationEnvVar = createTestInstallation( "Maven Heap Size", InstallationService.ENVVAR_TYPE, "MAVEN_OPTS", "-Xms256m -Xmx256m" ); ProjectNotifier testGroupNotifier1 = createTestNotifier( 1, true, false, true, "type1" ); ProjectNotifier testGroupNotifier2 = createTestNotifier( 2, false, true, false, "type2" ); ProjectNotifier testGroupNotifier3 = createTestNotifier( 3, true, false, false, "type3" ); ProjectNotifier testNotifier1 = createTestNotifier( 11, true, true, false, "type11" ); ProjectNotifier testNotifier2 = createTestNotifier( 12, false, false, true, "type12" ); ProjectNotifier testNotifier3 = createTestNotifier( 13, false, true, false, "type13" ); ProjectDeveloper testDeveloper1 = createTestDeveloper( 1, "email1", "name1", "scmId1" ); ProjectDeveloper testDeveloper2 = createTestDeveloper( 2, "email2", "name2", "scmId2" ); ProjectDeveloper testDeveloper3 = createTestDeveloper( 3, "email3", "name3", "scmId3" ); ProjectDependency testDependency1 = createTestDependency( "groupId1", "artifactId1", "version1" ); ProjectDependency testDependency2 = createTestDependency( "groupId2", "artifactId2", "version2" ); ProjectDependency testDependency3 = createTestDependency( "groupId3", "artifactId3", "version3" ); // TODO: simplify by deep copying the relationships in createTest... ? baseTime = System.currentTimeMillis(); Calendar cal = Calendar.getInstance(); cal.setTime( new Date( baseTime ) ); cal.add( Calendar.DAY_OF_MONTH, 1 ); long newTime = cal.getTimeInMillis(); // successful forced build testBuildResult1 = createTestBuildResult( 1, true, 2, 1, "error1", 1, baseTime, baseTime + 1000, "user" ); BuildResult buildResult1 = createTestBuildResult( testBuildResult1 ); ScmResult scmResult = createTestScmResult( "commandOutput1", "providerMessage1", true, "1" ); buildResult1.setScmResult( scmResult ); ScmResult testBuildResult1ScmResult = createTestScmResult( scmResult, "1" ); testBuildResult1.setScmResult( testBuildResult1ScmResult ); testCheckoutResult1 = createTestScmResult( "commandOutputCO1", "providerMessageCO1", false, "CO1" ); ScmResult checkoutResult1 = createTestScmResult( testCheckoutResult1, "CO1" ); testProject1.setCheckoutResult( checkoutResult1 ); testProject1.addBuildResult( buildResult1 ); // failed scheduled build testBuildResult2 = createTestBuildResult( 2, false, 3, 2, "error2", 2, newTime, newTime + 3000, "schedule" ); BuildResult buildResult2 = createTestBuildResult( testBuildResult2 ); testProject1.addBuildResult( buildResult2 ); cal.add( Calendar.DAY_OF_MONTH, 2 ); newTime = cal.getTimeInMillis(); // successful scheduled build testBuildResult3 = createTestBuildResult( 2, true, 2, 3, "error3", 3, newTime, newTime + 5000, "schedule" ); BuildResult buildResult3 = createTestBuildResult( testBuildResult3 ); scmResult = createTestScmResult( "commandOutput3", "providerMessage3", true, "3" ); buildResult3.setScmResult( scmResult ); testBuildResult3.setScmResult( createTestScmResult( scmResult, "3" ) ); testProject2.addBuildResult( buildResult3 ); // TODO: better way? this assumes that some untested methods already work! Schedule schedule2 = createTestSchedule( testSchedule2 ); if ( addToStore ) { schedule2 = scheduleDao.addSchedule( schedule2 ); testSchedule2.setId( schedule2.getId() ); } else { // from expected.xml, continuum-data-management testSchedule2.setId( 1 ); } Schedule schedule1 = createTestSchedule( testSchedule1 ); if ( addToStore ) { schedule1 = scheduleDao.addSchedule( schedule1 ); testSchedule1.setId( schedule1.getId() ); } else { // from expected.xml, continuum-data-management testSchedule1.setId( 2 ); } Schedule schedule3 = createTestSchedule( testSchedule3 ); if ( addToStore ) { schedule3 = scheduleDao.addSchedule( schedule3 ); testSchedule3.setId( schedule3.getId() ); } else { // from expected.xml, continuum-data-management testSchedule3.setId( 3 ); } Installation installationJava14 = createTestInstallation( testInstallationJava14 ); if ( addToStore ) { installationJava14 = installationDao.addInstallation( installationJava14 ); } else { installationJava14.setInstallationId( 1 ); } Installation installationMaven20a3 = createTestInstallation( testInstallationMaven20a3 ); if ( addToStore ) { installationMaven20a3 = installationDao.addInstallation( installationMaven20a3 ); } else { installationMaven20a3.setInstallationId( 2 ); } Installation installationJava13 = createTestInstallation( testInstallationJava13 ); if ( addToStore ) { installationJava13 = installationDao.addInstallation( installationJava13 ); } else { installationJava13.setInstallationId( 3 ); } Installation installationEnvVar = createTestInstallation( testInstallationEnvVar ); if ( addToStore ) { installationEnvVar = installationDao.addInstallation( installationEnvVar ); } else { installationEnvVar.setInstallationId( 4 ); } testProfile1 = createTestProfile( "name1", "description1", 1, true, true, installationJava13, installationMaven20a3 ); testProfile2 = createTestProfile( "name2", "description2", 2, false, true, installationJava14, installationMaven20a3 ); testProfile3 = createTestProfile( "name3", "description3", 3, true, false, installationJava14, installationMaven20a3 ); testProfile4 = createTestProfile( "name4", "description4", 4, false, false, installationJava14, installationMaven20a3 ); testProfile4.addEnvironmentVariable( installationEnvVar ); Profile profile1 = createTestProfile( testProfile1 ); if ( addToStore ) { profile1 = profileDao.addProfile( profile1 ); testProfile1.setId( profile1.getId() ); } else { testProfile1.setId( 1 ); } Profile profile2 = createTestProfile( testProfile2 ); if ( addToStore ) { profile2 = profileDao.addProfile( profile2 ); testProfile2.setId( profile2.getId() ); } else { testProfile2.setId( 2 ); } Profile profile3 = createTestProfile( testProfile3 ); if ( addToStore ) { profile3 = profileDao.addProfile( profile3 ); testProfile3.setId( profile3.getId() ); } else { profile3.setId( 3 ); } Profile profile4 = createTestProfile( testProfile4 ); if ( addToStore ) { profile4 = profileDao.addProfile( profile4 ); testProfile4.setId( profile4.getId() ); } else { profile4.setId( 4 ); } testRepoPurgeConfiguration1 = createTestRepositoryPurgeConfiguration( true, 5, 50, false, schedule2, true, localRepository1 ); if ( addToStore ) { testRepoPurgeConfiguration1 = repositoryPurgeConfigurationDao.addRepositoryPurgeConfiguration( testRepoPurgeConfiguration1 ); } else { testRepoPurgeConfiguration1.setId( 1 ); } testRepoPurgeConfiguration2 = createTestRepositoryPurgeConfiguration( false, 10, 200, true, schedule1, true, localRepository2 ); if ( addToStore ) { testRepoPurgeConfiguration2 = repositoryPurgeConfigurationDao.addRepositoryPurgeConfiguration( testRepoPurgeConfiguration2 ); } else { testRepoPurgeConfiguration2.setId( 2 ); } testRepoPurgeConfiguration3 = createTestRepositoryPurgeConfiguration( false, 10, 200, true, schedule2, true, localRepository1 ); if ( addToStore ) { testRepoPurgeConfiguration3 = repositoryPurgeConfigurationDao.addRepositoryPurgeConfiguration( testRepoPurgeConfiguration3 ); } else { testRepoPurgeConfiguration3.setId( 3 ); } testDirectoryPurgeConfig = createTestDirectoryPurgeConfiguration( "location1", "directoryType1", true, 10, 50, schedule2, true ); if ( addToStore ) { testDirectoryPurgeConfig = directoryPurgeConfigurationDao.addDirectoryPurgeConfiguration( testDirectoryPurgeConfig ); } else { testDirectoryPurgeConfig.setId( 1 ); } BuildDefinition testGroupBuildDefinition1 = createTestBuildDefinition( "arguments1", "buildFile1", "goals1", profile1, schedule2, false, false ); BuildDefinition testGroupBuildDefinition2 = createTestBuildDefinition( "arguments2", "buildFile2", "goals2", profile1, schedule1, false, false ); BuildDefinition testGroupBuildDefinition3 = createTestBuildDefinition( "arguments3", "buildFile3", "goals3", profile2, schedule1, false, false ); BuildDefinition testGroupBuildDefinition4 = createTestBuildDefinition( null, null, "deploy", null, null, false, false ); BuildDefinition testBuildDefinition1 = createTestBuildDefinition( "arguments11", "buildFile11", "goals11", profile2, schedule1, false, false ); BuildDefinition testBuildDefinition2 = createTestBuildDefinition( "arguments12", "buildFile12", "goals12", profile2, schedule2, false, false ); BuildDefinition testBuildDefinition3 = createTestBuildDefinition( "arguments13", "buildFile13", "goals13", profile1, schedule2, false, false ); BuildDefinition testBuildDefinition4 = createTestBuildDefinition( null, null, "deploy", null, null, false, false ); BuildDefinition testBuildDefinition5 = createTestBuildDefinition( "arguments14", "buildFile14", "goals14", profile1, schedule1, false, false ); testBuildDefinition5.setTemplate( true ); BuildDefinitionTemplate testBuildDefinitionTemplate1 = createTestBuildDefinitionTemplate( "template2", "type2", false ); testBuildDefinitionTemplate1.addBuildDefinition( testBuildDefinition5 ); if ( addToStore ) { buildDefinitionTemplateDao.addBuildDefinitionTemplate( testBuildDefinitionTemplate1 ); } ProjectGroup group = createTestProjectGroup( defaultProjectGroup ); Project project1 = createTestProject( testProject1 ); project1.addBuildResult( buildResult1 ); project1.addBuildResult( buildResult2 ); project1.setCheckoutResult( checkoutResult1 ); ProjectNotifier notifier1 = createTestNotifier( testNotifier1 ); project1.addNotifier( notifier1 ); testProject1.addNotifier( testNotifier1 ); BuildDefinition buildDefinition1 = createTestBuildDefinition( testBuildDefinition1 ); project1.addBuildDefinition( buildDefinition1 ); testProject1.addBuildDefinition( testBuildDefinition1 ); BuildDefinition buildDefinition2 = createTestBuildDefinition( testBuildDefinition2 ); project1.addBuildDefinition( buildDefinition2 ); testProject1.addBuildDefinition( testBuildDefinition2 ); ProjectDeveloper projectDeveloper1 = createTestDeveloper( testDeveloper1 ); project1.addDeveloper( projectDeveloper1 ); testProject1.addDeveloper( testDeveloper1 ); ProjectDependency projectDependency1 = createTestDependency( testDependency1 ); project1.addDependency( projectDependency1 ); testProject1.addDependency( testDependency1 ); ProjectDependency projectDependency2 = createTestDependency( testDependency2 ); project1.addDependency( projectDependency2 ); testProject1.addDependency( testDependency2 ); group.addProject( project1 ); defaultProjectGroup.addProject( project1 ); Project project2 = createTestProject( testProject2 ); project2.addBuildResult( buildResult3 ); ProjectNotifier notifier2 = createTestNotifier( testNotifier2 ); project2.addNotifier( notifier2 ); testProject2.addNotifier( testNotifier2 ); ProjectNotifier notifier3 = createTestNotifier( testNotifier3 ); project2.addNotifier( notifier3 ); testProject2.addNotifier( testNotifier3 ); BuildDefinition buildDefinition3 = createTestBuildDefinition( testBuildDefinition3 ); project2.addBuildDefinition( buildDefinition3 ); testProject2.addBuildDefinition( testBuildDefinition3 ); BuildDefinition buildDefinition4 = createTestBuildDefinition( testBuildDefinition4 ); project2.addBuildDefinition( buildDefinition4 ); testProject2.addBuildDefinition( testBuildDefinition4 ); ProjectDeveloper projectDeveloper2 = createTestDeveloper( testDeveloper2 ); project2.addDeveloper( projectDeveloper2 ); testProject2.addDeveloper( testDeveloper2 ); ProjectDeveloper projectDeveloper3 = createTestDeveloper( testDeveloper3 ); project2.addDeveloper( projectDeveloper3 ); testProject2.addDeveloper( testDeveloper3 ); ProjectDependency projectDependency3 = createTestDependency( testDependency3 ); project2.addDependency( projectDependency3 ); testProject2.addDependency( testDependency3 ); group.addProject( project2 ); defaultProjectGroup.addProject( project2 ); ProjectNotifier groupNotifier1 = createTestNotifier( testGroupNotifier1 ); group.addNotifier( groupNotifier1 ); defaultProjectGroup.addNotifier( testGroupNotifier1 ); ProjectNotifier groupNotifier2 = createTestNotifier( testGroupNotifier2 ); group.addNotifier( groupNotifier2 ); defaultProjectGroup.addNotifier( testGroupNotifier2 ); BuildDefinition groupBuildDefinition1 = createTestBuildDefinition( testGroupBuildDefinition1 ); group.addBuildDefinition( groupBuildDefinition1 ); defaultProjectGroup.addBuildDefinition( testGroupBuildDefinition1 ); if ( addToStore ) { group = projectGroupDao.addProjectGroup( group ); defaultProjectGroup.setId( group.getId() ); testProject1.setId( project1.getId() ); testProject2.setId( project2.getId() ); testBuildResult1.setId( buildResult1.getId() ); testBuildResult2.setId( buildResult2.getId() ); testBuildResult3.setId( buildResult3.getId() ); } else { // from expected.xml, continuum-data-management defaultProjectGroup.setId( 1 ); testProject1.setId( 1 ); testProject2.setId( 2 ); } group = createTestProjectGroup( testProjectGroup2 ); ProjectNotifier groupNotifier3 = createTestNotifier( testGroupNotifier3 ); group.addNotifier( groupNotifier3 ); testProjectGroup2.addNotifier( testGroupNotifier3 ); BuildDefinition groupBuildDefinition2 = createTestBuildDefinition( testGroupBuildDefinition2 ); group.addBuildDefinition( groupBuildDefinition2 ); testProjectGroup2.addBuildDefinition( testGroupBuildDefinition2 ); BuildDefinition groupBuildDefinition3 = createTestBuildDefinition( testGroupBuildDefinition3 ); group.addBuildDefinition( groupBuildDefinition3 ); testProjectGroup2.addBuildDefinition( testGroupBuildDefinition3 ); BuildDefinition groupBuildDefinition4 = createTestBuildDefinition( testGroupBuildDefinition4 ); group.addBuildDefinition( groupBuildDefinition4 ); testProjectGroup2.addBuildDefinition( testGroupBuildDefinition4 ); if ( addToStore ) { group = projectGroupDao.addProjectGroup( group ); testProjectGroup2.setId( group.getId() ); } else { group.setId( 2 ); testProjectGroup2.setId( 2 ); // from expected.xml, continuum-data-management } systemConfiguration = new SystemConfiguration(); systemConfiguration.setBaseUrl( "baseUrl" ); systemConfiguration.setBuildOutputDirectory( "buildOutputDirectory" ); systemConfiguration.setDefaultScheduleCronExpression( "* * * * *" ); systemConfiguration.setDefaultScheduleDescription( "Description" ); systemConfiguration.setDeploymentRepositoryDirectory( "deployment" ); systemConfiguration.setGuestAccountEnabled( false ); systemConfiguration.setInitialized( true ); systemConfiguration.setWorkingDirectory( "workingDirectory" ); if ( addToStore && !isTestFromDataManagementTool ) { systemConfiguration = systemConfigurationDao.addSystemConfiguration( systemConfiguration ); } else { // hack for DataManagementTool test // data-management-jdo has a dependency to continuum-commons where DefaultConfigurationService // is located. DefaultConfiguration loads the data and already adds a system configuration, causing // this to throw an exception boolean isExisting = false; try { systemConfigurationDao.getSystemConfiguration(); } catch ( ContinuumStoreException e ) { isExisting = true; } if ( !isExisting ) { systemConfiguration = systemConfigurationDao.getSystemConfiguration(); systemConfiguration.setBaseUrl( "baseUrl" ); systemConfiguration.setBuildOutputDirectory( "buildOutputDirectory" ); systemConfiguration.setDefaultScheduleCronExpression( "* * * * *" ); systemConfiguration.setDefaultScheduleDescription( "Description" ); systemConfiguration.setDeploymentRepositoryDirectory( "deployment" ); systemConfiguration.setGuestAccountEnabled( false ); systemConfiguration.setInitialized( true ); systemConfiguration.setWorkingDirectory( "workingDirectory" ); systemConfigurationDao.updateSystemConfiguration( systemConfiguration ); } } testProjectScmRoot = createTestProjectScmRoot( "scmRootAddress1", 1, 0, "error1", group ); ProjectScmRoot scmRoot = createTestProjectScmRoot( testProjectScmRoot ); if ( addToStore ) { scmRoot = projectScmRootDao.addProjectScmRoot( scmRoot ); testProjectScmRoot.setId( scmRoot.getId() ); } else { testProjectScmRoot.setId( 1 ); } testContinuumReleaseResult = createTestContinuumReleaseResult( group, null, "releaseGoal", 0, 0, 0 ); ContinuumReleaseResult releaseResult = createTestContinuumReleaseResult( testContinuumReleaseResult ); if ( addToStore ) { releaseResult = releaseResultDao.addContinuumReleaseResult( releaseResult ); testContinuumReleaseResult.setId( releaseResult.getId() ); } else { testContinuumReleaseResult.setId( 1 ); } } protected void assertBuildDatabase() throws ContinuumStoreException { assertProjectGroupEquals( defaultProjectGroup, projectGroupDao.getProjectGroup( defaultProjectGroup.getId() ) ); assertProjectGroupEquals( testProjectGroup2, projectGroupDao.getProjectGroup( testProjectGroup2.getId() ) ); assertProjectEquals( testProject1, projectDao.getProject( testProject1.getId() ) ); assertProjectEquals( testProject2, projectDao.getProject( testProject2.getId() ) ); assertScheduleEquals( testSchedule1, scheduleDao.getSchedule( testSchedule1.getId() ) ); assertScheduleEquals( testSchedule2, scheduleDao.getSchedule( testSchedule2.getId() ) ); assertScheduleEquals( testSchedule3, scheduleDao.getSchedule( testSchedule3.getId() ) ); Iterator<Installation> iterator = installationDao.getAllInstallations().iterator(); assertInstallationEquals( testInstallationJava13, iterator.next() ); assertInstallationEquals( testInstallationJava14, iterator.next() ); assertInstallationEquals( testInstallationMaven20a3, iterator.next() ); /* // TODO!!! -- definitely need to test the changeset stuff since it uses modello.refid ProjectNotifier testGroupNotifier1 = createTestNotifier( 1, true, false, true, "type1" ); ProjectNotifier testGroupNotifier2 = createTestNotifier( 2, false, true, false, "type2" ); ProjectNotifier testGroupNotifier3 = createTestNotifier( 3, true, false, false, "type3" ); ProjectNotifier testNotifier1 = createTestNotifier( 11, true, true, false, "type11" ); ProjectNotifier testNotifier2 = createTestNotifier( 12, false, false, true, "type12" ); ProjectNotifier testNotifier3 = createTestNotifier( 13, false, true, false, "type13" ); ProjectDeveloper testDeveloper1 = createTestDeveloper( 1, "email1", "name1", "scmId1" ); ProjectDeveloper testDeveloper2 = createTestDeveloper( 2, "email2", "name2", "scmId2" ); ProjectDeveloper testDeveloper3 = createTestDeveloper( 3, "email3", "name3", "scmId3" ); ProjectDependency testDependency1 = createTestDependency( "groupId1", "artifactId1", "version1" ); ProjectDependency testDependency2 = createTestDependency( "groupId2", "artifactId2", "version2" ); ProjectDependency testDependency3 = createTestDependency( "groupId3", "artifactId3", "version3" ); // TODO: simplify by deep copying the relationships in createTest... ? long baseTime = System.currentTimeMillis(); testBuildResult1 = createTestBuildResult( 1, true, 1, 1, "error1", 1, baseTime, baseTime + 1000 ); BuildResult buildResult1 = createTestBuildResult( testBuildResult1 ); ScmResult scmResult = createTestScmResult( "commandOutput1", "providerMessage1", true, "1" ); buildResult1.setScmResult( scmResult ); ScmResult testBuildResult1ScmResult = createTestScmResult( scmResult, "1" ); testBuildResult1.setScmResult( testBuildResult1ScmResult ); testCheckoutResult1 = createTestScmResult( "commandOutputCO1", "providerMessageCO1", false, "CO1" ); ScmResult checkoutResult1 = createTestScmResult( testCheckoutResult1, "CO1" ); testProject1.setCheckoutResult( checkoutResult1 ); testProject1.addBuildResult( buildResult1 ); testBuildResult2 = createTestBuildResult( 2, false, 2, 2, "error2", 2, baseTime + 2000, baseTime + 3000 ); BuildResult buildResult2 = createTestBuildResult( testBuildResult2 ); testProject1.addBuildResult( buildResult2 ); testBuildResult3 = createTestBuildResult( 3, true, 3, 3, "error3", 3, baseTime + 4000, baseTime + 5000 ); BuildResult buildResult3 = createTestBuildResult( testBuildResult3 ); scmResult = createTestScmResult( "commandOutput3", "providerMessage3", true, "3" ); buildResult3.setScmResult( scmResult ); testBuildResult3.setScmResult( createTestScmResult( scmResult, "3" ) ); testProject2.addBuildResult( buildResult3 ); BuildDefinition testGroupBuildDefinition1 = createTestBuildDefinition( "arguments1", "buildFile1", "goals1", profile1, schedule2 ); BuildDefinition testGroupBuildDefinition2 = createTestBuildDefinition( "arguments2", "buildFile2", "goals2", profile1, schedule1 ); BuildDefinition testGroupBuildDefinition3 = createTestBuildDefinition( "arguments3", "buildFile3", "goals3", profile2, schedule1 ); BuildDefinition testBuildDefinition1 = createTestBuildDefinition( "arguments11", "buildFile11", "goals11", profile2, schedule1 ); BuildDefinition testBuildDefinition2 = createTestBuildDefinition( "arguments12", "buildFile12", "goals12", profile2, schedule2 ); BuildDefinition testBuildDefinition3 = createTestBuildDefinition( "arguments13", "buildFile13", "goals13", profile1, schedule2 ); ProjectGroup group = createTestProjectGroup( defaultProjectGroup ); Project project1 = createTestProject( testProject1 ); project1.addBuildResult( buildResult1 ); project1.addBuildResult( buildResult2 ); project1.setCheckoutResult( checkoutResult1 ); ProjectNotifier notifier1 = createTestNotifier( testNotifier1 ); project1.addNotifier( notifier1 ); testProject1.addNotifier( testNotifier1 ); BuildDefinition buildDefinition1 = createTestBuildDefinition( testBuildDefinition1 ); project1.addBuildDefinition( buildDefinition1 ); testProject1.addBuildDefinition( testBuildDefinition1 ); BuildDefinition buildDefinition2 = createTestBuildDefinition( testBuildDefinition2 ); project1.addBuildDefinition( buildDefinition2 ); testProject1.addBuildDefinition( testBuildDefinition2 ); ProjectDeveloper projectDeveloper1 = createTestDeveloper( testDeveloper1 ); project1.addDeveloper( projectDeveloper1 ); testProject1.addDeveloper( testDeveloper1 ); ProjectDependency projectDependency1 = createTestDependency( testDependency1 ); project1.addDependency( projectDependency1 ); testProject1.addDependency( testDependency1 ); ProjectDependency projectDependency2 = createTestDependency( testDependency2 ); project1.addDependency( projectDependency2 ); testProject1.addDependency( testDependency2 ); group.addProject( project1 ); defaultProjectGroup.addProject( project1 ); Project project2 = createTestProject( testProject2 ); project2.addBuildResult( buildResult3 ); ProjectNotifier notifier2 = createTestNotifier( testNotifier2 ); project2.addNotifier( notifier2 ); testProject2.addNotifier( testNotifier2 ); ProjectNotifier notifier3 = createTestNotifier( testNotifier3 ); project2.addNotifier( notifier3 ); testProject2.addNotifier( testNotifier3 ); BuildDefinition buildDefinition3 = createTestBuildDefinition( testBuildDefinition3 ); project2.addBuildDefinition( buildDefinition3 ); testProject2.addBuildDefinition( testBuildDefinition3 ); ProjectDeveloper projectDeveloper2 = createTestDeveloper( testDeveloper2 ); project2.addDeveloper( projectDeveloper2 ); testProject2.addDeveloper( testDeveloper2 ); ProjectDeveloper projectDeveloper3 = createTestDeveloper( testDeveloper3 ); project2.addDeveloper( projectDeveloper3 ); testProject2.addDeveloper( testDeveloper3 ); ProjectDependency projectDependency3 = createTestDependency( testDependency3 ); project2.addDependency( projectDependency3 ); testProject2.addDependency( testDependency3 ); group.addProject( project2 ); defaultProjectGroup.addProject( project2 ); ProjectNotifier groupNotifier1 = createTestNotifier( testGroupNotifier1 ); group.addNotifier( groupNotifier1 ); defaultProjectGroup.addNotifier( testGroupNotifier1 ); ProjectNotifier groupNotifier2 = createTestNotifier( testGroupNotifier2 ); group.addNotifier( groupNotifier2 ); defaultProjectGroup.addNotifier( testGroupNotifier2 ); BuildDefinition groupBuildDefinition1 = createTestBuildDefinition( testGroupBuildDefinition1 ); group.addBuildDefinition( groupBuildDefinition1 ); defaultProjectGroup.addBuildDefinition( testGroupBuildDefinition1 ); store.addProjectGroup( group ); defaultProjectGroup.setId( group.getId() ); testProject1.setId( project1.getId() ); testBuildResult1.setId( buildResult1.getId() ); testBuildResult2.setId( buildResult2.getId() ); testProject2.setId( project2.getId() ); testBuildResult3.setId( buildResult3.getId() ); group = createTestProjectGroup( testProjectGroup2 ); ProjectNotifier groupNotifier3 = createTestNotifier( testGroupNotifier3 ); group.addNotifier( groupNotifier3 ); testProjectGroup2.addNotifier( testGroupNotifier3 ); BuildDefinition groupBuildDefinition2 = createTestBuildDefinition( testGroupBuildDefinition2 ); group.addBuildDefinition( groupBuildDefinition2 ); testProjectGroup2.addBuildDefinition( testGroupBuildDefinition2 ); BuildDefinition groupBuildDefinition3 = createTestBuildDefinition( testGroupBuildDefinition3 ); group.addBuildDefinition( groupBuildDefinition3 ); testProjectGroup2.addBuildDefinition( testGroupBuildDefinition3 ); store.addProjectGroup( group ); testProjectGroup2.setId( group.getId() ); */ assertSystemConfiguration( systemConfiguration, systemConfigurationDao.getSystemConfiguration() ); assertLocalRepositoryEquals( testLocalRepository1, localRepositoryDao.getLocalRepository( testLocalRepository1.getId() ) ); assertLocalRepositoryEquals( testLocalRepository2, localRepositoryDao.getLocalRepository( testLocalRepository2.getId() ) ); assertLocalRepositoryEquals( testLocalRepository3, localRepositoryDao.getLocalRepository( testLocalRepository3.getId() ) ); /* assertRepositoryPurgeConfigurationEquals( testRepoPurgeConfiguration1, repositoryPurgeConfigurationDao.getRepositoryPurgeConfiguration( testRepoPurgeConfiguration1.getId() ) ); assertRepositoryPurgeConfigurationEquals( testRepoPurgeConfiguration2, repositoryPurgeConfigurationDao.getRepositoryPurgeConfiguration( testRepoPurgeConfiguration2.getId() ) ); assertRepositoryPurgeConfigurationEquals( testRepoPurgeConfiguration3, repositoryPurgeConfigurationDao.getRepositoryPurgeConfiguration( testRepoPurgeConfiguration3.getId() ) ); assertDirectoryPurgeConfigurationEquals( testDirectoryPurgeConfig, directoryPurgeConfigurationDao.getDirectoryPurgeConfiguration( testDirectoryPurgeConfig.getId() ) ); */ assertProjectScmRootEquals( testProjectScmRoot, projectScmRootDao.getProjectScmRoot( testProjectScmRoot.getId() ) ); assertReleaseResultEquals( testContinuumReleaseResult, releaseResultDao.getContinuumReleaseResult( testContinuumReleaseResult.getId() ) ); } private void assertSystemConfiguration( SystemConfiguration expected, SystemConfiguration actual ) { assertNotSame( expected, actual ); assertEquals( expected.getBaseUrl(), actual.getBaseUrl() ); assertEquals( expected.getBuildOutputDirectory(), actual.getBuildOutputDirectory() ); assertEquals( expected.getDefaultScheduleCronExpression(), actual.getDefaultScheduleCronExpression() ); assertEquals( expected.getDefaultScheduleDescription(), actual.getDefaultScheduleDescription() ); assertEquals( expected.getDeploymentRepositoryDirectory(), actual.getDeploymentRepositoryDirectory() ); assertEquals( expected.isGuestAccountEnabled(), actual.isGuestAccountEnabled() ); assertEquals( expected.isInitialized(), actual.isInitialized() ); assertEquals( expected.getWorkingDirectory(), actual.getWorkingDirectory() ); } protected void assertEmpty( boolean isTestFromDataManagementTool ) throws ContinuumStoreException { assertEquals( 0, installationDao.getAllInstallations().size() ); assertEquals( 0, profileDao.getAllProfilesByName().size() ); assertEquals( 0, projectGroupDao.getAllProjectGroups().size() ); assertEquals( 0, projectDao.getAllProjectsByName().size() ); if ( !isTestFromDataManagementTool ) { assertNull( systemConfigurationDao.getSystemConfiguration() ); } } protected static BuildDefinition createTestBuildDefinition( BuildDefinition buildDefinition ) { return createTestBuildDefinition( buildDefinition.getArguments(), buildDefinition.getBuildFile(), buildDefinition.getGoals(), buildDefinition.getProfile(), buildDefinition.getSchedule(), buildDefinition.isDefaultForProject(), buildDefinition.isBuildFresh() ); } protected static BuildDefinition createTestBuildDefinition( String arguments, String buildFile, String goals, Profile profile, Schedule schedule, boolean defaultForProject, boolean buildFresh ) { BuildDefinition definition = new BuildDefinition(); definition.setArguments( arguments ); definition.setBuildFile( buildFile ); definition.setGoals( goals ); definition.setProfile( profile ); definition.setSchedule( schedule ); definition.setDefaultForProject( defaultForProject ); definition.setBuildFresh( buildFresh ); return definition; } protected static ProjectNotifier createTestNotifier( ProjectNotifier notifier ) { return createTestNotifier( notifier.getRecipientType(), notifier.isSendOnError(), notifier.isSendOnFailure(), notifier.isSendOnSuccess(), notifier.getType() ); } protected static ProjectNotifier createTestNotifier( int recipientType, boolean sendOnError, boolean sendOnFailure, boolean sendOnSuccess, String type ) { Map<String, String> configuration = new HashMap<String, String>(); configuration.put( "key1", "value1" ); configuration.put( "key2", "value2" ); ProjectNotifier notifier = new ProjectNotifier(); notifier.setConfiguration( configuration ); notifier.setRecipientType( recipientType ); notifier.setSendOnError( sendOnError ); notifier.setSendOnFailure( sendOnFailure ); notifier.setSendOnSuccess( sendOnSuccess ); notifier.setType( type ); return notifier; } private static ScmResult createTestScmResult( ScmResult scmResult, String base ) { return createTestScmResult( scmResult.getCommandOutput(), scmResult.getProviderMessage(), scmResult.isSuccess(), base ); } private static ScmResult createTestScmResult( String commandOutput, String providerMessage, boolean success, String base ) { ScmResult scmResult = new ScmResult(); scmResult.setCommandOutput( commandOutput ); scmResult.setProviderMessage( providerMessage ); scmResult.setSuccess( success ); List<ChangeSet> changes = new ArrayList<ChangeSet>(); changes.add( createTestChangeSet( "author" + base + ".1", "comment" + base + ".1", base + ".1" ) ); changes.add( createTestChangeSet( "author" + base + ".2", "comment" + base + ".2", base + ".2" ) ); scmResult.setChanges( changes ); return scmResult; } private static ChangeSet createTestChangeSet( String author, String comment, String base ) { ChangeSet changeSet = new ChangeSet(); changeSet.setAuthor( author ); changeSet.setComment( comment ); changeSet.setDate( System.currentTimeMillis() ); List<ChangeFile> files = new ArrayList<ChangeFile>(); files.add( createTestChangeFile( "name" + base + ".1", "rev" + base + ".1" ) ); files.add( createTestChangeFile( "name" + base + ".2", "rev" + base + ".2" ) ); files.add( createTestChangeFile( "name" + base + ".3", "rev" + base + ".3" ) ); changeSet.setFiles( files ); return changeSet; } private static ChangeFile createTestChangeFile( String name, String revision ) { ChangeFile changeFile = new ChangeFile(); changeFile.setName( name ); changeFile.setRevision( revision ); return changeFile; } private static BuildResult createTestBuildResult( BuildResult buildResult ) { return createTestBuildResult( buildResult.getTrigger(), buildResult.isSuccess(), buildResult.getState(), buildResult.getExitCode(), buildResult.getError(), buildResult.getBuildNumber(), buildResult.getStartTime(), buildResult.getEndTime(), buildResult.getUsername() ); } private static BuildResult createTestBuildResult( int trigger, boolean success, int state, int exitCode, String error, int buildNumber, long startTime, long endTime, String triggeredBy ) { BuildResult result = new BuildResult(); result.setBuildNumber( buildNumber ); result.setStartTime( startTime ); result.setEndTime( endTime ); result.setError( error ); result.setExitCode( exitCode ); result.setState( state ); result.setSuccess( success ); result.setTrigger( trigger ); result.setUsername( triggeredBy ); return result; } protected static Installation createTestInstallation( String name, String type, String varName, String varValue ) { Installation installation = new Installation(); installation.setName( name ); installation.setType( type ); installation.setVarName( varName ); installation.setVarValue( varValue ); return installation; } protected static Installation createTestInstallation( Installation installation ) { return createTestInstallation( installation.getName(), installation.getType(), installation.getVarName(), installation.getVarValue() ); } protected static Schedule createTestSchedule( Schedule schedule ) { return createTestSchedule( schedule.getName(), schedule.getDescription(), schedule.getDelay(), schedule.getCronExpression(), schedule.isActive(), schedule.getBuildQueues() ); } protected static Schedule createTestSchedule( String name, String description, int delay, String cronExpression, boolean active ) { return createTestSchedule( name, description, delay, cronExpression, active, null ); } protected static Schedule createTestSchedule( String name, String description, int delay, String cronExpression, boolean active, List<BuildQueue> buildQueues ) { Schedule schedule = new Schedule(); schedule.setActive( active ); schedule.setCronExpression( cronExpression ); schedule.setDelay( delay ); schedule.setDescription( description ); schedule.setName( name ); schedule.setBuildQueues( buildQueues ); return schedule; } protected static Profile createTestProfile( Profile profile ) { return createTestProfile( profile.getName(), profile.getDescription(), profile.getScmMode(), profile.isBuildWithoutChanges(), profile.isActive(), profile.getJdk(), profile.getBuilder(), profile.getEnvironmentVariables() ); } protected static Profile createTestProfile( String name, String description, int scmMode, boolean buildWithoutChanges, boolean active, Installation jdk, Installation builder ) { return createTestProfile( name, description, scmMode, buildWithoutChanges, active, jdk, builder, null ); } protected static Profile createTestProfile( String name, String description, int scmMode, boolean buildWithoutChanges, boolean active, Installation jdk, Installation builder, List<Installation> envVars ) { Profile profile = new Profile(); profile.setActive( active ); profile.setBuildWithoutChanges( buildWithoutChanges ); profile.setScmMode( scmMode ); profile.setDescription( description ); profile.setName( name ); profile.setBuilder( builder ); profile.setJdk( jdk ); profile.setEnvironmentVariables( envVars ); return profile; } protected static ProjectGroup createTestProjectGroup( ProjectGroup group ) { return createTestProjectGroup( group.getName(), group.getDescription(), group.getGroupId(), group.getLocalRepository() ); } protected static ProjectGroup createTestProjectGroup( String name, String description, String groupId, LocalRepository repository ) { ProjectGroup group = new ProjectGroup(); group.setName( name ); group.setDescription( description ); group.setGroupId( groupId ); group.setLocalRepository( repository ); return group; } protected static Project createTestProject( Project project ) { return createTestProject( project.getArtifactId(), project.getBuildNumber(), project.getDescription(), project.getGroupId(), project.getName(), project.getScmUrl(), project.getState(), project.getUrl(), project.getVersion(), project.getWorkingDirectory() ); } protected static Project createTestProject( String artifactId, int buildNumber, String description, String groupId, String name, String scmUrl, int state, String url, String version, String workingDirectory ) { Project project = new Project(); project.setArtifactId( artifactId ); project.setBuildNumber( buildNumber ); project.setDescription( description ); project.setGroupId( groupId ); project.setName( name ); project.setScmUrl( scmUrl ); project.setState( state ); project.setUrl( url ); project.setVersion( version ); project.setWorkingDirectory( workingDirectory ); return project; } protected static void assertProjectEquals( Project expectedProject, Project project ) { assertEquals( "compare projects", expectedProject, project ); assertNotSame( expectedProject, project ); // aggressive compare, as equals is using the identity assertEquals( "compare expectedProject - name", expectedProject.getName(), project.getName() ); assertEquals( "compare expectedProject - desc", expectedProject.getDescription(), project.getDescription() ); assertEquals( "compare expectedProject - groupId", expectedProject.getGroupId(), project.getGroupId() ); assertEquals( "compare expectedProject - artifactId", expectedProject.getArtifactId(), project.getArtifactId() ); assertEquals( "compare expectedProject - buildNumber", expectedProject.getBuildNumber(), project.getBuildNumber() ); assertEquals( "compare expectedProject - scmUrl", expectedProject.getScmUrl(), project.getScmUrl() ); assertEquals( "compare expectedProject - state", expectedProject.getState(), project.getState() ); assertEquals( "compare expectedProject - url", expectedProject.getUrl(), project.getUrl() ); assertEquals( "compare expectedProject - version", expectedProject.getVersion(), project.getVersion() ); assertEquals( "compare expectedProject - workingDirectory", expectedProject.getWorkingDirectory(), project.getWorkingDirectory() ); } protected static void assertProjectGroupEquals( ProjectGroup expectedGroup, ProjectGroup actualGroup ) { assertEquals( "compare project groups", expectedGroup, actualGroup ); assertNotSame( expectedGroup, actualGroup ); // aggressive compare, as equals is using the identity assertEquals( "compare project groups - name", expectedGroup.getName(), actualGroup.getName() ); assertEquals( "compare project groups - desc", expectedGroup.getDescription(), actualGroup.getDescription() ); assertEquals( "compare project groups - groupId", expectedGroup.getGroupId(), actualGroup.getGroupId() ); } protected static void assertScheduleEquals( Schedule expectedSchedule, Schedule actualSchedule ) { assertEquals( expectedSchedule, actualSchedule ); if ( expectedSchedule != null ) { assertNotSame( expectedSchedule, actualSchedule ); assertEquals( "compare schedule - id", expectedSchedule.getId(), actualSchedule.getId() ); assertEquals( "compare schedule - name", expectedSchedule.getName(), actualSchedule.getName() ); assertEquals( "compare schedule - desc", expectedSchedule.getDescription(), actualSchedule.getDescription() ); assertEquals( "compare schedule - delay", expectedSchedule.getDelay(), actualSchedule.getDelay() ); assertEquals( "compare schedule - cron", expectedSchedule.getCronExpression(), actualSchedule.getCronExpression() ); assertEquals( "compare schedule - active", expectedSchedule.isActive(), actualSchedule.isActive() ); } } protected static void assertProfileEquals( Profile expectedProfile, Profile actualProfile ) { assertEquals( expectedProfile, actualProfile ); if ( expectedProfile != null ) { assertNotSame( expectedProfile, actualProfile ); assertEquals( "compare profile - name", expectedProfile.getName(), actualProfile.getName() ); assertEquals( "compare profile - desc", expectedProfile.getDescription(), actualProfile.getDescription() ); assertEquals( "compare profile - scmMode", expectedProfile.getScmMode(), actualProfile.getScmMode() ); assertEquals( "compare profile - build w/o changes", expectedProfile.isBuildWithoutChanges(), actualProfile.isBuildWithoutChanges() ); assertEquals( "compare profile - active", expectedProfile.isActive(), actualProfile.isActive() ); } } protected static void assertInstallationEquals( Installation expected, Installation actual ) { assertNotNull( actual ); assertEquals( "compare installation - name", expected.getName(), actual.getName() ); assertEquals( "compare installation - varName", expected.getVarName(), actual.getVarName() ); assertEquals( "compare installation - varValue", expected.getVarValue(), actual.getVarValue() ); } protected static void assertBuildResultEquals( BuildResult expected, BuildResult actual ) { assertEquals( "compare build result - build #", expected.getBuildNumber(), actual.getBuildNumber() ); assertEquals( "compare build result - end time", expected.getEndTime(), actual.getEndTime() ); assertEquals( "compare build result - error", expected.getError(), actual.getError() ); assertEquals( "compare build result - exit code", expected.getExitCode(), actual.getExitCode() ); assertEquals( "compare build result - start time", expected.getStartTime(), actual.getStartTime() ); assertEquals( "compare build result - state", expected.getState(), actual.getState() ); assertEquals( "compare build result - trigger", expected.getTrigger(), actual.getTrigger() ); } protected static void assertScmResultEquals( ScmResult expected, ScmResult actual ) { assertEquals( "compare SCM result - output", expected.getCommandOutput(), actual.getCommandOutput() ); assertEquals( "compare SCM result - message", expected.getProviderMessage(), actual.getProviderMessage() ); assertEquals( "compare SCM result - success", expected.isSuccess(), actual.isSuccess() ); assertEquals( "compare SCM result - changes size", actual.getChanges().size(), expected.getChanges().size() ); for ( int i = 0; i < actual.getChanges().size(); i++ ) { assertChangeSetEquals( (ChangeSet) expected.getChanges().get( i ), (ChangeSet) actual.getChanges().get( i ) ); } } private static void assertChangeSetEquals( ChangeSet expected, ChangeSet actual ) { assertEquals( "compare change set result - author", expected.getAuthor(), actual.getAuthor() ); assertEquals( "compare change set result - comment", expected.getComment(), actual.getComment() ); //Remove this test, in some case we have a 1ms difference between two dates //assertEquals( "compare change set result - date", changeSet.getDate(), retrievedChangeSet.getDate() ); assertEquals( "compare change set result - files size", expected.getFiles().size(), actual.getFiles().size() ); for ( int i = 0; i < actual.getFiles().size(); i++ ) { assertChangeFileEquals( (ChangeFile) expected.getFiles().get( i ), (ChangeFile) actual.getFiles().get( i ) ); } } private static void assertChangeFileEquals( ChangeFile expected, ChangeFile actual ) { assertEquals( "compare change file result - name", expected.getName(), actual.getName() ); assertEquals( "compare change file result - revision", expected.getRevision(), actual.getRevision() ); } protected static void assertNotifiersEqual( List<ProjectNotifier> expected, List<ProjectNotifier> actual ) { for ( int i = 0; i < actual.size(); i++ ) { assertNotifierEquals( expected.get( i ), actual.get( i ) ); } } protected static void assertNotifierEquals( ProjectNotifier expected, ProjectNotifier actual ) { assertEquals( "compare notifier - recipient type", expected.getRecipientType(), actual.getRecipientType() ); assertEquals( "compare notifier - type", expected.getType(), actual.getType() ); assertEquals( "compare notifier - configuration", expected.getConfiguration(), actual.getConfiguration() ); assertEquals( "compare notifier - send on success", expected.isSendOnSuccess(), actual.isSendOnSuccess() ); assertEquals( "compare notifier - send on failure", expected.isSendOnFailure(), actual.isSendOnFailure() ); assertEquals( "compare notifier - send on error", expected.isSendOnError(), actual.isSendOnError() ); } protected static void assertBuildDefinitionsEqual( List<BuildDefinition> expectedBuildDefinitions, List<BuildDefinition> actualBuildDefinitions ) { for ( int i = 0; i < expectedBuildDefinitions.size(); i++ ) { BuildDefinition expectedBuildDefinition = expectedBuildDefinitions.get( i ); BuildDefinition actualBuildDefinition = actualBuildDefinitions.get( i ); assertBuildDefinitionEquals( expectedBuildDefinition, actualBuildDefinition ); assertScheduleEquals( expectedBuildDefinition.getSchedule(), actualBuildDefinition.getSchedule() ); assertProfileEquals( expectedBuildDefinition.getProfile(), actualBuildDefinition.getProfile() ); } } protected static void assertBuildDefinitionEquals( BuildDefinition expectedBuildDefinition, BuildDefinition actualBuildDefinition ) { assertEquals( "compare build definition - arguments", expectedBuildDefinition.getArguments(), actualBuildDefinition.getArguments() ); assertEquals( "compare build definition - build file", expectedBuildDefinition.getBuildFile(), actualBuildDefinition.getBuildFile() ); assertEquals( "compare build definition - goals", expectedBuildDefinition.getGoals(), actualBuildDefinition.getGoals() ); assertEquals( "compare build definition - build fresh", expectedBuildDefinition.isBuildFresh(), actualBuildDefinition.isBuildFresh() ); assertEquals( "compare build definition - defaultForProject", expectedBuildDefinition.isDefaultForProject(), actualBuildDefinition.isDefaultForProject() ); } protected static void assertDevelopersEqual( List<ProjectDeveloper> expectedDevelopers, List<ProjectDeveloper> actualDevelopers ) { for ( int i = 0; i < actualDevelopers.size(); i++ ) { assertDeveloperEquals( expectedDevelopers.get( i ), actualDevelopers.get( i ) ); } } protected static void assertDeveloperEquals( ProjectDeveloper expectedDeveloper, ProjectDeveloper actualDeveloper ) { assertEquals( "compare developer - name", expectedDeveloper.getName(), actualDeveloper.getName() ); assertEquals( "compare developer - email", expectedDeveloper.getEmail(), actualDeveloper.getEmail() ); assertEquals( "compare developer - scmId", expectedDeveloper.getScmId(), actualDeveloper.getScmId() ); assertEquals( "compare developer - continuumId", expectedDeveloper.getContinuumId(), actualDeveloper.getContinuumId() ); } protected static void assertDependenciesEqual( List<ProjectDependency> expectedDependencies, List<ProjectDependency> actualDependencies ) { for ( int i = 0; i < actualDependencies.size(); i++ ) { assertDependencyEquals( expectedDependencies.get( i ), actualDependencies.get( i ) ); } } protected static void assertDependencyEquals( ProjectDependency expectedDependency, ProjectDependency actualDependency ) { assertEquals( "compare dependency - groupId", expectedDependency.getGroupId(), actualDependency.getGroupId() ); assertEquals( "compare dependency - artifactId", expectedDependency.getArtifactId(), actualDependency.getArtifactId() ); assertEquals( "compare dependency - version", expectedDependency.getVersion(), actualDependency.getVersion() ); } protected static ProjectDependency createTestDependency( ProjectDependency dependency ) { return createTestDependency( dependency.getGroupId(), dependency.getArtifactId(), dependency.getVersion() ); } protected static ProjectDeveloper createTestDeveloper( ProjectDeveloper developer ) { return createTestDeveloper( developer.getContinuumId(), developer.getEmail(), developer.getName(), developer.getScmId() ); } protected static ProjectDependency createTestDependency( String groupId, String artifactId, String version ) { ProjectDependency dependency = new ProjectDependency(); dependency.setArtifactId( artifactId ); dependency.setGroupId( groupId ); dependency.setVersion( version ); return dependency; } protected static ProjectDeveloper createTestDeveloper( int continuumId, String email, String name, String scmId ) { ProjectDeveloper developer = new ProjectDeveloper(); developer.setContinuumId( continuumId ); developer.setEmail( email ); developer.setName( name ); developer.setScmId( scmId ); return developer; } protected static LocalRepository createTestLocalRepository( LocalRepository repository ) { return createTestLocalRepository( repository.getName(), repository.getLocation(), repository.getLayout() ); } protected static LocalRepository createTestLocalRepository( String name, String location, String layout ) { LocalRepository repository = new LocalRepository(); repository.setName( name ); repository.setLocation( location ); repository.setLayout( layout ); return repository; } protected static RepositoryPurgeConfiguration createTestRepositoryPurgeConfiguration( RepositoryPurgeConfiguration purgeConfig ) { return createTestRepositoryPurgeConfiguration( purgeConfig.isDeleteAll(), purgeConfig.getRetentionCount(), purgeConfig.getDaysOlder(), purgeConfig.isDeleteReleasedSnapshots(), purgeConfig.getSchedule(), purgeConfig.isEnabled(), purgeConfig.getRepository() ); } protected static RepositoryPurgeConfiguration createTestRepositoryPurgeConfiguration( boolean deleteAllArtifacts, int retentionCount, int daysOlder, boolean deleteReleasedSnapshots, Schedule schedule, boolean enabled, LocalRepository repository ) { RepositoryPurgeConfiguration purgeConfig = new RepositoryPurgeConfiguration(); purgeConfig.setDeleteAll( deleteAllArtifacts ); purgeConfig.setEnabled( enabled ); purgeConfig.setRetentionCount( retentionCount ); purgeConfig.setDaysOlder( daysOlder ); purgeConfig.setDeleteReleasedSnapshots( deleteReleasedSnapshots ); purgeConfig.setSchedule( schedule ); purgeConfig.setRepository( repository ); return purgeConfig; } protected static DirectoryPurgeConfiguration createTestDirectoryPurgeConfiguration( DirectoryPurgeConfiguration purgeConfig ) { return createTestDirectoryPurgeConfiguration( purgeConfig.getLocation(), purgeConfig.getDirectoryType(), purgeConfig.isDeleteAll(), purgeConfig.getRetentionCount(), purgeConfig.getDaysOlder(), purgeConfig.getSchedule(), purgeConfig.isEnabled() ); } protected static DirectoryPurgeConfiguration createTestDirectoryPurgeConfiguration( String location, String directoryType, boolean deleteAllDirectories, int retentionCount, int daysOlder, Schedule schedule, boolean enabled ) { DirectoryPurgeConfiguration purgeConfig = new DirectoryPurgeConfiguration(); purgeConfig.setDaysOlder( daysOlder ); purgeConfig.setDeleteAll( deleteAllDirectories ); purgeConfig.setDirectoryType( directoryType ); purgeConfig.setEnabled( enabled ); purgeConfig.setLocation( location ); purgeConfig.setRetentionCount( retentionCount ); purgeConfig.setSchedule( schedule ); return purgeConfig; } protected static void assertLocalRepositoryEquals( LocalRepository expectedRepository, LocalRepository actualRepository ) { assertEquals( expectedRepository, actualRepository ); if ( expectedRepository != null ) { assertNotSame( expectedRepository, actualRepository ); assertEquals( "compare local repository - id", expectedRepository.getId(), actualRepository.getId() ); assertEquals( "compare local repository - name", expectedRepository.getName(), actualRepository.getName() ); assertEquals( "compare local repository - location", expectedRepository.getLocation(), actualRepository.getLocation() ); assertEquals( "compare local repository - layout", expectedRepository.getLayout(), actualRepository.getLayout() ); } } protected static void assertRepositoryPurgeConfigurationEquals( RepositoryPurgeConfiguration expectedConfig, RepositoryPurgeConfiguration actualConfig ) { assertEquals( "compare repository purge configuration - id", expectedConfig.getId(), actualConfig.getId() ); assertEquals( "compare repository purge configuration - deleteAll", expectedConfig.isDeleteAll(), actualConfig.isDeleteAll() ); assertEquals( "compare repository purge configuration - retentionCount", expectedConfig.getRetentionCount(), actualConfig.getRetentionCount() ); assertEquals( "compare repository purge configuration - daysOlder", expectedConfig.getDaysOlder(), actualConfig.getDaysOlder() ); assertEquals( "compare repository purge configuration - deleteReleasedSnapshots", expectedConfig.isDeleteReleasedSnapshots(), actualConfig.isDeleteReleasedSnapshots() ); assertEquals( "compare repository purge configuration - enabled", expectedConfig.isEnabled(), actualConfig.isEnabled() ); } protected static void assertDirectoryPurgeConfigurationEquals( DirectoryPurgeConfiguration expectedConfig, DirectoryPurgeConfiguration actualConfig ) { assertEquals( "compare directory purge configuration - id", expectedConfig.getId(), actualConfig.getId() ); assertEquals( "compare directory purge configuration - location", expectedConfig.getLocation(), actualConfig.getLocation() ); assertEquals( "compare directory purge configuration - directoryType", expectedConfig.getDirectoryType(), actualConfig.getDirectoryType() ); assertEquals( "compare directory purge configuration - deleteAll", expectedConfig.isDeleteAll(), actualConfig.isDeleteAll() ); assertEquals( "compare directory purge configuration - retentionCount", expectedConfig.getRetentionCount(), actualConfig.getRetentionCount() ); assertEquals( "compare directory purge configuration - daysOlder", expectedConfig.getDaysOlder(), actualConfig.getDaysOlder() ); assertEquals( "compare directory purge configuration - enabled", expectedConfig.isEnabled(), actualConfig.isEnabled() ); } protected static ProjectScmRoot createTestProjectScmRoot( String scmRootAddress, int state, int oldState, String error, ProjectGroup group ) { ProjectScmRoot projectScmRoot = new ProjectScmRoot(); projectScmRoot.setScmRootAddress( scmRootAddress ); projectScmRoot.setState( state ); projectScmRoot.setOldState( oldState ); projectScmRoot.setError( error ); projectScmRoot.setProjectGroup( group ); return projectScmRoot; } protected static ProjectScmRoot createTestProjectScmRoot( ProjectScmRoot scmRoot ) { return createTestProjectScmRoot( scmRoot.getScmRootAddress(), scmRoot.getState(), scmRoot.getOldState(), scmRoot.getError(), scmRoot.getProjectGroup() ); } protected static void assertProjectScmRootEquals( ProjectScmRoot expectedConfig, ProjectScmRoot actualConfig ) { assertEquals( "compare project scm root - id", expectedConfig.getId(), actualConfig.getId() ); assertEquals( "compare project scm root - scmUrl", expectedConfig.getScmRootAddress(), actualConfig.getScmRootAddress() ); assertEquals( "compare project scm root - state", expectedConfig.getState(), actualConfig.getState() ); assertEquals( "compare project scm root - oldState", expectedConfig.getOldState(), actualConfig.getOldState() ); assertEquals( "compare project scm root - error", expectedConfig.getError(), actualConfig.getError() ); } protected static ContinuumReleaseResult createTestContinuumReleaseResult( ProjectGroup group, Project project, String releaseGoal, int resultCode, long startTime, long endTime ) { ContinuumReleaseResult releaseResult = new ContinuumReleaseResult(); releaseResult.setProjectGroup( group ); releaseResult.setProject( project ); releaseResult.setReleaseGoal( releaseGoal ); releaseResult.setResultCode( resultCode ); releaseResult.setStartTime( startTime ); releaseResult.setEndTime( endTime ); return releaseResult; } protected static ContinuumReleaseResult createTestContinuumReleaseResult( ContinuumReleaseResult releaseResult ) { return createTestContinuumReleaseResult( releaseResult.getProjectGroup(), releaseResult.getProject(), releaseResult.getReleaseGoal(), releaseResult.getResultCode(), releaseResult.getStartTime(), releaseResult.getEndTime() ); } protected static void assertReleaseResultEquals( ContinuumReleaseResult expectedConfig, ContinuumReleaseResult actualConfig ) { assertEquals( "compare continuum release result - id", expectedConfig.getId(), actualConfig.getId() ); assertEquals( "compare continuum release result - releaseGoal", expectedConfig.getReleaseGoal(), actualConfig.getReleaseGoal() ); assertEquals( "compare continuum release result - resultCode", expectedConfig.getResultCode(), actualConfig.getResultCode() ); assertEquals( "compare continuum release result - startTime", expectedConfig.getStartTime(), actualConfig.getStartTime() ); assertEquals( "compare continuum release result - endTime", expectedConfig.getEndTime(), actualConfig.getEndTime() ); } protected static BuildQueue createTestBuildQueue( String name ) { BuildQueue buildQueue = new BuildQueue(); buildQueue.setName( name ); return buildQueue; } protected static BuildQueue createTestBuildQueue( BuildQueue buildQueue ) { return createTestBuildQueue( buildQueue.getName() ); } protected static void assertBuildQueueEquals( BuildQueue expectedConfig, BuildQueue actualConfig ) { assertEquals( "compare build queue - id", expectedConfig.getId(), actualConfig.getId() ); assertEquals( "compare build queue - name", expectedConfig.getName(), actualConfig.getName() ); } protected static BuildDefinitionTemplate createTestBuildDefinitionTemplate( String name, String type, boolean continuumDefault ) { BuildDefinitionTemplate template = new BuildDefinitionTemplate(); template.setName( name ); template.setType( type ); template.setContinuumDefault( continuumDefault ); return template; } /** * Setup JDO Factory * * @todo push down to a Jdo specific test */ protected void createStore() throws Exception { DefaultConfigurableJdoFactory jdoFactory = (DefaultConfigurableJdoFactory) lookup( JdoFactory.ROLE, "continuum" ); jdoFactory.setUrl( "jdbc:hsqldb:mem:" + getName() ); daoUtilsImpl = (DaoUtils) lookup( DaoUtils.class.getName() ); } }
5,192
0
Create_ds/continuum/continuum-store/src/main/java/org/apache/continuum
Create_ds/continuum/continuum-store/src/main/java/org/apache/continuum/dao/BuildDefinitionDaoImpl.java
package org.apache.continuum.dao; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.maven.continuum.execution.ContinuumBuildExecutorConstants; import org.apache.maven.continuum.model.project.BuildDefinition; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.model.project.ProjectGroup; import org.apache.maven.continuum.store.ContinuumObjectNotFoundException; import org.apache.maven.continuum.store.ContinuumStoreException; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.util.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Repository; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.jdo.Extent; import javax.jdo.PersistenceManager; import javax.jdo.Query; import javax.jdo.Transaction; /** * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a> */ @Repository( "buildDefinitionDao" ) @Component( role = org.apache.continuum.dao.BuildDefinitionDao.class ) public class BuildDefinitionDaoImpl extends AbstractDao implements BuildDefinitionDao { private static final Logger log = LoggerFactory.getLogger( BuildDefinitionDaoImpl.class ); @Resource @Requirement( role = org.apache.continuum.dao.ProjectDao.class ) private ProjectDao projectDao; @Resource @Requirement( role = org.apache.continuum.dao.ProjectGroupDao.class ) private ProjectGroupDao projectGroupDao; public BuildDefinition getBuildDefinition( int buildDefinitionId ) throws ContinuumStoreException { return getObjectById( BuildDefinition.class, buildDefinitionId ); } public void removeBuildDefinition( BuildDefinition buildDefinition ) throws ContinuumStoreException { removeObject( buildDefinition ); } public BuildDefinition storeBuildDefinition( BuildDefinition buildDefinition ) throws ContinuumStoreException { updateObject( buildDefinition ); return buildDefinition; } public BuildDefinition addBuildDefinition( BuildDefinition buildDefinition ) throws ContinuumStoreException { return addObject( buildDefinition ); } public List<BuildDefinition> getAllBuildDefinitions() throws ContinuumStoreException { PersistenceManager pm = getPersistenceManager(); Transaction tx = pm.currentTransaction(); try { tx.begin(); Extent extent = pm.getExtent( BuildDefinition.class, true ); Query query = pm.newQuery( extent ); List result = (List) query.execute(); return result == null ? Collections.EMPTY_LIST : (List<BuildDefinition>) pm.detachCopyAll( result ); } finally { tx.commit(); rollback( tx ); } } public Map<Integer, Integer> getDefaultBuildDefinitions() { PersistenceManager pm = getPersistenceManager(); Transaction tx = pm.currentTransaction(); try { tx.begin(); Extent extent = pm.getExtent( Project.class, true ); Query query = pm.newQuery( extent ); query.declareImports( "import org.apache.maven.continuum.model.project.BuildDefinition" ); query.setFilter( "this.buildDefinitions.contains(buildDef) && buildDef.defaultForProject == true" ); query.declareVariables( "BuildDefinition buildDef" ); query.setResult( "this.id, buildDef.id" ); List result = (List) query.execute(); // result = (List) pm.detachCopyAll( result ); Map<Integer, Integer> builds = new HashMap<Integer, Integer>(); if ( result != null && !result.isEmpty() ) { for ( Object aResult : result ) { Object[] obj = (Object[]) aResult; builds.put( (Integer) obj[0], (Integer) obj[1] ); } return builds; } } finally { tx.commit(); rollback( tx ); } return null; } public List<BuildDefinition> getDefaultBuildDefinitionsForProjectGroup( int projectGroupId ) throws ContinuumStoreException { PersistenceManager pm = getPersistenceManager(); Transaction tx = pm.currentTransaction(); try { tx.begin(); Extent extent = pm.getExtent( ProjectGroup.class, true ); Query query = pm.newQuery( extent ); query.declareImports( "import " + BuildDefinition.class.getName() ); query.declareParameters( "int projectGroupId" ); query.setFilter( "this.id == projectGroupId && this.buildDefinitions.contains(buildDef) && buildDef.defaultForProject == true" ); query.declareVariables( "BuildDefinition buildDef" ); query.setResult( "buildDef" ); List<BuildDefinition> result = (List<BuildDefinition>) query.execute( projectGroupId ); result = (List<BuildDefinition>) pm.detachCopyAll( result ); tx.commit(); if ( result != null ) { return result; } } finally { rollback( tx ); } return new ArrayList<BuildDefinition>(); } public List<BuildDefinition> getDefaultBuildDefinitionsForProjectGroup( ProjectGroup projectGroup ) throws ContinuumStoreException { return getDefaultBuildDefinitionsForProjectGroup( projectGroup.getId() ); } public BuildDefinition getDefaultBuildDefinitionForProject( int projectId ) throws ContinuumStoreException { PersistenceManager pm = getPersistenceManager(); Transaction tx = pm.currentTransaction(); try { tx.begin(); Extent extent = pm.getExtent( BuildDefinition.class, true ); Query query = pm.newQuery( extent ); query.declareImports( "import " + Project.class.getName() ); query.declareParameters( "int projectId" ); query.setFilter( "project.id == projectId && project.buildDefinitions.contains(this) && this.defaultForProject == true" ); query.declareVariables( "Project project" ); query.setResult( "this" ); List<BuildDefinition> result = (List<BuildDefinition>) query.execute( projectId ); result = (List<BuildDefinition>) pm.detachCopyAll( result ); tx.commit(); if ( result != null && !result.isEmpty() ) { return result.get( 0 ); } } finally { rollback( tx ); } throw new ContinuumObjectNotFoundException( "no default build definition declared for project " + projectId ); } public BuildDefinition getDefaultBuildDefinitionForProject( Project project ) throws ContinuumStoreException { return getDefaultBuildDefinitionForProject( project.getId() ); } public BuildDefinition getDefaultBuildDefinition( int projectId ) throws ContinuumStoreException { //TODO: Move this method to a service class BuildDefinition bd = null; try { bd = getDefaultBuildDefinitionForProject( projectId ); } catch ( ContinuumObjectNotFoundException cne ) { // ignore since we will try the project group log.debug( "no default build definition on project, trying project group" ); } // project group should have default build definition defined if ( bd == null ) { ProjectGroup projectGroup = projectGroupDao.getProjectGroupByProjectId( projectId ); Project p = projectDao.getProject( projectId ); List<BuildDefinition> bds = getDefaultBuildDefinitionsForProjectGroup( projectGroup.getId() ); for ( BuildDefinition bdef : bds ) { if ( p.getExecutorId().equals( bdef.getType() ) || ( StringUtils.isEmpty( bdef.getType() ) && ContinuumBuildExecutorConstants.MAVEN_TWO_BUILD_EXECUTOR.equals( p.getExecutorId() ) ) ) { return bdef; } } } return bd; } public List<BuildDefinition> getAllTemplates() throws ContinuumStoreException { PersistenceManager pm = getPersistenceManager(); Transaction tx = pm.currentTransaction(); try { tx.begin(); Extent extent = pm.getExtent( BuildDefinition.class, true ); Query query = pm.newQuery( extent ); query.setFilter( "this.template == true" ); List result = (List) query.execute(); return result == null ? Collections.EMPTY_LIST : (List) pm.detachCopyAll( result ); } finally { tx.commit(); rollback( tx ); } } public List<BuildDefinition> getBuildDefinitionsBySchedule( int scheduleId ) { PersistenceManager pm = getPersistenceManager(); Transaction tx = pm.currentTransaction(); try { tx.begin(); Extent extent = pm.getExtent( BuildDefinition.class, true ); Query query = pm.newQuery( extent ); query.declareParameters( "int scheduleId" ); query.setFilter( "this.schedule.id == scheduleId" ); List result = (List) query.execute( scheduleId ); return result == null ? Collections.EMPTY_LIST : (List) pm.detachCopyAll( result ); } finally { tx.commit(); rollback( tx ); } } }
5,193
0
Create_ds/continuum/continuum-store/src/main/java/org/apache/continuum
Create_ds/continuum/continuum-store/src/main/java/org/apache/continuum/dao/ProjectGroupDaoImpl.java
package org.apache.continuum.dao; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.maven.continuum.model.project.BuildDefinition; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.model.project.ProjectGroup; import org.apache.maven.continuum.store.ContinuumObjectNotFoundException; import org.apache.maven.continuum.store.ContinuumStoreException; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.jdo.PlexusJdoUtils; import org.springframework.stereotype.Repository; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import javax.annotation.Resource; import javax.jdo.Extent; import javax.jdo.PersistenceManager; import javax.jdo.Query; import javax.jdo.Transaction; /** * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a> */ @Repository( "projectGroupDao" ) @Component( role = org.apache.continuum.dao.ProjectGroupDao.class ) public class ProjectGroupDaoImpl extends AbstractDao implements ProjectGroupDao { @Resource @Requirement( role = org.apache.continuum.dao.ProjectDao.class ) private ProjectDao projectDao; public ProjectGroup addProjectGroup( ProjectGroup group ) { return addObject( group ); } public void removeProjectGroup( ProjectGroup projectGroup ) { ProjectGroup pg = null; try { pg = getProjectGroupWithBuildDetailsByProjectGroupId( projectGroup.getId() ); } catch ( Exception e ) { // Do nothing } if ( pg != null ) { // TODO: why do we need to do this? if not - build results are not // removed and a integrity constraint is violated. I assume its // because of the fetch groups for ( Project p : (List<Project>) pg.getProjects() ) { projectDao.removeProject( p ); } List<BuildDefinition> buildDefs = new ArrayList<BuildDefinition>(); Iterator<BuildDefinition> it = pg.getBuildDefinitions().listIterator(); boolean template = false; while ( it.hasNext() ) { BuildDefinition bd = it.next(); if ( bd.isTemplate() ) { template = true; } else { buildDefs.add( bd ); } } if ( template ) { try { pg.setBuildDefinitions( buildDefs ); updateProjectGroup( pg ); } catch ( ContinuumStoreException e ) { // Do nothing } } removeObject( pg ); } } public ProjectGroup getProjectGroup( int projectGroupId ) throws ContinuumStoreException { return getObjectById( ProjectGroup.class, projectGroupId ); } public ProjectGroup getProjectGroupByGroupId( String groupId ) throws ContinuumStoreException { return getObjectFromQuery( ProjectGroup.class, "groupId", groupId, null ); } public ProjectGroup getProjectGroupByGroupIdWithBuildDetails( String groupId ) throws ContinuumStoreException { return getObjectFromQuery( ProjectGroup.class, "groupId", groupId, PROJECT_BUILD_DETAILS_FETCH_GROUP ); } public ProjectGroup getProjectGroupByGroupIdWithProjects( String groupId ) throws ContinuumStoreException { return getObjectFromQuery( ProjectGroup.class, "groupId", groupId, PROJECTGROUP_PROJECTS_FETCH_GROUP ); } public ProjectGroup getProjectGroupByProjectId( int projectId ) throws ContinuumObjectNotFoundException { try { return projectDao.getProject( projectId ).getProjectGroup(); } catch ( ContinuumStoreException e ) { throw new ContinuumObjectNotFoundException( "unable to find project group containing project with id: " + projectId ); } } public ProjectGroup getProjectGroupByProject( Project project ) throws ContinuumObjectNotFoundException { return getProjectGroupByProjectId( project.getId() ); } public void updateProjectGroup( ProjectGroup group ) throws ContinuumStoreException { updateObject( group ); } public ProjectGroup getProjectGroupWithProjects( int projectGroupId ) throws ContinuumStoreException { return getObjectById( ProjectGroup.class, projectGroupId, PROJECTGROUP_PROJECTS_FETCH_GROUP ); } public Collection<ProjectGroup> getAllProjectGroupsWithProjects() { return getAllObjectsDetached( ProjectGroup.class, "name ascending", PROJECTGROUP_PROJECTS_FETCH_GROUP ); } public List<ProjectGroup> getAllProjectGroupsWithBuildDetails() { return getAllObjectsDetached( ProjectGroup.class, "name ascending", PROJECT_BUILD_DETAILS_FETCH_GROUP ); } public List<ProjectGroup> getAllProjectGroups() { return getAllObjectsDetached( ProjectGroup.class, "name ascending", null ); } public List<ProjectGroup> getAllProjectGroupsWithTheLot() { List fetchGroups = Arrays.asList( new String[] { PROJECT_WITH_BUILDS_FETCH_GROUP, PROJECTGROUP_PROJECTS_FETCH_GROUP, BUILD_RESULT_WITH_DETAILS_FETCH_GROUP, PROJECT_WITH_CHECKOUT_RESULT_FETCH_GROUP, PROJECT_ALL_DETAILS_FETCH_GROUP, PROJECT_BUILD_DETAILS_FETCH_GROUP } ); return PlexusJdoUtils.getAllObjectsDetached( getPersistenceManager(), ProjectGroup.class, "name ascending", fetchGroups ); } public ProjectGroup getProjectGroupWithBuildDetailsByProjectGroupId( int projectGroupId ) throws ContinuumStoreException { return getObjectById( ProjectGroup.class, projectGroupId, PROJECT_BUILD_DETAILS_FETCH_GROUP ); } public List<ProjectGroup> getProjectGroupByRepository( int repositoryId ) { PersistenceManager pm = getPersistenceManager(); Transaction tx = pm.currentTransaction(); try { tx.begin(); Extent extent = pm.getExtent( ProjectGroup.class, true ); Query query = pm.newQuery( extent ); query.declareParameters( "int repositoryId" ); query.setFilter( "this.localRepository.id == repositoryId" ); List result = (List) query.execute( repositoryId ); return result == null ? Collections.EMPTY_LIST : (List) pm.detachCopyAll( result ); } finally { tx.commit(); rollback( tx ); } } }
5,194
0
Create_ds/continuum/continuum-store/src/main/java/org/apache/continuum
Create_ds/continuum/continuum-store/src/main/java/org/apache/continuum/dao/StoreUtilities.java
package org.apache.continuum.dao; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.jdo.JdoFactory; import org.springframework.stereotype.Service; import javax.annotation.Resource; import javax.jdo.PersistenceManagerFactory; /** * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a> */ @Service( "storeUtilities" ) @Component( role = org.apache.continuum.dao.StoreUtilities.class ) public class StoreUtilities { @Resource( name = "jdoFactory#continuum" ) @Requirement( hint = "continuum" ) private JdoFactory continuumJdoFactory; private PersistenceManagerFactory continuumPersistenceManagerFactory; public PersistenceManagerFactory getContinuumPersistenceManagerFactory() { if ( continuumPersistenceManagerFactory == null ) { buildFactory(); } return continuumPersistenceManagerFactory; } /** * Useful when reconfiguring the {@link JdoFactory} since it is cached. Caller should ensure existing * {@link PersistenceManagerFactory} is gracefully torn down since this simply replaces its reference with a newly * configured one. */ public void buildFactory() { continuumPersistenceManagerFactory = continuumJdoFactory.getPersistenceManagerFactory(); } }
5,195
0
Create_ds/continuum/continuum-store/src/main/java/org/apache/continuum
Create_ds/continuum/continuum-store/src/main/java/org/apache/continuum/dao/SystemConfigurationDaoImpl.java
package org.apache.continuum.dao; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.maven.continuum.model.system.SystemConfiguration; import org.apache.maven.continuum.store.ContinuumStoreException; import org.codehaus.plexus.component.annotations.Component; import org.springframework.stereotype.Repository; import java.util.List; /** * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a> */ @Repository( "systemConfigurationDao" ) @Component( role = org.apache.continuum.dao.SystemConfigurationDao.class ) public class SystemConfigurationDaoImpl extends AbstractDao implements SystemConfigurationDao { public SystemConfiguration addSystemConfiguration( SystemConfiguration systemConf ) { return addObject( systemConf ); } public void updateSystemConfiguration( SystemConfiguration systemConf ) throws ContinuumStoreException { updateObject( systemConf ); } public SystemConfiguration getSystemConfiguration() throws ContinuumStoreException { List systemConfs = getAllObjectsDetached( SystemConfiguration.class ); if ( systemConfs == null || systemConfs.isEmpty() ) { return null; } else if ( systemConfs.size() > 1 ) { throw new ContinuumStoreException( "Database is corrupted. There are more than one systemConfiguration object." ); } else { return (SystemConfiguration) systemConfs.get( 0 ); } } }
5,196
0
Create_ds/continuum/continuum-store/src/main/java/org/apache/continuum
Create_ds/continuum/continuum-store/src/main/java/org/apache/continuum/dao/BuildResultDaoImpl.java
package org.apache.continuum.dao; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.maven.continuum.model.project.BuildResult; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.project.ContinuumProjectState; import org.apache.maven.continuum.store.ContinuumStoreException; import org.codehaus.plexus.component.annotations.Component; import org.springframework.stereotype.Repository; import javax.jdo.Extent; import javax.jdo.JDOHelper; import javax.jdo.PersistenceManager; import javax.jdo.Query; import javax.jdo.Transaction; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import static org.apache.maven.continuum.project.ContinuumProjectState.BUILDING; import static org.apache.maven.continuum.project.ContinuumProjectState.CANCELLED; /** * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a> */ @Repository( "buildResultDao" ) @Component( role = org.apache.continuum.dao.BuildResultDao.class ) public class BuildResultDaoImpl extends AbstractDao implements BuildResultDao { public void updateBuildResult( BuildResult build ) throws ContinuumStoreException { PersistenceManager pm = getPersistenceManager(); Transaction tx = pm.currentTransaction(); Project project = build.getProject(); try { tx.begin(); if ( !JDOHelper.isDetached( build ) ) { throw new ContinuumStoreException( "Not detached: " + build ); } pm.makePersistent( build ); if ( !JDOHelper.isDetached( project ) ) { throw new ContinuumStoreException( "Not detached: " + project ); } project.setState( build.getState() ); //TODO: Use projectDao pm.makePersistent( project ); tx.commit(); } finally { rollback( tx ); } } public void addBuildResult( Project project, BuildResult build ) throws ContinuumStoreException { PersistenceManager pm = getPersistenceManager(); Transaction tx = pm.currentTransaction(); try { tx.begin(); pm.getFetchPlan().addGroup( PROJECT_WITH_BUILDS_FETCH_GROUP ); Object objectId = pm.newObjectIdInstance( Project.class, project.getId() ); project = (Project) pm.getObjectById( objectId ); build = makePersistent( pm, build, false ); // TODO: these are in the wrong spot - set them on success (though // currently some depend on latest build being the one in progress) project.setLatestBuildId( build.getId() ); project.setState( build.getState() ); project.addBuildResult( build ); tx.commit(); } finally { rollback( tx ); } } public BuildResult getLatestBuildResultForProject( int projectId ) { PersistenceManager pm = getPersistenceManager(); Transaction tx = pm.currentTransaction(); try { tx.begin(); Extent extent = pm.getExtent( BuildResult.class, true ); Query query = pm.newQuery( extent ); query.declareParameters( "int projectId" ); query.setFilter( "this.project.id == projectId && this.project.latestBuildId == this.id" ); List<BuildResult> result = (List<BuildResult>) query.execute( projectId ); result = (List<BuildResult>) pm.detachCopyAll( result ); tx.commit(); if ( result != null && !result.isEmpty() ) { return result.get( 0 ); } } finally { rollback( tx ); } return null; } public BuildResult getLatestBuildResultForProjectWithDetails( int projectId ) { PersistenceManager pm = getPersistenceManager(); Transaction tx = pm.currentTransaction(); try { tx.begin(); pm.getFetchPlan().addGroup( BUILD_RESULT_WITH_DETAILS_FETCH_GROUP ); Extent extent = pm.getExtent( BuildResult.class, true ); Query query = pm.newQuery( extent ); query.declareParameters( "int projectId" ); query.setFilter( "this.project.id == projectId && this.project.latestBuildId == this.id" ); List<BuildResult> result = (List<BuildResult>) query.execute( projectId ); result = (List<BuildResult>) pm.detachCopyAll( result ); tx.commit(); if ( result != null && !result.isEmpty() ) { return result.get( 0 ); } } finally { rollback( tx ); } return null; } public BuildResult getLatestBuildResultForBuildDefinition( int projectId, int buildDefinitionId ) { PersistenceManager pm = getPersistenceManager(); Transaction tx = pm.currentTransaction(); try { tx.begin(); Extent extent = pm.getExtent( BuildResult.class, true ); Query query = pm.newQuery( extent ); query.declareParameters( "int projectId, int buildDefinitionId" ); query.setFilter( "this.project.id == projectId && this.buildDefinition.id == buildDefinitionId" ); query.setRange( 0, 1 ); query.setOrdering( "this.id descending" ); Object[] params = new Object[2]; params[0] = projectId; params[1] = buildDefinitionId; List<BuildResult> result = (List<BuildResult>) query.executeWithArray( params ); result = (List<BuildResult>) pm.detachCopyAll( result ); tx.commit(); if ( result != null && !result.isEmpty() ) { return result.get( 0 ); } } finally { rollback( tx ); } return null; } public BuildResult getPreviousBuildResultForBuildDefinition( int projectId, int buildDefinitionId, int buildResultId ) { PersistenceManager pm = getPersistenceManager(); Transaction tx = pm.currentTransaction(); try { tx.begin(); Extent extent = pm.getExtent( BuildResult.class, true ); Query query = pm.newQuery( extent ); query.declareParameters( "int projectId, int buildDefinitionId, int buildResultId" ); query.setFilter( "this.project.id == projectId && this.buildDefinition.id == buildDefinitionId " + "&& this.id < buildResultId" ); query.setRange( 0, 1 ); query.setOrdering( "this.id descending" ); Object[] params = new Object[3]; params[0] = projectId; params[1] = buildDefinitionId; params[2] = buildResultId; List<BuildResult> result = (List<BuildResult>) query.executeWithArray( params ); result = (List<BuildResult>) pm.detachCopyAll( result ); tx.commit(); if ( result != null && !result.isEmpty() ) { return result.get( 0 ); } } finally { rollback( tx ); } return null; } public Map<Integer, BuildResult> getLatestBuildResultsByProjectGroupId( int projectGroupId ) { PersistenceManager pm = getPersistenceManager(); Transaction tx = pm.currentTransaction(); try { tx.begin(); Extent extent = pm.getExtent( BuildResult.class, true ); Query query = pm.newQuery( extent ); String filter = "this.project.latestBuildId == this.id"; if ( projectGroupId > 0 ) { query.declareParameters( "int projectGroupId" ); filter += " && this.project.projectGroup.id == projectGroupId"; } query.setFilter( filter ); List<BuildResult> result; if ( projectGroupId > 0 ) { result = (List<BuildResult>) query.execute( projectGroupId ); } else { result = (List<BuildResult>) query.execute(); } result = (List<BuildResult>) pm.detachCopyAll( result ); tx.commit(); if ( result != null && !result.isEmpty() ) { Map<Integer, BuildResult> builds = new HashMap<Integer, BuildResult>(); for ( BuildResult br : result ) { builds.put( br.getProject().getId(), br ); } return builds; } } finally { rollback( tx ); } return null; } public void removeBuildResult( BuildResult buildResult ) { removeObject( buildResult ); } public List<BuildResult> getAllBuildsForAProjectByDate( int projectId ) { PersistenceManager pm = getPersistenceManager(); Transaction tx = pm.currentTransaction(); try { tx.begin(); Query query = pm.newQuery( "SELECT FROM " + BuildResult.class.getName() + " WHERE project.id == projectId PARAMETERS int projectId ORDER BY endTime DESC" ); query.declareImports( "import java.lang.Integer" ); query.declareParameters( "Integer projectId" ); List<BuildResult> result = (List<BuildResult>) query.execute( projectId ); result = (List<BuildResult>) pm.detachCopyAll( result ); tx.commit(); return result; } finally { rollback( tx ); } } public BuildResult getBuildResult( int buildId ) throws ContinuumStoreException { return getObjectById( BuildResult.class, buildId, BUILD_RESULT_WITH_DETAILS_FETCH_GROUP ); } public List<BuildResult> getBuildResultsByBuildDefinition( int projectId, int buildDefinitionId ) { return getBuildResultsByBuildDefinition( projectId, buildDefinitionId, -1, -1 ); } public List<BuildResult> getBuildResultsByBuildDefinition( int projectId, int buildDefinitionId, long startIndex, long endIndex ) { PersistenceManager pm = getPersistenceManager(); Transaction tx = pm.currentTransaction(); try { tx.begin(); Extent extent = pm.getExtent( BuildResult.class, true ); Query query = pm.newQuery( extent ); if ( startIndex >= 0 && endIndex >= 0 ) { query.setRange( startIndex, endIndex ); } query.declareParameters( "int projectId, int buildDefinitionId" ); query.setFilter( "this.project.id == projectId && this.buildDefinition.id == buildDefinitionId" ); query.setOrdering( "this.id descending" ); List<BuildResult> result = (List<BuildResult>) query.execute( projectId, buildDefinitionId ); result = (List<BuildResult>) pm.detachCopyAll( result ); tx.commit(); return result; } finally { rollback( tx ); } } public long getNbBuildResultsForProject( int projectId ) { PersistenceManager pm = getPersistenceManager(); Transaction tx = pm.currentTransaction(); try { tx.begin(); Query query = pm.newQuery( BuildResult.class, "project.id == projectId" ); query.declareParameters( "int projectId" ); query.setResult( "count(this)" ); long result = (Long) query.execute( projectId ); tx.commit(); return result; } finally { rollback( tx ); } } public long getNbBuildResultsInSuccessForProject( int projectId, long fromDate ) { PersistenceManager pm = getPersistenceManager(); Transaction tx = pm.currentTransaction(); try { tx.begin(); Extent extent = pm.getExtent( BuildResult.class, true ); Query query = pm.newQuery( extent ); query.declareParameters( "int projectId, long fromDate, int state" ); query.setFilter( "this.project.id == projectId && this.startTime > fromDate && this.state == state" ); query.setResult( "count(this)" ); long result = (Long) query.execute( projectId, fromDate, ContinuumProjectState.OK ); tx.commit(); return result; } finally { rollback( tx ); } } public List<BuildResult> getBuildResultsForProjectWithDetails( int projectId, int fromResultId, int toResultId ) { PersistenceManager pm = getPersistenceManager(); Transaction tx = pm.currentTransaction(); try { tx.begin(); Extent extent = pm.getExtent( BuildResult.class, true ); pm.getFetchPlan().addGroup( BUILD_RESULT_WITH_DETAILS_FETCH_GROUP ); Query query = pm.newQuery( extent ); String parameters = "int projectId, int fromResultId"; String filter = "this.project.id == projectId && this.id > fromResultId"; if ( toResultId > 0 ) { parameters += ", int toResultId"; filter += " && this.id < toResultId"; } query.declareParameters( parameters ); query.setFilter( filter ); query.setOrdering( "this.id ascending" ); List<BuildResult> result; if ( toResultId > 0 ) { result = (List<BuildResult>) query.execute( projectId, fromResultId, toResultId ); } else { result = (List<BuildResult>) query.execute( projectId, fromResultId ); } result = (List<BuildResult>) pm.detachCopyAll( result ); tx.commit(); return result; } finally { rollback( tx ); } } public List<BuildResult> getBuildResultsForProject( int projectId, long startIndex, long endIndex, boolean fullDetails ) { PersistenceManager pm = getPersistenceManager(); Transaction tx = pm.currentTransaction(); try { tx.begin(); Extent extent = pm.getExtent( BuildResult.class, true ); if ( fullDetails ) { pm.getFetchPlan().addGroup( BUILD_RESULT_WITH_DETAILS_FETCH_GROUP ); } Query query = pm.newQuery( extent ); query.declareParameters( "int projectId" ); query.setFilter( "this.project.id == projectId" ); query.setOrdering( "this.id descending" ); query.setRange( startIndex, endIndex ); List<BuildResult> result = (List<BuildResult>) query.execute( projectId ); result = (List<BuildResult>) pm.detachCopyAll( result ); tx.commit(); return result; } finally { rollback( tx ); } } public List<BuildResult> getBuildResultsForProjectFromId( int projectId, long startId ) throws ContinuumStoreException { PersistenceManager pm = getPersistenceManager(); Transaction tx = pm.currentTransaction(); pm.getFetchPlan().addGroup( BUILD_RESULT_WITH_DETAILS_FETCH_GROUP ); try { tx.begin(); Extent extent = pm.getExtent( BuildResult.class, true ); Query query = pm.newQuery( extent ); query.declareParameters( "int projectId, int buildNumber" ); query.setFilter( "this.project.id == projectId && this.buildNumber >= buildNumber" ); query.setOrdering( "this.startTime descending" ); List<BuildResult> result = (List<BuildResult>) query.execute( projectId, startId ); result = (List<BuildResult>) pm.detachCopyAll( result ); tx.commit(); return result; } catch ( Exception e ) { throw new ContinuumStoreException( e.getMessage(), e ); } finally { rollback( tx ); } } public BuildResult getLatestBuildResultInSuccess( int projectId ) { PersistenceManager pm = getPersistenceManager(); Transaction tx = pm.currentTransaction(); try { tx.begin(); Extent extent = pm.getExtent( BuildResult.class, true ); Query query = pm.newQuery( extent ); query.declareParameters( "int projectId" ); String filter = "this.project.buildNumber == this.buildNumber && this.project.id == projectId"; query.setFilter( filter ); query.setUnique( true ); BuildResult result = (BuildResult) query.execute( projectId ); result = (BuildResult) pm.detachCopy( result ); tx.commit(); return result; } finally { rollback( tx ); } } public Set<Integer> resolveOrphanedInProgressResults( long ageCutoff ) throws ContinuumStoreException { PersistenceManager pm = getPersistenceManager(); Transaction tx = pm.currentTransaction(); try { tx.begin(); Query query = pm.newQuery( BuildResult.class ); query.declareParameters( "long orphanCutoff" ); String filter = String.format( " this.state == %s && this.startTime < orphanCutoff", BUILDING ); query.setFilter( filter ); List<BuildResult> orphans = (List<BuildResult>) pm.detachCopyAll( (List) query.execute( ageCutoff ) ); Set<Integer> updatedIds = new HashSet<Integer>(); for ( BuildResult orphan : orphans ) { if ( updatedIds.contains( orphan.getId() ) ) continue; orphan.setState( CANCELLED ); orphan.setError( "Build appears to have been orphaned, final status is unknown." ); orphan.setEndTime( System.currentTimeMillis() ); updateObject( orphan ); updatedIds.add( orphan.getId() ); } tx.commit(); return updatedIds; } finally { rollback( tx ); } } public BuildResult getPreviousBuildResultInSuccess( int projectId, int buildResultId ) { PersistenceManager pm = getPersistenceManager(); Transaction tx = pm.currentTransaction(); try { tx.begin(); Extent extent = pm.getExtent( BuildResult.class, true ); Query query = pm.newQuery( extent ); query.declareParameters( "int projectId, int buildResultId" ); String filter = "this.project.id == projectId" + " && this.state == " + ContinuumProjectState.OK + " && this.id < buildResultId"; query.setFilter( filter ); query.setOrdering( "this.id descending" ); query.setRange( 0, 1 ); List<BuildResult> results = (List<BuildResult>) query.execute( projectId, buildResultId ); tx.commit(); return results.size() > 0 ? results.get( 0 ) : null; } finally { rollback( tx ); } } public Map<Integer, BuildResult> getBuildResultsInSuccessByProjectGroupId( int projectGroupId ) { PersistenceManager pm = getPersistenceManager(); Transaction tx = pm.currentTransaction(); try { tx.begin(); Extent extent = pm.getExtent( BuildResult.class, true ); Query query = pm.newQuery( extent ); String filter = "this.project.buildNumber == this.buildNumber"; if ( projectGroupId > 0 ) { query.declareParameters( "int projectGroupId" ); filter += " && this.project.projectGroup.id == projectGroupId"; } query.setFilter( filter ); List<BuildResult> result; if ( projectGroupId > 0 ) { result = (List<BuildResult>) query.execute( projectGroupId ); } else { result = (List<BuildResult>) query.execute(); } result = (List<BuildResult>) pm.detachCopyAll( result ); tx.commit(); if ( result != null && !result.isEmpty() ) { Map<Integer, BuildResult> builds = new HashMap<Integer, BuildResult>(); for ( BuildResult br : result ) { builds.put( br.getProject().getId(), br ); } return builds; } } finally { rollback( tx ); } return null; } public List<BuildResult> getBuildResultsInRange( Date fromDate, Date toDate, int state, String triggeredBy, Collection<Integer> projectGroupIds, int offset, int length ) { PersistenceManager pm = getPersistenceManager(); Transaction tx = pm.currentTransaction(); try { tx.begin(); pm.getFetchPlan().addGroup( BUILD_RESULT_WITH_DETAILS_FETCH_GROUP ); Extent extent = pm.getExtent( BuildResult.class, true ); Query query = pm.newQuery( extent ); InRangeQueryAttrs inRangeQueryAttrs = new InRangeQueryAttrs( fromDate, toDate, state, triggeredBy, projectGroupIds, query ).build(); String parameters = inRangeQueryAttrs.getParameters(); String filter = inRangeQueryAttrs.getFilter(); Map params = inRangeQueryAttrs.getParams(); query.declareParameters( parameters ); query.setFilter( filter ); query.setRange( offset, offset + length ); List<BuildResult> result = (List<BuildResult>) query.executeWithMap( params ); result = (List<BuildResult>) pm.detachCopyAll( result ); tx.commit(); return result; } finally { rollback( tx ); } } private class InRangeQueryAttrs { private Date fromDate; private Date toDate; private int state; private String triggeredBy; private Collection<Integer> projectGroupIds; private Query query; private String parameters; private String filter; private Map params; public InRangeQueryAttrs( Date fromDate, Date toDate, int state, String triggeredBy, Collection<Integer> projectGroupIds, Query query ) { this.fromDate = fromDate; this.toDate = toDate; this.state = state; this.triggeredBy = triggeredBy; this.projectGroupIds = projectGroupIds; this.query = query; } public String getParameters() { return parameters; } public String getFilter() { return filter; } public Map getParams() { return params; } public InRangeQueryAttrs build() { parameters = ""; filter = ""; params = new HashMap(); if ( state > 0 ) { params.put( "state", state ); parameters += "int state, "; filter += "this.state == state && "; } if ( projectGroupIds != null && !projectGroupIds.isEmpty() ) { params.put( "projectGroupIds", projectGroupIds ); query.declareImports( "import java.util.Collection" ); parameters += "Collection projectGroupIds, "; filter += "projectGroupIds.contains(this.project.projectGroup.id) && "; } if ( triggeredBy != null && !triggeredBy.equals( "" ) ) { params.put( "triggeredBy", triggeredBy ); query.declareImports( "import java.lang.String" ); parameters += "String triggeredBy, "; filter += "this.username == triggeredBy && "; } if ( fromDate != null ) { params.put( "fromDate", fromDate.getTime() ); parameters += "long fromDate, "; filter += "this.startTime >= fromDate && "; } if ( toDate != null ) { Calendar cal = Calendar.getInstance(); cal.setTime( toDate ); cal.add( Calendar.DAY_OF_MONTH, 1 ); params.put( "toDate", cal.getTimeInMillis() ); parameters += "long toDate"; filter += "this.startTime < toDate"; } if ( filter.endsWith( "&& " ) ) { filter = filter.substring( 0, filter.length() - 3 ); parameters = parameters.substring( 0, parameters.length() - 2 ); } return this; } } }
5,197
0
Create_ds/continuum/continuum-store/src/main/java/org/apache/continuum
Create_ds/continuum/continuum-store/src/main/java/org/apache/continuum/dao/ProjectDaoImpl.java
package org.apache.continuum.dao; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.continuum.model.project.ProjectGroupSummary; import org.apache.continuum.model.project.ProjectSummaryResult; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.model.project.ProjectGroup; import org.apache.maven.continuum.store.ContinuumObjectNotFoundException; import org.apache.maven.continuum.store.ContinuumStoreException; import org.codehaus.plexus.component.annotations.Component; import org.springframework.stereotype.Repository; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.jdo.Extent; import javax.jdo.PersistenceManager; import javax.jdo.Query; import javax.jdo.Transaction; /** * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a> */ @Repository( "projectDao" ) @Component( role = org.apache.continuum.dao.ProjectDao.class ) public class ProjectDaoImpl extends AbstractDao implements ProjectDao { public void removeProject( Project project ) { removeObject( project ); } public void updateProject( Project project ) throws ContinuumStoreException { updateObject( project ); } public Project getProject( int projectId ) throws ContinuumStoreException { return getObjectById( Project.class, projectId ); } public Project getProject( String groupId, String artifactId, String version ) throws ContinuumStoreException { PersistenceManager pm = getPersistenceManager(); Transaction tx = pm.currentTransaction(); try { tx.begin(); Extent extent = pm.getExtent( Project.class, true ); Query query = pm.newQuery( extent ); query.declareImports( "import java.lang.String" ); query.declareParameters( "String groupId, String artifactId, String version" ); query.setFilter( "this.groupId == groupId && this.artifactId == artifactId && this.version == version" ); Object[] params = new Object[3]; params[0] = groupId; params[1] = artifactId; params[2] = version; Collection result = (Collection) query.executeWithArray( params ); if ( result.size() == 0 ) { tx.commit(); return null; } Object object = pm.detachCopy( result.iterator().next() ); tx.commit(); return (Project) object; } finally { rollback( tx ); } } public Project getProjectByName( String name ) throws ContinuumStoreException { PersistenceManager pm = getPersistenceManager(); Transaction tx = pm.currentTransaction(); try { tx.begin(); Extent extent = pm.getExtent( Project.class, true ); Query query = pm.newQuery( extent ); query.declareImports( "import java.lang.String" ); query.declareParameters( "String name" ); query.setFilter( "this.name == name" ); Collection result = (Collection) query.execute( name ); if ( result.size() == 0 ) { tx.commit(); return null; } Object object = pm.detachCopy( result.iterator().next() ); tx.commit(); return (Project) object; } finally { rollback( tx ); } } public List<Project> getProjectsWithDependenciesByGroupId( int projectGroupId ) { PersistenceManager pm = getPersistenceManager(); Transaction tx = pm.currentTransaction(); try { tx.begin(); Extent extent = pm.getExtent( Project.class, true ); Query query = pm.newQuery( extent, "projectGroup.id == " + projectGroupId ); pm.getFetchPlan().addGroup( PROJECT_DEPENDENCIES_FETCH_GROUP ); List<Project> result = (List<Project>) query.execute(); result = (List<Project>) pm.detachCopyAll( result ); tx.commit(); return result; } finally { rollback( tx ); } } public Project getProjectWithBuilds( int projectId ) throws ContinuumStoreException { return getObjectById( Project.class, projectId, PROJECT_WITH_BUILDS_FETCH_GROUP ); } public Project getProjectWithBuildDetails( int projectId ) throws ContinuumStoreException { return getObjectById( Project.class, projectId, PROJECT_BUILD_DETAILS_FETCH_GROUP ); } public Project getProjectWithCheckoutResult( int projectId ) throws ContinuumStoreException { return getObjectById( Project.class, projectId, PROJECT_WITH_CHECKOUT_RESULT_FETCH_GROUP ); } public List<Project> getProjectsInGroup( int projectGroupId ) throws ContinuumStoreException { PersistenceManager pm = getPersistenceManager(); Transaction tx = pm.currentTransaction(); try { tx.begin(); Extent extent = pm.getExtent( Project.class, true ); Query query = pm.newQuery( extent, "projectGroup.id == " + projectGroupId ); query.setOrdering( "name ascending" ); List<Project> result = (List<Project>) query.execute(); result = (List<Project>) pm.detachCopyAll( result ); tx.commit(); return result; } finally { rollback( tx ); } } public List<Project> getProjectsInGroupWithDependencies( int projectGroupId ) throws ContinuumStoreException { PersistenceManager pm = getPersistenceManager(); Transaction tx = pm.currentTransaction(); try { tx.begin(); Extent extent = pm.getExtent( Project.class, true ); Query query = pm.newQuery( extent, "projectGroup.id == " + projectGroupId ); query.setOrdering( "name ascending" ); pm.getFetchPlan().addGroup( PROJECT_DEPENDENCIES_FETCH_GROUP ); pm.getFetchPlan().addGroup( PROJECTGROUP_PROJECTS_FETCH_GROUP ); List<Project> result = (List<Project>) query.execute(); result = (List<Project>) pm.detachCopyAll( result ); tx.commit(); return result; } finally { rollback( tx ); } } public Project getProjectWithAllDetails( int projectId ) throws ContinuumStoreException { return getObjectById( Project.class, projectId, PROJECT_ALL_DETAILS_FETCH_GROUP ); } public List<Project> getAllProjectsByName() { return getAllObjectsDetached( Project.class, "name ascending", null ); } public List<Project> getAllProjectsByNameWithDependencies() { return getAllObjectsDetached( Project.class, "name ascending", PROJECT_DEPENDENCIES_FETCH_GROUP ); } public List<Project> getAllProjectsByNameWithBuildDetails() { return getAllObjectsDetached( Project.class, "name ascending", PROJECT_BUILD_DETAILS_FETCH_GROUP ); } public ProjectGroup getProjectGroupByProjectId( int projectId ) throws ContinuumObjectNotFoundException { try { return getProject( projectId ).getProjectGroup(); } catch ( ContinuumStoreException e ) { throw new ContinuumObjectNotFoundException( "unable to find project group containing project with id: " + projectId ); } } public Project getProjectWithDependencies( int projectId ) throws ContinuumStoreException { return getObjectById( Project.class, projectId, PROJECT_DEPENDENCIES_FETCH_GROUP ); } public Map<Integer, ProjectGroupSummary> getProjectsSummary() { PersistenceManager pm = getPersistenceManager(); Transaction tx = pm.currentTransaction(); try { tx.begin(); Extent extent = pm.getExtent( Project.class ); Query query = pm.newQuery( extent ); query.setResult( "projectGroup.id as projectGroupId, state as projectState, count(state) as size" ); query.setResultClass( ProjectSummaryResult.class ); query.setGrouping( "projectGroup.id, state" ); List<ProjectSummaryResult> results = (List<ProjectSummaryResult>) query.execute(); Map<Integer, ProjectGroupSummary> summaries = processProjectGroupSummary( results ); tx.commit(); return summaries; } finally { rollback( tx ); } } private Map<Integer, ProjectGroupSummary> processProjectGroupSummary( List<ProjectSummaryResult> results ) { Map<Integer, ProjectGroupSummary> map = new HashMap<Integer, ProjectGroupSummary>(); for ( ProjectSummaryResult result : results ) { ProjectGroupSummary summary; int projectGroupId = result.getProjectGroupId(); int size = new Long( result.getSize() ).intValue(); int state = result.getProjectState(); if ( map.containsKey( projectGroupId ) ) { summary = map.get( projectGroupId ); } else { summary = new ProjectGroupSummary( projectGroupId ); } summary.addProjects( size ); if ( state == 2 ) { summary.addNumberOfSuccesses( size ); } else if ( state == 3 ) { summary.addNumberOfFailures( size ); } else if ( state == 4 ) { summary.addNumberOfErrors( size ); } map.put( projectGroupId, summary ); } return map; } }
5,198
0
Create_ds/continuum/continuum-store/src/main/java/org/apache/continuum
Create_ds/continuum/continuum-store/src/main/java/org/apache/continuum/dao/AbstractDao.java
package org.apache.continuum.dao; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.maven.continuum.store.ContinuumObjectNotFoundException; import org.apache.maven.continuum.store.ContinuumStoreException; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.jdo.PlexusJdoUtils; import org.codehaus.plexus.jdo.PlexusObjectNotFoundException; import org.codehaus.plexus.jdo.PlexusStoreException; import javax.annotation.Resource; import javax.jdo.FetchPlan; import javax.jdo.PersistenceManager; import javax.jdo.PersistenceManagerFactory; import javax.jdo.Transaction; import java.util.List; /** * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a> */ public class AbstractDao { // ---------------------------------------------------------------------- // Fetch Groups // ---------------------------------------------------------------------- protected static final String PROJECT_WITH_BUILDS_FETCH_GROUP = "project-with-builds"; protected static final String PROJECT_WITH_CHECKOUT_RESULT_FETCH_GROUP = "project-with-checkout-result"; protected static final String BUILD_RESULT_WITH_DETAILS_FETCH_GROUP = "build-result-with-details"; protected static final String PROJECT_BUILD_DETAILS_FETCH_GROUP = "project-build-details"; protected static final String PROJECT_ALL_DETAILS_FETCH_GROUP = "project-all-details"; protected static final String PROJECT_DEPENDENCIES_FETCH_GROUP = "project-dependencies"; protected static final String PROJECTGROUP_PROJECTS_FETCH_GROUP = "projectgroup-projects"; protected static final String BUILD_TEMPLATE_BUILD_DEFINITIONS = "build-template-build-definitions"; @Resource @Requirement protected StoreUtilities storeUtilities; protected <T> T addObject( T object ) { return addObject( getPersistenceManager(), object ); } private <T> T addObject( PersistenceManager pmf, T object ) { return (T) PlexusJdoUtils.addObject( pmf, object ); } protected void removeObject( Object o ) { PlexusJdoUtils.removeObject( getPersistenceManager(), o ); } protected void updateObject( Object object ) throws ContinuumStoreException { updateObject( getPersistenceManager(), object ); } private void updateObject( PersistenceManager pmf, Object object ) throws ContinuumStoreException { try { PlexusJdoUtils.updateObject( pmf, object ); } catch ( PlexusStoreException e ) { throw new ContinuumStoreException( e.getMessage(), e ); } } protected <T> T getObjectById( Class<T> clazz, int id ) throws ContinuumStoreException { return getObjectById( clazz, id, null ); } protected <T> T getObjectById( Class<T> clazz, int id, String fetchGroup ) throws ContinuumStoreException { try { return (T) PlexusJdoUtils.getObjectById( getPersistenceManager(), clazz, id, fetchGroup ); } catch ( PlexusObjectNotFoundException e ) { throw new ContinuumObjectNotFoundException( e.getMessage() ); } catch ( PlexusStoreException e ) { throw new ContinuumStoreException( e.getMessage(), e ); } } protected <T> T getObjectFromQuery( Class<T> clazz, String idField, String id, String fetchGroup ) throws ContinuumStoreException { try { return (T) PlexusJdoUtils.getObjectFromQuery( getPersistenceManager(), clazz, idField, id, fetchGroup ); } catch ( PlexusObjectNotFoundException e ) { throw new ContinuumObjectNotFoundException( e.getMessage() ); } catch ( PlexusStoreException e ) { throw new ContinuumStoreException( e.getMessage(), e ); } } protected <T> List<T> getAllObjectsDetached( Class<T> clazz ) { return getAllObjectsDetached( clazz, null ); } protected <T> List<T> getAllObjectsDetached( Class<T> clazz, String fetchGroup ) { return getAllObjectsDetached( clazz, null, fetchGroup ); } protected <T> List<T> getAllObjectsDetached( Class<T> clazz, String ordering, String fetchGroup ) { return getAllObjectsDetached( getPersistenceManager(), clazz, ordering, fetchGroup ); } protected <T> List<T> getAllObjectsDetached( PersistenceManager pmf, Class<T> clazz, String ordering, String fetchGroup ) { return PlexusJdoUtils.getAllObjectsDetached( pmf, clazz, ordering, fetchGroup ); } protected void rollback( Transaction tx ) { PlexusJdoUtils.rollbackIfActive( tx ); } protected void attachAndDelete( Object object ) { PlexusJdoUtils.attachAndDelete( getPersistenceManager(), object ); } protected PersistenceManager getPersistenceManager() { return getPersistenceManager( getContinuumPersistenceManagerFactory() ); } private PersistenceManager getPersistenceManager( PersistenceManagerFactory pmf ) { PersistenceManager pm = pmf.getPersistenceManager(); pm.getFetchPlan().setMaxFetchDepth( -1 ); pm.getFetchPlan().setDetachmentOptions( FetchPlan.DETACH_LOAD_FIELDS ); return pm; } protected PersistenceManagerFactory getContinuumPersistenceManagerFactory() { return storeUtilities.getContinuumPersistenceManagerFactory(); } protected <T> T makePersistent( PersistenceManager pm, T object, boolean detach ) { return (T) PlexusJdoUtils.makePersistent( pm, object, detach ); } }
5,199