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-purge/src/main/java/org/apache/continuum/purge/executor
Create_ds/continuum/continuum-purge/src/main/java/org/apache/continuum/purge/executor/repo/ReleasedSnapshotsRepositoryPurgeExecutor.java
package org.apache.continuum.purge.executor.repo; /* * 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.ContinuumPurgeConstants; import org.apache.continuum.purge.executor.ContinuumPurgeExecutorException; import org.apache.continuum.purge.repository.content.RepositoryManagedContent; import org.apache.maven.archiva.common.utils.VersionComparator; import org.apache.maven.archiva.common.utils.VersionUtil; import org.apache.maven.archiva.model.ArtifactReference; import org.apache.maven.archiva.model.ProjectReference; import org.apache.maven.archiva.model.VersionedReference; import org.apache.maven.archiva.repository.ContentNotFoundException; import org.apache.maven.archiva.repository.layout.LayoutException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Codes were taken from Archiva's CleanupReleasedSnapshotsRepositoryPurge and just made some few changes * * @author Maria Catherine Tan */ public class ReleasedSnapshotsRepositoryPurgeExecutor extends AbstractRepositoryPurgeExecutor { private Logger log = LoggerFactory.getLogger( ReleasedSnapshotsRepositoryPurgeExecutor.class ); private final RepositoryManagedContent repository; public ReleasedSnapshotsRepositoryPurgeExecutor( RepositoryManagedContent repository ) { this.repository = repository; } public void purge( String path ) throws ContinuumPurgeExecutorException { try { File artifactFile = new File( repository.getRepoRoot(), path ); if ( !artifactFile.exists() ) { // Nothing to do here, file doesn't exist, skip it. return; } ArtifactReference artifact = repository.toArtifactReference( path ); if ( !VersionUtil.isSnapshot( artifact.getVersion() ) ) { // Nothing to do here, not a snapshot, skip it. return; } ProjectReference reference = new ProjectReference(); reference.setGroupId( artifact.getGroupId() ); reference.setArtifactId( artifact.getArtifactId() ); // Gather up all of the versions. List<String> allVersions = new ArrayList<String>( repository.getVersions( reference ) ); // Split the versions into released and snapshots. List<String> releasedVersions = new ArrayList<String>(); List<String> snapshotVersions = new ArrayList<String>(); for ( String version : allVersions ) { if ( VersionUtil.isSnapshot( version ) ) { snapshotVersions.add( version ); } else { releasedVersions.add( version ); } } Collections.sort( allVersions, VersionComparator.getInstance() ); Collections.sort( releasedVersions, VersionComparator.getInstance() ); Collections.sort( snapshotVersions, VersionComparator.getInstance() ); VersionedReference versionRef = new VersionedReference(); versionRef.setGroupId( artifact.getGroupId() ); versionRef.setArtifactId( artifact.getArtifactId() ); for ( String version : snapshotVersions ) { if ( releasedVersions.contains( VersionUtil.getReleaseVersion( version ) ) ) { versionRef.setVersion( version ); repository.deleteVersion( versionRef ); log.info( ContinuumPurgeConstants.PURGE_PROJECT + " - " + VersionedReference.toKey( versionRef ) ); removeMetadata( versionRef ); } } } catch ( LayoutException e ) { throw new ContinuumPurgeExecutorException( e.getMessage(), e ); } catch ( ContentNotFoundException e ) { throw new ContinuumPurgeExecutorException( e.getMessage(), e ); } } private void removeMetadata( VersionedReference versionRef ) throws ContinuumPurgeExecutorException { String path = repository.toMetadataPath( versionRef ); File projectPath = new File( repository.getRepoRoot(), path ); File projectDir = projectPath.getParentFile(); purgeSupportFiles( projectDir, "maven-metadata" ); } }
4,900
0
Create_ds/continuum/continuum-purge/src/main/java/org/apache/continuum/purge/executor
Create_ds/continuum/continuum-purge/src/main/java/org/apache/continuum/purge/executor/repo/MultiplexedPurgeExecutor.java
package org.apache.continuum.purge.executor.repo; /* * 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.executor.ContinuumPurgeExecutor; import org.apache.continuum.purge.executor.ContinuumPurgeExecutorException; import java.util.Arrays; import java.util.List; public class MultiplexedPurgeExecutor implements ContinuumPurgeExecutor { private List<ContinuumPurgeExecutor> constituents; public MultiplexedPurgeExecutor( ContinuumPurgeExecutor... executors ) { constituents = Arrays.asList( executors ); } public void purge( String path ) throws ContinuumPurgeExecutorException { for ( ContinuumPurgeExecutor child : constituents ) { child.purge( path ); } } }
4,901
0
Create_ds/continuum/continuum-purge/src/main/java/org/apache/continuum/purge/executor
Create_ds/continuum/continuum-purge/src/main/java/org/apache/continuum/purge/executor/repo/RepositoryPurgeExecutorFactory.java
package org.apache.continuum.purge.executor.repo; /* * 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.executor.ContinuumPurgeExecutor; import org.apache.continuum.purge.repository.content.RepositoryManagedContent; public interface RepositoryPurgeExecutorFactory { ContinuumPurgeExecutor create( boolean deleteAll, int daysOld, int retentionCount, boolean deleteReleasedSnapshots, RepositoryManagedContent repoContent ); }
4,902
0
Create_ds/continuum/continuum-purge/src/main/java/org/apache/continuum/purge/executor
Create_ds/continuum/continuum-purge/src/main/java/org/apache/continuum/purge/executor/repo/RetentionCountRepositoryPurgeExecutor.java
package org.apache.continuum.purge.executor.repo; /* * 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.executor.ContinuumPurgeExecutor; import org.apache.continuum.purge.executor.ContinuumPurgeExecutorException; import org.apache.continuum.purge.repository.content.RepositoryManagedContent; import org.apache.maven.archiva.common.utils.VersionComparator; import org.apache.maven.archiva.common.utils.VersionUtil; import org.apache.maven.archiva.model.ArtifactReference; import org.apache.maven.archiva.model.VersionedReference; import org.apache.maven.archiva.repository.ContentNotFoundException; import org.apache.maven.archiva.repository.layout.LayoutException; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Set; /** * Codes were taken from Archiva's RetentionCountRepository Purge and made some few changes. * * @author Maria Catherine Tan */ public class RetentionCountRepositoryPurgeExecutor extends AbstractRepositoryPurgeExecutor implements ContinuumPurgeExecutor { private final int retentionCount; private final RepositoryManagedContent repository; public RetentionCountRepositoryPurgeExecutor( RepositoryManagedContent repository, int retentionCount ) { this.repository = repository; this.retentionCount = retentionCount; } public void purge( String path ) throws ContinuumPurgeExecutorException { try { File artifactFile = new File( repository.getRepoRoot(), path ); if ( !artifactFile.exists() ) { return; } ArtifactReference artifact = repository.toArtifactReference( path ); if ( VersionUtil.isSnapshot( artifact.getVersion() ) ) { VersionedReference reference = new VersionedReference(); reference.setGroupId( artifact.getGroupId() ); reference.setArtifactId( artifact.getArtifactId() ); reference.setVersion( artifact.getVersion() ); List<String> versions = new ArrayList<String>( repository.getVersions( reference ) ); Collections.sort( versions, VersionComparator.getInstance() ); if ( retentionCount > versions.size() ) { // Done. nothing to do here. skip it. return; } int countToPurge = versions.size() - retentionCount; for ( String version : versions ) { if ( countToPurge-- <= 0 ) { break; } doPurgeAllRelated( artifact, version ); } } } catch ( LayoutException e ) { throw new ContinuumPurgeExecutorException( e.getMessage(), e ); } catch ( ContentNotFoundException e ) { // Nothing to do here. // TODO: Log this condition? } } private void doPurgeAllRelated( ArtifactReference reference, String version ) throws LayoutException { ArtifactReference artifact = new ArtifactReference(); artifact.setGroupId( reference.getGroupId() ); artifact.setArtifactId( reference.getArtifactId() ); artifact.setVersion( version ); artifact.setClassifier( reference.getClassifier() ); artifact.setType( reference.getType() ); try { Set<ArtifactReference> related = repository.getRelatedArtifacts( artifact ); purge( related, repository ); } catch ( ContentNotFoundException e ) { // Nothing to do here. // TODO: Log this? } } }
4,903
0
Create_ds/continuum/continuum-purge/src/main/java/org/apache/continuum/purge/executor
Create_ds/continuum/continuum-purge/src/main/java/org/apache/continuum/purge/executor/repo/AbstractRepositoryPurgeExecutor.java
package org.apache.continuum.purge.executor.repo; /* * 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.ContinuumPurgeConstants; import org.apache.continuum.purge.executor.ContinuumPurgeExecutor; import org.apache.continuum.purge.repository.content.RepositoryManagedContent; import org.apache.maven.archiva.consumers.core.repository.ArtifactFilenameFilter; import org.apache.maven.archiva.model.ArtifactReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FilenameFilter; import java.util.Set; /** * Some codes were taken from Archiva. * * @author Maria Catherine Tan */ public abstract class AbstractRepositoryPurgeExecutor implements ContinuumPurgeExecutor { private static final Logger log = LoggerFactory.getLogger( AbstractRepositoryPurgeExecutor.class ); public void purge( Set<ArtifactReference> references, RepositoryManagedContent repository ) { if ( references != null && !references.isEmpty() ) { for ( ArtifactReference reference : references ) { File artifactFile = repository.toFile( reference ); artifactFile.delete(); log.info( ContinuumPurgeConstants.PURGE_ARTIFACT + " - " + artifactFile.getName() ); purgeSupportFiles( artifactFile, artifactFile.getName() ); // purge maven metadata purgeSupportFiles( artifactFile.getParentFile(), "maven-metadata" ); } } } /** * <p> * This find support files for the artifactFile and deletes them. * </p> * <p> * Support Files are things like ".sha1", ".md5", ".asc", etc. * </p> * * @param artifactFile the file to base off of. */ protected void purgeSupportFiles( File artifactFile, String filename ) { File parentDir = artifactFile.getParentFile(); if ( !parentDir.exists() ) { return; } FilenameFilter filter = new ArtifactFilenameFilter( filename ); File[] files = parentDir.listFiles( filter ); for ( File file : files ) { if ( file.exists() && file.isFile() ) { file.delete(); log.info( ContinuumPurgeConstants.PURGE_FILE + " - " + file.getName() ); } } } }
4,904
0
Create_ds/continuum/continuum-purge/src/main/java/org/apache/continuum/purge/executor
Create_ds/continuum/continuum-purge/src/main/java/org/apache/continuum/purge/executor/repo/DaysOldRepositoryPurgeExecutor.java
package org.apache.continuum.purge.executor.repo; /* * 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.time.DateUtils; import org.apache.continuum.purge.executor.ContinuumPurgeExecutor; import org.apache.continuum.purge.executor.ContinuumPurgeExecutorException; import org.apache.continuum.purge.repository.content.RepositoryManagedContent; import org.apache.maven.archiva.common.utils.VersionComparator; import org.apache.maven.archiva.common.utils.VersionUtil; import org.apache.maven.archiva.model.ArtifactReference; import org.apache.maven.archiva.model.VersionedReference; import org.apache.maven.archiva.repository.ContentNotFoundException; import org.apache.maven.archiva.repository.layout.LayoutException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Set; import java.util.regex.Matcher; /** * Codes were taken from Archiva's DaysOldRepositoryPurge and made some few changes. * * @author Maria Catherine Tan */ public class DaysOldRepositoryPurgeExecutor extends AbstractRepositoryPurgeExecutor implements ContinuumPurgeExecutor { private static final Logger log = LoggerFactory.getLogger( DaysOldRepositoryPurgeExecutor.class ); private final int daysOlder; private final int retentionCount; private final RepositoryManagedContent repository; private final SimpleDateFormat timestampParser; public DaysOldRepositoryPurgeExecutor( RepositoryManagedContent repository, int daysOlder, int retentionCount ) { this.repository = repository; this.daysOlder = daysOlder; this.retentionCount = retentionCount; timestampParser = new SimpleDateFormat( "yyyyMMdd.HHmmss" ); timestampParser.setTimeZone( DateUtils.UTC_TIME_ZONE ); } public void purge( String path ) throws ContinuumPurgeExecutorException { File artifactFile = new File( repository.getRepoRoot(), path ); if ( !artifactFile.exists() ) { return; } ArtifactReference artifact; List<String> versions; Calendar olderThanThisDate; try { artifact = repository.toArtifactReference( path ); olderThanThisDate = Calendar.getInstance( DateUtils.UTC_TIME_ZONE ); olderThanThisDate.add( Calendar.DATE, -daysOlder ); // respect retention count VersionedReference reference = new VersionedReference(); reference.setGroupId( artifact.getGroupId() ); reference.setArtifactId( artifact.getArtifactId() ); reference.setVersion( artifact.getVersion() ); versions = new ArrayList<String>( repository.getVersions( reference ) ); } catch ( Exception le ) { log.warn( "ignoring {}, could not identify artifact versions: {}", path, le.getMessage() ); return; } Collections.sort( versions, VersionComparator.getInstance() ); if ( retentionCount > versions.size() ) { // Done. nothing to do here. skip it. return; } int countToPurge = versions.size() - retentionCount; for ( String version : versions ) { try { if ( countToPurge <= 0 ) { break; } ArtifactReference newArtifactReference = repository.toArtifactReference( artifactFile.getAbsolutePath() ); newArtifactReference.setVersion( version ); File newArtifactFile = repository.toFile( newArtifactReference ); // Is this a generic snapshot "1.0-SNAPSHOT" ? if ( VersionUtil.isGenericSnapshot( newArtifactReference.getVersion() ) ) { if ( newArtifactFile.lastModified() < olderThanThisDate.getTimeInMillis() ) { doPurgeAllRelated( newArtifactReference ); countToPurge--; } } // Is this a timestamp snapshot "1.0-20070822.123456-42" ? else if ( VersionUtil.isUniqueSnapshot( newArtifactReference.getVersion() ) ) { Calendar timestampCal = uniqueSnapshotToCalendar( newArtifactReference.getVersion() ); if ( timestampCal.getTimeInMillis() < olderThanThisDate.getTimeInMillis() ) { doPurgeAllRelated( newArtifactReference ); countToPurge--; } else if ( newArtifactFile.lastModified() < olderThanThisDate.getTimeInMillis() ) { doPurgeAllRelated( newArtifactReference ); countToPurge--; } } } catch ( LayoutException le ) { log.warn( "ignoring version {} of '{}': {}", new Object[] { version, artifactFile, le.getMessage() } ); } } } private Calendar uniqueSnapshotToCalendar( String version ) { // The latestVersion will contain the full version string "1.0-alpha-5-20070821.213044-8" // This needs to be broken down into ${base}-${timestamp}-${build_number} Matcher m = VersionUtil.UNIQUE_SNAPSHOT_PATTERN.matcher( version ); if ( m.matches() ) { Matcher mtimestamp = VersionUtil.TIMESTAMP_PATTERN.matcher( m.group( 2 ) ); if ( mtimestamp.matches() ) { String tsDate = mtimestamp.group( 1 ); String tsTime = mtimestamp.group( 2 ); Date versionDate; try { versionDate = timestampParser.parse( tsDate + "." + tsTime ); Calendar cal = Calendar.getInstance( DateUtils.UTC_TIME_ZONE ); cal.setTime( versionDate ); return cal; } catch ( ParseException e ) { // Invalid Date/Time return null; } } } return null; } private void doPurgeAllRelated( ArtifactReference reference ) throws LayoutException { try { Set<ArtifactReference> related = repository.getRelatedArtifacts( reference ); purge( related, repository ); } catch ( ContentNotFoundException e ) { // Nothing to do here. // TODO: Log this? } } }
4,905
0
Create_ds/continuum/continuum-purge/src/main/java/org/apache/continuum/purge/executor
Create_ds/continuum/continuum-purge/src/main/java/org/apache/continuum/purge/executor/repo/ScanningPurgeExecutor.java
package org.apache.continuum.purge.executor.repo; /* * 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.executor.ContinuumPurgeExecutor; import org.apache.continuum.purge.executor.ContinuumPurgeExecutorException; import org.apache.continuum.purge.repository.scanner.RepositoryScanner; import org.apache.continuum.purge.repository.scanner.ScannerHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; public class ScanningPurgeExecutor implements ContinuumPurgeExecutor, ScannerHandler { private static final Logger log = LoggerFactory.getLogger( ScanningPurgeExecutor.class ); private RepositoryScanner scanner; private ContinuumPurgeExecutor executor; public ScanningPurgeExecutor( RepositoryScanner scanner, ContinuumPurgeExecutor executor ) { this.scanner = scanner; this.executor = executor; } public void purge( String path ) throws ContinuumPurgeExecutorException { scanner.scan( new File( path ), this ); } public void handle( String path ) { try { executor.purge( path ); } catch ( ContinuumPurgeExecutorException e ) { log.error( String.format( "handling failed %s: %s", path, e.getMessage() ), e ); } } }
4,906
0
Create_ds/continuum/continuum-notifiers/continuum-notifier-api/src/main/java/org/apache/maven/continuum
Create_ds/continuum/continuum-notifiers/continuum-notifier-api/src/main/java/org/apache/maven/continuum/notification/MessageContext.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.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.ProjectNotifier; import java.util.List; /** * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a> */ public class MessageContext { private Project project; private BuildDefinition buildDefinition; private List<ProjectNotifier> notifiers; private BuildResult buildResult; private ProjectScmRoot projectScmRoot; public Project getProject() { return project; } public void setProject( Project project ) { this.project = project; } public BuildDefinition getBuildDefinition() { return buildDefinition; } public void setBuildDefinition( BuildDefinition buildDefinition ) { this.buildDefinition = buildDefinition; } public List<ProjectNotifier> getNotifiers() { return notifiers; } public void setNotifier( List<ProjectNotifier> notifiers ) { this.notifiers = notifiers; } public BuildResult getBuildResult() { return buildResult; } public void setBuildResult( BuildResult buildResult ) { this.buildResult = buildResult; } public ProjectScmRoot getProjectScmRoot() { return projectScmRoot; } public void setProjectScmRoot( ProjectScmRoot projectScmRoot ) { this.projectScmRoot = projectScmRoot; } }
4,907
0
Create_ds/continuum/continuum-notifiers/continuum-notifier-api/src/main/java/org/apache/maven/continuum
Create_ds/continuum/continuum-notifiers/continuum-notifier-api/src/main/java/org/apache/maven/continuum/notification/NotificationException.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. */ /** * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a> */ public class NotificationException extends Exception { public NotificationException( String message ) { super( message ); } public NotificationException( String message, Throwable cause ) { super( message, cause ); } }
4,908
0
Create_ds/continuum/continuum-notifiers/continuum-notifier-api/src/main/java/org/apache/maven/continuum
Create_ds/continuum/continuum-notifiers/continuum-notifier-api/src/main/java/org/apache/maven/continuum/notification/AbstractContinuumNotifier.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.configuration.ContinuumConfigurationException; import org.apache.continuum.dao.BuildResultDao; import org.apache.continuum.dao.ProjectDao; import org.apache.continuum.dao.ProjectScmRootDao; 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.ConfigurationLoadingException; 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.project.ProjectGroup; import org.apache.maven.continuum.model.project.ProjectNotifier; import org.apache.maven.continuum.project.ContinuumProjectState; import org.apache.maven.continuum.store.ContinuumStoreException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; import javax.annotation.Resource; public abstract class AbstractContinuumNotifier implements Notifier { public static final String ADDRESS_FIELD = "address"; public static final String COMMITTER_FIELD = "committers"; public static final String DEVELOPER_FIELD = "developers"; private static final Logger log = LoggerFactory.getLogger( AbstractContinuumNotifier.class ); @Resource private ConfigurationService configurationService; @Resource private BuildResultDao buildResultDao; @Resource private ProjectDao projectDao; @Resource private ProjectScmRootDao projectScmRootDao; private boolean alwaysSend = false; protected String getBuildOutput( Project project, BuildResult buildResult ) { if ( buildResult == null ) { return ""; } try { if ( buildResult.getEndTime() != 0 ) { return configurationService.getBuildOutput( buildResult.getId(), project.getId() ); } else { return ""; } } catch ( ConfigurationException e ) { String msg = "Error while population the notification context."; log.error( msg, e ); return msg; } } /** * Returns url of the last build * * @param project The project * @param build The build * @param configurationService The configuration Service * @return The report URL * @throws ContinuumException whne the configuration can't be loaded */ public String getReportUrl( Project project, BuildResult build, ConfigurationService configurationService ) throws ContinuumException { try { if ( !configurationService.isLoaded() ) { configurationService.reload(); } StringBuffer buf = new StringBuffer( configurationService.getUrl() ); if ( project != null && build != null ) { if ( !buf.toString().endsWith( "/" ) ) { buf.append( "/" ); } buf.append( "buildResult.action?buildId=" ).append( build.getId() ).append( "&projectId=" ).append( project.getId() ); } return buf.toString(); } catch ( ConfigurationLoadingException e ) { throw new ContinuumException( "Can't obtain the base url from configuration.", e ); } catch ( ContinuumConfigurationException e ) { throw new ContinuumException( "Can't obtain the base url from configuration.", e ); } } public String getReportUrl( ProjectGroup projectGroup, ProjectScmRoot projectScmRoot, ConfigurationService configurationService ) throws ContinuumException { try { if ( !configurationService.isLoaded() ) { configurationService.reload(); } StringBuffer buf = new StringBuffer( configurationService.getUrl() ); if ( projectGroup != null && projectScmRoot != null ) { if ( !buf.toString().endsWith( "/" ) ) { buf.append( "/" ); } buf.append( "scmResult.action?projectScmRootId=" ).append( projectScmRoot.getId() ).append( "&projectGroupId=" ).append( projectGroup.getId() ); } return buf.toString(); } catch ( ConfigurationLoadingException e ) { throw new ContinuumException( "Can't obtain the base url from configuration.", e ); } catch ( ContinuumConfigurationException e ) { throw new ContinuumException( "Can't obtain the base url from configuration.", e ); } } /** * Determine if message must be sent * * @param build The current build result * @param previousBuild The previous build result * @param projectNotifier The project notifier * @return True if a message must be sent */ public boolean shouldNotify( BuildResult build, BuildResult previousBuild, ProjectNotifier projectNotifier ) { if ( projectNotifier == null ) { projectNotifier = new ProjectNotifier(); } if ( build == null ) { return false; } if ( alwaysSend ) { return true; } if ( build.getState() == ContinuumProjectState.FAILED && projectNotifier.isSendOnFailure() ) { return true; } if ( build.getState() == ContinuumProjectState.ERROR && projectNotifier.isSendOnError() ) { return true; } // Send if this is the first build if ( previousBuild == null ) { if ( build.getState() == ContinuumProjectState.ERROR ) { return projectNotifier.isSendOnError(); } if ( build.getState() == ContinuumProjectState.FAILED ) { return projectNotifier.isSendOnFailure(); } if ( build.getState() == ContinuumProjectState.OK ) { return projectNotifier.isSendOnSuccess(); } return build.getState() != ContinuumProjectState.WARNING || projectNotifier.isSendOnWarning(); } // Send if the state has changed if ( log.isDebugEnabled() ) { log.debug( "Current build state: " + build.getState() + ", previous build state: " + previousBuild.getState() ); } if ( build.getState() != previousBuild.getState() ) { if ( build.getState() == ContinuumProjectState.ERROR ) { return projectNotifier.isSendOnError(); } if ( build.getState() == ContinuumProjectState.FAILED ) { return projectNotifier.isSendOnFailure(); } if ( build.getState() == ContinuumProjectState.OK ) { return projectNotifier.isSendOnSuccess(); } return build.getState() != ContinuumProjectState.WARNING || projectNotifier.isSendOnWarning(); } log.info( "Same state, not sending message." ); return false; } public boolean shouldNotify( ProjectScmRoot projectScmRoot, ProjectNotifier projectNotifier ) { if ( projectNotifier == null ) { projectNotifier = new ProjectNotifier(); } return projectScmRoot != null && ( alwaysSend || projectScmRoot.getState() == ContinuumProjectState.ERROR && projectNotifier.isSendOnScmFailure() && projectScmRoot.getOldState() != projectScmRoot.getState() ); } protected BuildResult getPreviousBuild( Project project, BuildDefinition buildDef, BuildResult currentBuild ) throws NotificationException { List<BuildResult> builds; try { if ( buildDef != null ) { builds = buildResultDao.getBuildResultsByBuildDefinition( project.getId(), buildDef.getId(), 0, 2 ); if ( builds.size() < 2 ) { return null; } //builds are sorted in descending way BuildResult build = builds.get( 0 ); if ( currentBuild != null && build.getId() != currentBuild.getId() ) { throw new NotificationException( "INTERNAL ERROR: The current build wasn't the first in the build list. " + "Current build: '" + currentBuild.getId() + "', " + "first build: '" + build.getId() + "'." ); } else { return builds.get( 1 ); } } else { //Normally, it isn't possible, buildDef should be != null if ( project.getId() > 0 ) { project = projectDao.getProjectWithBuilds( project.getId() ); } builds = project.getBuildResults(); if ( builds.size() < 2 ) { return null; } BuildResult build = builds.get( builds.size() - 1 ); if ( currentBuild != null && build.getId() != currentBuild.getId() ) { throw new NotificationException( "INTERNAL ERROR: The current build wasn't the first in the build list. " + "Current build: '" + currentBuild.getId() + "', " + "first build: '" + build.getId() + "'." ); } return builds.get( builds.size() - 2 ); } } catch ( ContinuumStoreException e ) { throw new NotificationException( "Unable to obtain project builds", e ); } } protected String generateMessage( Project project, BuildResult build, ConfigurationService configurationService ) throws NotificationException { int state = project.getState(); if ( build != null ) { state = build.getState(); } String message; if ( state == ContinuumProjectState.OK ) { message = "BUILD SUCCESSFUL: " + project.getName(); } else if ( state == ContinuumProjectState.FAILED ) { message = "BUILD FAILURE: " + project.getName(); } else if ( state == ContinuumProjectState.ERROR ) { message = "BUILD ERROR: " + project.getName(); } else { log.warn( "Unknown build state " + state + " for project " + project.getId() ); message = "ERROR: Unknown build state " + state + " for " + project.getName() + " project"; } try { return message + " " + getReportUrl( project, build, configurationService ); } catch ( ContinuumException e ) { throw new NotificationException( "Cannot generate message", e ); } } protected String generateMessage( ProjectScmRoot projectScmRoot, ConfigurationService configurationService ) throws NotificationException { int state = projectScmRoot.getState(); String scmRootAddress = projectScmRoot.getScmRootAddress(); String message; if ( state == ContinuumProjectState.UPDATED ) { message = "PREPARE BUILD SUCCESSFUL: " + scmRootAddress; } else if ( state == ContinuumProjectState.ERROR ) { message = "PREPARE BUILD ERROR: " + scmRootAddress; } else { log.warn( "Unknown prepare build state " + state + " for SCM root URL " + scmRootAddress ); message = "ERROR: Unknown prepare build state " + state + " for SCM root URL" + scmRootAddress; } try { return message + " " + getReportUrl( projectScmRoot.getProjectGroup(), projectScmRoot, configurationService ); } catch ( ContinuumException e ) { throw new NotificationException( "Cannot generate message", e ); } } }
4,909
0
Create_ds/continuum/continuum-notifiers/continuum-notifier-api/src/main/java/org/apache/maven/continuum
Create_ds/continuum/continuum-notifiers/continuum-notifier-api/src/main/java/org/apache/maven/continuum/notification/Notifier.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. */ /** * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a> */ public interface Notifier { String getType(); void sendMessage( String messageId, MessageContext context ) throws NotificationException; }
4,910
0
Create_ds/continuum/continuum-notifiers/continuum-notifier-jabber/src/main/java/org/apache/maven/continuum/notification
Create_ds/continuum/continuum-notifiers/continuum-notifier-jabber/src/main/java/org/apache/maven/continuum/notification/jabber/JabberContinuumNotifier.java
package org.apache.maven.continuum.notification.jabber; /* * 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.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.project.ProjectNotifier; 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.Configuration; import org.codehaus.plexus.jabber.JabberClient; import org.codehaus.plexus.jabber.JabberClientException; import org.codehaus.plexus.util.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.annotation.Resource; /** * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a> */ @Service( "notifier#jabber" ) public class JabberContinuumNotifier extends AbstractContinuumNotifier { private static final Logger log = LoggerFactory.getLogger( JabberContinuumNotifier.class ); // ---------------------------------------------------------------------- // Requirements // ---------------------------------------------------------------------- @Resource private JabberClient jabberClient; @Resource private ConfigurationService configurationService; // ---------------------------------------------------------------------- // Configuration // ---------------------------------------------------------------------- @Configuration( "" ) private String fromAddress; @Configuration( "" ) private String fromPassword; @Configuration( "" ) private String host; @Configuration( "" ) private int port; @Configuration( "" ) private String imDomainName; @Configuration( "" ) private boolean sslConnection; // ---------------------------------------------------------------------- // Notifier Implementation // ---------------------------------------------------------------------- public String getType() { return "jabber"; } public void sendMessage( String messageId, MessageContext context ) throws NotificationException { Project project = context.getProject(); List<ProjectNotifier> notifiers = context.getNotifiers(); BuildDefinition buildDefinition = context.getBuildDefinition(); BuildResult build = context.getBuildResult(); 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; } // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- List<String> recipients = new ArrayList<String>(); for ( ProjectNotifier notifier : notifiers ) { Map<String, String> configuration = notifier.getConfiguration(); if ( configuration != null && StringUtils.isNotEmpty( configuration.get( ADDRESS_FIELD ) ) ) { recipients.add( configuration.get( ADDRESS_FIELD ) ); } } if ( recipients.size() == 0 ) { log.info( "No Jabber recipients for '" + project.getName() + "'." ); return; } // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- if ( messageId.equals( ContinuumNotificationDispatcher.MESSAGE_ID_BUILD_COMPLETE ) ) { for ( ProjectNotifier notifier : notifiers ) { buildComplete( project, notifier, build, buildDefinition ); } } else if ( isPrepareBuildComplete ) { for ( ProjectNotifier notifier : notifiers ) { prepareBuildComplete( projectScmRoot, notifier ); } } } // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- private void buildComplete( Project project, ProjectNotifier notifier, BuildResult build, BuildDefinition buildDef ) throws NotificationException { // ---------------------------------------------------------------------- // Check if the mail should be sent at all // ---------------------------------------------------------------------- BuildResult previousBuild = getPreviousBuild( project, buildDef, build ); if ( !shouldNotify( build, previousBuild, notifier ) ) { return; } sendMessage( notifier.getConfiguration(), generateMessage( project, build, configurationService ) ); } private void prepareBuildComplete( ProjectScmRoot projectScmRoot, ProjectNotifier notifier ) throws NotificationException { if ( !shouldNotify( projectScmRoot, notifier ) ) { return; } sendMessage( notifier.getConfiguration(), generateMessage( projectScmRoot, configurationService ) ); } private void sendMessage( Map<String, String> configuration, String message ) throws NotificationException { jabberClient.setHost( getHost( configuration ) ); jabberClient.setPort( getPort( configuration ) ); jabberClient.setUser( getUsername( configuration ) ); jabberClient.setPassword( getPassword( configuration ) ); jabberClient.setImDomainName( getImDomainName( configuration ) ); jabberClient.setSslConnection( isSslConnection( configuration ) ); try { jabberClient.connect(); jabberClient.logon(); if ( configuration != null && StringUtils.isNotEmpty( configuration.get( ADDRESS_FIELD ) ) ) { String address = configuration.get( ADDRESS_FIELD ); String[] recipients = StringUtils.split( address, "," ); for ( String recipient : recipients ) { if ( isGroup( configuration ) ) { jabberClient.sendMessageToGroup( recipient, message ); } else { jabberClient.sendMessageToUser( recipient, message ); } } } } catch ( JabberClientException e ) { throw new NotificationException( "Exception while sending message.", e ); } finally { try { jabberClient.logoff(); } catch ( JabberClientException e ) { } } } private String getHost( Map<String, String> configuration ) { if ( configuration.containsKey( "host" ) ) { return configuration.get( "host" ); } else { if ( configuration.containsKey( "address" ) ) { String username = configuration.get( "address" ); if ( username.indexOf( "@" ) > 0 ) { return username.substring( username.indexOf( "@" ) + 1 ); } } } return host; } private int getPort( Map<String, String> configuration ) { if ( configuration.containsKey( "port" ) ) { try { return Integer.parseInt( configuration.get( "port" ) ); } catch ( NumberFormatException e ) { log.error( "jabber port isn't a number.", e ); } } if ( port > 0 ) { return port; } else if ( isSslConnection( configuration ) ) { return 5223; } else { return 5222; } } private String getUsername( Map<String, String> configuration ) { if ( configuration.containsKey( "login" ) ) { String username = configuration.get( "login" ); if ( username.indexOf( "@" ) > 0 ) { username = username.substring( 0, username.indexOf( "@" ) ); } return username; } return fromAddress; } private String getPassword( Map<String, String> configuration ) { if ( configuration.containsKey( "password" ) ) { return configuration.get( "password" ); } return fromPassword; } private boolean isSslConnection( Map<String, String> configuration ) { if ( configuration.containsKey( "sslConnection" ) ) { return convertBoolean( configuration.get( "sslConnection" ) ); } return sslConnection; } private String getImDomainName( Map<String, String> configuration ) { if ( configuration.containsKey( "domainName" ) ) { return configuration.get( "domainName" ); } return imDomainName; } private boolean isGroup( Map<String, String> configuration ) { return configuration.containsKey( "isGroup" ) && convertBoolean( configuration.get( "isGroup" ) ); } private boolean convertBoolean( String value ) { return "true".equalsIgnoreCase( value ) || "on".equalsIgnoreCase( value ) || "yes".equalsIgnoreCase( value ); } }
4,911
0
Create_ds/continuum/continuum-notifiers/continuum-notifier-msn/src/main/java/org/apache/maven/continuum/notification
Create_ds/continuum/continuum-notifiers/continuum-notifier-msn/src/main/java/org/apache/maven/continuum/notification/msn/MsnContinuumNotifier.java
package org.apache.maven.continuum.notification.msn; /* * 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.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.project.ProjectNotifier; 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.Configuration; import org.codehaus.plexus.msn.MsnClient; import org.codehaus.plexus.msn.MsnException; import org.codehaus.plexus.util.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.annotation.Resource; /** * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a> */ @Service( "notifier#msn" ) public class MsnContinuumNotifier extends AbstractContinuumNotifier { private static final Logger log = LoggerFactory.getLogger( MsnContinuumNotifier.class ); // ---------------------------------------------------------------------- // Requirements // ---------------------------------------------------------------------- @Resource private MsnClient msnClient; @Resource private ConfigurationService configurationService; // ---------------------------------------------------------------------- // Configuration // ---------------------------------------------------------------------- @Configuration( "" ) private String fromAddress; @Configuration( "" ) private String fromPassword; // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- // ---------------------------------------------------------------------- // Notifier Implementation // ---------------------------------------------------------------------- public String getType() { return "msn"; } public void sendMessage( String messageId, MessageContext context ) throws NotificationException { Project project = context.getProject(); List<ProjectNotifier> notifiers = context.getNotifiers(); BuildDefinition buildDefinition = context.getBuildDefinition(); BuildResult build = context.getBuildResult(); 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; } // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- List<String> recipients = new ArrayList<String>(); for ( ProjectNotifier notifier : notifiers ) { Map<String, String> configuration = notifier.getConfiguration(); if ( configuration != null && StringUtils.isNotEmpty( configuration.get( ADDRESS_FIELD ) ) ) { recipients.add( configuration.get( ADDRESS_FIELD ) ); } } if ( recipients.size() == 0 ) { log.info( "No MSN recipients for '" + project.getName() + "'." ); return; } // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- if ( messageId.equals( ContinuumNotificationDispatcher.MESSAGE_ID_BUILD_COMPLETE ) ) { for ( ProjectNotifier notifier : notifiers ) { buildComplete( project, notifier, build, buildDefinition ); } } else if ( isPrepareBuildComplete ) { for ( ProjectNotifier notifier : notifiers ) { prepareBuildComplete( projectScmRoot, notifier ); } } } // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- private void buildComplete( Project project, ProjectNotifier notifier, BuildResult build, BuildDefinition buildDef ) throws NotificationException { // ---------------------------------------------------------------------- // Check if the message should be sent at all // ---------------------------------------------------------------------- BuildResult previousBuild = getPreviousBuild( project, buildDef, build ); if ( !shouldNotify( build, previousBuild, notifier ) ) { return; } sendMessage( notifier.getConfiguration(), generateMessage( project, build, configurationService ) ); } private void prepareBuildComplete( ProjectScmRoot projectScmRoot, ProjectNotifier notifier ) throws NotificationException { if ( !shouldNotify( projectScmRoot, notifier ) ) { return; } sendMessage( notifier.getConfiguration(), generateMessage( projectScmRoot, configurationService ) ); } private void sendMessage( Map<String, String> configuration, String message ) throws NotificationException { msnClient.setLogin( getUsername( configuration ) ); msnClient.setPassword( getPassword( configuration ) ); try { msnClient.login(); if ( configuration != null && StringUtils.isNotEmpty( configuration.get( ADDRESS_FIELD ) ) ) { String address = configuration.get( ADDRESS_FIELD ); String[] recipients = StringUtils.split( address, "," ); for ( String recipient : recipients ) { msnClient.sendMessage( recipient, message ); } } } catch ( MsnException e ) { throw new NotificationException( "Exception while sending message.", e ); } finally { try { msnClient.logout(); } catch ( MsnException e ) { } } } private String getUsername( Map<String, String> configuration ) { if ( configuration.containsKey( "login" ) ) { return configuration.get( "login" ); } return fromAddress; } private String getPassword( Map<String, String> configuration ) { if ( configuration.containsKey( "password" ) ) { return configuration.get( "password" ); } return fromPassword; } }
4,912
0
Create_ds/continuum/continuum-notifiers/continuum-notifier-wagon/src/test/java/org/apache/maven/continuum
Create_ds/continuum/continuum-notifiers/continuum-notifier-wagon/src/test/java/org/apache/maven/continuum/wagon/Context.java
package org.apache.maven.continuum.wagon; /* * 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.wagon.authentication.AuthenticationInfo; import java.util.List; /** * Context * * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a> */ public class Context { private String id; private AuthenticationInfo authenticationInfo; private List servlets; public String getId() { return id; } public AuthenticationInfo getAuthenticationInfo() { return authenticationInfo; } public List getServlets() { return servlets; } }
4,913
0
Create_ds/continuum/continuum-notifiers/continuum-notifier-wagon/src/test/java/org/apache/maven/continuum
Create_ds/continuum/continuum-notifiers/continuum-notifier-wagon/src/test/java/org/apache/maven/continuum/wagon/ServletServer.java
package org.apache.maven.continuum.wagon; /* * 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.wagon.authentication.AuthenticationInfo; 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.mortbay.http.BasicAuthenticator; import org.mortbay.http.HashUserRealm; import org.mortbay.http.SecurityConstraint; import org.mortbay.http.SocketListener; import org.mortbay.http.handler.SecurityHandler; import org.mortbay.jetty.Server; import org.mortbay.jetty.servlet.ServletHolder; import org.mortbay.jetty.servlet.ServletHttpContext; import org.mortbay.util.MultiException; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; /** * Plexus Component to start a Jetty Server with servlet settings. * * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a> */ public class ServletServer implements Initializable, Startable { public static final String ROLE = ServletServer.class.getName(); private Server server; private int port; private List contexts; public void initialize() throws InitializationException { server = new Server(); SocketListener listener = new SocketListener(); listener.setPort( port ); server.addListener( listener ); if ( contexts != null ) { try { Iterator itcontext = contexts.iterator(); while ( itcontext.hasNext() ) { Context wdc = (Context) itcontext.next(); ServletHttpContext context = (ServletHttpContext) server.getContext( wdc.getId() ); initContext( wdc, context ); } } catch ( Exception e ) { throw new InitializationException( "Unable to initialize.", e ); } } } private void initContext( Context wdc, ServletHttpContext context ) throws ClassNotFoundException, InstantiationException, IllegalAccessException { AuthenticationInfo authenticationInfo = wdc.getAuthenticationInfo(); if ( authenticationInfo != null ) { HashUserRealm userRealm = new HashUserRealm( "basic" ); userRealm.put( authenticationInfo.getUserName(), authenticationInfo.getPassword() ); context.getHttpServer().addRealm( userRealm ); context.setAuthenticator( new BasicAuthenticator() ); context.addSecurityConstraint( "/*", new SecurityConstraint( "any", SecurityConstraint.ANY_ROLE ) ); context.addHandler( new SecurityHandler() ); } Iterator itpaths = wdc.getServlets().iterator(); while ( itpaths.hasNext() ) { Servlet servlet = (Servlet) itpaths.next(); initServlet( context, servlet ); } } private void initServlet( ServletHttpContext context, Servlet path ) throws ClassNotFoundException, InstantiationException, IllegalAccessException { ServletHolder servlet = context.addServlet( path.getId(), path.getPath(), path.getServlet() ); Iterator itparams = path.getParameters().entrySet().iterator(); while ( itparams.hasNext() ) { Map.Entry entry = (Entry) itparams.next(); servlet.setInitParameter( (String) entry.getKey(), (String) entry.getValue() ); } } public void start() throws StartingException { try { server.start(); } catch ( MultiException e ) { throw new StartingException( "Error starting the jetty webdav server: ", e ); } } public void stop() throws StoppingException { try { server.stop(); } catch ( InterruptedException e ) { throw new StoppingException( "Error stopping the jetty webdav server: ", e ); } } }
4,914
0
Create_ds/continuum/continuum-notifiers/continuum-notifier-wagon/src/test/java/org/apache/maven/continuum
Create_ds/continuum/continuum-notifiers/continuum-notifier-wagon/src/test/java/org/apache/maven/continuum/wagon/WagonContinuumNotifierTest.java
package org.apache.maven.continuum.wagon; /* * 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.PlexusSpringTestCase; 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.notification.ContinuumNotificationDispatcher; import org.apache.maven.continuum.notification.MessageContext; import org.apache.maven.continuum.notification.Notifier; import org.apache.maven.continuum.project.ContinuumProjectState; import org.junit.Before; import org.junit.Test; /** * @author <a href="mailto:nramirez@exist">Napoleon Esmundo C. Ramirez</a> */ public class WagonContinuumNotifierTest extends PlexusSpringTestCase { private ServletServer server; private Notifier notifier; private MessageContext context; @Before public void setUp() throws Exception { server = lookup( ServletServer.class ); notifier = (Notifier) lookup( Notifier.class.getName(), "wagon" ); Project project = new Project(); project.setId( 2 ); BuildResult build = new BuildResult(); build.setId( 1 ); build.setProject( project ); build.setStartTime( System.currentTimeMillis() ); build.setEndTime( System.currentTimeMillis() + 1234567 ); build.setState( ContinuumProjectState.OK ); build.setTrigger( ContinuumProjectState.TRIGGER_FORCED ); build.setExitCode( 0 ); BuildDefinition buildDefinition = new BuildDefinition(); buildDefinition.setBuildFile( "pom.xml" ); context = new MessageContext(); context.setProject( project ); context.setBuildResult( build ); context.setBuildDefinition( buildDefinition ); String basedir = System.getProperty( "basedir" ); if ( basedir == null ) { throw new Exception( "basedir must be defined" ); } } @Test public void testSendNotification() throws Exception { notifier.sendMessage( ContinuumNotificationDispatcher.MESSAGE_ID_BUILD_COMPLETE, context ); } }
4,915
0
Create_ds/continuum/continuum-notifiers/continuum-notifier-wagon/src/test/java/org/apache/maven/continuum
Create_ds/continuum/continuum-notifiers/continuum-notifier-wagon/src/test/java/org/apache/maven/continuum/wagon/Servlet.java
package org.apache.maven.continuum.wagon; /* * 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.Properties; /** * Servlet * * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a> */ public class Servlet { private String id; private Properties parameters; private String path; private String servlet; public String getId() { return id; } public Properties getParameters() { return parameters; } public String getPath() { return path; } public String getServlet() { return servlet; } }
4,916
0
Create_ds/continuum/continuum-notifiers/continuum-notifier-wagon/src/main/java/org/apache/maven/continuum/notification
Create_ds/continuum/continuum-notifiers/continuum-notifier-wagon/src/main/java/org/apache/maven/continuum/notification/wagon/WagonContinuumNotifier.java
package org.apache.maven.continuum.notification.wagon; /* * 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.artifact.manager.WagonManager; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.repository.DefaultArtifactRepository; import org.apache.maven.artifact.repository.layout.DefaultRepositoryLayout; 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.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.ProjectNotifier; 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.model.DistributionManagement; import org.apache.maven.model.Site; import org.apache.maven.profiles.DefaultProfileManager; import org.apache.maven.profiles.ProfileManager; import org.apache.maven.project.MavenProject; import org.apache.maven.project.MavenProjectBuilder; import org.apache.maven.project.ProjectBuildingException; import org.apache.maven.settings.MavenSettingsBuilder; import org.apache.maven.settings.Proxy; import org.apache.maven.settings.Server; import org.apache.maven.settings.Settings; import org.apache.maven.wagon.CommandExecutionException; import org.apache.maven.wagon.CommandExecutor; import org.apache.maven.wagon.ConnectionException; import org.apache.maven.wagon.ResourceDoesNotExistException; import org.apache.maven.wagon.TransferFailedException; import org.apache.maven.wagon.UnsupportedProtocolException; import org.apache.maven.wagon.Wagon; import org.apache.maven.wagon.authentication.AuthenticationException; import org.apache.maven.wagon.authentication.AuthenticationInfo; import org.apache.maven.wagon.authorization.AuthorizationException; import org.apache.maven.wagon.observers.Debug; import org.apache.maven.wagon.proxy.ProxyInfo; import org.apache.maven.wagon.repository.Repository; import org.codehaus.plexus.PlexusConstants; import org.codehaus.plexus.PlexusContainer; import org.codehaus.plexus.component.annotations.Configuration; 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.util.StringUtils; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import java.io.File; import java.io.IOException; import java.util.List; import java.util.Map; import javax.annotation.Resource; /** * @author <a href="mailto:hisidro@exist.com">Henry Isidro</a> * @author <a href="mailto:nramirez@exist.com">Napoleon Esmundo C. Ramirez</a> */ @Service( "notifier#wagon" ) public class WagonContinuumNotifier extends AbstractContinuumNotifier implements Contextualizable { public static final String BUILD_OUTPUT_FILE_NAME = "buildresult.txt"; private static final Logger log = LoggerFactory.getLogger( WagonContinuumNotifier.class ); @Resource private ConfigurationService configurationService; @Resource private WagonManager wagonManager; @Resource private MavenProjectBuilder projectBuilder; @Resource private MavenSettingsBuilder settingsBuilder; @Configuration( "" ) private String localRepository; private Settings settings; private ProfileManager profileManager; private PlexusContainer container; public WagonContinuumNotifier() { } public String getType() { return "wagon"; } public void sendMessage( String messageId, MessageContext context ) throws NotificationException { Project project = context.getProject(); List<ProjectNotifier> notifiers = context.getNotifiers(); BuildResult build = context.getBuildResult(); BuildDefinition buildDefinition = context.getBuildDefinition(); // ---------------------------------------------------------------------- // If there wasn't any building done, don't notify // ---------------------------------------------------------------------- if ( build == null ) { return; } // ---------------------------------------------------------------------- // Deloy build result to given url // ---------------------------------------------------------------------- try { /* * acquire the MavenProject associated to the Project in context */ MavenProject mavenProject = getMavenProject( project, buildDefinition ); if ( messageId.equals( ContinuumNotificationDispatcher.MESSAGE_ID_BUILD_COMPLETE ) ) { for ( ProjectNotifier notifier : notifiers ) { buildComplete( notifier, build, mavenProject ); } } } catch ( ContinuumException e ) { throw new NotificationException( "Error while notifiying.", e ); } } private void buildComplete( ProjectNotifier notifier, BuildResult build, MavenProject mavenProject ) throws ContinuumException { String id; String url; Map<String, String> configuration = notifier.getConfiguration(); if ( configuration.containsKey( "url" ) ) { url = configuration.get( "url" ); id = configuration.get( "id" ); } else { DistributionManagement distributionManagement = mavenProject.getDistributionManagement(); if ( distributionManagement == null ) { throw new ContinuumException( "Missing distribution management information in the project." ); } Site site = distributionManagement.getSite(); if ( site == null ) { throw new ContinuumException( "Missing site information in the distribution management element in the project." ); } url = site.getUrl(); id = site.getId(); } if ( url == null ) { throw new ContinuumException( "The URL to the site is not defined." ); } Repository repository = new Repository( id, url ); Wagon wagon; try { wagon = wagonManager.getWagon( repository.getProtocol() ); } catch ( UnsupportedProtocolException e ) { throw new ContinuumException( "Unsupported protocol: '" + repository.getProtocol() + "'", e ); } if ( !wagon.supportsDirectoryCopy() ) { throw new ContinuumException( "Wagon protocol '" + repository.getProtocol() + "' doesn't support directory copying" ); } try { if ( log.isDebugEnabled() ) { Debug debug = new Debug(); wagon.addSessionListener( debug ); wagon.addTransferListener( debug ); } ProxyInfo proxyInfo = getProxyInfo( repository ); if ( proxyInfo != null ) { wagon.connect( repository, getAuthenticationInfo( id ), proxyInfo ); } else { wagon.connect( repository, getAuthenticationInfo( id ) ); } File buildOutputFile = configurationService.getBuildOutputFile( build.getId(), build.getProject().getId() ); wagon.put( buildOutputFile, BUILD_OUTPUT_FILE_NAME ); // TODO: current wagon uses zip which will use the umask on remote host instead of honouring our settings // Force group writeable if ( wagon instanceof CommandExecutor ) { CommandExecutor exec = (CommandExecutor) wagon; exec.executeCommand( "chmod -Rf g+w " + repository.getBasedir() ); } } catch ( ConfigurationException e ) { throw new ContinuumException( "Error uploading build results to deployed site.", e ); } catch ( ResourceDoesNotExistException e ) { throw new ContinuumException( "Error uploading site", e ); } catch ( TransferFailedException e ) { throw new ContinuumException( "Error uploading site", e ); } catch ( AuthorizationException e ) { throw new ContinuumException( "Error uploading site", e ); } catch ( ConnectionException e ) { throw new ContinuumException( "Error uploading site", e ); } catch ( AuthenticationException e ) { throw new ContinuumException( "Error uploading site", e ); } catch ( CommandExecutionException e ) { throw new ContinuumException( "Error uploading site", e ); } finally { try { wagon.disconnect(); } catch ( ConnectionException e ) { log.error( "Error disconnecting wagon - ignored", e ); } } } private MavenProject getMavenProject( Project project, BuildDefinition buildDefinition ) throws ContinuumException { File projectWorkingDir = new File( configurationService.getWorkingDirectory(), Integer.toString( project.getId() ) ); File pomFile = new File( projectWorkingDir, buildDefinition.getBuildFile() ); MavenProject mavenProject; try { mavenProject = projectBuilder.build( pomFile, getLocalRepository(), getProfileManager() ); } catch ( ProjectBuildingException e ) { throw new ContinuumException( "Unable to acquire the MavenProject in " + pomFile.getAbsolutePath(), e ); } return mavenProject; } private Settings getSettings() { if ( settings == null ) { try { settings = settingsBuilder.buildSettings(); } catch ( IOException e ) { log.error( "Failed to get Settings", e ); } catch ( XmlPullParserException e ) { log.error( "Failed to get Settings", e ); } } return settings; } private ArtifactRepository getLocalRepository() { String repo = localRepository; if ( getSettings() != null && !StringUtils.isEmpty( getSettings().getLocalRepository() ) ) { repo = getSettings().getLocalRepository(); } return new DefaultArtifactRepository( "local-repository", "file://" + repo, new DefaultRepositoryLayout() ); } private ProfileManager getProfileManager() { if ( profileManager == null ) { profileManager = new DefaultProfileManager( container, getSettings() ); } return profileManager; } public void contextualize( Context context ) throws ContextException { container = (PlexusContainer) context.get( PlexusConstants.PLEXUS_KEY ); } private ProxyInfo getProxyInfo( Repository repository ) { Settings settings = getSettings(); if ( settings.getProxies() != null && !settings.getProxies().isEmpty() ) { for ( Proxy p : (List<Proxy>) settings.getProxies() ) { wagonManager.addProxy( p.getProtocol(), p.getHost(), p.getPort(), p.getUsername(), p.getPassword(), p.getNonProxyHosts() ); } } return wagonManager.getProxy( repository.getProtocol() ); } private AuthenticationInfo getAuthenticationInfo( String repositoryId ) { Settings settings = getSettings(); Server server = settings.getServer( repositoryId ); if ( server == null ) { return null; } wagonManager.addAuthenticationInfo( repositoryId, server.getUsername(), server.getPassword(), server.getPrivateKey(), server.getPassphrase() ); return wagonManager.getAuthenticationInfo( repositoryId ); } }
4,917
0
Create_ds/continuum/continuum-notifiers/continuum-notifier-irc/src/main/java/org/apache/maven/continuum/notification
Create_ds/continuum/continuum-notifiers/continuum-notifier-irc/src/main/java/org/apache/maven/continuum/notification/irc/IrcContinuumNotifier.java
package org.apache.maven.continuum.notification.irc; /* * 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.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.project.ProjectNotifier; 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.personality.plexus.lifecycle.phase.Disposable; import org.codehaus.plexus.util.StringUtils; import org.schwering.irc.lib.IRCConnection; import org.schwering.irc.lib.IRCConstants; import org.schwering.irc.lib.IRCEventListener; import org.schwering.irc.lib.IRCModeParser; import org.schwering.irc.lib.IRCUser; import org.schwering.irc.lib.ssl.SSLDefaultTrustManager; import org.schwering.irc.lib.ssl.SSLIRCConnection; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; /** * <b>This implementation assumes there aren't concurrent acces to the IRCConnection</b> * * @author <a href="mailto:evenisse@apache.org">Emmanuel Venisse</a> */ @Service( "notifier#irc" ) public class IrcContinuumNotifier extends AbstractContinuumNotifier implements Disposable { private static final Logger log = LoggerFactory.getLogger( IrcContinuumNotifier.class ); // ---------------------------------------------------------------------- // Requirements // ---------------------------------------------------------------------- @Resource private ConfigurationService configurationService; private int defaultPort = 6667; /** * key is upper(hostname) + port + upper(nick) + upper(alternateNick) */ private Map<String, IRCConnection> hostConnections = new HashMap<String, IRCConnection>(); private Map<String, List<String>> channelConnections = new HashMap<String, List<String>>(); // ---------------------------------------------------------------------- // Plexus Lifecycle // ---------------------------------------------------------------------- public void dispose() { // cleanup connections for ( String key : hostConnections.keySet() ) { IRCConnection connection = hostConnections.get( key ); if ( connection.isConnected() ) { connection.doQuit( "Continuum shutting down" ); connection.close(); } } } // ---------------------------------------------------------------------- // Internal connections // ---------------------------------------------------------------------- private IRCConnection getIRConnection( String host, int port, String password, String nick, String alternateNick, String userName, String realName, String channel, boolean ssl ) throws IOException { String key = getConnectionKey( host, port, nick, alternateNick ); IRCConnection conn = hostConnections.get( key ); if ( conn != null ) { checkConnection( conn, key ); return conn; } if ( !ssl ) { conn = new IRCConnection( host, new int[]{port}, password, nick, userName, realName ); } else { conn = new SSLIRCConnection( host, new int[]{port}, password, nick, userName, realName ); ( (SSLIRCConnection) conn ).addTrustManager( new SSLDefaultTrustManager() ); } conn.addIRCEventListener( new Listener( conn, nick, alternateNick ) ); checkConnection( conn, key ); checkChannel( conn, key, channel ); hostConnections.put( key, conn ); return conn; } private String getConnectionKey( String host, int port, String nick, String alternateNick ) { String nickname = nick; String alternateNickName = alternateNick; if ( nick == null ) { nickname = "null"; } if ( alternateNick == null ) { alternateNickName = "null"; } return host.toUpperCase() + Integer.toString( port ) + nickname.toUpperCase() + alternateNickName.toUpperCase(); } private void checkConnection( IRCConnection conn, String key ) throws IOException { if ( !conn.isConnected() ) { conn.connect(); //required for some servers that are slow to initialise the connection, in most of case, servers with auth try { Thread.sleep( 5000 ); } catch ( InterruptedException e ) { //nothing to do } //join to all channels List<String> channels = channelConnections.get( key ); if ( channels != null ) { for ( String channel : channels ) { connectToChannel( conn, channel ); } } } } private void checkChannel( IRCConnection conn, String key, String channel ) { List<String> channels = channelConnections.get( key ); if ( channels == null ) { connectToChannel( conn, channel ); channels = new ArrayList<String>(); channels.add( channel ); channelConnections.put( key, channels ); } else { boolean found = false; for ( String c : channels ) { if ( c.equalsIgnoreCase( channel ) ) { found = true; } } if ( !found ) { channels.add( channel ); channelConnections.put( key, channels ); } //reconnect unconditionally connectToChannel( conn, channel ); } } private void connectToChannel( IRCConnection conn, String channel ) { conn.doJoin( channel ); } // ---------------------------------------------------------------------- // Notifier Implementation // ---------------------------------------------------------------------- public String getType() { return "irc"; } public void sendMessage( String messageId, MessageContext context ) throws NotificationException { Project project = context.getProject(); List<ProjectNotifier> notifiers = context.getNotifiers(); BuildDefinition buildDefinition = context.getBuildDefinition(); BuildResult build = context.getBuildResult(); 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 message // ---------------------------------------------------------------------- if ( messageId.equals( ContinuumNotificationDispatcher.MESSAGE_ID_BUILD_COMPLETE ) ) { for ( ProjectNotifier notifier : notifiers ) { buildComplete( project, notifier, build, buildDefinition ); } } else if ( isPrepareBuildComplete ) { for ( ProjectNotifier notifier : notifiers ) { prepareBuildComplete( projectScmRoot, notifier ); } } } private void buildComplete( Project project, ProjectNotifier projectNotifier, BuildResult build, BuildDefinition buildDef ) throws NotificationException { // ---------------------------------------------------------------------- // Check if the message should be sent at all // ---------------------------------------------------------------------- BuildResult previousBuild = getPreviousBuild( project, buildDef, build ); if ( !shouldNotify( build, previousBuild, projectNotifier ) ) { return; } sendMessage( projectNotifier.getConfiguration(), generateMessage( project, build, configurationService ) ); } private void prepareBuildComplete( ProjectScmRoot projectScmRoot, ProjectNotifier projectNotifier ) throws NotificationException { // ---------------------------------------------------------------------- // Check if the message should be sent at all // ---------------------------------------------------------------------- if ( !shouldNotify( projectScmRoot, projectNotifier ) ) { return; } sendMessage( projectNotifier.getConfiguration(), generateMessage( projectScmRoot, configurationService ) ); } private void sendMessage( Map<String, String> configuration, String message ) throws NotificationException { // ---------------------------------------------------------------------- // Gather configuration values // ---------------------------------------------------------------------- String host = configuration.get( "host" ); String portAsString = configuration.get( "port" ); int port = defaultPort; if ( portAsString != null ) { port = Integer.parseInt( portAsString ); } String channel = configuration.get( "channel" ); String nickName = configuration.get( "nick" ); if ( StringUtils.isEmpty( nickName ) ) { nickName = "continuum"; } String alternateNickName = configuration.get( "alternateNick" ); if ( StringUtils.isEmpty( alternateNickName ) ) { alternateNickName = "continuum_"; } String userName = configuration.get( "username" ); if ( StringUtils.isEmpty( userName ) ) { userName = nickName; } String fullName = configuration.get( "fullName" ); if ( StringUtils.isEmpty( fullName ) ) { fullName = nickName; } String password = configuration.get( "password" ); boolean isSsl = Boolean.parseBoolean( configuration.get( "ssl" ) ); try { IRCConnection ircConnection = getIRConnection( host, port, password, nickName, alternateNickName, userName, fullName, channel, isSsl ); ircConnection.doPrivmsg( channel, message ); } catch ( IOException e ) { throw new NotificationException( "Exception while checkConnection to irc ." + host, e ); } } /** * Treats IRC events. The most of them are just printed. */ class Listener implements IRCEventListener { private String nick; private String alternateNick; private IRCConnection conn; public Listener( IRCConnection conn, String nick, String alternateNick ) { this.conn = conn; this.nick = nick; this.alternateNick = alternateNick; } public void onRegistered() { log.info( "Connected" ); } public void onDisconnected() { log.info( "Disconnected" ); } public void onError( String msg ) { log.error( "Error: " + msg ); } public void onError( int num, String msg ) { log.error( "Error #" + num + ": " + msg ); if ( num == IRCConstants.ERR_NICKNAMEINUSE ) { if ( alternateNick != null ) { log.info( "reconnection with alternate nick: '" + alternateNick + "'" ); try { boolean ssl = false; if ( conn instanceof SSLIRCConnection ) { ssl = true; } String key = getConnectionKey( conn.getHost(), conn.getPort(), nick, alternateNick ); conn = getIRConnection( conn.getHost(), conn.getPort(), conn.getPassword(), alternateNick, null, conn.getUsername(), conn.getRealname(), "#foo", ssl ); hostConnections.put( key, conn ); } catch ( IOException e ) { e.printStackTrace(); } } } } public void onInvite( String chan, IRCUser u, String nickPass ) { if ( log.isDebugEnabled() ) { log.debug( chan + "> " + u.getNick() + " invites " + nickPass ); } } public void onJoin( String chan, IRCUser u ) { if ( log.isDebugEnabled() ) { log.debug( chan + "> " + u.getNick() + " joins" ); } } public void onKick( String chan, IRCUser u, String nickPass, String msg ) { if ( log.isDebugEnabled() ) { log.debug( chan + "> " + u.getNick() + " kicks " + nickPass ); } } public void onMode( IRCUser u, String nickPass, String mode ) { if ( log.isDebugEnabled() ) { log.debug( "Mode: " + u.getNick() + " sets modes " + mode + " " + nickPass ); } } public void onMode( String chan, IRCUser u, IRCModeParser mp ) { if ( log.isDebugEnabled() ) { log.debug( chan + "> " + u.getNick() + " sets mode: " + mp.getLine() ); } } public void onNick( IRCUser u, String nickNew ) { if ( log.isDebugEnabled() ) { log.debug( "Nick: " + u.getNick() + " is now known as " + nickNew ); } } public void onNotice( String target, IRCUser u, String msg ) { log.info( target + "> " + u.getNick() + " (notice): " + msg ); } public void onPart( String chan, IRCUser u, String msg ) { if ( log.isDebugEnabled() ) { log.debug( chan + "> " + u.getNick() + " parts" ); } } public void onPrivmsg( String chan, IRCUser u, String msg ) { if ( log.isDebugEnabled() ) { log.debug( chan + "> " + u.getNick() + ": " + msg ); } } public void onQuit( IRCUser u, String msg ) { if ( log.isDebugEnabled() ) { log.debug( "Quit: " + u.getNick() ); } } public void onReply( int num, String value, String msg ) { log.info( "Reply #" + num + ": " + value + " " + msg ); } public void onTopic( String chan, IRCUser u, String topic ) { if ( log.isDebugEnabled() ) { log.debug( chan + "> " + u.getNick() + " changes topic into: " + topic ); } } public void onPing( String p ) { if ( log.isDebugEnabled() ) { log.debug( "Ping:" + p ); } } public void unknown( String a, String b, String c, String d ) { if ( log.isDebugEnabled() ) { log.debug( "UNKNOWN: " + a + " b " + c + " " + d ); } } } }
4,918
0
Create_ds/continuum/continuum-reports/src/test/java/org/apache/maven/continuum/reports
Create_ds/continuum/continuum-reports/src/test/java/org/apache/maven/continuum/reports/surefire/ConfigurationServiceMock.java
package org.apache.maven.continuum.reports.surefire; /* * 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 java.io.File; public class ConfigurationServiceMock extends org.apache.maven.continuum.configuration.ConfigurationServiceMock { public File getTestReportsDirectory( int buildId, int projectId ) throws ConfigurationException { return new File( "src" + File.separatorChar + "test" + File.separatorChar + "resources" + File.separatorChar + "continuum-core" ); } }
4,919
0
Create_ds/continuum/continuum-reports/src/test/java/org/apache/maven/continuum/reports
Create_ds/continuum/continuum-reports/src/test/java/org/apache/maven/continuum/reports/surefire/DefaultReportTestSuiteGeneratorTest.java
package org.apache.maven.continuum.reports.surefire; /* * 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.PlexusSpringTestCase; import org.junit.Test; import java.io.File; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * @author <a href="mailto:olamy@apache.org">olamy</a> * @since 12 nov. 07 */ public class DefaultReportTestSuiteGeneratorTest extends PlexusSpringTestCase { private File getReportsDirectory( String pathDir ) { return new File( getBasedir() + File.separatorChar + "src" + File.separatorChar + "test" + File.separatorChar + "resources" + File.separatorChar + pathDir ); } @Test public void testSimpleFile() throws Exception { File testDirectory = getReportsDirectory( "simplereport" ); ReportTestSuiteGenerator generator = lookup( ReportTestSuiteGenerator.class, "default" ); List<ReportTestSuite> reports = generator.generateReports( testDirectory ); assertEquals( 1, reports.size() ); ReportTestSuite report = reports.get( 0 ); assertEquals( "AppTest", report.getName() ); assertEquals( 1, report.getNumberOfTests() ); } @Test public void testContinuumCore() throws Exception { ReportTestSuiteGenerator generator = lookup( ReportTestSuiteGenerator.class, "default" ); List<ReportTestSuite> reports = generator.generateReports( 1, 1 ); assertEquals( 18, reports.size() ); for ( ReportTestSuite report : reports ) { if ( report.getName().equals( "MailContinuumNotifierTest" ) && report.getPackageName().equals( "org.apache.maven.continuum.notification.mail" ) ) { assertEquals( 1, report.getNumberOfFailures() ); // don't test this because can plate forme dependant //assertEquals( 11.578, report.getTimeElapsed() ); assertEquals( 3, report.getNumberOfTests() ); for ( ReportTestCase testCase : report.getTestCases() ) { if ( testCase.getName().equals( "testSuccessfulBuild" ) ) { assertEquals( "junit.framework.ComparisonFailure", testCase.getFailureType() ); assertEquals( "expected:&lt;...s&gt; but was:&lt;...&gt;", testCase.getFailureMessage() ); assertTrue( testCase.getFailureDetails().startsWith( "junit.framework.ComparisonFailure" ) ); } } } } } @Test public void testGenerateReportTestResult() throws Exception { ReportTestSuiteGenerator generator = lookup( ReportTestSuiteGenerator.class, "default" ); ReportTestResult reportTestResult = generator.generateReportTestResult( 1, 1 ); assertEquals( 18, reportTestResult.getSuiteResults().size() ); assertEquals( 1, reportTestResult.getFailureCount() ); assertEquals( 62, reportTestResult.getTestCount() ); assertEquals( 1, reportTestResult.getErrorCount() ); } }
4,920
0
Create_ds/continuum/continuum-reports/src/main/java/org/apache/maven/continuum/reports
Create_ds/continuum/continuum-reports/src/main/java/org/apache/maven/continuum/reports/surefire/ReportTestSuiteGenerator.java
package org.apache.maven.continuum.reports.surefire; /* * 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.List; /** * @author <a href="mailto:olamy@apache.org">olamy</a> * @since 12 nov. 07 */ public interface ReportTestSuiteGenerator { /** * @param directory directory containing surefire tests files * @param includes file types to include * @param excludes file types to exclude * @return List of {@link ReportTestSuite} * @throws ReportTestSuiteGeneratorException * */ List<ReportTestSuite> generateReports( File directory, List<String> includes, List<String> excludes ) throws ReportTestSuiteGeneratorException; /** * Use generateReports with default includes *.xml and default excludes *.txt * * @param directory directory containing surefire tests files * @return List of {@link ReportTestSuite} * @throws ReportTestSuiteGeneratorException * */ List<ReportTestSuite> generateReports( File directory ) throws ReportTestSuiteGeneratorException; /** * @param buildId * @param projectId * @return List of {@link ReportTestSuite} * @throws ReportTestSuiteGeneratorException * */ List<ReportTestSuite> generateReports( int buildId, int projectId ) throws ReportTestSuiteGeneratorException; /** * @param buildId * @param projectId * @return List of {@link ReportTestResult} * @throws ReportTestSuiteGeneratorException * */ ReportTestResult generateReportTestResult( int buildId, int projectId ) throws ReportTestSuiteGeneratorException; }
4,921
0
Create_ds/continuum/continuum-reports/src/main/java/org/apache/maven/continuum/reports
Create_ds/continuum/continuum-reports/src/main/java/org/apache/maven/continuum/reports/surefire/ReportTest.java
package org.apache.maven.continuum.reports.surefire; /* * 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.List; /** * @author <a href="mailto:olamy@apache.org">olamy</a> * @since 12 nov. 07 */ public class ReportTest { private String id; private String name; private int tests; private int errors; private int failures; private float elapsedTime; private List children; public String getName() { return name; } public void setName( String name ) { this.name = name; } public int getTests() { return tests; } public void setTests( int tests ) { this.tests = tests; } public int getErrors() { return errors; } public void setErrors( int errors ) { this.errors = errors; } public int getFailures() { return failures; } public void setFailures( int failures ) { this.failures = failures; } public float getSuccessRate() { float percentage; if ( tests == 0 ) { percentage = 0; } else { percentage = ( (float) ( tests - errors - failures ) / (float) tests ) * 100; } return percentage; } public float getElapsedTime() { return elapsedTime; } public void setElapsedTime( float elapsedTime ) { this.elapsedTime = elapsedTime; } public List getChildren() { if ( children == null ) { children = new ArrayList(); } return children; } public void setChildren( List children ) { this.children = children; } public String getId() { return id; } public void setId( String id ) { this.id = id; } }
4,922
0
Create_ds/continuum/continuum-reports/src/main/java/org/apache/maven/continuum/reports
Create_ds/continuum/continuum-reports/src/main/java/org/apache/maven/continuum/reports/surefire/ReportTestSuiteGeneratorException.java
package org.apache.maven.continuum.reports.surefire; /* * 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:olamy@apache.org">olamy</a> * @since 12 nov. 07 */ public class ReportTestSuiteGeneratorException extends Exception { /** * */ public ReportTestSuiteGeneratorException() { // nothing } /** * @param message */ public ReportTestSuiteGeneratorException( String message ) { super( message ); } /** * @param cause */ public ReportTestSuiteGeneratorException( Throwable cause ) { super( cause ); } /** * @param message * @param cause */ public ReportTestSuiteGeneratorException( String message, Throwable cause ) { super( message, cause ); } }
4,923
0
Create_ds/continuum/continuum-reports/src/main/java/org/apache/maven/continuum/reports
Create_ds/continuum/continuum-reports/src/main/java/org/apache/maven/continuum/reports/surefire/ReportFailure.java
package org.apache.maven.continuum.reports.surefire; /* * 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:olamy@apache.org">olamy</a> * @since 13 nov. 07 */ public class ReportFailure { private String type; private String exception; private String testName; public ReportFailure( String type, String exception, String testName ) { this.type = type; this.exception = exception; this.testName = testName; } public String getType() { return type; } public void setType( String type ) { this.type = type; } public String getException() { return exception; } public void setException( String exception ) { this.exception = exception; } public String getTestName() { return testName; } public void setTestName( String testName ) { this.testName = testName; } }
4,924
0
Create_ds/continuum/continuum-reports/src/main/java/org/apache/maven/continuum/reports
Create_ds/continuum/continuum-reports/src/main/java/org/apache/maven/continuum/reports/surefire/ReportTestResult.java
package org.apache.maven.continuum.reports.surefire; /* * 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.LinkedList; import java.util.List; /** * @author <a href="mailto:olamy@apache.org">olamy</a> * @since 13 nov. 07 */ public class ReportTestResult { private int testCount = 0; private int failureCount = 0; private int errorCount = 0; private float totalTime = 0; private List<ReportTestSuite> suiteResults; public void addReportTestSuite( ReportTestSuite reportTestSuite ) { if ( this.suiteResults == null ) { this.suiteResults = new LinkedList<ReportTestSuite>(); } this.suiteResults.add( reportTestSuite ); this.testCount += reportTestSuite.getNumberOfTests(); this.failureCount += reportTestSuite.getNumberOfFailures(); this.errorCount += reportTestSuite.getNumberOfErrors(); this.totalTime += reportTestSuite.getTimeElapsed(); } public int getTestCount() { return testCount; } public void setTestCount( int testCount ) { this.testCount = testCount; } public int getFailureCount() { return failureCount; } public void setFailureCount( int failureCount ) { this.failureCount = failureCount; } public int getErrorCount() { return errorCount; } public void setErrorCount( int errorCount ) { this.errorCount = errorCount; } public List<ReportTestSuite> getSuiteResults() { return suiteResults; } public void setSuiteResults( List<ReportTestSuite> suiteResults ) { this.suiteResults = suiteResults; } public float getTotalTime() { return totalTime; } public void setTotalTime( float totalTime ) { this.totalTime = totalTime; } }
4,925
0
Create_ds/continuum/continuum-reports/src/main/java/org/apache/maven/continuum/reports
Create_ds/continuum/continuum-reports/src/main/java/org/apache/maven/continuum/reports/surefire/ReportTestCase.java
package org.apache.maven.continuum.reports.surefire; /* * 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. */ /** * Taken from maven-surefire-report-plugin * * @author <a href="mailto:olamy@apache.org">olamy</a> * @since 12 nov. 07 */ public class ReportTestCase { private String fullClassName; private String className; private String fullName; private String name; private float time; private String failureType; private String failureMessage; private String failureDetails; public String getName() { return name; } public void setName( String name ) { this.name = name; } public String getFullClassName() { return fullClassName; } public void setFullClassName( String name ) { this.fullClassName = name; } public String getClassName() { return className; } public void setClassName( String name ) { this.className = name; } public float getTime() { return time; } public void setTime( float time ) { this.time = time; } public String getFullName() { return fullName; } public void setFullName( String fullName ) { this.fullName = fullName; } public String getFailureType() { return failureType; } public void setFailureType( String failureType ) { this.failureType = failureType; } public String getFailureMessage() { return failureMessage; } public void setFailureMessage( String failureMessage ) { this.failureMessage = failureMessage; } public String getFailureDetails() { return failureDetails; } public void setFailureDetails( String failureDetails ) { this.failureDetails = failureDetails; } }
4,926
0
Create_ds/continuum/continuum-reports/src/main/java/org/apache/maven/continuum/reports
Create_ds/continuum/continuum-reports/src/main/java/org/apache/maven/continuum/reports/surefire/ReportTestSuite.java
package org.apache.maven.continuum.reports.surefire; /* * 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.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import java.io.File; import java.io.IOException; import java.text.NumberFormat; import java.text.ParseException; import java.util.Collections; import java.util.LinkedList; import java.util.List; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; /** * @author <a href="mailto:olamy@apache.org">olamy</a> * @since 12 nov. 07 */ public class ReportTestSuite extends DefaultHandler { private List<ReportTestCase> testCases; private int numberOfErrors; private int numberOfFailures; private int numberOfTests; private String name; private String fullClassName; private String packageName; private float timeElapsed; private final NumberFormat numberFormat = NumberFormat.getInstance(); /** * @noinspection StringBufferField */ private StringBuffer currentElement; private ReportTestCase testCase; private List<ReportFailure> reportFailures; public void parse( String xmlPath ) throws ParserConfigurationException, SAXException, IOException { SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); saxParser.parse( new File( xmlPath ), this ); } public void startElement( String uri, String localName, String qName, Attributes attributes ) throws SAXException { try { if ( "testsuite".equals( qName ) ) { numberOfErrors = Integer.parseInt( attributes.getValue( "errors" ) ); numberOfFailures = Integer.parseInt( attributes.getValue( "failures" ) ); numberOfTests = Integer.parseInt( attributes.getValue( "tests" ) ); Number time = numberFormat.parse( attributes.getValue( "time" ) ); timeElapsed = time.floatValue(); //check if group attribute is existing if ( attributes.getValue( "group" ) != null && !"".equals( attributes.getValue( "group" ) ) ) { packageName = attributes.getValue( "group" ); name = attributes.getValue( "name" ); fullClassName = packageName + "." + name; } else { fullClassName = attributes.getValue( "name" ); name = fullClassName.substring( fullClassName.lastIndexOf( "." ) + 1, fullClassName.length() ); int lastDotPosition = fullClassName.lastIndexOf( "." ); if ( lastDotPosition < 0 ) { /* no package name */ packageName = ""; } else { packageName = fullClassName.substring( 0, lastDotPosition ); } } testCases = new LinkedList<ReportTestCase>(); } else if ( "testcase".equals( qName ) ) { currentElement = new StringBuffer(); testCase = new ReportTestCase(); testCase.setFullClassName( fullClassName ); testCase.setName( attributes.getValue( "name" ) ); testCase.setClassName( name ); String timeAsString = attributes.getValue( "time" ); Number time = 0; if ( timeAsString != null ) { time = numberFormat.parse( timeAsString ); } testCase.setTime( time.floatValue() ); testCase.setFullName( packageName + "." + name + "." + testCase.getName() ); } else if ( "failure".equals( qName ) ) { testCase.setFailureType( attributes.getValue( "type" ) ); testCase.setFailureMessage( attributes.getValue( "message" ) ); } else if ( "error".equals( qName ) ) { testCase.setFailureType( attributes.getValue( "type" ) ); testCase.setFailureMessage( attributes.getValue( "message" ) ); } } catch ( ParseException e ) { throw new SAXException( e.getMessage(), e ); } } public void endElement( String uri, String localName, String qName ) throws SAXException { if ( "testcase".equals( qName ) ) { testCases.add( testCase ); } else if ( "failure".equals( qName ) ) { testCase.setFailureDetails( currentElement.toString() ); this.addReportFailure( new ReportFailure( testCase.getFailureType(), testCase.getFailureDetails(), testCase.getName() ) ); } else if ( "error".equals( qName ) ) { testCase.setFailureDetails( currentElement.toString() ); this.addReportFailure( new ReportFailure( testCase.getFailureType(), testCase.getFailureDetails(), testCase.getName() ) ); } } public void characters( char[] ch, int start, int length ) throws SAXException { String s = new String( ch, start, length ); if ( !"".equals( s.trim() ) ) { currentElement.append( s ); } } public List<ReportTestCase> getTestCases() { return this.testCases; } public int getNumberOfErrors() { return numberOfErrors; } public void setNumberOfErrors( int numberOfErrors ) { this.numberOfErrors = numberOfErrors; } public int getNumberOfFailures() { return numberOfFailures; } public void setNumberOfFailures( int numberOfFailures ) { this.numberOfFailures = numberOfFailures; } public int getNumberOfTests() { return numberOfTests; } public void setNumberOfTests( int numberOfTests ) { this.numberOfTests = numberOfTests; } public String getName() { return name; } public void setName( String name ) { this.name = name; } public String getFName() { return name; } public void setFName( String name ) { this.name = name; } public String getPackageName() { return packageName; } public void setPackageName( String packageName ) { this.packageName = packageName; } public float getTimeElapsed() { return this.timeElapsed; } public void setTimeElapsed( float timeElapsed ) { this.timeElapsed = timeElapsed; } /* private List<String> parseCause( String detail ) { String fullName = testCase.getFullName(); String name = fullName.substring( fullName.lastIndexOf( "." ) + 1 ); return parseCause( detail, name ); } private List<String> parseCause( String detail, String compareTo ) { StringTokenizer stringTokenizer = new StringTokenizer( detail, "\n" ); List<String> parsedDetail = new ArrayList<String>( stringTokenizer.countTokens() ); while ( stringTokenizer.hasMoreTokens() ) { String lineString = stringTokenizer.nextToken().trim(); parsedDetail.add( lineString ); if ( lineString.indexOf( compareTo ) >= 0 ) { break; } } return parsedDetail; } */ public void setTestCases( List<ReportTestCase> testCases ) { this.testCases = Collections.unmodifiableList( testCases ); } @SuppressWarnings( "unchecked" ) public List<ReportFailure> getReportFailures() { return reportFailures == null ? Collections.EMPTY_LIST : reportFailures; } public void setReportFailures( List<ReportFailure> reportFailures ) { this.reportFailures = reportFailures; } public void addReportFailure( ReportFailure reportFailure ) { if ( this.reportFailures == null ) { this.reportFailures = new LinkedList<ReportFailure>(); } this.reportFailures.add( reportFailure ); } }
4,927
0
Create_ds/continuum/continuum-reports/src/main/java/org/apache/maven/continuum/reports
Create_ds/continuum/continuum-reports/src/main/java/org/apache/maven/continuum/reports/surefire/DefaultReportTestSuiteGenerator.java
package org.apache.maven.continuum.reports.surefire; /* * 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.codehaus.plexus.personality.plexus.lifecycle.phase.Initializable; import org.codehaus.plexus.personality.plexus.lifecycle.phase.InitializationException; import org.codehaus.plexus.util.DirectoryScanner; import org.springframework.stereotype.Service; import org.xml.sax.SAXException; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; import javax.annotation.Resource; import javax.xml.parsers.ParserConfigurationException; /** * @author <a href="mailto:olamy@apache.org">olamy</a> * @since 12 nov. 07 */ @Service( "reportTestSuiteGenerator" ) public class DefaultReportTestSuiteGenerator implements ReportTestSuiteGenerator, Initializable { @Resource private ConfigurationService configurationService; private List<String> defaultIncludes; private List<String> defaultexcludes; // ----------------------------- // Plexus Lifecycle // ----------------------------- public void initialize() throws InitializationException { defaultIncludes = new ArrayList<String>( 1 ); defaultIncludes.add( "*.xml" ); defaultexcludes = new ArrayList<String>( 1 ); defaultexcludes.add( "*.txt" ); } /** * @see org.apache.maven.continuum.reports.surefire.ReportTestSuiteGenerator#generateReports(java.io.File, java.util.List, java.util.List) */ public List<ReportTestSuite> generateReports( File directory, List<String> includes, List<String> excludes ) throws ReportTestSuiteGeneratorException { if ( directory == null ) { return Collections.EMPTY_LIST; } if ( !directory.exists() ) { return Collections.EMPTY_LIST; } List<ReportTestSuite> reportTestSuites = new LinkedList<ReportTestSuite>(); String[] includesArray; if ( includes == null ) { includesArray = new String[0]; } else { includesArray = includes.toArray( new String[includes.size()] ); } String[] excludesArray; if ( excludes == null ) { excludesArray = new String[0]; } else { excludesArray = excludes.toArray( new String[excludes.size()] ); } String[] xmlReportFiles = getIncludedFiles( directory, includesArray, excludesArray ); if ( xmlReportFiles == null ) { return Collections.EMPTY_LIST; } if ( xmlReportFiles.length == 0 ) { return Collections.EMPTY_LIST; } for ( String currentReport : xmlReportFiles ) { ReportTestSuite testSuite = new ReportTestSuite(); try { testSuite.parse( directory + File.separator + currentReport ); } catch ( ParserConfigurationException e ) { throw new ReportTestSuiteGeneratorException( "Error setting up parser for Surefire XML report", e ); } catch ( SAXException e ) { throw new ReportTestSuiteGeneratorException( "Error parsing Surefire XML report " + currentReport, e ); } catch ( IOException e ) { throw new ReportTestSuiteGeneratorException( "Error reading Surefire XML report " + currentReport, e ); } reportTestSuites.add( testSuite ); } return reportTestSuites; } /** * @see org.apache.maven.continuum.reports.surefire.ReportTestSuiteGenerator#generateReports(java.io.File) */ public List<ReportTestSuite> generateReports( File directory ) throws ReportTestSuiteGeneratorException { return generateReports( directory, defaultIncludes, defaultexcludes ); } /** * @see org.apache.maven.continuum.reports.surefire.ReportTestSuiteGenerator#generateReports(int, int) */ public List<ReportTestSuite> generateReports( int buildId, int projectId ) throws ReportTestSuiteGeneratorException { try { File directory = configurationService.getTestReportsDirectory( buildId, projectId ); return generateReports( directory ); } catch ( ConfigurationException e ) { throw new ReportTestSuiteGeneratorException( e.getMessage(), e ); } } /** * @see org.apache.maven.continuum.reports.surefire.ReportTestSuiteGenerator#generateReportTestResult(int, int) */ public ReportTestResult generateReportTestResult( int buildId, int projectId ) throws ReportTestSuiteGeneratorException { List<ReportTestSuite> reportTestSuites = generateReports( buildId, projectId ); ReportTestResult reportTestResult = new ReportTestResult(); for ( ReportTestSuite reportTestSuite : reportTestSuites ) { reportTestResult.addReportTestSuite( reportTestSuite ); } return reportTestResult; } private String[] getIncludedFiles( File directory, String[] includes, String[] excludes ) { DirectoryScanner scanner = new DirectoryScanner(); scanner.setBasedir( directory ); scanner.setIncludes( includes ); scanner.setExcludes( excludes ); scanner.scan(); return scanner.getIncludedFiles(); } }
4,928
0
Create_ds/continuum/continuum-test/src/main/java/org/apache/maven
Create_ds/continuum/continuum-test/src/main/java/org/apache/maven/continuum/AbstractContinuumTest.java
package org.apache.maven.continuum; /* * 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.DaoUtils; import org.apache.continuum.dao.ProjectDao; import org.apache.continuum.dao.ProjectGroupDao; import org.apache.continuum.dao.ProjectScmRootDao; import org.apache.continuum.dao.ScheduleDao; import org.apache.continuum.utils.file.FileSystemManager; import org.apache.maven.continuum.configuration.ConfigurationService; import org.apache.maven.continuum.execution.ContinuumBuildExecutor; import org.apache.maven.continuum.execution.ContinuumBuildExecutorConstants; import org.apache.maven.continuum.initialization.ContinuumInitializer; import org.apache.maven.continuum.jdo.MemoryJdoFactory; 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.ProjectNotifier; import org.apache.maven.continuum.model.scm.ScmResult; import org.apache.maven.continuum.store.ContinuumObjectNotFoundException; import org.apache.maven.continuum.store.ContinuumStoreException; import org.codehaus.plexus.jdo.JdoFactory; import org.jpox.SchemaTool; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.rules.TestName; import javax.jdo.PersistenceManager; import javax.jdo.PersistenceManagerFactory; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Properties; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; /** * @author <a href="mailto:trygvis@inamo.no">Trygve Laugst&oslash;l</a> */ public abstract class AbstractContinuumTest extends PlexusSpringTestCase { private DaoUtils daoUtils; private ProjectDao projectDao; private ProjectGroupDao projectGroupDao; private ScheduleDao scheduleDao; private ProjectScmRootDao projectScmRootDao; private FileSystemManager fsManager; @Rule public TestName testName = new TestName(); protected String getName() { return testName.getMethodName(); } // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- @Before public void setupContinuum() throws Exception { init(); getProjectDao(); getProjectGroupDao(); getScheduleDao(); getProjectScmRootDao(); getFileSystemManager(); setUpConfigurationService( (ConfigurationService) lookup( "configurationService" ) ); Collection<ProjectGroup> projectGroups = projectGroupDao.getAllProjectGroupsWithProjects(); if ( projectGroups.size() == 0 ) //if ContinuumInitializer is loaded by Spring at startup, size == 1 { createDefaultProjectGroup(); projectGroups = projectGroupDao.getAllProjectGroupsWithProjects(); } assertEquals( 1, projectGroups.size() ); } @After public void wipeData() throws Exception { daoUtils.eraseDatabase(); } protected void createDefaultProjectGroup() throws Exception { try { getDefaultProjectGroup(); } catch ( ContinuumObjectNotFoundException e ) { ProjectGroup group; group = new ProjectGroup(); group.setName( "Default Project Group" ); group.setGroupId( ContinuumInitializer.DEFAULT_PROJECT_GROUP_GROUP_ID ); group.setDescription( "Contains all projects that do not have a group of their own" ); projectGroupDao.addProjectGroup( group ); } } public static void setUpConfigurationService( ConfigurationService configurationService ) throws Exception { configurationService.setBuildOutputDirectory( getTestFile( "target/build-output" ) ); configurationService.setWorkingDirectory( getTestFile( "target/working-directory" ) ); configurationService.setReleaseOutputDirectory( getTestFile( "target/release-output" ) ); configurationService.store(); } protected ProjectGroup getDefaultProjectGroup() throws ContinuumStoreException { return projectGroupDao.getProjectGroupByGroupIdWithProjects( ContinuumInitializer.DEFAULT_PROJECT_GROUP_GROUP_ID ); } // ---------------------------------------------------------------------- // Store // ---------------------------------------------------------------------- private void init() throws Exception { // ---------------------------------------------------------------------- // Set up the JDO factory // ---------------------------------------------------------------------- MemoryJdoFactory jdoFactory = (MemoryJdoFactory) lookup( JdoFactory.class, "continuum" ); assertEquals( MemoryJdoFactory.class.getName(), jdoFactory.getClass().getName() ); String url = "jdbc:hsqldb:mem:" + getClass().getName() + "." + getName(); jdoFactory.setUrl( url ); jdoFactory.reconfigure(); // ---------------------------------------------------------------------- // Check the configuration // ---------------------------------------------------------------------- PersistenceManagerFactory pmf = jdoFactory.getPersistenceManagerFactory(); assertNotNull( pmf ); assertEquals( url, pmf.getConnectionURL() ); PersistenceManager pm = pmf.getPersistenceManager(); pm.close(); // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- Properties properties = jdoFactory.getProperties(); for ( Map.Entry entry : properties.entrySet() ) { System.setProperty( (String) entry.getKey(), (String) entry.getValue() ); } SchemaTool.createSchemaTables( new URL[] { getClass().getResource( "/package.jdo" ) }, new URL[] {}, null, false, null ); // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- daoUtils = lookup( DaoUtils.class ); daoUtils.rebuildStore(); } protected ProjectDao getProjectDao() { if ( projectDao == null ) { projectDao = (ProjectDao) lookup( ProjectDao.class.getName() ); } return projectDao; } protected ProjectGroupDao getProjectGroupDao() { if ( projectGroupDao == null ) { projectGroupDao = (ProjectGroupDao) lookup( ProjectGroupDao.class.getName() ); } return projectGroupDao; } protected ScheduleDao getScheduleDao() { if ( scheduleDao == null ) { scheduleDao = (ScheduleDao) lookup( ScheduleDao.class.getName() ); } return scheduleDao; } protected ProjectScmRootDao getProjectScmRootDao() { if ( projectScmRootDao == null ) { projectScmRootDao = (ProjectScmRootDao) lookup( ProjectScmRootDao.class.getName() ); } return projectScmRootDao; } public FileSystemManager getFileSystemManager() { if ( fsManager == null ) { fsManager = (FileSystemManager) lookup( FileSystemManager.class ); } return fsManager; } // ---------------------------------------------------------------------- // Build Executor // ---------------------------------------------------------------------- protected ContinuumBuildExecutor getBuildExecutor( String id ) throws Exception { ContinuumBuildExecutor buildExecutor = (ContinuumBuildExecutor) lookup( ContinuumBuildExecutor.ROLE, id ); assertNotNull( "Could not look up build executor '" + id + "'", buildExecutor ); return buildExecutor; } // ---------------------------------------------------------------------- // Maven 2 Project Generators // ---------------------------------------------------------------------- public static Project makeStubProject( String name ) { return makeProject( name, "foo@bar.com", "1.0" ); } public static Project makeProject( String name, String emailAddress, String version ) { Project project = new Project(); makeProject( project, name, version ); List<ProjectNotifier> notifiers = createMailNotifierList( emailAddress ); project.setNotifiers( notifiers ); return project; } // ---------------------------------------------------------------------- // Shell Project Generators // ---------------------------------------------------------------------- public static Project makeStubShellProject( String name, String script ) { Project project = new Project(); makeProject( project, name, "1.0" ); project.setExecutorId( ContinuumBuildExecutorConstants.SHELL_BUILD_EXECUTOR ); BuildDefinition def = new BuildDefinition(); def.setBuildFile( script ); project.addBuildDefinition( def ); return project; } public static Project makeProject( Project project, String name, String version ) { project.setExecutorId( ContinuumBuildExecutorConstants.MAVEN_TWO_BUILD_EXECUTOR ); project.setName( name ); project.setVersion( version ); return project; } protected static List<ProjectNotifier> createMailNotifierList( String emailAddress ) { if ( emailAddress == null ) { return null; } ProjectNotifier notifier = new ProjectNotifier(); notifier.setType( "mail" ); Properties props = new Properties(); props.put( "address", emailAddress ); notifier.setConfiguration( props ); List<ProjectNotifier> notifiers = new ArrayList<ProjectNotifier>(); notifiers.add( notifier ); return notifiers; } // ---------------------------------------------------------------------- // Public utility methods // ---------------------------------------------------------------------- public Project addProject( Project project ) throws Exception { ProjectGroup defaultProjectGroup = getDefaultProjectGroup(); // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- ScmResult scmResult = new ScmResult(); scmResult.setSuccess( true ); scmResult.setCommandOutput( "commandOutput" ); scmResult.setProviderMessage( "providerMessage" ); project.setCheckoutResult( scmResult ); defaultProjectGroup.addProject( project ); projectGroupDao.updateProjectGroup( defaultProjectGroup ); project = projectDao.getProject( project.getId() ); assertNotNull( "project group == null", project.getProjectGroup() ); return project; } public Project addProject( String name ) throws Exception { return addProject( makeStubProject( name ) ); } // ---------------------------------------------------------------------- // Assertions // ---------------------------------------------------------------------- public void assertProjectEquals( Project expected, Project actual ) { assertProjectEquals( expected.getName(), expected.getNotifiers(), expected.getVersion(), actual ); } public void assertProjectEquals( String name, String emailAddress, String version, Project actual ) { assertProjectEquals( name, createMailNotifierList( emailAddress ), version, actual ); } public void assertProjectEquals( String name, List<ProjectNotifier> notifiers, String version, Project actual ) { assertEquals( "project.name", name, actual.getName() ); if ( notifiers != null ) { assertNotNull( "project.notifiers", actual.getNotifiers() ); assertEquals( "project.notifiers.size", notifiers.size(), actual.getNotifiers().size() ); for ( int i = 0; i < notifiers.size(); i++ ) { ProjectNotifier notifier = notifiers.get( i ); ProjectNotifier actualNotifier = (ProjectNotifier) actual.getNotifiers().get( i ); assertEquals( "project.notifiers.notifier.type", notifier.getType(), actualNotifier.getType() ); assertEquals( "project.notifiers.notifier.configuration.address", notifier.getConfiguration().get( "address" ), actualNotifier.getConfiguration().get( "address" ) ); } } assertEquals( "project.version", version, actual.getVersion() ); } // ---------------------------------------------------------------------- // Simple utils // ---------------------------------------------------------------------- public ProjectGroup createStubProjectGroup( String name, String description ) { ProjectGroup projectGroup = new ProjectGroup(); projectGroup.setName( name ); projectGroup.setGroupId( name ); projectGroup.setDescription( description ); return projectGroup; } public Project addProject( String name, ProjectGroup group ) throws Exception { Project project = makeStubProject( name ); project.setGroupId( group.getGroupId() ); group.addProject( project ); try { projectGroupDao.getProjectGroup( group.getId() ); projectGroupDao.updateProjectGroup( group ); } catch ( ContinuumObjectNotFoundException e ) { projectGroupDao.addProjectGroup( group ); } return projectDao.getProject( project.getId() ); } }
4,929
0
Create_ds/continuum/continuum-test/src/main/java/org/apache/maven
Create_ds/continuum/continuum-test/src/main/java/org/apache/maven/continuum/PlexusSpringTestCase.java
package org.apache.maven.continuum; /* * 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.PlexusContainer; import org.codehaus.plexus.spring.PlexusClassPathXmlApplicationContext; import org.codehaus.plexus.spring.PlexusToSpringUtils; import org.junit.After; import org.junit.Before; import org.springframework.context.ConfigurableApplicationContext; import java.io.File; import java.io.InputStream; /** * Adapted from {@link org.codehaus.plexus.spring.PlexusInSpringTestCase} for use with JUnit 4 and generics. */ public class PlexusSpringTestCase { protected ConfigurableApplicationContext applicationContext; @Before public void buildContext() throws Exception { preContextStart(); applicationContext = new PlexusClassPathXmlApplicationContext( getConfigLocations() ); } /** * Used for rare cases when subclasses need to do something before context is built. */ protected void preContextStart() throws Exception { } @After public void teardownContext() throws Exception { if ( applicationContext != null ) { applicationContext.close(); } } protected String[] getConfigLocations() { return new String[] { "classpath*:META-INF/spring-context.xml", "classpath*:META-INF/plexus/components.xml", "classpath*:" + getPlexusConfigLocation(), "classpath*:" + getSpringConfigLocation() }; } protected String getSpringConfigLocation() { return getClass().getName().replace( '.', '/' ) + "-context.xml"; } protected String getPlexusConfigLocation() { return getClass().getName().replace( '.', '/' ) + ".xml"; } public static String getBasedir() { return PlexusToSpringUtils.getBasedir(); } public String getTestConfiguration() { return getTestConfiguration( getClass() ); } public static String getTestConfiguration( Class clazz ) { String s = clazz.getName().replace( '.', '/' ); return s.substring( 0, s.indexOf( "$" ) ) + ".xml"; } public <T> T lookup( Class<T> role ) { return lookup( role, null ); } public <T> T lookup( Class<T> role, String roleHint ) { return (T) lookup( role.getName(), roleHint ); } public Object lookup( String role ) { return lookup( role, null ); } public Object lookup( String role, String roleHint ) { return applicationContext.getBean( PlexusToSpringUtils.buildSpringId( role, roleHint ) ); } public static File getTestFile( String path ) { return new File( PlexusToSpringUtils.getBasedir(), path ); } public static File getTestFile( String basedir, String path ) { File basedirFile = new File( basedir ); if ( !basedirFile.isAbsolute() ) { basedirFile = getTestFile( basedir ); } return new File( basedirFile, path ); } public static String getTestPath( String path ) { return getTestFile( path ).getAbsolutePath(); } public static String getTestPath( String basedir, String path ) { return getTestFile( basedir, path ).getAbsolutePath(); } protected ConfigurableApplicationContext getApplicationContext() { return applicationContext; } protected void release( Object component ) throws Exception { // nothing } protected PlexusContainer getContainer() { return (PlexusContainer) applicationContext.getBean( "plexusContainer" ); } protected InputStream getResourceAsStream( String resource ) { return getClass().getResourceAsStream( resource ); } }
4,930
0
Create_ds/continuum/continuum-test/src/main/java/org/apache/maven/continuum
Create_ds/continuum/continuum-test/src/main/java/org/apache/maven/continuum/configuration/ConfigurationServiceMock.java
package org.apache.maven.continuum.configuration; /* * 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.BuildAgentConfiguration; import org.apache.continuum.configuration.BuildAgentGroupConfiguration; import org.apache.maven.continuum.model.project.BuildQueue; import org.apache.maven.continuum.model.project.Schedule; import org.apache.maven.continuum.store.ContinuumStoreException; import java.io.File; import java.util.List; import java.util.Map; /** * Mock class for testing WagonContinuumNotifier's call to ConfigurationService.getBuildOutputFile() * * @author <a href="mailto:nramirez@exist">Napoleon Esmundo C. Ramirez</a> */ public class ConfigurationServiceMock implements ConfigurationService { private final String basedir; public ConfigurationServiceMock() { basedir = System.getProperty( "basedir" ); } public File getBuildOutputDirectory() { return new File( basedir, "src/test/resources" + "/" + "build-output-directory" ); } public File getBuildOutputDirectory( int projectId ) { return new File( getBuildOutputDirectory(), Integer.toString( projectId ) ); } public File getBuildOutputFile( int buildId, int projectId ) throws ConfigurationException { File dir = getBuildOutputDirectory( projectId ); if ( !dir.exists() && !dir.mkdirs() ) { throw new ConfigurationException( "Could not make the build output directory: " + "'" + dir.getAbsolutePath() + "'." ); } return new File( dir, buildId + ".log.txt" ); } public File getWorkingDirectory() { return new File( basedir, "src/test/resources" + "/" + "working-directory" ); } public File getTestReportsDirectory( int buildId, int projectId ) throws ConfigurationException { File dir = getBuildOutputDirectory( projectId ); if ( !dir.exists() && !dir.mkdirs() ) { throw new ConfigurationException( "Could not make the build output directory: " + "'" + dir.getAbsolutePath() + "'." ); } return new File( dir.getPath() + File.separatorChar + buildId + File.separatorChar + "surefire-reports " ); } public File getApplicationHome() { return null; } public boolean isInitialized() { return false; } public void setInitialized( boolean initialized ) { } public String getUrl() { return null; } public void setUrl( String url ) { } public void setBuildOutputDirectory( File buildOutputDirectory ) { } public void setWorkingDirectory( File workingDirectory ) { } public File getDeploymentRepositoryDirectory() { return null; } public void setDeploymentRepositoryDirectory( File deploymentRepositoryDirectory ) { } public void setJdks( Map jdks ) { } public String getCompanyLogo() { return null; } public void setCompanyLogo( String companyLogoUrl ) { } public String getCompanyName() { return null; } public void setCompanyName( String companyName ) { } public String getCompanyUrl() { return null; } public void setCompanyUrl( String companyUrl ) { } public boolean isGuestAccountEnabled() { return false; } public void setGuestAccountEnabled( boolean enabled ) { } public String getBuildOutput( int buildId, int projectId ) throws ConfigurationException { return null; } public File getFile( String filename ) { return null; } public String getSharedSecretPassword() { return null; } public void setSharedSecretPassword( String sharedSecretPassword ) { } public boolean isLoaded() { return false; } public void reload() throws ConfigurationLoadingException { } public void store() throws ConfigurationStoringException { } public BuildQueue getDefaultBuildQueue() throws BuildQueueServiceException { return null; } public Schedule getDefaultSchedule() throws ContinuumStoreException { // TODO Auto-generated method stub return null; } public File getChrootJailDirectory() { // TODO Auto-generated method stub return null; } public void setChrootJailDirectory( File chrootJailDirectory ) { // TODO Auto-generated method stub } public File getReleaseOutputDirectory() { return new File( basedir, "src/test/resources" + "/" + "release-output-directory" ); } public File getReleaseOutputDirectory( int projectGroupId ) { return new File( getReleaseOutputDirectory(), Integer.toString( projectGroupId ) ); } public File getReleaseOutputFile( int projectGroupId, String releaseName ) throws ConfigurationException { File dir = getReleaseOutputDirectory( projectGroupId ); if ( !dir.exists() && !dir.mkdirs() ) { throw new ConfigurationException( "Could not make the release output directory: " + "'" + dir.getAbsolutePath() + "'." ); } return new File( dir, releaseName + ".log.txt" ); } public void setReleaseOutputDirectory( File releaseOutputDirectory ) { } public String getReleaseOutput( int projectGroupId, String name ) { return null; } public int getNumberOfBuildsInParallel() { return 1; } public void setNumberOfBuildsInParallel( int num ) { } public void addBuildAgent( BuildAgentConfiguration buildAgent ) throws ConfigurationException { } public List<BuildAgentConfiguration> getBuildAgents() { return null; } public boolean isDistributedBuildEnabled() { return false; } public void removeBuildAgent( BuildAgentConfiguration buildAgent ) { } public void setDistributedBuildEnabled( boolean distributedBuildEnabled ) { } public void updateBuildAgent( BuildAgentConfiguration buildAgent ) { } public void addBuildAgentGroup( BuildAgentGroupConfiguration buildAgentGroup ) throws ConfigurationException { } public void removeBuildAgentGroup( BuildAgentGroupConfiguration buildAgentGroup ) throws ConfigurationException { } public void updateBuildAgentGroup( BuildAgentGroupConfiguration buildAgentGroup ) throws ConfigurationException { } public List<BuildAgentGroupConfiguration> getBuildAgentGroups() { return null; } public void addBuildAgent( BuildAgentGroupConfiguration buildAgentGroup, BuildAgentConfiguration buildAgent ) throws ConfigurationException { } public void removeBuildAgent( BuildAgentGroupConfiguration buildAgentGroup, BuildAgentConfiguration buildAgent ) throws ConfigurationException { } public BuildAgentGroupConfiguration getBuildAgentGroup( String name ) { return null; } public BuildAgentConfiguration getBuildAgent( String url ) { return null; } public boolean containsBuildAgentUrl( String buildAgentUrl, BuildAgentGroupConfiguration buildAgentGroup ) { return false; } }
4,931
0
Create_ds/continuum/continuum-test/src/main/java/org/apache/maven/continuum
Create_ds/continuum/continuum-test/src/main/java/org/apache/maven/continuum/jdo/MemoryJdoFactory.java
package org.apache.maven.continuum.jdo; /* * 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.jdo.DefaultConfigurableJdoFactory; import java.util.Properties; public class MemoryJdoFactory extends DefaultConfigurableJdoFactory { public Properties getOtherProperties() { return otherProperties; } public void setOtherProperties( Properties otherProperties ) { this.otherProperties = otherProperties; } public void reconfigure() { configured = Boolean.FALSE; getPersistenceManagerFactory(); } }
4,932
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-webapp/src/main/java/org/apache/continuum/web
Create_ds/continuum/continuum-buildagent/continuum-buildagent-webapp/src/main/java/org/apache/continuum/web/startup/BuildAgentStartup.java
package org.apache.continuum.web.startup; /* * 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.spring.PlexusToSpringUtils; import org.codehaus.plexus.taskqueue.execution.TaskQueueExecutor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; public class BuildAgentStartup implements ServletContextListener { private static final Logger log = LoggerFactory.getLogger( BuildAgentStartup.class ); /** * @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.ServletContextEvent) */ public void contextDestroyed( ServletContextEvent sce ) { // nothing to do here } /** * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent) */ public void contextInitialized( ServletContextEvent sce ) { log.info( "Initializing Build Agent Task Queue Executor" ); WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext( sce.getServletContext() ); TaskQueueExecutor buildAgent = (TaskQueueExecutor) wac.getBean( PlexusToSpringUtils.buildSpringId( TaskQueueExecutor.class, "build-agent" ) ); TaskQueueExecutor prepareBuildAgent = (TaskQueueExecutor) wac.getBean( PlexusToSpringUtils.buildSpringId( TaskQueueExecutor.class, "prepare-build-agent" ) ); TaskQueueExecutor prepareRelease = (TaskQueueExecutor) wac.getBean( PlexusToSpringUtils.buildSpringId( TaskQueueExecutor.class, "prepare-release" ) ); TaskQueueExecutor performRelease = (TaskQueueExecutor) wac.getBean( PlexusToSpringUtils.buildSpringId( TaskQueueExecutor.class, "perform-release" ) ); TaskQueueExecutor rollbackRelease = (TaskQueueExecutor) wac.getBean( PlexusToSpringUtils.buildSpringId( TaskQueueExecutor.class, "rollback-release" ) ); } }
4,933
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-webdav-client/src/main/java/org/apache/continuum/buildagent/webdav
Create_ds/continuum/continuum-buildagent/continuum-buildagent-webdav-client/src/main/java/org/apache/continuum/buildagent/webdav/client/WorkingCopyWebdavClient.java
package org.apache.continuum.buildagent.webdav.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.commons.httpclient.Credentials; import org.apache.commons.httpclient.HostConfiguration; import org.apache.commons.httpclient.HttpConnectionManager; import org.apache.commons.httpclient.HttpMethod; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.params.HttpConnectionManagerParams; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; 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.apache.jackrabbit.webdav.DavConstants; import org.apache.jackrabbit.webdav.DavException; import org.apache.jackrabbit.webdav.MultiStatus; import org.apache.jackrabbit.webdav.MultiStatusResponse; import org.apache.jackrabbit.webdav.client.methods.DavMethod; import org.apache.jackrabbit.webdav.client.methods.PropFindMethod; import org.apache.jackrabbit.webdav.property.DavProperty; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; public class WorkingCopyWebdavClient { public static void main( String[] args ) throws Exception { System.out.println( "Running webdav client.." ); // get resource getResourceUsingHttpclient( args[0], "", args[1] ); // list resources getResourcesUsingJackrabbit( args[0], "", args[1] ); } private static void getResourceUsingHttpclient( String resourceUrl, String username, String password ) throws URISyntaxException, IOException { SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register( new Scheme( "http", PlainSocketFactory.getSocketFactory(), 80 ) ); HttpParams params = new BasicHttpParams(); params.setParameter( ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30 ); params.setParameter( ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean( 30 ) ); HttpProtocolParams.setVersion( params, HttpVersion.HTTP_1_1 ); ClientConnectionManager cm = new ThreadSafeClientConnManager( params, schemeRegistry ); DefaultHttpClient httpClient = new DefaultHttpClient( cm, params ); URL url = new URL( resourceUrl ); URI uri = url.toURI(); HttpGet httpGet = new HttpGet( uri ); httpClient.getCredentialsProvider().setCredentials( new AuthScope( uri.getHost(), uri.getPort() ), new UsernamePasswordCredentials( username, password ) ); HttpHost targetHost = new HttpHost( url.getHost(), url.getPort(), url.getProtocol() ); AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put( targetHost, basicAuth ); BasicHttpContext localcontext = new BasicHttpContext(); localcontext.setAttribute( ClientContext.AUTH_CACHE, authCache ); System.out.println( "Retrieving resource '" + url.toString() + "' using HttpClient's get method.." ); HttpResponse httpResponse = httpClient.execute( targetHost, httpGet, localcontext ); System.out.println( "Response status code :: " + httpResponse.getStatusLine().getStatusCode() ); InputStream is = IOUtils.toInputStream( EntityUtils.toString( httpResponse.getEntity(), EntityUtils.getContentCharSet( httpResponse.getEntity() ) ) ); String content = IOUtils.toString( is ); System.out.println( "Content :: " + content ); } private static void getResourcesUsingJackrabbit( String filePath, String username, String password ) throws IOException, URISyntaxException, DavException { int idx = filePath.lastIndexOf( "/" ); if ( idx != -1 ) { filePath = StringUtils.substring( filePath, 0, idx + 1 ); } System.out.println( "\nRetrieve resources from '" + filePath + "' using Jackrabbit's webdav client.." ); URL url = new URL( filePath ); URI uri = url.toURI(); DavMethod pFind = new PropFindMethod( uri.toString(), DavConstants.PROPFIND_ALL_PROP, DavConstants.DEPTH_1 ); executeMethod( username, password, uri, pFind ); MultiStatus multiStatus = pFind.getResponseBodyAsMultiStatus(); MultiStatusResponse[] responses = multiStatus.getResponses(); MultiStatusResponse currResponse; System.out.println( "Folders and files in " + filePath + ":" ); for ( int i = 0; i < responses.length; i++ ) { currResponse = responses[i]; if ( !( currResponse.getHref().equals( uri.toString() ) || currResponse.getHref().equals( uri.toString() + "/" ) ) ) { String currResponseHref = StringUtils.trim( currResponse.getHref() ); System.out.println( "\nResource url :: " + currResponseHref ); DavProperty displayNameDavProperty = currResponse.getProperties( HttpStatus.SC_OK ).get( "displayname" ); String displayName; if ( displayNameDavProperty != null ) { displayName = (String) displayNameDavProperty.getValue(); } else { displayName = StringUtils.substring( currResponseHref, currResponseHref.lastIndexOf( "/" ) ); } HttpMethod httpGet = new GetMethod( currResponseHref ); URL resourceUrl = new URL( currResponseHref ); executeMethod( username, password, resourceUrl.toURI(), httpGet ); System.out.println( "Returned status code :: " + httpGet.getStatusCode() ); if ( httpGet.getStatusCode() == HttpStatus.SC_OK ) { InputStream is = httpGet.getResponseBodyAsStream(); try { System.out.println( "Contents of file '" + displayName + "' :: " + IOUtils.toString( is ) ); } finally { IOUtils.closeQuietly( is ); } } } } } private static void executeMethod( String username, String password, URI uri, HttpMethod pFind ) throws IOException { HostConfiguration hostConfig = new HostConfiguration(); hostConfig.setHost( uri.getHost() ); int maxHostConnections = 20; HttpConnectionManagerParams params = new HttpConnectionManagerParams(); params.setMaxConnectionsPerHost( hostConfig, maxHostConnections ); HttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); connectionManager.setParams( params ); org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient( connectionManager ); Credentials creds = new org.apache.commons.httpclient.UsernamePasswordCredentials( username, password ); client.getState().setCredentials( org.apache.commons.httpclient.auth.AuthScope.ANY, creds ); client.setHostConfiguration( hostConfig ); client.getParams().setAuthenticationPreemptive( true ); client.executeMethod( hostConfig, pFind ); } }
4,934
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-api/src/main/java/org/apache/continuum
Create_ds/continuum/continuum-buildagent/continuum-buildagent-api/src/main/java/org/apache/continuum/buildagent/ContinuumBuildAgentException.java
package org.apache.continuum.buildagent; /* * 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. */ public class ContinuumBuildAgentException extends Exception { public ContinuumBuildAgentException( String message ) { super( message ); } public ContinuumBuildAgentException( Throwable cause ) { super( cause ); } public ContinuumBuildAgentException( String message, Throwable cause ) { super( message, cause ); } }
4,935
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-api/src/main/java/org/apache/continuum
Create_ds/continuum/continuum-buildagent/continuum-buildagent-api/src/main/java/org/apache/continuum/buildagent/ContinuumBuildAgentService.java
package org.apache.continuum.buildagent; /* * 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.List; import java.util.Map; import java.util.Properties; public interface ContinuumBuildAgentService { void buildProjects( List<Map<String, Object>> projectsBuildContext ) throws ContinuumBuildAgentException; List<Map<String, String>> getAvailableInstallations() throws ContinuumBuildAgentException; Map<String, Object> getBuildResult( int projectId ) throws ContinuumBuildAgentException; Map<String, Object> getProjectCurrentlyBuilding() throws ContinuumBuildAgentException; void cancelBuild() throws ContinuumBuildAgentException; String generateWorkingCopyContent( int projectId, String userDirectory, String baseUrl, String imagesBaseUrl ) throws ContinuumBuildAgentException; Map<String, Object> getProjectFile( int projectId, String directory, String filename ) throws ContinuumBuildAgentException; Map<String, Object> getReleasePluginParameters( int projectId, String pomFilename ) throws ContinuumBuildAgentException; List<Map<String, String>> processProject( int projectId, String pomFilename, boolean autoVersionSubmodules ) throws ContinuumBuildAgentException; String releasePrepare( Map project, Properties properties, Map releaseVersion, Map developmentVersion, Map<String, String> environments, String username ) throws ContinuumBuildAgentException; Map<String, Object> getReleaseResult( String releaseId ) throws ContinuumBuildAgentException; Map<String, Object> getListener( String releaseId ) throws ContinuumBuildAgentException; void removeListener( String releaseId ) throws ContinuumBuildAgentException; String getPreparedReleaseName( String releaseId ) throws ContinuumBuildAgentException; void releasePerform( String releaseId, String goals, String arguments, boolean useReleaseProfile, Map repository, String username ) throws ContinuumBuildAgentException; String releasePerformFromScm( String goals, String arguments, boolean useReleaseProfile, Map repository, String scmUrl, String scmUsername, String scmPassword, String scmTag, String scmTagBase, Map<String, String> environments, String username ) throws ContinuumBuildAgentException; String releaseCleanup( String releaseId ) throws ContinuumBuildAgentException; void releaseRollback( String releaseId, int projectId ) throws ContinuumBuildAgentException; List<Map<String, Object>> getProjectsInPrepareBuildQueue() throws ContinuumBuildAgentException; List<Map<String, Object>> getProjectsAndBuildDefinitionsInPrepareBuildQueue() throws ContinuumBuildAgentException; List<Map<String, Object>> getProjectsInBuildQueue() throws ContinuumBuildAgentException; int getBuildSizeOfAgent() throws ContinuumBuildAgentException; Map<String, Object> getProjectCurrentlyPreparingBuild() throws ContinuumBuildAgentException; List<Map<String, Object>> getProjectsAndBuildDefinitionsCurrentlyPreparingBuild() throws ContinuumBuildAgentException; boolean isProjectGroupInQueue( int projectGroupId ); boolean isProjectScmRootInQueue( int projectScmRootId, List<Integer> projectIds ); boolean isProjectCurrentlyBuilding( int projectId, int buildDefinitionId ); boolean isProjectInBuildQueue( int projectId, int buildDefinitionId ); boolean isProjectGroupInPrepareBuildQueue( int projectGroupId ); boolean isProjectGroupCurrentlyPreparingBuild( int projectGroupId ); boolean isProjectInPrepareBuildQueue( int projectId, int buildDefinitionId ); boolean isProjectCurrentlyPreparingBuild( int projectId, int buildDefinitionId ); boolean removeFromPrepareBuildQueue( int projectGroupId, int scmRootId ) throws ContinuumBuildAgentException; void removeFromPrepareBuildQueue( List<String> hashCodes ) throws ContinuumBuildAgentException; boolean removeFromBuildQueue( int projectId, int builddefinitonId ) throws ContinuumBuildAgentException; void removeFromBuildQueue( List<String> hashCodes ) throws ContinuumBuildAgentException; boolean ping() throws ContinuumBuildAgentException; /** * Get build agent's platform. * * @return The operating system name of the build agent * @throws Exception */ String getBuildAgentPlatform() throws ContinuumBuildAgentException; /** * Determines if build agent is currently executing a build * * @return true if executing build; false otherwise */ boolean isExecutingBuild(); /** * Determines if build agent is currently executing a release * * @return true if executing release; false otherwise * @throws ContinuumBuildAgentException if unable to determine if buildagent is executing a release */ boolean isExecutingRelease() throws ContinuumBuildAgentException; /** * Execute a directory purge on the build agent * * @param directoryType valid types are <i>working</i> and <i>releases</i> * @param daysOlder days older * @param retentionCount retention count * @param deleteAll delete all flag * @return true if purge is successful; false otherwise * @throws ContinuumBuildAgentException error that will occur during the purge */ void executeDirectoryPurge( String directoryType, int daysOlder, int retentionCount, boolean deleteAll ) throws ContinuumBuildAgentException; /** * Execute a repository purge on the build agent * * @param repoName used to determine location at the build agent * @param daysOlder age in days when file is eligible for purging * @param retentionCount number of artifact versions required to retain * @param deleteAll triggers full deletion * @param deleteReleasedSnapshots whether to remove all snapshots matching a released artifact version * @throws Exception */ public void executeRepositoryPurge( String repoName, int daysOlder, int retentionCount, boolean deleteAll, boolean deleteReleasedSnapshots ) throws ContinuumBuildAgentException; }
4,936
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-api/src/main/java/org/apache/continuum
Create_ds/continuum/continuum-buildagent/continuum-buildagent-api/src/main/java/org/apache/continuum/buildagent/NoBuildAgentException.java
package org.apache.continuum.buildagent; /* * 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. */ public class NoBuildAgentException extends Exception { public NoBuildAgentException( String message ) { super( message ); } public NoBuildAgentException( Throwable cause ) { super( cause ); } public NoBuildAgentException( String message, Throwable cause ) { super( message, cause ); } }
4,937
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-api/src/main/java/org/apache/continuum
Create_ds/continuum/continuum-buildagent/continuum-buildagent-api/src/main/java/org/apache/continuum/buildagent/NoBuildAgentInGroupException.java
package org.apache.continuum.buildagent; /* * 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. */ public class NoBuildAgentInGroupException extends Exception { public NoBuildAgentInGroupException( String message ) { super( message ); } public NoBuildAgentInGroupException( Throwable cause ) { super( cause ); } public NoBuildAgentInGroupException( String message, Throwable cause ) { super( message, cause ); } }
4,938
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-api/src/main/java/org/apache/continuum/buildagent
Create_ds/continuum/continuum-buildagent/continuum-buildagent-api/src/main/java/org/apache/continuum/buildagent/configuration/BuildAgentConfigurationService.java
package org.apache.continuum.buildagent.configuration; /* * 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.model.Installation; import org.apache.continuum.buildagent.model.LocalRepository; import java.io.File; import java.util.List; public interface BuildAgentConfigurationService { String ROLE = BuildAgentConfigurationService.class.getName(); File getBuildOutputDirectory(); File getBuildOutputDirectory( int projectId ); File getWorkingDirectory(); File getWorkingDirectory( int projectId ); String getContinuumServerUrl(); String getBuildOutput( int projectId ) throws BuildAgentConfigurationException; File getBuildOutputFile( int projectId ) throws BuildAgentConfigurationException; List<Installation> getAvailableInstallations(); LocalRepository getLocalRepositoryByName( String name ) throws BuildAgentConfigurationException; String getSharedSecretPassword(); void store() throws BuildAgentConfigurationException; }
4,939
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-api/src/main/java/org/apache/continuum/buildagent
Create_ds/continuum/continuum-buildagent/continuum-buildagent-api/src/main/java/org/apache/continuum/buildagent/configuration/BuildAgentConfigurationException.java
package org.apache.continuum.buildagent.configuration; /* * 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. */ public class BuildAgentConfigurationException extends Exception { public BuildAgentConfigurationException( String message ) { super( message ); } public BuildAgentConfigurationException( Throwable cause ) { super( cause ); } public BuildAgentConfigurationException( String message, Throwable cause ) { super( message, cause ); } }
4,940
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/test/java/org/apache/continuum/buildagent
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/test/java/org/apache/continuum/buildagent/stubs/ContinuumActionStub.java
package org.apache.continuum.buildagent.stubs; /* * 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.utils.ContinuumBuildAgentUtil; import org.codehaus.plexus.action.AbstractAction; import java.util.Map; /** * This is used for testing the fix for CONTINUUM-2391. See BuildPRrojectTaskExecutorTest.java and * BuildProjectTaskExecutorTest.xml for details. */ public class ContinuumActionStub extends AbstractAction { public void execute( Map context ) throws Exception { if ( !ContinuumBuildAgentUtil.getLocalRepository( context ).equals( "/home/user/.m2/repository" ) ) { throw new Exception( "Local repository set in the build context should not have been a full path!" ); } } }
4,941
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/test/java/org/apache/continuum/buildagent
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/test/java/org/apache/continuum/buildagent/stubs/ContinuumReleaseManagerStub.java
package org.apache.continuum.buildagent.stubs; /* * 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.release.ContinuumReleaseException; import org.apache.maven.continuum.release.ContinuumReleaseManagerListener; import org.apache.maven.continuum.release.DefaultContinuumReleaseManager; import java.io.File; public class ContinuumReleaseManagerStub extends DefaultContinuumReleaseManager { public void perform( String releaseId, File buildDirectory, String goals, String arguments, boolean useReleaseProfile, ContinuumReleaseManagerListener listener, LocalRepository repository ) throws ContinuumReleaseException { if ( !repository.getName().equalsIgnoreCase( "default" ) ) { throw new ContinuumReleaseException( "Incorrect local repository name!" ); } if ( !repository.getLocation().equals( "/home/user/.m2/repository" ) ) { throw new ContinuumReleaseException( "Incorrect local repository location!" ); } if ( !repository.getLayout().equals( "default" ) ) { throw new ContinuumReleaseException( "Incorrect local repository layout!" ); } } }
4,942
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/test/java/org/apache/continuum/buildagent/taskqueue
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/test/java/org/apache/continuum/buildagent/taskqueue/execution/BuildProjectTaskExecutorTest.java
package org.apache.continuum.buildagent.taskqueue.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.buildagent.build.execution.ContinuumAgentBuildExecutor; import org.apache.continuum.buildagent.build.execution.manager.BuildAgentBuildExecutorManager; import org.apache.continuum.buildagent.buildcontext.BuildContext; import org.apache.continuum.buildagent.buildcontext.manager.BuildContextManager; import org.apache.continuum.buildagent.configuration.BuildAgentConfigurationService; import org.apache.continuum.buildagent.manager.BuildAgentManager; import org.apache.continuum.buildagent.model.Installation; import org.apache.continuum.buildagent.model.LocalRepository; import org.apache.continuum.buildagent.utils.ContinuumBuildAgentUtil; import org.apache.continuum.taskqueue.BuildProjectTask; import org.apache.continuum.utils.build.BuildTrigger; import org.apache.maven.continuum.ContinuumException; import org.apache.maven.continuum.PlexusSpringTestCase; import org.apache.maven.continuum.execution.ContinuumBuildExecutorConstants; import org.apache.maven.continuum.model.project.BuildDefinition; import org.apache.maven.continuum.model.scm.ScmResult; import org.apache.maven.project.MavenProject; import org.codehaus.plexus.taskqueue.execution.TaskExecutor; import org.junit.Before; import org.junit.Test; import java.io.File; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.junit.Assert.*; import static org.mockito.Mockito.*; public class BuildProjectTaskExecutorTest extends PlexusSpringTestCase { private BuildContextManager buildContextManager; private BuildAgentBuildExecutorManager buildAgentBuildExecutorManager; private BuildAgentConfigurationService buildAgentConfigurationService; private BuildAgentManager buildAgentManager; private BuildProjectTaskExecutor buildProjectExecutor; private BuildContext buildContext; private List<LocalRepository> localRepos; private Map<String, String> masterBuildEnvironments; private List<Installation> slaveBuildEnvironments = new ArrayList<Installation>(); private ContinuumAgentBuildExecutor executor; private File workingDir; private MavenProject project; private File outputFile; @Before public void setUp() throws Exception { buildContextManager = mock( BuildContextManager.class ); buildAgentBuildExecutorManager = mock( BuildAgentBuildExecutorManager.class ); buildAgentConfigurationService = mock( BuildAgentConfigurationService.class ); buildAgentManager = mock( BuildAgentManager.class ); executor = mock( ContinuumAgentBuildExecutor.class ); buildProjectExecutor = (BuildProjectTaskExecutor) lookup( TaskExecutor.class, "build-agent" ); buildProjectExecutor.setBuildAgentBuildExecutorManager( buildAgentBuildExecutorManager ); buildProjectExecutor.setBuildAgentConfigurationService( buildAgentConfigurationService ); buildProjectExecutor.setBuildContextManager( buildContextManager ); buildProjectExecutor.setBuildAgentManager( buildAgentManager ); buildContext = createBuildContext(); localRepos = new ArrayList<LocalRepository>(); localRepos.add( createLocalRepository( "temp", "/tmp/.m2/repository", "default" ) ); localRepos.add( createLocalRepository( "default", "/home/user/.m2/repository", "default" ) ); for ( LocalRepository localRepo : localRepos ) { when( buildAgentConfigurationService.getLocalRepositoryByName( localRepo.getName() ) ).thenReturn( localRepo ); } masterBuildEnvironments = new HashMap<String, String>(); masterBuildEnvironments.put( "M2_HOME", "/tmp/apache-maven-2.2.1" ); slaveBuildEnvironments = new ArrayList<Installation>(); workingDir = new File( "/tmp/data/working-directory/project-test" ); project = new MavenProject(); outputFile = new File( "/tmp/data/build-output-directory/output.txt" ); when( buildContextManager.getBuildContext( 1 ) ).thenReturn( buildContext ); when( buildAgentManager.getEnvironments( 1, "maven2" ) ).thenReturn( masterBuildEnvironments ); when( buildAgentConfigurationService.getAvailableInstallations() ).thenReturn( slaveBuildEnvironments ); when( buildAgentManager.shouldBuild( anyMap() ) ).thenReturn( true ); when( buildAgentBuildExecutorManager.getBuildExecutor( ContinuumBuildExecutorConstants.MAVEN_TWO_BUILD_EXECUTOR ) ).thenReturn( executor ); when( buildAgentConfigurationService.getWorkingDirectory( 1 ) ).thenReturn( workingDir ); when( executor.getMavenProject( any( File.class ), any( BuildDefinition.class ) ) ).thenReturn( project ); when( buildAgentConfigurationService.getBuildOutputFile( 1 ) ).thenReturn( outputFile ); } // CONTINUUM-2391 // Note: The checking of the local repo set in the context is in ContinuumActionStub. If the // local repo path is incorrect, an exception will be thrown by the action stub. @Test public void testBuildProjectLocalRepository() throws Exception { try { buildProjectExecutor.executeTask( createBuildProjectTask() ); } catch ( Exception e ) { fail( "An exception should not have been thrown!" ); } assertBuilt(); } @Test public void testBuildProjectWithConfiguredInstallationsFromBuildAgent() throws Exception { Installation slaveBuildEnvironment = createInstallation( "M2_HOME", "/home/user/apache-maven-2.2.1" ); slaveBuildEnvironments.add( slaveBuildEnvironment ); slaveBuildEnvironment = createInstallation( "EXTRA_VAR", "/home/user/extra" ); slaveBuildEnvironments.add( slaveBuildEnvironment ); try { buildProjectExecutor.executeTask( createBuildProjectTask() ); Map<String, String> environments = (Map<String, String>) buildContext.getActionContext().get( ContinuumBuildAgentUtil.KEY_ENVIRONMENTS ); assertEquals( 2, environments.size() ); assertTrue( environments.containsKey( "M2_HOME" ) ); assertTrue( environments.containsKey( "EXTRA_VAR" ) ); // shows that build agent's environment variables overwrites Continuum Master's environment variables assertEquals( "/home/user/apache-maven-2.2.1", environments.get( "M2_HOME" ) ); assertEquals( "/home/user/extra", environments.get( "EXTRA_VAR" ) ); } catch ( Exception e ) { fail( "An exception should not have been thrown!" ); } assertBuilt(); } @Test public void testBuildProjectWithNoConfiguredInstallationsFromBuildAgent() throws Exception { try { buildProjectExecutor.executeTask( createBuildProjectTask() ); Map<String, String> environments = (Map<String, String>) buildContext.getActionContext().get( ContinuumBuildAgentUtil.KEY_ENVIRONMENTS ); assertEquals( 1, environments.size() ); assertTrue( environments.containsKey( "M2_HOME" ) ); assertEquals( "/tmp/apache-maven-2.2.1", environments.get( "M2_HOME" ) ); } catch ( Exception e ) { fail( "An exception should not have been thrown!" ); } assertBuilt(); } private void assertBuilt() throws ContinuumException { verify( buildAgentManager ).startProjectBuild( 1, 1 ); verify( buildAgentManager ).returnBuildResult( anyMap() ); verify( buildContextManager ).removeBuildContext( 1 ); } private BuildProjectTask createBuildProjectTask() { BuildProjectTask task = new BuildProjectTask( 1, 1, new BuildTrigger( 1 ), "Test Project", "Default Build Definition", new ScmResult(), 1 ); return task; } private BuildContext createBuildContext() { BuildContext context = new BuildContext(); context.setProjectId( 1 ); context.setProjectVersion( "1.0-SNAPSHOT" ); context.setBuildDefinitionId( 1 ); context.setBuildFile( "pom.xml" ); context.setExecutorId( ContinuumBuildExecutorConstants.MAVEN_TWO_BUILD_EXECUTOR ); context.setGoals( "clean intall" ); context.setArguments( "--batch --non-recursive" ); context.setScmUrl( "scm:svn:http://svn.example.com/repos/dummy/trunk" ); context.setScmUsername( "" ); context.setScmPassword( "" ); context.setBuildFresh( false ); context.setProjectGroupId( 1 ); context.setProjectGroupName( "Test Project Group" ); context.setScmRootAddress( "scm:svn:http://svn.example.com/repos/dummy" ); context.setScmRootId( 1 ); context.setProjectName( "Test Project" ); context.setProjectState( 1 ); context.setTrigger( 1 ); context.setUsername( "" ); context.setLocalRepository( "default" ); context.setBuildNumber( 1 ); ScmResult scmResult = new ScmResult(); scmResult.setSuccess( true ); context.setScmResult( scmResult ); context.setLatestUpdateDate( Calendar.getInstance().getTime() ); context.setBuildAgentUrl( "http://localhost:8181/continuum-buildagent/xmlrpc" ); context.setMaxExecutionTime( 7200 ); context.setBuildDefinitionLabel( "Default Build Definition" ); context.setScmTag( "scm:svn:http://svn.example.com/repos/dummy/tags" ); return context; } private LocalRepository createLocalRepository( String name, String locataion, String layout ) { LocalRepository localRepository = new LocalRepository(); localRepository.setName( name ); localRepository.setLocation( locataion ); localRepository.setLayout( layout ); return localRepository; } private Installation createInstallation( String varName, String varValue ) { Installation installation = new Installation(); installation.setVarName( varName ); installation.setVarValue( varValue ); return installation; } }
4,943
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/test/java/org/apache/continuum/buildagent
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/test/java/org/apache/continuum/buildagent/configuration/BuildAgentConfigurationTest.java
package org.apache.continuum.buildagent.configuration; /* * 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.model.Installation; import org.apache.continuum.buildagent.model.LocalRepository; import org.apache.maven.continuum.PlexusSpringTestCase; import org.junit.Test; import java.io.File; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.*; public class BuildAgentConfigurationTest extends PlexusSpringTestCase { @Test public void testInitialize() throws Exception { DefaultBuildAgentConfiguration config = (DefaultBuildAgentConfiguration) lookup( BuildAgentConfiguration.class ); config.setConfigurationFile( new File( getBasedir(), "target/test-classes/buildagent-config/continuum-buildagent.xml" ) ); config.initialize(); GeneralBuildAgentConfiguration generalConfig = config.getContinuumBuildAgentConfiguration(); assertEquals( "http://localhost:9595/continuum/master-xmlrpc", generalConfig.getContinuumServerUrl() ); assertEquals( new File( "/tmp/data/build-output-directory" ), generalConfig.getBuildOutputDirectory() ); assertEquals( new File( "/tmp/data/working-directory" ), generalConfig.getWorkingDirectory() ); assertEquals( 1, generalConfig.getInstallations().size() ); Installation installation = generalConfig.getInstallations().get( 0 ); assertEquals( "Tool", installation.getType() ); assertEquals( "Maven 2.2.1 Installation", installation.getName() ); assertEquals( "M2_HOME", installation.getVarName() ); assertEquals( "/tmp/apache-maven-2.2.1", installation.getVarValue() ); LocalRepository localRepo = generalConfig.getLocalRepositories().get( 0 ); assertLocalRepository( getExpectedLocalRepo(), localRepo ); } @Test public void testSaveExistingConfiguration() throws Exception { DefaultBuildAgentConfiguration config = (DefaultBuildAgentConfiguration) lookup( BuildAgentConfiguration.class ); config.setConfigurationFile( new File( getBasedir(), "target/test-classes/buildagent-config/continuum-buildagent-edit.xml" ) ); config.initialize(); String expected = "http://192.165.240.12:8080/continuum/master-xmlrpc"; GeneralBuildAgentConfiguration generalConfig = config.getContinuumBuildAgentConfiguration(); assertEquals( "http://localhost:9595/continuum/master-xmlrpc", generalConfig.getContinuumServerUrl() ); assertEquals( 1, generalConfig.getInstallations().size() ); generalConfig.setContinuumServerUrl( expected ); Installation expectedInstallation = getExpectedInstallation(); generalConfig.getInstallations().add( expectedInstallation ); LocalRepository expectedLocalRepo = getExpectedLocalRepo(); List<LocalRepository> localRepos = new ArrayList<LocalRepository>(); localRepos.add( expectedLocalRepo ); generalConfig.setLocalRepositories( localRepos ); config.save(); config.reload(); assertEquals( expected, config.getContinuumBuildAgentConfiguration().getContinuumServerUrl() ); assertEquals( 2, config.getContinuumBuildAgentConfiguration().getInstallations().size() ); Installation installation = generalConfig.getInstallations().get( 1 ); assertInstallation( expectedInstallation, installation ); LocalRepository localRepo = generalConfig.getLocalRepositories().get( 0 ); assertLocalRepository( expectedLocalRepo, localRepo ); } @Test public void testSaveNewConfiguration() throws Exception { File configFile = new File( getBasedir(), "target/test-classes/buildagent-config/continuum-buildagent-new.xml" ); DefaultBuildAgentConfiguration config = (DefaultBuildAgentConfiguration) lookup( BuildAgentConfiguration.class ); config.setConfigurationFile( configFile ); config.initialize(); String expectedUrl = "http://localhost:8080/continuum/master-xmlrpc"; File expectedBuildOutputDir = new File( "/tmp/data/build-output-directory" ); File expectedWorkingDir = new File( "/tmp/data/working-directory" ); GeneralBuildAgentConfiguration generalConfig = config.getContinuumBuildAgentConfiguration(); assertNull( generalConfig.getContinuumServerUrl() ); assertNull( generalConfig.getBuildOutputDirectory() ); assertNull( generalConfig.getWorkingDirectory() ); assertNull( generalConfig.getInstallations() ); Installation expectedInstallation = getExpectedInstallation(); List<Installation> installations = new ArrayList<Installation>(); installations.add( expectedInstallation ); LocalRepository expectedLocalRepo = getExpectedLocalRepo(); List<LocalRepository> localRepos = new ArrayList<LocalRepository>(); localRepos.add( expectedLocalRepo ); generalConfig.setContinuumServerUrl( expectedUrl ); generalConfig.setBuildOutputDirectory( expectedBuildOutputDir ); generalConfig.setWorkingDirectory( expectedWorkingDir ); generalConfig.setInstallations( installations ); generalConfig.setLocalRepositories( localRepos ); config.save(); config.reload(); assertTrue( configFile.exists() ); assertEquals( expectedUrl, config.getContinuumBuildAgentConfiguration().getContinuumServerUrl() ); assertEquals( expectedBuildOutputDir, config.getContinuumBuildAgentConfiguration().getBuildOutputDirectory() ); assertEquals( expectedWorkingDir, config.getContinuumBuildAgentConfiguration().getWorkingDirectory() ); assertEquals( 1, config.getContinuumBuildAgentConfiguration().getInstallations().size() ); Installation installation = generalConfig.getInstallations().get( 0 ); assertInstallation( expectedInstallation, installation ); LocalRepository localRepo = generalConfig.getLocalRepositories().get( 0 ); assertLocalRepository( expectedLocalRepo, localRepo ); } private Installation getExpectedInstallation() { Installation expectedInstallation = new Installation(); expectedInstallation.setName( "Maven 2.0.10 Installation" ); expectedInstallation.setType( "Tool" ); expectedInstallation.setVarName( "M2_HOME" ); expectedInstallation.setVarValue( "/tmp/apache-maven-2.1.10" ); return expectedInstallation; } private LocalRepository getExpectedLocalRepo() { LocalRepository expectedLocalRepo = new LocalRepository(); expectedLocalRepo.setName( "DEFAULT" ); expectedLocalRepo.setLayout( "default" ); expectedLocalRepo.setLocation( "/tmp/.m2/repository" ); return expectedLocalRepo; } private void assertLocalRepository( LocalRepository expectedLocalRepo, LocalRepository localRepo ) { assertEquals( expectedLocalRepo.getName(), localRepo.getName() ); assertEquals( expectedLocalRepo.getLayout(), localRepo.getLayout() ); assertEquals( expectedLocalRepo.getLocation(), localRepo.getLocation() ); } private void assertInstallation( Installation expectedInstallation, Installation installation ) { assertEquals( expectedInstallation.getType(), installation.getType() ); assertEquals( expectedInstallation.getName(), installation.getName() ); assertEquals( expectedInstallation.getVarName(), installation.getVarName() ); assertEquals( expectedInstallation.getVarValue(), installation.getVarValue() ); } }
4,944
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/test/java/org/apache/continuum/buildagent
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/test/java/org/apache/continuum/buildagent/manager/BuildAgentPurgeManagerTest.java
package org.apache.continuum.buildagent.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.configuration.BuildAgentConfigurationService; import org.apache.continuum.utils.file.FileSystemManager; import org.apache.maven.continuum.PlexusSpringTestCase; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import static org.apache.continuum.purge.ContinuumPurgeConstants.PURGE_DIRECTORY_RELEASES; import static org.apache.continuum.purge.ContinuumPurgeConstants.PURGE_DIRECTORY_WORKING; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * For CONTINUUM-2658 tests, Support purging of working and release directories of build agents on a schedule */ public class BuildAgentPurgeManagerTest extends PlexusSpringTestCase { private static final int AGE = 2; private static final int NONE = 0; private static final int RELEASE_DIRS = 5; private static final int OLD_RELEASE_DIRS = 3; private static final int WORKING_DIRS = 10; private static final int OLD_WORKING_DIRS = 9; private static final int REGULAR_FILES = 2; public static final int TOTAL_FILES_AND_DIRS = RELEASE_DIRS + WORKING_DIRS + REGULAR_FILES; private static final int MILLIS_IN_DAY = 24 * 60 * 60 * 1000; private BuildAgentConfigurationService buildAgentConfigurationService; private DefaultBuildAgentPurgeManager purgeManager; private FileSystemManager fsManager; private File tempDir; @Before public void setUp() throws Exception { purgeManager = (DefaultBuildAgentPurgeManager) lookup( BuildAgentPurgeManager.class ); fsManager = lookup( FileSystemManager.class ); buildAgentConfigurationService = mock( BuildAgentConfigurationService.class ); purgeManager.setBuildAgentConfigurationService( buildAgentConfigurationService ); createTestFiles(); assertEquals( TOTAL_FILES_AND_DIRS, tempDir.list().length ); when( buildAgentConfigurationService.getWorkingDirectory() ).thenReturn( tempDir ); } @After public void tearDown() throws Exception { purgeManager = null; cleanUpTestFiles(); } // CONTINUUM-2658 @Test public void testAllWorking() throws Exception { int ignored = 1; purgeManager.executeDirectoryPurge( PURGE_DIRECTORY_WORKING, ignored, ignored, true ); assertEquals( RELEASE_DIRS + REGULAR_FILES, fileCount() ); } // CONTINUUM-2658 @Test public void testAllReleases() throws Exception { int ignored = 1; purgeManager.executeDirectoryPurge( PURGE_DIRECTORY_RELEASES, ignored, ignored, true ); assertEquals( WORKING_DIRS + REGULAR_FILES, fileCount() ); } // CONTINUUM-2658 @Test public void testAllWorkingAndReleases() throws Exception { int ignored = 1; purgeManager.executeDirectoryPurge( PURGE_DIRECTORY_WORKING, ignored, ignored, true ); purgeManager.executeDirectoryPurge( PURGE_DIRECTORY_RELEASES, ignored, ignored, true ); assertEquals( REGULAR_FILES, fileCount() ); } @Test public void testRetentionOnlyWorking() throws Exception { int retainedWorking = 2; purgeManager.executeDirectoryPurge( PURGE_DIRECTORY_WORKING, NONE, retainedWorking, false ); assertEquals( RELEASE_DIRS + REGULAR_FILES + retainedWorking, fileCount() ); } @Test public void testRetentionOnlyReleases() throws Exception { int retainedReleases = 4; purgeManager.executeDirectoryPurge( PURGE_DIRECTORY_RELEASES, NONE, retainedReleases, false ); assertEquals( WORKING_DIRS + retainedReleases + REGULAR_FILES, fileCount() ); } @Test public void testRetentionOnlyWorkingAndReleases() throws Exception { int retainedReleases = 4, retainedWorking = 2; purgeManager.executeDirectoryPurge( PURGE_DIRECTORY_WORKING, NONE, retainedWorking, false ); purgeManager.executeDirectoryPurge( PURGE_DIRECTORY_RELEASES, NONE, retainedReleases, false ); assertEquals( retainedWorking + retainedReleases + REGULAR_FILES, fileCount() ); } @Test public void testDaysOldOnlyWorking() throws Exception { int maxAge = 1, ineligibleWorkDirs = WORKING_DIRS - OLD_WORKING_DIRS; purgeManager.executeDirectoryPurge( PURGE_DIRECTORY_WORKING, maxAge, NONE, false ); assertEquals( RELEASE_DIRS + ineligibleWorkDirs + REGULAR_FILES, fileCount() ); } @Test public void testDaysOldOnlyReleases() throws Exception { int maxAge = 1, ineligibleReleaseDirs = RELEASE_DIRS - OLD_RELEASE_DIRS; purgeManager.executeDirectoryPurge( PURGE_DIRECTORY_RELEASES, maxAge, NONE, false ); assertEquals( WORKING_DIRS + ineligibleReleaseDirs + REGULAR_FILES, fileCount() ); } @Test public void testDaysOldOnlyWorkingAndReleases() throws Exception { int maxAge = 1; int ineligibleWorkDirs = WORKING_DIRS - OLD_WORKING_DIRS; int ineligibleReleaseDirs = RELEASE_DIRS - OLD_RELEASE_DIRS; purgeManager.executeDirectoryPurge( PURGE_DIRECTORY_WORKING, maxAge, NONE, false ); purgeManager.executeDirectoryPurge( PURGE_DIRECTORY_RELEASES, maxAge, NONE, false ); assertEquals( ineligibleWorkDirs + ineligibleReleaseDirs + REGULAR_FILES, fileCount() ); } @Test public void testRetentionAndDaysOldWorking() throws Exception { int maxAge = 1; int retainWorking = 5; int ineligibleWorkDirs = WORKING_DIRS - OLD_WORKING_DIRS; int expectedWorkDirs = retainWorking + ineligibleWorkDirs; purgeManager.executeDirectoryPurge( PURGE_DIRECTORY_WORKING, maxAge, retainWorking, false ); assertEquals( RELEASE_DIRS + expectedWorkDirs + REGULAR_FILES, fileCount() ); } @Test public void testRetentionAndDaysOldReleases() throws Exception { int maxAge = 1; int retainRelease = 1; int ineligibleReleaseDirs = RELEASE_DIRS - OLD_RELEASE_DIRS; int expectedReleaseDirs = retainRelease + ineligibleReleaseDirs; purgeManager.executeDirectoryPurge( PURGE_DIRECTORY_RELEASES, maxAge, retainRelease, false ); assertEquals( WORKING_DIRS + expectedReleaseDirs + REGULAR_FILES, fileCount() ); } @Test public void testRetentionAndDaysOldWorkingAndReleases() throws Exception { int maxAge = 1; int retainWorking = 5, retainRelease = 1; int ineligibleWorkDirs = WORKING_DIRS - OLD_WORKING_DIRS; int ineligibleReleaseDirs = RELEASE_DIRS - OLD_RELEASE_DIRS; int expectedWorkDirs = retainWorking + ineligibleWorkDirs; int expectedReleaseDirs = retainRelease + ineligibleReleaseDirs; purgeManager.executeDirectoryPurge( PURGE_DIRECTORY_WORKING, maxAge, retainWorking, false ); purgeManager.executeDirectoryPurge( PURGE_DIRECTORY_RELEASES, maxAge, retainRelease, false ); assertEquals( expectedReleaseDirs + expectedWorkDirs + REGULAR_FILES, fileCount() ); } private int fileCount() { return tempDir.list().length; } private void createTestFiles() throws Exception { SimpleDateFormat format = new SimpleDateFormat( "yyyyMMddHHmmss" ); tempDir = new File( System.getProperty( "java.io.tmpdir" ) + System.getProperty( "file.separator" ) + format.format( new Date() ) ); if ( !tempDir.mkdirs() ) { throw new IOException( "Unable to create test directory: " + tempDir.getName() ); } createReleasesDirectories( RELEASE_DIRS, AGE, OLD_RELEASE_DIRS ); createWorkingDirectories( WORKING_DIRS, AGE, OLD_WORKING_DIRS ); createRegularFile( "random.txt" ); createRegularFile( "releases-random.txt" ); } private void cleanUpTestFiles() throws IOException { fsManager.removeDir( tempDir ); } private void createReleasesDirectories( int count, int daysOld, int daysOldCount ) throws Exception { createDirectories( "releases-", count, daysOld, daysOldCount ); } private void createWorkingDirectories( int count, int daysOld, int daysOldCount ) throws IOException { createDirectories( "", count, daysOld, daysOldCount ); } private void createDirectories( String namePrefix, int count, int age, int toAge ) throws IOException { long generationStart = System.currentTimeMillis(); for ( int x = 1; x <= count; x++ ) { File file = new File( tempDir.getAbsolutePath() + System.getProperty( "file.separator" ) + namePrefix + x ); if ( !file.mkdirs() ) { throw new IOException( "Unable to create test directory: " + file.getName() ); } if ( x <= toAge ) { file.setLastModified( generationStart - ( age * MILLIS_IN_DAY ) ); } } } private File createRegularFile( String fileName ) throws IOException { File randomFile = new File( tempDir.getAbsolutePath() + System.getProperty( "file.separator" ) + fileName ); if ( !randomFile.exists() ) { randomFile.createNewFile(); } return randomFile; } }
4,945
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/test/java/org/apache/continuum/buildagent
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/test/java/org/apache/continuum/buildagent/manager/BuildAgentReleaseManagerTest.java
package org.apache.continuum.buildagent.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.configuration.BuildAgentConfigurationException; import org.apache.continuum.buildagent.configuration.BuildAgentConfigurationService; import org.apache.continuum.buildagent.model.LocalRepository; import org.apache.continuum.buildagent.utils.ContinuumBuildAgentUtil; import org.apache.maven.continuum.PlexusSpringTestCase; import org.apache.maven.continuum.release.ContinuumReleaseException; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * For the CONTINUUM-2391 tests, checking of the local repository details is in ContinuumReleaseManagerStub. An * exception is thrown if the set local repository in the repository map is incorrect. */ public class BuildAgentReleaseManagerTest extends PlexusSpringTestCase { public static final String DEFAULT_NAME = "DEFAULT"; public static final String UNKNOWN_NAME = "NON-EXISTENT"; private BuildAgentConfigurationService buildAgentConfigurationService; private DefaultBuildAgentReleaseManager releaseManager; @Before public void setUp() throws Exception { releaseManager = (DefaultBuildAgentReleaseManager) lookup( BuildAgentReleaseManager.class ); buildAgentConfigurationService = mock( BuildAgentConfigurationService.class ); releaseManager.setBuildAgentConfigurationService( buildAgentConfigurationService ); final List<LocalRepository> localRepos = createLocalRepositories(); final File workingDir = new File( getBasedir(), "target/test-classes/working-dir" ); for ( LocalRepository localRepo : localRepos ) { String repoName = localRepo.getName(); when( buildAgentConfigurationService.getLocalRepositoryByName( repoName ) ).thenReturn( localRepo ); when( buildAgentConfigurationService.getLocalRepositoryByName( repoName.toUpperCase() ) ).thenReturn( localRepo ); } when( buildAgentConfigurationService.getLocalRepositoryByName( UNKNOWN_NAME ) ).thenThrow( new BuildAgentConfigurationException( "could not locate the repo" ) ); when( buildAgentConfigurationService.getWorkingDirectory( 1 ) ).thenReturn( workingDir ); when( buildAgentConfigurationService.getWorkingDirectory() ).thenReturn( workingDir ); } @After public void tearDown() throws Exception { releaseManager = null; } // CONTINUUM-2391 @Test public void testLocalRepositoryInReleasePrepare() throws Exception { when( buildAgentConfigurationService.getAvailableInstallations() ).thenReturn( null ); try { releaseManager.releasePrepare( createProjectMap(), createProperties(), createReleaseVersionMap(), createDevVersionMap(), createEnvironmentsMap(), "user" ); } catch ( ContinuumReleaseException e ) { fail( "An exception should not have been thrown!" ); } } // CONTINUUM-2391 @Test public void testLocalRepositoryNameMismatchedCaseInReleasePrepare() throws Exception { when( buildAgentConfigurationService.getAvailableInstallations() ).thenReturn( null ); Map<String, Object> map = createProjectMap(); map.put( ContinuumBuildAgentUtil.KEY_LOCAL_REPOSITORY_NAME, DEFAULT_NAME ); try { releaseManager.releasePrepare( map, createProperties(), createReleaseVersionMap(), createDevVersionMap(), createEnvironmentsMap(), "user" ); } catch ( ContinuumReleaseException e ) { fail( "An exception should not have been thrown!" ); } } @Test public void testUnknownRepositoryNameInReleasePrepare() throws Exception { when( buildAgentConfigurationService.getAvailableInstallations() ).thenReturn( null ); Map<String, Object> map = createProjectMap(); map.put( ContinuumBuildAgentUtil.KEY_LOCAL_REPOSITORY_NAME, DEFAULT_NAME ); try { releaseManager.releasePrepare( map, createProperties(), createReleaseVersionMap(), createDevVersionMap(), createEnvironmentsMap(), "user" ); } catch ( ContinuumReleaseException e ) { fail( "An exception should not have been thrown!" ); } } // CONTINUUM-2391 @Test @SuppressWarnings( "unchecked" ) public void testLocalRepositoryInReleasePerform() throws Exception { try { releaseManager.releasePerform( "1", "clean deploy", "", true, createRepositoryMap(), "user" ); } catch ( ContinuumReleaseException e ) { fail( "An exception should not have been thrown!" ); } } // CONTINUUM-2391 @Test public void testLocalRepositoryNameMismatchedCaseInReleasePerform() throws Exception { Map repoMap = createRepositoryMap(); repoMap.put( ContinuumBuildAgentUtil.KEY_LOCAL_REPOSITORY_NAME, DEFAULT_NAME ); try { releaseManager.releasePerform( "1", "clean deploy", "", true, repoMap, "user" ); } catch ( ContinuumReleaseException e ) { fail( "An exception should not have been thrown!" ); } } @Test public void testUnknownRepositoryNameInReleasePerform() throws Exception { Map repoMap = createRepositoryMap(); repoMap.put( ContinuumBuildAgentUtil.KEY_LOCAL_REPOSITORY_NAME, DEFAULT_NAME ); try { releaseManager.releasePerform( "1", "clean deploy", "", true, repoMap, "user" ); } catch ( ContinuumReleaseException e ) { fail( "An exception should not have been thrown!" ); } } // CONTINUUM-2391 @Test @SuppressWarnings( "unchecked" ) public void testLocalRepositoryInReleasePerformFromScm() throws Exception { Map repository = new HashMap(); repository.put( ContinuumBuildAgentUtil.KEY_USERNAME, "user" ); repository.put( ContinuumBuildAgentUtil.KEY_LOCAL_REPOSITORY_NAME, "default" ); try { releaseManager.releasePerformFromScm( "clean deploy", "", true, repository, "scm:svn:http://svn.example.com/repos/test-project", "user", "mypasswrd", "scm:svn:http://svn.example.com/repos/test-project/tags/test-project-1.0", "scm:svn:http://svn.example.com/repos/test-project/tags", null, "user" ); } catch ( ContinuumReleaseException e ) { fail( "An exception should not have been thrown!" ); } } private List<LocalRepository> createLocalRepositories() { List<LocalRepository> localRepos = new ArrayList<LocalRepository>(); LocalRepository localRepo = new LocalRepository(); localRepo.setName( "temp" ); localRepo.setLocation( "/tmp/.m2/repository" ); localRepo.setLayout( "default" ); localRepos.add( localRepo ); localRepo = new LocalRepository(); localRepo.setName( "default" ); localRepo.setLocation( "/home/user/.m2/repository" ); localRepo.setLayout( "default" ); localRepos.add( localRepo ); return localRepos; } private Map<String, String> createEnvironmentsMap() { Map<String, String> environments = new HashMap<String, String>(); environments.put( "M2_HOME", "/tmp/bin/apache-maven-2.2.1" ); return environments; } private Map<String, String> createDevVersionMap() { Map<String, String> devVersion = new HashMap<String, String>(); devVersion.put( "1.1-SNAPSHOT", "1.1-SNAPSHOT" ); return devVersion; } private Map<String, String> createReleaseVersionMap() { Map<String, String> releaseVersion = new HashMap<String, String>(); releaseVersion.put( "1.0", "1.0" ); return releaseVersion; } private Properties createProperties() { Properties properties = new Properties(); properties.put( ContinuumBuildAgentUtil.KEY_SCM_USERNAME, "scmusername" ); properties.put( ContinuumBuildAgentUtil.KEY_SCM_PASSWORD, "scmpassword" ); properties.put( ContinuumBuildAgentUtil.KEY_SCM_TAGBASE, "scm:svn:http://svn.example.com/repos/test-project/tags" ); properties.put( ContinuumBuildAgentUtil.KEY_PREPARE_GOALS, "clean install" ); properties.put( ContinuumBuildAgentUtil.KEY_ARGUMENTS, "" ); properties.put( ContinuumBuildAgentUtil.KEY_SCM_TAG, "test-project-1.0" ); return properties; } private Map<String, Object> createProjectMap() { Map<String, Object> map = new HashMap<String, Object>(); map.put( ContinuumBuildAgentUtil.KEY_LOCAL_REPOSITORY_NAME, "default" ); map.put( ContinuumBuildAgentUtil.KEY_PROJECT_ID, 1 ); map.put( ContinuumBuildAgentUtil.KEY_GROUP_ID, "1" ); map.put( ContinuumBuildAgentUtil.KEY_ARTIFACT_ID, "test-project" ); map.put( ContinuumBuildAgentUtil.KEY_SCM_URL, "scm:svn:http://svn.example.com/repos/test-project/trunk" ); return map; } @SuppressWarnings( "unchecked" ) private Map createRepositoryMap() { Map repository = new HashMap(); repository.put( ContinuumBuildAgentUtil.KEY_USERNAME, "user" ); repository.put( ContinuumBuildAgentUtil.KEY_LOCAL_REPOSITORY_NAME, "default" ); return repository; } }
4,946
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/test/java/org/apache/continuum/buildagent/build/execution/maven
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/test/java/org/apache/continuum/buildagent/build/execution/maven/m2/DefaultBuildAgentMavenBuilderHelperTest.java
package org.apache.continuum.buildagent.build.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.PlexusSpringTestCase; import org.apache.maven.continuum.project.builder.ContinuumProjectBuildingResult; import org.apache.maven.project.MavenProject; import org.apache.maven.settings.MavenSettingsBuilder; import org.apache.maven.settings.Profile; import org.apache.maven.settings.Repository; import org.apache.maven.settings.RepositoryPolicy; import org.apache.maven.settings.Settings; import org.junit.Before; import org.junit.Test; import java.io.File; import static org.junit.Assert.assertNotNull; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class DefaultBuildAgentMavenBuilderHelperTest extends PlexusSpringTestCase { private DefaultBuildAgentMavenBuilderHelper helper; @Before public void setUp() throws Exception { helper = (DefaultBuildAgentMavenBuilderHelper) lookup( BuildAgentMavenBuilderHelper.class ); MavenSettingsBuilder builder = mock( MavenSettingsBuilder.class ); when( builder.buildSettings( false ) ).thenReturn( createSettings() ); helper.setMavenSettingsBuilder( builder ); } private static Settings createSettings() { Settings settings = new Settings(); settings.setLocalRepository( getTestFile( "target/local-repository" ).getAbsolutePath() ); Profile profile = new Profile(); profile.setId( "repo" ); Repository repository = new Repository(); repository.setId( "central" ); repository.setUrl( getTestFile( "src/test/test-repo" ).toURI().toString() ); RepositoryPolicy policy = new RepositoryPolicy(); policy.setEnabled( true ); policy.setUpdatePolicy( "always" ); repository.setSnapshots( policy ); profile.addRepository( repository ); settings.addProfile( profile ); settings.addActiveProfile( "repo" ); return settings; } @Test public void testGetMavenProjectWithMaven3Metadata() throws Exception { File pomFile = getTestFile( "src/test/test-projects/maven3-metadata/pom.xml" ); MavenProject project = helper.getMavenProject( new ContinuumProjectBuildingResult(), pomFile ); assertNotNull( project ); } }
4,947
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/ContinuumBuildAgentServiceImpl.java
package org.apache.continuum.buildagent; /* * 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.commons.lang.StringEscapeUtils; import org.apache.continuum.buildagent.buildcontext.BuildContext; import org.apache.continuum.buildagent.buildcontext.manager.BuildContextManager; import org.apache.continuum.buildagent.configuration.BuildAgentConfigurationException; import org.apache.continuum.buildagent.configuration.BuildAgentConfigurationService; import org.apache.continuum.buildagent.manager.BuildAgentManager; import org.apache.continuum.buildagent.manager.BuildAgentPurgeManager; import org.apache.continuum.buildagent.manager.BuildAgentReleaseManager; import org.apache.continuum.buildagent.model.Installation; import org.apache.continuum.buildagent.model.LocalRepository; import org.apache.continuum.buildagent.taskqueue.PrepareBuildProjectsTask; import org.apache.continuum.buildagent.taskqueue.manager.BuildAgentTaskQueueManager; import org.apache.continuum.buildagent.utils.ContinuumBuildAgentUtil; import org.apache.continuum.buildagent.utils.WorkingCopyContentGenerator; import org.apache.continuum.release.utils.ReleaseHelper; import org.apache.continuum.taskqueue.BuildProjectTask; import org.apache.continuum.taskqueue.manager.TaskQueueManagerException; import org.apache.continuum.utils.build.BuildTrigger; import org.apache.continuum.utils.file.FileSystemManager; import org.apache.continuum.utils.m2.LocalRepositoryHelper; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.continuum.ContinuumException; import org.apache.maven.continuum.execution.SettingsConfigurationException; import org.apache.maven.continuum.model.project.BuildResult; 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.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.taskqueue.TaskQueueException; import org.codehaus.plexus.util.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.activation.MimetypesFileTypeMap; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; @Component( role = ContinuumBuildAgentService.class ) public class ContinuumBuildAgentServiceImpl implements ContinuumBuildAgentService { private static final Logger log = LoggerFactory.getLogger( ContinuumBuildAgentServiceImpl.class ); private static final String FILE_SEPARATOR = System.getProperty( "file.separator" ); @Requirement private BuildAgentConfigurationService buildAgentConfigurationService; @Requirement private BuildAgentTaskQueueManager buildAgentTaskQueueManager; @Requirement private BuildContextManager buildContextManager; @Requirement private WorkingCopyContentGenerator generator; @Requirement private BuildAgentReleaseManager buildAgentReleaseManager; @Requirement private BuildAgentManager buildAgentManager; @Requirement private BuildAgentPurgeManager purgeManager; @Requirement private ReleaseHelper releaseHelper; @Requirement private LocalRepositoryHelper localRepositoryHelper; @Requirement private FileSystemManager fsManager; public void buildProjects( List<Map<String, Object>> projectsBuildContext ) throws ContinuumBuildAgentException { List<BuildContext> buildContextList = initializeBuildContext( projectsBuildContext ); PrepareBuildProjectsTask task = createPrepareBuildProjectsTask( buildContextList ); if ( task == null ) { return; } try { log.info( "Adding project group {} to prepare build queue", task.getProjectGroupId() ); buildAgentTaskQueueManager.getPrepareBuildQueue().put( task ); } catch ( TaskQueueException e ) { throw new ContinuumBuildAgentException( "Error while enqueuing projects", e ); } } public List<Map<String, String>> getAvailableInstallations() throws ContinuumBuildAgentException { List<Map<String, String>> installationsList = new ArrayList<Map<String, String>>(); List<Installation> installations = buildAgentConfigurationService.getAvailableInstallations(); for ( Installation installation : installations ) { Map<String, String> map = new HashMap<String, String>(); if ( StringUtils.isBlank( installation.getName() ) ) { map.put( ContinuumBuildAgentUtil.KEY_INSTALLATION_NAME, "" ); } else { map.put( ContinuumBuildAgentUtil.KEY_INSTALLATION_NAME, installation.getName() ); } if ( StringUtils.isBlank( installation.getType() ) ) { map.put( ContinuumBuildAgentUtil.KEY_INSTALLATION_TYPE, "" ); } else { map.put( ContinuumBuildAgentUtil.KEY_INSTALLATION_TYPE, installation.getType() ); } if ( StringUtils.isBlank( installation.getVarName() ) ) { map.put( ContinuumBuildAgentUtil.KEY_INSTALLATION_VAR_NAME, "" ); } else { map.put( ContinuumBuildAgentUtil.KEY_INSTALLATION_VAR_VALUE, installation.getVarValue() ); } if ( StringUtils.isBlank( installation.getVarValue() ) ) { map.put( ContinuumBuildAgentUtil.KEY_INSTALLATION_VAR_VALUE, "" ); } else { map.put( ContinuumBuildAgentUtil.KEY_INSTALLATION_VAR_VALUE, installation.getVarValue() ); } installationsList.add( map ); } return installationsList; } public Map<String, Object> getBuildResult( int projectId ) throws ContinuumBuildAgentException { log.debug( "Get build result of project {}", projectId ); Map<String, Object> result = new HashMap<String, Object>(); int currentBuildId = 0; try { log.debug( "Get current build project" ); currentBuildId = buildAgentTaskQueueManager.getIdOfProjectCurrentlyBuilding(); } catch ( TaskQueueManagerException e ) { throw new ContinuumBuildAgentException( e.getMessage(), e ); } log.debug( "Check if project {} is the one currently building in the agent", projectId ); if ( projectId == currentBuildId ) { BuildContext buildContext = buildContextManager.getBuildContext( projectId ); result.put( ContinuumBuildAgentUtil.KEY_PROJECT_ID, buildContext.getProjectId() ); result.put( ContinuumBuildAgentUtil.KEY_BUILD_DEFINITION_ID, buildContext.getBuildDefinitionId() ); result.put( ContinuumBuildAgentUtil.KEY_TRIGGER, buildContext.getTrigger() ); result.put( ContinuumBuildAgentUtil.KEY_USERNAME, buildContext.getUsername() ); BuildResult buildResult = buildContext.getBuildResult(); if ( buildResult != null ) { if ( buildResult.getStartTime() <= 0 ) { result.put( ContinuumBuildAgentUtil.KEY_START_TIME, Long.toString( buildContext.getBuildStartTime() ) ); } else { result.put( ContinuumBuildAgentUtil.KEY_START_TIME, Long.toString( buildResult.getStartTime() ) ); } if ( buildResult.getError() == null ) { result.put( ContinuumBuildAgentUtil.KEY_BUILD_ERROR, "" ); } else { result.put( ContinuumBuildAgentUtil.KEY_BUILD_ERROR, buildResult.getError() ); } result.put( ContinuumBuildAgentUtil.KEY_BUILD_STATE, buildResult.getState() ); result.put( ContinuumBuildAgentUtil.KEY_END_TIME, Long.toString( buildResult.getEndTime() ) ); result.put( ContinuumBuildAgentUtil.KEY_BUILD_EXIT_CODE, buildResult.getExitCode() ); } else { result.put( ContinuumBuildAgentUtil.KEY_START_TIME, Long.toString( buildContext.getBuildStartTime() ) ); result.put( ContinuumBuildAgentUtil.KEY_END_TIME, Long.toString( 0 ) ); result.put( ContinuumBuildAgentUtil.KEY_BUILD_STATE, ContinuumProjectState.BUILDING ); result.put( ContinuumBuildAgentUtil.KEY_BUILD_ERROR, "" ); result.put( ContinuumBuildAgentUtil.KEY_BUILD_EXIT_CODE, 0 ); } String buildOutput = getBuildOutputText( projectId ); if ( buildOutput == null ) { result.put( ContinuumBuildAgentUtil.KEY_BUILD_OUTPUT, "" ); } else { result.put( ContinuumBuildAgentUtil.KEY_BUILD_OUTPUT, buildOutput ); } result.put( ContinuumBuildAgentUtil.KEY_SCM_RESULT, ContinuumBuildAgentUtil.createScmResult( buildContext ) ); } else { log.debug( "Unable to get build result because project {} is not currently building in the agent", projectId ); } return result; } public void cancelBuild() throws ContinuumBuildAgentException { try { log.debug( "Cancelling current build" ); buildAgentTaskQueueManager.cancelBuild(); } catch ( TaskQueueManagerException e ) { throw new ContinuumBuildAgentException( e.getMessage(), e ); } } public String generateWorkingCopyContent( int projectId, String userDirectory, String baseUrl, String imagesBaseUrl ) throws ContinuumBuildAgentException { File workingDirectory = buildAgentConfigurationService.getWorkingDirectory( projectId ); try { List<File> files = ContinuumBuildAgentUtil.getFiles( userDirectory, workingDirectory ); return generator.generate( files, baseUrl, imagesBaseUrl, workingDirectory ); } catch ( ContinuumException e ) { log.error( "Failed to generate working copy content", e ); } return ""; } public Map<String, Object> getProjectFile( int projectId, String directory, String filename ) throws ContinuumBuildAgentException { Map<String, Object> projectFile = new HashMap<String, Object>(); String relativePath = "\\.\\./"; // prevent users from using relative paths. Pattern pattern = Pattern.compile( relativePath ); Matcher matcher = pattern.matcher( directory ); String filteredDirectory = matcher.replaceAll( "" ); matcher = pattern.matcher( filename ); String filteredFilename = matcher.replaceAll( "" ); File workingDirectory = buildAgentConfigurationService.getWorkingDirectory( projectId ); File fileDirectory = new File( workingDirectory, filteredDirectory ); File userFile = new File( fileDirectory, filteredFilename ); byte[] downloadFile; try { downloadFile = fsManager.fileBytes( userFile ); } catch ( IOException e ) { throw new ContinuumBuildAgentException( "Can't read file: " + filename ); } MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap(); mimeTypesMap.addMimeTypes( "application/java-archive jar war ear" ); mimeTypesMap.addMimeTypes( "application/java-class class" ); mimeTypesMap.addMimeTypes( "image/png png" ); String mimeType = mimeTypesMap.getContentType( userFile ); String fileContent; boolean isStream = false; if ( ( mimeType.indexOf( "image" ) >= 0 ) || ( mimeType.indexOf( "java-archive" ) >= 0 ) || ( mimeType.indexOf( "java-class" ) >= 0 ) || ( userFile.length() > 100000 ) ) { fileContent = ""; isStream = true; } else { try { fileContent = fsManager.fileContents( userFile ); } catch ( IOException e ) { throw new ContinuumBuildAgentException( "Can't read file " + filename, e ); } } projectFile.put( "downloadFileName", userFile.getName() ); projectFile.put( "downloadFileLength", Long.toString( userFile.length() ) ); projectFile.put( "downloadFile", downloadFile ); projectFile.put( "mimeType", mimeType ); projectFile.put( "fileContent", fileContent ); projectFile.put( "isStream", isStream ); return projectFile; } private ArtifactRepository getArtifactRepository( int projectId ) throws SettingsConfigurationException, ContinuumBuildAgentException { BuildContext buildContext = buildContextManager.getBuildContext( projectId ); if ( buildContext == null ) { String notFoundMsg = String.format( "build context for project id %s not found", projectId ); log.warn( notFoundMsg ); throw new ContinuumBuildAgentException( notFoundMsg ); } org.apache.continuum.model.repository.LocalRepository localRepo = null; try { LocalRepository agentRepo = buildAgentConfigurationService.getLocalRepositoryByName( buildContext.getLocalRepository() ); localRepo = localRepositoryHelper.convertAgentRepo( agentRepo ); } catch ( BuildAgentConfigurationException e ) { log.warn( "failed to find local repo for project {}: {}", projectId, e.getMessage() ); } return localRepositoryHelper.getLocalRepository( localRepo ); } public Map<String, Object> getReleasePluginParameters( int projectId, String pomFilename ) throws ContinuumBuildAgentException { String workingDirectory = buildAgentConfigurationService.getWorkingDirectory( projectId ).getPath(); try { log.debug( "Getting release plugin parameters of project {}", projectId ); ArtifactRepository repo = getArtifactRepository( projectId ); return releaseHelper.extractPluginParameters( repo, workingDirectory, pomFilename ); } catch ( Exception e ) { throw new ContinuumBuildAgentException( "Error getting release plugin parameters from pom file", e ); } } public List<Map<String, String>> processProject( int projectId, String pomFilename, boolean autoVersionSubmodules ) throws ContinuumBuildAgentException { List<Map<String, String>> projects = new ArrayList<Map<String, String>>(); String workingDirectory = buildAgentConfigurationService.getWorkingDirectory( projectId ).getPath(); try { ArtifactRepository repo = getArtifactRepository( projectId ); releaseHelper.buildVersionParams( repo, workingDirectory, pomFilename, autoVersionSubmodules, projects ); } catch ( Exception e ) { throw new ContinuumBuildAgentException( "Unable to process project " + projectId, e ); } return projects; } public String releasePrepare( Map project, Properties properties, Map releaseVersion, Map developmentVersion, Map<String, String> environments, String username ) throws ContinuumBuildAgentException { try { log.debug( "Preparing release" ); return buildAgentReleaseManager.releasePrepare( project, properties, releaseVersion, developmentVersion, environments, username ); } catch ( ContinuumReleaseException e ) { throw new ContinuumBuildAgentException( "Unable to prepare release", e ); } } public Map<String, Object> getReleaseResult( String releaseId ) throws ContinuumBuildAgentException { log.debug( "Getting release result of release {}", releaseId ); ReleaseResult result = buildAgentReleaseManager.getReleaseResult( releaseId ); Map<String, Object> map = new HashMap<String, Object>(); map.put( ContinuumBuildAgentUtil.KEY_START_TIME, Long.toString( result.getStartTime() ) ); map.put( ContinuumBuildAgentUtil.KEY_END_TIME, Long.toString( result.getEndTime() ) ); map.put( ContinuumBuildAgentUtil.KEY_RELEASE_RESULT_CODE, result.getResultCode() ); map.put( ContinuumBuildAgentUtil.KEY_RELEASE_OUTPUT, result.getOutput() ); return map; } public Map<String, Object> getListener( String releaseId ) throws ContinuumBuildAgentException { return buildAgentReleaseManager.getListener( releaseId ); } public void removeListener( String releaseId ) { buildAgentReleaseManager.removeListener( releaseId ); } public String getPreparedReleaseName( String releaseId ) { return buildAgentReleaseManager.getPreparedReleaseName( releaseId ); } public void releasePerform( String releaseId, String goals, String arguments, boolean useReleaseProfile, Map repository, String username ) throws ContinuumBuildAgentException { try { log.debug( "Performing release" ); buildAgentReleaseManager.releasePerform( releaseId, goals, arguments, useReleaseProfile, repository, username ); } catch ( ContinuumReleaseException e ) { throw new ContinuumBuildAgentException( "Unable to perform release " + releaseId, e ); } } public String releasePerformFromScm( String goals, String arguments, boolean useReleaseProfile, Map repository, String scmUrl, String scmUsername, String scmPassword, String scmTag, String scmTagBase, Map<String, String> environments, String username ) throws ContinuumBuildAgentException { try { log.debug( "Performing release from scm" ); return buildAgentReleaseManager.releasePerformFromScm( goals, arguments, useReleaseProfile, repository, scmUrl, scmUsername, scmPassword, scmTag, scmTagBase, environments, username ); } catch ( ContinuumReleaseException e ) { throw new ContinuumBuildAgentException( "Unable to perform release from scm", e ); } } public String releaseCleanup( String releaseId ) throws ContinuumBuildAgentException { log.debug( "Cleanup release {}", releaseId ); return buildAgentReleaseManager.releaseCleanup( releaseId ); } public void releaseRollback( String releaseId, int projectId ) throws ContinuumBuildAgentException { try { log.debug( "Release rollback release {} with project {}", releaseId, projectId ); buildAgentReleaseManager.releaseRollback( releaseId, projectId ); } catch ( ContinuumReleaseException e ) { throw new ContinuumBuildAgentException( e ); } } public int getBuildSizeOfAgent() { int size = 0; try { log.debug( "Getting number of projects in any queue" ); if ( buildAgentTaskQueueManager.getCurrentProjectInBuilding() != null ) { size++; } PrepareBuildProjectsTask currentPrepareBuild = buildAgentTaskQueueManager.getCurrentProjectInPrepareBuild(); if ( currentPrepareBuild != null ) { // need to get actual number of projects. size = size + currentPrepareBuild.getBuildContexts().size(); } size = size + buildAgentTaskQueueManager.getProjectsInBuildQueue().size(); for ( PrepareBuildProjectsTask prepareBuildTask : buildAgentTaskQueueManager.getProjectsInPrepareBuildQueue() ) { if ( prepareBuildTask != null ) { size = size + prepareBuildTask.getBuildContexts().size(); } } } catch ( TaskQueueManagerException e ) { log.error( "Error occurred while getting build size of agent" ); } return size; } public List<Map<String, Object>> getProjectsInPrepareBuildQueue() throws ContinuumBuildAgentException { try { log.debug( "Getting projects in prepare build queue" ); List<Map<String, Object>> projects = new ArrayList<Map<String, Object>>(); for ( PrepareBuildProjectsTask task : buildAgentTaskQueueManager.getProjectsInPrepareBuildQueue() ) { Map<String, Object> map = new HashMap<String, Object>(); map.put( ContinuumBuildAgentUtil.KEY_PROJECT_GROUP_ID, new Integer( task.getProjectGroupId() ) ); map.put( ContinuumBuildAgentUtil.KEY_SCM_ROOT_ID, new Integer( task.getScmRootId() ) ); map.put( ContinuumBuildAgentUtil.KEY_SCM_ROOT_ADDRESS, task.getScmRootAddress() ); map.put( ContinuumBuildAgentUtil.KEY_TRIGGER, task.getBuildTrigger().getTrigger() ); map.put( ContinuumBuildAgentUtil.KEY_USERNAME, task.getBuildTrigger().getTriggeredBy() ); projects.add( map ); } return projects; } catch ( TaskQueueManagerException e ) { log.error( "Error occurred while retrieving projects in prepare build queue", e ); throw new ContinuumBuildAgentException( "Error occurred while retrieving projects in prepare build queue", e ); } } public List<Map<String, Object>> getProjectsAndBuildDefinitionsInPrepareBuildQueue() throws ContinuumBuildAgentException { try { log.debug( "Getting projects in prepare build queue" ); List<Map<String, Object>> projects = new ArrayList<Map<String, Object>>(); for ( PrepareBuildProjectsTask task : buildAgentTaskQueueManager.getProjectsInPrepareBuildQueue() ) { for ( BuildContext context : task.getBuildContexts() ) { Map<String, Object> map = new HashMap<String, Object>(); map.put( ContinuumBuildAgentUtil.KEY_PROJECT_ID, context.getProjectId() ); map.put( ContinuumBuildAgentUtil.KEY_BUILD_DEFINITION_ID, context.getBuildDefinitionId() ); projects.add( map ); } } return projects; } catch ( TaskQueueManagerException e ) { log.error( "Error occurred while retrieving projects in prepare build queue", e ); throw new ContinuumBuildAgentException( "Error occurred while retrieving projects in prepare build queue", e ); } } public List<Map<String, Object>> getProjectsInBuildQueue() throws ContinuumBuildAgentException { try { log.debug( "Getting projects in build queue" ); List<Map<String, Object>> projects = new ArrayList<Map<String, Object>>(); for ( BuildProjectTask task : buildAgentTaskQueueManager.getProjectsInBuildQueue() ) { Map<String, Object> map = new HashMap<String, Object>(); map.put( ContinuumBuildAgentUtil.KEY_PROJECT_ID, new Integer( task.getProjectId() ) ); map.put( ContinuumBuildAgentUtil.KEY_BUILD_DEFINITION_ID, new Integer( task.getBuildDefinitionId() ) ); map.put( ContinuumBuildAgentUtil.KEY_TRIGGER, task.getBuildTrigger().getTrigger() ); map.put( ContinuumBuildAgentUtil.KEY_USERNAME, task.getBuildTrigger().getTriggeredBy() ); map.put( ContinuumBuildAgentUtil.KEY_PROJECT_GROUP_ID, new Integer( task.getProjectGroupId() ) ); map.put( ContinuumBuildAgentUtil.KEY_BUILD_DEFINITION_LABEL, task.getBuildDefinitionLabel() ); projects.add( map ); } return projects; } catch ( TaskQueueManagerException e ) { log.error( "Error occurred while retrieving projects in build queue", e ); throw new ContinuumBuildAgentException( "Error occurred while retrieving projects in build queue", e ); } } public Map<String, Object> getProjectCurrentlyPreparingBuild() throws ContinuumBuildAgentException { try { log.debug( "Get project currently preparing build" ); Map<String, Object> project = new HashMap<String, Object>(); PrepareBuildProjectsTask task = buildAgentTaskQueueManager.getCurrentProjectInPrepareBuild(); if ( task != null ) { project.put( ContinuumBuildAgentUtil.KEY_PROJECT_GROUP_ID, new Integer( task.getProjectGroupId() ) ); project.put( ContinuumBuildAgentUtil.KEY_SCM_ROOT_ID, new Integer( task.getScmRootId() ) ); project.put( ContinuumBuildAgentUtil.KEY_SCM_ROOT_ADDRESS, task.getScmRootAddress() ); project.put( ContinuumBuildAgentUtil.KEY_TRIGGER, task.getBuildTrigger().getTrigger() ); project.put( ContinuumBuildAgentUtil.KEY_USERNAME, task.getBuildTrigger().getTriggeredBy() ); } return project; } catch ( TaskQueueManagerException e ) { log.error( "Error occurred while retrieving current project in prepare build", e ); throw new ContinuumBuildAgentException( "Error occurred while retrieving current project in prepare build", e ); } } public List<Map<String, Object>> getProjectsAndBuildDefinitionsCurrentlyPreparingBuild() throws ContinuumBuildAgentException { try { log.debug( "Getting projects currently preparing build" ); List<Map<String, Object>> projects = new ArrayList<Map<String, Object>>(); PrepareBuildProjectsTask task = buildAgentTaskQueueManager.getCurrentProjectInPrepareBuild(); if ( task != null ) { for ( BuildContext context : task.getBuildContexts() ) { Map<String, Object> map = new HashMap<String, Object>(); map.put( ContinuumBuildAgentUtil.KEY_PROJECT_ID, context.getProjectId() ); map.put( ContinuumBuildAgentUtil.KEY_BUILD_DEFINITION_ID, context.getBuildDefinitionId() ); projects.add( map ); } } return projects; } catch ( TaskQueueManagerException e ) { log.error( "Error occurred while retrieving current projects in prepare build", e ); throw new ContinuumBuildAgentException( "Error occurred while retrieving current projects in prepare build", e ); } } public Map<String, Object> getProjectCurrentlyBuilding() throws ContinuumBuildAgentException { try { log.debug( "Getting currently building project" ); Map<String, Object> project = new HashMap<String, Object>(); BuildProjectTask task = buildAgentTaskQueueManager.getCurrentProjectInBuilding(); if ( task != null ) { project.put( ContinuumBuildAgentUtil.KEY_PROJECT_ID, new Integer( task.getProjectId() ) ); project.put( ContinuumBuildAgentUtil.KEY_BUILD_DEFINITION_ID, new Integer( task.getBuildDefinitionId() ) ); project.put( ContinuumBuildAgentUtil.KEY_TRIGGER, task.getBuildTrigger().getTrigger() ); project.put( ContinuumBuildAgentUtil.KEY_USERNAME, task.getBuildTrigger().getTriggeredBy() ); project.put( ContinuumBuildAgentUtil.KEY_PROJECT_GROUP_ID, new Integer( task.getProjectGroupId() ) ); project.put( ContinuumBuildAgentUtil.KEY_BUILD_DEFINITION_LABEL, task.getBuildDefinitionLabel() ); } return project; } catch ( TaskQueueManagerException e ) { log.error( "Error occurred while retrieving current project in building", e ); throw new ContinuumBuildAgentException( "Error occurred while retrieving current project in building", e ); } } public boolean isProjectGroupInQueue( int projectGroupId ) { try { log.debug( "Checking if project group is in any queue", projectGroupId ); for ( PrepareBuildProjectsTask task : buildAgentTaskQueueManager.getProjectsInPrepareBuildQueue() ) { if ( task.getProjectGroupId() == projectGroupId ) { log.debug( "projectGroup {} is in prepare build queue", projectGroupId ); return true; } } PrepareBuildProjectsTask currentPrepareBuildTask = buildAgentTaskQueueManager.getCurrentProjectInPrepareBuild(); if ( currentPrepareBuildTask != null && currentPrepareBuildTask.getProjectGroupId() == projectGroupId ) { log.debug( "projectGroup {} is currently preparing build", projectGroupId ); return true; } for ( BuildProjectTask task : buildAgentTaskQueueManager.getProjectsInBuildQueue() ) { if ( task.getProjectGroupId() == projectGroupId ) { log.debug( "projectGroup {} is in build queue", projectGroupId ); return true; } } BuildProjectTask currentBuildTask = buildAgentTaskQueueManager.getCurrentProjectInBuilding(); if ( currentBuildTask != null && currentBuildTask.getProjectGroupId() == projectGroupId ) { log.debug( "projectGroup {} is currently building", projectGroupId ); return true; } } catch ( TaskQueueManagerException e ) { log.error( "Error while checking if project group " + projectGroupId + " is queued in agent", e ); } return false; } public boolean isProjectScmRootInQueue( int projectScmRootId, List<Integer> projectIds ) { try { log.debug( "Checking if projects {} is in any queue", projectIds ); PrepareBuildProjectsTask currentPrepareBuildTask = buildAgentTaskQueueManager.getCurrentProjectInPrepareBuild(); if ( currentPrepareBuildTask != null && currentPrepareBuildTask.getScmRootId() == projectScmRootId ) { return true; } BuildProjectTask currentBuildTask = buildAgentTaskQueueManager.getCurrentProjectInBuilding(); if ( currentBuildTask != null ) { int projectId = currentBuildTask.getProjectId(); for ( Integer pid : projectIds ) { if ( pid == projectId ) { return true; } } } for ( PrepareBuildProjectsTask task : buildAgentTaskQueueManager.getProjectsInPrepareBuildQueue() ) { if ( task.getScmRootId() == projectScmRootId ) { return true; } } for ( BuildProjectTask task : buildAgentTaskQueueManager.getProjectsInBuildQueue() ) { int projectId = task.getProjectId(); for ( Integer pid : projectIds ) { if ( pid == projectId ) { return true; } } } } catch ( TaskQueueManagerException e ) { log.error( "Error while checking if project scm root " + projectScmRootId + " is queued in agent", e ); } return false; } public boolean isProjectGroupInPrepareBuildQueue( int projectGroupId ) { try { log.debug( "Checking if project group {} is in prepare build queue", projectGroupId ); for ( PrepareBuildProjectsTask task : buildAgentTaskQueueManager.getProjectsInPrepareBuildQueue() ) { if ( task.getProjectGroupId() == projectGroupId ) { return true; } } } catch ( TaskQueueManagerException e ) { log.error( "Error while checking if project group " + projectGroupId + " is in prepare build queue in agent", e ); } return false; } public boolean isProjectInPrepareBuildQueue( int projectId, int buildDefinitionId ) { try { log.debug( "Checking if projectId={}, buildDefinitionId={} is in prepare build queue", projectId, buildDefinitionId ); for ( PrepareBuildProjectsTask task : buildAgentTaskQueueManager.getProjectsInPrepareBuildQueue() ) { if ( task != null ) { for ( BuildContext context : task.getBuildContexts() ) { if ( context.getProjectId() == projectId && ( buildDefinitionId == -1 || context.getBuildDefinitionId() == buildDefinitionId ) ) { log.debug( "projectId={}, buildDefinitionId={} is in prepare build queue" ); return true; } } } } } catch ( TaskQueueManagerException e ) { log.error( "Error while checking if projectId=" + projectId + ", buildDefinitionId=" + buildDefinitionId + " is in prepare build queue in agent", e ); } return false; } public boolean isProjectGroupCurrentlyPreparingBuild( int projectGroupId ) { try { log.debug( "Checking if project group {} currently preparing build", projectGroupId ); PrepareBuildProjectsTask currentPrepareBuildTask = buildAgentTaskQueueManager.getCurrentProjectInPrepareBuild(); if ( currentPrepareBuildTask != null && currentPrepareBuildTask.getProjectGroupId() == projectGroupId ) { return true; } } catch ( TaskQueueManagerException e ) { log.error( "Error while checking if project group " + projectGroupId + " is currently preparing build in agent", e ); } return false; } public boolean isProjectCurrentlyPreparingBuild( int projectId, int buildDefinitionId ) { try { log.debug( "Checking if projectId={}, buildDefinitionId={} currently preparing build", projectId, buildDefinitionId ); PrepareBuildProjectsTask currentPrepareBuildTask = buildAgentTaskQueueManager.getCurrentProjectInPrepareBuild(); if ( currentPrepareBuildTask != null ) { for ( BuildContext context : currentPrepareBuildTask.getBuildContexts() ) { if ( context.getProjectId() == projectId && ( buildDefinitionId == -1 || context.getBuildDefinitionId() == buildDefinitionId ) ) { log.debug( "projectId={}, buildDefinitionId={} is currently preparing build" ); return true; } } } } catch ( TaskQueueManagerException e ) { log.error( "Error while checking if projectId=" + projectId + ", buildDefinitionId=" + buildDefinitionId + " is currently preparing build in agent", e ); } return false; } public boolean isProjectCurrentlyBuilding( int projectId, int buildDefinitionId ) { try { log.debug( "Checking if projectId={}, buildDefinitionId={} is currently building", projectId, buildDefinitionId ); BuildProjectTask currentBuildTask = buildAgentTaskQueueManager.getCurrentProjectInBuilding(); if ( currentBuildTask != null && currentBuildTask.getProjectId() == projectId && ( buildDefinitionId == -1 || currentBuildTask.getBuildDefinitionId() == buildDefinitionId ) ) { log.debug( "projectId={}, buildDefinitionId={} is currently building" ); return true; } } catch ( TaskQueueManagerException e ) { log.error( "Error occurred while checking if projectId=" + projectId + ", buildDefinitionId=" + buildDefinitionId + " is currently building in agent", e ); } return false; } public boolean isProjectInBuildQueue( int projectId, int buildDefinitionId ) { try { log.debug( "Checking if projectId={}, buildDefinitionId={} is in build queue", projectId, buildDefinitionId ); List<BuildProjectTask> buildTasks = buildAgentTaskQueueManager.getProjectsInBuildQueue(); if ( buildTasks != null ) { for ( BuildProjectTask task : buildTasks ) { if ( task.getProjectId() == projectId && ( buildDefinitionId == -1 || task.getBuildDefinitionId() == buildDefinitionId ) ) { log.debug( "projectId={}, buildDefinitionId={} is in build queue" ); return true; } } } } catch ( TaskQueueManagerException e ) { log.error( "Error occurred while checking if projectId=" + projectId + ", buildDefinitionId=" + buildDefinitionId + " is in build queue of agent", e ); } return false; } public boolean removeFromPrepareBuildQueue( int projectGroupId, int scmRootId ) throws ContinuumBuildAgentException { try { log.info( "Removing project group {} from prepare build queue", projectGroupId ); return buildAgentTaskQueueManager.removeFromPrepareBuildQueue( projectGroupId, scmRootId ); } catch ( TaskQueueManagerException e ) { log.error( "Error occurred while removing projects from prepare build queue", e ); throw new ContinuumBuildAgentException( "Error occurred while removing projects from prepare build queue", e ); } } public void removeFromPrepareBuildQueue( List<String> hashCodes ) throws ContinuumBuildAgentException { try { log.info( "Removing project groups {} from prepare build queue", hashCodes ); buildAgentTaskQueueManager.removeFromPrepareBuildQueue( listToIntArray( hashCodes ) ); } catch ( TaskQueueManagerException e ) { log.error( "Error occurred while removing projects from prepare build queue", e ); throw new ContinuumBuildAgentException( "Error occurred while removing projects from prepare build queue", e ); } } public boolean removeFromBuildQueue( int projectId, int buildDefinitionId ) throws ContinuumBuildAgentException { try { log.info( "Removing project {} with buildDefinition {} from build queue", projectId, buildDefinitionId ); return buildAgentTaskQueueManager.removeFromBuildQueue( projectId, buildDefinitionId ); } catch ( TaskQueueManagerException e ) { log.error( "Error occurred while removing project from build queue", e ); throw new ContinuumBuildAgentException( "Error occurred while removing project from build queue ", e ); } } public void removeFromBuildQueue( List<String> hashCodes ) throws ContinuumBuildAgentException { try { log.info( "Removing projects {} from build queue", hashCodes ); buildAgentTaskQueueManager.removeFromBuildQueue( listToIntArray( hashCodes ) ); } catch ( TaskQueueManagerException e ) { log.error( "Error occurred while removing projects from build queue", e ); throw new ContinuumBuildAgentException( "Error occurred while removing project from build queue ", e ); } } public boolean ping() throws ContinuumBuildAgentException { try { // check first if it can ping the master return buildAgentManager.pingMaster(); } catch ( ContinuumException e ) { throw new ContinuumBuildAgentException( e.getMessage() ); } } public String getBuildAgentPlatform() throws ContinuumBuildAgentException { try { log.debug( "Getting build agent platform" ); return System.getProperty( "os.name" ); } catch ( Exception e ) { log.error( "Error in when trying to get build agent's platform", e ); throw new ContinuumBuildAgentException( "Error in when trying to get build agent's platform", e ); } } public boolean isExecutingBuild() { return getBuildSizeOfAgent() > 0; } public boolean isExecutingRelease() throws ContinuumBuildAgentException { try { return buildAgentReleaseManager.getReleaseManager().isExecutingRelease(); } catch ( Exception e ) { throw new ContinuumBuildAgentException( e.getMessage(), e ); } } private void assertPurgePossible() throws ContinuumBuildAgentException { if ( isExecutingBuild() ) { throw new ContinuumBuildAgentException( "agent is executing build" ); } if ( isExecutingRelease() ) { throw new ContinuumBuildAgentException( "agent is executing release" ); } } public void executeDirectoryPurge( String directoryType, int daysOlder, int retentionCount, boolean deleteAll ) throws ContinuumBuildAgentException { assertPurgePossible(); try { purgeManager.executeDirectoryPurge( directoryType, daysOlder, retentionCount, deleteAll ); } catch ( Exception e ) { throw new ContinuumBuildAgentException( e.getMessage(), e ); } } public void executeRepositoryPurge( String repoName, int daysOlder, int retentionCount, boolean deleteAll, boolean deleteReleasedSnapshots ) throws ContinuumBuildAgentException { assertPurgePossible(); try { purgeManager.executeRepositoryPurge( repoName, daysOlder, retentionCount, deleteAll, deleteReleasedSnapshots ); } catch ( Exception e ) { throw new ContinuumBuildAgentException( e.getMessage(), e ); } } private List<BuildContext> initializeBuildContext( List<Map<String, Object>> projectsBuildContext ) { List<BuildContext> buildContext = new ArrayList<BuildContext>(); for ( Map<String, Object> map : projectsBuildContext ) { BuildContext context = new BuildContext(); context.setProjectId( ContinuumBuildAgentUtil.getProjectId( map ) ); context.setProjectVersion( ContinuumBuildAgentUtil.getProjectVersion( map ) ); context.setBuildDefinitionId( ContinuumBuildAgentUtil.getBuildDefinitionId( map ) ); context.setBuildFile( ContinuumBuildAgentUtil.getBuildFile( map ) ); context.setExecutorId( ContinuumBuildAgentUtil.getExecutorId( map ) ); context.setGoals( ContinuumBuildAgentUtil.getGoals( map ) ); context.setArguments( ContinuumBuildAgentUtil.getArguments( map ) ); context.setScmUrl( ContinuumBuildAgentUtil.getScmUrl( map ) ); context.setScmUsername( ContinuumBuildAgentUtil.getScmUsername( map ) ); context.setScmPassword( ContinuumBuildAgentUtil.getScmPassword( map ) ); context.setBuildFresh( ContinuumBuildAgentUtil.isBuildFresh( map ) ); context.setProjectGroupId( ContinuumBuildAgentUtil.getProjectGroupId( map ) ); context.setProjectGroupName( ContinuumBuildAgentUtil.getProjectGroupName( map ) ); context.setScmRootAddress( ContinuumBuildAgentUtil.getScmRootAddress( map ) ); context.setScmRootId( ContinuumBuildAgentUtil.getScmRootId( map ) ); context.setProjectName( ContinuumBuildAgentUtil.getProjectName( map ) ); context.setProjectState( ContinuumBuildAgentUtil.getProjectState( map ) ); context.setTrigger( ContinuumBuildAgentUtil.getTrigger( map ) ); context.setUsername( ContinuumBuildAgentUtil.getUsername( map ) ); context.setLocalRepository( ContinuumBuildAgentUtil.getLocalRepository( map ) ); context.setBuildNumber( ContinuumBuildAgentUtil.getBuildNumber( map ) ); context.setOldScmResult( getScmResult( ContinuumBuildAgentUtil.getOldScmChanges( map ) ) ); context.setLatestUpdateDate( ContinuumBuildAgentUtil.getLatestUpdateDate( map ) ); context.setBuildAgentUrl( ContinuumBuildAgentUtil.getBuildAgentUrl( map ) ); context.setMaxExecutionTime( ContinuumBuildAgentUtil.getMaxExecutionTime( map ) ); context.setBuildDefinitionLabel( ContinuumBuildAgentUtil.getBuildDefinitionLabel( map ) ); context.setScmTag( ContinuumBuildAgentUtil.getScmTag( map ) ); buildContext.add( context ); } buildContextManager.addBuildContexts( buildContext ); return buildContext; } private String getBuildOutputText( int projectId ) { try { File buildOutputFile = buildAgentConfigurationService.getBuildOutputFile( projectId ); if ( buildOutputFile.exists() ) { return StringEscapeUtils.escapeHtml( fsManager.fileContents( buildOutputFile ) ); } } catch ( Exception e ) { // do not throw exception, just log it log.error( "Error retrieving build output file", e ); } return null; } private ScmResult getScmResult( List<Map<String, Object>> scmChanges ) { ScmResult scmResult = null; if ( scmChanges != null && scmChanges.size() > 0 ) { scmResult = new ScmResult(); for ( Map<String, Object> map : scmChanges ) { ChangeSet changeSet = new ChangeSet(); changeSet.setAuthor( ContinuumBuildAgentUtil.getChangeSetAuthor( map ) ); changeSet.setComment( ContinuumBuildAgentUtil.getChangeSetComment( map ) ); changeSet.setDate( ContinuumBuildAgentUtil.getChangeSetDate( map ) ); setChangeFiles( changeSet, map ); scmResult.addChange( changeSet ); } } return scmResult; } private void setChangeFiles( ChangeSet changeSet, Map<String, Object> context ) { List<Map<String, Object>> files = ContinuumBuildAgentUtil.getChangeSetFiles( context ); if ( files != null ) { for ( Map<String, Object> map : files ) { ChangeFile changeFile = new ChangeFile(); changeFile.setName( ContinuumBuildAgentUtil.getChangeFileName( map ) ); changeFile.setRevision( ContinuumBuildAgentUtil.getChangeFileRevision( map ) ); changeFile.setStatus( ContinuumBuildAgentUtil.getChangeFileStatus( map ) ); changeSet.addFile( changeFile ); } } } private PrepareBuildProjectsTask createPrepareBuildProjectsTask( List<BuildContext> buildContexts ) throws ContinuumBuildAgentException { if ( buildContexts != null && buildContexts.size() > 0 ) { BuildContext context = buildContexts.get( 0 ); return new PrepareBuildProjectsTask( buildContexts, new BuildTrigger( context.getTrigger(), context.getUsername() ), context.getProjectGroupId(), context.getScmRootAddress(), context.getScmRootId() ); } else { log.info( "Nothing to build" ); return null; } } private int[] listToIntArray( List<String> strings ) { if ( strings == null || strings.isEmpty() ) { return new int[0]; } int[] array = new int[0]; for ( String intString : strings ) { array = ArrayUtils.add( array, Integer.parseInt( intString ) ); } return array; } }
4,948
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/taskqueue/PrepareBuildProjectsTask.java
package org.apache.continuum.buildagent.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.continuum.buildagent.buildcontext.BuildContext; import org.apache.continuum.utils.build.BuildTrigger; import org.codehaus.plexus.taskqueue.Task; import java.util.List; public class PrepareBuildProjectsTask implements Task { private final List<BuildContext> buildContexts; private BuildTrigger buildTrigger; private final int projectGroupId; private final String scmRootAddress; private final int scmRootId; public PrepareBuildProjectsTask( List<BuildContext> buildContexts, BuildTrigger buildTrigger, int projectGroupId, String scmRootAddress, int scmRootId ) { this.buildContexts = buildContexts; this.buildTrigger = buildTrigger; this.projectGroupId = projectGroupId; this.scmRootAddress = scmRootAddress; this.scmRootId = scmRootId; } public long getMaxExecutionTime() { // TODO Auto-generated method stub return 0; } public List<BuildContext> getBuildContexts() { return buildContexts; } public BuildTrigger getBuildTrigger() { return buildTrigger; } public int getProjectGroupId() { return projectGroupId; } public String getScmRootAddress() { return scmRootAddress; } public int getScmRootId() { return scmRootId; } public int getHashCode() { return projectGroupId + scmRootId + buildTrigger.getTrigger(); } }
4,949
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/taskqueue
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/taskqueue/manager/DefaultBuildAgentTaskQueueManager.java
package org.apache.continuum.buildagent.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.buildagent.taskqueue.PrepareBuildProjectsTask; import org.apache.continuum.taskqueue.BuildProjectTask; import org.apache.continuum.taskqueue.manager.TaskQueueManagerException; import org.apache.continuum.utils.build.BuildTrigger; 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.List; @Component( role = org.apache.continuum.buildagent.taskqueue.manager.BuildAgentTaskQueueManager.class, hint = "default" ) public class DefaultBuildAgentTaskQueueManager implements BuildAgentTaskQueueManager, Contextualizable { private static final Logger log = LoggerFactory.getLogger( DefaultBuildAgentTaskQueueManager.class ); @Requirement( hint = "build-agent" ) private TaskQueue buildAgentBuildQueue; @Requirement( hint = "prepare-build-agent" ) private TaskQueue buildAgentPrepareBuildQueue; private PlexusContainer container; public void cancelBuild() throws TaskQueueManagerException { Task task = getBuildTaskQueueExecutor().getCurrentTask(); if ( task != null ) { if ( task instanceof BuildProjectTask ) { log.info( "Cancelling current build task of project " + ( (BuildProjectTask) task ).getProjectId() ); getBuildTaskQueueExecutor().cancelTask( task ); } else { log.warn( "Current task not a BuildProjectTask - not cancelling" ); } } else { log.warn( "No task running - not cancelling" ); } } public TaskQueue getBuildQueue() { return buildAgentBuildQueue; } public int getIdOfProjectCurrentlyBuilding() throws TaskQueueManagerException { Task task = getBuildTaskQueueExecutor().getCurrentTask(); if ( task != null ) { if ( task instanceof BuildProjectTask ) { log.debug( "Current project building: {}", ( (BuildProjectTask) task ).getProjectName() ); return ( (BuildProjectTask) task ).getProjectId(); } } return -1; } public TaskQueue getPrepareBuildQueue() { return buildAgentPrepareBuildQueue; } private void removeProjectsFromBuildQueue() throws TaskQueueManagerException { try { List<BuildProjectTask> queues = buildAgentBuildQueue.getQueueSnapshot(); if ( queues != null ) { for ( BuildProjectTask task : queues ) { if ( task != null ) { log.info( "remove project '{}' from build queue", task.getProjectName() ); buildAgentBuildQueue.remove( task ); } } } else { log.info( "no build task in queue" ); } } catch ( TaskQueueException e ) { throw new TaskQueueManagerException( "Error while getting build tasks from queue", e ); } } public TaskQueueExecutor getBuildTaskQueueExecutor() throws TaskQueueManagerException { try { return (TaskQueueExecutor) container.lookup( TaskQueueExecutor.class, "build-agent" ); } catch ( ComponentLookupException e ) { throw new TaskQueueManagerException( e.getMessage(), e ); } } public TaskQueueExecutor getPrepareBuildTaskQueueExecutor() throws TaskQueueManagerException { try { return (TaskQueueExecutor) container.lookup( TaskQueueExecutor.class, "prepare-build-agent" ); } catch ( ComponentLookupException e ) { throw new TaskQueueManagerException( e.getMessage(), e ); } } public boolean hasBuildTaskInQueue() throws TaskQueueManagerException { try { if ( getBuildQueue().getQueueSnapshot() != null && getBuildQueue().getQueueSnapshot().size() > 0 ) { return true; } } catch ( TaskQueueException e ) { throw new TaskQueueManagerException( e.getMessage(), e ); } return false; } public boolean isProjectInBuildQueue( int projectId ) throws TaskQueueManagerException { try { List<BuildProjectTask> queues = buildAgentBuildQueue.getQueueSnapshot(); if ( queues != null ) { for ( BuildProjectTask task : queues ) { if ( task != null && task.getProjectId() == projectId ) { log.debug( "project {} is in build queue", task.getProjectName() ); return true; } } } else { log.info( "no build task in queue" ); } } catch ( TaskQueueException e ) { throw new TaskQueueManagerException( e.getMessage(), e ); } return false; } public boolean isInPrepareBuildQueue( int projectGroupId, BuildTrigger buildTrigger, String scmRootAddress ) throws TaskQueueManagerException { try { List<PrepareBuildProjectsTask> queues = buildAgentPrepareBuildQueue.getQueueSnapshot(); if ( queues != null ) { for ( PrepareBuildProjectsTask task : queues ) { if ( task != null && task.getProjectGroupId() == projectGroupId && task.getBuildTrigger().getTrigger() == buildTrigger.getTrigger() && task.getScmRootAddress().equals( scmRootAddress ) ) { log.info( "project group {} in prepare build queue", task.getProjectGroupId() ); return true; } } } else { log.info( "no prepare build task in queue" ); } } catch ( TaskQueueException e ) { throw new TaskQueueManagerException( e.getMessage(), e ); } return false; } public List<PrepareBuildProjectsTask> getProjectsInPrepareBuildQueue() throws TaskQueueManagerException { try { return buildAgentPrepareBuildQueue.getQueueSnapshot(); } catch ( TaskQueueException e ) { log.error( "Error occurred while retrieving projects in prepare build queue", e ); throw new TaskQueueManagerException( "Error occurred while retrieving projects in prepare build queue", e ); } } public List<BuildProjectTask> getProjectsInBuildQueue() throws TaskQueueManagerException { try { return buildAgentBuildQueue.getQueueSnapshot(); } catch ( TaskQueueException e ) { log.error( "Error occurred while retrieving projects in build queue", e ); throw new TaskQueueManagerException( "Error occurred while retrieving projects in build queue", e ); } } public PrepareBuildProjectsTask getCurrentProjectInPrepareBuild() throws TaskQueueManagerException { Task task = getPrepareBuildTaskQueueExecutor().getCurrentTask(); if ( task != null ) { log.debug( "Current project group preparing build: {}", ( (PrepareBuildProjectsTask) task ).getProjectGroupId() ); return (PrepareBuildProjectsTask) task; } return null; } public BuildProjectTask getCurrentProjectInBuilding() throws TaskQueueManagerException { Task task = getBuildTaskQueueExecutor().getCurrentTask(); if ( task != null ) { log.debug( "Current project building: {}", ( (BuildProjectTask) task ).getProjectName() ); return (BuildProjectTask) task; } return null; } public boolean removeFromPrepareBuildQueue( int projectGroupId, int scmRootId ) throws TaskQueueManagerException { List<PrepareBuildProjectsTask> tasks = getProjectsInPrepareBuildQueue(); if ( tasks != null ) { for ( PrepareBuildProjectsTask task : tasks ) { if ( task != null && task.getProjectGroupId() == projectGroupId && task.getScmRootId() == scmRootId ) { log.debug( "Remove project group {} from prepare build queue", projectGroupId ); return getPrepareBuildQueue().remove( task ); } } } return false; } public void removeFromPrepareBuildQueue( int[] hashCodes ) throws TaskQueueManagerException { List<PrepareBuildProjectsTask> tasks = getProjectsInPrepareBuildQueue(); if ( tasks != null ) { for ( PrepareBuildProjectsTask task : tasks ) { if ( task != null && ArrayUtils.contains( hashCodes, task.getHashCode() ) ) { log.debug( "Remove project group '{}' from prepare build queue", task.getProjectGroupId() ); getPrepareBuildQueue().remove( task ); } } } } public boolean removeFromBuildQueue( int projectId, int buildDefinitionId ) throws TaskQueueManagerException { List<BuildProjectTask> tasks = getProjectsInBuildQueue(); if ( tasks != null ) { for ( BuildProjectTask task : tasks ) { if ( task != null && task.getProjectId() == projectId && task.getBuildDefinitionId() == buildDefinitionId ) { log.debug( "Remove project {} with buildDefinition{} from build queue", task.getProjectName(), task.getBuildDefinitionId() ); return getBuildQueue().remove( task ); } } } return false; } public void removeFromBuildQueue( int[] hashCodes ) throws TaskQueueManagerException { List<BuildProjectTask> tasks = getProjectsInBuildQueue(); if ( tasks != null ) { for ( BuildProjectTask task : tasks ) { if ( task != null && ArrayUtils.contains( hashCodes, task.getHashCode() ) ) { log.debug( "Remove project '{}' from build queue", task.getProjectName() ); getBuildQueue().remove( task ); } } } } public void contextualize( Context context ) throws ContextException { container = (PlexusContainer) context.get( PlexusConstants.PLEXUS_KEY ); } }
4,950
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/taskqueue
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/taskqueue/manager/BuildAgentTaskQueueManager.java
package org.apache.continuum.buildagent.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.continuum.buildagent.taskqueue.PrepareBuildProjectsTask; import org.apache.continuum.taskqueue.BuildProjectTask; import org.apache.continuum.taskqueue.manager.TaskQueueManagerException; import org.apache.continuum.utils.build.BuildTrigger; import org.codehaus.plexus.taskqueue.TaskQueue; import java.util.List; public interface BuildAgentTaskQueueManager { String ROLE = BuildAgentTaskQueueManager.class.getName(); TaskQueue getBuildQueue(); TaskQueue getPrepareBuildQueue(); void cancelBuild() throws TaskQueueManagerException; int getIdOfProjectCurrentlyBuilding() throws TaskQueueManagerException; BuildProjectTask getCurrentProjectInBuilding() throws TaskQueueManagerException; PrepareBuildProjectsTask getCurrentProjectInPrepareBuild() throws TaskQueueManagerException; boolean hasBuildTaskInQueue() throws TaskQueueManagerException; boolean isProjectInBuildQueue( int projectId ) throws TaskQueueManagerException; boolean isInPrepareBuildQueue( int projectGroupId, BuildTrigger trigger, String scmRootAddress ) throws TaskQueueManagerException; List<PrepareBuildProjectsTask> getProjectsInPrepareBuildQueue() throws TaskQueueManagerException; List<BuildProjectTask> getProjectsInBuildQueue() throws TaskQueueManagerException; boolean removeFromPrepareBuildQueue( int projectGroupId, int scmRootId ) throws TaskQueueManagerException; void removeFromPrepareBuildQueue( int[] hashCodes ) throws TaskQueueManagerException; boolean removeFromBuildQueue( int projectId, int buildDefinitionId ) throws TaskQueueManagerException; void removeFromBuildQueue( int[] hashCodes ) throws TaskQueueManagerException; }
4,951
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/taskqueue
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/taskqueue/execution/PrepareBuildProjectsTaskExecutor.java
package org.apache.continuum.buildagent.taskqueue.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.buildagent.buildcontext.BuildContext; import org.apache.continuum.buildagent.configuration.BuildAgentConfigurationService; import org.apache.continuum.buildagent.manager.BuildAgentManager; import org.apache.continuum.buildagent.taskqueue.PrepareBuildProjectsTask; import org.apache.continuum.buildagent.utils.BuildContextToBuildDefinition; import org.apache.continuum.buildagent.utils.BuildContextToProject; import org.apache.continuum.buildagent.utils.ContinuumBuildAgentUtil; import org.apache.maven.continuum.ContinuumException; import org.apache.maven.continuum.model.project.BuildDefinition; import org.apache.maven.continuum.model.project.Project; 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.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.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; @Component( role = org.codehaus.plexus.taskqueue.execution.TaskExecutor.class, hint = "prepare-build-agent" ) public class PrepareBuildProjectsTaskExecutor implements TaskExecutor { private static final Logger log = LoggerFactory.getLogger( PrepareBuildProjectsTaskExecutor.class ); @Requirement private ActionManager actionManager; @Requirement private BuildAgentConfigurationService buildAgentConfigurationService; @Requirement private BuildAgentManager buildAgentManager; public void executeTask( Task task ) throws TaskExecutionException { List<BuildContext> buildContexts = ( (PrepareBuildProjectsTask) task ).getBuildContexts(); Map<String, Object> context = null; try { if ( buildContexts != null && buildContexts.size() > 0 ) { try { for ( BuildContext buildContext : buildContexts ) { BuildDefinition buildDef = BuildContextToBuildDefinition.getBuildDefinition( buildContext ); log.debug( "Check scm root state of project group '{}'", buildContext.getProjectGroupName() ); if ( !checkProjectScmRoot( context ) ) { break; } log.info( "Starting prepare build of project group '{}'", buildContext.getProjectGroupName() ); startPrepareBuild( buildContext ); log.info( "Initializing prepare build" ); initializeActionContext( buildContext ); try { if ( buildDef.isBuildFresh() ) { log.info( "Clean up working directory of project '{}'", buildContext.getProjectName() ); cleanWorkingDirectory( buildContext ); } log.info( "Updating working directory of project '{}'", buildContext.getProjectName() ); updateWorkingDirectory( buildContext ); //CONTINUUM-1393 if ( !buildDef.isBuildFresh() ) { log.info( "Merging SCM results of project '{}'", buildContext.getProjectName() ); mergeScmResults( buildContext ); } } finally { endProjectPrepareBuild( buildContext ); context = buildContext.getActionContext(); } } } finally { endPrepareBuild( context ); } if ( checkProjectScmRoot( context ) ) { log.debug( "Successful prepare build. Creating build task" ); buildProjects( buildContexts ); } } else { throw new TaskExecutionException( "No project build context" ); } } catch ( TaskExecutionException e ) { log.error( "Error while preparing build of project: {}", e.getMessage() ); } } private void startPrepareBuild( BuildContext buildContext ) throws TaskExecutionException { Map<String, Object> actionContext = buildContext.getActionContext(); if ( actionContext == null || !( ContinuumBuildAgentUtil.getScmRootState( actionContext ) == ContinuumProjectState.UPDATING ) ) { Map<String, Object> map = new HashMap<String, Object>(); map.put( ContinuumBuildAgentUtil.KEY_PROJECT_GROUP_ID, buildContext.getProjectGroupId() ); map.put( ContinuumBuildAgentUtil.KEY_SCM_ROOT_ADDRESS, buildContext.getScmRootAddress() ); map.put( ContinuumBuildAgentUtil.KEY_BUILD_AGENT_URL, buildContext.getBuildAgentUrl() ); try { buildAgentManager.startPrepareBuild( map ); } catch ( ContinuumException e ) { throw new TaskExecutionException( e.getMessage(), e ); } } } private void initializeActionContext( BuildContext buildContext ) { Map<String, Object> actionContext = new HashMap<String, Object>(); actionContext.put( ContinuumBuildAgentUtil.KEY_PROJECT_ID, buildContext.getProjectId() ); actionContext.put( ContinuumBuildAgentUtil.KEY_PROJECT, BuildContextToProject.getProject( buildContext ) ); actionContext.put( ContinuumBuildAgentUtil.KEY_BUILD_DEFINITION, BuildContextToBuildDefinition.getBuildDefinition( buildContext ) ); actionContext.put( ContinuumBuildAgentUtil.KEY_SCM_ROOT_STATE, ContinuumProjectState.UPDATING ); actionContext.put( ContinuumBuildAgentUtil.KEY_PROJECT_GROUP_ID, buildContext.getProjectGroupId() ); actionContext.put( ContinuumBuildAgentUtil.KEY_SCM_ROOT_ADDRESS, buildContext.getScmRootAddress() ); actionContext.put( ContinuumBuildAgentUtil.KEY_OLD_SCM_RESULT, buildContext.getOldScmResult() ); actionContext.put( ContinuumBuildAgentUtil.KEY_LATEST_UPDATE_DATE, buildContext.getLatestUpdateDate() ); actionContext.put( ContinuumBuildAgentUtil.KEY_TRIGGER, buildContext.getTrigger() ); actionContext.put( ContinuumBuildAgentUtil.KEY_USERNAME, buildContext.getUsername() ); actionContext.put( ContinuumBuildAgentUtil.KEY_SCM_USERNAME, buildContext.getScmUsername() ); actionContext.put( ContinuumBuildAgentUtil.KEY_SCM_PASSWORD, buildContext.getScmPassword() ); actionContext.put( ContinuumBuildAgentUtil.KEY_BUILD_AGENT_URL, buildContext.getBuildAgentUrl() ); buildContext.setActionContext( actionContext ); } private boolean checkProjectScmRoot( Map<String, Object> context ) { return !( context != null && ContinuumBuildAgentUtil.getScmRootState( context ) == ContinuumProjectState.ERROR ); } private void cleanWorkingDirectory( BuildContext buildContext ) throws TaskExecutionException { performAction( "clean-agent-working-directory", buildContext ); } private void updateWorkingDirectory( BuildContext buildContext ) throws TaskExecutionException { Map<String, Object> actionContext = buildContext.getActionContext(); performAction( "check-agent-working-directory", buildContext ); boolean workingDirectoryExists = ContinuumBuildAgentUtil.getBoolean( actionContext, ContinuumBuildAgentUtil.KEY_WORKING_DIRECTORY_EXISTS ); ScmResult scmResult; Date date; if ( workingDirectoryExists ) { performAction( "update-agent-working-directory", buildContext ); scmResult = ContinuumBuildAgentUtil.getUpdateScmResult( actionContext, null ); date = ContinuumBuildAgentUtil.getLatestUpdateDate( actionContext ); } else { Project project = ContinuumBuildAgentUtil.getProject( actionContext ); actionContext.put( ContinuumBuildAgentUtil.KEY_WORKING_DIRECTORY, buildAgentConfigurationService.getWorkingDirectory( project.getId() ).getAbsolutePath() ); performAction( "checkout-agent-project", buildContext ); scmResult = ContinuumBuildAgentUtil.getCheckoutScmResult( actionContext, null ); performAction( "changelog-agent-project", buildContext ); date = ContinuumBuildAgentUtil.getLatestUpdateDate( actionContext ); } buildContext.setScmResult( scmResult ); buildContext.setLatestUpdateDate( date ); actionContext.put( ContinuumBuildAgentUtil.KEY_SCM_RESULT, scmResult ); } private void endProjectPrepareBuild( BuildContext buildContext ) throws TaskExecutionException { Map<String, Object> context = buildContext.getActionContext(); ScmResult scmResult = ContinuumBuildAgentUtil.getScmResult( context, null ); log.debug( "End prepare build of project '{}'", buildContext.getProjectName() ); if ( scmResult == null || !scmResult.isSuccess() ) { context.put( ContinuumBuildAgentUtil.KEY_SCM_ROOT_STATE, ContinuumProjectState.ERROR ); } else { buildContext.setScmResult( scmResult ); } } private void endPrepareBuild( Map<String, Object> context ) throws TaskExecutionException { if ( context != null ) { Map<String, Object> result = new HashMap<String, Object>(); result.put( ContinuumBuildAgentUtil.KEY_PROJECT_GROUP_ID, ContinuumBuildAgentUtil.getProjectGroupId( context ) ); result.put( ContinuumBuildAgentUtil.KEY_SCM_ROOT_ADDRESS, ContinuumBuildAgentUtil.getScmRootAddress( context ) ); result.put( ContinuumBuildAgentUtil.KEY_SCM_ROOT_STATE, ContinuumBuildAgentUtil.getScmRootState( context ) ); result.put( ContinuumBuildAgentUtil.KEY_BUILD_AGENT_URL, ContinuumBuildAgentUtil.getBuildAgentUrl( context ) ); if ( ContinuumBuildAgentUtil.getScmRootState( context ) == ContinuumProjectState.ERROR ) { String error = convertScmResultToError( ContinuumBuildAgentUtil.getScmResult( context, null ) ); if ( StringUtils.isEmpty( error ) ) { result.put( ContinuumBuildAgentUtil.KEY_SCM_ERROR, "" ); } else { result.put( ContinuumBuildAgentUtil.KEY_SCM_ERROR, error ); } } else { result.put( ContinuumBuildAgentUtil.KEY_SCM_ERROR, "" ); } try { log.debug( "End prepare build of project group '{}'", ContinuumBuildAgentUtil.getProjectGroupId( context ) ); buildAgentManager.endPrepareBuild( result ); } catch ( ContinuumException e ) { throw new TaskExecutionException( e.getMessage(), e ); } } else { throw new TaskExecutionException( "No project build context" ); } } 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 performAction( String actionName, BuildContext buildContext ) throws TaskExecutionException { TaskExecutionException exception; try { log.info( "Performing action " + actionName ); actionManager.lookup( actionName ).execute( buildContext.getActionContext() ); 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( ContinuumBuildAgentUtil.throwableToString( exception ) ); buildContext.setScmResult( result ); buildContext.getActionContext().put( ContinuumBuildAgentUtil.KEY_UPDATE_SCM_RESULT, result ); throw exception; } private void mergeScmResults( BuildContext buildContext ) { Map<String, Object> context = buildContext.getActionContext(); ScmResult oldScmResult = ContinuumBuildAgentUtil.getOldScmResult( context, null ); ScmResult newScmResult = ContinuumBuildAgentUtil.getScmResult( context, null ); if ( oldScmResult != null ) { if ( newScmResult == null ) { context.put( ContinuumBuildAgentUtil.KEY_SCM_RESULT, 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 buildProjects( List<BuildContext> buildContexts ) throws TaskExecutionException { Map<String, Object> map = new HashMap<String, Object>(); map.put( ContinuumBuildAgentUtil.KEY_BUILD_CONTEXTS, buildContexts ); BuildContext context = new BuildContext(); context.setActionContext( map ); performAction( "create-agent-build-project-task", context ); } }
4,952
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/taskqueue
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/taskqueue/execution/BuildProjectTaskExecutor.java
package org.apache.continuum.buildagent.taskqueue.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.commons.lang.StringEscapeUtils; import org.apache.continuum.buildagent.build.execution.ContinuumAgentBuildExecutor; import org.apache.continuum.buildagent.build.execution.ContinuumAgentBuildExecutorException; import org.apache.continuum.buildagent.build.execution.manager.BuildAgentBuildExecutorManager; import org.apache.continuum.buildagent.buildcontext.BuildContext; import org.apache.continuum.buildagent.buildcontext.manager.BuildContextManager; import org.apache.continuum.buildagent.configuration.BuildAgentConfigurationException; import org.apache.continuum.buildagent.configuration.BuildAgentConfigurationService; import org.apache.continuum.buildagent.installation.BuildAgentInstallationService; import org.apache.continuum.buildagent.manager.BuildAgentManager; import org.apache.continuum.buildagent.model.Installation; import org.apache.continuum.buildagent.model.LocalRepository; import org.apache.continuum.buildagent.utils.BuildContextToBuildDefinition; import org.apache.continuum.buildagent.utils.BuildContextToProject; import org.apache.continuum.buildagent.utils.ContinuumBuildAgentUtil; import org.apache.continuum.taskqueue.BuildProjectTask; import org.apache.continuum.utils.file.FileSystemManager; import org.apache.maven.continuum.ContinuumException; import org.apache.maven.continuum.execution.ContinuumBuildExecutorConstants; 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.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.project.MavenProject; 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.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.Iterator; import java.util.List; import java.util.Map; @Component( role = org.codehaus.plexus.taskqueue.execution.TaskExecutor.class, hint = "build-agent" ) public class BuildProjectTaskExecutor implements TaskExecutor { private static final Logger log = LoggerFactory.getLogger( BuildProjectTaskExecutor.class ); @Requirement private BuildContextManager buildContextManager; @Requirement private ActionManager actionManager; @Requirement private BuildAgentConfigurationService buildAgentConfigurationService; @Requirement private BuildAgentManager buildAgentManager; @Requirement private BuildAgentBuildExecutorManager buildAgentBuildExecutorManager; @Requirement FileSystemManager fsManager; public void executeTask( Task task ) throws TaskExecutionException { BuildProjectTask buildProjectTask = (BuildProjectTask) task; int projectId = buildProjectTask.getProjectId(); try { log.info( "Initializing build (projectId={})", projectId ); BuildContext context = buildContextManager.getBuildContext( projectId ); initializeBuildContext( context ); if ( !checkScmResult( context ) ) { return; } log.info( "Checking if project '{}' should build", context.getProjectName() ); if ( !shouldBuild( context ) ) { return; } log.info( "Starting build of {}", context.getProjectName() ); startBuild( context ); try { try { performAction( "update-project-from-agent-working-directory", context ); } catch ( TaskExecutionException e ) { updateBuildResult( context, ContinuumBuildAgentUtil.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-agent-working-directory '", e ); } performAction( "execute-agent-builder", context ); log.info( "Updating build result of project '{}'", context.getProjectName() ); updateBuildResult( context, null ); } finally { log.info( "End build of project '{}'", context.getProjectName() ); endBuild( context ); } } catch ( TaskExecutionException e ) { log.error( "Error while trying to build the project {}: {}", projectId, e.getMessage() ); } } private void initializeBuildContext( BuildContext buildContext ) throws TaskExecutionException { Map<String, Object> actionContext = new HashMap<String, Object>(); actionContext.put( ContinuumBuildAgentUtil.KEY_PROJECT_ID, buildContext.getProjectId() ); Project project = BuildContextToProject.getProject( buildContext ); ProjectGroup projectGroup = new ProjectGroup(); projectGroup.setId( buildContext.getProjectGroupId() ); projectGroup.setName( buildContext.getProjectGroupName() ); project.setProjectGroup( projectGroup ); actionContext.put( ContinuumBuildAgentUtil.KEY_PROJECT, project ); actionContext.put( ContinuumBuildAgentUtil.KEY_BUILD_DEFINITION, BuildContextToBuildDefinition.getBuildDefinition( buildContext ) ); actionContext.put( ContinuumBuildAgentUtil.KEY_BUILD_DEFINITION_ID, buildContext.getBuildDefinitionId() ); actionContext.put( ContinuumBuildAgentUtil.KEY_TRIGGER, buildContext.getTrigger() ); actionContext.put( ContinuumBuildAgentUtil.KEY_USERNAME, buildContext.getUsername() ); actionContext.put( ContinuumBuildAgentUtil.KEY_ENVIRONMENTS, getEnvironments( buildContext.getBuildDefinitionId(), getInstallationType( buildContext ) ) ); // CONTINUUM-2391 String localRepoName = buildContext.getLocalRepository(); if ( localRepoName != null ) { try { LocalRepository localRepo = buildAgentConfigurationService.getLocalRepositoryByName( localRepoName ); actionContext.put( ContinuumBuildAgentUtil.KEY_LOCAL_REPOSITORY, localRepo.getLocation() ); } catch ( BuildAgentConfigurationException e ) { log.warn( "failed to initialize local repo", e ); } } actionContext.put( ContinuumBuildAgentUtil.KEY_SCM_RESULT, buildContext.getScmResult() ); buildContext.setActionContext( actionContext ); buildContext.setBuildStartTime( System.currentTimeMillis() ); } private boolean checkScmResult( BuildContext buildContext ) { if ( buildContext.getScmResult() == null ) { log.info( "Error updating from SCM, SCM result is null, not building" ); return false; } else if ( !buildContext.getScmResult().isSuccess() ) { log.info( "Error updating from SCM, SCM result has errors, not building" ); return false; } return true; } private void startBuild( BuildContext buildContext ) throws TaskExecutionException { try { buildAgentManager.startProjectBuild( buildContext.getProjectId(), buildContext.getBuildDefinitionId() ); } catch ( ContinuumException e ) { // do not throw exception, just log? log.error( "Failed to start project '" + buildContext.getProjectName() + "'", e ); throw new TaskExecutionException( "Failed to start project '" + buildContext.getProjectName() + "'", e ); } } private void endBuild( BuildContext buildContext ) throws TaskExecutionException { // return build result to master BuildResult buildResult = buildContext.getBuildResult(); Map<String, Object> result = new HashMap<String, Object>(); result.put( ContinuumBuildAgentUtil.KEY_PROJECT_ID, buildContext.getProjectId() ); result.put( ContinuumBuildAgentUtil.KEY_BUILD_DEFINITION_ID, buildContext.getBuildDefinitionId() ); result.put( ContinuumBuildAgentUtil.KEY_TRIGGER, buildContext.getTrigger() ); result.put( ContinuumBuildAgentUtil.KEY_USERNAME, buildContext.getUsername() ); result.put( ContinuumBuildAgentUtil.KEY_BUILD_STATE, buildResult.getState() ); result.put( ContinuumBuildAgentUtil.KEY_START_TIME, Long.toString( buildResult.getStartTime() ) ); result.put( ContinuumBuildAgentUtil.KEY_END_TIME, Long.toString( buildResult.getEndTime() ) ); result.put( ContinuumBuildAgentUtil.KEY_BUILD_EXIT_CODE, buildResult.getExitCode() ); if ( buildContext.getLatestUpdateDate() != null ) { result.put( ContinuumBuildAgentUtil.KEY_LATEST_UPDATE_DATE, buildContext.getLatestUpdateDate() ); } String buildOutput = getBuildOutputText( buildContext.getProjectId() ); if ( buildOutput == null ) { result.put( ContinuumBuildAgentUtil.KEY_BUILD_OUTPUT, "" ); } else { result.put( ContinuumBuildAgentUtil.KEY_BUILD_OUTPUT, buildOutput ); } if ( buildResult.getError() != null ) { result.put( ContinuumBuildAgentUtil.KEY_BUILD_ERROR, buildResult.getError() ); } else { result.put( ContinuumBuildAgentUtil.KEY_BUILD_ERROR, "" ); } result.put( ContinuumBuildAgentUtil.KEY_SCM_RESULT, ContinuumBuildAgentUtil.createScmResult( buildContext ) ); result.put( ContinuumBuildAgentUtil.KEY_BUILD_AGENT_URL, buildContext.getBuildAgentUrl() ); try { buildAgentManager.returnBuildResult( result ); buildContextManager.removeBuildContext( buildContext.getProjectId() ); } catch ( ContinuumException e ) { log.error( "Failed to return build result for project '" + buildContext.getProjectName() + "'", e ); throw new TaskExecutionException( "Failed to return build result for project '" + buildContext.getProjectName() + "'", e ); } } 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 = ContinuumBuildAgentUtil.throwableToString( e ); exception = new TaskExecutionException( "Error looking up action '" + actionName + "'", e ); } catch ( ScmRepositoryException e ) { error = getValidationMessages( e ) + "\n" + ContinuumBuildAgentUtil.throwableToString( e ); exception = new TaskExecutionException( "SCM error while executing '" + actionName + "'", e ); } catch ( ScmException e ) { error = ContinuumBuildAgentUtil.throwableToString( e ); exception = new TaskExecutionException( "SCM error while executing '" + actionName + "'", e ); } catch ( Exception e ) { exception = new TaskExecutionException( "Error executing action '" + actionName + "'", e ); error = ContinuumBuildAgentUtil.throwableToString( exception ); } updateBuildResult( context, error ); throw exception; } private void updateBuildResult( BuildContext context, String error ) { context.setBuildResult( ContinuumBuildAgentUtil.getBuildResult( context.getActionContext(), null ) ); if ( context.getBuildResult() == null ) { BuildResult build = new BuildResult(); build.setState( ContinuumProjectState.ERROR ); build.setTrigger( context.getTrigger() ); build.setUsername( context.getUsername() ); build.setStartTime( context.getBuildStartTime() ); build.setEndTime( System.currentTimeMillis() ); build.setBuildDefinition( BuildContextToBuildDefinition.getBuildDefinition( context ) ); build.setScmResult( context.getScmResult() ); if ( error != null ) { build.setError( error ); } context.setBuildResult( build ); } } 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(); } private String getBuildOutputText( int projectId ) { try { File buildOutputFile = buildAgentConfigurationService.getBuildOutputFile( projectId ); if ( buildOutputFile.exists() ) { return StringEscapeUtils.escapeHtml( fsManager.fileContents( buildOutputFile ) ); } } catch ( Exception e ) { // do not throw exception, just log it log.error( "Error retrieving build output file", e ); } return null; } private Map<String, String> getEnvironments( int buildDefinitionId, String installationType ) throws TaskExecutionException { try { // get environments from Master (Continuum) Map<String, String> environments = buildAgentManager.getEnvironments( buildDefinitionId, installationType ); List<Installation> installations = buildAgentConfigurationService.getAvailableInstallations(); if ( installations != null ) { // get environments from Slave (Build Agent) for ( Installation installation : installations ) { // combine environments (Master and Slave); Slave's environments overwrite Master's environments environments.put( installation.getVarName(), installation.getVarValue() ); } } return environments; } catch ( ContinuumException e ) { log.error( "Error while retrieving environments of build definition: " + buildDefinitionId, e ); throw new TaskExecutionException( "Error while retrieving environments of build definition: " + buildDefinitionId, e ); } } private String getInstallationType( BuildContext buildContext ) { String executorId = buildContext.getExecutorId(); if ( ContinuumBuildExecutorConstants.MAVEN_TWO_BUILD_EXECUTOR.equals( executorId ) ) { return BuildAgentInstallationService.MAVEN2_TYPE; } else if ( ContinuumBuildExecutorConstants.MAVEN_ONE_BUILD_EXECUTOR.equals( executorId ) ) { return BuildAgentInstallationService.MAVEN1_TYPE; } else if ( ContinuumBuildExecutorConstants.ANT_BUILD_EXECUTOR.equals( executorId ) ) { return BuildAgentInstallationService.ANT_TYPE; } return ""; } private boolean shouldBuild( BuildContext context ) throws TaskExecutionException { Map<String, Object> map = new HashMap<String, Object>(); map.put( ContinuumBuildAgentUtil.KEY_PROJECT_ID, context.getProjectId() ); map.put( ContinuumBuildAgentUtil.KEY_BUILD_DEFINITION_ID, context.getBuildDefinitionId() ); map.put( ContinuumBuildAgentUtil.KEY_TRIGGER, context.getTrigger() ); map.put( ContinuumBuildAgentUtil.KEY_USERNAME, context.getUsername() ); map.put( ContinuumBuildAgentUtil.KEY_SCM_CHANGES, getScmChanges( context.getScmResult() ) ); map.put( ContinuumBuildAgentUtil.KEY_BUILD_AGENT_URL, context.getBuildAgentUrl() ); if ( context.getExecutorId().equals( ContinuumBuildExecutorConstants.MAVEN_TWO_BUILD_EXECUTOR ) ) { map.put( ContinuumBuildAgentUtil.KEY_MAVEN_PROJECT, getMavenProject( context ) ); } if ( context.getLatestUpdateDate() != null ) { map.put( ContinuumBuildAgentUtil.KEY_LATEST_UPDATE_DATE, context.getLatestUpdateDate() ); } try { return buildAgentManager.shouldBuild( map ); } catch ( ContinuumException e ) { log.error( "Failed to determine if project should build", e ); throw new TaskExecutionException( "Failed to determine if project should build", e ); } } 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( ContinuumBuildAgentUtil.KEY_CHANGESET_AUTHOR, changeSet.getAuthor() ); } else { map.put( ContinuumBuildAgentUtil.KEY_CHANGESET_AUTHOR, "" ); } if ( StringUtils.isNotEmpty( changeSet.getComment() ) ) { map.put( ContinuumBuildAgentUtil.KEY_CHANGESET_COMMENT, changeSet.getComment() ); } else { map.put( ContinuumBuildAgentUtil.KEY_CHANGESET_COMMENT, "" ); } if ( changeSet.getDateAsDate() != null ) { map.put( ContinuumBuildAgentUtil.KEY_CHANGESET_DATE, changeSet.getDateAsDate() ); } map.put( ContinuumBuildAgentUtil.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( ContinuumBuildAgentUtil.KEY_CHANGEFILE_NAME, changeFile.getName() ); } else { map.put( ContinuumBuildAgentUtil.KEY_CHANGEFILE_NAME, "" ); } if ( StringUtils.isNotEmpty( changeFile.getRevision() ) ) { map.put( ContinuumBuildAgentUtil.KEY_CHANGEFILE_REVISION, changeFile.getRevision() ); } else { map.put( ContinuumBuildAgentUtil.KEY_CHANGEFILE_REVISION, "" ); } if ( StringUtils.isNotEmpty( changeFile.getStatus() ) ) { map.put( ContinuumBuildAgentUtil.KEY_CHANGEFILE_STATUS, changeFile.getStatus() ); } else { map.put( ContinuumBuildAgentUtil.KEY_CHANGEFILE_STATUS, "" ); } scmChangeFiles.add( map ); } } return scmChangeFiles; } private Map getMavenProject( BuildContext context ) throws TaskExecutionException { Map<String, Object> mavenProject = new HashMap<String, Object>(); try { ContinuumAgentBuildExecutor buildExecutor = buildAgentBuildExecutorManager.getBuildExecutor( context.getExecutorId() ); BuildDefinition buildDefinition = BuildContextToBuildDefinition.getBuildDefinition( context ); File workingDirectory = buildAgentConfigurationService.getWorkingDirectory( context.getProjectId() ); MavenProject project = buildExecutor.getMavenProject( workingDirectory, buildDefinition ); mavenProject.put( ContinuumBuildAgentUtil.KEY_PROJECT_VERSION, project.getVersion() ); if ( project.getModules() != null ) { mavenProject.put( ContinuumBuildAgentUtil.KEY_PROJECT_MODULES, project.getModules() ); } } catch ( ContinuumAgentBuildExecutorException e ) { log.error( "Error getting maven project", e ); } catch ( ContinuumException e ) { log.error( "Error getting build executor", e ); } return mavenProject; } public void setBuildContextManager( BuildContextManager buildContextManager ) { this.buildContextManager = buildContextManager; } public void setActionManager( ActionManager actionManager ) { this.actionManager = actionManager; } public void setBuildAgentConfigurationService( BuildAgentConfigurationService buildAgentConfigurationService ) { this.buildAgentConfigurationService = buildAgentConfigurationService; } public void setBuildAgentManager( BuildAgentManager buildAgentManager ) { this.buildAgentManager = buildAgentManager; } public void setBuildAgentBuildExecutorManager( BuildAgentBuildExecutorManager buildAgentBuildExecutorManager ) { this.buildAgentBuildExecutorManager = buildAgentBuildExecutorManager; } }
4,953
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/configuration/DefaultBuildAgentConfiguration.java
package org.apache.continuum.buildagent.configuration; /* * 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.model.ContinuumBuildAgentConfigurationModel; import org.apache.continuum.buildagent.model.io.xpp3.ContinuumBuildAgentConfigurationModelXpp3Reader; import org.apache.continuum.buildagent.model.io.xpp3.ContinuumBuildAgentConfigurationModelXpp3Writer; import org.codehaus.plexus.util.IOUtil; import org.codehaus.plexus.util.StringUtils; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; 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; public class DefaultBuildAgentConfiguration implements BuildAgentConfiguration { private static final Logger log = LoggerFactory.getLogger( DefaultBuildAgentConfiguration.class ); private File configurationFile; private GeneralBuildAgentConfiguration generalBuildAgentConfiguration; protected void initialize() { if ( log.isDebugEnabled() ) { log.debug( "configurationFile null " + ( configurationFile.getPath() == null ) ); } if ( configurationFile != null && configurationFile.exists() ) { try { reload( configurationFile ); } catch ( BuildAgentConfigurationException e ) { // skip this and only log a warn log.warn( " error on loading configuration from file " + configurationFile.getPath() ); } } else { log.info( "build agent configuration file does not exists" ); this.generalBuildAgentConfiguration = new GeneralBuildAgentConfiguration(); } } public GeneralBuildAgentConfiguration getContinuumBuildAgentConfiguration() { return generalBuildAgentConfiguration; } public void reload() throws BuildAgentConfigurationException { this.initialize(); } public void reload( File file ) throws BuildAgentConfigurationException { FileInputStream fis = null; try { fis = new FileInputStream( file ); ContinuumBuildAgentConfigurationModelXpp3Reader configurationXpp3Reader = new ContinuumBuildAgentConfigurationModelXpp3Reader(); ContinuumBuildAgentConfigurationModel configuration = configurationXpp3Reader.read( new InputStreamReader( fis ) ); this.generalBuildAgentConfiguration = new GeneralBuildAgentConfiguration(); if ( StringUtils.isNotEmpty( configuration.getBuildOutputDirectory() ) ) { this.generalBuildAgentConfiguration.setBuildOutputDirectory( new File( configuration.getBuildOutputDirectory() ) ); } if ( StringUtils.isNotEmpty( configuration.getWorkingDirectory() ) ) { this.generalBuildAgentConfiguration.setWorkingDirectory( new File( configuration.getWorkingDirectory() ) ); } this.generalBuildAgentConfiguration.setContinuumServerUrl( configuration.getContinuumServerUrl() ); this.generalBuildAgentConfiguration.setInstallations( configuration.getInstallations() ); this.generalBuildAgentConfiguration.setLocalRepositories( configuration.getLocalRepositories() ); this.generalBuildAgentConfiguration.setSharedSecretPassword( configuration.getSharedSecretPassword() ); } catch ( IOException e ) { log.error( e.getMessage(), e ); throw new BuildAgentConfigurationException( e.getMessage(), e ); } catch ( XmlPullParserException e ) { log.error( e.getMessage(), e ); throw new BuildAgentConfigurationException( e.getMessage(), e ); } finally { if ( fis != null ) { IOUtil.close( fis ); } } } public void save() throws BuildAgentConfigurationException { if ( !configurationFile.exists() ) { configurationFile.getParentFile().mkdirs(); } save( configurationFile ); } public void save( File file ) throws BuildAgentConfigurationException { try { ContinuumBuildAgentConfigurationModel configurationModel = new ContinuumBuildAgentConfigurationModel(); if ( this.generalBuildAgentConfiguration.getBuildOutputDirectory() != null ) { configurationModel.setBuildOutputDirectory( this.generalBuildAgentConfiguration.getBuildOutputDirectory().getPath() ); } if ( this.generalBuildAgentConfiguration.getWorkingDirectory() != null ) { configurationModel.setWorkingDirectory( this.generalBuildAgentConfiguration.getWorkingDirectory().getPath() ); } configurationModel.setContinuumServerUrl( this.generalBuildAgentConfiguration.getContinuumServerUrl() ); configurationModel.setInstallations( this.generalBuildAgentConfiguration.getInstallations() ); configurationModel.setLocalRepositories( this.generalBuildAgentConfiguration.getLocalRepositories() ); configurationModel.setSharedSecretPassword( this.generalBuildAgentConfiguration.getSharedSecretPassword() ); ContinuumBuildAgentConfigurationModelXpp3Writer writer = new ContinuumBuildAgentConfigurationModelXpp3Writer(); FileWriter fileWriter = new FileWriter( file ); writer.write( fileWriter, configurationModel ); fileWriter.flush(); fileWriter.close(); } catch ( IOException e ) { log.error( e.getMessage(), e ); throw new BuildAgentConfigurationException( e.getMessage(), e ); } } public void setContinuumBuildAgentConfiguration( GeneralBuildAgentConfiguration buildAgentConfiguration ) { this.generalBuildAgentConfiguration = buildAgentConfiguration; } public File getConfigurationFile() { return configurationFile; } public void setConfigurationFile( File configurationFile ) { this.configurationFile = configurationFile; } }
4,954
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/configuration/GeneralBuildAgentConfiguration.java
package org.apache.continuum.buildagent.configuration; /* * 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.model.Installation; import org.apache.continuum.buildagent.model.LocalRepository; import java.io.File; import java.util.List; public class GeneralBuildAgentConfiguration { private File workingDirectory; private File buildOutputDirectory; private String continuumServerUrl; private List<Installation> installations; private List<LocalRepository> localRepositories; private String sharedSecretPassword; public File getWorkingDirectory() { return workingDirectory; } public void setWorkingDirectory( File workingDirectory ) { this.workingDirectory = workingDirectory; } public File getBuildOutputDirectory() { return buildOutputDirectory; } public void setBuildOutputDirectory( File buildOutputDirectory ) { this.buildOutputDirectory = buildOutputDirectory; } public String getContinuumServerUrl() { return continuumServerUrl; } public void setContinuumServerUrl( String continuumServerUrl ) { this.continuumServerUrl = continuumServerUrl; } public List<Installation> getInstallations() { return installations; } public void setInstallations( List<Installation> installations ) { this.installations = installations; } public List<LocalRepository> getLocalRepositories() { return localRepositories; } public void setLocalRepositories( List<LocalRepository> localRepositories ) { this.localRepositories = localRepositories; } public void setSharedSecretPassword( String sharedSecretPassword ) { this.sharedSecretPassword = sharedSecretPassword; } public String getSharedSecretPassword() { return sharedSecretPassword; } }
4,955
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/configuration/DefaultBuildAgentConfigurationService.java
package org.apache.continuum.buildagent.configuration; /* * 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.model.Installation; import org.apache.continuum.buildagent.model.LocalRepository; import org.apache.continuum.utils.file.FileSystemManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Resource; import java.io.File; import java.io.IOException; import java.util.List; public class DefaultBuildAgentConfigurationService implements BuildAgentConfigurationService { private static final Logger log = LoggerFactory.getLogger( DefaultBuildAgentConfigurationService.class ); @Resource private BuildAgentConfiguration buildAgentConfiguration; @Resource FileSystemManager fsManager; private GeneralBuildAgentConfiguration generalBuildAgentConfiguration; public void initialize() throws BuildAgentConfigurationException { loadData(); } public BuildAgentConfiguration getBuildAgentConfiguration() { return buildAgentConfiguration; } public void setBuildAgentConfiguration( BuildAgentConfiguration buildAgentConfiguration ) { this.buildAgentConfiguration = buildAgentConfiguration; } public File getBuildOutputDirectory() { return generalBuildAgentConfiguration.getBuildOutputDirectory(); } public File getBuildOutputDirectory( int projectId ) { File dir = new File( getBuildOutputDirectory(), Integer.toString( projectId ) ); try { dir = dir.getCanonicalFile(); } catch ( IOException e ) { } return dir; } public File getWorkingDirectory() { return generalBuildAgentConfiguration.getWorkingDirectory(); } public File getWorkingDirectory( int projectId ) { File dir = new File( generalBuildAgentConfiguration.getWorkingDirectory(), Integer.toString( projectId ) ); try { dir = dir.getCanonicalFile(); } catch ( IOException e ) { } return dir; } public String getBuildOutput( int projectId ) throws BuildAgentConfigurationException { File file = getBuildOutputFile( projectId ); try { if ( file.exists() ) { return fsManager.fileContents( file ); } else { return "There is no output for this build."; } } catch ( IOException e ) { log.warn( "Error reading build output for project '" + projectId + "'.", e ); return null; } } public File getBuildOutputFile( int projectId ) throws BuildAgentConfigurationException { File dir = getBuildOutputDirectory( projectId ); if ( !dir.exists() && !dir.mkdirs() ) { throw new BuildAgentConfigurationException( "Could not make the build output directory: " + "'" + dir.getAbsolutePath() + "'." ); } return new File( dir, "build.log.txt" ); } public String getContinuumServerUrl() { return generalBuildAgentConfiguration.getContinuumServerUrl(); } public List<Installation> getAvailableInstallations() { return generalBuildAgentConfiguration.getInstallations(); } public List<LocalRepository> getLocalRepositories() { return generalBuildAgentConfiguration.getLocalRepositories(); } public LocalRepository getLocalRepositoryByName( String name ) throws BuildAgentConfigurationException { for ( LocalRepository repo : generalBuildAgentConfiguration.getLocalRepositories() ) { if ( name.equalsIgnoreCase( repo.getName() ) ) { return repo; } } throw new BuildAgentConfigurationException( String.format( "local repository matching '%s' not found", name ) ); } public String getSharedSecretPassword() { return generalBuildAgentConfiguration.getSharedSecretPassword(); } public void store() throws BuildAgentConfigurationException { buildAgentConfiguration.setContinuumBuildAgentConfiguration( generalBuildAgentConfiguration ); buildAgentConfiguration.save(); } private void loadData() throws BuildAgentConfigurationException { generalBuildAgentConfiguration = buildAgentConfiguration.getContinuumBuildAgentConfiguration(); } }
4,956
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/configuration/BuildAgentConfiguration.java
package org.apache.continuum.buildagent.configuration; /* * 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; public interface BuildAgentConfiguration { String ROLE = BuildAgentConfiguration.class.getName(); GeneralBuildAgentConfiguration getContinuumBuildAgentConfiguration() throws BuildAgentConfigurationException; void setContinuumBuildAgentConfiguration( GeneralBuildAgentConfiguration configuration ); void save() throws BuildAgentConfigurationException; void save( File file ) throws BuildAgentConfigurationException; void reload() throws BuildAgentConfigurationException; void reload( File file ) throws BuildAgentConfigurationException; }
4,957
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/buildcontext/BuildContext.java
package org.apache.continuum.buildagent.buildcontext; /* * 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.scm.ScmResult; import java.util.Date; import java.util.Map; public class BuildContext { private int projectId; private String projectName; private String projectVersion; private int projectState; private int buildNumber; private int buildDefinitionId; private String buildDefinitionLabel; private String buildFile; private String goals; private String arguments; private String executorId; private String scmUrl; private String scmUsername; private String scmPassword; private String scmTag; private int trigger; private String username; private boolean buildFresh; private int projectGroupId; private String projectGroupName; private String scmRootAddress; private int scmRootId; private Map<String, Object> actionContext; private ScmResult scmResult; private BuildResult buildResult; private long buildStartTime; private String localRepository; private ScmResult oldScmResult; private Date latestUpdateDate; private String buildAgentUrl; private int maxExecutionTime; public int getProjectGroupId() { return projectGroupId; } public void setProjectGroupId( int projectGroupId ) { this.projectGroupId = projectGroupId; } public String getScmRootAddress() { return scmRootAddress; } public void setScmRootAddress( String scmRootAddress ) { this.scmRootAddress = scmRootAddress; } public int getProjectId() { return projectId; } public void setProjectId( int projectId ) { this.projectId = projectId; } public String getProjectName() { return projectName; } public void setProjectName( String projectName ) { this.projectName = projectName; } public int getProjectState() { return projectState; } public void setProjectState( int projectState ) { this.projectState = projectState; } public int getBuildDefinitionId() { return buildDefinitionId; } public void setBuildDefinitionId( int buildDefinitionId ) { this.buildDefinitionId = buildDefinitionId; } public String getBuildFile() { return buildFile; } public void setBuildFile( String buildFile ) { this.buildFile = buildFile; } public String getGoals() { return goals; } public void setGoals( String goals ) { this.goals = goals; } public String getArguments() { return arguments; } public void setArguments( String arguments ) { this.arguments = arguments; } public String getExecutorId() { return executorId; } public void setExecutorId( String executorId ) { this.executorId = executorId; } public String getScmUrl() { return scmUrl; } public void setScmUrl( String scmUrl ) { this.scmUrl = scmUrl; } public String getScmUsername() { return scmUsername; } public void setScmUsername( String scmUsername ) { this.scmUsername = scmUsername; } public String getScmPassword() { return scmPassword; } public void setScmPassword( String scmPassword ) { this.scmPassword = scmPassword; } public String getScmTag() { return scmTag; } public void setScmTag( String scmTag ) { this.scmTag = scmTag; } public int getTrigger() { return trigger; } public void setTrigger( int trigger ) { this.trigger = trigger; } public boolean isBuildFresh() { return buildFresh; } public void setBuildFresh( boolean buildFresh ) { this.buildFresh = buildFresh; } public Map<String, Object> getActionContext() { return actionContext; } public void setActionContext( Map<String, Object> actionContext ) { this.actionContext = actionContext; } public ScmResult getScmResult() { return scmResult; } public void setScmResult( ScmResult scmResult ) { this.scmResult = scmResult; } public BuildResult getBuildResult() { return buildResult; } public void setBuildResult( BuildResult buildResult ) { this.buildResult = buildResult; } public long getBuildStartTime() { return buildStartTime; } public void setBuildStartTime( long buildStartTime ) { this.buildStartTime = buildStartTime; } public String getLocalRepository() { return localRepository; } public void setLocalRepository( String localRepository ) { this.localRepository = localRepository; } public void setProjectGroupName( String projectGroupName ) { this.projectGroupName = projectGroupName; } public String getProjectGroupName() { return projectGroupName; } public void setProjectVersion( String projectVersion ) { this.projectVersion = projectVersion; } public String getProjectVersion() { return projectVersion; } public void setBuildNumber( int buildNumber ) { this.buildNumber = buildNumber; } public int getBuildNumber() { return buildNumber; } public void setOldScmResult( ScmResult oldScmResult ) { this.oldScmResult = oldScmResult; } public ScmResult getOldScmResult() { return oldScmResult; } public void setLatestUpdateDate( Date latestUpdateDate ) { this.latestUpdateDate = latestUpdateDate; } public Date getLatestUpdateDate() { return latestUpdateDate; } public void setBuildAgentUrl( String buildAgentUrl ) { this.buildAgentUrl = buildAgentUrl; } public String getBuildAgentUrl() { return buildAgentUrl; } public void setMaxExecutionTime( int maxExecutionTime ) { this.maxExecutionTime = maxExecutionTime; } public int getMaxExecutionTime() { return maxExecutionTime; } public void setScmRootId( int scmRootId ) { this.scmRootId = scmRootId; } public int getScmRootId() { return scmRootId; } public void setBuildDefinitionLabel( String buildDefinitionLabel ) { this.buildDefinitionLabel = buildDefinitionLabel; } public String getBuildDefinitionLabel() { return buildDefinitionLabel; } public void setUsername( String username ) { this.username = username; } public String getUsername() { return username; } }
4,958
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/buildcontext
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/buildcontext/manager/BuildContextManager.java
package org.apache.continuum.buildagent.buildcontext.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.buildcontext.BuildContext; import java.util.List; /** * @author Jan Stevens Ancajas */ public interface BuildContextManager { String ROLE = BuildContextManager.class.getName(); public void addBuildContexts( List<BuildContext> buildContextList ); public List<BuildContext> getBuildContexts(); public BuildContext getBuildContext( int projectId ); public void removeBuildContext( int projectId ); }
4,959
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/buildcontext
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/buildcontext/manager/DefaultBuildContextManager.java
package org.apache.continuum.buildagent.buildcontext.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.buildcontext.BuildContext; import org.codehaus.plexus.component.annotations.Component; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author Jan Steven Ancajas */ @Component( role = org.apache.continuum.buildagent.buildcontext.manager.BuildContextManager.class, hint = "default" ) public class DefaultBuildContextManager implements BuildContextManager { public Map<Integer, BuildContext> buildContexts; public BuildContext getBuildContext( int projectId ) { if ( buildContexts != null ) { return buildContexts.get( projectId ); } return null; } public List<BuildContext> getBuildContexts() { List<BuildContext> bContexts = new ArrayList<BuildContext>(); if ( buildContexts != null ) { bContexts.addAll( buildContexts.values() ); } return bContexts; } public void addBuildContexts( List<BuildContext> buildContextList ) { if ( buildContexts == null ) { buildContexts = new HashMap<Integer, BuildContext>(); } for ( BuildContext buildContext : buildContextList ) { buildContexts.put( buildContext.getProjectId(), buildContext ); } } public void removeBuildContext( int projectId ) { BuildContext buildContext = getBuildContext( projectId ); if ( buildContext != null ) { buildContexts.remove( buildContext ); } } }
4,960
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/utils/WorkingCopyContentGenerator.java
package org.apache.continuum.buildagent.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.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.util.StringUtils; import java.io.File; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.List; @Component( role = org.apache.continuum.buildagent.utils.WorkingCopyContentGenerator.class ) public class WorkingCopyContentGenerator { private static final DecimalFormat decFormatter = new DecimalFormat( "###.##" ); private File basedir; private String urlParamSeparator; private static final long KILO = 1024; private static final long MEGA = 1024 * KILO; private static final long GIGA = 1024 * MEGA; private boolean odd = false; public String generate( List<File> files, String baseUrl, String imagesBaseUrl, File basedir ) { this.basedir = basedir; if ( baseUrl.indexOf( "?" ) > 0 ) { urlParamSeparator = "&"; } else { urlParamSeparator = "?"; } StringBuffer buf = new StringBuffer(); buf.append( "<div class=\"eXtremeTable\" >" ); buf.append( "<table class=\"tableRegion\" width=\"100%\">\n" ); buf.append( "<tr class=\"odd\"><td><img src=\"" ).append( imagesBaseUrl ).append( "icon_arrowfolder1_sml.gif\">&nbsp;<a href=\"" ).append( baseUrl ).append( urlParamSeparator ).append( "userDirectory=/\">/</a><br /></td><td>&nbsp;</td><td>&nbsp;</td>" ); print( basedir, files, baseUrl, imagesBaseUrl, buf ); buf.append( "</table>\n" ); buf.append( "</div>\n" ); return buf.toString(); } private void print( File basedir, List<File> files, String baseUrl, String imagesBaseUrl, StringBuffer buf ) { for ( File f : files ) { print( f, getIndent( basedir, f ), baseUrl, imagesBaseUrl, buf ); } } private void print( File f, String indent, String baseUrl, String imagesBaseUrl, StringBuffer buf ) { String cssClass = odd ? "odd" : "even"; if ( !f.isDirectory() ) { String fileName = f.getName(); if ( !".cvsignore".equals( fileName ) && !"vssver.scc".equals( fileName ) && !".DS_Store".equals( fileName ) && !"release.properties".equals( fileName ) ) { String userDirectory; if ( f.getParentFile().getAbsolutePath().equals( basedir.getAbsolutePath() ) ) { userDirectory = "/"; } else { userDirectory = f.getParentFile().getAbsolutePath().substring( basedir.getAbsolutePath().length() + 1 ); } userDirectory = StringUtils.replace( userDirectory, "\\", "/" ); buf.append( "<tr class=\"" ).append( cssClass ).append( "\">" ); buf.append( "<td width=\"98%\">" ).append( indent ).append( "&nbsp;&nbsp;<img src=\"" ).append( imagesBaseUrl ).append( "file.gif\">&nbsp;<a href=\"" ).append( baseUrl ).append( urlParamSeparator ).append( "userDirectory=" ).append( userDirectory ).append( "&file=" ).append( fileName ).append( "\">" ).append( fileName ).append( "</a></td><td width=\"1%\">" ).append( getReadableFileSize( f.length() ) ).append( "</td><td width=\"1%\">" ).append( getFormattedDate( f.lastModified() ) ).append( "</td>\n" ); buf.append( "</tr>\n" ); odd = !odd; } } else { String directoryName = f.getName(); if ( !"CVS".equals( directoryName ) && !".svn".equals( directoryName ) && !"SCCS".equals( directoryName ) ) { String userDirectory = f.getAbsolutePath().substring( basedir.getAbsolutePath().length() + 1 ); userDirectory = StringUtils.replace( userDirectory, "\\", "/" ); buf.append( "<tr class=\"" ).append( cssClass ).append( "\">" ); buf.append( "<td width=\"98%\">" ).append( indent ).append( "<img src=\"" ).append( imagesBaseUrl ).append( "icon_arrowfolder1_sml.gif\">&nbsp;<a href =\"" ).append( baseUrl ).append( urlParamSeparator ).append( "userDirectory=" ).append( userDirectory ).append( "\">" ).append( directoryName ).append( "</a></td><td width=\"1%\">" + "&nbsp;" + "</td><td width=\"1%\">" ).append( getFormattedDate( f.lastModified() ) ).append( "</td>" ); buf.append( "</tr>\n" ); odd = !odd; } } } private String getFormattedDate( long timestamp ) { Calendar cal = Calendar.getInstance(); cal.setTimeInMillis( timestamp ); Date date = cal.getTime(); String res = new SimpleDateFormat( "MMM dd, yyyy hh:mm:ss aaa z" ).format( date ); return StringUtils.replace( res, " ", "&nbsp;" ); } private static String getReadableFileSize( long fileSizeInBytes ) { if ( fileSizeInBytes >= GIGA ) { return decFormatter.format( fileSizeInBytes / GIGA ) + "&nbsp;Gb"; } else if ( fileSizeInBytes >= MEGA ) { return decFormatter.format( fileSizeInBytes / MEGA ) + "&nbsp;Mb"; } else if ( fileSizeInBytes >= KILO ) { return decFormatter.format( fileSizeInBytes / KILO ) + "&nbsp;Kb"; } else if ( fileSizeInBytes > 0 && fileSizeInBytes < KILO ) { return decFormatter.format( fileSizeInBytes ) + "&nbsp;b"; } return "0&nbsp;b"; } private String getIndent( File basedir, File userFile ) { String root = basedir.getAbsolutePath(); String userdir; if ( userFile.isDirectory() ) { userdir = userFile.getAbsolutePath(); } else { userdir = userFile.getParentFile().getAbsolutePath(); } userdir = userdir.substring( root.length() ); StringBuffer indent = new StringBuffer(); while ( userdir.indexOf( File.separator ) >= 0 ) { indent.append( "&nbsp;&nbsp;" ); userdir = userdir.substring( userdir.indexOf( File.separator ) + 1 ); } return indent.toString(); } }
4,961
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/utils/BuildContextToBuildDefinition.java
package org.apache.continuum.buildagent.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.buildagent.buildcontext.BuildContext; import org.apache.maven.continuum.model.project.BuildDefinition; /** * @author Maria Catherine Tan */ public class BuildContextToBuildDefinition { public static BuildDefinition getBuildDefinition( BuildContext buildContext ) { BuildDefinition buildDefinition = new BuildDefinition(); buildDefinition.setId( buildContext.getBuildDefinitionId() ); buildDefinition.setAlwaysBuild( true ); buildDefinition.setArguments( buildContext.getArguments() ); buildDefinition.setBuildFile( buildContext.getBuildFile() ); buildDefinition.setBuildFresh( buildContext.isBuildFresh() ); buildDefinition.setGoals( buildContext.getGoals() ); return buildDefinition; } }
4,962
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/utils/ContinuumBuildAgentUtil.java
package org.apache.continuum.buildagent.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.buildagent.buildcontext.BuildContext; import org.apache.continuum.utils.build.BuildTrigger; import org.apache.maven.continuum.ContinuumException; 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.codehaus.plexus.util.StringUtils; import java.io.File; import java.io.PrintWriter; import java.io.StringWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; public class ContinuumBuildAgentUtil { public static final String EOL = System.getProperty( "line.separator" ); public static final String KEY_PROJECT_ID = "project-id"; public static final String KEY_PROJECT_VERSION = "project-version"; public static final String KEY_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_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_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_STATE = "scm-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_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_ROOT_STATE = "scm-root-state"; public static final String KEY_CHECKOUT_SCM_RESULT = "checkout-scm-result"; public static final String KEY_UPDATE_SCM_RESULT = "update-scm-result"; public static final String KEY_WORKING_DIRECTORY_EXISTS = "working-directory-exists"; public static final String KEY_PROJECT = "project"; public static final String KEY_BUILD_DEFINITION = "build-definition"; public static final String KEY_SCM_RESULT = "scm-result"; public static final String KEY_WORKING_DIRECTORY = "working-directory"; public static final String KEY_SCM_SUCCESS = "scm-success"; public static final String KEY_SCM_ERROR = "scm-error"; public static final String KEY_BUILD_RESULT = "build-result"; public static final String KEY_PROJECT_NAME = "project-name"; public static final String KEY_BUILD_OUTPUT = "build-output"; 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_ENVIRONMENTS = "environments"; public static final String KEY_LOCAL_REPOSITORY = "local-repository"; public static final String KEY_SCM_CHANGES = "scm-changes"; 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_RESULT = "old-scm-result"; 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_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_PROJECT_MODULES = "project-modules"; public static final String KEY_MAVEN_PROJECT = "maven-project"; 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_SCM_TAGBASE = "scm-tagbase"; 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_USE_RELEASE_PROFILE = "use-release-profile"; public static final String KEY_RELEASE_VERSION = "release-version"; public static final String KEY_DEVELOPMENT_VERSION = "development-version"; public static final String KEY_USE_EDIT_MODE = "use-edit-mode"; 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_BUILD_CONTEXTS = "build-contexts"; public static final String KEY_MAX_JOB_EXEC_TIME = "max-job-exec-time"; public static final String KEY_RELEASE_STATE = "state"; public static final String KEY_RELEASE_PHASES = "release-phases"; public static final String KEY_RELEASE_IN_PROGRESS = "release-in-progress"; public static final String KEY_COMPLETED_RELEASE_PHASES = "completed-release-phases"; public static final String KEY_RELEASE_ERROR = "release-error"; public static final String KEY_LOCAL_REPOSITORY_NAME = "repo-name"; public static final String KEY_LOCAL_REPOSITORY_LAYOUT = "repo-layout"; public static Integer getProjectId( Map<String, Object> context ) { return getInteger( context, KEY_PROJECT_ID ); } public static String getProjectName( Map<String, Object> context ) { return getString( context, KEY_PROJECT_NAME ); } public static Integer getProjectState( Map<String, Object> context ) { return getInteger( context, KEY_PROJECT_STATE ); } public static Integer getBuildDefinitionId( Map<String, Object> context ) { return getInteger( context, KEY_BUILD_DEFINITION_ID ); } public static String getBuildFile( Map<String, Object> context ) { return getString( context, KEY_BUILD_FILE ); } public static String getExecutorId( Map<String, Object> context ) { return getString( context, KEY_EXECUTOR_ID ); } public static String getGoals( Map<String, Object> context ) { return getString( context, KEY_GOALS ); } public static String getArguments( Map<String, Object> context ) { return getString( context, KEY_ARGUMENTS ); } public static String getScmUrl( Map<String, Object> context ) { return getString( context, KEY_SCM_URL ); } public static String getScmUsername( Map<String, Object> context ) { return getString( context, KEY_SCM_USERNAME, "" ); } public static String getScmPassword( Map<String, Object> context ) { return getString( context, KEY_SCM_PASSWORD, "" ); } public static boolean isBuildFresh( Map<String, Object> context ) { return getBoolean( context, KEY_BUILD_FRESH ); } 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 int getScmRootState( Map<String, Object> context ) { return getInteger( context, KEY_SCM_ROOT_STATE ); } public static Project getProject( Map<String, Object> context ) { return (Project) getObject( context, KEY_PROJECT ); } public static BuildDefinition getBuildDefinition( Map<String, Object> context ) { return (BuildDefinition) getObject( context, KEY_BUILD_DEFINITION ); } public static ScmResult getCheckoutScmResult( Map<String, Object> context, Object defaultValue ) { return (ScmResult) getObject( context, KEY_CHECKOUT_SCM_RESULT, defaultValue ); } public static ScmResult getUpdateScmResult( Map<String, Object> context, Object defaultValue ) { return (ScmResult) getObject( context, KEY_UPDATE_SCM_RESULT, defaultValue ); } public static ScmResult getScmResult( Map<String, Object> context, Object defaultValue ) { return (ScmResult) getObject( context, KEY_SCM_RESULT, defaultValue ); } 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, "scheduled" ); } public static BuildTrigger getBuildTrigger( Map<String, Object> context ) { return new BuildTrigger( getTrigger( context ), getUsername( context ) ); } public static BuildResult getBuildResult( Map<String, Object> context, Object defaultValue ) { return (BuildResult) getObject( context, KEY_BUILD_RESULT, defaultValue ); } public static Map<String, String> getEnvironments( Map<String, Object> context ) { return (Map<String, String>) getObject( context, KEY_ENVIRONMENTS ); } public static String getLocalRepository( Map<String, Object> context ) { return getString( context, KEY_LOCAL_REPOSITORY, "" ); } public static String getProjectVersion( Map<String, Object> context ) { return getString( context, KEY_PROJECT_VERSION ); } public static String getProjectGroupName( Map<String, Object> context ) { return getString( context, KEY_PROJECT_GROUP_NAME ); } public static int getBuildNumber( Map<String, Object> context ) { return getInteger( context, KEY_BUILD_NUMBER ); } public static List<Map<String, Object>> getOldScmChanges( Map<String, Object> context ) { return getList( context, KEY_OLD_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 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 ScmResult getOldScmResult( Map<String, Object> context, ScmResult defaultValue ) { return (ScmResult) getObject( context, KEY_OLD_SCM_RESULT, defaultValue ); } public static List getScmChanges( Map<String, Object> context ) { return getList( context, KEY_SCM_CHANGES ); } 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 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 Map getReleaseVersion( Map<String, Object> context ) { return getMap( context, KEY_RELEASE_VERSION ); } public static Map getDevelopmentVersion( Map<String, Object> context ) { return getMap( context, KEY_DEVELOPMENT_VERSION ); } public static String getScmTagBase( Map<String, Object> context ) { return getString( context, KEY_SCM_TAGBASE, "" ); } public static String getScmCommentPrefix( Map<String, Object> context ) { return getString( context, KEY_SCM_COMMENT_PREFIX, "" ); } public static String getScmTag( Map<String, Object> context ) { return getString( context, KEY_SCM_TAG, "" ); } public static String getPrepareGoals( Map<String, Object> context ) { return getString( context, KEY_PREPARE_GOALS, "" ); } public static String getPerformGoals( Map<String, Object> context ) { return getString( context, KEY_PERFORM_GOALS, "" ); } public static String getUseEditMode( Map<String, Object> context ) { return getString( context, KEY_USE_EDIT_MODE, "" ); } public static String getAddSchema( Map<String, Object> context ) { return getString( context, KEY_ADD_SCHEMA, "" ); } public static String getAutoVersionSubmodules( Map<String, Object> context ) { return getString( context, KEY_AUTO_VERSION_SUBMODULES, "" ); } public static List getBuildContexts( Map<String, Object> context ) { return getList( context, KEY_BUILD_CONTEXTS ); } public static int getMaxExecutionTime( Map<String, Object> context ) { return getInteger( context, KEY_MAX_JOB_EXEC_TIME ); } public static String getLocalRepositoryName( Map<String, Object> context ) { return getString( context, KEY_LOCAL_REPOSITORY_NAME, "" ); } public static String getLocalRepositoryLayout( Map<String, Object> context ) { return getString( context, KEY_LOCAL_REPOSITORY_LAYOUT, "" ); } 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, "" ); } // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- 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 int getInteger( Map<String, Object> context, String key ) { Object obj = getObject( context, key, null ); if ( obj == null ) { return 0; } else { return (Integer) obj; } } public 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>(); if ( obj instanceof Object[] ) { Object[] objA = (Object[]) obj; list.addAll( Arrays.asList( objA ) ); } else { list = (List<Object>) obj; } return list; } } public 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 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; } public static String throwableToString( Throwable error ) { if ( error == null ) { return ""; } StringWriter writer = new StringWriter(); PrintWriter printer = new PrintWriter( writer ); error.printStackTrace( printer ); printer.flush(); return writer.getBuffer().toString(); } public static String throwableMessagesToString( Throwable error ) { if ( error == null ) { return ""; } StringBuffer buffer = new StringBuffer(); buffer.append( error.getMessage() ); error = error.getCause(); while ( error != null ) { buffer.append( EOL ); buffer.append( error.getMessage() ); error = error.getCause(); } return buffer.toString(); } public static Map<String, Object> createScmResult( BuildContext buildContext ) { Map<String, Object> result = new HashMap<String, Object>(); ScmResult scmResult = buildContext.getScmResult(); result.put( ContinuumBuildAgentUtil.KEY_PROJECT_ID, buildContext.getProjectId() ); if ( StringUtils.isEmpty( scmResult.getCommandLine() ) ) { result.put( ContinuumBuildAgentUtil.KEY_SCM_COMMAND_LINE, "" ); } else { result.put( ContinuumBuildAgentUtil.KEY_SCM_COMMAND_LINE, scmResult.getCommandLine() ); } if ( StringUtils.isEmpty( scmResult.getCommandOutput() ) ) { result.put( ContinuumBuildAgentUtil.KEY_SCM_COMMAND_OUTPUT, "" ); } else { result.put( ContinuumBuildAgentUtil.KEY_SCM_COMMAND_OUTPUT, scmResult.getCommandOutput() ); } if ( StringUtils.isEmpty( scmResult.getProviderMessage() ) ) { result.put( ContinuumBuildAgentUtil.KEY_SCM_PROVIDER_MESSAGE, "" ); } else { result.put( ContinuumBuildAgentUtil.KEY_SCM_PROVIDER_MESSAGE, scmResult.getProviderMessage() ); } if ( StringUtils.isEmpty( scmResult.getException() ) ) { result.put( ContinuumBuildAgentUtil.KEY_SCM_EXCEPTION, "" ); } else { result.put( ContinuumBuildAgentUtil.KEY_SCM_EXCEPTION, scmResult.getException() ); } result.put( ContinuumBuildAgentUtil.KEY_SCM_SUCCESS, scmResult.isSuccess() ); result.put( ContinuumBuildAgentUtil.KEY_SCM_CHANGES, getScmChanges( scmResult ) ); return result; } private static List<Map<String, Object>> getScmChanges( ScmResult scmResult ) { List<Map<String, Object>> scmChanges = new ArrayList<Map<String, Object>>(); List<ChangeSet> changes = scmResult.getChanges(); if ( changes != null ) { for ( ChangeSet cs : changes ) { Map<String, Object> changeSet = new HashMap<String, Object>(); if ( StringUtils.isNotEmpty( cs.getAuthor() ) ) { changeSet.put( ContinuumBuildAgentUtil.KEY_CHANGESET_AUTHOR, cs.getAuthor() ); } else { changeSet.put( ContinuumBuildAgentUtil.KEY_CHANGESET_AUTHOR, "" ); } if ( StringUtils.isNotEmpty( cs.getComment() ) ) { changeSet.put( ContinuumBuildAgentUtil.KEY_CHANGESET_COMMENT, cs.getComment() ); } else { changeSet.put( ContinuumBuildAgentUtil.KEY_CHANGESET_COMMENT, "" ); } if ( cs.getDateAsDate() != null ) { changeSet.put( ContinuumBuildAgentUtil.KEY_CHANGESET_DATE, cs.getDateAsDate() ); } changeSet.put( ContinuumBuildAgentUtil.KEY_CHANGESET_FILES, getChangeFiles( cs.getFiles() ) ); scmChanges.add( changeSet ); } } return scmChanges; } private static List<Map<String, String>> getChangeFiles( List<ChangeFile> changeFiles ) { List<Map<String, String>> files = new ArrayList<Map<String, String>>(); if ( changeFiles != null ) { for ( ChangeFile file : changeFiles ) { Map<String, String> changeFile = new HashMap<String, String>(); if ( StringUtils.isNotEmpty( file.getName() ) ) { changeFile.put( ContinuumBuildAgentUtil.KEY_CHANGEFILE_NAME, file.getName() ); } else { changeFile.put( ContinuumBuildAgentUtil.KEY_CHANGEFILE_NAME, "" ); } if ( StringUtils.isNotEmpty( file.getRevision() ) ) { changeFile.put( ContinuumBuildAgentUtil.KEY_CHANGEFILE_REVISION, file.getRevision() ); } else { changeFile.put( ContinuumBuildAgentUtil.KEY_CHANGEFILE_REVISION, "" ); } if ( StringUtils.isNotEmpty( file.getStatus() ) ) { changeFile.put( ContinuumBuildAgentUtil.KEY_CHANGEFILE_STATUS, file.getStatus() ); } else { changeFile.put( ContinuumBuildAgentUtil.KEY_CHANGEFILE_STATUS, "" ); } files.add( changeFile ); } } return files; } public static List<File> getFiles( String userDirectory, File workingDirectory ) throws ContinuumException { return getFiles( workingDirectory, null, userDirectory ); } private static List<File> getFiles( File baseDirectory, String currentSubDirectory, String userDirectory ) { List<File> dirs = new ArrayList<File>(); File workingDirectory; if ( currentSubDirectory != null ) { workingDirectory = new File( baseDirectory, currentSubDirectory ); } else { workingDirectory = baseDirectory; } String[] files = workingDirectory.list(); if ( files != null ) { for ( String file : files ) { File current = new File( workingDirectory, file ); String currentFile; if ( currentSubDirectory == null ) { currentFile = file; } else { currentFile = currentSubDirectory + "/" + file; } if ( userDirectory != null && current.isDirectory() && userDirectory.startsWith( currentFile ) ) { dirs.add( current ); dirs.addAll( getFiles( baseDirectory, currentFile, userDirectory ) ); } else { dirs.add( current ); } } } return dirs; } }
4,963
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/utils/BuildContextToProject.java
package org.apache.continuum.buildagent.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.buildagent.buildcontext.BuildContext; import org.apache.maven.continuum.model.project.Project; /** * @author Jan Stevens Ancajas */ public class BuildContextToProject { public static Project getProject( BuildContext buildContext ) { Project project = new Project(); project.setId( buildContext.getProjectId() ); project.setName( buildContext.getProjectName() ); project.setVersion( buildContext.getProjectVersion() ); project.setScmUrl( buildContext.getScmUrl() ); project.setScmUsername( buildContext.getScmUsername() ); project.setScmPassword( buildContext.getScmPassword() ); project.setScmTag( buildContext.getScmTag() ); project.setExecutorId( buildContext.getExecutorId() ); project.setState( buildContext.getProjectState() ); project.setOldState( buildContext.getProjectState() ); project.setBuildNumber( buildContext.getBuildNumber() ); return project; } }
4,964
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/installation/DefaultBuildAgentInstallationService.java
package org.apache.continuum.buildagent.installation; /* * 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.ExecutorConfigurator; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.personality.plexus.lifecycle.phase.Initializable; import org.codehaus.plexus.personality.plexus.lifecycle.phase.InitializationException; import java.util.HashMap; import java.util.Map; @Component( role = org.apache.continuum.buildagent.installation.BuildAgentInstallationService.class, hint = "default" ) public class DefaultBuildAgentInstallationService implements BuildAgentInstallationService, Initializable { private Map<String, ExecutorConfigurator> typesValues; public ExecutorConfigurator getExecutorConfigurator( String type ) { return this.typesValues.get( type ); } public void initialize() throws InitializationException { this.typesValues = new HashMap<String, ExecutorConfigurator>(); this.typesValues.put( BuildAgentInstallationService.ANT_TYPE, new ExecutorConfigurator( "ant", "bin", "ANT_HOME", "-version" ) ); this.typesValues.put( BuildAgentInstallationService.ENVVAR_TYPE, null ); this.typesValues.put( BuildAgentInstallationService.JDK_TYPE, new ExecutorConfigurator( "java", "bin", "JAVA_HOME", "-version" ) ); this.typesValues.put( BuildAgentInstallationService.MAVEN1_TYPE, new ExecutorConfigurator( "maven", "bin", "MAVEN_HOME", "-v" ) ); this.typesValues.put( BuildAgentInstallationService.MAVEN2_TYPE, new ExecutorConfigurator( "mvn", "bin", "M2_HOME", "-v" ) ); } public String getEnvVar( String type ) { ExecutorConfigurator executorConfigurator = this.typesValues.get( type ); return executorConfigurator == null ? null : executorConfigurator.getEnvVar(); } }
4,965
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/installation/BuildAgentInstallationService.java
package org.apache.continuum.buildagent.installation; /* * 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.ExecutorConfigurator; public interface BuildAgentInstallationService { String ROLE = BuildAgentInstallationService.class.getName(); String JDK_TYPE = "jdk"; String MAVEN2_TYPE = "maven2"; String MAVEN1_TYPE = "maven1"; String ANT_TYPE = "ant"; String ENVVAR_TYPE = "envvar"; /** * @param type * @return ExecutorConfigurator or null if unknown type */ public ExecutorConfigurator getExecutorConfigurator( String type ); public String getEnvVar( String type ); }
4,966
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/manager/BuildAgentReleaseManager.java
package org.apache.continuum.buildagent.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.release.ContinuumReleaseException; import org.apache.maven.continuum.release.ContinuumReleaseManager; import org.apache.maven.shared.release.ReleaseResult; import java.util.Map; import java.util.Properties; public interface BuildAgentReleaseManager { String ROLE = BuildAgentReleaseManager.class.getName(); String releasePrepare( Map<String, Object> project, Properties properties, Map<String, String> releaseVersion, Map<String, String> developmentVersion, Map<String, String> environments, String username ) throws ContinuumReleaseException; ReleaseResult getReleaseResult( String releaseId ); Map<String, Object> getListener( String releaseId ); void removeListener( String releaseId ); String getPreparedReleaseName( String releaseId ); void releasePerform( String releaseId, String goals, String arguments, boolean useReleaseProfile, Map repository, String username ) throws ContinuumReleaseException; String releasePerformFromScm( String goals, String arguments, boolean useReleaseProfile, Map repository, String scmUrl, String scmUsername, String scmPassword, String scmTag, String scmTagBase, Map<String, String> environments, String username ) throws ContinuumReleaseException; String releaseCleanup( String releaseId ); void releaseRollback( String releaseId, int projectId ) throws ContinuumReleaseException; ContinuumReleaseManager getReleaseManager(); }
4,967
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/manager/DefaultBuildAgentPurgeManager.java
package org.apache.continuum.buildagent.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.configuration.BuildAgentConfigurationException; import org.apache.continuum.buildagent.configuration.BuildAgentConfigurationService; import org.apache.continuum.buildagent.model.LocalRepository; import org.apache.continuum.purge.executor.ContinuumPurgeExecutor; import org.apache.continuum.purge.executor.ContinuumPurgeExecutorException; import org.apache.continuum.purge.executor.dir.DirectoryPurgeExecutorFactory; import org.apache.continuum.purge.executor.repo.RepositoryPurgeExecutorFactory; import org.apache.continuum.purge.repository.content.RepositoryManagedContent; import org.apache.continuum.purge.repository.content.RepositoryManagedContentFactory; import org.apache.continuum.utils.m2.LocalRepositoryHelper; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.component.repository.exception.ComponentLookupException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; @Component( role = org.apache.continuum.buildagent.manager.BuildAgentPurgeManager.class, hint = "default" ) public class DefaultBuildAgentPurgeManager implements BuildAgentPurgeManager { private static final Logger log = LoggerFactory.getLogger( DefaultBuildAgentPurgeManager.class ); @Requirement private BuildAgentConfigurationService buildAgentConfigurationService; @Requirement private DirectoryPurgeExecutorFactory dirExecutorFactory; @Requirement private RepositoryPurgeExecutorFactory repoExecutorFactory; @Requirement private RepositoryManagedContentFactory contentFactory; @Requirement private LocalRepositoryHelper localRepositoryHelper; public void executeDirectoryPurge( String directoryType, int daysOlder, int retentionCount, boolean deleteAll ) throws ContinuumPurgeExecutorException { File directory = buildAgentConfigurationService.getWorkingDirectory(); String path = directory.getAbsolutePath(); ContinuumPurgeExecutor executor = dirExecutorFactory.create( deleteAll, daysOlder, retentionCount, directoryType ); log.info( "purging directory '{}' [type={},full={},age={},retain={}]", new Object[] { path, directoryType, deleteAll, daysOlder, retentionCount } ); executor.purge( path ); log.info( "purge completed '{}'", path ); } public void executeRepositoryPurge( String repoName, int daysOlder, int retentionCount, boolean deleteAll, boolean deleteReleasedSnapshots ) throws ContinuumPurgeExecutorException { try { LocalRepository localRepo = buildAgentConfigurationService.getLocalRepositoryByName( repoName ); String path = localRepo.getLocation(), layout = localRepo.getLayout(); RepositoryManagedContent managedContent = getManagedContent( localRepo ); ContinuumPurgeExecutor executor = repoExecutorFactory.create( deleteAll, daysOlder, retentionCount, deleteReleasedSnapshots, managedContent ); log.info( "purging repo '{}' [full={},age={},retain={},snapshots={},layout={}]", new Object[] { path, deleteAll, daysOlder, retentionCount, deleteReleasedSnapshots, layout } ); executor.purge( path ); log.info( "purge completed '{}'", path ); } catch ( BuildAgentConfigurationException e ) { log.warn( "ignoring repository purge, check agent repo configuration: {}", e.getMessage() ); } } private RepositoryManagedContent getManagedContent( LocalRepository localRepo ) throws BuildAgentConfigurationException { String layout = localRepo.getLayout(); try { RepositoryManagedContent managedContent = contentFactory.create( layout ); managedContent.setRepository( localRepositoryHelper.convertAgentRepo( localRepo ) ); return managedContent; } catch ( ComponentLookupException e ) { throw new BuildAgentConfigurationException( String.format( "managed repo layout %s not found", layout ) ); } } public void setBuildAgentConfigurationService( BuildAgentConfigurationService buildAgentConfigurationService ) { this.buildAgentConfigurationService = buildAgentConfigurationService; } }
4,968
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/manager/DefaultBuildAgentManager.java
package org.apache.continuum.buildagent.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.buildcontext.BuildContext; import org.apache.continuum.buildagent.buildcontext.manager.BuildContextManager; import org.apache.continuum.buildagent.configuration.BuildAgentConfigurationService; import org.apache.continuum.buildagent.utils.ContinuumBuildAgentUtil; import org.apache.continuum.distributed.transport.master.MasterBuildAgentTransportClient; import org.apache.maven.continuum.ContinuumException; 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.net.MalformedURLException; import java.net.URL; import java.util.Map; @Component( role = org.apache.continuum.buildagent.manager.BuildAgentManager.class, hint = "default" ) public class DefaultBuildAgentManager implements BuildAgentManager { private static final Logger log = LoggerFactory.getLogger( DefaultBuildAgentManager.class ); @Requirement private BuildAgentConfigurationService buildAgentConfigurationService; @Requirement private BuildContextManager buildContextManager; public void startProjectBuild( int projectId, int buildDefinition ) throws ContinuumException { try { MasterBuildAgentTransportClient client = new MasterBuildAgentTransportClient( new URL( buildAgentConfigurationService.getContinuumServerUrl() ) ); client.startProjectBuild( projectId, buildDefinition, getBuildAgentUrl( projectId ) ); } catch ( MalformedURLException e ) { log.error( "Invalid continuum server URL '" + buildAgentConfigurationService.getContinuumServerUrl() + "'" ); throw new ContinuumException( "Invalid continuum server URL '" + buildAgentConfigurationService.getContinuumServerUrl() + "'" ); } catch ( Exception e ) { log.error( "Error starting project build", e ); throw new ContinuumException( "Error starting project build", e ); } } public void returnBuildResult( Map buildResult ) throws ContinuumException { try { MasterBuildAgentTransportClient client = new MasterBuildAgentTransportClient( new URL( buildAgentConfigurationService.getContinuumServerUrl() ) ); client.returnBuildResult( buildResult, ContinuumBuildAgentUtil.getBuildAgentUrl( buildResult ) ); } catch ( MalformedURLException e ) { log.error( "Invalid continuum server URL '" + buildAgentConfigurationService.getContinuumServerUrl() + "'" ); throw new ContinuumException( "Invalid continuum server URL '" + buildAgentConfigurationService.getContinuumServerUrl() + "'" ); } catch ( Exception e ) { log.error( "Error while returning build result to the continuum server", e ); throw new ContinuumException( e.getMessage(), e ); } } public Map<String, String> getEnvironments( int buildDefinitionId, String installationType ) throws ContinuumException { try { MasterBuildAgentTransportClient client = new MasterBuildAgentTransportClient( new URL( buildAgentConfigurationService.getContinuumServerUrl() ) ); return client.getEnvironments( buildDefinitionId, installationType ); } catch ( MalformedURLException e ) { log.error( "Invalid continuum server URL '" + buildAgentConfigurationService.getContinuumServerUrl() + "'" ); throw new ContinuumException( "Invalid continuum server URL '" + buildAgentConfigurationService.getContinuumServerUrl() + "'" ); } catch ( Exception e ) { log.error( "Error while retrieving environments for build definition " + buildDefinitionId, e ); throw new ContinuumException( e.getMessage(), e ); } } public void updateProject( Map project ) throws ContinuumException { try { MasterBuildAgentTransportClient client = new MasterBuildAgentTransportClient( new URL( buildAgentConfigurationService.getContinuumServerUrl() ) ); client.updateProject( project ); } catch ( MalformedURLException e ) { log.error( "Invalid continuum server URL '" + buildAgentConfigurationService.getContinuumServerUrl() + "'" ); throw new ContinuumException( "Invalid continuum server URL '" + buildAgentConfigurationService.getContinuumServerUrl() + "'" ); } catch ( Exception e ) { log.error( "Error while updating project", e ); throw new ContinuumException( e.getMessage(), e ); } } public boolean shouldBuild( Map<String, Object> context ) throws ContinuumException { try { MasterBuildAgentTransportClient client = new MasterBuildAgentTransportClient( new URL( buildAgentConfigurationService.getContinuumServerUrl() ) ); return client.shouldBuild( context, ContinuumBuildAgentUtil.getBuildAgentUrl( context ) ); } catch ( MalformedURLException e ) { log.error( "Invalid continuum server URL '" + buildAgentConfigurationService.getContinuumServerUrl() + "'" ); throw new ContinuumException( "Invalid continuum server URL '" + buildAgentConfigurationService.getContinuumServerUrl() + "'" ); } catch ( Exception e ) { log.error( "Failed to determine if project should build", e ); throw new ContinuumException( "Failed to determine if project should build", e ); } } public void startPrepareBuild( Map<String, Object> context ) throws ContinuumException { try { MasterBuildAgentTransportClient client = new MasterBuildAgentTransportClient( new URL( buildAgentConfigurationService.getContinuumServerUrl() ) ); client.startPrepareBuild( context, ContinuumBuildAgentUtil.getBuildAgentUrl( context ) ); } catch ( MalformedURLException e ) { log.error( "Invalid continuum server URL '" + buildAgentConfigurationService.getContinuumServerUrl() + "'" ); throw new ContinuumException( "Invalid continuum server URL '" + buildAgentConfigurationService.getContinuumServerUrl() + "'", e ); } catch ( Exception e ) { log.error( "Error starting prepare build", e ); throw new ContinuumException( "Error starting prepare build", e ); } } public void endPrepareBuild( Map<String, Object> context ) throws ContinuumException { try { MasterBuildAgentTransportClient client = new MasterBuildAgentTransportClient( new URL( buildAgentConfigurationService.getContinuumServerUrl() ) ); client.prepareBuildFinished( context, ContinuumBuildAgentUtil.getBuildAgentUrl( context ) ); } catch ( MalformedURLException e ) { throw new ContinuumException( "Invalid Continuum Server URL '" + buildAgentConfigurationService.getContinuumServerUrl() + "'" ); } catch ( Exception e ) { throw new ContinuumException( "Error while finishing prepare build", e ); } } public boolean pingMaster() throws ContinuumException { String continuumServerUrl = buildAgentConfigurationService.getContinuumServerUrl(); try { if ( StringUtils.isBlank( continuumServerUrl ) ) { throw new ContinuumException( "Build agent is not configured properly. Missing continuumServerUrl in the configuration file" ); } MasterBuildAgentTransportClient client = new MasterBuildAgentTransportClient( new URL( continuumServerUrl ) ); return client.ping(); } catch ( MalformedURLException e ) { log.error( "Invalid continuum server URL '" + continuumServerUrl + "'", e ); throw new ContinuumException( "Invalid continuum server URL '" + continuumServerUrl + "'", e ); } catch ( Exception e ) { log.error( "Unable to ping master " + continuumServerUrl, e ); throw new ContinuumException( "Unable to ping master " + continuumServerUrl + " from build agent", e ); } } private String getBuildAgentUrl( int projectId ) { BuildContext context = buildContextManager.getBuildContext( projectId ); if ( context != null ) { return context.getBuildAgentUrl(); } return ""; } }
4,969
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/manager/BuildAgentManager.java
package org.apache.continuum.buildagent.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 java.util.Map; public interface BuildAgentManager { String ROLE = BuildAgentManager.class.getName(); void returnBuildResult( Map<String, Object> result ) throws ContinuumException; void startProjectBuild( int projectId, int buildDefinition ) throws ContinuumException; Map<String, String> getEnvironments( int buildDefinitionId, String installationType ) throws ContinuumException; void updateProject( Map<String, Object> project ) throws ContinuumException; boolean shouldBuild( Map<String, Object> context ) throws ContinuumException; void startPrepareBuild( Map<String, Object> context ) throws ContinuumException; void endPrepareBuild( Map<String, Object> context ) throws ContinuumException; boolean pingMaster() throws ContinuumException; }
4,970
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/manager/DefaultBuildAgentReleaseManager.java
package org.apache.continuum.buildagent.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.configuration.BuildAgentConfigurationException; import org.apache.continuum.buildagent.configuration.BuildAgentConfigurationService; import org.apache.continuum.buildagent.installation.BuildAgentInstallationService; import org.apache.continuum.buildagent.model.Installation; import org.apache.continuum.buildagent.utils.ContinuumBuildAgentUtil; import org.apache.continuum.model.repository.LocalRepository; import org.apache.continuum.release.config.ContinuumReleaseDescriptor; import org.apache.continuum.utils.m2.LocalRepositoryHelper; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.model.project.ProjectGroup; import org.apache.maven.continuum.release.ContinuumReleaseException; import org.apache.maven.continuum.release.ContinuumReleaseManager; import org.apache.maven.continuum.release.ContinuumReleaseManagerListener; import org.apache.maven.continuum.release.DefaultReleaseManagerListener; import org.apache.maven.shared.release.ReleaseResult; import org.apache.maven.shared.release.config.ReleaseDescriptor; 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.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; @Component( role = org.apache.continuum.buildagent.manager.BuildAgentReleaseManager.class, hint = "default" ) public class DefaultBuildAgentReleaseManager implements BuildAgentReleaseManager { private static final Logger log = LoggerFactory.getLogger( DefaultBuildAgentReleaseManager.class ); @Requirement ContinuumReleaseManager releaseManager; @Requirement BuildAgentConfigurationService buildAgentConfigurationService; @Requirement BuildAgentInstallationService buildAgentInstallationService; @Requirement LocalRepositoryHelper localRepositoryHelper; public String releasePrepare( Map<String, Object> projectMap, Properties releaseProperties, Map<String, String> releaseVersion, Map<String, String> developmentVersion, Map<String, String> environments, String username ) throws ContinuumReleaseException { Project project = getProject( projectMap ); ContinuumReleaseManagerListener listener = new DefaultReleaseManagerListener(); listener.setUsername( username ); String workingDirectory = buildAgentConfigurationService.getWorkingDirectory( project.getId() ).getPath(); String executable = buildAgentInstallationService.getExecutorConfigurator( BuildAgentInstallationService.MAVEN2_TYPE ).getExecutable(); if ( environments == null ) { environments = new HashMap<String, String>(); } // get environments from Slave (Build Agent) List<Installation> installations = buildAgentConfigurationService.getAvailableInstallations(); if ( installations != null ) { for ( Installation installation : installations ) { // combine environments (Master and Slave); Slave's environments overwrite Master's environments environments.put( installation.getVarName(), installation.getVarValue() ); } } if ( environments != null ) { String m2Home = environments.get( buildAgentInstallationService.getEnvVar( BuildAgentInstallationService.MAVEN2_TYPE ) ); if ( StringUtils.isNotEmpty( m2Home ) ) { executable = m2Home + File.separator + "bin" + File.separator + executable; } } try { return releaseManager.prepare( project, releaseProperties, releaseVersion, developmentVersion, listener, workingDirectory, environments, executable ); } catch ( ContinuumReleaseException e ) { log.error( "Error while preparing release", e ); throw e; } } public ReleaseResult getReleaseResult( String releaseId ) { return (ReleaseResult) releaseManager.getReleaseResults().get( releaseId ); } public Map<String, Object> getListener( String releaseId ) { ContinuumReleaseManagerListener listener = (ContinuumReleaseManagerListener) releaseManager.getListeners().get( releaseId ); Map<String, Object> map = new HashMap<String, Object>(); if ( listener != null ) { map.put( ContinuumBuildAgentUtil.KEY_RELEASE_STATE, listener.getState() ); map.put( ContinuumBuildAgentUtil.KEY_USERNAME, listener.getUsername() ); if ( listener.getPhases() != null ) { map.put( ContinuumBuildAgentUtil.KEY_RELEASE_PHASES, listener.getPhases() ); } if ( listener.getCompletedPhases() != null ) { map.put( ContinuumBuildAgentUtil.KEY_COMPLETED_RELEASE_PHASES, listener.getCompletedPhases() ); } if ( listener.getInProgress() != null ) { map.put( ContinuumBuildAgentUtil.KEY_RELEASE_IN_PROGRESS, listener.getInProgress() ); } if ( listener.getError() != null ) { map.put( ContinuumBuildAgentUtil.KEY_RELEASE_ERROR, listener.getError() ); } } return map; } public void removeListener( String releaseId ) { releaseManager.getListeners().remove( releaseId ); } public String getPreparedReleaseName( String releaseId ) { Map preparedReleases = releaseManager.getPreparedReleases(); if ( preparedReleases.containsKey( releaseId ) ) { ReleaseDescriptor descriptor = (ReleaseDescriptor) preparedReleases.get( releaseId ); return descriptor.getReleaseVersions().get( releaseId ).toString(); } return ""; } @SuppressWarnings( "unchecked" ) public void releasePerform( String releaseId, String goals, String arguments, boolean useReleaseProfile, Map repository, String username ) throws ContinuumReleaseException { ContinuumReleaseManagerListener listener = new DefaultReleaseManagerListener(); listener.setUsername( username ); LocalRepository repo = null; if ( !repository.isEmpty() ) { String repoName = ContinuumBuildAgentUtil.getLocalRepositoryName( repository ); try { org.apache.continuum.buildagent.model.LocalRepository agentRepo = buildAgentConfigurationService.getLocalRepositoryByName( repoName ); repo = localRepositoryHelper.convertAgentRepo( agentRepo ); } catch ( BuildAgentConfigurationException e ) { log.warn( "failed to configure local repo during perform", e.getMessage() ); } } File performDirectory = new File( buildAgentConfigurationService.getWorkingDirectory(), "releases-" + System.currentTimeMillis() ); performDirectory.mkdirs(); releaseManager.perform( releaseId, performDirectory, goals, arguments, useReleaseProfile, listener, repo ); } public String releasePerformFromScm( String goals, String arguments, boolean useReleaseProfile, Map repository, String scmUrl, String scmUsername, String scmPassword, String scmTag, String scmTagBase, Map<String, String> environments, String username ) throws ContinuumReleaseException { ContinuumReleaseDescriptor descriptor = new ContinuumReleaseDescriptor(); descriptor.setScmSourceUrl( scmUrl ); descriptor.setScmUsername( scmUsername ); descriptor.setScmPassword( scmPassword ); descriptor.setScmReleaseLabel( scmTag ); descriptor.setScmTagBase( scmTagBase ); descriptor.setEnvironments( environments ); String releaseId = ""; do { releaseId = String.valueOf( System.currentTimeMillis() ); } while ( releaseManager.getPreparedReleases().containsKey( releaseId ) ); releaseManager.getPreparedReleases().put( releaseId, descriptor ); releasePerform( releaseId, goals, arguments, useReleaseProfile, repository, username ); return releaseId; } public String releaseCleanup( String releaseId ) { releaseManager.getReleaseResults().remove( releaseId ); ContinuumReleaseManagerListener listener = (ContinuumReleaseManagerListener) releaseManager.getListeners().remove( releaseId ); if ( listener != null ) { return listener.getGoalName() + "Finished"; } else { return ""; } } public void releaseRollback( String releaseId, int projectId ) throws ContinuumReleaseException { ContinuumReleaseManagerListener listener = new DefaultReleaseManagerListener(); releaseManager.rollback( releaseId, buildAgentConfigurationService.getWorkingDirectory( projectId ).getPath(), listener ); //recurse until rollback is finished while ( listener.getState() != ContinuumReleaseManagerListener.FINISHED ) { try { Thread.sleep( 1000 ); } catch ( InterruptedException e ) { //do nothing } } releaseManager.getPreparedReleases().remove( releaseId ); if ( StringUtils.isNotBlank( listener.getError() ) ) { throw new ContinuumReleaseException( "Failed to rollback release: " + listener.getError() ); } } private Project getProject( Map<String, Object> context ) { Project project = new Project(); project.setId( ContinuumBuildAgentUtil.getProjectId( context ) ); project.setGroupId( ContinuumBuildAgentUtil.getGroupId( context ) ); project.setArtifactId( ContinuumBuildAgentUtil.getArtifactId( context ) ); project.setScmUrl( ContinuumBuildAgentUtil.getScmUrl( context ) ); ProjectGroup group = new ProjectGroup(); String localRepoName = ContinuumBuildAgentUtil.getLocalRepositoryName( context ); if ( StringUtils.isBlank( localRepoName ) ) { group.setLocalRepository( null ); } else { try { org.apache.continuum.buildagent.model.LocalRepository agentRepo = buildAgentConfigurationService.getLocalRepositoryByName( localRepoName ); LocalRepository convertedRepo = localRepositoryHelper.convertAgentRepo( agentRepo ); group.setLocalRepository( convertedRepo ); } catch ( BuildAgentConfigurationException e ) { log.warn( "failed to configure local repo", e ); } } project.setProjectGroup( group ); return project; } public void setBuildAgentConfigurationService( BuildAgentConfigurationService buildAgentConfigurationService ) { this.buildAgentConfigurationService = buildAgentConfigurationService; } public ContinuumReleaseManager getReleaseManager() { return releaseManager; } }
4,971
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/manager/BuildAgentPurgeManager.java
package org.apache.continuum.buildagent.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. */ public interface BuildAgentPurgeManager { String ROLE = BuildAgentPurgeManager.class.getName(); void executeDirectoryPurge( String directoryType, int daysOlder, int retentionCount, boolean deleteAll ) throws Exception; void executeRepositoryPurge( String repoName, int daysOlder, int retentionCount, boolean deleteAll, boolean deleteReleasedSnapshots ) throws Exception; }
4,972
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/action/ChangeLogProjectAction.java
package org.apache.continuum.buildagent.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.buildagent.configuration.BuildAgentConfigurationService; import org.apache.continuum.buildagent.utils.ContinuumBuildAgentUtil; import org.apache.continuum.scm.ContinuumScm; import org.apache.continuum.scm.ContinuumScmConfiguration; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.scm.ChangeSet; import org.apache.maven.scm.ScmException; import org.apache.maven.scm.command.changelog.ChangeLogScmResult; import org.apache.maven.scm.command.changelog.ChangeLogSet; import org.codehaus.plexus.action.AbstractAction; 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; @Component( role = org.codehaus.plexus.action.Action.class, hint = "changelog-agent-project") public class ChangeLogProjectAction extends AbstractAction { @Requirement private BuildAgentConfigurationService buildAgentConfigurationService; @Requirement private ContinuumScm scm; public void execute( Map context ) throws Exception { Project project = ContinuumBuildAgentUtil.getProject( context ); try { File workingDirectory = buildAgentConfigurationService.getWorkingDirectory( project.getId() ); ContinuumScmConfiguration config = createScmConfiguration( project, workingDirectory ); config.setLatestUpdateDate( ContinuumBuildAgentUtil.getLatestUpdateDate( context ) ); getLogger().info( "Getting changeLog of project: " + project.getName() ); ChangeLogScmResult changeLogResult = scm.changeLog( config ); if ( !changeLogResult.isSuccess() ) { getLogger().warn( "Error getting change log of project " + project.getName() ); getLogger().warn( "Command Output: " + changeLogResult.getCommandOutput() ); getLogger().warn( "Provider Message: " + changeLogResult.getProviderMessage() ); } context.put( ContinuumBuildAgentUtil.KEY_LATEST_UPDATE_DATE, getLatestUpdateDate( changeLogResult ) ); } catch ( ScmException e ) { context.put( ContinuumBuildAgentUtil.KEY_LATEST_UPDATE_DATE, null ); getLogger().error( e.getMessage(), e ); } } private ContinuumScmConfiguration createScmConfiguration( Project project, File workingDirectory ) { ContinuumScmConfiguration config = new ContinuumScmConfiguration(); config.setUrl( project.getScmUrl() ); config.setUsername( project.getScmUsername() ); config.setPassword( project.getScmPassword() ); config.setUseCredentialsCache( project.isScmUseCache() ); config.setWorkingDirectory( workingDirectory ); config.setTag( project.getScmTag() ); return config; } private Date getLatestUpdateDate( ChangeLogScmResult changeLogScmResult ) { ChangeLogSet changeLogSet = changeLogScmResult.getChangeLog(); if ( changeLogSet != null ) { List<ChangeSet> changes = changeLogSet.getChangeSets(); if ( changes != null && !changes.isEmpty() ) { long date = 0; for ( ChangeSet change : changes ) { if ( date < change.getDate().getTime() ) { date = change.getDate().getTime(); } } if ( date != 0 ) { return new Date( date ); } } } return null; } public void setScm( ContinuumScm scm ) { this.scm = scm; } public void setBuildAgentConfigurationService( BuildAgentConfigurationService buildAgentConfigurationService ) { this.buildAgentConfigurationService = buildAgentConfigurationService; } }
4,973
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/action/UpdateWorkingDirectoryAction.java
package org.apache.continuum.buildagent.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.buildagent.configuration.BuildAgentConfigurationService; import org.apache.continuum.buildagent.utils.ContinuumBuildAgentUtil; import org.apache.continuum.scm.ContinuumScm; import org.apache.continuum.scm.ContinuumScmConfiguration; import org.apache.continuum.scm.ContinuumScmUtils; 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.scm.ScmException; import org.apache.maven.scm.ScmFile; import org.apache.maven.scm.command.update.UpdateScmResult; import org.apache.maven.scm.manager.NoSuchScmProviderException; import org.apache.maven.scm.repository.ScmRepositoryException; import org.codehaus.plexus.action.AbstractAction; 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.Iterator; import java.util.List; import java.util.Map; @Component( role = org.codehaus.plexus.action.Action.class, hint = "update-agent-working-directory" ) public class UpdateWorkingDirectoryAction extends AbstractAction { @Requirement private BuildAgentConfigurationService buildAgentConfigurationService; @Requirement private ContinuumScm scm; public void execute( Map context ) throws Exception { Project project = ContinuumBuildAgentUtil.getProject( context ); UpdateScmResult scmResult; ScmResult result; try { File workingDirectory = buildAgentConfigurationService.getWorkingDirectory( project.getId() ); ContinuumScmConfiguration config = createScmConfiguration( project, workingDirectory ); config.setLatestUpdateDate( ContinuumBuildAgentUtil.getLatestUpdateDate( context ) ); String tag = config.getTag(); String msg = project.getName() + "', id: '" + project.getId() + "' to '" + workingDirectory.getAbsolutePath() + "'" + ( tag != null ? " with branch/tag " + tag + "." : "." ); getLogger().info( "Updating project: " + msg ); scmResult = scm.update( config ); if ( !scmResult.isSuccess() ) { getLogger().warn( "Error while updating the code for project: '" + msg ); getLogger().warn( "Command output: " + scmResult.getCommandOutput() ); getLogger().warn( "Provider message: " + scmResult.getProviderMessage() ); } if ( scmResult.getUpdatedFiles() != null && scmResult.getUpdatedFiles().size() > 0 ) { getLogger().info( "Updated " + scmResult.getUpdatedFiles().size() + " files." ); } result = convertScmResult( scmResult ); } catch ( ScmRepositoryException e ) { result = new ScmResult(); result.setSuccess( false ); result.setProviderMessage( e.getMessage() + ": " + getValidationMessages( e ) ); getLogger().error( e.getMessage(), e ); } catch ( NoSuchScmProviderException e ) { // TODO: this is not making it back into a result of any kind - log it at least. Same is probably the case for ScmException result = new ScmResult(); result.setSuccess( false ); result.setProviderMessage( e.getMessage() ); getLogger().error( e.getMessage(), e ); } catch ( ScmException e ) { result = new ScmResult(); result.setSuccess( false ); result.setException( ContinuumBuildAgentUtil.throwableMessagesToString( e ) ); getLogger().error( e.getMessage(), e ); } context.put( ContinuumBuildAgentUtil.KEY_UPDATE_SCM_RESULT, result ); Date latestUpdateDate = getLatestUpdateDate( result ); if ( latestUpdateDate == null ) { latestUpdateDate = ContinuumBuildAgentUtil.getLatestUpdateDate( context ); } context.put( ContinuumBuildAgentUtil.KEY_LATEST_UPDATE_DATE, latestUpdateDate ); } private ContinuumScmConfiguration createScmConfiguration( Project project, File workingDirectory ) { ContinuumScmConfiguration config = new ContinuumScmConfiguration(); config.setUrl( project.getScmUrl() ); // CONTINUUM-2628 config = ContinuumScmUtils.setSCMCredentialsforSSH( config, project.getScmUrl(), project.getScmUsername(), project.getScmPassword() ); config.setUseCredentialsCache( project.isScmUseCache() ); config.setWorkingDirectory( workingDirectory ); config.setTag( project.getScmTag() ); return config; } private ScmResult convertScmResult( UpdateScmResult scmResult ) { ScmResult result = new ScmResult(); result.setCommandLine( maskPassword( scmResult.getCommandLine() ) ); result.setSuccess( scmResult.isSuccess() ); result.setCommandOutput( scmResult.getCommandOutput() ); result.setProviderMessage( scmResult.getProviderMessage() ); if ( scmResult.getChanges() != null && !scmResult.getChanges().isEmpty() ) { for ( org.apache.maven.scm.ChangeSet scmChangeSet : (List<org.apache.maven.scm.ChangeSet>) scmResult.getChanges() ) { ChangeSet change = new ChangeSet(); change.setAuthor( scmChangeSet.getAuthor() ); change.setComment( scmChangeSet.getComment() ); if ( scmChangeSet.getDate() != null ) { change.setDate( scmChangeSet.getDate().getTime() ); } if ( scmChangeSet.getFiles() != null ) { for ( org.apache.maven.scm.ChangeFile f : (List<org.apache.maven.scm.ChangeFile>) scmChangeSet.getFiles() ) { ChangeFile file = new ChangeFile(); file.setName( f.getName() ); file.setRevision( f.getRevision() ); change.addFile( file ); } } result.addChange( change ); } } else { // We don't have a changes information probably because provider doesn't have a changelog command // so we use the updated list that contains only the updated files list ChangeSet changeSet = convertScmFileSetToChangeSet( scmResult.getUpdatedFiles() ); if ( changeSet != null ) { result.addChange( changeSet ); } } return result; } private static ChangeSet convertScmFileSetToChangeSet( List<ScmFile> files ) { ChangeSet changeSet = null; if ( files != null && !files.isEmpty() ) { changeSet = new ChangeSet(); // TODO: author, etc. for ( ScmFile scmFile : files ) { ChangeFile file = new ChangeFile(); file.setName( scmFile.getPath() ); // TODO: revision? file.setStatus( scmFile.getStatus().toString() ); changeSet.addFile( file ); } } return changeSet; } // TODO: migrate to the SvnCommandLineUtils version (preferably properly encapsulated in the provider) private String maskPassword( String commandLine ) { String cmd = commandLine; if ( cmd != null && cmd.startsWith( "svn" ) ) { String pwdString = "--password"; if ( cmd.indexOf( pwdString ) > 0 ) { int index = cmd.indexOf( pwdString ) + pwdString.length() + 1; int nextSpace = cmd.indexOf( " ", index ); cmd = cmd.substring( 0, index ) + "********" + cmd.substring( nextSpace ); } } return cmd; } 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(); } private Date getLatestUpdateDate( ScmResult result ) { List<ChangeSet> changes = result.getChanges(); if ( changes != null && !changes.isEmpty() ) { long date = 0; for ( ChangeSet change : changes ) { if ( date < change.getDate() ) { date = change.getDate(); } } if ( date != 0 ) { return new Date( date ); } } return null; } }
4,974
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/action/CreateBuildProjectTaskAction.java
package org.apache.continuum.buildagent.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.buildagent.buildcontext.BuildContext; import org.apache.continuum.buildagent.taskqueue.manager.BuildAgentTaskQueueManager; import org.apache.continuum.buildagent.utils.ContinuumBuildAgentUtil; import org.apache.continuum.taskqueue.BuildProjectTask; import org.apache.continuum.taskqueue.manager.TaskQueueManagerException; import org.apache.continuum.utils.build.BuildTrigger; import org.apache.maven.continuum.ContinuumException; import org.codehaus.plexus.action.AbstractAction; 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; import java.util.Map; @Component( role = org.codehaus.plexus.action.Action.class, hint = "create-agent-build-project-task" ) public class CreateBuildProjectTaskAction extends AbstractAction { private static final Logger log = LoggerFactory.getLogger( CreateBuildProjectTaskAction.class ); @Requirement private BuildAgentTaskQueueManager buildAgentTaskQueueManager; public void execute( Map context ) throws Exception { List<BuildContext> buildContexts = ContinuumBuildAgentUtil.getBuildContexts( context ); for ( BuildContext buildContext : buildContexts ) { BuildTrigger buildTrigger = new BuildTrigger( buildContext.getTrigger(), buildContext.getUsername() ); BuildProjectTask buildProjectTask = new BuildProjectTask( buildContext.getProjectId(), buildContext.getBuildDefinitionId(), buildTrigger, buildContext.getProjectName(), buildContext.getBuildDefinitionLabel(), buildContext.getScmResult(), buildContext.getProjectGroupId() ); buildProjectTask.setMaxExecutionTime( buildContext.getMaxExecutionTime() * 1000 ); try { if ( !buildAgentTaskQueueManager.isProjectInBuildQueue( buildProjectTask.getProjectId() ) ) { log.info( "Adding project {} to build queue", buildProjectTask.getProjectId() ); buildAgentTaskQueueManager.getBuildQueue().put( buildProjectTask ); } } catch ( TaskQueueException e ) { log.error( "Error while enqueing build task for project " + buildContext.getProjectId(), e ); throw new ContinuumException( "Error while enqueuing build task for project " + buildContext.getProjectId(), e ); } catch ( TaskQueueManagerException e ) { log.error( "Error while checking if project " + buildContext.getProjectId() + " is in build queue", e ); throw new ContinuumException( "Error while checking if project " + buildContext.getProjectId() + " is in build queue", e ); } } } }
4,975
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/action/CheckWorkingDirectoryAction.java
package org.apache.continuum.buildagent.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.buildagent.configuration.BuildAgentConfigurationService; import org.apache.continuum.buildagent.utils.ContinuumBuildAgentUtil; import org.apache.maven.continuum.model.project.Project; import org.codehaus.plexus.action.AbstractAction; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import java.io.File; import java.util.Map; @Component( role = org.codehaus.plexus.action.Action.class, hint = "check-agent-working-directory" ) public class CheckWorkingDirectoryAction extends AbstractAction { @Requirement BuildAgentConfigurationService buildAgentConfigurationService; public void execute( Map context ) throws Exception { Project project = ContinuumBuildAgentUtil.getProject( context ); File workingDirectory = buildAgentConfigurationService.getWorkingDirectory( project.getId() ); if ( !workingDirectory.exists() ) { context.put( ContinuumBuildAgentUtil.KEY_WORKING_DIRECTORY_EXISTS, Boolean.FALSE ); return; } File[] files = workingDirectory.listFiles(); context.put( ContinuumBuildAgentUtil.KEY_WORKING_DIRECTORY_EXISTS, files.length > 0 ); } }
4,976
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/action/ExecuteBuilderAction.java
package org.apache.continuum.buildagent.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.buildagent.build.execution.ContinuumAgentBuildCancelledException; import org.apache.continuum.buildagent.build.execution.ContinuumAgentBuildExecutionResult; import org.apache.continuum.buildagent.build.execution.ContinuumAgentBuildExecutor; import org.apache.continuum.buildagent.build.execution.manager.BuildAgentBuildExecutorManager; import org.apache.continuum.buildagent.configuration.BuildAgentConfigurationService; import org.apache.continuum.buildagent.utils.ContinuumBuildAgentUtil; 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.action.AbstractAction; 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.Map; @Component( role = org.codehaus.plexus.action.Action.class, hint = "execute-agent-builder" ) public class ExecuteBuilderAction extends AbstractAction { @Requirement private BuildAgentBuildExecutorManager buildAgentBuildExecutorManager; @Requirement private BuildAgentConfigurationService buildAgentConfigurationService; public void execute( Map context ) throws Exception { // ---------------------------------------------------------------------- // Get parameters from the context // ---------------------------------------------------------------------- Project project = ContinuumBuildAgentUtil.getProject( context ); BuildDefinition buildDefinition = ContinuumBuildAgentUtil.getBuildDefinition( context ); Map<String, String> environments = ContinuumBuildAgentUtil.getEnvironments( context ); String localRepository = ContinuumBuildAgentUtil.getLocalRepository( context ); int trigger = ContinuumBuildAgentUtil.getTrigger( context ); String username = ContinuumBuildAgentUtil.getUsername( context ); ContinuumAgentBuildExecutor buildExecutor = buildAgentBuildExecutorManager.getBuildExecutor( project.getExecutorId() ); // ---------------------------------------------------------------------- // Make the buildResult // ---------------------------------------------------------------------- BuildResult buildResult = new BuildResult(); buildResult.setStartTime( new Date().getTime() ); buildResult.setState( ContinuumProjectState.BUILDING ); buildResult.setTrigger( trigger ); buildResult.setUsername( username ); buildResult.setBuildDefinition( buildDefinition ); buildResult.setScmResult( ContinuumBuildAgentUtil.getScmResult( context, null ) ); context.put( ContinuumBuildAgentUtil.KEY_BUILD_RESULT, buildResult ); try { File buildOutputFile = buildAgentConfigurationService.getBuildOutputFile( project.getId() ); getLogger().debug( "Start building of project " + project.getId() ); ContinuumAgentBuildExecutionResult result = buildExecutor.build( project, buildDefinition, buildOutputFile, environments, localRepository ); buildResult.setState( result.getExitCode() == 0 ? ContinuumProjectState.OK : ContinuumProjectState.FAILED ); buildResult.setExitCode( result.getExitCode() ); } catch ( ContinuumAgentBuildCancelledException e ) { getLogger().info( "Cancelled build" ); buildResult.setState( ContinuumProjectState.CANCELLED ); buildResult.setError( "Build was canceled. It may have been canceled manually or exceeded its schedule's" + " maximum execution time." ); } catch ( Throwable e ) { getLogger().error( "Error running buildResult", e ); buildResult.setState( ContinuumProjectState.ERROR ); buildResult.setError( ContinuumBuildAgentUtil.throwableToString( e ) ); } finally { 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 ); } context.put( ContinuumBuildAgentUtil.KEY_BUILD_RESULT, buildResult ); } } }
4,977
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/action/CheckoutProjectAction.java
package org.apache.continuum.buildagent.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.buildagent.configuration.BuildAgentConfigurationService; import org.apache.continuum.buildagent.utils.ContinuumBuildAgentUtil; import org.apache.continuum.scm.ContinuumScm; import org.apache.continuum.scm.ContinuumScmConfiguration; import org.apache.continuum.scm.ContinuumScmUtils; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.model.scm.ScmResult; import org.apache.maven.scm.ScmException; import org.apache.maven.scm.command.checkout.CheckOutScmResult; import org.apache.maven.scm.manager.NoSuchScmProviderException; import org.apache.maven.scm.repository.ScmRepositoryException; import org.codehaus.plexus.action.AbstractAction; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import java.io.File; import java.util.Iterator; import java.util.List; import java.util.Map; @Component( role = org.codehaus.plexus.action.Action.class, hint = "checkout-agent-project" ) public class CheckoutProjectAction extends AbstractAction { @Requirement private BuildAgentConfigurationService buildAgentConfigurationService; @Requirement private ContinuumScm scm; public void execute( Map context ) throws Exception { Project project = ContinuumBuildAgentUtil.getProject( context ); File workingDirectory = buildAgentConfigurationService.getWorkingDirectory( project.getId() ); // ---------------------------------------------------------------------- // Check out the project // ---------------------------------------------------------------------- ScmResult result; try { String scmUserName = ContinuumBuildAgentUtil.getString( context, ContinuumBuildAgentUtil.KEY_SCM_USERNAME, project.getScmUsername() ); String scmPassword = ContinuumBuildAgentUtil.getString( context, ContinuumBuildAgentUtil.KEY_SCM_PASSWORD, project.getScmPassword() ); ContinuumScmConfiguration config = createScmConfiguration( project, workingDirectory, scmUserName, scmPassword ); String tag = config.getTag(); getLogger().info( "Checking out project: '" + project.getName() + "', id: '" + project.getId() + "' " + "to '" + workingDirectory + "'" + ( tag != null ? " with branch/tag " + tag + "." : "." ) ); CheckOutScmResult checkoutResult = scm.checkout( config ); //if ( StringUtils.isNotEmpty( checkoutResult.getRelativePathProjectDirectory() ) ) //{ // context.put( AbstractContinuumAction.KEY_PROJECT_RELATIVE_PATH, // checkoutResult.getRelativePathProjectDirectory() ); //} if ( !checkoutResult.isSuccess() ) { // TODO: is it more appropriate to return this in the converted result so that it can be presented to // the user? String msg = "Error while checking out the code for project: '" + project.getName() + "', id: '" + project.getId() + "' to '" + workingDirectory.getAbsolutePath() + "'" + ( tag != null ? " with branch/tag " + tag + "." : "." ); getLogger().warn( msg ); getLogger().warn( "Command output: " + checkoutResult.getCommandOutput() ); getLogger().warn( "Provider message: " + checkoutResult.getProviderMessage() ); } else { getLogger().info( "Checked out " + checkoutResult.getCheckedOutFiles().size() + " files." ); } result = convertScmResult( checkoutResult ); } catch ( ScmRepositoryException e ) { result = new ScmResult(); result.setSuccess( false ); result.setProviderMessage( e.getMessage() + ": " + getValidationMessages( e ) ); getLogger().error( e.getMessage(), e ); } catch ( NoSuchScmProviderException e ) { // TODO: this is not making it back into a result of any kind - log it at least. Same is probably the case for ScmException result = new ScmResult(); result.setSuccess( false ); result.setProviderMessage( e.getMessage() ); getLogger().error( e.getMessage(), e ); } catch ( ScmException e ) { result = new ScmResult(); result.setSuccess( false ); result.setException( ContinuumBuildAgentUtil.throwableMessagesToString( e ) ); getLogger().error( e.getMessage(), e ); } catch ( Throwable t ) { // TODO: do we want this here, or should it be to the logs? // TODO: what throwables do we really get here that we can cope with? result = new ScmResult(); result.setSuccess( false ); result.setException( ContinuumBuildAgentUtil.throwableMessagesToString( t ) ); getLogger().error( t.getMessage(), t ); } context.put( ContinuumBuildAgentUtil.KEY_CHECKOUT_SCM_RESULT, result ); } private ContinuumScmConfiguration createScmConfiguration( Project project, File workingDirectory, String scmUserName, String scmPassword ) { ContinuumScmConfiguration config = new ContinuumScmConfiguration(); // CONTINUUM-2628 config = ContinuumScmUtils.setSCMCredentialsforSSH( config, project.getScmUrl(), scmUserName, scmPassword ); config.setUrl( project.getScmUrl() ); config.setUseCredentialsCache( project.isScmUseCache() ); config.setWorkingDirectory( workingDirectory ); config.setTag( project.getScmTag() ); return config; } private ScmResult convertScmResult( CheckOutScmResult scmResult ) { ScmResult result = new ScmResult(); result.setSuccess( scmResult.isSuccess() ); result.setCommandLine( maskPassword( scmResult.getCommandLine() ) ); result.setCommandOutput( scmResult.getCommandOutput() ); result.setProviderMessage( scmResult.getProviderMessage() ); return result; } // TODO: migrate to the SvnCommandLineUtils version (preferably properly encapsulated in the provider) private String maskPassword( String commandLine ) { String cmd = commandLine; if ( cmd != null && cmd.startsWith( "svn" ) ) { String pwdString = "--password"; if ( cmd.indexOf( pwdString ) > 0 ) { int index = cmd.indexOf( pwdString ) + pwdString.length() + 1; int nextSpace = cmd.indexOf( " ", index ); cmd = cmd.substring( 0, index ) + "********" + cmd.substring( nextSpace ); } } return cmd; } 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(); } }
4,978
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/action/UpdateProjectFromWorkingDirectoryAction.java
package org.apache.continuum.buildagent.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.buildagent.build.execution.ContinuumAgentBuildExecutor; import org.apache.continuum.buildagent.build.execution.manager.BuildAgentBuildExecutorManager; import org.apache.continuum.buildagent.configuration.BuildAgentConfigurationService; import org.apache.continuum.buildagent.utils.ContinuumBuildAgentUtil; import org.apache.maven.continuum.model.project.BuildDefinition; import org.apache.maven.continuum.model.project.Project; import org.codehaus.plexus.action.AbstractAction; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.util.Map; @Component( role = org.codehaus.plexus.action.Action.class, hint = "update-project-from-agent-working-directory" ) public class UpdateProjectFromWorkingDirectoryAction extends AbstractAction { private static final Logger logger = LoggerFactory.getLogger( UpdateProjectFromWorkingDirectoryAction.class ); @Requirement private BuildAgentBuildExecutorManager buildAgentBuildExecutorManager; @Requirement private BuildAgentConfigurationService buildAgentConfigurationService; public void execute( Map context ) throws Exception { Project project = ContinuumBuildAgentUtil.getProject( context ); logger.info( "Updating project '" + project.getName() + "' from checkout." ); BuildDefinition buildDefinition = ContinuumBuildAgentUtil.getBuildDefinition( context ); File workingDirectory = buildAgentConfigurationService.getWorkingDirectory( project.getId() ); ContinuumAgentBuildExecutor buildExecutor = buildAgentBuildExecutorManager.getBuildExecutor( project.getExecutorId() ); buildExecutor.updateProjectFromWorkingDirectory( workingDirectory, project, buildDefinition ); } }
4,979
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/action/CleanWorkingDirectoryAction.java
package org.apache.continuum.buildagent.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.buildagent.configuration.BuildAgentConfigurationService; import org.apache.continuum.buildagent.utils.ContinuumBuildAgentUtil; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.shared.model.fileset.FileSet; import org.apache.maven.shared.model.fileset.util.FileSetManager; import org.codehaus.plexus.action.AbstractAction; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import java.io.File; import java.util.Map; @Component( role = org.codehaus.plexus.action.Action.class, hint = "clean-agent-working-directory" ) public class CleanWorkingDirectoryAction extends AbstractAction { @Requirement private BuildAgentConfigurationService buildAgentConfigurationService; public void execute( Map context ) throws Exception { Project project = ContinuumBuildAgentUtil.getProject( context ); File workingDirectory = buildAgentConfigurationService.getWorkingDirectory( project.getId() ); if ( workingDirectory.exists() ) { getLogger().debug( "Cleaning working directory " + workingDirectory.getAbsolutePath() ); FileSetManager fileSetManager = new FileSetManager(); FileSet fileSet = new FileSet(); fileSet.setDirectory( workingDirectory.getPath() ); fileSet.addInclude( "**/**" ); // TODO : this with a configuration option somewhere ? fileSet.setFollowSymlinks( false ); fileSetManager.delete( fileSet ); } } }
4,980
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/build
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/build/execution/AbstractBuildExecutor.java
package org.apache.continuum.buildagent.build.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.buildagent.configuration.BuildAgentConfigurationService; import org.apache.continuum.buildagent.installation.BuildAgentInstallationService; import org.apache.continuum.buildagent.manager.BuildAgentManager; import org.apache.continuum.buildagent.utils.ContinuumBuildAgentUtil; 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.model.project.BuildDefinition; 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.ContinuumProjectState; import org.apache.maven.project.MavenProject; import org.codehaus.plexus.commandline.ExecutableResolver; 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.codehaus.plexus.util.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; public abstract class AbstractBuildExecutor implements ContinuumAgentBuildExecutor, Initializable { protected static final Logger log = LoggerFactory.getLogger( AbstractBuildExecutor.class ); @Requirement private ShellCommandHelper shellCommandHelper; @Requirement private ExecutableResolver executableResolver; @Requirement private BuildAgentConfigurationService buildAgentConfigurationService; @Requirement private BuildAgentInstallationService buildAgentInstallationService; @Configuration( "" ) private String defaultExecutable; @Requirement private BuildAgentManager buildAgentManager; // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- 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 setDefaultExecutable( String defaultExecutable ) { this.defaultExecutable = defaultExecutable; } public BuildAgentConfigurationService getBuildAgentConfigurationService() { return buildAgentConfigurationService; } public void setBuildAgentConfigurationService( BuildAgentConfigurationService buildAgentConfigurationService ) { this.buildAgentConfigurationService = buildAgentConfigurationService; } public BuildAgentInstallationService getBuildAgentInstallationService() { return buildAgentInstallationService; } public void setBuildAgentInstallationService( BuildAgentInstallationService buildAgentInstallationService ) { this.buildAgentInstallationService = buildAgentInstallationService; } public BuildAgentManager getBuildAgentManager() { return buildAgentManager; } public void setBuildAgentManager( BuildAgentManager buildAgentManager ) { this.buildAgentManager = buildAgentManager; } // ---------------------------------------------------------------------- // 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.debug( "Could not find the executable '" + executable + "' in this path: " ); for ( String element : path ) { log.debug( 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 ContinuumAgentBuildExecutionResult executeShellCommand( Project project, String executable, String arguments, File output, Map<String, String> environments ) throws ContinuumAgentBuildExecutorException, ContinuumAgentBuildCancelledException { File workingDirectory = getWorkingDirectory( project.getId() ); String actualExecutable = findExecutable( executable, defaultExecutable, resolveExecutable, workingDirectory ); // ---------------------------------------------------------------------- // Execute the build // ---------------------------------------------------------------------- try { ExecutionResult result = getShellCommandHelper().executeShellCommand( workingDirectory, actualExecutable, arguments, output, project.getId(), environments ); log.info( "Exit code: " + result.getExitCode() ); return new ContinuumAgentBuildExecutionResult( output, result.getExitCode() ); } catch ( Exception e ) { if ( e.getCause() instanceof InterruptedException ) { throw new ContinuumAgentBuildCancelledException( "The build was cancelled", e ); } else { throw new ContinuumAgentBuildExecutorException( "Error while executing shell command. The most common error is that '" + executable + "' " + "is not in your path.", e ); } } } 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( BuildDefinition buildDefinition ) { return StringUtils.clean( buildDefinition.getBuildFile() ); } protected void updateProject( Project project ) throws ContinuumAgentBuildExecutorException { Map<String, Object> projectMap = new HashMap<String, Object>(); projectMap.put( ContinuumBuildAgentUtil.KEY_PROJECT_ID, project.getId() ); if ( StringUtils.isNotEmpty( project.getVersion() ) ) { projectMap.put( ContinuumBuildAgentUtil.KEY_PROJECT_VERSION, project.getVersion() ); } else { projectMap.put( ContinuumBuildAgentUtil.KEY_PROJECT_VERSION, "" ); } if ( StringUtils.isNotEmpty( project.getArtifactId() ) ) { projectMap.put( ContinuumBuildAgentUtil.KEY_ARTIFACT_ID, project.getArtifactId() ); } else { projectMap.put( ContinuumBuildAgentUtil.KEY_ARTIFACT_ID, "" ); } if ( StringUtils.isNotEmpty( project.getGroupId() ) ) { projectMap.put( ContinuumBuildAgentUtil.KEY_GROUP_ID, project.getGroupId() ); } else { projectMap.put( ContinuumBuildAgentUtil.KEY_GROUP_ID, "" ); } if ( StringUtils.isNotEmpty( project.getName() ) ) { projectMap.put( ContinuumBuildAgentUtil.KEY_PROJECT_NAME, project.getName() ); } else { projectMap.put( ContinuumBuildAgentUtil.KEY_PROJECT_NAME, "" ); } if ( StringUtils.isNotEmpty( project.getDescription() ) ) { projectMap.put( ContinuumBuildAgentUtil.KEY_PROJECT_DESCRIPTION, project.getDescription() ); } else { projectMap.put( ContinuumBuildAgentUtil.KEY_PROJECT_DESCRIPTION, "" ); } if ( StringUtils.isNotEmpty( project.getScmUrl() ) ) { projectMap.put( ContinuumBuildAgentUtil.KEY_SCM_URL, project.getScmUrl() ); } else { projectMap.put( ContinuumBuildAgentUtil.KEY_SCM_URL, "" ); } if ( StringUtils.isNotEmpty( project.getScmTag() ) ) { projectMap.put( ContinuumBuildAgentUtil.KEY_SCM_TAG, project.getScmTag() ); } else { projectMap.put( ContinuumBuildAgentUtil.KEY_SCM_TAG, "" ); } if ( StringUtils.isNotEmpty( project.getUrl() ) ) { projectMap.put( ContinuumBuildAgentUtil.KEY_PROJECT_URL, project.getUrl() ); } else { projectMap.put( ContinuumBuildAgentUtil.KEY_PROJECT_URL, "" ); } projectMap.put( ContinuumBuildAgentUtil.KEY_PROJECT_PARENT, getProjectParent( project.getParent() ) ); projectMap.put( ContinuumBuildAgentUtil.KEY_PROJECT_DEVELOPERS, getProjectDevelopers( project.getDevelopers() ) ); projectMap.put( ContinuumBuildAgentUtil.KEY_PROJECT_DEPENDENCIES, getProjectDependencies( project.getDependencies() ) ); projectMap.put( ContinuumBuildAgentUtil.KEY_PROJECT_NOTIFIERS, getProjectNotifiers( project.getNotifiers() ) ); try { log.debug( "Update project {}" + project.getId() ); buildAgentManager.updateProject( projectMap ); } catch ( Exception e ) { throw new ContinuumAgentBuildExecutorException( "Failed to update project", e ); } } protected List<Map<String, String>> getProjectDevelopers( List<ProjectDeveloper> developers ) { List<Map<String, String>> pDevelopers = new ArrayList<Map<String, String>>(); if ( developers != null ) { for ( ProjectDeveloper developer : developers ) { Map<String, String> map = new HashMap<String, String>(); if ( StringUtils.isNotEmpty( developer.getName() ) ) { map.put( ContinuumBuildAgentUtil.KEY_PROJECT_DEVELOPER_NAME, developer.getName() ); } else { map.put( ContinuumBuildAgentUtil.KEY_PROJECT_DEVELOPER_NAME, "" ); } if ( StringUtils.isNotEmpty( developer.getEmail() ) ) { map.put( ContinuumBuildAgentUtil.KEY_PROJECT_DEVELOPER_EMAIL, developer.getEmail() ); } else { map.put( ContinuumBuildAgentUtil.KEY_PROJECT_DEVELOPER_EMAIL, "" ); } if ( StringUtils.isNotEmpty( developer.getScmId() ) ) { map.put( ContinuumBuildAgentUtil.KEY_PROJECT_DEVELOPER_SCMID, developer.getScmId() ); } else { map.put( ContinuumBuildAgentUtil.KEY_PROJECT_DEVELOPER_SCMID, "" ); } pDevelopers.add( map ); } } return pDevelopers; } protected Map<String, Object> getProjectParent( ProjectDependency parent ) { Map<String, Object> map = new HashMap<String, Object>(); if ( parent != null ) { if ( StringUtils.isNotEmpty( parent.getGroupId() ) ) { map.put( ContinuumBuildAgentUtil.KEY_GROUP_ID, parent.getGroupId() ); } else { map.put( ContinuumBuildAgentUtil.KEY_GROUP_ID, "" ); } if ( StringUtils.isNotEmpty( parent.getArtifactId() ) ) { map.put( ContinuumBuildAgentUtil.KEY_ARTIFACT_ID, parent.getArtifactId() ); } else { map.put( ContinuumBuildAgentUtil.KEY_ARTIFACT_ID, "" ); } if ( StringUtils.isNotEmpty( parent.getVersion() ) ) { map.put( ContinuumBuildAgentUtil.KEY_PROJECT_VERSION, parent.getVersion() ); } else { map.put( ContinuumBuildAgentUtil.KEY_PROJECT_VERSION, "" ); } } return map; } protected List<Map<String, Object>> getProjectDependencies( List<ProjectDependency> dependencies ) { List<Map<String, Object>> pDependencies = new ArrayList<Map<String, Object>>(); if ( dependencies != null ) { for ( ProjectDependency dependency : dependencies ) { Map<String, Object> map = new HashMap<String, Object>(); if ( StringUtils.isNotEmpty( dependency.getGroupId() ) ) { map.put( ContinuumBuildAgentUtil.KEY_GROUP_ID, dependency.getGroupId() ); } else { map.put( ContinuumBuildAgentUtil.KEY_GROUP_ID, "" ); } if ( StringUtils.isNotEmpty( dependency.getArtifactId() ) ) { map.put( ContinuumBuildAgentUtil.KEY_ARTIFACT_ID, dependency.getArtifactId() ); } else { map.put( ContinuumBuildAgentUtil.KEY_ARTIFACT_ID, "" ); } if ( StringUtils.isNotEmpty( dependency.getVersion() ) ) { map.put( ContinuumBuildAgentUtil.KEY_PROJECT_VERSION, dependency.getVersion() ); } else { map.put( ContinuumBuildAgentUtil.KEY_PROJECT_VERSION, "" ); } pDependencies.add( map ); } } return pDependencies; } protected List<Map<String, Object>> getProjectNotifiers( List<ProjectNotifier> notifiers ) { List<Map<String, Object>> pNotifiers = new ArrayList<Map<String, Object>>(); if ( notifiers != null ) { for ( ProjectNotifier notifier : notifiers ) { Map<String, Object> map = new HashMap<String, Object>(); if ( notifier.getConfiguration() != null ) { map.put( ContinuumBuildAgentUtil.KEY_NOTIFIER_CONFIGURATION, notifier.getConfiguration() ); } else { map.put( ContinuumBuildAgentUtil.KEY_NOTIFIER_CONFIGURATION, "" ); } if ( StringUtils.isNotBlank( notifier.getType() ) ) { map.put( ContinuumBuildAgentUtil.KEY_NOTIFIER_TYPE, notifier.getType() ); } else { map.put( ContinuumBuildAgentUtil.KEY_NOTIFIER_TYPE, "" ); } map.put( ContinuumBuildAgentUtil.KEY_NOTIFIER_FROM, notifier.getFrom() ); map.put( ContinuumBuildAgentUtil.KEY_NOTIFIER_RECIPIENT_TYPE, notifier.getRecipientType() ); map.put( ContinuumBuildAgentUtil.KEY_NOTIFIER_ENABLED, notifier.isEnabled() ); map.put( ContinuumBuildAgentUtil.KEY_NOTIFIER_SEND_ON_ERROR, notifier.isSendOnError() ); map.put( ContinuumBuildAgentUtil.KEY_NOTIFIER_SEND_ON_SUCCESS, notifier.isSendOnSuccess() ); map.put( ContinuumBuildAgentUtil.KEY_NOTIFIER_SEND_ON_FAILURE, notifier.isSendOnFailure() ); map.put( ContinuumBuildAgentUtil.KEY_NOTIFIER_SEND_ON_SCMFAILURE, notifier.isSendOnScmFailure() ); map.put( ContinuumBuildAgentUtil.KEY_NOTIFIER_SEND_ON_WARNING, notifier.isSendOnWarning() ); pNotifiers.add( map ); } } return pNotifiers; } 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 ContinuumAgentBuildExecutorException { // Not supported by this builder return Collections.EMPTY_LIST; } public MavenProject getMavenProject( File workingDirectory, BuildDefinition buildDefinition ) throws ContinuumAgentBuildExecutorException { return null; } public File getWorkingDirectory( int projectId ) { return getBuildAgentConfigurationService().getWorkingDirectory( projectId ); } 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; } }
4,981
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/build
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/build/execution/ContinuumAgentBuildExecutor.java
package org.apache.continuum.buildagent.build.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.maven.artifact.Artifact; import org.apache.maven.continuum.model.project.BuildDefinition; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.project.MavenProject; import java.io.File; import java.util.List; import java.util.Map; public interface ContinuumAgentBuildExecutor { String ROLE = ContinuumAgentBuildExecutor.class.getName(); ContinuumAgentBuildExecutionResult build( Project project, BuildDefinition buildDefinition, File buildOutput, Map<String, String> environments, String localRepository ) throws ContinuumAgentBuildExecutorException, ContinuumAgentBuildCancelledException; boolean isBuilding( Project project ); void killProcess( Project project ); // TODO: are these part of the builder interface, or a separate project/build definition interface? List<Artifact> getDeployableArtifacts( Project project, File workingDirectory, BuildDefinition buildDefinition ) throws ContinuumAgentBuildExecutorException; void updateProjectFromWorkingDirectory( File workingDirectory, Project project, BuildDefinition buildDefinition ) throws ContinuumAgentBuildExecutorException; MavenProject getMavenProject( File workingDirectory, BuildDefinition buildDefinition ) throws ContinuumAgentBuildExecutorException; }
4,982
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/build
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/build/execution/ContinuumAgentBuildExecutionResult.java
package org.apache.continuum.buildagent.build.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 java.io.File; public class ContinuumAgentBuildExecutionResult { private final File output; private final int exitCode; public ContinuumAgentBuildExecutionResult( File output, int exitCode ) { this.output = output; this.exitCode = exitCode; } public File getOutput() { return output; } public int getExitCode() { return exitCode; } }
4,983
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/build
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/build/execution/ContinuumAgentBuildCancelledException.java
package org.apache.continuum.buildagent.build.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.maven.continuum.execution.ContinuumBuildExecutorException; public class ContinuumAgentBuildCancelledException extends ContinuumBuildExecutorException { public ContinuumAgentBuildCancelledException( String message ) { super( message ); } public ContinuumAgentBuildCancelledException( String message, Throwable cause ) { super( message, cause ); } }
4,984
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/build
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/build/execution/ContinuumAgentBuildExecutorException.java
package org.apache.continuum.buildagent.build.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. */ public class ContinuumAgentBuildExecutorException extends Exception { public ContinuumAgentBuildExecutorException( String message ) { super( message ); } public ContinuumAgentBuildExecutorException( Throwable cause ) { super( cause ); } public ContinuumAgentBuildExecutorException( String message, Throwable cause ) { super( message, cause ); } }
4,985
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/build/execution
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/build/execution/ant/AntBuildExecutor.java
package org.apache.continuum.buildagent.build.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.continuum.buildagent.build.execution.AbstractBuildExecutor; import org.apache.continuum.buildagent.build.execution.ContinuumAgentBuildCancelledException; import org.apache.continuum.buildagent.build.execution.ContinuumAgentBuildExecutionResult; import org.apache.continuum.buildagent.build.execution.ContinuumAgentBuildExecutor; import org.apache.continuum.buildagent.build.execution.ContinuumAgentBuildExecutorException; import org.apache.continuum.buildagent.installation.BuildAgentInstallationService; 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.codehaus.plexus.util.StringUtils; import java.io.File; import java.util.Enumeration; import java.util.Map; import java.util.Properties; public class AntBuildExecutor extends AbstractBuildExecutor implements ContinuumAgentBuildExecutor { public static final String CONFIGURATION_EXECUTABLE = "executable"; public static final String CONFIGURATION_TARGETS = "targets"; public static final String ID = ContinuumBuildExecutorConstants.ANT_BUILD_EXECUTOR; protected AntBuildExecutor() { super( ID, true ); } public ContinuumAgentBuildExecutionResult build( Project project, BuildDefinition buildDefinition, File buildOutput, Map<String, String> environments, String localRepository ) throws ContinuumAgentBuildExecutorException, ContinuumAgentBuildCancelledException { String executable = getBuildAgentInstallationService().getExecutorConfigurator( BuildAgentInstallationService.ANT_TYPE ).getExecutable(); StringBuffer arguments = new StringBuffer(); String buildFile = getBuildFileForProject( 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() ) ); String antHome = null; if ( environments != null ) { antHome = environments.get( getBuildAgentInstallationService().getEnvVar( BuildAgentInstallationService.ANT_TYPE ) ); } if ( StringUtils.isNotEmpty( antHome ) ) { executable = antHome + File.separator + "bin" + File.separator + executable; setResolveExecutable( false ); } return executeShellCommand( project, executable, arguments.toString(), buildOutput, environments ); } public void updateProjectFromWorkingDirectory( File workingDirectory, Project project, BuildDefinition buildDefinition ) throws ContinuumAgentBuildExecutorException { // nothing to do here } }
4,986
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/build/execution
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/build/execution/shell/ShellBuildExecutor.java
package org.apache.continuum.buildagent.build.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.continuum.buildagent.build.execution.AbstractBuildExecutor; import org.apache.continuum.buildagent.build.execution.ContinuumAgentBuildCancelledException; import org.apache.continuum.buildagent.build.execution.ContinuumAgentBuildExecutionResult; import org.apache.continuum.buildagent.build.execution.ContinuumAgentBuildExecutor; import org.apache.continuum.buildagent.build.execution.ContinuumAgentBuildExecutorException; import org.apache.maven.continuum.execution.ContinuumBuildExecutorConstants; import org.apache.maven.continuum.model.project.BuildDefinition; import org.apache.maven.continuum.model.project.Project; import java.io.File; import java.util.Map; public class ShellBuildExecutor extends AbstractBuildExecutor implements ContinuumAgentBuildExecutor { public static final String CONFIGURATION_EXECUTABLE = "executable"; public static final String ID = ContinuumBuildExecutorConstants.SHELL_BUILD_EXECUTOR; public ShellBuildExecutor() { super( ID, false ); } public ContinuumAgentBuildExecutionResult build( Project project, BuildDefinition buildDefinition, File buildOutput, Map<String, String> environments, String localRepository ) throws ContinuumAgentBuildExecutorException, ContinuumAgentBuildCancelledException { String executable = getBuildFileForProject( buildDefinition ); return executeShellCommand( project, executable, buildDefinition.getArguments(), buildOutput, environments ); } public void updateProjectFromWorkingDirectory( File workingDirectory, Project project, BuildDefinition buildDefinition ) throws ContinuumAgentBuildExecutorException { // nothing to do here } }
4,987
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/build/execution/maven
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/build/execution/maven/m1/MavenOneBuildExecutor.java
package org.apache.continuum.buildagent.build.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.buildagent.build.execution.AbstractBuildExecutor; import org.apache.continuum.buildagent.build.execution.ContinuumAgentBuildCancelledException; import org.apache.continuum.buildagent.build.execution.ContinuumAgentBuildExecutionResult; import org.apache.continuum.buildagent.build.execution.ContinuumAgentBuildExecutor; import org.apache.continuum.buildagent.build.execution.ContinuumAgentBuildExecutorException; import org.apache.continuum.buildagent.installation.BuildAgentInstallationService; 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.project.builder.ContinuumProjectBuildingResult; import org.codehaus.plexus.util.StringUtils; import java.io.File; import java.util.Enumeration; import java.util.Map; import java.util.Properties; import javax.annotation.Resource; public class MavenOneBuildExecutor extends AbstractBuildExecutor implements ContinuumAgentBuildExecutor { public final static String CONFIGURATION_GOALS = "goals"; public final static String ID = ContinuumBuildExecutorConstants.MAVEN_ONE_BUILD_EXECUTOR; @Resource private BuildAgentMavenOneMetadataHelper buildAgentMavenOneMetadataHelper; public MavenOneBuildExecutor() { super( ID, true ); } public ContinuumAgentBuildExecutionResult build( Project project, BuildDefinition buildDefinition, File buildOutput, Map<String, String> environments, String localRepository ) throws ContinuumAgentBuildExecutorException, ContinuumAgentBuildCancelledException { String executable = getBuildAgentInstallationService().getExecutorConfigurator( BuildAgentInstallationService.MAVEN1_TYPE ).getExecutable(); StringBuffer arguments = new StringBuffer(); String buildFile = getBuildFileForProject( 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( "\" " ); } if ( StringUtils.isNotEmpty( localRepository ) ) { arguments.append( "\"-Dmaven.repo.local=" ).append( StringUtils.clean( localRepository ) ).append( "\" " ); } arguments.append( StringUtils.clean( buildDefinition.getGoals() ) ); String m1Home = null; if ( environments != null ) { m1Home = environments.get( getBuildAgentInstallationService().getEnvVar( BuildAgentInstallationService.MAVEN1_TYPE ) ); } if ( StringUtils.isNotEmpty( m1Home ) ) { executable = m1Home + File.separator + "bin" + File.separator + executable; setResolveExecutable( false ); } return executeShellCommand( project, executable, arguments.toString(), buildOutput, environments ); } public void updateProjectFromWorkingDirectory( File workingDirectory, Project project, BuildDefinition buildDefinition ) throws ContinuumAgentBuildExecutorException { 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 ContinuumAgentBuildExecutorException( "Could not find Maven project descriptor." ); } try { ContinuumProjectBuildingResult result = new ContinuumProjectBuildingResult(); buildAgentMavenOneMetadataHelper.mapMetadata( result, projectXmlFile, project ); if ( result.hasErrors() ) { throw new ContinuumAgentBuildExecutorException( "Error while mapping metadata:" + result.getErrorsAsString() ); } updateProject( project ); } catch ( BuildAgentMavenOneMetadataHelperException e ) { throw new ContinuumAgentBuildExecutorException( "Error while mapping metadata.", e ); } } }
4,988
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/build/execution/maven
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/build/execution/maven/m1/BuildAgentMavenOneMetadataHelperException.java
package org.apache.continuum.buildagent.build.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. */ public class BuildAgentMavenOneMetadataHelperException extends Exception { public BuildAgentMavenOneMetadataHelperException( String message ) { super( message ); } public BuildAgentMavenOneMetadataHelperException( Throwable cause ) { super( cause ); } public BuildAgentMavenOneMetadataHelperException( String message, Throwable cause ) { super( message, cause ); } }
4,989
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/build/execution/maven
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/build/execution/maven/m1/DefaultBuildAgentMavenOneMetadataHelper.java
package org.apache.continuum.buildagent.build.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.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; @Component( role = org.apache.continuum.buildagent.build.execution.maven.m1.BuildAgentMavenOneMetadataHelper.class, hint = "default" ) public class DefaultBuildAgentMavenOneMetadataHelper implements BuildAgentMavenOneMetadataHelper { private static final Logger log = LoggerFactory.getLogger( DefaultBuildAgentMavenOneMetadataHelper.class ); public void mapMetadata( ContinuumProjectBuildingResult result, File metadata, Project project ) throws BuildAgentMavenOneMetadataHelperException { 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( "address", 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 ); 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(); } }
4,990
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/build/execution/maven
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/build/execution/maven/m1/BuildAgentMavenOneMetadataHelper.java
package org.apache.continuum.buildagent.build.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; public interface BuildAgentMavenOneMetadataHelper { String ROLE = BuildAgentMavenOneMetadataHelper.class.getName(); void mapMetadata( ContinuumProjectBuildingResult result, File metadata, Project project ) throws BuildAgentMavenOneMetadataHelperException; }
4,991
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/build/execution/maven
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/build/execution/maven/m2/BuildAgentMavenBuilderHelper.java
package org.apache.continuum.buildagent.build.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; public interface BuildAgentMavenBuilderHelper { String ROLE = BuildAgentMavenBuilderHelper.class.getName(); MavenProject getMavenProject( ContinuumProjectBuildingResult result, File file ); void mapMetadataToProject( ContinuumProjectBuildingResult result, File metadata, Project project ); }
4,992
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/build/execution/maven
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/build/execution/maven/m2/MavenTwoBuildExecutor.java
package org.apache.continuum.buildagent.build.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.buildagent.build.execution.AbstractBuildExecutor; import org.apache.continuum.buildagent.build.execution.ContinuumAgentBuildCancelledException; import org.apache.continuum.buildagent.build.execution.ContinuumAgentBuildExecutionResult; import org.apache.continuum.buildagent.build.execution.ContinuumAgentBuildExecutor; import org.apache.continuum.buildagent.build.execution.ContinuumAgentBuildExecutorException; import org.apache.continuum.buildagent.installation.BuildAgentInstallationService; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.metadata.ArtifactMetadata; 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.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.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.Map; import java.util.Properties; public class MavenTwoBuildExecutor extends AbstractBuildExecutor implements ContinuumAgentBuildExecutor { public static final String CONFIGURATION_GOALS = "goals"; public static final String ID = ContinuumBuildExecutorConstants.MAVEN_TWO_BUILD_EXECUTOR; @Requirement private MavenProjectHelper projectHelper; @Requirement private BuildAgentMavenBuilderHelper buildAgentMavenBuilderHelper; public MavenTwoBuildExecutor() { super( ID, true ); } public MavenProjectHelper getProjectHelper() { return projectHelper; } public void setProjectHelper( MavenProjectHelper projectHelper ) { this.projectHelper = projectHelper; } public BuildAgentMavenBuilderHelper getBuildAgentMavenBuilderHelper() { return buildAgentMavenBuilderHelper; } public void setBuildAgentMavenBuilderHelper( BuildAgentMavenBuilderHelper builderHelper ) { this.buildAgentMavenBuilderHelper = builderHelper; } public ContinuumAgentBuildExecutionResult build( Project project, BuildDefinition buildDefinition, File buildOutput, Map<String, String> environments, String localRepository ) throws ContinuumAgentBuildExecutorException, ContinuumAgentBuildCancelledException { String executable = getBuildAgentInstallationService().getExecutorConfigurator( BuildAgentInstallationService.MAVEN2_TYPE ).getExecutable(); StringBuffer arguments = new StringBuffer(); String buildFile = getBuildFileForProject( 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( "\" " ); } if ( StringUtils.isNotEmpty( localRepository ) ) { arguments.append( "\"-Dmaven.repo.local=" ).append( StringUtils.clean( localRepository ) ).append( "\" " ); } arguments.append( StringUtils.clean( buildDefinition.getGoals() ) ); String m2Home = null; if ( environments != null ) { m2Home = environments.get( getBuildAgentInstallationService().getEnvVar( BuildAgentInstallationService.MAVEN2_TYPE ) ); } if ( StringUtils.isNotEmpty( m2Home ) ) { executable = m2Home + File.separator + "bin" + File.separator + executable; setResolveExecutable( false ); } return executeShellCommand( project, executable, arguments.toString(), buildOutput, environments ); } @Override public List<Artifact> getDeployableArtifacts( Project continuumProject, File workingDirectory, BuildDefinition buildDefinition ) throws ContinuumAgentBuildExecutorException { MavenProject project = getMavenProject( 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; } public void updateProjectFromWorkingDirectory( File workingDirectory, Project project, BuildDefinition buildDefinition ) throws ContinuumAgentBuildExecutorException { File f = getPomFile( getBuildFileForProject( buildDefinition ), workingDirectory ); if ( !f.exists() ) { throw new ContinuumAgentBuildExecutorException( "Could not find Maven project descriptor." ); } ContinuumProjectBuildingResult result = new ContinuumProjectBuildingResult(); buildAgentMavenBuilderHelper.mapMetadataToProject( result, f, project ); if ( result.hasErrors() ) { throw new ContinuumAgentBuildExecutorException( "Error while mapping metadata:" + result.getErrorsAsString() ); } else { updateProject( project ); } } @Override public MavenProject getMavenProject( File workingDirectory, BuildDefinition buildDefinition ) throws ContinuumAgentBuildExecutorException { ContinuumProjectBuildingResult result = new ContinuumProjectBuildingResult(); File f = getPomFile( getBuildFileForProject( buildDefinition ), workingDirectory ); if ( !f.exists() ) { throw new ContinuumAgentBuildExecutorException( "Could not find Maven project descriptor '" + f + "'." ); } MavenProject project = buildAgentMavenBuilderHelper.getMavenProject( result, f ); if ( result.hasErrors() ) { throw new ContinuumAgentBuildExecutorException( "Unable to read the Maven project descriptor '" + f + "': " + result.getErrorsAsString() ); } return project; } 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; } }
4,993
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/build/execution/maven
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/build/execution/maven/m2/DefaultBuildAgentMavenBuilderHelper.java
package org.apache.continuum.buildagent.build.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.artifact.manager.WagonManager; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.repository.ArtifactRepositoryFactory; import org.apache.maven.artifact.repository.layout.ArtifactRepositoryLayout; import org.apache.maven.artifact.resolver.ArtifactNotFoundException; 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.MavenSettingsBuilder; 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.codehaus.plexus.util.xml.pull.XmlPullParserException; 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; @Component( role = org.apache.continuum.buildagent.build.execution.maven.m2.BuildAgentMavenBuilderHelper.class, hint = "default" ) public class DefaultBuildAgentMavenBuilderHelper implements BuildAgentMavenBuilderHelper, Contextualizable, Initializable { private static final Logger log = LoggerFactory.getLogger( DefaultBuildAgentMavenBuilderHelper.class ); @Requirement private MavenProjectBuilder projectBuilder; @Requirement private MavenSettingsBuilder mavenSettingsBuilder; @Requirement private ArtifactRepositoryFactory artifactRepositoryFactory; @Requirement private ArtifactRepositoryLayout defaultRepositoryLayout; private PlexusContainer container; 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 = getSettings(); if ( log.isDebugEnabled() ) { writeSettings( settings ); } ProfileManager profileManager = new DefaultProfileManager( container, settings ); project = projectBuilder.build( file, getRepository( settings ), profileManager, false ); 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 void mapMetadataToProject( ContinuumProjectBuildingResult result, File metadata, Project continuumProject ) { 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, false ); } public void mapMavenProjectToContinuumProject( ContinuumProjectBuildingResult result, MavenProject mavenProject, Project continuumProject, boolean groupPom ) { if ( mavenProject == null ) { result.addError( ContinuumProjectBuildingResult.ERROR_UNKNOWN, "The maven project is null." ); return; } // ---------------------------------------------------------------------- // Name // ---------------------------------------------------------------------- continuumProject.setName( getProjectName( mavenProject ) ); // ---------------------------------------------------------------------- // 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() ); } } // ---------------------------------------------------------------------- // Version // ---------------------------------------------------------------------- continuumProject.setVersion( getVersion( mavenProject ) ); // ---------------------------------------------------------------------- // 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, continuumProject ); if ( notifiers != null ) { continuumProject.setNotifiers( notifiers ); } for ( ProjectNotifier notifier : userNotifiers ) { continuumProject.addNotifier( notifier ); } } private String getScmUrl( MavenProject project ) { return project.getScm().getConnection(); } private List<ProjectNotifier> getNotifiers( ContinuumProjectBuildingResult result, MavenProject mavenProject, Project continuumProject ) { 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 Settings getSettings() throws SettingsConfigurationException { try { return mavenSettingsBuilder.buildSettings( false ); } catch ( IOException e ) { throw new SettingsConfigurationException( "Error reading settings file", e ); } catch ( XmlPullParserException e ) { throw new SettingsConfigurationException( e.getMessage(), e.getDetail(), e.getLineNumber(), e.getColumnNumber() ); } } private ArtifactRepository getRepository( Settings settings ) { return artifactRepositoryFactory.createArtifactRepository( "local", "file://" + settings.getLocalRepository(), defaultRepositoryLayout, null, null ); } public String getProjectName( MavenProject project ) { String name = project.getName(); if ( StringUtils.isEmpty( name ) ) { return project.getId(); } return name; } 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() ); } public void contextualize( Context context ) throws ContextException { container = (PlexusContainer) context.get( PlexusConstants.PLEXUS_KEY ); } public void initialize() throws InitializationException { try { Settings settings = getSettings(); resolveParameters( settings ); } catch ( Exception e ) { throw new InitializationException( "Can't initialize '" + getClass().getName() + "'", e ); } } /** * @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 ); } } void setMavenSettingsBuilder( MavenSettingsBuilder mavenSettingsBuilder ) { this.mavenSettingsBuilder = mavenSettingsBuilder; } }
4,994
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/build/execution/maven
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/build/execution/maven/m2/SettingsConfigurationException.java
package org.apache.continuum.buildagent.build.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. */ public class SettingsConfigurationException extends Exception { private int lineNumber; private int columnNumber; public SettingsConfigurationException( String message ) { super( message ); } public SettingsConfigurationException( String message, Throwable cause ) { super( message, cause ); } public SettingsConfigurationException( String message, Throwable cause, int lineNumber, int columnNumber ) { super( message + ( lineNumber > 0 ? "\n Line: " + lineNumber : "" ) + ( columnNumber > 0 ? "\n Column: " + columnNumber : "" ), cause ); this.lineNumber = lineNumber; this.columnNumber = columnNumber; } public int getColumnNumber() { return columnNumber; } public int getLineNumber() { return lineNumber; } }
4,995
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/build/execution
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/build/execution/manager/DefaultBuildAgentBuildExecutorManager.java
package org.apache.continuum.buildagent.build.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.continuum.buildagent.build.execution.ContinuumAgentBuildExecutor; import org.apache.maven.continuum.ContinuumException; 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.HashMap; import java.util.Map; @Component( role = org.apache.continuum.buildagent.build.execution.manager.BuildAgentBuildExecutorManager.class, hint = "default" ) public class DefaultBuildAgentBuildExecutorManager implements BuildAgentBuildExecutorManager { private static final Logger log = LoggerFactory.getLogger( DefaultBuildAgentBuildExecutorManager.class ); @Requirement( role = org.apache.continuum.buildagent.build.execution.ContinuumAgentBuildExecutor.class ) private Map<String, ContinuumAgentBuildExecutor> executors; // ---------------------------------------------------------------------- // Component Lifecycle // ---------------------------------------------------------------------- public void initialize() { if ( executors == null ) { executors = new HashMap<String, ContinuumAgentBuildExecutor>(); } 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 ContinuumAgentBuildExecutor getBuildExecutor( String builderType ) throws ContinuumException { ContinuumAgentBuildExecutor 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 ); } }
4,996
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/build/execution
Create_ds/continuum/continuum-buildagent/continuum-buildagent-core/src/main/java/org/apache/continuum/buildagent/build/execution/manager/BuildAgentBuildExecutorManager.java
package org.apache.continuum.buildagent.build.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.continuum.buildagent.build.execution.ContinuumAgentBuildExecutor; import org.apache.maven.continuum.ContinuumException; public interface BuildAgentBuildExecutorManager { String ROLE = BuildAgentBuildExecutorManager.class.getName(); ContinuumAgentBuildExecutor getBuildExecutor( String executorId ) throws ContinuumException; boolean hasBuildExecutor( String executorId ); }
4,997
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-webdav/src/test/java/org/apache/continuum
Create_ds/continuum/continuum-buildagent/continuum-buildagent-webdav/src/test/java/org/apache/continuum/webdav/WorkingCopyServletTest.java
package org.apache.continuum.webdav; /* * 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.meterware.httpunit.GetMethodWebRequest; import com.meterware.httpunit.HttpUnitOptions; import com.meterware.httpunit.WebLink; import com.meterware.httpunit.WebRequest; import com.meterware.httpunit.WebResponse; import com.meterware.servletunit.ServletRunner; import com.meterware.servletunit.ServletUnitClient; import net.sf.ehcache.CacheManager; import org.apache.commons.io.IOUtils; import org.apache.continuum.utils.file.FileSystemManager; import org.apache.maven.continuum.PlexusSpringTestCase; import org.codehaus.plexus.util.Base64; import org.junit.After; import org.junit.Before; import org.junit.Test; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; public class WorkingCopyServletTest extends PlexusSpringTestCase { private static final String REQUEST_PATH = "http://machine.com/workingcopy/1/"; private WebRequest request; private WebResponse response; private ServletRunner sr; private ServletUnitClient sc; private FileSystemManager fsManager; private File workingDirectory; @Before public void setUp() throws Exception { String appserverBase = getTestFile( "target/appserver-base" ).getAbsolutePath(); System.setProperty( "appserver.base", appserverBase ); workingDirectory = new File( appserverBase, "data/working-directory" ); CacheManager.getInstance().removeCache( "url-failures-cache" ); HttpUnitOptions.setExceptionsThrownOnErrorStatus( false ); sr = new ServletRunner( getTestFile( "src/test/resources/WEB-INF/web.xml" ) ); sr.registerServlet( "/workingcopy/*", MockWorkingCopyServlet.class.getName() ); sc = sr.newClient(); fsManager = lookup( FileSystemManager.class ); new File( workingDirectory, "1/src/main/java/org/apache/continuum" ).mkdirs(); new File( workingDirectory, "1/src/main/java/org/apache/continuum/App.java" ).createNewFile(); new File( workingDirectory, "1/src/test" ).mkdirs(); new File( workingDirectory, "1/pom.xml" ).createNewFile(); new File( workingDirectory, "1/target" ).mkdir(); new File( workingDirectory, "1/target/continuum-artifact-1.0.jar" ).createNewFile(); } @After public void tearDown() throws Exception { if ( sc != null ) { sc.clearContents(); } if ( sr != null ) { sr.shutDown(); } if ( workingDirectory.exists() ) { fsManager.removeDir( workingDirectory ); } } @Test public void testGetWorkingCopy() throws Exception { MockWorkingCopyServlet servlet = (MockWorkingCopyServlet) sc.newInvocation( REQUEST_PATH ).getServlet(); assertNotNull( servlet ); } @Test public void testBrowse() throws Exception { request = new GetMethodWebRequest( REQUEST_PATH ); request.setHeaderField( "Authorization", getAuthorizationHeader() ); response = sc.getResponse( request ); assertEquals( "Response", HttpServletResponse.SC_OK, response.getResponseCode() ); String expectedLinks[] = new String[] { "pom.xml", "src/", "target/" }; assertLinks( expectedLinks, response.getLinks() ); } @Test public void testBrowseSubDirectory() throws Exception { request = new GetMethodWebRequest( REQUEST_PATH + "src/" ); request.setHeaderField( "Authorization", getAuthorizationHeader() ); response = sc.getResponse( request ); assertEquals( "Response", HttpServletResponse.SC_OK, response.getResponseCode() ); String expectedLinks[] = new String[] { "../", "main/", "test/" }; assertLinks( expectedLinks, response.getLinks() ); } @Test public void testGetFile() throws Exception { request = new GetMethodWebRequest( REQUEST_PATH + "src/main/java/org/apache/continuum" ); request.setHeaderField( "Authorization", getAuthorizationHeader() ); response = sc.getResponse( request ); assertEquals( "Response", HttpServletResponse.SC_OK, response.getResponseCode() ); request = new GetMethodWebRequest( REQUEST_PATH + "src/main/java/org/apache/continuum/" ); request.setHeaderField( "Authorization", getAuthorizationHeader() ); response = sc.getResponse( request ); assertEquals( "Response", HttpServletResponse.SC_OK, response.getResponseCode() ); request = new GetMethodWebRequest( REQUEST_PATH + "src/main/java/org/apache/continuum/App.java" ); request.setHeaderField( "Authorization", getAuthorizationHeader() ); response = sc.getResponse( request ); assertEquals( "Response", HttpServletResponse.SC_OK, response.getResponseCode() ); request = new GetMethodWebRequest( REQUEST_PATH + "src/main/java/org/apache/continuum/App.java/" ); request.setHeaderField( "Authorization", getAuthorizationHeader() ); response = sc.getResponse( request ); assertEquals( "Response", HttpServletResponse.SC_NOT_FOUND, response.getResponseCode() ); request = new GetMethodWebRequest( REQUEST_PATH + "pom.xml" ); request.setHeaderField( "Authorization", getAuthorizationHeader() ); response = sc.getResponse( request ); assertEquals( "Response", HttpServletResponse.SC_OK, response.getResponseCode() ); request = new GetMethodWebRequest( REQUEST_PATH + "pom.xml/" ); request.setHeaderField( "Authorization", getAuthorizationHeader() ); response = sc.getResponse( request ); assertEquals( "Response", HttpServletResponse.SC_NOT_FOUND, response.getResponseCode() ); request = new GetMethodWebRequest( REQUEST_PATH + "target/continuum-artifact-1.0.jar" ); request.setHeaderField( "Authorization", getAuthorizationHeader() ); response = sc.getResponse( request ); assertEquals( "Response", HttpServletResponse.SC_OK, response.getResponseCode() ); request = new GetMethodWebRequest( REQUEST_PATH + "target/continuum-artifact-1.0.jar/" ); request.setHeaderField( "Authorization", getAuthorizationHeader() ); response = sc.getResponse( request ); assertEquals( "Response", HttpServletResponse.SC_NOT_FOUND, response.getResponseCode() ); } private void assertLinks( String expectedLinks[], WebLink actualLinks[] ) { assertEquals( "Links.length", expectedLinks.length, actualLinks.length ); for ( int i = 0; i < actualLinks.length; i++ ) { assertEquals( "Link[" + i + "]", expectedLinks[i], actualLinks[i].getURLString() ); } } private String getAuthorizationHeader() { try { String encodedPassword = IOUtils.toString( Base64.encodeBase64( ":secret".getBytes() ) ); return "Basic " + encodedPassword; } catch ( IOException e ) { return ""; } } }
4,998
0
Create_ds/continuum/continuum-buildagent/continuum-buildagent-webdav/src/test/java/org/apache/continuum
Create_ds/continuum/continuum-buildagent/continuum-buildagent-webdav/src/test/java/org/apache/continuum/webdav/MockWorkingCopyServlet.java
package org.apache.continuum.webdav; /* * 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.configuration.DefaultBuildAgentConfigurationService; import javax.servlet.ServletConfig; public class MockWorkingCopyServlet extends WorkingCopyServlet { @Override public synchronized void initServers( ServletConfig servletConfig ) { super.initServers( servletConfig ); sessionProvider = new ContinuumBuildAgentDavSessionProvider( new BuildAgentConfigurationServiceMock() ); } public class BuildAgentConfigurationServiceMock extends DefaultBuildAgentConfigurationService { @Override public String getSharedSecretPassword() { return "secret"; } } }
4,999